#!/usr/bin/env python3 """Small McQueen Bluetooth control example. Python 3.10+; live use needs bleak. No firmware/content writes. --scan is discovery only; actions require --address. --drive is capped at 30% throttle for 3 seconds and attempts stop in finally. Offline --self-test needs only the standard library. Hardware is not certified by these tests; inspect the car and keep a clear test area before live use. """ import argparse import asyncio import math import struct import sys SUFFIX = '-574f-4f20-5370-6865726f2121' API = '00010002' + SUFFIX ANTIDOS = '00020005' + SUFFIX ESC = {0x8D: b'\xab\x05', 0xD8: b'\xab\x50', 0xAB: b'\xab\x23'} UNESC = {5: 0x8D, 0x50: 0xD8, 0x23: 0xAB} def packet(device, command, sequence, payload=b'', flags=0x0A): if not 0 <= sequence < 255 or flags & 0x30 or len(payload) > 64: raise ValueError('Example encoder supports short untargeted requests only') body = bytes((flags, device, command, sequence)) + payload body += bytes((~sum(body) & 255,)) return b'\x8d' + b''.join(ESC.get(b, bytes((b,))) for b in body) + b'\xd8' def decode(body): if len(body) < 5 or sum(body) & 255 != 255: raise ValueError('Bad packet length or checksum') flags, index = body[0], 1 route = {} for mask, name in ((0x10, 'target'), (0x20, 'source')): if flags & mask: if index >= len(body) - 1: raise ValueError('Truncated route') route[name] = body[index] index += 1 if len(body) - index < 4: raise ValueError('Truncated command header') return dict(flags=flags, device=body[index], command=body[index + 1], sequence=body[index + 2], payload=bytes(body[index + 3:-1]), **route) class Parser: """Bounded stream parser; notification boundaries need not match packets.""" def __init__(self): self.body = None self.escaped = False def feed(self, data): for b in data: if b == 0x8D and not self.escaped: self.body, self.escaped = bytearray(), False continue if self.body is None: continue if self.escaped: if b not in UNESC: self.body, self.escaped = None, False continue self.body.append(UNESC[b]) self.escaped = False elif b == 0xAB: self.escaped = True elif b == 0xD8: body, self.body = self.body, None try: yield decode(body) except ValueError: pass else: self.body.append(b) if self.body is not None and len(self.body) > 1024: self.body, self.escaped = None, False def drive_payload(steering, speed): if not all(math.isfinite(v) for v in (steering, speed)): raise ValueError('Drive values must be finite') if not -1 <= steering <= 1 or not -0.3 <= speed <= 0.3: raise ValueError('Example limit: steering -1..1, throttle -0.3..0.3') return struct.pack('>ff', steering, speed) class Session: def __init__(self, client, characteristic): self.client, self.characteristic = client, characteristic self.with_response = 'write-without-response' not in characteristic.properties self.parser, self.sequence, self.pending = Parser(), 0, None self.drive_error = None def next_sequence(self): value = self.sequence self.sequence = (value + 1) % 255 return value def notify(self, _sender, data): for p in self.parser.feed(data): key = (p['device'], p['command'], p['sequence']) if p['flags'] & 1: if self.pending and key == self.pending[0]: future = self.pending[1] if not future.done(): future.set_result(p['payload']) if key[:2] == (0x16, 2) and p['payload'] and p['payload'][0]: self.drive_error = p['payload'][0] elif key[:2] == (0x17, 0x11): print('Animation-complete event (check physical output separately).') async def write(self, frame): if not self.client.is_connected: raise ConnectionError('Disconnected; commands cannot reach the car') # Every request exposed by this demo fits the legacy 20-byte GATT payload. if len(frame) > 20: raise ValueError('This demo has no bulk/fragmented-write transport') await asyncio.wait_for(self.client.write_gatt_char( self.characteristic, frame, response=self.with_response), timeout=3) async def request(self, device, command, payload=b'', timeout=4): if self.pending: raise RuntimeError('Only one ordinary request may be outstanding') seq = self.next_sequence() future = asyncio.get_running_loop().create_future() self.pending = ((device, command, seq), future) try: await self.write(packet(device, command, seq, payload)) raw = await asyncio.wait_for(asyncio.shield(future), timeout) if not raw or raw[0] != 0: status = f'{raw[0]:02X}' if raw else 'missing' raise RuntimeError(f'{device:02X}/{command:02X} rejected: status {status}') return raw[1:] finally: self.pending = None if not future.done(): future.cancel() async def drive(self, steering, speed): await self.write(packet(0x16, 2, self.next_sequence(), drive_payload(steering, speed), flags=0x08)) async def timed_drive(self, steering, speed, seconds): drive_payload(steering, speed) if not math.isfinite(seconds) or not 0 < seconds <= 3: raise ValueError('Drive duration must be greater than 0 and at most 3 seconds') state = await self.request(0x13, 4) if len(state) != 1 or state[0] not in (2, 3): raise RuntimeError('Drive requires confirmed unplugged, non-low battery state') await self.request(0x17, 0x0B, b'\x01') try: end = asyncio.get_running_loop().time() + seconds while asyncio.get_running_loop().time() < end: if self.drive_error is not None: raise RuntimeError(f'Drive rejected: status {self.drive_error:02X}') await self.drive(steering, speed) await asyncio.sleep(min(1 / 15, max(0, end - asyncio.get_running_loop().time()))) finally: try: await asyncio.wait_for(asyncio.shield(self.drive(0, 0)), timeout=2) print('Stop packet sent; verify the car stopped.') except Exception as error: print(f'STOP UNCONFIRMED: {error}. Use the car power button.', file=sys.stderr) raise RuntimeError('Stop delivery unconfirmed; check the car immediately') from error async def run(args): try: from bleak import BleakClient, BleakScanner except ImportError: raise RuntimeError('Live use requires bleak; see the guide installation steps') from None if args.scan or not args.address: if not args.scan and (args.stop or args.read_volume or any( getattr(args, name) is not None for name in ('headlights', 'taillights', 'volume', 'profile', 'audio', 'drive'))): raise ValueError('Select a device with --address before requesting an action') for device, adv in (await BleakScanner.discover(timeout=6, return_adv=True)).values(): name = adv.local_name or device.name or '' if name.startswith('LM-'): print(device.address, name) return device = await BleakScanner.find_device_by_address(args.address, timeout=10) if device is None: raise RuntimeError('Selected car not found; wake it and close other control apps') async with BleakClient(device) as client: api = client.services.get_characteristic(API) anti = client.services.get_characteristic(ANTIDOS) if api is None or anti is None: raise RuntimeError('Normal API/handshake unavailable; no DFU command will be sent') if not {'write', 'write-without-response'}.intersection(api.properties): raise RuntimeError('API characteristic is not writable') if not {'write', 'write-without-response'}.intersection(anti.properties): raise RuntimeError('Anti-DoS characteristic is not writable') session = Session(client, api) await client.write_gatt_char(anti, b'usetheforce...band', response='write' in anti.properties) await asyncio.sleep(0.1) await client.start_notify(api, session.notify) await session.request(0x13, 0x0D, timeout=8) # Original untargeted wake route. version = None for attempt in range(3): await asyncio.sleep(1) try: version = await session.request(0x11, 0, timeout=3) break except asyncio.TimeoutError: if attempt == 2: raise if version is None or len(version) < 6: raise RuntimeError('Missing/malformed A version; control not attempted') version = struct.unpack('>HHH', version[:6]) print('Firmware A:', '.'.join(map(str, version))) if version != (2, 173, 0): raise RuntimeError('Demo actions require reference standard A 2.173.0; no update attempted') if args.drive is not None: await session.timed_drive(args.steering, args.drive, args.seconds) elif args.stop: await session.drive(0, 0) print('Stop packet sent; not a physical stop confirmation.') elif args.headlights is not None: await session.request(0x1A, 0x13, bytes((args.headlights,))) elif args.taillights is not None: await session.request(0x1A, 0x14, bytes((args.taillights,))) elif args.volume is not None or args.read_volume: if args.volume is not None: await session.request(0x1A, 8, bytes((args.volume,))) value = await session.request(0x1A, 9) if len(value) != 1: raise RuntimeError('Malformed volume readback') print('Volume:', value[0], '/255') elif args.profile is not None or args.audio is not None: if args.profile is not None: await session.request(0x17, 5, struct.pack('>H', args.profile)) else: await session.request(0x1A, 7, struct.pack('>HB', args.audio, 0)) await asyncio.sleep(args.listen) print('Requested exchange finished; observe output separately.') def self_test(): assert packet(0x17, 5, 0x42, b'\x00\x69') == bytes.fromhex('8D0A17054200692ED8') assert packet(0x16, 2, 0, drive_payload(0, 0), 8) == bytes.fromhex('8D081602000000000000000000DFD8') assert drive_payload(0.5, -0.25) == bytes.fromhex('3F000000BE800000') frame = packet(0x1A, 8, 7, b'\x8d\xd8\xab') p, result = Parser(), [] for byte in frame: result.extend(p.feed(bytes((byte,)))) assert result[0]['payload'] == b'\x8d\xd8\xab' bad = bytearray(frame); bad[-2] ^= 1 assert list(Parser().feed(bad)) == [] print('Offline packet, float, split-notification and checksum fixtures passed.') def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--address', help='identifier from --scan; UUID on macOS') parser.add_argument('--self-test', action='store_true') action = parser.add_mutually_exclusive_group() action.add_argument('--scan', action='store_true') action.add_argument('--headlights', type=int, choices=range(256), metavar='0..255') action.add_argument('--taillights', type=int, choices=range(256), metavar='0..255') action.add_argument('--volume', type=int, choices=range(256), metavar='0..255') action.add_argument('--read-volume', action='store_true') action.add_argument('--profile', type=lambda s: int(s, 0)) action.add_argument('--audio', type=lambda s: int(s, 0), help='verified logical FILE start, not profile ID') action.add_argument('--drive', type=float, help='explicit throttle, -0.3..0.3') action.add_argument('--stop', action='store_true') parser.add_argument('--steering', type=float, default=0) parser.add_argument('--seconds', type=float, default=1) parser.add_argument('--listen', type=float, default=5) args = parser.parse_args() if args.self_test: self_test() return if not math.isfinite(args.listen) or not 0 <= args.listen <= 30: parser.error('--listen must be 0..30 seconds') for name in ('profile', 'audio'): if getattr(args, name) is not None and not 0 <= getattr(args, name) <= 65535: parser.error(f'--{name} must be a uint16') if args.drive is not None: drive_payload(args.steering, args.drive) if not math.isfinite(args.seconds) or not 0 < args.seconds <= 3: parser.error('--seconds must be greater than 0 and at most 3') asyncio.run(run(args)) if __name__ == '__main__': try: main() except KeyboardInterrupt: print('Interrupted; verify the car stopped.', file=sys.stderr) except Exception as error: print(f'Error: {error}', file=sys.stderr) sys.exit(1)