Skip to content

Commit 4ce68db

Browse files
committed
feature: Firmware download
1 parent 6cb2b0f commit 4ce68db

5 files changed

Lines changed: 496 additions & 2 deletions

File tree

‎pyproject.toml‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ name = "signalduino-mqtt"
77
version = "0.1.0"
88
description = "SignalDuino Protocols in Python with MQTT bridge"
99
authors = [{name="Sven"}]
10-
dependencies = []
10+
dependencies = [
11+
"requests",
12+
"pyserial"
13+
]
1114

1215
[tool.pytest.ini_options]
1316
testpaths = ["tests"]

‎requirements.txt‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
pytest
1+
pyserial
2+
requests

‎signalduino/firmware.py‎

Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
"""
2+
Firmware management for SIGNALduino.
3+
Handles checking for updates, downloading firmware, and flashing devices.
4+
"""
5+
import os
6+
import logging
7+
import subprocess
8+
import shutil
9+
import tempfile
10+
import requests
11+
import asyncio
12+
from typing import List, Dict, Optional, Tuple, Any
13+
from pathlib import Path
14+
15+
from .hardware import get_hardware_config, is_supported_for_flashing
16+
17+
_LOGGER = logging.getLogger(__name__)
18+
19+
GITHUB_RELEASES_URL = "https://api.github.com/repos/RFD-FHEM/SIGNALDuino/releases"
20+
21+
class FirmwareError(Exception):
22+
"""Base exception for firmware operations."""
23+
pass
24+
25+
class FirmwareDownloadError(FirmwareError):
26+
"""Error during firmware download."""
27+
pass
28+
29+
class FirmwareFlashError(FirmwareError):
30+
"""Error during firmware flashing."""
31+
pass
32+
33+
async def check_for_updates(hardware_type: str, channel: str = "stable") -> List[Dict[str, Any]]:
34+
"""
35+
Check for available firmware updates on GitHub.
36+
37+
Args:
38+
hardware_type: The hardware type to filter for (e.g. 'nanoCC1101').
39+
channel: Update channel ('stable' or 'testing'). 'testing' includes pre-releases.
40+
41+
Returns:
42+
List of available firmware assets matching the hardware type.
43+
"""
44+
try:
45+
response = requests.get(GITHUB_RELEASES_URL, timeout=10)
46+
response.raise_for_status()
47+
releases = response.json()
48+
except requests.RequestException as e:
49+
_LOGGER.error(f"Failed to fetch releases from GitHub: {e}")
50+
return []
51+
52+
available_firmware = []
53+
54+
for release in releases:
55+
# Filter by channel
56+
if channel == "stable" and release.get("prerelease", False):
57+
continue
58+
59+
tag_name = release.get("tag_name", "")
60+
61+
for asset in release.get("assets", []):
62+
name = asset.get("name", "")
63+
# Case-insensitive match for hardware type in filename
64+
if hardware_type.lower() in name.lower() and name.endswith(".hex"):
65+
available_firmware.append({
66+
"version": tag_name,
67+
"filename": name,
68+
"download_url": asset.get("browser_download_url"),
69+
"date": asset.get("created_at"),
70+
"prerelease": release.get("prerelease", False)
71+
})
72+
# Only take the first matching asset per release?
73+
# Perl implementation seems to take the first match per release.
74+
break
75+
76+
return available_firmware
77+
78+
async def download_firmware(url: str, target_path: Optional[str] = None) -> str:
79+
"""
80+
Download firmware from a URL.
81+
82+
Args:
83+
url: The URL to download from.
84+
target_path: Optional local path to save to. If None, a temporary file is created.
85+
86+
Returns:
87+
Path to the downloaded file.
88+
"""
89+
try:
90+
response = requests.get(url, stream=True, timeout=30)
91+
response.raise_for_status()
92+
93+
if target_path is None:
94+
# Create a temp file
95+
filename = url.split("/")[-1]
96+
if not filename.endswith(".hex"):
97+
filename += ".hex"
98+
99+
# Use a named temporary file that persists so we can return the path
100+
# The caller is responsible for cleanup if needed, but for firmware flashing usually we keep it or overwrite
101+
fd, path = tempfile.mkstemp(suffix=".hex", prefix="signalduino_fw_")
102+
os.close(fd)
103+
target_path = path
104+
105+
with open(target_path, 'wb') as f:
106+
for chunk in response.iter_content(chunk_size=8192):
107+
f.write(chunk)
108+
109+
_LOGGER.info(f"Downloaded firmware to {target_path}")
110+
return target_path
111+
112+
except requests.RequestException as e:
113+
raise FirmwareDownloadError(f"Failed to download firmware: {e}")
114+
except IOError as e:
115+
raise FirmwareDownloadError(f"Failed to save firmware file: {e}")
116+
117+
def prepare_flash_command(
118+
device_port: str,
119+
hex_file: str,
120+
hardware_type: str,
121+
custom_flash_cmd: Optional[str] = None
122+
) -> Tuple[str, dict]:
123+
"""
124+
Construct the avrdude command for flashing.
125+
126+
Args:
127+
device_port: Serial port (e.g. /dev/ttyUSB0).
128+
hex_file: Path to the .hex file.
129+
hardware_type: The hardware type identifier.
130+
custom_flash_cmd: Optional user-provided flash command template.
131+
132+
Returns:
133+
Tuple containing the command string (for logging) and execution context.
134+
"""
135+
config = get_hardware_config(hardware_type)
136+
if not config:
137+
raise FirmwareError(f"Unsupported hardware type for flashing: {hardware_type}")
138+
139+
if not shutil.which("avrdude"):
140+
raise FirmwareError("avrdude tool not found. Please install it (e.g., 'sudo apt-get install avrdude').")
141+
142+
cmd_template = custom_flash_cmd if custom_flash_cmd else config.flash_cmd_template
143+
144+
# We need a logfile for avrdude output capture if we want to parse it later,
145+
# but for now we might just want to capture stdout/stderr via subprocess.
146+
# The Perl module uses 2>[LOGFILE]. Here we will let subprocess handle capture.
147+
# We strip the redirection part if present in custom command for Python execution compatibility,
148+
# or better, we construct our own clean command list.
149+
150+
# For simplicity and robustness, we'll construct the command arguments list if using default,
151+
# or parse the string if custom.
152+
153+
# Let's simple replace placeholders in the string.
154+
# [BAUDRATE], [PORT], [HEXFILE], [LOGFILE], [PROGRAMMER], [PARTNO]
155+
156+
cmd_str = cmd_template.replace("[BAUDRATE]", str(config.baudrate))
157+
cmd_str = cmd_str.replace("[PORT]", device_port)
158+
cmd_str = cmd_str.replace("[HEXFILE]", hex_file)
159+
cmd_str = cmd_str.replace("[PROGRAMMER]", config.avrdude_programmer)
160+
cmd_str = cmd_str.replace("[PARTNO]", config.avrdude_partno)
161+
162+
# Handle LOGFILE placeholder by removing it or redirecting to a temp file?
163+
# Python subprocess captures output directly, so we might want to remove file redirection
164+
# if it exists in the template.
165+
# Simple regex to remove '2>[LOGFILE]' or similar might be needed if users copy-paste Perl attributes.
166+
# For now, let's assume we replace it with a temp file path if present, or ignore.
167+
log_file = os.path.join(tempfile.gettempdir(), "signalduino_flash.log")
168+
cmd_str = cmd_str.replace("[LOGFILE]", log_file)
169+
170+
return cmd_str, {"requires_1200bps_reset": config.requires_1200bps_reset}
171+
172+
async def flash_firmware(
173+
device_port: str,
174+
hex_file: str,
175+
hardware_type: str,
176+
custom_flash_cmd: Optional[str] = None
177+
) -> str:
178+
"""
179+
Flash the firmware to the device.
180+
181+
Args:
182+
device_port: Serial port.
183+
hex_file: Path to firmware file.
184+
hardware_type: Hardware identifier.
185+
custom_flash_cmd: Optional custom command template.
186+
187+
Returns:
188+
Output log from the flashing process.
189+
"""
190+
if not is_supported_for_flashing(hardware_type):
191+
raise FirmwareError(f"Flashing not supported for hardware: {hardware_type}")
192+
193+
cmd_str, context = prepare_flash_command(device_port, hex_file, hardware_type, custom_flash_cmd)
194+
195+
_LOGGER.info(f"Preparing to flash {hardware_type} on {device_port}")
196+
197+
# Handle 1200bps reset for Radino/Leonardo/ProMicro if needed
198+
if context.get("requires_1200bps_reset"):
199+
_LOGGER.info("Performing 1200bps reset trigger...")
200+
try:
201+
# Open port at 1200 baud and close it to trigger bootloader
202+
import serial
203+
with serial.Serial(device_port, 1200) as ser:
204+
pass
205+
# Wait for bootloader to activate
206+
await asyncio.sleep(2)
207+
208+
# Radino might change port name on Linux/Windows?
209+
# Perl code mentions port change logic: "$port =~ s/usb-Unknown_radino/usb-In-Circuit_radino/g;"
210+
# We will rely on persistent device paths (e.g. /dev/serial/by-id/...) for stability if possible.
211+
# If the user provided a raw /dev/ttyACM0 it might change index.
212+
# For now, we assume the port stays valid or the user uses by-id links.
213+
214+
except Exception as e:
215+
_LOGGER.warning(f"1200bps reset trigger failed: {e}")
216+
217+
_LOGGER.info(f"Executing flash command: {cmd_str}")
218+
219+
# Execute the command
220+
# Use shell=True because cmd_str is a full string potentially with redirections (though we tried to handle logfile)
221+
# Ideally we should split into args for security, but custom commands make that hard.
222+
223+
process = await asyncio.create_subprocess_shell(
224+
cmd_str,
225+
stdout=asyncio.subprocess.PIPE,
226+
stderr=asyncio.subprocess.PIPE
227+
)
228+
229+
stdout, stderr = await process.communicate()
230+
231+
output = ""
232+
if stdout:
233+
output += stdout.decode('utf-8', errors='replace')
234+
if stderr:
235+
output += stderr.decode('utf-8', errors='replace')
236+
237+
# Also read from logfile if it was used in command
238+
if "[LOGFILE]" in (custom_flash_cmd or "") or "2>" in cmd_str:
239+
# Check if we defined a logfile path in prepare_flash_command
240+
log_file = os.path.join(tempfile.gettempdir(), "signalduino_flash.log")
241+
if os.path.exists(log_file):
242+
with open(log_file, 'r') as f:
243+
output += "\n--- Logfile Content ---\n"
244+
output += f.read()
245+
246+
if process.returncode != 0:
247+
_LOGGER.error(f"Flashing failed with code {process.returncode}")
248+
_LOGGER.error(output)
249+
raise FirmwareFlashError(f"Flashing failed: {output}")
250+
251+
_LOGGER.info("Flashing successful")
252+
return output

‎signalduino/hardware.py‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
"""
2+
Hardware definitions for SIGNALduino.
3+
"""
4+
from enum import Enum
5+
from dataclasses import dataclass
6+
from typing import Dict, Optional
7+
8+
class HardwareType(str, Enum):
9+
"""Supported hardware types."""
10+
NANO_328 = "nano328"
11+
NANO_CC1101 = "nanoCC1101"
12+
MINI_CUL_CC1101 = "miniculCC1101"
13+
PRO_MINI_8_S = "promini8s"
14+
PRO_MINI_8_CC1101 = "promini8cc1101"
15+
PRO_MINI_16_S = "promini16s"
16+
PRO_MINI_16_CC1101 = "promini16cc1101"
17+
RADINO_CC1101 = "radinoCC1101"
18+
# ESP types are listed but flashing is not fully supported via module logic in Perl yet,
19+
# but we list them for completeness and future support.
20+
ESP32_S = "esp32s"
21+
ESP32_CC1101 = "esp32cc1101"
22+
ESP8266_S = "esp8266s"
23+
ESP8266_CC1101 = "esp8266cc1101"
24+
MAPLE_MINI_F103CB_S = "MAPLEMINI_F103CBs"
25+
MAPLE_MINI_F103CB_CC1101 = "MAPLEMINI_F103CBcc1101"
26+
27+
@dataclass
28+
class HardwareConfig:
29+
"""Configuration for a specific hardware type."""
30+
name: str
31+
avrdude_programmer: str
32+
avrdude_partno: str
33+
baudrate: int
34+
requires_1200bps_reset: bool = False
35+
36+
# Default flash command template
37+
# Placeholders: [BAUDRATE], [PORT], [HEXFILE], [LOGFILE]
38+
flash_cmd_template: str = "avrdude -c [PROGRAMMER] -b [BAUDRATE] -P [PORT] -p [PARTNO] -vv -U flash:w:[HEXFILE] 2>[LOGFILE]"
39+
40+
# Mapping of hardware types to their configuration
41+
HARDWARE_CONFIGS: Dict[str, HardwareConfig] = {
42+
HardwareType.NANO_328: HardwareConfig(
43+
name="Arduino Nano 328",
44+
avrdude_programmer="arduino",
45+
avrdude_partno="atmega328p",
46+
baudrate=57600
47+
),
48+
HardwareType.NANO_CC1101: HardwareConfig(
49+
name="Arduino Nano 328 with CC1101",
50+
avrdude_programmer="arduino",
51+
avrdude_partno="atmega328p",
52+
baudrate=57600
53+
),
54+
HardwareType.MINI_CUL_CC1101: HardwareConfig(
55+
name="Arduino Pro Mini with CC1101 (MiniCUL)",
56+
avrdude_programmer="arduino",
57+
avrdude_partno="atmega328p",
58+
baudrate=57600
59+
),
60+
HardwareType.PRO_MINI_8_S: HardwareConfig(
61+
name="Arduino Pro Mini 328 8Mhz",
62+
avrdude_programmer="arduino",
63+
avrdude_partno="atmega328p",
64+
baudrate=57600
65+
),
66+
HardwareType.PRO_MINI_8_CC1101: HardwareConfig(
67+
name="Arduino Pro Mini 328 8Mhz with CC1101",
68+
avrdude_programmer="arduino",
69+
avrdude_partno="atmega328p",
70+
baudrate=57600
71+
),
72+
HardwareType.PRO_MINI_16_S: HardwareConfig(
73+
name="Arduino Pro Mini 328 16Mhz",
74+
avrdude_programmer="arduino",
75+
avrdude_partno="atmega328p",
76+
baudrate=57600
77+
),
78+
HardwareType.PRO_MINI_16_CC1101: HardwareConfig(
79+
name="Arduino Pro Mini 328 16Mhz with CC1101",
80+
avrdude_programmer="arduino",
81+
avrdude_partno="atmega328p",
82+
baudrate=57600
83+
),
84+
HardwareType.RADINO_CC1101: HardwareConfig(
85+
name="Radino CC1101",
86+
avrdude_programmer="avr109",
87+
avrdude_partno="atmega32u4",
88+
baudrate=57600,
89+
requires_1200bps_reset=True,
90+
# Radino needs -D flag (disable auto erase) typically? Perl code says:
91+
# avrdude -c avr109 -b [BAUDRATE] -P [PORT] -p atmega32u4 -vv -D -U flash:w:[HEXFILE] 2>[LOGFILE]
92+
flash_cmd_template="avrdude -c [PROGRAMMER] -b [BAUDRATE] -P [PORT] -p [PARTNO] -vv -D -U flash:w:[HEXFILE] 2>[LOGFILE]"
93+
),
94+
}
95+
96+
def get_hardware_config(hardware_type: str) -> Optional[HardwareConfig]:
97+
"""Get configuration for a hardware type."""
98+
return HARDWARE_CONFIGS.get(hardware_type)
99+
100+
def is_supported_for_flashing(hardware_type: str) -> bool:
101+
"""Check if the hardware type is supported for flashing via this module."""
102+
# Currently only AVR based boards are supported for flashing via avrdude
103+
return hardware_type in HARDWARE_CONFIGS

0 commit comments

Comments
 (0)