diff --git a/public/data/traceability_export.csv b/public/data/traceability_export.csv index 44e0caa..a6691cf 100644 --- a/public/data/traceability_export.csv +++ b/public/data/traceability_export.csv @@ -1,4 +1,417 @@ ID,Type,Status,Title,Description,Parent_ID,Relations +38,Task,In progress,review sensor list [ammonia],"**Criteria:** + +* Availability. + +* Price \[USD\]. + +* Manufacturer. \[\]not boycott\]. + +* peripheral or communication protocoled. + +* Range quantity \[ex 0c to 100c\]. + +* Covered Area, \[m2\]. i**f possible.** + +* Data. \[public data about sensor\] + +* What type of external peripherals will be needed with esp-32 like (RS-485). + + +
+ +

Sensor (type)

Manufacturer (origin)

Est. price (USD)

Comm. protocol / outputs

NH₃ range (ppm)

Accuracy / precision

Operating voltage

Availability

Datasheet

Product link

PCB-solderable?

DOL 53 Ammonia Sensor

DOL-sensors (Denmark)

~$1,389

Analog (0–10 V or 4–20 mA)

0–100

±1.5 ppm or ±10%

24 VDC (15–30 VDC)

Available worldwide via distributors

[Spec]

Manufacturer

No (probe)

DOL 51 (Air-clean)

DOL-sensors (Denmark)

~$4,182

Analog (0–10 V or 4–20 mA)

0–50

±1.5 ppm or ±10%

24 VDC (22–26 VDC)

High-humidity tolerant (0–100% RH)

[Spec]

Manufacturer

No (probe)

Fancom NH₃ Sensor

Fancom (Netherlands)

N/A (est. ~$1,000)

Analog (0–10 V)

0–100

±1.5 ppm or ±10%

24 VDC (15–30 VDC)

Widely used in EU farms

[Factsheet]

Manufacturer

No (probe)

Aranet NH₃ Kit (0–100 ppm)

Aranet (Lithuania)

~$1,770

Wireless (LoRaWAN, via Aranet transmitter)

0–100

(accuracy not given)

24 VDC supply

Industrial IoT sensor kit (includes DOL-53)

[Manual]

Manufacturer / Distributor

No (kit)

SGX-4NH3-100

Amphenol SGX (UK)

~$85

Electrochemical (current output)

0–100

±0.5 ppm (500 ppb)

– (no external supply)

Sold by electronics distributors (e.g. Newark)

[Datasheet]

Distributor

Yes

Alphasense NH3-B1

Alphasense (UK)

~$242

Electrochemical (nA output, requires amplifier)

0–100

20–60 nA/ppm sensitivity (≈0.3 ppm resolution)

– (uses internal bias ~200 mV)

Available via distributors (e.g. WinSensors)

[Specs]

Distributor

Yes

Membrapor NH3/MR-100

Membrapor (Switzerland)

N/A (~$100)

Electrochemical (110 nA/ppm)

0–100

<0.5 ppm resolution

– (passive)

Niche sensor; available through specialty suppliers

[Datasheet]

Distributor

Yes

Figaro TGS826

Figaro (Japan)

~$50–60

MOS (resistive; needs external circuit)

~30–300

(no spec’d ppm accuracy; rough resistive)

Heater 5 V (833 mW)

Widely available sensor element

[Datasheet]

Distributor

Yes

Winsen MQ-137

Winsen (China)

~$64

MOS (analog voltage output)

~10–1000 (module 5–500)

(low-precision, requires calibration)

5 VDC (heater)

Off-the-shelf/electronics hobbyist modules

[SparkFun PDF]

SparkFun

No (sensor pins)

L-com SRAQ-G216 (MQ-137)

L-com (USA)

~$210 (£172)

Analog + digital TTL outputs

5–500

(sensitivity adjustable; no spec’d accuracy)

5 VDC

Commercial module for NH₃

[Datasheet]

Distributor

Yes

SGX MiCS-6814

SGX Sensortech (Netherlands)

~$20 (module)

Analog resistances for CO/NO₂/NH₃

1–300

(see graph; low ppm sensitivity)

5 VDC (heater)

Multi-gas MEMS module, available from electronics suppliers

[Datasheet]

Distributor

Yes


+ +
+ +## ✅ **Industrial-Grade & Reliable NH₃ Sensors** + +These sensors are designed for **continuous monitoring in harsh environments**, offer repeatability/accuracy, longer life, robust housings, and are used in ventilation control, poultry/livestock farms, safety systems, or industrial automation. + +

Sensor

Industrial Grade?

Why (Summary)

DOL 53 Ammonia Sensor

✔️ Industrial

Designed specifically for livestock/farm monitoring, long life, replaceable head, 36 month service life, IP65 protection and analog 4–20 mA/0–10 V outputs for PLC/automation systems. (pro.aranet.com)

DOL 51 Ammonia Sensor

✔️ Industrial

Similar to DOL 53 but for post-air-cleaning environments; built for high humidity and continuous use.

Fancom NH₃ Sensor Probe

✔️ Industrial

Plug-and-play ammonia probe designed for climate control in agricultural settings (poultry houses).

Aranet NH₃ Sensor Kit

✔️ Industrial

Includes DOL sensor with industrial transmitter (IP65) and integration options; intended for livestock gas monitoring. (pro.aranet.com)

NexaSens Ammonia Gas Sensor (industrial module)

✔️ Industrial

Rugged design, 4–20 mA & RS-485 outputs, robust humidity/temperature range, made for industrial NH₃ applications. (SENSORS & ROBOTICS)

Sensorix NH₃ Series (100–5000 ppm)

✔️ Industrial

German electrochemical sensors with class-leading stability and selectivity, ideal for industrial air monitoring. (sensorix.com)

+ +**Why these are industrial grade:** +✔ Designed for continuous operation +✔ Can handle humidity/temperature variations seen in barns +✔ Outputs compatible with PLC/automation (4-20 mA, RS-485) +✔ Often comply with safety standards for industrial gas detection +✔ Typically longer lifetime and defined calibration cycles + +## ⚠️ **Semi-Industrial / Intermediate Reliability** + +These can be used in monitoring systems _if properly calibrated and used with protective housings & signal conditioning_, but they are **not as robust as true industrial products** and may require more frequent calibration or additional circuitry. + +

Sensor

Industrial Grade?

Notes

SGX-4NH3-100

⚠️ Semi-industrial / sensor element

Electrochemical with industrial footprint, but requires own housing & signal circuitry. Typically used in industrial detectors, not as standalone outdoor probes. (RS Components)

Alphasense NH3-B1

⚠️ Semi-industrial / OEM

High-quality electrochemical sensor elements from established industrial supplier, but needs proper packaging & conditioning hardware. (alphasense.com)

Membrapor NH3 (EC)

⚠️ Semi-industrial / OEM

Electrochemical cell that must be integrated into a system; stable but needs proper circuit and housing. (gasdetect.com)

+ +**Reasoning:** These are **sensor elements** from industrial suppliers, but they lack ruggedized packaging and integrated outputs. They are often used inside industrial analyzers or detectors rather than directly mounted in the environment. + +## ❌ **Non-Industrial / Hobby / Low-Reliability Sensors** + +These are better suited for prototyping, hobby projects, or short-term monitoring — **not continuous industrial farming environments** without additional conditioning and enclosure. + +

Sensor

Industrial Grade?

Why Not

Figaro TGS826 (MOS type)

❌ Not industrial grade

This is a consumer/hobby sensor element with no integrated calibration or industrial output. It can be used for prototypes or simple monitoring but lacks accuracy specs and robustness. (figarosensor.com)

Winsen MQ-137 / SRAQ-G216

❌ Not industrial grade

Cheap semiconductor NH₃ sensors (e.g., MQ-series) – poor precision, strong cross-sensitivity, and large drift; unsuitable for industrial climate control without heavy calibration. (sg.rs-online.com)

SGX MiCS-6814 (multi-gas)

❌ Not industrial grade

Multi-gas hobby module; not dedicated NH₃ detector and not accurate/reliable enough for industrial safety or precise control. (Reddit)

+ +**Typical issues with hobby sensors:** +⚠ Low accuracy and repeatability +⚠ Strong cross-sensitivity to other gases +⚠ Large drift and frequent calibration needed +⚠ Not robust against humidity or temperature changes + +## 🧠 Summary + +### **Industrial-Grade (Best for Poultry Farms & Ventilation Control)** + +✅ DOL 53, DOL 51 (DOL-Sensors) +✅ Fancom NH₃ Probes +✅ Aranet NH₃ Kit +✅ NexaSens industrial NH₃ modules +✅ Sensorix NH₃ series + +→ These are **reliable, robust, and designed for long-term continuous operation**, with proper mounting and integration. + +### **Semi-Industrial / OEM Sensor Elements** + +⚠ SGX-4NH3-100 +⚠ Alphasense NH3 series +⚠ Membrapor NH3 + +→ Good as sensor elements in a custom detector/board with housing and industrial electronics. + +### **Not Industrial / Hobby Only** + +❌ Figaro TGS826 +❌ Winsen MQ-137 / L-com modules +❌ SGX MiCS-6814 + +
+ +Important upfront note (engineering reality): + +* **Ammonia ≠ VOC** + +* NH₃ _does_ require at least **one electrochemical “truth” sensor** if you want reliable control. + +* Cheap NH₃ sensors are **trend-only**, not absolute truth. + +* Your requested budgets are **tight but workable** with the right expectations. + + +# 3\. Ammonia Gas (NH₃) + +## 3.1 Selection Criteria + +Ammonia sensors are used for **animal welfare, ventilation control, and early warning**, not laboratory-grade measurement. + +Key criteria: + +* One **electrochemical reference sensor** for absolute ppm anchoring + +* One **low-cost PCB-compatible sensor** for spatial trend detection + +* Known drift characteristics and predictable aging + +* Tolerance to humidity (critical in poultry houses) + +* Clear separation of **truth vs trend** roles + + +## 3.2 Recommended NH₃ Sensors + +### Criteria + +


Reference Sensor

Distributed PCB Sensor (×5+)

Sensor Name

Alphasense NH3-B1

Figaro TGS826

Manufacturer

Alphasense (UK)

Figaro Engineering (Japan)

Sensor Technology

Electrochemical

MOS (Metal Oxide Semiconductor)

Measurement Output

Absolute NH₃ (ppm)

Relative NH₃ concentration

Role in System

Source of truth / calibration anchor

Distributed trend sensing

Typical Price

~$140–190

~$25–35

Best Use

Control reference, alarms, calibration

Spatial variation & early buildup

Communication

Analog current (nA → ppm)

Analog resistance

Integration Form

Sensor cell (OEM)

PCB-mount sensor

PCB Compatibility

Needs analog front-end

Direct PCB soldering

Humidity Tolerance

High (designed for industrial use)

Poor–moderate (needs compensation)

Datasheet

https://www.alphasense.com/products/nh3-b1/

https://www.figarosensor.com/product/entry/tgs826.html

+ +### Why these two? + +#### ✅ **Alphasense NH3-B1 — “Source of Truth”** + +* True **electrochemical NH₃ sensor** + +* Used inside many **industrial gas detectors** + +* Much more stable than MOS + +* Predictable drift curve + +* Your budget ($100–200) fits **exactly** here + + +⚠️ Tradeoffs: + +* Needs **analog front-end** (TIA + ADC) + +* Limited lifespan (typically 2–3 years) + +* Not PCB-drop-in by itself + + +#### ✅ **Figaro TGS826 — PCB-Compatible & Cheap** + +* Easily soldered to PCB + +* Widely available + +* Cheap enough to deploy many units + +* Very good for **relative ammonia buildup detection** + + +⚠️ Limitations (important): + +* Not ppm-accurate + +* Strong temperature & humidity sensitivity + +* Drift over time + +* Must be **normalized against reference sensor** + + +## 3.3 Architecture Notes (NH₃) + +### Critical Design Principles + +* **NH₃ ppm values must come from electrochemical sensors** + +* MOS sensors **cannot be trusted alone** for ammonia safety + +* Use the system like this: + + +```text +[Alphasense NH3-B1] + ↓ +Absolute ppm reference + ↓ +Normalization & correction + ↓ +[TGS826 × N nodes] +``` + +### Recommended Usage Pattern + +* 1 × **NH3-B1** per house (or per zone) + +* 5–10 × **TGS826** distributed near: + + * Litter level + + * Exhaust fans + + * Dead air zones + + +### Firmware Strategy + +* Temperature & humidity compensation **mandatory** + +* Apply: + + * Long-term drift tracking + + * Relative deviation detection + +* Trigger ventilation based on: + + * Reference ppm + + * Distributed deviation spikes + + +## 3.4 Why NOT Other Options (Quick Justification) + +

Sensor

Reason Rejected

DOL 53 / Fancom

Excellent, but far above budget

MQ-137

Too unstable, hobby-grade

MiCS-6814

Multi-gas, poor NH₃ specificity

Aranet NH₃

Industrial, but far too expensive

SGX-4NH3-100

Good sensor, but usually >$80 and harder to source

+ +## 3.5 Final Recommendation (Clear & Actionable) + +### ✅ Use this pair: + +* **Reference NH₃ sensor:** + **Alphasense NH3-B1** + +* **PCB / distributed sensor:** + **Figaro TGS826** + + +
+ +
",, +40,Task,In progress,review sensor list [CO2],"**Criteria:** + +* Availability. + +* Price \[USD\]. + +* Manufacturer. \[\]not boycott\]. + +* peripheral or communication protocoled. + +* Range quantity \[ex 0c to 100c\]. + +* Covered Area, \[m2\]. i**f possible.** + +* Data. \[public data about sensor\] + +* What type of external peripherals will be needed with esp-32 like (RS-485). + + +
+ +Results to discuss + +

Sensor (CO₂)

Manufacturer (Origin)

Price [USD]

Interface/Protocol

Availability

Range (ppm)

Accuracy/Precision

Datasheet / Link

Product Link

Voltage (V)

Sensirion SCD30

Sensirion (Switzerland)

~$40

UART, I²C, PWM

High (commercial module)

400–10 000

±(30 ppm + 3% of reading)

Sensirion SCD30 Datasheet

Newark/Newark element14 SCD30

3.3–5.5

Sensirion SCD40

Sensirion (Switzerland)

~$18

I²C (digital)

Moderate (newer module)

400–2 000

±(50 ppm + 5% of reading)

Sensirion SCD4x Datasheet (SCD40 variant)

Digi-Key SCD40

2.4–5.5

MH-Z19B

Zhengzhou Winsen (China)

~$25

UART (TTL)/PWM

High (common hobbyist)

400–2 000 (5000 opt.)

±(50 ppm + 5% of reading)

Winsen MH-Z19B Datasheet

eBay/Xspar (MH‑Z19B)

4.5–5.5

CCS811 (eCO₂)

ams (Austria)

~$20

I²C (digital)

High (widely used)

400–8 192 (equivalent)

(eCO₂ estimate – VOC-based)

Adafruit CCS811 info

Adafruit CCS811 (VOC/eCO₂)

3.3 (breakout reg.)

Renke RS-CO₂ --2-EX (0–5000 ppm)

Renke (China)

~$40

Analog (0–5 V/0–10 V/4–20 mA) or RS-485

Moderate (industrial)

0–5 000

±(50 ppm + 3% of FS)

Renke RS-CO₂ product page

Renke RS-CO₂-*-2-EX

10–30

Senseair K30 (FR)

Senseair (Sweden)

~$50

UART (Modbus or TTL) + 0–5 V/0–10 V analog

Moderate (OEM module)

0–5 000

±(30 ppm + 3% of reading)

Senseair K30 FR Datasheet

Digi-Key K30 (5kppm)

4.5–14


+ +Extended table 😀  + +

#

Sensor (type)

Manufacturer (origin)

Est. price (USD)

Comm. protocol / outputs

CO₂ range

Accuracy / precision

Operating voltage

Availability

Datasheet

Product link

PCB-solderable?

1

Sensirion SCD30 (module: NDIR + T/H)

Sensirion (Switzerland)

~$35–$55

I²C, UART, PWM

400–10,000 ppm

±(30 ppm + 3% of reading)

3.3–5.5 V (module) — can be powered by 5 V; use regulator for 12/24V

High

Datasheet: SCD30 datasheet (Sensirion PDF). (Sensirion AG)

Product / buy: Digi-Key SCD30 product page. (DigiKey)

No — module (through-hole / small module).

2

Sensirion SCD4x (SCD40 / SCD41) (miniature/photoacoustic NDIR)

Sensirion (Switzerland)

SMD chip cost ~$8–$25 (breakout/module ~$20–$50)

I²C (digital)

typical 400–2,000 ppm (application target) — SCD4x family supports broader ranges

High: comparable to SCD30, photoacoustic NDIR (datasheet shows tight spec)

SMD part — 1.8–5.5V depending on variant / recommended per datasheet

Moderate → High (growing adoption)

Datasheet: SCD4x datasheet (Sensirion PDF). (Sensirion AG)

Product / buy: Digi-Key / Sensirion product pages (SCD4x family). (Sensirion AG)

YES — SMD (meant for PCB assembly). Good for direct PCB integration.

3

MH-Z19B (NDIR module)

Winsen / Zhengzhou (China)

~$20–$35

UART (TTL), PWM; some clones expose analog

400–2,000 ppm (configurable to 5k/10k on some firmwares)

~±(50 ppm + 5%) (typical per datasheet)

4.5–5.5 V (module) — needs regulator from 12/24V

Very high (hobby & commercial sellers)

Datasheet: MH-Z19B PDF (Winsen). (Winsen Sensor)

Product / buy: widely sold (Amazon, eBay, AliExpress); example vendor listings shown by distributors. (Winsen Sensor)

No — module (not SMD-friendly).

4

CCS811 (eCO₂ + TVOC) (MOx VOC → eCO₂ estimate)

ams/CCS (Austria) / widely sold on breakouts

~$10–$30 (breakout)

I²C (digital)

eCO₂ 400–8,192 ppm (equivalent CO₂ estimate)

TVOC/eCO₂ are estimates — accuracy moderate; datasheet: algorithmic conversion; not an NDIR

Chip: ~1.8V; breakout boards provide 3.3V/reg

High (many breakouts, libraries)

Datasheet: CCS811 datasheet (ams/Sparkfun PDF). (cdn.sparkfun.com)

Product / buy: Adafruit / SparkFun CCS811 breakout pages. (Adafruit Learning System)

Chip-level: YES — CCS811 available as IC (QFN) but many use breakout. If using chip directly, follow ams integration guidelines.

5

Sensirion SGP30 (MOx TVOC / eCO₂ IC)

Sensirion (Switzerland)

chip ~$6–$15; breakout ~$12–$30

I²C

eCO₂ (equivalent) — used as CO₂eq indicator (400–60k ppm reported on some breakout docs)

~±15% (TVOC/eCO₂ algorithmic) (datasheet)

1.62–1.98 V (chip) — breakout required for convenient 3.3/5V use

Good (but SGP30 lifecycle status varies — check current stock)

Datasheet: SGP30 datasheet (Sensirion). (Sensirion AG)

Product / buy: Adafruit / Mouser / Digi-Key SGP30 product pages. (DigiKey)

YES — SMD IC (DFN 6) meant for PCB assembly.

6

Renke RS-CO₂ (industrial transmitter)

Renke (China)

~$30–$50 (depends model)

Analog (0–5V / 0–10V / 4–20 mA) or RS-485 (Modbus)

0–5,000 ppm (typical model)

~±(40–50 ppm + 3% FS) (manufacturer spec)

10–30 V DC (fits your 12/24V requirement)

Moderate (industrial / OEM channels)

Product page / specs: Renke RS-CO2 product page. (renkeer.com)

Product / buy: Renke official product page (quote / distributor). (renkeer.com)

No — industrial transmitter (probe).

7

Senseair K30 (K30 FR variant) (OEM NDIR module)

Senseair (Sweden)

~$40–$60 (varies)

UART (TTL)/analog (0–5V) / Modbus options on variants

0–5,000 ppm (K30 FR common variant)

±(30 ppm + 3%) (typical spec)

4.5–14 V (suitable via 12 V)

Moderate (OEM distributors)

Datasheet: CO2Meter / Senseair K30 FR datasheet PDF. (co2meters.com)

Product / buy: Senseair product page / CO2Meter distribution pages. (senseair.com)

No — module (OEM)

8

Seeed SenseCAP SOLO CO₂ 5000 (NDIR transmitter)

Seeed Studio (China)

~$79 (slightly above your upper limit; included for reference)

RS-485 (Modbus-RTU), SDI-12

400–5,000 ppm

±(50 ppm + 5% MV) (manufacturer)

Power: 5–16 V (can be used with 12/24 V via regulator)

High (Seeed distribution)

Datasheet / User guide: SenseCAP SOLO CO2 5000 datasheet/user guide (Seeed). (files.seeedstudio.com)

Product / buy: Seeed product page. (files.seeedstudio.com)

No — enclosed transmitter


+ +
+ +

Role

Selected Sensor

Why

Reference (Source of Truth)

Sensirion SCD30

Proven industrial-grade NDIR, stable long-term accuracy

Distributed / Cheap PCB Sensors (×5)

Sensirion SCD40 (SCD4x family)

True CO₂, SMD, low cost, designed for PCB integration


+ +## ✅ Recommended Architecture (Summary) + +* **1 × Industrial / Reference CO₂ sensor** + → Used as **Source of Truth**, calibration anchor, alarms, long-term reliability + +* **5 × Low-cost PCB-integrated CO₂ sensors** + → Used for **spatial distribution**, trend detection, redundancy, and ventilation optimization + → Periodically **cross-checked / auto-calibrated** against the reference sensor + + +# ✅ Final Recommended Sensors + +

Role

Selected Sensor

Why

Reference (Source of Truth)

Sensirion SCD30

Proven industrial-grade NDIR, stable long-term accuracy

Distributed / Cheap PCB Sensors (×5)

Sensirion SCD40 (SCD4x family)

True CO₂, SMD, low cost, designed for PCB integration

+ +# 📊 Selection Table (Final – Only the 2 Chosen Sensors) + +

Criteria

Reference Sensor

Distributed PCB Sensor

Sensor name

Sensirion SCD30

Sensirion SCD40 (SCD4x)

Manufacturer

Sensirion (Switzerland)

Sensirion (Switzerland)

Sensor technology

NDIR (true CO₂)

Photoacoustic NDIR (true CO₂)

Role in system

Source of truth / calibration anchor

Distributed sensing (×5 units)

Price (USD)

~$35–50

~$18–30 (chip)

CO₂ range

400 – 10,000 ppm

Optimized for indoor/agriculture (400–2,000+ ppm)

Accuracy

±(30 ppm + 3%)

Very good for size class (close to SCD30)

Long-term stability

Excellent (industrial-grade)

Good (depends on calibration strategy)

PCB compatibility

❌ Module (not SMD)

SMD IC – PCB mount

Communication

I²C / UART / PWM

I²C

Operating voltage

3.3–5.5 V

1.8–5.5 V (variant dependent)

12V/24V compatible

Yes (via regulator)

Yes (via regulator)

Availability

High

High

Country of origin

Switzerland (non-Israel)

Switzerland (non-Israel)

+ +# 🎯 Why This Is the Best Combination + +## 1️⃣ Why **SCD30** as the _Source of Truth_ + +**Key reasons:** + +* ✔ Proven **industrial reliability** + +* ✔ True NDIR CO₂ (not estimated eCO₂) + +* ✔ Excellent long-term drift performance + +* ✔ Widely used in HVAC, agriculture, laboratories + +* ✔ Multiple interfaces (UART/I²C/PWM) + +* ✔ Strong documentation & field history + + +**In your system:** + +* Installed in the **most representative location** + +* Used to: + + * Validate system health + + * Trigger alarms + + * Periodically **re-align/calibrate the 5 cheaper sensors** + + +This is exactly how commercial poultry climate controllers are designed. + +## 2️⃣ Why **SCD40** for the Other 5 Sensors + +**This is the key decision that makes your system scalable and professional.** + +### Why SCD40 (instead of CCS811 / SGP30 / MH-Z19B): + +

Option

Why Not Ideal

CCS811 / SGP30

❌ eCO₂ only (VOC-based, drifts badly in barns)

MH-Z19B

❌ Module only, inconsistent QC, not PCB-friendly

Industrial transmitters

❌ Too expensive ×5

+ +### Why SCD40 **is ideal** + +* ✅ **True CO₂ (NDIR)** — same physics as reference + +* ✅ **SMD package** → perfect for PCB + +* ✅ Much **cheaper than SCD30** + +* ✅ Designed specifically for **OEM products** + +* ✅ Same manufacturer → consistent calibration philosophy + +* ✅ Small size → easy to place multiple sensors + + +**This allows:** + +* Reliable CO₂ gradient mapping across the house + +* Sensor redundancy + +* Software-based cross-calibration against SCD30 + + +# 🧠 Recommended Calibration Strategy (Important) + +To maximize accuracy and lifetime: + +1. Power-up: + + * Let all sensors warm up (NDIR needs thermal stability) + +2. Use **SCD30 as master** + +3. Periodically: + + * Compare SCD40 readings to SCD30 + + * Apply **offset correction in firmware** + +4. Store offsets in EEPROM / flash + +5. Repeat monthly or when ventilation conditions stabilize + + +➡ This dramatically improves cheap sensor accuracy without hardware cost. + +# 🧩 Typical System Block Diagram (Conceptual) + +```text +[ SCD30 Reference ] + | + | (I²C / UART) + | +[ MCU / ESP32 / STM32 ] + | | | | | +[ SCD40 ][ SCD40 ][ SCD40 ][ SCD40 ][ SCD40 ] +``` + +* All powered from 12/24V → DC-DC → 5V/3.3V rails + +* I²C bus with proper pull-ups and cable length control + +* Optional RS-485 uplink to farm controller + + +# ✅ Final Verdict + +**This pairing gives you:** + +* Industrial-grade reliability where it matters + +* Low cost where you need quantity + +* True CO₂ everywhere (no fake eCO₂) + +* Clean PCB design + +* Future-proof scalability + + +
",, +44,Task,On hold,PCB schematic,,, 45,Requirements,Specified,"The system shall include a central server that aggregates and analyzes data from all main hubs across different farms, using machine learning algorithms to optimize control strategies for each farm based on collected data.","The system shall include a central server that aggregates and analyzes data from all main hubs across different farms, using machine learning algorithms to optimize control strategies for each farm based on collected data.",, 46,Requirements,Specified,"The sub-hub shall be capable of performing minor calibration functions, including sensor recalibration, before sending data to the main hub.","The sub-hub shall be capable of performing minor calibration functions, including sensor recalibration, before sending data to the main hub.",, 47,Requirements,Specified,"The main hub shall include control algorithms for managing the environment of the poultry house, including temperature, humidity, and air quality, by controlling the actuators like ventilation fans, heaters, lighting systems, and feeding systems.","The main hub shall include control algorithms for managing the environment of the poultry house, including temperature, humidity, and air quality, by controlling the actuators like ventilation fans, heaters, lighting systems, and feeding systems.",, @@ -20,6 +433,932 @@ 63,Requirements,Specified,"The system shall include fail-safe mechanisms to ensure continuous operation in case of failure in communication or hardware, including backup power and data storage.","The system shall include fail-safe mechanisms to ensure continuous operation in case of failure in communication or hardware, including backup power and data storage.",, 64,Requirements,Specified,"The system shall be designed for ease of use, with a user-friendly interface for farm managers to configure, monitor, and control the system.","The system shall be designed for ease of use, with a user-friendly interface for farm managers to configure, monitor, and control the system.",, 65,Requirements,Specified,"The system shall enable remote diagnostics for troubleshooting and support, reducing the need for on-site visits.","The system shall enable remote diagnostics for troubleshooting and support, reducing the need for on-site visits.",, +336,Phase,New,Main-Board pilot,,, +337,Phase,New,ASF_01 pilot,,, +338,Milestone,New,Requirements & Design,,337, +339,Milestone,New,Hardware Selection,,337,relates(#344); relates(#343); relates(#342); relates(#341); relates(#340) +340,Milestone,New,System Integration,,337,relates(#339) +341,Milestone,New,Stress & Load Testing,,337,relates(#339) +342,Milestone,New,Pilot Deployment,,337,relates(#339) +343,Milestone,New,AI Feedback Loop & Optimization,,337,relates(#339) +344,Milestone,New,Field Testing,,337,relates(#339) +345,Milestone,New,Functional / Software requirements,,349, +346,Milestone,New,Firmware Dev,,349, +347,Milestone,New,Dev phase 2 (integration),,349, +348,Milestone,New,Software testing UT/CC/INT tests,,349, +349,Phase,New,Sensor Hub pilot,,, +350,Milestone,New,Field testing phase1,,349, +351,Milestone,New,Field testing phase 2,,349, +352,Milestone,New,Firmware Dev,,336,relates(#357); relates(#356); relates(#355); relates(#354); relates(#353) +353,Milestone,New,Control Logic & OTA,,336,relates(#352) +354,Milestone,New,Field testing,,336,relates(#352) +355,Milestone,New,Functional / Software requirements,,336,relates(#352) +356,Milestone,New,Main-Hub Pilot,,336,relates(#352) +357,Milestone,New,Software testing UT/CC/INT tests,,336,relates(#352) +358,Phase,New,cloud server pilot,,, +359,Milestone,New,Data Pipeline + API,,358, +360,Milestone,New,AI/ML Engine,,358, +361,Phase,New,mobile app pilot,,, +362,Milestone,New,Mobile App Dev,,361, +365,Task,In progress,sensor selection [humid],"
+ +**Criteria:** + +* Availability. + +* Price \[USD\]. + +* Manufacturer. \[\]not boycott\]. + +* peripheral or communication protocoled. + +* Range quantity \[ex 0c to 100c\]. + +* Covered Area, \[m2\]. i**f possible.** + +* Data. \[public data about sensor\] + +* What type of external peripherals will be needed with esp-32 like (RS-485).",, +366,Task,In progress,sensor selection [temp],"**Criteria:** + +* Availability. + +* Price \[USD\]. + +* Manufacturer. \[\]not boycott\]. + +* peripheral or communication protocoled. + +* Range quantity \[ex 0c to 100c\]. + +* Covered Area, \[m2\]. i**f possible.** + +* Data. \[public data about sensor\] + +* What type of external peripherals will be needed with esp-32 like (RS-485). + + + +

Sensor

Range

Accuracy

Interface/Output

Typical Use

Datasheet Link

Product Link

DS18B20 (1-Wire, Digital)

–55…+125 °C

±0.5 °C (–10…+85 °C)

1-Wire Digital

HVAC, distributed temp sensing

Maxim DS18B20 Datasheet

Adafruit DS18B20 Module

LM35 (Analog)

–55…+150 °C

±0.5 °C at +25 °C

Analog (10 mV/°C)

Low-cost analog temp sensing

TI LM35 Datasheet

LM35 TO-92 Transistor

AD22100 (Analog)

–50…+150 °C

±2% of span

Analog (0.25–4.75 V)

Instrumentation/HVAC

Analog AD22100 Datasheet

Analog Devices AD22100 Product


+ +

Sensor

Range

Accuracy

Interface/Output

Typical Use

Datasheet Link

Product Link

DHT22 (AM2302)

0–100 %RH; –40…+80 °C

±2 %RH; ±0.5 °C

1-Wire Digital

Low-cost indoor measurements

DHT22/AM2302 Datasheet

Adafruit DHT22 Module

Si7021

0–100 %RH; –40…+125 °C

±3 %RH; ±0.4 °C

I²C Digital

Indoor climate sensing

Si7021 Datasheet

Adafruit Si7021 Breakout

HDC1080

0–100 %RH; –20…+85 °C (typ)

±2 %RH (typ); ±0.2 °C (typ)

I²C Digital

Battery-powered HVAC, IoT

HDC1080 Datasheet

Texas Instruments HDC1080


+ +

Sensor

Range (Temp/RH)

Accuracy (Temp/RH)

Interface/Output

Typical Use

Datasheet Link

Product Link

BME280

–40…+85 °C; 0–100 %RH

±1.0 °C; ±3 %RH

I²C/SPI Digital

Environmental sensing (weather stations)

BME280 Datasheet

Adafruit BME280 Breakout

SHT30-ARP

–40…+125 °C; 0–100 %RH

±0.3 °C; ±3 %RH

Analog Voltage

High-precision OEM applications

Sensirion SHT3x-ARP Datasheet

(Available via distributors)


+ +# ✅ Final Recommended Sensor Selections + +_(Temperature & Humidity)_ + +## 1️⃣ TEMPERATURE — Dedicated Sensor + +### ✔ Industrial Reference Sensor (Source of Truth) + +

Item

Selection

Sensor

PT1000 Class A Probe (industrial RTD)

Typical product

DOL 112 PT1000 / E+E / Omega / SensyTemp

Type

Platinum RTD (resistive)

Range

–40 to +100 °C (often higher)

Accuracy

Class A: ±0.15 °C @ 0 °C

Output

Passive RTD (2/3/4-wire)

Voltage

External excitation (ADC / RTD front-end)

Environment

Industrial, high humidity, dust

Why industrial

Physics-based sensor, long-term stability, no drift like IC sensors

+ +**Why this is the right reference** + +* RTDs are **the gold standard** for industrial temperature + +* No aging like silicon sensors + +* Survives ammonia, dust, moisture + +* Easy to recalibrate or replace probe only + + +📄 Datasheet example: +[https://dol-sensors.com/products/dol-112-temperature-sensor](https://dol-sensors.com/products/dol-112-temperature-sensor) + +🛒 Example product: +[https://www.qcsupply.com/dol-112-temperature-sensor.html](https://www.qcsupply.com/dol-112-temperature-sensor.html) + +### ✔ PCB-Integrable Temperature Sensor (Per-node) + +

Item

Selection

Sensor

TMP117 (Texas Instruments)

Type

Digital temperature IC

Range

–55 to +150 °C

Accuracy

±0.1 °C (–20 to +50 °C)

Interface

I²C

Voltage

1.8–5.5 V

Package

SMD (PCB mount)

Cost

~$6–10

+ +**Why this pairs well** + +* Very low drift + +* Factory calibrated + +* Excellent repeatability between units + +* Easy digital integration to ESP32 + +* Used widely in industrial electronics + + +📄 Datasheet: +[https://www.ti.com/lit/ds/symlink/tmp117.pdf](https://www.ti.com/lit/ds/symlink/tmp117.pdf) + +🛒 Product: +[https://www.ti.com/product/TMP117](https://www.ti.com/product/TMP117) + +### 🔁 How they work together + +* PT1000 defines **absolute temperature truth** + +* TMP117 sensors are **offset-calibrated** in firmware against PT1000 + +* You get **industrial accuracy at system level**, low cost per node + + +## 2️⃣ HUMIDITY — Dedicated Sensor + +### ✔ Industrial Reference Sensor (Source of Truth) + +

Item

Selection

Sensor

E+E EE07 / DOL 104 / Rotronic HygroClip

Type

Industrial RH transmitter

Range

0–100 % RH

Accuracy

±1.5–2 % RH

Output

4–20 mA or 0–10 V

Voltage

12–24 V

Environment

Condensation-resistant

Why industrial

Replaceable sensing element, long-term stability

+ +📄 Datasheet (E+E example): +[https://www.epluse.com/fileadmin/data/product/ee07/datasheet\_EE07.pdf](https://www.epluse.com/fileadmin/data/product/ee07/datasheet_EE07.pdf) + +🛒 Product: +[https://www.epluse.com/en/products/humidity-temperature/ee07.html](https://www.epluse.com/en/products/humidity-temperature/ee07.html) + +### ✔ PCB-Integrable Humidity Sensor (Per-node) + +

Item

Selection

Sensor

Sensirion SHT31 / SHT35

Type

Digital RH + Temp IC

Range

0–100 % RH

Accuracy

±2 % RH (SHT31), ±1.5 % (SHT35)

Interface

I²C

Voltage

2.4–5.5 V

Package

SMD

Cost

~$6–15

+ +📄 Datasheet: +[https://sensirion.com/media/documents/213E6A3B/63A5A569/Sensirion\_Humidity\_Sensors\_SHT3x\_Datasheet.pdf](https://sensirion.com/media/documents/213E6A3B/63A5A569/Sensirion_Humidity_Sensors_SHT3x_Datasheet.pdf) + +🛒 Product (SHT31): +[https://www.mouser.com/ProductDetail/Sensirion/SHT31-DIS-B](https://www.mouser.com/ProductDetail/Sensirion/SHT31-DIS-B) + +### 🔁 How they work together + +* Industrial RH sensor is used for **control + alarms** + +* SHT31 sensors give **spatial RH distribution** + +* Periodic calibration offsets keep all nodes aligned + + +## 3️⃣ COMBINED TEMPERATURE + HUMIDITY (Optional) + +### ✔ Industrial Combo Sensor + +

Sensor

Why

DOL 114

Designed for livestock houses

E+E EE210

Industrial HVAC grade

Rotronic HC2A

Very high accuracy

+ +### ✔ PCB Combo Sensor + +

Sensor

Why

Sensirion SHT31 / SHT35

Best stability vs price

Bosch BME280

Cheaper, good enough for trends

+ +## ✅ Final Architecture Summary + +

Measurement

Industrial Reference

PCB Sensor (×5+)

Temperature

PT1000 Class A

TMP117

Humidity

EE07 / DOL 104

SHT31 / SHT35

Combined T+RH

DOL 114

SHT31

+ +## + +
",, +367,Task,On hold,sensor selection [Particulate Matter],,, +368,Task,In progress,sensor selection [VOC],"**Criteria:** + +* Availability. + +* Price \[USD\]. + +* Manufacturer. \[\]not boycott\]. + +* peripheral or communication protocoled. + +* Range quantity \[ex 0c to 100c\]. + +* Covered Area, \[m2\]. i**f possible.** + +* Data. \[public data about sensor\] + +* What type of external peripherals will be needed with esp-32 like (RS-485). + + +
+ +results: +**Comprehensive CO₂ and VOC Sensor Inventory for Chicken Farm Climate Control** + +This inventory provides a detailed comparison of 12 sensors (6 CO₂ and 6 VOC) suitable for industrial climate control in closed chicken farms, focusing on the user's criteria: availability, price, manufacturer origin (non-boycott), communication protocol, measurement range, covered area, data/community support, and ESP32 integration requirements. + +The sensors include the three previously recommended options, the six sensors from the user's provided list, and three additional industrial-grade sensors from EU and Chinese manufacturers. + +

Sensor (Gas)

Availability

Price [USD] (Est.)

Manufacturer

Origin (Non-Boycott)

Protocol

Range Quantity

Covered Area [m²]

Data/Community Support

ESP32 External Peripherals Needed

1. Sensirion SGP41 (VOC)

High

$15 - $25

Sensirion

Switzerland

I²C

Relative VOC Index (0-500)

N/A (Module)

Very High (Market leader, dedicated ESP32 libraries)

Minimal. Direct I²C connection.

2. ACI VOC-R (VOC)

Moderate

~$547

ACI

USA

RS-485 (Modbus) / 4-20mA / 0-10V

0–1,000 ppb

N/A (Room-mounted)

Moderate (Industrial focus, professional manuals)

RS-485 Transceiver or ADC/Current Loop Interface for analog outputs. Stable 16V-35V supply.

3. Sensirion SGP30 (VOC)

High

~$8

Sensirion

Switzerland

I²C

TVOC: 0–60,000 ppb

N/A (Module)

Very High (Extensive community, low-cost)

Minimal. Direct I²C connection.

4. Bosch BME680 (VOC)

Very High

~$19 (Breakout)

Bosch Sensortec

Germany

I²C / SPI

Relative IAQ Index

N/A (Module)

Very High (Extensive community, well-supported libraries)

Minimal. Direct I²C/SPI connection.

5. Cubic P300 (VOC/Multi)

Moderate

$150 - $250

Cubic Sensor and Instrument

China

RS-485 (Modbus)

TVOC: 0-5000 ppb

N/A (Module)

Moderate (Growing industrial use, good documentation)

RS-485 Transceiver. Stable 5V supply.

6. E+E EE891 (VOC/Multi)

Moderate

$300 - $400

E+E Elektronik

Austria

RS-485 (Modbus)

TVOC: 0-100% (Relative)

N/A (Module)

High (Industrial focus, excellent documentation)

RS-485 Transceiver. Stable 12V/24V supply.


+ +

Sensor (Gas)

Availability

Price [USD] (Est.)

Manufacturer

Origin (Non-Boycott)

Protocol

Range Quantity

Covered Area [m²]

Data/Community Support

ESP32 External Peripherals Needed

Data sheet

1. Sensirion SGP41 (VOC)

High

$15 - $25

Sensirion

Switzerland

I²C

Relative VOC Index (0-500)

N/A (Module)

Very High (Market leader, dedicated ESP32 libraries)

Minimal. Direct I²C connection.

SGP41 Datasheet

4. Bosch BME680 (VOC)

Very High

~$19 (Breakout)

Bosch Sensortec

Germany

I²C / SPI

Relative IAQ Index

N/A (Module)

Very High (Extensive community, well-supported libraries)

Minimal. Direct I²C/SPI connection.

BME680 Datasheet

+ + +Extended list: + + +

Sensor (Output Gas)

Availability

Price (USD)

Manufacturer (Origin)

Interface

Range / Output (units)

Covered Area

Data/Community Support

ESP32 Peripherals Needed

Sensirion SGP41(VOC sensor)

High (in stock, ~1,300+)

~$8 (1 pc)

Sensirion (Switzerland)

I²C (digital)

Processed output: VOC index 0–500;Measurement range ~0–1000 ppm VOC

N/A (chip/module)

Very high (market leader; plentiful code/libraries)

Minimal – direct I²C bus

Sensirion SGP30(TVOC + eCO₂)

Moderate (limited stock; product marked obsolete)

~$8 (legacy/obsolete)

Sensirion (Switzerland)

I²C (digital)

TVOC (total VOC) 0–1000 ppb;CO₂-equivalent 0–1000 ppm

N/A (chip/module)

Very high (well-known in IoT/hobbyist community)

Minimal – direct I²C bus

Sensirion SGP40(VOC sensor)

High (in production)

~$6.70

Sensirion (Switzerland)

I²C (digital)

VOC index 0–500;Measurement range ~0–1000 ppm VOC

N/A (chip/module)

Very high (successor to SGP30, broad library support)

Minimal – direct I²C bus

Bosch BME688(VOC/gas + P/T/H)

Very high (stock ≈18k)

$8.65

Bosch Sensortec (Germany)

I²C/SPI (digital)

Detects VOCs (gas index) to ppb sensitivity

N/A (chip/module)

High (Bosch ecosystem; BSEC libraries available)

Minimal – direct I²C/SPI bus

AMS/ScioSense iAQ-Core C(TVOC + eCO₂)

Moderate (discontinued module)

~$15–20 (est.)

AMS AG (Austria)

I²C (digital)

CO₂-eq 450–2000 ppm;TVOC 125–600 ppb

N/A (module)

High (well-documented IAQ module)

Minimal – direct I²C bus

ScioSense ENS160(TVOC + eCO₂)

High (current product)

~$6.78

ScioSense (Netherlands)

I²C/SPI (digital)

Outputs equivalent CO₂ and TVOC (wideband MOX)

N/A (chip/module)

Moderate (newer product; growing support)

Minimal – direct I²C/SPI bus

#

Sensor (short)

Manufacturer (origin)

Est. price (USD)

Protocol / Output

VOC measurement type / range

Accuracy / sensitivity (from datasheet)

Operating voltage

Availability (distributor)

Datasheet

Product / distributor page

PCB-integrable

1

Sensirion SGP41

Sensirion (Switzerland)

$5–$10 (IC, volume pricing varies)

I²C (digital)

VOC + NOx index; preprocessed gas-index signals for IAQ (index outputs)

High sensitivity; on-chip hotplate + algorithm (see datasheet).

3.3 V typical (check datasheet).

In stock at distributors / reel options.

Datasheet — SGP41 (Sensirion PDF). (Sensirion AG)

Mouser / Future Electronics product pages (SGP41). (Mouser Electronics)

YES — SMD IC (reel / DFN) — meant for PCB assembly

2

Sensirion SGP30

Sensirion (Switzerland)

~$6–$12 (chip / breakout ~$8–$20)

I²C (digital)

TVOC & eCO₂ (equivalent CO₂) — IAQ indices (TVOC range in datasheet)

Typical accuracy ~10–20% for TVOC/eCO₂ (algorithmic). See datasheet.

Chip-level low-voltage (use breakout for 3.3 V/5 V systems).

Widely available (breakouts common); SGP30 legacy/obsolescence notes — check supply.

Datasheet — SGP30 (Sensirion PDF). (Sensirion AG)

Adafruit / distributors (SGP30 breakout pages). (Micro Center)

YES — SMD IC (DFN) or breakout

3

Sensirion SGP40

Sensirion (Switzerland)

~$6–$12 (chip; breakout slightly more)

I²C (digital)

VOC index (humidity compensated) — intended for IAQ apps

Sensitivity & repeatability per datasheet (use Gas Index algorithm).

3.3 V typical (datasheet).

In production; distributor stock varies.

Datasheet — SGP40 (Sensirion PDF). (Sensirion AG)

Sensirion product page / distributors. (Sensirion AG)

YES — SMD IC (reel) / OEM use

4

Bosch BME688 (BME68x family)

Bosch Sensortec (Germany)

~$8–$20 (chip; breakout ~$15–$30)

I²C / SPI (digital)

Gas/VOC index (uses AI/BSEC libs) — provides TVOC/IAQ values (ppb-level detection)

Good sensitivity; use Bosch BSEC library for compensated outputs; see datasheet.

1.2–3.6 V (chip-level); breakout boards provide 3.3 V.

Widely available at major distributors (Mouser, Digi-Key).

Datasheet — BME688 (Bosch PDF). (Bosch Sensortec)

Mouser / product page. (Mouser Electronics)

YES — SMD IC (3×3 mm LGA) — suitable for PCB assembly

5

ScioSense ENS160

ScioSense (Netherlands)

~$6–$12 (IC)

I²C / SPI (digital)

TVOC + eCO₂ (MOx multi-element sensor, processed outputs)

Multi-MOX, humidity compensated; see ENS160 datasheet for sensitivity & warm-up times.

1.67–1.98 V (chip); use breakout/regulator for 3.3 V systems.

In stock at Mouser and other distributors.

Datasheet — ENS160 (ScioSense PDF). (ScioSense)

Mouser product page (ENS160). (Mouser Electronics)

YES — SMD (LGA) — designed for PCB use

6

ACI VOC-R (room transmitter)

ACI / WorkACI (USA distribution)

~$300–$600 (industrial transmitter) — outside $5–30 but included for industrial reference

RS-485 (Modbus), 4–20 mA, 0–10 V

TVOC: 0–1000 ppb (typical metal-oxide sensor output for TVOC)

Industrial spec sheet lists accuracy (see datasheet)

16–35 V (typical industrial line power)

Widely sold through HVAC distributors; datasheet & vendor pages available.

Datasheet — ACI VOC datasheet (PDF). (Kele)

Product pages (ACI / RSP Supply / EnergyControl). (Blackhawk Supply)

NO — room transmitter (not PCB SMD)


+ +
+ +## ✅ VOC Sensor Selection (Budget-constrained) + +

Role

Sensor

Manufacturer (Origin)

Est. Price

Protocol / Output

VOC Type

Operating Voltage

Availability

Datasheet

Product link

Why selected

Reference (Reliable industrial-like)

SGP40 VOC (digital module)

Sensirion / breakout (Switzerland)

~$14–$35

I²C (digital)

Relative VOC / IAQ index

3.3–5 V (module)

High

uses SGP40 data (RS Online)

DFRobot SGP40 breakout (~$14.50) (DFRobot Electronics) / Waveshare SGP40 (~$34.49) (The Retail Market)

Good stability & digital output; fits budget; widely available; mature IAQ performance

Distributed / PCB-integrable (×5)

Sensirion SGP41 DFN (SMD)

Sensirion (Switzerland)

~$4–$10 (IC)

I²C (digital)

VOC + NOx index

1.7–3.6 V (IC)

High

SGP41 datasheet (PDF) (Sensirion Admin)

RS Online SGP41 DFN listing (~€8/≈$9.70) (RS Components)

True PCB integrable SMD; very low cost; suitable for mass repeating; same tech family

+ +## 📌 Why These Choices + +### 🔹 **Reference: SGP40 Digital VOC Module (~$14–$35)** + +* **Budget-friendly “industrial-ish” reference element:** While not a full standalone industrial transmitter, the **SGP40 gas sensor breakout module** is a _true Sensirion VOC sensor_ with a simple wired I²C interface – suitable as your system’s anchor. ([DFRobot Electronics](https://www.dfrobot.com/product-2241.html?utm_source=chatgpt.com)) + +* **Digital interface (I²C)** — works cleanly into your ESP32 system without external ADC or analog conditioning. ([The Retail Market](https://www.retailmarket.net/products/digital-sgp40-voc-volatile-organic-compounds-gas-sensor-for-easy-integration-into-air-treatment-devices-and-air-quality-monitors-i2c-bus-compatible-with-raspberry-pi-stm32/?utm_source=chatgpt.com)) + +* **Operating voltage:** typically **3.3 V (5 V tolerant)** on modules; works well with your 5 V or 12/24 V via regulator. ([The Retail Market](https://www.retailmarket.net/products/digital-sgp40-voc-volatile-organic-compounds-gas-sensor-for-easy-integration-into-air-treatment-devices-and-air-quality-monitors-i2c-bus-compatible-with-raspberry-pi-stm32/?utm_source=chatgpt.com)) + +* **Good availability & pricing:** breakout boards are plentiful and often under $30 – e.g., DFRobot’s ~**$14.50** version or Waveshare’s ~$34.49 variant. ([DFRobot Electronics](https://www.dfrobot.com/product-2241.html?utm_source=chatgpt.com)) + +* **Not a module with industrial enclosure:** it’s a breakout — you’ll need enclosure/protection, but the core sensor IC is robust and digitally accessible. + + +📌 Example product pages: + +* SGP40 breakout by DFRobot — ~$14.50: [https://www.dfrobot.com/product-2241.html](https://www.dfrobot.com/product-2241.html) ([DFRobot Electronics](https://www.dfrobot.com/product-2241.html?utm_source=chatgpt.com)) + +* Digital SGP40 module (Waveshare) — ~$34.49: [https://www.retailmarket.net/products/digital-sgp40-voc-volatile-organic-compounds-gas-sensor](https://www.retailmarket.net/products/digital-sgp40-voc-volatile-organic-compounds-gas-sensor) ([The Retail Market](https://www.retailmarket.net/products/digital-sgp40-voc-volatile-organic-compounds-gas-sensor-for-easy-integration-into-air-treatment-devices-and-air-quality-monitors-i2c-bus-compatible-with-raspberry-pi-stm32/?utm_source=chatgpt.com)) + + +### 🔹 **Distributed / PCB-integrable: Sensirion SGP41 DFN (~$4–$10)** + +* **SMD / PCB mount device:** The **SGP41** is a small SMD (DFN) VOC + NOx sensor suitable for mounting directly on your custom boards. ([Sensirion Admin](https://admin.sensirion.com/media/documents/5FE8673C/61E96F50/Sensirion_Gas_Sensors_Datasheet_SGP41.pdf?utm_source=chatgpt.com)) + +* **Digital I²C interface:** Easy to connect to ESP32 without extra components. ([RS Components](https://befr.rs-online.com/web/p/environmental-sensor-ics/2348991?utm_source=chatgpt.com)) + +* **Operating voltage:** Designed for 1.7–3.6 V (use your board’s regulator to supply 3.3 V). ([Sensirion Admin](https://admin.sensirion.com/media/documents/5FE8673C/61E96F50/Sensirion_Gas_Sensors_Datasheet_SGP41.pdf?utm_source=chatgpt.com)) + +* **Low cost & scalable:** Buying in small quantities (eg ~€8 ≈ $9.7) makes it ideal as a distributed sensor. ([RS Components](https://befr.rs-online.com/web/p/environmental-sensor-ics/2348991?utm_source=chatgpt.com)) + +* **Same technology family as SGP40:** This means your reference and distributed nodes use compatible MOx/CMOSens tech, making correction and calibration more consistent. + + +📌 Example product page: + +* SGP41 DFN (RS Online) — ~€8 / ~ $9.7: [https://befr.rs-online.com/web/p/environmental-sensor-ics/2348991](https://befr.rs-online.com/web/p/environmental-sensor-ics/2348991) ([RS Components](https://befr.rs-online.com/web/p/environmental-sensor-ics/2348991?utm_source=chatgpt.com)) + + +## 🧠 Notes on Accuracy & Function + +* **SGP40 & SGP41** sensors are **VOC index / IAQ sensors** — they do not provide absolute concentrations of every VOC compound, but rather a processed gas index representing overall VOC activity. For ventilation control, this is generally sufficient. ([DFRobot Electronics](https://www.dfrobot.com/product-2241.html?utm_source=chatgpt.com)) + +* They perform well in **trend detection** and **comparative monitoring** across multiple sensors, and can be calibrated relative to each other to improve spatial response performance. + + +## 📌 Wiring & Integration Tips + +* Both reference module (SGP40 breakout) and distributed sensors (SGP41 SMD) communicate **via I²C**, which is perfect for multi-node systems with ESP32. + +* Use proper pull-ups on the I²C bus and short lines for best signal quality. + +* Power them from a **3.3 V rail** regulated from your 5 V/12 V system. + + +## ⚡ Summary Recommendation + +

Role

Sensor

Best Use

Reference / Source of Truth

SGP40 module (~$14–$35)

Strong digital sensor to anchor 5 nodes; wired I²C; fits your cost cap.

Distributed / PCB sensors (×5)

SGP41 DFN (~$4–$10)

PCB-friendly, same family tech; easy integration to ESP32; low per-node cost.

+ +## + +
",, +369,Task,New,sensor selection [Light],"**Criteria:** + +* Availability. + +* Price \[USD\]. + +* Manufacturer. \[\]not boycott\]. + +* peripheral or communication protocoled. + +* Range quantity \[ex 0c to 100c\]. + +* Covered Area, \[m2\]. i**f possible.** + +* Data. \[public data about sensor\] + +* What type of external peripherals will be needed with esp-32 like (RS-485). + + +

Sensor (Example Product)

Interface/Output

Measured Range

Price (approx)

Notes

BH1750 (Adafruit BH1750 Breakout)

I²C (digital, lux)

0–65,535 lux

~$4.50

Low-cost 16-bit lux sensor; up to ~65k lux (can extend to ~100k). Plug-&-play; no ADC needed.

VEML7700 (Adafruit VEML7700)

I²C (digital, lux)

0–120,000 lux

~$4.95

Wide-range ambient-light sensor; 16-bit resolution, 0.0036 lux sensitivity. 0–120k lux range. Easy library support.

TSL2591 (Adafruit TSL2591)

I²C (digital, lux)

~0.188 μlux–88,000 lux

~$6.95

High-dynamic-range sensor (visible+IR); measures from ultra-dark (0.000188 lux) to very bright (88k lux). Good for both indoor and bright outdoor light.

ALS-PT19 Analog Photodiode (Adafruit)

Analog (voltage)

~Analog 0–VCC (rises with light)

~$2.50

Simple analog photodiode breakout (PT19). Voltage output increases with light. Requires ADC on MCU. Covers roughly indoor light levels.

TEMT6000 Analog Sensor (DFRobot)

Analog (voltage)

1–1000 lux

~$5.90

Analog ambient-light sensor (TEMT6000). Range ~1–1000 lux, human-eye spectral response. 0–5 V output proportional to light (max ~1000 lux).

Generic LDR Module (photoresistor)

Analog (voltage)

~0–10,000+ lux (uncalibrated)

~$1–3 (clone modules)

Cheap photocell module (often with LM393 comparator). Analog output (0–V) roughly ~0–10k lux. Very low cost but non-linear and needs calibration. Often used with a simple voltage divider.


+ +# 4\. Light Intensity (Illuminance / Lux) + +## 4.1 Selection Criteria + +Light sensors in poultry farms are used for **photoperiod control, uniformity of illumination, and energy optimization**, not laboratory-grade optical measurements. + +Key criteria: + +* Stable and repeatable lux readings + +* Digital output preferred to reduce ADC noise + +* Wide enough dynamic range to handle: + + * Low night lighting (1–20 lux) + + * Daylight intrusion from windows (1,000–20,000 lux) + +* PCB compatibility for distributed sensing + +* Low cost to allow multiple sensors per house + +* Minimal temperature drift + + +## 4.2 Recommended Light Sensors + +### Criteria + +


Reference Sensor

Distributed PCB Sensor (×5+)

Sensor Name

VEML7700 (module)

BH1750 (module)

Manufacturer

Vishay (USA)

Rohm (Japan)

Sensor Technology

Silicon photodiode + ADC

Silicon photodiode + ADC

Measurement Output

Absolute lux (digital)

Absolute lux (digital)

Role in System

Lighting control reference

Spatial light uniformity

Typical Price

~$4–6

~$3–5

Best Use

Day/night decision, control anchor

Multi-point comparison

Communication

I²C

I²C

Integration Form

PCB module / SMD IC

PCB module / SMD IC

Lux Range

~0–120,000 lux

~0–65,000 lux

PCB Compatibility

Excellent

Excellent

Datasheet

https://www.vishay.com/docs/84286/veml7700.pdf

https://www.rohm.com/products/sensors/light-sensors/bh1750fvi-product

+ +### Why these two? + +#### ✅ **VEML7700 — Reference Sensor** + +* Very wide dynamic range (handles sunlight through windows) + +* Good low-lux sensitivity (night mode / dim light) + +* Stable, temperature-compensated readings + +* Digital output → no ADC drift + +* Still **cheap enough** to deploy as a reference + + +This becomes your **lighting “truth anchor”**. + +#### ✅ **BH1750 — Distributed Sensor** + +* Extremely common and well understood + +* Cheap and reliable + +* Good enough accuracy for **relative comparison** + +* Simple I²C integration + +* Very low firmware complexity + + +Ideal for **multiple mounting points** across the barn. + +## 4.3 Architecture Notes (Light) + +### System Philosophy + +Light is **not a safety-critical parameter** like NH₃. +Therefore: + +* No electrochemical “truth” sensor needed + +* Digital lux sensors are sufficient + + +Recommended architecture: + +```text +[VEML7700] + ↓ +Reference lux value + ↓ +Lighting control decision + ↓ +[BH1750 × N nodes] +``` + +### Recommended Deployment + +* **1 × VEML7700**: + + * Near center of the barn + + * Shielded from direct lamp glare + +* **5–10 × BH1750**: + + * Near walls + + * Near windows + + * Near feeder/drinker lines + + * At bird-eye height + + +This ensures: + +* Uniform lighting + +* Detection of bright/dark zones + +* Compensation for daylight leakage + + +### Firmware Strategy + +* Read lux every 1–5 seconds + +* Apply: + + * Moving average (5–30 samples) + + * Daylight detection threshold + +* Control logic example: + + * If average lux < target → increase artificial light + + * If lux > target (sunlight) → dim or turn off lamps + + +## 4.4 Why NOT Industrial Sensors for This Role + +

Sensor

Reason Not Selected

DOL 16

Excellent, but far above budget and analog-only

Aranet LUX

Wireless IoT, expensive, slow update

Apogee PAR

Measures PAR, not lux; overkill

Li-Cor

Research-grade, unnecessary

+ +Industrial sensors are useful for **certification or auditing**, but **not needed** for control loops in closed poultry houses. + +## 4.5 Final Recommendation (Clear & Actionable) + +### ✅ Use this pair: + +* **Reference Light Sensor:** + **VEML7700** + +* **Distributed / PCB Sensor:** + **BH1750** + + +This mirrors your VOC and NH₃ strategy exactly: + +

Parameter

Strategy

VOC

One reference + many cheap

NH₃

One electrochemical + many MOS

Light

One wide-range lux + many cheap lux


+ +
",, +370,Task,New,Backup plan for cloud server,,, +371,Task,New,OTA arch,"Criteria: + +* Responsibilities. + +* Interfaces. + +* Dependencies. + +* Constrains. + +* Link to requirement. + +* (Takes and periodicity and priority). + +* Expected behavior (for testing) + + * Behavior diagram with dependencies. + + * Use case component.",, +372,Task,New,main hub APIS,"Criteria: + +* Responsibilities. + +* Interfaces. + +* Dependencies. + +* Constrains. + +* Link to requirement. + +* (Takes and periodicity and priority). + +* Expected behavior (for testing) + + * Behavior diagram with dependencies. + + * Use case component.",, +373,Task,New,Event system,"Criteria: + +* Responsibilities. + +* Interfaces. + +* Dependencies. + +* Constrains. + +* Link to requirement. + +* (Takes and periodicity and priority). + +* Expected behavior (for testing) + + * Behavior diagram with dependencies. + + * Use case component.",, +374,Task,New,Sensor manager,"Criteria: + +* Responsibilities. + +* Interfaces. + +* Dependencies. + +* Constrains. + +* Link to requirement. + +* (Takes and periodicity and priority). + +* Expected behavior (for testing) + + * Behavior diagram with dependencies. + + * Use case component.",, +375,Task,New,STM,"Criteria: + +* Responsibilities. + +* Interfaces. + +* Dependencies. + +* Constrains. + +* Link to requirement. + +* (Takes and periodicity and priority). + +* Expected behavior (for testing) + + * Behavior diagram with dependencies. + + * Use case component.",, +376,Task,New,MCs,"Criteria: + +* Responsibilities. + +* Interfaces. + +* Dependencies. + +* Constrains. + +* Link to requirement. + +* (Takes and periodicity and priority). + +* Expected behavior (for testing) + + * Behavior diagram with dependencies. + + * Use case component.",, +377,Task,New,Diag taks,"Criteria: + +* Responsibilities. + +* Interfaces. + +* Dependencies. + +* Constrains. + +* Link to requirement. + +* (Takes and periodicity and priority). + +* Expected behavior (for testing) + + * Behavior diagram with dependencies. + + * Use case component.",, +378,Task,New,Error handling,"Criteria: + +* Responsibilities. + +* Interfaces. + +* Dependencies. + +* Constrains. + +* Link to requirement. + +* (Takes and periodicity and priority). + +* Expected behavior (for testing) + + * Behavior diagram with dependencies. + + * Use case component.",, +379,Task,On hold,Presentation of HW design,,, +380,Task,In progress,Review sensor list,1- Temp & Humid,, +381,Task,In progress,review sensor list,"Review:  + +1- NH3 + +
",, +382,Task,New,Implement test arena,,, +383,Task,New,implement monitor page for asf resources,,, +388,Feature,In specification,[F-DAQ-01] Multi-Sensor Data Acquisition,"The Sensor Hub shall acquire environmental data from multiple heterogeneous sensors installed on the device.\n\nThis feature enables concurrent acquisition of temperature, humidity, CO2, NH3, VOC, particulate matter, and light sensors.\n\nEach sensor is associated with a predefined hardware slot and a dedicated driver abstraction.\n\nOnly sensors detected as present and enabled shall be initialized and included in the acquisition cycle.",,includes(#394); includes(#395); includes(#396); includes(#393) +389,Feature,In specification,[F-DAQ-02] High-Frequency Sampling and Local Filtering,The Sensor Hub shall perform high-frequency sampling for each enabled sensor during an acquisition cycle.\n\nEach sensor shall be sampled multiple times (default: 10 samples per cycle) within a bounded time window.\n\nThe system shall apply a local filtering mechanism to raw samples to generate a single representative sensor value.\n\nFiltering is performed locally on the Sensor Hub to reduce noise and improve data stability before further processing.,,includes(#399); includes(#398); includes(#397); includes(#393) +390,Feature,In specification,[F-DAQ-03] Timestamped Sensor Data Generation,"The Sensor Hub shall generate a timestamped sensor data record for each processed sensor value.\n\nTimestamps shall be generated after completion of local filtering and shall represent the effective measurement time.\n\nEach sensor data record shall include sensor identifier, sensor type, filtered value, unit of measurement, timestamp, and data validity status.\n\nTimestamped data shall be made available for persistence and on-demand communication with the Main Hub.",,includes(#400); includes(#401); includes(#402); includes(#403); includes(#393) +393,Feature,In specification,[F-DAQ] Sensor Data Acquisition Features,"# **ASF Sensor Hub** + +## **Feature Engineering Specification** + +## **Sensor Data Acquisition Features** + +## **1\. Feature Overview** + +### **Feature Name** + +Sensor Data Acquisition Features + +### **Feature ID** + +FEAT-DAQ + +### **Subsystem** + +ASF Sensor Hub (Sub-Hub) + +### **Target Platform** + +ESP32-S3–based embedded system + +### **Scope** + +This feature defines the capabilities of the Sensor Hub related to: + +* Environmental sensor data acquisition + +* Local preprocessing and filtering + +* Timestamping and preparation of sensor data for persistence and communication + + +This feature **does NOT include**: + +* Main Hub processing + +* Cloud analytics + +* Control logic + +* OTA, diagnostics, or persistence mechanisms (referenced only as dependencies) + + +## **2\. Purpose and Engineering Rationale** + +Modern poultry farm automation systems require **high-resolution, reliable, and time-correlated environmental data** to enable: + +* Accurate environmental control + +* Early fault detection + +* Advanced analytics and machine learning + + +The Sensor Data Acquisition feature ensures: + +* Deterministic sensor sampling + +* Noise-resilient measurements + +* Temporal traceability of data + +* Decoupling of acquisition from communication and control + + +This aligns with **distributed intelligence principles** used in leading international poultry automation systems. + +## **3\. Feature Decomposition** + +The Sensor Data Acquisition feature is decomposed into the following sub-features: + +

Sub-Feature ID

Name

F-DAQ-01

Multi-Sensor Data Acquisition

F-DAQ-02

High-Frequency Sampling and Local Filtering

F-DAQ-03

Timestamped Sensor Data Generation

+ +## **4\. Functional Description** + +### **4.1 F-DAQ-01: Multi-Sensor Data Acquisition** + +#### **Description** + +The Sensor Hub acquires environmental data from multiple heterogeneous sensors connected to dedicated hardware interfaces. + +#### **Supported Sensor Types** + +* Temperature + +* Relative Humidity + +* Carbon Dioxide (CO₂) + +* Ammonia (NH₃) + +* Volatile Organic Compounds (VOC) + +* Particulate Matter (PM) + +* Light Intensity + + +Each sensor: + +* Is mapped to a predefined hardware slot + +* Has a dedicated driver abstraction + +* Can be independently enabled or disabled + + +#### **Key Characteristics** + +* Concurrent sensor handling + +* Modular sensor driver architecture + +* Runtime awareness of sensor presence + + +### **4.2 F-DAQ-02: High-Frequency Sampling and Local Filtering** + +#### **Description** + +For each enabled sensor, the system performs multiple raw readings per acquisition cycle and applies a local filtering mechanism to produce a single representative value. + +#### **Sampling Behavior** + +* Each sensor is sampled **N times per cycle** (default: 10) + +* Sampling occurs within a bounded time window + +* Sampling frequency is configurable via Machine Constants + + +#### **Filtering Behavior** + +* Filtering is executed locally on the Sensor Hub + +* Filtering algorithms are abstracted and replaceable + +* Examples (non-exhaustive): + + * Moving average + + * Median filter + + * Outlier rejection + + +#### **Objective** + +* Reduce sensor noise + +* Improve data stability + +* Avoid propagating raw sensor jitter upstream + + +### **4.3 F-DAQ-03: Timestamped Sensor Data Generation** + +#### **Description** + +Each processed sensor value is associated with a timestamp generated by the Sensor Hub. + +#### **Timestamp Characteristics** + +* Generated after filtering completion + +* Represents the effective measurement time + +* Based on system time (RTC or synchronized clock) + + +#### **Sensor Data Record** + +Each record includes: + +* Sensor ID + +* Sensor type + +* Filtered value + +* Unit of measurement + +* Timestamp + +* Data validity status + + +## **5\. Operational Flow** + +### **Normal Acquisition Cycle** + +1. Detect enabled sensors + +2. Initialize sensor drivers (if not already active) + +3. Perform high-frequency sampling per sensor + +4. Apply local filtering + +5. Generate timestamp + +6. Create sensor data record + +7. Forward data to: + + * Data Persistence component + + * Communication component (on request) + + +## **6\. Constraints and Assumptions** + +### **Constraints** + +* Sensor acquisition must not block system-critical tasks + +* Sampling and filtering must complete within a bounded cycle time + +* Memory usage must be deterministic + + +### **Assumptions** + +* Sensor presence detection is handled by a separate feature + +* Time synchronization is provided by another system component + +* Storage and communication are decoupled from acquisition + + +## **7\. Architecture Diagram (PlantUML)** + +### **7.1 Sensor Data Acquisition – Logical View** + +
+ +`@startuml package ""Sensor Hub"" {  component ""Sensor Drivers"" as SD  component ""Sampling Engine"" as SE  component ""Filtering Engine"" as FE  component ""Timestamp Service"" as TS  component ""Sensor Data Buffer"" as DB  SD --> SE : raw samples  SE --> FE : sampled data  FE --> TS : filtered value  TS --> DB : timestamped record } @enduml` + +### **7.2 Acquisition Cycle Sequence Diagram** + +
+ +`@startuml participant ""Sensor Driver"" as S participant ""Sampling Engine"" as SE participant ""Filtering Engine"" as FE participant ""Timestamp Service"" as TS S -> SE : read() loop N samples  SE -> S : sample() end SE -> FE : raw sample set FE -> TS : filtered value TS -> FE : timestamp @enduml` + +## **8\. Formal System SHALL Requirements** + +### **8.1 Requirement Style** + +* Each requirement uses **“The system shall …”** + +* Each requirement has a unique ID + +* Requirements are atomic and testable + + +### **8.2 Requirements List** + +#### **Multi-Sensor Acquisition** + +* **REQ-DAQ-001** + The system shall support acquisition of data from multiple environmental sensor types simultaneously. + +* **REQ-DAQ-002** + The system shall provide a dedicated software driver abstraction for each supported sensor type. + +* **REQ-DAQ-003** + The system shall acquire sensor data only from sensors detected as present and enabled. + + +#### **High-Frequency Sampling & Filtering** + +* **REQ-DAQ-004** + The system shall sample each enabled sensor multiple times within a single acquisition cycle. + +* **REQ-DAQ-005** + The system shall apply a local filtering mechanism to raw sensor samples to produce a single representative value. + +* **REQ-DAQ-006** + The system shall allow configuration of sampling count and filtering parameters via system configuration data. + + +#### **Timestamped Data Generation** + +* **REQ-DAQ-007** + The system shall associate each processed sensor value with a timestamp. + +* **REQ-DAQ-008** + The system shall generate timestamps after completion of filtering. + +* **REQ-DAQ-009** + The system shall include sensor identifier, sensor type, value, unit, timestamp, and validity status in each sensor data record. + + +## **9\. Feature-to-Requirement Traceability** + +

Feature ID

Requirement IDs

F-DAQ-01

REQ-DAQ-001, REQ-DAQ-002, REQ-DAQ-003

F-DAQ-02

REQ-DAQ-004, REQ-DAQ-005, REQ-DAQ-006

F-DAQ-03

REQ-DAQ-007, REQ-DAQ-008, REQ-DAQ-009

",,includes(#528); includes(#390); includes(#388); includes(#389) 394,Requirements,In specification,[SR-DAQ-001] Support Multi-Sensor Environmental Data Acquisition,"The system shall support simultaneous acquisition of environmental data from multiple sensor types, including temperature, humidity, CO2, NH3, VOC, particulate matter, and ambient light.\n\nThis requirements traces to feature [F-DAQ-01].",,includes(#388) 395,Requirements,In specification,[SR-DAQ-002] Dedicated Sensor Slot Mapping,The system shall assign each supported sensor type to a predefined and unique hardware slot to prevent incorrect sensor insertion or configuration.\n\nThis requirements traces to feature [F-DAQ-01].,,includes(#388) 396,Requirements,In specification,[SR-DAQ-003] Sensor Presence Detection,The system shall detect the physical presence of each sensor via a dedicated hardware detection signal prior to sensor initialization.\n\nThis requirements traces to feature [F-DAQ-01].,,includes(#388) @@ -30,6 +1369,10 @@ 401,Requirements,In specification,[SR-DAQ-008] Timestamp Generation for Sensor Data,The system shall generate a timestamp for each filtered sensor value upon completion of the acquisition and filtering process.\n\nThis requirements traces to feature [F-DAQ-03].,,includes(#390) 402,Requirements,In specification,[SR-DAQ-009] Timestamped Sensor Data Record Structure,"The system shall generate a timestamped sensor data record containing at minimum the sensor identifier, sensor type, filtered value, unit of measurement, timestamp, and data validity status.\n\nThis requirements traces to feature [F-DAQ-03].",,includes(#390) 403,Requirements,In specification,[SR-DAQ-010] Availability of Latest Sensor Data,The system shall maintain the most recent timestamped sensor data record in memory and make it available for persistence and on-demand communication requests.\n\nThis requirements traces to feature [F-DAQ-03].,,includes(#390) +405,Feature,In specification,[F-DQC-01] Automatic Sensor Detection,The system provides automatic detection of physically connected sensors on the Sensor Hub. Each sensor slot includes a dedicated detection mechanism that allows the system to identify whether a sensor is installed and eligible for initialization. Detected sensors are dynamically registered during system startup or reinitialization.,,includes(#411); includes(#410); includes(#409); includes(#424) +406,Feature,In specification,[F-DQC-02] Sensor Type Enforcement,"The system enforces strict sensor-to-slot compatibility. Each physical sensor slot is assigned to a specific sensor type, and incorrect sensor insertion is detected and rejected to prevent invalid data acquisition and configuration errors.",,includes(#414); includes(#413); includes(#412); includes(#424) +407,Feature,In specification,[F-DQC-03] Sensor Failure Detection,"The system continuously monitors sensor behavior to detect failures such as disconnection, non-responsiveness, or invalid measurements. Failed sensors are isolated, logged, and reported to the Main Hub.",,includes(#418); includes(#417); includes(#416); includes(#415); includes(#424) +408,Feature,In specification,[F-DQC-04] Machine Constants & Calibration Management,"The system manages Machine Constants and calibration parameters defining sensor configuration, calibration coefficients, and communication identifiers. These parameters are persisted in non-volatile storage and may be updated remotely via the Main Hub.",,includes(#422); includes(#421); includes(#420); includes(#423); includes(#419); includes(#424) 409,Requirements,In specification,[SR-DQC-001] Detect Sensor Presence,The system shall detect the physical presence of each sensor using a dedicated hardware-based detection mechanism. This requirement traces to feature [F-DQC-01].,,includes(#405) 410,Requirements,In specification,[SR-DQC-002] Perform Sensor Detection During Initialization,The system shall perform sensor presence detection during system startup and after any reinitialization or reconfiguration event. This requirement traces to feature [F-DQC-01].,,includes(#405) 411,Requirements,In specification,[SR-DQC-003] Conditional Sensor Initialization,The system shall initialize and activate only sensors that are detected as present. This requirement traces to feature [F-DQC-01].,,includes(#405) @@ -45,6 +1388,335 @@ 421,Requirements,In specification,[SR-DQC-013] Load Machine Constants at Startup,The system shall load and apply the Machine Constants dataset during system initialization. This requirement traces to feature [F-DQC-04].,,includes(#408) 422,Requirements,In specification,[SR-DQC-014] Support Remote Machine Constants Update,The system shall support remote updates of the Machine Constants dataset initiated by the Main Hub. This requirement traces to feature [F-DQC-04].,,includes(#408) 423,Requirements,In specification,[SR-DQC-015] Controlled Reinitialization After Update,The system shall apply updated Machine Constants only after executing a controlled teardown and reinitialization procedure. This requirement traces to feature [F-DQC-04].,,includes(#408) +424,Feature,In specification,[FG-DQC-] Data Quality & Calibration Features," + + +# Feature Engineering Specification + +## Data Quality & Calibration Features + +**Feature Group ID:** FG-DQC +**Scope:** Sensor Hub (Sub-Hub only) +**Target Platform:** ESP32-S3–based Sensor Hub +**Applies To:** Indoor poultry farm sensor hubs +**Dependencies:** Sensor Data Acquisition Features (FG-DAQ), Diagnostics Features (FG-DIAG), Persistence / DP Stack + +## 1\. Purpose and Objectives + +The **Data Quality & Calibration Features** ensure that all sensor data generated by the Sensor Hub is **valid, trustworthy, correctly classified, and calibrated** throughout the system lifecycle. These features provide mechanisms for: + +* Automatic identification of connected sensors + +* Enforcing correct sensor–slot compatibility + +* Early detection and isolation of faulty sensors + +* Centralized management of machine constants and calibration parameters + + +The goal is to maintain **high data integrity**, reduce commissioning errors, support **remote reconfiguration**, and ensure safe operation during updates or failures. + +## 2\. Feature Overview and Relationships + +

Feature ID

Feature Name

Primary Objective

Related Features

F-DQC-01

Automatic Sensor Detection

Detect connected sensors dynamically

F-DAQ-01, F-DIAG-01

F-DQC-02

Sensor Type Enforcement

Prevent incorrect sensor-slot usage

F-DQC-01

F-DQC-03

Sensor Failure Detection

Identify and isolate faulty sensors

F-DIAG-02

F-DQC-04

Machine Constants & Calibration Management

Manage static configuration and calibration

OTA, Persistence, Teardown

+ +## 3\. Functional Feature Descriptions + +### 3.1 F-DQC-01: Automatic Sensor Detection + +**Description** +The Sensor Hub shall automatically detect which sensors are physically connected at runtime. Each sensor slot provides a dedicated detection mechanism (e.g., GPIO presence pin or ID signal) that allows the system to determine whether a sensor is installed. + +Detected sensors are dynamically initialized and incorporated into the data acquisition workflow without requiring firmware changes. + +**Key Capabilities** + +* Hardware-based presence detection + +* Runtime sensor enumeration + +* Dynamic initialization during boot or reconfiguration + +* Integration with diagnostics and data acquisition + + +### 3.2 F-DQC-02: Sensor Type Enforcement + +**Description** +Each physical sensor slot on the Sensor Hub is dedicated to a specific sensor type. The system enforces sensor-slot compatibility to prevent incorrect sensor insertion (e.g., humidity sensor in temperature slot). + +This enforcement is achieved via electrical identification, pin mapping, or firmware configuration defined in Machine Constants. + +**Key Capabilities** + +* Fixed sensor-to-slot mapping + +* Sensor identity verification + +* Rejection of invalid sensor configurations + +* Diagnostic reporting of configuration violations + + +### 3.3 F-DQC-03: Sensor Failure Detection + +**Description** +The Sensor Hub continuously monitors sensor behavior to detect failures such as disconnection, out-of-range values, non-responsive sensors, or abnormal signal patterns. + +Detected sensor failures are classified, logged, timestamped, and reported to the Main Hub. Failed sensors are excluded from control and analytics workflows to prevent propagation of invalid data. + +**Key Capabilities** + +* Runtime health monitoring + +* Failure classification + +* Fault isolation + +* Diagnostic event generation + + +### 3.4 F-DQC-04: Machine Constants & Calibration Management + +**Description** +The system maintains a **Machine Constants (MC)** dataset that defines static and semi-static configuration parameters for the Sensor Hub, including: + +* Installed sensor types and slots + +* Communication identifiers and addressing + +* Calibration coefficients and offsets + +* Sensor-specific limits and scaling + + +Machine Constants are persisted in non-volatile storage (SD card) and loaded during system initialization. Updates may be received from the Main Hub and applied via a controlled teardown and reinitialization process. + +**Key Capabilities** + +* Persistent configuration storage + +* Runtime loading and validation + +* Remote update support + +* Controlled reinitialization sequence + + +## 4\. System Requirements (Formal SHALL Statements) + +### 4.1 Automatic Sensor Detection + +**SR-DQC-001** +The system shall detect the presence of each sensor using a dedicated hardware detection mechanism. + +**SR-DQC-002** +The system shall perform sensor presence detection during system startup and after any reinitialization event. + +**SR-DQC-003** +The system shall initialize only those sensors that are detected as present. + +### 4.2 Sensor Type Enforcement + +**SR-DQC-004** +The system shall assign each sensor slot to a predefined sensor type. + +**SR-DQC-005** +The system shall verify that the detected sensor matches the expected sensor type for the slot. + +**SR-DQC-006** +The system shall reject and report any sensor-slot mismatch as a diagnostic event. + +### 4.3 Sensor Failure Detection + +**SR-DQC-007** +The system shall continuously monitor sensor responsiveness and signal validity during operation. + +**SR-DQC-008** +The system shall detect sensor failures including disconnection, non-responsiveness, and invalid measurement ranges. + +**SR-DQC-009** +The system shall mark a failed sensor as defective and exclude it from data reporting. + +**SR-DQC-010** +The system shall report detected sensor failures to the Main Hub with timestamps and failure classification. + +### 4.4 Machine Constants & Calibration Management + +**SR-DQC-011** +The system shall maintain a Machine Constants dataset defining sensor configuration, calibration parameters, and communication identifiers. + +**SR-DQC-012** +The system shall persist the Machine Constants dataset in non-volatile storage. + +**SR-DQC-013** +The system shall load and apply Machine Constants during system initialization. + +**SR-DQC-014** +The system shall support remote updates of the Machine Constants dataset initiated by the Main Hub. + +**SR-DQC-015** +The system shall apply updated Machine Constants only after executing a controlled teardown and reinitialization sequence. + +## 5\. Traceability Summary + +

Feature ID

System Requirements

F-DQC-01

SR-DQC-001 → SR-DQC-003

F-DQC-02

SR-DQC-004 → SR-DQC-006

F-DQC-03

SR-DQC-007 → SR-DQC-010

F-DQC-04

SR-DQC-011 → SR-DQC-015

+ +##",,includes(#529); includes(#408); includes(#407); includes(#406); includes(#405) +425,Feature,In specification,[FG-COM] Communication Features," + + +# Feature Engineering Specification + +## Communication Features + +**Feature Group ID:** FG-COM +**Scope:** Sensor Hub (Sub-Hub only) +**Target Platform:** ESP32-S3–based Sensor Hub +**Applies To:** Indoor poultry farm sensor hubs +**Dependencies:** + +* Sensor Data Acquisition (FG-DAQ) + +* Data Quality & Calibration (FG-DQC) + +* Diagnostics & Health Monitoring (FG-DIAG) + +* Security & Safety Features (FG-SEC) + + +## 1\. Purpose and Objectives + +The **Communication Features** define how the Sensor Hub exchanges data and control information with external entities. These features ensure that sensor data, diagnostics, configuration updates, and control requests are transferred in a **reliable, secure, and deterministic manner**. + +The communication layer is designed to: + +* Support hierarchical farm architecture (Sensor Hub → Main Hub) + +* Enable on-demand and event-driven data transfer + +* Allow limited peer-to-peer communication between Sensor Hubs + +* Maintain robustness under intermittent connectivity + + +## 2\. Feature Overview and Relationships + +

Feature ID

Feature Name

Primary Objective

Related Features

F-COM-01

Main Hub Communication

Primary uplink/downlink with Main Hub

OTA, Diagnostics, MC Management

F-COM-02

On-Demand Data Broadcasting

Provide latest data upon request

DAQ, DP Stack

F-COM-03

Peer Sensor Hub Communication

Limited hub-to-hub coordination

System Management

+ +## 3\. Functional Feature Descriptions + +### 3.1 F-COM-01: Main Hub Communication + +**Description** +The Sensor Hub shall establish and maintain a bidirectional communication channel with the Main Hub. This channel is used for transmitting sensor data, diagnostics, alarms, and status information, as well as receiving commands, firmware updates, and Machine Constants updates. + +The communication mechanism shall support reliable delivery, message integrity verification, and connection state monitoring. + +**Key Capabilities** + +* Bidirectional communication + +* Command and response handling + +* Diagnostics and status reporting + +* Integration with OTA and MC updates + + +### 3.2 F-COM-02: On-Demand Data Broadcasting + +**Description** +The Sensor Hub shall support on-demand transmission of the most recent sensor data upon request from the Main Hub. This allows the Main Hub to query real-time conditions without waiting for periodic reporting cycles. + +Data broadcasts include timestamped sensor values and associated validity status. + +**Key Capabilities** + +* Request/response data exchange + +* Latest-value data delivery + +* Timestamp and validity inclusion + +* Low-latency response + + +### 3.3 F-COM-03: Peer Sensor Hub Communication + +**Description** +Sensor Hubs shall be capable of limited peer-to-peer communication for coordination purposes such as connectivity checks, time synchronization assistance, or basic status exchange. + +Peer communication is optional, demand-driven, and does not replace the primary communication path through the Main Hub. + +**Key Capabilities** + +* Hub-to-hub message exchange + +* Minimal command set + +* No dependency on centralized infrastructure + +* Isolation from control logic + + +## 4\. System Requirements (Formal SHALL Statements) + +### 4.1 Main Hub Communication + +**SR-COM-001** +The system shall support bidirectional communication between the Sensor Hub and the Main Hub. + +**SR-COM-002** +The system shall transmit sensor data, diagnostics, and system status information to the Main Hub. + +**SR-COM-003** +The system shall receive commands, configuration updates, and firmware update requests from the Main Hub. + +**SR-COM-004** +The system shall monitor and report the communication link status with the Main Hub. + +### 4.2 On-Demand Data Broadcasting + +**SR-COM-005** +The system shall support on-demand requests from the Main Hub for sensor data. + +**SR-COM-006** +The system shall respond to on-demand data requests with the most recent timestamped sensor data. + +**SR-COM-007** +The system shall include data validity and sensor status information in on-demand responses. + +### 4.3 Peer Sensor Hub Communication + +**SR-COM-008** +The system shall support limited peer-to-peer communication between Sensor Hubs. + +**SR-COM-009** +The system shall allow peer communication for basic coordination functions such as connectivity checks or time synchronization. + +**SR-COM-010** +The system shall ensure that peer Sensor Hub communication does not interfere with Main Hub communication or control operations. + +## 5\. Traceability Mapping + +### 5.1 Feature → System Requirement Mapping + +

Feature ID

System Requirements

F-COM-01

SR-COM-001, SR-COM-002, SR-COM-003, SR-COM-004

F-COM-02

SR-COM-005, SR-COM-006, SR-COM-007

F-COM-03

SR-COM-008, SR-COM-009, SR-COM-010

+ +## 6\. Engineering Notes and Constraints + +* Communication protocol selection (Wi-Fi, ESP-NOW, proprietary RF, etc.) is deferred to the Software Requirements phase. + +* Security (authentication, encryption) is defined under **Security & Safety Features**. + +* Communication failures shall trigger diagnostics events but shall not block sensor acquisition. + + +##",,includes(#530); includes(#428); includes(#427); includes(#426) +426,Feature,In specification,[F-COM-01] Main Hub Communication,"The system provides bidirectional communication between the Sensor Hub and the Main Hub. This communication channel is used to transmit sensor data, diagnostics, and system status information, as well as to receive commands, configuration updates, and firmware update requests.",,includes(#590); includes(#589); includes(#588); includes(#432); includes(#431); includes(#430); includes(#429); includes(#425) +427,Feature,In specification,[F-COM-02] On-Demand Data Broadcasting,"The system supports on-demand transmission of the most recent timestamped sensor data upon request from the Main Hub, enabling real-time data access outside periodic reporting cycles.",,includes(#435); includes(#434); includes(#433); includes(#425) +428,Feature,In specification,[F-COM-03] Peer Sensor Hub Communication,"The system supports limited peer-to-peer communication between Sensor Hubs for coordination purposes such as connectivity checks or basic time synchronization, without replacing Main Hub communication.",,includes(#592); includes(#591); includes(#438); includes(#437); includes(#436); includes(#425) 429,Requirements,In specification,[SR-COM-001] Bidirectional Main Hub Communication,The system shall support bidirectional communication between the Sensor Hub and the Main Hub. This requirement traces to feature [F-COM-01].,,includes(#426) 430,Requirements,In specification,[SR-COM-002] Transmit Data to Main Hub,"The system shall transmit sensor data, diagnostics information, and system status to the Main Hub. This requirement traces to feature [F-COM-01].",,includes(#426) 431,Requirements,In specification,[SR-COM-003] Receive Commands from Main Hub,"The system shall receive commands, configuration updates, and firmware update requests from the Main Hub. This requirement traces to feature [F-COM-01].",,includes(#426) @@ -55,6 +1727,173 @@ 436,Requirements,In specification,[SR-COM-008] Support Peer Sensor Hub Communication,The system shall support limited peer-to-peer communication between Sensor Hubs. This requirement traces to feature [F-COM-03].,,includes(#428) 437,Requirements,In specification,[SR-COM-009] Allow Peer Coordination Functions,The system shall allow peer communication for basic coordination functions such as connectivity checks or time synchronization. This requirement traces to feature [F-COM-03].,,includes(#428) 438,Requirements,In specification,[SR-COM-010] Isolate Peer Communication from Control Logic,The system shall ensure that peer Sensor Hub communication does not interfere with Main Hub communication or control operations. This requirement traces to feature [F-COM-03].,,includes(#428) +439,Feature,New,[FG-DIAG-] Diagnostics & Health Monitoring Features,"# Feature Engineering Specification + +## Diagnostics & Health Monitoring Features + +**Feature Group ID:** FG-DIAG +**Scope:** Sensor Hub (Sub-Hub only) +**Target Platform:** ESP32-S3–based Sensor Hub +**Applies To:** Indoor poultry farm sensor hubs +**Dependencies:** + +* Sensor Data Acquisition (FG-DAQ) + +* Data Quality & Calibration (FG-DQC) + +* Communication Features (FG-COM) + +* Persistence / DP Stack + + +## 1\. Purpose and Objectives + +The **Diagnostics & Health Monitoring Features** provide a structured and persistent mechanism to detect, classify, record, and expose system faults, warnings, and health states. + +These features ensure that: + +* Failures are detectable and explainable + +* Root causes are traceable + +* Diagnostic data survives resets and power loss + +* Engineers can access diagnostic information locally or remotely + + +The diagnostics subsystem is **non-intrusive**, meaning it shall not block core sensing or communication functions unless the system enters a fatal state. + +## 2\. Feature Overview and Relationships + +

Feature ID

Feature Name

Primary Objective

Related Features

F-DIAG-01

Diagnostic Code Management

Standardize fault and warning identification

DQC, COM

F-DIAG-02

Diagnostic Data Storage

Persist diagnostic events

DP Stack

F-DIAG-03

Diagnostic Session

Engineer access to diagnostics

COM, System Mgmt

+ +## 3\. Functional Feature Descriptions + +### 3.1 F-DIAG-01: Diagnostic Code Management + +**Description** +The system shall implement a structured diagnostic code framework to represent system health conditions, warnings, errors, and fatal faults. + +Each diagnostic event is associated with: + +* A unique diagnostic code + +* Severity level (info, warning, error, fatal) + +* A hierarchical root-cause classification + +* Timestamp and source component + + +This framework enables consistent fault handling across all system components. + +**Key Capabilities** + +* Unique diagnostic code registry + +* Severity classification + +* Root-cause hierarchy + +* Event-based reporting + + +### 3.2 F-DIAG-02: Diagnostic Data Storage + +**Description** +The system shall persist diagnostic events in non-volatile storage to allow post-failure analysis and long-term health monitoring. + +Stored diagnostics remain available across system resets and power cycles until explicitly cleared by an authorized diagnostic session or command. + +**Key Capabilities** + +* Persistent storage of diagnostic events + +* Timestamped records + +* Bounded storage with overwrite policy + +* Integration with DP / Persistence layer + + +### 3.3 F-DIAG-03: Diagnostic Session + +**Description** +The system shall provide a diagnostic session that allows authorized engineers or tools to access diagnostic data, inspect system health, and perform maintenance operations. + +The diagnostic session may be accessed locally or remotely via the communication interface and supports read and limited control operations. + +**Key Capabilities** + +* Session-based access + +* Read diagnostics and health data + +* Clear diagnostic records + +* Controlled command execution + + +## 4\. System Requirements (Formal SHALL Statements) + +### 4.1 Diagnostic Code Management + +**SR-DIAG-001** +The system shall implement a diagnostic code framework for reporting system health, warnings, errors, and fatal faults. + +**SR-DIAG-002** +The system shall assign a unique diagnostic code to each detected fault or abnormal condition. + +**SR-DIAG-003** +The system shall classify diagnostic codes by severity level. + +**SR-DIAG-004** +The system shall associate each diagnostic event with a timestamp and source component. + +### 4.2 Diagnostic Data Storage + +**SR-DIAG-005** +The system shall persist diagnostic events in non-volatile storage. + +**SR-DIAG-006** +The system shall retain diagnostic data across system resets and power cycles. + +**SR-DIAG-007** +The system shall implement a bounded diagnostic storage mechanism with a defined overwrite or rollover policy. + +### 4.3 Diagnostic Session + +**SR-DIAG-008** +The system shall provide a diagnostic session interface for accessing diagnostic data. + +**SR-DIAG-009** +The system shall allow authorized diagnostic sessions to retrieve stored diagnostic events. + +**SR-DIAG-010** +The system shall allow authorized diagnostic sessions to clear diagnostic records. + +**SR-DIAG-011** +The system shall ensure that diagnostic sessions do not interfere with normal sensor acquisition or communication operations. + +## 5\. Feature ↔ System Requirement Mapping + +

Feature ID

System Requirements

F-DIAG-01

SR-DIAG-001, SR-DIAG-002, SR-DIAG-003, SR-DIAG-004

F-DIAG-02

SR-DIAG-005, SR-DIAG-006, SR-DIAG-007

F-DIAG-03

SR-DIAG-008, SR-DIAG-009, SR-DIAG-010, SR-DIAG-011

+ +## 6\. Engineering Notes + +* Diagnostic codes should be versioned to support firmware evolution. + +* Diagnostic severity may be linked to LED indicators (green/yellow/red). + +* Fatal diagnostics may trigger the teardown mechanism defined elsewhere. + +* Security and access control for diagnostic sessions are handled under **Security & Safety Features**. + + +##",,includes(#442); includes(#441); includes(#440) +440,Feature,New,[F-DIAG-01] Diagnostic Code Management,"The system provides a structured diagnostic code framework to represent system health states, warnings, errors, and fatal faults. Each diagnostic event is associated with a unique code, severity level, root-cause classification, timestamp, and source component.",,includes(#446); includes(#445); includes(#444); includes(#443); includes(#439) +441,Feature,New,[F-DIAG-02] Diagnostic Data Storage,The system persists diagnostic events in non-volatile storage to enable post-failure analysis and long-term health monitoring. Stored diagnostic data remains available across resets and power cycles until explicitly cleared.,,includes(#449); includes(#448); includes(#447); includes(#439) +442,Feature,New,[F-DIAG-03] Diagnostic Session,"The system provides a diagnostic session that allows authorized engineers or tools to access diagnostic data, inspect system health, and perform limited maintenance actions without disrupting normal operation.",,includes(#531); includes(#453); includes(#452); includes(#451); includes(#450); includes(#439) 443,Requirements,New,[SR-DIAG-001] Implement Diagnostic Code Framework,"The system shall implement a diagnostic code framework for reporting system health conditions, warnings, errors, and fatal faults. This requirement traces to feature [F-DIAG-01].",,includes(#440) 444,Requirements,New,[SR-DIAG-002] Assign Unique Diagnostic Codes,The system shall assign a unique diagnostic code to each detected fault or abnormal condition. This requirement traces to feature [F-DIAG-01].,,includes(#440) 445,Requirements,New,[SR-DIAG-003] Classify Diagnostic Severity,"The system shall classify diagnostic codes by severity level including informational, warning, error, and fatal. This requirement traces to feature [F-DIAG-01].",,includes(#440) @@ -66,6 +1905,322 @@ 451,Requirements,New,[SR-DIAG-009] Retrieve Diagnostic Records,The system shall allow authorized diagnostic sessions to retrieve stored diagnostic events. This requirement traces to feature [F-DIAG-03].,,includes(#442) 452,Requirements,New,[SR-DIAG-010] Clear Diagnostic Records,The system shall allow authorized diagnostic sessions to clear stored diagnostic records. This requirement traces to feature [F-DIAG-03].,,includes(#442) 453,Requirements,New,[SR-DIAG-011] Non-Intrusive Diagnostic Sessions,The system shall ensure that diagnostic sessions do not interfere with normal sensor acquisition or communication operations. This requirement traces to feature [F-DIAG-03].,,includes(#442) +454,Feature,New,[FG-DATA] Persistence & Data Management Features," + + +# Feature Engineering Specification + +## Persistence & Data Management Features + +**Feature Group ID:** FG-DATA +**Scope:** Sensor Hub (Sub-Hub only) +**Target Platform:** ESP32-S3–based Sensor Hub +**Applies To:** Indoor poultry farm sensor hubs +**Dependencies:** + +* Sensor Data Acquisition (FG-DAQ) + +* Data Quality & Calibration (FG-DQC) + +* Diagnostics & Health Monitoring (FG-DIAG) + +* System State Management / Teardown Mechanism + + +## 1\. Purpose and Objectives + +The **Persistence & Data Management Features** define how the Sensor Hub stores, protects, and manages critical runtime and historical data. These features ensure that: + +* Sensor data and system state are not lost during resets or failures + +* Data storage is abstracted from application logic + +* Critical data is safely handled during firmware updates, configuration changes, or fatal faults + + +The persistence layer is a **foundational system service**, supporting diagnostics, calibration, OTA, and recovery operations. + +## 2\. Feature Overview and Relationships + +

Feature ID

Feature Name

Primary Objective

Related Features

F-DATA-01

Persistent Sensor Data Storage

Store timestamped sensor data

DAQ, COM

F-DATA-02

Data Persistence Abstraction (DP)

Abstract storage access

Application Layer

F-DATA-03

Safe Data Handling During State Transitions

Protect data during teardown

OTA, System Mgmt

+ +## 3\. Functional Feature Descriptions + +### 3.1 F-DATA-01: Persistent Sensor Data Storage + +**Description** +The system shall persist timestamped sensor data to non-volatile storage to support historical analysis, diagnostics correlation, and recovery scenarios. + +Persistence may include: + +* Filtered sensor values + +* Timestamps + +* Sensor validity and status metadata + + +The persistence policy (frequency, retention window, overwrite behavior) is configurable and optimized for storage longevity and performance. + +**Key Capabilities** + +* Non-volatile storage (SD card / NVM) + +* Timestamped records + +* Configurable retention policy + +* Integration with DAQ and COM + + +### 3.2 F-DATA-02: Data Persistence Abstraction (DP Component) + +**Description** +The system shall provide a **Data Persistence (DP) component** that abstracts storage access for all upper layers. Application and feature modules interact with the DP component rather than directly accessing storage hardware. + +The DP component manages: + +* Data model definitions + +* Serialization and deserialization + +* Storage backend selection + +* Consistency and integrity guarantees + + +**Key Capabilities** + +* Unified persistence API + +* Storage backend abstraction + +* Centralized data ownership + +* Reduced coupling between layers + + +### 3.3 F-DATA-03: Safe Data Handling During State Transitions + +**Description** +The system shall ensure safe and deterministic handling of data during critical state transitions, including: + +* Firmware updates (OTA) + +* Machine Constants updates + +* System resets + +* Fatal error handling + + +Before entering such transitions, the system executes a controlled data finalization process to flush buffers, persist critical state, and verify data integrity. + +**Key Capabilities** + +* Controlled data flush + +* Atomic write operations + +* Data integrity checks + +* Coordination with teardown mechanism + + +## 4\. System Requirements (Formal SHALL Statements) + +### 4.1 Persistent Sensor Data Storage + +**SR-DATA-001** +The system shall persist timestamped sensor data in non-volatile storage. + +**SR-DATA-002** +The system shall store sensor data together with sensor identifiers, timestamps, and validity status. + +**SR-DATA-003** +The system shall support configurable data retention and overwrite policies. + +### 4.2 Data Persistence Abstraction (DP Component) + +**SR-DATA-004** +The system shall provide a Data Persistence (DP) component as the sole interface for persistent data access. + +**SR-DATA-005** +The system shall prevent application and feature modules from directly accessing storage hardware. + +**SR-DATA-006** +The DP component shall support serialization and deserialization of structured system data. + +### 4.3 Safe Data Handling During State Transitions + +**SR-DATA-007** +The system shall ensure that all critical runtime data is flushed to non-volatile storage before entering a controlled teardown or reset. + +**SR-DATA-008** +The system shall protect data integrity during firmware updates and configuration changes. + +**SR-DATA-009** +The system shall verify successful data persistence before completing a state transition. + +## 5\. Feature ↔ System Requirement Mapping + +

Feature ID

System Requirements

F-DATA-01

SR-DATA-001, SR-DATA-002, SR-DATA-003

F-DATA-02

SR-DATA-004, SR-DATA-005, SR-DATA-006

F-DATA-03

SR-DATA-007, SR-DATA-008, SR-DATA-009

+ +## 6\. Engineering Notes + +* The DP component aligns with your **DP Stack** already defined in the architecture. + +* Atomic write strategies (e.g., temp file + rename) are recommended. + +* Diagnostic events should be generated on persistence failures. + +* Storage wear-leveling considerations apply for SD/NVM. + + +##",,includes(#532); includes(#464); includes(#463); includes(#462) +455,Task,New,Test backup,,, +456,Task,New,Plan for Sensor Hub version 1,,, +457,Task,New,planning scope SH v1,"## Phase 1 — System Validation & Refinement (NOW) + +**Goal:** Freeze system intent before design + +### Tasks + +* ✔ Review Feature Coverage (you are almost done) + +* ✔ Review SR completeness (done) + +* ⏳ Add _cross-feature constraints_ (small doc) + +* ⏳ Add _system assumptions & limitations_ + + +📄 Output: + +* **System Requirements Baseline (Frozen)** + +* **Architecture Overview (Sensor Hub)** + + +## Phase 2 — Architecture Definition (Before Coding) + +This is where **AI shines**. + +### Deliverables + +* Functional Requirement Document (FRD) + +* Software Architecture Document (SAD) + +* Component diagrams + +* State diagrams + +* Data flow diagrams + + +📄 These should be **Markdown-first**, versioned. + +## Phase 3 — Software Requirements (Later, per component) + +Not now — **you’re right to delay this**. + +## Phase 4 — Implementation with AI IDEs + +Only after architecture is stable.",, +458,Task,New,Create sprints,,, +459,Task,New,Plan for sprints,,, +460,Task,New,System feature review ,"
+ +

Area

Goal

Feature completeness

Are any operational gaps missing?

Cross-feature conflicts

OTA vs Persistence vs Security

State handling

Are all features state-aware?

Safety behavior

Fault paths, teardown correctness

Scalability

Future-proofing without overengineering


+ +### 🟦 IEC 61508 (Functional Safety – _Guidance Only_) + +**What you already match well:** + +* Deterministic states (F-SYS-01) + +* Controlled teardown (F-SYS-02) + +* Diagnostics & fault handling + +* Separation of concerns + + +**What to add later (optional):** + +* Safety integrity levels (SIL-like classification) + +* Fault reaction time definitions + + +### 🟦 IEC 61499 (Distributed Automation – _Conceptual Alignment_) + +This is very relevant philosophically. + +**Strong matches:** + +* Event-driven design + +* Distributed nodes (sensor hubs) + +* State-based behavior + +* Clear separation of data and logic + + +Later, you can map: + +* Features → Function Blocks + +* DP → Data services + +* Communication → Event channels + + +### 🟦 ISA-95 (Industrial Automation Layers) + +You are building **Level 1–2 perfectly**: + +* Sensors + +* Control logic + +* Local diagnostics + +* HMI (OLED) + + +Main Hub / Cloud later becomes: + +* Level 2/3 (supervisory & management) + + + +### 🟦 ISO 27001 / IEC 62443 (Security – _Principles Only_) + +You already cover: + +* Secure boot + +* Secure storage + +* Encrypted communication + +* Access control (debug sessions) + + +Later, you can formalize: + +* Threat model + +* Key lifecycle + +* Secure provisioning",, +461,Task,New,planning,,, +462,Feature,New,[F-DATA-01] Persistent Sensor Data Storage,"Provides persistent storage of timestamped sensor data in non-volatile memory. Ensures sensor readings, timestamps, and validity metadata are retained for historical analysis, diagnostics, and system recovery. Supports configurable retention and overwrite policies.",,includes(#467); includes(#466); includes(#465); includes(#454) +463,Feature,New,[F-DATA-02] Data Persistence Abstraction (DP Component),Provides a centralized Data Persistence (DP) component that abstracts all access to non-volatile storage. Ensures application and feature modules interact through a unified persistence interface without direct storage hardware dependency.,,includes(#470); includes(#469); includes(#468); includes(#454) +464,Feature,New,[F-DATA-03] Safe Data Handling During State Transitions,"Ensures safe and deterministic handling of persistent data during critical system state transitions such as firmware updates, machine constant updates, resets, and fatal fault conditions.",,includes(#473); includes(#472); includes(#471); includes(#454) 465,Requirements,New,[SR-DATA-001] Persistent Timestamped Sensor Data,The system shall persist timestamped sensor data in non-volatile storage.,,includes(#462) 466,Requirements,New,[SR-DATA-002] Sensor Data Metadata Storage,"The system shall store sensor data together with sensor identifiers, timestamps, and validity status.",,includes(#462) 467,Requirements,New,[SR-DATA-003] Configurable Data Retention Policy,The system shall support configurable data retention and overwrite policies for persisted sensor data.,,includes(#462) @@ -75,6 +2230,195 @@ 471,Requirements,New,[SR-DATA-007] Data Flush Before Teardown,The system shall flush all critical runtime data to non-volatile storage before entering a controlled teardown or reset state.,,includes(#464) 472,Requirements,New,[SR-DATA-008] Data Integrity During Updates,The system shall protect data integrity during firmware updates and machine constant updates.,,includes(#464) 473,Requirements,New,[SR-DATA-009] Persistence Verification,The system shall verify successful data persistence before completing a system state transition.,,includes(#464) +474,Feature,New,[OTA] Firmware Update (OTA) Features," + + +# 8\. Firmware Update (OTA) Features + +## 8.1 Feature Overview + +The **Firmware Update (OTA) Features** enable the Sensor Hub (Sub-Hub) to safely receive, validate, and activate new firmware images provided by the Main Hub. +These features ensure **controlled firmware lifecycle management**, **data integrity**, **system availability**, and **fault containment** during firmware update operations. + +The OTA process is designed to: + +* Prevent unauthorized or corrupted firmware installation + +* Preserve critical system data and calibration information + +* Ensure recoverability in case of update failure + +* Minimize operational disruption + + +This feature set applies **only to the Sensor Hub (ESP32-S3 based)** and does not include cloud-side or Main Hub OTA logic. + +## 8.2 Scope and Assumptions + +### In Scope + +* OTA negotiation and readiness handshake with Main Hub + +* Firmware image reception over secure communication + +* Temporary firmware storage on SD card + +* Firmware integrity verification (e.g., CRC, hash) + +* Controlled firmware activation and reboot + + +### Out of Scope + +* Firmware generation and signing + +* Cloud-side firmware distribution + +* Rollback policy definition (may be extended later) + + +## 8.3 Sub-Features + +### 8.3.1 F-OTA-01: OTA Update Negotiation + +**Description** +This sub-feature governs the initial negotiation phase between the Sensor Hub and the Main Hub prior to any firmware transfer. +The Sensor Hub validates its current operational state and explicitly signals readiness before accepting an OTA update. + +**Responsibilities** + +* Receive OTA availability notification + +* Validate system readiness (power, storage, state) + +* Acknowledge or reject OTA request + +* Transition system into OTA-preparation mode + + +### 8.3.2 F-OTA-02: Firmware Reception and Storage + +**Description** +This sub-feature handles the controlled reception of the firmware image from the Main Hub and its storage in non-volatile memory (SD card) without overwriting the currently running firmware. + +**Responsibilities** + +* Receive firmware in chunks + +* Store firmware image on SD card + +* Monitor transfer completeness + +* Prevent execution during download + + +### 8.3.3 F-OTA-03: Firmware Integrity Validation + +**Description** +This sub-feature validates the integrity and correctness of the received firmware image prior to activation, ensuring that corrupted or incomplete firmware is never flashed. + +**Responsibilities** + +* Perform integrity checks (CRC, checksum, hash) + +* Validate firmware size and metadata + +* Reject invalid firmware images + +* Report validation status to Main Hub + + +### 8.3.4 F-OTA-04: Safe Firmware Activation + +**Description** +This sub-feature manages the safe transition from the current firmware to the new firmware, ensuring all critical data is preserved and the system is left in a known safe state. + +**Responsibilities** + +* Trigger teardown procedure + +* Persist runtime and calibration data + +* Flash validated firmware image + +* Reboot system into updated firmware + + +## 8.4 System Requirements (Formal SHALL Statements) + +### OTA Negotiation Requirements + +* **SR-OTA-001**: The system shall support OTA update negotiation initiated by the Main Hub. + +* **SR-OTA-002**: The system shall verify internal readiness before accepting an OTA update request. + +* **SR-OTA-003**: The system shall explicitly acknowledge or reject OTA requests. + + +### Firmware Reception & Storage Requirements + +* **SR-OTA-004**: The system shall receive firmware images over the established communication channel. + +* **SR-OTA-005**: The system shall store received firmware images in non-volatile storage prior to validation. + +* **SR-OTA-006**: The system shall prevent overwriting the active firmware during firmware reception. + + +### Firmware Integrity Requirements + +* **SR-OTA-007**: The system shall validate the integrity of the received firmware image before activation. + +* **SR-OTA-008**: The system shall reject firmware images that fail integrity validation. + +* **SR-OTA-009**: The system shall report firmware validation results to the Main Hub. + + +### Safe Activation Requirements + +* **SR-OTA-010**: The system shall execute a controlled teardown before firmware activation. + +* **SR-OTA-011**: The system shall persist critical runtime data prior to firmware flashing. + +* **SR-OTA-012**: The system shall activate new firmware only after successful validation. + +* **SR-OTA-013**: The system shall reboot into the new firmware following successful activation. + + +## 8.5 Feature-to-Requirement Traceability + +

Feature ID

Related System Requirements

F-OTA-01

SR-OTA-001, SR-OTA-002, SR-OTA-003

F-OTA-02

SR-OTA-004, SR-OTA-005, SR-OTA-006

F-OTA-03

SR-OTA-007, SR-OTA-008, SR-OTA-009

F-OTA-04

SR-OTA-010, SR-OTA-011, SR-OTA-012, SR-OTA-013

+ +## 8.6 Architectural Considerations (Informative) + +* OTA logic shall be implemented as a **dedicated OTA Manager component** + +* Firmware storage shall be accessed via the **DP (Data Persistence) component** + +* OTA state transitions shall interact with: + + * Diagnostics subsystem + + * Machine Constants management + + * Teardown mechanism + +* OTA execution shall not block critical system diagnostics reporting + + +## 8.7 Related Features + +* **Persistence & Data Management Features (F-DATA-03)** + +* **Diagnostics & Health Monitoring Features** + +* **Security & Safety Features (Secure Boot, Secure Flash)** + + +###",,includes(#533); includes(#478); includes(#477); includes(#476); includes(#475) +475,Feature,New,[F-OTA-01] OTA Update Negotiation,"Handles the initial OTA handshake between the Sensor Hub and Main Hub. The system validates readiness, acknowledges or rejects OTA requests, and transitions the system into OTA-preparation mode.",,includes(#481); includes(#480); includes(#479); includes(#474) +476,Feature,New,[F-OTA-02] Firmware Reception and Storage,Receives firmware images from the Main Hub in a controlled manner and stores them in non-volatile storage without affecting the currently running firmware.,,includes(#484); includes(#483); includes(#482); includes(#474) +477,Feature,New,[F-OTA-03] Firmware Integrity Validation,"Validates the integrity and correctness of the received firmware image using CRC, checksum, or hash mechanisms before allowing activation.",,includes(#487); includes(#486); includes(#485); includes(#474) +478,Feature,New,[F-OTA-04] Safe Firmware Activation,"Executes a controlled teardown, persists critical data, flashes validated firmware, and reboots the system into the updated firmware safely.",,includes(#491); includes(#490); includes(#489); includes(#488); includes(#474) 479,Requirements,New,[SR-OTA-001] OTA Negotiation Support,The system shall support OTA update negotiation initiated by the Main Hub.,,includes(#475) 480,Requirements,New,[SR-OTA-002] OTA Readiness Validation,The system shall verify internal readiness conditions before accepting an OTA update request.,,includes(#475) 481,Requirements,New,[SR-OTA-003] OTA Acknowledgement,The system shall explicitly acknowledge or reject OTA update requests.,,includes(#475) @@ -88,6 +2432,237 @@ 489,Requirements,New,[SR-OTA-011] Data Persistence Before Flashing,The system shall persist critical runtime data and calibration data before flashing new firmware.,,includes(#478) 490,Requirements,New,[SR-OTA-012] Controlled Firmware Activation,The system shall activate new firmware only after successful integrity validation.,,includes(#478) 491,Requirements,New,[SR-OTA-013] OTA Reboot Execution,The system shall reboot into the new firmware after successful activation.,,includes(#478) +492,Feature,New,[SEC] Security & Safety Features," + + +# +Security & Safety Features + +## Sensor Hub (Sub-Hub) Scope Only + +## 1 Feature Overview + +The **Security & Safety Features** ensure that the Sensor Hub operates only with trusted firmware, protects sensitive data at rest, and guarantees confidentiality and integrity of all communications. These features are foundational and cross-cutting, supporting all other functional features (DAQ, DQC, COM, DIAG, DATA, OTA). + +This feature set is designed to: + +* Prevent execution of unauthorized or malicious firmware + +* Protect firmware, configuration, and machine constants stored in memory + +* Secure all communications with cryptographic mechanisms + +* Provide deterministic and auditable behavior in case of security violations + + +## 2 Scope and Assumptions + +**In Scope** + +* Sensor Hub (ESP32-S3–based) + +* Boot process security + +* Flash and external storage protection + +* Communication security with Main Hub and peer Sensor Hubs + + +**Out of Scope** + +* Cloud server security policies + +* User identity management + +* Physical tamper detection hardware (optional future feature) + + +## 3 Sub-Feature Breakdown + +### 3.1 F-SEC-01: Secure Boot + +#### Description + +Secure Boot ensures that only authenticated and authorized firmware images are executed on the Sensor Hub. During system startup, the bootloader verifies the cryptographic signature of the firmware image before handing over execution. + +If verification fails, the system enters a defined **security fault state** and prevents normal operation. + +#### Responsibilities + +* Firmware authenticity verification + +* Root-of-trust enforcement + +* Prevention of downgrade or rollback attacks (if enabled) + + +#### Constraints + +* Must complete before any application code execution + +* Must be enforced on every boot (cold or warm) + + +### 3.2 F-SEC-02: Secure Flash Storage + +#### Description + +Secure Flash Storage protects sensitive data stored in internal flash and external storage (e.g., SD card) from unauthorized access or modification. + +Sensitive data includes: + +* Firmware images + +* Machine constants + +* Calibration data + +* Cryptographic material + +* Persistent diagnostics and logs + + +#### Responsibilities + +* Encrypted storage of sensitive regions + +* Access control enforcement + +* Prevention of unauthorized read/write operations + + +#### Constraints + +* Encryption must not compromise system boot reliability + +* Storage access must be mediated through controlled software components (e.g., DP component) + + +### 3.3 F-SEC-03: Encrypted Communication + +#### Description + +Encrypted Communication ensures that all data exchanged between the Sensor Hub and other entities (Main Hub, peer Sensor Hubs) is protected against eavesdropping, tampering, and impersonation. + +This includes: + +* Sensor data transmission + +* Diagnostics reporting + +* OTA negotiation and data transfer + +* Configuration and machine constant updates + + +#### Responsibilities + +* Confidentiality of transmitted data + +* Integrity and authenticity verification + +* Secure session establishment + + +#### Constraints + +* Must be compatible with ESP32-S3 cryptographic capabilities + +* Must support reconnection and key renewal mechanisms + + +## 4 Functional Flow Overview + +### Secure Boot Flow (Simplified) + +```text +Power On + ↓ +ROM Bootloader + ↓ +Verify Firmware Signature + ↓ +[Valid] → Jump to Application +[Invalid] → Enter Security Fault State +``` + +### Secure Communication Flow (Simplified) + +```text +Session Request + ↓ +Mutual Authentication + ↓ +Key Exchange + ↓ +Encrypted Data Exchange +``` + +## 5 System SHALL Requirements (Formal) + +### Secure Boot Requirements + +* **SR-SEC-001**: The system shall verify the authenticity of the firmware image before execution during every boot cycle. + +* **SR-SEC-002**: The system shall prevent execution of firmware images that fail cryptographic verification. + +* **SR-SEC-003**: The system shall enter a defined security fault state upon secure boot failure. + +* **SR-SEC-004**: The system shall protect the root-of-trust against modification. + + +### Secure Flash Storage Requirements + +* **SR-SEC-005**: The system shall protect sensitive data stored in internal flash memory from unauthorized access. + +* **SR-SEC-006**: The system shall support encryption of sensitive data stored in external storage. + +* **SR-SEC-007**: The system shall restrict access to cryptographic keys to authorized system components only. + +* **SR-SEC-008**: The system shall ensure data integrity for stored configuration and machine constant files. + + +### Encrypted Communication Requirements + +* **SR-SEC-009**: The system shall encrypt all communication with the Main Hub. + +* **SR-SEC-010**: The system shall ensure integrity and authenticity of all received and transmitted messages. + +* **SR-SEC-011**: The system shall use secure communication channels for OTA firmware updates. + +* **SR-SEC-012**: The system shall detect and report communication security violations. + + +## 6 Traceability Matrix (Feature → System Requirements) + +

Feature ID

Related System Requirements

F-SEC-01

SR-SEC-001, SR-SEC-002, SR-SEC-003, SR-SEC-004

F-SEC-02

SR-SEC-005, SR-SEC-006, SR-SEC-007, SR-SEC-008

F-SEC-03

SR-SEC-009, SR-SEC-010, SR-SEC-011, SR-SEC-012

+ +## 7 Design & Implementation Notes (Non-Normative) + +* ESP32-S3 secure boot and flash encryption features should be leveraged where possible. + +* Key provisioning should occur during manufacturing or secure onboarding. + +* Security failures should integrate with the Diagnostics & Health Monitoring feature set. + +* Security features must be active before any sensor data acquisition or communication begins. + + +## 8 Dependencies + +* **OTA Features** (for secure firmware updates) + +* **Communication Features** (transport layer) + +* **Diagnostics Features** (security fault reporting) + +* **Persistence & DP Component** (secure storage abstraction) + + +###",,includes(#534); includes(#495); includes(#494); includes(#493) +493,Feature,New,[F-SEC-01] Secure Boot,Ensures that only authenticated and authorized firmware images are executed on the Sensor Hub by verifying cryptographic signatures during every system boot.,,includes(#499); includes(#498); includes(#497); includes(#496); includes(#492) +494,Feature,New,[F-SEC-02] Secure Flash Storage,"Protects firmware, machine constants, calibration data, cryptographic material, and sensitive system data stored in internal flash and external storage against unauthorized access or modification.",,includes(#503); includes(#502); includes(#501); includes(#500); includes(#492) +495,Feature,New,[F-SEC-03] Encrypted Communication,"Provides encrypted, authenticated, and integrity-protected communication between the Sensor Hub, Main Hub, and peer Sensor Hubs for all data exchange.",,includes(#507); includes(#506); includes(#505); includes(#504); includes(#492) 496,Requirements,New,[SR-SEC-001] Firmware Authenticity Verification,The system shall verify the authenticity of the firmware image before execution during every boot cycle.,,includes(#493) 497,Requirements,New,[SR-SEC-002] Unauthorized Firmware Blocking,The system shall prevent execution of firmware images that fail cryptographic verification.,,includes(#493) 498,Requirements,New,[SR-SEC-003] Secure Boot Failure Handling,The system shall enter a defined security fault state when secure boot verification fails.,,includes(#493) @@ -100,6 +2675,324 @@ 505,Requirements,New,[SR-SEC-010] Message Integrity and Authenticity,The system shall ensure integrity and authenticity of all transmitted and received messages.,,includes(#495) 506,Requirements,New,[SR-SEC-011] Secure OTA Data Transfer,The system shall use encrypted and authenticated communication channels for OTA firmware updates.,,includes(#495) 507,Requirements,New,[SR-SEC-012] Security Violation Reporting,The system shall detect and report communication and security violations to the Main Hub.,,includes(#495) +508,Feature,New,[SYS] System Management Features," + + +# +System Management Features + +## Sensor Hub (Sub-Hub) Scope + +## 1 Feature Overview + +The **System Management Features** provide deterministic control over the Sensor Hub’s operational lifecycle, runtime state visibility, controlled shutdown behavior, and engineering interaction capabilities. + +This feature group is responsible for: + +* Managing system operational states and transitions + +* Ensuring safe teardown during updates or failures + +* Providing local human–machine interaction via OLED display and buttons + +* Supporting engineering/debug sessions for diagnostics and maintenance + + +These features act as the **supervisory layer** governing all other functional domains (DAQ, DQC, COM, DIAG, DATA, OTA, SEC). + +## 2 Scope and Assumptions + +**In Scope** + +* ESP32-S3 Sensor Hub + +* OLED-based local UI (I2C) + +* Physical input buttons + +* Controlled state transitions and teardown + +* Debug and engineering access + + +**Out of Scope** + +* Main Hub UI + +* Cloud dashboards + +* User authentication / role management + + +## 3 Sub-Feature Breakdown + +### 3.1 F-SYS-01: System State Management + +#### Description + +System State Management defines and controls the operational states of the Sensor Hub and governs all valid transitions between them. + +The system operates as a **finite state machine (FSM)** with deterministic behavior. + +#### Typical System States + +* **INIT** – Hardware and software initialization + +* **RUNNING** – Normal sensor acquisition and communication + +* **WARNING** – Non-fatal fault detected, degraded operation + +* **FAULT** – Fatal error, core functionality disabled + +* **OTA\_UPDATE** – Firmware update in progress + +* **MC\_UPDATE** – Machine constants update in progress + +* **TEARDOWN** – Controlled shutdown sequence + +* **IDLE / SERVICE** – Engineering or diagnostic interaction + + +#### Responsibilities + +* Enforce valid state transitions + +* Notify dependent components of state changes + +* Prevent unsafe operations during restricted states + + +### 3.2 F-SYS-02: Controlled Teardown Mechanism + +#### Description + +The Controlled Teardown Mechanism ensures that the Sensor Hub transitions safely from an active state into reset, update, or shutdown without data loss or corruption. + +Teardown is triggered by: + +* Firmware update + +* Machine constant update + +* Fatal system fault + +* Manual engineering command + + +#### Teardown Sequence (Mandatory) + +1. Stop sensor acquisition tasks + +2. Flush pending data via DP component + +3. Persist calibration, diagnostics, and runtime state + +4. Close communication sessions + +5. Release hardware resources + +6. Enter target state (reset, OTA, idle) + + +#### Responsibilities + +* Guarantee data consistency + +* Ensure deterministic shutdown behavior + +* Prevent flash or SD corruption + + +### 3.3 F-SYS-03: Status Indication (OLED-Based HMI) + +#### Description + +The Sensor Hub provides local system visibility using an **OLED display connected via I2C**, replacing LED indicators. + +The display, together with **three physical buttons (Up / Down / Select)**, forms a minimal local Human–Machine Interface (HMI). + +#### Default Information Displayed (Main Screen) + +1. **Connectivity status** + + * Connected / Disconnected + + * Signal strength (RSSI) if available + +2. **System status** + + * Current system state (RUNNING, WARNING, FAULT, OTA, etc.) + +3. **Connected sensors** + + * Count and/or summary status + +4. **Time and date** + + * Synchronized system time + + +#### Menu Navigation Behavior + +* **Select button** + + * From main screen → opens menu + + * From submenu → returns to main screen + +* **Up / Down buttons** + + * Navigate menu entries + + * Scroll within pages if applicable + + +#### Menu Structure + +**Main Menu** + +* **Diagnostics** + + * Lists active and stored diagnostic codes + + * Displays occurrence count per diagnostic + +* **Sensors** + + * Lists all detected sensors + + * Displays sensor type and configuration status + +* **Health** + + * Displays SD card usage + + * Displays overall system health indicators + + +#### Responsibilities + +* Provide real-time system visibility + +* Support local inspection without external tools + +* Reflect system state and diagnostics accurately + + +### 3.4 F-SYS-04: Debug & Engineering Sessions + +#### Description + +Debug & Engineering Sessions allow authorized engineers to interact with the Sensor Hub for diagnostics, inspection, and controlled operations. + +Sessions may be established via: + +* Wired interface (e.g., USB/UART) + +* Secure communication channel (logical session) + + +#### Supported Capabilities + +* Retrieve diagnostic logs + +* Read machine constant files + +* Inspect system state and health + +* Trigger controlled actions (e.g., reboot, teardown) + +* Monitor runtime logs + + +#### Session Types + +* **Diagnostic Session** – Read-only access for inspection + +* **Debug Session** – Command execution and deeper inspection + + +## 4 Functional Interaction Overview + +### System State & Teardown Relationship + +```text +RUNNING + ↓ (Update / Fault) +TEARDOWN + ↓ +OTA_UPDATE / MC_UPDATE / RESET +``` + +### Local HMI Interaction + +```text +OLED Display ← System State Manager +Buttons → UI Controller → State/Menu Logic +``` + +## 5 System SHALL Requirements (Formal) + +### System State Management + +* **SR-SYS-001**: The system shall implement a defined finite state machine for operational control. + +* **SR-SYS-002**: The system shall restrict operations based on the current system state. + +* **SR-SYS-003**: The system shall notify system components of state transitions. + + +### Controlled Teardown + +* **SR-SYS-004**: The system shall execute a controlled teardown sequence before firmware or machine constant updates. + +* **SR-SYS-005**: The system shall persist all critical runtime data before completing teardown. + +* **SR-SYS-006**: The system shall prevent data corruption during teardown and reset operations. + + +### Status Indication & HMI + +* **SR-SYS-007**: The system shall provide a local OLED display using I2C communication. + +* **SR-SYS-008**: The system shall display connectivity status, system state, sensor summary, and time/date. + +* **SR-SYS-009**: The system shall provide menu navigation using Up, Down, and Select buttons. + +* **SR-SYS-010**: The system shall provide diagnostic, sensor, and health information via the local menu. + + +### Debug & Engineering Sessions + +* **SR-SYS-011**: The system shall support diagnostic sessions for retrieving logs and system status. + +* **SR-SYS-012**: The system shall support debug sessions for controlled engineering operations. + +* **SR-SYS-013**: The system shall restrict debug actions to authorized sessions only. + + +## 6 Traceability Matrix + +

Feature ID

System Requirements

F-SYS-01

SR-SYS-001, SR-SYS-002, SR-SYS-003

F-SYS-02

SR-SYS-004, SR-SYS-005, SR-SYS-006

F-SYS-03

SR-SYS-007, SR-SYS-008, SR-SYS-009, SR-SYS-010

F-SYS-04

SR-SYS-011, SR-SYS-012, SR-SYS-013

+ +## 7 Dependencies + +* Diagnostics & Health Monitoring Features + +* Persistence & DP Component + +* Communication Features + +* Security & Safety Features + +* OTA Features + + +##",,includes(#535); includes(#512); includes(#511); includes(#510); includes(#509) +509,Feature,New,[F-SYS-01] System State Management,Defines and controls the operational states of the Sensor Hub using a deterministic finite state machine and enforces valid transitions between system states.,,includes(#515); includes(#514); includes(#513); includes(#508) +510,Feature,New,[F-SYS-02] Controlled Teardown Mechanism,"Provides a controlled and safe teardown sequence to ensure data integrity and orderly shutdown during updates, failures, or maintenance operations.",,includes(#518); includes(#517); includes(#516); includes(#508) +511,Feature,New,[F-SYS-03] Status Indication via OLED HMI,"Provides local system status visibility through an OLED display with button-based navigation, replacing LED indicators.",,includes(#522); includes(#521); includes(#520); includes(#519); includes(#508) +512,Feature,New,[F-SYS-04] Debug & Engineering Sessions,"Enables diagnostic and debug sessions allowing engineers to inspect system status, retrieve logs, and perform controlled maintenance actions.",,includes(#525); includes(#524); includes(#523); includes(#508) 513,Requirements,New,[SR-SYS-001] Finite State Machine Control,The system shall implement a defined finite state machine to manage operational states and transitions.,,includes(#509) 514,Requirements,New,[SR-SYS-002] State-Based Operation Restriction,The system shall restrict functional operations based on the current system state.,,includes(#509) 515,Requirements,New,[SR-SYS-003] State Transition Notification,The system shall notify system components when a system state transition occurs.,,includes(#509) @@ -113,6 +3006,430 @@ 523,Requirements,New,[SR-SYS-011] Diagnostic Session Support,The system shall support diagnostic sessions for retrieving system status and diagnostic data.,,includes(#512) 524,Requirements,New,[SR-SYS-012] Debug Session Support,The system shall support debug sessions allowing controlled engineering commands.,,includes(#512) 525,Requirements,New,[SR-SYS-013] Authorized Debug Access Control,The system shall restrict debug session actions to authorized engineering access only.,,includes(#512) +526,Feature,New,[FG-PWR-] Power & Fault Handling Features,"# **Power & Fault Handling Features** + +**Feature Group ID:** FG-PWR +**Version:** 1.0 +**Date:** 2025-01-19 +**Scope:** Sensor Hub (Sub-Hub only) +**Target Platform:** ESP32-S3–based Sensor Hub, ESP-IDF v5.4 + +## **1 Feature Overview** + +The **Power & Fault Handling Features** ensure that the Sensor Hub operates reliably under power fluctuations and recovers gracefully from power interruptions. These features protect critical data during brownouts and enable clean recovery after power restoration. + +**Technology:** + +* **Brownout Detection:** Hardware brownout detector (BOD) + +* **Power-Loss Protection:** Supercapacitor (optional, recommended) + +* **RTC Backup:** External RTC battery (CR2032, optional) + + +## **2 Scope and Assumptions** + +**In Scope** + +* Brownout detection and handling + +* Power-loss data protection + +* Graceful shutdown on power loss + +* Clean recovery after power restoration + + +**Out of Scope** + +* Battery-powered operation (system assumes continuous power) + +* Power management for low-power modes (not applicable for real-time requirements) + + +## **3 Sub-Feature Breakdown** + +### **3.1 F-PWR-01: Brownout Detection and Handling** + +#### **Description** + +The system monitors input voltage and takes immediate action if it drops below safe threshold. + +**Configuration:** + +* **Brownout Threshold:** 3.0V (hardware-configurable) + +* **Detection:** Hardware brownout detector (BOD) in ESP32-S3 + +* **ISR Action:** Set "Power Loss" flag and immediately flush critical buffers to NVS/SD + +* **Recovery:** Perform clean reboot once power is stable + + +**Hardware Support:** + +* **Supercapacitor (Recommended):** 0.5-1.0F for 1-2s at 3.3V + + * Provides runtime during brownout to complete data flush + + * Enables graceful shutdown + +* **External RTC Battery (Optional):** CR2032, 3V, 220mAh + + * Maintains time accuracy during power loss + + * Not required for basic operation + + +#### **Responsibilities** + +* Monitor input voltage + +* Detect brownout condition + +* Trigger immediate data flush + +* Enter graceful shutdown mode + + +#### **Constraints** + +* Brownout detection must be hardware-based (ESP32-S3 BOD) + +* Data flush must complete within supercapacitor runtime (1-2 seconds) + +* System must reboot cleanly after power restoration + + +### **3.2 F-PWR-02: Power-Loss Recovery** + +#### **Description** + +The system recovers gracefully from power interruptions (< 1 second). + +**Recovery Behavior:** + +* Clean reboot after power stabilization + +* Data integrity verification + +* State restoration from persistent storage + +* Diagnostic event generation (if data loss detected) + + +**Recovery Sequence:** + +1. Power restoration detected + +2. Wait for power stabilization (100ms) + +3. Perform clean reboot + +4. Initialize system from persistent storage + +5. Verify data integrity + +6. Report recovery status via diagnostics + + +#### **Responsibilities** + +* Detect power restoration + +* Perform clean reboot + +* Restore system state from persistent storage + +* Verify data integrity + +* Report recovery status + + +## **4 System Requirements (Formal SHALL Statements)** + +### **Brownout Detection Requirements** + +* **SR-PWR-001**: The system shall monitor input voltage and detect brownout conditions below 3.0V. + +* **SR-PWR-002**: The system shall immediately flush critical data buffers to non-volatile storage upon brownout detection. + +* **SR-PWR-003**: The system shall enter graceful shutdown mode during brownout conditions. + +* **SR-PWR-004**: The system shall perform clean reboot after power stabilization. + + +### **Power-Loss Recovery Requirements** + +* **SR-PWR-005**: The system shall recover gracefully from power interruptions. + +* **SR-PWR-006**: The system shall verify data integrity after power restoration. + +* **SR-PWR-007**: The system shall restore system state from persistent storage after power restoration. + +* **SR-PWR-008**: The system shall report power-loss and recovery events via diagnostics. + + +## **5 Traceability Matrix (Feature → System Requirements)** + +

Feature ID

Related System Requirements

F-PWR-01

SR-PWR-001, SR-PWR-002, SR-PWR-003, SR-PWR-004

F-PWR-02

SR-PWR-005, SR-PWR-006, SR-PWR-007, SR-PWR-008

+ +## **6 Design & Implementation Notes (Non-Normative)** + +* **Supercapacitor:** Recommended for production deployment to enable graceful shutdown + +* **RTC Battery:** Optional, improves time accuracy during power loss + +* **Brownout Threshold:** 3.0V is conservative; adjust based on power supply characteristics + +* **Data Flush Priority:** Critical data (calibration, diagnostics) must be flushed first + +* **Recovery Time:** System should recover within 5 seconds after power restoration + + +## **7 Dependencies** + +* **Persistence & Data Management Features** (data flush mechanism) + +* **Diagnostics Features** (power-loss event reporting) + +* **System Management Features** (graceful shutdown, state restoration) + + +## **8 Hardware Recommendations** + +

Component

Specification

Purpose

Supercapacitor

0.5-1.0F, 3.3V

Provides runtime during brownout for data flush

RTC Battery

CR2032, 3V, 220mAh

Maintains time accuracy during power loss

Power Supply

3.3V ±5%, minimum 500mA

Stable power for reliable operation

",,includes(#537); includes(#536) +527,Feature,New,[FG-HW-] Hardware Abstraction Features,"# **Hardware Abstraction Features** + +**Feature Group ID:** FG-HW +**Version:** 1.0 +**Date:** 2025-01-19 +**Scope:** Sensor Hub (Sub-Hub only) +**Target Platform:** ESP32-S3–based Sensor Hub, ESP-IDF v5.4 + +## **1 Feature Overview** + +The **Hardware Abstraction Features** provide a clean separation between application logic and hardware interfaces. These features ensure hardware independence, maintainability, and testability of the system. + +**Architecture Principle:** Application layer SHALL NOT access hardware directly (CFC-ARCH-01). + +## **2 Scope and Assumptions** + +**In Scope** + +* Sensor Abstraction Layer (SAL) + +* Hardware interface abstraction (I2C, SPI, UART, ADC, GPIO) + +* Storage interface abstraction (SD Card, NVM) + +* Display interface abstraction (OLED I2C) + + +**Out of Scope** + +* Hardware driver implementation details (ESP-IDF drivers) + +* Hardware-specific optimizations (deferred to implementation) + + +## **3 Sub-Feature Breakdown** + +### **3.1 F-HW-01: Sensor Abstraction Layer (SAL)** + +#### **Description** + +The system provides a Sensor Abstraction Layer (SAL) to ensure hardware independence and maintainability. + +**Interface Functions:** + +* `sensor_read()`: Retrieve the latest value + +* `sensor_calibrate()`: Perform sensor-specific calibration + +* `sensor_validate()`: Check if the reading is within physical bounds + +* `sensor_health_check()`: Verify the operational status of the hardware + +* `sensor_getMetadata()`: Get sensor capabilities (range, accuracy, etc.) + +* `sensor_reset()`: Recovery from fault states + + +**Sensor State Management:** + +* **INIT:** Sensor initialization + +* **WARMUP:** Sensor warming up (not yet stable) + +* **STABLE:** Sensor operational and stable + +* **DEGRADED:** Sensor operational but degraded + +* **FAILED:** Sensor failed, not operational + + +#### **Responsibilities** + +* Abstract sensor hardware interfaces + +* Provide uniform sensor API + +* Manage sensor state + +* Handle sensor-specific calibration + +* Validate sensor readings + + +#### **Constraints** + +* All sensor access must go through SAL + +* Application layer must not access sensor hardware directly + +* Sensor state must be tracked and reported + + +### **3.2 F-HW-02: Hardware Interface Abstraction** + +#### **Description** + +The system abstracts all hardware interfaces through driver layers. + +**Abstraction Layers:** + +* **I2C Interface:** Abstracted via ESP-IDF I2C driver wrapper + +* **SPI Interface:** Abstracted via ESP-IDF SPI driver wrapper + +* **UART Interface:** Abstracted via ESP-IDF UART driver wrapper + +* **ADC Interface:** Abstracted via ESP-IDF ADC driver wrapper + +* **GPIO Interface:** Abstracted via ESP-IDF GPIO driver wrapper + +* **Storage Interfaces:** SD Card (SDMMC), NVM (NVS) + +* **Display Interface:** OLED I2C + + +**GPIO Discipline:** + +* **No Strapping Pins:** Avoid using strapping pins (GPIO 0, 3, 45, 46) for general-purpose I/O + +* **I2C Pull-up Audit:** Ensure all shared I2C buses have appropriate physical pull-up resistors (2.2kΩ - 4.7kΩ for 3.3V) + +* **No ADC2 with Wi-Fi:** ADC2 unit cannot be used when Wi-Fi is active. All analog sensors must be connected to ADC1 pins + +* **Canonical GPIO Map:** Single authoritative GPIO map document must be maintained + + +#### **Responsibilities** + +* Abstract hardware interfaces + +* Provide uniform API for hardware access + +* Enforce GPIO discipline + +* Manage hardware resource conflicts + + +#### **Constraints** + +* Application layer must not access hardware directly + +* GPIO usage must follow canonical GPIO map + +* Hardware conflicts must be detected and reported + + +## **4 System Requirements (Formal SHALL Statements)** + +### **Sensor Abstraction Layer Requirements** + +* **SR-HW-001**: The system shall provide a Sensor Abstraction Layer (SAL) for all sensor access. + +* **SR-HW-002**: The system shall prevent application layer from directly accessing sensor hardware. + +* **SR-HW-003**: The system shall track sensor state (INIT, WARMUP, STABLE, DEGRADED, FAILED). + +* **SR-HW-004**: The system shall provide sensor validation and health check functions. + + +### **Hardware Interface Abstraction Requirements** + +* **SR-HW-005**: The system shall abstract all hardware interfaces (I2C, SPI, UART, ADC, GPIO) through driver layers. + +* **SR-HW-006**: The system shall enforce GPIO discipline (no strapping pins, proper pull-ups, ADC1/ADC2 separation). + +* **SR-HW-007**: The system shall maintain a canonical GPIO map document. + +* **SR-HW-008**: The system shall detect and report hardware resource conflicts. + + +## **5 Traceability Matrix (Feature → System Requirements)** + +

Feature ID

Related System Requirements

F-HW-01

SR-HW-001, SR-HW-002, SR-HW-003, SR-HW-004

F-HW-02

SR-HW-005, SR-HW-006, SR-HW-007, SR-HW-008

+ +## **6 Design & Implementation Notes (Non-Normative)** + +* **SAL Implementation:** Each sensor type implements SAL interface + +* **Driver Wrappers:** ESP-IDF drivers wrapped in application-specific abstraction layer + +* **GPIO Map:** Must be maintained as single source of truth + +* **Hardware Conflicts:** Runtime detection and reporting via diagnostics + + +## **7 Dependencies** + +* **ESP-IDF Drivers:** I2C, SPI, UART, ADC, GPIO, SDMMC, NVS + +* **System Management Features:** Hardware initialization and teardown + +* **Diagnostics Features:** Hardware fault reporting + + +## **8 GPIO Map Guidelines** + +**Strapping Pins (DO NOT USE):** + +* GPIO 0: Boot mode selection + +* GPIO 3: JTAG + +* GPIO 45: Strapping pin + +* GPIO 46: Strapping pin + + +**ADC Constraints:** + +* **ADC1:** Available when Wi-Fi is active + +* **ADC2:** NOT available when Wi-Fi is active (use ADC1 for all analog sensors) + + +**I2C Pull-up Requirements:** + +* **Physical Pull-ups:** 2.2kΩ - 4.7kΩ for 3.3V + +* **Software Pull-ups:** Not recommended for production (use physical pull-ups)",,includes(#539); includes(#538) +528,Feature,New,[F-DAQ-04] Sensor State Management,"The system tracks sensor operational states (INIT, WARMUP, STABLE, DEGRADED, FAILED). Raw values are never published without an accompanying validity flag indicating the current state.",,includes(#584); includes(#582); includes(#583); includes(#581); includes(#393) +529,Feature,New,[F-DQC-05] Redundant Sensor Support,"For critical parameters (CO2, NH3), the system supports primary and backup sensors using different technologies or interfaces to avoid common-mode failures. System implements sensor fusion algorithm.",,includes(#586); includes(#585); includes(#587); includes(#424) +530,Feature,New,[F-COM-04] Long-Range Fallback Communication,The system supports optional long-range fallback communication using LoRa (External Module) or cellular (LTE-M/NB-IoT) for farm-scale distances where Wi-Fi may not reach.,,includes(#594); includes(#593); includes(#425) +531,Feature,New,[F-DIAG-04] Layered Watchdog System,"The system implements multiple levels of watchdogs: Task WDT (10s), Interrupt WDT (3s), and RTC WDT (30s) to ensure responsiveness and detect deadlocks/hangs.",,includes(#597); includes(#596); includes(#595); includes(#442) +532,Feature,New,[F-DATA-04] Power-Loss Data Protection,"


The system detects brownout conditions (3.0V) and immediately flushes critical data buffers to non-volatile storage. Implements wear-aware batch writing to prevent SD card wear.

",,includes(#601); includes(#600); includes(#599); includes(#598); includes(#454) +533,Feature,New,[F-OTA-05] A/B Partitioning with Rollback,The system implements A/B partitioning for safe firmware updates with automatic rollback capability if new firmware fails validation or health check.,,includes(#604); includes(#603); includes(#602); includes(#474) +534,Feature,New,[F-SEC-04] Security Violation Handling,"The system detects and reports security violations (secure boot failures, authentication failures, message tampering, unauthorized access) as FATAL diagnostic events.",,includes(#607); includes(#606); includes(#605); includes(#492) +535,Feature,New,[F-SYS-05] GPIO & Hardware Discipline,"The system enforces strict GPIO discipline: no strapping pins, proper I2C pull-ups, ADC1/ADC2 separation, and maintains a canonical GPIO map document.",,includes(#608); includes(#611); includes(#610); includes(#609); includes(#508) +536,Feature,New,[F-PWR-01] Brownout Detection and Handling,The system monitors input voltage and detects brownout conditions below 3.0V. Immediately flushes critical data buffers and enters graceful shutdown mode.,,includes(#615); includes(#614); includes(#613); includes(#612); includes(#526) +537,Feature,New,[F-PWR-02] Power-Loss Recovery,"The system recovers gracefully from power interruptions (< 1 second). Performs clean reboot, verifies data integrity, and restores system state from persistent storage.",,includes(#619); includes(#618); includes(#617); includes(#616); includes(#526) +538,Feature,New,[F-HW-01] Sensor Abstraction Layer (SAL),The system provides a Sensor Abstraction Layer (SAL) for all sensor access. Prevents application layer from directly accessing sensor hardware. Tracks sensor state and provides validation functions.,,includes(#622); includes(#623); includes(#621); includes(#620); includes(#527) +539,Feature,New,[F-HW-02] Hardware Interface Abstraction,"The system abstracts all hardware interfaces (I2C, SPI, UART, ADC, GPIO) through driver layers. Enforces GPIO discipline and detects hardware resource conflicts.",,includes(#625); includes(#624); includes(#627); includes(#626); includes(#527) 581,Requirements,New,"[SR-DAQ-011] The system shall track sensor operational states (INIT, WARMUP, STABLE, DEGRADED, FAILED).",This is the description,,includes(#528) 582,Requirements,New,"[SR-DAQ-011] The system shall track sensor operational states (INIT, WARMUP, STABLE, DEGRADED, FAILED).","The system shall track sensor operational states (INIT, WARMUP, STABLE, DEGRADED, FAILED).",,includes(#528) 583,Requirements,New,[SR-DAQ-012] The system shall never publish raw sensor values without an accompanying validity flag indicating the current state.,The system shall never publish raw sensor values without an accompanying validity flag indicating the current state.,,includes(#528) diff --git a/src/App.tsx b/src/App.tsx index fef2dbe..0096cd7 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -12,6 +12,7 @@ import ALMTypePage from "./pages/ALMTypePage"; import TraceabilityMatrixPage from "./pages/TraceabilityMatrixPage"; import ESPIDFHelperPage from "./pages/ESPIDFHelperPage"; import WorkPackageGraphPage from "./pages/WorkPackageGraphPage"; +import SelectedSensorsPage from "./pages/SelectedSensorsPage"; import LoginPage from "./pages/LoginPage"; import NotFound from "./pages/NotFound"; @@ -74,6 +75,14 @@ const App = () => ( } /> + + + + } + /> void; @@ -40,11 +36,10 @@ export function DataUpdateDialog({ onDataLoaded, onClose }: DataUpdateDialogProp const [fileName, setFileName] = useState(''); const fileInputRef = useRef(null); - // Backend proxy config - const [proxyUrl, setProxyUrl] = useState(''); - - // Direct OpenProject config - const [opConfig, setOpConfig] = useState(DEFAULT_CONFIG); + // Server endpoint config - persisted + const [serverUrl, setServerUrl] = useState(() => + localStorage.getItem(SERVER_URL_KEY) || '/api/traceability' + ); // Drag and drop state const [isDragging, setIsDragging] = useState(false); @@ -53,6 +48,15 @@ export function DataUpdateDialog({ onDataLoaded, onClose }: DataUpdateDialogProp setLogs(prev => [...prev, log]); }; + const persistData = (workPackages: WorkPackage[]) => { + const data = { + lastUpdated: new Date().toISOString(), + workPackages + }; + localStorage.setItem(STORAGE_KEY, JSON.stringify(data)); + addLog(`💾 Data persisted to storage (${workPackages.length} items)`); + }; + const handleFile = async (file: File) => { setFileName(file.name); setIsLoading(true); @@ -60,10 +64,13 @@ export function DataUpdateDialog({ onDataLoaded, onClose }: DataUpdateDialogProp setErrors([]); try { + addLog(`📂 Reading file: ${file.name} (${(file.size / 1024).toFixed(1)} KB)`); const text = await file.text(); + addLog(`📝 File loaded, ${text.length} characters`); + const result = parseCSVContent(text); setParseResult(result); - setLogs(result.logs); + setLogs(prev => [...prev, ...result.logs]); setErrors(result.errors); } finally { setIsLoading(false); @@ -84,66 +91,87 @@ export function DataUpdateDialog({ onDataLoaded, onClose }: DataUpdateDialogProp if (file) handleFile(file); }; - const handleFetchFromProxy = async () => { - if (!proxyUrl) { - setErrors(['Please enter a backend proxy URL']); + const handleFetchFromServer = async () => { + if (!serverUrl) { + setErrors(['Please enter a server endpoint URL']); return; } + // Save URL for next time + localStorage.setItem(SERVER_URL_KEY, serverUrl); + setIsLoading(true); setLogs([]); setErrors([]); setParseResult(null); try { - const result = await fetchFromBackendProxy(proxyUrl, addLog); - setLogs(result.logs); - setErrors(result.errors); + addLog(`🔍 Connecting to server: ${serverUrl}`); - if (result.success) { - const typeCounts = result.workPackages.reduce((acc, wp) => { + const response = await fetch(serverUrl, { + method: 'GET', + headers: { + 'Accept': 'application/json, text/csv' + } + }); + + if (!response.ok) { + throw new Error(`Server Error: ${response.status} ${response.statusText}`); + } + + const contentType = response.headers.get('content-type') || ''; + addLog(`📄 Response content-type: ${contentType}`); + + if (contentType.includes('text/csv')) { + addLog(`📋 Parsing CSV response...`); + const csvText = await response.text(); + const result = parseCSVContent(csvText); + + setLogs(prev => [...prev, ...result.logs]); + setErrors(result.errors); + setParseResult(result); + + } else if (contentType.includes('application/json')) { + addLog(`📋 Parsing JSON response...`); + const data = await response.json(); + + let workPackages: WorkPackage[]; + if (Array.isArray(data)) { + workPackages = data; + } else if (data.workPackages) { + workPackages = data.workPackages; + } else { + throw new Error('Invalid JSON format: expected array or {workPackages: [...]}'); + } + + addLog(`✅ Received ${workPackages.length} work packages`); + + const typeCounts = workPackages.reduce((acc, wp) => { acc[wp.type] = (acc[wp.type] || 0) + 1; return acc; }, {} as Record); setParseResult({ success: true, - workPackages: result.workPackages, - logs: result.logs, - errors: result.errors, + workPackages, + logs: [], + errors: [], typeCounts }); + } else { + // Try to parse as CSV anyway + addLog(`⚠️ Unknown content-type, attempting CSV parse...`); + const text = await response.text(); + const result = parseCSVContent(text); + setLogs(prev => [...prev, ...result.logs]); + setErrors(result.errors); + setParseResult(result); } - } finally { - setIsLoading(false); - } - }; - - const handleFetchFromOpenProject = async () => { - setIsLoading(true); - setLogs([]); - setErrors([]); - setParseResult(null); - - try { - const result = await fetchFromOpenProject(opConfig, undefined, addLog); - setLogs(result.logs); - setErrors(result.errors); - if (result.success) { - const typeCounts = result.workPackages.reduce((acc, wp) => { - acc[wp.type] = (acc[wp.type] || 0) + 1; - return acc; - }, {} as Record); - - setParseResult({ - success: true, - workPackages: result.workPackages, - logs: result.logs, - errors: result.errors, - typeCounts - }); - } + } catch (error) { + const errorMsg = error instanceof Error ? error.message : 'Unknown error'; + setErrors([errorMsg]); + addLog(`❌ Error: ${errorMsg}`); } finally { setIsLoading(false); } @@ -151,6 +179,8 @@ export function DataUpdateDialog({ onDataLoaded, onClose }: DataUpdateDialogProp const handleApply = () => { if (parseResult?.success && parseResult.workPackages.length > 0) { + // Persist to localStorage for other users/sessions + persistData(parseResult.workPackages); onDataLoaded(parseResult.workPackages); onClose?.(); } @@ -174,23 +204,19 @@ export function DataUpdateDialog({ onDataLoaded, onClose }: DataUpdateDialogProp Update Traceability Data - Choose how to update your data from OpenProject + Upload a CSV file or fetch from your server - + Upload CSV - + - Backend API - - - - Direct Fetch + Server Fetch @@ -222,103 +248,46 @@ export function DataUpdateDialog({ onDataLoaded, onClose }: DataUpdateDialogProp

- Run python get_traceability.py locally to generate the CSV + Run python get_traceability.py to generate the CSV file

- {/* Tab 2: Backend Proxy */} - + {/* Tab 2: Server Fetch */} +
- + setProxyUrl(e.target.value)} + id="serverUrl" + placeholder="/api/traceability or https://your-server.com/api/data" + value={serverUrl} + onChange={(e) => setServerUrl(e.target.value)} />

- Your backend should return JSON or CSV with work package data + Endpoint that runs your Python script and returns CSV or JSON

-

Backend Setup Guide:

+

Server Setup:

    -
  1. Deploy the Python script on your server
  2. -
  3. Create an API endpoint that runs the script
  4. -
  5. Return JSON or serve the generated CSV
  6. +
  7. Create an endpoint that runs get_traceability.py
  8. +
  9. Return the CSV file or JSON with work packages
  10. +
  11. Example: GET /api/traceability → returns CSV
- - {/* Tab 3: Direct OpenProject Fetch */} - -
-
- - setOpConfig(prev => ({ ...prev, baseUrl: e.target.value }))} - /> -
-
- - setOpConfig(prev => ({ ...prev, projectIdentifier: e.target.value }))} - /> -
-
- - setOpConfig(prev => ({ ...prev, apiKey: e.target.value }))} - /> -
- -
-
-
- -
-

CORS Notice

-

- Direct browser fetch may fail due to CORS. Configure your OpenProject server to allow - cross-origin requests, or use the Backend API option. -

-
-
-
-
{/* Results Section */} @@ -387,7 +356,7 @@ export function DataUpdateDialog({ onDataLoaded, onClose }: DataUpdateDialogProp {parseResult?.success && ( )} - diff --git a/src/pages/SelectedSensorsPage.tsx b/src/pages/SelectedSensorsPage.tsx new file mode 100644 index 0000000..e24ac6b --- /dev/null +++ b/src/pages/SelectedSensorsPage.tsx @@ -0,0 +1,659 @@ +import { useState } from "react"; +import { AppLayout } from "@/components/layout/AppLayout"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { Separator } from "@/components/ui/separator"; +import { + Cpu, + Thermometer, + Droplets, + Wind, + Gauge, + ExternalLink, + FileText, + Zap, + Cable, + Code, + Info, + CheckCircle, + AlertTriangle +} from "lucide-react"; +import { cn } from "@/lib/utils"; + +// Sensor data with datasheet links +const sensors = { + bme680: { + id: 'bme680', + name: 'BME680', + manufacturer: 'Bosch Sensortec', + subtitle: 'Environmental 4-in-1 Sensor', + description: 'Low-power MEMS sensor measuring gas, pressure, temperature, and humidity. Critical for Indoor Air Quality (IAQ) monitoring.', + datasheetUrl: 'https://eu.mouser.com/datasheet/3/1278/1/A2F32BC94C3A80DFBB84AF6E5127DF06330B8846DE5C551EF47B9C5F80540CFA.pdf', + color: 'blue', + icon: Wind, + specs: { + 'Supply Voltage': '1.71V - 3.6V', + 'Interface': 'I2C / SPI', + 'I2C Address': '0x76 (SDO=GND) / 0x77 (SDO=VDD)', + 'Temp Range': '-40 to 85 °C', + 'Pressure Range': '300 to 1100 hPa', + 'Humidity Range': '0 to 100 %RH', + 'Gas Sensing': 'VOCs (0-500 IAQ index)', + 'Temp Accuracy': '±0.5 °C', + 'Humidity Accuracy': '±3 %RH', + 'Pressure Accuracy': '±0.6 hPa' + }, + power: { + sleep: 0.00015, + idle: 0.15, + active: 12, + unit: 'mA' + }, + wiring: [ + { pin: 'VDD', connect: '3.3V', note: 'Main supply' }, + { pin: 'GND', connect: 'GND', note: '' }, + { pin: 'SDA', connect: 'GPIO21', note: 'I2C Data' }, + { pin: 'SCL', connect: 'GPIO22', note: 'I2C Clock' }, + { pin: 'SDO', connect: 'GND or VDD', note: 'Address select' }, + { pin: 'CS', connect: 'VDD', note: 'I2C mode select' } + ], + notes: [ + 'Requires Bosch BSEC2 library for IAQ scores', + 'Native read provides raw gas resistance (Ohms)', + 'Gas sensor requires 24-48h burn-in for accuracy', + 'Keep away from direct heat sources' + ] + }, + ens160: { + id: 'ens160', + name: 'ENS160', + manufacturer: 'ScioSense', + subtitle: 'Digital Metal-Oxide Multi-Gas Sensor', + description: 'TrueVOC™ technology with on-chip algorithms for eCO2 and TVOC output. Features independent hotplates for selective gas detection.', + datasheetUrl: 'https://eu.mouser.com/datasheet/3/1500/1/518e5e0e1bfa8fdf441c96f0a3d093ad.pdf', + color: 'green', + icon: Wind, + specs: { + 'Supply VDD': '1.71 - 1.98V', + 'Supply VDDIO': '1.71 - 3.6V', + 'Interface': 'I2C / SPI', + 'I2C Address': '0x52 (Alt) / 0x53 (Default)', + 'Outputs': 'TVOC (ppb), eCO2 (ppm), AQI-UBA', + 'Warm-up Time': '3 min initial, 1 hr stabilization', + 'TVOC Range': '0 - 65,000 ppb', + 'eCO2 Range': '400 - 65,000 ppm' + }, + power: { + sleep: 0.1, + idle: 0.9, + active: 29, + unit: 'mA' + }, + wiring: [ + { pin: 'VDD', connect: '1.8V LDO', note: '1.8V core supply' }, + { pin: 'VDDIO', connect: '3.3V', note: 'I/O voltage' }, + { pin: 'GND', connect: 'GND', note: '' }, + { pin: 'SDA', connect: 'GPIO21', note: 'I2C Data' }, + { pin: 'SCL', connect: 'GPIO22', note: 'I2C Clock' }, + { pin: 'ADDR', connect: 'GND/VDD', note: 'Address select' } + ], + notes: [ + 'Requires strict adherence to heater timings', + 'Most modules include 1.8V LDO on-board', + 'On-chip processing reduces ESP32 load', + 'Independent hotplates for selective detection' + ] + }, + sen6x: { + id: 'sen6x', + name: 'SEN6x', + manufacturer: 'Sensirion', + subtitle: 'All-in-One Air Quality Module', + description: 'Comprehensive module integrating PM1.0, PM2.5, PM4.0, PM10, NOx, VOC, RH, and Temperature sensors. Simplifies hardware design.', + datasheetUrl: 'https://eu.mouser.com/datasheet/3/1278/1/Sensirion_Datasheet_SEN6x.pdf', + color: 'purple', + icon: Gauge, + specs: { + 'Supply Voltage': '4.5V - 5.5V (5V typical)', + 'Interface': 'I2C', + 'I2C Address': '0x69 (fixed)', + 'PM Accuracy': '±5 μg/m³ or ±5%', + 'Particle Sizes': 'PM1.0, PM2.5, PM4.0, PM10', + 'Additional Sensors': 'NOx, VOC, RH, Temperature', + 'Lifetime': '> 10 years (24/7 operation)', + 'Response Time': '< 10 seconds (PM)' + }, + power: { + sleep: 2.6, + idle: 6.5, + active: 110, + unit: 'mA' + }, + wiring: [ + { pin: 'PIN 1 (VDD)', connect: '5V (VBUS)', note: 'CRITICAL: 3.3V insufficient!' }, + { pin: 'PIN 2 (GND)', connect: 'GND', note: '' }, + { pin: 'PIN 3 (SDA)', connect: 'GPIO21', note: 'I2C Data (3.3V logic compatible)' }, + { pin: 'PIN 4 (SCL)', connect: 'GPIO22', note: 'I2C Clock' }, + { pin: 'PIN 5 (SEL)', connect: 'GND', note: 'I2C mode select' } + ], + notes: [ + 'REQUIRES 5V supply - do not use 3.3V!', + 'Logic levels are 3.3V compatible', + 'Large data frames over I2C', + 'Built-in fan for active sampling', + 'Replaces multiple discrete sensors' + ] + }, + sht4xi: { + id: 'sht4xi', + name: 'SHT4xI', + manufacturer: 'Sensirion', + subtitle: 'Industrial Precision RH/T Sensor', + description: 'Ruggedized version designed for harsh environments. Features built-in heater to remove condensation and prevent drift in high humidity.', + datasheetUrl: 'https://eu.mouser.com/datasheet/3/1278/1/HT_DS_Datasheet_SHT4xI_Digital_1.pdf', + color: 'amber', + icon: Droplets, + specs: { + 'Supply Voltage': '2.3V - 5.5V', + 'Interface': 'I2C', + 'I2C Address': '0x44 (fixed)', + 'Temp Accuracy': '±0.1 °C', + 'Humidity Accuracy': '±1.5 %RH', + 'Temp Range': '-40 to 125 °C', + 'Humidity Range': '0 to 100 %RH', + 'Heater': 'Three levels (up to 200mW)' + }, + power: { + sleep: 0.001, + idle: 0.02, + active: 0.35, + unit: 'mA' + }, + wiring: [ + { pin: 'VDD', connect: '3.3V', note: 'Supply' }, + { pin: 'GND', connect: 'GND', note: '' }, + { pin: 'SDA', connect: 'GPIO21', note: 'I2C Data' }, + { pin: 'SCL', connect: 'GPIO22', note: 'I2C Clock' } + ], + notes: [ + 'Simplest integration - standard I2C read', + 'Heater commands block measurement during execution', + 'Heater can draw up to 35mA at high setting', + 'Industrial-grade: designed for harsh environments', + 'Gold standard for T/RH reference measurement' + ] + } +}; + +const colorMap: Record = { + blue: { bg: 'bg-blue-500/10', border: 'border-blue-500/30', text: 'text-blue-600', light: 'bg-blue-50' }, + green: { bg: 'bg-green-500/10', border: 'border-green-500/30', text: 'text-green-600', light: 'bg-green-50' }, + purple: { bg: 'bg-purple-500/10', border: 'border-purple-500/30', text: 'text-purple-600', light: 'bg-purple-50' }, + amber: { bg: 'bg-amber-500/10', border: 'border-amber-500/30', text: 'text-amber-600', light: 'bg-amber-50' } +}; + +// I2C Bus Map +const i2cBusMap = [ + { addr: '0x44', name: 'SHT4xI', color: 'amber' }, + { addr: '0x52', name: 'ENS160 (Alt)', color: 'green' }, + { addr: '0x53', name: 'ENS160 (Def)', color: 'green' }, + { addr: '0x69', name: 'SEN6x', color: 'purple' }, + { addr: '0x76', name: 'BME680 (SDO=GND)', color: 'blue' }, + { addr: '0x77', name: 'BME680 (SDO=VDD)', color: 'blue' } +]; + +export default function SelectedSensorsPage() { + const [selectedSensor, setSelectedSensor] = useState('overview'); + const [activeTab, setActiveTab] = useState('specs'); + const [powerModes, setPowerModes] = useState>({ + bme680: 'idle', + ens160: 'idle', + sen6x: 'idle', + sht4xi: 'idle', + esp32: 'active' + }); + + const calculateTotalPower = () => { + let total = 0; + Object.entries(sensors).forEach(([key, sensor]) => { + const mode = powerModes[key] || 'idle'; + total += sensor.power[mode]; + }); + // Add ESP32-S3 base power + total += powerModes.esp32 === 'active' ? 80 : 10; + return total; + }; + + const renderOverview = () => ( +
+ {/* Header */} +
+

System Integration Dashboard

+

+ ESP32-S3 environmental sensing array overview. Analyze power consumption and I2C topology before implementation. +

+
+ +
+ {/* Power Budget Calculator */} + + + + + Power Consumption Simulator + 3.3V Rail + + + +
+ {Object.entries(sensors).map(([key, sensor]) => ( +
+
+ {sensor.name} + +
+ + {sensor.power[powerModes[key] || 'idle']} mA + +
+ ))} +
+
+ ESP32-S3 + +
+ + {powerModes.esp32 === 'active' ? 80 : 10} mA + +
+
+ +
+ Estimated Total + + {calculateTotalPower().toFixed(2)} mA + +
+
+
+ + {/* I2C Bus Map */} + + + + + I2C Bus Map + SDA/SCL + + + +
+

Master

+
+ ESP32-S3 (I2C Controller 0) +
+
+
+
+

Slaves

+
+ {i2cBusMap.map((dev) => ( +
+ + {dev.addr} + + {dev.name} +
+ ))} +
+
+
+

• Disable internal pull-ups if external 2.2kΩ/4.7kΩ resistors present.

+

• SEN6x and SHT4x have fixed addresses. ENS160/BME680 are configurable.

+
+ + +
+ + {/* Quick Sensor Cards */} +
+ {Object.values(sensors).map((sensor) => { + const colors = colorMap[sensor.color]; + const Icon = sensor.icon; + return ( + { + setSelectedSensor(sensor.id); + setActiveTab('specs'); + }} + > + + + + {sensor.name} + + {sensor.subtitle} + + + + + + ); + })} +
+
+ ); + + const renderSensorDetail = (sensorId: string) => { + const sensor = sensors[sensorId as keyof typeof sensors]; + if (!sensor) return null; + + const colors = colorMap[sensor.color]; + const Icon = sensor.icon; + + return ( +
+ {/* Header */} +
+
+
+
+ + + {sensor.manufacturer} + +
+

+ + {sensor.name}: {sensor.subtitle} +

+

{sensor.description}

+
+ + + View Datasheet + + +
+
+ + + + + + Specifications + + + + Wiring & Hardware + + + + ESP-IDF Integration + + + + +
+ + + Technical Specifications + + +
+ {Object.entries(sensor.specs).map(([key, value]) => ( +
+
{key}
+
{value}
+
+ ))} +
+
+
+ + + + Power Consumption Profile + + +
+
+ Sleep Mode + {sensor.power.sleep} mA +
+
+ Idle Mode + {sensor.power.idle} mA +
+
+ Active Mode + {sensor.power.active} mA +
+
+

+ Typical values at 3.3V / 25°C +

+
+
+
+ + + + Important Notes + + +
    + {sensor.notes.map((note, idx) => ( +
  • + {note.includes('CRITICAL') || note.includes('REQUIRES') ? ( + + ) : ( + + )} + {note} +
  • + ))} +
+
+
+
+ + + + + Pin Connections to ESP32-S3 + Standard I2C wiring configuration + + +
+
+ {sensor.wiring.map((wire, idx) => ( +
+ {wire.pin} + ➜ {wire.connect} + {wire.note && ( + {wire.note} + )} +
+ ))} +
+
+ +
+

Pull-up Resistors

+
    +
  • • Use 4.7kΩ pull-ups on SDA and SCL if not present on module
  • +
  • • Disable ESP32 internal pull-ups when external resistors used
  • +
  • • For 400kHz I2C, 2.2kΩ pull-ups may be needed with long cables
  • +
+
+
+
+
+ + + + + ESP-IDF v5.4 Integration + I2C initialization and basic read pattern + + +
+
+{`// I2C Master Configuration for ${sensor.name}
+#include "driver/i2c_master.h"
+
+#define I2C_MASTER_NUM    I2C_NUM_0
+#define I2C_MASTER_SDA    GPIO_NUM_21
+#define I2C_MASTER_SCL    GPIO_NUM_22
+#define I2C_MASTER_FREQ   400000  // 400kHz
+
+#define ${sensor.name.toUpperCase()}_ADDR  ${Object.keys(sensor.specs).includes('I2C Address') ? sensor.specs['I2C Address'].split(' ')[0] : '0x00'}
+
+i2c_master_bus_handle_t bus_handle;
+i2c_master_bus_config_t bus_config = {
+    .clk_source = I2C_CLK_SRC_DEFAULT,
+    .i2c_port = I2C_MASTER_NUM,
+    .scl_io_num = I2C_MASTER_SCL,
+    .sda_io_num = I2C_MASTER_SDA,
+    .glitch_ignore_cnt = 7,
+    .flags.enable_internal_pullup = false,
+};
+
+ESP_ERROR_CHECK(i2c_new_master_bus(&bus_config, &bus_handle));
+
+// Add device
+i2c_device_config_t dev_config = {
+    .dev_addr_length = I2C_ADDR_BIT_LEN_7,
+    .device_address = ${sensor.name.toUpperCase()}_ADDR,
+    .scl_speed_hz = I2C_MASTER_FREQ,
+};
+
+i2c_master_dev_handle_t ${sensor.id}_handle;
+ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_config, &${sensor.id}_handle));`}
+                  
+
+ +
+

Recommended Libraries

+ +
+
+
+
+
+
+ ); + }; + + return ( + +
+ {/* Page Header */} +
+
+

+ + Selected Sensors +

+

+ ESP32-S3 Sensor Array Analysis & Integration Guide +

+
+ + ESP-IDF v5.4 | ESP32-S3 + +
+ + {/* Navigation */} +
+ + {Object.values(sensors).map((sensor) => { + const colors = colorMap[sensor.color]; + return ( + + ); + })} +
+ + + + {/* Content */} + + {selectedSensor === 'overview' ? renderOverview() : renderSensorDetail(selectedSensor)} + +
+
+ ); +} diff --git a/src/pages/TraceabilityMatrixPage.tsx b/src/pages/TraceabilityMatrixPage.tsx index af7e4cf..3a9e91b 100644 --- a/src/pages/TraceabilityMatrixPage.tsx +++ b/src/pages/TraceabilityMatrixPage.tsx @@ -9,6 +9,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { ScrollArea } from "@/components/ui/scroll-area"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { GitBranch, Search, @@ -23,11 +24,19 @@ import { Layers, AlertCircle, Download, - Printer + Printer, + Link2 } from "lucide-react"; import { cn } from "@/lib/utils"; -import { WorkPackage, ParsedRelation } from "@/types/traceability"; +import { WorkPackage, WorkPackageType } from "@/types/traceability"; import { generateTraceabilityMarkdown, downloadMarkdown, printToPDF } from "@/lib/exportUtils"; +import { + buildTraceabilityGraph, + getTypeConfig, + FlexibleChain, + FlexibleChainNode, + buildChainsFromType +} from "@/lib/traceabilityUtils"; const OPENPROJECT_BASE_URL = "https://openproject.nabd-co.com/projects/asf/work_packages"; @@ -35,30 +44,6 @@ function getWorkPackageUrl(id: number): string { return `${OPENPROJECT_BASE_URL}/${id}/activity`; } -function parseRelations(relationsStr: string): ParsedRelation[] { - if (!relationsStr) return []; - const relations: ParsedRelation[] = []; - const matches = relationsStr.matchAll(/(\w+)\(#(\d+)\)/g); - for (const match of matches) { - relations.push({ - type: match[1], - targetId: parseInt(match[2], 10), - }); - } - return relations; -} - -interface TraceabilityChain { - feature: WorkPackage; - requirements: { - requirement: WorkPackage; - swRequirements: { - swReq: WorkPackage; - testCases: WorkPackage[]; - }[]; - }[]; -} - function getStatusColor(status: string): string { const statusLower = status.toLowerCase(); if (statusLower.includes("done") || statusLower.includes("closed") || statusLower.includes("resolved")) { @@ -79,131 +64,263 @@ function getCoverageColor(coverage: number): string { return "text-red-600"; } +// Recursive component to render flexible chain nodes +function ChainNodeComponent({ + node, + expandedNodes, + toggleNode +}: { + node: FlexibleChainNode; + expandedNodes: Set; + toggleNode: (id: number) => void; +}) { + const typeConfig = getTypeConfig(node.workPackage.type); + const hasChildren = node.children.length > 0; + const isExpanded = expandedNodes.has(node.workPackage.id); + + return ( +
+
hasChildren && toggleNode(node.workPackage.id)} + > + {hasChildren ? ( + + ) : ( + + )} + + + {node.workPackage.type} + + + e.stopPropagation()} + className={cn("font-mono text-xs hover:underline flex items-center gap-1", typeConfig.color)} + > + #{node.workPackage.id} + + + + {node.workPackage.title} + + + + {node.relationType} + + + + {node.workPackage.status} + + + {hasChildren && ( + + {node.children.length} linked + + )} +
+ + {hasChildren && isExpanded && ( +
+ {node.children.map((child) => ( + + ))} +
+ )} +
+ ); +} + +// Root chain component +function RootChainComponent({ + chain, + expandedRoots, + expandedNodes, + toggleRoot, + toggleNode +}: { + chain: FlexibleChain; + expandedRoots: Set; + expandedNodes: Set; + toggleRoot: (id: number) => void; + toggleNode: (id: number) => void; +}) { + const typeConfig = getTypeConfig(chain.root.type); + const isExpanded = expandedRoots.has(chain.root.id); + const hasChildren = chain.children.length > 0; + + return ( + toggleRoot(chain.root.id)} + > + +
+ {isExpanded ? ( + + ) : ( + + )} + + + {chain.root.type} + + + e.stopPropagation()} + className={cn("font-mono text-xs hover:underline flex items-center gap-1", typeConfig.color)} + > + #{chain.root.id} + + + + {chain.root.title} + + + {chain.root.status} + + + + {chain.totalDescendants} linked items + +
+
+ + +
+ {!hasChildren ? ( +
+ No linked work packages +
+ ) : ( + chain.children.map((child) => ( + + )) + )} +
+
+
+ ); +} + export default function TraceabilityMatrixPage() { const { data, loading, groupedByType } = useTraceabilityData(); const [searchQuery, setSearchQuery] = useState(""); - const [expandedFeatures, setExpandedFeatures] = useState>(new Set()); - const [expandedReqs, setExpandedReqs] = useState>(new Set()); + const [expandedRoots, setExpandedRoots] = useState>(new Set()); + const [expandedNodes, setExpandedNodes] = useState>(new Set()); + const [selectedRootType, setSelectedRootType] = useState('feature'); - // Build traceability chains - const traceabilityChains = useMemo(() => { + // Get available root types (types that have work packages) + const availableTypes = useMemo(() => { if (!data?.workPackages) return []; - - const allWPs = data.workPackages; - const features = allWPs.filter(wp => wp.type === 'feature'); - const requirements = allWPs.filter(wp => wp.type === 'requirements'); - const swReqs = allWPs.filter(wp => wp.type === 'swreq'); - const testCases = allWPs.filter(wp => wp.type === 'software test case' || wp.type === 'system test'); - - // Create lookup maps - const wpById = new Map(allWPs.map(wp => [wp.id, wp])); - - // Find related items by checking relations and parent - function findRelatedIds(wp: WorkPackage): number[] { - const relations = parseRelations(wp.relations); - const relatedIds = relations.map(r => r.targetId); - if (wp.parentId) { - relatedIds.push(parseInt(wp.parentId, 10)); - } - return relatedIds; - } - - // Build chains starting from features - const chains: TraceabilityChain[] = features.map(feature => { - // Find requirements linked to this feature - const linkedReqs = requirements.filter(req => { - const relatedIds = findRelatedIds(req); - return relatedIds.includes(feature.id) || - req.parentId === String(feature.id) || - findRelatedIds(feature).includes(req.id); - }); - - return { - feature, - requirements: linkedReqs.map(req => { - // Find SW requirements linked to this requirement - const linkedSWReqs = swReqs.filter(swReq => { - const relatedIds = findRelatedIds(swReq); - return relatedIds.includes(req.id) || - swReq.parentId === String(req.id) || - findRelatedIds(req).includes(swReq.id); - }); - - return { - requirement: req, - swRequirements: linkedSWReqs.map(swReq => { - // Find test cases linked to this SW requirement - const linkedTests = testCases.filter(tc => { - const relatedIds = findRelatedIds(tc); - return relatedIds.includes(swReq.id) || - tc.parentId === String(swReq.id) || - findRelatedIds(swReq).includes(tc.id); - }); - - return { - swReq, - testCases: linkedTests - }; - }) - }; - }) - }; - }); - - return chains; + const types = new Set(data.workPackages.map(wp => wp.type)); + return Array.from(types).sort(); }, [data]); + // Build traceability graph and chains + const { graph, chains } = useMemo(() => { + if (!data?.workPackages) return { graph: null, chains: [] }; + + const g = buildTraceabilityGraph(data.workPackages); + const c = buildChainsFromType(data.workPackages, selectedRootType, 5); + + return { graph: g, chains: c }; + }, [data, selectedRootType]); + // Filter chains by search const filteredChains = useMemo(() => { - if (!searchQuery) return traceabilityChains; + if (!searchQuery) return chains; const query = searchQuery.toLowerCase(); - return traceabilityChains.filter(chain => { - const featureMatch = chain.feature.title.toLowerCase().includes(query) || - String(chain.feature.id).includes(query); - const reqMatch = chain.requirements.some(r => - r.requirement.title.toLowerCase().includes(query) || - String(r.requirement.id).includes(query) - ); - const swReqMatch = chain.requirements.some(r => - r.swRequirements.some(sw => - sw.swReq.title.toLowerCase().includes(query) || - String(sw.swReq.id).includes(query) - ) - ); - return featureMatch || reqMatch || swReqMatch; - }); - }, [traceabilityChains, searchQuery]); - - // Calculate coverage statistics - const stats = useMemo(() => { - const features = groupedByType['feature'] || []; - const requirements = groupedByType['requirements'] || []; - const swReqs = groupedByType['swreq'] || []; - const testCases = groupedByType['test case'] || []; - - const featuresWithReqs = traceabilityChains.filter(c => c.requirements.length > 0).length; - const reqsWithSWReqs = traceabilityChains.reduce((acc, c) => - acc + c.requirements.filter(r => r.swRequirements.length > 0).length, 0); - const swReqsWithTests = traceabilityChains.reduce((acc, c) => - acc + c.requirements.reduce((acc2, r) => - acc2 + r.swRequirements.filter(sw => sw.testCases.length > 0).length, 0), 0); - - return { - totalFeatures: features.length, - totalRequirements: requirements.length, - totalSWReqs: swReqs.length, - totalTestCases: testCases.length, - featuresWithReqs, - reqsWithSWReqs, - swReqsWithTests, - featureCoverage: features.length ? Math.round((featuresWithReqs / features.length) * 100) : 0, - reqCoverage: requirements.length ? Math.round((reqsWithSWReqs / requirements.length) * 100) : 0, - swReqCoverage: swReqs.length ? Math.round((swReqsWithTests / swReqs.length) * 100) : 0, + + const matchesSearch = (wp: WorkPackage): boolean => { + return wp.title.toLowerCase().includes(query) || + String(wp.id).includes(query); }; - }, [groupedByType, traceabilityChains]); + + const chainMatchesSearch = (chain: FlexibleChain): boolean => { + if (matchesSearch(chain.root)) return true; + + const checkChildren = (nodes: FlexibleChainNode[]): boolean => { + return nodes.some(n => + matchesSearch(n.workPackage) || checkChildren(n.children) + ); + }; + + return checkChildren(chain.children); + }; + + return chains.filter(chainMatchesSearch); + }, [chains, searchQuery]); - const toggleFeature = (id: number) => { - setExpandedFeatures(prev => { + // Calculate coverage statistics (flexible - based on graph) + const stats = useMemo(() => { + if (!graph || !data?.workPackages) { + return { + totalItems: 0, + linkedItems: 0, + coverage: 0, + typeStats: {} as Record + }; + } + + const typeStats: Record = {}; + + data.workPackages.forEach(wp => { + if (!typeStats[wp.type]) { + typeStats[wp.type] = { total: 0, linked: 0 }; + } + typeStats[wp.type].total++; + + const node = graph.nodes.get(wp.id); + if (node && node.linkedItems.length > 0) { + typeStats[wp.type].linked++; + } + }); + + const totalItems = data.workPackages.length; + const linkedItems = Array.from(graph.nodes.values()).filter(n => n.linkedItems.length > 0).length; + + return { + totalItems, + linkedItems, + coverage: totalItems > 0 ? Math.round((linkedItems / totalItems) * 100) : 0, + typeStats + }; + }, [graph, data]); + + const toggleRoot = (id: number) => { + setExpandedRoots(prev => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); @@ -211,8 +328,8 @@ export default function TraceabilityMatrixPage() { }); }; - const toggleReq = (id: number) => { - setExpandedReqs(prev => { + const toggleNode = (id: number) => { + setExpandedNodes(prev => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); @@ -221,15 +338,20 @@ export default function TraceabilityMatrixPage() { }; const expandAll = () => { - setExpandedFeatures(new Set(traceabilityChains.map(c => c.feature.id))); - setExpandedReqs(new Set( - traceabilityChains.flatMap(c => c.requirements.map(r => r.requirement.id)) - )); + const allRootIds = chains.map(c => c.root.id); + setExpandedRoots(new Set(allRootIds)); + + // Collect all node IDs from children + const collectNodeIds = (nodes: FlexibleChainNode[]): number[] => { + return nodes.flatMap(n => [n.workPackage.id, ...collectNodeIds(n.children)]); + }; + const allNodeIds = chains.flatMap(c => collectNodeIds(c.children)); + setExpandedNodes(new Set(allNodeIds)); }; const collapseAll = () => { - setExpandedFeatures(new Set()); - setExpandedReqs(new Set()); + setExpandedRoots(new Set()); + setExpandedNodes(new Set()); }; if (loading) { @@ -242,8 +364,33 @@ export default function TraceabilityMatrixPage() { ); } + // For export, build legacy format + const legacyChains = chains.map(chain => ({ + feature: chain.root, + requirements: chain.children.map(child => ({ + requirement: child.workPackage, + swRequirements: child.children.map(sw => ({ + swReq: sw.workPackage, + testCases: sw.children.map(tc => tc.workPackage) + })) + })) + })); + + const legacyStats = { + totalFeatures: groupedByType['feature']?.length || 0, + totalRequirements: groupedByType['requirements']?.length || 0, + totalSWReqs: groupedByType['swreq']?.length || 0, + totalTestCases: (groupedByType['software test case']?.length || 0) + (groupedByType['system test']?.length || 0), + featuresWithReqs: chains.filter(c => c.children.length > 0).length, + reqsWithSWReqs: 0, + swReqsWithTests: 0, + featureCoverage: 0, + reqCoverage: 0, + swReqCoverage: 0 + }; + const handleExportMarkdown = () => { - const markdown = generateTraceabilityMarkdown(traceabilityChains, stats); + const markdown = generateTraceabilityMarkdown(legacyChains, legacyStats); downloadMarkdown(markdown, `traceability-matrix-${new Date().toISOString().split('T')[0]}.md`); }; @@ -251,6 +398,11 @@ export default function TraceabilityMatrixPage() { printToPDF(); }; + // Get top 4 type stats for display + const topTypeStats = Object.entries(stats.typeStats) + .sort((a, b) => b[1].total - a[1].total) + .slice(0, 4); + return (
@@ -262,7 +414,7 @@ export default function TraceabilityMatrixPage() { Traceability Matrix

- Complete chain from Features → Requirements → SW Requirements → Test Cases + Flexible cross-type linking between all work packages

@@ -279,74 +431,35 @@ export default function TraceabilityMatrixPage() { {/* Coverage Statistics */}
- - - - - Features - - - -
{stats.totalFeatures}
-

- - {stats.featureCoverage}% - - {" "}linked to requirements -

-
-
- - - - - - Requirements - - - -
{stats.totalRequirements}
-

- - {stats.reqCoverage}% - - {" "}linked to SW reqs -

-
-
- - - - - - SW Requirements - - - -
{stats.totalSWReqs}
-

- - {stats.swReqCoverage}% - - {" "}have test cases -

-
-
- - - - - - Test Cases - - - -
{stats.totalTestCases}
-

- Total verification tests -

-
-
+ {topTypeStats.map(([type, stat]) => { + const typeConfig = getTypeConfig(type); + const coverage = stat.total > 0 ? Math.round((stat.linked / stat.total) * 100) : 0; + return ( + + + +
+ {type === 'feature' && } + {type === 'requirements' && } + {type === 'swreq' && } + {(type === 'software test case' || type === 'system test') && } + {!['feature', 'requirements', 'swreq', 'software test case', 'system test'].includes(type) && } +
+ {type} +
+
+ +
{stat.total}
+

+ + {coverage}% + + {" "}have links ({stat.linked}) +

+
+
+ ); + })}
@@ -357,7 +470,7 @@ export default function TraceabilityMatrixPage() { - Matrix View + All Links View @@ -365,19 +478,34 @@ export default function TraceabilityMatrixPage() { -
+
Traceability Tree - Hierarchical view of requirements traceability + Explore relationships starting from any work package type
-
+
+
setSearchQuery(e.target.value)} - className="pl-9 w-64" + className="pl-9 w-48" />
@@ -543,265 +543,90 @@ export default function TraceabilityMatrixPage() { - {/* Matrix View */} + {/* All Links View */} - Traceability Matrix Table - Flat table view showing all traceability links + All Work Package Links + Flat table showing all relationships between work packages - -
- - Feature -
-
- - -
- - Requirement -
-
- - -
- - SW Requirement -
-
- - -
- - Test Case -
-
+ Source ID + Source Type + Source Title + Relation + Target ID + Target Type + Target Title
- {filteredChains.flatMap((chain) => { - const rows: React.ReactNode[] = []; - - if (chain.requirements.length === 0) { - rows.push( - - - - #{chain.feature.id} - - -
{chain.feature.title}
-
- - - - - No linked requirements - -
- ); - } else { - chain.requirements.forEach((reqChain, reqIdx) => { - if (reqChain.swRequirements.length === 0) { - rows.push( - + {graph && Array.from(graph.nodes.values()) + .filter(node => node.linkedItems.length > 0) + .flatMap(node => + node.linkedItems + .filter(item => item.direction === 'outgoing') + .map((item, idx) => { + const sourceConfig = getTypeConfig(node.workPackage.type); + const targetConfig = getTypeConfig(item.workPackage.type); + + return ( + - {reqIdx === 0 && ( - <> - - #{chain.feature.id} - - -
{chain.feature.title}
- - )} + + #{node.workPackage.id} + +
- + + {node.workPackage.type} + + + + {node.workPackage.title} + + +
+ + + {item.relationType} + +
- #{reqChain.requirement.id} + #{item.workPackage.id} -
{reqChain.requirement.title}
- + + {item.workPackage.type} + - - No linked SW requirements + + {item.workPackage.title}
); - } else { - reqChain.swRequirements.forEach((swReqChain, swIdx) => { - if (swReqChain.testCases.length === 0) { - rows.push( - - - {reqIdx === 0 && swIdx === 0 && ( - <> - - #{chain.feature.id} - - -
{chain.feature.title}
- - )} -
- - - - - {swIdx === 0 && ( - <> - - #{reqChain.requirement.id} - - -
{reqChain.requirement.title}
- - )} -
- - - - - - #{swReqChain.swReq.id} - - -
{swReqChain.swReq.title}
-
- - - - - No test cases - -
- ); - } else { - swReqChain.testCases.forEach((tc, tcIdx) => { - rows.push( - - - {reqIdx === 0 && swIdx === 0 && tcIdx === 0 && ( - <> - - #{chain.feature.id} - - -
{chain.feature.title}
- - )} -
- - - - - {swIdx === 0 && tcIdx === 0 && ( - <> - - #{reqChain.requirement.id} - - -
{reqChain.requirement.title}
- - )} -
- - - - - {tcIdx === 0 && ( - <> - - #{swReqChain.swReq.id} - - -
{swReqChain.swReq.title}
- - )} -
- - - - - - #{tc.id} - - -
{tc.title}
-
-
- ); - }); - } - }); - } - }); - } - - return rows; - })} + }) + ) + }