diff --git a/hardware/opentrons_hardware/scripts/can_comm.py b/hardware/opentrons_hardware/scripts/can_comm.py index c55e9b6ef80..f5f74881ddf 100644 --- a/hardware/opentrons_hardware/scripts/can_comm.py +++ b/hardware/opentrons_hardware/scripts/can_comm.py @@ -7,6 +7,7 @@ from logging.config import dictConfig from typing import Type, Sequence, Callable, TypeVar +from opentrons_hardware.drivers.can_bus import build from opentrons_hardware.firmware_bindings.constants import ( MessageId, NodeId, @@ -20,7 +21,6 @@ from opentrons_hardware.drivers.can_bus.abstract_driver import AbstractCanDriver from opentrons_hardware.firmware_bindings.messages.messages import get_definition -from opentrons_hardware.drivers.can_bus.build import build_driver from opentrons_hardware.scripts.can_args import add_can_args, build_settings from opentrons_hardware.firmware_bindings.utils import ( BinarySerializable, @@ -213,10 +213,8 @@ async def ui_task(can_driver: AbstractCanDriver) -> None: print(in_red(str(e))) -async def run(args: argparse.Namespace) -> None: - """Entry point for script.""" - driver = await build_driver(build_settings(args)) - +async def run_ui(driver: AbstractCanDriver) -> None: + """Run the UI.""" loop = asyncio.get_event_loop() fut = asyncio.gather( loop.create_task(listen_task(driver)), loop.create_task(ui_task(driver)) @@ -227,8 +225,12 @@ async def run(args: argparse.Namespace) -> None: fut.cancel() except asyncio.CancelledError: pass - finally: - driver.shutdown() + + +async def run(args: argparse.Namespace) -> None: + """Entry point for script.""" + async with build.driver(build_settings(args)) as driver: + await (run_ui(driver)) def in_red(s: str) -> str: diff --git a/hardware/opentrons_hardware/scripts/can_control.py b/hardware/opentrons_hardware/scripts/can_control.py index 533b14e27c1..a0f84bf2a38 100644 --- a/hardware/opentrons_hardware/scripts/can_control.py +++ b/hardware/opentrons_hardware/scripts/can_control.py @@ -11,13 +11,10 @@ from logging.config import dictConfig from typing import TextIO, Optional +from opentrons_hardware.drivers.can_bus import build, CanMessenger from opentrons_hardware.drivers.can_bus.abstract_driver import AbstractCanDriver -from opentrons_hardware.drivers.can_bus.can_messenger import ( - CanMessenger, -) -from opentrons_hardware.firmware_bindings.message import CanMessage -from opentrons_hardware.drivers.can_bus.build import build_driver +from opentrons_hardware.firmware_bindings.message import CanMessage from opentrons_hardware.scripts.can_args import add_can_args, build_settings from .can_mon import task as monitor_task @@ -76,24 +73,19 @@ async def input_task( async def run(args: argparse.Namespace) -> None: """Entry point for script.""" - driver = await build_driver(build_settings(args)) - - messenger = CanMessenger(driver) - messenger.start() - - try: - all_fut = asyncio.gather( - monitor_task(messenger, args.output), - input_task(driver, args.input, args.output), - ) - await all_fut - except KeyboardInterrupt: - all_fut.cancel() - except asyncio.CancelledError: - pass - finally: - await messenger.stop() - driver.shutdown() + async with build.driver(build_settings(args)) as driver, CanMessenger( + driver + ) as messenger: + try: + all_fut = asyncio.gather( + monitor_task(messenger, args.output), + input_task(driver, args.input, args.output), + ) + await all_fut + except KeyboardInterrupt: + all_fut.cancel() + except asyncio.CancelledError: + pass LOG_CONFIG = { diff --git a/hardware/opentrons_hardware/scripts/can_mon.py b/hardware/opentrons_hardware/scripts/can_mon.py index 87220657dd7..cf55fac22e9 100644 --- a/hardware/opentrons_hardware/scripts/can_mon.py +++ b/hardware/opentrons_hardware/scripts/can_mon.py @@ -9,8 +9,8 @@ from logging.config import dictConfig from typing import List, TextIO - -from opentrons_hardware.drivers.can_bus.can_messenger import ( +from opentrons_hardware.drivers.can_bus import ( + build, CanMessenger, WaitableCallback, ) @@ -19,7 +19,6 @@ NodeId, ) -from opentrons_hardware.drivers.can_bus.build import build_driver from opentrons_hardware.scripts.can_args import add_can_args, build_settings log = logging.getLogger(__name__) @@ -114,22 +113,15 @@ async def task( async def run(args: argparse.Namespace) -> None: """Entry point for script.""" - driver = await build_driver(build_settings(args)) - - messenger = CanMessenger(driver) - messenger.start() - - loop = asyncio.get_event_loop() - fut = loop.create_task(task(messenger, args.output)) - try: - await fut - except KeyboardInterrupt: - fut.cancel() - except asyncio.CancelledError: - pass - finally: - await messenger.stop() - driver.shutdown() + async with build.can_messenger(build_settings(args)) as messenger: + loop = asyncio.get_event_loop() + fut = loop.create_task(task(messenger, args.output)) + try: + await fut + except KeyboardInterrupt: + fut.cancel() + except asyncio.CancelledError: + pass LOG_CONFIG = { diff --git a/hardware/opentrons_hardware/scripts/gripper.py b/hardware/opentrons_hardware/scripts/gripper.py index 928061df2f9..8dedfa306f0 100644 --- a/hardware/opentrons_hardware/scripts/gripper.py +++ b/hardware/opentrons_hardware/scripts/gripper.py @@ -6,6 +6,8 @@ from typing import Callable from logging.config import dictConfig + +from opentrons_hardware.drivers.can_bus import build from opentrons_hardware.firmware_bindings.messages import payloads from opentrons_hardware.firmware_bindings.messages.message_definitions import ( SetupRequest, @@ -15,7 +17,6 @@ from opentrons_hardware.drivers.can_bus.can_messenger import CanMessenger from opentrons_hardware.firmware_bindings.constants import NodeId from opentrons_hardware.scripts.can_args import add_can_args, build_settings -from opentrons_hardware.drivers.can_bus.build import build_driver from opentrons_hardware.hardware_control.gripper_settings import ( set_pwm_param, set_reference_voltage, @@ -82,19 +83,12 @@ def output_details(i: int, freq: int, duty_cycle: int, v_ref: float) -> None: print(f"PWM: {freq}Hz {duty_cycle}%\n") -async def run(args: argparse.Namespace) -> None: - """Entry point for script.""" - os.system("cls") - os.system("clear") - - print("Gripper testing beings... \n") +async def run_test(messenger: CanMessenger) -> None: + """Run the for test.""" + print("Gripper testing begins... \n") pwm_freq = prompt_int_input("PWM frequency in Hz (int)") pwm_duty = prompt_int_input("PWM duty cycle in % (int)") - driver = await build_driver(build_settings(args)) - messenger = CanMessenger(driver=driver) - messenger.start() - """Setup gripper""" try: await messenger.send(node_id=NodeId.gripper, message=SetupRequest()) @@ -119,8 +113,15 @@ async def run(args: argparse.Namespace) -> None: finally: print("\nTesting finishes...\n") await messenger.send(node_id=NodeId.gripper, message=DisableMotorRequest()) - await messenger.stop() - driver.shutdown() + + +async def run(args: argparse.Namespace) -> None: + """Entry point for script.""" + os.system("cls") + os.system("clear") + + async with build.can_messenger(build_settings(args)) as messenger: + await run_test(messenger) log = logging.getLogger(__name__) diff --git a/hardware/opentrons_hardware/scripts/gripper_currents.py b/hardware/opentrons_hardware/scripts/gripper_currents.py index e88b809a89f..9a33a875561 100644 --- a/hardware/opentrons_hardware/scripts/gripper_currents.py +++ b/hardware/opentrons_hardware/scripts/gripper_currents.py @@ -6,6 +6,8 @@ from typing import Callable from logging.config import dictConfig + +from opentrons_hardware.drivers.can_bus import build from opentrons_hardware.firmware_bindings.messages.message_definitions import ( SetupRequest, DisableMotorRequest, @@ -17,7 +19,6 @@ from opentrons_hardware.drivers.can_bus.can_messenger import CanMessenger from opentrons_hardware.firmware_bindings.constants import NodeId from opentrons_hardware.scripts.can_args import add_can_args, build_settings -from opentrons_hardware.drivers.can_bus.build import build_driver from opentrons_hardware.hardware_control.gripper_settings import ( set_pwm_param, set_reference_voltage, @@ -73,22 +74,15 @@ async def execute_move(messenger: CanMessenger) -> None: ) -async def run(args: argparse.Namespace) -> None: - """Entry point for script.""" - os.system("cls") - os.system("clear") - - print("Gripper testing beings... \n") +async def run_test(messenger: CanMessenger) -> None: + """Run test.""" + print("Gripper testing begins... \n") print("Hints: \033[96mdefaults values\033[0m \n") v_ref = prompt_float_input( "Set reference voltage in A (float, \033[96m0.5A\033[0m)" ) pwm_freq = prompt_int_input("Set PWM frequency in Hz (int, \033[96m32000Hz\033[0m)") - driver = await build_driver(build_settings(args)) - messenger = CanMessenger(driver=driver) - messenger.start() - try: await messenger.send(node_id=NodeId.gripper, message=SetupRequest()) await set_reference_voltage(messenger, v_ref) @@ -114,8 +108,15 @@ async def run(args: argparse.Namespace) -> None: finally: print("\nTesting finishes...\n") await messenger.send(node_id=NodeId.gripper, message=DisableMotorRequest()) - await messenger.stop() - driver.shutdown() + + +async def run(args: argparse.Namespace) -> None: + """Entry point for script.""" + os.system("cls") + os.system("clear") + + async with build.can_messenger(build_settings(args)) as messenger: + await run_test(messenger) log = logging.getLogger(__name__) diff --git a/hardware/opentrons_hardware/scripts/monitor_sensors.py b/hardware/opentrons_hardware/scripts/monitor_sensors.py index 292214148bc..47b730b2bf5 100644 --- a/hardware/opentrons_hardware/scripts/monitor_sensors.py +++ b/hardware/opentrons_hardware/scripts/monitor_sensors.py @@ -3,7 +3,8 @@ import argparse import datetime -from opentrons_hardware.drivers.can_bus.can_messenger import ( +from opentrons_hardware.drivers.can_bus import ( + build, CanMessenger, WaitableCallback, ) @@ -19,7 +20,6 @@ sensor_fixed_point_conversion, ) -from opentrons_hardware.drivers.can_bus.build import build_driver from opentrons_hardware.scripts.can_args import add_can_args, build_settings @@ -67,14 +67,12 @@ async def do_run( async def run(args: argparse.Namespace) -> None: """Entry point for script.""" - driver = await build_driver(build_settings(args)) target = constants.NodeId["pipette_" + args.mount] sensor = constants.SensorType[args.sensor] - messenger = CanMessenger(driver) - messenger.start() - with WaitableCallback(messenger) as reader: - return await do_run(messenger, reader, target, sensor, args.threshold) + async with build.can_messenger(build_settings(args)) as messenger: + with WaitableCallback(messenger) as reader: + return await do_run(messenger, reader, target, sensor, args.threshold) def main() -> None: diff --git a/hardware/opentrons_hardware/scripts/move.py b/hardware/opentrons_hardware/scripts/move.py index f48e66ad09f..aa861450dc3 100644 --- a/hardware/opentrons_hardware/scripts/move.py +++ b/hardware/opentrons_hardware/scripts/move.py @@ -4,10 +4,8 @@ import logging from numpy import float64 from logging.config import dictConfig -from typing import Optional -from opentrons_hardware.drivers.can_bus import CanDriver -from opentrons_hardware.drivers.can_bus.can_messenger import CanMessenger +from opentrons_hardware.drivers.can_bus import build, CanMessenger from opentrons_hardware.firmware_bindings.constants import NodeId from opentrons_hardware.firmware_bindings.messages.message_definitions import ( @@ -16,8 +14,7 @@ ) from opentrons_hardware.hardware_control.motion import MoveGroupSingleAxisStep from opentrons_hardware.hardware_control.move_group_runner import MoveGroupRunner -from opentrons_hardware.scripts.can_args import add_can_args - +from opentrons_hardware.scripts.can_args import add_can_args, build_settings log = logging.getLogger(__name__) @@ -43,15 +40,8 @@ } -async def run(interface: str, bitrate: int, channel: Optional[str] = None) -> None: - """Entry point for script.""" - log.info(f"Connecting to {interface} {bitrate} {channel}") - driver = await CanDriver.build( - bitrate=bitrate, interface=interface, channel=channel - ) - messenger = CanMessenger(driver=driver) - messenger.start() - +async def run_move(messenger: CanMessenger) -> None: + """Run the move.""" await messenger.send(node_id=NodeId.broadcast, message=SetupRequest()) await messenger.send(node_id=NodeId.broadcast, message=EnableMotorRequest()) @@ -99,9 +89,12 @@ async def run(interface: str, bitrate: int, channel: Optional[str] = None) -> No await runner.run(can_messenger=messenger) except asyncio.CancelledError: pass - finally: - await messenger.stop() - driver.shutdown() + + +async def run(args: argparse.Namespace) -> None: + """Entry point for script.""" + async with build.can_messenger(build_settings(args)) as messenger: + await run_move(messenger) def main() -> None: @@ -113,7 +106,7 @@ def main() -> None: args = parser.parse_args() - asyncio.run(run(args.interface, args.bitrate, args.channel)) + asyncio.run(run(args)) if __name__ == "__main__": diff --git a/hardware/opentrons_hardware/scripts/sensor_pass.py b/hardware/opentrons_hardware/scripts/sensor_pass.py index 3388752bda4..565e77ed2c5 100644 --- a/hardware/opentrons_hardware/scripts/sensor_pass.py +++ b/hardware/opentrons_hardware/scripts/sensor_pass.py @@ -6,8 +6,7 @@ from logging.config import dictConfig from typing import Iterator, List, Any, Dict -from opentrons_hardware.drivers.can_bus.build import build_driver -from opentrons_hardware.drivers.can_bus.can_messenger import CanMessenger +from opentrons_hardware.drivers.can_bus import build, CanMessenger from opentrons_hardware.firmware_bindings.utils.binary_serializable import Int32Field from opentrons_hardware.firmware_bindings.constants import NodeId, SensorType from opentrons_hardware.firmware_bindings.arbitration_id import ArbitrationId @@ -89,15 +88,11 @@ def __call__( ) -async def run(args: argparse.Namespace) -> None: - """Entry point for script.""" - driver = await build_driver(build_settings(args)) - messenger = CanMessenger(driver=driver) - messenger.start() - +async def run_test(messenger: CanMessenger, args: argparse.Namespace) -> None: + """Run the test.""" target_z = NodeId["head_" + args.mount[0]] target_pipette = NodeId["pipette_" + args.mount] - found = await probe(messenger, set((NodeId.head, target_pipette)), 10) + found = await probe(messenger, {NodeId.head, target_pipette}, 10) if NodeId.head not in found or target_pipette not in found: raise RuntimeError(f"could not find targets for {args.mount} in {found}") @@ -171,8 +166,12 @@ async def run(args: argparse.Namespace) -> None: runner = MoveGroupRunner(move_groups=[move_groups[0]]) await runner.run(can_messenger=messenger) await messenger.send(NodeId.broadcast, message_definitions.DisableMotorRequest()) - await messenger.stop() - driver.shutdown() + + +async def run(args: argparse.Namespace) -> None: + """Entry point for script.""" + async with build.can_messenger(build_settings(args)) as messenger: + await run_test(messenger, args) def main() -> None: diff --git a/hardware/opentrons_hardware/scripts/sensors.py b/hardware/opentrons_hardware/scripts/sensors.py index 88741395f5e..c59a301e905 100644 --- a/hardware/opentrons_hardware/scripts/sensors.py +++ b/hardware/opentrons_hardware/scripts/sensors.py @@ -5,10 +5,11 @@ from enum import Enum from typing import Type, Sequence, Callable, Tuple from logging.config import dictConfig + +from opentrons_hardware.drivers.can_bus import build from opentrons_hardware.drivers.can_bus.abstract_driver import AbstractCanDriver from opentrons_hardware.firmware_bindings.constants import NodeId, SensorType from opentrons_hardware.scripts.can_args import add_can_args, build_settings -from opentrons_hardware.drivers.can_bus.build import build_driver from .sensor_utils import ( SensorRun, @@ -162,18 +163,15 @@ async def ui_task(can_driver: AbstractCanDriver) -> None: async def run(args: argparse.Namespace) -> None: """Entry point for script.""" - driver = await build_driver(build_settings(args)) - - loop = asyncio.get_event_loop() - task = loop.create_task(ui_task(driver)) - try: - await task - except KeyboardInterrupt: - task.cancel() - except asyncio.CancelledError: - pass - finally: - driver.shutdown() + async with build.driver(build_settings(args)) as driver: + loop = asyncio.get_event_loop() + task = loop.create_task(ui_task(driver)) + try: + await task + except KeyboardInterrupt: + task.cancel() + except asyncio.CancelledError: + pass log = logging.getLogger(__name__) diff --git a/hardware/opentrons_hardware/scripts/set_current.py b/hardware/opentrons_hardware/scripts/set_current.py index b319ba36003..66aaebadec5 100644 --- a/hardware/opentrons_hardware/scripts/set_current.py +++ b/hardware/opentrons_hardware/scripts/set_current.py @@ -7,10 +7,9 @@ from logging.config import dictConfig from typing import Dict, Tuple -from opentrons_hardware.drivers.can_bus.can_messenger import CanMessenger +from opentrons_hardware.drivers.can_bus import build from opentrons_hardware.firmware_bindings.constants import NodeId -from opentrons_hardware.drivers.can_bus.build import build_driver from opentrons_hardware.hardware_control.current_settings import set_currents from opentrons_hardware.scripts.can_args import add_can_args, build_settings @@ -41,10 +40,6 @@ async def run(args: argparse.Namespace) -> None: """Entry point for script.""" - driver = await build_driver(build_settings(args)) - messenger = CanMessenger(driver=driver) - messenger.start() - with open(args.params_file_path, "r") as f: current_params = json.load(f) @@ -52,13 +47,11 @@ async def run(args: argparse.Namespace) -> None: for k, v in current_params.items(): currents[NodeId[k]] = (float(v["hold_current"]), float(v["run_current"])) - try: - await set_currents(messenger, currents) - except asyncio.CancelledError: - pass - finally: - await messenger.stop() - driver.shutdown() + async with build.can_messenger(build_settings(args)) as messenger: + try: + await set_currents(messenger, currents) + except asyncio.CancelledError: + pass def main() -> None: diff --git a/hardware/opentrons_hardware/scripts/update_fw.py b/hardware/opentrons_hardware/scripts/update_fw.py index 50e1ec3d299..2e7235e6cf8 100644 --- a/hardware/opentrons_hardware/scripts/update_fw.py +++ b/hardware/opentrons_hardware/scripts/update_fw.py @@ -6,8 +6,7 @@ from typing_extensions import Final -from opentrons_hardware.drivers.can_bus import CanMessenger -from opentrons_hardware.drivers.can_bus.build import build_driver +from opentrons_hardware.drivers.can_bus import build from opentrons_hardware.firmware_bindings import NodeId from opentrons_hardware.firmware_update.run import run_update from .can_args import add_can_args, build_settings @@ -53,12 +52,7 @@ async def run(args: argparse.Namespace) -> None: timeout_seconds = args.timeout_seconds erase = not args.no_erase - driver = await build_driver(build_settings(args)) - - messenger = CanMessenger(driver) - messenger.start() - - try: + async with build.can_messenger(build_settings(args)) as messenger: await run_update( messenger=messenger, node_id=target, @@ -67,8 +61,6 @@ async def run(args: argparse.Namespace) -> None: timeout_seconds=timeout_seconds, erase=erase, ) - finally: - await messenger.stop() logger.info("Done") diff --git a/hardware/tests/firmware_integration/conftest.py b/hardware/tests/firmware_integration/conftest.py index badad47f022..fe4bf09cb46 100644 --- a/hardware/tests/firmware_integration/conftest.py +++ b/hardware/tests/firmware_integration/conftest.py @@ -26,10 +26,8 @@ async def can_messenger( driver: AbstractCanDriver, ) -> AsyncIterator[CanMessenger]: """Create Can messenger.""" - messenger = CanMessenger(driver) - messenger.start() - yield messenger - await messenger.stop() + async with CanMessenger(driver) as messenger: + yield messenger @pytest.fixture