sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def manage_aldb_record(self, control_code, control_flags, group, address, data1, data2, data3): """Update an IM All-Link record. Control Code values: - 0x00 Find First Starting at the top of the ALDB, search for the first ALL-Link Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. The search ignores byte 4, <ALL-Link Record Flags>. You will receive an ACK at the end of the returned message if such an ALL-Link Record exists, or else a NAK if it doesn’t. If the record exists, the IM will return it in an ALL-Link Record Response (0x51) message. - 0x01 Find Next Search for the next ALL-Link Record following the one found using <Control Code> 0x00 above. This allows you to find both Controller and Responder records for a given <ALL-Link Group> and <ID>. Be sure to use the same <ALL-Link Group> and <ID> (bytes 5 – 8) as you used for <Control Code> 0x00. You will receive an ACK at the end of the returned message if another matching ALL-Link Record exists, or else a NAK if it doesn’t. If the record exists, the IM will return it in an ALL-Link Record Response (0x51) message. - 0x20 Modify First Found or Add Modify an existing or else add a new ALL-Link Record for either a Controller or Responder. Starting at the top of the ALDB, search for the first ALL-Link Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. The search ignores byte 4, <ALL-Link Record Flags>. If such an ALL-Link Record exists, overwrite it with the data in bytes 4 – 11; otherwise, create a new ALL-Link Record using bytes 4 – 11. Note that the IM will copy <ALL-Link Record Flags> you supplied in byte 4 below directly into the <ALL-Link Record Flags> byte of the ALL-Link Record in an ALDB-L (linear) database. Use caution, because you can damage an ALDB-L if you misuse this Command. For instance, if you zero the <ALL-Link Record Flags> byte in the first ALL-Link Record, the IM’s ALDB-L database will then appear empty. - 0x40 Modify First Controller Found or Add Modify an existing or else add a new Controller (master) ALL-Link Record. Starting at the top of the ALDB, search for the first ALL-Link Controller Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. An ALL-Link Controller Record has bit 6 of its <ALL-Link Record Flags> byte set to 1. If such a Controller ALL-Link Record exists, overwrite it with the data in bytes 5 – 11; otherwise, create a new ALL-Link Record using bytes 5 – 11. In either case, the IM will set bit 6 of the <ALL-Link Record Flags> byte in the ALL-Link Record to 1 to indicate that the record is for a Controller. - 0x41 Modify First Responder Found or Add Modify an existing or else add a new Responder (slave) ALLLink Record. Starting at the top of the ALDB, search for the first ALL-Link Responder Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. An ALL-Link Responder Record has bit 6 of its <ALL-Link Record Flags> byte cleared to 0. If such a Responder ALL-Link Record exists, overwrite it with the data in bytes 5 – 11; otherwise, create a new ALL-Link Record using bytes 5 – 11. In either case, The IM will clear bit 6 of the <ALL-Link Record Flags> byte in the ALL-Link Record to 0 to indicate that the record is for a Responder. - 0x80 Delete First Found Delete an ALL-Link Record. Starting at the top of the ALDB, search for the first ALL-Link Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. The search ignores byte 4, <ALL-Link Record Flags>. You will receive an ACK at the end of the returned message if such an ALL-Link Record existed and was deleted, or else a NAK no such record exists. """ found_first = False for memaddr in self.aldb: found = False rec = self.aldb[memaddr] found = Address(address) == rec.address found = found & int(group) == rec.group if control_code == 0x00: if found: return (True, rec) if rec.control_flags.is_high_water_mark: return (False, None) if control_code == 0x01: if found & found_first: return (True, rec) if rec.control_flags.is_high_water_mark: return (False, None) if found: found_first = True elif control_code == 0x20: if found or rec.control_flags.is_high_water_mark: new_rec = self._write_new_aldb_rec( rec.mem_addr, control_flags, group, address, data1, data2, data3) return (found, new_rec) elif control_code == 0x40: found = found & rec.control_flags.is_controller if found or rec.control_flags.is_high_water_mark: new_rec = self._write_new_aldb_rec( rec.mem_addr, control_flags, group, address, data1, data2, data3) return (found, new_rec) elif control_code == 0x41: found = found & rec.control_flags.is_responder if found or rec.control_flags.is_high_water_mark: new_rec = self._write_new_aldb_rec( rec.mem_addr, control_flags, group, address, data1, data2, data3) return (found, new_rec) elif control_code == 0x80: if found: cf = rec.control_flags new_control_flags = ControlFlags(False, cf.is_controller, cf.is_high_water_mark, False, False) new_rec = self._write_new_aldb_rec( rec.mem_addr, new_control_flags, rec.group, rec.address, rec.data1, rec.data2, rec.data3) return (found, new_rec) return (False, rec)
Update an IM All-Link record. Control Code values: - 0x00 Find First Starting at the top of the ALDB, search for the first ALL-Link Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. The search ignores byte 4, <ALL-Link Record Flags>. You will receive an ACK at the end of the returned message if such an ALL-Link Record exists, or else a NAK if it doesn’t. If the record exists, the IM will return it in an ALL-Link Record Response (0x51) message. - 0x01 Find Next Search for the next ALL-Link Record following the one found using <Control Code> 0x00 above. This allows you to find both Controller and Responder records for a given <ALL-Link Group> and <ID>. Be sure to use the same <ALL-Link Group> and <ID> (bytes 5 – 8) as you used for <Control Code> 0x00. You will receive an ACK at the end of the returned message if another matching ALL-Link Record exists, or else a NAK if it doesn’t. If the record exists, the IM will return it in an ALL-Link Record Response (0x51) message. - 0x20 Modify First Found or Add Modify an existing or else add a new ALL-Link Record for either a Controller or Responder. Starting at the top of the ALDB, search for the first ALL-Link Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. The search ignores byte 4, <ALL-Link Record Flags>. If such an ALL-Link Record exists, overwrite it with the data in bytes 4 – 11; otherwise, create a new ALL-Link Record using bytes 4 – 11. Note that the IM will copy <ALL-Link Record Flags> you supplied in byte 4 below directly into the <ALL-Link Record Flags> byte of the ALL-Link Record in an ALDB-L (linear) database. Use caution, because you can damage an ALDB-L if you misuse this Command. For instance, if you zero the <ALL-Link Record Flags> byte in the first ALL-Link Record, the IM’s ALDB-L database will then appear empty. - 0x40 Modify First Controller Found or Add Modify an existing or else add a new Controller (master) ALL-Link Record. Starting at the top of the ALDB, search for the first ALL-Link Controller Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. An ALL-Link Controller Record has bit 6 of its <ALL-Link Record Flags> byte set to 1. If such a Controller ALL-Link Record exists, overwrite it with the data in bytes 5 – 11; otherwise, create a new ALL-Link Record using bytes 5 – 11. In either case, the IM will set bit 6 of the <ALL-Link Record Flags> byte in the ALL-Link Record to 1 to indicate that the record is for a Controller. - 0x41 Modify First Responder Found or Add Modify an existing or else add a new Responder (slave) ALLLink Record. Starting at the top of the ALDB, search for the first ALL-Link Responder Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. An ALL-Link Responder Record has bit 6 of its <ALL-Link Record Flags> byte cleared to 0. If such a Responder ALL-Link Record exists, overwrite it with the data in bytes 5 – 11; otherwise, create a new ALL-Link Record using bytes 5 – 11. In either case, The IM will clear bit 6 of the <ALL-Link Record Flags> byte in the ALL-Link Record to 0 to indicate that the record is for a Responder. - 0x80 Delete First Found Delete an ALL-Link Record. Starting at the top of the ALDB, search for the first ALL-Link Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. The search ignores byte 4, <ALL-Link Record Flags>. You will receive an ACK at the end of the returned message if such an ALL-Link Record existed and was deleted, or else a NAK no such record exists.
entailment
def write_aldb(self, mem_addr: int, mode: str, group: int, target, data1=0x00, data2=0x00, data3=0x00): """Write to the device All-Link Database. Parameters: Required: mode: r - device is a responder of target c - device is a controller of target group: Link group target: Address of the other device Optional: data1: Device dependant data2: Device dependant data3: Device dependant """ if isinstance(mode, str) and mode.lower() in ['c', 'r']: pass else: _LOGGER.error('Insteon link mode: %s', mode) raise ValueError("Mode must be 'c' or 'r'") if isinstance(group, int): pass else: raise ValueError("Group must be an integer") target_addr = Address(target) _LOGGER.debug('calling aldb write_record') self._aldb.write_record(mem_addr, mode, group, target_addr, data1, data2, data3) self._aldb.add_loaded_callback(self._aldb_loaded_callback)
Write to the device All-Link Database. Parameters: Required: mode: r - device is a responder of target c - device is a controller of target group: Link group target: Address of the other device Optional: data1: Device dependant data2: Device dependant data3: Device dependant
entailment
def del_aldb(self, mem_addr: int): """Delete an All-Link Database record.""" self._aldb.del_record(mem_addr) self._aldb.add_loaded_callback(self._aldb_loaded_callback)
Delete an All-Link Database record.
entailment
def _refresh_aldb_records(self, linkcode, address, group): """Refresh the IM and device ALDB records.""" if self.aldb.status in [ALDBStatus.LOADED, ALDBStatus.PARTIAL]: for mem_addr in self.aldb: rec = self.aldb[mem_addr] if linkcode in [0, 1, 3]: if rec.control_flags.is_high_water_mark: _LOGGER.debug('Removing HWM record %04x', mem_addr) self.aldb.pop(mem_addr) elif not rec.control_flags.is_in_use: _LOGGER.debug('Removing not in use record %04x', mem_addr) self.aldb.pop(mem_addr) else: if rec.address == self.address and rec.group == group: _LOGGER.debug('Removing record %04x with addr %s and ' 'group %d', mem_addr, rec.address, rec.group) self.aldb.pop(mem_addr) self.read_aldb()
Refresh the IM and device ALDB records.
entailment
def receive_message(self, msg): """Receive a messages sent to this device.""" _LOGGER.debug('Starting Device.receive_message') if hasattr(msg, 'isack') and msg.isack: _LOGGER.debug('Got Message ACK') if self._sent_msg_wait_for_directACK.get('callback') is not None: _LOGGER.debug('Look for direct ACK') asyncio.ensure_future(self._wait_for_direct_ACK(), loop=self._plm.loop) else: _LOGGER.debug('DA queue: %s', self._sent_msg_wait_for_directACK) _LOGGER.debug('Message ACK with no callback') if (hasattr(msg, 'flags') and hasattr(msg.flags, 'isDirectACK') and msg.flags.isDirectACK): _LOGGER.debug('Got Direct ACK message') if self._send_msg_lock.locked(): self._directACK_received_queue.put_nowait(msg) else: _LOGGER.debug('But Direct ACK not expected') if not self._is_duplicate(msg): callbacks = self._message_callbacks.get_callbacks_from_message(msg) for callback in callbacks: _LOGGER.debug('Scheduling msg callback: %s', callback) self._plm.loop.call_soon(callback, msg) else: _LOGGER.debug('msg is duplicate') _LOGGER.debug(msg) self._last_communication_received = datetime.datetime.now() _LOGGER.debug('Ending Device.receive_message')
Receive a messages sent to this device.
entailment
def receive_message(self, msg): """Receive a message sent to this device.""" _LOGGER.debug('Starting X10Device.receive_message') if hasattr(msg, 'isack') and msg.isack: _LOGGER.debug('Got Message ACK') if self._send_msg_lock.locked(): self._send_msg_lock.release() callbacks = self._message_callbacks.get_callbacks_from_message(msg) _LOGGER.debug('Found %d callbacks for msg %s', len(callbacks), msg) for callback in callbacks: _LOGGER.debug('Scheduling msg callback: %s', callback) self._plm.loop.call_soon(callback, msg) self._last_communication_received = datetime.datetime.now() _LOGGER.debug('Ending Device.receive_message')
Receive a message sent to this device.
entailment
def add(self, plm, device, stateType, stateName, group, defaultValue=None): """Add a state to the StateList.""" self._stateList[group] = stateType(plm, device, stateName, group, defaultValue=defaultValue)
Add a state to the StateList.
entailment
def create_from_userdata(userdata): """Create ALDB Record from the userdata dictionary.""" memhi = userdata.get('d3') memlo = userdata.get('d4') memory = memhi << 8 | memlo control_flags = userdata.get('d6') group = userdata.get('d7') addrhi = userdata.get('d8') addrmed = userdata.get('d9') addrlo = userdata.get('d10') addr = Address(bytearray([addrhi, addrmed, addrlo])) data1 = userdata.get('d11') data2 = userdata.get('d12') data3 = userdata.get('d13') return ALDBRecord(memory, control_flags, group, addr, data1, data2, data3)
Create ALDB Record from the userdata dictionary.
entailment
def to_userdata(self): """Return a Userdata dictionary.""" userdata = Userdata({'d3': self.memhi, 'd4': self.memlo, 'd6': self.control_flags, 'd7': self.group, 'd8': self.address.bytes[2], 'd9': self.address.bytes[1], 'd10': self.address.bytes[0], 'd11': self.data1, 'd12': self.data2, 'd13': self.data3}) return userdata
Return a Userdata dictionary.
entailment
def byte(self): """Return a byte representation of ControlFlags.""" flags = int(self._in_use) << 7 \ | int(self._controller) << 6 \ | int(self._bit5) << 5 \ | int(self._bit4) << 4 \ | int(self._used_before) << 1 return flags
Return a byte representation of ControlFlags.
entailment
def create_from_byte(control_flags): """Create a ControlFlags class from a control flags byte.""" in_use = bool(control_flags & 1 << 7) controller = bool(control_flags & 1 << 6) bit5 = bool(control_flags & 1 << 5) bit4 = bool(control_flags & 1 << 4) used_before = bool(control_flags & 1 << 1) flags = ControlFlags(in_use, controller, used_before, bit5=bit5, bit4=bit4) return flags
Create a ControlFlags class from a control flags byte.
entailment
def add_loaded_callback(self, callback): """Add a callback to be run when the ALDB load is complete.""" if callback not in self._cb_aldb_loaded: self._cb_aldb_loaded.append(callback)
Add a callback to be run when the ALDB load is complete.
entailment
async def load(self, mem_addr=0x0000, rec_count=0, retry=0): """Read the device database and load.""" if self._version == ALDBVersion.Null: self._status = ALDBStatus.LOADED _LOGGER.debug('Device has no ALDB') else: self._status = ALDBStatus.LOADING _LOGGER.debug('Tring to lock from load') await self._rec_mgr_lock _LOGGER.debug('load yielded lock') mem_hi = mem_addr >> 8 mem_lo = mem_addr & 0xff log_output = 'ALDB read' max_retries = 0 if rec_count: max_retries = ALDB_RECORD_RETRIES if mem_addr == 0x0000: log_output = '{:s} first record'.format(log_output) else: log_output = '{:s} record {:04x}'.format(log_output, mem_addr) else: max_retries = ALDB_ALL_RECORD_RETRIES log_output = '{:s} all records'.format(log_output) if retry: log_output = '{:s} retry {:d} of {:d}'.format(log_output, retry, max_retries) _LOGGER.info(log_output) userdata = Userdata({'d1': 0, 'd2': 0, 'd3': mem_hi, 'd4': mem_lo, 'd5': rec_count}) msg = ExtendedSend(self._address, COMMAND_EXTENDED_READ_WRITE_ALDB_0X2F_0X00, userdata=userdata) msg.set_checksum() self._send_method(msg, self._handle_read_aldb_ack, True) if not self._load_action: self._set_load_action(mem_addr, rec_count, -1, False)
Read the device database and load.
entailment
def write_record(self, mem_addr: int, mode: str, group: int, target, data1=0x00, data2=0x00, data3=0x00): """Write an All-Link database record.""" if not (self._have_first_record() and self._have_last_record()): _LOGGER.error('Must load the Insteon All-Link Database before ' 'writing to it') else: self._prior_status = self._status self._status = ALDBStatus.LOADING mem_hi = mem_addr >> 8 mem_lo = mem_addr & 0xff controller = mode == 'c' control_flag = ControlFlags(True, controller, True, False, False) addr = Address(target) addr_lo = addr.bytes[0] addr_mid = addr.bytes[1] addr_hi = addr.bytes[2] userdata = Userdata({'d1': 0, 'd2': 0x02, 'd3': mem_hi, 'd4': mem_lo, 'd5': 0x08, 'd6': control_flag.byte, 'd7': group, 'd8': addr_lo, 'd9': addr_mid, 'd10': addr_hi, 'd11': data1, 'd12': data2, 'd13': data3}) msg = ExtendedSend(self._address, COMMAND_EXTENDED_READ_WRITE_ALDB_0X2F_0X00, userdata=userdata) msg.set_checksum() _LOGGER.debug('writing message %s', msg) self._send_method(msg, self._handle_write_aldb_ack, True) self._load_action = LoadAction(mem_addr, 1, 0)
Write an All-Link database record.
entailment
def del_record(self, mem_addr: int): """Write an All-Link database record.""" record = self._records.get(mem_addr) if not record: _LOGGER.error('Must load the Insteon All-Link Database record ' 'before deleting it') else: self._prior_status = self._status self._status = ALDBStatus.LOADING mem_hi = mem_addr >> 8 mem_lo = mem_addr & 0xff controller = record.control_flags.is_controller control_flag = ControlFlags(False, controller, True, False, False) addr = record.address addr_lo = addr.bytes[0] addr_mid = addr.bytes[1] addr_hi = addr.bytes[2] group = record.group data1 = record.data1 data2 = record.data2 data3 = record.data3 userdata = Userdata({'d1': 0, 'd2': 0x02, 'd3': mem_hi, 'd4': mem_lo, 'd5': 0x08, 'd6': control_flag.byte, 'd7': group, 'd8': addr_lo, 'd9': addr_mid, 'd10': addr_hi, 'd11': data1, 'd12': data2, 'd13': data3}) msg = ExtendedSend(self._address, COMMAND_EXTENDED_READ_WRITE_ALDB_0X2F_0X00, userdata=userdata) msg.set_checksum() _LOGGER.debug('writing message %s', msg) self._send_method(msg, self._handle_write_aldb_ack, True) self._load_action = LoadAction(mem_addr, 1, 0)
Write an All-Link database record.
entailment
def find_matching_link(self, mode, group, addr): """Find a matching link in the current device. Mode: r | c is the mode of the link in the linked device This method will search for a corresponding link in the reverse direction. group: All-Link group number addr: Inteon address of the linked device """ found_rec = None mode_test = None if mode.lower() in ['c', 'r']: link_group = int(group) link_addr = Address(addr) for mem_addr in self: rec = self[mem_addr] if mode.lower() == 'r': mode_test = rec.control_flags.is_controller else: mode_test = rec.control_flags.is_responder if (mode_test and rec.group == link_group and rec.address == link_addr): found_rec = rec return found_rec
Find a matching link in the current device. Mode: r | c is the mode of the link in the linked device This method will search for a corresponding link in the reverse direction. group: All-Link group number addr: Inteon address of the linked device
entailment
def record_received(self, msg): """Handle ALDB record received from device.""" release_lock = False userdata = msg.userdata rec = ALDBRecord.create_from_userdata(userdata) self._records[rec.mem_addr] = rec _LOGGER.debug('ALDB Record: %s', rec) rec_count = self._load_action.rec_count if rec_count == 1 or self._have_all_records(): release_lock = True if self._is_first_record(rec): self._mem_addr = rec.mem_addr if release_lock and self._rec_mgr_lock.locked(): _LOGGER.debug('Releasing lock because record received') self._rec_mgr_lock.release()
Handle ALDB record received from device.
entailment
def load_saved_records(self, status, records): """Load ALDB records from a set of saved records.""" if isinstance(status, ALDBStatus): self._status = status else: self._status = ALDBStatus(status) for mem_addr in records: rec = records[mem_addr] control_flags = int(rec.get('control_flags', 0)) group = int(rec.get('group', 0)) rec_addr = rec.get('address', '000000') data1 = int(rec.get('data1', 0)) data2 = int(rec.get('data2', 0)) data3 = int(rec.get('data3', 0)) self[int(mem_addr)] = ALDBRecord(int(mem_addr), control_flags, group, rec_addr, data1, data2, data3) if self._status == ALDBStatus.LOADED: keys = list(self._records.keys()) keys.sort(reverse=True) first_key = keys[0] self._mem_addr = first_key
Load ALDB records from a set of saved records.
entailment
def _set_load_action(self, mem_addr, rec_count, retries, read_complete=False): """Calculate the next record to read. If the last record was successful and one record was being read then look for the next record until we get to the high water mark. If the last read was successful and all records were being read then look for the first record. if the last read was unsuccessful and one record was being read then repeat the last read until max retries If the last read was unsuccessful and all records were being read then repeat the last read until max retries or look for the first record. """ if self._have_all_records(): mem_addr = None rec_count = 0 retries = 0 elif read_complete: retries = 0 if rec_count: mem_addr = self._next_address(mem_addr) else: mem_addr = self._next_address(mem_addr) rec_count = 1 retries = 0 elif rec_count and retries < ALDB_RECORD_RETRIES: retries = retries + 1 elif not rec_count and retries < ALDB_ALL_RECORD_RETRIES: retries = retries + 1 elif not rec_count and retries >= ALDB_ALL_RECORD_RETRIES: mem_addr = self._next_address(mem_addr) rec_count = 1 retries = 0 else: mem_addr = None rec_count = 0 retries = 0 self._load_action = LoadAction(mem_addr, rec_count, retries) if mem_addr is not None: _LOGGER.debug('Load action: addr: %04x rec_count: %d retries: %d', self._load_action.mem_addr, self._load_action.rec_count, self._load_action.retries)
Calculate the next record to read. If the last record was successful and one record was being read then look for the next record until we get to the high water mark. If the last read was successful and all records were being read then look for the first record. if the last read was unsuccessful and one record was being read then repeat the last read until max retries If the last read was unsuccessful and all records were being read then repeat the last read until max retries or look for the first record.
entailment
def register_updates(self, callback): """Register a callback to notify a listener of state changes.""" _LOGGER.debug("Registered callback for state: %s", self._stateName) self._observer_callbacks.append(callback)
Register a callback to notify a listener of state changes.
entailment
def _update_subscribers(self, val): """Save state value and notify listeners of the change.""" self._value = val for callback in self._observer_callbacks: callback(self._address, self._group, val)
Save state value and notify listeners of the change.
entailment
def from_raw_message(cls, rawmessage): """Create message from raw byte stream.""" userdata = Userdata.from_raw_message(rawmessage[11:25]) return ExtendedReceive(rawmessage[2:5], rawmessage[5:8], {'cmd1': rawmessage[9], 'cmd2': rawmessage[10]}, userdata, flags=rawmessage[8])
Create message from raw byte stream.
entailment
def template(cls, address=None, target=None, commandtuple=None, userdata=None, cmd2=-1, flags=None): """Create message template for callbacks.""" msgraw = bytearray([0x02, cls._code]) msgraw.extend(bytes(cls._receivedSize)) msg = ExtendedReceive.from_raw_message(msgraw) if commandtuple: cmd1 = commandtuple.get('cmd1') cmd2out = commandtuple.get('cmd2') else: cmd1 = None cmd2out = None if cmd2 is not -1: cmd2out = cmd2 msg._address = Address(address) msg._target = Address(target) msg._messageFlags = MessageFlags(flags) msg._cmd1 = cmd1 msg._cmd2 = cmd2out msg._userdata = Userdata.create_pattern(userdata) return msg
Create message template for callbacks.
entailment
def targetLow(self): """Return the low byte of the target address field. Used in All-Link Cleanup messages. """ low_byte = None if self.target is not None and self._messageFlags.isBroadcast: low_byte = self.target.bytes[0] return low_byte
Return the low byte of the target address field. Used in All-Link Cleanup messages.
entailment
def set_level(self, val): """Set the devive ON LEVEL.""" if val == 0: self.off() else: setlevel = 255 if val < 1: setlevel = val * 100 elif val <= 0xff: setlevel = val set_command = StandardSend( self._address, COMMAND_LIGHT_ON_0X11_NONE, cmd2=setlevel) self._send_method(set_command, self._on_message_received)
Set the devive ON LEVEL.
entailment
def brighten(self): """Brighten the device one step.""" brighten_command = StandardSend( self._address, COMMAND_LIGHT_BRIGHTEN_ONE_STEP_0X15_0X00) self._send_method(brighten_command)
Brighten the device one step.
entailment
def dim(self): """Dim the device one step.""" dim_command = StandardSend( self._address, COMMAND_LIGHT_DIM_ONE_STEP_0X16_0X00) self._send_method(dim_command)
Dim the device one step.
entailment
def set_level(self, val): """Set the fan speed.""" speed = self._value_to_fan_speed(val) if val == 0: self.off() else: set_command = ExtendedSend(self._address, COMMAND_LIGHT_ON_0X11_NONE, self._udata, cmd2=speed) set_command.set_checksum() self._send_method(set_command, self._on_message_received)
Set the fan speed.
entailment
def open(self): """Turn the device ON.""" open_command = StandardSend(self._address, COMMAND_LIGHT_ON_0X11_NONE, cmd2=0xff) self._send_method(open_command, self._open_message_received)
Turn the device ON.
entailment
def open_fast(self): """Turn the device ON Fast.""" open_command = StandardSend(self._address, COMMAND_LIGHT_ON_FAST_0X12_NONE, cmd2=0xff) self._send_method(open_command, self._open_message_received)
Turn the device ON Fast.
entailment
def close(self): """Turn the device off.""" close_command = StandardSend(self._address, COMMAND_LIGHT_OFF_0X13_0X00) self._send_method(close_command, self._closed_message_received)
Turn the device off.
entailment
def close_fast(self): """Turn the device off.""" close_command = StandardSend(self._address, COMMAND_LIGHT_OFF_FAST_0X14_0X00) self._send_method(close_command, self._closed_message_received)
Turn the device off.
entailment
def set_position(self, val): """Set the devive OPEN LEVEL.""" if val == 0: self.close() else: setlevel = 255 if val < 1: setlevel = val * 100 elif val <= 0xff: setlevel = val set_command = StandardSend( self._address, COMMAND_LIGHT_ON_0X11_NONE, cmd2=setlevel) self._send_method(set_command, self._open_message_received)
Set the devive OPEN LEVEL.
entailment
def set_position_fast(self, val): """Set the devive OPEN LEVEL.""" if val == 0: self.close_fast() else: setlevel = 255 if val < 1: setlevel = val * 100 elif val <= 0xff: setlevel = val set_command = StandardSend( self._address, COMMAND_LIGHT_ON_FAST_0X12_NONE, cmd2=setlevel) self._send_method(set_command, self._open_message_received)
Set the devive OPEN LEVEL.
entailment
def async_refresh_state(self): """Request each state to provide status update.""" _LOGGER.debug('Setting up extended status') ext_status = ExtendedSend( address=self._address, commandtuple=COMMAND_EXTENDED_GET_SET_0X2E_0X00, cmd2=0x02, userdata=Userdata()) ext_status.set_crc() _LOGGER.debug('Sending ext status: %s', ext_status) self._send_msg(ext_status) _LOGGER.debug('Sending temp status request') self.temperature.async_refresh_state()
Request each state to provide status update.
entailment
def byte_to_housecode(bytecode): """Return an X10 housecode value from a byte value.""" hc = list(HC_LOOKUP.keys())[list(HC_LOOKUP.values()).index(bytecode)] return hc.upper()
Return an X10 housecode value from a byte value.
entailment
def byte_to_unitcode(bytecode): """Return an X10 unitcode value from a byte value.""" return list(UC_LOOKUP.keys())[list(UC_LOOKUP.values()).index(bytecode)]
Return an X10 unitcode value from a byte value.
entailment
def x10_command_type(command): """Return the X10 command type from an X10 command.""" command_type = X10CommandType.DIRECT if command in [X10_COMMAND_ALL_UNITS_OFF, X10_COMMAND_ALL_LIGHTS_ON, X10_COMMAND_ALL_LIGHTS_OFF]: command_type = X10CommandType.BROADCAST return command_type
Return the X10 command type from an X10 command.
entailment
def set_bit(bitmask, bit, is_on): """Set the value of a bit in a bitmask on or off. Uses the low bit is 1 and the high bit is 8. """ bitshift = bit - 1 if is_on: return bitmask | (1 << bitshift) return bitmask & (0xff & ~(1 << bitshift))
Set the value of a bit in a bitmask on or off. Uses the low bit is 1 and the high bit is 8.
entailment
def from_raw_message(cls, rawmessage): """Create a message from a raw byte stream.""" if (rawmessage[5] & MESSAGE_FLAG_EXTENDED_0X10) == MESSAGE_FLAG_EXTENDED_0X10: if len(rawmessage) >= ExtendedSend.receivedSize: msg = ExtendedSend.from_raw_message(rawmessage) else: msg = None else: msg = StandardSend(rawmessage[2:5], {'cmd1': rawmessage[6], 'cmd2': rawmessage[7]}, flags=rawmessage[5], acknak=rawmessage[8:9]) return msg
Create a message from a raw byte stream.
entailment
def from_raw_message(cls, rawmessage): """Create a message from a raw byte stream.""" userdata_dict = Userdata(rawmessage[8:22]) return ExtendedSend(rawmessage[2:5], {'cmd1': rawmessage[6], 'cmd2': rawmessage[7]}, userdata_dict, flags=rawmessage[5], acknak=rawmessage[22:23])
Create a message from a raw byte stream.
entailment
def template(cls, address=None, commandtuple=None, userdata=None, cmd2=-1, flags=None, acknak=None): """Create a message template used for callbacks.""" msgraw = bytearray([0x02, cls._code]) msgraw.extend(bytes(cls._receivedSize)) msg = ExtendedSend.from_raw_message(msgraw) if commandtuple: cmd1 = commandtuple.get('cmd1') cmd2out = commandtuple.get('cmd2') else: cmd1 = None cmd2out = None if cmd2 is not -1: cmd2out = cmd2 msg._address = Address(address) msg._messageFlags = MessageFlags(flags) msg._messageFlags.extended = 1 msg._cmd1 = cmd1 msg._cmd2 = cmd2out msg._userdata = Userdata.template(userdata) msg._acknak = acknak return msg
Create a message template used for callbacks.
entailment
def set_checksum(self): """Set byte 14 of the userdata to a checksum value.""" data_sum = self.cmd1 + self.cmd2 for i in range(1, 14): data_sum += self._userdata['d{:d}'.format(i)] chksum = 0xff - (data_sum & 0xff) + 1 self._userdata['d14'] = chksum
Set byte 14 of the userdata to a checksum value.
entailment
def set_crc(self): """Set Userdata[13] and Userdata[14] to the CRC value.""" data = self.bytes[6:20] crc = int(0) for b in data: # pylint: disable=unused-variable for bit in range(0, 8): fb = b & 0x01 fb = fb ^ 0x01 if (crc & 0x8000) else fb fb = fb ^ 0x01 if (crc & 0x4000) else fb fb = fb ^ 0x01 if (crc & 0x1000) else fb fb = fb ^ 0x01 if (crc & 0x0008) else fb crc = ((crc << 1) | fb) & 0xffff b = b >> 1 self._userdata['d13'] = (crc >> 8) & 0xff self._userdata['d14'] = crc & 0xff
Set Userdata[13] and Userdata[14] to the CRC value.
entailment
def from_raw_message(cls, rawmessage): """Create message from a raw byte stream.""" return StandardReceive(rawmessage[2:5], rawmessage[5:8], {'cmd1': rawmessage[9], 'cmd2': rawmessage[10]}, flags=rawmessage[8])
Create message from a raw byte stream.
entailment
def targetMed(self): """Return the middle byte of the target message property. Used in All-Link Cleanup message types. """ med_byte = None if self.target.addr is not None and self._messageFlags.isBroadcast: med_byte = self.target.bytes[1] return med_byte
Return the middle byte of the target message property. Used in All-Link Cleanup message types.
entailment
def targetHi(self): """Return the high byte of the target message property. Used in All-Link Cleanup message types. """ hi_byte = None if self.target.addr is not None and self._messageFlags.isBroadcast: hi_byte = self.target.bytes[2] return hi_byte
Return the high byte of the target message property. Used in All-Link Cleanup message types.
entailment
def from_raw_message(cls, rawmessage): """Create a message from a raw byte stream.""" return AllLinkComplete(rawmessage[2], rawmessage[3], rawmessage[4:7], rawmessage[7], rawmessage[8], rawmessage[9])
Create a message from a raw byte stream.
entailment
def create(rawmessage): """Return an INSTEON message class based on a raw byte stream.""" rawmessage = _trim_buffer_garbage(rawmessage) if len(rawmessage) < 2: return (None, rawmessage) code = rawmessage[1] msgclass = _get_msg_class(code) msg = None remaining_data = rawmessage if msgclass is None: _LOGGER.debug('Did not find message class 0x%02x', rawmessage[1]) rawmessage = rawmessage[1:] rawmessage = _trim_buffer_garbage(rawmessage, False) if rawmessage: _LOGGER.debug('Create: %s', create) _LOGGER.debug('rawmessage: %s', binascii.hexlify(rawmessage)) msg, remaining_data = create(rawmessage) else: remaining_data = rawmessage else: if iscomplete(rawmessage): msg = msgclass.from_raw_message(rawmessage) if msg: remaining_data = rawmessage[len(msg.bytes):] # _LOGGER.debug("Returning msg: %s", msg) # _LOGGER.debug('Returning buffer: %s', binascii.hexlify(remaining_data)) return (msg, remaining_data)
Return an INSTEON message class based on a raw byte stream.
entailment
def iscomplete(rawmessage): """Test if the raw message is a complete message.""" if len(rawmessage) < 2: return False if rawmessage[0] != 0x02: raise ValueError('message does not start with 0x02') messageBuffer = bytearray() filler = bytearray(30) messageBuffer.extend(rawmessage) messageBuffer.extend(filler) msg = _get_msg_class(rawmessage[1]) if hasattr(msg, 'receivedSize') and msg.receivedSize: expectedSize = msg.receivedSize else: _LOGGER.error('Unable to find a receivedSize for code 0x%x', rawmessage[1]) return ValueError is_expected_size = False if len(rawmessage) >= expectedSize: is_expected_size = True return is_expected_size
Test if the raw message is a complete message.
entailment
def _get_msg_class(code): """Get the message class based on the message code.""" msg_classes = {} msg_classes = _add_msg_class(msg_classes, MESSAGE_STANDARD_MESSAGE_RECEIVED_0X50, StandardReceive) msg_classes = _add_msg_class(msg_classes, MESSAGE_EXTENDED_MESSAGE_RECEIVED_0X51, ExtendedReceive) msg_classes = _add_msg_class(msg_classes, MESSAGE_X10_MESSAGE_RECEIVED_0X52, X10Received) msg_classes = _add_msg_class(msg_classes, MESSAGE_ALL_LINKING_COMPLETED_0X53, AllLinkComplete) msg_classes = _add_msg_class(msg_classes, MESSAGE_BUTTON_EVENT_REPORT_0X54, ButtonEventReport) msg_classes = _add_msg_class(msg_classes, MESSAGE_USER_RESET_DETECTED_0X55, UserReset) msg_classes = _add_msg_class(msg_classes, MESSAGE_ALL_LINK_CEANUP_FAILURE_REPORT_0X56, AllLinkCleanupFailureReport) msg_classes = _add_msg_class(msg_classes, MESSAGE_ALL_LINK_RECORD_RESPONSE_0X57, AllLinkRecordResponse) msg_classes = _add_msg_class(msg_classes, MESSAGE_ALL_LINK_CLEANUP_STATUS_REPORT_0X58, AllLinkCleanupStatusReport) msg_classes = _add_msg_class(msg_classes, MESSAGE_GET_IM_INFO_0X60, GetImInfo) msg_classes = _add_msg_class(msg_classes, MESSAGE_SEND_ALL_LINK_COMMAND_0X61, SendAllLinkCommand) msg_classes = _add_msg_class(msg_classes, MESSAGE_SEND_STANDARD_MESSAGE_0X62, StandardSend) msg_classes = _add_msg_class(msg_classes, MESSAGE_X10_MESSAGE_SEND_0X63, X10Send) msg_classes = _add_msg_class(msg_classes, MESSAGE_START_ALL_LINKING_0X64, StartAllLinking) msg_classes = _add_msg_class(msg_classes, MESSAGE_CANCEL_ALL_LINKING_0X65, CancelAllLinking) msg_classes = _add_msg_class(msg_classes, MESSAGE_RESET_IM_0X67, ResetIM) msg_classes = _add_msg_class(msg_classes, MESSAGE_GET_FIRST_ALL_LINK_RECORD_0X69, GetFirstAllLinkRecord) msg_classes = _add_msg_class(msg_classes, MESSAGE_GET_NEXT_ALL_LINK_RECORD_0X6A, GetNextAllLinkRecord) msg_classes = _add_msg_class(msg_classes, MESSAGE_MANAGE_ALL_LINK_RECORD_0X6F, ManageAllLinkRecord) msg_classes = _add_msg_class(msg_classes, MESSAGE_SET_IM_CONFIGURATION_0X6B, SetIMConfiguration) msg_classes = _add_msg_class(msg_classes, MESSAGE_GET_IM_CONFIGURATION_0X73, GetImConfiguration) return msg_classes.get(code, None)
Get the message class based on the message code.
entailment
def _trim_buffer_garbage(rawmessage, debug=True): """Remove leading bytes from a byte stream. A proper message byte stream begins with 0x02. """ while rawmessage and rawmessage[0] != MESSAGE_START_CODE_0X02: if debug: _LOGGER.debug('Buffer content: %s', binascii.hexlify(rawmessage)) _LOGGER.debug('Trimming leading buffer garbage') rawmessage = rawmessage[1:] return rawmessage
Remove leading bytes from a byte stream. A proper message byte stream begins with 0x02.
entailment
def matches_pattern(self, other): """Test if current message match a patterns or template.""" if hasattr(other, 'messageType'): messageTypeIsEqual = False if self.messageType is None or other.messageType is None: messageTypeIsEqual = True else: messageTypeIsEqual = (self.messageType == other.messageType) extendedIsEqual = False if self.extended is None or other.extended is None: extendedIsEqual = True else: extendedIsEqual = (self.extended == other.extended) return messageTypeIsEqual and extendedIsEqual return False
Test if current message match a patterns or template.
entailment
def get_properties(cls): """Get all properties of the MessageFlags class.""" property_names = [p for p in dir(cls) if isinstance(getattr(cls, p), property)] return property_names
Get all properties of the MessageFlags class.
entailment
def isDirect(self): """Test if the message is a direct message type.""" direct = (self._messageType == 0x00) if self.isDirectACK or self.isDirectNAK: direct = True return direct
Test if the message is a direct message type.
entailment
def create(cls, messageType, extended, hopsleft=3, hopsmax=3): """Create message flags. messageType: integter 0 to 7: MESSAGE_TYPE_DIRECT_MESSAGE = 0 MESSAGE_TYPE_DIRECT_MESSAGE_ACK = 1 MESSAGE_TYPE_ALL_LINK_CLEANUP = 2 MESSAGE_TYPE_ALL_LINK_CLEANUP_ACK = 3 MESSAGE_TYPE_BROADCAST_MESSAGE = 4 MESSAGE_TYPE_DIRECT_MESSAGE_NAK = 5 MESSAGE_TYPE_ALL_LINK_BROADCAST = 6 MESSAGE_TYPE_ALL_LINK_CLEANUP_NAK = 7 extended: 1 for extended, 0 for standard hopsleft: int 0 - 3 hopsmax: int 0 - 3 """ flags = MessageFlags(None) if messageType < 8: flags._messageType = messageType else: flags._messageType = messageType >> 5 if extended in [0, 1, True, False]: if extended: flags._extended = 1 else: flags._extended = 0 else: flags._extended = extended >> 4 flags._hopsLeft = hopsleft flags._hopsMax = hopsmax return flags
Create message flags. messageType: integter 0 to 7: MESSAGE_TYPE_DIRECT_MESSAGE = 0 MESSAGE_TYPE_DIRECT_MESSAGE_ACK = 1 MESSAGE_TYPE_ALL_LINK_CLEANUP = 2 MESSAGE_TYPE_ALL_LINK_CLEANUP_ACK = 3 MESSAGE_TYPE_BROADCAST_MESSAGE = 4 MESSAGE_TYPE_DIRECT_MESSAGE_NAK = 5 MESSAGE_TYPE_ALL_LINK_BROADCAST = 6 MESSAGE_TYPE_ALL_LINK_CLEANUP_NAK = 7 extended: 1 for extended, 0 for standard hopsleft: int 0 - 3 hopsmax: int 0 - 3
entailment
def bytes(self): """Return a byte representation of the message flags.""" flagByte = 0x00 messageType = 0 if self._messageType is not None: messageType = self._messageType << 5 extendedBit = 0 if self._extended is None else self._extended << 4 hopsMax = 0 if self._hopsMax is None else self._hopsMax hopsLeft = 0 if self._hopsLeft is None else (self._hopsLeft << 2) flagByte = flagByte | messageType | extendedBit | hopsLeft | hopsMax return bytes([flagByte])
Return a byte representation of the message flags.
entailment
def _normalize(self, flags): """Take any format of flags and turn it into a hex string.""" norm = None if isinstance(flags, MessageFlags): norm = flags.bytes elif isinstance(flags, bytearray): norm = binascii.hexlify(flags) elif isinstance(flags, int): norm = bytes([flags]) elif isinstance(flags, bytes): norm = binascii.hexlify(flags) elif isinstance(flags, str): flags = flags[0:2] norm = binascii.hexlify(binascii.unhexlify(flags.lower())) elif flags is None: norm = None else: _LOGGER.warning('MessageFlags with unknown type %s: %r', type(flags), flags) return norm
Take any format of flags and turn it into a hex string.
entailment
def _set_properties(self, flags): """Set the properties of the message flags based on a byte input.""" flagByte = self._normalize(flags) if flagByte is not None: self._messageType = (flagByte[0] & 0xe0) >> 5 self._extended = (flagByte[0] & MESSAGE_FLAG_EXTENDED_0X10) >> 4 self._hopsLeft = (flagByte[0] & 0x0c) >> 2 self._hopsMax = flagByte[0] & 0x03 else: self._messageType = None self._extended = None self._hopsLeft = None self._hopsMax = None
Set the properties of the message flags based on a byte input.
entailment
def set_value(self, dry_wet: LeakSensorState): """Set the value of the state to dry or wet.""" value = 0 if dry_wet == self._dry_wet_type: value = 1 self._update_subscribers(value)
Set the value of the state to dry or wet.
entailment
def _dry_wet_message_received(self, msg): """Report a dry or a wet state.""" for callback in self._dry_wet_callbacks: callback(self._dry_wet_type) self._update_subscribers(0x01)
Report a dry or a wet state.
entailment
def set_value(self, dry_wet: LeakSensorState): """Set the state to wet or dry.""" if dry_wet == LeakSensorState.DRY: self._update_subscribers(0x11) else: self._update_subscribers(0x13)
Set the state to wet or dry.
entailment
def _dry_message_received(self, msg): """Report a dry state.""" for callback in self._dry_wet_callbacks: callback(LeakSensorState.DRY) self._update_subscribers(0x11)
Report a dry state.
entailment
def _wet_message_received(self, msg): """Report a wet state.""" for callback in self._dry_wet_callbacks: callback(LeakSensorState.WET) self._update_subscribers(0x13)
Report a wet state.
entailment
def add(self, msg, callback, override=False): """Add a callback to the callback list. msg: Message template. callback: Callback method override: True - replace all existing callbacks for that template False - append the list of callbacks for that message Default is False """ if override: if isinstance(callback, list): self._dict[msg] = callback else: self._dict[msg] = [callback] else: cb = self[msg] cb.append(callback) self._dict[msg] = cb
Add a callback to the callback list. msg: Message template. callback: Callback method override: True - replace all existing callbacks for that template False - append the list of callbacks for that message Default is False
entailment
def remove(self, msg, callback): """Remove a callback from the callback list. msg: Message template callback: Callback method to remove. If callback is None, all callbacks for the message template are removed. """ if callback is None: self._dict.pop(msg, None) else: cb = self._dict.get(msg, []) try: cb.remove(callback) except ValueError: pass if cb: _LOGGER.debug('%d callbacks for message: %s', len(cb), msg) self.add(msg, cb, True) else: self._dict.pop(msg, None) _LOGGER.debug('Removed all callbacks for message: %s', msg)
Remove a callback from the callback list. msg: Message template callback: Callback method to remove. If callback is None, all callbacks for the message template are removed.
entailment
def get_callbacks_from_message(self, msg): """Return the callbacks associated with a message template.""" callbacks = [] for key in self._find_matching_keys(msg): for callback in self[key]: callbacks.append(callback) return callbacks
Return the callbacks associated with a message template.
entailment
def x10(self, feature): """Return an X10 device based on a feature. Current features: - OnOff - Dimmable """ x10_product = None for product in self._x10_products: if feature.lower() == product.feature: x10_product = product if not x10_product: x10_product = X10Product(feature, None) return x10_product
Return an X10 device based on a feature. Current features: - OnOff - Dimmable
entailment
def from_raw_message(cls, rawmessage): """Create message from raw byte stream.""" return AllLinkRecordResponse(rawmessage[2], rawmessage[3], rawmessage[4:7], rawmessage[7], rawmessage[8], rawmessage[9])
Create message from raw byte stream.
entailment
def monitor(): """Connect to receiver and show events as they occur. Pulls the following arguments from the command line: :param device: Unix device where the PLM is attached :param address: Insteon address of the device to link with :param group: Insteon group for the link :param: linkcode Link direction: 0 - PLM is responder 1 - PLM is controller 3 - IM is responder or controller' :param verbose: Show debug logging. """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--device', default='/dev/ttyUSB0', help='Path to PLM device') parser.add_argument('--verbose', '-v', action='count', help='Set logging level to verbose') parser.add_argument('-l', '--logfile', default='', help='Log file name') parser.add_argument('--workdir', default='', help='Working directory for reading and saving ' 'device information.') args = parser.parse_args() loop = asyncio.get_event_loop() monTool = Tools(loop, args) asyncio.ensure_future(monTool.monitor_mode()) try: loop.run_forever() except KeyboardInterrupt: if monTool.plm: if monTool.plm.transport: _LOGGING.info('Closing the session') asyncio.ensure_future(monTool.plm.transport.close(), loop=loop) loop.stop() pending = asyncio.Task.all_tasks(loop=loop) for task in pending: task.cancel() try: loop.run_until_complete(task) except asyncio.CancelledError: pass except KeyboardInterrupt: pass loop.close()
Connect to receiver and show events as they occur. Pulls the following arguments from the command line: :param device: Unix device where the PLM is attached :param address: Insteon address of the device to link with :param group: Insteon group for the link :param: linkcode Link direction: 0 - PLM is responder 1 - PLM is controller 3 - IM is responder or controller' :param verbose: Show debug logging.
entailment
def interactive(): """Create an interactive command line tool. Wrapper for an interactive session for manual commands to be entered. """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--device', default='/dev/ttyUSB0', help='Path to PLM device') parser.add_argument('-v', '--verbose', action='count', help='Set logging level to verbose') parser.add_argument('-l', '--logfile', default='', help='Log file name') parser.add_argument('--workdir', default='', help='Working directory for reading and saving ' 'device information.') args = parser.parse_args() loop = asyncio.get_event_loop() cmd = Commander(loop, args) cmd.start() try: loop.run_forever() except KeyboardInterrupt: if cmd.tools.plm: if cmd.tools.plm.transport: # _LOGGING.info('Closing the session') cmd.tools.plm.transport.close() loop.stop() pending = asyncio.Task.all_tasks(loop=loop) for task in pending: task.cancel() try: loop.run_until_complete(task) except asyncio.CancelledError: pass except KeyboardInterrupt: pass loop.close()
Create an interactive command line tool. Wrapper for an interactive session for manual commands to be entered.
entailment
async def connect(self, poll_devices=False, device=None, workdir=None): """Connect to the IM.""" await self.aldb_load_lock.acquire() device = self.host if self.host else self.device _LOGGING.info('Connecting to Insteon Modem at %s', device) self.device = device if device else self.device self.workdir = workdir if workdir else self.workdir conn = await insteonplm.Connection.create( device=self.device, host=self.host, port=self.port, username=self.username, password=self.password, loop=self.loop, poll_devices=poll_devices, workdir=self.workdir) _LOGGING.info('Connecton made to Insteon Modem at %s', device) conn.protocol.add_device_callback(self.async_new_device_callback) conn.protocol.add_all_link_done_callback( self.async_aldb_loaded_callback) self.plm = conn.protocol await self.aldb_load_lock if self.aldb_load_lock.locked(): self.aldb_load_lock.release()
Connect to the IM.
entailment
async def monitor_mode(self, poll_devices=False, device=None, workdir=None): """Place the IM in monitoring mode.""" print("Running monitor mode") await self.connect(poll_devices, device, workdir) self.plm.monitor_mode()
Place the IM in monitoring mode.
entailment
def async_new_device_callback(self, device): """Log that our new device callback worked.""" _LOGGING.info( 'New Device: %s cat: 0x%02x subcat: 0x%02x desc: %s, model: %s', device.id, device.cat, device.subcat, device.description, device.model) for state in device.states: device.states[state].register_updates( self.async_state_change_callback)
Log that our new device callback worked.
entailment
def async_state_change_callback(self, addr, state, value): """Log the state change.""" _LOGGING.info('Device %s state %s value is changed to %s', addr, state, value)
Log the state change.
entailment
def async_aldb_loaded_callback(self): """Unlock the ALDB load lock when loading is complete.""" if self.aldb_load_lock.locked(): self.aldb_load_lock.release() _LOGGING.info('ALDB Loaded')
Unlock the ALDB load lock when loading is complete.
entailment
async def start_all_linking(self, linkcode, group, address=None): """Start the All-Linking process with the IM and device.""" _LOGGING.info('Starting the All-Linking process') if address: linkdevice = self.plm.devices[Address(address).id] if not linkdevice: linkdevice = create(self.plm, address, None, None) _LOGGING.info('Attempting to link the PLM to device %s. ', address) self.plm.start_all_linking(linkcode, group) asyncio.sleep(.5, loop=self.loop) linkdevice.enter_linking_mode(group=group) else: _LOGGING.info('Starting All-Linking on PLM. ' 'Waiting for button press') self.plm.start_all_linking(linkcode, group) await asyncio.sleep(self.wait_time, loop=self.loop) _LOGGING.info('%d devices added to the All-Link Database', len(self.plm.devices)) await asyncio.sleep(.1, loop=self.loop)
Start the All-Linking process with the IM and device.
entailment
def list_devices(self): """List devices in the ALDB.""" if self.plm.devices: for addr in self.plm.devices: device = self.plm.devices[addr] if device.address.is_x10: _LOGGING.info('Device: %s %s', device.address.human, device.description) else: _LOGGING.info('Device: %s cat: 0x%02x subcat: 0x%02x ' 'desc: %s, model: %s', device.address.human, device.cat, device.subcat, device.description, device.model) else: _LOGGING.info('No devices found') if not self.plm.transport: _LOGGING.info('IM connection has not been made.') _LOGGING.info('Use `connect [device]` to open the connection')
List devices in the ALDB.
entailment
def print_device_aldb(self, addr): """Diplay the All-Link database for a device.""" if Address(addr).id == self.plm.address.id: device = self.plm else: dev_addr = Address(addr) device = self.plm.devices[dev_addr.id] if device: if device.aldb.status in [ALDBStatus.LOADED, ALDBStatus.PARTIAL]: if device.aldb.status == ALDBStatus.PARTIAL: _LOGGING.info('ALDB partially loaded for device %s', addr) for mem_addr in device.aldb: record = device.aldb[mem_addr] _LOGGING.debug('mem_addr: %s', mem_addr) _LOGGING.info('ALDB record: %s', record) else: _LOGGING.info('ALDB not loaded. ' 'Use `load_aldb %s` first.', device.address.id) else: _LOGGING.info('Device not found.')
Diplay the All-Link database for a device.
entailment
def print_all_aldb(self): """Diplay the All-Link database for all devices.""" addr = self.plm.address.id _LOGGING.info('ALDB for PLM device %s', addr) self.print_device_aldb(addr) if self.plm.devices: for addr in self.plm.devices: _LOGGING.info('ALDB for device %s', addr) self.print_device_aldb(addr) else: _LOGGING.info('No devices found') if not self.plm.transport: _LOGGING.info('IM connection has not been made.') _LOGGING.info('Use `connect [device]` to open the connection')
Diplay the All-Link database for all devices.
entailment
async def load_device_aldb(self, addr, clear=True): """Read the device ALDB.""" dev_addr = Address(addr) device = None if dev_addr == self.plm.address: device = self.plm else: device = self.plm.devices[dev_addr.id] if device: if clear: device.aldb.clear() device.read_aldb() await asyncio.sleep(1, loop=self.loop) while device.aldb.status == ALDBStatus.LOADING: await asyncio.sleep(1, loop=self.loop) if device.aldb.status == ALDBStatus.LOADED: _LOGGING.info('ALDB loaded for device %s', addr) self.print_device_aldb(addr) else: _LOGGING.error('Could not find device %s', addr)
Read the device ALDB.
entailment
async def load_all_aldb(self, clear=True): """Read all devices ALDB.""" for addr in self.plm.devices: await self.load_device_aldb(addr, clear)
Read all devices ALDB.
entailment
async def write_aldb(self, addr, mem_addr: int, mode: str, group: int, target, data1=0x00, data2=0x00, data3=0x00): """Write a device All-Link record.""" dev_addr = Address(addr) target_addr = Address(target) device = self.plm.devices[dev_addr.id] if device: _LOGGING.debug('calling device write_aldb') device.write_aldb(mem_addr, mode, group, target_addr, data1, data2, data3) await asyncio.sleep(1, loop=self.loop) while device.aldb.status == ALDBStatus.LOADING: await asyncio.sleep(1, loop=self.loop) self.print_device_aldb(addr)
Write a device All-Link record.
entailment
async def del_aldb(self, addr, mem_addr: int): """Write a device All-Link record.""" dev_addr = Address(addr) device = self.plm.devices[dev_addr.id] if device: _LOGGING.debug('calling device del_aldb') device.del_aldb(mem_addr) await asyncio.sleep(1, loop=self.loop) while device.aldb.status == ALDBStatus.LOADING: await asyncio.sleep(1, loop=self.loop) self.print_device_aldb(addr)
Write a device All-Link record.
entailment
def add_device_override(self, addr, cat, subcat, firmware=None): """Add a device override to the PLM.""" self.plm.devices.add_override(addr, 'cat', cat) self.plm.devices.add_override(addr, 'subcat', subcat) if firmware: self.plm.devices.add_override(addr, 'firmware', firmware)
Add a device override to the PLM.
entailment
def add_x10_device(self, housecode, unitcode, dev_type): """Add an X10 device to the PLM.""" device = None try: device = self.plm.devices.add_x10_device(self.plm, housecode, unitcode, dev_type) except ValueError: pass return device
Add an X10 device to the PLM.
entailment
def kpl_status(self, address, group): """Get the status of a KPL button.""" addr = Address(address) device = self.plm.devices[addr.id] device.states[group].async_refresh_state()
Get the status of a KPL button.
entailment
def kpl_on(self, address, group): """Get the status of a KPL button.""" addr = Address(address) device = self.plm.devices[addr.id] device.states[group].on()
Get the status of a KPL button.
entailment
def kpl_off(self, address, group): """Get the status of a KPL button.""" addr = Address(address) device = self.plm.devices[addr.id] device.states[group].off()
Get the status of a KPL button.
entailment
def kpl_set_on_mask(self, address, group, mask): """Get the status of a KPL button.""" addr = Address(address) device = self.plm.devices[addr.id] device.states[group].set_on_mask(mask)
Get the status of a KPL button.
entailment
def start(self): """Start the command process loop.""" self.loop.create_task(self._read_line()) self.loop.create_task(self._greeting())
Start the command process loop.
entailment
async def do_connect(self, args): """Connect to the PLM device. Usage: connect [device [workdir]] Arguments: device: PLM device (default /dev/ttyUSB0) workdir: Working directory to save and load device information """ params = args.split() device = '/dev/ttyUSB0' workdir = None try: device = params[0] except IndexError: if self.tools.device: device = self.tools.device try: workdir = params[1] except IndexError: if self.tools.workdir: workdir = self.tools.workdir if device: await self.tools.connect(False, device=device, workdir=workdir) _LOGGING.info('Connection complete.')
Connect to the PLM device. Usage: connect [device [workdir]] Arguments: device: PLM device (default /dev/ttyUSB0) workdir: Working directory to save and load device information
entailment
def do_running_tasks(self, arg): """List tasks running in the background. Usage: running_tasks Arguments: """ for task in asyncio.Task.all_tasks(loop=self.loop): _LOGGING.info(task)
List tasks running in the background. Usage: running_tasks Arguments:
entailment
def do_add_all_link(self, args): """Add an All-Link record to the IM and a device. Usage: add_all_link [linkcode] [group] [address] Arguments: linkcode: 0 - PLM is responder 1 - PLM is controller 3 - PLM is controller or responder Default 1 group: All-Link group number (0 - 255). Default 0. address: INSTEON device to link with (not supported by all devices) """ linkcode = 1 group = 0 addr = None params = args.split() if params: try: linkcode = int(params[0]) except IndexError: linkcode = 1 except ValueError: linkcode = None try: group = int(params[1]) except IndexError: group = 0 except ValueError: group = None try: addr = params[2] except IndexError: addr = None if linkcode in [0, 1, 3] and 255 >= group >= 0: self.loop.create_task( self.tools.start_all_linking(linkcode, group, addr)) else: _LOGGING.error('Link code %d or group number %d not valid', linkcode, group) self.do_help('add_all_link')
Add an All-Link record to the IM and a device. Usage: add_all_link [linkcode] [group] [address] Arguments: linkcode: 0 - PLM is responder 1 - PLM is controller 3 - PLM is controller or responder Default 1 group: All-Link group number (0 - 255). Default 0. address: INSTEON device to link with (not supported by all devices)
entailment
def do_print_aldb(self, args): """Print the All-Link database for a device. Usage: print_aldb address|plm|all Arguments: address: INSTEON address of the device plm: Print the All-Link database for the PLM all: Print the All-Link database for all devices This method requires that the device ALDB has been loaded. To load the device ALDB use the command: load_aldb address|plm|all """ params = args.split() addr = None try: addr = params[0] except IndexError: _LOGGING.error('Device address required.') self.do_help('print_aldb') if addr: if addr.lower() == 'all': self.tools.print_all_aldb() elif addr.lower() == 'plm': addr = self.tools.plm.address.id self.tools.print_device_aldb(addr) else: self.tools.print_device_aldb(addr)
Print the All-Link database for a device. Usage: print_aldb address|plm|all Arguments: address: INSTEON address of the device plm: Print the All-Link database for the PLM all: Print the All-Link database for all devices This method requires that the device ALDB has been loaded. To load the device ALDB use the command: load_aldb address|plm|all
entailment
def do_set_hub_connection(self, args): """Set Hub connection parameters. Usage: set_hub_connection username password host [port] Arguments: username: Hub username password: Hub password host: host name or IP address port: IP port [default 25105] """ params = args.split() username = None password = None host = None port = None try: username = params[0] password = params[1] host = params[2] port = params[3] except IndexError: pass if username and password and host: if not port: port = 25105 self.tools.username = username self.tools.password = password self.tools.host = host self.tools.port = port else: _LOGGING.error('username password host are required') self.do_help('set_hub_connection')
Set Hub connection parameters. Usage: set_hub_connection username password host [port] Arguments: username: Hub username password: Hub password host: host name or IP address port: IP port [default 25105]
entailment
def do_set_log_file(self, args): """Set the log file. Usage: set_log_file filename Parameters: filename: log file name to write to THIS CAN ONLY BE CALLED ONCE AND MUST BE CALLED BEFORE ANY LOGGING STARTS. """ params = args.split() try: filename = params[0] logging.basicConfig(filename=filename) except IndexError: self.do_help('set_log_file')
Set the log file. Usage: set_log_file filename Parameters: filename: log file name to write to THIS CAN ONLY BE CALLED ONCE AND MUST BE CALLED BEFORE ANY LOGGING STARTS.
entailment
async def do_load_aldb(self, args): """Load the All-Link database for a device. Usage: load_aldb address|all [clear_prior] Arguments: address: NSTEON address of the device all: Load the All-Link database for all devices clear_prior: y|n y - Clear the prior data and start fresh. n - Keep the prior data and only apply changes Default is y This does NOT write to the database so no changes are made to the device with this command. """ params = args.split() addr = None clear = True try: addr = params[0] except IndexError: _LOGGING.error('Device address required.') self.do_help('load_aldb') try: clear_prior = params[1] _LOGGING.info('param clear_prior %s', clear_prior) if clear_prior.lower() == 'y': clear = True elif clear_prior.lower() == 'n': clear = False else: _LOGGING.error('Invalid value for parameter `clear_prior`') _LOGGING.error('Valid values are `y` or `n`') except IndexError: pass if addr: if addr.lower() == 'all': await self.tools.load_all_aldb(clear) else: await self.tools.load_device_aldb(addr, clear) else: self.do_help('load_aldb')
Load the All-Link database for a device. Usage: load_aldb address|all [clear_prior] Arguments: address: NSTEON address of the device all: Load the All-Link database for all devices clear_prior: y|n y - Clear the prior data and start fresh. n - Keep the prior data and only apply changes Default is y This does NOT write to the database so no changes are made to the device with this command.
entailment
async def do_write_aldb(self, args): """Write device All-Link record. WARNING THIS METHOD CAN DAMAGE YOUR DEVICE IF USED INCORRECTLY. Please ensure the memory id is appropriate for the device. You must load the ALDB of the device before using this method. The memory id must be an existing memory id in the ALDB or this method will return an error. If you are looking to create a new link between two devices, use the `link_devices` command or the `start_all_linking` command. Usage: write_aldb addr memory mode group target [data1 data2 data3] Required Parameters: addr: Inseon address of the device to write memory: record ID of the record to write (i.e. 0fff) mode: r | c r = Device is a responder of target c = Device is a controller of target group: All-Link group integer target: Insteon address of the link target device Optional Parameters: data1: int = Device sepcific data2: int = Device specific data3: int = Device specific """ params = args.split() addr = None mem_bytes = None memory = None mode = None group = None target = None data1 = 0x00 data2 = 0x00 data3 = 0x00 try: addr = Address(params[0]) mem_bytes = binascii.unhexlify(params[1]) memory = int.from_bytes(mem_bytes, byteorder='big') mode = params[2] group = int(params[3]) target = Address(params[4]) _LOGGING.info('address: %s', addr) _LOGGING.info('memory: %04x', memory) _LOGGING.info('mode: %s', mode) _LOGGING.info('group: %d', group) _LOGGING.info('target: %s', target) except IndexError: _LOGGING.error('Device address memory mode group and target ' 'are all required.') self.do_help('write_aldb') except ValueError: _LOGGING.error('Value error - Check parameters') self.do_help('write_aldb') try: data1 = int(params[5]) data2 = int(params[6]) data3 = int(params[7]) except IndexError: pass except ValueError: addr = None _LOGGING.error('Value error - Check parameters') self.do_help('write_aldb') return if addr and memory and mode and isinstance(group, int) and target: await self.tools.write_aldb(addr, memory, mode, group, target, data1, data2, data3)
Write device All-Link record. WARNING THIS METHOD CAN DAMAGE YOUR DEVICE IF USED INCORRECTLY. Please ensure the memory id is appropriate for the device. You must load the ALDB of the device before using this method. The memory id must be an existing memory id in the ALDB or this method will return an error. If you are looking to create a new link between two devices, use the `link_devices` command or the `start_all_linking` command. Usage: write_aldb addr memory mode group target [data1 data2 data3] Required Parameters: addr: Inseon address of the device to write memory: record ID of the record to write (i.e. 0fff) mode: r | c r = Device is a responder of target c = Device is a controller of target group: All-Link group integer target: Insteon address of the link target device Optional Parameters: data1: int = Device sepcific data2: int = Device specific data3: int = Device specific
entailment
async def do_del_aldb(self, args): """Delete device All-Link record. WARNING THIS METHOD CAN DAMAGE YOUR DEVICE IF USED INCORRECTLY. Please ensure the memory id is appropriate for the device. You must load the ALDB of the device before using this method. The memory id must be an existing memory id in the ALDB or this method will return an error. If you are looking to create a new link between two devices, use the `link_devices` command or the `start_all_linking` command. Usage: del_aldb addr memory Required Parameters: addr: Inseon address of the device to write memory: record ID of the record to write (i.e. 0fff) """ params = args.split() addr = None mem_bytes = None memory = None try: addr = Address(params[0]) mem_bytes = binascii.unhexlify(params[1]) memory = int.from_bytes(mem_bytes, byteorder='big') _LOGGING.info('address: %s', addr) _LOGGING.info('memory: %04x', memory) except IndexError: _LOGGING.error('Device address and memory are required.') self.do_help('del_aldb') except ValueError: _LOGGING.error('Value error - Check parameters') self.do_help('write_aldb') if addr and memory: await self.tools.del_aldb(addr, memory)
Delete device All-Link record. WARNING THIS METHOD CAN DAMAGE YOUR DEVICE IF USED INCORRECTLY. Please ensure the memory id is appropriate for the device. You must load the ALDB of the device before using this method. The memory id must be an existing memory id in the ALDB or this method will return an error. If you are looking to create a new link between two devices, use the `link_devices` command or the `start_all_linking` command. Usage: del_aldb addr memory Required Parameters: addr: Inseon address of the device to write memory: record ID of the record to write (i.e. 0fff)
entailment