|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# |
| 4 | +# Custom Improv onboarding server for imx93-jaguar-eink board |
| 5 | +# Based on onboarding-server.py but with board-specific customizations |
| 6 | +# |
| 7 | + |
| 8 | +from improv import * |
| 9 | +from bless import ( # type: ignore |
| 10 | + BlessServer, |
| 11 | + BlessGATTCharacteristic, |
| 12 | + GATTCharacteristicProperties, |
| 13 | + GATTAttributePermissions |
| 14 | +) |
| 15 | +from bless.backends.bluezdbus.server import BlessServerBlueZDBus |
| 16 | +from typing import Any, Dict, Union, Optional |
| 17 | +import sys |
| 18 | +import threading |
| 19 | +import asyncio |
| 20 | +import logging |
| 21 | +import uuid |
| 22 | +import nmcli |
| 23 | +import os |
| 24 | +import re |
| 25 | + |
| 26 | +logging.basicConfig(level=logging.DEBUG) |
| 27 | +logger = logging.getLogger(name=__name__) |
| 28 | + |
| 29 | +# NOTE: Some systems require different synchronization methods. |
| 30 | +trigger: Union[asyncio.Event, threading.Event] |
| 31 | +if sys.platform in ["darwin", "win32"]: |
| 32 | + trigger = threading.Event() |
| 33 | +else: |
| 34 | + trigger = asyncio.Event() |
| 35 | + |
| 36 | +logging.basicConfig(level=logging.DEBUG) |
| 37 | +logger = logging.getLogger(name=__name__) |
| 38 | + |
| 39 | + |
| 40 | +def build_gatt(): |
| 41 | + gatt: Dict = { |
| 42 | + ImprovUUID.SERVICE_UUID.value: { |
| 43 | + ImprovUUID.STATUS_UUID.value: { |
| 44 | + "Properties": (GATTCharacteristicProperties.read | |
| 45 | + GATTCharacteristicProperties.notify), |
| 46 | + "Permissions": (GATTAttributePermissions.readable | |
| 47 | + GATTAttributePermissions.writeable) |
| 48 | + }, |
| 49 | + ImprovUUID.ERROR_UUID.value: { |
| 50 | + "Properties": (GATTCharacteristicProperties.read | |
| 51 | + GATTCharacteristicProperties.notify), |
| 52 | + "Permissions": (GATTAttributePermissions.readable | |
| 53 | + GATTAttributePermissions.writeable) |
| 54 | + }, |
| 55 | + ImprovUUID.RPC_COMMAND_UUID.value: { |
| 56 | + "Properties": (GATTCharacteristicProperties.read | |
| 57 | + GATTCharacteristicProperties.write | |
| 58 | + GATTCharacteristicProperties.write_without_response), |
| 59 | + "Permissions": (GATTAttributePermissions.readable | |
| 60 | + GATTAttributePermissions.writeable) |
| 61 | + }, |
| 62 | + ImprovUUID.RPC_RESULT_UUID.value: { |
| 63 | + "Properties": (GATTCharacteristicProperties.read | |
| 64 | + GATTCharacteristicProperties.notify), |
| 65 | + "Permissions": (GATTAttributePermissions.readable) |
| 66 | + }, |
| 67 | + ImprovUUID.CAPABILITIES_UUID.value: { |
| 68 | + "Properties": (GATTCharacteristicProperties.read), |
| 69 | + "Permissions": (GATTAttributePermissions.readable) |
| 70 | + }, |
| 71 | + } |
| 72 | + } |
| 73 | + return gatt |
| 74 | + |
| 75 | +""" |
| 76 | + Names longer than 10 characters will result in bless |
| 77 | + only advertising the name without the UUIDs on macOS, |
| 78 | + leading to a break with the Improv spec: |
| 79 | +
|
| 80 | + Bluetooth LE Advertisement |
| 81 | +The device MUST advertise the Service UUID. |
| 82 | +""" |
| 83 | + |
| 84 | +def get_board_id(): |
| 85 | + """Get unique board ID from SOC serial number. |
| 86 | + |
| 87 | + Reads the SOC serial number from /sys/devices/soc0/serial_number |
| 88 | + and extracts the last 4 characters to create a unique board identifier. |
| 89 | + |
| 90 | + Returns: |
| 91 | + str: Board ID in format "XXXX" (4 hex characters), or "0000" if unavailable |
| 92 | + """ |
| 93 | + try: |
| 94 | + # Read SOC serial number (32-character hex string) |
| 95 | + soc_serial_path = "/sys/devices/soc0/serial_number" |
| 96 | + if os.path.exists(soc_serial_path): |
| 97 | + with open(soc_serial_path, 'r') as f: |
| 98 | + serial = f.read().strip() |
| 99 | + # Extract last 4 characters (most unique portion) |
| 100 | + # Remove any non-hex characters and take last 4 |
| 101 | + serial_clean = re.sub(r'[^0-9a-fA-F]', '', serial) |
| 102 | + if len(serial_clean) >= 4: |
| 103 | + board_id = serial_clean[-4:].upper() # Last 4 chars, uppercase |
| 104 | + logger.info(f"Board ID from SOC serial: {board_id}") |
| 105 | + return board_id |
| 106 | + logger.warning("SOC serial number not found, using default board ID") |
| 107 | + except Exception as e: |
| 108 | + logger.error(f"Error reading board ID: {e}") |
| 109 | + |
| 110 | + # Fallback to default if unavailable |
| 111 | + return "0000" |
| 112 | + |
| 113 | +# Board-specific configuration for imx93-jaguar-eink |
| 114 | +# Can be overridden via environment variables |
| 115 | +SERVER_HOST = os.getenv("IMPROV_SERVER_HOST", "api.co.uk") |
| 116 | +# Generate unique service name from board ID: "eink-XXXX" where XXXX is last 4 chars of SOC serial |
| 117 | +BOARD_ID = get_board_id() |
| 118 | +DEFAULT_SERVICE_NAME = f"eink-{BOARD_ID}" |
| 119 | +SERVICE_NAME = os.getenv("IMPROV_SERVICE_NAME", DEFAULT_SERVICE_NAME) |
| 120 | +CON_NAME = os.getenv("IMPROV_CONNECTION_NAME", "improv-eink") |
| 121 | +INTERFACE = os.getenv("IMPROV_WIFI_INTERFACE", "wlan0") # imx93-jaguar-eink uses wlan0 |
| 122 | +TIMEOUT = int(os.getenv("IMPROV_CONNECTION_TIMEOUT", "10000")) |
| 123 | + |
| 124 | +loop = asyncio.get_event_loop() |
| 125 | +server = BlessServer(name=SERVICE_NAME, loop=loop) |
| 126 | + |
| 127 | +def wifi_connect(ssid: str, passwd: str) -> Optional[list[str]]: |
| 128 | + logger.warning( |
| 129 | + f"Creating Improv WiFi connection for '{ssid.decode('utf-8')}' with password: '{passwd.decode('utf-8')}'") |
| 130 | + |
| 131 | + try: |
| 132 | + nmcli.connection.delete(f"{CON_NAME}") |
| 133 | + except: |
| 134 | + print(f'No connection {CON_NAME} to remove') |
| 135 | + |
| 136 | + try: |
| 137 | + nmcli.connection.add('wifi', { 'ssid':ssid.decode('utf-8'), 'wifi-sec.key-mgmt':'wpa-psk', 'wifi-sec.psk':passwd.decode('utf-8') }, f"{INTERFACE}", f"{CON_NAME}", True) |
| 138 | + except: |
| 139 | + print(f'Could not add new connection {CON_NAME}') |
| 140 | + return None |
| 141 | + |
| 142 | + try: |
| 143 | + nmcli.connection.up(f"{CON_NAME}", TIMEOUT) |
| 144 | + except: |
| 145 | + print(f'Error bringing connection {CON_NAME} up') |
| 146 | + return None |
| 147 | + |
| 148 | + dev_details = nmcli.device.show(f"{INTERFACE}") |
| 149 | + if 'IP4.ADDRESS[1]' in dev_details.keys(): |
| 150 | + dev_addr = dev_details['IP4.ADDRESS[1]'] |
| 151 | + ip_addr = dev_addr.split('/')[0] |
| 152 | + else: |
| 153 | + print('Error connecting') |
| 154 | + return None |
| 155 | + |
| 156 | + token = uuid.uuid4() |
| 157 | + server = f"https://{SERVER_HOST}?ip_address={ip_addr}&token={token}" |
| 158 | + return [server] |
| 159 | + |
| 160 | +improv_server = ImprovProtocol(wifi_connect_callback=wifi_connect) |
| 161 | + |
| 162 | +def read_request( |
| 163 | + characteristic: BlessGATTCharacteristic, |
| 164 | + **kwargs |
| 165 | +) -> bytearray: |
| 166 | + try: |
| 167 | + improv_char = ImprovUUID(characteristic.uuid) |
| 168 | + logger.info(f"Reading {improv_char} : {characteristic}") |
| 169 | + except Exception: |
| 170 | + logger.info(f"Reading {characteristic.uuid}") |
| 171 | + pass |
| 172 | + if characteristic.service_uuid == ImprovUUID.SERVICE_UUID.value: |
| 173 | + return improv_server.handle_read(characteristic.uuid) |
| 174 | + return characteristic.value |
| 175 | + |
| 176 | + |
| 177 | +def write_request( |
| 178 | + characteristic: BlessGATTCharacteristic, |
| 179 | + value: bytearray, |
| 180 | + **kwargs |
| 181 | +): |
| 182 | + |
| 183 | + if characteristic.service_uuid == ImprovUUID.SERVICE_UUID.value: |
| 184 | + (target_uuid, target_values) = improv_server.handle_write( |
| 185 | + characteristic.uuid, value) |
| 186 | + if target_uuid != None and target_values != None: |
| 187 | + for value in target_values: |
| 188 | + logger.debug( |
| 189 | + f"Setting {ImprovUUID(target_uuid)} to {value}") |
| 190 | + server.get_characteristic( |
| 191 | + target_uuid, |
| 192 | + ).value = value |
| 193 | + success = server.update_value( |
| 194 | + ImprovUUID.SERVICE_UUID.value, |
| 195 | + target_uuid |
| 196 | + ) |
| 197 | + if not success: |
| 198 | + logger.warning( |
| 199 | + f"Updating characteristic return status={success}") |
| 200 | + |
| 201 | +async def run(loop): |
| 202 | + |
| 203 | + server.read_request_func = read_request |
| 204 | + server.write_request_func = write_request |
| 205 | + |
| 206 | + if isinstance(server, BlessServerBlueZDBus): |
| 207 | + await server.setup_task |
| 208 | + interface = server.adapter.get_interface('org.bluez.Adapter1') |
| 209 | + powered = await interface.get_powered() |
| 210 | + if not powered: |
| 211 | + logger.info("bluetooth device is not powered, powering now!") |
| 212 | + await interface.set_powered(True) |
| 213 | + |
| 214 | + await server.add_gatt(build_gatt()) |
| 215 | + await server.start() |
| 216 | + |
| 217 | + logger.info("Server started") |
| 218 | + |
| 219 | + try: |
| 220 | + trigger.clear() |
| 221 | + if trigger.__module__ == "threading": |
| 222 | + trigger.wait() |
| 223 | + else: |
| 224 | + await trigger.wait() |
| 225 | + except KeyboardInterrupt: |
| 226 | + logger.debug("Shutting Down") |
| 227 | + pass |
| 228 | + await server.stop() |
| 229 | + |
| 230 | +# Actually start the server |
| 231 | +try: |
| 232 | + loop.run_until_complete(run(loop)) |
| 233 | +except KeyboardInterrupt: |
| 234 | + logger.debug("Shutting Down") |
| 235 | + trigger.set() |
| 236 | + pass |
| 237 | + |
0 commit comments