containerized-mioty-service-center

BSSCI Service Center - Complete Documentation

Overview

The BSSCI Service Center is a comprehensive IoT device management system that provides secure communication between mioty sensors, base stations, and MQTT brokers. It implements the BSSCI (Base Station Service Center Interface) protocol with advanced features for sensor lifecycle management, automatic detachment, and real-time monitoring.

Table of Contents

  1. System Architecture
  2. Core Features
  3. Installation & Setup
  4. Configuration
  5. Sensor Management
  6. Auto-Detach System
  7. MQTT Integration
  8. Web Interface
  9. API Reference
  10. Troubleshooting
  11. Advanced Features
  12. OMS/Wireless M-Bus Support
  13. User Authentication & Access Control

System Architecture

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Base Station  │◄──►│  Service Center  │◄──►│  MQTT Broker    │
│                 │TLS │                  │    │                 │
│  - Sensor Mgmt  │    │ - TLS Server     │    │ - Data Topics   │
│  - Data Collect │    │ - MQTT Client    │    │ - Config Topics │
│  - Status Rep.  │    │ - Web Interface  │    │ - Status Topics │
│                 │    │ - Auto-Detach    │    │ - Commands      │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                │
                         ┌──────▼──────┐
                         │ Web Browser │
                         │ Management  │
                         └─────────────┘

Key Components

Core Features

Sensor Lifecycle Management

Sensor Detail Dashboard

Click on any sensor EUI to view comprehensive statistics:

Network Topology Visualization

Interactive network visualization showing the complete mioty infrastructure:

System Health Dashboard

Comprehensive system monitoring and health metrics:

Base Station Management

Dedicated management interface for base stations:

Traffic Dashboard

Enhanced real-time traffic visualization:

Variable MAC (VM) Sub-Channel Support

Full ETSI TS 103357 compliant Variable MAC implementation for metering devices:

OMS/Wireless M-Bus (wMBUS) Meter Support

Full EN 13757 compliant wireless M-Bus frame parsing for OMS-compatible metering devices received via VM sub-channel:

Coverage Map

Interactive floorplan-based device positioning for network coverage visualization:

Real-Time Monitoring

Data Processing

Update System

Seamless software updates for both standalone and Docker installations:

Tested Base Stations

The BSSCI Service Center has been tested and verified with the following base station hardware:

Manufacturer Device
Diehl Metering Premium Gateway
Weptech AVA1
Miromico Edge
Diehl Metering Compact Gateway
RAK WisGate Connect for mioty

Installation & Setup

Prerequisites

Quick Start

  1. Clone and Setup:
    git clone <repository-url>
    cd bssci-service-center
    pip install -r requirements.txt
    
  2. Configure Environment:
    cp .env.example .env
    # Edit .env with your settings
    
  3. Generate Certificates (if needed):
    mkdir certs
    # Use web UI certificate management or manual generation
    
  4. Start the Service:
    python web_main.py
    
  5. Access Web Interface: Open http://localhost:5000 in your browser

Configuration

Environment Variables (.env)

# TLS Server Configuration
LISTEN_HOST=0.0.0.0
LISTEN_PORT=8000
CERT_FILE=certs/service_center_cert.pem
KEY_FILE=certs/service_center_key.pem
CA_FILE=certs/ca_cert.pem

# MQTT Configuration
MQTT_BROKER=your-mqtt-broker.com
MQTT_PORT=1883
MQTT_USERNAME=your-username
MQTT_PASSWORD=your-password
BASE_TOPIC=mioty

# Auto-detach Configuration
AUTO_DETACH_ENABLED=true
AUTO_DETACH_TIMEOUT=259200          # 72 hours in seconds
AUTO_DETACH_WARNING_TIMEOUT=129600  # 36 hours in seconds
AUTO_DETACH_CHECK_INTERVAL=3600     # Check every hour

# Application Configuration
SENSOR_CONFIG_FILE=endpoints.json
STATUS_INTERVAL=300
DEDUPLICATION_DELAY=2.0

Main Configuration (bssci_config.py)

The system uses a Python configuration file for core settings:

# Network Configuration
LISTEN_HOST = "0.0.0.0"
LISTEN_PORT = 16018

# SSL/TLS Certificates
CERT_FILE = "certs/service_center_cert.pem"
KEY_FILE = "certs/service_center_key.pem" 
CA_FILE = "certs/ca_cert.pem"

# Auto-detach Settings (configurable via web UI)
AUTO_DETACH_ENABLED = True
AUTO_DETACH_TIMEOUT = 72 * 3600      # 72 hours
AUTO_DETACH_WARNING_TIMEOUT = 36 * 3600  # 36 hours
AUTO_DETACH_CHECK_INTERVAL = 3600    # 1 hour

Sensor Management

Adding Sensors

Via Web Interface

  1. Navigate to “Manage Sensors” in the web UI
  2. Click “Add New Sensor”
  3. Fill in required fields:
    • EUI: 16-character hexadecimal identifier
    • Network Key: 32-character hexadecimal key
    • Short Address: 4-character hexadecimal address
    • Bidirectional: Enable/disable bidirectional communication

Primary Method: Legacy sensor registration via topic: {BASE_TOPIC}/ep/{EUI}/register

Required JSON Payload:

{
  "nwKey": "0011223344556677889AABBCCDDEEFF00",
  "shortAddr": "1234",
  "bidi": false
}

Practical Example:

# Register sensor with EUI FCA84A0300001234 (Legacy method - RECOMMENDED)
mosquitto_pub -h your-broker.com -u username -p password \
  -t "mioty/ep/FCA84A0300001234/register" \
  -m '{"nwKey": "0011223344556677889AABBCCDDEEFF00", "shortAddr": "1234", "bidi": false}'

Alternative Configuration Method: Use config topic: {BASE_TOPIC}/ep/{EUI}/config

# Alternative configuration method (still supported)
mosquitto_pub -h your-broker.com -u username -p password \
  -t "mioty/ep/FCA84A0300001234/config" \
  -m '{"nwKey": "0011223344556677889AABBCCDDEEFF00", "shortAddr": "1234", "bidi": false}'

Sensor Control Commands: Use unified command topic: {BASE_TOPIC}/ep/{EUI}/cmd

Available Commands:

Command Examples:

# Attach sensor
mosquitto_pub -h broker -t "mioty/ep/FCA84A0300001234/cmd" -m "attach"

# Detach sensor
mosquitto_pub -h broker -t "mioty/ep/FCA84A0300001234/cmd" -m "detach"

# Request status
mosquitto_pub -h broker -t "mioty/ep/FCA84A0300001234/cmd" -m "status"

Important Notes:

Sensor Status Indicators

The web interface displays comprehensive sensor status:

Manual Detachment

Single Sensor Detachment

Bulk Detachment

Auto-Detach System

The auto-detach system provides automated sensor lifecycle management based on communication activity.

Configuration Parameters

Parameter Default Description
AUTO_DETACH_ENABLED true Enable/disable auto-detach functionality
AUTO_DETACH_TIMEOUT 259200 Seconds (72 hours) before auto-detach
AUTO_DETACH_WARNING_TIMEOUT 129600 Seconds (36 hours) before warning
AUTO_DETACH_CHECK_INTERVAL 3600 Seconds (1 hour) between checks

Auto-Detach Process

  1. Activity Monitoring: System tracks last communication from each sensor
  2. Warning Phase (after 36 hours):
    • Warning status displayed in web interface
    • MQTT warning notification sent to ep/{EUI}/warning
    • Sensor status shows hours until detachment
  3. Auto-Detach Phase (after 72 hours):
    • Sensor automatically detached from all base stations
    • MQTT notification sent to ep/{EUI}/status
    • Sensor removed from registration tracking
    • Status updated in web interface

Warning Information

When sensors enter warning state, the following information is available:

{
  "action": "inactivity_warning",
  "sensor_eui": "FCA84A0300001234",
  "inactive_hours": 36.5,
  "hours_until_detach": 35.5,
  "warning_threshold_hours": 36,
  "detach_threshold_hours": 72,
  "timestamp": 1703123456.789
}

MQTT Integration

Unified Topic Structure

The system uses a simplified, unified MQTT topic structure under {BASE_TOPIC}/ep/{EUI}/:

{BASE_TOPIC}/
├── ep/{EUI}/
│   ├── register        # 🎯 SENSOR REGISTRATION (Legacy - RECOMMENDED)
│   ├── config          # Alternative sensor configuration
│   ├── cmd             # 🎯 UNIFIED SENSOR COMMANDS (attach, detach, status)
│   ├── ul              # Uplink data from sensors
│   ├── dl              # Downlink data to sensors  
│   ├── status          # Sensor status updates
│   ├── warning         # Inactivity warnings
│   ├── response        # Command responses
│   ├── error           # Error notifications
│   └── vm/             # Variable MAC sub-channel
│       ├── activate    # VM activation commands
│       ├── deactivate  # VM deactivation commands
│       ├── status      # VM status updates
│       ├── ulData      # VM uplink data
│       └── dlData      # VM downlink data
├── ep/oms_{MFR}_{SERIAL}/
│   └── ul              # OMS meter uplink data
├── bs/{EUI}/           # Base station status
├── config/             # System configuration
└── health_check        # Connection health monitoring

Subscription Topics (what the system listens to):

Publication Topics (what the system sends):

Key Simplifications:

Unified Command System

The system now uses a single, unified command pattern for all sensor operations:

One Command Topic: {BASE_TOPIC}/ep/{EUI}/cmd

Complete Sensor Workflow

Step 1: Register Sensor (Legacy Method - RECOMMENDED)

# Register sensor using legacy topic (recommended for compatibility)
mosquitto_pub -h broker -u user -p pass \
  -t "mioty/ep/FCA84A0300001234/register" \
  -m '{"nwKey": "0011223344556677889AABBCCDDEEFF00", "shortAddr": "1234", "bidi": false}'

Step 2: Control Sensor (Unified Commands)

# All sensor commands use the same unified topic pattern

# Attach sensor to base stations
mosquitto_pub -h broker -t "mioty/ep/FCA84A0300001234/cmd" -m "attach"

# Detach sensor from base stations
mosquitto_pub -h broker -t "mioty/ep/FCA84A0300001234/cmd" -m "detach"

# Request sensor status
mosquitto_pub -h broker -t "mioty/ep/FCA84A0300001234/cmd" -m "status"

Legacy Support

✅ Legacy Registration: The /bssci/ep/eui/register topic is fully supported for backward compatibility with existing systems.

# Legacy registration (RECOMMENDED for stability)
mosquitto_pub -h broker -t "mioty/ep/FCA84A0300001234/register" \
  -m '{"nwKey": "0011223344556677889AABBCCDDEEFF00", "shortAddr": "1234", "bidi": false}'

Simplified Architecture

Command Responses

All commands receive acknowledgments on: {BASE_TOPIC}/ep/{EUI}/response

{
  "command": "attach",
  "status": "received",
  "timestamp": 1703123456.789
}

Command Responses

Commands receive responses on topic EP/{EUI}/response:

{
  "command": "detach",
  "status": "received",
  "timestamp": 1703123456.789
}

Auto-Detach Notifications

Warning Notification (ep/{EUI}/warning)

{
  "action": "inactivity_warning",
  "sensor_eui": "FCA84A0300001234", 
  "inactive_hours": 36.5,
  "hours_until_detach": 35.5,
  "timestamp": 1703123456.789
}

Auto-Detach Notification (ep/{EUI}/status)

{
  "action": "auto_detached",
  "sensor_eui": "FCA84A0300001234",
  "reason": "inactivity", 
  "inactive_hours": 72.3,
  "threshold_hours": 72,
  "timestamp": 1703123456.789
}

OMS Meter MQTT Publishing

OMS/wMBUS meters detected via the VM sub-channel are automatically published to MQTT using a unified payload format. Each meter publishes under a dedicated topic based on its manufacturer and serial number.

Topic Format: {BASE_TOPIC}/ep/oms_{manufacturer}_{serial}/ul

Example Topic: mioty/ep/oms_DME_269898905/ul

Payload Format:

{
  "bs_eui": "00073200007E21C5",
  "snr": 3.96,
  "rssi": -122.13,
  "data": "5544a511995416107607...",
  "mac_type": 0,
  "timestamp": 1739012345.67,
  "oms": {
    "serial": "269898905",
    "serial_hex": "10165499",
    "manufacturer": "DME",
    "manufacturer_name": "DIEHL Metering",
    "version": 118,
    "device_type": 7,
    "device_type_name": "Water",
    "meter_id": "A51110165499"
  }
}

The payload follows the same structure as standard mioty sensor uplinks (bs_eui, snr, rssi, data, mac_type, timestamp) with an additional oms block containing the decoded wMBUS meter information.

Web Interface

Dashboard Overview

The main dashboard provides a redesigned real-time system overview with mioty branding:

Sensor Management Interface

Sensor List View

Sensor Details

Configuration Management

General Settings

Auto-Detach Settings

Certificate Management

SSL Certificate Operations

Certificate Files Required

API Reference

Sensor Operations

Get All Sensors

GET /api/sensors

Returns complete sensor status including registration, activity, and warning information.

Add/Update Sensor

POST /api/sensors
Content-Type: application/json

{
  "eui": "FCA84A0300001234",
  "nwKey": "0011223344556677889AABBCCDDEEFF00", 
  "shortAddr": "1234",
  "bidi": false
}

Delete Sensor

DELETE /api/sensors/{eui}

Detach Single Sensor

POST /api/sensors/{eui}/detach

Detaches the sensor from all connected base stations.

Clear All Sensors

POST /api/sensors/clear

Performs bulk detachment and clears all sensor configurations.

Export Sensors to CSV

GET /api/sensors/export

Downloads all sensor configurations as CSV file with columns: eui, nwKey, shortAddr, bidi.

Import Sensors from CSV/TXT

POST /api/sensors/import
Content-Type: multipart/form-data

file: <csv or txt file>

Imports sensors from CSV or TXT file. Supports comma, semicolon, and tab delimiters. Automatically detects header row.

Variable MAC (VM) Operations

Activate VM Sub-Channel

POST /api/vm/activate
Content-Type: application/json

{
  "eui": "FCA84A0300001234"
}

Deactivate VM Sub-Channel

POST /api/vm/deactivate
Content-Type: application/json

{
  "eui": "FCA84A0300001234"
}

Get VM Status

GET /api/vm/status

Returns status of all active VM sub-channels.

POST /api/vm/dlData
Content-Type: application/json

{
  "eui": "FCA84A0300001234",
  "payload": "48656C6C6F"
}

Traffic Monitoring

Get Traffic Metrics

GET /api/traffic/metrics

Returns real-time traffic statistics including:

Reset Traffic Metrics

POST /api/traffic/reset

Resets all traffic counters to zero.

System Status

Service Status

GET /api/bssci/status

Returns comprehensive system status including:

Base Station Status

GET /api/base_stations

Returns detailed information about connected and connecting base stations.

Configuration Management

Get Configuration

GET /config

Update Configuration

POST /api/config
Content-Type: application/json

{
  "MQTT_BROKER": "your-broker.com",
  "AUTO_DETACH_ENABLED": true,
  "AUTO_DETACH_TIMEOUT": 259200,
  "AUTO_DETACH_WARNING_TIMEOUT": 129600
}

Advanced Features

Message Deduplication

The system implements sophisticated message deduplication for multi-base station deployments:

How It Works

  1. Message Reception: Same sensor message received from multiple base stations
  2. Quality Comparison: SNR values compared between base stations
  3. Best Path Selection: Message with highest SNR is selected for publication
  4. Preferred Path Update: System learns optimal routing for each sensor
  5. Duplicate Filtering: Lower quality duplicates are discarded

Configuration

Statistics Available

The system automatically tracks the best communication path for each sensor:

Signal Quality Tracking

Path Selection Algorithm

  1. Message received with SNR measurement
  2. Compare with current preferred path SNR
  3. Update preferred path if new SNR is better
  4. Save configuration with updated preferred path
  5. Use preferred path for future downlink messages

Queue Management System

Asynchronous Queue Architecture

Queue Statistics

Security Features

SSL/TLS Security

User Authentication & Role-Based Access Control

The system implements a comprehensive authentication and authorization system:

Access Control

Troubleshooting

Common Issues

Base Station Connection Issues

Problem: Base stations cannot connect to TLS server

Solutions:

  1. Certificate Issues:
    # Check certificate validity
    openssl x509 -in certs/service_center_cert.pem -text -noout
       
    # Verify CA certificate
    openssl verify -CAfile certs/ca_cert.pem certs/service_center_cert.pem
    
  2. Network Connectivity:
    # Check if port is accessible
    telnet <service-center-ip> 16018
       
    # Verify firewall settings
    netstat -tlnp | grep 16018
    
  3. SSL Configuration:
    • Ensure base station has correct CA certificate
    • Verify base station client certificate is signed by same CA
    • Check certificate expiration dates

MQTT Connectivity Issues

Problem: MQTT broker connection failures

Solutions:

  1. Authentication Issues:
    • Verify MQTT_USERNAME and MQTT_PASSWORD in configuration
    • Check broker access control lists (ACLs)
    • Test credentials with mosquitto_pub/sub
  2. Network Issues:
    # Test MQTT connectivity
    mosquitto_pub -h <broker-host> -p <port> -u <username> -P <password> -t "test" -m "hello"
    
  3. Topic Permissions:
    • Ensure user has publish/subscribe permissions for all required topics
    • Check broker topic filter configurations

Sensor Registration Problems

Problem: Sensors not registering properly

Solutions:

  1. Configuration Validation:
    • Verify EUI format (16 hex characters)
    • Check network key format (32 hex characters)
    • Validate short address (4 hex characters)
    • Ensure sensor configuration is saved in endpoints.json
  2. Base Station Issues:
    • Verify base station is connected to service center
    • Check base station sensor capacity
    • Review base station logs for errors
  3. Protocol Issues:
    • Monitor TLS server logs for BSSCI protocol errors
    • Verify BSSCI protocol version compatibility
    • Check for network timeout issues

Auto-Detach Issues

Problem: Sensors being detached unexpectedly

Solutions:

  1. Timeout Configuration:
    • Review AUTO_DETACH_TIMEOUT setting (default 72 hours)
    • Check AUTO_DETACH_WARNING_TIMEOUT (default 36 hours)
    • Verify sensor communication frequency
  2. Activity Tracking:
    • Monitor sensor last-seen timestamps in web interface
    • Check for network issues preventing sensor communication
    • Verify sensor transmission schedules
  3. Disable Auto-Detach:
    # In bssci_config.py or via web interface
    AUTO_DETACH_ENABLED = False
    

Debugging Tools

Log Analysis

# View real-time logs
tail -f logs/bssci_service.log

# Filter by log level
grep "ERROR" logs/bssci_service.log

# Search for specific sensor
grep "FCA84A0300001234" logs/bssci_service.log

# Monitor auto-detach activity
grep "AUTO-DETACH" logs/bssci_service.log

MQTT Debugging

# Monitor all MQTT traffic
mosquitto_sub -h <broker> -u <user> -P <pass> -t "#" -v

# Test sensor commands
mosquitto_pub -h <broker> -u <user> -P <pass> -t "EP/FCA84A0300001234/cmd/" -m "status"

# Monitor specific sensor
mosquitto_sub -h <broker> -u <user> -P <pass> -t "mioty/ep/FCA84A0300001234/#" -v

Web Interface Debugging

Performance Monitoring

System Metrics

Queue Monitoring

# Monitor queue sizes via web interface
curl http://localhost:5000/api/bssci/status | jq '.queue_statistics'

Base Station Load

Data Flow Details

Sensor Data Flow

Sensor → Base Station → Service Center → MQTT → Your Application
  1. Sensor Transmission: Sensor sends data via mioty radio protocol
  2. Base Station Reception: Base station receives and processes sensor data
  3. TLS Forwarding: Base station forwards data to service center via secure TLS
  4. Deduplication: Service center processes and deduplicates messages
  5. MQTT Publication: Deduplicated data published to MQTT broker
  6. Application Consumption: Your application receives data from MQTT topics

Configuration Flow

Web UI/MQTT → Service Center → Base Station → Sensor
  1. Configuration Input: Via web interface or MQTT topic
  2. Validation: Service center validates configuration parameters
  3. Storage: Configuration saved to endpoints.json
  4. Propagation: Attach requests sent to connected base stations
  5. Registration: Base stations register sensors with provided configuration
  6. Confirmation: Registration status reported back to service center

Command Flow

MQTT/Web UI → Service Center → Base Station → Sensor
  1. Command Reception: Commands received via MQTT or web interface
  2. Processing: Service center processes and validates commands
  3. Execution: Appropriate BSSCI protocol messages sent to base stations
  4. Response: Base stations respond with execution status
  5. Notification: Status updates sent via MQTT and web interface

Deployment Options

Development Mode

python web_main.py

Production Mode

python main.py

Docker Deployment

Standard Deployment

docker-compose up -d --build

Docker Compose Configuration

version: '3.8'

services:
  bssci-service-center:
    build: .
    container_name: bssci-service-center
    user: "0:0"  # Run as root for write permissions
    init: true
    ports:
      - "16019:16018"  # TLS Server port
      - "5056:5000"    # Web UI port
    volumes:
      - ./certs:/app/certs:ro
      - ./endpoints.json:/app/endpoints.json:rw
      - ./bssci_config.py:/app/bssci_config.py:rw
      - ./.env:/app/.env:rw
      - ./base_stations.json:/app/data/base_stations.json:rw
      - ./logs:/app/logs
      - ./VERSION:/app/VERSION:rw  # Required for persistent updates
    restart: unless-stopped
    environment:
      - PYTHONUNBUFFERED=1
      - BASE_STATION_CONFIG_FILE=/app/data/base_stations.json

Live-Update Mode (Synology/Docker)

For installations where you want to update via the web UI without rebuilding the container:

docker-compose -f docker-compose.live-update.yml up -d --build

Important for Live-Updates:

Synology NAS Setup

# Set file permissions
chmod 666 /volume1/docker/bssci/endpoints.json
chmod 666 /volume1/docker/bssci/VERSION
chmod 666 /volume1/docker/bssci/.env

Monitoring and Alerting

Log Monitoring

Health Checks

Alerting Integration

Integration Examples

Python Application Integration

import paho.mqtt.client as mqtt
import json

def on_message(client, userdata, message):
    topic = message.topic
    payload = json.loads(message.payload.decode())
    
    if "/ul" in topic:
        # Handle sensor data
        sensor_eui = topic.split('/')[2]
        sensor_data = payload['data']
        print(f"Data from {sensor_eui}: {sensor_data}")
    
    elif "/warning" in topic:
        # Handle inactivity warnings
        sensor_eui = payload['sensor_eui'] 
        hours_inactive = payload['inactive_hours']
        print(f"Warning: Sensor {sensor_eui} inactive for {hours_inactive} hours")
    
    elif "/status" in topic and payload.get('action') == 'auto_detached':
        # Handle auto-detach notifications
        sensor_eui = payload['sensor_eui']
        print(f"Alert: Sensor {sensor_eui} was auto-detached due to inactivity")

client = mqtt.Client()
client.on_message = on_message
client.connect("broker-host", 1883, 60)
client.subscribe("mioty/ep/+/ul")        # Sensor data
client.subscribe("mioty/ep/+/warning")   # Inactivity warnings  
client.subscribe("mioty/ep/+/status")    # Status updates
client.loop_forever()

Remote Sensor Management

import paho.mqtt.publish as publish

def detach_sensor(sensor_eui):
    """Remotely detach a sensor"""
    topic = f"EP/{sensor_eui}/cmd/"
    payload = "detach"
    publish.single(topic, payload, hostname="broker-host")

def attach_sensor(sensor_eui):
    """Remotely attach a sensor"""
    topic = f"EP/{sensor_eui}/cmd/"
    payload = "attach" 
    publish.single(topic, payload, hostname="broker-host")

def get_sensor_status(sensor_eui):
    """Request sensor status"""
    topic = f"EP/{sensor_eui}/cmd/"
    payload = "status"
    publish.single(topic, payload, hostname="broker-host")

Best Practices

Configuration Management

Security

Performance Optimization

Operational Procedures

Documentation

The documentation is built with VitePress and supports Mermaid diagrams.

Build Documentation

# Install dependencies
npm install

# Development server (live reload)
npm run docs:dev

# Build static documentation
npm run docs:build

# Preview built documentation
npm run docs:preview

The built documentation is output to the dist/ directory.

License

This project is licensed under the terms specified in the LICENSE file.

Support

For technical support and questions:


BSSCI Service Center v1.660 - Professional IoT Device Management Platform