pyvisionect 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. pyvisionect/__init__.py +120 -0
  2. pyvisionect/devices/__init__.py +92 -0
  3. pyvisionect/devices/enums.py +403 -0
  4. pyvisionect/devices/panels.py +242 -0
  5. pyvisionect/devices/tclv.py +460 -0
  6. pyvisionect/imaging/README.md +175 -0
  7. pyvisionect/imaging/__init__.py +181 -0
  8. pyvisionect/imaging/checksum.py +114 -0
  9. pyvisionect/imaging/constants.py +131 -0
  10. pyvisionect/imaging/data/blue_noise_64.npy +0 -0
  11. pyvisionect/imaging/decode.py +172 -0
  12. pyvisionect/imaging/dither.py +357 -0
  13. pyvisionect/imaging/encoder.py +594 -0
  14. pyvisionect/imaging/geometry.py +129 -0
  15. pyvisionect/imaging/grey.py +104 -0
  16. pyvisionect/imaging/interlace.py +244 -0
  17. pyvisionect/imaging/pack.py +142 -0
  18. pyvisionect/imaging/panel.py +339 -0
  19. pyvisionect/imaging/partial.py +931 -0
  20. pyvisionect/imaging/rects.py +466 -0
  21. pyvisionect/io/__init__.py +33 -0
  22. pyvisionect/io/tcp.py +795 -0
  23. pyvisionect/io/usb/__init__.py +237 -0
  24. pyvisionect/io/usb/cli.py +278 -0
  25. pyvisionect/io/usb/commands.py +781 -0
  26. pyvisionect/io/usb/console.py +730 -0
  27. pyvisionect/io/usb/device.py +914 -0
  28. pyvisionect/io/usb/discovery.py +260 -0
  29. pyvisionect/io/usb/encryption.py +262 -0
  30. pyvisionect/io/usb/errors.py +175 -0
  31. pyvisionect/io/usb/fake.py +292 -0
  32. pyvisionect/io/usb/parsers.py +1464 -0
  33. pyvisionect/io/usb/provisioning.py +502 -0
  34. pyvisionect/packets/__init__.py +135 -0
  35. pyvisionect/packets/control.py +95 -0
  36. pyvisionect/packets/file.py +325 -0
  37. pyvisionect/packets/image.py +234 -0
  38. pyvisionect/packets/misc.py +202 -0
  39. pyvisionect/packets/param.py +284 -0
  40. pyvisionect/packets/status.py +518 -0
  41. pyvisionect/packets/stored.py +217 -0
  42. pyvisionect/py.typed +0 -0
  43. pyvisionect/session/__init__.py +100 -0
  44. pyvisionect/session/connection.py +1043 -0
  45. pyvisionect/session/device.py +587 -0
  46. pyvisionect/session/events.py +196 -0
  47. pyvisionect/session/filetransfer.py +251 -0
  48. pyvisionect/session/pending.py +425 -0
  49. pyvisionect/wire/__init__.py +91 -0
  50. pyvisionect/wire/blocks.py +350 -0
  51. pyvisionect/wire/checksum.py +115 -0
  52. pyvisionect/wire/errors.py +176 -0
  53. pyvisionect/wire/framing.py +334 -0
  54. pyvisionect-0.1.0.dist-info/METADATA +1030 -0
  55. pyvisionect-0.1.0.dist-info/RECORD +58 -0
  56. pyvisionect-0.1.0.dist-info/WHEEL +4 -0
  57. pyvisionect-0.1.0.dist-info/entry_points.txt +3 -0
  58. pyvisionect-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,292 @@
1
+ r'''A fake transport carrying the real sign's real replies.
2
+
3
+ Every string in :data:`CAPTURED` was read off ``/dev/ttyUSB0`` from a live
4
+ Visionect 32" sign running firmware 7.4.4407, then put through one scrubbing
5
+ pass: the device UUID, the WiFi SSID, every MAC and BSSID, the server hostname
6
+ and the stale static IPv4 block were replaced with documentation-range
7
+ placeholders. **Nothing else was touched** -- the padding, the inconsistent
8
+ quoting, the blank line before the UUID, the ``rv: 0`` that comes before
9
+ ``certs_config_get``'s body and the ``PROTOCOL VERSION`` key with a space in it
10
+ are all exactly as the firmware emits them.
11
+
12
+ That matters more than it sounds. A fixture written by hand from a parser's
13
+ point of view tests the parser against its own assumptions; these strings test
14
+ it against the device. Several of the parsers in
15
+ :mod:`pyvisionect.io.usb.parsers` are shaped the way they are only because of a
16
+ detail visible here and nowhere in the vendor's documentation.
17
+
18
+ Scrub map, for reference when comparing against a fresh capture:
19
+
20
+ ==================================== ================================
21
+ real published
22
+ ==================================== ================================
23
+ device UUID (12 bytes + 4 NULs) ``00112233-4455-6677-8899-aabb...``
24
+ WiFi SSID ``ExampleAP``
25
+ WiFi and BSSID MACs ``00:00:5e:00:53:00``
26
+ Ethernet MAC ``02:00:5e:00:53:00``
27
+ server hostname ``visionect.internal.example.com``
28
+ stored static IPv4 block ``192.0.2.0/24``
29
+ stored EAP username ``exampleuser``
30
+ ==================================== ================================
31
+
32
+ The Ethernet MAC keeps its leading ``02``, because that bit -- the
33
+ locally-administered flag -- is the evidence that the field holds a synthesised
34
+ default rather than a real vendor address. Scrubbing it to ``00:`` would have
35
+ quietly deleted the finding.
36
+
37
+ The UUID's trailing zero bytes are **deliberately preserved**: the factory
38
+ identifier is 12 bytes zero-padded to 16, so a scrubbed UUID that ended in
39
+ random hex would misrepresent the format.
40
+ '''
41
+
42
+ from __future__ import annotations
43
+
44
+ from collections.abc import Iterable, Mapping, Sequence
45
+
46
+ __all__ = ["ASYNC_LOG_CAPTURE", "CAPTURED", "HELP_TEXT", "FakeTransport", "fake_console"]
47
+
48
+ CAPTURED: Mapping[str, str] = {
49
+ 'battery_conf_get': 'battery_conf_get\r\nThreshold OFF: 3500 mV\r\nThreshold ON: 3400 mV\r\nThreshold CNT: 1\r\n> ',
50
+ 'border_get': 'border_get\r\nBorder support: No\r\nBorder: Server\r\n> ',
51
+ 'bq24023_mode_get': 'bq24023_mode_get\r\nBQ: fast charge\r\nIbatt: 50 mA\r\nVbatt: 4214 mV\r\n> ',
52
+ 'cc3100_fw_version': 'cc3100_fw_version\r\nNWP 2.12.2.8\r\nMAC 1.5.0.10\r\nPHY 1.0.3.37\r\nChipId 67108864\r\nROM 13107\r\n> ',
53
+ 'cc3100_mac_address': 'cc3100_mac_address\r\n00:00:5e:00:53:00\r\nrv: 0\r\n> ',
54
+ 'cc3100_rssi': 'cc3100_rssi\r\nRSSI:-31 dBm\r\n> ',
55
+ 'certs_config_get': 'certs_config_get\r\nrv: 0\r\nNo EAP cert found!\r\n> ',
56
+ 'cli_version_get': 'cli_version_get\r\nCLI version: 1.2\r\n> ',
57
+ 'conn_fw_ver': 'conn_fw_ver\r\n6.4294967295.3310684876\r\nrv: 0\r\n> ',
58
+ 'conn_retry_get': 'conn_retry_get\r\nNet error retry: 1\r\n> ',
59
+ 'conn_state_get': 'conn_state_get\r\nConn: tcp open\r\n> ',
60
+ 'conn_type_get': 'conn_type_get\r\nCC3100 (6) active\r\n> ',
61
+ 'conn_type_list': 'conn_type_list\r\nW5500 (3)\r\nCC3100 (6)\r\nNone (0)\r\n> ',
62
+ 'display_conf_get': 'display_conf_get\r\nVcom 0: 2400 mV\r\nVcom 1: 2400 mV\r\nVcom 2: 2400 mV\r\nVcom 3: 2400 mV\r\nVcom 4: 0 mV\r\nVcom 5: 0 mV\r\nVcom 6: 0 mV\r\nVcom 7: 0 mV\r\nDisplay type: 3255107880\r\n> ',
63
+ 'encryption_config_get': "encryption_config_get\r\nOutbound enc: Disabled\r\nKey: ''\r\n> ",
64
+ 'eth_conf_get': 'eth_conf_get\r\nMAC: 02:00:5E:00:53:00\r\nTRC: 8\r\nTRT: 2000\r\n> ',
65
+ 'feat_get': 'feat_get\r\nFeature touch: enabled\r\nFeature EAP: enabled\r\n> ',
66
+ 'fs_ls': 'fs_ls\r\n/image0.pv2 0 134409\r\n/image1.pv2 0 199047\r\n/image2.pv2 0 1213841\r\n/image3.pv2 0 781996\r\n/image4.pv2 0 453496\r\n/image5.pv2 0 1007217\r\nrv: 0\r\n> ',
67
+ 'fs_stats': 'fs_stats\r\ntotal blocks: 2048, in use: 931\r\n> ',
68
+ 'fw_version_get': 'fw_version_get\r\nFW Version: 7.4.4407\r\nFW Build date: 10 9 2025\r\nFW Crc=0x652be4ad, Hash=0x8281f596, Length=408876\r\nBL Version: 7.4.4407\r\nBL Build date: 10 9 2025\r\nBuild Version: 7.4.4407\r\nHW: PP32 v1.1, BOM: 0, APP: Joan\r\nEPD: 31.2",2x2880x640,WF=31.2_C296,IC=31.2_p224rev0050\r\n> ',
69
+ 'gtin_get': 'gtin_get\r\nGTIN: 3830065461792\r\n> ',
70
+ 'image_rotate_config_get': 'image_rotate_config_get\r\nMode: off\r\nTimeout: 75 sec\r\nNumber of images: 0\r\n> ',
71
+ 'ipv4_conf_get': 'ipv4_conf_get\r\nIP: 192.0.2.31\r\nNM: 255.255.255.0\r\nGW: 192.0.2.250\r\nDNS: 0.0.0.0\r\nMODE: 1\r\n> ',
72
+ 'lmr': 'lmr\r\nLM75: 24 degC\r\n> ',
73
+ 'log_config_get': 'log_config_get\r\nMobile: 0\r\n> ',
74
+ 'max17135_dump': 'max17135_dump\r\nIncorrect command parameter(s). Enter "help" to view a list of available commands.\r\n\r\n> ',
75
+ 'server_hb_get': 'server_hb_get\r\nHB interval: 1\r\n> ',
76
+ 'server_tcp_get': 'server_tcp_get\r\nServer IP/DNS: visionect.internal.example.com\r\nServer port: 11113\r\n> ',
77
+ 'sf_list': 'sf_list\r\nIDX | SPI_CHANNEL\r\n----|------------\r\n 00 | 2\r\n\r\nrv: 0x0\r\n> ',
78
+ 'sf_rdid': 'sf_rdid\r\nassert: spi_flash_cli.c:139\r\n',
79
+ 'sf_rdst': 'sf_rdst\r\nassert: spi_flash_cli.c:188\r\n',
80
+ 'status_get': 'status_get\r\nCONNECT_REASON: 0x0\r\nERROR_CODE: 0x0\r\nHW_ID: 0xFFFFFFFF\r\nFW_CRC: 0x652BE4AD\r\nWIFI_MODULE_ID: 0x6\r\nMOBILE_MODULE_ID: 0xFFFFFFFF\r\nCONNECTIVITY_USED: 6\r\nNUMBER_OF_SUPPORTED_DISPLAYS: 2\r\nDISPLAYS_ID: 0xC2050128\r\nDISPLAY_STATE_CRC: 0x8C3650A8\r\nBATTERY_LEVEL: 100\r\nCHARGING_STATUS: 0x1\r\nMIN_TEMPERATURE: 24\r\nSIGNAL_STRENGTH: 31\r\nSYSTEM_UPTIME: 5\r\nFIRMWARE_VERSION_MAJOR: 7\r\nFIRMWARE_VERSION_MINOR: 4\r\nFIRMWARE_VERSION_REVISION: 4407\r\nBOOTLOADER_VERSION_MAJOR: 7\r\nBOOTLOADER_VERSION_MINOR: 4\r\nBOOTLOADER_VERSION_REVISION: 4407\r\nHARDWARE_NAME_ID: 0x8\r\nHARDWARE_VERSION_MAJOR: 1\r\nHARDWARE_VERSION_MINOR: 1\r\nHARDWARE_VERSION_REVISION: 0\r\nHARDWARE_FIRMWARE_INTERFACE: 0x0\r\nHEART_BEAT_INTERVAL: 1\r\nTOUCH_TYPE: 0x0\r\nTOUCH_FW_VERSION_MAJOR: 0\r\nTOUCH_FW_VERSION_MINOR: 0\r\nTOUCH_EVT_COUNT: 0\r\nBATTERY_VOLTAGE: 4214\r\nBATTERY_CURRENT: 48\r\nEVENT_QUEUE_OVERFLOW: 0\r\nDISPLAY_WIDTH: 2880\r\nDISPLAY_HEIGHT: 640\r\nPROTOCOL VERSION: 3\r\nFEATURES1: 585\r\nEPD_TEMP_SENSOR: 24\r\nFL_BUTTON_COUNT: 0\r\nWIRELESS_LINK_TYPE: -1\r\nGTIN: 3830065461792\r\nIMAGE_ALLOW: 1\r\nMOB_SECURITY: 2\r\nFS_TOTAL_SIZE: 8388608\r\nFS_FREE_SIZE: 4575232\r\nPROXIMITY_COUNT: 0\r\nNETWORK_ERROR_COUNT: 0\r\nMCU_AWAKE_COUNT: 20\r\nDCM_STATE: 0\r\nWIFI_DTIM: 100\r\nPROXIMITY_THRESHOLD: -1\r\nBSSID_1: 0x5E0000\r\nBSSID_2: 0x53\r\nLAST_STATUS: 0x282296CD\r\nDISPLAY_UPDATE_COUNT: 1\r\nCONN_VER_MAJOR: 6\r\nCONN_VER_MINOR: -1\r\nCONN_VER_REVISION: -984282420\r\nSTATUS_END\r\n> ',
81
+ 'system_conf_get': 'system_conf_get\r\nBattery mode: 0\r\nTouch mode: 3\r\nShipping mode: 0\r\n> ',
82
+ 'task_list': 'task_list\r\ntask name \tstate\tstk free\ttask nr\r\nusb_cli_task \tX\t402\t6\r\nIDLE \tR\t222\t2\r\nvp_debounce_task \tB\t220\t9\r\nW5500 \tB\t988\t10\r\ntouch_hal \tB\t450\t13\r\nconnectivity_task \tB\t300\t7\r\ntimer ms \tB\t480\t3\r\ntimer rtc \tB\t184\t4\r\nmain \tB\t754\t5\r\nCC3100 \tB\t932\t11\r\npv2_receiver_task \tB\t376\t8\r\nCC3100 RX \tB\t418\t14\r\npv_tx \tB\t474\t12\r\ninit \tB\t432\t1\r\nHeap free: 19136\r\n> ',
83
+ 'uptime': 'uptime\r\nUptime in min: 5\r\n> ',
84
+ 'uuid_get': 'uuid_get\r\n\r\nUUID: 0x00 0x11 0x22 0x33 0x44 0x55 0x66 0x77 0x88 0x99 0xaa 0xbb 0x00 0x00 0x00 0x00 \r\n> ',
85
+ 'wifi_bssid_get': 'wifi_bssid_get\r\n00:00:5e:00:53:00\r\nrv: 0x0\r\n> ',
86
+ 'wifi_conf_get': 'wifi_conf_get\r\nSSID: ExampleAP\r\nSecurity: wpa2\r\nBand: 0\r\n> ',
87
+ 'wifi_eap_conf_get': 'wifi_eap_conf_get\r\nEAP method: PEAP/MSCHAPV2\r\nUsername: exampleuser\r\n> ',
88
+ 'wifi_mac_conf_get': 'wifi_mac_conf_get\r\nWiFi MAC: 00:00:5e:00:53:00\r\n> ',
89
+ }
90
+ """Command -> the complete frame the device sent back, echo and prompt included.
91
+
92
+ Keyed by the command exactly as it was sent. The value starts with the device's
93
+ echo of that command and ends with the ``"> "`` prompt, because that is what a
94
+ reader has to cope with.
95
+ """
96
+
97
+ HELP_TEXT = "help\n\n24aa256_test: EEPROM pattern read/write test\n\napp_sleep <minutes>: Put app into deep sleep\n\napp_wakeup: Wake-up app from the deep sleep\n\nautoconn <timeout>: Disable auto-connect\n\nbattery_conf_get: Display battery cfg\n\nbattery_conf_set <thr_off> <thr_on> <thr_cnt>: Set battery cfg\n\nborder_get: Get border mode\n\nbq24023_mode_get: Display state\n\nbsim <mode> <force>: Simulate battery state\n\nbsimi <mode> <current>: Simulate battery charging current\n\nbsimv <voltage>: Simulate battery voltage\n\ncc3100_dns <url>: Resolve IP from URL\n\ncc3100_format: Formats the CC3100 SPI FLASH\n\ncc3100_fw_upgrade: Force FW upgrade\n\ncc3100_fw_version: Display WiFi FW version\n\ncc3100_mac_address: Display WiFi MAC address\n\ncc3100_rssi: Read RSSI value from CC3100 WiFi module\n\ncc3100_scan: Scan for WiFi APs\n\ncerts_config_get: Display WiFi certificate cfg\n\ncli_password_set <password> <password>: Sets CLI password\n\ncli_version_get: Display CLI version\n\nconn_fw_ver: Scan for WiFi APs\n\nconn_retry_get: Display conn error retry interval\n\nconn_retry_set <time>: Set conn. error retry interval\n\nconn_scan: Scan for WiFi APs\n\nconn_state_get: Display connection state\n\nconn_type_get: Display connectivity type\n\nconn_type_list: List available connections\n\nconn_type_set <type>: Set connectivity type\n\ncs <state>: Change connection state\n\ndcmb <mode>: Sets the border mode\n\ndcmc <color>: Clears the display to a specified color\n\ndcmd: DCM Power-down display driver\n\ndcmh <mode>: Runs EPD pre/post-update hook\n\ndcms: Put display driver to sleep\n\ndcmt <driver_no>: DCM Select ESPON driver to communicate with\n\ndcmu: DCM Power-up display driver an put it to sleep\n\ndcmw: DCM Wake-up display driver\n\ndisplay_conf_get: Display VCOMs and display type\n\ndisplay_conf_set <vcom1> <vcom2> ... <vcom16> <display_id>: Set display cfg\n\nencryption_config_get: Display encryption settings\n\nencryption_key_set <key>: Set encryption key\n\nencryption_mode_set <mode>: Set encryption mode\n\neth_conf_ext_set <mac> <trc> <trt>: Set extented Eth cfg\n\neth_conf_get: Display Eth cfg\n\neth_conf_mac_reset Reset Eth MAC cfg\n\neth_conf_set <mac>: Set Eth MAC\n\nfeat_disable <key>: Disable feature\n\nfeat_enable <key>: Enable feature\n\nfeat_get: List features status\n\nflash_load: Reload settings\n\nflash_save: Save settings\n\nfs_format: Formats the file system\n\nfs_ls: List files on the file system.\n\nfs_stats: Displays block usage statistics\n\nfw_version_get: Show system FW version\n\ngtin_get: Get GTIN code\n\nhelp: Lists all the registered commands\n\nimage_rotate_config_get: Display image rotate cfg\n\nimage_rotate_config_set <mode> <timeout> <num_images>: Sets image rotate cfg\n\nipv4_conf_get: Display IPv4 cfg\n\nipv4_conf_set <ip> <nm> <gw> <dns> <mode>: Set IPv4 Eth cfg\n\nlmr: Read temperature from LM75\n\nlms <mode> <value>: Simulates LM75 temperature\n\nlog_config_get: Display debug logging\n\nlog_config_set <module> <value>: Set debug logging\n\nm2m_mode <timeout>: Disable autonomous connectivity reconnection\n\nmax17135_dump: Dump register values\n\nmax17135_pwr <enable>: Enables/disables MAX17135 power\n\nmax17135_selftest <i2c_channel>: Performs MAX17135 selftest\n\nmax17135_sleep <i2c_channel>: Puts MAX17135 to sleep\n\nmax17135_wakeup <i2c_channel>: Wakes up MAX17135\n\npbs: PV2 send button\n\npgs: PV2 send GPS\n\nplay_music: Play built-in song\n\npss: PV2 send status\n\npts <x> <y>: PV2 send touch\n\nreboot: Reboot device\n\nserver_hb_get: Display HB\n\nserver_hb_set <time>: Set heart-beat\n\nserver_tcp_get: Display server's IP and port\n\nserver_tcp_set <ip> <port>: Set server's IP and port\n\nsf_list: Lists all registered SPI FLASH devices\n\nsf_rdid: Reads SPI FLASH chip ID\n\nsf_rdst: Reads SPI FLASH chip status\n\nsf_select: Selects a SPI FLASH decice from the list\n\nsf_unprot: Unprotects the SPI FLASH chip\n\nsf_wrst: Writes 0x00 to SPI FLASH chip status register\n\nstatus_get: Display status packet\n\nsystem_conf_get: Display system cfg\n\nsystem_conf_set <batt_ind_en> <touch_en> <ship_en>: Set system cfg\n\ntask_list: Show registered tasks\n\nuptime: Display system uptime\n\nuuid_get: Display device's UUID\n\nvlog_set_default_levels: Reset logger levels to default\n\nvlog_set_destination_level <destination> <level>: Set logger level on a destination side\n\nvlog_set_source_level <source> <level>: Set logger level on a source side\n\nvlog_unify_levels <usb_level>: Reset logger levels to default for USB\n\nwifi_bssid_get: Get WiFi BSSID\n\nwifi_conf_get: Get WiFi cfg\n\nwifi_conf_set <ssid> <psk> <security> <band>: Set WiFi connection\n\nwifi_eap_conf_em_set <eap_method>: Set WiFi EAP method\n\nwifi_eap_conf_get: Display WiFi EAP cfg\n\nwifi_eap_conf_pwd_set <password>: Set WiFi EAP password\n\nwifi_eap_conf_usr_set <username>: Set WiFi EAP username\n\nwifi_ext_mode_set <mode>: Sets WiFi mode\n\nwifi_ext_region_set <region>: Set WiFi region cfg\n\nwifi_mac_conf_get: Display WiFi MAC cfg\n\nwifi_mac_conf_set <mac>: Set WiFi MAC cfg\n\nwifi_psk_set <psk>: Set wpa2 password\n\nwifi_security_set <security>: Set WiFi security mode\n\nrv: 0\n> "
98
+ """The full ``help`` frame, ~5 KB: the 111 commands this firmware's ``help`` prints.
99
+
100
+ Not every command the firmware *has*: ``wifi_ssid_set`` is present and answers,
101
+ and is deliberately not in here, because it is not in the capture either. See
102
+ :data:`pyvisionect.io.usb.commands.HIDDEN_IN_7_4_4407`.
103
+ """
104
+
105
+ ASYNC_LOG_CAPTURE = '\nuptime\nUptime in min: 0\n> border (0 1)\nUPD_FULL\nborder (0 1)\nUPD_FULL\nborder (0 1)\nUPD_FULL\nborder (0 1)\nUPD_FULL\nborder (0 1)\nUPD_FULL\nborder (0 1)\nUPD_FULL\ndisplay update id: 0x8c3650a8\nDisplay updated!\nmake packet type=1, id=891437714\nFrame send 64 bytes\nSetting heartbeat after 1 min\nProfiling:Total=6184,RxHole=0,Decrypt=0,Decomp=69,EpdLoad=494,EpdWake=49,EpdSleep=2,EpdStart=0,EpdEnd=0,EpdOther=244,EpdUpd=5298,Pv2Len=20508,RawLen=1843200,ImgOpt=0x00003024,ImgId=0x8c3650a8\nuptime\nUptime in min: 0\n> uptime\nUptime in min: 0\n> sys evt vplatform_heartbeat.c:19, Heartbeat (7)\nReceived event: Heartbeat (7)\nHeart-beat event\nsending pv2 status on heartbeat\nmake packet type=3, id=2\nFrame send 552 bytes\nSetting heartbeat after 1 min\nGot response (id=2)\nSetting heartbeat after 1 min\nuptime\nUptime in min: 1\n> uptime\nUptime in min: 1\n> sys evt vplatform_heartbeat.c:19, Heartbeat (7)\nReceived event: Heartbeat (7)\nHeart-beat event\nsending pv2 status on heartbeat\nmake packet type=3, id=3\nFrame send 552 bytes\nSetting heartbeat after 1 min\nGot response (id=3)\nSetting heartbeat after 1 min\nuptime\nUptime in min: 2\n> uptime\nUptime in min: 2\n> sys evt vplatform_heartbeat.c:19, Heartbeat (7)\nReceived event: Heartbeat (7)\nHeart-beat event\nsending pv2 status on heartbeat\nmake packet type=3, id=4\nFrame send 552 bytes\nSetting heartbeat after 1 min\nGot response (id=4)\nSetting heartbeat after 1 min\nuptime\nUptime in min: 3\n> uptime\nUptime in min: 3\n> uptime\nUptime in min: 3\n> sys evt vplatform_heartbeat.c:19, Heartbeat (7)\nReceived event: Heartbeat (7)\nHeart-beat event\nsending pv2 status on heartbeat\nmake packet type=3, id=5\nFrame send 552 bytes\nSetting heartbeat after 1 min\nGot response (id=5)\nSetting heartbeat after 1 min\nuptime\nUptime in min: 4\n> '
106
+ """Four and a half minutes of unsolicited UART output, verbatim.
107
+
108
+ Captured by sitting on the port and nudging it with ``uptime`` every 25
109
+ seconds, which is why reply frames and log bursts are interleaved here exactly
110
+ as they arrive in practice. Contains four heartbeat bursts, a ``Profiling:``
111
+ line from an image push, and the prompt/echo pattern around each ``uptime``.
112
+
113
+ This is the fixture behind the interleaving tests: the heartbeat burst is a real
114
+ eight-line block that really does land between a command and its prompt.
115
+ """
116
+
117
+
118
+ _UNKNOWN = (
119
+ "Command {command!r} not recognised. Enter 'help' to view a list of "
120
+ "available commands."
121
+ ).replace("{command!r}", "'{command}'")
122
+
123
+ _PROMPT = "> "
124
+
125
+
126
+ class FakeTransport:
127
+ r"""A :class:`~pyvisionect.io.usb.console.SerialTransport` with no hardware.
128
+
129
+ Answers from :data:`CAPTURED` by default, so a test exercises the real
130
+ parser against the real bytes. Unknown commands get the firmware's real
131
+ unrecognised-command string, so the error path is exercised too.
132
+
133
+ Args:
134
+ replies: command -> the frame to send back. Defaults to
135
+ :data:`CAPTURED`. A value may omit the echo and the prompt; this
136
+ class adds whichever is missing, so a hand-written reply is just its
137
+ body.
138
+ echo: whether to echo the command line, as the real device does.
139
+ prompt: the prompt to append.
140
+ async_lines: lines to inject as unsolicited log output. Each entry is
141
+ ``(after_n_commands, text)``: the text is queued to arrive just
142
+ *before* the reply to command number ``after_n_commands``
143
+ (0-based), which is the case that a drain-before-send handles.
144
+ interleave: ``(command, after_line_index, text)`` entries that splice a
145
+ log line **into the middle of a reply**, after the given reply line.
146
+ This is the failure mode that matters, and it is hard to provoke on
147
+ real hardware on demand, so it is injectable here.
148
+ pre_echo: ``(command, text)`` entries emitted after the command is
149
+ written but **before** the device's echo of it, which is the real
150
+ arrival pattern for a log line that fires while the command is in
151
+ flight. Exercises the echo anchor.
152
+ unknown_commands: names to answer as unrecognised even if they are in
153
+ *replies*. For testing the firmware-delta path.
154
+ terminator_required: the byte that must end a written line before the
155
+ fake will answer. Defaults to ``b"\r"``, matching the device: a
156
+ line ending only in ``\n`` is echoed and then **held**, exactly as
157
+ the real firmware holds it, so a test can catch a wrong terminator.
158
+
159
+ Example:
160
+ >>> from pyvisionect.io.usb import SerialConsole
161
+ >>> console = SerialConsole(transport=FakeTransport())
162
+ >>> console.command("uptime").field("Uptime in min")
163
+ '5'
164
+ """
165
+
166
+ def __init__(
167
+ self,
168
+ replies: Mapping[str, str] | None = None,
169
+ *,
170
+ echo: bool = True,
171
+ prompt: str = _PROMPT,
172
+ async_lines: Sequence[tuple[int, str]] = (),
173
+ interleave: Sequence[tuple[str, int, str]] = (),
174
+ pre_echo: Sequence[tuple[str, str]] = (),
175
+ unknown_commands: Iterable[str] = (),
176
+ terminator_required: bytes = b"\r",
177
+ ) -> None:
178
+ self.replies = dict(replies) if replies is not None else {
179
+ **CAPTURED,
180
+ "help": HELP_TEXT,
181
+ }
182
+ self.echo = echo
183
+ self.prompt = prompt
184
+ self.async_lines = list(async_lines)
185
+ self.interleave = list(interleave)
186
+ self.pre_echo = list(pre_echo)
187
+ self._fired: set[int] = set()
188
+ self.unknown_commands = set(unknown_commands)
189
+ self.terminator_required = terminator_required
190
+ self.written: list[str] = []
191
+ self.commands: list[str] = []
192
+ self.closed = False
193
+ self._out = bytearray()
194
+ self._held = ""
195
+
196
+ # ---------------------------------------------------- transport protocol
197
+
198
+ @property
199
+ def in_waiting(self) -> int:
200
+ return len(self._out)
201
+
202
+ def write(self, data: bytes, /) -> int:
203
+ text = data.decode("ascii")
204
+ self.written.append(text)
205
+ self._held += text
206
+ while self.terminator_required.decode("ascii") in self._held:
207
+ line, _, self._held = self._held.partition(
208
+ self.terminator_required.decode("ascii")
209
+ )
210
+ self._submit(line.strip("\r\n"))
211
+ return len(data)
212
+
213
+ def flush(self) -> None:
214
+ pass
215
+
216
+ def read(self, size: int = 1, /) -> bytes:
217
+ out, self._out = self._out[:size], self._out[size:]
218
+ return bytes(out)
219
+
220
+ def close(self) -> None:
221
+ self.closed = True
222
+
223
+ # -------------------------------------------------------------- internals
224
+
225
+ def _submit(self, line: str) -> None:
226
+ index = len(self.commands)
227
+ for slot, (after, text) in enumerate(self.async_lines):
228
+ if after == index and slot not in self._fired:
229
+ self._fired.add(slot)
230
+ self._out += (text + "\r\n").encode("ascii")
231
+ if not line:
232
+ # bare CR: the device answers "\r\n> "
233
+ self._out += ("\r\n" + self.prompt).encode("ascii")
234
+ return
235
+ self.commands.append(line)
236
+ self._out += self._frame(line).encode("ascii")
237
+
238
+ def _frame(self, line: str) -> str:
239
+ name = line.split()[0].lower() if line.split() else ""
240
+ if name in self.unknown_commands or (
241
+ line not in self.replies and name not in self.replies
242
+ ):
243
+ body = [_UNKNOWN.format(command=line), ""]
244
+ captured = None
245
+ else:
246
+ captured = self.replies.get(line, self.replies.get(name, ""))
247
+ body = self._body_of(captured, line)
248
+
249
+ splices = [(i, t) for cmd, i, t in self.interleave if cmd == line]
250
+ if splices:
251
+ out: list[str] = [t for at, t in splices if at < 0]
252
+ for i, reply_line in enumerate(body):
253
+ out.append(reply_line)
254
+ for at, text in splices:
255
+ if at == i:
256
+ out.append(text)
257
+ body = out
258
+
259
+ head = "".join(
260
+ f"{text}\r\n" for cmd, text in self.pre_echo if cmd == line
261
+ )
262
+ head += f"{line}\r\n" if self.echo else ""
263
+ tail = "".join(f"{reply_line}\r\n" for reply_line in body)
264
+ return head + tail + self.prompt
265
+
266
+ def _body_of(self, captured: str, line: str) -> list[str]:
267
+ """Strip a captured frame back to its reply lines."""
268
+ text = captured
269
+ if self.prompt and text.endswith(self.prompt):
270
+ text = text[: -len(self.prompt)]
271
+ parts = text.replace("\r\n", "\n").split("\n")
272
+ if parts and parts[0].strip().lower() == line.strip().lower():
273
+ parts = parts[1:]
274
+ while parts and not parts[-1].strip():
275
+ parts.pop()
276
+ return parts
277
+
278
+
279
+ def fake_console(**kwargs: object) -> object:
280
+ """A :class:`~pyvisionect.io.usb.console.SerialConsole` on a :class:`FakeTransport`.
281
+
282
+ Timeouts are set small so a test that provokes a timeout does not take
283
+ seconds. Keyword arguments go to :class:`FakeTransport`.
284
+ """
285
+ from .console import SerialConsole
286
+
287
+ return SerialConsole(
288
+ transport=FakeTransport(**kwargs), # type: ignore[arg-type]
289
+ command_timeout=1.0,
290
+ idle_timeout=0.05,
291
+ read_timeout=0.0,
292
+ )