Exemple #1
0
def _helper_offset_data_format(filepath: str, delta: 'Point') -> dict:
    if not Path(filepath).is_file():
        calibration_data = {
            "default": {
                "offset": [delta.x, delta.y, delta.z],
                "lastModified": utc_now()
            }
        }
    else:
        calibration_data = io.read_cal_file(filepath)
        calibration_data['default']['offset'] = [delta.x, delta.y, delta.z]
        calibration_data['default']['lastModified'] =\
            utc_now()
    return calibration_data
Exemple #2
0
def test_json_datetime_encoder():
    fake_time = utc_now()
    original = {'mock_hash': {'tipLength': 25.0, 'lastModified': fake_time}}

    encoded = json.dumps(original, cls=ed.DateTimeEncoder)
    decoded = json.loads(encoded, cls=ed.DateTimeDecoder)
    assert decoded == original
Exemple #3
0
async def set_system_time(new_time_dt: datetime,
                          loop: asyncio.AbstractEventLoop = None) -> datetime:
    """
    Set the system time unless system time is already being synchronized using
    an RTC or NTPsync.
    Raise error with message, if any.
    :return: current date read.
    """
    if not IS_ROBOT:
        raise errors.SystemSetTimeException(
            msg="Not supported on dev server.",
            definition=CommonErrorDef.NOT_IMPLEMENTED)

    status = await _time_status(loop)
    if status.get('LocalRTC') is True or status.get('NTPSynchronized') is True:
        # TODO: Update this to handle RTC sync correctly once we introduce RTC
        raise errors.SystemTimeAlreadySynchronized(
            'Cannot set system time; already synchronized with NTP or RTC')
    else:
        new_time_dt = new_time_dt.astimezone(tz=timezone.utc)
        new_time_str = new_time_dt.strftime("%Y-%m-%d %H:%M:%S")
        log.info(f'Setting time to {new_time_str} UTC')
        _, err = await _set_time(new_time_str)
        if err:
            raise errors.SystemSetTimeException(err)
    return utc_now()
Exemple #4
0
async def create_access_token() -> access.AccessTokenResponse:
    token = secrets.token_urlsafe(nbytes=8)
    # TODO Store the token
    return access.AccessTokenResponse(
        data=access.ResponseDataModel.create(
            attributes=access.AccessTokenInfo(
                token=token,
                createdAt=utc_now()),
            resource_id=token,
        ))
def test_load_malformed_calibration(ot_config_tempdir):
    pathway = config.get_opentrons_path(
        'robot_calibration_dir') / 'deck_calibration.json'
    data = {
        'atsadasitude': [[1, 0, 1], [0, 1, -.5], [0, 0, 1]],
        'last_modified': utc_now(),
        'tiprack': 'hash',
        'statu': [1, 2, 3],
    }
    io.save_to_file(pathway, data)
    obj = robot_calibration.load_attitude_matrix()
    assert np.allclose(obj.attitude, [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
def test_load_calibration(ot_config_tempdir):
    pathway = config.get_opentrons_path(
        'robot_calibration_dir') / 'deck_calibration.json'
    data = {
        'attitude': [[1, 0, 1], [0, 1, -.5], [0, 0, 1]],
        'pipette_calibrated_with': 'fake',
        'last_modified': utc_now(),
        'tiprack': 'hash'
    }
    io.save_to_file(pathway, data)
    obj = robot_calibration.load_attitude_matrix()
    transform = [[1, 0, 1], [0, 1, -.5], [0, 0, 1]]
    assert np.allclose(obj.attitude, transform)
Exemple #7
0
def save_robot_deck_attitude(transform: local_types.AttitudeMatrix,
                             pip_id: typing.Optional[str],
                             lw_hash: typing.Optional[str]):
    robot_dir = config.get_opentrons_path('robot_calibration_dir')
    robot_dir.mkdir(parents=True, exist_ok=True)
    gantry_path = robot_dir / 'deck_calibration.json'
    gantry_dict: 'DeckCalibrationData' = {
        'attitude': transform,
        'pipette_calibrated_with': pip_id,
        'last_modified': utc_now(),
        'tiprack': lw_hash
    }
    io.save_to_file(gantry_path, gantry_dict)
    async def on_protocol_event(self, cmd: typing.Any):
        """worker listener callback"""
        # These are broker notifications from Session object.
        topic = cmd.get('topic')
        if topic == Session.TOPIC:
            payload = cmd.get('payload')
            if isinstance(payload, dict):
                self.current_state = payload.get('state')
            elif hasattr(payload, 'state'):
                self.current_state = payload.state
        else:
            dollar_val = cmd.get('$')
            event_name = cmd.get('name')
            event = None
            if dollar_val == 'before':
                # text may be a format string using the payload vals as kwargs
                text = deep_get(cmd, ('payload', 'text',), "")
                if text:
                    text = text.format(**cmd.get('payload', {}))
                event = models.ProtocolSessionEvent(
                    source=models.EventSource.protocol_event,
                    event=f'{event_name}.start',
                    commandId=self._id_maker.create_id(),
                    params={'text': text},
                    timestamp=utc_now(),
                )
            elif dollar_val == 'after':
                result = deep_get(cmd, ('payload', 'return',))
                event = models.ProtocolSessionEvent(
                    source=models.EventSource.protocol_event,
                    event=f'{event_name}.end',
                    commandId=self._id_maker.use_last_id(),
                    timestamp=utc_now(),
                    result=result,
                )

            if event:
                self._events.append(event)
Exemple #9
0
def save_pipette_calibration(offset: 'Point', pip_id: str, mount: Mount,
                             tiprack_hash: str, tiprack_uri: str):
    pip_dir = config.get_opentrons_path(
        'pipette_calibration_dir') / mount.name.lower()
    pip_dir.mkdir(parents=True, exist_ok=True)
    offset_path = pip_dir / f'{pip_id}.json'
    offset_dict: 'PipetteCalibrationData' = {
        'offset': [offset.x, offset.y, offset.z],
        'tiprack': tiprack_hash,
        'uri': tiprack_uri,
        'last_modified': utc_now(),
    }
    io.save_to_file(offset_path, offset_dict)
    _add_to_pipette_offset_index_file(pip_id, mount)
def test_load_tip_length_calibration_v1(robot):
    lw = containers_load(robot, 'opentrons_96_tiprack_10ul', '1')
    hash = lw.properties['labware_hash']

    tip_length_data = {'tipLength': 19.99, 'lastModified': utc_now()}
    tip_length_cal = {hash: tip_length_data}
    pip_id = 'fake_id'
    modify.save_tip_length_calibration(pip_id=pip_id,
                                       tip_length_cal=tip_length_cal)

    result = load_tip_length_calibration(pip_id, lw.wells('A1'))

    assert result == tip_length_data

    delete.clear_tip_length_calibration()  # clean up
def test_load_pipette_offset(ot_config_tempdir):
    pip_id = 'fakePip'
    mount = Mount.LEFT
    pip_dir = config.get_opentrons_path('pipette_calibration_dir') / 'left'
    pip_dir.mkdir(parents=True, exist_ok=True)
    pathway = pip_dir / 'fakePip.json'
    data = {
        'offset': [1, 2, 3],
        'tiprack': 'hash',
        'uri': 'opentrons/opentrons_96_tiprack_10ul/1',
        'last_modified': utc_now()
    }
    io.save_to_file(pathway, data)
    obj = robot_calibration.load_pipette_offset(pip_id, mount)
    offset = [1, 2, 3]
    assert np.allclose(obj.offset, offset)
Exemple #12
0
    def add(self, support_file: UploadFile):
        """Add a support file to protocol temp directory"""
        temp_dir = Path(self._meta.directory.name)

        path = temp_dir / support_file.filename
        if path.exists():
            raise ProtocolAlreadyExistsException(
                f"File {support_file.filename} already exists"
            )

        file_meta = save_upload(directory=temp_dir, upload_file=support_file)

        self._meta = replace(
            self._meta,
            support_files=self._meta.support_files + [file_meta],
            last_modified_at=utc_now()
        )
Exemple #13
0
def test_create_tip_length_calibration_data(monkeypatch):

    fake_time = utc_now()

    monkeypatch.setattr(modify, 'utc_now', lambda: fake_time)

    monkeypatch.setattr(
        helpers,
        'hash_labware_def', mock_hash_labware)

    tip_length = 22.0
    parent = ''
    expected_data = {
        MOCK_HASH: {
            'tipLength': tip_length,
            'lastModified': fake_time
        }
    }
    result = modify.create_tip_length_data(
        minimalLabwareDef, parent, tip_length)
    assert result == expected_data
Exemple #14
0
def test_schema_shape(monkeypatch, clear_calibration):
    fake_time = utc_now()
    time_string = fake_time.isoformat()
    from_iso = datetime.datetime.fromisoformat(time_string)

    class fake_datetime:
        @classmethod
        def fromisoformat(cls, obj):
            return from_iso

        @classmethod
        def isoformat(cls):
            return time_string

    mock = Mock(spec=fake_datetime)
    mock.__class__ = datetime.datetime

    test_labware = labware.Labware(minimalLabwareDef,
                                   Location(Point(0, 0, 0), 'deck'))

    monkeypatch.setattr(
       helpers,
       'hash_labware_def', mock_hash_labware
    )

    expected = {"default": {"offset": [1, 1, 1], "lastModified": fake_time}}

    def fake_helper_data(path, delta):
        return expected

    monkeypatch.setattr(
        modify,
        '_helper_offset_data_format',
        fake_helper_data
    )

    labware.save_calibration(test_labware, Point(1, 1, 1))
    with open(path(MOCK_HASH)) as f:
        result = json.load(f, cls=ed.DateTimeDecoder)
    assert result == expected
Exemple #15
0
def create_tip_length_data(definition: 'LabwareDefinition', parent: str,
                           length: float) -> 'PipTipLengthCalibration':
    """
    Function to correctly format tip length data.

    :param definition: full labware definition
    :param parent: the slot associated with the tiprack
    [not yet implemented, so it is always an empty string]
    :param length: the tip length to save
    """
    # TODO(lc, 07-14-2020) since we're trying not to utilize
    # a labware object for these functions, the is tiprack
    # check should happen outside of this function.
    # assert labware._is_tiprack, \
    #     'cannot save tip length for non-tiprack labware'
    labware_hash = helpers.hash_labware_def(definition)

    tip_length_data: 'TipLengthCalibration' = {
        'tipLength': length,
        'lastModified': utc_now()
    }

    data = {labware_hash + parent: tip_length_data}
    return data
Exemple #16
0
async def get_system_time(loop: asyncio.AbstractEventLoop = None) -> datetime:
    """
    :return: Just the system time as a UTC datetime object.
    """
    return utc_now()
Exemple #17
0
 def __enter__(self):
     self.start = utc_now()
     return self
Exemple #18
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     self.end = utc_now()