> ## Documentation Index
> Fetch the complete documentation index at: https://docs.industrialpmr.com/llms.txt
> Use this file to discover all available pages before exploring further.

# System Architecture

> Comprehensive end-to-end data pipeline from physical edge sensors to cloud analytics and web dashboards.

The Industrial PMR architecture is engineered for low latency, high resilience, and industrial-grade reliability in demanding factory environments.

## End-to-End Pipeline Overview

```mermaid theme={null}
flowchart TD
    subgraph Floor ["🏭 Physical Factory Floor"]
        M1["Standard Production Machinery<br/>(Cycle & Stroke Counting)"] -->|Pulse Sensor & CT Clamps| N1["ipmr223m-v1<br/>Legacy Production Node"]
        M2["Heavy Production & 3-Phase Machinery<br/>(Full Energy & Cycle Intelligence)"] -->|Pulse Sensors & 3-Phase Terminals| N2["ipmr226<br/>Refined Integrated Controller<br/>(Power Analyzer + Cycles)"]
    end

    subgraph EdgeTransport ["⚡ Edge Buffering & Transport"]
        N1 & N2 -.->|Network Outage| FlashBuf[("Onboard SPI Flash Ring-Buffer<br/>(Zero Data Loss)")]
        N1 & N2 -->|BLE 5.0 Commissioning| MobileTool["Technician Setup Tool<br/>(Mobile / Tablet)"]
        N1 & N2 -->|MQTT over TLS (Port 8883)| MQTTBroker["Enterprise MQTT Broker<br/>mqtt.industrialpmr.com"]
        N1 & N2 -->|HTTP/REST Fallback| RestIngest["REST Ingestion Middleware<br/>rest-middleware-01.industrialpmr.com"]
    end

    subgraph MiddlewareCloud ["☁️ Real-Time Pipeline & Cloud Processing"]
        MQTTBroker --> MQTTWorker["iPMR MQTT Worker Service<br/>(PubSub Dispatcher & Influx Streamer)"]
        MQTTWorker --> PubSub["Google Cloud Pub/Sub<br/>(ipmr-v2-records-pipeline / ipmr-v2-electricity-pipeline)"]
        MQTTWorker --> InfluxDB[("InfluxDB Time-Series Engine<br/>Bucket: ipmr-v2-streams")]
        PubSub --> TelemetryFunc["Cloud Functions Processing Engine<br/>(Shift Aggregator, OEE & Anomaly)"]
        TelemetryFunc --> RTDB[("Firebase Realtime Database<br/>(Live Dials & Device States)")]
        ERPBridge["Enterprise ERP Connector<br/>(Secure RFC/HTTP Proxy)"] <--> TelemetryFunc
    end

    subgraph ClientLayer ["🖥️ Monitoring & User Applications"]
        RTDB <-->|Live WebSocket Synchronization| WebDash["Industrial PMR Dashboard<br/>https://dash.industrialpmr.com"]
        MQTTBroker <-->|WSS (Port 8084)| WebDash
        WebDash --> Wallboards["Shop Floor Wallboards & Kiosks"]
        WebDash --> Management["Plant Leadership & Operations"]
    end
```

***

## Architectural Layers Detailed

### 1. Edge Hardware Layer

The physical sensor interface is handled by two specialized edge hardware models:

* **`ipmr223m-v1` (Legacy Production Node)**:
  * Earlier, simpler controller focused on core cycle and stroke monitoring.
  * Connects to machine limit switches, proximity sensors, or optical photo-eyes via optoisolated digital inputs.
  * Monitors operating current via non-invasive split-core Current Transducers (CTs) to identify running vs. idling states.
  * Features an onboard battery-backed Real-Time Clock (RTC) for microsecond timestamp precision and SPI flash ring-buffering.
* **`ipmr226` (Flagship Integrated Power Analyzer & Production Node)**:
  * New, refined controller combining cycle counting with a high-precision polyphase power analyzer.
  * Direct 4-wire potential measurement (Phase $R, Y, B$ + Neutral) for true RMS line-to-neutral and line-to-line voltages.
  * Computes active power (kW), reactive power (kVAR), power factor (PF), frequency (Hz), phase balance, and cumulative kWh.
* **Local SPI Flash Ring-Buffer**:
  * Automatically activates on both `ipmr223m-v1` and `ipmr226` whenever factory Wi-Fi or broker connectivity drops.
  * Telemetry records are written to non-volatile flash memory and chronologically replayed with original RTC timestamps once the network is restored.

***

### 2. Transport & Messaging Layer

Telemetry transmission is optimized for minimal network overhead and high reliability:

* **MQTT Protocol**: Operates over TLS on port 8883 (`mqtts://mqtt.industrialpmr.com`) using QoS 1/2 for reliable delivery.
* **Shard-Aware Topics**:
  * `ipmr/{shard}/{mac}/telemetry`: High-frequency sensor streams from edge units.
  * `ipmr/{shard}/{mac}/downlink`: Client-to-node control (keep-alive pings, configuration adjustments, sampling rate commands).
  * `unit_to_server/#`: Backward-compatible protocol pipeline for legacy node firmware.
* **On-Demand Downlink Keep-Alive**:
  To protect factory cellular or Wi-Fi bandwidth when hundreds of nodes are deployed, edge nodes default to a low-frequency heartbeat. When an operator opens a machine card on the web dashboard, the dashboard issues a `KEEP_ALIVE` downlink pulse. The node then escalates to 1 Hz live streaming for as long as the supervisor is viewing that machine.

***

### 3. Cloud Ingestion & Analytics Pipeline

The cloud backend processes millions of incoming data points using a distributed, event-driven pipeline:

* **MQTT Middleware Dispatcher**:
  * High-throughput Node.js microservice running in container clusters.
  * Performs validation, timestamp normalization, and dual-dispatch to InfluxDB and Google Cloud Pub/Sub.
* **Google Cloud Pub/Sub**:
  * Shards incoming records into dedicated topics: `ipmr-v2-records-pipeline` (cycle pulses and machine states) and `ipmr-v2-electricity-pipeline` (3-phase energy parameters).
* **Time-Series Storage (InfluxDB)**:
  * High-density retention for second-by-second voltage waveforms, current peaks, and power factor histories.
* **Firebase Realtime Database (RTDB)**:
  * Serves as the real-time operational state cache, powering instantaneous multi-user web dashboard synchronization.

***

### 4. Client Dashboard Layer (Web Application)

* **Architecture**: Built on modern React and TypeScript using the Chakra UI design system with full support for light and dark factory floor modes.
* **Reactive State Management**: Implements Jotai atoms with custom reactive hooks (`useDeviceTelemetry`, `useUnitMac`) that maintain WebSocket links with automatic unmount garbage collection.
* **Continuous Operation**: Designed for 24/7 unassisted operation on plant wallboards, with automatic memory cleanup and reconnection resilience.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.