mqtt-alerts 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,225 @@
1
+ Metadata-Version: 2.4
2
+ Name: mqtt-alerts
3
+ Version: 0.1.0
4
+ Summary: MQTT alert daemon with pluggable notification backends
5
+ Author-email: topo <tvallas@iki.fi>
6
+ Project-URL: Homepage, https://github.com/tvallas/mqtt-alerts
7
+ Project-URL: Repository, https://github.com/tvallas/mqtt-alerts
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: paho-mqtt<3,>=2
11
+ Requires-Dist: PyYAML<7,>=6
12
+
13
+ # mqtt-alerts
14
+
15
+ `mqtt-alerts` is a small daemon-style CLI that subscribes to MQTT topics, evaluates alert rules, and sends notifications through pluggable backends.
16
+
17
+ It exists separately from [`mtr2mqtt`](https://github.com/tvallas/mtr2mqtt) on purpose:
18
+
19
+ - `mtr2mqtt` publishes measurement data to MQTT.
20
+ - `mqtt-alerts` consumes MQTT data and turns sustained threshold violations into notifications.
21
+
22
+ That separation keeps the data publishing path simple while allowing alerting and notification behavior to evolve independently.
23
+
24
+ ## What It Does
25
+
26
+ - subscribes to configured MQTT topics
27
+ - parses JSON payloads and extracts a configured value field
28
+ - evaluates multiple independent rules per sensor
29
+ - tracks alert timing per rule with a hold duration such as `15m`
30
+ - persists minimal per-rule state in SQLite so restart recovery is correct
31
+ - sends notifications through pluggable backends
32
+ - sends automatic recovery notifications when triggered rules return to normal
33
+
34
+ ## What It Does Not Do
35
+
36
+ This MVP intentionally does not include:
37
+
38
+ - arbitrary expressions or a custom rule language
39
+ - multiple payload extraction syntaxes
40
+ - dashboards or a web UI
41
+ - acknowledgements, silencing windows, or schedules
42
+ - repeated reminders or escalation chains
43
+ - non-`ntfy` notification backends yet
44
+
45
+ The architecture is prepared for more backends later, but only `ntfy` is implemented in the first release.
46
+
47
+ ## Installation
48
+
49
+ ### Using pip
50
+
51
+ ```sh
52
+ pip install mqtt-alerts
53
+ ```
54
+
55
+ ### Using uv for development
56
+
57
+ ```sh
58
+ uv sync --group dev
59
+ ```
60
+
61
+ ## Basic Usage
62
+
63
+ Create a config file and run:
64
+
65
+ ```sh
66
+ mqtt-alerts --config sample_config.yml
67
+ ```
68
+
69
+ CLI flags:
70
+
71
+ - `--config`, `-c`: path to the YAML configuration file
72
+ - `--debug`, `-d`: enable debug logging
73
+ - `--quiet`, `-q`: only log warnings and errors
74
+ - `--version`, `-v`: print the installed version
75
+
76
+ Environment variables:
77
+
78
+ - `MQTT_ALERTS_CONFIG_FILE`
79
+ - `MQTT_ALERTS_DEBUG`
80
+ - `MQTT_ALERTS_QUIET`
81
+
82
+ ## Configuration
83
+
84
+ The configuration is YAML and keeps MQTT input, persisted state, sensors and rules, and notification backends separate.
85
+
86
+ ```yaml
87
+ mqtt:
88
+ host: localhost
89
+ port: 1883
90
+ topic_prefix: measurements
91
+
92
+ state:
93
+ database: ./mqtt-alerts.sqlite3
94
+
95
+ notifications:
96
+ backends:
97
+ - id: main_ntfy
98
+ type: ntfy
99
+ server: https://ntfy.sh
100
+ topic: some-secret-topic
101
+
102
+ sensors:
103
+ - id: freezer_1
104
+ name: Freezer 1
105
+ topic: receiver1/freezer1
106
+ value_field: temperature
107
+ rules:
108
+ - id: high_warn
109
+ direction: above
110
+ threshold: 5.0
111
+ hysteresis: 0.5
112
+ for: 15m
113
+ severity: low
114
+ backend: main_ntfy
115
+ enabled: true
116
+ title: Freezer 1 warning
117
+ message: Temperature is above limit
118
+ recovery_enabled: true
119
+ recovery_title: Freezer 1 recovered
120
+ recovery_message: Temperature is back within range
121
+
122
+ - id: high_critical
123
+ direction: above
124
+ threshold: 8.0
125
+ for: 10m
126
+ severity: critical
127
+ backend: main_ntfy
128
+ enabled: true
129
+ ```
130
+
131
+ Notes:
132
+
133
+ - `mqtt.topic_prefix` is optional. If set, sensor topics are resolved under that prefix unless already fully prefixed.
134
+ - each sensor can have many rules
135
+ - each rule has its own severity, backend, timing, and enabled flag
136
+ - each rule can define `hysteresis` to avoid alert/recovery flapping near the threshold
137
+ - each rule can customize automatic recovery messages (`recovery_enabled`, `recovery_title`, `recovery_message`)
138
+ - state is tracked per `(sensor_id, rule_id)` pair
139
+
140
+ ## Notification Backends
141
+
142
+ The core evaluator emits a generic notification object. Delivery is handled by a backend abstraction so new backends can be added later without redesigning rule evaluation or persistence.
143
+
144
+ The MVP ships with one backend:
145
+
146
+ - `ntfy`
147
+
148
+ The `ntfy` backend supports:
149
+
150
+ - server URL
151
+ - topic
152
+ - title
153
+ - message body
154
+ - severity mapping to `ntfy` priority and tags
155
+
156
+ ## How It Fits With `mtr2mqtt`
157
+
158
+ A typical setup looks like this:
159
+
160
+ 1. `mtr2mqtt` reads measurements from physical sensors and publishes JSON to MQTT topics.
161
+ 2. `mqtt-alerts` subscribes to selected measurement topics.
162
+ 3. `mqtt-alerts` extracts the configured value field and evaluates one or more rules per sensor.
163
+ 4. When a condition stays active for long enough, `mqtt-alerts` sends a notification through a configured backend.
164
+
165
+ ## Architecture
166
+
167
+ The code is intentionally split into small modules:
168
+
169
+ - `mqtt_alerts.config`: YAML loading and validation
170
+ - `mqtt_alerts.engine`: per-rule threshold and duration evaluation
171
+ - `mqtt_alerts.persistence`: SQLite state storage
172
+ - `mqtt_alerts.notifications`: backend abstraction and `ntfy` delivery
173
+ - `mqtt_alerts.runtime`: MQTT subscription loop and application wiring
174
+ - `mqtt_alerts.cli`: CLI entrypoint
175
+
176
+ The persisted state stores only the minimum required fields for restart recovery:
177
+
178
+ - latest value
179
+ - latest timestamp
180
+ - whether the condition is active
181
+ - when the condition became active
182
+ - whether the alert has already triggered
183
+ - when the alert triggered
184
+ - last notification timestamp
185
+
186
+ ## Docker
187
+
188
+ Pull the latest image:
189
+
190
+ ```sh
191
+ docker pull tvallas/mqtt-alerts:latest
192
+ ```
193
+
194
+ Run it with a mounted config:
195
+
196
+ ```sh
197
+ docker run --rm \
198
+ -v "$(pwd)/sample_config.yml:/config/config.yml:ro" \
199
+ -v "$(pwd)/state:/state" \
200
+ tvallas/mqtt-alerts:latest \
201
+ --config /config/config.yml
202
+ ```
203
+
204
+ There is also a sibling `docker-compose.yml` example in the repository.
205
+
206
+ ## Development
207
+
208
+ Common commands:
209
+
210
+ ```sh
211
+ make install
212
+ make lint
213
+ make test
214
+ make build
215
+ ```
216
+
217
+ ## Release Flow
218
+
219
+ The repository mirrors the current `mtr2mqtt` approach:
220
+
221
+ - pull request CI for lint, tests, and package build
222
+ - Docker build smoke test for pull requests
223
+ - semantic-release driven GitHub and PyPI release flow
224
+ - Docker publish after a successful tagged release
225
+ - Dependabot for Python, Docker, and GitHub Actions updates
@@ -0,0 +1,213 @@
1
+ # mqtt-alerts
2
+
3
+ `mqtt-alerts` is a small daemon-style CLI that subscribes to MQTT topics, evaluates alert rules, and sends notifications through pluggable backends.
4
+
5
+ It exists separately from [`mtr2mqtt`](https://github.com/tvallas/mtr2mqtt) on purpose:
6
+
7
+ - `mtr2mqtt` publishes measurement data to MQTT.
8
+ - `mqtt-alerts` consumes MQTT data and turns sustained threshold violations into notifications.
9
+
10
+ That separation keeps the data publishing path simple while allowing alerting and notification behavior to evolve independently.
11
+
12
+ ## What It Does
13
+
14
+ - subscribes to configured MQTT topics
15
+ - parses JSON payloads and extracts a configured value field
16
+ - evaluates multiple independent rules per sensor
17
+ - tracks alert timing per rule with a hold duration such as `15m`
18
+ - persists minimal per-rule state in SQLite so restart recovery is correct
19
+ - sends notifications through pluggable backends
20
+ - sends automatic recovery notifications when triggered rules return to normal
21
+
22
+ ## What It Does Not Do
23
+
24
+ This MVP intentionally does not include:
25
+
26
+ - arbitrary expressions or a custom rule language
27
+ - multiple payload extraction syntaxes
28
+ - dashboards or a web UI
29
+ - acknowledgements, silencing windows, or schedules
30
+ - repeated reminders or escalation chains
31
+ - non-`ntfy` notification backends yet
32
+
33
+ The architecture is prepared for more backends later, but only `ntfy` is implemented in the first release.
34
+
35
+ ## Installation
36
+
37
+ ### Using pip
38
+
39
+ ```sh
40
+ pip install mqtt-alerts
41
+ ```
42
+
43
+ ### Using uv for development
44
+
45
+ ```sh
46
+ uv sync --group dev
47
+ ```
48
+
49
+ ## Basic Usage
50
+
51
+ Create a config file and run:
52
+
53
+ ```sh
54
+ mqtt-alerts --config sample_config.yml
55
+ ```
56
+
57
+ CLI flags:
58
+
59
+ - `--config`, `-c`: path to the YAML configuration file
60
+ - `--debug`, `-d`: enable debug logging
61
+ - `--quiet`, `-q`: only log warnings and errors
62
+ - `--version`, `-v`: print the installed version
63
+
64
+ Environment variables:
65
+
66
+ - `MQTT_ALERTS_CONFIG_FILE`
67
+ - `MQTT_ALERTS_DEBUG`
68
+ - `MQTT_ALERTS_QUIET`
69
+
70
+ ## Configuration
71
+
72
+ The configuration is YAML and keeps MQTT input, persisted state, sensors and rules, and notification backends separate.
73
+
74
+ ```yaml
75
+ mqtt:
76
+ host: localhost
77
+ port: 1883
78
+ topic_prefix: measurements
79
+
80
+ state:
81
+ database: ./mqtt-alerts.sqlite3
82
+
83
+ notifications:
84
+ backends:
85
+ - id: main_ntfy
86
+ type: ntfy
87
+ server: https://ntfy.sh
88
+ topic: some-secret-topic
89
+
90
+ sensors:
91
+ - id: freezer_1
92
+ name: Freezer 1
93
+ topic: receiver1/freezer1
94
+ value_field: temperature
95
+ rules:
96
+ - id: high_warn
97
+ direction: above
98
+ threshold: 5.0
99
+ hysteresis: 0.5
100
+ for: 15m
101
+ severity: low
102
+ backend: main_ntfy
103
+ enabled: true
104
+ title: Freezer 1 warning
105
+ message: Temperature is above limit
106
+ recovery_enabled: true
107
+ recovery_title: Freezer 1 recovered
108
+ recovery_message: Temperature is back within range
109
+
110
+ - id: high_critical
111
+ direction: above
112
+ threshold: 8.0
113
+ for: 10m
114
+ severity: critical
115
+ backend: main_ntfy
116
+ enabled: true
117
+ ```
118
+
119
+ Notes:
120
+
121
+ - `mqtt.topic_prefix` is optional. If set, sensor topics are resolved under that prefix unless already fully prefixed.
122
+ - each sensor can have many rules
123
+ - each rule has its own severity, backend, timing, and enabled flag
124
+ - each rule can define `hysteresis` to avoid alert/recovery flapping near the threshold
125
+ - each rule can customize automatic recovery messages (`recovery_enabled`, `recovery_title`, `recovery_message`)
126
+ - state is tracked per `(sensor_id, rule_id)` pair
127
+
128
+ ## Notification Backends
129
+
130
+ The core evaluator emits a generic notification object. Delivery is handled by a backend abstraction so new backends can be added later without redesigning rule evaluation or persistence.
131
+
132
+ The MVP ships with one backend:
133
+
134
+ - `ntfy`
135
+
136
+ The `ntfy` backend supports:
137
+
138
+ - server URL
139
+ - topic
140
+ - title
141
+ - message body
142
+ - severity mapping to `ntfy` priority and tags
143
+
144
+ ## How It Fits With `mtr2mqtt`
145
+
146
+ A typical setup looks like this:
147
+
148
+ 1. `mtr2mqtt` reads measurements from physical sensors and publishes JSON to MQTT topics.
149
+ 2. `mqtt-alerts` subscribes to selected measurement topics.
150
+ 3. `mqtt-alerts` extracts the configured value field and evaluates one or more rules per sensor.
151
+ 4. When a condition stays active for long enough, `mqtt-alerts` sends a notification through a configured backend.
152
+
153
+ ## Architecture
154
+
155
+ The code is intentionally split into small modules:
156
+
157
+ - `mqtt_alerts.config`: YAML loading and validation
158
+ - `mqtt_alerts.engine`: per-rule threshold and duration evaluation
159
+ - `mqtt_alerts.persistence`: SQLite state storage
160
+ - `mqtt_alerts.notifications`: backend abstraction and `ntfy` delivery
161
+ - `mqtt_alerts.runtime`: MQTT subscription loop and application wiring
162
+ - `mqtt_alerts.cli`: CLI entrypoint
163
+
164
+ The persisted state stores only the minimum required fields for restart recovery:
165
+
166
+ - latest value
167
+ - latest timestamp
168
+ - whether the condition is active
169
+ - when the condition became active
170
+ - whether the alert has already triggered
171
+ - when the alert triggered
172
+ - last notification timestamp
173
+
174
+ ## Docker
175
+
176
+ Pull the latest image:
177
+
178
+ ```sh
179
+ docker pull tvallas/mqtt-alerts:latest
180
+ ```
181
+
182
+ Run it with a mounted config:
183
+
184
+ ```sh
185
+ docker run --rm \
186
+ -v "$(pwd)/sample_config.yml:/config/config.yml:ro" \
187
+ -v "$(pwd)/state:/state" \
188
+ tvallas/mqtt-alerts:latest \
189
+ --config /config/config.yml
190
+ ```
191
+
192
+ There is also a sibling `docker-compose.yml` example in the repository.
193
+
194
+ ## Development
195
+
196
+ Common commands:
197
+
198
+ ```sh
199
+ make install
200
+ make lint
201
+ make test
202
+ make build
203
+ ```
204
+
205
+ ## Release Flow
206
+
207
+ The repository mirrors the current `mtr2mqtt` approach:
208
+
209
+ - pull request CI for lint, tests, and package build
210
+ - Docker build smoke test for pull requests
211
+ - semantic-release driven GitHub and PyPI release flow
212
+ - Docker publish after a successful tagged release
213
+ - Dependabot for Python, Docker, and GitHub Actions updates
@@ -0,0 +1 @@
1
+ """mqtt-alerts package."""
@@ -0,0 +1,103 @@
1
+ """CLI entrypoint for mqtt-alerts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from argparse import ArgumentParser
6
+ from importlib.metadata import PackageNotFoundError, version
7
+ import logging
8
+ import os
9
+ import sys
10
+
11
+ from mqtt_alerts.config import ConfigError
12
+ from mqtt_alerts.runtime import ApplicationError, run_application
13
+
14
+
15
+ def create_parser() -> ArgumentParser:
16
+ """Build the command line parser."""
17
+ parser = ArgumentParser(
18
+ description=(
19
+ "Subscribe to MQTT topics, evaluate alert rules, and send notifications."
20
+ )
21
+ )
22
+ parser.add_argument(
23
+ "--config",
24
+ "-c",
25
+ default=os.environ.get("MQTT_ALERTS_CONFIG_FILE"),
26
+ help="Path to YAML config file (ENV: MQTT_ALERTS_CONFIG_FILE)",
27
+ )
28
+ group = parser.add_mutually_exclusive_group()
29
+ group.add_argument(
30
+ "--debug",
31
+ "-d",
32
+ default=_env_flag("MQTT_ALERTS_DEBUG", False),
33
+ action="store_true",
34
+ help="Enable debug logging (ENV: MQTT_ALERTS_DEBUG)",
35
+ )
36
+ group.add_argument(
37
+ "--quiet",
38
+ "-q",
39
+ default=_env_flag("MQTT_ALERTS_QUIET", False),
40
+ action="store_true",
41
+ help="Only log warnings and errors (ENV: MQTT_ALERTS_QUIET)",
42
+ )
43
+ group.add_argument(
44
+ "--version",
45
+ "-v",
46
+ default=False,
47
+ action="store_true",
48
+ help="Print the mqtt-alerts version and exit",
49
+ )
50
+ return parser
51
+
52
+
53
+ def main(argv: list[str] | None = None) -> int:
54
+ """Run the CLI and return a process exit code."""
55
+ parser = create_parser()
56
+ args = parser.parse_args(argv)
57
+
58
+ if args.version:
59
+ print(_project_version())
60
+ return 0
61
+
62
+ if not args.config:
63
+ parser.error("--config is required unless MQTT_ALERTS_CONFIG_FILE is set")
64
+
65
+ configure_logging(args.debug, args.quiet)
66
+
67
+ try:
68
+ run_application(args.config)
69
+ except (ApplicationError, ConfigError) as error:
70
+ logging.getLogger(__name__).error("%s", error)
71
+ return 1
72
+
73
+ return 0
74
+
75
+
76
+ def configure_logging(debug: bool, quiet: bool) -> None:
77
+ """Configure the root logger for the selected verbosity mode."""
78
+ if debug:
79
+ logging.basicConfig(
80
+ level=logging.DEBUG,
81
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
82
+ )
83
+ return
84
+ if quiet:
85
+ logging.basicConfig(level=logging.WARNING)
86
+ return
87
+
88
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s")
89
+ sys.tracebacklimit = 0
90
+
91
+
92
+ def _project_version() -> str:
93
+ try:
94
+ return version("mqtt-alerts")
95
+ except PackageNotFoundError:
96
+ return "0.0.0"
97
+
98
+
99
+ def _env_flag(name: str, default: bool) -> bool:
100
+ value = os.environ.get(name)
101
+ if value is None:
102
+ return default
103
+ return value.lower() in {"true", "1", "yes", "on"}