diff --git a/docs/resources/index.md b/docs/resources/index.md index 86aa4006dbc..d101fca9d08 100644 --- a/docs/resources/index.md +++ b/docs/resources/index.md @@ -175,6 +175,7 @@ library/agenbio library/agilent library/alpaqua library/azenta +library/beckman_coulter library/bioer library/biorad library/boekel diff --git a/docs/resources/library/beckman_coulter.md b/docs/resources/library/beckman_coulter.md new file mode 100644 index 00000000000..af2e392ebd7 --- /dev/null +++ b/docs/resources/library/beckman_coulter.md @@ -0,0 +1,45 @@ +# Beckman Coulter + +Company page: [Beckman Coulter Life Sciences](https://www.beckman.com) + +Transcribed from the tip and labware classes of Biomek 5, Beckman Coulter's software for its Biomek +liquid handlers. The labware is defined as Biomek defines it, under Biomek's class names (in +quotes), whoever makes it. Tips are `BiomekTip`s, which also carry the tip's cone; wells are +`BiomekWell`s, which also carry Biomek's outline of the well by height. + +## Tips + +| Description | Image | PLR definition | +|-|-|-| +| 'T50F'
Biomek tip, 50 uL, filter | | `beckman_coulter_biomek_tip_50uL_filter` | +| 'T190F'
Biomek tip, 190 uL, filter | | `beckman_coulter_biomek_tip_190uL_filter` | +| 'T230'
Biomek tip, 230 uL, no filter | | `beckman_coulter_biomek_tip_230uL` | +| 'T1025F'
Biomek tip, 1025 uL, filter | | `beckman_coulter_biomek_tip_1025uL_filter` | +| 'T1070'
Biomek tip, 1070 uL, no filter | | `beckman_coulter_biomek_tip_1070uL` | + +## Tip racks + +| Description | Image | PLR definition | +|-|-|-| +| 'BC50F'
Part no.: B85888
Biomek tip box: 96 T50F tips | | `beckman_coulter_biomek_96_tiprack_50uL_filter` | +| 'BC190F'
Part no.: B85911
Biomek tip box: 96 T190F tips | | `beckman_coulter_biomek_96_tiprack_190uL_filter` | +| 'BC230'
Part no.: B85906 (sterile), B85903 (non-sterile)
Biomek tip box: 96 T230 tips | | `beckman_coulter_biomek_96_tiprack_230uL` | +| 'BC1025F'
Part no.: B85955
Biomek tip box: 96 T1025F tips | | `beckman_coulter_biomek_96_tiprack_1025uL_filter` | +| 'BC1070'
Part no.: B85945 (sterile), B85940 (non-sterile)
Biomek tip box: 96 T1070 tips | | `beckman_coulter_biomek_96_tiprack_1070uL` | + +## Plates + +| Description | Image | PLR definition | +|-|-|-| +| 'Thermo96VB_PP'
96 round, V-bottomed wells; with its 'TiterplateLid' | | `beckman_coulter_biomek_96_wellplate_vb` | +| 'BCFlat96'
Part no.: 609844
96 round, flat-bottomed wells; with its 'TiterplateLid' | | `beckman_coulter_biomek_96_wellplate_flat` | +| 'BCDeep96Square'
Part no.: 140504
96 deep, square, V-bottomed wells | | `beckman_coulter_biomek_96_deepwell_square` | +| 'Thomson_24w_Square_RB'
Part no.: 931568
24 square, round-bottomed wells; with its lid | | `beckman_coulter_biomek_24_wellplate_square_rb` | + +## Reservoirs + +| Description | Image | PLR definition | +|-|-|-| +| 'ThermoNUNC_350CB'
one flat-bottomed section; with its 'TiterplateLid' | | `beckman_coulter_biomek_reservoir_350cb` | +| 'Reservoir'
Part no.: 148033
one flat-bottomed section | | `beckman_coulter_biomek_reservoir` | +| 'ModularReservoir'
Part no.: 372795 (frame)
four V-bottomed sections | | `beckman_coulter_biomek_modular_reservoir` | diff --git a/pylabrobot/beckman_coulter/__init__.py b/pylabrobot/beckman_coulter/__init__.py new file mode 100644 index 00000000000..e113ad03137 --- /dev/null +++ b/pylabrobot/beckman_coulter/__init__.py @@ -0,0 +1 @@ +"""Beckman Coulter devices.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/__init__.py new file mode 100644 index 00000000000..421a55e4014 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/__init__.py @@ -0,0 +1 @@ +"""Beckman Coulter Biomek i7, driven over USB through its ACE boards.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py new file mode 100644 index 00000000000..b7118bd6e87 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py @@ -0,0 +1,13 @@ +"""A generic Biomek i7's cold start: what a simulated instrument answers when given no instrument's +own recording. + +Made from one instrument's cold-start recording (the requests the Master Controller sent at a +start and the boards' replies), with every serial number replaced by a placeholder of the same +length. +""" + +from pathlib import Path + +HERE = Path(__file__).parent + +GENERIC_RECORDING = HERE / "biomek_i7_generic_coldstart.json" diff --git a/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_coldstart.json b/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_coldstart.json new file mode 100644 index 00000000000..32739c1cac9 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_coldstart.json @@ -0,0 +1,3004 @@ +{ + "source": "the cold start of one Biomek i7, serial numbers replaced", + "boards": { + "chassis": [ + [ + "00000000", + [ + "000000010002008000" + ] + ], + [ + "00000003", + [ + "000000020302000200" + ] + ], + [ + "00000002", + [ + "0000000302020053494d554c415445443030313030303030303030303030303030303030303030" + ] + ], + [ + "00000012", + [ + "0000000412020078DB2D6D" + ] + ], + [ + "00000011", + [ + "00000005110200C4100400" + ] + ], + [ + "00000008", + [ + "000000060802000101000201002D0100" + ] + ], + [ + "02010003", + [ + "02010007030200E500" + ] + ], + [ + "02010010", + [ + "02010008100200302E322E34" + ] + ], + [ + "20000008", + [ + "2000000A080200210100220900280100" + ] + ], + [ + "22090001", + [ + "2209000B01020054656D7065726174757265" + ] + ], + [ + "22090012", + [ + "2209000C1202006465672E2043" + ] + ], + [ + "22080001", + [ + "2208000D010200416972205072657373757265" + ] + ], + [ + "22080012", + [ + "2208000E1202006B5061" + ] + ], + [ + "22070001", + [ + "2207000F01020048756D6964697479" + ] + ], + [ + "22070012", + [ + "2207001012020025205248" + ] + ], + [ + "22060001", + [ + "220600110102004C69676874204375727461696E20526567756C61746F72" + ] + ], + [ + "22060012", + [ + "2206001212020056" + ] + ], + [ + "22050001", + [ + "220500130102002B33365620496E7465726C6F636B6564" + ] + ], + [ + "22050012", + [ + "2205001412020056" + ] + ], + [ + "22040001", + [ + "220400150102002B333656205377697463686564" + ] + ], + [ + "22040012", + [ + "2204001612020056" + ] + ], + [ + "22030001", + [ + "220300170102002B323456205377697463686564" + ] + ], + [ + "22030012", + [ + "2203001812020056" + ] + ], + [ + "22020001", + [ + "220200190102002B333656" + ] + ], + [ + "22020012", + [ + "2202001A12020056" + ] + ], + [ + "22010001", + [ + "2201001B0102002B35562056427573" + ] + ], + [ + "22010012", + [ + "2201001C12020056" + ] + ], + [ + "21010001", + [ + "2101001E010200446F6F722053656E736F72" + ] + ], + [ + "2101001101", + [ + "2101001F110200" + ] + ], + [ + "21010010", + [ + "2101002010020001" + ] + ], + [ + "28010001", + [ + "280100220102004465636B204C69676874" + ] + ], + [ + "2801001101", + [ + "28010023110200" + ] + ], + [ + "28010010", + [ + "2801002410020000" + ] + ], + [ + "22010010", + [ + "22010025100200F173A540" + ] + ], + [ + "fe000018", + [ + "FE00002618020001000600" + ] + ], + [ + "01010050", + [ + "01010027500200" + ] + ], + [ + "0101001101", + [ + "01010028110200" + ] + ], + [ + "2d01001002", + [ + "2D010029100200" + ] + ], + [ + "ff0100100201", + [ + "FF01002A1002000101" + ] + ], + [ + "01010051", + [ + "0101002B51020000" + ] + ], + [ + "2d01001003", + [ + "2D01002C100200" + ] + ], + [ + "ff01001001790001", + [ + "FF01002F10020001790000" + ] + ], + [ + "ff01001001790000", + [ + "FF01003110020001790000" + ] + ], + [ + "ff010010019300", + [ + "FF010032100200019300" + ] + ], + [ + "22020010", + [ + "220200371002005E050F42" + ] + ], + [ + "22030010", + [ + "220300381002007470BF41" + ] + ], + [ + "22040010", + [ + "22040039100200884D0D42" + ] + ], + [ + "22050010", + [ + "2205003A100200A10E0E42" + ] + ], + [ + "22060010", + [ + "2206003B1002001854AF41" + ] + ], + [ + "22070010", + [ + "2207003C1002000B2B1642" + ] + ], + [ + "22080010", + [ + "2208003D100200EDFBDB42" + ] + ], + [ + "22090010", + [ + "2209003E100200C0F4BB41" + ] + ] + ], + "multichannel": [ + [ + "00000000", + [ + "00000001000200FD01" + ] + ], + [ + "00000003", + [ + "000000020302000100" + ] + ], + [ + "00000002", + [ + "0000000302020053494d554c415445443030323030303030303030303030303030303030303030" + ] + ], + [ + "00000012", + [ + "0000000412020078DB2D6D" + ] + ], + [ + "00000011", + [ + "00000005110200C4100400" + ] + ], + [ + "00000008", + [ + "00000006080200010100020700" + ] + ], + [ + "02070003", + [ + "02070007030200E300" + ] + ], + [ + "02070010", + [ + "02070009100200322E322E33" + ] + ], + [ + "02060003", + [ + "0206000A0302000001" + ] + ], + [ + "02060002", + [ + "0206000b02020053494d554c415445443030333030303030303030303030303030303030303030" + ] + ], + [ + "02060012", + [ + "0206000C12020078DB2D6D" + ] + ], + [ + "02060011", + [ + "0206000D110200C4100400" + ] + ], + [ + "02050003", + [ + "0205000E0302000001" + ] + ], + [ + "02050002", + [ + "0205000f02020053494d554c415445443030343030303030303030303030303030303030303030" + ] + ], + [ + "02050012", + [ + "0205001012020078DB2D6D" + ] + ], + [ + "02050011", + [ + "02050011110200C4100400" + ] + ], + [ + "02040003", + [ + "020400120302000001" + ] + ], + [ + "02040002", + [ + "0204001302020053494d554c415445443030353030303030303030303030303030303030303030" + ] + ], + [ + "02040012", + [ + "0204001412020078DB2D6D" + ] + ], + [ + "02040011", + [ + "02040015110200C4100400" + ] + ], + [ + "02030003", + [ + "020300160302000001" + ] + ], + [ + "02030002", + [ + "0203001702020053494d554c415445443030363030303030303030303030303030303030303030" + ] + ], + [ + "02030012", + [ + "0203001812020078DB2D6D" + ] + ], + [ + "02030011", + [ + "02030019110200C4100400" + ] + ], + [ + "02020003", + [ + "0202001A0302000001" + ] + ], + [ + "02020002", + [ + "0202001b02020053494d554c415445443030373030303030303030303030303030303030303030" + ] + ], + [ + "02020012", + [ + "0202001C12020078DB2D6D" + ] + ], + [ + "02020011", + [ + "0202001D110200C4100400" + ] + ], + [ + "02010003", + [ + "0201001E0302000001" + ] + ], + [ + "02010002", + [ + "0201001f02020053494d554c415445443030383030303030303030303030303030303030303030" + ] + ], + [ + "02010012", + [ + "0201002012020078DB2D6D" + ] + ], + [ + "02010011", + [ + "02010021110200C4100400" + ] + ], + [ + "20000008", + [ + "20000023080200220400" + ] + ], + [ + "22040001", + [ + "220400240102002B33365620496E7465726C6F636B" + ] + ], + [ + "22040012", + [ + "2204002512020056" + ] + ], + [ + "22030001", + [ + "220300260102002B355620555342" + ] + ], + [ + "22030012", + [ + "2203002712020056" + ] + ], + [ + "22020001", + [ + "220200280102002B333656" + ] + ], + [ + "22020012", + [ + "2202002912020056" + ] + ], + [ + "22010001", + [ + "2201002A0102002B35562056427573" + ] + ], + [ + "22010012", + [ + "2201002B12020056" + ] + ], + [ + "22010010", + [ + "2201002E1002004DC8A440" + ] + ], + [ + "02070004", + [ + "02070031040200312E302E30" + ] + ], + [ + "af0100f7", + [ + "AF010032F70200280FBB405DDC7740E2A38A40" + ] + ], + [ + "110100100001000000807d02000100000000fc0300010000000088130000000000005a050003000300320000605b0300c8000000002d3101b80b0000000200000180ff800c0000b80b307532000000803801000a0000b80b000050000000000000fb1027000010270000000000000000000060ea000000000000800100000000f401a00f00000000000000ffffffff0a0064000000000000002f440000803f000000000000905f0100c94eaa3acea074395d1feb330000000000000000141b000014000000b1010000ea100000401f000000000000f4010000102700000f0000000000000000000000000000000000020000002c01000032000000", + [ + "11010033100200" + ] + ], + [ + "11020010000100000000ee02000100000000b0040001000000001027000000000000e80300030003003200000071020064000000c0e1e400d007000000020000018000800c0000b80b307532000000803801000a0000b004000050000000000000fb1027000010270000000000000000000060ea000000000000800100000000f401a00f00000000000000ffffffff0a0064000000000000002f440000803f000000000000905f0100c94eaa3acea074395d1feb330000000000000000141b000014000000b1010000ea100000401f000000000000f4010000102700000f0000000000000000000000000000000000020000002c01000032000000", + [ + "11020034100200" + ] + ], + [ + "110300100001000000005f00000100000000f401000100000000aa0a000018fcff0000000003000300140000a0860100e803000040420f00e80300008000000008800034080000800c0852d007000000000000010000f401000050000000000000fa1027000010270000c8000000000000003075000018fcffff800100000000e803881300000000000080ffffffff0a006400000000000000000000000000000000000000000000000000000000000000000000000000000050c3000000000000000000000000000000000000000000000000000000000000000000000fd007410000000000000002000000000000000000000000000000000000", + [ + "11030035100200" + ] + ], + [ + "110400100001000000000003000100000000c01200000000000000000000000000801a06000300000050000050c300006400000000000000c8000000b80b00000d00ff480d0000f00a3075b4000000000000000a0000c012000040010000000000fb10270000401f00000000000000000000a8610000a8a80000000000000000f401dc0500000000000080ffffffff0a00102700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + [ + "11040036100200" + ] + ], + [ + "110500100001000000030f01000100000029830100010000009b1f0f000000000052060300030003f23d0000400d0300e80300000048e80194110000f30100000d0000b0040000dc05640018010000000000000a00298301006f4d000000000000fb10270000d6060a000000000000000000983a000000000000c60000000000f401a00f00000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + [ + "11050037100200" + ] + ], + [ + "1106001000010000001966010001000000f9f91b0001000000bac317010000000002f00200030003b735000050c30000e803000080841e00d0070000e10300000d0000bc020000dc056400fa000000e02e00000a00f9f91b001966010000000000fb4c1d000020030a000000000000000000a861000000000000290700000000f401d00700000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000d4feffff3705000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + [ + "11060038100200" + ] + ], + [ + "11070010000a000000415d0000bc02000030b301000000000000000000d03effff00000000010003380600000000000000000000000000000000000000000000090000b80b0000dc05e8030000000000000000000030b30100161f000000000000fc1027000088130a000000000000000000c8af0000000000003e0158020000640000000000e803fa0000ffffffff0a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + [ + "11070039100200" + ] + ], + [ + "110800100001000000ebb8010001000000b9bd050001000000e5f61600c396c6ff000000000300039475000020a107006400000080841e00f40100004b0000000d0000bc020000dc05640004010000b03600000200b9bd050075dc000000000000fa4c1d000020030a000000000000000000983a000000000000f00200000000f401c40900000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + [ + "1108003A100200" + ] + ], + [ + "0000000f", + [ + "0000003B0F0200" + ] + ], + [ + "11010021", + [ + "1101003C21020001" + ] + ], + [ + "1103001200", + [ + "1103003D120200" + ] + ], + [ + "1000000f", + [ + "1000003E0F0200" + ] + ], + [ + "1107001200", + [ + "1107003F120200" + ] + ], + [ + "1108001200", + [ + "11080040120200" + ] + ], + [ + "1105001200", + [ + "11050041120200" + ] + ], + [ + "1106001200", + [ + "11060042120200" + ] + ], + [ + "1104001200", + [ + "11040044120200" + ] + ], + [ + "1101001200", + [ + "11010045120200" + ] + ], + [ + "1102001200", + [ + "11020046120200" + ] + ], + [ + "11070024", + [ + "110700472402005EFFFFFF" + ] + ], + [ + "11080024", + [ + "11080048240200B352FDFF" + ] + ], + [ + "11050024", + [ + "1105004924020009F90000" + ] + ], + [ + "11060024", + [ + "1106004A24020000000000" + ] + ], + [ + "11030024", + [ + "1103004B24020001FFFFFF" + ] + ], + [ + "11040024", + [ + "1104004C24020090A80000" + ] + ], + [ + "11010024", + [ + "1101004D240200E28B0000" + ] + ], + [ + "11020024", + [ + "1102004E2402008D910000" + ] + ], + [ + "11030040005f000000f4010000aa0a000000000018fcffff0000", + [ + "11030072400032" + ] + ], + [ + "11030051", + [ + "11030073510100", + "11030073510200" + ] + ], + [ + "11070040415d000030b301000000000000000000000000000000", + [ + "11070075400032" + ] + ], + [ + "11070051", + [ + "11070079510100", + "11070079510200" + ] + ], + [ + "1106004019660100f9f91b00bac3170100000000000000000000", + [ + "1106007B400032" + ] + ], + [ + "11060051", + [ + "1106007C510100", + "1106007C510200" + ] + ], + [ + "1106004019660100f9f91b00bac3170100000000a98b00000000", + [ + "1106007E400200" + ] + ], + [ + "1106005030750000", + [ + "1106007F500100", + "1106007F500200" + ] + ], + [ + "11080040ebb80100b9bd0500e5f6160000000000000000000000", + [ + "11080081400032" + ] + ], + [ + "11080051", + [ + "11080082510100", + "11080082510200" + ] + ], + [ + "22020010", + [ + "22020083100200491C1042" + ] + ], + [ + "11080040ebb80100b9bd0500e5f61600000000009bc1fcff0000", + [ + "11080085400200" + ] + ], + [ + "1108005030750000", + [ + "11080086500100", + "11080086500200" + ] + ], + [ + "11080040ebb80100b9bd0500e5f61600000000009454fdff0000", + [ + "11080088400200" + ] + ], + [ + "11050040030f0100298301009b1f0f0000000000000000000000", + [ + "1105008B400032" + ] + ], + [ + "11050051", + [ + "1105008C510100", + "1105008C510200" + ] + ], + [ + "22030010", + [ + "2203008D1002007A9EA740" + ] + ], + [ + "1107005030750000", + [ + "11070090500100", + "11070090500200" + ] + ], + [ + "11050040030f0100298301009b1f0f0000000000d6b900000000", + [ + "11050093400200" + ] + ], + [ + "1105005030750000", + [ + "11050094500100", + "11050094500200" + ] + ], + [ + "1102004000ee020000b004000010270000000000000000000000", + [ + "11020096400032" + ] + ], + [ + "11020051", + [ + "11020097510100", + "11020097510200" + ] + ], + [ + "1102005030750000", + [ + "1102009A500100", + "1102009A500200" + ] + ], + [ + "11080040ebb80100b9bd0500e5f6160000000000dbd8fdff0000", + [ + "1108009C400200" + ] + ], + [ + "11010040807d020000fc03000088130000000000000000000000", + [ + "1101009F400032" + ] + ], + [ + "11010051", + [ + "110100A0510100", + "110100A0510200" + ] + ], + [ + "22040010", + [ + "220400A110020033BD1042" + ] + ], + [ + "11010040807d020000fc03000088130000000000008c00000000", + [ + "110100A3400200" + ] + ], + [ + "1101005030750000", + [ + "110100A4500100", + "110100A4500200" + ] + ], + [ + "110400400000030000c012000000000000000000a8a800000000", + [ + "110400A6400032" + ] + ], + [ + "11040051", + [ + "110400A7510100", + "110400A7510200" + ] + ], + [ + "11030040005f000000f4010000aa0a000000000000fbffff0000", + [ + "110300F7400200" + ] + ], + [ + "1000005073140000", + [ + "100000F8500100", + "100000F8500200" + ] + ], + [ + "11080040a925000037c60000403a0400000000006cd8fdff0000", + [ + "11080002400200" + ] + ], + [ + "11080040ebb80100b9bd0500e5f6160000000000ad52fdff0000", + [ + "1108000D400200" + ] + ], + [ + "1103004095090000f01f0000bf7f00000000000000ffffff0000", + [ + "1103000E400200" + ] + ], + [ + "100000500c170000", + [ + "1000000F500100", + "1000000F500200" + ] + ], + [ + "11010040150000001f0000003201000000000000038c00000000", + [ + "11010018400200" + ] + ], + [ + "11050040030f0100298301009b1f0f000000000013f900000000", + [ + "11050019400200" + ] + ], + [ + "11020040b86f0200077b030044ce2200000000008a9100000000", + [ + "1102001A400200" + ] + ], + [ + "100000501b170000", + [ + "1000001B500100", + "1000001B500200" + ] + ], + [ + "11070040415d000030b30100000000000000000061ffffff0000", + [ + "11070024400200" + ] + ], + [ + "10000050d4130000", + [ + "10000025500100", + "10000025500200" + ] + ], + [ + "1106004019660100f9f91b00bac3170100000000a78800000000", + [ + "11060026400200" + ] + ], + [ + "10000050f7130000", + [ + "10000027500100", + "10000027500200" + ] + ] + ], + "span8": [ + [ + "00000000", + [ + "00000001000200FB02" + ] + ], + [ + "00000003", + [ + "000000020302000100" + ] + ], + [ + "00000002", + [ + "0000000302020053494d554c415445443030393030303030303030303030303030303030303030" + ] + ], + [ + "00000012", + [ + "0000000412020078DB2D6D" + ] + ], + [ + "00000011", + [ + "00000005110200C4100400" + ] + ], + [ + "00000008", + [ + "00000006080200010100020A00" + ] + ], + [ + "020a0003", + [ + "020A0007030200E300" + ] + ], + [ + "02090003", + [ + "02090009030200E200" + ] + ], + [ + "02090010", + [ + "0209000A100200352E302E39" + ] + ], + [ + "02080003", + [ + "0208000B0302000001" + ] + ], + [ + "02080002", + [ + "0208000c02020053494d554c415445443031303030303030303030303030303030303030303030" + ] + ], + [ + "02080012", + [ + "0208000D12020078DB2D6D" + ] + ], + [ + "02080011", + [ + "0208000E110200C4100400" + ] + ], + [ + "02070003", + [ + "0207000F0302000001" + ] + ], + [ + "02070002", + [ + "0207001002020053494d554c415445443031313030303030303030303030303030303030303030" + ] + ], + [ + "02070012", + [ + "0207001112020078DB2D6D" + ] + ], + [ + "02070011", + [ + "02070012110200C4100400" + ] + ], + [ + "02060003", + [ + "02060013030200E100" + ] + ], + [ + "02060010", + [ + "02060014100200302E372E38" + ] + ], + [ + "02050003", + [ + "02050015030200E000" + ] + ], + [ + "02050010", + [ + "02050016100200302E332E3134" + ] + ], + [ + "02040003", + [ + "02040017030200E000" + ] + ], + [ + "02040010", + [ + "02040018100200302E332E3134" + ] + ], + [ + "02030003", + [ + "02030019030200E000" + ] + ], + [ + "02030010", + [ + "0203001A100200302E332E3134" + ] + ], + [ + "02020003", + [ + "0202001B030200E000" + ] + ], + [ + "02020010", + [ + "0202001C100200302E332E3134" + ] + ], + [ + "02010003", + [ + "0201001D0302000001" + ] + ], + [ + "02010002", + [ + "0201001e02020053494d554c415445443031323030303030303030303030303030303030303030" + ] + ], + [ + "02010012", + [ + "0201001F12020078DB2D6D" + ] + ], + [ + "02010011", + [ + "02010020110200C4100400" + ] + ], + [ + "20000008", + [ + "20000022080200220400" + ] + ], + [ + "22040001", + [ + "220400230102002B33365620496E7465726C6F636B" + ] + ], + [ + "22040012", + [ + "2204002412020056" + ] + ], + [ + "22030001", + [ + "220300250102002B355620555342" + ] + ], + [ + "22030012", + [ + "2203002612020056" + ] + ], + [ + "22020001", + [ + "220200270102002B333656" + ] + ], + [ + "22020012", + [ + "2202002812020056" + ] + ], + [ + "22010001", + [ + "220100290102002B35562056427573" + ] + ], + [ + "22010012", + [ + "2201002A12020056" + ] + ], + [ + "22010010", + [ + "2201002D100200C92CA640" + ] + ], + [ + "11010010000100000000ee02000100000000b00400010000000010270000a6faff0000000003000300320000007102006400000080c3c901b80b0000000200000180ff800c0000b80b307532000000803801000a0000b80b000050000000000000fa1027000010270000000000000000000060ea000000000000800100000000f401a00f00000000000000ffffffff0a0064000000000000002f440000803f000000000000905f0100c94eaa3acea074395d1feb330000000000000000141b000014000000b1010000ea100000401f000000000000f4010000102700000f0000000000000000000000000000001800020000002c01000032000000", + [ + "1101002E100200" + ] + ], + [ + "11020010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "1102002F100200" + ] + ], + [ + "11030010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11030030100200" + ] + ], + [ + "11040010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11040031100200" + ] + ], + [ + "11050010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11050032100200" + ] + ], + [ + "11060010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11060033100200" + ] + ], + [ + "11070010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11070034100200" + ] + ], + [ + "11080010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11080035100200" + ] + ], + [ + "11090010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11090036100200" + ] + ], + [ + "110a0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + [ + "110A0037100200" + ] + ], + [ + "110b0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + [ + "110B0038100200" + ] + ], + [ + "110c0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + [ + "110C0039100200" + ] + ], + [ + "110d0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + [ + "110D003A100200" + ] + ], + [ + "110e0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + [ + "110E003B100200" + ] + ], + [ + "110f0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + [ + "110F003C100200" + ] + ], + [ + "11100010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + [ + "1110003D100200" + ] + ], + [ + "11110010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + [ + "1111003E100200" + ] + ], + [ + "12010010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "1201003F100200" + ] + ], + [ + "12020010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12020040100200" + ] + ], + [ + "12030010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12030041100200" + ] + ], + [ + "12040010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12040042100200" + ] + ], + [ + "12050010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12050043100200" + ] + ], + [ + "12060010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12060044100200" + ] + ], + [ + "12070010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12070045100200" + ] + ], + [ + "12080010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12080046100200" + ] + ], + [ + "111200100001000000030f01000100000029830100010000009b1f0f000000000052060300030003f23d0000400d0300e80300000048e80194110000f30100000d0000b0040000dc05640018010000000000000a00298301006f4d000000000000fb10270000d6060a000000000000000000983a000000000000c60000000000f401a00f00000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000001800000000000000000000000000", + [ + "11120047100200" + ] + ], + [ + "1113001000010000001966010001000000f9f91b0001000000bac317010000000002f00200030003b735000050c30000e803000080841e00d0070000e10300000d0000bc020000dc056400fa000000e02e00000a00f9f91b001966010000000000fb4c1d000020030a000000000000000000a861000000000000290700000000f401d00700000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000d4feffff3705000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + [ + "11130048100200" + ] + ], + [ + "11140010000a000000415d0000bc02000030b301000000000000000000d03effff00000000010003380600000000000000000000000000000000000000000000090000b80b0000dc05e8030000000000000000000030b30100161f000000000000fc1027000088130a000000000000000000c8af0000000000003e0158020000640000000000e803fa0000ffffffff0a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + [ + "11140049100200" + ] + ], + [ + "111500100001000000ebb8010001000000b9bd050001000000e5f61600c396c6ff000000000300039475000020a107006400000080841e00f40100004b0000000d0000bc020000dc05640004010000b03600000200b9bd050075dc000000000000fa4c1d000020030a000000000000000000983a000000000000f00200000000f401c40900000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + [ + "1115004A100200" + ] + ], + [ + "0000000f", + [ + "0000004B0F0200" + ] + ], + [ + "1000000f", + [ + "1000004C0F0200" + ] + ], + [ + "1115001200", + [ + "1115004D120200" + ] + ], + [ + "1113001200", + [ + "1113004E120200" + ] + ], + [ + "1114001200", + [ + "1114004F120200" + ] + ], + [ + "1208001200", + [ + "12080050120200" + ] + ], + [ + "1112001200", + [ + "11120051120200" + ] + ], + [ + "1206001200", + [ + "12060052120200" + ] + ], + [ + "1207001200", + [ + "12070053120200" + ] + ], + [ + "1204001200", + [ + "12040054120200" + ] + ], + [ + "1205001200", + [ + "12050055120200" + ] + ], + [ + "1202001200", + [ + "12020056120200" + ] + ], + [ + "1203001200", + [ + "12030057120200" + ] + ], + [ + "1111001200", + [ + "11110058120200" + ] + ], + [ + "1201001200", + [ + "12010059120200" + ] + ], + [ + "110f001200", + [ + "110F005A120200" + ] + ], + [ + "1110001200", + [ + "1110005B120200" + ] + ], + [ + "110d001200", + [ + "110D005C120200" + ] + ], + [ + "110e001200", + [ + "110E005D120200" + ] + ], + [ + "110b001200", + [ + "110B005E120200" + ] + ], + [ + "110c001200", + [ + "110C005F120200" + ] + ], + [ + "1109001200", + [ + "11090060120200" + ] + ], + [ + "110a001200", + [ + "110A0061120200" + ] + ], + [ + "1107001200", + [ + "11070062120200" + ] + ], + [ + "1108001200", + [ + "11080063120200" + ] + ], + [ + "1105001200", + [ + "11050064120200" + ] + ], + [ + "1106001200", + [ + "11060065120200" + ] + ], + [ + "1103001200", + [ + "11030066120200" + ] + ], + [ + "1104001200", + [ + "11040067120200" + ] + ], + [ + "1101001200", + [ + "11010068120200" + ] + ], + [ + "1102001200", + [ + "11020069120200" + ] + ], + [ + "11150024", + [ + "1115006A2402006251FDFF" + ] + ], + [ + "11130024", + [ + "1113006B24020000000000" + ] + ], + [ + "11140024", + [ + "1114006C2402005EFFFFFF" + ] + ], + [ + "12080024", + [ + "1208006D240200E0010000" + ] + ], + [ + "11120024", + [ + "1112006E2402008EF80000" + ] + ], + [ + "12060024", + [ + "1206006F240200E0010000" + ] + ], + [ + "12070024", + [ + "12070070240200E0010000" + ] + ], + [ + "12040024", + [ + "12040071240200E0010000" + ] + ], + [ + "12050024", + [ + "12050072240200E0010000" + ] + ], + [ + "12020024", + [ + "12020073240200E0010000" + ] + ], + [ + "12030024", + [ + "12030074240200E0010000" + ] + ], + [ + "11110024", + [ + "111100752402006B200000" + ] + ], + [ + "12010024", + [ + "12010076240200E0010000" + ] + ], + [ + "110f0024", + [ + "110F0077240200DC1F0000" + ] + ], + [ + "11100024", + [ + "1110007824020052200000" + ] + ], + [ + "110d0024", + [ + "110D0079240200EE1F0000" + ] + ], + [ + "110e0024", + [ + "110E007A2402000A200000" + ] + ], + [ + "110b0024", + [ + "110B007B240200F81F0000" + ] + ], + [ + "110c0024", + [ + "110C007C24020026200000" + ] + ], + [ + "11090024", + [ + "1109007D2402006D1A0300" + ] + ], + [ + "110a0024", + [ + "110A007E240200E71F0000" + ] + ], + [ + "11070024", + [ + "1107007F2402005F1A0300" + ] + ], + [ + "11080024", + [ + "110800802402006B1A0300" + ] + ], + [ + "11050024", + [ + "110500812402006B1A0300" + ] + ], + [ + "11060024", + [ + "110600822402006B1A0300" + ] + ], + [ + "11030024", + [ + "110300832402006A1A0300" + ] + ], + [ + "11040024", + [ + "110400842402006B1A0300" + ] + ], + [ + "11010024", + [ + "110100852402006CE1FFFF" + ] + ], + [ + "11020024", + [ + "11020086240200691A0300" + ] + ], + [ + "11100040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "11100005400032" + ] + ], + [ + "11110040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "11110006400032" + ] + ], + [ + "110e0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110E0007400032" + ] + ], + [ + "110f0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110F0008400032" + ] + ], + [ + "110c0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110C0009400032" + ] + ], + [ + "110d0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110D000A400032" + ] + ], + [ + "110a0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110A000B400032" + ] + ], + [ + "110b0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110B000C400032" + ] + ], + [ + "110a0051", + [ + "110A0010510100", + "110A0010510200" + ] + ], + [ + "110e0051", + [ + "110E0011510100", + "110E0011510200" + ] + ], + [ + "110b0051", + [ + "110B0014510100", + "110B0014510200" + ] + ], + [ + "110f0051", + [ + "110F0015510100", + "110F0015510200" + ] + ], + [ + "110c0051", + [ + "110C0018510100", + "110C0018510200" + ] + ], + [ + "11100051", + [ + "11100019510100", + "11100019510200" + ] + ], + [ + "110d0051", + [ + "110D001C510100", + "110D001C510200" + ] + ], + [ + "11110051", + [ + "1111001D510100", + "1111001D510200" + ] + ], + [ + "1000005088130000", + [ + "1000002E500100", + "1000002E500200" + ] + ], + [ + "11140040415d000030b301000000000000000000000000000000", + [ + "11140030400032" + ] + ], + [ + "11140051", + [ + "11140035510100", + "11140035510200" + ] + ], + [ + "1113004019660100f9f91b00bac3170100000000000000000000", + [ + "11130037400032" + ] + ], + [ + "11130051", + [ + "11130039510100", + "11130039510200" + ] + ], + [ + "1113004019660100f9f91b00bac3170100000000a98b00000000", + [ + "1113003B400200" + ] + ], + [ + "1113005030750000", + [ + "1113003C500100", + "1113003C500200" + ] + ], + [ + "22020010", + [ + "2202003D1002001AFC0F42" + ] + ], + [ + "11150040ebb80100b9bd0500e5f6160000000000000000000000", + [ + "1115003F400032" + ] + ], + [ + "11150051", + [ + "11150041510100", + "11150041510200" + ] + ], + [ + "11150040ebb80100b9bd0500e5f61600000000009bc1fcff0000", + [ + "11150043400200" + ] + ], + [ + "1115005030750000", + [ + "11150044500100", + "11150044500200" + ] + ], + [ + "11150040ebb80100b9bd0500e5f61600000000009454fdff0000", + [ + "11150046400200" + ] + ], + [ + "11120040030f0100298301009b1f0f0000000000000000000000", + [ + "11120049400032" + ] + ], + [ + "11120051", + [ + "1112004B510100", + "1112004B510200" + ] + ], + [ + "22030010", + [ + "2203004C100200424FA740" + ] + ], + [ + "1114005030750000", + [ + "1114004F500100", + "1114004F500200" + ] + ], + [ + "11120040030f0100298301009b1f0f0000000000d6b900000000", + [ + "11120053400200" + ] + ], + [ + "1112005030750000", + [ + "11120054500100", + "11120054500200" + ] + ], + [ + "1108004043700100f0f2020080e29e0000000000000000000000", + [ + "1108005D400032" + ] + ], + [ + "1109004043700100f0f2020080e29e0000000000000000000000", + [ + "1109005E400032" + ] + ], + [ + "1106004043700100f0f2020080e29e0000000000000000000000", + [ + "1106005F400032" + ] + ], + [ + "1107004043700100f0f2020080e29e0000000000000000000000", + [ + "11070060400032" + ] + ], + [ + "1104004043700100f0f2020080e29e0000000000000000000000", + [ + "11040061400032" + ] + ], + [ + "1105004043700100f0f2020080e29e0000000000000000000000", + [ + "11050062400032" + ] + ], + [ + "1102004043700100f0f2020080e29e0000000000000000000000", + [ + "11020063400032" + ] + ], + [ + "1103004043700100f0f2020080e29e0000000000000000000000", + [ + "11030064400032" + ] + ], + [ + "11020051", + [ + "1102006E510100", + "1102006E510200" + ] + ], + [ + "22040010", + [ + "2204006F100200A5E60F42" + ] + ], + [ + "11150040ebb80100b9bd0500e5f6160000000000dbd8fdff0000", + [ + "11150093400200" + ] + ], + [ + "1101004000ee020000b004000010270000000000000000000000", + [ + "11010096400032" + ] + ], + [ + "11010051", + [ + "11010098510100", + "11010098510200" + ] + ], + [ + "1101004000ee020000b00400001027000000000000f6ffff0000", + [ + "1101009A400200" + ] + ], + [ + "1101005030750000", + [ + "1101009B500100", + "1101009B500200" + ] + ], + [ + "13010010", + [ + "1301009C1002000202020202020202" + ] + ], + [ + "110b0040ffaa0200ae59110021bdb131000000009d1500000000", + [ + "110B00C8400200" + ] + ], + [ + "110a0040fcad02001d6d11007766e931000000008b1500000000", + [ + "110A00C9400200" + ] + ], + [ + "110d0040feab020029601100e84ac43100000000971500000000", + [ + "110D00CA400200" + ] + ], + [ + "110c004007a30200dc251100e54e1d3100000000cd1500000000", + [ + "110C00CB400200" + ] + ], + [ + "110f0040a6ae02006f711100fcc4f53100000000871500000000", + [ + "110F00CC400200" + ] + ], + [ + "110e004083a60200883c11001f3f5e3100000000b81500000000", + [ + "110E00CD400200" + ] + ], + [ + "11110040bd97020071dc100011084b3000000000111600000000", + [ + "111100CE400200" + ] + ], + [ + "11100040649b020032f41000ed0f8f3000000000fb1500000000", + [ + "111000CF400200" + ] + ], + [ + "1000005002140000", + [ + "100000D0500100", + "100000D0500200" + ] + ], + [ + "110b004001260200d0f80d00f89a0428000000009a1500000000", + [ + "110B000C400200" + ] + ], + [ + "110a004001260200d0f80d00f89a042800000000881500000000", + [ + "110A000D400200" + ] + ], + [ + "110d004001260200d0f80d00f89a042800000000941500000000", + [ + "110D000E400200" + ] + ], + [ + "110c004001260200d0f80d00f89a042800000000ca1500000000", + [ + "110C000F400200" + ] + ], + [ + "110f0040ac6e01008b500900a5bcad1a00000000851500000000", + [ + "110F0010400200" + ] + ], + [ + "110e004001260200d0f80d00f89a042800000000b51500000000", + [ + "110E0011400200" + ] + ], + [ + "11110040ac6e01008b500900a5bcad1a000000000f1600000000", + [ + "11110012400200" + ] + ], + [ + "11100040ac6e01008b500900a5bcad1a00000000f91500000000", + [ + "11100013400200" + ] + ], + [ + "100000508e130000", + [ + "10000014500100", + "10000014500200" + ] + ], + [ + "11150040ebb80100b9bd0500e5f616000000000099d8fdff0000", + [ + "1115004F400200" + ] + ], + [ + "11010040ae060000451600001359000000000000faf5ffff0000", + [ + "11010050400200" + ] + ], + [ + "10000050f8130000", + [ + "10000051500100", + "10000051500200" + ] + ], + [ + "1101004000ee020000b004000010270000000000afe1ffff0000", + [ + "1101006F400200" + ] + ], + [ + "100000501a150000", + [ + "10000070500100", + "10000070500200" + ] + ], + [ + "1103004043700100f0f2020080e29e00000000006a1a03000000", + [ + "1103008E400200" + ] + ], + [ + "1102004043700100f0f2020080e29e00000000006a1a03000000", + [ + "1102008F400200" + ] + ], + [ + "1105004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11050090400200" + ] + ], + [ + "1104004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11040091400200" + ] + ], + [ + "1107004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11070092400200" + ] + ], + [ + "1106004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11060093400200" + ] + ], + [ + "1109004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11090094400200" + ] + ], + [ + "1108004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11080095400200" + ] + ], + [ + "10000050f01d0000", + [ + "10000096500100", + "10000096500200" + ] + ], + [ + "11150040ebb80100b9bd0500e5f61600000000006251fdff0000", + [ + "111500B5400200" + ] + ], + [ + "100000500f170000", + [ + "100000B6500100", + "100000B6500200" + ] + ], + [ + "110b0040099e020066051100ee56c03000000000e91800000000", + [ + "110B00B9400200" + ] + ], + [ + "110a004046ac020000621100b190c93100000000e91800000000", + [ + "110A00BA400200" + ] + ], + [ + "110d0040c8a202004424110084bf183100000000e91800000000", + [ + "110D00BB400200" + ] + ], + [ + "110c004011780200760e10003b12fd2d00000000e91800000000", + [ + "110C00BC400200" + ] + ], + [ + "110f0040a6ae02006f711100fcc4f53100000000e91800000000", + [ + "110F00BD400200" + ] + ], + [ + "110e0040ad8802007f7a10004980322f00000000e91800000000", + [ + "110E00BE400200" + ] + ], + [ + "111100407b4102007eab0e00795f042a00000000e91800000000", + [ + "111100BF400200" + ] + ], + [ + "11100040e2520200ac1c0f00a189482b00000000e91800000000", + [ + "111000C0400200" + ] + ], + [ + "10000050c1130000", + [ + "100000C1500100", + "100000C1500200" + ] + ], + [ + "1101004000ee020000b004000010270000000000aee1ffff0000", + [ + "1101001A400200" + ] + ], + [ + "10000050a0130000", + [ + "1000001B500100", + "1000001B500200" + ] + ], + [ + "110b004099aa000073550400856f1f0e000000007de2feff0000", + [ + "110B0058400200" + ] + ], + [ + "110a0040f8aa0000d9570400d54c270e00000000d1e1feff0000", + [ + "110A0059400200" + ] + ], + [ + "110d0040aaab00005c5c04002509360e000000008ee0feff0000", + [ + "110D005A400200" + ] + ], + [ + "110c0040d7aa0000035704007991240e000000000de2feff0000", + [ + "110C005B400200" + ] + ], + [ + "110f0040d8aa000006570400aaa6240e000000000ce2feff0000", + [ + "110F005C400200" + ] + ], + [ + "110e00403dab00009859040022032d0e0000000054e1feff0000", + [ + "110E005D400200" + ] + ], + [ + "1111004096aa00005a550400f12f1f0e0000000084e2feff0000", + [ + "1111005E400200" + ] + ], + [ + "1110004082aa0000d954040016881d0e00000000a8e2feff0000", + [ + "1110005F400200" + ] + ], + [ + "100000503f1b0000", + [ + "10000060500100", + "10000060500200" + ] + ], + [ + "12010051", + [ + "12010069510100", + "12010069510200" + ] + ], + [ + "12020040c8000000a05a0000c800000050c300000000000000", + [ + "1202007B400200" + ] + ], + [ + "12010040c8000000a05a0000c800000050c300000000000000", + [ + "1201007C400200" + ] + ], + [ + "12040040c8000000a05a0000c800000050c300000000000000", + [ + "1204007D400200" + ] + ], + [ + "12030040c8000000a05a0000c800000050c300000000000000", + [ + "1203007E400200" + ] + ], + [ + "12060040c8000000a05a0000c800000050c300000000000000", + [ + "1206007F400200" + ] + ], + [ + "12050040c8000000a05a0000c800000050c300000000000000", + [ + "12050080400200" + ] + ], + [ + "12080040c8000000a05a0000c800000050c300000000000000", + [ + "12080081400200" + ] + ], + [ + "12070040c8000000a05a0000c800000050c300000000000000", + [ + "12070082400200" + ] + ], + [ + "1000005070170000", + [ + "10000083500100", + "10000083500200" + ] + ], + [ + "12020040c800000098480000c8000000409c0000c05d000000", + [ + "12020084400200" + ] + ], + [ + "12010040c800000098480000c8000000409c0000c05d000000", + [ + "12010085400200" + ] + ], + [ + "12040040c800000098480000c8000000409c0000c05d000000", + [ + "12040086400200" + ] + ], + [ + "12030040c800000098480000c8000000409c0000c05d000000", + [ + "12030087400200" + ] + ], + [ + "12060040c800000098480000c8000000409c0000c05d000000", + [ + "12060088400200" + ] + ], + [ + "12050040c800000098480000c8000000409c0000c05d000000", + [ + "12050089400200" + ] + ], + [ + "12080040c800000098480000c8000000409c0000c05d000000", + [ + "1208008A400200" + ] + ], + [ + "12070040c800000098480000c8000000409c0000c05d000000", + [ + "1207008B400200" + ] + ], + [ + "10000050b41a0000", + [ + "1000008C500100", + "1000008C500200" + ] + ], + [ + "12020040c8000000a05a0000c800000050c30000c05d000001", + [ + "1202008D400200" + ] + ], + [ + "12010040c8000000a05a0000c800000050c30000c05d000001", + [ + "1201008E400200" + ] + ], + [ + "12040040c8000000a05a0000c800000050c30000c05d000001", + [ + "1204008F400200" + ] + ], + [ + "12030040c8000000a05a0000c800000050c30000c05d000001", + [ + "12030090400200" + ] + ], + [ + "12060040c8000000a05a0000c800000050c30000c05d000001", + [ + "12060091400200" + ] + ], + [ + "12050040c8000000a05a0000c800000050c30000c05d000001", + [ + "12050092400200" + ] + ], + [ + "12080040c8000000a05a0000c800000050c30000c05d000001", + [ + "12080093400200" + ] + ], + [ + "12070040c8000000a05a0000c800000050c30000c05d000001", + [ + "12070094400200" + ] + ], + [ + "12020040c800000098480000c8000000409c00000000000001", + [ + "12020096400200" + ] + ], + [ + "12010040c800000098480000c8000000409c00000000000001", + [ + "12010097400200" + ] + ], + [ + "12040040c800000098480000c8000000409c00000000000001", + [ + "12040098400200" + ] + ], + [ + "12030040c800000098480000c8000000409c00000000000001", + [ + "12030099400200" + ] + ], + [ + "12060040c800000098480000c8000000409c00000000000001", + [ + "1206009A400200" + ] + ], + [ + "12050040c800000098480000c8000000409c00000000000001", + [ + "1205009B400200" + ] + ], + [ + "12080040c800000098480000c8000000409c00000000000001", + [ + "1208009C400200" + ] + ], + [ + "12070040c800000098480000c8000000409c00000000000001", + [ + "1207009D400200" + ] + ], + [ + "100000505b1a0000", + [ + "1000009E500100", + "1000009E500200" + ] + ], + [ + "110b004066aa0200ca551100fcc4f53100000000e91800000000", + [ + "110B0032400200" + ] + ], + [ + "110a0040e0ab0200655f1100fcc4f53100000000e91800000000", + [ + "110A0033400200" + ] + ], + [ + "110d0040a6ae02006f711100fcc4f53100000000e91800000000", + [ + "110D0034400200" + ] + ], + [ + "110c00405cab02000c5c1100fcc4f53100000000e91800000000", + [ + "110C0035400200" + ] + ], + [ + "110f00405eab02001a5c1100fcc4f53100000000e91800000000", + [ + "110F0036400200" + ] + ], + [ + "110e0040f3ac020060661100fcc4f53100000000e91800000000", + [ + "110E0037400200" + ] + ], + [ + "1111004056aa020066551100fcc4f53100000000e91800000000", + [ + "11110038400200" + ] + ], + [ + "1110004007aa020064531100fcc4f53100000000e91800000000", + [ + "11100039400200" + ] + ], + [ + "10000050eb150000", + [ + "1000003A500100", + "1000003A500200" + ] + ], + [ + "12020040c8000000e8000000c800000010270000e001000001", + [ + "1202003B400200" + ] + ], + [ + "12010040c8000000e8000000c800000010270000e001000001", + [ + "1201003C400200" + ] + ], + [ + "12040040c8000000e8000000c800000010270000e001000001", + [ + "1204003D400200" + ] + ], + [ + "12030040c8000000e8000000c800000010270000e001000001", + [ + "1203003E400200" + ] + ], + [ + "12060040c8000000e8000000c800000010270000e001000001", + [ + "1206003F400200" + ] + ], + [ + "12050040c8000000e8000000c800000010270000e001000001", + [ + "12050040400200" + ] + ], + [ + "12080040c8000000e8000000c800000010270000e001000001", + [ + "12080041400200" + ] + ], + [ + "12070040c8000000e8000000c800000010270000e001000001", + [ + "12070042400200" + ] + ], + [ + "10000050951e0000", + [ + "10000043500100", + "10000043500200" + ] + ], + [ + "110b0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110B00D5400200" + ] + ], + [ + "110a0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110A00D6400200" + ] + ], + [ + "110d0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110D00D7400200" + ] + ], + [ + "110c0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110C00D8400200" + ] + ], + [ + "110f0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110F00D9400200" + ] + ], + [ + "110e0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110E00DA400200" + ] + ], + [ + "11110040a6ae02006f711100fcc4f53100000000542200000000", + [ + "111100DB400200" + ] + ], + [ + "11100040a6ae02006f711100fcc4f53100000000542200000000", + [ + "111000DC400200" + ] + ], + [ + "10000050e6130000", + [ + "100000DD500100", + "100000DD500200" + ] + ], + [ + "11010040360000005d01000024e7030000000000aee1ffff0000", + [ + "110100FB400200" + ] + ], + [ + "110b00400aaa020075531100e9e79f31000000009d1500000000", + [ + "110B00FC400200" + ] + ], + [ + "110a0040cfad0200fc6b11006d28e631000000008b1500000000", + [ + "110A00FD400200" + ] + ], + [ + "110d00404cab0200a25b1100c052b73100000000971500000000", + [ + "110D00FE400200" + ] + ], + [ + "110c0040fb9f02000c1211003491e43000000000cd1500000000", + [ + "110C00FF400200" + ] + ], + [ + "110e004062a40200aa2e11002387363100000000b81500000000", + [ + "110E0002400200" + ] + ], + [ + "11110040bc91020063b51000b32bdb2f00000000111600000000", + [ + "11110003400200" + ] + ], + [ + "11100040589602005dd31000c608313000000000fb1500000000", + [ + "11100004400200" + ] + ], + [ + "10000050f5130000", + [ + "10000005500100", + "10000005500200" + ] + ], + [ + "110a0040513b0000bd540000634f030000000000452300000000", + [ + "110A0023400200" + ] + ], + [ + "110c0040343a000026530000793f030000000000452300000000", + [ + "110C0024400200" + ] + ], + [ + "110b0040033b00004e5400000c4b030000000000452300000000", + [ + "110B0025400200" + ] + ], + [ + "110e00408f3a0000a75300008944030000000000452300000000", + [ + "110E0026400200" + ] + ], + [ + "110d00401d3b0000735400007f4c030000000000452300000000", + [ + "110D0027400200" + ] + ], + [ + "111000406d3900000a5200006134030000000000452300000000", + [ + "11100028400200" + ] + ], + [ + "110f0040623b0000d65400005a50030000000000452300000000", + [ + "110F0029400200" + ] + ], + [ + "11120040030f0100298301009b1f0f00000000008df800000000", + [ + "1112002A400200" + ] + ], + [ + "111100400e39000082510000132f030000000000452300000000", + [ + "1111002B400200" + ] + ], + [ + "1000005018170000", + [ + "1000002C500100", + "1000002C500200" + ] + ], + [ + "11140040415d000030b30100000000000000000061ffffff0000", + [ + "1114004A400200" + ] + ], + [ + "10000050d4130000", + [ + "1000004B500100", + "1000004B500200" + ] + ], + [ + "1113004019660100f9f91b00bac3170100000000398800000000", + [ + "1113004C400200" + ] + ], + [ + "10000050fc130000", + [ + "1000004D500100", + "1000004D500200" + ] + ] + ] + } +} diff --git a/pylabrobot/beckman_coulter/biomek_i7/design.md b/pylabrobot/beckman_coulter/biomek_i7/design.md new file mode 100644 index 00000000000..6f5de098859 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/design.md @@ -0,0 +1,28 @@ +# How the Biomek i7 integration is built + +The patterns this driver follows. It follows the STAR's (`pylabrobot/hamilton/star/design.md`, +P1-P20); this says only where the Biomek differs or adds something. + +## What makes the Biomek different + +A STAR takes operations ("pick up tips here") and plans the motion itself. A Biomek's boards take +one axis at a time, in encoder counts. Three layers of Beckman software sit between a method and the +boards: **Biomek** (the application) plans operations, safe heights, collisions and liquid handling; +**the Master Controller** (MC) takes host commands in counts (`AM`, `HM`, `LT`...), coordinates each +pod's axes and keeps their positions; **the ACE boards** (a chassis and one per pod) take +single-axis commands over USB. This driver replaces the top two and talks to the boards directly. + +| Layer | What it reproduces | Where | +|---|---|---| +| L1 wire | the ACE messages | `driver/framing.py`, `board.py`, `protocol.py` | +| L2 board commands | one board request each | `_unchecked_fw_*` on the pods and chassis | +| L3 MC | one MC host command each | the pods' public primitives, `driver/recipes/` | +| L4 planning | Biomek's planning | `driver/motion.py`, `pod_geometry.py`, `liquid.py` (no I/O) | +| L5 PyLabRobot | the PLR API | `device.py`, the operation features, `resource_model/` | + +Each layer calls only the one below it. + +**I1. The boards say what is fitted.** `discover()` (read-only) asks each board its module type and +side; that places it, not the USB serial number or the enumeration order. An unknown type or side, +two boards claiming one place, or no chassis is refused. `driver/simulator.py` simulates the boards +at the wire, answering identity reads from a recording of a real instrument's. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/driver/__init__.py new file mode 100644 index 00000000000..582f4e5646a --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/__init__.py @@ -0,0 +1 @@ +"""The Biomek i7's ACE boards: framing, messages, and the boards themselves.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/board.py b/pylabrobot/beckman_coulter/biomek_i7/driver/board.py new file mode 100644 index 00000000000..1eddc8fdfd7 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/board.py @@ -0,0 +1,292 @@ +"""One ACE board: its USB link, its sequence numbers, and the replies it sends back. + +A Biomek i7 has one ACE board per module (the chassis, and one per arm), each its own USB device +(VID 0x0AB5, PID 0xACE0). A board accepts many requests at once and answers them in whatever +order they finish, so replies are matched to requests by their header, not by order. Moves and +homes answer twice, ACCEPTED when they start and DONE when they finish. The board also sends +messages nobody asked for, with sequence 0; those go to subscribers. + +When a Move All fails, the axes that failed answer with the Move All's sequence under their own +device and index, before the Move All's own DONE; those replies are kept with the Move All and +raised with it. +""" + +import asyncio +import logging +from dataclasses import dataclass, field, replace +from typing import Callable, Dict, List, Optional, Sequence, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import FrameError, ace_error +from pylabrobot.beckman_coulter.biomek_i7.driver.framing import IN_PACKET_SIZE, FrameReader, pack +from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import ( + SAGIAN_CAN, + Reply, + Request, + Status, + describe_routine_unsolicited, + describe_sagian_can, +) +from pylabrobot.io.usb import USB + +logger = logging.getLogger(__name__) + +ACE_VENDOR_ID = 0x0AB5 +ACE_PRODUCT_ID = 0xACE0 +ACE_READ_ENDPOINT = 0x81 +ACE_WRITE_ENDPOINT = 0x02 + +UnsolicitedCallback = Callable[[Reply], None] + + +@dataclass +class _Pending: + request: Request + done: "asyncio.Future[Reply]" + accepted: "asyncio.Future[Reply]" + related: List[Reply] = field(default_factory=list) + + +class AceBoard: + """The link to one ACE board.""" + + def __init__( + self, + serial_number: Optional[str] = None, + device_address: Optional[int] = None, + io: Optional[USB] = None, + name: str = "Biomek i7 ACE board", + default_timeout: float = 10.0, + ): + """ + Args: + serial_number: the board's USB serial number. With neither it nor `device_address`, the + first ACE board found is used. + device_address: the board's USB address, an alternative to the serial number. + io: a transport to use instead of opening the USB device; for tests and simulators. + name: what logs and errors call this board. + default_timeout: seconds to wait for a request's final reply when the caller gives none. + """ + self.name = name + self.usb_serial_number = serial_number + self.default_timeout = default_timeout + self.io = io or USB( + id_vendor=ACE_VENDOR_ID, + id_product=ACE_PRODUCT_ID, + human_readable_device_name=name, + serial_number=serial_number, + device_address=device_address, + read_endpoint_address=ACE_READ_ENDPOINT, + write_endpoint_address=ACE_WRITE_ENDPOINT, + zero_length_packets=False, + packet_read_timeout=0.5, + ) + self._frames = FrameReader() + self._pending: Dict[Tuple[int, int, int, int], _Pending] = {} + self._sequence = 0 + self._write_lock = asyncio.Lock() + self._reader: Optional["asyncio.Task[None]"] = None + self._subscribers: List[UnsolicitedCallback] = [] + + # -- lifecycle ------------------------------------------------------------- + + async def setup(self) -> None: + """Open the board and start reading its replies.""" + await self.io.setup() + self._frames.reset() + self._reader = asyncio.create_task(self._read_loop(), name=f"{self.name} reader") + + async def stop(self) -> None: + """Stop reading, fail every request still waiting, and release the board.""" + if self._reader is not None: + self._reader.cancel() + try: + await self._reader + except asyncio.CancelledError: + pass + self._reader = None + self._fail_pending(ConnectionError(f"{self.name} stopped")) + await self.io.stop() + + @property + def connected(self) -> bool: + return self._reader is not None and not self._reader.done() + + def subscribe(self, callback: UnsolicitedCallback) -> Callable[[], None]: + """Call `callback` with every message the board sends unasked. Returns an unsubscribe.""" + self._subscribers.append(callback) + return lambda: self._subscribers.remove(callback) + + # -- requests -------------------------------------------------------------- + + async def send(self, request: Request, timeout: Optional[float] = None) -> Reply: + """Send one request and return its final reply. + + Raises: + AceError: if the board reports an error. + TimeoutError: if no final reply arrives within `timeout` seconds. + """ + return (await self.send_many([request], timeout=timeout))[0] + + async def send_many( + self, + requests: Sequence[Request], + timeout: Optional[float] = None, + raise_errors: bool = True, + ) -> List[Reply]: + """Send requests together, packed into as few transfers as fit, and return their final + replies in request order. Every request is waited for before any error is raised; the first + error in request order is raised. + + Args: + requests: the requests, sent in this order. + timeout: seconds to wait for every final reply. Defaults to `default_timeout`. + raise_errors: when False, replies that report an error are returned instead of raised, for + a caller that decides on them (such as a move refused because the axis is not homed). + + Raises: + AceError: if `raise_errors` and the board reports an error for any of them. + TimeoutError: if any final reply does not arrive within `timeout` seconds. + """ + if not self.connected: + raise ConnectionError(f"{self.name} is not set up") + timeout = self.default_timeout if timeout is None else timeout + loop = asyncio.get_running_loop() + entries: List[Tuple[Tuple[int, int, int, int], _Pending]] = [] + messages = [] + for request in requests: + sequence = self._next_sequence() + key = (request.device, request.index, sequence, request.opcode) + entry = _Pending(request, loop.create_future(), loop.create_future()) + self._pending[key] = entry + entries.append((key, entry)) + messages.append(request.encode(sequence)) + try: + async with self._write_lock: + for message in messages: # one line per message, unframed, as Biomek's `ace_io` logs them + logger.debug("%s write %s", self.name, message.hex()) + for transfer in pack(messages): + await self.io.write(transfer) + done, not_done = await asyncio.wait([e.done for _, e in entries], timeout=timeout) + if not_done: + late = [str(e.request) for _, e in entries if not e.done.done()] + raise TimeoutError(f"{self.name}: no reply within {timeout} s to {', '.join(late)}") + replies = [replace(e.done.result(), related=tuple(e.related)) for _, e in entries] + if raise_errors: + for (_, entry), reply in zip(entries, replies): + self._raise_for(entry, reply) + return replies + finally: + for key, entry in entries: + self._pending.pop(key, None) + for future in (entry.done, entry.accepted): + if not future.done(): + future.cancel() + + def _raise_for(self, entry: _Pending, reply: Reply) -> None: + """Raise the reply's error, with the errors of the axes a failed Move All names.""" + if reply.error_code is None: + return + error = ace_error( + reply.error_code, reply.device_error, str(entry.request), reply.device, reply.index + ) + causes = [r for r in entry.related if r.error_code is not None] + if causes: + error.axis_errors = [ + ace_error( + r.error_code or 0, + r.device_error, + f"device 0x{r.device:02X} index {r.index}", + r.device, + r.index, + ) + for r in causes + ] + error.args = (str(error) + "; " + "; ".join(str(e) for e in error.axis_errors),) + raise error + + def _next_sequence(self) -> int: + """The next free sequence number, 1-255 then 1 again; 0 is the board's own.""" + in_use = {key[2] for key in self._pending} + for _ in range(255): + self._sequence = self._sequence % 255 + 1 + if self._sequence not in in_use: + return self._sequence + raise RuntimeError(f"{self.name}: all 255 sequence numbers are waiting for replies") + + # -- replies --------------------------------------------------------------- + + async def _read_loop(self) -> None: + while True: + try: + data = await self.io.read(timeout=1, size=IN_PACKET_SIZE) + except TimeoutError: + continue + except asyncio.CancelledError: + raise + except Exception as e: # the link is gone; nobody will answer what is waiting + logger.error("%s: read failed: %s", self.name, e) + self._fail_pending(ConnectionError(f"{self.name}: read failed: {e}")) + return + try: + messages = self._frames.feed(data) + except FrameError as e: + logger.error("%s: %s", self.name, e) + continue + for message in messages: + self._dispatch(message) + + def _dispatch(self, message: bytes) -> None: + logger.debug("%s read %s", self.name, message.hex()) + try: + reply = Reply.parse(message) + except ValueError as e: + logger.error("%s: %s", self.name, e) + return + if reply.unsolicited: + self._deliver_unsolicited(reply) + return + entry = self._pending.get(reply.key) + if entry is None: + related = self._pending_with_sequence(reply.sequence, reply.opcode) + if related is not None: + related.related.append(reply) + else: + logger.warning("%s: reply to no waiting request: %s", self.name, message.hex()) + return + if reply.status == Status.ACCEPTED and reply.error_code is None: + if not entry.accepted.done(): + entry.accepted.set_result(reply) + return + if not entry.done.done(): + entry.done.set_result(reply) + + def _pending_with_sequence(self, sequence: int, opcode: int) -> Optional[_Pending]: + for key, entry in self._pending.items(): + if key[2] == sequence and key[3] == opcode: + return entry + return None + + def _deliver_unsolicited(self, reply: Reply) -> None: + if (reply.device, reply.opcode) == SAGIAN_CAN: + # A message the board saw on its SAGIAN CAN bus, passed up: normal when a success or a + # request (see `describe_sagian_can`), flagged otherwise. + text, normal = describe_sagian_can(reply.data) + if normal: + logger.debug("%s: SAGIAN CAN %s (forwarded, normal)", self.name, text) + else: + logger.info("%s: SAGIAN CAN %s: a status not seen in normal operation", self.name, text) + elif (routine := describe_routine_unsolicited(reply)) is not None: + logger.debug("%s: %s (routine)", self.name, routine) + elif reply.status in (Status.EMERGENCY, Status.EVENT) or reply.error_code is not None: + logger.info("%s: unsolicited %s", self.name, reply) + for callback in list(self._subscribers): + try: + callback(reply) + except Exception: + logger.exception("%s: subscriber failed on %s", self.name, reply) + + def _fail_pending(self, error: Exception) -> None: + for entry in self._pending.values(): + if not entry.done.done(): + entry.done.set_exception(error) + self._pending.clear() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/board_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/board_tests.py new file mode 100644 index 00000000000..f625baa7680 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/board_tests.py @@ -0,0 +1,183 @@ +"""AceBoard against a fake board: matching, two-stage replies, unsolicited messages, errors.""" + +import asyncio +import unittest +from typing import Callable, List, Optional + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import ( + InterlockTrippedError, + MotionError, + NotHomedError, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.framing import frame, split +from pylabrobot.io.usb import USB + +Handler = Callable[[bytes], List[bytes]] + + +def done(request: bytes, payload: bytes = b"") -> bytes: + return request[:5] + b"\x02\x00" + payload + + +def accepted(request: bytes) -> bytes: + return request[:5] + b"\x01\x00" + + +def recorder(into: List[bytes], answer: Handler = lambda m: []) -> Handler: + """A handler that keeps every request in `into`, then answers with `answer`.""" + + def handler(message: bytes) -> List[bytes]: + into.append(message) + return answer(message) + + return handler + + +def answer_done(message: bytes) -> List[bytes]: + return [done(message)] + + +class FakeAceUSB(USB): + """A board on the far side of the USB link: records transfers, answers through `handler`, and + sends replies in 16-byte packets as a board does.""" + + def __init__(self, handler: Optional[Handler] = None): + super().__init__(0x0AB5, 0xACE0, "fake ACE board") + self.handler: Handler = handler or answer_done + self.transfers: List[bytes] = [] + self._packets: "asyncio.Queue[bytes]" = asyncio.Queue() + + async def setup(self, empty_buffer=True): + pass + + async def stop(self): + pass + + async def write(self, data: bytes, timeout: Optional[float] = None): + self.transfers.append(data) + for message in split(data): + for reply in self.handler(message): + self.push(reply) + + def push(self, message: bytes) -> None: + framed = frame(message) + for i in range(0, len(framed), 16): + self._packets.put_nowait(framed[i : i + 16]) + + async def read(self, timeout=None, size=None, endpoint=None) -> bytes: + try: + return await asyncio.wait_for(self._packets.get(), timeout=0.01) + except asyncio.TimeoutError: + raise TimeoutError("no packet") from None + + +class BoardTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + self.usb = FakeAceUSB() + self.board = AceBoard(io=self.usb, default_timeout=1) + await self.board.setup() + + async def asyncTearDown(self) -> None: + await self.board.stop() + + async def test_simple_request(self) -> None: + self.usb.handler = lambda m: [done(m, b"\x80\x00")] + reply = await self.board.send(p.get_module_id()) + self.assertEqual(p.parse_module_id(reply.payload).type, "chassis") + self.assertEqual(self.usb.transfers, [frame(p.get_module_id().encode(1))]) + + async def test_replies_out_of_order_match_their_requests(self) -> None: + held: List[bytes] = [] + self.usb.handler = recorder(held) + task = asyncio.create_task( + self.board.send_many([p.get_current_position(p.Device.MOTOR, axis) for axis in range(1, 9)]) + ) + while len(held) < 8: + await asyncio.sleep(0) + for message in reversed(held): + self.usb.push(done(message, message[1].to_bytes(4, "little"))) + replies = await task + self.assertEqual([p.parse_s32(r.payload) for r in replies], list(range(1, 9))) + self.assertEqual(len(self.usb.transfers), 1) # packed together + + async def test_two_stage_reply_waits_for_done(self) -> None: + held: List[bytes] = [] + self.usb.handler = recorder(held, lambda m: [accepted(m)]) + task = asyncio.create_task(self.board.send(p.move_all(5000))) + await asyncio.sleep(0.05) + self.assertFalse(task.done()) + self.usb.push(done(held[0])) + self.assertEqual((await task).status, p.Status.DONE) + + async def test_unsolicited_messages_go_to_subscribers_between_replies(self) -> None: + seen: List[p.Reply] = [] + self.board.subscribe(seen.append) + host_alive = bytes.fromhex("0000000040FE00") + emcy = bytes.fromhex("0000000031FF007E0010013704110000") + self.usb.handler = lambda m: [host_alive, emcy, done(m)] + await self.board.send(p.get_module_serial_number()) + await asyncio.sleep(0.05) + self.assertEqual([(r.device, r.opcode) for r in seen], [p.HOST_ALIVE, p.EMCY]) + self.assertEqual(p.parse_emcy(seen[1].data).device_error, 0x0437) + + async def test_error_status_raises(self) -> None: + self.usb.handler = lambda m: [m[:5] + b"\x00\x32"] + with self.assertRaises(NotHomedError): + await self.board.send(p.set_motor_move_parameters(1, 0, 1, 1, 1)) + + async def test_failed_move_all_raises_with_its_axes(self) -> None: + def handler(m: bytes) -> List[bytes]: + axis = bytes([0x11, 0x0A, 0x00, m[3], 0x50, 0x02, 0x3C, 0x00, 0x01, 0x00, 0x00]) + return [accepted(m), axis, m[:5] + b"\x02\x38"] + + self.usb.handler = handler + with self.assertRaises(MotionError) as ctx: + await self.board.send(p.move_all(5000)) + self.assertEqual([e.device_error for e in ctx.exception.axis_errors], [0x100]) + self.assertIn("motion error window exceeded", str(ctx.exception)) + + async def test_interlock_on_completion(self) -> None: + self.usb.handler = lambda m: [accepted(m), m[:5] + b"\x02\x0f\x07\x04\x00\x00"] + with self.assertRaises(InterlockTrippedError) as ctx: + await self.board.send(p.move(1, 30000)) + self.assertEqual(ctx.exception.device_error, 0x407) + + async def test_timeout_releases_the_sequence(self) -> None: + self.usb.handler = lambda m: [] + with self.assertRaises(TimeoutError): + await self.board.send(p.get_module_id(), timeout=0.05) + self.assertEqual(self.board._pending, {}) + + async def test_sequence_wraps_past_zero_and_skips_waiting_ones(self) -> None: + self.board._sequence = 254 + seen_requests: List[bytes] = [] + self.usb.handler = recorder(seen_requests, lambda m: [done(m)]) + for _ in range(3): + await self.board.send(p.get_module_id()) + self.assertEqual([m[3] for m in seen_requests], [255, 1, 2]) + + held: List[bytes] = [] + self.usb.handler = recorder(held) + waiting = asyncio.create_task(self.board.send(p.get_module_id())) # takes 3 + await asyncio.sleep(0) + self.board._sequence = 2 + self.usb.handler = recorder(seen_requests, lambda m: [done(m)]) + await self.board.send(p.get_module_serial_number()) + self.assertEqual(seen_requests[-1][3], 4) + self.usb.push(done(held[0])) + await waiting + + async def test_stop_fails_waiting_requests(self) -> None: + self.usb.handler = lambda m: [] + task = asyncio.create_task(self.board.send(p.get_module_id())) + await asyncio.sleep(0.02) + await self.board.stop() + with self.assertRaises(ConnectionError): + await task + await self.board.setup() # so tearDown can stop it again + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py new file mode 100644 index 00000000000..892bf89baeb --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py @@ -0,0 +1,69 @@ +"""What the driver knows about an instrument: facts only (STAR design.md P3). + +What the boards answer about themselves at setup: each module's identity, its boards with their +application images and versions, and the names of its inputs and outputs (`ModuleConfiguration`, +`BoardInfo`). +""" + +from dataclasses import dataclass, field +from typing import Dict, List, Optional + +from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import HardwareVersion, ModuleId + +# The firmware this driver has been run against (one instrument, 2026-10-24 through 2026-11-10): +# every motion board and module the same image, and the other boards' application versions +# (chassis 0.2.4, SAGIAN Motion 0.3.14, LLS 0.7.8, syringe pump 5.0.9). The Master Controller +# flashes the boards when it brings other firmware, which would change what the boards answer. +TESTED_FIRMWARE_IMAGES = {(0x6D2DDB78, 266436)} +TESTED_APPLICATION_VERSIONS = {"0.2.4", "0.3.14", "0.7.8", "5.0.9"} + + +@dataclass +class BoardInfo: + """One board inside a module, as the module reports it.""" + + index: int + hardware: HardwareVersion + serial_number: Optional[str] = None + application_version: Optional[str] = None + application_crc: Optional[int] = None + application_length: Optional[int] = None + + +@dataclass +class ModuleConfiguration: + """One ACE module (the chassis, or an arm): its identity, its boards, and its inputs.""" + + module_id: ModuleId + usb_serial_number: Optional[str] + serial_number: str + hardware: HardwareVersion + application_crc: int + application_length: int + device_counts: Dict[int, int] + boards: List[BoardInfo] = field(default_factory=list) + analog_inputs: Dict[int, str] = field(default_factory=dict) + analog_units: Dict[int, str] = field(default_factory=dict) + digital_inputs: Dict[int, str] = field(default_factory=dict) + digital_outputs: Dict[int, str] = field(default_factory=dict) + + def untested_firmware(self) -> List[str]: + """What this module runs that the driver has not been run against: one line per image or + version, empty when everything is tested.""" + found = [] + if (self.application_crc, self.application_length) not in TESTED_FIRMWARE_IMAGES: + found.append( + f"module image CRC {self.application_crc:#010x}, {self.application_length} bytes" + ) + for b in self.boards: + image = (b.application_crc, b.application_length) + if b.application_crc is not None and image not in TESTED_FIRMWARE_IMAGES: + found.append( + f"board {b.index} image CRC {b.application_crc:#010x}, {b.application_length} bytes" + ) + if ( + b.application_version is not None + and b.application_version not in TESTED_APPLICATION_VERSIONS + ): + found.append(f"board {b.index} application {b.application_version}") + return found diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py b/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py new file mode 100644 index 00000000000..dfe7c096599 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py @@ -0,0 +1,141 @@ +"""Biomek i7 error types, and the reply bytes that raise them.""" + +from typing import Dict, List, Mapping, Optional, Tuple + +# ACE error codes, the byte after a reply's status. The Master Controller names more, but their +# numbers are not guessed. +ACE_ERROR_NAMES: Dict[int, str] = { + 0x0F: "interlock tripped", + 0x30: "motion device not configured", + 0x31: "motion device not enabled", + 0x32: "motion device not homed", + 0x38: "coordinated motion failed", + 0x3C: "motion error window exceeded", +} + +# Device error codes: the drive's own reason, after the ACE error code of a failed move, and in an +# EMCY message. Each one here was seen in a reply or an EMCY message. +DEVICE_ERROR_NAMES: Dict[int, str] = { + 0x0100: "motion error window exceeded", + 0x0407: "interlock tripped", + 0x0416: "interlock active", + 0x0431: "servo home aborted", + 0x0437: "stepper glitch", +} + + +class FrameError(Exception): + """Bytes from a board that do not split into whole frames.""" + + +class AceError(Exception): + """A board refused a command or reported that it failed. + + Attributes: + code: the ACE error code. + device_error: the drive's own error code, when the reply carries one. + request: a short description of the command that failed. + axis_errors: for a failed Move All, the errors the axes that failed reported. + """ + + def __init__( + self, + code: int, + device_error: Optional[int], + request: str, + device: Optional[int] = None, + index: Optional[int] = None, + ): + self.code = code + self.device_error = device_error + self.request = request + # The device and index the reply came from, when known: which axis failed. + self.device = device + self.index = index + self.axis_errors: List["AceError"] = [] + self.reason = ACE_ERROR_NAMES.get(code, f"ACE error 0x{code:02X}") + name = ACE_ERROR_NAMES.get(code, f"ACE error 0x{code:02X}") + detail = "" + if device_error is not None: + device_name = DEVICE_ERROR_NAMES.get(device_error) + detail = f" (device error 0x{device_error:X}" + (f": {device_name})" if device_name else ")") + super().__init__(f"{request}: {name}{detail}") + + +class InterlockTrippedError(AceError): + """The interlock tripped (light curtain broken, or tripped by the host), so the board stopped or + refused the move.""" + + +class NotConfiguredError(AceError): + """The axis has no motor table loaded: the board was powered up, or the drive lost its + parameters, since the last Configure.""" + + +class NotEnabledError(AceError): + """The axis is configured but disabled (Set State ENABLED has not been sent since).""" + + +class NotHomedError(AceError): + """The axis has not been homed since the board started.""" + + +class MotionError(AceError): + """A move did not complete: the axis left its error window, or a coordinated move failed.""" + + +# The ACE error a board answers when the interlock is tripped. +INTERLOCK_TRIPPED_CODE = 0x0F + +_ERROR_CLASSES = { + INTERLOCK_TRIPPED_CODE: InterlockTrippedError, + 0x30: NotConfiguredError, + 0x31: NotEnabledError, + 0x32: NotHomedError, + 0x38: MotionError, + 0x3C: MotionError, +} + + +def ace_error( + code: int, + device_error: Optional[int], + request: str, + device: Optional[int] = None, + index: Optional[int] = None, +) -> AceError: + """Build the exception for an ACE error code.""" + return _ERROR_CLASSES.get(code, AceError)(code, device_error, request, device, index) + + +# The errors the Master Controller reports as one axis's motion failing (not enabled, homing failed, operational parameters exceeded, error window exceeded, framing +# error, controller error; only those with a known number here). +_MOTION_FAILED_CODES = {0x31, 0x3C} +COORDINATED_MOTION_FAILED_CODE = 0x38 + + +def english(error: AceError, axis_names: Mapping[Tuple[int, int], str]) -> str: + """What the Master Controller replies for a command that failed with `error`, as its logs show + it, with each axis named by `axis_names` ((device, index) -> + name): + + - not homed: "The instrument needs to be homed."; + - interlock tripped: "A light curtain violation has occurred."; + - a coordinated move failed: "The motion failed: ." for each axis that reported; + - an axis's own motion error: the same, for that axis; + - anything else: " failed: ". + """ + + def motion_failed(e: AceError) -> str: + name = axis_names.get((e.device, e.index)) if e.device is not None else None # type: ignore[arg-type] + return f"The {name or e.request} motion failed: {e.reason}." + + if isinstance(error, NotHomedError): + return "The instrument needs to be homed." + if isinstance(error, InterlockTrippedError): + return "A light curtain violation has occurred." + if error.code == COORDINATED_MOTION_FAILED_CODE and error.axis_errors: + return " ".join(motion_failed(e) for e in error.axis_errors) + if error.code in _MOTION_FAILED_CODES and error.device is not None: + return motion_failed(error) + return f"{error.request} failed: {error.reason}." diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/errors_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/errors_tests.py new file mode 100644 index 00000000000..fa88302e947 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/errors_tests.py @@ -0,0 +1,41 @@ +"""Board errors as the Master Controller words them in its replies, as its logs show them.""" + +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import ace_error, english + +NAMES = {(0x11, 1): "left X", (0x11, 3): "left Z"} + + +class EnglishTests(unittest.TestCase): + def test_not_homed_and_interlock(self) -> None: + self.assertEqual( + english(ace_error(0x32, None, "Set X Move Parameters"), NAMES), + "The instrument needs to be homed.", + ) + self.assertEqual( + english(ace_error(0x0F, None, "Move All"), NAMES), + "A light curtain violation has occurred.", + ) + + def test_a_coordinated_move_names_each_axis_that_failed(self) -> None: + error = ace_error(0x38, None, "Move All", 0x10, 0) + error.axis_errors = [ + ace_error(0x3C, 0x0100, "device 0x11 index 1", 0x11, 1), + ace_error(0x3C, None, "device 0x11 index 3", 0x11, 3), + ] + self.assertEqual( + english(error, NAMES), + "The left X motion failed: motion error window exceeded. " + "The left Z motion failed: motion error window exceeded.", + ) + + def test_an_axis_error_and_anything_else(self) -> None: + self.assertEqual( + english(ace_error(0x31, None, "Move", 0x11, 1), NAMES), + "The left X motion failed: motion device not enabled.", + ) + self.assertEqual( + english(ace_error(0x0A, None, "Get Tip Status"), NAMES), + "Get Tip Status failed: ACE error 0x0A.", + ) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py new file mode 100644 index 00000000000..fc83f97406e --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py @@ -0,0 +1 @@ +"""What a Biomek i7 is fitted with: the chassis, and a pod per side (`pod.py`, STAR's X-arm).""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py new file mode 100644 index 00000000000..df4974fd77a --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py @@ -0,0 +1,67 @@ +"""The chassis module: its inputs and outputs, the legacy deck devices it lists, and the interlock's +state.""" + +from typing import Dict, List, Optional + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ModuleConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( + read_analog_inputs, + read_module, +) + + +class Chassis: + """The chassis's ACE module. Reached as `driver.chassis`.""" + + def __init__(self, board: AceBoard): + self.board = board + self.configuration: Optional[ModuleConfiguration] = None + + async def discover(self) -> ModuleConfiguration: + """Read what the chassis says about itself. Moves nothing.""" + self.configuration = await read_module(self.board) + return self.configuration + + def _require_configuration(self) -> ModuleConfiguration: + if self.configuration is None: + raise RuntimeError("the chassis has not been read; call `discover()` or `setup()` first") + return self.configuration + + async def request_analog_inputs(self) -> Dict[str, float]: + """Every analog input (supply voltages, temperature...) by name, in its units.""" + return await read_analog_inputs(self.board, self._require_configuration()) + + async def request_digital_inputs(self) -> Dict[str, int]: + config = self._require_configuration() + replies = await self.board.send_many( + [p.read_input_output(p.Device.DIGITAL_INPUT, i) for i in config.digital_inputs] + ) + return {config.digital_inputs[i]: r.payload[0] for i, r in zip(config.digital_inputs, replies)} + + async def request_digital_outputs(self) -> Dict[str, int]: + config = self._require_configuration() + replies = await self.board.send_many( + [p.read_input_output(p.Device.DIGITAL_OUTPUT, i) for i in config.digital_outputs] + ) + return { + config.digital_outputs[i]: r.payload[0] for i, r in zip(config.digital_outputs, replies) + } + + async def request_legacy_alp_devices(self) -> List[bytes]: + """The legacy ALP devices the chassis lists, as the raw entries it answers.""" + payload = (await self.board.send(p.list_legacy_alp_devices())).payload + return [payload[i : i + 2] for i in range(0, len(payload), 2)] + + # -- interlock ------------------------------------------------------------- + # The interlock cuts the arms' drive power when the light curtain is broken or the host trips it; + # nothing moves while it is tripped. Here it is only read. + + async def request_interlock_state(self) -> p.InterlockState: + """`armed` (the drives may have power) or `tripped`. Moves nothing. + + Biomek's logs never show the Master Controller sending Get Interlock Status. The request only + reads the state; it changes nothing. + """ + return p.parse_interlock_status((await self.board.send(p.get_interlock_status())).payload) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py new file mode 100644 index 00000000000..d23b667f1fa --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -0,0 +1,77 @@ +"""One pod: an arm on the shared X rail, and its ACE module.""" + +from typing import Dict, Literal, Optional, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ModuleConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( + read_analog_inputs, + read_module, +) + +# How Biomek numbers its pods. Pod1 is the left pod and Pod2 the right on the instrument this +# driver was written against; whether that holds on every build is not established. +POD_NUMBERS = {"left": 1, "right": 2} +COMPONENT_PREFIXES = {"multichannel": "MC", "span8": "SPAN8"} + +# The arm board's analog input carrying the interlocked motor supply ("+36V Interlock"). +DRIVE_SUPPLY_INPUT = "+36V Interlock" + + +class Pod: + """One pod. Reached as `driver.left_x_arm` / `driver.right_x_arm`: it fills the slot of STAR's + `XArm`, though more of the instrument hangs on it. One board drives its X, Y and Z, its head + or channels and its gripper. + + `module_type` is what the board reports itself to be (Get Module ID): `multichannel` (a + 96-channel head) or `span8` (eight independent channels). + """ + + def __init__(self, board: AceBoard, side: Literal["left", "right"], module_type: str): + self.board = board + self.side = side + self.module_type = module_type + self.configuration: Optional[ModuleConfiguration] = None + + @property + def pod_number(self) -> int: + return POD_NUMBERS[self.side] + + def __str__(self) -> str: + return f"{self.side} pod (Pod{self.pod_number}, {self.module_type})" + + @property + def component(self) -> str: + """The name Biomek gives this pod's component in its logs (`host_command.component`): + `MC_1`, `SPAN8_2`.""" + return f"{COMPONENT_PREFIXES[self.module_type]}_{self.pod_number}" + + async def discover(self) -> ModuleConfiguration: + """Read what the pod's module says about itself. Moves nothing.""" + self.configuration = await read_module(self.board) + return self.configuration + + async def request_drive_supply(self) -> float: + """The pod's interlocked motor supply, in volts: about 36 with the interlock armed, about 0.1 + tripped. Moves nothing. + + Raises: + RuntimeError: if the pod has no input named for it. + """ + if self.configuration is None: + raise RuntimeError(f"{self} has not been read; call `discover()` or `setup()` first") + for index, name in self.configuration.analog_inputs.items(): + if name.startswith(DRIVE_SUPPLY_INPUT): + reply = await self.board.send(p.read_input_output(p.Device.ANALOG_INPUT, index)) + return p.parse_float(reply.payload) + raise RuntimeError(f"{self} has no {DRIVE_SUPPLY_INPUT!r} analog input") + + async def request_accuframe_offsets(self) -> Tuple[float, float, float]: + """The X, Y and Z offsets the pod's AccuFrame board holds.""" + return p.parse_accuframe_offsets((await self.board.send(p.get_accuframe_offsets())).payload) + + async def request_analog_inputs(self) -> Dict[str, float]: + if self.configuration is None: + raise RuntimeError(f"{self} has not been read; call `discover()` or `setup()` first") + return await read_analog_inputs(self.board, self.configuration) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/framing.py b/pylabrobot/beckman_coulter/biomek_i7/driver/framing.py new file mode 100644 index 00000000000..5407f0f16c6 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/framing.py @@ -0,0 +1,100 @@ +"""ACE framing: how messages travel in the Biomek i7's USB transfers. + +Every message travels as a frame, a length byte followed by that many message bytes:: + + length (1) | message (length) + +The host packs one or more frames into an interrupt OUT transfer on endpoint 0x02 (32-byte +packets) and sends no zero-length packet after one that fills its last packet. A board sends one +frame per interrupt IN transfer on endpoint 0x81 (16-byte packets); a frame longer than 15 bytes +spans several packets. Established on a cold start captured with USBPcap, 2026-10-24: all 3,507 +transfers split into whole frames. +""" + +from typing import Iterable, List + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import FrameError + +# The largest OUT transfer the Master Controller sent in the captured cold start. Larger ones are +# not known to be accepted, so frames are packed no further than this. +MAX_OUT_TRANSFER = 253 + +# The IN endpoint's packet size: one read returns at most one packet. +IN_PACKET_SIZE = 16 + + +def frame(message: bytes) -> bytes: + """Prefix one message with its length byte. + + Raises: + ValueError: if the message is empty or longer than 255 bytes. + """ + if not 0 < len(message) <= 0xFF: + raise ValueError(f"an ACE message is 1-255 bytes, got {len(message)}") + return bytes([len(message)]) + message + + +def pack(messages: Iterable[bytes], max_transfer: int = MAX_OUT_TRANSFER) -> List[bytes]: + """Pack messages, in order, into as few OUT transfers as fit `max_transfer` bytes each.""" + transfers: List[bytes] = [] + current = b"" + for message in messages: + framed = frame(message) + if len(framed) > max_transfer: + raise ValueError(f"a {len(framed)}-byte frame does not fit a {max_transfer}-byte transfer") + if len(current) + len(framed) > max_transfer: + transfers.append(current) + current = b"" + current += framed + if current: + transfers.append(current) + return transfers + + +def split(transfer: bytes) -> List[bytes]: + """Split one whole transfer into its messages. + + Raises: + FrameError: if the transfer does not end on a frame boundary, or holds an empty frame. + """ + reader = FrameReader() + messages = reader.feed(transfer) + if reader.pending: + raise FrameError(f"transfer ends inside a frame: {transfer.hex()}") + return messages + + +class FrameReader: + """Reassemble frames from IN packets, which may end anywhere inside a frame.""" + + def __init__(self) -> None: + self._buffer = bytearray() + + @property + def pending(self) -> int: + """How many bytes of an unfinished frame are held.""" + return len(self._buffer) + + def feed(self, data: bytes) -> List[bytes]: + """Take the next bytes read and return every message they complete. + + Raises: + FrameError: on a zero length byte, which no board sends and which would never advance. + """ + self._buffer += data + messages: List[bytes] = [] + while self._buffer: + length = self._buffer[0] + if length == 0: + bad = bytes(self._buffer) + self._buffer.clear() + raise FrameError(f"zero-length frame in {bad.hex()}") + if len(self._buffer) < length + 1: + break + messages.append(bytes(self._buffer[1 : length + 1])) + del self._buffer[: length + 1] + return messages + + def reset(self) -> None: + """Drop an unfinished frame, as after a read error.""" + self._buffer.clear() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/framing_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/framing_tests.py new file mode 100644 index 00000000000..bb4663ce5ee --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/framing_tests.py @@ -0,0 +1,118 @@ +"""ACE framing: length-prefixed messages, packed into OUT transfers and read back from 16-byte IN +packets.""" + +import random +import unittest +from typing import List + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import FrameError +from pylabrobot.beckman_coulter.biomek_i7.driver.framing import ( + IN_PACKET_SIZE, + MAX_OUT_TRANSFER, + FrameReader, + frame, + pack, + split, +) + +# Transfers from a captured cold start, each as it went over the wire: three Set Move Parameters +# packed into one OUT transfer, and three answers, each its own IN transfer, the last longer than a +# packet (an analog input's name, "Temperature"). +CAPTURED_OUT = ( + "1b1101001840150000001f0000003201000000000000038c00000000" + "1b1105001940030f0100298301009b1f0f000000000013f900000000" + "1b1102001a40b86f0200077b030044ce2200000000008a9100000000" +) +CAPTURED_IN = [ + "09000000010002008000", + "0902010007030200e500", + "122209000b01020054656d7065726174757265", +] + + +def messages(rng: random.Random, count: int) -> List[bytes]: + return [bytes(rng.randrange(256) for _ in range(rng.randrange(1, 256))) for _ in range(count)] + + +class CapturedTransferTests(unittest.TestCase): + def test_a_packed_out_transfer_splits_into_its_requests(self) -> None: + data = bytes.fromhex(CAPTURED_OUT) + requests = split(data) + self.assertEqual([(m[0], m[1], m[3], m[4]) for m in requests], + [(0x11, 1, 0x18, 0x40), (0x11, 5, 0x19, 0x40), (0x11, 2, 0x1A, 0x40)]) # fmt: skip + self.assertEqual(pack(requests), [data]) + + def test_in_transfers_hold_one_frame_each(self) -> None: + for hex_data in CAPTURED_IN: + data = bytes.fromhex(hex_data) + (message,) = split(data) + self.assertEqual(frame(message), data) + + +class InverseTests(unittest.TestCase): + """Framing and splitting undo each other, for any messages.""" + + def setUp(self) -> None: + self.rng = random.Random(11) + + def test_frame_then_split(self) -> None: + for message in messages(self.rng, 200) + [b"\x00", b"\xff" * 255]: + self.assertEqual(split(frame(message)), [message]) + + def test_pack_then_split_keeps_order_and_fits(self) -> None: + for _ in range(50): + batch = [m[: MAX_OUT_TRANSFER - 1] for m in messages(self.rng, self.rng.randrange(1, 12))] + transfers = pack(batch) + self.assertTrue(all(len(t) <= MAX_OUT_TRANSFER for t in transfers)) + self.assertEqual([m for t in transfers for m in split(t)], batch) + + def test_frames_reassemble_from_packets(self) -> None: + """Read packet by packet, as the board's reader does, the frames come out unchanged.""" + reader = FrameReader() + for message in messages(self.rng, 200): + data = frame(message) + out: List[bytes] = [] + for i in range(0, len(data), IN_PACKET_SIZE): + out += reader.feed(data[i : i + IN_PACKET_SIZE]) + self.assertEqual(out, [message]) + self.assertEqual(reader.pending, 0) + + def test_frames_reassemble_from_any_cut(self) -> None: + stream = b"".join(frame(m) for m in messages(self.rng, 20)) + for _ in range(20): + reader = FrameReader() + cuts = sorted(self.rng.sample(range(1, len(stream)), 15)) + out: List[bytes] = [] + for a, b in zip([0] + cuts, cuts + [len(stream)]): + out += reader.feed(stream[a:b]) + self.assertEqual(out, split(stream)) + + +class PackTests(unittest.TestCase): + def test_packs_in_order_until_the_transfer_is_full(self) -> None: + messages = [bytes([i]) * 100 for i in range(3)] + transfers = pack(messages) + self.assertEqual(transfers, [frame(messages[0]) + frame(messages[1]), frame(messages[2])]) + self.assertTrue(all(len(t) <= MAX_OUT_TRANSFER for t in transfers)) + + def test_rejects_empty_and_oversized_messages(self) -> None: + with self.assertRaises(ValueError): + frame(b"") + with self.assertRaises(ValueError): + frame(b"x" * 256) + with self.assertRaises(ValueError): + pack([b"x" * 255]) # a frame larger than a transfer + + def test_split_rejects_a_truncated_transfer(self) -> None: + with self.assertRaises(FrameError): + split(bytes([5, 1, 2])) + + def test_zero_length_frame_is_an_error(self) -> None: + reader = FrameReader() + with self.assertRaises(FrameError): + reader.feed(b"\x00\x01") + self.assertEqual(reader.pending, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py new file mode 100644 index 00000000000..21b0e1b98b8 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py @@ -0,0 +1,225 @@ +"""BiomekI7Driver: finds the instrument's ACE boards, works out what each one is, and owns them. + +A Biomek i7 shows up as one USB device per ACE module: the chassis, and one per arm. Which is which +is not fixed by USB order or serial number, so setup opens every ACE device, asks each its module +ID (its type, and an arm's side), and builds the chassis and a pod per arm from the answers. Only one +program can hold an ACE board at a time: Biomek's Master Controller must not be running. +""" + +import logging +from typing import Dict, List, Optional, Sequence, Tuple, Union + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import ( + ACE_PRODUCT_ID, + ACE_VENDOR_ID, + AceBoard, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ModuleConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod +from pylabrobot.io.usb import USB + +logger = logging.getLogger(__name__) + + +def find_ace_boards() -> Dict[str, int]: + """Every ACE board attached: its USB serial number and current USB address. + + Reading a serial number opens the device; the handle is released straight after, because a + WinUSB device admits one open handle at a time. + """ + import usb.util # optional dependency, as in pylabrobot.io.usb + + boards: Dict[str, int] = {} + for device in USB(ACE_VENDOR_ID, ACE_PRODUCT_ID, "ACE board").get_available_devices(): + try: + boards[str(device.serial_number)] = device.address + finally: + usb.util.dispose_resources(device) + return boards + + +class BiomekI7Driver: + """The Biomek i7's ACE boards, as a chassis and up to two pods.""" + + def __init__( + self, + serial_numbers: Optional[Sequence[str]] = None, + boards: Optional[Sequence[AceBoard]] = None, + ): + """ + Args: + serial_numbers: the ACE boards' USB serial numbers. Defaults to every ACE board attached. + boards: boards to use instead of opening USB devices: a simulated instrument + (`simulator.replay_boards`). + """ + self._serial_numbers = list(serial_numbers) if serial_numbers is not None else None + self._given_boards = list(boards) if boards is not None else None + self.boards: List[AceBoard] = [] + self._connected = False + self.chassis: Optional[Chassis] = None + # The pods, named as STAR names its X-arms: each fills an X-arm's slot (design.md, Feature map). + self.left_x_arm: Optional[Pod] = None + self.right_x_arm: Optional[Pod] = None + + # -- lifecycle ------------------------------------------------------------- + + async def setup(self) -> None: + """Connect to the instrument and find out what it is. Reads only: nothing is written to a + board and nothing moves. Repeatable: the boards stay open, and discovery reads them again. A + setup that fails part way releases the boards. + + Raises: + RuntimeError: if no chassis is found, or a board cannot be placed (`discover`). + """ + logger.warning( + "The Biomek i7 driver's discovery has run on one instrument; it is untested on other " + "instruments. Please report what works and what does not." + ) + if not self._connected: + await self._open() + try: + await self.discover() + except BaseException: + await self.stop() + raise + + async def _open(self) -> None: + """Open every ACE board and start reading it.""" + if self._given_boards is not None: + self.boards = list(self._given_boards) + else: + found = find_ace_boards() + if not found: + raise RuntimeError("no ACE boards (USB 0AB5:ACE0) found") + serials = self._serial_numbers or sorted(found) + missing = [s for s in serials if s not in found] + if missing: + raise RuntimeError(f"ACE boards {missing} not found; attached: {sorted(found)}") + # Opened by the address just enumerated: matching on serial number would open each device + # again to read its descriptor. + self.boards = [AceBoard(device_address=found[s], name=f"ACE {s}") for s in serials] + for board, serial in zip(self.boards, serials): + board.usb_serial_number = serial + self._connected = True + for board in self.boards: + await board.setup() + + async def discover(self) -> None: + """Work out which board is which, then read each module, chassis first. Moves nothing, arms + nothing and writes nothing: it opens the boards if `setup` has not, and can be called on its + own. + + Each board says what it is: Get Module ID answers a module type (`protocol.MODULE_TYPES`: + chassis, Multichannel, Span-8) and a side (left, right). That, not its USB serial number or + order, places it. Seen on one instrument; an unknown type or side, two boards claiming one + place, or no chassis is refused. + + Raises: + RuntimeError: for a board this driver cannot place, or no chassis. + """ + if not self._connected: + await self._open() + places: Dict[str, AceBoard] = {} + types: Dict[str, str] = {} + for board in self.boards: + module = p.parse_module_id((await board.send(p.get_module_id())).payload) + if module.type is None: + raise RuntimeError( + f"{board.name}: module type 0x{module.type_code:02X} is not one this driver knows" + ) + place = "chassis" if module.type == "chassis" else str(module.side) + if place in places: + raise RuntimeError( + f"{board.name} and {places[place].name} both report themselves as {place}" + ) + if place not in ("chassis", "left", "right"): + raise RuntimeError( + f"{board.name}: {module.type} module reports side 0x{module.side_code:02X}" + ) + places[place] = board + types[place] = module.type + if "chassis" not in places: + raise RuntimeError("no chassis module among the ACE boards") + self.chassis = Chassis(places["chassis"]) + self.left_x_arm = Pod(places["left"], "left", types["left"]) if "left" in places else None + self.right_x_arm = Pod(places["right"], "right", types["right"]) if "right" in places else None + modules: List[Tuple[str, ModuleConfiguration]] = [("chassis", await self.chassis.discover())] + for pod in self.arms: + modules.append((str(pod), await pod.discover())) + logger.info( + "found %s, module %s", pod, pod.configuration.serial_number if pod.configuration else "?" + ) + for name, found in modules: + untested = found.untested_firmware() + if untested: + logger.warning( + "%s runs firmware this driver has not been run against: %s", name, "; ".join(untested) + ) + + async def request_serial_numbers(self) -> Dict[str, Optional[str]]: + """The serial numbers the modules report: `chassis`, and `left` / `right` for each pod found. + Moves nothing. + + Raises: + RuntimeError: before discovery (`discover` or `setup`). + """ + return self._serial_numbers_found() + + def _serial_numbers_found(self) -> Dict[str, Optional[str]]: + if self.chassis is None or self.chassis.configuration is None: + raise RuntimeError("the modules have not been read; call `discover()` or `setup()` first") + found: Dict[str, Optional[str]] = {"chassis": self.chassis.configuration.serial_number} + for pod in self.arms: + found[pod.side] = pod.configuration.serial_number if pod.configuration else None + return found + + async def stop(self) -> None: + """Release every board. Writes nothing and moves nothing.""" + for board in self.boards: + try: + await board.stop() + except Exception: + logger.exception("failed to release %s", board.name) + self._connected = False + + # -- what the instrument has ------------------------------------------------ + + @property + def arms(self) -> List[Pod]: + """The pods this instrument has, left first (STAR's `arms`).""" + return [pod for pod in (self.left_x_arm, self.right_x_arm) if pod is not None] + + @property + def x_arm(self) -> Pod: + """The pod, on an instrument with one (STAR's `x_arm`). + + Raises: + RuntimeError: before discovery, when which pods are fitted is not yet known. + ValueError: with no pod, or two; reach two as `left_x_arm` and `right_x_arm`. + """ + if self.chassis is None: + raise RuntimeError("the instrument has not been read; call `discover()` or `setup()` first") + arms = self.arms + if not arms: + raise ValueError("this instrument has no pod") + if len(arms) > 1: + raise ValueError( + "this instrument has two pods, so `x_arm` is ambiguous - reach it through " + "`left_x_arm` or `right_x_arm`." + ) + return arms[0] + + def arm(self, name: Union[str, int]) -> Pod: + """A pod by any name it goes by: its side (`"left"`), Biomek's number (`1`, `"Pod1"`), or + Biomek's component name in its logs (`"MC_1"`). For porting Biomek methods and logs, which + name pods by number; the driver itself names them by side. + + Raises: + KeyError: if no pod goes by that name. + """ + for pod in self.arms: + if name in (pod.side, pod.pod_number, f"Pod{pod.pod_number}", pod.component): + return pod + raise KeyError(f"no pod {name!r}; have {[(p.side, p.component) for p in self.arms]}") diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master_tests.py new file mode 100644 index 00000000000..2df0cea1da8 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master_tests.py @@ -0,0 +1,218 @@ +"""Discovery on a replayed instrument: each board placed by what it says it is, then read.""" + +import asyncio +import itertools +import unittest +from typing import Any, Dict, List + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_boards, + generic_driver, + generic_recording, +) + +# The commands that only read: discovery sends nothing else. +READS = {name for name in p.COMMANDS.values() if name.startswith(("Get ", "Read ", "List "))} + + +def answer(recording: Dict[str, Any], module: str, key: str, reply: str) -> None: + """Have `module` answer the request `key` (its bytes less the sequence) with `reply`.""" + entries: List[List[Any]] = recording["boards"][module] + for entry in entries: + if entry[0] == key: + entry[1] = [reply] + return + entries.append([key, [reply]]) + + +def module_id(recording: Dict[str, Any], module: str, type_code: int, side_code: int) -> None: + answer(recording, module, "00000000", f"00000000000200{type_code:02X}{side_code:02X}") + + +class ReplayedTestCase(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) # the test loop's debug mode makes replays slow + + +class PlacementTests(ReplayedTestCase): + async def test_boards_are_placed_by_what_they_say_in_any_order(self) -> None: + for order in itertools.permutations(["chassis", "multichannel", "span8"]): + with self.subTest(order=order): + driver = generic_driver(generic_boards(modules=order)) + await driver.discover() + try: + self.assertIsNotNone(driver.chassis) + assert driver.chassis is not None and driver.left_x_arm and driver.right_x_arm + self.assertEqual(driver.chassis.board.name, "replayed chassis") + self.assertEqual(driver.left_x_arm.board.name, "replayed multichannel") + self.assertEqual(driver.right_x_arm.board.name, "replayed span8") + finally: + await driver.stop() + left, right = driver.left_x_arm, driver.right_x_arm + assert left is not None and right is not None + self.assertEqual(str(left), "left pod (Pod1, multichannel)") + self.assertEqual((left.component, left.pod_number), ("MC_1", 1)) + self.assertEqual((right.component, right.pod_number), ("SPAN8_2", 2)) + self.assertEqual(driver.arms, [left, right]) + + async def test_two_boards_in_one_place_are_refused(self) -> None: + recording = generic_recording() + module_id(recording, "span8", 0xFB, 0x01) # a second left pod + driver = generic_driver(generic_boards(recording)) + with self.assertRaisesRegex(RuntimeError, "replayed span8 and replayed multichannel both"): + await driver.discover() + await driver.stop() + + async def test_no_chassis_is_refused(self) -> None: + driver = generic_driver(generic_boards(modules=["multichannel", "span8"])) + with self.assertRaisesRegex(RuntimeError, "no chassis"): + await driver.discover() + await driver.stop() + + async def test_an_unknown_module_type_is_refused(self) -> None: + recording = generic_recording() + module_id(recording, "span8", 0x42, 0x02) + driver = generic_driver(generic_boards(recording)) + with self.assertRaisesRegex(RuntimeError, "module type 0x42"): + await driver.discover() + await driver.stop() + + async def test_an_unknown_side_is_refused(self) -> None: + recording = generic_recording() + module_id(recording, "span8", 0xFB, 0x07) + driver = generic_driver(generic_boards(recording)) + with self.assertRaisesRegex(RuntimeError, "side 0x07"): + await driver.discover() + await driver.stop() + + async def test_setup_releases_the_boards_when_discovery_fails(self) -> None: + boards = generic_boards(modules=["multichannel", "span8"]) + with self.assertRaisesRegex(RuntimeError, "no chassis"): + await generic_driver(boards).setup() + self.assertFalse(any(board.connected for board in boards)) + + +class PodNameTests(ReplayedTestCase): + async def test_one_pod(self) -> None: + driver = generic_driver(generic_boards(modules=["chassis", "span8"])) + with self.assertRaisesRegex(RuntimeError, "discover"): + driver.x_arm + await driver.discover() + self.assertIsNone(driver.left_x_arm) + self.assertIs(driver.x_arm, driver.right_x_arm) + await driver.stop() + + async def test_two_pods(self) -> None: + driver = generic_driver() + await driver.discover() + with self.assertRaisesRegex(ValueError, "left_x_arm"): + driver.x_arm + for name in ("left", 1, "Pod1", "MC_1"): + self.assertIs(driver.arm(name), driver.left_x_arm) + for name in ("right", 2, "Pod2", "SPAN8_2"): + self.assertIs(driver.arm(name), driver.right_x_arm) + with self.assertRaises(KeyError): + driver.arm("MC_2") + await driver.stop() + + +class ReadTests(ReplayedTestCase): + async def asyncSetUp(self) -> None: + await super().asyncSetUp() + self.boards = generic_boards() + self.driver = generic_driver(self.boards) + + async def asyncTearDown(self) -> None: + await self.driver.stop() + + async def test_discovery_on_its_own_opens_the_boards_and_only_reads(self) -> None: + await self.driver.discover() + self.assertTrue(all(board.connected for board in self.boards)) + for board in self.boards: + assert isinstance(board.io, ReplayAceUSB) + self.assertEqual(board.io.unanswered, [], board.name) + sent = {p.COMMANDS[(m[0], m[4])] for m in board.io.requests} + self.assertLessEqual(sent, READS, board.name) + + async def test_serial_numbers(self) -> None: + with self.assertRaisesRegex(RuntimeError, "discover"): + await self.driver.request_serial_numbers() + await self.driver.discover() + serials = await self.driver.request_serial_numbers() + self.assertEqual(set(serials), {"chassis", "left", "right"}) + for serial in serials.values(): + assert serial is not None + self.assertTrue(serial.startswith("SIMULATED"), serial) + self.assertEqual(len(set(serials.values())), 3) + + async def test_each_modules_boards_and_inputs(self) -> None: + await self.driver.discover() + chassis, left, right = self.driver.chassis, self.driver.left_x_arm, self.driver.right_x_arm + assert chassis and chassis.configuration and left and left.configuration + assert right and right.configuration + self.assertEqual(chassis.configuration.module_id.type, "chassis") + self.assertEqual(chassis.configuration.digital_inputs[1], "Door Sensor") + self.assertEqual(chassis.configuration.analog_units[9], "deg. C") + self.assertEqual( + [b.index for b in left.configuration.boards], + list(range(len(left.configuration.boards), 0, -1)), # highest index first + ) + self.assertTrue(any(b.hardware.name == "AccuFrame" for b in left.configuration.boards)) + self.assertEqual(right.configuration.untested_firmware(), []) + + async def test_sensor_reads(self) -> None: + await self.driver.discover() + chassis, left, right = self.driver.chassis, self.driver.left_x_arm, self.driver.right_x_arm + assert chassis and left and right + analog = await chassis.request_analog_inputs() + self.assertIn("Temperature", analog) + self.assertEqual(set(await chassis.request_digital_inputs()), {"Door Sensor"}) + self.assertEqual(len(await chassis.request_digital_outputs()), 1) + self.assertIsInstance(await chassis.request_legacy_alp_devices(), list) + for pod in (left, right): + # The recording answers as the instrument did when it was made, with the interlock armed. + self.assertGreater(await pod.request_drive_supply(), 30.0) + self.assertIn("+36V Interlock", await pod.request_analog_inputs()) + self.assertEqual(len(await left.request_accuframe_offsets()), 3) + + async def test_untested_firmware_is_warned_about(self) -> None: + with self.assertNoLogs("pylabrobot.beckman_coulter.biomek_i7.driver.master", "WARNING"): + await self.driver.discover() + recording = generic_recording() + answer(recording, "span8", "00000012", "000000001202" + "00EFBEADDE") + driver = generic_driver(generic_boards(recording)) + with self.assertLogs("pylabrobot.beckman_coulter.biomek_i7.driver.master", "WARNING") as logs: + await driver.discover() + await driver.stop() + self.assertIn("module image CRC 0xdeadbeef", "\n".join(logs.output)) + + async def test_stop_releases_the_boards_and_discovery_runs_again(self) -> None: + await self.driver.discover() + await self.driver.stop() + self.assertFalse(any(board.connected for board in self.boards)) + await self.driver.discover() + self.assertTrue(all(board.connected for board in self.boards)) + + +class InterlockStateTests(unittest.IsolatedAsyncioTestCase): + """Get Interlock Status, which the Master Controller never sends, answers the interlock's byte + (read on the instrument 2026-11-09: `FF` tripped, `00` armed).""" + + async def test_states(self) -> None: + for byte, state in (("FF", "tripped"), ("00", "armed")): + board = AceBoard( + io=ReplayAceUSB({"01010010": ["0101000010" + "0200" + byte]}), default_timeout=0.3 + ) + await board.setup() + try: + self.assertEqual(await Chassis(board).request_interlock_state(), state) + finally: + await board.stop() + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/module.py b/pylabrobot/beckman_coulter/biomek_i7/driver/module.py new file mode 100644 index 00000000000..3956e87bfd8 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/module.py @@ -0,0 +1,72 @@ +"""Reading what an ACE module says about itself: identity, its boards, and its inputs. + +The order follows the Master Controller's cold start: the module, then each of its boards from +the highest index down (a motion board's serial number and firmware image, any other board's +application version), then the names of its inputs and outputs. Nothing here moves or writes. +""" + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import BoardInfo, ModuleConfiguration + +# Board kinds whose identity is a serial number and firmware image; every other kind reports an +# application version. AccuFrame boards are left at their hardware version. +_IMAGE_BOARDS = {0x00} +_ACCUFRAME = 0xE3 + + +async def read_module(board: AceBoard) -> ModuleConfiguration: + """Read a module's identity, board inventory and input/output names.""" + module_id = p.parse_module_id((await board.send(p.get_module_id())).payload) + hardware = p.parse_hardware_version((await board.send(p.get_module_hardware_version())).payload) + serial = p.parse_string((await board.send(p.get_module_serial_number())).payload) + crc = p.parse_u32((await board.send(p.get_module_application_image_crc())).payload) + length = p.parse_u32((await board.send(p.get_module_application_image_length())).payload) + counts = p.parse_device_count((await board.send(p.get_module_device_count())).payload) + usb_serial = board.usb_serial_number + config = ModuleConfiguration(module_id, usb_serial, serial, hardware, crc, length, counts) + + for index in range(counts.get(p.Device.BOARD, 0), 0, -1): + info = BoardInfo( + index, + p.parse_hardware_version((await board.send(p.get_board_hardware_version(index))).payload), + ) + if info.hardware.type_code in _IMAGE_BOARDS: + info.serial_number = p.parse_string( + (await board.send(p.get_board_serial_number(index))).payload + ) + info.application_crc = p.parse_u32( + (await board.send(p.get_board_application_image_crc(index))).payload + ) + info.application_length = p.parse_u32( + (await board.send(p.get_board_application_image_length(index))).payload + ) + elif info.hardware.type_code != _ACCUFRAME: + info.application_version = p.parse_string( + (await board.send(p.get_board_application_version(index))).payload + ) + config.boards.append(info) + + io_counts = p.parse_device_count((await board.send(p.get_io_service_device_count())).payload) + for index in range(1, io_counts.get(p.Device.ANALOG_INPUT, 0) + 1): + name = await board.send(p.get_input_output_name(p.Device.ANALOG_INPUT, index)) + units = await board.send(p.get_analog_input_units(index)) + config.analog_inputs[index] = p.parse_string(name.payload) + config.analog_units[index] = p.parse_string(units.payload) + for index in range(1, io_counts.get(p.Device.DIGITAL_INPUT, 0) + 1): + name = await board.send(p.get_input_output_name(p.Device.DIGITAL_INPUT, index)) + config.digital_inputs[index] = p.parse_string(name.payload) + for index in range(1, io_counts.get(p.Device.DIGITAL_OUTPUT, 0) + 1): + name = await board.send(p.get_input_output_name(p.Device.DIGITAL_OUTPUT, index)) + config.digital_outputs[index] = p.parse_string(name.payload) + return config + + +async def read_analog_inputs(board: AceBoard, config: ModuleConfiguration) -> dict: + """Every analog input's value, by name, in its units.""" + replies = await board.send_many( + [p.read_input_output(p.Device.ANALOG_INPUT, i) for i in config.analog_inputs] + ) + return { + config.analog_inputs[i]: p.parse_float(r.payload) for i, r in zip(config.analog_inputs, replies) + } diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/protocol.py b/pylabrobot/beckman_coulter/biomek_i7/driver/protocol.py new file mode 100644 index 00000000000..63b78df4497 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/protocol.py @@ -0,0 +1,711 @@ +"""ACE messages: what the Biomek i7's boards are sent and what they answer. + +A request is a 5-byte header and its parameters, little-endian:: + + device (1) | index (1) | 0x00 | sequence (1) | opcode (1) | parameters + +`device` names the kind of thing addressed on the board (the module itself, one of its boards, a +motor, a syringe pump, an input...), `index` which one of them, and `opcode` the operation, whose +meaning depends on `device`. A board answers with the same header, then a status byte and the +status's data:: + + device | index | 0x00 | sequence | opcode | status (1) | data + +A command that starts something answers twice, ACCEPTED and then DONE; anything else answers +DONE once. Boards also send messages nobody asked for, with sequence 0: EVENT (an input changed, +the interlock tripped), NOTICE (the host-alive heartbeat, a move stopped by the interlock) and +EMERGENCY (CANopen EMCY from a drive, SAGIAN CAN traffic). + +The requests here are the ones the Master Controller was logged sending, plus the reads in +`FIRMWARE_READS`, and nothing else: `Request` refuses any device/opcode pair not in `COMMANDS`, +so firmware upgrade and flash commands cannot be sent through this module. A firmware read is one the Master Controller never sends, which only reads a state and changes +nothing. +""" + +import enum +import struct +from dataclasses import dataclass, field +from typing import Dict, List, Literal, Optional, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import INTERLOCK_TRIPPED_CODE, ace_error + + +class Device(enum.IntEnum): + """The device byte: what kind of thing on a board a message addresses.""" + + MODULE = 0x00 + INTERLOCK = 0x01 + BOARD = 0x02 + MOTION_SERVICE = 0x10 + MOTOR = 0x11 + PUMP = 0x12 + TIP_SENSOR = 0x13 + IO_SERVICE = 0x20 + DIGITAL_INPUT = 0x21 + ANALOG_INPUT = 0x22 + DIGITAL_OUTPUT = 0x28 + STATUS_DISPLAY = 0x2D + ACCUFRAME = 0xAF + LEGACY_ALP = 0xFE + IO_BOX = 0xFF + + +class Status(enum.IntEnum): + """A reply's status byte.""" + + ERROR = 0x00 + ACCEPTED = 0x01 + DONE = 0x02 + EVENT = 0x03 + NOTICE = 0xFE + EMERGENCY = 0xFF + + +# Every request this driver may send, by (device, opcode). The names are the Master Controller's. +COMMANDS: Dict[Tuple[int, int], str] = { + (Device.MODULE, 0x00): "Get Module ID", + (Device.MODULE, 0x02): "Get Module Serial Number", + (Device.MODULE, 0x03): "Get Module Hardware Version", + (Device.MODULE, 0x08): "Get Module Device Count", + (Device.MODULE, 0x0F): "Stop Module Execution", + (Device.MODULE, 0x11): "Get Module Application Image Length", + (Device.MODULE, 0x12): "Get Module Application Image CRC", + (Device.BOARD, 0x02): "Get Board Serial Number", + (Device.BOARD, 0x03): "Get Board Hardware Version", + (Device.BOARD, 0x04): "Get Board Bootloader Version", + (Device.BOARD, 0x10): "Get Board Application Version", + (Device.BOARD, 0x11): "Get Board Application Image Length", + (Device.BOARD, 0x12): "Get Board Application Image CRC", + (Device.INTERLOCK, 0x11): "Notify On Interlock Trip", + (Device.INTERLOCK, 0x50): "Trip Interlock", + (Device.INTERLOCK, 0x51): "Re-Arm Interlock", + (Device.MOTION_SERVICE, 0x0F): "Stop Motion Service", + (Device.MOTION_SERVICE, 0x50): "Move All", + (Device.MOTOR, 0x10): "Configure", + (Device.MOTOR, 0x12): "Set State", + (Device.MOTOR, 0x21): "Get Homed State", + (Device.MOTOR, 0x24): "Get Current Position", + (Device.MOTOR, 0x31): "Get Control Effort", + (Device.MOTOR, 0x40): "Set Move Parameters", + (Device.MOTOR, 0x50): "Move", + (Device.MOTOR, 0x51): "Home", + (Device.PUMP, 0x10): "Configure", + (Device.PUMP, 0x12): "Set State", + (Device.PUMP, 0x21): "Get Homed State", + (Device.PUMP, 0x24): "Get Current Position", + (Device.PUMP, 0x40): "Set Move Parameters", + (Device.PUMP, 0x51): "Home", + (Device.TIP_SENSOR, 0x10): "Get Tip Status", + (Device.TIP_SENSOR, 0x41): "Set LLS/CD Sensitivity", + (Device.IO_SERVICE, 0x08): "Get IO Service Device Count", + (Device.DIGITAL_INPUT, 0x01): "Get Digital Input Name", + (Device.DIGITAL_INPUT, 0x10): "Read Digital Input", + (Device.DIGITAL_INPUT, 0x11): "Notify On Digital Input Change", + (Device.ANALOG_INPUT, 0x01): "Get Analog Input Name", + (Device.ANALOG_INPUT, 0x10): "Read Analog Input", + (Device.ANALOG_INPUT, 0x12): "Get Analog Input Units", + (Device.DIGITAL_OUTPUT, 0x01): "Get Digital Output Name", + (Device.DIGITAL_OUTPUT, 0x10): "Read Digital Output", + (Device.DIGITAL_OUTPUT, 0x11): "Notify On Digital Output Change", + (Device.STATUS_DISPLAY, 0x10): "Set Status Display", + (Device.ACCUFRAME, 0xF7): "Get AccuFrame Offsets", + (Device.LEGACY_ALP, 0x18): "List Legacy ALP Devices", + (Device.IO_BOX, 0x10): "Send Digital I/O Box", +} + +# Reads the Master Controller never sends. Get State answers an axis's state byte (`AxisState`) +# with no precondition, and changes nothing. Get Interlock Status answers the interlock's state +# byte; the Master Controller's log names it "Get Interlock Status". +FIRMWARE_READS: Dict[Tuple[int, int], str] = { + (Device.MOTOR, 0x11): "Get State", + (Device.PUMP, 0x11): "Get State", + (Device.INTERLOCK, 0x10): "Get Interlock Status", +} +COMMANDS.update(FIRMWARE_READS) + +# Requests that answer ACCEPTED before DONE. +TWO_STAGE: frozenset = frozenset( + {(Device.MOTION_SERVICE, 0x50), (Device.MOTOR, 0x50), (Device.MOTOR, 0x51), (Device.PUMP, 0x51)} +) + +# The opcode a board's unsolicited messages carry, by (device, opcode). +HOST_ALIVE = (Device.MODULE, 0x40) +EMCY = (Device.MODULE, 0x31) +SAGIAN_CAN = (Device.MODULE, 0x30) +INTERLOCK_TRIPPED = (Device.INTERLOCK, 0x10) +DIGITAL_INPUT_VALUE = (Device.DIGITAL_INPUT, 0x10) + +# A SAGIAN CAN message a Span-8 board passes up: the message's kind and status bytes, named as the +# Master Controller's log names them ("SAGIAN CAN TO_NODE 05:00 READ SUCCESS F7 ..."). The board +# shares the CAN bus with the SAGIAN devices behind it (the AccuFrame is node 05) and forwards what +# it sees there, the answers to the host's own requests included: reading the AccuFrame's offsets +# through the Multichannel's board brings the AccuFrame's answer back from the Span-8's as well. +# Every such message in the Master Controller's logs (2026-07-27 .. 10-27) is a success or a +# request; any other status is not known to be harmless. +SAGIAN_CAN_KINDS = {0x00: "ACTION", 0x01: "READ", 0x02: "WRITE", 0x03: "EVENT"} +SAGIAN_CAN_KNOWN_STATUSES = {0x00: "REQUEST", 0x01: "SUCCESS"} + + +def describe_sagian_can(data: bytes) -> Tuple[str, bool]: + """A forwarded SAGIAN CAN message as the Master Controller's log words it + (`TO_NODE 05:00 READ SUCCESS F7 28 0F BB 40`), and whether its status is one of those seen in + normal operation (`SAGIAN_CAN_KNOWN_STATUSES`).""" + if len(data) < 7: + return f"short message {data.hex()}", False + kind = SAGIAN_CAN_KINDS.get(data[5], f"kind 0x{data[5]:02X}") + status = SAGIAN_CAN_KNOWN_STATUSES.get(data[6]) + words = [ + "TO_NODE" if data[1] == 0x01 else f"direction 0x{data[1]:02X}", + f"{data[2]:02X}:{data[4]:02X}", + kind, + status or f"status 0x{data[6]:02X}", + ] + if len(data) > 7: + words.append(data[7:].hex(" ").upper()) + return " ".join(words), status is not None and data[1] == 0x01 + + +# A drive's own error code while its motor power is off, the interlock tripped ("interlock active"). +INTERLOCK_ACTIVE = 0x0416 + + +def describe_routine_unsolicited(reply: "Reply") -> Optional[str]: + """What an unsolicited message every session sees says, or None for one worth showing. + + Routine: a drive's EMCY with error 0000 (its fault cleared, as it is enabled), a drive's EMCY + naming `interlock active`, and a Move All notice ending in `interlock tripped`. The last two + follow every interlock trip, the driver's own at `stop` included. So does the chassis's trip event + (Notify On Interlock Trip), which is logged at INFO; `BiomekI7Driver` tells a trip it made from + one it did not.""" + if (reply.device, reply.opcode) == EMCY and reply.status == Status.EMERGENCY: + if len(reply.data) < 8: + return None + emcy = parse_emcy(reply.data) + if emcy.error_code == 0: + return f"drive node 0x{emcy.node:02X}: fault cleared (EMCY 0000)" + if emcy.device_error == INTERLOCK_ACTIVE: + return f"drive node 0x{emcy.node:02X}: interlock active (EMCY {emcy.error_code:04X})" + return None + if reply.status == Status.NOTICE and reply.error_code == INTERLOCK_TRIPPED_CODE: + return f"device 0x{reply.device:02X} index {reply.index}: move ended, interlock tripped" + return None + + +@dataclass(frozen=True) +class Request: + """One request, before a sequence number is given to it.""" + + device: int + index: int + opcode: int + params: bytes = b"" + + def __post_init__(self) -> None: + if (self.device, self.opcode) not in COMMANDS: + raise ValueError( + f"device 0x{self.device:02X} opcode 0x{self.opcode:02X} is not a command this driver sends" + ) + if not 0 <= self.index <= 0xFF: + raise ValueError(f"index must be 0-255, got {self.index}") + + @property + def name(self) -> str: + return COMMANDS[(self.device, self.opcode)] + + @property + def two_stage(self) -> bool: + """Whether the board answers ACCEPTED before DONE.""" + return (self.device, self.opcode) in TWO_STAGE + + def encode(self, sequence: int) -> bytes: + """The message bytes, with `sequence` (1-255; 0 is the boards' own).""" + if not 1 <= sequence <= 0xFF: + raise ValueError(f"sequence must be 1-255, got {sequence}") + return bytes([self.device, self.index, 0x00, sequence, self.opcode]) + self.params + + def __str__(self) -> str: + return f"{self.name} (device 0x{self.device:02X}, index {self.index})" + + +@dataclass(frozen=True) +class Reply: + """One message from a board.""" + + device: int + index: int + sequence: int + opcode: int + status: int + data: bytes + # Replies the board sent under this request's sequence for other devices: a Move All's axes + # report there when they end other than plainly. Set by `AceBoard` on the final reply. + related: Tuple["Reply", ...] = field(default=(), compare=False) + + @classmethod + def parse(cls, message: bytes) -> "Reply": + """Split a message into its header, status and data. + + Raises: + ValueError: if the message is shorter than a header and a status byte. + """ + if len(message) < 6: + raise ValueError(f"ACE reply too short: {message.hex()}") + device, index, _, sequence, opcode, status = message[:6] + return cls(device, index, sequence, opcode, status, bytes(message[6:])) + + @property + def key(self) -> Tuple[int, int, int, int]: + """What a reply shares with the request it answers.""" + return (self.device, self.index, self.sequence, self.opcode) + + @property + def unsolicited(self) -> bool: + return self.sequence == 0 + + @property + def error_code(self) -> Optional[int]: + """The ACE error code, or None when the reply reports success.""" + if self.status == Status.ERROR: + return self.data[0] if self.data else 0 + if self.status in (Status.ACCEPTED, Status.DONE, Status.NOTICE) and self.data and self.data[0]: + return self.data[0] + return None + + @property + def device_error(self) -> Optional[int]: + """The drive's own error code that follows the ACE error code, when there is one.""" + if self.error_code is None or len(self.data) < 2: + return None + return int.from_bytes(self.data[1:], "little") + + @property + def payload(self) -> bytes: + """What a successful reply returns, after its zero error byte.""" + return self.data[1:] + + def raise_for_error(self, request: str) -> None: + """Raise the `AceError` this reply reports, if it reports one.""" + code = self.error_code + if code is not None: + raise ace_error(code, self.device_error, request, self.device, self.index) + + def check(self, request: str) -> "Reply": + """Return this reply, or raise the `AceError` it reports.""" + self.raise_for_error(request) + return self + + +# -- requests ---------------------------------------------------------------- + + +def get_module_id() -> Request: + return Request(Device.MODULE, 0, 0x00) + + +def get_module_serial_number() -> Request: + return Request(Device.MODULE, 0, 0x02) + + +def get_module_hardware_version() -> Request: + return Request(Device.MODULE, 0, 0x03) + + +def get_module_device_count() -> Request: + return Request(Device.MODULE, 0, 0x08) + + +def get_module_application_image_length() -> Request: + return Request(Device.MODULE, 0, 0x11) + + +def get_module_application_image_crc() -> Request: + return Request(Device.MODULE, 0, 0x12) + + +def stop_module_execution() -> Request: + return Request(Device.MODULE, 0, 0x0F) + + +def get_board_serial_number(board: int) -> Request: + return Request(Device.BOARD, board, 0x02) + + +def get_board_hardware_version(board: int) -> Request: + return Request(Device.BOARD, board, 0x03) + + +def get_board_bootloader_version(board: int) -> Request: + return Request(Device.BOARD, board, 0x04) + + +def get_board_application_version(board: int) -> Request: + return Request(Device.BOARD, board, 0x10) + + +def get_board_application_image_length(board: int) -> Request: + return Request(Device.BOARD, board, 0x11) + + +def get_board_application_image_crc(board: int) -> Request: + return Request(Device.BOARD, board, 0x12) + + +def get_interlock_status(interlock: int = 1) -> Request: + return Request(Device.INTERLOCK, interlock, 0x10) + + +def notify_on_interlock_trip(interlock: int = 1, notify: bool = True) -> Request: + return Request(Device.INTERLOCK, interlock, 0x11, bytes([int(notify)])) + + +def trip_interlock(interlock: int = 1) -> Request: + return Request(Device.INTERLOCK, interlock, 0x50) + + +def rearm_interlock(interlock: int = 1) -> Request: + return Request(Device.INTERLOCK, interlock, 0x51) + + +def stop_motion_service() -> Request: + return Request(Device.MOTION_SERVICE, 0, 0x0F) + + +def move_all(timeout_ms: int) -> Request: + """Start every move whose parameters were set since the last move, together.""" + return Request(Device.MOTION_SERVICE, 0, 0x50, struct.pack(" Request: + """Load an axis's motor table. `payload` is the table exactly as the Master Controller sent it.""" + return Request(device, axis, 0x10, payload) + + +def set_state_enabled(device: int, axis: int) -> Request: + return Request(device, axis, 0x12, b"\x00") + + +def get_state(device: int, axis: int) -> Request: + """Ask a motor or pump for its state byte; see `AxisState`.""" + return Request(device, axis, 0x11) + + +def get_homed_state(device: int, axis: int) -> Request: + """Whether a motor or a pump (`device`) has been homed since the board started.""" + return Request(device, axis, 0x21) + + +def get_current_position(device: int, axis: int) -> Request: + return Request(device, axis, 0x24) + + +def get_control_effort(axis: int) -> Request: + return Request(Device.MOTOR, axis, 0x31) + + +# The largest force limit Set Move Parameters can carry: a u32 of the Master Controller's units x1000. +MAX_FORCE = 4294967.295 + + +def set_motor_move_parameters( + axis: int, + position: int, + velocity: int, + acceleration: int, + jerk: int, + force: int = 0, + sensor: int = 0, + trigger: int = 0, +) -> Request: + """Set a motor's next move, in counts, laid out as the Master Controller's logged requests lay + it out. `force` is the force limit x1000 (grip and tip loading), 0 for none. `sensor` + and `trigger` make the move stop where a sensor fires: liquid-level sensing on a Span-8 Z, the + AccuFrame when framing (0, 0: no sensor).""" + params = struct.pack(" Request: + """Set a syringe pump's next move, in counts, with the valve position it moves through.""" + params = struct.pack( + " Request: + """Start one motor's move on its own.""" + return Request(Device.MOTOR, axis, 0x50, struct.pack(" Request: + return Request(device, axis, 0x51) + + +def get_tip_status(sensor: int = 1) -> Request: + return Request(Device.TIP_SENSOR, sensor, 0x10) + + +def set_lls_cd_sensitivity(clot_detection: bool, value: int) -> Request: + """Liquid-level (or, with `clot_detection`, clot-detection) sensitivity, 0-4095, on the Span-8's + LLS/CD board (the device that also answers Get Tip Status): what the Master Controller sends + for `SS`.""" + if not 0 <= value <= 4095: + raise ValueError(f"sensitivity {value} is outside 0..4095") + return Request(Device.TIP_SENSOR, 1, 0x41, struct.pack(" Request: + return Request(Device.IO_SERVICE, 0, 0x08) + + +def get_input_output_name(device: int, index: int) -> Request: + return Request(device, index, 0x01) + + +def read_input_output(device: int, index: int) -> Request: + return Request(device, index, 0x10) + + +def notify_on_change(device: int, index: int, notify: bool = True) -> Request: + return Request(device, index, 0x11, bytes([int(notify)])) + + +def get_analog_input_units(index: int) -> Request: + return Request(Device.ANALOG_INPUT, index, 0x12) + + +# ERROR is what the Master Controller shows after a failed move (2026-07-31, `2D 01 00 seq 10 05`). +StatusDisplayState = Literal["ready", "running", "paused", "error"] +STATUS_DISPLAY_STATES = {"ready": 0x02, "running": 0x03, "paused": 0x04, "error": 0x05} + + +def set_status_display(state: StatusDisplayState, display: int = 1) -> Request: + return Request(Device.STATUS_DISPLAY, display, 0x10, bytes([STATUS_DISPLAY_STATES[state]])) + + +def get_accuframe_offsets(accuframe: int = 1) -> Request: + return Request(Device.ACCUFRAME, accuframe, 0xF7) + + +def list_legacy_alp_devices() -> Request: + return Request(Device.LEGACY_ALP, 0, 0x18) + + +def send_digital_io_box(params: bytes, box: int = 1) -> Request: + """Pass a command to the digital I/O box. Its bytes are the box's own and are not decoded here.""" + return Request(Device.IO_BOX, box, 0x10, params) + + +# -- replies ----------------------------------------------------------------- + +# Get Module ID's two bytes, as the Master Controller's log decodes them ("Chassis", "Left +# Multichannel", "Right Span-8"). Only these three were seen, on one instrument. +MODULE_TYPES = {0x80: "chassis", 0xFD: "multichannel", 0xFB: "span8"} +MODULE_SIDES = {0x00: None, 0x01: "left", 0x02: "right"} + +# Hardware version type codes, as the Master Controller names them. +HARDWARE_NAMES = { + 0x00: "Motion Board", + 0x01: "Transport Supervisor", + 0x02: "Chassis Supervisor", + 0xE0: "SAGIAN Motion Board", + 0xE1: "SAGIAN LLS Board", + 0xE2: "SAGIAN Syringe Pump Board", + 0xE3: "AccuFrame", + 0xE5: "Device Controller", +} + +# Tip sensor codes. 1 is "cannot determine" in the Master Controller's `VT` replies. +TIP_STATES = {0x00: "loaded", 0x01: "unknown", 0x02: "unloaded"} + +# What an axis reports when its part of a Move All ends other than plainly. A 1-byte report is +# one of the statuses; a 5-byte report is a type and the s32 position where its sensor fired. +LLS_LIQUID_SENSED = 69 +LLS_LIQUID_NOT_SENSED = 70 +CD_CLOT_NOT_DETECTED = 71 +CD_CLOT_DETECTED = 72 +ACCUFRAME = 175 +MotionOutcome = Literal[ + "done", "liquid-sensed", "accuframe", "liquid-not-sensed", "clot-not-detected", "clot-detected" +] +MOTION_OUTCOMES: Dict[int, MotionOutcome] = { + LLS_LIQUID_SENSED: "liquid-sensed", + LLS_LIQUID_NOT_SENSED: "liquid-not-sensed", + CD_CLOT_NOT_DETECTED: "clot-not-detected", + CD_CLOT_DETECTED: "clot-detected", + ACCUFRAME: "accuframe", +} + + +class AxisState(enum.IntEnum): + """A motor's or pump's state byte, as Get State answers it. + + An axis starts NOT_CONFIGURED at power-up, and goes back to it when Configure starts or a SAGIAN + drive reports it lost its parameters. Configure ends DISABLED; Set State moves between DISABLED + and ENABLED; Home and moves need ENABLED. FAULT follows a drive error. + """ + + ENABLED = 0x00 + DISABLED = 0x01 + NOT_CONFIGURED = 0xFE + FAULT = 0xFF + + +AxisStateName = Literal["enabled", "disabled", "not_configured", "fault"] +"""An `AxisState` as the public API gives it (`Pod.request_axis_states`): its name, lower case.""" + + +@dataclass(frozen=True) +class ModuleId: + """What Get Module ID answers: the kind of module and, for an arm's, its side.""" + + type_code: int + side_code: int + + @property + def type(self) -> Optional[str]: + """`chassis`, `multichannel` or `span8`; None for a code not seen yet.""" + return MODULE_TYPES.get(self.type_code) + + @property + def side(self) -> Optional[str]: + """`left` or `right` for an arm's module, None for the chassis.""" + return MODULE_SIDES.get(self.side_code) + + +@dataclass(frozen=True) +class HardwareVersion: + type_code: int + revision: int + + @property + def name(self) -> str: + return HARDWARE_NAMES.get(self.type_code, f"hardware 0x{self.type_code:02X}") + + def __str__(self) -> str: + return f"{self.name} {self.revision}" + + +@dataclass(frozen=True) +class Emcy: + """A CANopen emergency message a drive sent through its board.""" + + node: int + error_code: int + error_register: int + device_error: int + source: int + + +def parse_module_id(payload: bytes) -> ModuleId: + return ModuleId(payload[0], payload[1]) + + +def parse_string(payload: bytes) -> str: + return payload.decode("ascii") + + +def parse_hardware_version(payload: bytes) -> HardwareVersion: + return HardwareVersion(payload[0], payload[1]) + + +def parse_device_count(payload: bytes) -> Dict[int, int]: + """Each kind of device a module or service holds, by device byte, and how many.""" + if len(payload) % 3: + raise ValueError(f"device count is (device, u16 count) triples, got {payload.hex()}") + return { + payload[i]: int.from_bytes(payload[i + 1 : i + 3], "little") for i in range(0, len(payload), 3) + } + + +def parse_u32(payload: bytes) -> int: + return int(struct.unpack_from(" int: + return int(struct.unpack_from(" float: + return float(struct.unpack_from(" Tuple[float, float, float]: + x, y, z = struct.unpack_from(" InterlockState: + """Raises `ValueError` for a byte not seen.""" + state = INTERLOCK_STATES.get(payload[0]) + if state is None: + raise ValueError(f"interlock state 0x{payload[0]:02X} has not been seen") + return state # type: ignore[return-value] + + +def parse_axis_state(payload: bytes) -> AxisState: + """Raises `ValueError` for a state byte the firmware does not set.""" + return AxisState(payload[0]) + + +def parse_tip_status(payload: bytes) -> List[Optional[str]]: + """Each channel's tip, `loaded` or `unloaded`; None for a code not seen yet.""" + return [TIP_STATES.get(b) for b in payload] + + +@dataclass(frozen=True) +class MotionComplete: + """How one axis's part of a Move All ended: `done`, or a sensor outcome; `position` is where a + sensor stopped it (liquid sensed, AccuFrame), else None.""" + + device: int + index: int + outcome: MotionOutcome + position: Optional[int] = None + + +def parse_motion_complete(reply: Reply) -> MotionComplete: + """An axis's report inside a Move All.""" + payload = reply.payload + if len(payload) == 5: + (position,) = struct.unpack_from(" Emcy: + """Decode an EMERGENCY reply's data: node, CANopen error code and register, then the drive's own + error code and the source it names.""" + node = data[1] + error_code, error_register, device_error, source = struct.unpack_from(" (the request, its sequence, the frame's bytes, what the log says it is). +# The reads the Master Controller never sends (`FIRMWARE_READS`) were never logged; their frames +# follow the request layout. +FRAMES: Dict[Tuple[int, int], Tuple[Callable[[], p.Request], int, str, str]] = { + (0x00, 0x00): (p.get_module_id, 0x01, "0000000100", "Get Module ID"), + (0x00, 0x02): (p.get_module_serial_number, 0x03, "0000000302", "Get Module Serial Number"), + (0x00, 0x03): (p.get_module_hardware_version, 0x02, "0000000203", "Get Module Hardware Version"), + (0x00, 0x08): (p.get_module_device_count, 0x06, "0000000608", "Get Module Device Count"), + (0x00, 0x0F): (p.stop_module_execution, 0x75, "000000750F", "Stop Module Execution"), + (0x00, 0x11): ( + p.get_module_application_image_length, + 0x05, + "0000000511", + "Get Module Application Image Length", + ), + (0x00, 0x12): ( + p.get_module_application_image_crc, + 0x04, + "0000000412", + "Get Module Application Image CRC", + ), + (0x02, 0x02): ( + lambda: p.get_board_serial_number(6), + 0x0B, + "0206000B02", + "Get Board 6 Serial Number", + ), + (0x02, 0x03): ( + lambda: p.get_board_hardware_version(1), + 0x07, + "0201000703", + "Get Board 1 Hardware Version", + ), + (0x02, 0x04): ( + lambda: p.get_board_bootloader_version(7), + 0x31, + "0207003104", + "Get Board 7 Bootloader Version", + ), + (0x02, 0x10): ( + lambda: p.get_board_application_version(1), + 0x08, + "0201000810", + "Get Board 1 Application Version", + ), + (0x02, 0x11): ( + lambda: p.get_board_application_image_length(6), + 0x0D, + "0206000D11", + "Get Board 6 Application Image Length", + ), + (0x02, 0x12): ( + lambda: p.get_board_application_image_crc(6), + 0x0C, + "0206000C12", + "Get Board 6 Application Image CRC", + ), + (0x01, 0x10): (p.get_interlock_status, 0x09, "0101000910", "(never logged)"), + (0x01, 0x11): (p.notify_on_interlock_trip, 0x28, "010100281101", "Notify On Interlock Trip TRUE"), + (0x01, 0x50): (p.trip_interlock, 0xEA, "010100EA50", "Trip Interlock"), + (0x01, 0x51): (p.rearm_interlock, 0xE1, "010100E151", "Re-Arm Interlock"), + (0x10, 0x0F): (p.stop_motion_service, 0x67, "100000670F", "Stop Motion Service"), + (0x10, 0x50): (lambda: p.move_all(5000), 0x28, "100000285088130000", "Move All Timeout:5000"), + (0x11, 0x10): ( + lambda: p.configure(p.Device.MOTOR, 2, MOTOR_TABLE), + 0x2F, + "1102002F10" + MOTOR_TABLE.hex(), + "Configure Y1 Minimum Velocity:23 ...", + ), + (0x11, 0x11): (lambda: p.get_state(p.Device.MOTOR, 3), 0x07, "1103000711", "(never logged)"), + (0x11, 0x12): ( + lambda: p.set_state_enabled(p.Device.MOTOR, 3), + 0x76, + "110300761200", + "Set Z State ENABLED", + ), + (0x11, 0x21): ( + lambda: p.get_homed_state(p.Device.MOTOR, 1), + 0x3C, + "1101003C21", + "Get X Homed State", + ), + (0x11, 0x24): ( + lambda: p.get_current_position(p.Device.MOTOR, 7), + 0x80, + "1107008024", + "Get GZ Current Position", + ), + (0x11, 0x31): (lambda: p.get_control_effort(0x13), 0x96, "1113009631", "Get GG Control Effort"), + (0x11, 0x40): ( + lambda: p.set_motor_move_parameters( + 3, position=-1000, velocity=24320, acceleration=128000, jerk=698880 + ), + 0xAB, + "110300AB40005F000000F4010000AA0A000000000018FCFFFF0000", + "Set Z Move Parameters Position:-1000 Velocity:24320 Acceleration:128000 Jerk:698880", + ), + (0x11, 0x50): (lambda: p.move(3, 30000), 0xAC, "110300AC5030750000", "Move Z Timeout:30000"), + (0x11, 0x51): (lambda: p.home(p.Device.MOTOR, 3), 0xAD, "110300AD51", "Home Z"), + (0x12, 0x10): ( + lambda: p.configure(p.Device.PUMP, 1, PUMP_TABLE), + 0x3F, + "1201003F10" + PUMP_TABLE.hex(), + "Configure D1 Minimum Start Velocity:200 ...", + ), + (0x12, 0x11): (lambda: p.get_state(p.Device.PUMP, 1), 0x07, "1201000711", "(never logged)"), + (0x12, 0x12): ( + lambda: p.set_state_enabled(p.Device.PUMP, 8), + 0x6B, + "1208006B1200", + "Set D8 State ENABLED", + ), + (0x12, 0x21): ( + lambda: p.get_homed_state(p.Device.PUMP, 1), + 0xDB, + "120100DB21", + "Get D1 Homed State", + ), + (0x12, 0x24): ( + lambda: p.get_current_position(p.Device.PUMP, 8), + 0x88, + "1208008824", + "Get D8 Current Position", + ), + (0x12, 0x40): ( + lambda: p.set_pump_move_parameters( + 2, + position=0, + start_velocity=200, + max_velocity=23200, + cutoff_velocity=200, + acceleration=50000, + valve="input", + ), + 0x72, + "1202007240C8000000A05A0000C800000050C300000000000000", + "Set D2 Move Parameters Position:0 Valve:INPUT Start Velocity:200 Maximum Velocity:23200 " + "Cutoff Velocity:200 Acceleration:50000", + ), + (0x12, 0x51): (lambda: p.home(p.Device.PUMP, 1), 0x60, "1201006051", "Home D1"), + (0x13, 0x10): (p.get_tip_status, 0x95, "1301009510", "Get Tip Status"), + (0x13, 0x41): ( + lambda: p.set_lls_cd_sensitivity(False, 3500), + 0xA2, + "130100A24100AC0D", + "Set LLS Sensitivity 3500", + ), + (0x20, 0x08): (p.get_io_service_device_count, 0x0A, "2000000A08", "Get IO Service Device Count"), + (0x21, 0x01): ( + lambda: p.get_input_output_name(p.Device.DIGITAL_INPUT, 1), + 0x1E, + "2101001E01", + "Get Digital Input 1 Name", + ), + (0x21, 0x10): ( + lambda: p.read_input_output(p.Device.DIGITAL_INPUT, 1), + 0x20, + "2101002010", + "Read Digital Input 1", + ), + (0x21, 0x11): ( + lambda: p.notify_on_change(p.Device.DIGITAL_INPUT, 1), + 0x1F, + "2101001F1101", + "Notify On Digital Input 1 Change TRUE", + ), + (0x22, 0x01): ( + lambda: p.get_input_output_name(p.Device.ANALOG_INPUT, 9), + 0x0B, + "2209000B01", + "Get Analog Input 9 Name", + ), + (0x22, 0x10): ( + lambda: p.read_input_output(p.Device.ANALOG_INPUT, 1), + 0x65, + "2201006510", + "Read Analog Input 1", + ), + (0x22, 0x12): ( + lambda: p.get_analog_input_units(9), + 0x0C, + "2209000C12", + "Get Analog Input 9 Units", + ), + (0x28, 0x01): ( + lambda: p.get_input_output_name(p.Device.DIGITAL_OUTPUT, 1), + 0x22, + "2801002201", + "Get Digital Output 1 Name", + ), + (0x28, 0x10): ( + lambda: p.read_input_output(p.Device.DIGITAL_OUTPUT, 1), + 0x24, + "2801002410", + "Read Digital Output 1", + ), + (0x28, 0x11): ( + lambda: p.notify_on_change(p.Device.DIGITAL_OUTPUT, 1), + 0x23, + "280100231101", + "Notify On Digital Output 1 Change TRUE", + ), + (0x2D, 0x10): ( + lambda: p.set_status_display("running"), + 0xE2, + "2D0100E21003", + "Set Status Display RUNNING", + ), + (0xAF, 0xF7): (p.get_accuframe_offsets, 0x32, "AF010032F7", "Get AccuFrame Offsets"), + (0xFE, 0x18): (p.list_legacy_alp_devices, 0x26, "FE00002618", "List Legacy ALP Devices"), + (0xFF, 0x10): ( + lambda: p.send_digital_io_box(b"\x02\x01"), + 0xE0, + "FF0100E0100201", + "Send Digital I/O Box 00 WRITE 01", + ), +} + + +def decode(message: bytes) -> Tuple[int, int, int, int, bytes]: + """A request's header and parameters, by the layout in `protocol.py`'s docstring.""" + device, index, zero, sequence, opcode = message[:5] + assert zero == 0 + return device, index, sequence, opcode, message[5:] + + +class ExactFrameTests(unittest.TestCase): + def test_every_command_has_its_frame(self) -> None: + """A command added to `COMMANDS` needs its frame here.""" + self.assertEqual(set(FRAMES), set(p.COMMANDS)) + + def test_each_request_is_the_logged_frame(self) -> None: + for key, (build, sequence, frame_hex, logged) in FRAMES.items(): + with self.subTest(command=p.COMMANDS[key], logged=logged): + request = build() + self.assertEqual((request.device, request.opcode), key) + self.assertEqual(request.encode(sequence), bytes.fromhex(frame_hex)) + + def test_reads_never_logged_only_read(self) -> None: + for key, name in p.FIRMWARE_READS.items(): + self.assertTrue(name.startswith("Get "), name) + self.assertEqual(p.COMMANDS[key], name) + + def test_status_display_error_is_the_logged_frame(self) -> None: + # Log.db3, after a failed move: `2D 01 00 seq 10 05`. + self.assertEqual(p.set_status_display("error").encode(0x2E), bytes.fromhex("2D01002E1005")) + + def test_only_moves_and_homes_answer_twice(self) -> None: + two_stage = {key for key in FRAMES if FRAMES[key][0]().two_stage} + self.assertEqual(two_stage, {(0x10, 0x50), (0x11, 0x50), (0x11, 0x51), (0x12, 0x51)}) + + +class RoundTripTests(unittest.TestCase): + """Build, then parse: every field comes back out as it went in.""" + + def setUp(self) -> None: + self.random = random.Random(7) + + def test_header(self) -> None: + for key in FRAMES: + for _ in range(5): + index, sequence = self.random.randrange(256), self.random.randrange(1, 256) + params = bytes(self.random.randrange(256) for _ in range(self.random.randrange(4))) + message = p.Request(key[0], index, key[1], params).encode(sequence) + self.assertEqual(decode(message), (key[0], index, sequence, key[1], params)) + + def test_motor_move_parameters(self) -> None: + for _ in range(50): + values = dict( + velocity=self.random.randrange(2**32), + acceleration=self.random.randrange(2**32), + jerk=self.random.randrange(2**32), + force=self.random.randrange(2**32), + position=self.random.randrange(-(2**31), 2**31), + sensor=self.random.randrange(256), + trigger=self.random.randrange(256), + ) + axis = self.random.randrange(1, 32) + device, index, _, opcode, params = decode( + p.set_motor_move_parameters(axis, **values).encode(1) + ) + self.assertEqual((device, index, opcode), (p.Device.MOTOR, axis, 0x40)) + fields = struct.unpack(" None: + for valve, code in p.VALVE_POSITIONS.items(): + values = [self.random.randrange(2**32) for _ in range(4)] + position = self.random.randrange(-(2**31), 2**31) + request = p.set_pump_move_parameters( + 3, + position, + values[0], + values[1], + values[2], + values[3], + valve, # type: ignore[arg-type] + ) + _, index, _, opcode, params = decode(request.encode(1)) + self.assertEqual((request.device, index, opcode), (p.Device.PUMP, 3, 0x40)) + self.assertEqual(struct.unpack(" None: + for timeout in (0, 5000, 30000, 2**32 - 1): + self.assertEqual(struct.unpack(" None: + for table in (MOTOR_TABLE, PUMP_TABLE): + self.assertEqual(decode(p.configure(p.Device.MOTOR, 1, table).encode(1))[4], table) + + def test_lls_cd_sensitivity(self) -> None: + for clot in (False, True): + for value in (0, 1, 3500, 4095): + params = decode(p.set_lls_cd_sensitivity(clot, value).encode(1))[4] + self.assertEqual(struct.unpack(" None: + for _ in range(50): + header = [self.random.randrange(256) for _ in range(5)] + header[2] = 0 + status = self.random.choice(list(p.Status)) + data = bytes(self.random.randrange(256) for _ in range(self.random.randrange(8))) + reply = p.Reply.parse(bytes(header) + bytes([status]) + data) + self.assertEqual( + (reply.device, reply.index, reply.sequence, reply.opcode, reply.status, reply.data), + (header[0], header[1], header[3], header[4], status, data), + ) + self.assertEqual(reply.key, (header[0], header[1], header[3], header[4])) + self.assertEqual(reply.unsolicited, header[3] == 0) + + def test_numbers(self) -> None: + for _ in range(50): + s32 = self.random.randrange(-(2**31), 2**31) + u32 = self.random.randrange(2**32) + self.assertEqual(p.parse_s32(struct.pack(" None: + counts = {0x02: 6, 0x11: 21, 0x12: 8, 0x22: 300} + payload = b"".join(bytes([d]) + n.to_bytes(2, "little") for d, n in counts.items()) + self.assertEqual(p.parse_device_count(payload), counts) + with self.assertRaises(ValueError): + p.parse_device_count(payload[:-1]) + version = p.parse_hardware_version(bytes([0xE3, 4])) + self.assertEqual((version.type_code, version.revision, str(version)), (0xE3, 4, "AccuFrame 4")) + self.assertEqual(str(p.parse_hardware_version(bytes([0x7A, 1]))), "hardware 0x7A 1") + + +class RefusalTests(unittest.TestCase): + def test_unknown_commands_are_refused(self) -> None: + with self.assertRaises(ValueError): + p.Request(p.Device.BOARD, 1, 0x05) # not a logged opcode: other commands stay unsendable + + def test_index_and_sequence_ranges(self) -> None: + with self.assertRaises(ValueError): + p.Request(p.Device.MOTOR, 256, 0x24) + for sequence in (0, 256): + with self.assertRaises(ValueError): + p.get_module_id().encode(sequence) + + +class ReplyTests(unittest.TestCase): + """Replies as the boards send them (the header, status, then data).""" + + def test_module_id(self) -> None: + seen: List[Tuple[object, object]] = [] + for message in ("000000010002008000", "00000001000200FD01", "00000001000200FB02"): + module = p.parse_module_id( + p.Reply.parse(bytes.fromhex(message)).check("Get Module ID").payload + ) + seen.append((module.type, module.side)) + self.assertEqual(seen, [("chassis", None), ("multichannel", "left"), ("span8", "right")]) + unknown = p.parse_module_id(bytes([0x42, 0x07])) + self.assertEqual((unknown.type, unknown.side), (None, None)) + + def test_strings(self) -> None: + reply = p.Reply.parse(bytes.fromhex("0000000302020053494D554C41544544") + b"0" * 4) + self.assertEqual(p.parse_string(reply.payload), "SIMULATED0000") + reply = p.Reply.parse(bytes.fromhex("02010008100200302E322E34")) + self.assertEqual(p.parse_string(reply.payload), "0.2.4") + + def test_interlock_status(self) -> None: + self.assertEqual(p.parse_interlock_status(b"\x00"), "armed") + self.assertEqual(p.parse_interlock_status(b"\xff"), "tripped") + with self.assertRaisesRegex(ValueError, "not been seen"): + p.parse_interlock_status(b"\x01") + # The unsolicited trip event carries the same byte. + event = p.Reply.parse(bytes.fromhex("01010000100300FF")) + self.assertEqual((event.device, event.opcode), p.INTERLOCK_TRIPPED) + self.assertEqual(p.parse_interlock_status(event.payload), "tripped") + + def test_axis_state(self) -> None: + for code, state in [(0x00, "ENABLED"), (0x01, "DISABLED"), (0xFE, "NOT_CONFIGURED"), + (0xFF, "FAULT")]: # fmt: skip + self.assertEqual(p.parse_axis_state(bytes([code])).name, state) + with self.assertRaises(ValueError): + p.parse_axis_state(b"\x02") + + def test_tip_status(self) -> None: + states = p.parse_tip_status(bytes([0, 2, 1, 2, 0, 0, 2, 9])) + self.assertEqual( + states, ["loaded", "unloaded", "unknown", "unloaded", "loaded", "loaded", "unloaded", None] + ) + + def test_motion_complete(self) -> None: + sensed = p.Reply.parse( + bytes([0x11, 9, 0, 5, 0x50, 0x02, 0, p.LLS_LIQUID_SENSED]) + struct.pack(" None: + emcy = p.parse_emcy(bytes.fromhex("007700100116040100")) + self.assertEqual( + (emcy.node, emcy.error_code, emcy.error_register, emcy.device_error, emcy.source), + (0x77, 0x1000, 0x01, 0x0416, 0x01), + ) + + def test_success_has_no_error(self) -> None: + # Get Module ID's DONE; a Move's ACCEPTED and DONE; the host-alive NOTICE (sequence 0). + for message in ("000000010002" + "008000", "110300AC5001" + "00", "110300AC5002" + "00", + "0000000040FE" + "00"): # fmt: skip + self.assertIsNone(p.Reply.parse(bytes.fromhex(message)).error_code, message) + + def test_errors_raise_their_kind(self) -> None: + cases = { + "1103000712" + "0030": NotConfiguredError, + "1103000751" + "0031": NotEnabledError, + "1103000740" + "0032": NotHomedError, + "1003000750" + "000F": InterlockTrippedError, + "1003000750" + "0238": MotionError, + "110300075002" + "3C0001": MotionError, + "1103000750" + "0077": AceError, + } + for message, kind in cases.items(): + with self.subTest(message=message): + reply = p.Reply.parse(bytes.fromhex(message.replace(" ", ""))) + with self.assertRaises(kind): + reply.raise_for_error("request") + + def test_device_error_follows_the_ace_error(self) -> None: + # A Move whose axis left its error window: DONE, ACE error 0x3C, device error 0x0100. + reply = p.Reply.parse(bytes.fromhex("110300075002" + "3C0001")) + self.assertEqual((reply.error_code, reply.device_error), (0x3C, 0x0100)) + with self.assertRaisesRegex(MotionError, r"device error 0x100: motion error window exceeded"): + reply.raise_for_error("Move Z") + + +class SagianCanTests(unittest.TestCase): + """Forwarded SAGIAN CAN messages, worded as the Master Controller's log words them.""" + + # Every distinct pattern in the Master Controller's logs (2026-07-27 .. 10-27), with its words. + LOGGED = { + "00010500000101f7280fbb40": "TO_NODE 05:00 READ SUCCESS F7 28 0F BB 40", + "00010500000001f0": "TO_NODE 05:00 ACTION SUCCESS F0", + "0001050000020101": "TO_NODE 05:00 WRITE SUCCESS 01", + "000105000003016801": "TO_NODE 05:00 EVENT SUCCESS 68 01", + "00012300040300": "TO_NODE 23:04 EVENT REQUEST", + "00012a00080300": "TO_NODE 2A:08 EVENT REQUEST", + } + + def test_logged_messages_read_as_the_master_controller_reads_them(self) -> None: + for data, words in self.LOGGED.items(): + with self.subTest(data=data): + self.assertEqual(p.describe_sagian_can(bytes.fromhex(data)), (words, True)) + + def test_any_other_status_is_not_called_normal(self) -> None: + text, normal = p.describe_sagian_can(bytes.fromhex("00010500000102")) + self.assertFalse(normal) + self.assertIn("status 0x02", text) + self.assertFalse(p.describe_sagian_can(bytes([0, 1]))[1]) + + +class RoutineUnsolicitedTests(unittest.TestCase): + """Unsolicited messages every session sees, as the instrument sent them (2026-11-09).""" + + @staticmethod + def reply(message: str) -> p.Reply: + return p.Reply.parse(bytes.fromhex(message)) + + def test_a_drive_clearing_its_fault_is_routine(self) -> None: + text = p.describe_routine_unsolicited(self.reply("00000000 31ff 007e0000000000000000")) + self.assertEqual(text, "drive node 0x7E: fault cleared (EMCY 0000)") + + def test_a_drive_reporting_the_interlock_is_routine(self) -> None: + for source in ("01", "02"): + with self.subTest(source=source): + text = p.describe_routine_unsolicited( + self.reply(f"0000000031ff007700100116 04{source}0000") + ) + self.assertEqual(text, "drive node 0x77: interlock active (EMCY 1000)") + + def test_a_move_the_interlock_ended_is_routine(self) -> None: + text = p.describe_routine_unsolicited(self.reply("11120000 50fe 0f1604")) + self.assertEqual(text, "device 0x11 index 18: move ended, interlock tripped") + + def test_other_messages_are_shown(self) -> None: + for message in ( + "00000000 31ff 007e0010010704010000", # another drive error: interlock tripped (0407) + "11120000 50fe 3c0001", # a move ended by its error window + "01010000 1003 00ff", # the chassis: the interlock tripped + "21010000 1003 0001", # a digital input changed (the door) + "00000000 31ff 007e", # too short to read + ): + with self.subTest(message=message): + self.assertIsNone(p.describe_routine_unsolicited(self.reply(message.replace(" ", "")))) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py new file mode 100644 index 00000000000..357375452b9 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py @@ -0,0 +1,103 @@ +"""Simulated boards: boards that answer from what a real Biomek i7's boards answered. + +`ReplayAceUSB` replays a recording; nothing it does reaches a USB device. A replayed board holds a +recording of request -> replies, keyed on everything in a request but its sequence number, and +answers a request it has a recording for with those replies under the request's sequence number. +A request it has no recording for gets no answer, as a board that ignored it would, and is kept in +`unanswered`. +""" + +import asyncio +import gzip +import json +import os +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.framing import frame, split +from pylabrobot.io.usb import USB + +# Names the recording the simulator answers from (identity and sensor reads, recorded at an +# instrument's cold start) when no path is given. A generic one ships in `defaults/` +# (`biomek_i7_generic_coldstart.json`). +RECORDING_ENV = "BIOMEK_I7_SIMULATOR_RECORDING" + + +def recording_path(path: Optional[Union[str, Path]] = None) -> Path: + """`path`, else the file `$BIOMEK_I7_SIMULATOR_RECORDING` names. + + Raises: + ValueError: with neither. + """ + path = path or os.environ.get(RECORDING_ENV) + if not path: + raise ValueError( + f"no recording for the simulator to answer from: pass its path or set ${RECORDING_ENV}" + ) + return Path(path) + + +def load_recording(path: Optional[Union[str, Path]] = None) -> Dict[str, Any]: + """A recording (`recording_path`), gzipped (`.gz`) or not.""" + where = recording_path(path) + if where.suffix == ".gz": + with gzip.open(where, "rt", encoding="utf-8") as fh: + return dict(json.load(fh)) + with open(where, encoding="utf-8") as fh: + return dict(json.load(fh)) + + +def _request_key(message: bytes) -> str: + return (message[:3] + message[4:]).hex() + + +class ReplayAceUSB(USB): + """One board's USB link, answered from a recording.""" + + def __init__(self, recording: Dict[str, List[str]], name: str = "replayed ACE board"): + super().__init__(0x0AB5, 0xACE0, name) + self.recording = {k: [bytes.fromhex(r) for r in v] for k, v in recording.items()} + self.requests: List[bytes] = [] + self.unanswered: List[bytes] = [] + self._packets: "asyncio.Queue[bytes]" = asyncio.Queue() + + async def setup(self, empty_buffer=True): + pass + + async def stop(self): + pass + + async def write(self, data: bytes, timeout: Optional[float] = None): + for message in split(data): + self.requests.append(message) + replies = self.recording.get(_request_key(message)) + if replies is None: + self.unanswered.append(message) + continue + for reply in replies: + framed = frame(reply[:3] + message[3:4] + reply[4:]) + for i in range(0, len(framed), 16): + self._packets.put_nowait(framed[i : i + 16]) + + async def read(self, timeout=None, size=None, endpoint=None) -> bytes: + try: + return await asyncio.wait_for(self._packets.get(), timeout=0.05) + except asyncio.TimeoutError: + raise TimeoutError("no packet") from None + + +def replay_boards( + path: Optional[Union[str, Path]] = None, default_timeout: float = 1.0 +) -> List[AceBoard]: + """One replayed board per module in a recording (`recording_path`), as + `BiomekI7Driver(boards=...)` takes them.""" + data = load_recording(path) + return [ + AceBoard( + io=ReplayAceUSB(dict(entries), name=f"replayed {module}"), + name=f"replayed {module}", + default_timeout=default_timeout, + ) + for module, entries in data["boards"].items() + ] diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator_tests.py new file mode 100644 index 00000000000..d8fcebca10c --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator_tests.py @@ -0,0 +1,80 @@ +"""Replayed boards: what they answer, and what they do not.""" + +import gzip +import json +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ( + RECORDING_ENV, + ReplayAceUSB, + load_recording, + recording_path, + replay_boards, +) + +# Get Module ID answered once, and a Move answered twice (ACCEPTED, then DONE); keys leave out the +# sequence number, and the replies' sequence bytes are placeholders. +RECORDING = { + "00000000": ["000000000002008000"], + "1103005030750000": ["11030000500100", "11030000500200"], +} + + +class ReplayTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + self.io = ReplayAceUSB(RECORDING) + self.board = AceBoard(io=self.io, default_timeout=0.3) + await self.board.setup() + + async def asyncTearDown(self) -> None: + await self.board.stop() + + async def test_a_recorded_request_is_answered_under_its_own_sequence(self) -> None: + for _ in range(3): # each send takes the next sequence number; the recording ignores it + reply = await self.board.send(p.get_module_id()) + self.assertEqual(p.parse_module_id(reply.payload).type, "chassis") + self.assertEqual([m[3] for m in self.io.requests], [1, 2, 3]) + self.assertEqual(self.io.unanswered, []) + + async def test_replies_come_in_their_recorded_order(self) -> None: + reply = await self.board.send(p.move(3, 30000)) + self.assertEqual(reply.status, p.Status.DONE) + + async def test_an_unrecorded_request_gets_no_answer(self) -> None: + with self.assertRaises(TimeoutError): + await self.board.send(p.get_module_serial_number()) + self.assertEqual(self.io.unanswered, [p.get_module_serial_number().encode(1)]) + + +class RecordingFileTests(unittest.TestCase): + def test_gzipped_and_plain_recordings_load(self) -> None: + data = {"boards": {"chassis": [["00000000", ["000000000002008000"]]]}} + with tempfile.TemporaryDirectory() as folder: + plain = Path(folder) / "recording.json" + plain.write_text(json.dumps(data), encoding="utf-8") + packed = Path(folder) / "recording.json.gz" + with gzip.open(packed, "wt", encoding="utf-8") as fh: + json.dump(data, fh) + self.assertEqual(load_recording(plain), data) + self.assertEqual(load_recording(packed), data) + boards = replay_boards(packed) + self.assertEqual([b.name for b in boards], ["replayed chassis"]) + + def test_a_recording_must_be_named(self) -> None: + environment = {k: v for k, v in os.environ.items() if k != RECORDING_ENV} + with mock.patch.dict(os.environ, environment, clear=True): + with self.assertRaisesRegex(ValueError, RECORDING_ENV): + recording_path() + with mock.patch.dict(os.environ, {RECORDING_ENV: "from-the-environment.json"}): + self.assertEqual(recording_path(), Path("from-the-environment.json")) + self.assertEqual(recording_path("given.json"), Path("given.json")) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py new file mode 100644 index 00000000000..c07366257d4 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py @@ -0,0 +1,47 @@ +"""What the package's tests build their simulated Biomek i7 from: the generic one in `defaults/`, +named explicitly (never through `$BIOMEK_I7_SIMULATOR_RECORDING`). Not a test module itself.""" + +import copy +import json +from typing import Any, Dict, List, Optional, Sequence + +from pylabrobot.beckman_coulter.biomek_i7.defaults import GENERIC_RECORDING +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB + +_GENERIC: Optional[Dict[str, Any]] = None + + +def generic_recording() -> Dict[str, Any]: + """The generic cold-start recording, a fresh copy a test may change: `boards` maps each module + (`chassis`, `multichannel`, `span8`) to its [request key, [replies]] pairs.""" + global _GENERIC + if _GENERIC is None: + with open(GENERIC_RECORDING, encoding="utf-8") as fh: + _GENERIC = json.load(fh) + return copy.deepcopy(_GENERIC) + + +def generic_boards( + recording: Optional[Dict[str, Any]] = None, + modules: Optional[Sequence[str]] = None, + default_timeout: float = 1.0, +) -> List[AceBoard]: + """A replayed board per module of `recording` (by default the generic one), as + `simulator.replay_boards` builds them; `modules` picks and orders them.""" + data = recording if recording is not None else generic_recording() + names = list(data["boards"]) if modules is None else list(modules) + return [ + AceBoard( + io=ReplayAceUSB(dict(data["boards"][module]), name=f"replayed {module}"), + name=f"replayed {module}", + default_timeout=default_timeout, + ) + for module in names + ] + + +def generic_driver(boards: Optional[Sequence[AceBoard]] = None) -> BiomekI7Driver: + """A driver over `boards`, by default the generic instrument replayed.""" + return BiomekI7Driver(boards=generic_boards() if boards is None else boards) diff --git a/pylabrobot/io/usb.py b/pylabrobot/io/usb.py index d8028dbf8ee..8f8b98b524a 100644 --- a/pylabrobot/io/usb.py +++ b/pylabrobot/io/usb.py @@ -351,7 +351,9 @@ def get_available_devices(self) -> List["usb.core.Device"]: continue if self._serial_number is not None: - if dev._serial_number is None: + # PyUSB reads the serial number descriptor on first access; `_serial_number` is only its + # cache, empty until then. + if dev.iSerialNumber == 0 or dev.serial_number is None: raise RuntimeError( f"A serial number was specified for '{self.human_readable_device_name}', but the device does not have a serial number." ) diff --git a/pylabrobot/io/usb_tests.py b/pylabrobot/io/usb_tests.py index 358d1f12ad5..c8ab3787f12 100644 --- a/pylabrobot/io/usb_tests.py +++ b/pylabrobot/io/usb_tests.py @@ -189,3 +189,28 @@ def test_validator_replays_a_write(self) -> None: ] validator = USBValidator(capture, "mock USB", 1, 2) self.assertEqual(validator.ctrl_transfer(0x40, 1, 0, 0, b"\x01"), bytearray()) + + +class USBDeviceSelectionTests(unittest.TestCase): + """Pick a device by serial number, reading the descriptor rather than PyUSB's empty cache.""" + + def _devices(self, *serials): + devices = [] + for serial in serials: + dev = Mock(iSerialNumber=3 if serial else 0, _serial_number=None, serial_number=serial) + devices.append(dev) + return devices + + def test_serial_number_is_read_through_the_descriptor(self) -> None: + devices = self._devices("A", "B") + with patch.object(usb_module, "libusb_package", create=True) as lib: + lib.find.return_value = devices + self.assertEqual( + USB(1, 2, "mock USB", serial_number="B").get_available_devices(), [devices[1]] + ) + + def test_device_without_serial_number_is_refused(self) -> None: + with patch.object(usb_module, "libusb_package", create=True) as lib: + lib.find.return_value = self._devices(None) + with self.assertRaisesRegex(RuntimeError, "does not have a serial number"): + USB(1, 2, "mock USB", serial_number="B").get_available_devices() diff --git a/pylabrobot/resources/__init__.py b/pylabrobot/resources/__init__.py index 07e878f25eb..00d3176d54e 100644 --- a/pylabrobot/resources/__init__.py +++ b/pylabrobot/resources/__init__.py @@ -3,6 +3,7 @@ from .agilent import * from .alpaqua import * from .azenta import * +from .beckman_coulter import * from .biorad import * from .boekel import * from .btx import * diff --git a/pylabrobot/resources/beckman_coulter/__init__.py b/pylabrobot/resources/beckman_coulter/__init__.py new file mode 100644 index 00000000000..4d4403ce12c --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/__init__.py @@ -0,0 +1,24 @@ +from .biomek_resource import BiomekTip, BiomekWell, WellSegment +from .plates import ( + beckman_coulter_biomek_24_wellplate_square_rb, + beckman_coulter_biomek_96_deepwell_square, + beckman_coulter_biomek_96_wellplate_flat, + beckman_coulter_biomek_96_wellplate_vb, + beckman_coulter_biomek_modular_reservoir, + beckman_coulter_biomek_reservoir, + beckman_coulter_biomek_reservoir_350cb, +) +from .tip_racks import ( + beckman_coulter_biomek_96_tiprack_50uL_filter, + beckman_coulter_biomek_96_tiprack_190uL_filter, + beckman_coulter_biomek_96_tiprack_230uL, + beckman_coulter_biomek_96_tiprack_1025uL_filter, + beckman_coulter_biomek_96_tiprack_1070uL, +) +from .tips import ( + beckman_coulter_biomek_tip_50uL_filter, + beckman_coulter_biomek_tip_190uL_filter, + beckman_coulter_biomek_tip_230uL, + beckman_coulter_biomek_tip_1025uL_filter, + beckman_coulter_biomek_tip_1070uL, +) diff --git a/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py b/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py new file mode 100644 index 00000000000..9d267dddfc9 --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py @@ -0,0 +1,204 @@ +"""Beckman Coulter Biomek tips, tip boxes, plates and reservoirs, against the figures of the Biomek +classes they transcribe (cm there, mm here).""" + +import math +import unittest + +from pylabrobot.resources import ( + BiomekTip, + BiomekWell, + Plate, + Resource, + WellSegment, + beckman_coulter_biomek_24_wellplate_square_rb, + beckman_coulter_biomek_96_deepwell_square, + beckman_coulter_biomek_96_tiprack_50uL_filter, + beckman_coulter_biomek_96_tiprack_190uL_filter, + beckman_coulter_biomek_96_tiprack_230uL, + beckman_coulter_biomek_96_tiprack_1025uL_filter, + beckman_coulter_biomek_96_tiprack_1070uL, + beckman_coulter_biomek_96_wellplate_flat, + beckman_coulter_biomek_96_wellplate_vb, + beckman_coulter_biomek_modular_reservoir, + beckman_coulter_biomek_reservoir, + beckman_coulter_biomek_reservoir_350cb, + beckman_coulter_biomek_tip_50uL_filter, + beckman_coulter_biomek_tip_190uL_filter, + beckman_coulter_biomek_tip_230uL, + beckman_coulter_biomek_tip_1025uL_filter, + beckman_coulter_biomek_tip_1070uL, +) +from pylabrobot.resources.tip_rack import StandingTipRack + + +class BiomekTipTests(unittest.TestCase): + def test_a_tip_has_its_class_figures(self) -> None: + # tipheight, capacity, filtered, coniclength (cm); every class seats 0.775 cm on the mandrel. + for make, length, volume, has_filter, cone in ( + (beckman_coulter_biomek_tip_50uL_filter, 51.359, 50.0, True, 38.227), + (beckman_coulter_biomek_tip_190uL_filter, 51.435, 190.0, True, 28.194), + (beckman_coulter_biomek_tip_230uL, 51.435, 230.0, False, 28.194), + (beckman_coulter_biomek_tip_1025uL_filter, 109.855, 1025.0, True, 19.8374), + (beckman_coulter_biomek_tip_1070uL, 109.855, 1070.0, False, 19.8374), + ): + with self.subTest(make.__name__): + tip = make("tip") + self.assertIsInstance(tip, BiomekTip) + self.assertAlmostEqual(tip.get_size_z(), length) + self.assertEqual(tip.maximal_volume, volume) + self.assertEqual(tip.has_filter, has_filter) + self.assertAlmostEqual(tip.fitting_depth, 7.75) + self.assertAlmostEqual(tip.cone_length, cone) + self.assertFalse(tip.is_conductive) + self.assertEqual(tip.model, make.__name__) + + def test_a_tip_widens_along_its_cone(self) -> None: + tip = beckman_coulter_biomek_tip_1070uL("tip") # mintipradius 0.0635, maxtipradius 0.2413 cm + self.assertAlmostEqual(tip.radius_at(0), 0.635) + self.assertAlmostEqual(tip.radius_at(19.8374 / 2), (0.635 + 2.413) / 2) + self.assertAlmostEqual(tip.radius_at(50), 2.413) + + def test_a_tip_reads_back_from_its_serialization(self) -> None: + tip = beckman_coulter_biomek_tip_230uL("tip") + back = Resource.deserialize(tip.serialize()) + self.assertIsInstance(back, BiomekTip) + self.assertEqual(back, tip) + self.assertNotEqual(back, beckman_coulter_biomek_tip_1070uL("tip")) + + +class BiomekTipBoxTests(unittest.TestCase): + BOXES = ( + # make, height, well1xoffset (mm), tip length + (beckman_coulter_biomek_96_tiprack_50uL_filter, 55.9, 14.5, 51.359), + (beckman_coulter_biomek_96_tiprack_190uL_filter, 55.9, 14.5, 51.435), + (beckman_coulter_biomek_96_tiprack_230uL, 55.9, 14.5, 51.435), + (beckman_coulter_biomek_96_tiprack_1025uL_filter, 114.1, 14.4, 109.855), + (beckman_coulter_biomek_96_tiprack_1070uL, 114.1, 14.4, 109.855), + ) + + def test_a_box_holds_96_of_its_tips_on_a_9_mm_grid(self) -> None: + for make, _, _, tip_length in self.BOXES: + with self.subTest(make.__name__): + rack = make("rack") + self.assertIsInstance(rack, StandingTipRack) + self.assertEqual((rack.num_items_x, rack.num_items_y), (12, 8)) + self.assertTrue(all(spot.has_tip() for spot in rack.get_all_items())) + self.assertAlmostEqual(rack.get_item("A1").get_tip().get_size_z(), tip_length) + a1 = rack.get_item("A1").get_location_wrt(rack) + a2 = rack.get_item("A2").get_location_wrt(rack) + b1 = rack.get_item("B1").get_location_wrt(rack) + self.assertAlmostEqual(a2.x - a1.x, 9.0) + self.assertAlmostEqual(a1.y - b1.y, 9.0) + + def test_tip_a1_stands_where_the_class_puts_it(self) -> None: + """A1's centre is `well1xoffset` from the left edge and 1.12 cm from the back edge; the tips' + tops are at the box's height, where the head's mandrels meet them.""" + for make, height, a1_x, _ in self.BOXES: + with self.subTest(make.__name__): + rack = make("rack") + self.assertEqual((rack.get_size_x(), rack.get_size_y()), (127.9, 85.4)) + self.assertAlmostEqual(rack.get_size_z(), height) + centre = rack.get_item("A1").get_location_wrt(rack, "c", "c", "b") + self.assertAlmostEqual(centre.x, a1_x) + self.assertAlmostEqual(centre.y, 85.4 - 11.2) + self.assertAlmostEqual(centre.z, height) + + def test_a_box_is_gripped_below_its_top(self) -> None: + # gripperinfo: the pads at its centre, the fingertips 0.23 cm below its bottom. + rack = beckman_coulter_biomek_96_tiprack_230uL("rack") + point = rack.preferred_pickup_location + assert point is not None + self.assertAlmostEqual(point.x, 127.9 / 2) + self.assertAlmostEqual(point.y, 85.4 / 2) + self.assertAlmostEqual(point.z, -2.3) + + +class BiomekPlateTests(unittest.TestCase): + def test_a_segment_holds_biomeks_section_volume(self) -> None: + # `sectionvolume` (uL) of each segment, from its outline: a cone, a frustum, a rectangular + # section, a round bottom (a spherical cap). + for make, volumes in ( + (beckman_coulter_biomek_96_wellplate_vb, (15.6665, 427.2566)), + (beckman_coulter_biomek_96_wellplate_flat, (365.708,)), + (beckman_coulter_biomek_96_deepwell_square, (133.645, 2282.995)), + (beckman_coulter_biomek_24_wellplate_square_rb, (1072.3303, 9248.0)), + ): + well = make("plate").get_well("A1") + assert isinstance(well, BiomekWell) + for segment, volume in zip(well.segments, volumes): + with self.subTest(make.__name__, volume=volume): + self.assertAlmostEqual(segment.volume(segment.height), volume, delta=0.002 * volume) + + def test_the_logged_liquid_level(self) -> None: + # 200 uL in Thermo96VB_PP: the 96-head's logged dispense rose 0.567 cm with the liquid. + well = beckman_coulter_biomek_96_wellplate_vb("plate").get_well("A1") + self.assertAlmostEqual(well.compute_height_from_volume(200), 5.667, delta=0.01) + assert isinstance(well, BiomekWell) + self.assertAlmostEqual(well.wall_distance(3.67, 0.0), 4.0) + + def test_a_square_well_meets_its_wall_at_the_side(self) -> None: + well = beckman_coulter_biomek_96_deepwell_square("plate").get_well("A1") + assert isinstance(well, BiomekWell) + self.assertAlmostEqual(well.get_size_x(), 8.28) + self.assertAlmostEqual(well.wall_distance(20.0, 0.0), 4.14) + self.assertAlmostEqual(well.wall_distance(20.0, math.pi / 4), 4.14 * math.sqrt(2)) + + def test_a_well_reads_back_from_its_serialization(self) -> None: + plate = beckman_coulter_biomek_96_wellplate_vb("plate", with_lid=True) + back = Resource.deserialize(plate.serialize()) + assert isinstance(back, Plate) + well = back.get_item("A1") + assert isinstance(well, BiomekWell) + self.assertEqual(well, plate.get_item("A1")) + self.assertEqual(well.segments[0], WellSegment(2.0, 2.735, 2.735, 0.0, 0.0)) + + def test_a_lid_sits_where_biomek_seats_it(self) -> None: + # Logged: the fingertips 1.000 cm above the plate's bottom for TiterplateLid on Thermo96VB_PP, + # and 4.200 cm for the Thomson lid on its plate. The lid covers the plate's footprint. + for make, tips_above in ( + (beckman_coulter_biomek_96_wellplate_vb, 10.0), + (beckman_coulter_biomek_24_wellplate_square_rb, 42.0), + ): + with self.subTest(make.__name__): + plate = make("plate", with_lid=True) + lid = plate.lid + assert lid is not None and lid.location is not None + point = lid.preferred_pickup_location + assert point is not None + self.assertAlmostEqual(lid.location.z + point.z, tips_above) + self.assertEqual( + (lid.get_size_x(), lid.get_size_y()), (plate.get_size_x(), plate.get_size_y()) + ) + + def test_an_uncentred_seat_moves_the_grip_point(self) -> None: + # The Thomson lid's seat is its plate's corner: its centre 0.381 mm left, 1.46 mm back. + plate = beckman_coulter_biomek_24_wellplate_square_rb("plate", with_lid=True) + lid = plate.lid + assert lid is not None and lid.preferred_pickup_location is not None + self.assertAlmostEqual(lid.preferred_pickup_location.x - lid.get_size_x() / 2, -0.381) + self.assertAlmostEqual(lid.preferred_pickup_location.y - lid.get_size_y() / 2, 1.4605) + + def test_plates_are_gripped_below_their_bottom(self) -> None: + plate = beckman_coulter_biomek_96_wellplate_vb("plate") + assert plate.preferred_pickup_location is not None + self.assertAlmostEqual(plate.preferred_pickup_location.z, -2.3) + + +class BiomekReservoirTests(unittest.TestCase): + def test_a_reservoir_section_is_a_box(self) -> None: + well = beckman_coulter_biomek_reservoir_350cb("res").get_well("A1") + self.assertAlmostEqual(well.compute_volume_from_height(10), 123.8 * 81.5 * 10, delta=0.01) + self.assertEqual(well.max_volume, 300000.0) + + def test_reservoirs_have_a_well_per_section(self) -> None: + self.assertEqual(len(beckman_coulter_biomek_reservoir("res").children), 1) + modular = beckman_coulter_biomek_modular_reservoir("mod") + self.assertEqual(len(modular.children), 4) + a1 = modular.get_item("A1") + self.assertAlmostEqual(a1.get_size_x(), 23.65) # x1 1.105 to x2 3.47 cm + assert isinstance(a1, BiomekWell) + self.assertEqual(a1.segments, ()) # a V bottom Biomek does not outline + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/resources/beckman_coulter/biomek_resource.py b/pylabrobot/resources/beckman_coulter/biomek_resource.py new file mode 100644 index 00000000000..63f6721c23d --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/biomek_resource.py @@ -0,0 +1,219 @@ +"""Biomek's own shapes on PyLabRobot's resources: a tip's cone and a well's outline by height. + +Biomek describes a tip by its length, capacity and seating depth (which `Tip` holds) and also by its +cone, and a well by its sections from the bottom up, each with an outline that changes with height. +A Biomek touch-off places the tip against the wall at a height, so it needs both: these classes +carry them, and everything else about the resource is PyLabRobot's. +""" + +import math +from dataclasses import asdict, dataclass +from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union + +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.resource import Resource +from pylabrobot.resources.tip import Tip +from pylabrobot.resources.well import Well +from pylabrobot.utils.interpolation import interpolate_1d + + +class BiomekTip(Tip): + """A tip for Biomek instruments: a `Tip` with its cone, which Biomek uses to place the tip near a + wall (a touch-off), from `end_diameter` at its end to `diameter` over `cone_length` (mm).""" + + def __init__( + self, + name: str, + diameter: float, + size_z: float, + has_filter: bool, + maximal_volume: float, + fitting_depth: float, + end_diameter: float, + cone_length: float, + nominal_volume: Optional[float] = None, + collar_height: Optional[float] = None, + category: str = "tip", + model: Optional[str] = None, + pick_up_location: Optional[Coordinate] = None, + is_conductive: Optional[bool] = None, + ): + """Initialize a Biomek tip with its dimensions and its cone.""" + super().__init__( + name=name, + diameter=diameter, + size_z=size_z, + has_filter=has_filter, + maximal_volume=maximal_volume, + fitting_depth=fitting_depth, + nominal_volume=nominal_volume, + collar_height=collar_height, + category=category, + model=model, + pick_up_location=pick_up_location, + is_conductive=is_conductive, + ) + self.end_diameter = end_diameter + self.cone_length = cone_length + + def __eq__(self, other: object) -> bool: + """Compare tip fields and the cone.""" + return ( + isinstance(other, BiomekTip) + and super().__eq__(other) + and self.end_diameter == other.end_diameter + and self.cone_length == other.cone_length + ) + + def serialize(self) -> dict: + """Serialize a Biomek tip with its cone.""" + return { + **super().serialize(), + "end_diameter": self.end_diameter, + "cone_length": self.cone_length, + } + + def radius_at(self, from_end: float) -> float: + """The tip's outside radius `from_end` mm above its end: widening along the cone, then its + full radius.""" + end, full = self.end_diameter / 2, self.get_size_x() / 2 + if self.cone_length <= 0: + return full + return end + (full - end) * min(max(from_end, 0.0) / self.cone_length, 1.0) + + +@dataclass(frozen=True) +class WellSegment: + """One section of a Biomek well, from the bottom up, in mm. + + Attributes: + height: how tall the section is. + top_x, top_y: its half-widths at its top (the radius, for a round section). + bottom_x, bottom_y: its half-widths at its bottom (0 for a cone from a point). + round: whether its outline is round (else a rectangle). + cap: a round bottom: a spherical cap reaching `top_x` at `height`. + """ + + height: float + top_x: float + top_y: float + bottom_x: float + bottom_y: float + round: bool = True + cap: bool = False + + def half_widths(self, z: float) -> Tuple[float, float]: + """Half-widths (x, y), mm, `z` mm above the section's bottom.""" + if self.cap: + sphere = (self.top_x * self.top_x + self.height * self.height) / (2 * self.height) + r = math.sqrt(max(0.0, 2 * sphere * z - z * z)) + return r, r + t = z / self.height + return ( + self.bottom_x + (self.top_x - self.bottom_x) * t, + self.bottom_y + (self.top_y - self.bottom_y) * t, + ) + + def area(self, z: float) -> float: + """Cross-section, mm^2, `z` mm above the section's bottom.""" + hx, hy = self.half_widths(z) + return math.pi * hx * hy if self.round else 4 * hx * hy + + def volume(self, h: float) -> float: + """uL (mm^3) in the bottom `h` mm of the section. The area is quadratic in z for every shape, + so Simpson's rule is exact.""" + h = min(h, self.height) + if h <= 0: + return 0.0 + return h / 6 * (self.area(0) + 4 * self.area(h / 2) + self.area(h)) + + +# mm between a height -> volume table's heights where a section's cross-section changes with height +# (a cone, a cap): PyLabRobot interpolates between them. +KNOT_STEP = 0.1 + + +class BiomekWell(Well): + """A well with Biomek's outline by height (`segments`, bottom up): its height <-> volume table + (`height_volume_data`) is made from them, and `wall_distance` says where its wall is at a height. + With no segments it is a plain `Well`.""" + + def __init__( + self, + name: str, + size_x: float, + size_y: float, + size_z: float, + segments: Sequence[Union[WellSegment, Mapping[str, Any]]] = (), + height_volume_data: Optional[Dict[float, float]] = None, + max_volume: Optional[float] = None, + **kwargs: Any, + ): + self.segments: Tuple[WellSegment, ...] = tuple( + s if isinstance(s, WellSegment) else WellSegment(**s) for s in segments + ) + if height_volume_data is None and self.segments: + height_volume_data = self._height_volume_table(size_z) + if max_volume is None and height_volume_data is not None: + max_volume = interpolate_1d(size_z, height_volume_data, bounds_handling="error") + super().__init__( + name=name, + size_x=size_x, + size_y=size_y, + size_z=size_z, + height_volume_data=height_volume_data, + max_volume=max_volume, + **kwargs, + ) + + def half_widths(self, z: float) -> Tuple[float, float]: + """Half-widths (x, y), mm, `z` mm above the bottom (the top's above the top).""" + left = max(0.0, z) + for seg in self.segments: + if left <= seg.height: + return seg.half_widths(left) + left -= seg.height + last = self.segments[-1] + return last.half_widths(last.height) + + def wall_distance(self, z: float, angle: float) -> float: + """How far, mm, the wall is from the well's axis `z` mm above its bottom, in direction `angle` + (radians): the radius for a round well, to the nearest side for a rectangular one.""" + hx, hy = self.half_widths(z) + if all(s.round for s in self.segments): + return hx + c, s = abs(math.cos(angle)), abs(math.sin(angle)) + return min(hx / c if c > 1e-12 else math.inf, hy / s if s > 1e-12 else math.inf) + + def volume_at(self, z: float) -> float: + """uL held `z` mm above the bottom, by the segments.""" + left, v = z, 0.0 + for seg in self.segments: + v += seg.volume(left) + left -= seg.height + if left <= 0: + break + return v + + def _height_volume_table(self, depth: float) -> Dict[float, float]: + """A point at each section's ends, and every `KNOT_STEP` in a section whose cross-section + changes, up to the rim.""" + zs = [0.0] + for seg in self.segments: + h = seg.height + constant = seg.half_widths(0.0) == seg.half_widths(h) == seg.half_widths(h / 2) + n = 1 if constant else max(1, math.ceil(h / KNOT_STEP)) + zs += [zs[-1] + h * i / n for i in range(1, n + 1)] + if depth > zs[-1]: + zs.append(depth) + return {round(z, 6): self.volume_at(z) for z in zs} + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, BiomekWell) and super().__eq__(other) and self.segments == other.segments + ) + + __hash__ = Resource.__hash__ + + def serialize(self) -> dict: + return {**super().serialize(), "segments": [asdict(s) for s in self.segments]} diff --git a/pylabrobot/resources/beckman_coulter/plates.py b/pylabrobot/resources/beckman_coulter/plates.py new file mode 100644 index 00000000000..62de4335952 --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/plates.py @@ -0,0 +1,348 @@ +"""Plates and reservoirs on Biomek's labware classes (cm there, mm here). + +- `xspan`, `yspan`, `height`: the footprint and height; `wellsx` / `wellsy`, `wellxspacing` / + `wellyspacing`, `well1xoffset` / `well1yoffset` (A1's centre from the left and back edges): the + grid; `welldepth`, the top segment's `topx` / `topy`: a well's size. +- `segments`: a well's outline from the bottom up (`WellSegment`), which gives its height <-> + volume table and where its wall is. +- a reservoir's `sections`: its wells, `x1..x2`, `y1..y2` from the left and back edges, `depth`. +- `gripperinfo`: where Biomek's gripper pads go (`preferred_pickup_location`), the fingertips + `gripperzoffset` above the bottom (below it for a plate). +- `stackablelabwareclasses`: how deep a lid sits on it. +""" + +from typing import Dict, Optional + +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.lid import Lid +from pylabrobot.resources.plate import Plate +from pylabrobot.resources.utils import create_ordered_items_2d +from pylabrobot.resources.well import CrossSectionType, Well, WellBottomType + +from .biomek_resource import BiomekWell, WellSegment + +_96_WELLPLATE_VB_SEGMENTS = ( + WellSegment(2.0, 2.735, 2.735, 0.0, 0.0), + WellSegment(8.5, 4.0, 4.0, 4.0, 4.0), +) + +_96_WELLPLATE_FLAT_SEGMENTS = (WellSegment(10.668, 3.43, 3.43, 3.175, 3.175),) + +_96_DEEPWELL_SQUARE_SEGMENTS = ( + WellSegment(8.61, 3.85, 3.85, 0.0, 0.0), + WellSegment(33.3, 4.14, 4.14, 4.14, 4.14, round=False), +) + +_24_WELLPLATE_SQUARE_RB_SEGMENTS = ( + WellSegment(8.0, 8.0, 8.0, 0.0, 0.0, cap=True), + WellSegment(32.0, 8.5, 8.5, 8.5, 8.5, round=False), +) + + +def beckman_coulter_biomek_96_wellplate_vb(name: str, with_lid: bool = False) -> Plate: + """Greiner polystyrene microplate with 96 round, V-bottomed wells. Part no. 651XXX. + + Biomek labware class Thermo96VB_PP.""" + lid: Optional[Lid] = None + if with_lid: + # PyLabRobot's lid covers the plate's footprint; Biomek seats it + # (stackablelabwareclasses TiterplateLid: x 0.04, y 0.152, z 0.8 cm) 6.1 mm into the plate. + lid = Lid( + name=f"{name}_lid", + size_x=127.8, + size_y=85.6, + size_z=10.0, # TiterplateLid height 1.0 cm + nesting_z_height=6.1, + model="beckman_coulter_biomek_lid_titerplatelid", + ) + # Biomek's pads: the TiterplateLid's own centre on its seat, gripperzoffset above its bottom. + lid.preferred_pickup_location = Coordinate(63.9, 42.805, 2.0) + plate = Plate( + name=name, + size_x=127.8, # xspan 12.78 cm + size_y=85.6, # yspan 8.56 cm + size_z=14.1, # height 1.41 cm + model=beckman_coulter_biomek_96_wellplate_vb.__name__, + lid=lid, + ordered_items=create_ordered_items_2d( + BiomekWell, + num_items_x=12, + num_items_y=8, + dx=11.31, # well1xoffset 1.44 cm, less half the well + dy=8.31, # the front row; A1 (well1yoffset 1.12 cm) is at the back + dz=3.6, + item_dx=9.0, + item_dy=9.0, + size_x=6.18, + size_y=6.18, + size_z=10.5, # welldepth 1.05 cm + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.CIRCLE, + segments=_96_WELLPLATE_VB_SEGMENTS, + max_volume=440.0, # wellvolume + name_prefix=name, + ), + ) + plate.preferred_pickup_location = Coordinate(63.9, 42.8, -2.3) + return plate + + +def beckman_coulter_biomek_96_wellplate_flat(name: str, with_lid: bool = False) -> Plate: + """Beckman Coulter microplate with 96 round, flat-bottomed wells. Part no. 609844. + + Biomek labware class BCFlat96.""" + lid: Optional[Lid] = None + if with_lid: + # PyLabRobot's lid covers the plate's footprint; Biomek seats it + # (stackablelabwareclasses TiterplateLid: x 0.038, y 0.146, z 0.8 cm) 6.224 mm into the plate. + lid = Lid( + name=f"{name}_lid", + size_x=127.762, + size_y=85.471, + size_z=10.0, # TiterplateLid height 1.0 cm + nesting_z_height=6.224, + model="beckman_coulter_biomek_lid_titerplatelid", + ) + # Biomek's pads: the TiterplateLid's own centre on its seat, gripperzoffset above its bottom. + lid.preferred_pickup_location = Coordinate(63.88, 42.736, 2.0) + plate = Plate( + name=name, + size_x=127.762, # xspan 12.7762 cm + size_y=85.471, # yspan 8.5471 cm + size_z=14.224, # height 1.4224 cm + model=beckman_coulter_biomek_96_wellplate_flat.__name__, + lid=lid, + ordered_items=create_ordered_items_2d( + BiomekWell, + num_items_x=12, + num_items_y=8, + dx=10.95, # well1xoffset 1.438 cm, less half the well + dy=7.811, # the front row; A1 (well1yoffset 1.123 cm) is at the back + dz=3.556, + item_dx=9.0, + item_dy=9.0, + size_x=6.86, + size_y=6.86, + size_z=10.668, # welldepth 1.0668 cm + bottom_type=WellBottomType.FLAT, + cross_section_type=CrossSectionType.CIRCLE, + segments=_96_WELLPLATE_FLAT_SEGMENTS, + max_volume=362.76, # wellvolume + name_prefix=name, + ), + ) + plate.preferred_pickup_location = Coordinate(63.881, 42.7355, -2.3) + return plate + + +def beckman_coulter_biomek_96_deepwell_square(name: str) -> Plate: + """Beckman Coulter microplate with 96 deep, square, V-bottomed wells. Part no. 140504. + + Biomek labware class BCDeep96Square.""" + plate = Plate( + name=name, + size_x=128.17, # xspan 12.817 cm + size_y=85.98, # yspan 8.598 cm + size_z=44.2, # height 4.42 cm + model=beckman_coulter_biomek_96_deepwell_square.__name__, + ordered_items=create_ordered_items_2d( + BiomekWell, + num_items_x=12, + num_items_y=8, + dx=10.2364, # well1xoffset 1.43764 cm, less half the well + dy=7.46, # the front row; A1 (well1yoffset 1.138 cm) is at the back + dz=2.29, + item_dx=9.0, + item_dy=9.0, + size_x=8.28, + size_y=8.28, + size_z=41.91, # welldepth 4.191 cm + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.RECTANGLE, + segments=_96_DEEPWELL_SQUARE_SEGMENTS, + max_volume=2200.0, # wellvolume + name_prefix=name, + ), + ) + plate.preferred_pickup_location = Coordinate(64.085, 42.99, -2.3) + return plate + + +def beckman_coulter_biomek_24_wellplate_square_rb(name: str, with_lid: bool = False) -> Plate: + """Thomson microplate with 24 square, round-bottomed wells. Part no. 931568. + + Biomek labware class Thomson_24w_Square_RB.""" + lid: Optional[Lid] = None + if with_lid: + # PyLabRobot's lid covers the plate's footprint; Biomek seats it + # (stackablelabwareclasses Thomson_24w_Square_RB_Lid: x 0.0, y 0.0, z 3.4 cm) 10.0 mm into the plate. + lid = Lid( + name=f"{name}_lid", + size_x=127.762, + size_y=85.471, + size_z=10.0, # Thomson_24w_Square_RB_Lid height 1.0 cm + nesting_z_height=10.0, + model="beckman_coulter_biomek_lid_thomson_24w_square_rb_lid", + ) + # Biomek's pads: the Thomson_24w_Square_RB_Lid's own centre on its seat, gripperzoffset above its bottom. + lid.preferred_pickup_location = Coordinate(63.5, 44.196, 8.0) + plate = Plate( + name=name, + size_x=127.762, # xspan 12.7762 cm + size_y=85.471, # yspan 8.5471 cm + size_z=44.0, # height 4.4 cm + model=beckman_coulter_biomek_24_wellplate_square_rb.__name__, + lid=lid, + ordered_items=create_ordered_items_2d( + BiomekWell, + num_items_x=6, + num_items_y=4, + dx=10.5, # well1xoffset 1.9 cm, less half the well + dy=6.971, # the front row; A1 (well1yoffset 1.6 cm) is at the back + dz=4.0, + item_dx=18.0, + item_dy=18.0, + size_x=17.0, + size_y=17.0, + size_z=40.0, # welldepth 4.0 cm + bottom_type=WellBottomType.U, + cross_section_type=CrossSectionType.RECTANGLE, + segments=_24_WELLPLATE_SQUARE_RB_SEGMENTS, + max_volume=10000.0, # wellvolume + name_prefix=name, + ), + ) + plate.preferred_pickup_location = Coordinate(63.881, 42.7355, -2.3) + return plate + + +def beckman_coulter_biomek_reservoir_350cb(name: str, with_lid: bool = False) -> Plate: + """Thermo Nunc reservoir with one flat-bottomed section. + + Biomek labware class ThermoNUNC_350CB: a well per section.""" + lid: Optional[Lid] = None + if with_lid: + # PyLabRobot's lid covers the plate's footprint; Biomek seats it + # (stackablelabwareclasses TiterplateLid: x 0.0, y 0.0, z 3.4 cm) 4.0 mm into the plate. + lid = Lid( + name=f"{name}_lid", + size_x=127.8, + size_y=85.85, + size_z=10.0, # TiterplateLid height 1.0 cm + nesting_z_height=4.0, + model="beckman_coulter_biomek_lid_titerplatelid", + ) + # Biomek's pads: the TiterplateLid's own centre on its seat, gripperzoffset above its bottom. + lid.preferred_pickup_location = Coordinate(63.5, 44.575, 2.0) + wells: Dict[str, Well] = {} + wells["A1"] = BiomekWell( + name=f"{name}_A1", + size_x=123.8, # x1 0.2 to x2 12.58 cm + size_y=81.5, # y1 0.2 to y2 8.35 cm + size_z=37.4, # depth 3.74 cm + segments=(WellSegment(37.4, 61.9, 40.75, 61.9, 40.75, round=False),), + bottom_type=WellBottomType.FLAT, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=300000.0, # maxvolume + ) + wells["A1"].location = Coordinate(2.0, 2.35, 0.6) + plate = Plate( + name=name, + size_x=127.8, # xspan 12.78 cm + size_y=85.85, # yspan 8.585 cm + size_z=38.0, # height 3.8 cm + model=beckman_coulter_biomek_reservoir_350cb.__name__, + lid=lid, + ordered_items=wells, + ) + plate.preferred_pickup_location = Coordinate(63.9, 42.925, -2.0) + return plate + + +def beckman_coulter_biomek_reservoir(name: str) -> Plate: + """Reservoir used with the Multimek. Part no. 148033. + + Biomek labware class Reservoir: a well per section.""" + wells: Dict[str, Well] = {} + wells["A1"] = BiomekWell( + name=f"{name}_A1", + size_x=111.04, # x1 0.826 to x2 11.93 cm + size_y=72.65, # y1 0.635 to y2 7.9 cm + size_z=14.53, # depth 1.453 cm + segments=(WellSegment(14.53, 55.52, 36.325, 55.52, 36.325, round=False),), + bottom_type=WellBottomType.FLAT, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=110000.0, # maxvolume + ) + wells["A1"].location = Coordinate(8.26, 3.55, 14.68) + plate = Plate( + name=name, + size_x=127.0, # xspan 12.7 cm + size_y=82.55, # yspan 8.255 cm + size_z=29.21, # height 2.921 cm + model=beckman_coulter_biomek_reservoir.__name__, + ordered_items=wells, + ) + plate.preferred_pickup_location = Coordinate(63.5, 41.275, -2.3) + return plate + + +def beckman_coulter_biomek_modular_reservoir(name: str) -> Plate: + """Beckman Coulter reservoir that may be customized with added sections. Part no. 372795 (Frame); 372790(Quarter); 373792(Quarter Divided by Width); 372788 (Quarter Divided by Length); 372786(Half); 372794(Half Divided by Width). + + Biomek labware class ModularReservoir: a well per section.""" + wells: Dict[str, Well] = {} + wells["A1"] = BiomekWell( + name=f"{name}_A1", + size_x=23.65, # x1 1.105 to x2 3.47 cm + size_y=69.19, # y1 0.772 to y2 7.691 cm + size_z=24.79, # depth 2.479 cm + # a V bottom 1.156 cm deep: no outline + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=40700.0, # maxvolume + ) + wells["A1"].location = Coordinate(11.05, 8.69, 14.07) + wells["A2"] = BiomekWell( + name=f"{name}_A2", + size_x=23.65, # x1 3.84825 to x2 6.21325 cm + size_y=69.19, # y1 0.772 to y2 7.691 cm + size_z=24.79, # depth 2.479 cm + # a V bottom 1.156 cm deep: no outline + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=40700.0, # maxvolume + ) + wells["A2"].location = Coordinate(38.4825, 8.69, 14.07) + wells["A3"] = BiomekWell( + name=f"{name}_A3", + size_x=23.65, # x1 6.5915 to x2 8.9565 cm + size_y=69.19, # y1 0.772 to y2 7.691 cm + size_z=24.79, # depth 2.479 cm + # a V bottom 1.156 cm deep: no outline + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=40700.0, # maxvolume + ) + wells["A3"].location = Coordinate(65.915, 8.69, 14.07) + wells["A4"] = BiomekWell( + name=f"{name}_A4", + size_x=23.65, # x1 9.33475 to x2 11.69975 cm + size_y=69.19, # y1 0.772 to y2 7.691 cm + size_z=24.79, # depth 2.479 cm + # a V bottom 1.156 cm deep: no outline + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=40700.0, # maxvolume + ) + wells["A4"].location = Coordinate(93.3475, 8.69, 14.07) + plate = Plate( + name=name, + size_x=127.41, # xspan 12.741 cm + size_y=85.6, # yspan 8.56 cm + size_z=38.86, # height 3.886 cm + model=beckman_coulter_biomek_modular_reservoir.__name__, + ordered_items=wells, + ) + plate.preferred_pickup_location = Coordinate(63.705, 42.8, -2.3) + return plate diff --git a/pylabrobot/resources/beckman_coulter/tip_racks.py b/pylabrobot/resources/beckman_coulter/tip_racks.py new file mode 100644 index 00000000000..1e8ef072f54 --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/tip_racks.py @@ -0,0 +1,179 @@ +"""Beckman Coulter Biomek tip boxes, from Biomek's labware classes (cm there, mm here). + +- `xspan`, `yspan`, `height`: the box's footprint and height, tips in. +- `wellsx`, `wellsy`, `wellxspacing`, `wellyspacing`: the tip grid. +- `well1xoffset`, `well1yoffset`: tip A1's centre, from the box's left and back edges. +- `wellradius`: the radius of the hole a tip stands in. +- `gripperinfo`: where Biomek's gripper pads go (`preferred_pickup_location`). + +The tips' tops are at the box's `height`, where the head's mandrels meet them, so a tip spot sits +on the top face, as on a nested rack. +""" + +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.tip_rack import StandingTipRack, TipSpot +from pylabrobot.resources.utils import create_ordered_items_2d + +from .tips import ( + beckman_coulter_biomek_tip_50uL_filter, + beckman_coulter_biomek_tip_190uL_filter, + beckman_coulter_biomek_tip_230uL, + beckman_coulter_biomek_tip_1025uL_filter, + beckman_coulter_biomek_tip_1070uL, +) + + +def beckman_coulter_biomek_96_tiprack_50uL_filter( + name: str, with_tips: bool = True +) -> StandingTipRack: + """Biomek BC50F tip box: 96 T50F tips (`beckman_coulter_biomek_tip_50uL_filter`). Beckman Coulter tip box containing 96 Aerosol Resistant T50 filter tips. Part no. B85888. + + Labware class BC50F.""" + rack = StandingTipRack( + name=name, + size_x=127.9, # xspan 12.79 cm + size_y=85.4, # yspan 8.54 cm + size_z=55.9, # height 5.59 cm + model=beckman_coulter_biomek_96_tiprack_50uL_filter.__name__, + ordered_items=create_ordered_items_2d( + TipSpot, + num_items_x=12, + num_items_y=8, + dx=11.7, # well1xoffset 1.45 cm, less the hole's radius + dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back + dz=55.9, + item_dx=9.0, + item_dy=9.0, + size_x=5.6, # wellradius 0.28 cm + size_y=5.6, + make_tip=beckman_coulter_biomek_tip_50uL_filter, + name_prefix=name, + ), + with_tips=with_tips, + ) + rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3) + return rack + + +def beckman_coulter_biomek_96_tiprack_190uL_filter( + name: str, with_tips: bool = True +) -> StandingTipRack: + """Biomek BC190F tip box: 96 T190F tips (`beckman_coulter_biomek_tip_190uL_filter`). Beckman Coulter tip box containing 96 Aerosol Resistant T190 filter tips. Part no. B85911. + + Labware class BC190F.""" + rack = StandingTipRack( + name=name, + size_x=127.9, # xspan 12.79 cm + size_y=85.4, # yspan 8.54 cm + size_z=55.9, # height 5.59 cm + model=beckman_coulter_biomek_96_tiprack_190uL_filter.__name__, + ordered_items=create_ordered_items_2d( + TipSpot, + num_items_x=12, + num_items_y=8, + dx=11.7, # well1xoffset 1.45 cm, less the hole's radius + dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back + dz=55.9, + item_dx=9.0, + item_dy=9.0, + size_x=5.6, # wellradius 0.28 cm + size_y=5.6, + make_tip=beckman_coulter_biomek_tip_190uL_filter, + name_prefix=name, + ), + with_tips=with_tips, + ) + rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3) + return rack + + +def beckman_coulter_biomek_96_tiprack_230uL(name: str, with_tips: bool = True) -> StandingTipRack: + """Biomek BC230 tip box: 96 T230 tips (`beckman_coulter_biomek_tip_230uL`). Beckman Coulter tip box containing 96 T230 tips. Part no. Sterile: B85906, Non-Sterile: B85903. + + Labware class BC230.""" + rack = StandingTipRack( + name=name, + size_x=127.9, # xspan 12.79 cm + size_y=85.4, # yspan 8.54 cm + size_z=55.9, # height 5.59 cm + model=beckman_coulter_biomek_96_tiprack_230uL.__name__, + ordered_items=create_ordered_items_2d( + TipSpot, + num_items_x=12, + num_items_y=8, + dx=11.7, # well1xoffset 1.45 cm, less the hole's radius + dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back + dz=55.9, + item_dx=9.0, + item_dy=9.0, + size_x=5.6, # wellradius 0.28 cm + size_y=5.6, + make_tip=beckman_coulter_biomek_tip_230uL, + name_prefix=name, + ), + with_tips=with_tips, + ) + rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3) + return rack + + +def beckman_coulter_biomek_96_tiprack_1025uL_filter( + name: str, with_tips: bool = True +) -> StandingTipRack: + """Biomek BC1025F tip box: 96 T1025F tips (`beckman_coulter_biomek_tip_1025uL_filter`). Beckman Coulter tip box containing 96 Aerosol Resistant T1025 filtered tips. Part no. B85955. + + Labware class BC1025F.""" + rack = StandingTipRack( + name=name, + size_x=127.9, # xspan 12.79 cm + size_y=85.4, # yspan 8.54 cm + size_z=114.1, # height 11.41 cm + model=beckman_coulter_biomek_96_tiprack_1025uL_filter.__name__, + ordered_items=create_ordered_items_2d( + TipSpot, + num_items_x=12, + num_items_y=8, + dx=11.6, # well1xoffset 1.44 cm, less the hole's radius + dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back + dz=114.1, + item_dx=9.0, + item_dy=9.0, + size_x=5.6, # wellradius 0.28 cm + size_y=5.6, + make_tip=beckman_coulter_biomek_tip_1025uL_filter, + name_prefix=name, + ), + with_tips=with_tips, + ) + rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3) + return rack + + +def beckman_coulter_biomek_96_tiprack_1070uL(name: str, with_tips: bool = True) -> StandingTipRack: + """Biomek BC1070 tip box: 96 T1070 tips (`beckman_coulter_biomek_tip_1070uL`). Beckman Coulter tip box containing 96 T1070 tips. Part no. Sterile: B85945, Non-Sterile: B85940. + + Labware class BC1070.""" + rack = StandingTipRack( + name=name, + size_x=127.9, # xspan 12.79 cm + size_y=85.4, # yspan 8.54 cm + size_z=114.1, # height 11.41 cm + model=beckman_coulter_biomek_96_tiprack_1070uL.__name__, + ordered_items=create_ordered_items_2d( + TipSpot, + num_items_x=12, + num_items_y=8, + dx=11.6, # well1xoffset 1.44 cm, less the hole's radius + dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back + dz=114.1, + item_dx=9.0, + item_dy=9.0, + size_x=5.6, # wellradius 0.28 cm + size_y=5.6, + make_tip=beckman_coulter_biomek_tip_1070uL, + name_prefix=name, + ), + with_tips=with_tips, + ) + rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3) + return rack diff --git a/pylabrobot/resources/beckman_coulter/tips.py b/pylabrobot/resources/beckman_coulter/tips.py new file mode 100644 index 00000000000..756b870e92c --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/tips.py @@ -0,0 +1,96 @@ +"""Beckman Coulter Biomek tips, from Biomek's tip classes (lengths in cm there, mm here). + +- `tipheight`: the tip's length; `capacity`: its volume in uL; `filtered`: a filter tip. +- `spanseatingdepth`: how far a mandrel goes into the tip. +- `maxtipradius`: the tip's radius where it seats on the mandrel. +- `mintipradius`, `coniclength`: its radius at the end, and the length over which it widens from + there to `maxtipradius` (the cone). +- `lls`: whether the tip is conductive, for liquid-level sensing. +""" + +from .biomek_resource import BiomekTip + + +def beckman_coulter_biomek_tip_50uL_filter(name: str) -> BiomekTip: + """Biomek T50F tip, 50 uL, filter: tip class T50F.""" + return BiomekTip( + name=name, + model=beckman_coulter_biomek_tip_50uL_filter.__name__, + diameter=5.182, # maxtipradius 0.2591 cm + size_z=51.359, # tipheight 5.1359 cm + has_filter=True, + maximal_volume=50.0, # capacity + nominal_volume=50.0, + fitting_depth=7.75, # spanseatingdepth 0.775 cm + end_diameter=0.812, # mintipradius 0.0406 cm + cone_length=38.227, # coniclength 3.8227 cm + is_conductive=False, # lls + ) + + +def beckman_coulter_biomek_tip_190uL_filter(name: str) -> BiomekTip: + """Biomek T190F tip, 190 uL, filter: tip class T190F.""" + return BiomekTip( + name=name, + model=beckman_coulter_biomek_tip_190uL_filter.__name__, + diameter=4.826, # maxtipradius 0.2413 cm + size_z=51.435, # tipheight 5.1435 cm + has_filter=True, + maximal_volume=190.0, # capacity + nominal_volume=190.0, + fitting_depth=7.75, # spanseatingdepth 0.775 cm + end_diameter=1.27, # mintipradius 0.0635 cm + cone_length=28.194, # coniclength 2.8194 cm + is_conductive=False, # lls + ) + + +def beckman_coulter_biomek_tip_230uL(name: str) -> BiomekTip: + """Biomek T230 tip, 230 uL, no filter: tip class T230.""" + return BiomekTip( + name=name, + model=beckman_coulter_biomek_tip_230uL.__name__, + diameter=4.826, # maxtipradius 0.2413 cm + size_z=51.435, # tipheight 5.1435 cm + has_filter=False, + maximal_volume=230.0, # capacity + nominal_volume=230.0, + fitting_depth=7.75, # spanseatingdepth 0.775 cm + end_diameter=1.27, # mintipradius 0.0635 cm + cone_length=28.194, # coniclength 2.8194 cm + is_conductive=False, # lls + ) + + +def beckman_coulter_biomek_tip_1025uL_filter(name: str) -> BiomekTip: + """Biomek T1025F tip, 1025 uL, filter: tip class T1025F.""" + return BiomekTip( + name=name, + model=beckman_coulter_biomek_tip_1025uL_filter.__name__, + diameter=4.826, # maxtipradius 0.2413 cm + size_z=109.855, # tipheight 10.9855 cm + has_filter=True, + maximal_volume=1025.0, # capacity + nominal_volume=1025.0, + fitting_depth=7.75, # spanseatingdepth 0.775 cm + end_diameter=1.27, # mintipradius 0.0635 cm + cone_length=19.8374, # coniclength 1.98374 cm + is_conductive=False, # lls + ) + + +def beckman_coulter_biomek_tip_1070uL(name: str) -> BiomekTip: + """Biomek T1070 tip, 1070 uL, no filter: tip class T1070.""" + return BiomekTip( + name=name, + model=beckman_coulter_biomek_tip_1070uL.__name__, + diameter=4.826, # maxtipradius 0.2413 cm + size_z=109.855, # tipheight 10.9855 cm + has_filter=False, + maximal_volume=1070.0, # capacity + nominal_volume=1070.0, + fitting_depth=7.75, # spanseatingdepth 0.775 cm + end_diameter=1.27, # mintipradius 0.0635 cm + cone_length=19.8374, # coniclength 1.98374 cm + is_conductive=False, # lls + ) diff --git a/pylabrobot/resources/n_channel_pipettes.py b/pylabrobot/resources/n_channel_pipettes.py index 6e3fe04725c..72b6762fafe 100644 --- a/pylabrobot/resources/n_channel_pipettes.py +++ b/pylabrobot/resources/n_channel_pipettes.py @@ -4,7 +4,7 @@ from typing import Any, Dict, List, Literal, Mapping, Optional, cast, get_args from pylabrobot.resources.coordinate import Coordinate -from pylabrobot.resources.head_tool import HeadTool, move_tool +from pylabrobot.resources.head_tool import HeadTool, move_tool, release_named_tool from pylabrobot.resources.itemized_resource import ItemizedResource from pylabrobot.resources.resource import Resource from pylabrobot.resources.well import CrossSectionType @@ -145,6 +145,31 @@ def tip_bottom(self) -> Optional[Coordinate]: return None return Coordinate(0.0, 0.0, cast(Coordinate, tip.location).z) + def serialize_state(self) -> Dict[str, Any]: + """This shaft's state: the tool it carries (`tip`, as it serializes; None for none), as a tip + spot's state holds its tip. A device that cannot sense its tips reads them back from it.""" + tip = self.tip + return {**super().serialize_state(), "tip": None if tip is None else tip.serialize()} + + def load_state(self, state: Dict[str, Any]) -> None: + """Load this shaft's state: the saved `tip` goes onto it (a tool of the same name held + elsewhere in the same tree gives way first); a saved None takes off the one it carries. State + saved before shafts had any leaves it as it is.""" + super().load_state(state) + if "tip" not in state: + return + saved, current = state["tip"], self.tip + if current is not None and saved is not None and current.serialize() == saved: + return + if current is not None: + self.release_tip() + if saved is None: + return + release_named_tool(self.get_root(), saved["name"]) + tip = Resource.deserialize(saved) + assert isinstance(tip, HeadTool) + self.mount_tip(tip) + def serialize(self) -> dict: """What its size does not say: how it holds a tip, and that it is round rather than a box.""" return { diff --git a/pylabrobot/resources/n_channel_pipettes_tests.py b/pylabrobot/resources/n_channel_pipettes_tests.py index 319a5211e0f..394256531d5 100644 --- a/pylabrobot/resources/n_channel_pipettes_tests.py +++ b/pylabrobot/resources/n_channel_pipettes_tests.py @@ -4,6 +4,7 @@ from pylabrobot.resources.hamilton import hamilton_core_gripper_tool, hamilton_tip_300uL from pylabrobot.resources.n_channel_pipettes import TipMountingShaft from pylabrobot.resources.resource import Resource +from pylabrobot.resources.tip import Tip class TestTipMountingShaft(unittest.TestCase): @@ -18,6 +19,56 @@ def test_a_shaft_is_round(self): TipMountingShaft(name="shaft", tip_pickup_mode="core", cross_section_type="rectangle") +class ShaftSavesItsTip(unittest.TestCase): + """A shaft's state is the tool it carries, so a device that cannot sense its tips reads them back.""" + + def setUp(self): + self.shaft = TipMountingShaft(name="shaft", tip_pickup_mode="core") + + def test_a_carried_tip_is_saved_and_read_back(self): + tip = hamilton_tip_300uL(name="tip") + self.shaft.mount_tip(tip) + tip.tracker.set_volume(120) + state = self.shaft.serialize_all_state() + self.assertEqual(state["shaft"]["tip"], tip.serialize()) + + other = TipMountingShaft(name="shaft", tip_pickup_mode="core") + other.load_all_state(state) + self.assertTrue(other.has_tip()) + assert other.tip is not None + assert isinstance(other.tip, Tip) + self.assertEqual(other.tip.serialize(), tip.serialize()) + self.assertEqual(other.tip.location, tip.location) + self.assertEqual(other.tip.tracker.get_used_volume(), 120) # the tip's own state, after it + + def test_none_saved_takes_the_tip_off(self): + empty = self.shaft.serialize_all_state() + self.assertIsNone(empty["shaft"]["tip"]) + self.shaft.mount_tip(hamilton_tip_300uL(name="tip")) + self.shaft.load_all_state(empty) + self.assertFalse(self.shaft.has_tip()) + + def test_the_same_tip_stays_and_older_state_leaves_it(self): + tip = hamilton_tip_300uL(name="tip") + self.shaft.mount_tip(tip) + self.shaft.load_state(self.shaft.serialize_state()) + self.assertIs(self.shaft.tip, tip) + self.shaft.load_state({}) + self.assertIs(self.shaft.tip, tip) + + def test_a_tip_of_that_name_held_elsewhere_gives_way(self): + root = Resource("root", size_x=100, size_y=100, size_z=10) + first = TipMountingShaft(name="first", tip_pickup_mode="core") + second = TipMountingShaft(name="second", tip_pickup_mode="core") + root.assign_child_resource(first, location=Coordinate.zero()) + root.assign_child_resource(second, location=Coordinate(20, 0, 0)) + first.mount_tip(hamilton_tip_300uL(name="tip")) + saved = first.serialize_state() + second.load_state(saved) + self.assertTrue(second.has_tip()) + self.assertFalse(first.has_tip()) + + class ShaftHoldsItsTip(unittest.TestCase): """A mounting shaft carries its tip as a child, gripping it by the fitting depth."""