code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# options is an Any because the type annotation for EAP_CONFIG_SHAPE itself # can’t quite express the type properly because of the inference from the # dict annotation. arg_names = [k for k in config.keys() if k != 'eapType'] valid_names = [o['name'] for o in options] for an in arg_names: ...
def _eap_check_no_extra_args( config: Dict[str, Any], options: Any)
Check for args that are not required for this method (to aid debugging) ``config`` should be the user config. ``options`` should be the options submember for the eap method. Before this method is called, the validity of the 'eapType' key should be established.
7.921579
7.755432
1.021423
if opt['name'] not in config: if opt['required']: raise ConfigureArgsError( 'Required argument {} for eap method {} not present' .format(opt['displayName'], config['eapType'])) else: return name = opt['name'] o_type = opt['type'] ...
def _eap_check_option_ok(opt: Dict[str, str], config: Dict[str, Any])
Check that a given EAP option is in the user config (if required) and, if specified, is the right type. ``opt`` should be an options dict from EAP_CONFIG_SHAPE. ``config`` should be the user config dict. Before this method is called, the validity of the eapType key should be established.
3.202196
3.214015
0.996323
eap_type = eap_config.get('eapType') for method in EAP_CONFIG_SHAPE['options']: if method['name'] == eap_type: options = method['options'] break else: raise ConfigureArgsError('EAP method {} is not valid'.format(eap_type)) _eap_check_no_extra_args(eap_config...
def _eap_check_config(eap_config: Dict[str, Any]) -> Dict[str, Any]
Check the eap specific args, and replace values where needed. Similar to _check_configure_args but for only EAP.
5.264604
5.08429
1.035465
# Security should be one of our valid strings sec_translation = { 'wpa-psk': nmcli.SECURITY_TYPES.WPA_PSK, 'none': nmcli.SECURITY_TYPES.NONE, 'wpa-eap': nmcli.SECURITY_TYPES.WPA_EAP, } if not kwargs.get('securityType'): if kwargs.get('psk') and kwargs.get('eapConfig'...
def _deduce_security(kwargs) -> nmcli.SECURITY_TYPES
Make sure that the security_type is known, or throw.
2.508989
2.453795
1.022493
# SSID must always be present if not configure_args.get('ssid')\ or not isinstance(configure_args['ssid'], str): raise ConfigureArgsError("SSID must be specified") # If specified, hidden must be a bool if not configure_args.get('hidden'): configure_args['hidden'] = False ...
def _check_configure_args(configure_args: Dict[str, Any]) -> Dict[str, Any]
Check the arguments passed to configure. Raises an exception on failure. On success, returns a dict of configure_args with any necessary mutations.
2.8
2.856503
0.98022
try: body = await request.json() except json.JSONDecodeError as e: log.debug("Error: JSONDecodeError in /wifi/configure: {}".format(e)) return web.json_response({'message': e.msg}, status=400) try: configure_kwargs = _check_configure_args(body) except ConfigureArgsE...
async def configure(request: web.Request) -> web.Response
Post request should include a json body specifying config information (see below). Robot will attempt to connect to this network and respond with Ok if successful or an error code if not. Fields in the body are: ssid: str Required. The SSID to connect to. securityType: str Optional. one of 'none', ...
2.882984
2.792375
1.032448
connectivity = {'status': 'none', 'interfaces': {}} try: connectivity['status'] = await nmcli.is_connected() connectivity['interfaces'] = { i.value: await nmcli.iface_info(i) for i in nmcli.NETWORK_IFACES } log.debug("Connectivity: {}".format(connectivity['status...
async def status(request: web.Request) -> web.Response
Get request will return the status of the machine's connection to the internet as well as the status of its network interfaces. The body of the response is a json dict containing 'status': internet connectivity status, where the options are: "none" - no connection to router or network "portal"...
2.828723
2.697054
1.04882
keys_dir = CONFIG['wifi_keys_dir'] if not request.can_read_body: return web.json_response({'message': "Must upload key file"}, status=400) data = await request.post() keyfile = data.get('key') if not keyfile: return web.json_response( ...
async def add_key(request: web.Request) -> web.Response
Add a key file (for later use in EAP config) to the system. ``` POST /wifi/keys Content-Type: multipart/form-data, Body: file field named 'key' ``` returns ``` 201 Created { uri: '/wifi/keys/some-hex-digest', id: 'some-hex-digest', name: 'keyfile.pem' } ``...
2.097426
1.827567
1.14766
keys_dir = CONFIG['wifi_keys_dir'] keys: List[Dict[str, str]] = [] # TODO(mc, 2018-10-24): add last modified info to keys for sort purposes for path in os.listdir(keys_dir): full_path = os.path.join(keys_dir, path) if os.path.isdir(full_path): in_path = os.listdir(full_p...
async def list_keys(request: web.Request) -> web.Response
List the key files installed in the system. This responds with a list of the same objects as key: ``` GET /wifi/keys -> 200 OK { keys: [ { uri: '/wifi/keys/some-hex-digest', id: 'some-hex-digest', name: 'keyfile.pem' }, ... ] } ``...
3.147454
2.842992
1.107092
keys_dir = CONFIG['wifi_keys_dir'] available_keys = os.listdir(keys_dir) requested_hash = request.match_info['key_uuid'] if requested_hash not in available_keys: return web.json_response( {'message': 'No such key file {}' .format(requested_hash)}, status...
async def remove_key(request: web.Request) -> web.Response
Remove a key. ``` DELETE /wifi/keys/:id -> 200 OK {message: 'Removed key keyfile.pem'} ```
2.784093
2.563816
1.085918
return web.json_response(EAP_CONFIG_SHAPE, status=200)
async def eap_options(request: web.Request) -> web.Response
Get request returns the available configuration options for WPA-EAP. Because the options for connecting to WPA-EAP secured networks are quite complex, to avoid duplicating logic this endpoint returns a json object describing the structure of arguments and options for the eap_config arg to /wifi/configu...
8.536867
8.225211
1.03789
publish_command = functools.partial( broker.publish, topic=command_types.COMMAND) call_args = _get_args(f, args, kwargs) if when == 'before': broker.logger.info("{}: {}".format( f.__qualname__, {k: v for k, v in call_args.items() if str(k) != 'self'})) ...
def do_publish(broker, cmd, f, when, res, meta, *args, **kwargs)
Implement the publish so it can be called outside the decorator
4.638312
4.626839
1.00248
if not ff.use_protocol_api_v2(): p = hardware._driver.position return (p['X'], p['Y'], p[axis]) else: p = hardware.gantry_position(axis, critical_point=cp) return (p.x, p.y, p.z)
def position(axis, hardware, cp=None)
Read position from driver into a tuple and map 3-rd value to the axis of a pipette currently used
7.018977
5.27563
1.330453
machine_id = open('/etc/machine-id').read().strip() hostname = machine_id[:6] with open('/etc/hostname', 'w') as ehn: ehn.write(f'{hostname}\n') # First, we run hostnamed which will set the transient hostname # and loaded static hostname from the value we just wrote to # /etc/hostn...
async def setup_hostname() -> str
Intended to be run when the server starts. Sets the machine hostname. The machine hostname is set from the systemd-generated machine-id, which changes at every boot. Once the hostname is set, we restart avahi. This is a separate task from establishing and changing the opentrons machine name, whic...
2.754122
2.620592
1.050954
try: with open('/etc/machine-info') as emi: contents = emi.read() except OSError: LOG.exception("Couldn't read /etc/machine-info") contents = '' new_contents = '' for line in contents.split('\n'): if not line.startswith('PRETTY_HOSTNAME'): new...
def _update_pretty_hostname(new_val: str)
Write a new value for the pretty hostname. :raises OSError: If the new value could not be written.
2.387099
2.345696
1.017651
try: with open('/etc/machine-info') as emi: contents = emi.read() except OSError: LOG.exception( "Couldn't read /etc/machine-info") contents = '' for line in contents.split('\n'): if line.startswith('PRETTY_HOSTNAME='): return '='.join...
def get_name(default: str = 'no name set')
Get the currently-configured name of the machine
3.998425
3.735715
1.070324
if name: checked_name = name try: _update_pretty_hostname(checked_name) except OSError: LOG.exception("Could not set pretty hostname") checked_name = get_name() else: checked_name = get_name() async with _BUS_LOCK: await asyn...
async def set_name(name: str = None) -> str
Change the name by writing /etc/machine-info and then calling setup_name :param name: The name to set. If ``None``, read it from /etc/machine-info :returns: The name that was set. This may be different from ``name``, if ``name`` was none or if the pretty hostname could not be written
4.478209
3.639654
1.230394
def build_400(msg: str) -> web.Response: return web.json_response( data={'message': msg}, status=400) body = await request.json() if 'name' not in body or not isinstance(body['name'], str): return build_400('Body has no "name" key with a string') new_name ...
async def set_name_endpoint(request: web.Request) -> web.Response
Set the name of the robot. Request with POST /server/name {"name": new_name} Responds with 200 OK {"hostname": new_name, "prettyname": pretty_name} or 400 Bad Request In general, the new pretty name will be the specified name. The true hostname will be capped to 53 letters, and have any characters...
3.130803
3.189937
0.981462
return web.json_response( data={'name': request.app[DEVICE_NAME_VARNAME]}, status=200)
async def get_name_endpoint(request: web.Request) -> web.Response
Get the name of the robot. This information is also accessible in /server/update/health, but this endpoint provides symmetry with POST /server/name. GET /server/name -> 200 OK, {'name': robot name}
6.677651
7.888437
0.846511
def is_special_file(name): return name.startswith('.') res = [] top = infer_config_base_dir()/'containers' for root, dirnames, files in os.walk(top): for name in filter(is_special_file, dirnames): dirnames.remove(name) res.extend( [ ...
def get_custom_container_files()
Traverses environment.get_path('CONTAINERS_DIR') to retrieve all .json files
3.71085
3.442375
1.077991
return self._replace(point=self.point + point)
def move(self, point: Point) -> 'Location'
Alter the point stored in the location while preserving the labware. This returns a new Location and does not alter the current one. It should be used like .. code-block:: python >>> loc = Location(Point(1, 1, 1), 'Hi') >>> new_loc = loc.move(Point(1, 1, 1)) ...
7.836872
16.680805
0.469814
# First must populate "get persisted container" list old_container_loading.load_all_containers_from_disk() # Load container from old json file container = old_container_loading.get_persisted_container( container_name) # Rotate coordinates to fit the new deck map rotated_container = ...
def _load_weird_container(container_name)
Load a container from persisted containers, whatever that is
9.544224
8.554712
1.115669
for meth in (database.load_container, load_new_labware, _load_weird_container): log.debug( f"Trying to load container {container_name} via {meth.__name__}") try: container = meth(container_name) if meth == _load_weird_contain...
def _setup_container(container_name)
Try and find a container in a variety of methods
3.66664
3.44972
1.06288
for instrument in self._instruments.values(): if instrument.tip_attached: instrument._remove_tip(instrument._tip_length)
def clear_tips(self)
If reset is called with a tip attached, the tip must be removed before the poses and _instruments members are cleared. If the tip is not removed, the effective length of the pipette remains increased by the length of the tip, and subsequent `_add_tip` calls will increase the length in ad...
8.957178
3.758189
2.383376
self._actuators = { 'left': { 'carriage': Mover( driver=self._driver, src=pose_tracker.ROOT, dst=id(self.config.gantry_calibration), axis_mapping={'z': 'Z'}), 'plunger': Mover( ...
def reset(self)
Resets the state of the robot and clears: * Deck * Instruments * Command queue * Runtime warnings Examples -------- >>> from opentrons import robot # doctest: +SKIP >>> robot.reset() # doctest: +SKIP
4.287099
3.824392
1.120988
log.debug("Updating instrument model cache") for mount in self.model_by_mount.keys(): model_value = self._driver.read_pipette_model(mount) if model_value: id_response = self._driver.read_pipette_id(mount) else: id_response = No...
def cache_instrument_models(self)
Queries Smoothie for the model and ID strings of attached pipettes, and saves them so they can be reported without querying Smoothie again (as this could interrupt a command if done during a run or other movement). Shape of return dict should be: ``` { "left": { ...
2.915355
2.660752
1.095688
from time import sleep for i in range(seconds): self.turn_off_button_light() sleep(0.25) self.turn_on_button_light() sleep(0.25)
def identify(self, seconds)
Identify a robot by flashing the light around the frame button for 10s
3.017497
2.525688
1.194723
if mount in self._instruments: prev_instr = self._instruments[mount] raise RuntimeError('Instrument {0} already on {1} mount'.format( prev_instr.name, mount)) self._instruments[mount] = instrument instrument.instrument_actuator = self._actuators[...
def add_instrument(self, mount, instrument)
Adds instrument to a robot. Parameters ---------- mount : str Specifies which axis the instruments is attached to. Valid options are "left" or "right". instrument : Instrument An instance of a :class:`Pipette` to attached to the axis. Notes ...
5.661366
5.656023
1.000945
self._driver.connect(port=port) self.fw_version = self._driver.get_fw_version() # the below call to `cache_instrument_models` is relied upon by # `Session._simulate()`, which calls `robot.connect()` after exec'ing a # protocol. That protocol could very well have differ...
def connect(self, port=None, options=None)
Connects the robot to a serial port. Parameters ---------- port : str OS-specific port name or ``'Virtual Smoothie'`` options : dict if :attr:`port` is set to ``'Virtual Smoothie'``, provide the list of options to be passed to :func:`get_virtual_devic...
13.971452
13.334653
1.047755
# Home gantry first to avoid colliding with labware # and to make sure tips are not in the liquid while # homing plungers. Z/A axis will automatically home before X/Y self.poses = self.gantry.home(self.poses) # Then plungers self.poses = self._actuators['left'][...
def home(self, *args, **kwargs)
Home robot's head and plunger motors.
11.838361
10.642547
1.112362
user_set_speeds = {'x': x, 'y': y, 'z': z, 'a': a, 'b': b, 'c': c} axis_max_speeds = { axis: value for axis, value in user_set_speeds.items() if value } if axis_max_speeds: self._driver.set_axis_max_speed(axis_max_speeds) i...
def head_speed( self, combined_speed=None, x=None, y=None, z=None, a=None, b=None, c=None)
Set the speeds (mm/sec) of the robot Parameters ---------- combined_speed : number specifying a combined-axes speed <axis> : key/value pair, specifying the maximum speed of that axis Examples --------- >>> from opentrons import robot # doctest: +SKIP >>...
2.358375
2.722455
0.866268
placeable, coordinates = containers.unpack_location(location) # because the top position is what is tracked, # this checks if coordinates doesn't equal top offset = subtract(coordinates, placeable.top()[1]) if isinstance(placeable, containers.WellSeries): ...
def move_to( self, location, instrument, strategy='arc', **kwargs)
Move an instrument to a coordinate, container or a coordinate within a container. Parameters ---------- location : one of the following: 1. :class:`Placeable` (i.e. Container, Deck, Slot, Well) — will move to the origin of a container. 2. :class:`Vect...
6.530605
6.139788
1.063653
this_container = None if isinstance(placeable, containers.Well): this_container = placeable.get_parent() elif isinstance(placeable, containers.WellSeries): this_container = placeable.get_parent() elif isinstance(placeable, containers.Container): ...
def _create_arc(self, inst, destination, placeable=None)
Returns a list of coordinates to arrive to the destination coordinate
5.86667
5.744967
1.021184
if self._driver: self._driver.disconnect() self.axis_homed = { 'x': False, 'y': False, 'z': False, 'a': False, 'b': False}
def disconnect(self)
Disconnects from the robot.
4.899914
4.347211
1.12714
SLOT_OFFSETS = { 'slots': { 'col_offset': 132.50, 'row_offset': 90.5 } } slot_settings = SLOT_OFFSETS.get(self.get_deck_slot_types()) row_offset = slot_settings.get('row_offset') col_offset = slot_settings.get('col_...
def get_slot_offsets(self)
col_offset - from bottom left corner of 1 to bottom corner of 2 row_offset - from bottom left corner of 1 to bottom corner of 4 TODO: figure out actual X and Y offsets (from origin)
3.75332
3.420136
1.097418
if name: return self.get_instruments_by_name(name) return sorted( self._instruments.items(), key=lambda s: s[0].lower())
def get_instruments(self, name=None)
:returns: sorted list of (mount, instrument)
3.816371
3.16982
1.203971
self.poses = pose_tracker.add( self.poses, container, container.parent, pose_tracker.Point(*container._coordinates)) for well in container: center_x, center_y, center_z = well.top()[1] offset_x, offset_y, offset_z = well._...
def add_container_to_pose_tracker(self, location, container: Container)
Add container and child wells to pose tracker. Sets container.parent (slot) as pose tracker parent
3.407886
3.007218
1.133235
left_data = { 'mount_axis': 'z', 'plunger_axis': 'b', 'model': self.model_by_mount['left']['model'], 'id': self.model_by_mount['left']['id'] } left_model = left_data.get('model') if left_model: tip_...
def get_attached_pipettes(self)
Gets model names of attached pipettes :return: :dict with keys 'left' and 'right' and a model string for each mount, or 'uncommissioned' if no model string available
2.034034
2.003226
1.015379
'''Calibrates a container using the bottom of the first well''' well = container[0] # Get the relative position of well with respect to instrument delta = pose_tracker.change_base( self.poses, src=instrument, dst=well ) if fflags.cali...
def calibrate_container_with_instrument(self, container: Container, instrument, save: bool )
Calibrates a container using the bottom of the first well
4.983897
4.432906
1.124296
offset = placeable.top()[1] placeable_coordinate = add( pose_tracker.absolute( self.poses, placeable ), offset.coordinates ) placeable_tallest_point = pose_tracker.max_z(self.poses, placeable) return pla...
def max_placeable_height_on_deck(self, placeable)
:param placeable: :return: Calibrated height of container in mm from deck as the reference point
7.936347
7.415477
1.070241
if None is not session_from_request(request): LOG.warning("begin: requested with active session") return web.json_response( data={'message': 'An update session is already active on this robot', 'error': 'session-already-active'}, statu...
async def begin(request: web.Request) -> web.Response
Begin a session
5.93031
5.548858
1.068744
session.set_progress(0) session.set_stage(Stages.WRITING) write_future = asyncio.ensure_future(loop.run_in_executor( None, file_actions.write_update, rootfs_file_path, session.set_progress)) def write_done(fut): exc = fut.exception() if exc: session.set_...
def _begin_write(session: UpdateSession, loop: asyncio.AbstractEventLoop, rootfs_file_path: str)
Start the write process.
3.362678
3.20299
1.049856
session.set_stage(Stages.VALIDATING) cert_path = config.update_cert_path\ if config.signature_required else None validation_future \ = asyncio.ensure_future(loop.run_in_executor( None, file_actions.validate_update, downloaded_update_path, session.set_progress, c...
def _begin_validation( session: UpdateSession, config: config.Config, loop: asyncio.AbstractEventLoop, downloaded_update_path: str)\ -> asyncio.futures.Future
Start the validation process.
4.049229
3.936823
1.028553
if session.stage != Stages.AWAITING_FILE: return web.json_response( data={'error': 'file-already-uploaded', 'message': 'A file has already been sent for this update'}, status=409) reader = await request.multipart() async for part in reader: if p...
async def file_upload( request: web.Request, session: UpdateSession) -> web.Response
Serves /update/:session/file Requires multipart (encoding doesn't matter) with a file field in the body called 'ot2-system.zip'.
4.798051
3.796495
1.263811
if session.stage != Stages.DONE: return web.json_response( data={'error': 'not-ready', 'message': f'System is not ready to commit the update ' f'(currently {session.stage.value.short})'}, status=409) async with request.app[RESTART_LOCK_NAM...
async def commit( request: web.Request, session: UpdateSession) -> web.Response
Serves /update/:session/commit
6.062352
5.673224
1.06859
files = super()._get_data_files() # We don’t really want to duplicate logic used in the original # implementation, but we can back out what it did with commonpath - # should be something ending in opentrons build_base = os.path.commonpath([f[2] for f in files]) #...
def _get_data_files(self)
Override of build_py.get_data_files that includes out of tree configs. These are currently hardcoded to include everything in ../shared-data/robot-data, which will move to opentrons/config/shared-data
10.58272
8.801869
1.202326
def subtrees(commands, level): if not commands: return acc = [] parent, *commands = commands for command in commands: if command['level'] > level: acc.append(command) else: yield (parent, acc) ...
def from_list(commands)
Given a list of tuples of form (depth, text) that represents a DFS traversal of a command tree, returns a dictionary representing command tree.
3.608291
3.561529
1.01313
''' Calibration involves probing for top plate to get the plate height ''' if self._driver and self._driver.is_connected(): self._driver.probe_plate() # return if successful or not? self._engaged = False
def calibrate(self)
Calibration involves probing for top plate to get the plate height
17.372906
7.938597
2.18841
''' Move the magnet to either: the default height for the labware loaded on magdeck [engage()] or a +/- 'offset' from the default height for the labware [engage(offset=2)] or a 'height' value specified as mm from magdeck home position [en...
def engage(self, **kwargs)
Move the magnet to either: the default height for the labware loaded on magdeck [engage()] or a +/- 'offset' from the default height for the labware [engage(offset=2)] or a 'height' value specified as mm from magdeck home position [engage(height=20)]
4.551301
2.281651
1.994741
''' Home the magnet ''' if self._driver and self._driver.is_connected(): self._driver.home() self._engaged = False
def disengage(self)
Home the magnet
9.159646
4.964547
1.845011
''' Connect to the serial port ''' if self._port: self._driver = MagDeckDriver() self._driver.connect(self._port) self._device_info = self._driver.get_device_info() else: # Sanity check: Should never happen, because connect should ...
def connect(self)
Connect to the serial port
7.161404
6.524937
1.097544
global containers global instruments global labware global robot global reset global modules global hardware robot, reset, instruments, containers, labware, modules, hardware\ = build_globals(version, loop)
def reset_globals(version=None, loop=None)
Reinitialize the global singletons with a given API version. :param version: 1 or 2. If `None`, pulled from the `useProtocolApiV2` advanced setting.
9.820485
12.024855
0.816682
tb_info = traceback.extract_tb(tb) for frame in reversed(tb_info): if frame.filename == proto_name: return frame else: raise KeyError
def _find_protocol_error(tb, proto_name)
Return the FrameInfo for the lowest frame in the traceback from the protocol.
3.683342
3.227815
1.141126
if not config.IS_ROBOT: simulate = True # noqa - will be used later if None is context and simulate: true_context = ProtocolContext() true_context.home() MODULE_LOG.info("Generating blank protocol context for simulate") elif context: true_context = context el...
def run_protocol(protocol_code: Any = None, protocol_json: Dict[Any, Any] = None, simulate: bool = False, context: ProtocolContext = None)
Create a ProtocolRunner instance from one of a variety of protocol sources. :param protocol_bytes: If the protocol is a Python protocol, pass the file contents here. :param protocol_json: If the protocol is a json file, pass the contents here. :param simulate: True to simulate; False to execute...
3.888852
3.944217
0.985963
'''Returns all serial devices with a given name''' filtered_devices = filter( lambda device: device_name in device[1], list_ports.comports() ) device_ports = [device[0] for device in filtered_devices] return device_ports
def get_ports_by_name(device_name)
Returns all serial devices with a given name
3.822108
3.299851
1.158267
'''Implements a temporary timeout for a serial connection''' saved_timeout = serial_connection.timeout if timeout is not None: serial_connection.timeout = timeout yield serial_connection serial_connection.timeout = saved_timeout
def serial_with_temp_timeout(serial_connection, timeout)
Implements a temporary timeout for a serial connection
3.48098
3.047688
1.142171
'''Writes to a serial device. - Formats command - Wait for ack return - return parsed response''' log.debug('Write -> {}'.format(cmd.encode())) device_connection.write(cmd.encode()) response = device_connection.read_until(ack.encode()) log.debug('Read <- {}'.format(response)) if ack....
def _write_to_device_and_return(cmd, ack, device_connection)
Writes to a serial device. - Formats command - Wait for ack return - return parsed response
4.459498
3.068242
1.453438
'''Recovery after following a failed write_and_return() atempt''' with serial_with_temp_timeout(serial_conn, RECOVERY_TIMEOUT) as device: response = _write_to_device_and_return(command, ack, device) if response is None: log.debug("No valid response during _attempt_command_recovery") ...
def _attempt_command_recovery(command, ack, serial_conn)
Recovery after following a failed write_and_return() atempt
7.361259
4.903881
1.501109
'''Write a command and return the response''' clear_buffer(serial_connection) with serial_with_temp_timeout( serial_connection, timeout) as device_connection: response = _write_to_device_and_return(command, ack, device_connection) return response
def write_and_return( command, ack, serial_connection, timeout=DEFAULT_WRITE_TIMEOUT)
Write a command and return the response
4.810381
4.943326
0.973106
''' Creates a serial connection :param device_name: defaults to 'Smoothieboard' :param baudrate: integer frequency for serial communication :return: serial.Serial connection ''' if not port: port = get_ports_by_name(device_name=device_name)[0] log.debug("Device name: {}, Port: {}...
def connect(device_name=None, port=None, baudrate=115200)
Creates a serial connection :param device_name: defaults to 'Smoothieboard' :param baudrate: integer frequency for serial communication :return: serial.Serial connection
4.749563
2.413433
1.96797
res = _get_adv_settings() return web.json_response(res)
async def get_advanced_settings(request: web.Request) -> web.Response
Handles a GET request and returns a json body with the key "settings" and a value that is a list of objects where each object has keys "id", "title", "description", and "value"
7.328305
6.236404
1.175085
data = await request.json() key = data.get('id') value = data.get('value') if key and key in advs.settings_by_id.keys(): advs.set_adv_setting(key, value) res = _get_adv_settings() status = 200 else: res = {'message': 'ID {} not found in settings list'.format(key)...
async def set_advanced_setting(request: web.Request) -> web.Response
Handles a POST request with a json body that has keys "id" and "value", where the value of "id" must correspond to an id field of a setting in `opentrons.config.advanced_settings.settings`. Saves the value of "value" for the setting that matches the supplied id.
2.893626
2.72084
1.063504
data = await request.json() ok, bad_key = _check_reset(data) if not ok: return web.json_response( {'message': '{} is not a valid reset option' .format(bad_key)}, status=400) log.info("Reset requested for {}".format(', '.join(data.keys()))) if data.ge...
async def reset(request: web.Request) -> web.Response
Execute a reset of the requested parts of the user configuration.
5.508247
5.229458
1.053311
return web.json_response({'options': _settings_reset_options}, status=200)
async def available_resets(request: web.Request) -> web.Response
Indicate what parts of the user configuration are available for reset.
11.020308
6.112723
1.802848
pipette_id = request.match_info['id'] whole_config = pc.load_config_dict(pipette_id) config_match = pc.list_mutable_configs(pipette_id) data = await request.json() if not data.get('fields'): return web.json_response(config_match, status=200) for key, value in data['fields'].items()...
async def modify_pipette_settings(request: web.Request) -> web.Response
Expects a dictionary with mutable configs wrapped in a `fields` key such as: { 'fields': { 'pickUpCurrent': {'value': some_value}, 'dropTipSpeed': {'value': some_value} } } If a value needs to be reset, simply type in the body formatted as above: 'configK...
3.393004
3.085217
1.099762
fields = ['ssid', 'signal', 'active', 'security'] cmd = ['--terse', '--fields', ','.join(fields), 'device', 'wifi', 'list'] out, err = await _call(cmd) if err: raise RuntimeError(err) output = _dict_from_terse_tabular( field...
async def available_ssids() -> List[Dict[str, Any]]
List the visible (broadcasting SSID) wireless networks. Returns a list of the SSIDs. They may contain spaces and should be escaped if later passed to a shell.
4.855534
5.057379
0.960089
fields = ['name', 'type', 'active'] res, _ = await _call(['-t', '-f', ','.join(fields), 'connection', 'show']) found = _dict_from_terse_tabular( fields, res, # ’ethernet’ or ’wireless’ from ’802-11-wireless’ or ’802-4-ethernet’ # and bools from ’yes’ or ’no trans...
async def connections( for_type: Optional[CONNECTION_TYPES] = None) -> List[Dict[str, str]]
Return the list of configured connections. This is all connections that nmcli knows about and manages. Each connection is a dict containing some basic information - the information retrievable from nmcli connection show. Further information should be queried on a connection by connection basis. If...
4.706908
4.502687
1.045355
nmcli_conns = await connections() for wifi in [c['name'] for c in nmcli_conns if c['type'] == 'wireless']: res, _ = await _call(['-t', '-f', '802-11-wireless.ssid', '-m', 'tabular', 'connection', 'show', wifi]) if ...
async def connection_exists(ssid: str) -> Optional[str]
If there is already a connection for this ssid, return the name of the connection; if there is not, return None.
7.18696
7.42501
0.96794
existing_cons = await connections(for_type=con_type) not_us = [c['name'] for c in existing_cons if c['name'] != new_name] ok = True res = [] for c in not_us: this_ok, remove_res = await remove(name=c) ok = ok and this_ok if not this_ok: # This is not a failur...
async def _trim_old_connections( new_name: str, con_type: CONNECTION_TYPES) -> Tuple[bool, str]
Delete all connections of con_type but the one specified.
4.604868
4.602792
1.000451
args = ['wifi-sec.key-mgmt', 'wpa-eap'] eap_type = EAP_TYPES.by_qualified_name(eap_args['eapType']) type_args = eap_type.args() args += ['802-1x.eap', eap_type.outer.value.name] if eap_type.inner: args += ['802-1x.phase2-autheap', eap_type.inner.value.name] for ta in type_args: ...
def _add_eap_args(eap_args: Dict[str, str]) -> List[str]
Add configuration options suitable for an nmcli con add command for WPA-EAP configuration. These options are mostly in the 802-1x group. The eap_args dict should be a flat structure of arguments. They must contain at least 'eapType', specifying the EAP type to use (the qualified_name() of one of th...
5.159064
4.68848
1.10037
configure_cmd = ['connection', 'add', 'save', 'yes', 'autoconnect', 'yes', 'ifname', 'wlan0', 'type', 'wifi', 'con-name', ssid, 'wifi.ssid', ssid] if hidden: configure_cmd +...
def _build_con_add_cmd(ssid: str, security_type: SECURITY_TYPES, psk: Optional[str], hidden: bool, eap_args: Optional[Dict[str, Any]]) -> List[str]
Build the nmcli connection add command to configure the new network. The parameters are the same as configure but without the defaults; this should be called only by configure.
2.229436
2.19824
1.014192
already = await connection_exists(ssid) if already: # TODO(seth, 8/29/2018): We may need to do connection modifies # here for EAP configuration if e.g. we’re passing a keyfile in a # different http request _1, _2 = await _call(['connection', 'delete', already]) configur...
async def configure(ssid: str, securityType: SECURITY_TYPES, psk: Optional[str] = None, hidden: bool = False, eapConfig: Optional[Dict[str, Any]] = None, upRetries: int = 2) -> Tuple[bool, str]
Configure a connection but do not bring it up (though it is configured for autoconnect). Returns (success, message) where ``success`` is a ``bool`` and ``message`` is a ``str``. Only anticipated failures are treated that way - for instance, an ssid that doesn't exist will get a False and a message...
6.81076
7.057179
0.965082
if None is not ssid: name = await connection_exists(ssid) if None is not name: res, err = await _call(['connection', 'delete', name]) if 'successfully deleted' in res: return True, res else: return False, err else: return False, 'No connec...
async def remove(ssid: str = None, name: str = None) -> Tuple[bool, str]
Remove a network. Depending on what is known, specify either ssid (in which case this function will call ``connection_exists`` to get the nmcli connection name) or the nmcli connection name directly. Returns (True, msg) if the connection was deleted, (False, msg) otherwise.
4.378304
4.569663
0.958124
# example device info lines # GENERAL.HWADDR:B8:27:EB:24:D1:D0 # IP4.ADDRESS[1]:10.10.2.221/22 # capture the field name (without the number in brackets) and the value # using regex instead of split because there may be ":" in the value _DEV_INFO_LINE_RE = re.compile(r'([\w.]+)(?:\[\d+])?:...
async def iface_info(which_iface: NETWORK_IFACES) -> Dict[str, Optional[str]]
Get the basic network configuration of an interface. Returns a dict containing the info: { 'ipAddress': 'xx.xx.xx.xx/yy' (ip4 addr with subnet as CIDR) or None 'macAddress': 'aa:bb:cc:dd:ee:ff' or None 'gatewayAddress: 'zz.zz.zz.zz' or None } which_iface should be a string in IFACE_N...
4.998011
5.0388
0.991905
to_exec = [quote(c) for c in ['nmcli'] + cmd] cmd_str = ' '.join(to_exec) # We have to use a shell invocation here because nmcli will not accept # secrets specified on the command line unless it’s in a shell. The other # option is editing the connection configuration file in /etc/ afterwards ...
async def _call(cmd: List[str]) -> Tuple[str, str]
Runs the command in a subprocess and returns the captured stdout output. :param cmd: a list of arguments to nmcli. Should not include nmcli itself. :return: (stdout, stderr)
4.786394
4.756155
1.006358
sanitized = [] for idx, fieldname in enumerate(cmd): def _is_password(cmdstr): return 'wifi-sec.psk' in cmdstr\ or 'password' in cmdstr.lower() if idx > 0 and _is_password(cmd[idx-1]): sanitized.append('****') else: sanitized.appen...
def sanitize_args(cmd: List[str]) -> List[str]
Filter the command so that it no longer contains passwords
5.131022
4.668958
1.098965
res = [] for n in names: if n not in transformers: transformers[n] = lambda s: s for line in inp.split('\n'): if len(line) < 3: continue fields = line.split(':') res.append(dict([ (elem[0], transformers[elem[0]](elem[1])) f...
def _dict_from_terse_tabular( names: List[str], inp: str, transformers: Dict[str, Callable[[str], Any]] = {})\ -> List[Dict[str, Any]]
Parse NMCLI terse tabular output into a list of Python dict. ``names`` is a list of strings of field names to apply to the input data, which is assumed to be colon separated. ``inp`` is the input as a string (i.e. already decode()d) from nmcli ``transformers`` is a dict mapping field names to callabl...
2.575284
2.682289
0.960107
return inst.Pipette(self.robot, *args, **kwargs)
def Pipette(self, *args, **kwargs)
Deprecated -- do not use this constructor directly. Use the model- specific constructors available in this module.
8.288961
9.058082
0.91509
plan_iter = zip(self._volumes, self._sources, self._dests) for step_vol, src, dest in plan_iter: if self._strategy.new_tip == types.TransferTipPolicy.ALWAYS: yield self._format_dict('pick_up_tip', kwargs=self._tip_opts) max_vol = self._instr.max_volume - ...
def _plan_transfer(self)
* **Source/ Dest:** Multiple sources to multiple destinations. Src & dest should be equal length * **Volume:** Single volume or List of volumes is acceptable. This list should be same length as sources/destinations * **Behavior with transfer options:**...
6.29466
5.556226
1.132902
# TODO: decide whether default disposal vol for distribute should be # pipette min_vol or should we leave it to being 0 by default and # recommend users to specify a disposal vol when using distribute. # First method keeps distribute consistent with current behavior while ...
def _plan_distribute(self)
* **Source/ Dest:** One source to many destinations * **Volume:** Single volume or List of volumes is acceptable. This list should be same length as destinations * **Behavior with transfer options:** - New_tip: can be either NEVER or ONCE (ALWAYS...
7.112396
6.421566
1.10758
self.tip_attached = False self.placeables = [] self.previous_placeable = None self.current_volume = 0 self.reset_tip_tracking()
def reset(self)
Resets the state of this pipette, removing associated placeables, setting current volume to zero, and resetting tip tracking
9.947154
3.648928
2.726049
return (self.tip_racks is not None and isinstance(self.tip_racks, list) and len(self.tip_racks) > 0)
def has_tip_rack(self)
Returns True of this :any:`Pipette` was instantiated with tip_racks
2.606103
2.15987
1.206602
self.current_tip(None) self.tip_rack_iter = iter([]) if self.has_tip_rack(): iterables = self.tip_racks if self.channels > 1: iterables = [c for rack in self.tip_racks for c in rack.cols] else: iterables = [w for rack...
def reset_tip_tracking(self)
Resets the :any:`Pipette` tip tracking, "refilling" the tip racks
3.949211
3.653115
1.081053
if not location: return placeable, _ = unpack_location(location) self.previous_placeable = placeable if not self.placeables or (placeable != self.placeables[-1]): self.placeables.append(placeable)
def _associate_placeable(self, location)
Saves a reference to a placeable
3.868571
3.615436
1.070015
if not location: return self placeable, _ = unpack_location(location) if strategy is None: # if no strategy is specified, default to type 'arc' strategy = 'arc' # unless we are still within the same Well, then move directly i...
def move_to(self, location, strategy=None)
Move this :any:`Pipette` to a :any:`Placeable` on the :any:`Deck` Notes ----- Until obstacle-avoidance algorithms are in place, :any:`Robot` and :any:`Pipette` :meth:`move_to` use either an "arc" or "direct" Parameters ---------- location : :any:`Placeab...
7.25513
5.684646
1.276268
if not self.tip_attached: log.warning("Cannot aspirate without a tip attached.") # Note: volume positional argument may not be passed. if it isn't then # assume the first positional argument is the location if not helpers.is_number(volume): if volume and...
def aspirate(self, volume=None, location=None, rate=1.0)
Aspirate a volume of liquid (in microliters/uL) using this pipette from the specified location Notes ----- If only a volume is passed, the pipette will aspirate from it's current position. If only a location is passed, `aspirate` will default to it's `max_volume`. ...
4.17745
4.249507
0.983043
if not self.tip_attached: log.warning("Cannot dispense without a tip attached.") # Note: volume positional argument may not be passed. if it isn't then # assume the first positional argument is the location if not helpers.is_number(volume): if volume and...
def dispense(self, volume=None, location=None, rate=1.0)
Dispense a volume of liquid (in microliters/uL) using this pipette Notes ----- If only a volume is passed, the pipette will dispense from it's current position. If only a location is passed, `dispense` will default to it's `current_volume` The location may be a Well, or...
4.70572
4.766083
0.987335
placeable = None if location: placeable, _ = unpack_location(location) # go to top of source, if not already there if placeable != self.previous_placeable: self.move_to(placeable.top()) else: placeable = self.previous_plac...
def _position_for_aspirate(self, location=None, clearance=1.0)
Position this :any:`Pipette` for an aspiration, given it's current state
5.074559
5.087898
0.997378
if location: if isinstance(location, Placeable): location = location.bottom(min(location.z_size(), clearance)) self.move_to(location)
def _position_for_dispense(self, location=None, clearance=0.5)
Position this :any:`Pipette` for an dispense
7.071074
6.444818
1.097172
''' Move the pipette's mount upwards and away from the deck Parameters ---------- safety_margin: int Distance in millimeters awey from the limit switch, used during the mount's `fast_home()` method ''' self.previous_placeable = None # it ...
def retract(self, safety_margin=10)
Move the pipette's mount upwards and away from the deck Parameters ---------- safety_margin: int Distance in millimeters awey from the limit switch, used during the mount's `fast_home()` method
14.168052
3.520305
4.024666
if not self.tip_attached: log.warning("Cannot mix without a tip attached.") if volume is None: volume = self.max_volume if not location and self.previous_placeable: location = self.previous_placeable do_publish(self.broker, commands.mix, se...
def mix(self, repetitions=1, volume=None, location=None, rate=1.0)
Mix a volume of liquid (in microliters/uL) using this pipette Notes ----- If no `location` is passed, the pipette will mix from it's current position. If no `volume` is passed, `mix` will default to it's `max_volume` Parameters ---------- repetitions: in...
3.115203
3.312425
0.94046
if not self.tip_attached: log.warning("Cannot 'blow out' without a tip attached.") self.move_to(location) self.instrument_actuator.set_active_current(self._plunger_current) self.robot.poses = self.instrument_actuator.move( self.robot.poses, x...
def blow_out(self, location=None)
Force any remaining liquid to dispense, by moving this pipette's plunger to the calibrated `blow_out` position Notes ----- If no `location` is passed, the pipette will blow_out from it's current position. Parameters ---------- location : :any:`Placeable`...
6.594859
7.237925
0.911153
if not self.tip_attached: log.warning("Cannot touch tip without a tip attached.") if speed > 80.0: log.warning("Touch tip speeds greater than 80mm/s not allowed") speed = 80.0 if speed < 20.0: log.warning("Touch tip speeds greater than 80m...
def touch_tip(self, location=None, radius=1.0, v_offset=-1.0, speed=60.0)
Touch the :any:`Pipette` tip to the sides of a well, with the intent of removing left-over droplets Notes ----- If no `location` is passed, the pipette will touch_tip from it's current position. Parameters ---------- location : :any:`Placeable` or tuple(...
3.16576
3.392597
0.933138
if not self.tip_attached: log.warning("Cannot perform air_gap without a tip attached.") if height is None: height = 5 do_publish(self.broker, commands.air_gap, self.air_gap, 'before', self, None, self, volume, height) # if volumes is...
def air_gap(self, volume=None, height=None)
Pull air into the :any:`Pipette` current tip Notes ----- If no `location` is passed, the pipette will touch_tip from it's current position. Parameters ---------- volume : number The amount in uL to aspirate air into the tube. (Default wil...
6.251523
5.905224
1.058643
if not self.tip_attached: log.warning("Cannot return tip without tip attached.") if not self.current_tip(): self.robot.add_warning( 'Pipette has no tip to return, dropping in place') self.drop_tip(self.current_tip(), home_after=home_after) ...
def return_tip(self, home_after=True)
Drop the pipette's current tip to it's originating tip rack Notes ----- This method requires one or more tip-rack :any:`Container` to be in this Pipette's `tip_racks` list (see :any:`Pipette`) Returns ------- This instance of :class:`Pipette`. Examples...
6.333018
7.793534
0.812599
if not self.tip_attached: log.warning("Cannot drop tip without a tip attached.") if not location and self.trash_container: location = self.trash_container if isinstance(location, Placeable): # give space for the drop-tip mechanism # @TOD...
def drop_tip(self, location=None, home_after=True)
Drop the pipette's current tip Notes ----- If no location is passed, the pipette defaults to its `trash_container` (see :any:`Pipette`) Parameters ---------- location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`) The :any:`Placeable` (...
4.050521
4.145933
0.976987
def _home(mount): self.current_volume = 0 self.instrument_actuator.set_active_current(self._plunger_current) self.robot.poses = self.instrument_actuator.home( self.robot.poses) self.robot.poses = self.instrument_mover.home(self.robot.poses...
def home(self)
Home the pipette's plunger axis during a protocol run Notes ----- `Pipette.home()` homes the `Robot` Returns ------- This instance of :class:`Pipette`. Examples -------- .. >>> from opentrons import instruments, robot # doctest: +SKIP ...
6.105972
6.193899
0.985804
# Note: currently it varies whether the pipette should have a tip on # or not depending on the parameters for this call, so we cannot # create a very reliable assertion on tip status args = [volume, source, dest, *args] kwargs['mode'] = 'distribute' kwargs['mix_...
def distribute(self, volume, source, dest, *args, **kwargs)
Distribute will move a volume of liquid from a single of source to a list of target locations. See :any:`Transfer` for details and a full list of optional arguments. Returns ------- This instance of :class:`Pipette`. Examples -------- .. >>> fro...
7.464764
7.61665
0.980059
kwargs['mode'] = 'consolidate' kwargs['mix_before'] = (0, 0) kwargs['air_gap'] = 0 kwargs['disposal_vol'] = 0 args = [volume, source, dest, *args] return self.transfer(*args, **kwargs)
def consolidate(self, volume, source, dest, *args, **kwargs)
Consolidate will move a volume of liquid from a list of sources to a single target location. See :any:`Transfer` for details and a full list of optional arguments. Returns ------- This instance of :class:`Pipette`. Examples -------- .. >>> from ...
4.500978
4.154994
1.083269
minutes += int(seconds / 60) seconds = seconds % 60 seconds += float(minutes * 60) self.robot.pause() if not self.robot.is_simulating(): _sleep(seconds) self.robot.resume() return self
def delay(self, seconds=0, minutes=0)
Parameters ---------- seconds: float The number of seconds to freeze in place.
4.477829
4.424635
1.012022