air2mqtt 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Added
11
+
12
+ ### Changed
13
+
14
+ ### Deprecated
15
+
16
+ ### Removed
17
+
18
+ ### Fixed
19
+
20
+ ### Security
21
+
22
+ ### Dependencies
23
+
24
+ ## [v0.1.0](https://github.com/Neluxx/air2mqtt/releases/tag/v0.1.0) - 2026-11-17
25
+
26
+ ### Added
27
+ - Read CO₂ from an MH-Z19 via UART without root privileges
28
+ - Read temperature, humidity and pressure from a BME680 via I²C
29
+ - Publish all values to Home Assistant via device-based MQTT discovery
30
+ - Mark the device as unavailable via MQTT last will and expire stale values
31
+ - Reconnect to the MQTT broker automatically and drop measurements while it is unreachable
32
+ - Add `TEMPERATURE_OFFSET` to correct BME680 readings affected by heat from the Pi
33
+ - Configure everything via environment variables or a `.env` file
34
+ - Run as a systemd service
air2mqtt-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fabian Arndt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: air2mqtt
3
+ Version: 0.1.0
4
+ Summary: Reads BME680 and MH-Z19 sensors and publishes them to Home Assistant via MQTT.
5
+ Keywords: home-assistant,mqtt,raspberry-pi,bme680,mh-z19,co2,air-quality,sensor
6
+ Author: Fabian Arndt
7
+ Author-email: Fabian Arndt <fabian.arndt96@proton.me>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: No Input/Output (Daemon)
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Home Automation
21
+ Classifier: Topic :: System :: Hardware
22
+ Requires-Dist: bme680>=2.0
23
+ Requires-Dist: paho-mqtt>=2.1,<3
24
+ Requires-Dist: pyserial>=3.5
25
+ Requires-Dist: python-dotenv>=1.0
26
+ Requires-Python: >=3.11
27
+ Project-URL: Repository, https://github.com/Neluxx/air2mqtt
28
+ Project-URL: Issues, https://github.com/Neluxx/air2mqtt/issues
29
+ Project-URL: Changelog, https://github.com/Neluxx/air2mqtt/blob/main/CHANGELOG.md
30
+ Description-Content-Type: text/markdown
31
+
32
+ # air2mqtt
33
+
34
+ [![CI](https://github.com/Neluxx/air2mqtt/actions/workflows/ci.yml/badge.svg)](https://github.com/Neluxx/air2mqtt/actions/workflows/ci.yml)
35
+ [![PyPI](https://img.shields.io/pypi/v/air2mqtt)](https://pypi.org/project/air2mqtt/)
36
+ [![Python](https://img.shields.io/pypi/pyversions/air2mqtt)](https://pypi.org/project/air2mqtt/)
37
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/Neluxx/air2mqtt/blob/main/LICENSE)
38
+
39
+ **Indoor air quality for Home Assistant, from a Raspberry Pi.**
40
+
41
+ air2mqtt reads a **BME680** (temperature, humidity, pressure) and an **MH-Z19** (CO₂) sensor on a Raspberry Pi and publishes the values to **Home Assistant via MQTT**.
42
+
43
+ ```
44
+ BME680 ──I²C──┐
45
+ ├── Raspberry Pi (air2mqtt) ──MQTT──> Broker ──> Home Assistant
46
+ MH-Z19 ──UART─┘
47
+ ```
48
+
49
+ ## Features
50
+
51
+ - **No setup in Home Assistant:** the device and its entities appear automatically through MQTT discovery.
52
+ - **Runs unattended** as a systemd service and reconnects to the broker on its own.
53
+ - **Reliable availability:** the device shows as unavailable when the Pi goes offline, and values expire if a sensor stops reporting.
54
+ - **Fault tolerant:** if one sensor is missing or fails, the other keeps working.
55
+
56
+ ## Requirements
57
+
58
+ - Raspberry Pi (or another Linux board) with Python 3.11 or newer
59
+ - A BME680 and/or an MH-Z19 sensor, wired up with I²C/UART enabled
60
+ - Home Assistant 2024.11 or newer with an MQTT broker
61
+
62
+ See [Prerequisites](https://github.com/Neluxx/air2mqtt/blob/main/docs/PREREQUISITES.md) for wiring and broker setup.
63
+
64
+ ## Quick start
65
+
66
+ **1. Install** into a virtual environment:
67
+
68
+ ```bash
69
+ sudo mkdir /opt/air2mqtt && sudo chown $USER:$USER /opt/air2mqtt
70
+ cd /opt/air2mqtt
71
+ python3 -m venv .venv
72
+ .venv/bin/pip install air2mqtt
73
+ ```
74
+
75
+ **2. Configure.** Create `/opt/air2mqtt/.env` with your broker details:
76
+
77
+ ```ini
78
+ MQTT_HOST=homeassistant.local
79
+ MQTT_USERNAME=air2mqtt
80
+ MQTT_PASSWORD=change-me
81
+ ```
82
+
83
+ **3. Run:**
84
+
85
+ ```bash
86
+ .venv/bin/air2mqtt
87
+ ```
88
+
89
+ The device appears in Home Assistant under **Settings → Devices & services → MQTT**. To start air2mqtt automatically at boot, set it up as a [systemd service](https://github.com/Neluxx/air2mqtt/blob/main/docs/INSTALLATION.md#4-run-as-a-service).
90
+
91
+ ## Documentation
92
+
93
+ | Guide | Contents |
94
+ | --- | --- |
95
+ | [Prerequisites](https://github.com/Neluxx/air2mqtt/blob/main/docs/PREREQUISITES.md) | Sensors and wiring, enabling I²C/UART, Home Assistant and MQTT broker |
96
+ | [Installation](https://github.com/Neluxx/air2mqtt/blob/main/docs/INSTALLATION.md) | Installing, running as a service, updating and uninstalling |
97
+ | [Configuration](https://github.com/Neluxx/air2mqtt/blob/main/docs/CONFIGURATION.md) | All settings and their defaults |
98
+ | [Usage](https://github.com/Neluxx/air2mqtt/blob/main/docs/USAGE.md) | Operating the service, MQTT topics and troubleshooting |
99
+ | [Development](https://github.com/Neluxx/air2mqtt/blob/main/docs/DEVELOPMENT.md) | Setup, tests, conventions and releasing |
100
+ | [Changelog](https://github.com/Neluxx/air2mqtt/blob/main/CHANGELOG.md) | Changes in each release |
101
+
102
+ ## License
103
+
104
+ [MIT](https://github.com/Neluxx/air2mqtt/blob/main/LICENSE)
@@ -0,0 +1,73 @@
1
+ # air2mqtt
2
+
3
+ [![CI](https://github.com/Neluxx/air2mqtt/actions/workflows/ci.yml/badge.svg)](https://github.com/Neluxx/air2mqtt/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/air2mqtt)](https://pypi.org/project/air2mqtt/)
5
+ [![Python](https://img.shields.io/pypi/pyversions/air2mqtt)](https://pypi.org/project/air2mqtt/)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/Neluxx/air2mqtt/blob/main/LICENSE)
7
+
8
+ **Indoor air quality for Home Assistant, from a Raspberry Pi.**
9
+
10
+ air2mqtt reads a **BME680** (temperature, humidity, pressure) and an **MH-Z19** (CO₂) sensor on a Raspberry Pi and publishes the values to **Home Assistant via MQTT**.
11
+
12
+ ```
13
+ BME680 ──I²C──┐
14
+ ├── Raspberry Pi (air2mqtt) ──MQTT──> Broker ──> Home Assistant
15
+ MH-Z19 ──UART─┘
16
+ ```
17
+
18
+ ## Features
19
+
20
+ - **No setup in Home Assistant:** the device and its entities appear automatically through MQTT discovery.
21
+ - **Runs unattended** as a systemd service and reconnects to the broker on its own.
22
+ - **Reliable availability:** the device shows as unavailable when the Pi goes offline, and values expire if a sensor stops reporting.
23
+ - **Fault tolerant:** if one sensor is missing or fails, the other keeps working.
24
+
25
+ ## Requirements
26
+
27
+ - Raspberry Pi (or another Linux board) with Python 3.11 or newer
28
+ - A BME680 and/or an MH-Z19 sensor, wired up with I²C/UART enabled
29
+ - Home Assistant 2024.11 or newer with an MQTT broker
30
+
31
+ See [Prerequisites](https://github.com/Neluxx/air2mqtt/blob/main/docs/PREREQUISITES.md) for wiring and broker setup.
32
+
33
+ ## Quick start
34
+
35
+ **1. Install** into a virtual environment:
36
+
37
+ ```bash
38
+ sudo mkdir /opt/air2mqtt && sudo chown $USER:$USER /opt/air2mqtt
39
+ cd /opt/air2mqtt
40
+ python3 -m venv .venv
41
+ .venv/bin/pip install air2mqtt
42
+ ```
43
+
44
+ **2. Configure.** Create `/opt/air2mqtt/.env` with your broker details:
45
+
46
+ ```ini
47
+ MQTT_HOST=homeassistant.local
48
+ MQTT_USERNAME=air2mqtt
49
+ MQTT_PASSWORD=change-me
50
+ ```
51
+
52
+ **3. Run:**
53
+
54
+ ```bash
55
+ .venv/bin/air2mqtt
56
+ ```
57
+
58
+ The device appears in Home Assistant under **Settings → Devices & services → MQTT**. To start air2mqtt automatically at boot, set it up as a [systemd service](https://github.com/Neluxx/air2mqtt/blob/main/docs/INSTALLATION.md#4-run-as-a-service).
59
+
60
+ ## Documentation
61
+
62
+ | Guide | Contents |
63
+ | --- | --- |
64
+ | [Prerequisites](https://github.com/Neluxx/air2mqtt/blob/main/docs/PREREQUISITES.md) | Sensors and wiring, enabling I²C/UART, Home Assistant and MQTT broker |
65
+ | [Installation](https://github.com/Neluxx/air2mqtt/blob/main/docs/INSTALLATION.md) | Installing, running as a service, updating and uninstalling |
66
+ | [Configuration](https://github.com/Neluxx/air2mqtt/blob/main/docs/CONFIGURATION.md) | All settings and their defaults |
67
+ | [Usage](https://github.com/Neluxx/air2mqtt/blob/main/docs/USAGE.md) | Operating the service, MQTT topics and troubleshooting |
68
+ | [Development](https://github.com/Neluxx/air2mqtt/blob/main/docs/DEVELOPMENT.md) | Setup, tests, conventions and releasing |
69
+ | [Changelog](https://github.com/Neluxx/air2mqtt/blob/main/CHANGELOG.md) | Changes in each release |
70
+
71
+ ## License
72
+
73
+ [MIT](https://github.com/Neluxx/air2mqtt/blob/main/LICENSE)
@@ -0,0 +1,89 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.13.8,<0.14"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "air2mqtt"
7
+ version = "0.1.0"
8
+ description = "Reads BME680 and MH-Z19 sensors and publishes them to Home Assistant via MQTT."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ keywords = [
14
+ "home-assistant",
15
+ "mqtt",
16
+ "raspberry-pi",
17
+ "bme680",
18
+ "mh-z19",
19
+ "co2",
20
+ "air-quality",
21
+ "sensor",
22
+ ]
23
+ classifiers = [
24
+ "Development Status :: 4 - Beta",
25
+ "Environment :: No Input/Output (Daemon)",
26
+ "Intended Audience :: End Users/Desktop",
27
+ "Operating System :: POSIX :: Linux",
28
+ "Programming Language :: Python :: 3",
29
+ "Programming Language :: Python :: 3 :: Only",
30
+ "Programming Language :: Python :: 3.11",
31
+ "Programming Language :: Python :: 3.12",
32
+ "Programming Language :: Python :: 3.13",
33
+ "Programming Language :: Python :: 3.14",
34
+ "Topic :: Home Automation",
35
+ "Topic :: System :: Hardware",
36
+ ]
37
+ dependencies = [
38
+ "bme680>=2.0",
39
+ "paho-mqtt>=2.1,<3",
40
+ "pyserial>=3.5",
41
+ "python-dotenv>=1.0",
42
+ ]
43
+
44
+ [[project.authors]]
45
+ name = "Fabian Arndt"
46
+ email = "fabian.arndt96@proton.me"
47
+
48
+ [project.scripts]
49
+ air2mqtt = "air2mqtt.__main__:main"
50
+
51
+ [project.urls]
52
+ Repository = "https://github.com/Neluxx/air2mqtt"
53
+ Issues = "https://github.com/Neluxx/air2mqtt/issues"
54
+ Changelog = "https://github.com/Neluxx/air2mqtt/blob/main/CHANGELOG.md"
55
+
56
+ [dependency-groups]
57
+ dev = [
58
+ "pytest>=8",
59
+ "ruff>=0.6",
60
+ ]
61
+
62
+ [tool.uv.build-backend]
63
+ source-include = [
64
+ "tests/**",
65
+ "CHANGELOG.md",
66
+ ]
67
+
68
+ [tool.pytest.ini_options]
69
+ testpaths = ["tests"]
70
+ addopts = ["--import-mode=importlib"]
71
+
72
+ [tool.ruff]
73
+ line-length = 100
74
+ src = [
75
+ "src",
76
+ "tests",
77
+ ]
78
+
79
+ [tool.ruff.lint]
80
+ select = [
81
+ "E",
82
+ "F",
83
+ "W",
84
+ "I",
85
+ "B",
86
+ "UP",
87
+ "SIM",
88
+ "RUF",
89
+ ]
@@ -0,0 +1,74 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.13.8,<0.14"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "air2mqtt"
7
+ version = "0.1.0"
8
+ description = "Reads BME680 and MH-Z19 sensors and publishes them to Home Assistant via MQTT."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Fabian Arndt", email = "fabian.arndt96@proton.me" }]
13
+ requires-python = ">=3.11"
14
+ keywords = [
15
+ "home-assistant",
16
+ "mqtt",
17
+ "raspberry-pi",
18
+ "bme680",
19
+ "mh-z19",
20
+ "co2",
21
+ "air-quality",
22
+ "sensor",
23
+ ]
24
+ classifiers = [
25
+ "Development Status :: 4 - Beta",
26
+ "Environment :: No Input/Output (Daemon)",
27
+ "Intended Audience :: End Users/Desktop",
28
+ "Operating System :: POSIX :: Linux",
29
+ "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3 :: Only",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Programming Language :: Python :: 3.13",
34
+ "Programming Language :: Python :: 3.14",
35
+ "Topic :: Home Automation",
36
+ "Topic :: System :: Hardware",
37
+ ]
38
+ dependencies = [
39
+ "bme680>=2.0",
40
+ "paho-mqtt>=2.1,<3",
41
+ "pyserial>=3.5",
42
+ "python-dotenv>=1.0",
43
+ ]
44
+
45
+ [project.scripts]
46
+ air2mqtt = "air2mqtt.__main__:main"
47
+
48
+ [project.urls]
49
+ Repository = "https://github.com/Neluxx/air2mqtt"
50
+ Issues = "https://github.com/Neluxx/air2mqtt/issues"
51
+ Changelog = "https://github.com/Neluxx/air2mqtt/blob/main/CHANGELOG.md"
52
+
53
+ [dependency-groups]
54
+ dev = [
55
+ "pytest>=8",
56
+ "ruff>=0.6",
57
+ ]
58
+
59
+ [tool.uv.build-backend]
60
+ source-include = [
61
+ "tests/**",
62
+ "CHANGELOG.md",
63
+ ]
64
+
65
+ [tool.pytest.ini_options]
66
+ testpaths = ["tests"]
67
+ addopts = ["--import-mode=importlib"]
68
+
69
+ [tool.ruff]
70
+ line-length = 100
71
+ src = ["src", "tests"]
72
+
73
+ [tool.ruff.lint]
74
+ select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF"]
@@ -0,0 +1 @@
1
+ """air2mqtt - indoor air sensors for Home Assistant via MQTT."""
@@ -0,0 +1,60 @@
1
+ """Entry point: ``air2mqtt`` or ``python -m air2mqtt``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import signal
7
+ import sys
8
+ import threading
9
+ from importlib.metadata import version
10
+
11
+ from air2mqtt.app import Air2Mqtt
12
+ from air2mqtt.config import ConfigError, Settings
13
+ from air2mqtt.homeassistant import Topics
14
+ from air2mqtt.mqtt_client import MqttClient
15
+ from air2mqtt.sensors import create_sensors
16
+
17
+ log = logging.getLogger("air2mqtt")
18
+
19
+
20
+ def main() -> int:
21
+ try:
22
+ settings = Settings.from_env()
23
+ except ConfigError as exc:
24
+ print(f"Configuration error: {exc}", file=sys.stderr)
25
+ return 2
26
+
27
+ logging.basicConfig(
28
+ level=settings.log_level,
29
+ format="%(levelname)-8s %(name)s: %(message)s",
30
+ )
31
+ log.info("Starting air2mqtt %s as device '%s'.", version("air2mqtt"), settings.device_id)
32
+
33
+ sensors = create_sensors(settings)
34
+ if not sensors:
35
+ log.critical("No sensor could be initialised - exiting.")
36
+ return 1
37
+
38
+ topics = Topics(
39
+ base_topic=settings.base_topic,
40
+ discovery_prefix=settings.discovery_prefix,
41
+ device_id=settings.device_id,
42
+ )
43
+ mqtt = MqttClient(
44
+ settings.mqtt,
45
+ client_id=f"air2mqtt-{settings.device_id}",
46
+ availability_topic=topics.availability,
47
+ )
48
+ node = Air2Mqtt(settings, sensors, mqtt, topics)
49
+
50
+ stop_event = threading.Event()
51
+ for sig in (signal.SIGINT, signal.SIGTERM):
52
+ signal.signal(sig, lambda *_: stop_event.set())
53
+
54
+ node.run(stop_event)
55
+ log.info("Stopped.")
56
+ return 0
57
+
58
+
59
+ if __name__ == "__main__":
60
+ sys.exit(main())
@@ -0,0 +1,90 @@
1
+ """The main loop: read all sensors periodically and publish the values to MQTT."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import threading
8
+ import time
9
+ from collections.abc import Sequence
10
+
11
+ from air2mqtt.config import Settings
12
+ from air2mqtt.homeassistant import Topics, build_discovery_payload
13
+ from air2mqtt.mqtt_client import ONLINE, MqttClient
14
+ from air2mqtt.sensors import Sensor, SensorError
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+ # A value is marked unavailable in HA if no update arrives within this many intervals.
19
+ _EXPIRE_AFTER_INTERVALS = 3
20
+
21
+ # How long to wait for the broker at startup before taking the first measurement.
22
+ _STARTUP_CONNECT_TIMEOUT_SECONDS = 10
23
+
24
+
25
+ class Air2Mqtt:
26
+ def __init__(
27
+ self,
28
+ settings: Settings,
29
+ sensors: Sequence[Sensor],
30
+ mqtt: MqttClient,
31
+ topics: Topics,
32
+ ) -> None:
33
+ self._settings = settings
34
+ self._sensors = sensors
35
+ self._mqtt = mqtt
36
+ self._topics = topics
37
+
38
+ self._mqtt.add_connect_handler(self._publish_discovery)
39
+ self._mqtt.subscribe(topics.homeassistant_status, self._on_homeassistant_status)
40
+
41
+ def run(self, stop_event: threading.Event) -> None:
42
+ """Measure and publish until ``stop_event`` is set."""
43
+ self._mqtt.start()
44
+ if not self._mqtt.wait_until_connected(_STARTUP_CONNECT_TIMEOUT_SECONDS):
45
+ log.warning("MQTT broker not reachable yet, measuring anyway.")
46
+ try:
47
+ while not stop_event.is_set():
48
+ started = time.monotonic()
49
+ self._measure_and_publish()
50
+ elapsed = time.monotonic() - started
51
+ stop_event.wait(max(0.0, self._settings.read_interval - elapsed))
52
+ finally:
53
+ self._mqtt.stop()
54
+ for sensor in self._sensors:
55
+ sensor.close()
56
+
57
+ def _measure_and_publish(self) -> None:
58
+ for sensor in self._sensors:
59
+ try:
60
+ reading = sensor.read()
61
+ except SensorError as exc:
62
+ log.error("%s: %s", sensor.name, exc)
63
+ continue
64
+
65
+ results = [
66
+ self._mqtt.publish_state(self._topics.state(metric), metric.format(value))
67
+ for metric, value in reading.items()
68
+ ]
69
+ published = all(results)
70
+ values = ", ".join(f"{m.key}={m.format(v)} {m.unit}" for m, v in reading.items())
71
+
72
+ if published:
73
+ log.info("%s: %s", sensor.name, values)
74
+ else:
75
+ log.warning("%s: %s (not sent, MQTT broker unreachable)", sensor.name, values)
76
+
77
+ def _publish_discovery(self) -> None:
78
+ payload = build_discovery_payload(
79
+ topics=self._topics,
80
+ device_name=self._settings.device_name,
81
+ metrics=[metric for sensor in self._sensors for metric in sensor.metrics],
82
+ expire_after=self._settings.read_interval * _EXPIRE_AFTER_INTERVALS,
83
+ )
84
+ self._mqtt.publish(self._topics.discovery, json.dumps(payload), retain=True)
85
+ log.info("Published Home Assistant discovery to %s.", self._topics.discovery)
86
+
87
+ def _on_homeassistant_status(self, payload: str) -> None:
88
+ # Home Assistant announces "online" after a restart; re-announce ourselves.
89
+ if payload == ONLINE:
90
+ self._publish_discovery()
@@ -0,0 +1,125 @@
1
+ """Application settings, loaded from environment variables (and an optional ``.env`` file)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import socket
8
+ from dataclasses import dataclass
9
+
10
+ from dotenv import find_dotenv, load_dotenv
11
+
12
+ _LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR")
13
+ _TRUE_VALUES = {"1", "true", "yes", "on"}
14
+ _FALSE_VALUES = {"0", "false", "no", "off"}
15
+
16
+
17
+ class ConfigError(ValueError):
18
+ """Raised when a required setting is missing or a value is invalid."""
19
+
20
+
21
+ @dataclass(frozen=True, slots=True)
22
+ class MqttSettings:
23
+ host: str
24
+ port: int
25
+ username: str | None
26
+ password: str | None
27
+ use_tls: bool
28
+ keepalive: int
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class Settings:
33
+ mqtt: MqttSettings
34
+ base_topic: str
35
+ discovery_prefix: str
36
+ device_id: str
37
+ device_name: str
38
+ read_interval: int
39
+ temperature_offset: float
40
+ mhz19_port: str
41
+ log_level: str
42
+
43
+ @classmethod
44
+ def from_env(cls) -> Settings:
45
+ load_dotenv(find_dotenv(usecwd=True))
46
+
47
+ return cls(
48
+ mqtt=MqttSettings(
49
+ host=_require("MQTT_HOST"),
50
+ port=_int("MQTT_PORT", 1883),
51
+ username=os.getenv("MQTT_USERNAME") or None,
52
+ password=os.getenv("MQTT_PASSWORD") or None,
53
+ use_tls=_bool("MQTT_TLS", False),
54
+ keepalive=_int("MQTT_KEEPALIVE", 60),
55
+ ),
56
+ base_topic=os.getenv("MQTT_BASE_TOPIC", "air2mqtt").strip("/"),
57
+ discovery_prefix=os.getenv("HA_DISCOVERY_PREFIX", "homeassistant").strip("/"),
58
+ device_id=_slugify(os.getenv("DEVICE_ID") or socket.gethostname()),
59
+ device_name=os.getenv("DEVICE_NAME", "Air2MQTT"),
60
+ read_interval=_int("READ_INTERVAL", 60, minimum=5),
61
+ temperature_offset=_float("TEMPERATURE_OFFSET", 0.0, limit=10.0),
62
+ mhz19_port=os.getenv("MHZ19_PORT", "/dev/serial0"),
63
+ log_level=_choice("LOG_LEVEL", "INFO", _LOG_LEVELS),
64
+ )
65
+
66
+
67
+ def _require(name: str) -> str:
68
+ value = os.getenv(name, "").strip()
69
+ if not value:
70
+ raise ConfigError(f"Environment variable {name} is required.")
71
+ return value
72
+
73
+
74
+ def _int(name: str, default: int, *, minimum: int = 1) -> int:
75
+ raw = os.getenv(name)
76
+ if raw is None or raw.strip() == "":
77
+ return default
78
+ try:
79
+ value = int(raw)
80
+ except ValueError as exc:
81
+ raise ConfigError(f"{name} must be an integer, got {raw!r}.") from exc
82
+ if value < minimum:
83
+ raise ConfigError(f"{name} must be >= {minimum}, got {value}.")
84
+ return value
85
+
86
+
87
+ def _float(name: str, default: float, *, limit: float) -> float:
88
+ """Parse a float whose absolute value must not exceed ``limit``."""
89
+ raw = os.getenv(name)
90
+ if raw is None or raw.strip() == "":
91
+ return default
92
+ try:
93
+ value = float(raw)
94
+ except ValueError as exc:
95
+ raise ConfigError(f"{name} must be a number, got {raw!r}.") from exc
96
+ if not -limit <= value <= limit:
97
+ raise ConfigError(f"{name} must be between -{limit:g} and {limit:g}, got {value:g}.")
98
+ return value
99
+
100
+
101
+ def _bool(name: str, default: bool) -> bool:
102
+ raw = os.getenv(name)
103
+ if raw is None or raw.strip() == "":
104
+ return default
105
+ value = raw.strip().lower()
106
+ if value in _TRUE_VALUES:
107
+ return True
108
+ if value in _FALSE_VALUES:
109
+ return False
110
+ raise ConfigError(f"{name} must be true or false, got {raw!r}.")
111
+
112
+
113
+ def _choice(name: str, default: str, choices: tuple[str, ...]) -> str:
114
+ value = (os.getenv(name) or default).strip().upper()
115
+ if value not in choices:
116
+ raise ConfigError(f"{name} must be one of {', '.join(choices)}, got {value!r}.")
117
+ return value
118
+
119
+
120
+ def _slugify(value: str) -> str:
121
+ """Make a value safe for use in MQTT topics and Home Assistant unique IDs."""
122
+ slug = re.sub(r"[^a-z0-9_-]+", "_", value.strip().lower()).strip("_")
123
+ if not slug:
124
+ raise ConfigError(f"Cannot derive a valid device id from {value!r}.")
125
+ return slug
@@ -0,0 +1,86 @@
1
+ """Home Assistant MQTT discovery (device-based, HA 2024.11+)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass
7
+ from importlib.metadata import version
8
+ from typing import Any
9
+
10
+ from air2mqtt.metrics import Metric
11
+
12
+ REPOSITORY_URL = "https://github.com/Neluxx/air2mqtt"
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class Topics:
17
+ """All MQTT topics used by one node."""
18
+
19
+ base_topic: str
20
+ discovery_prefix: str
21
+ device_id: str
22
+
23
+ @property
24
+ def root(self) -> str:
25
+ return f"{self.base_topic}/{self.device_id}"
26
+
27
+ @property
28
+ def availability(self) -> str:
29
+ return f"{self.root}/availability"
30
+
31
+ @property
32
+ def discovery(self) -> str:
33
+ return f"{self.discovery_prefix}/device/{self.device_id}/config"
34
+
35
+ @property
36
+ def homeassistant_status(self) -> str:
37
+ return f"{self.discovery_prefix}/status"
38
+
39
+ def state(self, metric: Metric) -> str:
40
+ return f"{self.root}/{metric.key}"
41
+
42
+
43
+ def build_discovery_payload(
44
+ topics: Topics,
45
+ device_name: str,
46
+ metrics: Iterable[Metric],
47
+ expire_after: int,
48
+ ) -> dict[str, Any]:
49
+ """Describe the device and one sensor entity per metric for Home Assistant."""
50
+ return {
51
+ "device": {
52
+ "identifiers": [topics.device_id],
53
+ "name": device_name,
54
+ "model": "Air2MQTT",
55
+ "sw_version": version("air2mqtt"),
56
+ },
57
+ "origin": {
58
+ "name": "air2mqtt",
59
+ "sw_version": version("air2mqtt"),
60
+ "support_url": REPOSITORY_URL,
61
+ },
62
+ "availability_topic": topics.availability,
63
+ "qos": 1,
64
+ "components": {
65
+ _unique_id(topics, metric): _sensor_component(topics, metric, expire_after)
66
+ for metric in metrics
67
+ },
68
+ }
69
+
70
+
71
+ def _sensor_component(topics: Topics, metric: Metric, expire_after: int) -> dict[str, Any]:
72
+ return {
73
+ "platform": "sensor",
74
+ "unique_id": _unique_id(topics, metric),
75
+ "name": metric.name,
76
+ "device_class": metric.device_class,
77
+ "state_class": "measurement",
78
+ "unit_of_measurement": metric.unit,
79
+ "suggested_display_precision": metric.precision,
80
+ "state_topic": topics.state(metric),
81
+ "expire_after": expire_after,
82
+ }
83
+
84
+
85
+ def _unique_id(topics: Topics, metric: Metric) -> str:
86
+ return f"{topics.device_id}_{metric.key}"
@@ -0,0 +1,25 @@
1
+ """The physical quantities this node measures, described once and reused everywhere."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True, slots=True)
9
+ class Metric:
10
+ key: str
11
+ name: str
12
+ unit: str
13
+ device_class: str
14
+ precision: int
15
+
16
+ def format(self, value: float) -> str:
17
+ return f"{value:.{self.precision}f}"
18
+
19
+
20
+ TEMPERATURE = Metric("temperature", "Temperature", "°C", "temperature", precision=1)
21
+ HUMIDITY = Metric("humidity", "Humidity", "%", "humidity", precision=1)
22
+ PRESSURE = Metric("pressure", "Pressure", "hPa", "atmospheric_pressure", precision=1)
23
+ CARBON_DIOXIDE = Metric("carbon_dioxide", "CO₂", "ppm", "carbon_dioxide", precision=0)
24
+
25
+ Reading = dict[Metric, float]
@@ -0,0 +1,144 @@
1
+ """Thin wrapper around paho-mqtt with availability (LWT) and automatic reconnects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import threading
7
+ from collections.abc import Callable
8
+ from typing import Any
9
+
10
+ import paho.mqtt.client as mqtt
11
+ from paho.mqtt.enums import CallbackAPIVersion
12
+ from paho.mqtt.reasoncodes import ReasonCode
13
+
14
+ from air2mqtt.config import MqttSettings
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+ ONLINE = "online"
19
+ OFFLINE = "offline"
20
+
21
+ _QOS = 1
22
+ _RECONNECT_MIN_DELAY = 1
23
+ _RECONNECT_MAX_DELAY = 120
24
+ _SHUTDOWN_TIMEOUT_SECONDS = 5
25
+
26
+ MessageHandler = Callable[[str], None]
27
+ ConnectHandler = Callable[[], None]
28
+
29
+
30
+ class MqttClient:
31
+ def __init__(self, settings: MqttSettings, client_id: str, availability_topic: str) -> None:
32
+ self._settings = settings
33
+ self._availability_topic = availability_topic
34
+ self._connect_handlers: list[ConnectHandler] = []
35
+ self._subscriptions: dict[str, MessageHandler] = {}
36
+ self._connected = threading.Event()
37
+
38
+ self._client = mqtt.Client(
39
+ callback_api_version=CallbackAPIVersion.VERSION2,
40
+ client_id=client_id,
41
+ )
42
+ if settings.username:
43
+ self._client.username_pw_set(settings.username, settings.password)
44
+ if settings.use_tls:
45
+ self._client.tls_set()
46
+
47
+ # The broker publishes "offline" on our behalf if we disappear unexpectedly.
48
+ self._client.will_set(availability_topic, OFFLINE, qos=_QOS, retain=True)
49
+ self._client.reconnect_delay_set(_RECONNECT_MIN_DELAY, _RECONNECT_MAX_DELAY)
50
+
51
+ self._client.on_connect = self._handle_connect
52
+ self._client.on_disconnect = self._handle_disconnect
53
+
54
+ # -- Public API -----------------------------------------------------------
55
+
56
+ def add_connect_handler(self, handler: ConnectHandler) -> None:
57
+ """Run ``handler`` after every (re)connect, before the client announces itself online."""
58
+ self._connect_handlers.append(handler)
59
+
60
+ def subscribe(self, topic: str, handler: MessageHandler) -> None:
61
+ """Subscribe to ``topic``; the subscription is restored on every reconnect."""
62
+ self._subscriptions[topic] = handler
63
+ self._client.message_callback_add(topic, self._wrap(handler))
64
+
65
+ def publish(self, topic: str, payload: str, *, retain: bool = False) -> None:
66
+ """Publish reliably (QoS 1). Intended for config and availability messages."""
67
+ result = self._client.publish(topic, payload, qos=_QOS, retain=retain)
68
+ if result.rc not in (mqtt.MQTT_ERR_SUCCESS, mqtt.MQTT_ERR_NO_CONN):
69
+ log.warning("Publishing to %s failed: %s", topic, mqtt.error_string(result.rc))
70
+
71
+ def publish_state(self, topic: str, payload: str) -> bool:
72
+ """Publish a live measurement, or drop it if the broker is unreachable.
73
+
74
+ Measurements are deliberately not buffered: Home Assistant timestamps a
75
+ state on arrival, so values delivered late would show up at the wrong time.
76
+ Returns whether the value was handed to the broker connection.
77
+ """
78
+ if not self._client.is_connected():
79
+ return False
80
+ result = self._client.publish(topic, payload, qos=0, retain=False)
81
+ return result.rc == mqtt.MQTT_ERR_SUCCESS
82
+
83
+ def start(self) -> None:
84
+ log.info("Connecting to MQTT broker %s:%d …", self._settings.host, self._settings.port)
85
+ self._client.connect_async(
86
+ self._settings.host,
87
+ self._settings.port,
88
+ keepalive=self._settings.keepalive,
89
+ )
90
+ self._client.loop_start()
91
+
92
+ def wait_until_connected(self, timeout: float) -> bool:
93
+ """Block until the client is connected or ``timeout`` expires."""
94
+ return self._connected.wait(timeout)
95
+
96
+ def stop(self) -> None:
97
+ if self._client.is_connected():
98
+ info = self._client.publish(self._availability_topic, OFFLINE, qos=_QOS, retain=True)
99
+ info.wait_for_publish(timeout=_SHUTDOWN_TIMEOUT_SECONDS)
100
+ self._client.disconnect()
101
+ self._client.loop_stop()
102
+ log.info("Disconnected from MQTT broker.")
103
+
104
+ # -- Callbacks ------------------------------------------------------------
105
+
106
+ def _handle_connect(
107
+ self,
108
+ _client: mqtt.Client,
109
+ _userdata: Any,
110
+ _flags: mqtt.ConnectFlags,
111
+ reason_code: ReasonCode,
112
+ _properties: Any,
113
+ ) -> None:
114
+ if reason_code.is_failure:
115
+ log.error("MQTT connection refused: %s", reason_code)
116
+ return
117
+
118
+ log.info("Connected to MQTT broker.")
119
+ for topic in self._subscriptions:
120
+ self._client.subscribe(topic, qos=_QOS)
121
+
122
+ for handler in self._connect_handlers:
123
+ handler()
124
+ self.publish(self._availability_topic, ONLINE, retain=True)
125
+ self._connected.set()
126
+
127
+ def _handle_disconnect(
128
+ self,
129
+ _client: mqtt.Client,
130
+ _userdata: Any,
131
+ _flags: mqtt.DisconnectFlags,
132
+ reason_code: ReasonCode,
133
+ _properties: Any,
134
+ ) -> None:
135
+ self._connected.clear()
136
+ if reason_code.is_failure:
137
+ log.warning("Lost connection to MQTT broker (%s), reconnecting …", reason_code)
138
+
139
+ @staticmethod
140
+ def _wrap(handler: MessageHandler) -> Callable[[mqtt.Client, Any, mqtt.MQTTMessage], None]:
141
+ def on_message(_client: mqtt.Client, _userdata: Any, message: mqtt.MQTTMessage) -> None:
142
+ handler(message.payload.decode("utf-8", errors="replace"))
143
+
144
+ return on_message
@@ -0,0 +1,31 @@
1
+ """Sensor drivers and a factory that skips sensors which fail to initialise."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import Callable
7
+
8
+ from air2mqtt.config import Settings
9
+ from air2mqtt.sensors.base import Sensor, SensorError
10
+ from air2mqtt.sensors.bme680 import BME680Sensor
11
+ from air2mqtt.sensors.mhz19 import MHZ19Sensor
12
+
13
+ __all__ = ["Sensor", "SensorError", "create_sensors"]
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+
18
+ def create_sensors(settings: Settings) -> list[Sensor]:
19
+ """Initialise every known sensor; a missing sensor is logged, not fatal."""
20
+ factories: dict[str, Callable[[], Sensor]] = {
21
+ "BME680": lambda: BME680Sensor(settings.temperature_offset),
22
+ "MH-Z19": lambda: MHZ19Sensor(settings.mhz19_port),
23
+ }
24
+
25
+ sensors: list[Sensor] = []
26
+ for name, factory in factories.items():
27
+ try:
28
+ sensors.append(factory())
29
+ except SensorError as exc:
30
+ log.error("Skipping %s: %s", name, exc)
31
+ return sensors
@@ -0,0 +1,24 @@
1
+ """Common interface for all sensors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Protocol
6
+
7
+ from air2mqtt.metrics import Metric, Reading
8
+
9
+
10
+ class SensorError(RuntimeError):
11
+ """Raised whenever a sensor cannot be initialised or read."""
12
+
13
+
14
+ class Sensor(Protocol):
15
+ name: str
16
+ metrics: tuple[Metric, ...]
17
+
18
+ def read(self) -> Reading:
19
+ """Return the current values. Raises SensorError on failure."""
20
+ ...
21
+
22
+ def close(self) -> None:
23
+ """Release any hardware resources."""
24
+ ...
@@ -0,0 +1,77 @@
1
+ """Bosch BME680 - temperature, humidity and pressure via I²C (Pimoroni driver)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from types import ModuleType
8
+ from typing import Any
9
+
10
+ from air2mqtt.metrics import HUMIDITY, PRESSURE, TEMPERATURE, Reading
11
+ from air2mqtt.sensors.base import SensorError
12
+
13
+ log = logging.getLogger(__name__)
14
+
15
+ _READ_TIMEOUT_SECONDS = 5.0
16
+ _POLL_INTERVAL_SECONDS = 0.1
17
+
18
+
19
+ class BME680Sensor:
20
+ name = "BME680"
21
+ metrics = (TEMPERATURE, HUMIDITY, PRESSURE)
22
+
23
+ def __init__(self, temperature_offset: float = 0.0) -> None:
24
+ try:
25
+ import bme680
26
+ except ImportError as exc:
27
+ raise SensorError("The 'bme680' package is not installed.") from exc
28
+
29
+ self._sensor = self._connect(bme680)
30
+
31
+ # Oversampling and filter settings as recommended by Bosch.
32
+ self._sensor.set_humidity_oversample(bme680.OS_2X)
33
+ self._sensor.set_pressure_oversample(bme680.OS_4X)
34
+ self._sensor.set_temperature_oversample(bme680.OS_8X)
35
+ self._sensor.set_filter(bme680.FILTER_SIZE_3)
36
+
37
+ # The gas heater is not used and would skew the temperature reading.
38
+ self._sensor.set_gas_status(bme680.DISABLE_GAS_MEAS)
39
+
40
+ # Compensates self-heating (e.g. from the Pi below the sensor). The driver applies
41
+ # the offset before humidity compensation, so relative humidity stays consistent.
42
+ self._sensor.set_temp_offset(temperature_offset)
43
+
44
+ if temperature_offset:
45
+ log.info("BME680 initialised (temperature offset %+.2f °C).", temperature_offset)
46
+ else:
47
+ log.info("BME680 initialised.")
48
+
49
+ @staticmethod
50
+ def _connect(bme680: ModuleType) -> Any:
51
+ errors = []
52
+ for address in (bme680.I2C_ADDR_PRIMARY, bme680.I2C_ADDR_SECONDARY):
53
+ try:
54
+ return bme680.BME680(address)
55
+ except (OSError, RuntimeError) as exc:
56
+ errors.append(f"0x{address:02x}: {exc}")
57
+ raise SensorError(f"BME680 not found on I²C ({'; '.join(errors)}).")
58
+
59
+ def read(self) -> Reading:
60
+ deadline = time.monotonic() + _READ_TIMEOUT_SECONDS
61
+ try:
62
+ while not self._sensor.get_sensor_data():
63
+ if time.monotonic() >= deadline:
64
+ raise SensorError("BME680 returned no data in time.")
65
+ time.sleep(_POLL_INTERVAL_SECONDS)
66
+ except OSError as exc:
67
+ raise SensorError(f"BME680 read failed: {exc}") from exc
68
+
69
+ data = self._sensor.data
70
+ return {
71
+ TEMPERATURE: data.temperature,
72
+ HUMIDITY: data.humidity,
73
+ PRESSURE: data.pressure,
74
+ }
75
+
76
+ def close(self) -> None:
77
+ """The I²C bus is shared and needs no explicit cleanup."""
@@ -0,0 +1,70 @@
1
+ """Winsen MH-Z19 - CO₂ concentration via UART.
2
+
3
+ Speaks the sensor's serial protocol directly, so no root privileges or
4
+ service restarts are needed (unlike the ``mh-z19`` PyPI package).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+
11
+ import serial
12
+
13
+ from air2mqtt.metrics import CARBON_DIOXIDE, Reading
14
+ from air2mqtt.sensors.base import SensorError
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+ _BAUD_RATE = 9600
19
+ _TIMEOUT_SECONDS = 2.0
20
+ _FRAME_LENGTH = 9
21
+ _START_BYTE = 0xFF
22
+ _CMD_READ_CO2 = 0x86
23
+ _READ_CO2_REQUEST = bytes([_START_BYTE, 0x01, _CMD_READ_CO2, 0, 0, 0, 0, 0, 0x79])
24
+
25
+ _PLAUSIBLE_RANGE_PPM = range(300, 10_001)
26
+
27
+
28
+ def checksum(frame: bytes) -> int:
29
+ """Checksum as defined in the MH-Z19 datasheet: two's complement of bytes 1-7."""
30
+ return (0xFF - (sum(frame[1:8]) & 0xFF) + 1) & 0xFF
31
+
32
+
33
+ def parse_co2_response(frame: bytes) -> int:
34
+ """Extract the CO₂ value (ppm) from a response frame. Raises SensorError if invalid."""
35
+ if len(frame) != _FRAME_LENGTH:
36
+ raise SensorError(f"MH-Z19 sent {len(frame)} bytes, expected {_FRAME_LENGTH}.")
37
+ if frame[0] != _START_BYTE or frame[1] != _CMD_READ_CO2:
38
+ raise SensorError(f"MH-Z19 sent an unexpected frame: {frame.hex(' ')}.")
39
+ if frame[8] != checksum(frame):
40
+ raise SensorError("MH-Z19 response checksum mismatch.")
41
+ return (frame[2] << 8) | frame[3]
42
+
43
+
44
+ class MHZ19Sensor:
45
+ name = "MH-Z19"
46
+ metrics = (CARBON_DIOXIDE,)
47
+
48
+ def __init__(self, port: str) -> None:
49
+ try:
50
+ self._serial = serial.Serial(port, baudrate=_BAUD_RATE, timeout=_TIMEOUT_SECONDS)
51
+ except serial.SerialException as exc:
52
+ raise SensorError(f"Cannot open MH-Z19 serial port {port}: {exc}") from exc
53
+ log.info("MH-Z19 initialised on %s.", port)
54
+
55
+ def read(self) -> Reading:
56
+ try:
57
+ self._serial.reset_input_buffer()
58
+ self._serial.write(_READ_CO2_REQUEST)
59
+ frame = self._serial.read(_FRAME_LENGTH)
60
+ except serial.SerialException as exc:
61
+ raise SensorError(f"MH-Z19 read failed: {exc}") from exc
62
+
63
+ co2_ppm = parse_co2_response(frame)
64
+ if co2_ppm not in _PLAUSIBLE_RANGE_PPM:
65
+ log.warning("MH-Z19 reported an implausible value of %d ppm.", co2_ppm)
66
+
67
+ return {CARBON_DIOXIDE: co2_ppm}
68
+
69
+ def close(self) -> None:
70
+ self._serial.close()
@@ -0,0 +1,75 @@
1
+ import pytest
2
+
3
+ from air2mqtt.config import ConfigError, Settings
4
+
5
+ _VARIABLES = (
6
+ "MQTT_HOST",
7
+ "MQTT_PORT",
8
+ "MQTT_USERNAME",
9
+ "MQTT_PASSWORD",
10
+ "MQTT_TLS",
11
+ "MQTT_KEEPALIVE",
12
+ "MQTT_BASE_TOPIC",
13
+ "HA_DISCOVERY_PREFIX",
14
+ "DEVICE_ID",
15
+ "DEVICE_NAME",
16
+ "READ_INTERVAL",
17
+ "TEMPERATURE_OFFSET",
18
+ "MHZ19_PORT",
19
+ "LOG_LEVEL",
20
+ )
21
+
22
+
23
+ @pytest.fixture(autouse=True)
24
+ def clean_env(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
25
+ monkeypatch.chdir(tmp_path) # no stray .env file
26
+ for name in _VARIABLES:
27
+ monkeypatch.delenv(name, raising=False)
28
+ monkeypatch.setenv("MQTT_HOST", "broker.local")
29
+
30
+
31
+ def test_defaults() -> None:
32
+ settings = Settings.from_env()
33
+
34
+ assert settings.mqtt.host == "broker.local"
35
+ assert settings.mqtt.port == 1883
36
+ assert settings.mqtt.use_tls is False
37
+ assert settings.base_topic == "air2mqtt"
38
+ assert settings.discovery_prefix == "homeassistant"
39
+ assert settings.read_interval == 60
40
+ assert settings.temperature_offset == 0.0
41
+ assert settings.log_level == "INFO"
42
+
43
+
44
+ def test_device_id_is_slugified(monkeypatch: pytest.MonkeyPatch) -> None:
45
+ monkeypatch.setenv("DEVICE_ID", "Living Room #1")
46
+ assert Settings.from_env().device_id == "living_room_1"
47
+
48
+
49
+ def test_temperature_offset(monkeypatch: pytest.MonkeyPatch) -> None:
50
+ monkeypatch.setenv("TEMPERATURE_OFFSET", "-1.5")
51
+ assert Settings.from_env().temperature_offset == -1.5
52
+
53
+
54
+ def test_missing_host(monkeypatch: pytest.MonkeyPatch) -> None:
55
+ monkeypatch.delenv("MQTT_HOST")
56
+ with pytest.raises(ConfigError, match="MQTT_HOST"):
57
+ Settings.from_env()
58
+
59
+
60
+ @pytest.mark.parametrize(
61
+ ("name", "value"),
62
+ [
63
+ ("READ_INTERVAL", "abc"),
64
+ ("READ_INTERVAL", "2"),
65
+ ("MQTT_TLS", "ture"),
66
+ ("TEMPERATURE_OFFSET", "warm"),
67
+ ("TEMPERATURE_OFFSET", "-12"),
68
+ ("TEMPERATURE_OFFSET", "nan"),
69
+ ("LOG_LEVEL", "VERBOSE"),
70
+ ],
71
+ )
72
+ def test_invalid_values(monkeypatch: pytest.MonkeyPatch, name: str, value: str) -> None:
73
+ monkeypatch.setenv(name, value)
74
+ with pytest.raises(ConfigError, match=name):
75
+ Settings.from_env()
@@ -0,0 +1,33 @@
1
+ from air2mqtt.homeassistant import Topics, build_discovery_payload
2
+ from air2mqtt.metrics import CARBON_DIOXIDE, TEMPERATURE
3
+
4
+ TOPICS = Topics(base_topic="air2mqtt", discovery_prefix="homeassistant", device_id="livingroom")
5
+
6
+
7
+ def test_topics() -> None:
8
+ assert TOPICS.availability == "air2mqtt/livingroom/availability"
9
+ assert TOPICS.discovery == "homeassistant/device/livingroom/config"
10
+ assert TOPICS.homeassistant_status == "homeassistant/status"
11
+ assert TOPICS.state(TEMPERATURE) == "air2mqtt/livingroom/temperature"
12
+
13
+
14
+ def test_discovery_payload_contains_one_component_per_metric() -> None:
15
+ payload = build_discovery_payload(
16
+ TOPICS, "Living Room", [TEMPERATURE, CARBON_DIOXIDE], expire_after=180
17
+ )
18
+
19
+ assert payload["device"]["identifiers"] == ["livingroom"]
20
+ assert payload["availability_topic"] == TOPICS.availability
21
+ assert set(payload["components"]) == {"livingroom_temperature", "livingroom_carbon_dioxide"}
22
+
23
+ co2 = payload["components"]["livingroom_carbon_dioxide"]
24
+ assert co2["platform"] == "sensor"
25
+ assert co2["device_class"] == "carbon_dioxide"
26
+ assert co2["unit_of_measurement"] == "ppm"
27
+ assert co2["state_topic"] == "air2mqtt/livingroom/carbon_dioxide"
28
+ assert co2["expire_after"] == 180
29
+
30
+
31
+ def test_metric_formatting() -> None:
32
+ assert TEMPERATURE.format(21.456) == "21.5"
33
+ assert CARBON_DIOXIDE.format(812) == "812"
@@ -0,0 +1,37 @@
1
+ import pytest
2
+
3
+ from air2mqtt.sensors.base import SensorError
4
+ from air2mqtt.sensors.mhz19 import checksum, parse_co2_response
5
+
6
+
7
+ def _frame(co2_ppm: int) -> bytes:
8
+ body = bytes([0xFF, 0x86, co2_ppm >> 8, co2_ppm & 0xFF, 0x47, 0, 0, 0])
9
+ return body + bytes([checksum(body + b"\x00")])
10
+
11
+
12
+ def test_request_checksum_matches_datasheet() -> None:
13
+ assert checksum(bytes([0xFF, 0x01, 0x86, 0, 0, 0, 0, 0, 0])) == 0x79
14
+
15
+
16
+ def test_parse_valid_frame() -> None:
17
+ assert parse_co2_response(_frame(812)) == 812
18
+
19
+
20
+ def test_rejects_short_frame() -> None:
21
+ with pytest.raises(SensorError, match="bytes"):
22
+ parse_co2_response(b"\xff\x86\x03")
23
+
24
+
25
+ def test_rejects_bad_checksum() -> None:
26
+ frame = bytearray(_frame(812))
27
+ frame[8] ^= 0xFF
28
+ with pytest.raises(SensorError, match="checksum"):
29
+ parse_co2_response(bytes(frame))
30
+
31
+
32
+ def test_rejects_unexpected_command() -> None:
33
+ frame = bytearray(_frame(812))
34
+ frame[1] = 0x99
35
+ frame[8] = checksum(frame)
36
+ with pytest.raises(SensorError, match="unexpected"):
37
+ parse_co2_response(bytes(frame))