async def _update_firmware(filename, loop): """ This method remains in the API currently because of its use of the robot singleton's copy of the driver. This should move to the server lib project eventually and use its own driver object (preferably involving moving the drivers themselves to the serverlib) """ # ensure there is a reference to the port if not robot.is_connected(): robot.connect() # get port name port = str(robot._driver.port) # set smoothieware into programming mode robot._driver._smoothie_programming_mode() # close the port so other application can access it robot._driver._connection.close() # run lpc21isp, THIS WILL TAKE AROUND 1 MINUTE TO COMPLETE update_cmd = 'lpc21isp -wipe -donotstart {0} {1} {2} 12000'.format( filename, port, robot.config.serial_speed) proc = await asyncio.create_subprocess_shell( update_cmd, stdout=asyncio.subprocess.PIPE, loop=loop) rd = await proc.stdout.read() res = rd.decode().strip() await proc.wait() # re-open the port robot._driver._connection.open() # reset smoothieware robot._driver._smoothie_reset() # run setup gcodes robot._driver._setup() return res
def setup(): global header, p50, p300, stock_wells, tube_rack, df df = np.genfromtxt('solutionmaker.csv', delimiter=',', skip_header=1, missing_values='') with open('solutionmaker.csv') as csvfile: reader_object = csv.reader(csvfile) header = [row for i_row, row in enumerate(reader_object) if i_row == 0] (nrows, ncols) = df.shape for n_row in range(nrows): if (df[n_row, :].sum() > 1500): raise ValueError( 'Individual wells will not tolerate addition of this much volume' ) """ The following are constants for instantiation (mm/sec or ul/sec) ----------------------------------------- """ XSPEED = 600 YSPEED = 600 ZSPEED = 125 P300_ASPIRATERATE = 150 P50_ASPIRATE = 25 P50_DISPENSERATE = 100 P300_DISPENSERATE = 600 """ ------------------------------------------ """ # connects robot and sets robot settings robot.home() robot.connect() robot.head_speed(x=XSPEED, y=YSPEED, z=ZSPEED) # sets up labware and the layout of the experiment m300rack_1 = containers.load('tiprack-200ul', '10', share='True') m300rack_2 = containers.load('tiprack-200ul', '11', share='True') stock_wells = [] slot_plate_wells = ['4', '5'] for slot in slot_plate_wells: stock_wells.append(containers.load('plate_6_well', slot, share='True')) stock_wells.append(containers.load('96-flat', '6', share='True')) tube_rack = [] slots_tube_rack = ['1', '2', '3'] for slot in slots_tube_rack: tube_rack.append(containers.load('4x6_Tube_rack', slot, share='True')) # instantiates pipettes p50 = instruments.P50_Single(mount="right", tip_racks=[m300rack_1], aspirate_flow_rate=P50_ASPIRATE, dispense_flow_rate=P50_DISPENSERATE) p300 = instruments.P300_Single(mount="left", tip_racks=[m300rack_2], aspirate_flow_rate=P300_ASPIRATERATE, dispense_flow_rate=P300_DISPENSERATE)
def connect_to_robot(): ''' Connect over Serial to the Smoothieware motor driver ''' print() from opentrons import robot print('Connecting to robot...') robot.connect() return robot
def opentrons_connect(): try: # physical robot ports = robot.get_serial_ports_list() print(ports) robot.connect(ports[0]) except IndexError: # simulator robot.connect('Virtual Smoothie') robot.home(now=True)
async def test_multi_single(main_router, protocol, protocol_file, dummy_db): robot.connect() robot.home() session = main_router.session_manager.create(name='<blank>', contents=protocol.text) await main_router.wait_until(state('session', 'loaded')) main_router.calibration_manager.move_to(session.instruments[0], session.containers[2])
def main(): """ This application creates and starts the server for both the RPC routes handled by opentrons.server.rpc and HTTP endpoints defined here """ log_init() arg_parser = ArgumentParser(description="Opentrons application server", prog="opentrons.server.main") arg_parser.add_argument( "-H", "--hostname", help="TCP/IP hostname to serve on (default: %(default)r)", default="localhost") arg_parser.add_argument( "-P", "--port", help="TCP/IP port to serve on (default: %(default)r)", type=int, default="8080") arg_parser.add_argument( "-U", "--path", help="Unix file system path to serve on. Specifying a path will cause " "hostname and port arguments to be ignored.", ) args, _ = arg_parser.parse_known_args(sys.argv[1:]) if args.path: log.debug("Starting Opentrons server application on {}".format( args.path)) else: log.debug("Starting Opentrons server application on {}:{}".format( args.hostname, args.port)) try: robot.connect() except Exception as e: log.exception("Error while connecting to motor-driver: {}".format(e)) log.info("API server version: {}".format(__version__)) log.info("Smoothie FW version: {}".format(robot.fw_version)) if not ff.disable_home_on_boot(): log.info("Homing Z axes") robot.home_z() if not os.environ.get("ENABLE_VIRTUAL_SMOOTHIE"): setup_udev_rules_file() atexit.register(unlock_resin_updates) lock_resin_updates() web.run_app(init(), host=args.hostname, port=args.port, path=args.path) arg_parser.exit(message="Stopped\n")
def connect_to_port(): parser = optparse.OptionParser(usage='usage: %prog [options] ') parser.add_option("-p", "--p", dest="port", default='', type='str', help='serial port of the smoothie') options, _ = parser.parse_args(args=None, values=None) if options.port: robot.connect(options.port) else: robot.connect()
def opentrons_connect(ignore=''): try: # physical robot ports = robot.get_serial_ports_list() print(ports) for port in ports: if port == ignore: continue robot.connect(port) break except IndexError: # simulator robot.connect('Virtual Smoothie') robot.home(now=True)
def main(): """ A CLI application for performing factory calibration of an Opentrons robot Instructions: - Robot must be set up with a 300ul single-channel pipette installed on the right-hand mount. - Put a GEB 300ul tip onto the pipette. - Use the arrow keys to jog the robot over an open area of the deck (the base deck surface, not over a ridge or numeral engraving). You can use the '-' and '=' keys to decrease or increase the amount of distance moved with each jog action. - Use the 'q' and 'a' keys to jog the pipette up and down respectively until the tip is just touching the deck surface, then press 'z'. - Press '1' to automatically go to the expected location of the first calibration point. Jog the robot until the tip is actually at the point, then press 'enter'. - Repeat with '2' and '3'. - After calibrating all three points, press the space bar to save the configuration. - Optionally, press 4,5,6 or 7 to validate the new configuration. - Press 'p' to perform tip probe. - Press 'esc' to exit the program. """ prompt = input( ">>> Warning! Running this tool backup and clear any previous " "calibration data. Proceed (y/[n])? ") if prompt not in ['y', 'Y', 'yes']: print('Exiting--prior configuration data not changed') sys.exit() backup_configuration_and_reload() robot.connect() robot.home() # lights help the script user to see the points on the deck robot.turn_on_rail_lights() atexit.register(robot.turn_off_rail_lights) # Notes: # - 200ul tip is 51.7mm long when attached to a pipette # - For xyz coordinates, (0, 0, 0) is the lower-left corner of the robot cli = CLITool( point_set=get_calibration_points(), tip_length=51.7) cli.ui_loop.run() print('Robot config: \n', robot.config)
async def _update_firmware(filename, loop): """ Currently uses the robot singleton from the API server to connect to Smoothie. Those calls should be separated out from the singleton so it can be used directly without requiring a full initialization of the API robot. """ try: from opentrons import robot except ModuleNotFoundError: res = "Unable to find module `opentrons`--not updating firmware" rc = 1 log.error(res) else: # ensure there is a reference to the port if not robot.is_connected(): robot.connect() # get port name port = str(robot._driver.port) # set smoothieware into programming mode robot._driver._smoothie_programming_mode() # close the port so other application can access it robot._driver._connection.close() # run lpc21isp, THIS WILL TAKE AROUND 1 MINUTE TO COMPLETE update_cmd = 'lpc21isp -wipe -donotstart {0} {1} {2} 12000'.format( filename, port, robot.config.serial_speed) proc = await asyncio.create_subprocess_shell( update_cmd, stdout=asyncio.subprocess.PIPE, loop=loop) rd = await proc.stdout.read() res = rd.decode().strip() await proc.communicate() rc = proc.returncode if rc == 0: # re-open the port robot._driver._connection.open() # reset smoothieware robot._driver._smoothie_reset() # run setup gcodes robot._driver._setup() return res, rc
def test_switches_and_lights(): print('\n') print('* BUTTON\t--> BLUE') print('* PROBE\t\t--> GREEN') print('* ENDSTOP\t--> RED') print('* WINDOW\t--> LIGHTS') print('') print('Next\t--> CTRL-C') print('') # enter button-read loop robot.connect() try: while True: state = _get_state_of_inputs() _set_lights(state) except KeyboardInterrupt: print() pass
def initialize(magnet=False, **kwarg): """ connect, reset and home robot. create robot variables to use. initialize is already built into load_deck(deck_plan). don't need to specifically use initialize. """ from opentrons import labware, instruments, robot, modules import sys sys.path.append( "/data/user_storage/opentrons_data/jupyter/modules_storage") import labware_volume as lv global robot, labware, instruments, modules, lv robot, labware, instruments, modules, lv = robot, labware, instruments, modules, lv robot.connect() robot.reset() if magnet: for module in robot.modules: module.disconnect() robot.modules = modules.discover_and_connect()
def connectRobot(): port = request.json.get('port') options = request.json.get('options', {'limit_switches': False}) status = 'success' data = None robot = Robot.get_instance() try: robot.connect(port, options=options) except Exception as e: # any robot version incompatibility will be caught here robot.disconnect() status = 'error' data = str(e) if "versions are incompatible" in data: data += ". To upgrade, go to docs.opentrons.com" emit_notifications([data], 'danger') return flask.jsonify({'status': status, 'data': data})
def connect_to_robot(): ''' Connect over Serial to the Smoothieware motor driver ''' print() import optparse from opentrons import robot print('Connecting to robot...') parser = optparse.OptionParser(usage='usage: %prog [options] ') parser.add_option("-p", "--p", dest="port", default='', type='str', help='serial port of the smoothie') options, _ = parser.parse_args(args=None, values=None) if options.port: robot.connect(options.port) else: robot.connect() return robot
PORT = '/dev/tty.usbmodem621' tiprack = containers.load('tiprack-200ul', 'B2') plate = containers.load('96-flat', 'B1') ddH2O = containers.load('point', 'B3', 'ddH2O-trough') trash = containers.load('point', 'C2', 'holywastedplasticbatman') p200 = instruments.Pipette(axis='a', max_volume=230, min_volume=20, tip_racks=[tiprack], trash_container=trash, channels=8, name='p200-8') robot.connect(PORT) robot.home() # # with open('./calibrations/calibrations.json', 'r') as c: # import_calibration_json(c, robot, True) def move_liquid(start, end, volume): # robot.home(enqueue=True) robot.clear_commands() p200.pick_up_tip() p200.aspirate(volume, plate[start]) p200.dispense(volume, plate[end]) p200.drop_tip()
def smoke(): robot.connect() robot.reset() robot.home() robot._driver.log.clear() from tests.opentrons.data import smoke # NOQA
def test_smoothie_gpio(): from opentrons.drivers import serial_communication from opentrons.drivers.smoothie_drivers.driver_3_0 import SMOOTHIE_ACK def _write_and_return(msg): return serial_communication.write_and_return( msg + '\r\n\r\n', SMOOTHIE_ACK, robot._driver._connection, timeout=1) print('CONNECT') robot.connect() d = robot._driver # make sure the driver is currently working as expected version_response = _write_and_return('version') if 'version' in version_response: print(RESULT_SPACE.format(PASS)) else: print(RESULT_SPACE.format(FAIL)) print('DATA LOSS') [_write_and_return('version') for i in range(10)] data = [_write_and_return('version') for i in range(100)] if len(set(data)) == 1: print(RESULT_SPACE.format(PASS)) else: print(RESULT_SPACE.format(FAIL)) print('HALT') d._connection.reset_input_buffer() # drop the HALT line LOW, and make sure there is an error state d._smoothie_hard_halt() old_timeout = int(d._connection.timeout) d._connection.timeout = 1 # 1 second r = d._connection.readline().decode() if 'ALARM' in r: print(RESULT_SPACE.format(PASS)) else: print(RESULT_SPACE.format(FAIL)) d._reset_from_error() d._connection.timeout = old_timeout print('ISP') # drop the ISP line to LOW, and make sure it is dead d._smoothie_programming_mode() try: # NOQA _write_and_return('M999') # NOQA print(RESULT_SPACE.format(FAIL)) # NOQA except Exception: # NOQA print(RESULT_SPACE.format(PASS)) # NOQA print('RESET') # toggle the RESET line to LOW, and make sure it is NOT dead d._smoothie_reset() r = _write_and_return('M119') if 'X_max' in r: print(RESULT_SPACE.format(PASS)) else: print(RESULT_SPACE.format(FAIL))
def execute(protocol_file: TextIO, propagate_logs: bool = False, log_level: str = 'warning', emit_runlog: Callable[[Dict[str, Any]], None] = None): """ Run the protocol itself. This is a one-stop function to run a protocol, whether python or json, no matter the api verson, from external (i.e. not bound up in other internal server infrastructure) sources. To run an opentrons protocol from other places, pass in a file like object as protocol_file; this function either returns (if the run has no problems) or raises an exception. To call from the command line use either the autogenerated entrypoint ``opentrons_execute`` or ``python -m opentrons.execute``. If the protocol is using Opentrons Protocol API V1, it does not need to explicitly call :py:meth:`.Robot.connect` or :py:meth:`.Robot.discover_modules`, or :py:meth:`.Robot.cache_instrument_models`. :param file-like protocol_file: The protocol file to execute :param propagate_logs: Whether this function should allow logs from the Opentrons stack to propagate up to the root handler. This can be useful if you're integrating this function in a larger application, but most logs that occur during protocol simulation are best associated with the actions in the protocol that cause them. Default: ``False`` :type propagate_logs: bool :param log_level: The level of logs to emit on the command line.. Default: 'warning' :type log_level: 'debug', 'info', 'warning', or 'error' :param emit_runlog: A callback for printing the runlog. If specified, this will be called whenever a command adds an entry to the runlog, which can be used for display and progress estimation. If specified, the callback should take a single argument (the name doesn't matter) which will be a dictionary (see below). Default: ``None`` The format of the runlog entries is as follows: .. code-block:: python { 'name': command_name, 'payload': { 'text': string_command_text, # The rest of this struct is command-dependent; see # opentrons.commands.commands. Its keys match format # keys in 'text', so that # entry['payload']['text'].format(**entry['payload']) # will produce a string with information filled in } } """ stack_logger = logging.getLogger('opentrons') stack_logger.propagate = propagate_logs stack_logger.setLevel(getattr(logging, log_level.upper(), logging.WARNING)) contents = protocol_file.read() protocol = parse(contents, protocol_file.name) if ff.use_protocol_api_v2(): context = get_protocol_api( bundled_labware=getattr(protocol, 'bundled_labware', None), bundled_data=getattr(protocol, 'bundled_data', None)) if emit_runlog: context.broker.subscribe(commands.command_types.COMMAND, emit_runlog) context.home() execute_apiv2.run_protocol(protocol, simulate=False, context=context) else: robot.connect() robot.cache_instrument_models() robot.discover_modules() robot.home() if emit_runlog: robot.broker.subscribe(commands.command_types.COMMAND, emit_runlog) if isinstance(protocol, JsonProtocol): legacy_api.protocols.execute_protocol(protocol) else: exec(protocol.contents, {})
def plate(session,engine): ot.print_center("============ Beginning to plate ============") # Take in command line arguments parser = argparse.ArgumentParser(description="Resuspend a plate of DNA on an Opentrons OT-1 robot.") parser.add_argument('-r', '--run', required=False, action="store_true", help="Send commands to the robot and print command output.") parser.add_argument('-m', '--manual', required=False, action="store_true", help="Maunal entry of parameters.") args = parser.parse_args() # Verify that the correct robot is being used if args.run: ot.check_robot() assemblies = [] print("Choose which plate you would like to plate:") for index,assembly in enumerate(session.query(Plate).join(Build,Plate.builds)\ .filter(Build.status == 'building').filter(Plate.transformed == 'transformed')\ .filter(Plate.plated != 'plated').order_by(Build.build_name)): print("{}. {}".format(index,assembly.builds.build_name)) assemblies.append(assembly) plate_num = ot.request_info("Enter plate here: ",type='int') target_plate = assemblies[plate_num] build_map = target_plate.wells if len(target_plate.wells) > 48: print("Too many samples to plate at once") portion = int(ot.request_info("Choose which half to plate, 1 or 2: ",type='int')) if portion == 1: build_map = target_plate.wells[:48] else: build_map = target_plate.wells[48:] num_reactions = len(build_map) else: portion = 1 num_reactions = len(build_map) num_rows = math.ceil(num_reactions / 8) print("num rows: ",num_rows) trans_per_plate = 3 num_plates = num_rows // trans_per_plate agar_plate_names = [] for plate_num in range(num_plates): if portion == 2: plate_num += 2 current_plate = target_plate.builds.build_name + "_p" + str(plate_num + 1) agar_plate_names.append(current_plate) print(agar_plate_names) print("You will need {} agar plates".format(len(agar_plate_names))) ## ============================================= ## SETUP THE OT-1 DECK ## ============================================= # Allocate slots for the required agar plates AGAR_SLOTS = ['D2','D3'] layout = list(zip(agar_plate_names,AGAR_SLOTS[:len(agar_plate_names)])) print(layout) # Specify the locations of each object on the deck locations = { "tiprack-200" : "A3", "tiprack-10_2" : "E3", "tiprack-10_3" : "E2", "tiprack-10_1" : "E1", "trash" : "D1", "PCR-strip-tall" : "C3", "Transformation" : "C2", "Tube_rack" : "B1" } locations.update(dict(layout)) ot.print_layout(locations) ## Initialize the OT-1 ## ============================================ # Determine whether to simulate or run the protocol if args.run: port = os.environ["ROBOT_DEV"] print("Connecting robot to port {}".format(port)) robot.connect(port) else: print("Simulating protcol run") robot.connect() # Start timer start = datetime.now() print("Starting run at: ",start) # Start up and declare components on the deck robot.home() p200_tipracks = [ containers.load('tiprack-200ul', locations['tiprack-200']), ] p10_tipracks = [ containers.load('tiprack-10ul', locations['tiprack-10_2']), containers.load('tiprack-10ul', locations['tiprack-10_3']), containers.load('tiprack-10ul', locations['tiprack-10_1']) ] p10s_tipracks = [ ] transformation_plate = containers.load('96-PCR-tall', locations['Transformation']) trash = containers.load('point', locations['trash'], 'holywastedplasticbatman') centrifuge_tube = containers.load('tube-rack-2ml',locations['Tube_rack']) master = containers.load('PCR-strip-tall', locations['PCR-strip-tall']) agar_plates = {} for plate, slot in layout: agar_plates[plate] = containers.load('96-deep-well', slot) print("agar_plates", agar_plates[plate]) print("agar_plates",agar_plates,"\n") p10,p10s,p200 = ot.initialize_pipettes(p10_tipracks,p10s_tipracks,p200_tipracks,trash) def agar_plating(pipette,row,volume,calibrate,z): ''' Dispenses the cells to be plated prior to reaching the agar and then stabs the tips slightly into the agar such that the droplets that pull up on the side of the tips make contact with the agar ''' pipette.dispense(volume-1,row.top()) pipette.dispense(1,row.bottom()) if calibrate: calibrate,z = ot.change_height(p10,agar_plates[plate],agar_plates[plate].rows(plating_row)[0],recalibrate=True) return calibrate,z num_dilutions = 4 plate_vol = 7.5 dilution_vol = 9 waste_vol = 2.5 plating_row = 0 calibrate = True z = 0 media_per_tube = 150 plate = agar_plate_names[0] plate_counter = 0 # Aliquot the LB into the PCR tube strip for the dilutions p200.pick_up_tip() for well in range(8): print("Transferring {}ul to tube {}".format(media_per_tube,well)) p200.transfer(media_per_tube, centrifuge_tube['A1'].bottom(),master.wells(well).bottom(),new_tip='never') p200.drop_tip() #input("Start the other run") # Iterate through each row of the transformation plate for trans_row in range(num_rows): # Iterates through each dilution for dilution in range(num_dilutions): # Resets to switch to the next plate if plating_row == 12: p200.pick_up_tip() for well in range(8): print("Transferring {}ul to tube {}".format(media_per_tube,well)) p200.transfer(media_per_tube, centrifuge_tube['B1'].bottom(),master.wells(well).bottom(),new_tip='never') p200.drop_tip() plate = agar_plate_names[1] print("changing to :", plate) plating_row = 0 calibrate = True print("trans_row",trans_row, "dilution",dilution,"plate",plate,"plate row",plating_row) p10.pick_up_tip() print("Diluting cells in row {} with {}ul".format(trans_row, dilution_vol)) p10.transfer(dilution_vol, master['A1'].bottom(), transformation_plate.rows(trans_row).bottom(),new_tip='never',mix_before=(1,9)) print("Plating {}ul from transformation row {} onto {} in row {}".format(plate_vol,trans_row,plate,plating_row)) p10.aspirate(plate_vol,transformation_plate.rows(trans_row).bottom()) calibrate,z = agar_plating(p10,agar_plates[plate].rows(plating_row),plate_vol,calibrate,z) print("Discard {}ul from transformation row {} into waste tube".format(waste_vol,trans_row)) p10.aspirate(waste_vol,transformation_plate.rows(trans_row).bottom()) p10.drop_tip() plating_row += 1 stop = datetime.now() print(stop) runtime = stop - start print("Total runtime is: ", runtime) print("Rehoming") robot.home() commit = ot.request_info("Commit changes? (y/n): ",type='string',select_from=['y','n']) if commit == 'y': if len(target_plate.wells) <= 48: target_plate.plated = 'plated' else: ans = ot.request_info('Plated both halves of the build? (y/n): ',type='string',select_from=['y','n']) if ans == 'y': target_plate.plated = 'plated' session.commit() return
def pick_colonies(): parser = argparse.ArgumentParser( description="Resuspend a plate of DNA on an Opentrons OT-1 robot.") parser.add_argument( '-r', '--run', required=False, action="store_true", help="Send commands to the robot and print command output.") parser.add_argument( '-i', '--inoculate', required=False, action="store_true", help="Picks colonies and inoculates a deep well plate.") parser.add_argument('-c', '--check', required=False, action="store_true", help="Allows the user to choose the colonies.") args = parser.parse_args() if args.run: port = os.environ["ROBOT_DEV"] print("Connecting robot to port {}".format(port)) robot.connect(port) else: print("Simulating protcol run") robot.connect() robot.home() p200_tipracks = [] p10_tip_racks = [] p10s_tipracks = [ containers.load('tiprack-10ul', 'E1'), containers.load('tiprack-10ul', 'E2') ] trash = containers.load('point', 'D1', 'holywastedplasticbatman') deep_well = containers.load('96-deep-well', 'C2') trans_plate = containers.load('point', 'B2') p10, p10s, p200 = ot.initialize_pipettes(p10_tipracks, p10s_tipracks, p200_tipracks, trash) assemblies = [] print("Choose which build you would like to pick from:") for index, assembly in enumerate( session.query(Plate).join(Build, Plate.builds).filter( Plate.plated == 'not_plated').order_by(Build.build_name)): print("{}. {}".format(index, assembly.builds.build_name)) assemblies.append(assembly) plate_num = int(input("Enter plate here: ")) target_plate = assemblies[plate_num] build_name = target_plate.builds.build_name path = '{}/builds/{}/{}_trans_pics'.format(BASE_PATH, build_name, build_name) for file in sorted(glob.glob('{}/*.jpg'.format(path)), reverse=True): print("Current image: ", file) skip = input('Skip? (y/n): ') if skip == 'y': continue print("Inoculate: ", args.inoculate) input() centers, agar, x_dim, y_dim, missing = find_colony_coordinates( file, args.check) coords = ot_coords(centers, agar, x_dim, y_dim) run_ot(p10s, trans_plate, deep_well, agar, coords, centers, args.inoculate) print('The following wells were skipped:\n', missing) print("Complete") robot.home() cv2.destroyAllWindows()
ZSPEED = 125 DISPENSERATE = 100 P300_ASPIRATERATE = 150 P50_ASPIRATE = 25 P50_DISPENSERATE = 100 P300_DISPENSERATE = 600 TOUCH_RADIUS = 0.85 TOUCH_SPEED = 20.0 # slowest it can go BOTTOM_OFFSET_ASPIRATE = 3 # mm TOP_OFFSET_DISPENSE = -10 # mm PAUSE_BLOWOUT = 1 # seconds """ ------------------------------------------ """ from opentrons import labware, instruments, robot, containers """ # uncomment for working in jupyter robot.connect() robot.home() robot.head_speed(x=XSPEED, y=YSPEED, z=ZSPEED) """ # sets up labware and the layout of the experiment m300rack_1 = containers.load('tiprack-200ul', '10', share='True') m300rack_2 = containers.load('tiprack-200ul', '11', share='True') stock_wells = [] slot_plate_wells = ['4', '5'] for slot in slot_plate_wells: stock_wells.append(containers.load('plate_6_well', slot, share='True')) stock_wells.append(containers.load('96-flat', '6', share='True'))
def _run(self): def on_command(message): if message['$'] == 'before': self.log_append() if message['name'] == command_types.PAUSE: self.set_state('paused') if message['name'] == command_types.RESUME: self.set_state('running') self._reset() _unsubscribe = self._broker.subscribe(command_types.COMMAND, on_command) self.startTime = now() self.set_state('running') try: if self._use_v2: self.resume() self._pre_run_hooks() self._hardware.cache_instruments() ctx = ProtocolContext.build_using(self._protocol, loop=self._loop, broker=self._broker, extra_labware=getattr( self._protocol, 'extra_labware', {})) ctx.connect(self._hardware) ctx.home() run_protocol(self._protocol, context=ctx) else: robot.broker = self._broker assert isinstance(self._protocol, PythonProtocol),\ 'Internal error: v1 should only be used for python' if not robot.is_connected(): robot.connect() self.resume() self._pre_run_hooks() robot.cache_instrument_models() robot.discover_modules() exec(self._protocol.contents, {}) # If the last command in a protocol was a pause, the protocol # will immediately finish executing because there's no smoothie # command to block... except the home that's about to happen, # which will confuse the app and lock it up. So we need to # do our own pause here, and sleep the thread until/unless the # app resumes us. # # Cancelling from the app during this pause will result in the # smoothie giving us an error during the subsequent home, which # is tragic but expected. while self.state == 'paused': sleep(0.1) self.set_state('finished') self._hw_iface().home() except SmoothieAlarm: log.info("Protocol cancelled") except Exception as e: log.exception("Exception during run:") self.error_append(e) self.set_state('error') raise e finally: _unsubscribe()
max_volume=10, min_volume=0.5, tip_racks=p10s_tipracks, trash_container=trash, channels=1, name='p10-8s') p10 = instruments.Pipette(axis='a', max_volume=10, min_volume=0.5, tip_racks=p10_tipracks, trash_container=trash, channels=8, name='p10-8') p200 = instruments.Pipette(axis='b', max_volume=200, min_volume=20, tip_racks=p200_tipracks, trash_container=trash, channels=1, name='p200-1') # Go higher between wells robot.arc_height = 20 print("Connecting to robot {}".format(robot_dev)) robot.connect(robot_dev) IPython.embed()
def initall(): robot.connect(robot.get_serial_ports_list()[0]) robot.is_connected() robot.home()
def connect(): #robot.connect() robot.connect(robotUSB) #robot2.connect() robot2.connect(robot2USB)
from opentrons import robot, containers, instruments import argparse import sys import json import os import glob import re import getch import IPython port = os.environ["ROBOT_DEV"] robot.connect(port) p10_tiprack = containers.load('tiprack-10ul', "E2") trash = containers.load('point', 'D1', 'holywastedplasticbatman') uncalibrated = containers.load('96-deep-well', 'B2', 'uncalibrated') calibrated = containers.load('point', 'D2', 'calibrated') p10 = instruments.Pipette(axis='a', max_volume=10, min_volume=0.5, tip_racks=p10_tiprack, trash_container=trash, channels=8, name='p10-8') def change_height(container):
def _simulate(self): self._reset() stack = [] res = [] commands = [] self._containers.clear() self._instruments.clear() self._modules.clear() self._interactions.clear() def on_command(message): payload = message['payload'] description = payload.get('text', '').format(**payload) if message['$'] == 'before': level = len(stack) stack.append(message) commands.append(payload) res.append({ 'level': level, 'description': description, 'id': len(res) }) else: stack.pop() unsubscribe = self._broker.subscribe(command_types.COMMAND, on_command) old_robot_connect = robot.connect try: # ensure actual pipettes are cached before driver is disconnected self._hardware.cache_instruments() if self._use_v2: instrs = {} for mount, pip in self._hardware.attached_instruments.items(): if pip: instrs[mount] = { 'model': pip['model'], 'id': pip.get('pipette_id', '') } sim = adapters.SynchronousAdapter.build( API.build_hardware_simulator, instrs, [mod.name() for mod in self._hardware.attached_modules], strict_attached_instruments=False) sim.home() self._simulating_ctx = ProtocolContext.build_using( self._protocol, loop=self._loop, hardware=sim, broker=self._broker, extra_labware=getattr(self._protocol, 'extra_labware', {})) run_protocol(self._protocol, context=self._simulating_ctx) else: robot.broker = self._broker # we don't rely on being connected anymore so make sure we are robot.connect() robot.cache_instrument_models() robot.disconnect() def robot_connect_error(port=None, options=None): raise RuntimeError( 'Protocols executed through the Opentrons App may not ' 'use robot.connect(). Allowing this call would cause ' 'the robot to execute commands during simulation, and ' 'then raise an error on execution.') robot.connect = robot_connect_error exec(self._protocol.contents, {}) finally: # physically attached pipettes are re-cached during robot.connect() # which is important, because during a simulation, the robot could # think that it holds a pipette model that it actually does not if not self._use_v2: robot.connect = old_robot_connect robot.connect() unsubscribe() instruments, containers, modules, interactions = _accumulate( [_get_labware(command) for command in commands]) self._containers.extend(_dedupe(containers)) self._instruments.extend( _dedupe( instruments + list(self._simulating_ctx.loaded_instruments.values()))) self._modules.extend( _dedupe(modules + [ m._geometry for m in self._simulating_ctx.loaded_modules.values() ])) self._interactions.extend(_dedupe(interactions)) # Labware calibration happens after simulation and before run, so # we have to clear the tips if they are left on after simulation # to ensure that the instruments are in the expected state at the # beginning of the labware calibration flow if not self._use_v2: robot.clear_tips() return res
with open(path + labware_name + '/1.json', 'w') as myfile: myfile.write(new_json) myfile.close() #try: # offset = pickle.load(open("ax_offset.pickle", "rb")) #except (OSError, IOError) as e: # offset = [0,0,0] # pickle.dump(offset, open("ax_offset.pickle", "wb")) offset = update_offset("ax6_5",True) print(offset) robot.connect() robot.home() #Protocol pipette_300.pick_up_tip(tiprack.wells(piwells[int(usetip())])) print(usetip(1)) if cal_offset == 1: pipette_300.move_to(ax_6.wells("A1").top(10)) print("with offset") else: pipette_300.move_to(ax_6.wells("A1").top()) while True: mov_dir = input("Select movement direction and step size: ") mov_dir = mov_dir.split() calibrate_end = bool(int(mov_dir[2])) if calibrate_end == True:
from opentrons import robot, containers, instruments import opentrons import curses import time from curses import wrapper from equipment import getEquipment movementamounts= {1:0.1, 2:0.5, 3:1, 4:5, 5:10,6:20,7:40,8:80} equipment=getEquipment() robot.connect(robot.get_serial_ports_list()[0]) if not robot.is_connected(): raise Exception('Did not connect') input("Robot will now home, press enter to continue.") robot.home() placeables = {} pipettes = {} for key, value in equipment.items(): if hasattr(value, 'axis'): pipettes[key]=value else: placeables[key]=value placeableNames=sorted(list(placeables.keys())) pipetteNames=sorted(list(pipettes.keys())) def main(stdscr):
def test_smoothie_gpio(port_name=''): def _write_and_return(msg): return serial_communication.write_and_return(msg + '\r\n', 'ok\r\n', robot._driver._connection, timeout=1) print('CONNECT') if port_name: robot.connect(port_name) else: robot.connect() d = robot._driver # make sure the driver is currently working as expected version_response = _write_and_return('version') if 'version' in version_response: print(RESULT_SPACE.format(PASS)) else: print(RESULT_SPACE.format(FAIL)) print('DATA LOSS') [_write_and_return('version') for i in range(10)] # check that if we write the same thing to the smoothie a bunch # it works data = [_write_and_return('version') for i in range(100)] true_uniques = _get_unique_smoothie_responses(data) if len(true_uniques) == 1: print(RESULT_SPACE.format(PASS)) else: log.info(f'true uniques: {true_uniques}') print(RESULT_SPACE.format(FAIL)) print('HALT') d._connection.reset_input_buffer() # drop the HALT line LOW, and make sure there is an error state d.hard_halt() old_timeout = int(d._connection.timeout) d._connection.timeout = 1 # 1 second r = d._connection.readline().decode() if 'ALARM' in r: print(RESULT_SPACE.format(PASS)) else: print(RESULT_SPACE.format(FAIL)) d._reset_from_error() d._connection.timeout = old_timeout print('ISP') # drop the ISP line to LOW, and make sure it is dead d._smoothie_programming_mode() try: # NOQA _write_and_return('M999') # NOQA print(RESULT_SPACE.format(FAIL)) # NOQA except Exception: # NOQA print(RESULT_SPACE.format(PASS)) # NOQA print('RESET') # toggle the RESET line to LOW, and make sure it is NOT dead d._smoothie_reset() r = _write_and_return('M119') if 'X_max' in r: print(RESULT_SPACE.format(PASS)) else: print(RESULT_SPACE.format(FAIL))