idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
39,300
def get_engine_version ( self ) : msg = StandardSend ( self . _address , COMMAND_GET_INSTEON_ENGINE_VERSION_0X0D_0X00 ) self . _send_msg ( msg )
Get the device engine version .
39,301
def ping ( self ) : msg = StandardSend ( self . _address , COMMAND_PING_0X0F_0X00 ) self . _send_msg ( msg )
Ping a device .
39,302
def create_default_links ( self ) : self . _plm . manage_aldb_record ( 0x40 , 0xe2 , 0x00 , self . address , self . cat , self . subcat , self . product_key ) self . manage_aldb_record ( 0x41 , 0xa2 , 0x00 , self . _plm . address , self . _plm . cat , self . _plm . subcat , self . _plm . product_key ) for link in self . _stateList : state = self . _stateList [ link ] if state . is_responder : self . _plm . manage_aldb_record ( 0x40 , 0xe2 , link , self . _address , 0x00 , 0x00 , 0x00 ) self . manage_aldb_record ( 0x41 , 0xa2 , link , self . _plm . address , state . linkdata1 , state . linkdata2 , state . linkdata3 ) if state . is_controller : self . _plm . manage_aldb_record ( 0x41 , 0xa2 , link , self . _address , 0x00 , 0x00 , 0x00 ) self . manage_aldb_record ( 0x40 , 0xe2 , link , self . _plm . address , 0x00 , 0x00 , 0x00 ) self . read_aldb ( )
Create the default links between the IM and the device .
39,303
def read_aldb ( self , mem_addr = 0x0000 , num_recs = 0 ) : if self . _aldb . version == ALDBVersion . Null : _LOGGER . info ( 'Device %s does not contain an All-Link Database' , self . _address . human ) else : _LOGGER . info ( 'Reading All-Link Database for device %s' , self . _address . human ) asyncio . ensure_future ( self . _aldb . load ( mem_addr , num_recs ) , loop = self . _plm . loop ) self . _aldb . add_loaded_callback ( self . _aldb_loaded_callback )
Read the device All - Link Database .
39,304
def write_aldb ( self , mem_addr : int , mode : str , group : int , target , data1 = 0x00 , data2 = 0x00 , data3 = 0x00 ) : 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 .
39,305
def del_aldb ( self , mem_addr : int ) : self . _aldb . del_record ( mem_addr ) self . _aldb . add_loaded_callback ( self . _aldb_loaded_callback )
Delete an All - Link Database record .
39,306
def _refresh_aldb_records ( self , linkcode , address , group ) : 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 .
39,307
def receive_message ( self , msg ) : _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 .
39,308
def receive_message ( self , msg ) : _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 .
39,309
def add ( self , plm , device , stateType , stateName , group , defaultValue = None ) : self . _stateList [ group ] = stateType ( plm , device , stateName , group , defaultValue = defaultValue )
Add a state to the StateList .
39,310
def create_from_userdata ( userdata ) : 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 .
39,311
def to_userdata ( self ) : 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 .
39,312
def byte ( self ) : 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 .
39,313
def create_from_byte ( control_flags ) : 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 .
39,314
def add_loaded_callback ( self , callback ) : 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 .
39,315
async def load ( self , mem_addr = 0x0000 , rec_count = 0 , retry = 0 ) : 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 .
39,316
def find_matching_link ( self , mode , group , addr ) : 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 .
39,317
def record_received ( self , msg ) : 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 .
39,318
def load_saved_records ( self , status , 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 .
39,319
def _set_load_action ( self , mem_addr , rec_count , retries , read_complete = False ) : 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 .
39,320
def register_updates ( self , callback ) : _LOGGER . debug ( "Registered callback for state: %s" , self . _stateName ) self . _observer_callbacks . append ( callback )
Register a callback to notify a listener of state changes .
39,321
def _update_subscribers ( self , val ) : self . _value = val for callback in self . _observer_callbacks : callback ( self . _address , self . _group , val )
Save state value and notify listeners of the change .
39,322
def template ( cls , address = None , target = None , commandtuple = None , userdata = None , cmd2 = - 1 , flags = None ) : 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 .
39,323
def targetLow ( self ) : 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 .
39,324
def set_level ( self , val ) : 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 .
39,325
def set_level ( self , val ) : 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 .
39,326
def open ( self ) : 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 .
39,327
def open_fast ( self ) : 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 .
39,328
def async_refresh_state ( self ) : _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 .
39,329
def byte_to_housecode ( bytecode ) : hc = list ( HC_LOOKUP . keys ( ) ) [ list ( HC_LOOKUP . values ( ) ) . index ( bytecode ) ] return hc . upper ( )
Return an X10 housecode value from a byte value .
39,330
def byte_to_unitcode ( bytecode ) : return list ( UC_LOOKUP . keys ( ) ) [ list ( UC_LOOKUP . values ( ) ) . index ( bytecode ) ]
Return an X10 unitcode value from a byte value .
39,331
def x10_command_type ( 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 .
39,332
def set_bit ( bitmask , bit , is_on ) : 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 .
39,333
def template ( cls , address = None , commandtuple = None , userdata = None , cmd2 = - 1 , flags = None , acknak = None ) : 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 .
39,334
def set_checksum ( self ) : 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 .
39,335
def from_raw_message ( cls , rawmessage ) : return StandardReceive ( rawmessage [ 2 : 5 ] , rawmessage [ 5 : 8 ] , { 'cmd1' : rawmessage [ 9 ] , 'cmd2' : rawmessage [ 10 ] } , flags = rawmessage [ 8 ] )
Create message from a raw byte stream .
39,336
def targetMed ( self ) : 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 .
39,337
def targetHi ( self ) : 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 .
39,338
def create ( rawmessage ) : 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 ) : ] return ( msg , remaining_data )
Return an INSTEON message class based on a raw byte stream .
39,339
def iscomplete ( rawmessage ) : 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 .
39,340
def _get_msg_class ( 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 .
39,341
def _trim_buffer_garbage ( rawmessage , debug = True ) : 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 .
39,342
def matches_pattern ( self , other ) : 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 .
39,343
def get_properties ( cls ) : property_names = [ p for p in dir ( cls ) if isinstance ( getattr ( cls , p ) , property ) ] return property_names
Get all properties of the MessageFlags class .
39,344
def isDirect ( self ) : direct = ( self . _messageType == 0x00 ) if self . isDirectACK or self . isDirectNAK : direct = True return direct
Test if the message is a direct message type .
39,345
def create ( cls , messageType , extended , hopsleft = 3 , hopsmax = 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 .
39,346
def bytes ( self ) : 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 .
39,347
def _normalize ( self , flags ) : 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 .
39,348
def _set_properties ( self , flags ) : 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 .
39,349
def set_value ( self , dry_wet : LeakSensorState ) : 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 .
39,350
def _dry_wet_message_received ( self , msg ) : for callback in self . _dry_wet_callbacks : callback ( self . _dry_wet_type ) self . _update_subscribers ( 0x01 )
Report a dry or a wet state .
39,351
def set_value ( self , dry_wet : LeakSensorState ) : if dry_wet == LeakSensorState . DRY : self . _update_subscribers ( 0x11 ) else : self . _update_subscribers ( 0x13 )
Set the state to wet or dry .
39,352
def _dry_message_received ( self , msg ) : for callback in self . _dry_wet_callbacks : callback ( LeakSensorState . DRY ) self . _update_subscribers ( 0x11 )
Report a dry state .
39,353
def _wet_message_received ( self , msg ) : for callback in self . _dry_wet_callbacks : callback ( LeakSensorState . WET ) self . _update_subscribers ( 0x13 )
Report a wet state .
39,354
def add ( self , msg , callback , override = 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 .
39,355
def remove ( self , msg , callback ) : 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 .
39,356
def get_callbacks_from_message ( self , msg ) : 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 .
39,357
def x10 ( self , feature ) : 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 .
39,358
def interactive ( ) : 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 : 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 .
39,359
async def connect ( self , poll_devices = False , device = None , workdir = None ) : 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 .
39,360
async def monitor_mode ( self , poll_devices = False , device = None , workdir = None ) : print ( "Running monitor mode" ) await self . connect ( poll_devices , device , workdir ) self . plm . monitor_mode ( )
Place the IM in monitoring mode .
39,361
def async_new_device_callback ( self , device ) : _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 .
39,362
def async_state_change_callback ( self , addr , state , value ) : _LOGGING . info ( 'Device %s state %s value is changed to %s' , addr , state , value )
Log the state change .
39,363
def async_aldb_loaded_callback ( self ) : if self . aldb_load_lock . locked ( ) : self . aldb_load_lock . release ( ) _LOGGING . info ( 'ALDB Loaded' )
Unlock the ALDB load lock when loading is complete .
39,364
async def start_all_linking ( self , linkcode , group , address = None ) : _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 .
39,365
def list_devices ( self ) : 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 .
39,366
def print_device_aldb ( self , addr ) : 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 .
39,367
def print_all_aldb ( self ) : 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 .
39,368
async def load_device_aldb ( self , addr , clear = True ) : 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 .
39,369
async def load_all_aldb ( self , clear = True ) : for addr in self . plm . devices : await self . load_device_aldb ( addr , clear )
Read all devices ALDB .
39,370
def add_device_override ( self , addr , cat , subcat , firmware = None ) : 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 .
39,371
def add_x10_device ( self , housecode , unitcode , dev_type ) : 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 .
39,372
def start ( self ) : self . loop . create_task ( self . _read_line ( ) ) self . loop . create_task ( self . _greeting ( ) )
Start the command process loop .
39,373
async def do_connect ( self , args ) : 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 .
39,374
def do_running_tasks ( self , arg ) : for task in asyncio . Task . all_tasks ( loop = self . loop ) : _LOGGING . info ( task )
List tasks running in the background .
39,375
def do_add_all_link ( self , args ) : 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 .
39,376
def do_print_aldb ( self , args ) : 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 .
39,377
def do_set_hub_connection ( self , args ) : 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 .
39,378
def do_set_log_file ( self , args ) : params = args . split ( ) try : filename = params [ 0 ] logging . basicConfig ( filename = filename ) except IndexError : self . do_help ( 'set_log_file' )
Set the log file .
39,379
async def do_load_aldb ( self , args ) : 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 .
39,380
async def do_write_aldb ( self , args ) : 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 .
39,381
async def do_del_aldb ( self , args ) : 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 .
39,382
def do_set_log_level ( self , arg ) : if arg in [ 'i' , 'v' ] : _LOGGING . info ( 'Setting log level to %s' , arg ) if arg == 'i' : _LOGGING . setLevel ( logging . INFO ) _INSTEONPLM_LOGGING . setLevel ( logging . INFO ) else : _LOGGING . setLevel ( logging . DEBUG ) _INSTEONPLM_LOGGING . setLevel ( logging . DEBUG ) else : _LOGGING . error ( 'Log level value error.' ) self . do_help ( 'set_log_level' )
Set the log level .
39,383
def do_set_device ( self , args ) : params = args . split ( ) device = None try : device = params [ 0 ] except IndexError : _LOGGING . error ( 'Device name required.' ) self . do_help ( 'set_device' ) if device : self . tools . device = device
Set the PLM OS device .
39,384
def do_set_workdir ( self , args ) : params = args . split ( ) workdir = None try : workdir = params [ 0 ] except IndexError : _LOGGING . error ( 'Device name required.' ) self . do_help ( 'set_workdir' ) if workdir : self . tools . workdir = workdir
Set the working directory .
39,385
def do_help ( self , arg ) : cmds = arg . split ( ) if cmds : func = getattr ( self , 'do_{}' . format ( cmds [ 0 ] ) ) if func : _LOGGING . info ( func . __doc__ ) else : _LOGGING . error ( 'Command %s not found' , cmds [ 0 ] ) else : _LOGGING . info ( "Available command list: " ) for curr_cmd in dir ( self . __class__ ) : if curr_cmd . startswith ( "do_" ) and not curr_cmd == 'do_test' : print ( " - " , curr_cmd [ 3 : ] ) _LOGGING . info ( "For help with a command type `help command`" )
Help command .
39,386
def do_add_device_override ( self , args ) : params = args . split ( ) addr = None cat = None subcat = None firmware = None error = None try : addr = Address ( params [ 0 ] ) cat = binascii . unhexlify ( params [ 1 ] [ 2 : ] ) subcat = binascii . unhexlify ( params [ 2 ] [ 2 : ] ) firmware = binascii . unhexlify ( params [ 3 ] [ 2 : ] ) except IndexError : error = 'missing' except ValueError : error = 'value' if addr and cat and subcat : self . tools . add_device_override ( addr , cat , subcat , firmware ) else : if error == 'missing' : _LOGGING . error ( 'Device address, category and subcategory are ' 'required.' ) else : _LOGGING . error ( 'Check the vales for address, category and ' 'subcategory.' ) self . do_help ( 'add_device_override' )
Add a device override to the IM .
39,387
def do_add_x10_device ( self , args ) : params = args . split ( ) housecode = None unitcode = None dev_type = None try : housecode = params [ 0 ] unitcode = int ( params [ 1 ] ) if unitcode not in range ( 1 , 17 ) : raise ValueError dev_type = params [ 2 ] except IndexError : pass except ValueError : _LOGGING . error ( 'X10 unit code must be an integer 1 - 16' ) unitcode = None if housecode and unitcode and dev_type : device = self . tools . add_x10_device ( housecode , unitcode , dev_type ) if not device : _LOGGING . error ( 'Device not added. Please check the ' 'information you provided.' ) self . do_help ( 'add_x10_device' ) else : _LOGGING . error ( 'Device housecode, unitcode and type are ' 'required.' ) self . do_help ( 'add_x10_device' )
Add an X10 device to the IM .
39,388
def do_kpl_status ( self , args ) : params = args . split ( ) address = None group = None try : address = params [ 0 ] group = int ( params [ 1 ] ) except IndexError : _LOGGING . error ( "Address and group are regquired" ) self . do_help ( 'kpl_status' ) except TypeError : _LOGGING . error ( "Group must be an integer" ) self . do_help ( 'kpl_status' ) if address and group : self . tools . kpl_status ( address , group )
Get the status of a KeypadLinc button .
39,389
def do_kpl_on ( self , args ) : params = args . split ( ) address = None group = None try : address = params [ 0 ] group = int ( params [ 1 ] ) except IndexError : _LOGGING . error ( "Address and group are regquired" ) self . do_help ( 'kpl_status' ) except TypeError : _LOGGING . error ( "Group must be an integer" ) self . do_help ( 'kpl_status' ) if address and group : self . tools . kpl_on ( address , group )
Turn on a KeypadLinc button .
39,390
def do_kpl_off ( self , args ) : params = args . split ( ) address = None group = None try : address = params [ 0 ] group = int ( params [ 1 ] ) except IndexError : _LOGGING . error ( "Address and group are regquired" ) self . do_help ( 'kpl_status' ) except TypeError : _LOGGING . error ( "Group must be an integer" ) self . do_help ( 'kpl_status' ) if address and group : self . tools . kpl_off ( address , group )
Turn off a KeypadLinc button .
39,391
def do_kpl_set_on_mask ( self , args ) : params = args . split ( ) address = None group = None mask_string = None mask = None try : address = params [ 0 ] group = int ( params [ 1 ] ) mask_string = params [ 2 ] if mask_string [ 0 : 2 ] . lower ( ) == '0x' : mask = binascii . unhexlify ( mask_string [ 2 : ] ) else : mask = int ( mask_string ) except IndexError : _LOGGING . error ( "Address, group and mask are regquired" ) self . do_help ( 'kpl_status' ) except TypeError : _LOGGING . error ( "Group must be an integer" ) self . do_help ( 'kpl_status' ) if address and group and mask : self . tools . kpl_set_on_mask ( address , group , mask )
Set the on mask for a KeypadLinc button .
39,392
def from_raw_message ( cls , rawmessage ) : empty = cls . create_empty ( 0x00 ) userdata_dict = cls . normalize ( empty , rawmessage ) return Userdata ( userdata_dict )
Create a user data instance from a raw byte stream .
39,393
def create_pattern ( cls , userdata ) : empty = cls . create_empty ( None ) userdata_dict = cls . normalize ( empty , userdata ) return Userdata ( userdata_dict )
Create a user data instance with all values the same .
39,394
def template ( cls , userdata ) : ud = Userdata ( cls . normalize ( cls . create_empty ( None ) , userdata ) ) return ud
Create a template instance used for message callbacks .
39,395
def matches_pattern ( self , other ) : ismatch = False if isinstance ( other , Userdata ) : for key in self . _userdata : if self . _userdata [ key ] is None or other [ key ] is None : ismatch = True elif self . _userdata [ key ] == other [ key ] : ismatch = True else : ismatch = False break return ismatch
Test if the current instance matches a template instance .
39,396
def create_empty ( cls , val = 0x00 ) : userdata_dict = { } for i in range ( 1 , 15 ) : key = 'd{}' . format ( i ) userdata_dict . update ( { key : val } ) return userdata_dict
Create an empty Userdata object .
39,397
def normalize ( cls , empty , userdata ) : if isinstance ( userdata , Userdata ) : return userdata . to_dict ( ) if isinstance ( userdata , dict ) : return cls . _dict_to_dict ( empty , userdata ) if isinstance ( userdata , ( bytes , bytearray ) ) : return cls . _bytes_to_dict ( empty , userdata ) if userdata is None : return empty raise ValueError
Return normalized user data as a dictionary .
39,398
def hex ( self ) : props = self . _message_properties ( ) msg = bytearray ( [ MESSAGE_START_CODE_0X02 , self . _code ] ) for prop in props : for key , val in prop . items ( ) : if val is None : pass elif isinstance ( val , int ) : msg . append ( val ) elif isinstance ( val , Address ) : if val . addr is None : pass else : msg . extend ( val . bytes ) elif isinstance ( val , MessageFlags ) : msg . extend ( val . bytes ) elif isinstance ( val , bytearray ) : msg . extend ( val ) elif isinstance ( val , bytes ) : msg . extend ( val ) elif isinstance ( val , Userdata ) : msg . extend ( val . bytes ) return binascii . hexlify ( msg ) . decode ( )
Hexideciaml representation of the message in bytes .
39,399
def matches_pattern ( self , other ) : properties = self . _message_properties ( ) ismatch = False if isinstance ( other , Message ) and self . code == other . code : for prop in properties : for key , prop_val in prop . items ( ) : if hasattr ( other , key ) : key_val = getattr ( other , key ) ismatch = self . _test_match ( prop_val , key_val ) else : ismatch = False if not ismatch : break if not ismatch : break return ismatch
Return if the current message matches a message template .