Add Wi-Fi auto-boot connection, MCP JSON-RPC Server, and host bridge
This commit is contained in:
+36
@@ -33,6 +33,7 @@ class BLEUART:
|
||||
self._connections = set()
|
||||
self._rx_callback = None
|
||||
self._name = name
|
||||
self._scan_results = {}
|
||||
|
||||
self._advertise()
|
||||
|
||||
@@ -63,6 +64,27 @@ class BLEUART:
|
||||
except Exception as e:
|
||||
# Fallback for binary / non-UTF-8 data
|
||||
self._rx_callback(data_received)
|
||||
|
||||
elif event == 5: # _IRQ_GAP_SCAN_RESULT
|
||||
addr_type, addr, adv_type, rssi, adv_data = data
|
||||
# Convert address to string hex format
|
||||
mac = ':'.join(f'{b:02x}' for b in addr)
|
||||
name = ""
|
||||
try:
|
||||
# Parse advertising payload to extract complete (0x09) or short (0x08) name
|
||||
i = 0
|
||||
while i < len(adv_data):
|
||||
length = adv_data[i]
|
||||
if length == 0 or i + length + 1 > len(adv_data):
|
||||
break
|
||||
ad_type = adv_data[i+1]
|
||||
if ad_type in (0x08, 0x09):
|
||||
name = adv_data[i+2 : i+1+length].decode('utf-8')
|
||||
break
|
||||
i += length + 1
|
||||
except:
|
||||
pass
|
||||
self._scan_results[mac] = {"rssi": rssi, "name": name}
|
||||
|
||||
def _advertise(self):
|
||||
# Generate advertising payload (flags + service UUID = 3 + 18 = 21 bytes)
|
||||
@@ -131,6 +153,20 @@ class BLEUART:
|
||||
"""Returns True if at least one central is connected."""
|
||||
return len(self._connections) > 0
|
||||
|
||||
def scan(self, duration_ms=3000):
|
||||
"""Scans for nearby BLE devices and returns a dictionary of results.
|
||||
|
||||
Returns:
|
||||
dict: { 'mac_address': { 'rssi': -70, 'name': 'DeviceName' } }
|
||||
"""
|
||||
self._scan_results = {}
|
||||
# Start passive scan (active=True requests scan responses to get names)
|
||||
# Scan parameters: duration, interval (20ms), window (10ms), active (True)
|
||||
self._ble.gap_scan(duration_ms, 20000, 10000, True)
|
||||
time.sleep_ms(duration_ms + 100)
|
||||
self._ble.gap_scan(None) # Ensure scan stops
|
||||
return self._scan_results
|
||||
|
||||
def close(self):
|
||||
"""Disconnect and stop BLE."""
|
||||
self._ble.gap_advertise(None) # Stop advertising
|
||||
|
||||
Reference in New Issue
Block a user