jetstan-agent 0.1.11__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.
- jetstan_agent-0.1.11/LICENSE +21 -0
- jetstan_agent-0.1.11/MANIFEST.in +2 -0
- jetstan_agent-0.1.11/PKG-INFO +199 -0
- jetstan_agent-0.1.11/README.md +151 -0
- jetstan_agent-0.1.11/jetstan_agent/__init__.py +3 -0
- jetstan_agent-0.1.11/jetstan_agent/__main__.py +8 -0
- jetstan_agent-0.1.11/jetstan_agent/agent.py +40 -0
- jetstan_agent-0.1.11/jetstan_agent/cli.py +78 -0
- jetstan_agent-0.1.11/jetstan_agent/config.py +93 -0
- jetstan_agent-0.1.11/jetstan_agent/installer.py +311 -0
- jetstan_agent-0.1.11/jetstan_agent/logger.py +25 -0
- jetstan_agent-0.1.11/jetstan_agent/message_router.py +114 -0
- jetstan_agent-0.1.11/jetstan_agent/mqtt.py +141 -0
- jetstan_agent-0.1.11/jetstan_agent/sd_notify.py +37 -0
- jetstan_agent-0.1.11/jetstan_agent/service_cli.py +34 -0
- jetstan_agent-0.1.11/jetstan_agent/service_unit.py +45 -0
- jetstan_agent-0.1.11/jetstan_agent/system_checks.py +41 -0
- jetstan_agent-0.1.11/jetstan_agent/templates/__init__.py +1 -0
- jetstan_agent-0.1.11/jetstan_agent/templates/agent.env.example +5 -0
- jetstan_agent-0.1.11/jetstan_agent/templates/jetstan-agent.service.template +41 -0
- jetstan_agent-0.1.11/jetstan_agent/uninstaller.py +97 -0
- jetstan_agent-0.1.11/jetstan_agent/updater.py +106 -0
- jetstan_agent-0.1.11/jetstan_agent.egg-info/PKG-INFO +199 -0
- jetstan_agent-0.1.11/jetstan_agent.egg-info/SOURCES.txt +50 -0
- jetstan_agent-0.1.11/jetstan_agent.egg-info/dependency_links.txt +1 -0
- jetstan_agent-0.1.11/jetstan_agent.egg-info/entry_points.txt +4 -0
- jetstan_agent-0.1.11/jetstan_agent.egg-info/requires.txt +8 -0
- jetstan_agent-0.1.11/jetstan_agent.egg-info/top_level.txt +2 -0
- jetstan_agent-0.1.11/pyproject.toml +54 -0
- jetstan_agent-0.1.11/setup.cfg +4 -0
- jetstan_agent-0.1.11/software/__init__.py +6 -0
- jetstan_agent-0.1.11/software/frontend/__init__.py +1 -0
- jetstan_agent-0.1.11/software/frontend/index.html +388 -0
- jetstan_agent-0.1.11/software/gen_sample/__init__.py +3 -0
- jetstan_agent-0.1.11/software/gen_sample/simulator.py +92 -0
- jetstan_agent-0.1.11/software/handlers.py +28 -0
- jetstan_agent-0.1.11/software/logic/__init__.py +7 -0
- jetstan_agent-0.1.11/software/logic/calculations.py +157 -0
- jetstan_agent-0.1.11/software/test/__init__.py +3 -0
- jetstan_agent-0.1.11/software/test/server.py +81 -0
- jetstan_agent-0.1.11/tests/test_cli.py +67 -0
- jetstan_agent-0.1.11/tests/test_config.py +30 -0
- jetstan_agent-0.1.11/tests/test_gen_sample.py +44 -0
- jetstan_agent-0.1.11/tests/test_installer.py +158 -0
- jetstan_agent-0.1.11/tests/test_logic.py +154 -0
- jetstan_agent-0.1.11/tests/test_message_router.py +135 -0
- jetstan_agent-0.1.11/tests/test_mqtt.py +105 -0
- jetstan_agent-0.1.11/tests/test_service_cli.py +50 -0
- jetstan_agent-0.1.11/tests/test_service_unit.py +77 -0
- jetstan_agent-0.1.11/tests/test_system_checks.py +38 -0
- jetstan_agent-0.1.11/tests/test_uninstaller.py +76 -0
- jetstan_agent-0.1.11/tests/test_updater.py +97 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nihar Sharma
|
|
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,199 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jetstan-agent
|
|
3
|
+
Version: 0.1.11
|
|
4
|
+
Summary: Production-grade OTA agent for Linux-based vehicles — MQTT communication backbone.
|
|
5
|
+
Author: Nihar Sharma
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 Nihar Sharma
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Repository, https://github.com/PICODE-Labs/JETSTAN-PICODE
|
|
29
|
+
Keywords: ota,mqtt,embedded,automotive,raspberry-pi
|
|
30
|
+
Classifier: Development Status :: 3 - Alpha
|
|
31
|
+
Classifier: Intended Audience :: Developers
|
|
32
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
33
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
35
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
36
|
+
Classifier: Topic :: System :: Networking
|
|
37
|
+
Requires-Python: >=3.11
|
|
38
|
+
Description-Content-Type: text/markdown
|
|
39
|
+
License-File: LICENSE
|
|
40
|
+
Requires-Dist: paho-mqtt<3.0.0,>=2.1.0
|
|
41
|
+
Requires-Dist: python-dotenv<2.0.0,>=1.0.0
|
|
42
|
+
Requires-Dist: fastapi<1.0.0,>=0.110.0
|
|
43
|
+
Requires-Dist: uvicorn<1.0.0,>=0.29.0
|
|
44
|
+
Provides-Extra: dev
|
|
45
|
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
46
|
+
Requires-Dist: pytest-mock>=3.14.0; extra == "dev"
|
|
47
|
+
Dynamic: license-file
|
|
48
|
+
|
|
49
|
+
# Jetstan Agent
|
|
50
|
+
|
|
51
|
+
A production-grade OTA agent for Linux-based vehicles. It currently runs
|
|
52
|
+
on a Raspberry Pi, but the architecture is designed to move to
|
|
53
|
+
automotive Linux hardware without major changes.
|
|
54
|
+
|
|
55
|
+
It connects securely to HiveMQ Cloud, subscribes to the update topic,
|
|
56
|
+
routes incoming commands, and — for `ota.available` — upgrades itself
|
|
57
|
+
via `pip` and restarts. See **[INSTALL.md](INSTALL.md)** for running it
|
|
58
|
+
as a real systemd service (boot-start, crash/hang recovery, the OTA
|
|
59
|
+
update loop).
|
|
60
|
+
|
|
61
|
+
## Project layout
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
jetstan_agent/
|
|
65
|
+
__init__.py Package version.
|
|
66
|
+
__main__.py Enables `python -m jetstan_agent`.
|
|
67
|
+
cli.py argparse entrypoint (`jetstan-agent` console script).
|
|
68
|
+
config.py All tunable values and environment-variable loading.
|
|
69
|
+
mqtt.py TLS connection, subscribe, publish, auto-reconnect.
|
|
70
|
+
agent.py Wires MQTT to message routing; keeps the process alive.
|
|
71
|
+
message_router.py Parses JSON commands and dispatches by "type".
|
|
72
|
+
updater.py Self-upgrade via pip + restart-to-apply.
|
|
73
|
+
sd_notify.py Minimal systemd readiness/watchdog notifications.
|
|
74
|
+
logger.py Central logging configuration.
|
|
75
|
+
system_checks.py Read-only root/systemd/distro checks for the installer.
|
|
76
|
+
service_unit.py Renders the packaged systemd unit template.
|
|
77
|
+
service_cli.py systemctl/journalctl wrappers.
|
|
78
|
+
installer.py `jetstan-agent-install` entrypoint.
|
|
79
|
+
uninstaller.py `jetstan-agent-uninstall` entrypoint.
|
|
80
|
+
templates/ Packaged systemd unit + default agent.env.
|
|
81
|
+
tests/
|
|
82
|
+
(one test module per file above)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Why each file exists
|
|
86
|
+
|
|
87
|
+
- **`config.py`** — the single source of truth for connection settings.
|
|
88
|
+
Non-secret values (port, keepalive, topic) have defaults; the broker
|
|
89
|
+
host, username, and password have none and must come from environment
|
|
90
|
+
variables, so credentials never live in source control.
|
|
91
|
+
- **`mqtt.py`** — everything specific to talking to the broker (TLS
|
|
92
|
+
handshake, subscribe, reconnect, systemd readiness/watchdog signaling).
|
|
93
|
+
It knows nothing about OTA — it only hands raw `(topic, payload)` pairs
|
|
94
|
+
to a callback.
|
|
95
|
+
- **`message_router.py`** — parses each payload as JSON and dispatches by
|
|
96
|
+
`"type"`. Unknown types and invalid JSON are logged and swallowed, never
|
|
97
|
+
raised — a single bad message can't crash the agent.
|
|
98
|
+
- **`updater.py`** — the actual OTA logic: `pip install --upgrade
|
|
99
|
+
jetstan-agent==<version>`, then a deliberate process exit so systemd's
|
|
100
|
+
`Restart=always` relaunches into the newly installed code. No custom
|
|
101
|
+
download/signing pipeline — PyPI already does atomic package installs.
|
|
102
|
+
- **`agent.py`** — the composition root. It owns the MQTT client and
|
|
103
|
+
hands incoming payloads to `message_router`.
|
|
104
|
+
- **`logger.py`** — configures the root logger once, at startup.
|
|
105
|
+
- **`cli.py`** — `run` is the in-process foreground agent (what systemd's
|
|
106
|
+
`ExecStart=` invokes); `status`/`start`/`stop`/`restart`/`logs` are a
|
|
107
|
+
separate concern — they operate on the *systemd service* itself via
|
|
108
|
+
`service_cli.py`, so "start" never means two different things.
|
|
109
|
+
- **`installer.py` / `uninstaller.py` / `service_unit.py` /
|
|
110
|
+
`system_checks.py`** — turn `pip install jetstan-agent` into a managed,
|
|
111
|
+
hardened systemd service. See [INSTALL.md](INSTALL.md) for the full
|
|
112
|
+
flow and design rationale.
|
|
113
|
+
- **`__main__.py`** — enables `python -m jetstan_agent` (defaults to `run`).
|
|
114
|
+
|
|
115
|
+
## Configuration
|
|
116
|
+
|
|
117
|
+
All configuration is via environment variables (read by `config.py`).
|
|
118
|
+
|
|
119
|
+
| Variable | Required | Default |
|
|
120
|
+
|--------------------------------|----------|---------------------------|
|
|
121
|
+
| `MQTT_HOST` | Yes | — |
|
|
122
|
+
| `MQTT_USERNAME` | Yes | — |
|
|
123
|
+
| `MQTT_PASSWORD` | Yes | — |
|
|
124
|
+
| `MQTT_PORT` | No | `8883` |
|
|
125
|
+
| `MQTT_TOPIC` | No | `jetstan/demo/update` |
|
|
126
|
+
| `JETSTAN_MQTT_CLIENT_ID` | No | `jetstan-agent` |
|
|
127
|
+
| `JETSTAN_LOG_LEVEL` | No | `INFO` |
|
|
128
|
+
|
|
129
|
+
In production (systemd on the vehicle, CI, etc.) set these as real
|
|
130
|
+
environment variables — e.g. a systemd unit's `EnvironmentFile=` —
|
|
131
|
+
never hardcode them in a file that gets committed.
|
|
132
|
+
|
|
133
|
+
### Local development: `.env` file
|
|
134
|
+
|
|
135
|
+
For local development, `config.py` automatically loads a `.env` file
|
|
136
|
+
from the project root (via `python-dotenv`) before reading any
|
|
137
|
+
configuration — no manual `export` needed, and no code changes.
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
cp .env.example .env
|
|
141
|
+
# then edit .env and fill in MQTT_HOST / MQTT_USERNAME / MQTT_PASSWORD
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`.env` is git-ignored, so credentials never get committed. If a real
|
|
145
|
+
environment variable is already set, it takes precedence over `.env` —
|
|
146
|
+
so this has no effect on production deployments where `.env` won't
|
|
147
|
+
even exist.
|
|
148
|
+
|
|
149
|
+
## Install locally (editable)
|
|
150
|
+
|
|
151
|
+
```bash
|
|
152
|
+
python -m venv .venv
|
|
153
|
+
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
|
154
|
+
pip install -e ".[dev]"
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Run
|
|
158
|
+
|
|
159
|
+
Either export the variables directly:
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
export MQTT_HOST="xxxxxxxx.s1.eu.hivemq.cloud"
|
|
163
|
+
export MQTT_USERNAME="your-username"
|
|
164
|
+
export MQTT_PASSWORD="your-password"
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
or, for local development, create a `.env` file as shown above and skip
|
|
168
|
+
the `export` lines entirely. Then:
|
|
169
|
+
|
|
170
|
+
```bash
|
|
171
|
+
python -m jetstan_agent
|
|
172
|
+
# or, equivalently:
|
|
173
|
+
jetstan-agent run
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
On startup the agent connects over TLS, subscribes to
|
|
177
|
+
`jetstan/demo/update`, and logs every message it receives. If the
|
|
178
|
+
connection drops (or the broker is briefly unreachable), it reconnects
|
|
179
|
+
automatically with backoff — no restart needed.
|
|
180
|
+
|
|
181
|
+
## Test connectivity
|
|
182
|
+
|
|
183
|
+
1. Run the agent as shown above and leave it running.
|
|
184
|
+
2. From the [HiveMQ Cloud console](https://console.hivemq.cloud) (or
|
|
185
|
+
any MQTT client, e.g. `mosquitto_pub`), publish a message to
|
|
186
|
+
`jetstan/demo/update`:
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
mosquitto_pub -h <your-cluster-host> -p 8883 --cafile /etc/ssl/certs/ca-certificates.crt \
|
|
190
|
+
-u <username> -P <password> -t jetstan/demo/update -m '{"version": "1.0.1"}'
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
3. Confirm the agent's log output prints the received message.
|
|
194
|
+
|
|
195
|
+
## Run the test suite
|
|
196
|
+
|
|
197
|
+
```bash
|
|
198
|
+
pytest
|
|
199
|
+
```
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# Jetstan Agent
|
|
2
|
+
|
|
3
|
+
A production-grade OTA agent for Linux-based vehicles. It currently runs
|
|
4
|
+
on a Raspberry Pi, but the architecture is designed to move to
|
|
5
|
+
automotive Linux hardware without major changes.
|
|
6
|
+
|
|
7
|
+
It connects securely to HiveMQ Cloud, subscribes to the update topic,
|
|
8
|
+
routes incoming commands, and — for `ota.available` — upgrades itself
|
|
9
|
+
via `pip` and restarts. See **[INSTALL.md](INSTALL.md)** for running it
|
|
10
|
+
as a real systemd service (boot-start, crash/hang recovery, the OTA
|
|
11
|
+
update loop).
|
|
12
|
+
|
|
13
|
+
## Project layout
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
jetstan_agent/
|
|
17
|
+
__init__.py Package version.
|
|
18
|
+
__main__.py Enables `python -m jetstan_agent`.
|
|
19
|
+
cli.py argparse entrypoint (`jetstan-agent` console script).
|
|
20
|
+
config.py All tunable values and environment-variable loading.
|
|
21
|
+
mqtt.py TLS connection, subscribe, publish, auto-reconnect.
|
|
22
|
+
agent.py Wires MQTT to message routing; keeps the process alive.
|
|
23
|
+
message_router.py Parses JSON commands and dispatches by "type".
|
|
24
|
+
updater.py Self-upgrade via pip + restart-to-apply.
|
|
25
|
+
sd_notify.py Minimal systemd readiness/watchdog notifications.
|
|
26
|
+
logger.py Central logging configuration.
|
|
27
|
+
system_checks.py Read-only root/systemd/distro checks for the installer.
|
|
28
|
+
service_unit.py Renders the packaged systemd unit template.
|
|
29
|
+
service_cli.py systemctl/journalctl wrappers.
|
|
30
|
+
installer.py `jetstan-agent-install` entrypoint.
|
|
31
|
+
uninstaller.py `jetstan-agent-uninstall` entrypoint.
|
|
32
|
+
templates/ Packaged systemd unit + default agent.env.
|
|
33
|
+
tests/
|
|
34
|
+
(one test module per file above)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### Why each file exists
|
|
38
|
+
|
|
39
|
+
- **`config.py`** — the single source of truth for connection settings.
|
|
40
|
+
Non-secret values (port, keepalive, topic) have defaults; the broker
|
|
41
|
+
host, username, and password have none and must come from environment
|
|
42
|
+
variables, so credentials never live in source control.
|
|
43
|
+
- **`mqtt.py`** — everything specific to talking to the broker (TLS
|
|
44
|
+
handshake, subscribe, reconnect, systemd readiness/watchdog signaling).
|
|
45
|
+
It knows nothing about OTA — it only hands raw `(topic, payload)` pairs
|
|
46
|
+
to a callback.
|
|
47
|
+
- **`message_router.py`** — parses each payload as JSON and dispatches by
|
|
48
|
+
`"type"`. Unknown types and invalid JSON are logged and swallowed, never
|
|
49
|
+
raised — a single bad message can't crash the agent.
|
|
50
|
+
- **`updater.py`** — the actual OTA logic: `pip install --upgrade
|
|
51
|
+
jetstan-agent==<version>`, then a deliberate process exit so systemd's
|
|
52
|
+
`Restart=always` relaunches into the newly installed code. No custom
|
|
53
|
+
download/signing pipeline — PyPI already does atomic package installs.
|
|
54
|
+
- **`agent.py`** — the composition root. It owns the MQTT client and
|
|
55
|
+
hands incoming payloads to `message_router`.
|
|
56
|
+
- **`logger.py`** — configures the root logger once, at startup.
|
|
57
|
+
- **`cli.py`** — `run` is the in-process foreground agent (what systemd's
|
|
58
|
+
`ExecStart=` invokes); `status`/`start`/`stop`/`restart`/`logs` are a
|
|
59
|
+
separate concern — they operate on the *systemd service* itself via
|
|
60
|
+
`service_cli.py`, so "start" never means two different things.
|
|
61
|
+
- **`installer.py` / `uninstaller.py` / `service_unit.py` /
|
|
62
|
+
`system_checks.py`** — turn `pip install jetstan-agent` into a managed,
|
|
63
|
+
hardened systemd service. See [INSTALL.md](INSTALL.md) for the full
|
|
64
|
+
flow and design rationale.
|
|
65
|
+
- **`__main__.py`** — enables `python -m jetstan_agent` (defaults to `run`).
|
|
66
|
+
|
|
67
|
+
## Configuration
|
|
68
|
+
|
|
69
|
+
All configuration is via environment variables (read by `config.py`).
|
|
70
|
+
|
|
71
|
+
| Variable | Required | Default |
|
|
72
|
+
|--------------------------------|----------|---------------------------|
|
|
73
|
+
| `MQTT_HOST` | Yes | — |
|
|
74
|
+
| `MQTT_USERNAME` | Yes | — |
|
|
75
|
+
| `MQTT_PASSWORD` | Yes | — |
|
|
76
|
+
| `MQTT_PORT` | No | `8883` |
|
|
77
|
+
| `MQTT_TOPIC` | No | `jetstan/demo/update` |
|
|
78
|
+
| `JETSTAN_MQTT_CLIENT_ID` | No | `jetstan-agent` |
|
|
79
|
+
| `JETSTAN_LOG_LEVEL` | No | `INFO` |
|
|
80
|
+
|
|
81
|
+
In production (systemd on the vehicle, CI, etc.) set these as real
|
|
82
|
+
environment variables — e.g. a systemd unit's `EnvironmentFile=` —
|
|
83
|
+
never hardcode them in a file that gets committed.
|
|
84
|
+
|
|
85
|
+
### Local development: `.env` file
|
|
86
|
+
|
|
87
|
+
For local development, `config.py` automatically loads a `.env` file
|
|
88
|
+
from the project root (via `python-dotenv`) before reading any
|
|
89
|
+
configuration — no manual `export` needed, and no code changes.
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
cp .env.example .env
|
|
93
|
+
# then edit .env and fill in MQTT_HOST / MQTT_USERNAME / MQTT_PASSWORD
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`.env` is git-ignored, so credentials never get committed. If a real
|
|
97
|
+
environment variable is already set, it takes precedence over `.env` —
|
|
98
|
+
so this has no effect on production deployments where `.env` won't
|
|
99
|
+
even exist.
|
|
100
|
+
|
|
101
|
+
## Install locally (editable)
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
python -m venv .venv
|
|
105
|
+
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
|
106
|
+
pip install -e ".[dev]"
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Run
|
|
110
|
+
|
|
111
|
+
Either export the variables directly:
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
export MQTT_HOST="xxxxxxxx.s1.eu.hivemq.cloud"
|
|
115
|
+
export MQTT_USERNAME="your-username"
|
|
116
|
+
export MQTT_PASSWORD="your-password"
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
or, for local development, create a `.env` file as shown above and skip
|
|
120
|
+
the `export` lines entirely. Then:
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
python -m jetstan_agent
|
|
124
|
+
# or, equivalently:
|
|
125
|
+
jetstan-agent run
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
On startup the agent connects over TLS, subscribes to
|
|
129
|
+
`jetstan/demo/update`, and logs every message it receives. If the
|
|
130
|
+
connection drops (or the broker is briefly unreachable), it reconnects
|
|
131
|
+
automatically with backoff — no restart needed.
|
|
132
|
+
|
|
133
|
+
## Test connectivity
|
|
134
|
+
|
|
135
|
+
1. Run the agent as shown above and leave it running.
|
|
136
|
+
2. From the [HiveMQ Cloud console](https://console.hivemq.cloud) (or
|
|
137
|
+
any MQTT client, e.g. `mosquitto_pub`), publish a message to
|
|
138
|
+
`jetstan/demo/update`:
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
mosquitto_pub -h <your-cluster-host> -p 8883 --cafile /etc/ssl/certs/ca-certificates.crt \
|
|
142
|
+
-u <username> -P <password> -t jetstan/demo/update -m '{"version": "1.0.1"}'
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
3. Confirm the agent's log output prints the received message.
|
|
146
|
+
|
|
147
|
+
## Run the test suite
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
pytest
|
|
151
|
+
```
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Agent lifecycle: wires MQTT to message routing and keeps the process alive.
|
|
2
|
+
|
|
3
|
+
This is the composition point. Incoming payloads are handed to
|
|
4
|
+
``message_router`` for command dispatch; future OTA logic (downloads,
|
|
5
|
+
installs) is added there, not here or in ``mqtt.py``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
|
|
12
|
+
from jetstan_agent.config import MQTTConfig
|
|
13
|
+
from jetstan_agent.message_router import route_message
|
|
14
|
+
from jetstan_agent.mqtt import MQTTClient
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class JetstanAgent:
|
|
20
|
+
"""Top-level OTA agent process."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, config: MQTTConfig) -> None:
|
|
23
|
+
self._config = config
|
|
24
|
+
self._mqtt_client = MQTTClient(config=config, on_message=self._handle_message)
|
|
25
|
+
|
|
26
|
+
def run(self) -> None:
|
|
27
|
+
"""Start the agent and block until interrupted."""
|
|
28
|
+
logger.info("Jetstan Agent starting.")
|
|
29
|
+
try:
|
|
30
|
+
self._mqtt_client.run_forever()
|
|
31
|
+
except KeyboardInterrupt:
|
|
32
|
+
logger.info("Shutdown requested.")
|
|
33
|
+
finally:
|
|
34
|
+
self._mqtt_client.disconnect()
|
|
35
|
+
logger.info("Jetstan Agent stopped.")
|
|
36
|
+
|
|
37
|
+
def _handle_message(self, topic: str, payload: bytes) -> None:
|
|
38
|
+
"""Handle an incoming MQTT message by routing it to a command handler."""
|
|
39
|
+
logger.debug("Message received on '%s'.", topic)
|
|
40
|
+
route_message(payload)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Command-line entrypoint for the ``jetstan-agent`` console script.
|
|
2
|
+
|
|
3
|
+
``run`` is the in-process foreground agent (what the systemd unit's
|
|
4
|
+
``ExecStart=`` invokes). ``status``/``start``/``stop``/``restart``/``logs``
|
|
5
|
+
are a separate concern: they operate on the *systemd service* from the
|
|
6
|
+
operator's side, delegating to ``service_cli``. Keeping these as distinct
|
|
7
|
+
subcommands avoids the ambiguity of "start" meaning two different things.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import logging
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
from jetstan_agent import service_cli
|
|
17
|
+
from jetstan_agent.agent import JetstanAgent
|
|
18
|
+
from jetstan_agent.config import ConfigError, MQTTConfig
|
|
19
|
+
from jetstan_agent.logger import configure_logging
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
25
|
+
"""Build the CLI argument parser."""
|
|
26
|
+
parser = argparse.ArgumentParser(
|
|
27
|
+
prog="jetstan-agent",
|
|
28
|
+
description="Jetstan OTA agent for Linux-based vehicles.",
|
|
29
|
+
)
|
|
30
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
31
|
+
subparsers.add_parser("run", help="Run the agent in the foreground (used by systemd).")
|
|
32
|
+
subparsers.add_parser("status", help="Show systemd service status.")
|
|
33
|
+
subparsers.add_parser("start", help="Start the systemd service.")
|
|
34
|
+
subparsers.add_parser("stop", help="Stop the systemd service.")
|
|
35
|
+
subparsers.add_parser("restart", help="Restart the systemd service.")
|
|
36
|
+
logs_parser = subparsers.add_parser("logs", help="Show/follow service logs via journalctl.")
|
|
37
|
+
logs_parser.add_argument("-n", "--lines", type=int, default=100)
|
|
38
|
+
logs_parser.add_argument(
|
|
39
|
+
"--no-follow", action="store_true", help="Print recent logs and exit."
|
|
40
|
+
)
|
|
41
|
+
parser.set_defaults(command="run")
|
|
42
|
+
return parser
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main(argv: list[str] | None = None) -> int:
|
|
46
|
+
"""CLI entrypoint. Returns a process exit code."""
|
|
47
|
+
args = build_parser().parse_args(argv)
|
|
48
|
+
|
|
49
|
+
if args.command == "run":
|
|
50
|
+
configure_logging()
|
|
51
|
+
return _run()
|
|
52
|
+
if args.command == "status":
|
|
53
|
+
return service_cli.status()
|
|
54
|
+
if args.command == "start":
|
|
55
|
+
return service_cli.start()
|
|
56
|
+
if args.command == "stop":
|
|
57
|
+
return service_cli.stop()
|
|
58
|
+
if args.command == "restart":
|
|
59
|
+
return service_cli.restart()
|
|
60
|
+
if args.command == "logs":
|
|
61
|
+
return service_cli.logs(lines=args.lines, follow=not args.no_follow)
|
|
62
|
+
|
|
63
|
+
return 1
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _run() -> int:
|
|
67
|
+
try:
|
|
68
|
+
config = MQTTConfig.from_env()
|
|
69
|
+
except ConfigError as exc:
|
|
70
|
+
logger.error("Configuration error: %s", exc)
|
|
71
|
+
return 1
|
|
72
|
+
|
|
73
|
+
JetstanAgent(config=config).run()
|
|
74
|
+
return 0
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
if __name__ == "__main__":
|
|
78
|
+
sys.exit(main())
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Runtime configuration for the Jetstan Agent.
|
|
2
|
+
|
|
3
|
+
All tunable values live here so no other module contains a hardcoded
|
|
4
|
+
constant. Non-secret values (host, port, topic, keepalive) have sane
|
|
5
|
+
defaults for HiveMQ Cloud. Secrets (username, password) have no default
|
|
6
|
+
and must be supplied via environment variables — they must never be
|
|
7
|
+
committed to source control.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
from dotenv import load_dotenv
|
|
16
|
+
|
|
17
|
+
# Loads variables from a local .env file (if present) into the process
|
|
18
|
+
# environment for local development. Never overrides variables that are
|
|
19
|
+
# already set, so real deployments (systemd, CI) are unaffected. A no-op
|
|
20
|
+
# when no .env file exists, so this is always safe to call.
|
|
21
|
+
load_dotenv()
|
|
22
|
+
|
|
23
|
+
DEFAULT_PORT = 8883 # HiveMQ Cloud TLS port
|
|
24
|
+
DEFAULT_KEEPALIVE_SECONDS = 60
|
|
25
|
+
DEFAULT_TOPIC_UPDATE = "jetstan/demo/update"
|
|
26
|
+
DEFAULT_LOG_LEVEL = "INFO"
|
|
27
|
+
DEFAULT_CLIENT_ID = "jetstan-agent"
|
|
28
|
+
|
|
29
|
+
_ENV_HOST = "MQTT_HOST"
|
|
30
|
+
_ENV_PORT = "MQTT_PORT"
|
|
31
|
+
_ENV_USERNAME = "MQTT_USERNAME"
|
|
32
|
+
_ENV_PASSWORD = "MQTT_PASSWORD"
|
|
33
|
+
_ENV_CLIENT_ID = "JETSTAN_MQTT_CLIENT_ID"
|
|
34
|
+
_ENV_TOPIC_UPDATE = "MQTT_TOPIC"
|
|
35
|
+
_ENV_LOG_LEVEL = "JETSTAN_LOG_LEVEL"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ConfigError(RuntimeError):
|
|
39
|
+
"""Raised when required configuration is missing or invalid."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class MQTTConfig:
|
|
44
|
+
"""Connection settings for the HiveMQ Cloud MQTT broker."""
|
|
45
|
+
|
|
46
|
+
host: str
|
|
47
|
+
port: int
|
|
48
|
+
username: str
|
|
49
|
+
password: str
|
|
50
|
+
client_id: str
|
|
51
|
+
keepalive_seconds: int
|
|
52
|
+
topic_update: str
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def from_env(cls) -> "MQTTConfig":
|
|
56
|
+
"""Build configuration from environment variables.
|
|
57
|
+
|
|
58
|
+
Credentials are read from the environment (never hardcoded) so
|
|
59
|
+
the same code runs unmodified across a developer's Raspberry Pi,
|
|
60
|
+
CI, and future automotive targets — only the environment changes.
|
|
61
|
+
"""
|
|
62
|
+
host = os.environ.get(_ENV_HOST)
|
|
63
|
+
username = os.environ.get(_ENV_USERNAME)
|
|
64
|
+
password = os.environ.get(_ENV_PASSWORD)
|
|
65
|
+
|
|
66
|
+
missing = [
|
|
67
|
+
name
|
|
68
|
+
for name, value in (
|
|
69
|
+
(_ENV_HOST, host),
|
|
70
|
+
(_ENV_USERNAME, username),
|
|
71
|
+
(_ENV_PASSWORD, password),
|
|
72
|
+
)
|
|
73
|
+
if not value
|
|
74
|
+
]
|
|
75
|
+
if missing:
|
|
76
|
+
raise ConfigError(
|
|
77
|
+
f"Missing required environment variable(s): {', '.join(missing)}"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
return cls(
|
|
81
|
+
host=host,
|
|
82
|
+
port=int(os.environ.get(_ENV_PORT, DEFAULT_PORT)),
|
|
83
|
+
username=username,
|
|
84
|
+
password=password,
|
|
85
|
+
client_id=os.environ.get(_ENV_CLIENT_ID, DEFAULT_CLIENT_ID),
|
|
86
|
+
keepalive_seconds=DEFAULT_KEEPALIVE_SECONDS,
|
|
87
|
+
topic_update=os.environ.get(_ENV_TOPIC_UPDATE, DEFAULT_TOPIC_UPDATE),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def get_log_level() -> str:
|
|
92
|
+
"""Return the configured log level name (e.g. ``"INFO"``, ``"DEBUG"``)."""
|
|
93
|
+
return os.environ.get(_ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL).upper()
|