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
0 commit comments