mirror of
https://github.com/dptech-corp/Uni-Lab-OS.git
synced 2026-02-04 13:25:13 +00:00
* 0.10.7 Update (#101) * Cleanup registry to be easy-understanding (#76) * delete deprecated mock devices * rename categories * combine chromatographic devices * rename rviz simulation nodes * organic virtual devices * parse vessel_id * run registry completion before merge --------- Co-authored-by: Xuwznln <18435084+Xuwznln@users.noreply.github.com> * fix: workstation handlers and vessel_id parsing * fix: working dir error when input config path feat: report publish topic when error * modify default discovery_interval to 15s * feat: add trace log level * feat: 添加ChinWe设备控制类,支持串口通信和电机控制功能 (#79) * fix: drop_tips not using auto resource select * fix: discard_tips error * fix: discard_tips * fix: prcxi_res * add: prcxi res fix: startup slow * feat: workstation example * fix pumps and liquid_handler handle * feat: 优化protocol node节点运行日志 * fix all protocol_compilers and remove deprecated devices * feat: 新增use_remote_resource参数 * fix and remove redundant info * bugfixes on organic protocols * fix filter protocol * fix protocol node * 临时兼容错误的driver写法 * fix: prcxi import error * use call_async in all service to avoid deadlock * fix: figure_resource * Update recipe.yaml * add workstation template and battery example * feat: add sk & ak * update workstation base * Create workstation_architecture.md * refactor: workstation_base 重构为仅含业务逻辑,通信和子设备管理交给 ProtocolNode * refactor: ProtocolNode→WorkstationNode * Add:msgs.action (#83) * update: Workstation dev 将版本号从 0.10.3 更新为 0.10.4 (#84) * Add:msgs.action * update: 将版本号从 0.10.3 更新为 0.10.4 * simplify resource system * uncompleted refactor * example for use WorkstationBase * feat: websocket * feat: websocket test * feat: workstation example * feat: action status * fix: station自己的方法注册错误 * fix: 还原protocol node处理方法 * fix: build * fix: missing job_id key * ws test version 1 * ws test version 2 * ws protocol * 增加物料关系上传日志 * 增加物料关系上传日志 * 修正物料关系上传 * 修复工站的tracker实例追踪失效问题 * 增加handle检测,增加material edge关系上传 * 修复event loop错误 * 修复edge上报错误 * 修复async错误 * 更新schema的title字段 * 主机节点信息等支持自动刷新 * 注册表编辑器 * 修复status密集发送时,消息出错 * 增加addr参数 * fix: addr param * fix: addr param * 取消labid 和 强制config输入 * Add action definitions for LiquidHandlerSetGroup and LiquidHandlerTransferGroup - Created LiquidHandlerSetGroup.action with fields for group name, wells, and volumes. - Created LiquidHandlerTransferGroup.action with fields for source and target group names and unit volume. - Both actions include response fields for return information and success status. * Add LiquidHandlerSetGroup and LiquidHandlerTransferGroup actions to CMakeLists * Add set_group and transfer_group methods to PRCXI9300Handler and update liquid_handler.yaml * result_info改为字典类型 * 新增uat的地址替换 * runze multiple pump support (cherry picked from commit49354fcf39) * remove runze multiple software obtainer (cherry picked from commit8bcc92a394) * support multiple backbone (cherry picked from commit4771ff2347) * Update runze pump format * Correct runze multiple backbone * Update runze_multiple_backbone * Correct runze pump multiple receive method. * Correct runze pump multiple receive method. * 对于PRCXI9320的transfer_group,一对多和多对多 * 移除MQTT,更新launch文档,提供注册表示例文件,更新到0.10.5 * fix import error * fix dupe upload registry * refactor ws client * add server timeout * Fix: run-column with correct vessel id (#86) * fix run_column * Update run_column_protocol.py (cherry picked from commite5aa4d940a) * resource_update use resource_add * 新增版位推荐功能 * 重新规定了版位推荐的入参 * update registry with nested obj * fix protocol node log_message, added create_resource return value * fix protocol node log_message, added create_resource return value * try fix add protocol * fix resource_add * 修复移液站错误的aspirate注册表 * Feature/xprbalance-zhida (#80) * feat(devices): add Zhida GC/MS pretreatment automation workstation * feat(devices): add mettler_toledo xpr balance * balance * 重新补全zhida注册表 * PRCXI9320 json * PRCXI9320 json * PRCXI9320 json * fix resource download * remove class for resource * bump version to 0.10.6 * 更新所有注册表 * 修复protocolnode的兼容性 * 修复protocolnode的兼容性 * Update install md * Add Defaultlayout * 更新物料接口 * fix dict to tree/nested-dict converter * coin_cell_station draft * refactor: rename "station_resource" to "deck" * add standardized BIOYOND resources: bottle_carrier, bottle * refactor and add BIOYOND resources tests * add BIOYOND deck assignment and pass all tests * fix: update resource with correct structure; remove deprecated liquid_handler set_group action * feat: 将新威电池测试系统驱动与配置文件并入 workstation_dev_YB2 (#92) * feat: 新威电池测试系统驱动与注册文件 * feat: bring neware driver & battery.json into workstation_dev_YB2 * add bioyond studio draft * bioyond station with communication init and resource sync * fix bioyond station and registry * fix: update resource with correct structure; remove deprecated liquid_handler set_group action * frontend_docs * create/update resources with POST/PUT for big amount/ small amount data * create/update resources with POST/PUT for big amount/ small amount data * refactor: add itemized_carrier instead of carrier consists of ResourceHolder * create warehouse by factory func * update bioyond launch json * add child_size for itemized_carrier * fix bioyond resource io * Workstation templates: Resources and its CRUD, and workstation tasks (#95) * coin_cell_station draft * refactor: rename "station_resource" to "deck" * add standardized BIOYOND resources: bottle_carrier, bottle * refactor and add BIOYOND resources tests * add BIOYOND deck assignment and pass all tests * fix: update resource with correct structure; remove deprecated liquid_handler set_group action * feat: 将新威电池测试系统驱动与配置文件并入 workstation_dev_YB2 (#92) * feat: 新威电池测试系统驱动与注册文件 * feat: bring neware driver & battery.json into workstation_dev_YB2 * add bioyond studio draft * bioyond station with communication init and resource sync * fix bioyond station and registry * create/update resources with POST/PUT for big amount/ small amount data * refactor: add itemized_carrier instead of carrier consists of ResourceHolder * create warehouse by factory func * update bioyond launch json * add child_size for itemized_carrier * fix bioyond resource io --------- Co-authored-by: h840473807 <47357934+h840473807@users.noreply.github.com> Co-authored-by: Xie Qiming <97236197+Andy6M@users.noreply.github.com> * 更新物料接口 * Workstation dev yb2 (#100) * Refactor and extend reaction station action messages * Refactor dispensing station tasks to enhance parameter clarity and add batch processing capabilities - Updated `create_90_10_vial_feeding_task` to include detailed parameters for 90%/10% vial feeding, improving clarity and usability. - Introduced `create_batch_90_10_vial_feeding_task` for batch processing of 90%/10% vial feeding tasks with JSON formatted input. - Added `create_batch_diamine_solution_task` for batch preparation of diamine solution, also utilizing JSON formatted input. - Refined `create_diamine_solution_task` to include additional parameters for better task configuration. - Enhanced schema descriptions and default values for improved user guidance. * 修复to_plr_resources * add update remove * 支持选择器注册表自动生成 支持转运物料 * 修复资源添加 * 修复transfer_resource_to_another生成 * 更新transfer_resource_to_another参数,支持spot入参 * 新增test_resource动作 * fix host_node error * fix host_node test_resource error * fix host_node test_resource error * 过滤本地动作 * 移动内部action以兼容host node * 修复同步任务报错不显示的bug * feat: 允许返回非本节点物料,后面可以通过decoration进行区分,就不进行warning了 * update todo * modify bioyond/plr converter, bioyond resource registry, and tests * pass the tests * update todo * add conda-pack-build.yml * add auto install script for conda-pack-build.yml (cherry picked from commit172599adcf) * update conda-pack-build.yml * update conda-pack-build.yml * update conda-pack-build.yml * update conda-pack-build.yml * update conda-pack-build.yml * Add version in __init__.py Update conda-pack-build.yml Add create_zip_archive.py * Update conda-pack-build.yml * Update conda-pack-build.yml (with mamba) * Update conda-pack-build.yml * Fix FileNotFoundError * Try fix 'charmap' codec can't encode characters in position 16-23: character maps to <undefined> * Fix unilabos msgs search error * Fix environment_check.py * Update recipe.yaml * Update registry. Update uuid loop figure method. Update install docs. * Fix nested conda pack * Fix one-key installation path error * Bump version to 0.10.7 * Workshop bj (#99) * Add LaiYu Liquid device integration and tests Introduce LaiYu Liquid device implementation, including backend, controllers, drivers, configuration, and resource files. Add hardware connection, tip pickup, and simplified test scripts, as well as experiment and registry configuration for LaiYu Liquid. Documentation and .gitignore for the device are also included. * feat(LaiYu_Liquid): 重构设备模块结构并添加硬件文档 refactor: 重新组织LaiYu_Liquid模块目录结构 docs: 添加SOPA移液器和步进电机控制指令文档 fix: 修正设备配置中的最大体积默认值 test: 新增工作台配置测试用例 chore: 删除过时的测试脚本和配置文件 * add * 重构: 将 LaiYu_Liquid.py 重命名为 laiyu_liquid_main.py 并更新所有导入引用 - 使用 git mv 将 LaiYu_Liquid.py 重命名为 laiyu_liquid_main.py - 更新所有相关文件中的导入引用 - 保持代码功能不变,仅改善命名一致性 - 测试确认所有导入正常工作 * 修复: 在 core/__init__.py 中添加 LaiYuLiquidBackend 导出 - 添加 LaiYuLiquidBackend 到导入列表 - 添加 LaiYuLiquidBackend 到 __all__ 导出列表 - 确保所有主要类都可以正确导入 * 修复大小写文件夹名字 * 电池装配工站二次开发教程(带目录)上传至dev (#94) * 电池装配工站二次开发教程 * Update intro.md * 物料教程 * 更新物料教程,json格式注释 * Update prcxi driver & fix transfer_liquid mix_times (#90) * Update prcxi driver & fix transfer_liquid mix_times * fix: correct mix_times type * Update liquid_handler registry * test: prcxi.py * Update registry from pr * fix ony-key script not exist * clean files --------- Co-authored-by: Junhan Chang <changjh@dp.tech> Co-authored-by: ZiWei <131428629+ZiWei09@users.noreply.github.com> Co-authored-by: Guangxin Zhang <guangxin.zhang.bio@gmail.com> Co-authored-by: Xie Qiming <97236197+Andy6M@users.noreply.github.com> Co-authored-by: h840473807 <47357934+h840473807@users.noreply.github.com> Co-authored-by: LccLink <1951855008@qq.com> Co-authored-by: lixinyu1011 <61094742+lixinyu1011@users.noreply.github.com> Co-authored-by: shiyubo0410 <shiyubo@dp.tech> * fix startup env check. add auto install during one-key installation * Try fix one-key build on linux * Complete all one key installation * fix: rename schema field to resource_schema with serialization and validation aliases (#104) Co-authored-by: ZiWei <131428629+ZiWei09@users.noreply.github.com> * Fix one-key installation build Install conda-pack before pack command Add conda-pack to base when building one-key installer Fix param error when using mamba run Try fix one-key build on linux * Fix conda pack on windows * add plr_to_bioyond, and refactor bioyond stations * modify default config * Fix one-key installation build for windows * Fix workstation startup Update registry * Fix/resource UUID and doc fix (#109) * Fix ResourceTreeSet load error * Raise error when using unsupported type to create ResourceTreeSet * Fix children key error * Fix children key error * Fix workstation resource not tracking * Fix workstation deck & children resource dupe * Fix workstation deck & children resource dupe * Fix multiple resource error * Fix resource tree update * Fix resource tree update * Force confirm uuid * Tip more error log * Refactor Bioyond workstation and experiment workflow (#105) Refactored the Bioyond workstation classes to improve parameter handling and workflow management. Updated experiment.py to use BioyondReactionStation with deck and material mappings, and enhanced workflow step parameter mapping and execution logic. Adjusted JSON experiment configs, improved workflow sequence handling, and added UUID assignment to PLR materials. Removed unused station_config and material cache logic, and added detailed docstrings and debug output for workflow methods. * Fix resource get. Fix resource parent not found. Mapping uuid for all resources. * mount parent uuid * Add logging configuration based on BasicConfig in main function * fix workstation node error * fix workstation node error * Update boot example * temp fix for resource get * temp fix for resource get * provide error info when cant find plr type * pack repo info * fix to plr type error * fix to plr type error * Update regular container method * support no size init * fix comprehensive_station.json * fix comprehensive_station.json * fix type conversion * fix state loading for regular container * Update deploy-docs.yml * Update deploy-docs.yml --------- Co-authored-by: ZiWei <131428629+ZiWei09@users.noreply.github.com> * Close #107 Update doc url. * Fix/update resource (#112) * cancel upload_registry * Refactor Bioyond workstation and experiment workflow -fix (#111) * refactor(bioyond_studio): 优化材料缓存加载和参数验证逻辑 改进材料缓存加载逻辑以支持多种材料类型和详细材料处理 更新工作流参数验证中的字段名从key/value改为Key/DisplayValue 移除未使用的merge_workflow_with_parameters方法 添加get_station_info方法获取工作站基础信息 清理实验文件中的注释代码和更新导入路径 * fix: 修复资源移除时的父资源检查问题 在BaseROS2DeviceNode中,移除资源前添加对父资源是否为None的检查,避免空指针异常 同时更新Bottle和BottleCarrier类以支持**kwargs参数 修正测试文件中Liquid_feeding_beaker的大小写拼写错误 * correct return message --------- Co-authored-by: ZiWei <131428629+ZiWei09@users.noreply.github.com> * fix resource_get in action * fix(reaction_station): 清空工作流序列和参数避免重复执行 (#113) 在创建任务后清空工作流序列和参数,防止下次执行时累积重复 * Update create_resource device_id * Update ResourceTracker add more enumeration in POSE fix converter in resource_tracker * Update graphio together with workstation design. fix(reaction_station): 为步骤参数添加Value字段传个BY后端 fix(bioyond/warehouses): 修正仓库尺寸和物品排列参数 调整仓库的x轴和z轴物品数量以及物品尺寸参数,使其符合4x1x4的规格要求 fix warehouse serialize/deserialize fix bioyond converter fix itemized_carrier.unassign_child_resource allow not-loaded MSG in registry add layout serializer & converter warehouseuse A1-D4; add warehouse layout fix(graphio): 修正bioyond到plr资源转换中的坐标计算错误 Fix resource assignment and type mapping issues Corrects resource assignment in ItemizedCarrier by using the correct spot key from _ordering. Updates graphio to use 'typeName' instead of 'name' for type mapping in resource_bioyond_to_plr. Renames DummyWorkstation to BioyondWorkstation in workstation_http_service for clarity. * Update workstation & bioyond example Refine descriptions in Bioyond reaction station YAML Updated and clarified field and operation descriptions in the reaction_station_bioyond.yaml file for improved accuracy and consistency. Changes include more precise terminology, clearer parameter explanations, and standardized formatting for operation schemas. refactor(workstation): 更新反应站参数描述并添加分液站配置文件 修正反应站方法参数描述,使其更准确清晰 添加bioyond_dispensing_station.yaml配置文件 add create_workflow script and test add invisible_slots to carriers fix(warehouses): 修正bioyond_warehouse_1x4x4仓库的尺寸参数 调整仓库的num_items_x和num_items_z值以匹配实际布局,并更新物品尺寸参数 save resource get data. allow empty value for layout and cross_section_type More decks&plates support for bioyond (#115) refactor(registry): 重构反应站设备配置,简化并更新操作命令 移除旧的自动操作命令,新增针对具体化学操作的命令配置 更新模块路径和配置结构,优化参数定义和描述 fix(dispensing_station): 修正物料信息查询方法调用 将直接调用material_id_query改为通过hardware_interface调用,以符合接口设计规范 * PRCXI Update 修改prcxi连线 prcxi样例图 Create example_prcxi.json * Update resource extra & uuid. use ordering to convert identifier to idx convert identifier to site idx correct extra key update extra before transfer fix multiple instance error add resource_tree_transfer func fox itemrized carrier assign child resource support internal device material transfer remove extra key use same callback group support material extra support material extra support update_resource_site in extra * Update workstation. modify workstation_architecture docs bioyond_HR (#133) * feat: Enhance Bioyond synchronization and resource management - Implemented synchronization for all material types (consumables, samples, reagents) from Bioyond, logging detailed information for each type. - Improved error handling and logging during synchronization processes. - Added functionality to save Bioyond material IDs in UniLab resources for future updates. - Enhanced the `sync_to_external` method to handle material movements correctly, including querying and creating materials in Bioyond. - Updated warehouse configurations to support new storage types and improved layout for better resource management. - Introduced new resource types such as reactors and tip boxes, with detailed specifications. - Modified warehouse factory to support column offsets for naming conventions (e.g., A05-D08). - Improved resource tracking by merging extra attributes instead of overwriting them. - Added a new method for updating resources in Bioyond, ensuring better synchronization of resource changes. * feat: 添加TipBox和Reactor的配置到bottles.yaml * fix: 修复液体投料方法中的volume参数处理逻辑 修复solid_feeding_vials方法中的volume参数处理逻辑,优化solvents参数的使用条件 更新液体投料方法,支持通过溶剂信息自动计算体积,添加solvents参数并更新文档描述 Add batch creation methods for vial and solution tasks 添加批量创建90%10%小瓶投料任务和二胺溶液配置任务的功能,更新相关参数和默认值 * 封膜仪、撕膜仪、耗材站接口 * 添加Raman和xrd相关代码 * Resource update & asyncio fix correct bioyond config prcxi example fix append_resource fix regularcontainer fix cancel error fix resource_get param fix json dumps support name change during materials change enable slave mode change uuid logger to trace level correct remove_resource stats disable slave connect websocket adjust with_children param modify devices to use correct executor (sleep, create_task) support sleep and create_task in node fix run async execution error * bump version to 0.10.9 update registry * PRCXI Reset Error Correction (#166) * change 9320 desk row number to 4 * Updated 9320 host address * Updated 9320 host address * Add **kwargs in classes: PRCXI9300Deck and PRCXI9300Container * Removed all sample_id in prcxi_9320.json to avoid KeyError * 9320 machine testing settings * Typo * Rewrite setup logic to clear error code * 初始化 step_mode 属性 * 1114物料手册定义教程byxinyu (#165) * 宜宾奔耀工站deck前端by_Xinyu * 构建物料教程byxinyu * 1114物料手册定义教程 * 3d sim (#97) * 修改lh的json启动 * 修改lh的json启动 * 修改backend,做成sim的通用backend * 修改yaml的地址,3D模型适配网页生产环境 * 添加laiyu硬件连接 * 修改移液枪的状态判断方法, 修改移液枪的状态判断方法, 添加三轴的表定点与零点之间的转换 添加三轴真实移动的backend * 修改laiyu移液站 简化移动方法, 取消软件限制位置, 修改当值使用Z轴时也需要重新复位Z轴的问题 * 更新lh以及laiyu workshop 1,现在可以直接通过修改backend,适配其他的移液站,主类依旧使用LiquidHandler,不用重新编写 2,修改枪头判断标准,使用枪头自身判断而不是类的判断, 3,将归零参数用毫米计算,方便手动调整, 4,修改归零方式,上电使用机械归零,确定机械零点,手动归零设置工作区域零点方便计算,二者互不干涉 * 修改枪头动作 * 修改虚拟仿真方法 --------- Co-authored-by: zhangshixiang <@zhangshixiang> Co-authored-by: Junhan Chang <changjh@dp.tech> * 标准化opcua设备接入unilab (#78) * 初始提交,只保留工作区当前状态 * remove redundant arm_slider meshes --------- Co-authored-by: Junhan Chang <changjh@dp.tech> * add new laiyu liquid driver, yaml and json files (#164) * HR物料同步,前端展示位置修复 (#135) * 更新Bioyond工作站配置,添加新的物料类型映射和载架定义,优化物料查询逻辑 * 添加Bioyond实验配置文件,定义物料类型映射和设备配置 * 更新bioyond_warehouse_reagent_stack方法,修正试剂堆栈尺寸和布局描述 * 更新Bioyond实验配置,修正物料类型映射,优化设备配置 * 更新Bioyond资源同步逻辑,优化物料入库流程,增强错误处理和日志记录 * 更新Bioyond资源,添加配液站和反应站专用载架,优化仓库工厂函数的排序方式 * 更新Bioyond资源,添加配液站和反应站相关载架,优化试剂瓶和样品瓶配置 * 更新Bioyond实验配置,修正试剂瓶载架ID,确保与设备匹配 * 更新Bioyond资源,移除反应站单烧杯载架,添加反应站单烧瓶载架分类 * Refactor Bioyond resource synchronization and update bottle carrier definitions - Removed traceback printing in error handling for Bioyond synchronization. - Enhanced logging for existing Bioyond material ID usage during synchronization. - Added new bottle carrier definitions for single flask and updated existing ones. - Refactored dispensing station and reaction station bottle definitions for clarity and consistency. - Improved resource mapping and error handling in graphio for Bioyond resource conversion. - Introduced layout parameter in warehouse factory for better warehouse configuration. * 更新Bioyond仓库工厂,添加排序方式支持,优化坐标计算逻辑 * 更新Bioyond载架和甲板配置,调整样品板尺寸和仓库坐标 * 更新Bioyond资源同步,增强占用位置日志信息,修正坐标转换逻辑 * 更新Bioyond反应站和分配站配置,调整材料类型映射和ID,移除不必要的项 * support name change during materials change * fix json dumps * correct tip * 优化调度器API路径,更新相关方法描述 * 更新 BIOYOND 载架相关文档,调整 API 以支持自带试剂瓶的载架类型,修复资源获取时的子物料处理逻辑 * 实现资源删除时的同步处理,优化出库操作逻辑 * 修复 ItemizedCarrier 中的可见性逻辑 * 保存 Bioyond 原始信息到 unilabos_extra,以便出库时查询 * 根据 resource.capacity 判断是试剂瓶(载架)还是多瓶载架,走不同的奔曜转换 * Fix bioyond bottle_carriers ordering * 优化 Bioyond 物料同步逻辑,增强坐标解析和位置更新处理 * disable slave connect websocket * correct remove_resource stats * change uuid logger to trace level * enable slave mode * refactor(bioyond): 统一资源命名并优化物料同步逻辑 - 将DispensingStation和ReactionStation资源统一为PolymerStation命名 - 优化物料同步逻辑,支持耗材类型(typeMode=0)的查询 - 添加物料默认参数配置功能 - 调整仓库坐标布局 - 清理废弃资源定义 * feat(warehouses): 为仓库函数添加col_offset和layout参数 * refactor: 更新实验配置中的物料类型映射命名 将DispensingStation和ReactionStation的物料类型映射统一更名为PolymerStation,保持命名一致性 * fix: 更新实验配置中的载体名称从6VialCarrier到6StockCarrier * feat(bioyond): 实现物料创建与入库分离逻辑 将物料同步流程拆分为两个独立阶段:transfer阶段只创建物料,add阶段执行入库 简化状态检查接口,仅返回连接状态 * fix(reaction_station): 修正液体进料烧杯体积单位并增强返回结果 将液体进料烧杯的体积单位从μL改为g以匹配实际使用场景 在返回结果中添加merged_workflow和order_params字段,提供更完整的工作流信息 * feat(dispensing_station): 在任务创建返回结果中添加order_params信息 在create_order方法返回结果中增加order_params字段,以便调用方获取完整的任务参数 * fix(dispensing_station): 修改90%物料分配逻辑从分成3份改为直接使用 原逻辑将主称固体平均分成3份作为90%物料,现改为直接使用main_portion * feat(bioyond): 添加任务编码和任务ID的输出,支持批量任务创建后的状态监控 * refactor(registry): 简化设备配置中的任务结果处理逻辑 将多个单独的任务编码和ID字段合并为统一的return_info字段 更新相关描述以反映新的数据结构 * feat(工作站): 添加HTTP报送服务和任务完成状态跟踪 - 在graphio.py中添加API必需字段 - 实现工作站HTTP服务启动和停止逻辑 - 添加任务完成状态跟踪字典和等待方法 - 重写任务完成报送处理方法记录状态 - 支持批量任务完成等待和报告获取 * refactor(dispensing_station): 移除wait_for_order_completion_and_get_report功能 该功能已被wait_for_multiple_orders_and_get_reports替代,简化代码结构 * fix: 更新任务报告API错误 * fix(workstation_http_service): 修复状态查询中device_id获取逻辑 处理状态查询时安全获取device_id,避免因属性不存在导致的异常 * fix(bioyond_studio): 改进物料入库失败时的错误处理和日志记录 在物料入库API调用失败时,添加更详细的错误信息打印 同时修正station.py中对空响应和失败情况的判断逻辑 * refactor(bioyond): 优化瓶架载体的分配逻辑和注释说明 重构瓶架载体的分配逻辑,使用嵌套循环替代硬编码索引分配 添加更详细的坐标映射说明,明确PLR与Bioyond坐标的对应关系 * fix(bioyond_rpc): 修复物料入库成功时无data字段返回空的问题 当API返回成功但无data字段时,返回包含success标识的字典而非空字典 --------- Co-authored-by: Xuwznln <18435084+Xuwznln@users.noreply.github.com> Co-authored-by: Junhan Chang <changjh@dp.tech> * nmr * Update devices * bump version to 0.10.10 * Update repo files. * Add get_resource_with_dir & get_resource method * fix camera & workstation & warehouse & reaction station driver * update docs, test examples fix liquid_handler init bug * bump version to 0.10.11 * Add startup_json_path, disable_browser, port config * Update oss config * feat(bioyond_studio): 添加项目API接口支持及优化物料管理功能 添加通用项目API接口方法(_post_project_api, _delete_project_api)用于与LIMS系统交互 实现compute_experiment_design方法用于实验设计计算 新增brief_step_parameters等订单相关接口方法 优化物料转移逻辑,增加异步任务处理 扩展BioyondV1RPC类,添加批量物料操作、订单状态管理等功能 * feat(bioyond): 添加测量小瓶仓库和更新仓库工厂函数参数 * Support unilabos_samples key * add session_id and normal_exit * Add result schema and add TypedDict conversion. * Fix port error * Add backend api and update doc * Add get_regular_container func * Add get_regular_container func * Transfer_liquid (#176) * change 9320 desk row number to 4 * Updated 9320 host address * Updated 9320 host address * Add **kwargs in classes: PRCXI9300Deck and PRCXI9300Container * Removed all sample_id in prcxi_9320.json to avoid KeyError * 9320 machine testing settings * Typo * Typo in base_device_node.py * Enhance liquid handling functionality by adding support for multiple transfer modes (one-to-many, one-to-one, many-to-one) and improving parameter validation. Default channel usage is set when not specified. Adjusted mixing logic to ensure it only occurs when valid conditions are met. Updated documentation for clarity. * Auto dump logs, fix workstation input schema * Fix startup with remote resource error Resource dict fully change to "pose" key Update oss link Reduce pylabrobot conversion warning & force enable log dump. 更新 logo 图片 * signal when host node is ready * fix ros2 future print all logs to file fix resource dict dump error * update version to 0.10.12 * 修改sample_uuid的返回值 * 修改pose标签设定机制 * 添加 aspiate函数返回值 * 返回dispense后的sample_uuid * 添加self.pending_liquids_dict的重置方法 * 修改prcxi的json文件,解决trach错误问题 * 修改prcxijson,防止PlateT4的硬件错误 * 对laiyu移液站进行部分修改,取消多次初始化的问题 * 修改根据新的物料格式,修改可视化 * 添加切换枪头方法,添加mock振荡与加热方法 * 夹爪添加 * 删除多余的laiyu部分 * 云端可启动夹爪 * Delete __init__.py * Enhance PRCXI9300 classes with new Container and TipRack implementations, improving state management and initialization logic. Update JSON configuration to reflect type changes for containers and plates. * 修改上传数据 --------- Co-authored-by: Junhan Chang <changjh@dp.tech> Co-authored-by: ZiWei <131428629+ZiWei09@users.noreply.github.com> Co-authored-by: Guangxin Zhang <guangxin.zhang.bio@gmail.com> Co-authored-by: Xie Qiming <97236197+Andy6M@users.noreply.github.com> Co-authored-by: h840473807 <47357934+h840473807@users.noreply.github.com> Co-authored-by: LccLink <1951855008@qq.com> Co-authored-by: lixinyu1011 <61094742+lixinyu1011@users.noreply.github.com> Co-authored-by: shiyubo0410 <shiyubo@dp.tech> Co-authored-by: hh.(SII) <103566763+Mile-Away@users.noreply.github.com> Co-authored-by: Xianwei Qi <qxw@stu.pku.edu.cn> Co-authored-by: WenzheG <wenzheguo32@gmail.com> Co-authored-by: Harry Liu <113173203+ALITTLELZ@users.noreply.github.com> Co-authored-by: q434343 <73513873+q434343@users.noreply.github.com> Co-authored-by: tt <166512503+tt11142023@users.noreply.github.com> Co-authored-by: xyc <49015816+xiaoyu10031@users.noreply.github.com> Co-authored-by: zhangshixiang <@zhangshixiang> Co-authored-by: zhangshixiang <554662886@qq.com> Co-authored-by: ALITTLELZ <l_LZlz@163.com>
1104 lines
42 KiB
Python
1104 lines
42 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
移液控制器模块
|
||
封装SOPA移液器的高级控制功能
|
||
"""
|
||
|
||
# 添加项目根目录到Python路径以解决模块导入问题
|
||
import sys
|
||
import os
|
||
from tkinter import N
|
||
|
||
from unilabos.devices.liquid_handling.laiyu.drivers.xyz_stepper_driver import ModbusException
|
||
|
||
# 无论如何都添加项目根目录到路径
|
||
current_file = os.path.abspath(__file__)
|
||
# 从 .../Uni-Lab-OS/unilabos/devices/LaiYu_Liquid/controllers/pipette_controller.py
|
||
# 向上5级到 .../Uni-Lab-OS
|
||
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(current_file)))))
|
||
# 强制添加项目根目录到sys.path的开头
|
||
sys.path.insert(0, project_root)
|
||
|
||
import time
|
||
import logging
|
||
from typing import Optional, List, Dict, Tuple
|
||
from dataclasses import dataclass
|
||
from enum import Enum
|
||
|
||
from unilabos.devices.liquid_handling.laiyu.drivers.sopa_pipette_driver import (
|
||
SOPAPipette,
|
||
SOPAConfig,
|
||
SOPAStatusCode,
|
||
DetectionMode,
|
||
create_sopa_pipette,
|
||
)
|
||
# from unilabos.devices.liquid_handling.laiyu.drivers.xyz_stepper_driver import (
|
||
# XYZStepperController,
|
||
# MotorAxis,
|
||
# MotorStatus,
|
||
# ModbusException
|
||
# )
|
||
|
||
from unilabos.devices.liquid_handling.laiyu.controllers.xyz_controller import (
|
||
XYZController,
|
||
MotorAxis,
|
||
MotorStatus
|
||
)
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
class TipStatus(Enum):
|
||
"""枪头状态"""
|
||
NO_TIP = "no_tip"
|
||
TIP_ATTACHED = "tip_attached"
|
||
TIP_USED = "tip_used"
|
||
|
||
|
||
class LiquidClass(Enum):
|
||
"""液体类型"""
|
||
WATER = "water"
|
||
SERUM = "serum"
|
||
VISCOUS = "viscous"
|
||
VOLATILE = "volatile"
|
||
CUSTOM = "custom"
|
||
|
||
|
||
@dataclass
|
||
class LiquidParameters:
|
||
"""液体处理参数"""
|
||
aspirate_speed: int = 500 # 吸液速度
|
||
dispense_speed: int = 800 # 排液速度
|
||
air_gap: float = 10.0 # 空气间隙
|
||
blow_out: float = 5.0 # 吹出量
|
||
pre_wet: bool = False # 预润湿
|
||
mix_cycles: int = 0 # 混合次数
|
||
mix_volume: float = 50.0 # 混合体积
|
||
touch_tip: bool = False # 接触壁
|
||
delay_after_aspirate: float = 0.5 # 吸液后延时
|
||
delay_after_dispense: float = 0.5 # 排液后延时
|
||
|
||
|
||
class PipetteController:
|
||
"""移液控制器"""
|
||
|
||
# 预定义液体参数
|
||
LIQUID_PARAMS = {
|
||
LiquidClass.WATER: LiquidParameters(
|
||
aspirate_speed=500,
|
||
dispense_speed=800,
|
||
air_gap=10.0
|
||
),
|
||
LiquidClass.SERUM: LiquidParameters(
|
||
aspirate_speed=200,
|
||
dispense_speed=400,
|
||
air_gap=15.0,
|
||
pre_wet=True,
|
||
delay_after_aspirate=1.0
|
||
),
|
||
LiquidClass.VISCOUS: LiquidParameters(
|
||
aspirate_speed=100,
|
||
dispense_speed=200,
|
||
air_gap=20.0,
|
||
delay_after_aspirate=2.0,
|
||
delay_after_dispense=2.0
|
||
),
|
||
LiquidClass.VOLATILE: LiquidParameters(
|
||
aspirate_speed=800,
|
||
dispense_speed=1000,
|
||
air_gap=5.0,
|
||
delay_after_aspirate=0.2,
|
||
delay_after_dispense=0.2
|
||
)
|
||
}
|
||
|
||
def __init__(self, port: str, address: int = 4, xyz_port: Optional[str] = None):
|
||
"""
|
||
初始化移液控制器
|
||
|
||
Args:
|
||
port: 移液器串口端口
|
||
address: 移液器RS485地址
|
||
xyz_port: XYZ步进电机串口端口(可选,用于枪头装载等运动控制)
|
||
"""
|
||
self.config = SOPAConfig(
|
||
port=port,
|
||
address=address,
|
||
baudrate=115200
|
||
)
|
||
self.pipette = SOPAPipette(self.config)
|
||
self.pipette_port = port
|
||
self.tip_status = TipStatus.NO_TIP
|
||
self.current_volume = 0.0
|
||
self.max_volume = 1000.0 # 默认1000ul
|
||
self.liquid_class = LiquidClass.WATER
|
||
self.liquid_params = self.LIQUID_PARAMS[LiquidClass.WATER]
|
||
|
||
# XYZ步进电机控制器(用于运动控制)
|
||
self.xyz_controller: Optional[XYZController] = None
|
||
self.xyz_port = xyz_port if xyz_port else port
|
||
self.xyz_connected = True
|
||
|
||
# 统计信息
|
||
# self.tip_count = 0
|
||
self.aspirate_count = 0
|
||
self.dispense_count = 0
|
||
|
||
def connect(self) -> bool:
|
||
"""连接移液器和XYZ步进电机控制器"""
|
||
try:
|
||
# 连接移液器
|
||
if not self.pipette.connect():
|
||
logger.error("移液器连接失败")
|
||
return False
|
||
logger.info("移液器连接成功")
|
||
|
||
# 连接XYZ步进电机控制器(如果提供了端口)
|
||
if self.xyz_port != self.pipette_port:
|
||
try:
|
||
self.xyz_controller = XYZController(self.xyz_port)
|
||
if self.xyz_controller.connect():
|
||
self.xyz_connected = True
|
||
logger.info(f"XYZ步进电机控制器连接成功: {self.xyz_port}")
|
||
else:
|
||
logger.warning(f"XYZ步进电机控制器连接失败: {self.xyz_port}")
|
||
self.xyz_controller = None
|
||
except Exception as e:
|
||
logger.warning(f"XYZ步进电机控制器连接异常: {e}")
|
||
self.xyz_controller = None
|
||
self.xyz_connected = False
|
||
else:
|
||
try:
|
||
self.xyz_controller = XYZController(self.xyz_port, auto_connect=False)
|
||
self.xyz_controller.serial_conn = self.pipette.serial_port
|
||
self.xyz_controller.is_connected = True
|
||
except Exception as e:
|
||
logger.info("未配置XYZ步进电机端口,跳过运动控制器连接")
|
||
|
||
return True
|
||
except Exception as e:
|
||
logger.error(f"设备连接失败: {e}")
|
||
return False
|
||
|
||
def initialize(self) -> bool:
|
||
"""初始化移液器"""
|
||
try:
|
||
if self.pipette.initialize():
|
||
logger.info("移液器初始化成功")
|
||
# 检查枪头状态
|
||
self._update_tip_status()
|
||
self.xyz_controller.home_all_axes()
|
||
self.xyz_controller.move_to_work_coord_safe(x=0, y=-150, z=0)
|
||
return True
|
||
return False
|
||
except Exception as e:
|
||
logger.error(f"移液器初始化失败: {e}")
|
||
return False
|
||
|
||
def disconnect(self):
|
||
"""断开连接"""
|
||
# 断开移液器连接
|
||
self.pipette.disconnect()
|
||
logger.info("移液器已断开")
|
||
|
||
# 断开 XYZ 步进电机连接
|
||
if self.xyz_controller and self.xyz_connected:
|
||
try:
|
||
self.xyz_controller.disconnect()
|
||
self.xyz_connected = False
|
||
logger.info("XYZ 步进电机已断开")
|
||
except Exception as e:
|
||
logger.error(f"断开 XYZ 步进电机失败: {e}")
|
||
|
||
def _check_xyz_safety(self, axis: MotorAxis, target_position: int) -> bool:
|
||
"""
|
||
检查 XYZ 轴移动的安全性
|
||
|
||
Args:
|
||
axis: 电机轴
|
||
target_position: 目标位置(步数)
|
||
|
||
Returns:
|
||
是否安全
|
||
"""
|
||
try:
|
||
# 获取当前电机状态
|
||
motor_position = self.xyz_controller.get_motor_status(axis)
|
||
|
||
# 检查电机状态是否正常 (不是碰撞停止或限位停止)
|
||
if motor_position.status in [MotorStatus.COLLISION_STOP,
|
||
MotorStatus.FORWARD_LIMIT_STOP,
|
||
MotorStatus.REVERSE_LIMIT_STOP]:
|
||
logger.error(f"{axis.name} 轴电机处于错误状态: {motor_position.status.name}")
|
||
return False
|
||
|
||
# 检查位置限制 (扩大安全范围以适应实际硬件)
|
||
# 步进电机的位置范围通常很大,这里设置更合理的范围
|
||
if target_position < -500000 or target_position > 500000:
|
||
logger.error(f"{axis.name} 轴目标位置超出安全范围: {target_position}")
|
||
return False
|
||
|
||
# 检查移动距离是否过大 (单次移动不超过 20000 步,约12mm)
|
||
current_position = motor_position.steps
|
||
move_distance = abs(target_position - current_position)
|
||
if move_distance > 20000:
|
||
logger.error(f"{axis.name} 轴单次移动距离过大: {move_distance}步")
|
||
return False
|
||
|
||
return True
|
||
|
||
except Exception as e:
|
||
logger.error(f"安全检查失败: {e}")
|
||
return False
|
||
|
||
def move_z_relative(self, distance_mm: float, speed: int = 2000, acceleration: int = 500) -> bool:
|
||
"""
|
||
Z轴相对移动
|
||
|
||
Args:
|
||
distance_mm: 移动距离(mm),正值向下,负值向上
|
||
speed: 移动速度(rpm)
|
||
acceleration: 加速度(rpm/s)
|
||
|
||
Returns:
|
||
移动是否成功
|
||
"""
|
||
if not self.xyz_controller or not self.xyz_connected:
|
||
logger.error("XYZ 步进电机未连接,无法执行移动")
|
||
return False
|
||
|
||
try:
|
||
# 参数验证
|
||
if abs(distance_mm) > 15.0:
|
||
logger.error(f"移动距离过大: {distance_mm}mm,最大允许15mm")
|
||
return False
|
||
|
||
if speed < 100 or speed > 5000:
|
||
logger.error(f"速度参数无效: {speed}rpm,范围应为100-5000")
|
||
return False
|
||
|
||
# 获取当前 Z 轴位置
|
||
current_status = self.xyz_controller.get_motor_status(MotorAxis.Z)
|
||
current_z_position = current_status.steps
|
||
|
||
# 计算移动距离对应的步数 (1mm = 1638.4步)
|
||
mm_to_steps = 1638.4
|
||
move_distance_steps = int(distance_mm * mm_to_steps)
|
||
|
||
# 计算目标位置
|
||
target_z_position = current_z_position + move_distance_steps
|
||
|
||
# 安全检查
|
||
if not self._check_xyz_safety(MotorAxis.Z, target_z_position):
|
||
logger.error("Z轴移动安全检查失败")
|
||
return False
|
||
|
||
logger.info(f"Z轴相对移动: {distance_mm}mm ({move_distance_steps}步)")
|
||
logger.info(f"当前位置: {current_z_position}步 -> 目标位置: {target_z_position}步")
|
||
|
||
# 执行移动
|
||
success = self.xyz_controller.move_to_position(
|
||
axis=MotorAxis.Z,
|
||
position=target_z_position,
|
||
speed=speed,
|
||
acceleration=acceleration,
|
||
precision=50
|
||
)
|
||
|
||
if not success:
|
||
logger.error("Z轴移动命令发送失败")
|
||
return False
|
||
|
||
# 等待移动完成
|
||
if not self.xyz_controller.wait_for_completion(MotorAxis.Z, timeout=10.0):
|
||
logger.error("Z轴移动超时")
|
||
return False
|
||
|
||
# 验证移动结果
|
||
final_status = self.xyz_controller.get_motor_status(MotorAxis.Z)
|
||
final_position = final_status.steps
|
||
position_error = abs(final_position - target_z_position)
|
||
|
||
logger.info(f"Z轴移动完成,最终位置: {final_position}步,误差: {position_error}步")
|
||
|
||
if position_error > 100:
|
||
logger.warning(f"Z轴位置误差较大: {position_error}步")
|
||
|
||
return True
|
||
|
||
except ModbusException as e:
|
||
logger.error(f"Modbus通信错误: {e}")
|
||
return False
|
||
except Exception as e:
|
||
logger.error(f"Z轴移动失败: {e}")
|
||
return False
|
||
|
||
def emergency_stop(self) -> bool:
|
||
"""
|
||
紧急停止所有运动
|
||
|
||
Returns:
|
||
停止是否成功
|
||
"""
|
||
success = True
|
||
|
||
# 停止移液器操作
|
||
try:
|
||
if self.pipette and self.connected:
|
||
# 这里可以添加移液器的紧急停止逻辑
|
||
logger.info("移液器紧急停止")
|
||
except Exception as e:
|
||
logger.error(f"移液器紧急停止失败: {e}")
|
||
success = False
|
||
|
||
# 停止 XYZ 轴运动
|
||
try:
|
||
if self.xyz_controller and self.xyz_connected:
|
||
self.xyz_controller.emergency_stop()
|
||
logger.info("XYZ 轴紧急停止")
|
||
except Exception as e:
|
||
logger.error(f"XYZ 轴紧急停止失败: {e}")
|
||
success = False
|
||
|
||
return success
|
||
|
||
def pickup_tip(self) -> bool:
|
||
"""
|
||
装载枪头 - Z轴向下移动10mm进行枪头装载
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
self._update_tip_status()
|
||
if self.tip_status == TipStatus.TIP_ATTACHED:
|
||
logger.warning("已有枪头,无需重复装载")
|
||
return True
|
||
|
||
logger.info("开始装载枪头 - Z轴向下移动10mm")
|
||
|
||
# 使用相对移动方法,向下移动10mm
|
||
if self.move_z_relative(distance_mm=10.0, speed=2000, acceleration=500):
|
||
# 更新枪头状态
|
||
self._update_tip_status()
|
||
# self.tip_status = TipStatus.TIP_ATTACHED
|
||
# self.tip_count += 1
|
||
self.current_volume = 0.0
|
||
if self.tip_status == TipStatus.TIP_ATTACHED:
|
||
logger.info("枪头装载成功")
|
||
return True
|
||
else :
|
||
logger.info("枪头装载失败")
|
||
return False
|
||
else:
|
||
logger.error("枪头装载失败 - Z轴移动失败")
|
||
return False
|
||
|
||
def eject_tip(self) -> bool:
|
||
"""
|
||
弹出枪头
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
|
||
self._update_tip_status()
|
||
|
||
if self.tip_status == TipStatus.NO_TIP:
|
||
logger.warning("无枪头可弹出")
|
||
return True
|
||
|
||
try:
|
||
if self.pipette.eject_tip():
|
||
self._update_tip_status()
|
||
if self.tip_status == TipStatus.NO_TIP:
|
||
self.current_volume = 0.0
|
||
logger.info("枪头已弹出")
|
||
return True
|
||
return False
|
||
except Exception as e:
|
||
logger.error(f"弹出枪头失败: {e}")
|
||
return False
|
||
|
||
def aspirate(self, volume: float, liquid_class: Optional[LiquidClass] = None,
|
||
detection: bool = True) -> bool:
|
||
"""
|
||
吸液
|
||
|
||
Args:
|
||
volume: 吸液体积(ul)
|
||
liquid_class: 液体类型
|
||
detection: 是否开启液位检测
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
self._update_tip_status()
|
||
if self.tip_status != TipStatus.TIP_ATTACHED:
|
||
logger.error("无枪头,无法吸液")
|
||
return False
|
||
|
||
if self.current_volume + volume > self.max_volume:
|
||
logger.error(f"吸液量超过枪头容量: {self.current_volume + volume} > {self.max_volume}")
|
||
return False
|
||
|
||
# 设置液体参数
|
||
if liquid_class:
|
||
self.set_liquid_class(liquid_class)
|
||
|
||
try:
|
||
# 设置吸液速度
|
||
self.pipette.set_max_speed(self.liquid_params.aspirate_speed)
|
||
|
||
# 执行液位检测
|
||
if detection:
|
||
if not self.pipette.liquid_level_detection():
|
||
logger.warning("液位检测失败,继续吸液")
|
||
|
||
# 预润湿
|
||
if self.liquid_params.pre_wet and self.current_volume == 0:
|
||
logger.info("执行预润湿")
|
||
self._pre_wet(volume * 0.2)
|
||
|
||
# 吸液
|
||
if self.pipette.aspirate(volume, detection=False):
|
||
self.current_volume += volume
|
||
self.aspirate_count += 1
|
||
|
||
# 吸液后延时
|
||
time.sleep(self.liquid_params.delay_after_aspirate)
|
||
|
||
# 吸取空气间隙
|
||
if self.liquid_params.air_gap > 0:
|
||
self.pipette.aspirate(self.liquid_params.air_gap, detection=False)
|
||
self.current_volume += self.liquid_params.air_gap
|
||
|
||
logger.info(f"吸液完成: {volume}ul, 当前体积: {self.current_volume}ul")
|
||
return True
|
||
else:
|
||
logger.error("吸液失败")
|
||
return False
|
||
|
||
except Exception as e:
|
||
logger.error(f"吸液异常: {e}")
|
||
return False
|
||
|
||
def dispense(self, volume: float, blow_out: bool = False) -> bool:
|
||
"""
|
||
排液
|
||
|
||
Args:
|
||
volume: 排液体积(ul)
|
||
blow_out: 是否吹出
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
self._update_tip_status()
|
||
if self.tip_status != TipStatus.TIP_ATTACHED:
|
||
logger.error("无枪头,无法排液")
|
||
return False
|
||
|
||
if volume > self.current_volume:
|
||
logger.error(f"排液量超过当前体积: {volume} > {self.current_volume}")
|
||
return False
|
||
|
||
try:
|
||
# 设置排液速度
|
||
self.pipette.set_max_speed(self.liquid_params.dispense_speed)
|
||
|
||
# 排液
|
||
if self.pipette.dispense(volume):
|
||
self.current_volume -= volume
|
||
self.dispense_count += 1
|
||
|
||
# 排液后延时
|
||
time.sleep(self.liquid_params.delay_after_dispense)
|
||
|
||
# 吹出
|
||
if blow_out and self.liquid_params.blow_out > 0:
|
||
self.pipette.dispense(self.liquid_params.blow_out)
|
||
logger.debug(f"执行吹出: {self.liquid_params.blow_out}ul")
|
||
|
||
# 接触壁
|
||
if self.liquid_params.touch_tip:
|
||
self._touch_tip()
|
||
|
||
logger.info(f"排液完成: {volume}ul, 剩余体积: {self.current_volume}ul")
|
||
return True
|
||
else:
|
||
logger.error("排液失败")
|
||
return False
|
||
|
||
except Exception as e:
|
||
logger.error(f"排液异常: {e}")
|
||
return False
|
||
|
||
def transfer(self, volume: float,
|
||
source_well: Optional[str] = None,
|
||
dest_well: Optional[str] = None,
|
||
liquid_class: Optional[LiquidClass] = None,
|
||
new_tip: bool = True,
|
||
mix_before: Optional[Tuple[int, float]] = None,
|
||
mix_after: Optional[Tuple[int, float]] = None) -> bool:
|
||
"""
|
||
液体转移
|
||
|
||
Args:
|
||
volume: 转移体积
|
||
source_well: 源孔位
|
||
dest_well: 目标孔位
|
||
liquid_class: 液体类型
|
||
new_tip: 是否使用新枪头
|
||
mix_before: 吸液前混合(次数, 体积)
|
||
mix_after: 排液后混合(次数, 体积)
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
try:
|
||
# 装载新枪头
|
||
if new_tip:
|
||
self.eject_tip()
|
||
if not self.pickup_tip():
|
||
return False
|
||
|
||
# 设置液体类型
|
||
if liquid_class:
|
||
self.set_liquid_class(liquid_class)
|
||
|
||
# 吸液前混合
|
||
if mix_before:
|
||
cycles, mix_vol = mix_before
|
||
self.mix(cycles, mix_vol)
|
||
|
||
# 吸液
|
||
if not self.aspirate(volume):
|
||
return False
|
||
|
||
# 排液
|
||
if not self.dispense(volume, blow_out=True):
|
||
return False
|
||
|
||
# 排液后混合
|
||
if mix_after:
|
||
cycles, mix_vol = mix_after
|
||
self.mix(cycles, mix_vol)
|
||
|
||
logger.info(f"液体转移完成: {volume}ul")
|
||
return True
|
||
|
||
except Exception as e:
|
||
logger.error(f"液体转移失败: {e}")
|
||
return False
|
||
|
||
def mix(self, cycles: int = 3, volume: Optional[float] = None) -> bool:
|
||
"""
|
||
混合
|
||
|
||
Args:
|
||
cycles: 混合次数
|
||
volume: 混合体积
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
volume = volume or self.liquid_params.mix_volume
|
||
|
||
logger.info(f"开始混合: {cycles}次, {volume}ul")
|
||
|
||
for i in range(cycles):
|
||
if not self.aspirate(volume, detection=False):
|
||
return False
|
||
if not self.dispense(volume):
|
||
return False
|
||
|
||
logger.info("混合完成")
|
||
return True
|
||
|
||
def _pre_wet(self, volume: float):
|
||
"""预润湿"""
|
||
self.pipette.aspirate(volume, detection=False)
|
||
time.sleep(0.2)
|
||
self.pipette.dispense(volume)
|
||
time.sleep(0.2)
|
||
|
||
def _touch_tip(self):
|
||
"""接触壁(需要与运动控制配合)"""
|
||
# TODO: 实现接触壁动作
|
||
logger.debug("执行接触壁")
|
||
time.sleep(0.5)
|
||
|
||
def _update_tip_status(self):
|
||
"""更新枪头状态"""
|
||
if self.pipette.get_tip_status():
|
||
self.tip_status = TipStatus.TIP_ATTACHED
|
||
else:
|
||
self.tip_status = TipStatus.NO_TIP
|
||
|
||
def set_liquid_class(self, liquid_class: LiquidClass):
|
||
"""设置液体类型"""
|
||
self.liquid_class = liquid_class
|
||
if liquid_class in self.LIQUID_PARAMS:
|
||
self.liquid_params = self.LIQUID_PARAMS[liquid_class]
|
||
logger.info(f"液体类型设置为: {liquid_class.value}")
|
||
|
||
def set_custom_parameters(self, params: LiquidParameters):
|
||
"""设置自定义液体参数"""
|
||
self.liquid_params = params
|
||
self.liquid_class = LiquidClass.CUSTOM
|
||
|
||
def calibrate_volume(self, expected: float, actual: float):
|
||
"""
|
||
体积校准
|
||
|
||
Args:
|
||
expected: 期望体积
|
||
actual: 实际体积
|
||
"""
|
||
factor = actual / expected
|
||
self.pipette.set_calibration_factor(factor)
|
||
logger.info(f"体积校准系数: {factor}")
|
||
|
||
def get_status(self) -> Dict:
|
||
"""获取状态信息"""
|
||
self._update_tip_status()
|
||
return {
|
||
'tip_status': self.tip_status.value,
|
||
'current_volume': self.current_volume,
|
||
'max_volume': self.max_volume,
|
||
'liquid_class': self.liquid_class.value,
|
||
'statistics': {
|
||
# 'tip_count': self.tip_count,
|
||
'aspirate_count': self.aspirate_count,
|
||
'dispense_count': self.dispense_count
|
||
}
|
||
}
|
||
|
||
def reset_statistics(self):
|
||
"""重置统计信息"""
|
||
# self.tip_count = 0
|
||
self.aspirate_count = 0
|
||
self.dispense_count = 0
|
||
|
||
# ============================================================================
|
||
# 实例化代码块 - 移液控制器使用示例
|
||
# ============================================================================
|
||
|
||
if __name__ == "__main__":
|
||
# 配置日志
|
||
import logging
|
||
|
||
# 设置日志级别
|
||
logging.basicConfig(
|
||
level=logging.INFO,
|
||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||
)
|
||
|
||
def interactive_test():
|
||
"""交互式测试模式 - 适用于已连接的设备"""
|
||
print("\n" + "=" * 60)
|
||
print("🧪 移液器交互式测试模式")
|
||
print("=" * 60)
|
||
|
||
# 获取用户输入的连接参数
|
||
print("\n📡 设备连接配置:")
|
||
port = input("请输入移液器串口端口 (默认: /dev/ttyUSB_CH340): ").strip() or "/dev/ttyUSB_CH340"
|
||
address_input = input("请输入移液器设备地址 (默认: 4): ").strip()
|
||
address = int(address_input) if address_input else 4
|
||
|
||
# 询问是否连接 XYZ 步进电机控制器
|
||
xyz_enable = input("是否连接 XYZ 步进电机控制器? (y/N): ").strip().lower()
|
||
xyz_port = None
|
||
if xyz_enable not in ['n', 'no']:
|
||
xyz_port = input("请输入 XYZ 控制器串口端口 (默认: /dev/ttyUSB_CH340): ").strip() or "/dev/ttyUSB_CH340"
|
||
|
||
try:
|
||
# 创建移液控制器实例
|
||
if xyz_port:
|
||
print(f"\n🔧 创建移液控制器实例 (移液器端口: {port}, 地址: {address}, XYZ端口: {xyz_port})...")
|
||
pipette = PipetteController(port=port, address=address, xyz_port=xyz_port)
|
||
else:
|
||
print(f"\n🔧 创建移液控制器实例 (端口: {port}, 地址: {address})...")
|
||
pipette = PipetteController(port=port, address=address)
|
||
|
||
# 连接设备
|
||
print("\n📞 连接移液器设备...")
|
||
if not pipette.connect():
|
||
print("❌ 设备连接失败,请检查连接")
|
||
return
|
||
print("✅ 设备连接成功")
|
||
|
||
# 初始化设备
|
||
print("\n🚀 初始化设备...")
|
||
if not pipette.initialize():
|
||
print("❌ 设备初始化失败")
|
||
return
|
||
print("✅ 设备初始化成功")
|
||
|
||
# 交互式菜单
|
||
while True:
|
||
print("\n" + "=" * 50)
|
||
print("🎮 交互式操作菜单:")
|
||
print("1. 📋 查看设备状态")
|
||
print("2. 🔧 装载枪头")
|
||
print("3. 🗑️ 弹出枪头")
|
||
print("4. 💧 吸液操作")
|
||
print("5. 💦 排液操作")
|
||
print("6. 🌀 混合操作")
|
||
print("7. 🔄 液体转移")
|
||
print("8. ⚙️ 设置液体类型")
|
||
print("9. 🎯 自定义参数")
|
||
print("10. 📊 校准体积")
|
||
print("11. 🧹 重置统计")
|
||
print("12. 🔍 液体类型测试")
|
||
print("99. 🚨 紧急停止")
|
||
print("0. 🚪 退出程序")
|
||
print("=" * 50)
|
||
|
||
choice = input("\n请选择操作 (0-12, 99): ").strip()
|
||
|
||
if choice == "0":
|
||
print("\n👋 退出程序...")
|
||
break
|
||
elif choice == "1":
|
||
# 查看设备状态
|
||
status = pipette.get_status()
|
||
print("\n📊 设备状态信息:")
|
||
print(f" 🎯 枪头状态: {status['tip_status']}")
|
||
print(f" 💧 当前体积: {status['current_volume']}ul")
|
||
print(f" 📏 最大体积: {status['max_volume']}ul")
|
||
print(f" 🧪 液体类型: {status['liquid_class']}")
|
||
print(f" 📈 统计信息:")
|
||
# print(f" 🔧 枪头使用次数: {status['statistics']['tip_count']}")
|
||
print(f" ⬆️ 吸液次数: {status['statistics']['aspirate_count']}")
|
||
print(f" ⬇️ 排液次数: {status['statistics']['dispense_count']}")
|
||
|
||
elif choice == "2":
|
||
# 装载枪头
|
||
print("\n🔧 装载枪头...")
|
||
if pipette.xyz_connected:
|
||
print("📍 使用 XYZ 控制器进行 Z 轴定位 (下移 10mm)")
|
||
else:
|
||
print("⚠️ 未连接 XYZ 控制器,仅执行移液器枪头装载")
|
||
|
||
if pipette.pickup_tip():
|
||
print("✅ 枪头装载成功")
|
||
if pipette.xyz_connected:
|
||
print("📍 Z 轴已移动到装载位置")
|
||
else:
|
||
print("❌ 枪头装载失败")
|
||
|
||
elif choice == "3":
|
||
# 弹出枪头
|
||
print("\n🗑️ 弹出枪头...")
|
||
if pipette.eject_tip():
|
||
print("✅ 枪头弹出成功")
|
||
else:
|
||
print("❌ 枪头弹出失败")
|
||
|
||
elif choice == "4":
|
||
# 吸液操作
|
||
try:
|
||
volume = float(input("请输入吸液体积 (ul): "))
|
||
detection = input("是否启用液面检测? (y/n, 默认y): ").strip().lower() != 'n'
|
||
print(f"\n💧 执行吸液操作 ({volume}ul)...")
|
||
if pipette.aspirate(volume, detection=detection):
|
||
print(f"✅ 吸液成功: {volume}ul")
|
||
print(f"📊 当前体积: {pipette.current_volume}ul")
|
||
else:
|
||
print("❌ 吸液失败")
|
||
except ValueError:
|
||
print("❌ 请输入有效的数字")
|
||
|
||
elif choice == "5":
|
||
# 排液操作
|
||
try:
|
||
volume = float(input("请输入排液体积 (ul): "))
|
||
blow_out = input("是否执行吹出操作? (y/n, 默认n): ").strip().lower() == 'y'
|
||
print(f"\n💦 执行排液操作 ({volume}ul)...")
|
||
if pipette.dispense(volume, blow_out=blow_out):
|
||
print(f"✅ 排液成功: {volume}ul")
|
||
print(f"📊 剩余体积: {pipette.current_volume}ul")
|
||
else:
|
||
print("❌ 排液失败")
|
||
except ValueError:
|
||
print("❌ 请输入有效的数字")
|
||
|
||
elif choice == "6":
|
||
# 混合操作
|
||
try:
|
||
cycles = int(input("请输入混合次数 (默认3): ") or "3")
|
||
volume_input = input("请输入混合体积 (ul, 默认使用当前体积的50%): ").strip()
|
||
volume = float(volume_input) if volume_input else None
|
||
print(f"\n🌀 执行混合操作 ({cycles}次)...")
|
||
if pipette.mix(cycles=cycles, volume=volume):
|
||
print("✅ 混合完成")
|
||
else:
|
||
print("❌ 混合失败")
|
||
except ValueError:
|
||
print("❌ 请输入有效的数字")
|
||
|
||
elif choice == "7":
|
||
# 液体转移
|
||
try:
|
||
volume = float(input("请输入转移体积 (ul): "))
|
||
source = input("源孔位 (可选, 如A1): ").strip() or None
|
||
dest = input("目标孔位 (可选, 如B1): ").strip() or None
|
||
new_tip = input("是否使用新枪头? (y/n, 默认y): ").strip().lower() != 'n'
|
||
|
||
print(f"\n🔄 执行液体转移 ({volume}ul)...")
|
||
if pipette.transfer(volume=volume, source_well=source, dest_well=dest, new_tip=new_tip):
|
||
print("✅ 液体转移完成")
|
||
else:
|
||
print("❌ 液体转移失败")
|
||
except ValueError:
|
||
print("❌ 请输入有效的数字")
|
||
|
||
elif choice == "8":
|
||
# 设置液体类型
|
||
print("\n🧪 可用液体类型:")
|
||
liquid_options = {
|
||
"1": (LiquidClass.WATER, "水溶液"),
|
||
"2": (LiquidClass.SERUM, "血清"),
|
||
"3": (LiquidClass.VISCOUS, "粘稠液体"),
|
||
"4": (LiquidClass.VOLATILE, "挥发性液体")
|
||
}
|
||
|
||
for key, (liquid_class, description) in liquid_options.items():
|
||
print(f" {key}. {description}")
|
||
|
||
liquid_choice = input("请选择液体类型 (1-4): ").strip()
|
||
if liquid_choice in liquid_options:
|
||
liquid_class, description = liquid_options[liquid_choice]
|
||
pipette.set_liquid_class(liquid_class)
|
||
print(f"✅ 液体类型设置为: {description}")
|
||
|
||
# 显示参数
|
||
params = pipette.liquid_params
|
||
print(f"📋 参数设置:")
|
||
print(f" ⬆️ 吸液速度: {params.aspirate_speed}")
|
||
print(f" ⬇️ 排液速度: {params.dispense_speed}")
|
||
print(f" 💨 空气间隙: {params.air_gap}ul")
|
||
print(f" 💧 预润湿: {'是' if params.pre_wet else '否'}")
|
||
else:
|
||
print("❌ 无效选择")
|
||
|
||
elif choice == "9":
|
||
# 自定义参数
|
||
try:
|
||
print("\n⚙️ 设置自定义参数 (直接回车使用默认值):")
|
||
aspirate_speed = input("吸液速度 (默认500): ").strip()
|
||
dispense_speed = input("排液速度 (默认800): ").strip()
|
||
air_gap = input("空气间隙 (ul, 默认10.0): ").strip()
|
||
pre_wet = input("预润湿 (y/n, 默认n): ").strip().lower() == 'y'
|
||
|
||
custom_params = LiquidParameters(
|
||
aspirate_speed=int(aspirate_speed) if aspirate_speed else 500,
|
||
dispense_speed=int(dispense_speed) if dispense_speed else 800,
|
||
air_gap=float(air_gap) if air_gap else 10.0,
|
||
pre_wet=pre_wet
|
||
)
|
||
|
||
pipette.set_custom_parameters(custom_params)
|
||
print("✅ 自定义参数设置完成")
|
||
except ValueError:
|
||
print("❌ 请输入有效的数字")
|
||
|
||
elif choice == "10":
|
||
# 校准体积
|
||
try:
|
||
expected = float(input("期望体积 (ul): "))
|
||
actual = float(input("实际测量体积 (ul): "))
|
||
pipette.calibrate_volume(expected, actual)
|
||
print(f"✅ 校准完成,校准系数: {actual/expected:.3f}")
|
||
except ValueError:
|
||
print("❌ 请输入有效的数字")
|
||
|
||
elif choice == "11":
|
||
# 重置统计
|
||
pipette.reset_statistics()
|
||
print("✅ 统计信息已重置")
|
||
|
||
elif choice == "12":
|
||
# 液体类型测试
|
||
print("\n🧪 液体类型参数对比:")
|
||
liquid_tests = [
|
||
(LiquidClass.WATER, "水溶液"),
|
||
(LiquidClass.SERUM, "血清"),
|
||
(LiquidClass.VISCOUS, "粘稠液体"),
|
||
(LiquidClass.VOLATILE, "挥发性液体")
|
||
]
|
||
|
||
for liquid_class, description in liquid_tests:
|
||
params = pipette.LIQUID_PARAMS[liquid_class]
|
||
print(f"\n📋 {description} ({liquid_class.value}):")
|
||
print(f" ⬆️ 吸液速度: {params.aspirate_speed}")
|
||
print(f" ⬇️ 排液速度: {params.dispense_speed}")
|
||
print(f" 💨 空气间隙: {params.air_gap}ul")
|
||
print(f" 💧 预润湿: {'是' if params.pre_wet else '否'}")
|
||
print(f" ⏱️ 吸液后延时: {params.delay_after_aspirate}s")
|
||
|
||
elif choice == "99":
|
||
# 紧急停止
|
||
print("\n🚨 执行紧急停止...")
|
||
success = pipette.emergency_stop()
|
||
if success:
|
||
print("✅ 紧急停止执行成功")
|
||
print("⚠️ 所有运动已停止,请检查设备状态")
|
||
else:
|
||
print("❌ 紧急停止执行失败")
|
||
print("⚠️ 请手动检查设备状态并采取必要措施")
|
||
|
||
# 紧急停止后询问是否继续
|
||
continue_choice = input("\n是否继续操作?(y/n): ").strip().lower()
|
||
if continue_choice != 'y':
|
||
print("🚪 退出程序")
|
||
break
|
||
|
||
else:
|
||
print("❌ 无效选择,请重新输入")
|
||
|
||
# 等待用户确认继续
|
||
input("\n按回车键继续...")
|
||
|
||
except KeyboardInterrupt:
|
||
print("\n\n⚠️ 用户中断操作")
|
||
except Exception as e:
|
||
print(f"\n❌ 发生异常: {e}")
|
||
finally:
|
||
# 断开连接
|
||
print("\n📞 断开设备连接...")
|
||
try:
|
||
pipette.disconnect()
|
||
print("✅ 连接已断开")
|
||
except:
|
||
print("⚠️ 断开连接时出现问题")
|
||
|
||
def demo_test():
|
||
"""演示测试模式 - 完整功能演示"""
|
||
print("\n" + "=" * 60)
|
||
print("🎬 移液控制器演示测试")
|
||
print("=" * 60)
|
||
|
||
try:
|
||
# 创建移液控制器实例
|
||
print("1. 🔧 创建移液控制器实例...")
|
||
pipette = PipetteController(port="/dev/ttyUSB0", address=4)
|
||
print("✅ 移液控制器实例创建成功")
|
||
|
||
# 连接设备
|
||
print("\n2. 📞 连接移液器设备...")
|
||
if pipette.connect():
|
||
print("✅ 设备连接成功")
|
||
else:
|
||
print("❌ 设备连接失败")
|
||
return False
|
||
|
||
# 初始化设备
|
||
print("\n3. 🚀 初始化设备...")
|
||
if pipette.initialize():
|
||
print("✅ 设备初始化成功")
|
||
else:
|
||
print("❌ 设备初始化失败")
|
||
return False
|
||
|
||
# 装载枪头
|
||
print("\n4. 🔧 装载枪头...")
|
||
if pipette.pickup_tip():
|
||
print("✅ 枪头装载成功")
|
||
else:
|
||
print("❌ 枪头装载失败")
|
||
|
||
# 设置液体类型
|
||
print("\n5. 🧪 设置液体类型为血清...")
|
||
pipette.set_liquid_class(LiquidClass.SERUM)
|
||
print("✅ 液体类型设置完成")
|
||
|
||
# 吸液操作
|
||
print("\n6. 💧 执行吸液操作...")
|
||
volume_to_aspirate = 100.0
|
||
if pipette.aspirate(volume_to_aspirate, detection=True):
|
||
print(f"✅ 吸液成功: {volume_to_aspirate}ul")
|
||
print(f"📊 当前体积: {pipette.current_volume}ul")
|
||
else:
|
||
print("❌ 吸液失败")
|
||
|
||
# 排液操作
|
||
print("\n7. 💦 执行排液操作...")
|
||
volume_to_dispense = 50.0
|
||
if pipette.dispense(volume_to_dispense, blow_out=True):
|
||
print(f"✅ 排液成功: {volume_to_dispense}ul")
|
||
print(f"📊 剩余体积: {pipette.current_volume}ul")
|
||
else:
|
||
print("❌ 排液失败")
|
||
|
||
# 混合操作
|
||
print("\n8. 🌀 执行混合操作...")
|
||
if pipette.mix(cycles=3, volume=30.0):
|
||
print("✅ 混合完成")
|
||
else:
|
||
print("❌ 混合失败")
|
||
|
||
# 获取状态信息
|
||
print("\n9. 📊 获取设备状态...")
|
||
status = pipette.get_status()
|
||
print("设备状态信息:")
|
||
print(f" 🎯 枪头状态: {status['tip_status']}")
|
||
print(f" 💧 当前体积: {status['current_volume']}ul")
|
||
print(f" 📏 最大体积: {status['max_volume']}ul")
|
||
print(f" 🧪 液体类型: {status['liquid_class']}")
|
||
print(f" 📈 统计信息:")
|
||
# print(f" 🔧 枪头使用次数: {status['statistics']['tip_count']}")
|
||
print(f" ⬆️ 吸液次数: {status['statistics']['aspirate_count']}")
|
||
print(f" ⬇️ 排液次数: {status['statistics']['dispense_count']}")
|
||
|
||
# 弹出枪头
|
||
print("\n10. 🗑️ 弹出枪头...")
|
||
if pipette.eject_tip():
|
||
print("✅ 枪头弹出成功")
|
||
else:
|
||
print("❌ 枪头弹出失败")
|
||
|
||
print("\n" + "=" * 60)
|
||
print("✅ 移液控制器演示测试完成")
|
||
print("=" * 60)
|
||
|
||
return True
|
||
|
||
except Exception as e:
|
||
print(f"\n❌ 测试过程中发生异常: {e}")
|
||
return False
|
||
|
||
finally:
|
||
# 断开连接
|
||
print("\n📞 断开连接...")
|
||
pipette.disconnect()
|
||
print("✅ 连接已断开")
|
||
|
||
# 主程序入口
|
||
print("🧪 移液器控制器测试程序")
|
||
print("=" * 40)
|
||
print("1. 🎮 交互式测试 (推荐)")
|
||
print("2. 🎬 演示测试")
|
||
print("0. 🚪 退出")
|
||
print("=" * 40)
|
||
|
||
mode = input("请选择测试模式 (0-2): ").strip()
|
||
|
||
if mode == "1":
|
||
interactive_test()
|
||
elif mode == "2":
|
||
demo_test()
|
||
elif mode == "0":
|
||
print("👋 再见!")
|
||
else:
|
||
print("❌ 无效选择")
|
||
|
||
print("\n🎉 程序结束!")
|
||
print("\n💡 使用说明:")
|
||
print("1. 确保移液器硬件已正确连接")
|
||
print("2. 根据实际情况修改串口端口号")
|
||
print("3. 交互模式支持实时操作和参数调整")
|
||
print("4. 在实际使用中需要配合运动控制器进行位置移动")
|