def get_session() -> Session:
    """
    Creates web api session object.
    :return: Requests Session object
    :rtype: Session
    """
    s = Session()
    set_cfg('SESSION.USER_AGENT',
            'OpenGlow/%s' % get_cfg('FACTORY_FIRMWARE.FW_VERSION'))
    s.headers.update({'user-agent': get_cfg('SESSION.USER_AGENT')})
    logger.debug('Returning object : %s' % s)
    return s
Esempio n. 2
0
    def __init__(self):
        """
        Initializes the object, child threads and message queues.
        """
        self._action_thread: _ActionThread = _ActionThread(self, {})
        self._q_msg_tx: Union[Queue, None] = None
        self.running_action_id: Union[int, None] = 0
        self.running_action_type: Union[str, None] = None
        self._running_action_cancelled: bool = False
        self._session: Session = Union[Queue, None]

        set_cfg('FACTORY_FIRMWARE.FW_VERSION', get_machine_setting('MCov'),
                True)
        set_cfg('FACTORY_FIRMWARE.APP_VERSION', get_machine_setting('MCdv'),
                True)
def send_report(q: Queue, msg: dict) -> None:
    """
    Send device settings report in the required format.
    :param q: {WSS message queue
    :type q: Queue
    :param msg: WSS Message
    :type msg: dict
    :return:
    """
    settings = ''
    logger.info("START")
    for item, setting in MACHINE_SETTINGS.items():
        value = '' if setting.default is None else str(setting.default)
        if setting.in_report:
            if item == 'SAid':
                value = msg['id']
            if item in _CONFIG_PROVIDERS:
                config_value = get_cfg(_CONFIG_PROVIDERS.get(item))
                if config_value is not None:
                    value = str(config_value)
            if item in _REGISTERED_PROVIDERS:
                value = str(_REGISTERED_PROVIDERS[item]())
            if setting.type is int:
                value = int(float(value))
            elif setting.type is str:
                value = '"{}"'.format(value)
            else:
                value = setting.type(value)
            settings += '"{}":{},'.format(item, value)

    # The service appears to bypass the homing process if we send it an empty settings value.
    # It is assumed that this prevents the machine from re-homing every time it loses and regains
    # the connection to the Glowforge service (a seemingly frequent occurrence).
    if not get_cfg('SETTINGS.SET') and not get_cfg('EMULATOR.BYPASS_HOMING'):
        send_wss_event(q, msg['id'], 'settings:completed',
                       data={'key': 'settings', 'value': '{"values":{%s}}' % settings[:-1]})
        set_cfg('SETTINGS.SET', True)
    else:
        send_wss_event(q, msg['id'], 'settings:completed', data={'key': 'settings', 'value': '{}'})
    logger.info("COMPLETE")
def authenticate_machine(s: Session) -> bool:
    """
    Authenticates machine to service.
    POSTS serial number prefixed with an S and machine password to <server_url>/machines/sign_in.
    On success, server responds with JSON encoded 'ws_token' for WSS auth, and 'auth_token' that is
    added as a header to all session web API requests.
    Auth token header is 'Authorization': 'Bearer <auth_token>'
    :param s: Emulator session object.
    :type s: Session
    :return: Authentication result.
    :rtype: bool
    """
    logger.info('START')

    Retry.BACKOFF_MAX = 30
    retries = Retry(
        total=30,
        backoff_factor=5,
        method_whitelist=["GET"]
    )
    adapter = HTTPAdapter(max_retries=retries)
    s.mount("https://", adapter)

    r = request(s, get_cfg('SERVICE.SERVER_URL') + '/machines/sign_in', 'POST',
                data={'serial': 'S' + str(get_cfg('MACHINE.SERIAL')), 'password': get_cfg('MACHINE.PASSWORD')})
    if r:
        rj = r.json()
        logger.debug(rj)
        set_cfg('SESSION.WS_TOKEN', rj['ws_token'])
        set_cfg('SESSION.AUTH_TOKEN', rj['auth_token'])
        update_header(s, 'Authorization', "Bearer %s" % get_cfg('SESSION.AUTH_TOKEN'))
        logger.info('SUCCESS')
        return True
    else:
        logger.error('FAILED')
        return False
Esempio n. 5
0
    def __init__(self):
        update_settings({
            'AAid': {
                'idle': fans.air_assist.set_pwm
            },
            'AArd': {
                'run': fans.air_assist.set_pwm
            },
            'AAwd': {
                'cool_down': fans.air_assist.set_pwm
            },
            'EFid': {
                'idle': fans.exhaust.set_pwm
            },
            'EFrd': {
                'run': fans.exhaust.set_pwm
            },
            'EFwd': {
                'cool_down': fans.exhaust.set_pwm
            },
            'IFid': {
                'idle': fans.intake_1.set_pwm
            },
            'IFrd': {
                'run': fans.intake_1.set_pwm
            },
            'IFwd': {
                'cool_down': fans.intake_1.set_pwm
            },
            'STfr': {
                'run': cnc.set_step_freq
            },
            'XSdm': {
                'run': cnc.set_x_decay
            },
            "XShc": {
                'idle': cnc.set_x_current
            },
            'XSmm': {
                'run': cnc.set_x_mode
            },
            'XSrc': {
                'run': cnc.set_x_current
            },
            'YSdm': {
                'run': cnc.set_y_decay
            },
            "YShc": {
                'idle': cnc.set_y_current
            },
            'YSmm': {
                'run': cnc.set_y_mode
            },
            'YSrc': {
                'run': cnc.set_y_current
            },
            'ZSmd': {
                'run': ZAxis.set_mode_from_puls
            },
        })

        self._button_pressed: bool = False
        self._motion_stats: dict = {}
        self._sw_thread: SwitchMonitor = SwitchMonitor(SWITCH_DEVICE,
                                                       self._switch_event)

        set_cfg('MACHINE.HEAD_FIRMWARE', self.head_info().version, True)
        set_cfg('MACHINE.HEAD_ID', self.head_info().hardware_id, True)
        set_cfg('MACHINE.HEAD_SERIAL', self.head_info().hardware_id, True)

        set_cfg('MACHINE.SERIAL', id.serial(), True)
        set_cfg('MACHINE.HOSTNAME', id.hostname(), True)
        set_cfg('MACHINE.PASSWORD', id.password(), True)

        BaseMachine.__init__(self)