Exemplo n.º 1
0
    def json(self):
        '''Returns a dict to be used as a json reprentation of the link'''
        records = self.get_reciprocal_records()
        parsed_record = self.parse_record()
        ret = {
            'responder_key': None,
            'controller_key': None,
            'responder_id': None,
            'responder_name': None,
            'responder_group': None,
            'data_1': None,
            'data_2': None,
            'data_3': None,
            'status': self.status(),
            'controller_raw': None,
            'responder_raw': None,
            'controller_group': parsed_record['group']
        }
        if self.is_controller():
            ret['responder_id'] = self.get_linked_device_str()
            ret['controller_key'] = self.key
            ret['controller_raw'] = BYTE_TO_HEX(self.raw)
            if len(records) > 0:
                ret['responder_key'] = records[0].key
                ret['responder_raw'] = BYTE_TO_HEX(records[0].raw)
                parsed_record2 = records[0].parse_record()
                ret['data_1'] = parsed_record2['data_1']
                ret['data_2'] = parsed_record2['data_2']
                ret['data_3'] = parsed_record2['data_3']
            if self.linked_group is not None:
                ret['responder_name'] = self.linked_group.name
                ret['responder_group'] = self.linked_group.group_number
        else:
            ret['responder_id'] = self.device.dev_addr_str
            ret['responder_key'] = self.key
            ret['data_1'] = parsed_record['data_1']
            ret['data_2'] = parsed_record['data_2']
            ret['data_3'] = parsed_record['data_3']
            ret['responder_raw'] = BYTE_TO_HEX(self.raw)
            if len(records) > 0:
                ret['controller_key'] = records[0].key
                ret['controller_raw'] = BYTE_TO_HEX(records[0].raw)
            if self.group_obj is not None:
                ret['responder_name'] = self.group_obj.name
                ret['responder_group'] = self.group_obj.group_number

        # Define the UID for the Link
        rkey = '----'
        ckey = '----'
        if ret['responder_key'] is not None:
            rkey = ret['responder_key']
        if ret['controller_key'] is not None:
            ckey = ret['controller_key']
        return {ret['responder_id'] + rkey + ckey: ret}
Exemplo n.º 2
0
 def _advance_to_msg_start(self):
     '''Removes extraneous bytes from start of read buffer'''
     if len(self._read_buffer) >= 2:
         # Handle Errors First
         good_prefix = bytes.fromhex('02')
         wait_prefix = bytes.fromhex('15')
         if not self._read_buffer.startswith((good_prefix, wait_prefix)):
             print('Removed bad starting string from', BYTE_TO_HEX(
                 self._read_buffer))
             index = self._read_buffer.find(good_prefix)
             del self._read_buffer[0:index]
             print('resulting buffer is', BYTE_TO_HEX(self._read_buffer))
         if self._read_buffer.startswith(wait_prefix):
             print('need to slow down!!', BYTE_TO_HEX(self._read_buffer))
             self.wait_to_send = .5
             del self._read_buffer[0:1]
             self._advance_to_msg_start()
Exemplo n.º 3
0
 def _rcvd_all_link_clean_failed(self, msg):
     failed_addr = bytearray(3)
     failed_addr[0] = msg.get_byte_by_name('fail_addr_hi')
     failed_addr[1] = msg.get_byte_by_name('fail_addr_mid')
     failed_addr[2] = msg.get_byte_by_name('fail_addr_low')
     fail_device = self._device.get_device_by_addr(BYTE_TO_HEX(failed_addr))
     print('Scene Command Failed, Retrying')
     # TODO We are ignoring the all_link cleanup nacks sent directly
     # by the device, do anything with them?
     cmd = self._device._last_sent_msg.get_byte_by_name('cmd_1')
     fail_device.send_handler.send_all_link_clean(
         msg.get_byte_by_name('group'), cmd)
Exemplo n.º 4
0
 def from_addr_str(self):
     if 'to_addr_hi' in self._parent.attribute_positions:
         byte_pos_hi = self._parent.attribute_positions['from_addr_hi']
         byte_pos_mid = self._parent.attribute_positions['from_addr_mid']
         byte_pos_low = self._parent.attribute_positions['from_addr_low']
         return BYTE_TO_HEX(
             bytes((
                 self._parent.raw_msg[byte_pos_hi],
                 self._parent.raw_msg[byte_pos_mid],
                 self._parent.raw_msg[byte_pos_low],
             )))
     else:
         return False
Exemplo n.º 5
0
 def _rcvd_end_of_aldb(self, msg):
     # pylint: disable=W0613
     self._device._last_sent_msg.plm_ack = True
     print('reached the end of the PLMs ALDB')
     # Reassign the PLM ALDB keys, they are not permanent
     for link in self._device.get_all_user_links().values():
         if link._adoptable_responder_key() is not None:
             link.set_responder_key(link._adoptable_responder_key())
     for link in self._device.core.get_user_links_for_this_controller_device(
             self._device).values():
         if link._adoptable_controller_key() is not None:
             link.set_controller_key(link._adoptable_controller_key())
     records = self._device.aldb.get_all_records()
     for key in sorted(records):
         print(key, ":", BYTE_TO_HEX(records[key]))
Exemplo n.º 6
0
 def _write(self, msg):
     now = datetime.datetime.now().strftime("%M:%S.%f")
     if msg.insteon_msg:
         msg.insteon_msg._set_i2cs_checksum()
     if self.port_active:
         print(now, 'sending data', BYTE_TO_HEX(msg.raw_msg))
         msg.time_sent = time.time()
         self._write_to_port(msg.raw_msg)
     else:
         msg.failed = True
         print(
             now,
             'Error: the modem on port',
             self.port,
             'is not active, unable to send message'
         )
     return
Exemplo n.º 7
0
def hub_thread(hub):
    prev_end_pos = -1
    last_bytestring = ''

    while threading.main_thread().is_alive():
        # Read First
        bytestring = ''
        current_end_pos = 0
        start_time = time.time()

        # Get Buffer Contents
        try:
            response = requests.get('http://' + hub.ip + ':' +
                                    hub.port + '/buffstatus.xml',
                                    auth=requests.auth.HTTPBasicAuth(
                                        hub.user,
                                        hub.password),
                                    timeout=5)
        except requests.exceptions.Timeout:
            # TODO handle multiple timeouts, close connection or something
            print('-----------Timeout Occurred--------')
            time.sleep(.1)
            continue

        root = ET.fromstring(response.text)
        for response in root:
            if response.tag == 'BS':
                bytestring = response.text
                break

        # Place buffer in sequential order
        current_end_pos = int(bytestring[-2:], 16)
        bytestring = bytestring[current_end_pos:-2] + \
            bytestring[:current_end_pos]

        if last_bytestring != '' and prev_end_pos >= 0:
            new_length = current_end_pos - prev_end_pos
            new_length = (200 + new_length) if new_length < 0 else new_length
            verify_bytestring = bytestring[190 - new_length: 200 - new_length]
            if new_length > 0 and last_bytestring == verify_bytestring:
                # print(bytestring[-new_length:])
                hex_string = bytestring[-new_length:]
                hex_data = bytearray.fromhex(hex_string)
                hub._read_queue.put(bytearray(hex_data))

        last_bytestring = bytestring[-10:]
        prev_end_pos = current_end_pos

        # Now write
        if not hub._write_queue.empty():
            command = hub._write_queue.get()
            cmd_str = BYTE_TO_HEX(command)
            url = ('http://' + hub.ip + ':' +
                   hub.port + '/3?' + cmd_str + '=I=3')
            try:
                response = requests.get(url,
                                        auth=requests.auth.HTTPBasicAuth(
                                            hub.user,
                                            hub.password),
                                        timeout=3
                                        )
            except requests.exceptions.Timeout:
                # TODO what should happen here, assume it wasn't received?
                # but need to take into account that it was
                print('-----------Timeout In Sending--------')
                time.sleep(.1)
                continue
            last_bytestring = '0000000000'
            prev_end_pos = 0

        # Only hammering at hub server three times per second.  Seems to result
        # in the PLM ACK and device message arriving together, but no more than
        # that. Could consider slowing down, but waiting too long could cause
        # the buffer to overflow and would slow down our responses.  Would also
        # need to increase the hub ack_time accordingly too.
        sleep_time = (start_time + .5) - time.time()
        if sleep_time > 0:
            time.sleep(sleep_time)
        elif sleep_time < -2:
            seconds = str(round(abs(sleep_time), 2))
            print('warning, hub took', seconds, 'to respond')
Exemplo n.º 8
0
 def _get_search_key(self, msg):
     # Zero out max_hops and hops_left
     # arguable whether this should be done in the Insteon_Message class
     search_bytes = msg.raw_msg
     search_bytes[8] = search_bytes[8] & 0b11110000
     return BYTE_TO_HEX(search_bytes)
Exemplo n.º 9
0
 def get_aldb_key(self, msb, lsb):
     offset = 7 - (lsb % 8)
     highest_byte = lsb + offset
     key = bytes([msb, highest_byte])
     return BYTE_TO_HEX(key)
Exemplo n.º 10
0
 def _process_inc_msg(self, raw_msg):
     now = datetime.datetime.now().strftime("%M:%S.%f")
     print(now, 'found legitimate msg', BYTE_TO_HEX(raw_msg))
     msg = PLM_Message(self, raw_data=raw_msg, is_incomming=True)
     self._msg_dispatcher(msg)
     self.trigger_mngr.test_triggers(msg)
Exemplo n.º 11
0
 def print_records(self):
     records = self.get_all_records()
     for key in sorted(records):
         print(key, ":", BYTE_TO_HEX(records[key]))
Exemplo n.º 12
0
 def get_all_records_str(self):
     ret = {}
     for key, record in self.aldb.items():
         ret[key] = BYTE_TO_HEX(record.raw)
     return ret
Exemplo n.º 13
0
 def dev_addr_str(self):
     ret = BYTE_TO_HEX(
         bytes([self.dev_addr_hi, self.dev_addr_mid, self.dev_addr_low]))
     return ret