Databases, cloud services and asset tracking
UAT 459 UAS, Internet of Things and Smart Warehouse Systems
Lesson
By the end of this module you will be able to
- Design a database that separates master data from time-series data and write parameterised SQL to detect temperature excursions
- Calculate storage for the required record retention and summarise data with pandas while keeping original records under ALCOA+
- Choose a cloud service model and divide security responsibilities with the provider
- Compare asset tracking technologies, assess the accuracy of distance estimates from RSSI and calculate the time pallets spend outside the cold room from RFID events
Why this matters
Three months after the centre opens, a Thai FDA inspector asks for the temperature history of one vaccine lot from receipt to dispatch. The system must answer within minutes: where the pallet was at each time, which sensor measured that location, when that sensor was last calibrated, and how long the pallet ever spent outside the cold room. The answer comes from three differently stored sources: sensor temperatures, master data on sensors and locations, and pallet events from asset tracking.
This module covers two topics of the course description, databases and cloud services and asset tracking. They meet where tracking data becomes meaningful only after it is stored and linked with other data.
Two kinds of data in an IoT platform
The system holds two kinds of data that need different storage.
- Master and transactional data, such as the sensor list, installation locations, calibration due dates, users and pallet status. There is not much of it, but the relationships are complex and must always be correct, so it belongs in a relational database that enforces relationships between tables
- Time-series data, such as temperature every minute from 92 sensors. It is huge, always growing and usually queried by time range, so it suits a time-series database or tables designed for fast appends and time-range queries
In a pharmaceutical store these are GxP records. The WHO guideline on data integrity (World Health Organization, 2021) sets out ALCOA+: data must be attributable, legible, contemporaneous, original and accurate, and also complete, consistent, enduring and available. The same guideline requires an audit trail of every action on the data, with restricted rights to switch it off. The consequences for database design: never overwrite a measured value; if a correction is needed, add a new row with the reason and the person; and always store time in UTC, converting to local time only for display.
Example 1 Sensor and reading tables with parameterised SQL
Create an in-memory SQLite database. Table sensor holds master data and table reading holds measurements. Ask which sensors left their zone’s range in a given hour, and which sensors are due for calibration before the end of next month (assumed data).
import sqlite3
# master data and time series in one small relational database (in memory, assumed rows)
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE sensor (sensor_id TEXT PRIMARY KEY, zone TEXT NOT NULL, location TEXT NOT NULL,
cal_due TEXT NOT NULL);
CREATE TABLE reading (sensor_id TEXT NOT NULL REFERENCES sensor(sensor_id), ts_utc TEXT NOT NULL,
temp_c REAL NOT NULL, PRIMARY KEY (sensor_id, ts_utc));
""")
db.executemany("INSERT INTO sensor VALUES (?, ?, ?, ?)", [
("T2-07", "Z2", "R03-L5", "2027-03-31"), ("T2-11", "Z2", "R06-L1", "2026-10-15"),
("T1-22", "Z1", "R18-L6", "2027-01-20")])
db.executemany("INSERT INTO reading VALUES (?, ?, ?)", [
("T2-07", "2026-09-30T17:00:00Z", 5.1), ("T2-07", "2026-09-30T17:01:00Z", 7.9),
("T2-07", "2026-09-30T17:02:00Z", 8.3), ("T2-11", "2026-09-30T17:00:00Z", 3.2),
("T2-11", "2026-09-30T17:01:00Z", 3.1), ("T1-22", "2026-09-30T17:00:00Z", 26.4),
("T1-22", "2026-09-30T17:01:00Z", 24.8)])
limits = {"Z1": (15.0, 25.0), "Z2": (2.0, 8.0)}
q = """SELECT s.zone, r.sensor_id, MIN(r.temp_c), MAX(r.temp_c), COUNT(*)
FROM reading r JOIN sensor s USING (sensor_id)
WHERE r.ts_utc >= ? AND r.ts_utc < ? GROUP BY s.zone, r.sensor_id ORDER BY 1, 2"""
for zone, sid, tmin, tmax, n in db.execute(q, ("2026-09-30T17:00:00Z", "2026-09-30T18:00:00Z")):
lo, hi = limits[zone]
flag = "EXCURSION" if tmin < lo or tmax > hi else "ok"
print(f"{zone} {sid}: min {tmin:.1f} max {tmax:.1f} °C, {n} rows, {flag}")
due = db.execute("SELECT sensor_id FROM sensor WHERE cal_due < ? ORDER BY 1", ("2026-11-01",)).fetchall()
print("calibration due before 2026-11-01:", [d[0] for d in due])
Z1 T1-22: min 24.8 max 26.4 °C, 2 rows, EXCURSION
Z2 T2-07: min 5.1 max 8.3 °C, 3 rows, EXCURSION
Z2 T2-11: min 3.1 max 3.2 °C, 2 rows, ok
calibration due before 2026-11-01: ['T2-11']
17:00 UTC is one in the morning of 1 October in Thai time. Three points. First, the SQL uses ? placeholders instead of string concatenation, which prevents SQL injection. Second, the primary key (sensor_id, ts_utc) stops the same reading being stored twice when a gateway backfills. Third, sensor T2-11 is due for calibration in mid-October; if that date passes, readings taken afterwards are hard to use as evidence.
Retention and summarising
WHO requires temperature records to be kept for at least one year after the end of the product’s shelf life (World Health Organization, 2011). Most products here have a three-year shelf life and may stay in the centre up to a year after receipt, so the team keeps original records for five years. The key lesson: downsampling, such as keeping only hourly means, is normal in general IoT work, but in a pharmaceutical store it is allowed only for analysis copies. Original records must be kept complete for the whole retention period.
Example 2 Five-year storage and an hourly summary with pandas
92 sensors record every minute at 40 bytes per row including indexes (assumed). Then one sensor’s day is summarised as hourly minimum, mean and maximum with the pandas resample method (The pandas development team, n.d.).
import numpy as np, pandas as pd
# storage for 5 years of original records, then an hourly summary for dashboards (assumed sizes)
SENSORS, ROW_BYTES, YEARS = 92, 40, 5 # 3-year shelf life + 1 year after expiry + 1 year in store
rows_per_year = SENSORS * 1440 * 365
print(f"{rows_per_year:,} rows/year, {rows_per_year * ROW_BYTES / 1e9:.2f} GB/year, "
f"{rows_per_year * ROW_BYTES * YEARS / 1e9:.1f} GB kept for {YEARS} years")
idx = pd.date_range("2026-09-30 00:00", periods=1440, freq="min", tz="UTC")
t = pd.Series(5.0 + 0.6 * np.sin(np.arange(1440) / 1440 * 2 * np.pi * 4), index=idx)
hourly = t.resample("1h").agg(["min", "mean", "max"]).round(2)
print(hourly.head(3))
print(f"{len(t)} rows become {len(hourly)} hourly rows; originals are still kept")
48,355,200 rows/year, 1.93 GB/year, 9.7 GB kept for 5 years
min mean max
2026-09-30 00:00:00+00:00 5.00 5.28 5.51
2026-09-30 01:00:00+00:00 5.52 5.57 5.60
2026-09-30 02:00:00+00:00 5.01 5.29 5.52
1440 rows become 24 hourly rows; originals are still kept
Five years need less than 10 GB, very little for current systems. The real cost is not disk but backups, restore tests and keeping files readable as software changes over five years. The hourly summary cuts rows to 1 in 60 and suits dashboards and trend analysis, but it must keep minimum and maximum too, because a mean alone can hide a short excursion.
Figure 1 shows the team’s design. Data stay online in the time-series database for 13 months so years can be compared, then move to write once, read many (WORM) storage that cannot be changed or deleted before the retention date, matching the “original” and “enduring” principles of ALCOA+.
Cloud services
The monitoring system can run on site or in the cloud. WHO Supplement 6 notes that large pharmaceutical warehouses usually use a web-based system hosted and monitored by the organisation, while small pharmacies may use software as a service (SaaS), where the vendor hosts the software and database; either way, the system must be qualified before use (World Health Organization, 2015a).
The NIST definition of cloud computing (Mell & Grance, 2011) has three service models: IaaS, renting virtual machines and installing everything yourself; PaaS, deploying code onto a platform whose operating system the provider runs; and SaaS, using finished software in a browser. All follow a shared responsibility model: the provider is responsible for security “of” the cloud, the infrastructure running its services, while the customer is responsible for security “in” the cloud. The more abstracted the service, the more the provider manages, but the customer always remains responsible for its own data, encryption, classification and user permissions (Amazon Web Services, n.d.).
| Question before choosing | Why |
|---|---|
| In which country is the data stored? | Staff personal data fall under the Personal Data Protection Act B.E. 2562 (2019) |
| Do alarms still work if the internet link fails? | The module 6 alert time budget must not depend on a single external link |
| How often does the vendor change software versions? | Each change may require requalification |
| If we leave the service, in what format do we get our data back? | Records must remain complete for five years |
The distribution centre team chose a hybrid: gateways, broker and the main alarm rules run on site so alarms work without the internet, while long-term archives and management dashboards run in the cloud.
Asset tracking
Asset tracking means knowing where valuable things are, what state they are in and how they move. The distribution centre has four groups of assets needing different detail.
| Asset | What we need to know | Technology chosen |
|---|---|---|
| Every pallet of product | Which door it passed, when it entered or left the cold room | UHF RFID tags and RFID portals |
| High-value biologics pallets | Which zone, and the pallet’s own temperature | BLE tags that measure temperature |
| Ten forklifts | Position to a few tens of centimetres, to slow down near pedestrians | UWB tags and anchors |
| Two drones | Docked or flying, battery state | Data from docks and the drone fleet manager |
The survey by Zafari et al. (2019) groups indoor localisation techniques by what they measure, such as received signal strength (RSS), time of flight and angle of arrival, and compares systems for energy, cost, range, latency and accuracy. RSS works with any radio and is cheapest, but signal strength fluctuates heavily indoors. UWB, under IEEE 802.15.4 (IEEE, 2024), measures the flight time of very short pulses and therefore ranges far more precisely, but needs installed anchors and costlier tags. How UWB positions are calculated is covered in the knowledge unit on indoor positioning.
Why is RSS imprecise? Invert the ITU-R P.1238 model of module 7. If loss varies with standard deviation dB, the estimated distance is off by a factor , a proportion of the distance, so the error in metres grows with range.
Example 3 Distance error from RSSI and zone choice with hysteresis
Use the ITU-R P.1238-13 industrial line-of-sight values , dB. Then decide the zone of a BLE tag on a pallet from two receivers, changing zone only when the new receiver is at least 6 dB stronger (assumed RSSI values).
import math
# how far is a BLE tag from a receiver? RSSI ranging with ITU-R P.1238-13 industrial LoS (alpha 2.27, sigma 2.62 dB)
ALPHA, SIGMA = 2.27, 2.62
for d in (3, 10, 25):
f1 = 10 ** (SIGMA / (10 * ALPHA)) # distance factor for a 1-sigma RSSI error
f2 = 10 ** (1.96 * SIGMA / (10 * ALPHA)) # 95 % two-sided
print(f"true {d:>2} m: 68 % between {d / f1:4.1f} and {d * f1:4.1f} m, "
f"95 % between {d / f2:4.1f} and {d * f2:4.1f} m")
# zone = receiver with the strongest smoothed RSSI, switching only if the new one is 6 dB stronger
readings = [("RX-Z2", -71, "RX-DOCK", -80), ("RX-Z2", -76, "RX-DOCK", -73), ("RX-Z2", -74, "RX-DOCK", -75),
("RX-Z2", -82, "RX-DOCK", -70), ("RX-Z2", -85, "RX-DOCK", -68)]
zone, HYST = "RX-Z2", 6
for a, ra, b, rb in readings:
best, other = (a, ra), (b, rb)
if rb > ra:
best, other = (b, rb), (a, ra)
if best[0] != zone and best[1] - other[1] >= HYST:
zone = best[0]
print(f"{a} {ra} dBm, {b} {rb} dBm -> zone {zone}")
true 3 m: 68 % between 2.3 and 3.9 m, 95 % between 1.8 and 5.1 m
true 10 m: 68 % between 7.7 and 13.0 m, 95 % between 5.9 and 16.8 m
true 25 m: 68 % between 19.2 and 32.6 m, 95 % between 14.8 and 42.1 m
RX-Z2 -71 dBm, RX-DOCK -80 dBm -> zone RX-Z2
RX-Z2 -76 dBm, RX-DOCK -73 dBm -> zone RX-Z2
RX-Z2 -74 dBm, RX-DOCK -75 dBm -> zone RX-Z2
RX-Z2 -82 dBm, RX-DOCK -70 dBm -> zone RX-DOCK
RX-Z2 -85 dBm, RX-DOCK -68 dBm -> zone RX-DOCK
A tag truly 10 m away may be estimated anywhere from 6 to 17 m, even with line of sight. RSSI can therefore tell which room a pallet is in, not which rack slot. The 6 dB hysteresis rule stops the zone flipping on row 2, where RX-DOCK is only 3 dB stronger; the zone changes on row 4 with a 12 dB difference, when the pallet really has been taken out to the dock.
For ordinary pallets the team uses UHF RFID tags to the GS1 EPC Gen2 standard (GS1, 2026) built into the pallet label, with RFID portals at the cold-room door and the dock doors. Each time a pallet passes, a portal creates an event: which pallet, which door, which direction and when. Such data do not give continuous position, but they give what QA needs most: time out of refrigeration, to be compared with each product’s stability data.
Example 4 Cumulative time out of refrigeration for each pallet
Events from the cold-room RFID portal on one day (local time). According to its stability data, this product may spend at most 30 minutes in total outside 2 to 8 °C. It is now 15:46 (assumed data).
from datetime import datetime
# time out of refrigeration per pallet from RFID portal reads at the cold-room door (assumed events)
events = [("SSCC-0412", "OUT", "09:02"), ("SSCC-0412", "IN", "09:17"), ("SSCC-0412", "OUT", "13:40"),
("SSCC-0412", "IN", "13:58"), ("SSCC-0429", "OUT", "10:05"), ("SSCC-0429", "IN", "10:31"),
("SSCC-0433", "OUT", "11:20"), ("SSCC-0433", "IN", "11:24"), ("SSCC-0433", "OUT", "15:10")]
LIMIT_MIN, NOW = 30, "15:46" # allowed cumulative minutes from stability data (assumed)
def mins(a, b):
return (datetime.strptime(b, "%H:%M") - datetime.strptime(a, "%H:%M")).seconds // 60
def time_out(events):
"""Rule: keep the first OUT of a trip. A repeated OUT never overwrites it; an IN with no OUT adds no time.
Both are counted as odd reads so that a person checks them."""
out_since, total, odd = {}, {}, {}
for sscc, way, hhmm in events:
total.setdefault(sscc, 0)
if way == "OUT" and sscc not in out_since:
out_since[sscc] = hhmm
elif way == "IN" and sscc in out_since:
total[sscc] += mins(out_since.pop(sscc), hhmm)
else: # OUT twice in a row, or IN with no OUT
odd[sscc] = odd.get(sscc, 0) + 1
for sscc, since in out_since.items(): # pallets still outside now
total[sscc] += mins(since, NOW)
return total, out_since, odd
def report(events):
total, outside, odd = time_out(events)
for sscc in sorted(total):
state = "still outside" if sscc in outside else "inside"
flag = "HOLD for QA" if total[sscc] > LIMIT_MIN else "ok"
if odd.get(sscc):
flag = "CHECK EVENTS" if flag == "ok" else flag + ", CHECK EVENTS"
print(f"{sscc}: {total[sscc]:3d} min out of refrigeration, {state}, {flag}")
report(events)
one = [e for e in events if e[0] == "SSCC-0412"]
print("-- odd reads of pallet 0412 --")
report([e for e in one if e[2] != "09:17"]) # portal missed the first IN
report(one[:1] + [("SSCC-0412", "OUT", "09:03")] + one[1:]) # first OUT read twice
report([e for e in one if e[2] != "09:02"]) # portal missed the first OUT
SSCC-0412: 33 min out of refrigeration, inside, HOLD for QA
SSCC-0429: 26 min out of refrigeration, inside, ok
SSCC-0433: 40 min out of refrigeration, still outside, HOLD for QA
-- odd reads of pallet 0412 --
SSCC-0412: 296 min out of refrigeration, inside, HOLD for QA, CHECK EVENTS
SSCC-0412: 33 min out of refrigeration, inside, HOLD for QA, CHECK EVENTS
SSCC-0412: 18 min out of refrigeration, inside, CHECK EVENTS
Pallet 0412 went out twice, each time briefly (15 and 18 minutes), but the total of 33 minutes exceeds the limit; looking at single trips would miss it. Pallet 0433 has already been outside for 36 minutes; the system should warn before the limit, not after. Both pallets must be held for QA assessment, a request that module 9 sends into the WMS. The weakness of this method is that a portal may miss a read or read the same tag twice, so the code applies one clear rule: keep the first OUT of each trip, and never let a repeated OUT overwrite it. An IN with no OUT before it adds no time, because nobody knows when the pallet left. Both cases are counted as odd reads and tagged CHECK EVENTS for a person. The test on pallet 0412 in the last three lines shows what happens.
- The first IN at 09:17 is missed, so two OUTs come in a row. The code keeps the first OUT and treats the pallet as outside from 09:02 to 13:58, 296 minutes. This may be more than the truth, but it errs on the safe side: the pallet is held and a person checks.
- The OUT at 09:02 is read a second time at 09:03. The time stays at 33 minutes; the pallet is only tagged for checking.
- The OUT at 09:02 is missed. The code counts only 18 minutes, which is below the truth, so it must not say ok; it says CHECK EVENTS instead.
A version that overwrites the OUT every time it sees one (out_since[sscc] = hhmm) gives 18 minutes in the first case and passes wrongly, gives 32 minutes in the second, and stops with a KeyError in the third. The true value must be checked by a person against the door records and corrected with a correction row and a reason, never by overwriting the original.
Some asset tracking also tracks people. A UWB tag on a forklift tells where each driver is throughout the shift, so the data are personal data under the Personal Data Protection Act B.E. 2562 (2019) (Personal Data Protection Act B.E. 2562, 2019). The company must state the purpose (such as safety and forklift management), collect only what is needed, set a retention period and not use the data for other purposes, such as judging individual performance without notice. Module 10 returns to this point.
Module lab
Lab: a temperature record database and a mock pallet tracking system
- Extend the Example 1 database with a
calibrationtable (calibration history) and anaudit_logtable (who, what, when, why), load at least 24 hours of data from the module 7 mock gateway, and write at least three parameterised SQL queries - Try to “correct” one measured value, designing the schema so it cannot be overwritten: a correction row must be added with reason and person, and the original must remain visible
- Calculate storage as in Example 2 for the group’s system, summarise hourly with pandas, and compare which events the hourly mean hides
- Put BLE or RFID tags on three mock boxes, move them through a designated “cold-room door”, record the events, then use the code of Examples 3 and 4 to decide zones and compute time out of refrigeration, including one missed read and one duplicate read
Common mistakes
Watch out
- Keeping only hourly means and deleting originals, breaking ALCOA+ and hiding short excursions
- Overwriting measured values with no audit trail
- Building SQL by string concatenation instead of parameters, inviting injection
- Using RSSI to locate rack slots, when it is accurate only to a room or zone
- Counting time out of refrigeration trip by trip instead of cumulatively, and letting a repeated OUT read overwrite the first OUT, with no check of unusual event sequences
- Forgetting that tracking forklifts tracks drivers, which must follow personal data protection law
Summary
- Keep master data in a relational database and time-series data where appends are fast, linked by sensor ID; use parameterised SQL and primary keys against duplicates
- Pharmaceutical data must follow ALCOA+: UTC times, audit trails and complete originals for the retention period; summarising is allowed for analysis copies
- Cloud services come as IaaS, PaaS and SaaS under shared responsibility; the customer always owns data and user permissions, and alarms should not depend on a single internet link
- Choose tracking technology by the detail needed; RSSI error is a proportion of distance, , so it suits zone level, while RFID events give cumulative time out of refrigeration
Check your understanding
- 50 sensors record every 2 minutes at 40 bytes per row. How much storage do five years need?
- Why is keeping only hourly means not enough for a pharmaceutical store?
- With the Example 3 model (, dB), what range is estimated at 68% confidence for a tag truly 20 m away?
- A pallet leaves the cold room three times for 8, 12 and 14 minutes, and the limit is 30 minutes. What is the outcome?
- Under the shared responsibility model, if the centre uses SaaS, who is responsible for setting which users can view temperature data?
Answers
- bytes, about 2.6 GB
- A mean hides short excursions, and ALCOA+ and WHO requirements need complete original records for the retention period; means are fine only for analysis copies
- The factor is , so from m to m
- Total minutes, above 30, so the pallet must be held for QA even though each trip was short
- The customer (the distribution centre). The provider runs the infrastructure and software, but the customer remains responsible for its data and user permissions
Key formulas
| Storage for original records | |
| Distance range from RSSI | |
| Cumulative time out of refrigeration |
Key references
- World Health Organization. (2021). Guideline on data integrity (WHO Technical Report Series, No. 1033, Annex 4). WHO. link
- World Health Organization. (2011). Model guidance for the storage and transport of time- and temperature-sensitive pharmaceutical products (WHO Technical Report Series, No. 961, Annex 9). WHO. link
- World Health Organization. (2015). Temperature and humidity monitoring systems for fixed storage areas: Technical supplement to WHO Technical Report Series, No. 961, 2011, Annex 9 (Supplement 6). WHO. link
- Mell, P., & Grance, T. (2011). The NIST definition of cloud computing (NIST SP 800-145). National Institute of Standards and Technology. link
- Amazon Web Services. Shared responsibility model. AWS Compliance. link
- The pandas development team. pandas.DataFrame.resample. pandas API reference. link
- International Telecommunication Union. (2025). Propagation data and prediction methods for the planning of indoor radiocommunication systems and radio local area networks in the frequency range from 300 MHz to 450 GHz (Recommendation ITU-R P.1238-13). link
- Zafari, F., Gkelias, A., & Leung, K. K. (2019). A survey of indoor localization systems and technologies. IEEE Communications Surveys & Tutorials, 21(3), 2568–2599. link
- IEEE. (2024). IEEE standard for low-rate wireless networks (IEEE Std 802.15.4-2024). link
- GS1. (2026). EPC radio-frequency identity Generation-2 UHF RFID standard: Specification for RFID air interface protocol for communications at 860 MHz – 930 MHz (Release 3.0.1). link
- พระราชบัญญัติคุ้มครองข้อมูลส่วนบุคคล พ.ศ. 2562. ราชกิจจานุเบกษา, 136(69 ก), 52–95. link
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
คลาวด์และบริการข้อมูล IoT
ระบบระบุตำแหน่งภายในอาคาร
การจัดการและแสดงผลข้อมูลด้วย Python
In class / field
Lab or field practice from worksheets with a safety checklist
Learning evidence: Checked worksheets and quiz results