def group_voice(self, _src_sub, _dst_group, _ts, _end, _peerid, _data): if _end: _self_peer = self._config['LOCAL']['RADIO_ID'] _self_src = _self_peer[1:] if (_peerid == _self_peer) or (_src_sub == _self_src): self._logger.error('(%s) Just received a packet that appears to have been originated by us. PeerID: %s Subscriber: %s TS: %s, TGID: %s', self._system, int_id(_peerid), int_id(_src_sub), int(_ts), int_id(_dst_group)) return if trigger == False: if (_ts == 1 and _dst_group not in trigger_groups_1) or (_ts == 2 and _dst_group not in trigger_groups_2): return else: if (_ts == 1 and _dst_group not in trigger_groups_1) or (_ts == 2 and _dst_group not in trigger_groups_2): return self._logger.info('(%s) Event ID: %s - Playback triggered from SourceID: %s, TS: %s, TGID: %s, PeerID: %s', self._system, self.event_id, int_id(_src_sub), _ts, int_id(_dst_group), int_id(_peerid)) # Determine the type of voice packet this is (see top of file for possible types) _burst_data_type = _data[30] time.sleep(2) self.CALL_DATA = pickle.load(open(filename, 'rb')) self._logger.info('(%s) Event ID: %s - Playing back file: %s', self._system, self.event_id, filename) for i in self.CALL_DATA: _tmp_data = i # re-Write the peer radio ID to that of this program _tmp_data = _tmp_data.replace(_peerid, _self_peer) # re-Write the source subscriber ID to that of this program _tmp_data = _tmp_data.replace(_src_sub, _self_src) # Re-Write the destination Group ID _tmp_data = _tmp_data.replace(_tmp_data[9:12], _dst_group) # Re-Write IPSC timeslot value _call_info = int_id(_tmp_data[17:18]) if _ts == 1: _call_info &= ~(1 << 5) elif _ts == 2: _call_info |= 1 << 5 _call_info = chr(_call_info) _tmp_data = _tmp_data[:17] + _call_info + _tmp_data[18:] # Re-Write DMR timeslot value # Determine if the slot is present, so we can translate if need be if _burst_data_type == BURST_DATA_TYPE['SLOT1_VOICE'] or _burst_data_type == BURST_DATA_TYPE['SLOT2_VOICE']: # Re-Write timeslot if necessary... if _ts == 1: _burst_data_type = BURST_DATA_TYPE['SLOT1_VOICE'] elif _ts == 2: _burst_data_type = BURST_DATA_TYPE['SLOT2_VOICE'] _tmp_data = _tmp_data[:30] + _burst_data_type + _tmp_data[31:] # Send the packet to all peers in the target IPSC self.send_to_ipsc(_tmp_data) time.sleep(0.06) self.CALL_DATA = [] self._logger.info('(%s) Event ID: %s - Playback Completed', self._system, self.event_id) self.event_id = self.event_id + 1
def print_peer_list(_config, _network): _peers = _config['SYSTEMS'][_network]['PEERS'] _status = _config['SYSTEMS'][_network]['MASTER']['STATUS']['PEER_LIST'] #print('Peer List Status for {}: {}' .format(_network, _status)) if _status and not _config['SYSTEMS'][_network]['PEERS']: print('We are the only peer for: %s' % _network) print('') return print('Peer List for: %s' % _network) for peer in _peers.keys(): _this_peer = _peers[peer] _this_peer_stat = _this_peer['STATUS'] if peer == _config['SYSTEMS'][_network]['LOCAL']['RADIO_ID']: me = '(self)' else: me = '' print('\tRADIO ID: {} {}' .format(int_id(peer), me)) print('\t\tIP Address: {}:{}' .format(_this_peer['IP'], _this_peer['PORT'])) if _this_peer['MODE_DECODE'] and _config['REPORTS']['PRINT_PEERS_INC_MODE']: print('\t\tMode Values:') for name, value in _this_peer['MODE_DECODE'].items(): print('\t\t\t{}: {}' .format(name, value)) if _this_peer['FLAGS_DECODE'] and _config['REPORTS']['PRINT_PEERS_INC_FLAGS']: print('\t\tService Flags:') for name, value in _this_peer['FLAGS_DECODE'].items(): print('\t\t\t{}: {}' .format(name, value)) print('\t\tStatus: {}, KeepAlives Sent: {}, KeepAlives Outstanding: {}, KeepAlives Missed: {}' .format(_this_peer_stat['CONNECTED'], _this_peer_stat['KEEP_ALIVES_SENT'], _this_peer_stat['KEEP_ALIVES_OUTSTANDING'], _this_peer_stat['KEEP_ALIVES_MISSED'])) print('\t\t KeepAlives Received: {}, Last KeepAlive Received at: {}' .format(_this_peer_stat['KEEP_ALIVES_RECEIVED'], _this_peer_stat['KEEP_ALIVE_RX_TIME'])) print('')
def readConfigFile(self, configFileName, sec, networkName='DEFAULTS'): config = ConfigParser.ConfigParser() try: config.read(configFileName) if sec == None: sec = self.defaultOption(config, 'DEFAULTS', 'section', networkName) if config.has_section(sec) == False: logger.error('Section ' + sec + ' was not found, using DEFAULTS') sec = 'DEFAULTS' self._debug = bool(self.defaultOption(config, sec,'debug', self._debug) == 'True') self._outToFile = bool(self.defaultOption(config, sec,'outToFile', self._outToFile) == 'True') self._outToUDP = bool(self.defaultOption(config, sec,'outToUDP', self._outToUDP) == 'True') self._gateway = self.defaultOption(config, sec,'gateway', self._gateway) self._gateway_port = int(self.defaultOption(config, sec,'toGatewayPort', self._gateway_port)) self._remote_control_port = int(self.defaultOption(config, sec,'remoteControlPort', self._remote_control_port)) self._ambeRxPort = int(self.defaultOption(config, sec,'fromGatewayPort', self._ambeRxPort)) self._gateway_dmr_id = int(self.defaultOption(config, sec, 'gatewayDmrId', self._gateway_dmr_id)) _tgs = self.defaultOption(config, sec,'tgFilter', str(self._tg_filter).strip('[]')) self._tg_filter = map(int, _tgs.split(',')) self._tx_tg = hex_str_3(int(self.defaultOption(config, sec, 'txTg', int_id(self._tx_tg)))) self._tx_ts = int(self.defaultOption(config, sec, 'txTs', self._tx_ts)) except ConfigParser.NoOptionError as e: print('Using a default value:', e) except: traceback.print_exc() sys.exit('Configuration file \''+configFileName+'\' is not a valid configuration file! Exiting...')
def playbackFromUDP(self, _sock): _delay = 0.055 # Yes, I know it should be 0.06, but there seems to be some latency, so this is a hack _src_sub = hex_str_3(self._gateway_dmr_id) # DMR ID to sign this transmission with _src_peer = NETWORK[self._system]['LOCAL']['RADIO_ID'] # Use this peers ID as the source repeater logger.info('Transmit from gateway to TG {}:'.format(int_id(self._tx_tg)) ) try: try: _t = open('template.bin', 'rb') # Open the template file. This was recorded OTA _tempHead = [0] * 3 # It appears that there 3 frames of HEAD (mostly the same) for i in range(0, 3): _tempHead[i] = self.readRecord(_t, BURST_DATA_TYPE['VOICE_HEAD']) _tempVoice = [0] * 6 for i in range(0, 6): # Then there are 6 frames of AMBE. We will just use them in order _tempVoice[i] = self.readRecord(_t, BURST_DATA_TYPE['SLOT2_VOICE']) _tempTerm = self.readRecord(_t, BURST_DATA_TYPE['VOICE_TERM']) _t.close() except IOError: logger.error('Can not open template.bin file') return logger.debug('IPSC templates loaded') _eof = False self._seq = randint(0,32767) # A transmission uses a random number to begin its sequence (16 bit) for i in range(0, 3): # Output the 3 HEAD frames to our peers self.rewriteFrame(_tempHead[i], self._system, self._tx_ts, self._tx_tg, _src_sub, _src_peer) #self.group_voice(self._system, _src_sub, self._tx_tg, True, '', hex_str_3(0), _tempHead[i]) sleep(_delay) i = 0 # Initialize the VOICE template index while(_eof == False): _ambe = self.readAmbeFrameFromUDP(_sock) # Read the 49*3 bit sample from the stream if _ambe: i = (i + 1) % 6 # Round robbin with the 6 VOICE templates _frame = _tempVoice[i][:33] + _ambe + _tempVoice[i][52:] # Insert the 3 49 bit AMBE frames self.rewriteFrame(_frame, self._system, self._tx_ts, self._tx_tg, _src_sub, _src_peer) #self.group_voice(self._system, _src_sub, self._tx_tg, True, '', hex_str_3(0), _frame) sleep(_delay) # Since this comes from a file we have to add delay between IPSC frames else: _eof = True # There are no more AMBE frames, so terminate the loop self.rewriteFrame(_tempTerm, self._system, self._tx_ts, self._tx_tg, _src_sub, _src_peer) #self.group_voice(self._system, _src_sub, self._tx_tg, True, '', hex_str_3(0), _tempTerm) except IOError: logger.error('Can not transmit to peers') logger.info('Transmit complete')
def launchUDP(self): s = socket.socket() # Create a socket object s.bind(('', self._ambeRxPort)) # Bind to the port while (1): # Forever! s.listen(5) # Now wait for client connection. _sock, addr = s.accept() # Establish connection with client. if int_id(self._tx_tg) > 0: # Test if we are allowed to transmit self.playbackFromUDP(_sock, self._system) else: self.transmitDisabled(_sock, self._system) #tg is zero, so just eat the network trafic _sock.close()
def call_mon_status(self, _data): if not status: return _source = _data[1:5] _ipsc_src = _data[5:9] _seq_num = _data[9:13] _ts = _data[13] _status = _data[15] # suspect [14:16] but nothing in leading byte? _rf_src = _data[16:19] _rf_tgt = _data[19:22] _type = _data[22] _prio = _data[23] _sec = _data[24] _source = str(int_id(_source)) + ', ' + str(get_alias(_source, peer_ids)) _ipsc_src = str(int_id(_ipsc_src)) + ', ' + str(get_alias(_ipsc_src, peer_ids)) _rf_src = str(int_id(_rf_src)) + ', ' + str(get_alias(_rf_src, subscriber_ids)) if _type == '\x4F' or '\x51': _rf_tgt = 'TGID: ' + str(int_id(_rf_tgt)) + ', ' + str(get_alias(_rf_tgt, talkgroup_ids)) else: _rf_tgt = 'SID: ' + str(int_id(_rf_tgt)) + ', ' + str(get_alias(_rf_tgt, subscriber_ids)) print('Call Monitor - Call Status') print('TIME: ', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) print('DATA SOURCE: ', _source) print('IPSC: ', self._system) print('IPSC Source: ', _ipsc_src) print('Timeslot: ', TS[_ts]) try: print('Status: ', STATUS[_status]) except KeyError: print('Status (unknown): ', h(_status)) try: print('Type: ', TYPE[_type]) except KeyError: print('Type (unknown): ', h(_type)) print('Source Sub: ', _rf_src) print('Target Sub: ', _rf_tgt) print()
def __init__(self, _name, _config, _logger): # Housekeeping: create references to the configuration and status data for this IPSC instance. # Some configuration objects that are used frequently and have lengthy names are shortened # such as (self._master_sock) expands to (self._config['MASTER']['IP'], self._config['MASTER']['PORT']). # Note that many of them reference each other... this is the Pythonic way. # self._system = _name self._CONFIG = _config self._logger = _logger self._config = self._CONFIG['SYSTEMS'][self._system] # self._local = self._config['LOCAL'] self._local_id = self._local['RADIO_ID'] # self._master = self._config['MASTER'] self._master_stat = self._master['STATUS'] self._master_sock = self._master['IP'], self._master['PORT'] # self._peers = self._config['PEERS'] # # This is a regular list to store peers for the IPSC. At times, parsing a simple list is much less # Spendy than iterating a list of dictionaries... Maybe I'll find a better way in the future. Also # We have to know when we have a new peer list, so a variable to indicate we do (or don't) # args = () # Packet 'constructors' - builds the necessary control packets for this IPSC instance. # This isn't really necessary for anything other than readability (reduction of code golf) # # General Items self.TS_FLAGS = (self._local['MODE'] + self._local['FLAGS']) # # Peer Link Maintenance Packets self.MASTER_REG_REQ_PKT = (MASTER_REG_REQ + self._local_id + self.TS_FLAGS + IPSC_VER) self.MASTER_ALIVE_PKT = (MASTER_ALIVE_REQ + self._local_id + self.TS_FLAGS + IPSC_VER) self.PEER_LIST_REQ_PKT = (PEER_LIST_REQ + self._local_id) self.PEER_REG_REQ_PKT = (PEER_REG_REQ + self._local_id + IPSC_VER) self.PEER_REG_REPLY_PKT = (PEER_REG_REPLY + self._local_id + IPSC_VER) self.PEER_ALIVE_REQ_PKT = (PEER_ALIVE_REQ + self._local_id + self.TS_FLAGS) self.PEER_ALIVE_REPLY_PKT = (PEER_ALIVE_REPLY + self._local_id + self.TS_FLAGS) # # Master Link Maintenance Packets # self.MASTER_REG_REPLY_PKT is not static and must be generated when it is sent self.MASTER_ALIVE_REPLY_PKT = (MASTER_ALIVE_REPLY + self._local_id + self.TS_FLAGS + IPSC_VER) self.PEER_LIST_REPLY_PKT = (PEER_LIST_REPLY + self._local_id) # # General Link Maintenance Packets self.DE_REG_REQ_PKT = (DE_REG_REQ + self._local_id) self.DE_REG_REPLY_PKT = (DE_REG_REPLY + self._local_id) # self._logger.info('(%s) IPSC Instance Created: %s, %s:%s', self._system, int_id(self._local['RADIO_ID']), self._local['IP'], self._local['PORT'])
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data): pkt_time = time() dmrpkt = _data[20:53] _bits = int_id(_data[15]) if _call_type == 'group': # Is this is a new call stream? if (_stream_id != self.STATUS[_slot]['RX_STREAM_ID']): self.STATUS['RX_START'] = pkt_time logger.info('(%s) *CALL START* STREAM ID: %s SUB: %s (%s) REPEATER: %s (%s) TGID %s (%s), TS %s', \ self._system, int_id(_stream_id), get_alias(_rf_src, subscriber_ids), int_id(_rf_src), get_alias(_peer_id, peer_ids), int_id(_peer_id), get_alias(_dst_id, talkgroup_ids), int_id(_dst_id), _slot) # Final actions - Is this a voice terminator? if (_frame_type == hb_const.HBPF_DATA_SYNC) and (_dtype_vseq == hb_const.HBPF_SLT_VTERM) and (self.STATUS[_slot]['RX_TYPE'] != hb_const.HBPF_SLT_VTERM): call_duration = pkt_time - self.STATUS['RX_START'] logger.info('(%s) *CALL END* STREAM ID: %s SUB: %s (%s) REPEATER: %s (%s) TGID %s (%s), TS %s, Duration: %s', \ self._system, int_id(_stream_id), get_alias(_rf_src, subscriber_ids), int_id(_rf_src), get_alias(_peer_id, peer_ids), int_id(_peer_id), get_alias(_dst_id, talkgroup_ids), int_id(_dst_id), _slot, call_duration) self.CALL_DATA.append(_data) sleep(2) logger.info('(%s) Playing back transmission from subscriber: %s', self._system, int_id(_rf_src)) for i in self.CALL_DATA: self.send_system(i) sleep(0.06) self.CALL_DATA = [] else: if not self.CALL_DATA: logger.info('(%s) Receiving transmission to be played back from subscriber: %s', self._system, int_id(_rf_src)) self.CALL_DATA.append(_data) # Mark status variables for use later self.STATUS[_slot]['RX_RFS'] = _rf_src self.STATUS[_slot]['RX_TYPE'] = _dtype_vseq self.STATUS[_slot]['RX_TGID'] = _dst_id self.STATUS[_slot]['RX_TIME'] = pkt_time self.STATUS[_slot]['RX_STREAM_ID'] = _stream_id
def launchUDP(self, _name): s = socket.socket() # Create a socket object s.bind(('', self._ambeRxPort)) # Bind to the port while (1): # Forever! s.listen(5) # Now wait for client connection. _sock, addr = s.accept() # Establish connection with client. if int_id(self._tx_tg) > 0: # Test if we are allowed to transmit self.playbackFromUDP(_sock) # SSZ was here. else: self.transmitDisabled( _sock, self._system) #tg is zero, so just eat the network trafic _sock.close()
def rule_timer_loop(): logger.info('(ALL IPSC SYSTEMS) Rule timer loop started') _now = time() for _bridge in BRIDGES: for _system in BRIDGES[_bridge]: if _system['TO_TYPE'] == 'ON': if _system['ACTIVE'] == True: if _system['TIMER'] < _now: _system['ACTIVE'] = False logger.info( 'Conference Bridge TIMEOUT: DEACTIVATE System: %s, Bridge: %s, TS: %s, TGID: %s', _system['SYSTEM'], _bridge, _system['TS'], int_id(_system['TGID'])) else: timeout_in = _system['TIMER'] - _now logger.info( 'Conference Bridge ACTIVE (ON timer running): System: %s Bridge: %s, TS: %s, TGID: %s, Timeout in: %ss,', _system['SYSTEM'], _bridge, _system['TS'], int_id(_system['TGID']), timeout_in) elif _system['ACTIVE'] == False: logger.debug( 'Conference Bridge INACTIVE (no change): System: %s Bridge: %s, TS: %s, TGID: %s', _system['SYSTEM'], _bridge, _system['TS'], int_id(_system['TGID'])) elif _system['TO_TYPE'] == 'OFF': if _system['ACTIVE'] == False: if _system['TIMER'] < _now: _system['ACTIVE'] = True logger.info( 'Conference Bridge TIMEOUT: ACTIVATE System: %s, Bridge: %s, TS: %s, TGID: %s', _system['SYSTEM'], _bridge, _system['TS'], int_id(_system['TGID'])) else: timeout_in = _system['TIMER'] - _now logger.info( 'Conference Bridge INACTIVE (OFF timer running): System: %s Bridge: %s, TS: %s, TGID: %s, Timeout in: %ss,', _system['SYSTEM'], _bridge, _system['TS'], int_id(_system['TGID']), timeout_in) elif _system['ACTIVE'] == True: logger.debug( 'Conference Bridge ACTIVE (no change): System: %s Bridge: %s, TS: %s, TGID: %s', _system['SYSTEM'], _bridge, _system['TS'], int_id(_system['TGID'])) else: logger.debug( 'Conference Bridge NO ACTION: System: %s, Bridge: %s, TS: %s, TGID: %s', _system['SYSTEM'], _bridge, _system['TS'], int_id(_system['TGID'])) if BRIDGE_CONF['REPORT'] == 'network': report_server.send_clients('bridge updated')
def rule_timer_loop(): logger.debug('(ALL IPSC) Rule timer loop started') _now = time() for _network in RULES: for _rule in RULES[_network]['GROUP_VOICE']: if _rule['TO_TYPE'] == 'ON': if _rule['ACTIVE'] == True: if _rule['TIMER'] < _now: _rule['ACTIVE'] = False logger.info( '(%s) Rule timout DEACTIVATE: Rule name: %s, Target IPSC: %s, TS: %s, TGID: %s', _network, _rule['NAME'], _rule['DST_NET'], _rule['DST_TS'], int_id(_rule['DST_GROUP'])) else: timeout_in = _rule['TIMER'] - _now logger.info( '(%s) Rule ACTIVE with ON timer running: Timeout eligible in: %ds, Rule name: %s, Target IPSC: %s, TS: %s, TGID: %s', _network, timeout_in, _rule['NAME'], _rule['DST_NET'], _rule['DST_TS'], int_id(_rule['DST_GROUP'])) elif _rule['TO_TYPE'] == 'OFF': if _rule['ACTIVE'] == False: if _rule['TIMER'] < _now: _rule['ACTIVE'] = True logger.info( '(%s) Rule timout ACTIVATE: Rule name: %s, Target IPSC: %s, TS: %s, TGID: %s', _network, _rule['NAME'], _rule['DST_NET'], _rule['DST_TS'], int_id(_rule['DST_GROUP'])) else: timeout_in = _rule['TIMER'] - _now logger.info( '(%s) Rule DEACTIVE with OFF timer running: Timeout eligible in: %ds, Rule name: %s, Target IPSC: %s, TS: %s, TGID: %s', _network, timeout_in, _rule['NAME'], _rule['DST_NET'], _rule['DST_TS'], int_id(_rule['DST_GROUP'])) else: logger.debug('Rule timer loop made no rule changes')
def bridge_presence_loop(self): self._logger.debug('(%s) Bridge presence loop initiated', self._system) _temp_bridge = True for peer in self.BRIDGES: _peer = hex_str_4(peer) if _peer in self._peers.keys() and ( self._peers[_peer]['MODE_DECODE']['TS_1'] or self._peers[_peer]['MODE_DECODE']['TS_2']): _temp_bridge = False self._logger.debug('(%s) Peer %s is an active bridge', self._system, int_id(_peer)) if _peer == self._master['RADIO_ID'] \ and self._master['STATUS']['CONNECTED'] \ and (self._master['MODE_DECODE']['TS_1'] or self._master['MODE_DECODE']['TS_2']): _temp_bridge = False self._logger.debug('(%s) Master %s is an active bridge', self._system, int_id(_peer)) if self.BRIDGE != _temp_bridge: self._logger.info('(%s) Changing bridge status to: %s', self._system, _temp_bridge) self.BRIDGE = _temp_bridge
def rewriteFrame(self, _frame, _newSlot, _newGroup, _newSouceID, _newPeerID): _peerid = _frame[1:5] # int32 peer who is sending us a packet _src_sub = _frame[6:9] # int32 Id of source _burst_data_type = _frame[30] ######################################################################## # re-Write the peer radio ID to that of this program _frame = _frame.replace(_peerid, _newPeerID) # re-Write the source subscriber ID to that of this program _frame = _frame.replace(_src_sub, _newSouceID) # Re-Write the destination Group ID _frame = _frame.replace(_frame[9:12], _newGroup) # Re-Write IPSC timeslot value _call_info = int_id(_frame[17:18]) if _newSlot == 1: _call_info &= ~(1 << 5) elif _newSlot == 2: _call_info |= 1 << 5 _call_info = chr(_call_info) _frame = _frame[:17] + _call_info + _frame[18:] _x = struct.pack("i", self._seq) _frame = _frame[:20] + _x[1] + _x[0] + _frame[22:] self._seq = self._seq + 1 # Re-Write DMR timeslot value # Determine if the slot is present, so we can translate if need be if _burst_data_type == BURST_DATA_TYPE[ 'SLOT1_VOICE'] or _burst_data_type == BURST_DATA_TYPE[ 'SLOT2_VOICE']: # Re-Write timeslot if necessary... if _newSlot == 1: _burst_data_type = BURST_DATA_TYPE['SLOT1_VOICE'] elif _newSlot == 2: _burst_data_type = BURST_DATA_TYPE['SLOT2_VOICE'] _frame = _frame[:30] + _burst_data_type + _frame[31:] if (time() - self._busy_slots[_newSlot] ) >= 0.10: # slot is not busy so it is safe to transmit # Send the packet to all peers in the target IPSC self.send_to_ipsc(_frame) else: logger.info( 'Slot {} is busy, will not transmit packet from gateway'. format(_newSlot))
def private_voice(self, _src_sub, _dst_sub, _ts, _end, _peerid, _data): if id == _dst_sub and _ts in ts: if not _end: if not self.CALL_DATA: print( '({}) Recording transmission from subscriber: {}'. format(self._system, int_id(_src_sub))) self.CALL_DATA.append(_data) if _end: self.CALL_DATA.append(_data) print( '({}) Transmission ended, writing to disk: {}'.format( self._system, filename)) pickle.dump(self.CALL_DATA, open(filename, 'wb')) reactor.stop() print('Recording created, program terminating')
def peer_alive_req(self, _data, _peerid, _host, _port): _hex_mode = (_data[5]) _hex_flags = (_data[6:10]) _decoded_mode = process_mode_byte(_hex_mode) _decoded_flags = process_flags_bytes(_hex_flags) self._peers[_peerid]['MODE'] = _hex_mode self._peers[_peerid]['MODE_DECODE'] = _decoded_mode self._peers[_peerid]['FLAGS'] = _hex_flags self._peers[_peerid]['FLAGS_DECODE'] = _decoded_flags self.send_packet(self.PEER_ALIVE_REPLY_PKT, (_host, _port)) self.reset_keep_alive( _peerid ) # Might as well reset our own counter, we know it's out there... self._logger.debug('(%s) Keep-Alive reply sent to Peer %s, %s:%s', self._system, int_id(_peerid), _host, _port)
def rewriteFrame( self, _frame, _newSlot, _newGroup, _newSourceID, _newPeerID ): _peerid = _frame[1:5] # int32 peer who is sending us a packet _src_sub = _frame[6:9] # int32 Id of source _burst_data_type = _frame[30] _group = _frame[9:12] ######################################################################## # re-Write the peer radio ID to that of this program _frame = _frame.replace(_peerid, _newPeerID, 1) # re-Write the source subscriber ID + destination Group ID combo in the IPSC Header _frame = _frame.replace(_src_sub + _group, _newSourceID + _newGroup, 1) # Re-Write the destination Group ID + source subscriber ID combo in the decoded LCs _frame = _frame.replace(_group + _src_sub, _newGroup + _newSourceID, 1) _frame = _frame[:5] + struct.pack("i", self.ipsc_seq)[0] + _frame[6:] # ipsc sequence number increments on each transmission (stream id) # Re-Write IPSC timeslot value _call_info = int_id(_frame[17:18]) if _newSlot == 1: _call_info &= ~(1 << 5) elif _newSlot == 2: _call_info |= 1 << 5 _call_info = chr(_call_info) _frame = _frame[:17] + _call_info + _frame[18:] _x = struct.pack("i", self._seq) _frame = _frame[:20] + _x[1] + _x[0] + _frame[22:] # rtp sequence number increments for EACH frame sent out self._seq = self._seq + 1 # Re-Write DMR timeslot value # Determine if the slot is present, so we can translate if need be if _burst_data_type == BURST_DATA_TYPE['SLOT1_VOICE'] or _burst_data_type == BURST_DATA_TYPE['SLOT2_VOICE']: # Re-Write timeslot if necessary... if _newSlot == 1: _burst_data_type = BURST_DATA_TYPE['SLOT1_VOICE'] elif _newSlot == 2: _burst_data_type = BURST_DATA_TYPE['SLOT2_VOICE'] _frame = _frame[:30] + _burst_data_type + _frame[31:] if (time() - self._parent._busy_slots[_newSlot]) >= 0.10 : # slot is not busy so it is safe to transmit # Send the packet to all peers in the target IPSC self._parent.send_to_ipsc(_frame) else: self._logger.info('Slot {} is busy, will not transmit packet from gateway'.format(_newSlot)) self.rx[_newSlot].frame_count += 1 # update count (used for stats and to make sure header was sent)
def print_peer_list(_config, _network): _peers = _config['SYSTEMS'][_network]['PEERS'] _status = _config['SYSTEMS'][_network]['MASTER']['STATUS']['PEER_LIST'] #print('Peer List Status for {}: {}' .format(_network, _status)) if _status and not _config['SYSTEMS'][_network]['PEERS']: print('We are the only peer for: %s' % _network) print('') return print('Peer List for: %s' % _network) for peer in _peers.keys(): _this_peer = _peers[peer] _this_peer_stat = _this_peer['STATUS'] if peer == _config['SYSTEMS'][_network]['LOCAL']['RADIO_ID']: me = '(self)' else: me = '' print('\tRADIO ID: {} {}'.format(int_id(peer), me)) print('\t\tIP Address: {}:{}'.format(_this_peer['IP'], _this_peer['PORT'])) if _this_peer['MODE_DECODE'] and _config['REPORTS'][ 'PRINT_PEERS_INC_MODE']: print('\t\tMode Values:') for name, value in _this_peer['MODE_DECODE'].items(): print('\t\t\t{}: {}'.format(name, value)) if _this_peer['FLAGS_DECODE'] and _config['REPORTS'][ 'PRINT_PEERS_INC_FLAGS']: print('\t\tService Flags:') for name, value in _this_peer['FLAGS_DECODE'].items(): print('\t\t\t{}: {}'.format(name, value)) print( '\t\tStatus: {}, KeepAlives Sent: {}, KeepAlives Outstanding: {}, KeepAlives Missed: {}' .format(_this_peer_stat['CONNECTED'], _this_peer_stat['KEEP_ALIVES_SENT'], _this_peer_stat['KEEP_ALIVES_OUTSTANDING'], _this_peer_stat['KEEP_ALIVES_MISSED'])) print( '\t\t KeepAlives Received: {}, Last KeepAlive Received at: {}' .format(_this_peer_stat['KEEP_ALIVES_RECEIVED'], _this_peer_stat['KEEP_ALIVE_RX_TIME'])) print('')
def bridge_presence_loop(self): self._logger.debug('(%s) Bridge presence loop initiated', self._system) _temp_bridge = True for peer in self.BRIDGES: _peer = hex_str_4(peer) if _peer in self._peers.keys() and (self._peers[_peer]['MODE_DECODE']['TS_1'] or self._peers[_peer]['MODE_DECODE']['TS_2']): _temp_bridge = False self._logger.debug('(%s) Peer %s is an active bridge', self._system, int_id(_peer)) if _peer == self._master['RADIO_ID'] \ and self._master['STATUS']['CONNECTED'] \ and (self._master['MODE_DECODE']['TS_1'] or self._master['MODE_DECODE']['TS_2']): _temp_bridge = False self._logger.debug('(%s) Master %s is an active bridge',self._system, int_id(_peer)) if self.BRIDGE != _temp_bridge: self._logger.info('(%s) Changing bridge status to: %s', self._system, _temp_bridge ) self.BRIDGE = _temp_bridge
def build_dmrlink_table(_config, _stats_table): for _ipsc, _ipsc_data in _config.iteritems(): _stats_table[_ipsc] = {} _stats_table[_ipsc]['PEERS'] = {} _stats_table[_ipsc]['MASTER'] = _config[_ipsc]['LOCAL']['MASTER_PEER'] _stats_table[_ipsc]['RADIO_ID'] = int_id(_config[_ipsc]['LOCAL']['RADIO_ID']) _stats_table[_ipsc]['IP'] = _config[_ipsc]['LOCAL']['IP'] _stats_peers = _stats_table[_ipsc]['PEERS'] # if this peer is the master if _stats_table[_ipsc]['MASTER'] == False: _peer = _config[_ipsc]['MASTER']['RADIO_ID'] _config_peer_data = _config[_ipsc]['MASTER'] add_peer(_stats_peers, _peer, _config_peer_data, 'Master') # for all peers that are not the master for _peer, _config_peer_data in _config[_ipsc]['PEERS'].iteritems(): if _peer != _config[_ipsc]['LOCAL']['RADIO_ID']: add_peer(_stats_peers, _peer, _config_peer_data, 'Peer')
def master_reg_reply(self, _data, _peerid): _hex_mode = _data[5] _hex_flags = _data[6:10] _num_peers = _data[10:12] _decoded_mode = process_mode_byte(_hex_mode) _decoded_flags = process_flags_bytes(_hex_flags) self._local['NUM_PEERS'] = int(ahex(_num_peers), 16) self._master['RADIO_ID'] = _peerid self._master['MODE'] = _hex_mode self._master['MODE_DECODE'] = _decoded_mode self._master['FLAGS'] = _hex_flags self._master['FLAGS_DECODE'] = _decoded_flags self._master_stat['CONNECTED'] = True self._master_stat['KEEP_ALIVES_OUTSTANDING'] = 0 self._logger.warning( '(%s) Registration response (we requested reg) from the Master: %s, %s:%s (%s peers)', self._system, int_id(_peerid), self._master['IP'], self._master['PORT'], self._local['NUM_PEERS'])
def rewriteFrame( self, _frame, _newSlot, _newGroup, _newSouceID, _newPeerID ): _peerid = _frame[1:5] # int32 peer who is sending us a packet _src_sub = _frame[6:9] # int32 Id of source _burst_data_type = _frame[30] ######################################################################## # re-Write the peer radio ID to that of this program _frame = _frame.replace(_peerid, _newPeerID) # re-Write the source subscriber ID to that of this program _frame = _frame.replace(_src_sub, _newSouceID) # Re-Write the destination Group ID _frame = _frame.replace(_frame[9:12], _newGroup) # Re-Write IPSC timeslot value _call_info = int_id(_frame[17:18]) if _newSlot == 1: _call_info &= ~(1 << 5) elif _newSlot == 2: _call_info |= 1 << 5 _call_info = chr(_call_info) _frame = _frame[:17] + _call_info + _frame[18:] _x = struct.pack("i", self._seq) _frame = _frame[:20] + _x[1] + _x[0] + _frame[22:] self._seq = self._seq + 1 # Re-Write DMR timeslot value # Determine if the slot is present, so we can translate if need be if _burst_data_type == BURST_DATA_TYPE['SLOT1_VOICE'] or _burst_data_type == BURST_DATA_TYPE['SLOT2_VOICE']: # Re-Write timeslot if necessary... if _newSlot == 1: _burst_data_type = BURST_DATA_TYPE['SLOT1_VOICE'] elif _newSlot == 2: _burst_data_type = BURST_DATA_TYPE['SLOT2_VOICE'] _frame = _frame[:30] + _burst_data_type + _frame[31:] if (time() - self._busy_slots[_newSlot]) >= 0.10 : # slot is not busy so it is safe to transmit # Send the packet to all peers in the target IPSC self.send_to_ipsc(_frame) else: logger.info('Slot {} is busy, will not transmit packet from gateway'.format(_newSlot))
def begin_call(self, _slot, _src_id, _dst_id, _repeater_id, _cc, _seq, _stream_id): subscriber_ids, talkgroup_ids, peer_ids = self._parent.get_globals() _src_alias = get_alias(_src_id, subscriber_ids) metadata = _src_id[0:3] + _repeater_id[0:4] + _dst_id[0:3] + struct.pack("b", _slot) + struct.pack("b", _cc) self.send_tlv(TAG_BEGIN_TX, metadata) # start transmission self._sock.sendto('reply log2 {} {}'.format(_src_alias, int_id(_dst_id)), (self._dmrgui, 34003)) self._logger.info('Voice Transmission Start on TS {} and TG {} ({}) from {}'.format(_slot, get_alias(_dst_id, talkgroup_ids), int_id(_dst_id), _src_alias)) _tx_slot = self.tx[_slot] _tx_slot.slot = _slot _tx_slot.rf_src = _src_id _tx_slot.repeater_id = _repeater_id _tx_slot.dst_id = _dst_id _tx_slot.cc = _cc _tx_slot.stream_id = _stream_id _tx_slot.start_time = time() _tx_slot.frame_count = 0 _tx_slot.lostFrame = 0 _tx_slot.lastSeq = _seq
def master_reg_req(self, _data, _peerid, _host, _port): _ip_address = _host _port = _port _hex_mode = _data[5] _hex_flags = _data[6:10] _decoded_mode = process_mode_byte(_hex_mode) _decoded_flags = process_flags_bytes(_hex_flags) self.MASTER_REG_REPLY_PKT = (MASTER_REG_REPLY + self._local_id + self.TS_FLAGS + hex_str_2(self._local['NUM_PEERS']) + IPSC_VER) self.send_packet(self.MASTER_REG_REPLY_PKT, (_host, _port)) self._logger.info( '(%s) Master Registration Packet Received from peer %s, %s:%s', self._system, int_id(_peerid), _host, _port) # If this entry was NOT already in our list, add it. if _peerid not in self._peers.keys(): self._peers[_peerid] = { 'IP': _ip_address, 'PORT': _port, 'MODE': _hex_mode, 'MODE_DECODE': _decoded_mode, 'FLAGS': _hex_flags, 'FLAGS_DECODE': _decoded_flags, 'STATUS': { 'CONNECTED': True, 'KEEP_ALIVES_SENT': 0, 'KEEP_ALIVES_MISSED': 0, 'KEEP_ALIVES_OUTSTANDING': 0, 'KEEP_ALIVES_RECEIVED': 0, 'KEEP_ALIVE_RX_TIME': int(time()) } } self._local['NUM_PEERS'] = len(self._peers) self._logger.debug( '(%s) Peer Added To Peer List: %s, %s:%s (IPSC now has %s Peers)', self._system, self._peers[_peerid], _host, _port, self._local['NUM_PEERS'])
def build_hblink_table(_config): _stats_table = {'MASTERS': {}, 'CLIENTS': {}} for _hbp, _hbp_data in _config.iteritems(): if _hbp_data['ENABLED'] == True: if _hbp_data['MODE'] == 'MASTER': _stats_table['MASTERS'][_hbp] = {} _stats_table['MASTERS'][_hbp]['REPEAT'] = _hbp_data['REPEAT'] _stats_table['MASTERS'][_hbp]['CLIENTS'] = {} for _client in _hbp_data['CLIENTS']: _stats_table['MASTERS'][_hbp]['CLIENTS'][int_id( _client)] = {} _stats_table['MASTERS'][_hbp]['CLIENTS'][int_id(_client)][ 'CALLSIGN'] = _hbp_data['CLIENTS'][_client]['CALLSIGN'] _stats_table['MASTERS'][_hbp]['CLIENTS'][int_id( _client)]['CONNECTION'] = _hbp_data['CLIENTS'][ _client]['CONNECTION'] _stats_table['MASTERS'][_hbp]['CLIENTS'][int_id( _client)]['IP'] = _hbp_data['CLIENTS'][_client]['IP'] _stats_table['MASTERS'][_hbp]['CLIENTS'][int_id( _client)]['PINGS_RECEIVED'] = _hbp_data['CLIENTS'][ _client]['PINGS_RECEIVED'] _stats_table['MASTERS'][_hbp]['CLIENTS'][int_id( _client)]['LAST_PING'] = _hbp_data['CLIENTS'][_client][ 'LAST_PING'] _stats_table['MASTERS'][_hbp]['CLIENTS'][int_id(_client)][ 'PORT'] = _hbp_data['CLIENTS'][_client]['PORT'] elif _hbp_data['MODE'] == 'CLIENT': _stats_table['CLIENTS'][_hbp] = {} _stats_table['CLIENTS'][_hbp]['CALLSIGN'] = _hbp_data[ 'CALLSIGN'] _stats_table['CLIENTS'][_hbp]['RADIO_ID'] = int_id( _hbp_data['RADIO_ID']) _stats_table['CLIENTS'][_hbp]['MASTER_IP'] = _hbp_data[ 'MASTER_IP'] _stats_table['CLIENTS'][_hbp]['STATS'] = _hbp_data['STATS'] return (_stats_table)
def call_mon_rpt(self, _data): if not rpt: return _source = _data[1:5] _ts1_state = _data[5] _ts2_state = _data[6] _source = str(int_id(_source)) + ', ' + str(get_alias(_source, peer_ids)) print('Call Monitor - Repeater State') print('TIME: ', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) print('DATA SOURCE: ', _source) try: print('TS1 State: ', REPEAT[_ts1_state]) except KeyError: print('TS1 State (unknown): ', h(_ts1_state)) try: print('TS2 State: ', REPEAT[_ts2_state]) except KeyError: print('TS2 State (unknown): ', h(_ts2_state)) print()
def update_dmrlink_table(_config, _stats_table): for _ipsc, _ipsc_data in _config.iteritems(): _stats_peers = _stats_table[_ipsc]['PEERS'] # if this peer is the master if _stats_table[_ipsc]['MASTER'] == False: _peer = _config[_ipsc]['MASTER']['RADIO_ID'] _config_peer_data = _config[_ipsc]['MASTER'] _stats_peers[_peer]['RADIO_ID'] = int_id(_peer) update_peer(_stats_peers, _peer, _config_peer_data) # for all of the peers that are not the master... update or add for _peer, _config_peer_data in _config[_ipsc]['PEERS'].iteritems(): if _peer != _config[_ipsc]['LOCAL']['RADIO_ID']: _stats_peers = _stats_table[_ipsc]['PEERS'] # update the peer if we already have it if _peer in _stats_table[_ipsc]['PEERS']: update_peer(_stats_peers, _peer, _config_peer_data) # addit if we don't have it if _peer not in _stats_table[_ipsc]['PEERS']: add_peer(_stats_peers, _peer, _config_peer_data, 'peer') # for peers that need to be removed, never the master. This is complicated peers_to_delete = [] # find any peers missing in the config update for _peer, _stats_peer_data in _stats_table[_ipsc]['PEERS'].iteritems( ): if _peer not in _config[_ipsc][ 'PEERS'] and _peer != _config[_ipsc]['MASTER']['RADIO_ID']: peers_to_delete.append(_peer) # delte anything identified from the right part of the stats table delete_peers(peers_to_delete, _stats_table[_ipsc]['PEERS'])
def call_mon_rpt(self, _data): if not rpt: return _source = _data[1:5] _ts1_state = _data[5] _ts2_state = _data[6] _source = str(int_id(_source)) + ', ' + str( get_alias(_source, peer_ids)) print('Call Monitor - Repeater State') print('TIME: ', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) print('DATA SOURCE: ', _source) try: print('TS1 State: ', REPEAT[_ts1_state]) except KeyError: print('TS1 State (unknown): ', ahex(_ts1_state)) try: print('TS2 State: ', REPEAT[_ts2_state]) except KeyError: print('TS2 State (unknown): ', ahex(_ts2_state)) print()
def parseAMBE(self, _client, _data): _seq = int_id(_data[4:5]) _srcID = int_id(_data[5:8]) _dstID = int_id(_data[8:11]) _rptID = int_id(_data[11:15]) _bits = int_id(_data[15:16]) # SCDV NNNN (Slot|Call type|Data|Voice|Seq or Data type) _slot = 2 if _bits & 0x80 else 1 _callType = 1 if (_bits & 0x40) else 0 _frameType = (_bits & 0x30) >> 4 _voiceSeq = (_bits & 0x0f) _streamID = int_id(_data[16:20]) logger.debug('(%s) seq: %d srcID: %d dstID: %d rptID: %d bits: %0X slot:%d callType: %d frameType: %d voiceSeq: %d streamID: %0X', _client, _seq, _srcID, _dstID, _rptID, _bits, _slot, _callType, _frameType, _voiceSeq, _streamID ) #logger.debug('Frame 1:(%s)', self.ByteToHex(_data)) _dmr_frame = BitArray('0x'+ahex(_data[20:])) _ambe = _dmr_frame[0:108] + _dmr_frame[156:264] #_sock.sendto(_ambe.tobytes(), ("127.0.0.1", 31000)) ambeBytes = _ambe.tobytes() self._sock.sendto(ambeBytes[0:9], (self._exp_ip, self._exp_port)) self._sock.sendto(ambeBytes[9:18], (self._exp_ip, self._exp_port)) self._sock.sendto(ambeBytes[18:27], (self._exp_ip, self._exp_port))
def master_maintenance_loop(self): self._logger.debug('(%s) MASTER Connection Maintenance Loop Started', self._system) update_time = int(time()) for peer in self._peers.keys(): keep_alive_delta = update_time - self._peers[peer]['STATUS']['KEEP_ALIVE_RX_TIME'] self._logger.debug('(%s) Time Since Last KeepAlive Request from Peer %s: %s seconds', self._system, int_id(peer), keep_alive_delta) if keep_alive_delta > 120: self.de_register_peer(peer) self.send_to_ipsc(self.PEER_LIST_REPLY_PKT + build_peer_list(self._peers)) self._logger.warning('(%s) Timeout Exceeded for Peer %s, De-registering', self._system, int_id(peer))
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data): pkt_time = time() dmrpkt = _data[20:53] _bits = int_id(_data[15]) if _call_type == 'group': # Check for ACL match, and return if the subscriber is not allowed if allow_sub(_rf_src) == False: self._logger.warning( '(%s) Group Voice Packet ***REJECTED BY ACL*** From: %s, HBP Peer %s, Destination TGID %s', self._system, int_id(_rf_src), int_id(_peer_id), int_id(_dst_id)) return # Is this a new call stream? if (_stream_id != self.STATUS[_slot]['RX_STREAM_ID']): if (self.STATUS[_slot]['RX_TYPE'] != hb_const.HBPF_SLT_VTERM ) and (pkt_time < (self.STATUS[_slot]['RX_TIME'] + hb_const.STREAM_TO) ) and (_rf_src != self.STATUS[_slot]['RX_RFS']): self._logger.warning( '(%s) Packet received with STREAM ID: %s <FROM> SUB: %s PEER: %s <TO> TGID %s, SLOT %s collided with existing call', self._system, int_id(_stream_id), int_id(_rf_src), int_id(_peer_id), int_id(_dst_id), _slot) return # This is a new call stream self.STATUS['RX_START'] = pkt_time self._logger.info('(%s) *CALL START* STREAM ID: %s SUB: %s (%s) PEER: %s (%s) TGID %s (%s), TS %s', \ self._system, int_id(_stream_id), get_alias(_rf_src, subscriber_ids), int_id(_rf_src), get_alias(_peer_id, peer_ids), int_id(_peer_id), get_alias(_dst_id, talkgroup_ids), int_id(_dst_id), _slot) # If we can, use the LC from the voice header as to keep all options intact if _frame_type == hb_const.HBPF_DATA_SYNC and _dtype_vseq == hb_const.HBPF_SLT_VHEAD: decoded = decode.voice_head_term(dmrpkt) self.STATUS[_slot]['RX_LC'] = decoded['LC'] # If we don't have a voice header then don't wait to decode it from the Embedded LC # just make a new one from the HBP header. This is good enough, and it saves lots of time else: self.STATUS[_slot][ 'RX_LC'] = const.LC_OPT + _dst_id + _rf_src for rule in RULES[self._system]['GROUP_VOICE']: _target = rule['DST_NET'] _target_status = systems[_target].STATUS if (rule['SRC_GROUP'] == _dst_id and rule['SRC_TS'] == _slot and rule['ACTIVE'] == True): # BEGIN CONTENTION HANDLING # # The rules for each of the 4 "ifs" below are listed here for readability. The Frame To Send is: # From a different group than last RX from this HBSystem, but it has been less than Group Hangtime # From a different group than last TX to this HBSystem, but it has been less than Group Hangtime # From the same group as the last RX from this HBSystem, but from a different subscriber, and it has been less than stream timeout # From the same group as the last TX to this HBSystem, but from a different subscriber, and it has been less than stream timeout # The "continue" at the end of each means the next iteration of the for loop that tests for matching rules # if ((rule['DST_GROUP'] != _target_status[rule['DST_TS']]['RX_TGID']) and ((pkt_time - _target_status[rule['DST_TS']]['RX_TIME']) < RULES[_target]['GROUP_HANGTIME'])): if _frame_type == hb_const.HBPF_DATA_SYNC and _dtype_vseq == hb_const.HBPF_SLT_VHEAD: self._logger.info( '(%s) Call not routed to TGID%s, target active or in group hangtime: HBSystem: %s, TS: %s, TGID: %s', self._system, int_id(rule['DST_GROUP']), _target, rule['DST_TS'], int_id( _target_status[rule['DST_TS']]['RX_TGID'])) continue if ((rule['DST_GROUP'] != _target_status[rule['DST_TS']]['TX_TGID']) and ((pkt_time - _target_status[rule['DST_TS']]['TX_TIME']) < RULES[_target]['GROUP_HANGTIME'])): if _frame_type == hb_const.HBPF_DATA_SYNC and _dtype_vseq == hb_const.HBPF_SLT_VHEAD: self._logger.info( '(%s) Call not routed to TGID%s, target in group hangtime: HBSystem: %s, TS: %s, TGID: %s', self._system, int_id(rule['DST_GROUP']), _target, rule['DST_TS'], int_id( _target_status[rule['DST_TS']]['TX_TGID'])) continue if (rule['DST_GROUP'] == _target_status[rule['DST_TS']]['RX_TGID']) and ( (pkt_time - _target_status[rule['DST_TS']]['RX_TIME']) < hb_const.STREAM_TO): if _frame_type == hb_const.HBPF_DATA_SYNC and _dtype_vseq == hb_const.HBPF_SLT_VHEAD: self._logger.info( '(%s) Call not routed to TGID%s, matching call already active on target: HBSystem: %s, TS: %s, TGID: %s', self._system, int_id(rule['DST_GROUP']), _target, rule['DST_TS'], int_id( _target_status[rule['DST_TS']]['RX_TGID'])) continue if (rule['DST_GROUP'] == _target_status[rule['DST_TS']]['TX_TGID']) and ( _rf_src != _target_status[rule['DST_TS']]['TX_RFS']) and ( (pkt_time - _target_status[rule['DST_TS']]['TX_TIME']) < hb_const.STREAM_TO): if _frame_type == hb_const.HBPF_DATA_SYNC and _dtype_vseq == hb_const.HBPF_SLT_VHEAD: self._logger.info( '(%s) Call not routed for subscriber %s, call route in progress on target: HBSystem: %s, TS: %s, TGID: %s, SUB: %s', self._system, int_id(_rf_src), _target, rule['DST_TS'], int_id( _target_status[rule['DST_TS']]['TX_TGID']), _target_status[rule['DST_TS']]['TX_RFS']) continue # Set values for the contention handler to test next time there is a frame to forward _target_status[rule['DST_TS']]['TX_TIME'] = pkt_time if (_stream_id != self.STATUS[_slot]['RX_STREAM_ID']) or ( _target_status[rule['DST_TS']]['TX_RFS'] != _rf_src ) or (_target_status[rule['DST_TS']]['TX_TGID'] != rule['DST_GROUP']): # Record the DST TGID and Stream ID _target_status[ rule['DST_TS']]['TX_TGID'] = rule['DST_GROUP'] _target_status[ rule['DST_TS']]['TX_STREAM_ID'] = _stream_id _target_status[rule['DST_TS']]['TX_RFS'] = _rf_src # Generate LCs (full and EMB) for the TX stream # if _dst_id != rule['DST_GROUP']: dst_lc = self.STATUS[_slot]['RX_LC'][0:3] + rule[ 'DST_GROUP'] + _rf_src _target_status[rule['DST_TS']][ 'TX_H_LC'] = bptc.encode_header_lc(dst_lc) _target_status[rule['DST_TS']][ 'TX_T_LC'] = bptc.encode_terminator_lc(dst_lc) _target_status[rule['DST_TS']][ 'TX_EMB_LC'] = bptc.encode_emblc(dst_lc) self._logger.debug( '(%s) Packet DST TGID (%s) does not match SRC TGID(%s) - Generating FULL and EMB LCs', self._system, int_id(rule['DST_GROUP']), int_id(_dst_id)) self._logger.info( '(%s) Call routed to: System: %s TS: %s, TGID: %s', self._system, _target, rule['DST_TS'], int_id(rule['DST_GROUP'])) # Handle any necessary re-writes for the destination if rule['SRC_TS'] != rule['DST_TS']: _tmp_bits = _bits ^ 1 << 7 else: _tmp_bits = _bits # Assemble transmit HBP packet header _tmp_data = _data[:8] + rule['DST_GROUP'] + _data[ 11:15] + chr(_tmp_bits) + _data[16:20] # MUST TEST FOR NEW STREAM AND IF SO, RE-WRITE THE LC FOR THE TARGET # MUST RE-WRITE DESTINATION TGID IF DIFFERENT # if _dst_id != rule['DST_GROUP']: dmrbits = bitarray(endian='big') dmrbits.frombytes(dmrpkt) # Create a voice header packet (FULL LC) if _frame_type == hb_const.HBPF_DATA_SYNC and _dtype_vseq == hb_const.HBPF_SLT_VHEAD: dmrbits = _target_status[rule['DST_TS']]['TX_H_LC'][ 0:98] + dmrbits[98:166] + _target_status[ rule['DST_TS']]['TX_H_LC'][98:197] # Create a voice terminator packet (FULL LC) elif _frame_type == hb_const.HBPF_DATA_SYNC and _dtype_vseq == hb_const.HBPF_SLT_VTERM: dmrbits = _target_status[rule['DST_TS']]['TX_T_LC'][ 0:98] + dmrbits[98:166] + _target_status[ rule['DST_TS']]['TX_T_LC'][98:197] # Create a Burst B-E packet (Embedded LC) elif _dtype_vseq in [1, 2, 3, 4]: dmrbits = dmrbits[0:116] + _target_status[ rule['DST_TS']]['TX_EMB_LC'][ _dtype_vseq] + dmrbits[148:264] dmrpkt = dmrbits.tobytes() _tmp_data = _tmp_data + dmrpkt + _data[53:55] # Transmit the packet to the destination system systems[_target].send_system(_tmp_data) self._logger.debug( '(%s) Packet routed by rule: %s to %s system: %s', self._system, rule['NAME'], self._CONFIG['SYSTEMS'][_target]['MODE'], _target) # Final actions - Is this a voice terminator? if (_frame_type == hb_const.HBPF_DATA_SYNC ) and (_dtype_vseq == hb_const.HBPF_SLT_VTERM) and ( self.STATUS[_slot]['RX_TYPE'] != hb_const.HBPF_SLT_VTERM): call_duration = pkt_time - self.STATUS['RX_START'] self._logger.info('(%s) *CALL END* STREAM ID: %s SUB: %s (%s) PEER: %s (%s) TGID %s (%s), TS %s, Duration: %s', \ self._system, int_id(_stream_id), get_alias(_rf_src, subscriber_ids), int_id(_rf_src), get_alias(_peer_id, peer_ids), int_id(_peer_id), get_alias(_dst_id, talkgroup_ids), int_id(_dst_id), _slot, call_duration) # # Begin in-band signalling for call end. This has nothign to do with routing traffic directly. # # Iterate the rules dictionary for rule in RULES[self._system]['GROUP_VOICE']: _target = rule['DST_NET'] # TGID matches a rule source, reset its timer if _slot == rule['SRC_TS'] and _dst_id == rule[ 'SRC_GROUP'] and ((rule['TO_TYPE'] == 'ON' and (rule['ACTIVE'] == True)) or (rule['TO_TYPE'] == 'OFF' and rule['ACTIVE'] == False)): rule['TIMER'] = pkt_time + rule['TIMEOUT'] self._logger.info( '(%s) Source group transmission match for rule \"%s\". Reset timeout to %s', self._system, rule['NAME'], rule['TIMER']) # Scan for reciprocal rules and reset their timers as well. for target_rule in RULES[_target]['GROUP_VOICE']: if target_rule['NAME'] == rule['NAME']: target_rule['TIMER'] = pkt_time + target_rule[ 'TIMEOUT'] self._logger.info( '(%s) Reciprocal group transmission match for rule \"%s\" on IPSC \"%s\". Reset timeout to %s', self._system, target_rule['NAME'], _target, rule['TIMER']) # TGID matches an ACTIVATION trigger if _dst_id in rule['ON']: # Set the matching rule as ACTIVE rule['ACTIVE'] = True rule['TIMER'] = pkt_time + rule['TIMEOUT'] self._logger.info( '(%s) Primary routing Rule \"%s\" changed to state: %s', self._system, rule['NAME'], rule['ACTIVE']) # Set reciprocal rules for other IPSCs as ACTIVE for target_rule in RULES[_target]['GROUP_VOICE']: if target_rule['NAME'] == rule['NAME']: target_rule['ACTIVE'] = True target_rule['TIMER'] = pkt_time + target_rule[ 'TIMEOUT'] self._logger.info( '(%s) Reciprocal routing Rule \"%s\" in IPSC \"%s\" changed to state: %s', self._system, target_rule['NAME'], _target, rule['ACTIVE']) # TGID matches an DE-ACTIVATION trigger if _dst_id in rule['OFF']: # Set the matching rule as ACTIVE rule['ACTIVE'] = False self._logger.info( '(%s) Routing Rule \"%s\" changed to state: %s', self._system, rule['NAME'], rule['ACTIVE']) # Set reciprocal rules for other IPSCs as ACTIVE _target = rule['DST_NET'] for target_rule in RULES[_target]['GROUP_VOICE']: if target_rule['NAME'] == rule['NAME']: target_rule['ACTIVE'] = False self._logger.info( '(%s) Reciprocal routing Rule \"%s\" in IPSC \"%s\" changed to state: %s', self._system, target_rule['NAME'], _target, rule['ACTIVE']) # # END IN-BAND SIGNALLING # # Mark status variables for use later self.STATUS[_slot]['RX_RFS'] = _rf_src self.STATUS[_slot]['RX_TYPE'] = _dtype_vseq self.STATUS[_slot]['RX_TGID'] = _dst_id self.STATUS[_slot]['RX_TIME'] = pkt_time self.STATUS[_slot]['RX_STREAM_ID'] = _stream_id
def peer_list_req(self, _peerid): if _peerid in self._peers.keys(): self._logger.debug('(%s) Peer List Request from peer %s', self._system, int_id(_peerid)) self.send_to_ipsc(self.PEER_LIST_REPLY_PKT + build_peer_list(self._peers)) else: self._logger.warning('(%s) Peer List Request Received from *UNREGISTERED* peer %s', self._system, int_id(_peerid))
def repeater_wake_up(self, _data): _source = _data[1:5] _source_name = get_alias(_source, peer_ids) print('({}) Repeater Wake-Up Packet Received: {} ({})'.format( self._system, _source_name, int_id(_source)))
class HBSYSTEM(DatagramProtocol): def __init__(self, _name, _config, _logger): # Define a few shortcuts to make the rest of the class more readable self._CONFIG = _config self._system = _name self._logger = _logger self._config = self._CONFIG['SYSTEMS'][self._system] # Define shortcuts and generic function names based on the type of system we are if self._config['MODE'] == 'MASTER': self._clients = self._CONFIG['SYSTEMS'][self._system]['CLIENTS'] self.send_system = self.send_clients self.maintenance_loop = self.master_maintenance_loop self.datagramReceived = self.master_datagramReceived self.dereg = self.master_dereg elif self._config['MODE'] == 'CLIENT': self._stats = self._config['STATS'] self.send_system = self.send_master self.maintenance_loop = self.client_maintenance_loop self.datagramReceived = self.client_datagramReceived self.dereg = self.client_dereg # Configure for AMBE audio export if enabled if self._config['EXPORT_AMBE']: self._ambe = AMBE() def startProtocol(self): # Set up periodic loop for tracking pings from clients. Run every 'PING_TIME' seconds self._system_maintenance = task.LoopingCall(self.maintenance_loop) self._system_maintenance_loop = self._system_maintenance.start(self._CONFIG['GLOBAL']['PING_TIME']) # Aliased in __init__ to maintenance_loop if system is a master def master_maintenance_loop(self): self._logger.debug('(%s) Master maintenance loop started', self._system) for client in self._clients: _this_client = self._clients[client] # Check to see if any of the clients have been quiet (no ping) longer than allowed if _this_client['LAST_PING']+self._CONFIG['GLOBAL']['PING_TIME']*self._CONFIG['GLOBAL']['MAX_MISSED'] < time(): self._logger.info('(%s) Client %s (%s) has timed out', self._system, _this_client['CALLSIGN'], _this_client['RADIO_ID']) # Remove any timed out clients from the configuration del self._CONFIG['SYSTEMS'][self._system]['CLIENTS'][client] # Aliased in __init__ to maintenance_loop if system is a client def client_maintenance_loop(self): self._logger.debug('(%s) Client maintenance loop started', self._system) # If we're not connected, zero out the stats and send a login request RPTL if self._stats['CONNECTION'] == 'NO' or self._stats['CONNECTION'] == 'RTPL_SENT': self._stats['PINGS_SENT'] = 0 self._stats['PINGS_ACKD'] = 0 self._stats['CONNECTION'] = 'RTPL_SENT' self.send_master('RPTL'+self._config['RADIO_ID']) self._logger.info('(%s) Sending login request to master %s:%s', self._system, self._config['MASTER_IP'], self._config['MASTER_PORT']) # If we are connected, sent a ping to the master and increment the counter if self._stats['CONNECTION'] == 'YES': self.send_master('RPTPING'+self._config['RADIO_ID']) self._stats['PINGS_SENT'] += 1 self._logger.debug('(%s) RPTPING Sent to Master. Pings Since Connected: %s', self._system, self._stats['PINGS_SENT']) def send_clients(self, _packet): for _client in self._clients: self.send_client(_client, _packet) #self._logger.debug('(%s) Packet sent to client %s', self._system, self._clients[_client]['RADIO_ID']) def send_client(self, _client, _packet): _ip = self._clients[_client]['IP'] _port = self._clients[_client]['PORT'] self.transport.write(_packet, (_ip, _port)) # KEEP THE FOLLOWING COMMENTED OUT UNLESS YOU'RE DEBUGGING DEEPLY!!!! #self._logger.debug('(%s) TX Packet to %s on port %s: %s', self._clients[_client]['RADIO_ID'], self._clients[_client]['IP'], self._clients[_client]['PORT'], ahex(_packet)) def send_master(self, _packet): self.transport.write(_packet, (self._config['MASTER_IP'], self._config['MASTER_PORT'])) # KEEP THE FOLLOWING COMMENTED OUT UNLESS YOU'RE DEBUGGING DEEPLY!!!! #self._logger.debug('(%s) TX Packet to %s:%s -- %s', self._system, self._config['MASTER_IP'], self._config['MASTER_PORT'], ahex(_packet)) def dmrd_received(self, _radio_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data): pass def master_dereg(self): for _client in self._clients: self.send_client(_client, 'MSTCL'+_client) self._logger.info('(%s) De-Registration sent to Client: %s (%s)', self._system, self._clients[_client]['CALLSIGN'], self._clients[_client]['RADIO_ID']) def client_dereg(self): self.send_master('RPTCL'+self._config['RADIO_ID']) self._logger.info('(%s) De-Registeration sent to Master: %s:%s', self._system, self._config['MASTER_IP'], self._config['MASTER_PORT']) # Aliased in __init__ to datagramReceived if system is a master def master_datagramReceived(self, _data, (_host, _port)): # Keep This Line Commented Unless HEAVILY Debugging! #self._logger.debug('(%s) RX packet from %s:%s -- %s', self._system, _host, _port, ahex(_data)) # Extract the command, which is various length, all but one 4 significant characters -- RPTCL _command = _data[:4] if _command == 'DMRD': # DMRData -- encapsulated DMR data frame _radio_id = _data[11:15] if _radio_id in self._clients \ and self._clients[_radio_id]['CONNECTION'] == 'YES' \ and self._clients[_radio_id]['IP'] == _host \ and self._clients[_radio_id]['PORT'] == _port: _seq = _data[4] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = int_id(_data[15]) _slot = 2 if (_bits & 0x80) else 1 _call_type = 'unit' if (_bits & 0x40) else 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = (_bits & 0xF) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] #self._logger.debug('(%s) DMRD - Seqence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id)) # If AMBE audio exporting is configured... if self._config['EXPORT_AMBE']: self._ambe.parseAMBE(self._system, _data) # The basic purpose of a master is to repeat to the clients if self._config['REPEAT'] == True: for _client in self._clients: if _client != _radio_id: self.send_client(_client, _data) self._logger.debug('(%s) Packet on TS%s from %s (%s) for destination ID %s repeated to client: %s (%s) [Stream ID: %s]', self._system, _slot, self._clients[_radio_id]['CALLSIGN'], int_id(_radio_id), int_id(_dst_id), self._clients[_client]['CALLSIGN'], int_id(_client), int_id(_stream_id)) # Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_radio_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == 'RPTL': # RPTLogin -- a repeater wants to login _radio_id = _data[4:8] if _radio_id: # Future check here for valid Radio ID self._clients.update({_radio_id: { # Build the configuration data strcuture for the client 'CONNECTION': 'RPTL-RECEIVED', 'PINGS_RECEIVED': 0, 'LAST_PING': time(), 'IP': _host, 'PORT': _port, 'SALT': randint(0,0xFFFFFFFF), 'RADIO_ID': str(int(ahex(_radio_id), 16)), 'CALLSIGN': '', 'RX_FREQ': '', 'TX_FREQ': '', 'TX_POWER': '', 'COLORCODE': '', 'LATITUDE': '', 'LONGITUDE': '', 'HEIGHT': '', 'LOCATION': '', 'DESCRIPTION': '', 'SLOTS': '', 'URL': '', 'SOFTWARE_ID': '', 'PACKAGE_ID': '', }}) self._logger.info('(%s) Repeater Logging in with Radio ID: %s, %s:%s', self._system, int_id(_radio_id), _host, _port) _salt_str = hex_str_4(self._clients[_radio_id]['SALT']) self.send_client(_radio_id, 'RPTACK'+_salt_str) self._clients[_radio_id]['CONNECTION'] = 'CHALLENGE_SENT' self._logger.info('(%s) Sent Challenge Response to %s for login: %s', self._system, int_id(_radio_id), self._clients[_radio_id]['SALT']) else: self.transport.write('MSTNAK'+_radio_id, (_host, _port)) self._logger.warning('(%s) Invalid Login from Radio ID: %s', self._system, int_id(_radio_id)) elif _command == 'RPTK': # Repeater has answered our login challenge _radio_id = _data[4:8] if _radio_id in self._clients \ and self._clients[_radio_id]['CONNECTION'] == 'CHALLENGE_SENT' \ and self._clients[_radio_id]['IP'] == _host \ and self._clients[_radio_id]['PORT'] == _port: _this_client = self._clients[_radio_id] _this_client['LAST_PING'] = time() _sent_hash = _data[8:] _salt_str = hex_str_4(_this_client['SALT']) _calc_hash = bhex(sha256(_salt_str+self._config['PASSPHRASE']).hexdigest()) if _sent_hash == _calc_hash: _this_client['CONNECTION'] = 'WAITING_CONFIG' self.send_client(_radio_id, 'RPTACK'+_radio_id) self._logger.info('(%s) Client %s has completed the login exchange successfully', self._system, _this_client['RADIO_ID']) else: self._logger.info('(%s) Client %s has FAILED the login exchange successfully', self._system, _this_client['RADIO_ID']) self.transport.write('MSTNAK'+_radio_id, (_host, _port)) del self._clients[_radio_id] else: self.transport.write('MSTNAK'+_radio_id, (_host, _port)) self._logger.warning('(%s) Login challenge from Radio ID that has not logged in: %s', self._system, int_id(_radio_id)) elif _command == 'RPTC': # Repeater is sending it's configuraiton OR disconnecting if _data[:5] == 'RPTCL': # Disconnect command _radio_id = _data[5:9] if _radio_id in self._clients \ and self._clients[_radio_id]['CONNECTION'] == 'YES' \ and self._clients[_radio_id]['IP'] == _host \ and self._clients[_radio_id]['PORT'] == _port: self._logger.info('(%s) Client is closing down: %s (%s)', self._system, self._clients[_radio_id]['CALLSIGN'], int_id(_radio_id)) self.transport.write('MSTNAK'+_radio_id, (_host, _port)) del self._clients[_radio_id] else: _radio_id = _data[4:8] # Configure Command if _radio_id in self._clients \ and self._clients[_radio_id]['CONNECTION'] == 'WAITING_CONFIG' \ and self._clients[_radio_id]['IP'] == _host \ and self._clients[_radio_id]['PORT'] == _port: _this_client = self._clients[_radio_id] _this_client['CONNECTION'] = 'YES' _this_client['LAST_PING'] = time() _this_client['CALLSIGN'] = _data[8:16] _this_client['RX_FREQ'] = _data[16:25] _this_client['TX_FREQ'] = _data[25:34] _this_client['TX_POWER'] = _data[34:36] _this_client['COLORCODE'] = _data[36:38] _this_client['LATITUDE'] = _data[38:46] _this_client['LONGITUDE'] = _data[46:55] _this_client['HEIGHT'] = _data[55:58] _this_client['LOCATION'] = _data[58:78] _this_client['DESCRIPTION'] = _data[78:97] _this_client['SLOTS'] = _data[97:98] _this_client['URL'] = _data[98:222] _this_client['SOFTWARE_ID'] = _data[222:262] _this_client['PACKAGE_ID'] = _data[262:302] self.send_client(_radio_id, 'RPTACK'+_radio_id) self._logger.info('(%s) Client %s (%s) has sent repeater configuration', self._system, _this_client['CALLSIGN'], _this_client['RADIO_ID']) else: self.transport.write('MSTNAK'+_radio_id, (_host, _port)) self._logger.warning('(%s) Client info from Radio ID that has not logged in: %s', self._system, int_id(_radio_id)) elif _command == 'RPTP': # RPTPing -- client is pinging us _radio_id = _data[7:11] if _radio_id in self._clients \ and self._clients[_radio_id]['CONNECTION'] == "YES" \ and self._clients[_radio_id]['IP'] == _host \ and self._clients[_radio_id]['PORT'] == _port: self._clients[_radio_id]['LAST_PING'] = time() self.send_client(_radio_id, 'MSTPONG'+_radio_id) self._logger.debug('(%s) Received and answered RPTPING from client %s (%s)', self._system, self._clients[_radio_id]['CALLSIGN'], int_id(_radio_id)) else: self.transport.write('MSTNAK'+_radio_id, (_host, _port)) self._logger.warning('(%s) Client info from Radio ID that has not logged in: %s', self._system, int_id(_radio_id)) else: self._logger.error('(%s) Unrecognized command from: %s. Packet: %s', self._system, int_id(_radio_id), ahex(_data))
def master_datagramReceived(self, _data, _sockaddr): # Keep This Line Commented Unless HEAVILY Debugging! # self._logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_data)) # Extract the command, which is various length, all but one 4 significant characters -- RPTCL _command = _data[:4] if _command == 'DMRD': # DMRData -- encapsulated DMR data frame _peer_id = _data[11:15] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'YES' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _seq = _data[4] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = int_id(_data[15]) _slot = 2 if (_bits & 0x80) else 1 _call_type = 'unit' if (_bits & 0x40) else 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = ( _bits & 0xF ) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] #self._logger.debug('(%s) DMRD - Seqence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id)) # If AMBE audio exporting is configured... if self._config['EXPORT_AMBE']: self._ambe.parseAMBE(self._system, _data) # The basic purpose of a master is to repeat to the peers if self._config['REPEAT'] == True: for _peer in self._peers: if _peer != _peer_id: #self.send_peer(_peer, _data) self.send_peer(_peer, _data[:11] + _peer + _data[15:]) #self.send_peer(_peer, _data[:11] + self._config['RADIO_ID'] + _data[15:]) #self._logger.debug('(%s) Packet on TS%s from %s (%s) for destination ID %s repeated to peer: %s (%s) [Stream ID: %s]', self._system, _slot, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id), int_id(_dst_id), self._peers[_peer]['CALLSIGN'], int_id(_peer), int_id(_stream_id)) # Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == 'RPTL': # RPTLogin -- a repeater wants to login _peer_id = _data[4:8] if allow_reg(_peer_id): # Check for valid Radio ID self._peers.update({_peer_id: { # Build the configuration data strcuture for the peer 'CONNECTION': 'RPTL-RECEIVED', 'PINGS_RECEIVED': 0, 'LAST_PING': time(), 'SOCKADDR': _sockaddr, 'IP': _sockaddr[0], 'PORT': _sockaddr[1], 'SALT': randint(0,0xFFFFFFFF), 'RADIO_ID': str(int(ahex(_peer_id), 16)), 'CALLSIGN': '', 'RX_FREQ': '', 'TX_FREQ': '', 'TX_POWER': '', 'COLORCODE': '', 'LATITUDE': '', 'LONGITUDE': '', 'HEIGHT': '', 'LOCATION': '', 'DESCRIPTION': '', 'SLOTS': '', 'URL': '', 'SOFTWARE_ID': '', 'PACKAGE_ID': '', }}) self._logger.info( '(%s) Repeater Logging in with Radio ID: %s, %s:%s', self._system, int_id(_peer_id), _sockaddr[0], _sockaddr[1]) _salt_str = hex_str_4(self._peers[_peer_id]['SALT']) self.send_peer(_peer_id, 'RPTACK' + _salt_str) self._peers[_peer_id]['CONNECTION'] = 'CHALLENGE_SENT' self._logger.info( '(%s) Sent Challenge Response to %s for login: %s', self._system, int_id(_peer_id), self._peers[_peer_id]['SALT']) else: self.transport.write('MSTNAK' + _peer_id, _sockaddr) self._logger.warning( '(%s) Invalid Login from Radio ID: %s Denied by Registation ACL', self._system, int_id(_peer_id)) elif _command == 'RPTK': # Repeater has answered our login challenge _peer_id = _data[4:8] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'CHALLENGE_SENT' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _this_peer = self._peers[_peer_id] _this_peer['LAST_PING'] = time() _sent_hash = _data[8:] _salt_str = hex_str_4(_this_peer['SALT']) _calc_hash = bhex( sha256(_salt_str + self._config['PASSPHRASE']).hexdigest()) if _sent_hash == _calc_hash: _this_peer['CONNECTION'] = 'WAITING_CONFIG' self.send_peer(_peer_id, 'RPTACK' + _peer_id) self._logger.info( '(%s) Peer %s has completed the login exchange successfully', self._system, _this_peer['RADIO_ID']) else: self._logger.info( '(%s) Peer %s has FAILED the login exchange successfully', self._system, _this_peer['RADIO_ID']) self.transport.write('MSTNAK' + _peer_id, _sockaddr) del self._peers[_peer_id] else: self.transport.write('MSTNAK' + _peer_id, _sockaddr) self._logger.warning( '(%s) Login challenge from Radio ID that has not logged in: %s', self._system, int_id(_peer_id)) elif _command == 'RPTC': # Repeater is sending it's configuraiton OR disconnecting if _data[:5] == 'RPTCL': # Disconnect command _peer_id = _data[5:9] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'YES' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: self._logger.info('(%s) Peer is closing down: %s (%s)', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id)) self.transport.write('MSTNAK' + _peer_id, _sockaddr) del self._peers[_peer_id] else: _peer_id = _data[4:8] # Configure Command if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'WAITING_CONFIG' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _this_peer = self._peers[_peer_id] _this_peer['CONNECTION'] = 'YES' _this_peer['LAST_PING'] = time() _this_peer['CALLSIGN'] = _data[8:16] _this_peer['RX_FREQ'] = _data[16:25] _this_peer['TX_FREQ'] = _data[25:34] _this_peer['TX_POWER'] = _data[34:36] _this_peer['COLORCODE'] = _data[36:38] _this_peer['LATITUDE'] = _data[38:46] _this_peer['LONGITUDE'] = _data[46:55] _this_peer['HEIGHT'] = _data[55:58] _this_peer['LOCATION'] = _data[58:78] _this_peer['DESCRIPTION'] = _data[78:97] _this_peer['SLOTS'] = _data[97:98] _this_peer['URL'] = _data[98:222] _this_peer['SOFTWARE_ID'] = _data[222:262] _this_peer['PACKAGE_ID'] = _data[262:302] self.send_peer(_peer_id, 'RPTACK' + _peer_id) self._logger.info( '(%s) Peer %s (%s) has sent repeater configuration', self._system, _this_peer['CALLSIGN'], _this_peer['RADIO_ID']) else: self.transport.write('MSTNAK' + _peer_id, _sockaddr) self._logger.warning( '(%s) Peer info from Radio ID that has not logged in: %s', self._system, int_id(_peer_id)) elif _command == 'RPTP': # RPTPing -- peer is pinging us _peer_id = _data[7:11] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == "YES" \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: self._peers[_peer_id]['PINGS_RECEIVED'] += 1 self._peers[_peer_id]['LAST_PING'] = time() self.send_peer(_peer_id, 'MSTPONG' + _peer_id) self._logger.debug( '(%s) Received and answered RPTPING from peer %s (%s)', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id)) else: self.transport.write('MSTNAK' + _peer_id, _sockaddr) self._logger.warning( '(%s) Peer info from Radio ID that has not logged in: %s', self._system, int_id(_peer_id)) else: self._logger.error('(%s) Unrecognized command. Raw HBP PDU: %s', self._system, ahex(_data))
# Keep This Line Commented Unless HEAVILY Debugging! # self._logger.debug('(%s) RX packet from %s:%s -- %s', self._system, _host, _port, ahex(_data)) # Validate that we receveived this packet from the master - security check! if self._config['MASTER_IP'] == _host and self._config[ 'MASTER_PORT'] == _port: # Extract the command, which is various length, but only 4 significant characters _command = _data[:4] if _command == 'DMRD': # DMRData -- encapsulated DMR data frame _radio_id = _data[11:15] if self._config['LOOSE'] or _radio_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation _seq = _data[4:5] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = int_id(_data[15]) _slot = 2 if (_bits & 0x80) else 1 _call_type = 'unit' if (_bits & 0x40) else 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = ( _bits & 0xF ) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] self._logger.debug( '(%s) DMRD - Sequence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id)) # If AMBE audio exporting is configured... if self._config['EXPORT_AMBE']: self._ambe.parseAMBE(self._system, _data)
def private_voice(self, _src_sub, _dst_sub, _ts, _end, _peerid, _data): if HEX_SUB == _dst_sub and _ts in PRIVATE_TS: if not _end: if not self.CALL_DATA: self._logger.info('(%s) Receiving transmission to be played back from subscriber: %s, to subscriber: %s', self._system, int_id(_src_sub), int_id(_dst_sub)) _tmp_data = _data self.CALL_DATA.append(_tmp_data) if _end: self.CALL_DATA.append(_data) time.sleep(1) self._logger.info('(%s) Playing back transmission from subscriber: %s, to subscriber %s', self._system, int_id(_src_sub), int_id(_dst_sub)) _orig_src = _src_sub _orig_dst = _dst_sub for i in self.CALL_DATA: _tmp_data = i _tmp_data = _tmp_data.replace(_peerid, self._config['LOCAL']['RADIO_ID']) _tmp_data = _tmp_data.replace(_dst_sub, BOGUS_SUB) _tmp_data = _tmp_data.replace(_src_sub, _orig_dst) _tmp_data = _tmp_data.replace(BOGUS_SUB, _orig_src) # Send the packet to all peers in the target IPSC self.send_to_ipsc(_tmp_data) time.sleep(0.06) self.CALL_DATA = []
def build_bridge_table(): _now = time() _cnow = strftime('%Y-%m-%d %H:%M:%S', localtime(_now)) table = '<h3>Bridge Group Status Tables</h3>' table += '<p>Table Last Updated: {}<br>'.format(_cnow) table += 'Data Last Updated: {}</p>'.format(BRIDGES_RX) for bridge in BRIDGES: table += '<style>table, td, th {border: .5px solid black; padding: 2px; border-collapse: collapse}</style>' table += '<table style="width:90%; font: 10pt arial, sans-serif">' table += '<colgroup>\ <col style="width: 20%" />\ <col style="width: 5%" />\ <col style="width: 5%" />\ <col style="width: 10%" />\ <col style="width: 10%" />\ <col style="width: 10%" />\ <col style="width: 10%" />\ <col style="width: 10%" />\ <col style="width: 10%" />\ </colgroup>' table += '<caption>{}</caption>'.format(bridge) table += '<tr><th>System</th>\ <th>Slot</th>\ <th>TGID</th>\ <th>Status</th>\ <th>Timeout</th>\ <th>Timeout Action</th>\ <th>ON Triggers</th>\ <th>OFF Triggers</th></tr>' for system in BRIDGES[bridge]: on = '' off = '' active = '<td bgcolor="#FFFF00">Unknown</td>' if system['TO_TYPE'] == 'ON' or system['TO_TYPE'] == 'OFF': if system['TIMER'] - _now > 0: exp_time = int(system['TIMER'] - _now) else: exp_time = 'Expired' if system['TO_TYPE'] == 'ON': to_action = 'Turn OFF' else: to_action = 'Turn ON' else: exp_time = 'N/A' to_action = 'None' if system['ACTIVE'] == True: active = '<td bgcolor="#00FF00">Connected</td>' elif system['ACTIVE'] == False: active = '<td bgcolor="#FF0000">Disconnected</td>' for trigger in system['ON']: on += str(int_id(trigger)) + ' ' for trigger in system['OFF']: off += str(int_id(trigger)) + ' ' table += '<tr> <td>{}</td> <td>{}</td> <td>{}</td> {} <td>{}</td> <td>{}</td> <td>{}</td> <td>{}</td> </tr>'.format(\ system['SYSTEM'],\ system['TS'],\ int_id(system['TGID']),\ active,\ exp_time,\ to_action,\ on,\ off) table += '</table><br>' return table
def unknown_message(self, _packettype, _peerid, _data): self._logger.error('(%s) Unknown Message - Type: %s From: %s Packet: %s', ahex(_packettype), self._system, int_id(_peerid), ahex(_data))
def peer_alive_req(self, _data, _peerid, _host, _port): _hex_mode = (_data[5]) _hex_flags = (_data[6:10]) _decoded_mode = process_mode_byte(_hex_mode) _decoded_flags = process_flags_bytes(_hex_flags) self._peers[_peerid]['MODE'] = _hex_mode self._peers[_peerid]['MODE_DECODE'] = _decoded_mode self._peers[_peerid]['FLAGS'] = _hex_flags self._peers[_peerid]['FLAGS_DECODE'] = _decoded_flags self.send_packet(self.PEER_ALIVE_REPLY_PKT, (_host, _port)) self.reset_keep_alive(_peerid) # Might as well reset our own counter, we know it's out there... self._logger.debug('(%s) Keep-Alive reply sent to Peer %s, %s:%s', self._system, int_id(_peerid), _host, _port)
def private_data(self, _src_sub, _dst_sub, _ts, _end, _peerid, _data): self._logger.debug('(%s) Private Data Packet Received From: %s, IPSC Peer %s, Destination %s', self._system, int_id(_src_sub), int_id(_peerid), int_id(_dst_sub))
def group_voice(self, _src_sub, _dst_sub, _ts, _end, _peerid, _data): self._logger.debug('(%s) Group Voice Packet Received From: %s, IPSC Peer %s, Destination %s', self._system, int_id(_src_sub), int_id(_peerid), int_id(_dst_sub))
self._logger.debug('(%s) import_datagramReceived', self._system) _slot = self._slot _rx_slot = self.rx[_slot] # Parse out the TLV t = _data[0] if (t): l = _data[1] if (l): v = _data[2:] if (v): t = ord(t) if (t == TAG_BEGIN_TX) or (t == TAG_SET_INFO): if ord(l) > 1: _slot = int_id(v[10:11]) _rx_slot = self.rx[_slot] _rx_slot.slot = _slot _rx_slot.rf_src = hex_str_3(int_id(v[0:3])) _rx_slot.repeater_id = self._parent.get_repeater_id( hex_str_4(int_id(v[3:7]))) _rx_slot.dst_id = hex_str_3(int_id(v[7:10])) _rx_slot.cc = int_id(v[11:12]) if t == TAG_BEGIN_TX: _rx_slot.stream_id = hex_str_4( randint(0, 0xFFFFFFFF) ) # Every stream has a unique ID self._logger.info('(%s) Begin AMBE encode STREAM ID: %s SUB: %s (%s) REPEATER: %s (%s) TGID %s (%s), TS %s', \ self._system, int_id(_rx_slot.stream_id), get_alias(_rx_slot.rf_src, subscriber_ids), int_id(_rx_slot.rf_src), get_alias(_rx_slot.repeater_id, peer_ids), int_id(_rx_slot.repeater_id), get_alias(_rx_slot.dst_id, talkgroup_ids), int_id(_rx_slot.dst_id), _slot) self.send_voice_header(_rx_slot)
def peer_maintenance_loop(self): self._logger.debug('(%s) PEER Connection Maintenance Loop Started', self._system) # If the master isn't connected, we have to do that before we can do anything else! # if not self._master_stat['CONNECTED']: self.send_packet(self.MASTER_REG_REQ_PKT, self._master_sock) self._logger.info('(%s) Registering with the Master: %s:%s', self._system, self._master['IP'], self._master['PORT']) # Once the master is connected, we have to send keep-alives.. and make sure we get them back elif self._master_stat['CONNECTED']: # Send keep-alive to the master self.send_packet(self.MASTER_ALIVE_PKT, self._master_sock) self._logger.debug('(%s) Keep Alive Sent to the Master: %s, %s:%s', self._system, int_id(self._master['RADIO_ID']) ,self._master['IP'], self._master['PORT']) # If we had a keep-alive outstanding by the time we send another, mark it missed. if (self._master_stat['KEEP_ALIVES_OUTSTANDING']) > 0: self._master_stat['KEEP_ALIVES_MISSED'] += 1 self._logger.info('(%s) Master Keep-Alive Missed: %s:%s', self._system, self._master['IP'], self._master['PORT']) # If we have missed too many keep-alives, de-register the master and start over. if self._master_stat['KEEP_ALIVES_OUTSTANDING'] >= self._local['MAX_MISSED']: self._master_stat['CONNECTED'] = False self._master_stat['KEEP_ALIVES_OUTSTANDING'] = 0 self._logger.error('(%s) Maximum Master Keep-Alives Missed -- De-registering the Master: %s:%s', self._system, self._master['IP'], self._master['PORT']) # Update our stats before we move on... self._master_stat['KEEP_ALIVES_SENT'] += 1 self._master_stat['KEEP_ALIVES_OUTSTANDING'] += 1 else: # This is bad. If we get this message, we need to reset the state and try again self._logger.error('->> (%s) Master in UNKOWN STATE: %s:%s', self._system, self._master_sock) self._master_stat['CONNECTED'] = False # If the master is connected and we don't have a peer-list yet.... # if (self._master_stat['CONNECTED'] == True) and (self._master_stat['PEER_LIST'] == False): # Ask the master for a peer-list if self._local['NUM_PEERS']: self.send_packet(self.PEER_LIST_REQ_PKT, self._master_sock) self._logger.info('(%s), No Peer List - Requesting One From the Master', self._system) else: self._master_stat['PEER_LIST'] = True self._logger.debug('(%s), Skip asking for a Peer List, we are the only Peer', self._system) # If we do have a peer-list, we need to register with the peers and send keep-alives... # if self._master_stat['PEER_LIST']: # Iterate the list of peers... so we do this for each one. for peer in self._peers.keys(): # We will show up in the peer list, but shouldn't try to talk to ourselves. if peer == self._local_id: continue # If we haven't registered to a peer, send a registration if not self._peers[peer]['STATUS']['CONNECTED']: self.send_packet(self.PEER_REG_REQ_PKT, (self._peers[peer]['IP'], self._peers[peer]['PORT'])) self._logger.info('(%s) Registering with Peer %s, %s:%s', self._system, int_id(peer), self._peers[peer]['IP'], self._peers[peer]['PORT']) # If we have registered with the peer, then send a keep-alive elif self._peers[peer]['STATUS']['CONNECTED']: self.send_packet(self.PEER_ALIVE_REQ_PKT, (self._peers[peer]['IP'], self._peers[peer]['PORT'])) self._logger.debug('(%s) Keep-Alive Sent to the Peer %s, %s:%s', self._system, int_id(peer), self._peers[peer]['IP'], self._peers[peer]['PORT']) # If we have a keep-alive outstanding by the time we send another, mark it missed. if self._peers[peer]['STATUS']['KEEP_ALIVES_OUTSTANDING'] > 0: self._peers[peer]['STATUS']['KEEP_ALIVES_MISSED'] += 1 self._logger.info('(%s) Peer Keep-Alive Missed for %s, %s:%s', self._system, int_id(peer), self._peers[peer]['IP'], self._peers[peer]['PORT']) # If we have missed too many keep-alives, de-register the peer and start over. if self._peers[peer]['STATUS']['KEEP_ALIVES_OUTSTANDING'] >= self._local['MAX_MISSED']: self._peers[peer]['STATUS']['CONNECTED'] = False #del peer # Becuase once it's out of the dictionary, you can't use it for anything else. self._logger.warning('(%s) Maximum Peer Keep-Alives Missed -- De-registering the Peer: %s, %s:%s', self._system, int_id(peer), self._peers[peer]['IP'], self._peers[peer]['PORT']) # Update our stats before moving on... self._peers[peer]['STATUS']['KEEP_ALIVES_SENT'] += 1 self._peers[peer]['STATUS']['KEEP_ALIVES_OUTSTANDING'] += 1
def acl_check(_id, _acl): id = int_id(_id) for entry in _acl[1]: if entry[0] <= id <= entry[1]: return _acl[0] return not _acl[0]
def build_hblink_table(_config, _stats_table): for _hbp, _hbp_data in _config.iteritems(): if _hbp_data['ENABLED'] == True: # Process Master Systems if _hbp_data['MODE'] == 'MASTER': _stats_table['MASTERS'][_hbp] = {} if _hbp_data['REPEAT']: _stats_table['MASTERS'][_hbp]['REPEAT'] = "repeat" else: _stats_table['MASTERS'][_hbp]['REPEAT'] = "isolate" _stats_table['MASTERS'][_hbp]['PEERS'] = {} for _peer in _hbp_data['PEERS']: add_hb_peer(_hbp_data['PEERS'][_peer], _stats_table['MASTERS'][_hbp]['PEERS'], _peer) # Proccess Peer Systems elif _hbp_data['MODE'] == 'PEER' or _hbp_data['MODE'] == 'XLXPEER': _stats_table['PEERS'][_hbp] = {} _stats_table['PEERS'][_hbp]['MODE'] = _hbp_data['MODE'] _stats_table['PEERS'][_hbp]['CALLSIGN'] = _hbp_data['CALLSIGN'] _stats_table['PEERS'][_hbp]['LOCATION'] = _hbp_data['LOCATION'] _stats_table['PEERS'][_hbp]['RADIO_ID'] = int_id(_hbp_data['RADIO_ID']) _stats_table['PEERS'][_hbp]['MASTER_IP'] = _hbp_data['MASTER_IP'] _stats_table['PEERS'][_hbp]['MASTER_PORT'] = _hbp_data['MASTER_PORT'] _stats_table['PEERS'][_hbp]['STATS'] = {} if _stats_table['PEERS'][_hbp]['MODE'] == 'XLXPEER': _stats_table['PEERS'][_hbp]['STATS']['CONNECTION'] = _hbp_data['XLXSTATS']['CONNECTION'] _stats_table['PEERS'][_hbp]['STATS']['CONNECTED'] = since(_hbp_data['XLXSTATS']['CONNECTED']) _stats_table['PEERS'][_hbp]['STATS']['PINGS_SENT'] = _hbp_data['XLXSTATS']['PINGS_SENT'] _stats_table['PEERS'][_hbp]['STATS']['PINGS_ACKD'] = _hbp_data['XLXSTATS']['PINGS_ACKD'] else: _stats_table['PEERS'][_hbp]['STATS']['CONNECTION'] = _hbp_data['STATS']['CONNECTION'] _stats_table['PEERS'][_hbp]['STATS']['CONNECTED'] = since(_hbp_data['STATS']['CONNECTED']) _stats_table['PEERS'][_hbp]['STATS']['PINGS_SENT'] = _hbp_data['STATS']['PINGS_SENT'] _stats_table['PEERS'][_hbp]['STATS']['PINGS_ACKD'] = _hbp_data['STATS']['PINGS_ACKD'] if _hbp_data['SLOTS'] == 0: _stats_table['PEERS'][_hbp]['SLOTS'] = 'NONE' elif _hbp_data['SLOTS'] <= '2': _stats_table['PEERS'][_hbp]['SLOTS'] = _hbp_data['SLOTS'] elif _hbp_data['SLOTS'] == '3': _stats_table['PEERS'][_hbp]['SLOTS'] = 'BOTH' else: _stats_table['SLOTS'][_hbp]['SLOTS'] = 'DMO' # SLOT 1&2 - for real-time montior: make the structure for later use for ts in range(1,3): _stats_table['PEERS'][_hbp][ts]= {} _stats_table['PEERS'][_hbp][ts]['COLOR'] = '' _stats_table['PEERS'][_hbp][ts]['BGCOLOR'] = '' _stats_table['PEERS'][_hbp][ts]['TS'] = '' _stats_table['PEERS'][_hbp][ts]['TYPE'] = '' _stats_table['PEERS'][_hbp][ts]['SUB'] = '' _stats_table['PEERS'][_hbp][ts]['SRC'] = '' _stats_table['PEERS'][_hbp][ts]['DEST'] = '' # Process OpenBridge systems elif _hbp_data['MODE'] == 'OPENBRIDGE': _stats_table['OPENBRIDGES'][_hbp] = {} _stats_table['OPENBRIDGES'][_hbp]['NETWORK_ID'] = int_id(_hbp_data['NETWORK_ID']) _stats_table['OPENBRIDGES'][_hbp]['TARGET_IP'] = _hbp_data['TARGET_IP'] _stats_table['OPENBRIDGES'][_hbp]['TARGET_PORT'] = _hbp_data['TARGET_PORT'] _stats_table['OPENBRIDGES'][_hbp]['STREAMS'] = {}
def peer_list_reply(self, _data, _peerid): self._master['STATUS']['PEER_LIST'] = True if len(_data) > 18: self.process_peer_list(_data) self._logger.debug('(%s) Peer List Reply Received From Master %s, %s:%s', self._system, int_id(_peerid), self._master['IP'], self._master['PORT'])
def peer_datagramReceived(self, _data, _sockaddr): # Keep This Line Commented Unless HEAVILY Debugging! # self._logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_data)) # Validate that we receveived this packet from the master - security check! if self._config['MASTER_SOCKADDR'] == _sockaddr: # Extract the command, which is various length, but only 4 significant characters _command = _data[:4] if _command == 'DMRD': # DMRData -- encapsulated DMR data frame _peer_id = _data[11:15] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation _seq = _data[4:5] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = int_id(_data[15]) _slot = 2 if (_bits & 0x80) else 1 _call_type = 'unit' if (_bits & 0x40) else 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = ( _bits & 0xF ) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] self._logger.debug( '(%s) DMRD - Sequence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id)) # If AMBE audio exporting is configured... if self._config['EXPORT_AMBE']: self._ambe.parseAMBE(self._system, _data) # Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == 'MSTN': # Actually MSTNAK -- a NACK from the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._logger.warning( '(%s) MSTNAK Received. Resetting connection to the Master.', self._system) self._stats[ 'CONNECTION'] = 'NO' # Disconnect ourselves and re-register elif _command == 'RPTA': # Actually RPTACK -- an ACK from the master # Depending on the state, an RPTACK means different things, in each clause, we check and/or set the state if self._stats[ 'CONNECTION'] == 'RPTL_SENT': # If we've sent a login request... _login_int32 = _data[6:10] self._logger.info( '(%s) Repeater Login ACK Received with 32bit ID: %s', self._system, int_id(_login_int32)) _pass_hash = sha256( _login_int32 + self._config['PASSPHRASE']).hexdigest() _pass_hash = bhex(_pass_hash) self.send_master('RPTK' + self._config['RADIO_ID'] + _pass_hash) self._stats['CONNECTION'] = 'AUTHENTICATED' elif self._stats[ 'CONNECTION'] == 'AUTHENTICATED': # If we've sent the login challenge... _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._logger.info( '(%s) Repeater Authentication Accepted', self._system) _config_packet = self._config['RADIO_ID']+\ self._config['CALLSIGN']+\ self._config['RX_FREQ']+\ self._config['TX_FREQ']+\ self._config['TX_POWER']+\ self._config['COLORCODE']+\ self._config['LATITUDE']+\ self._config['LONGITUDE']+\ self._config['HEIGHT']+\ self._config['LOCATION']+\ self._config['DESCRIPTION']+\ self._config['SLOTS']+\ self._config['URL']+\ self._config['SOFTWARE_ID']+\ self._config['PACKAGE_ID'] self.send_master('RPTC' + _config_packet) self._stats['CONNECTION'] = 'CONFIG-SENT' self._logger.info('(%s) Repeater Configuration Sent', self._system) else: self._stats['CONNECTION'] = 'NO' self._logger.error( '(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif self._stats[ 'CONNECTION'] == 'CONFIG-SENT': # If we've sent out configuration to the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._logger.info( '(%s) Repeater Configuration Accepted', self._system) if self._config['OPTIONS']: self.send_master('RPTO' + self._config['RADIO_ID'] + self._config['OPTIONS']) self._stats['CONNECTION'] = 'OPTIONS-SENT' self._logger.info('(%s) Sent options: (%s)', self._system, self._config['OPTIONS']) else: self._stats['CONNECTION'] = 'YES' self._logger.info( '(%s) Connection to Master Completed', self._system) else: self._stats['CONNECTION'] = 'NO' self._logger.error( '(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif self._stats[ 'CONNECTION'] == 'OPTIONS-SENT': # If we've sent out options to the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._logger.info('(%s) Repeater Options Accepted', self._system) self._stats['CONNECTION'] = 'YES' self._logger.info( '(%s) Connection to Master Completed with options', self._system) else: self._stats['CONNECTION'] = 'NO' self._logger.error( '(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif _command == 'MSTP': # Actually MSTPONG -- a reply to RPTPING (send by peer) _peer_id = _data[7:11] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._stats['PING_OUTSTANDING'] = False self._stats['NUM_OUTSTANDING'] = 0 self._stats['PINGS_ACKD'] += 1 self._logger.debug( '(%s) MSTPONG Received. Pongs Since Connected: %s', self._system, self._stats['PINGS_ACKD']) elif _command == 'MSTC': # Actually MSTCL -- notify us the master is closing down _peer_id = _data[5:9] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._stats['CONNECTION'] = 'NO' self._logger.info('(%s) MSTCL Recieved', self._system) else: self._logger.error( '(%s) Received an invalid command in packet: %s', self._system, ahex(_data))
def master_reg_reply(self, _data, _peerid): _hex_mode = _data[5] _hex_flags = _data[6:10] _num_peers = _data[10:12] _decoded_mode = process_mode_byte(_hex_mode) _decoded_flags = process_flags_bytes(_hex_flags) self._local['NUM_PEERS'] = int(ahex(_num_peers), 16) self._master['RADIO_ID'] = _peerid self._master['MODE'] = _hex_mode self._master['MODE_DECODE'] = _decoded_mode self._master['FLAGS'] = _hex_flags self._master['FLAGS_DECODE'] = _decoded_flags self._master_stat['CONNECTED'] = True self._master_stat['KEEP_ALIVES_OUTSTANDING'] = 0 self._logger.warning('(%s) Registration response (we requested reg) from the Master: %s, %s:%s (%s peers)', self._system, int_id(_peerid), self._master['IP'], self._master['PORT'], self._local['NUM_PEERS'])
def group_voice(self, _src_sub, _dst_sub, _ts, _end, _peerid, _data): if HEX_TGID == _dst_sub and _ts in GROUP_TS: if not _end: if not self.CALL_DATA: self._logger.info('(%s) Receiving transmission to be played back from subscriber: %s', self._system, int_id(_src_sub)) _tmp_data = _data #_tmp_data = dmr_nat(_data, _src_sub, self._config['LOCAL']['RADIO_ID']) self.CALL_DATA.append(_tmp_data) if _end: self.CALL_DATA.append(_data) time.sleep(2) self._logger.info('(%s) Playing back transmission from subscriber: %s', self._system, int_id(_src_sub)) for i in self.CALL_DATA: _tmp_data = i _tmp_data = _tmp_data.replace(_peerid, self._config['LOCAL']['RADIO_ID']) if GROUP_SRC_SUB: _tmp_data = _tmp_data.replace(_src_sub, self.GROUP_SRC_SUB) # Send the packet to all peers in the target IPSC self.send_to_ipsc(_tmp_data) time.sleep(0.06) self.CALL_DATA = []
def master_reg_req(self, _data, _peerid, _host, _port): _ip_address = _host _port = _port _hex_mode = _data[5] _hex_flags = _data[6:10] _decoded_mode = process_mode_byte(_hex_mode) _decoded_flags = process_flags_bytes(_hex_flags) self.MASTER_REG_REPLY_PKT = (MASTER_REG_REPLY + self._local_id + self.TS_FLAGS + hex_str_2(self._local['NUM_PEERS']) + IPSC_VER) self.send_packet(self.MASTER_REG_REPLY_PKT, (_host, _port)) self._logger.info('(%s) Master Registration Packet Received from peer %s, %s:%s', self._system, int_id(_peerid), _host, _port) # If this entry was NOT already in our list, add it. if _peerid not in self._peers.keys(): self._peers[_peerid] = { 'IP': _ip_address, 'PORT': _port, 'MODE': _hex_mode, 'MODE_DECODE': _decoded_mode, 'FLAGS': _hex_flags, 'FLAGS_DECODE': _decoded_flags, 'STATUS': { 'CONNECTED': True, 'KEEP_ALIVES_SENT': 0, 'KEEP_ALIVES_MISSED': 0, 'KEEP_ALIVES_OUTSTANDING': 0, 'KEEP_ALIVES_RECEIVED': 0, 'KEEP_ALIVE_RX_TIME': int(time()) } } self._local['NUM_PEERS'] = len(self._peers) self._logger.debug('(%s) Peer Added To Peer List: %s, %s:%s (IPSC now has %s Peers)', self._system, self._peers[_peerid], _host, _port, self._local['NUM_PEERS'])
# Aliased in __init__ to datagramReceived if system is a client def client_datagramReceived(self, _data, (_host, _port)): # Keep This Line Commented Unless HEAVILY Debugging! # self._logger.debug('(%s) RX packet from %s:%s -- %s', self._system, _host, _port, ahex(_data)) # Validate that we receveived this packet from the master - security check! if self._config['MASTER_IP'] == _host and self._config['MASTER_PORT'] == _port: # Extract the command, which is various length, but only 4 significant characters _command = _data[:4] if _command == 'DMRD': # DMRData -- encapsulated DMR data frame _radio_id = _data[11:15] if _radio_id == self._config['RADIO_ID']: # Validate the source and intended target _seq = _data[4:5] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = int_id(_data[15]) _slot = 2 if (_bits & 0x80) else 1 _call_type = 'unit' if (_bits & 0x40) else 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = (_bits & 0xF) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] #self._logger.debug('(%s) DMRD - Seqence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id)) # If AMBE audio exporting is configured... if self._config['EXPORT_AMBE']: self._ambe.parseAMBE(self._system, _data) # Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_radio_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == 'MSTN': # Actually MSTNAK -- a NACK from the master
def master_alive_req(self, _peerid, _host, _port): if _peerid in self._peers.keys(): self._peers[_peerid]['STATUS']['KEEP_ALIVES_RECEIVED'] += 1 self._peers[_peerid]['STATUS']['KEEP_ALIVE_RX_TIME'] = int(time()) self.send_packet(self.MASTER_ALIVE_REPLY_PKT, (_host, _port)) self._logger.debug('(%s) Master Keep-Alive Request Received from peer %s, %s:%s', self._system, int_id(_peerid), _host, _port) else: self._logger.warning('(%s) Master Keep-Alive Request Received from *UNREGISTERED* peer %s, %s:%s', self._system, int_id(_peerid), _host, _port)
def peer_reg_req(self, _peerid, _host, _port): self.send_packet(self.PEER_REG_REPLY_PKT, (_host, _port)) self._logger.info('(%s) Peer Registration Request From: %s, %s:%s', self._system, int_id(_peerid), _host, _port)
# Check for auth and authenticate the packet # Strip the hash from the end... we don't need it anymore # # Once they're done, we move on to the processing or callbacks for each packet type. # # Callbacks are iterated in the order of "more likely" to "less likely" to reduce processing time # def datagramReceived(self, data, (host, port)): _packettype = data[0:1] _peerid = data[1:5] _ipsc_seq = data[5:6] # AUTHENTICATE THE PACKET if self._local['AUTH_ENABLED']: if not self.validate_auth(self._local['AUTH_KEY'], data): self._logger.warning('(%s) AuthError: IPSC packet failed authentication. Type %s: Peer: %s, %s:%s', self._system, ahex(_packettype), int_id(_peerid), host, port) return # REMOVE SHA-1 AUTHENTICATION HASH: WE NO LONGER NEED IT else: data = self.strip_hash(data) # PACKETS THAT WE RECEIVE FROM ANY VALID PEER OR VALID MASTER if _packettype in ANY_PEER_REQUIRED: if not(self.valid_master(_peerid) == False or self.valid_peer(_peerid) == False): self._logger.warning('(%s) PeerError: Peer not in peer-list: %s, %s:%s', self._system, int_id(_peerid), host, port) return # ORIGINATED BY SUBSCRIBER UNITS - a.k.a someone transmitted if _packettype in USER_PACKETS: # Extract IPSC header not already extracted
def build_dmrlink_table(): _cnow = strftime('%Y-%m-%d %H:%M:%S', localtime(time())) table = '<h3>IPSC Systems Status Tables</h3>' table += '<p>Table Last Updated: {} <br>'.format(_cnow) table += 'Data Last Updated: {}</p>'.format(CONFIG_RX) table += '<style>table, td, th {border: .5px solid black; padding: 2px; border-collapse: collapse}</style>' for ipsc in CONFIG: master = CONFIG[ipsc]['LOCAL']['MASTER_PEER'] table += '<table style="width:90%; font: 10pt arial, sans-serif">' table += '<colgroup>\ <col style="width: 30%" />\ <col style="width: 15%" />\ <col style="width: 15%" />\ <col style="width: 15%" />\ <col style="width: 10%" />\ <col style="width: 5%" />\ <col style="width: 5%" />\ <col style="width: 5%" />\ </colgroup>' table += '<caption>IPSC System: <b>{}</b><br>'.format(ipsc) if master: table += 'DMRlink is the system Master' else: table += 'DMRlink is a system Peer' table += '</caption>' table += '<tr><th rowspan="2">Alias</th>\ <th rowspan="2">Type</th>\ <th rowspan="2">Radio ID</th>\ <th rowspan="2">IP Address</th>\ <th rowspan="2">Status</th>\ <th colspan="3">Keep Alives</th></tr>\ <tr><th>Sent</th><th>Received</th><th>Missed</th></tr>' if not master: stat = CONFIG[ipsc]['MASTER']['STATUS'] if stat['CONNECTED'] == True: active = '<td bgcolor="#00FF00">Connected</td>' elif stat['CONNECTED'] == False: active = '<td bgcolor="#FF0000">Disconnected</td>' table += '<tr><td>{}</td><td>Master</td><td>{}</td><td>{}</td>{}<td>{}</td><td>{}</td><td>{}</td></tr>'.format(\ alias_string(CONFIG[ipsc]['MASTER']['RADIO_ID'], peer_ids),\ str(int_id(CONFIG[ipsc]['MASTER']['RADIO_ID'])).rjust(8,'0'),\ CONFIG[ipsc]['MASTER']['IP'],\ active,\ stat['KEEP_ALIVES_SENT'],\ stat['KEEP_ALIVES_RECEIVED'],\ stat['KEEP_ALIVES_MISSED'],) if master: for peer in CONFIG[ipsc]['PEERS']: stat = CONFIG[ipsc]['PEERS'][peer]['STATUS'] if stat['CONNECTED'] == True: active = '<td bgcolor="#00FF00">Connected</td>' elif stat['CONNECTED'] == False: active = '<td bgcolor="#FF0000">Disconnected</td>' table += '<tr><td>{}</td><td>Peer</td><td>{}</td><td>{}</td>{}<td>n/a</td><td>{}</td><td>n/a</td></tr>'.format(\ alias_string(peer, peer_ids),\ str(int_id(peer)).rjust(8,'0'),\ CONFIG[ipsc]['PEERS'][peer]['IP'],\ active,\ stat['KEEP_ALIVES_RECEIVED']) else: for peer in CONFIG[ipsc]['PEERS']: stat = CONFIG[ipsc]['PEERS'][peer]['STATUS'] if stat['CONNECTED'] == True: active = '<td bgcolor="#00FF00">Connected</td>' elif stat['CONNECTED'] == False: active = '<td bgcolor="#FF0000">Disconnected</td>' if peer != CONFIG[ipsc]['LOCAL']['RADIO_ID']: table += '<tr><td>{}</td><td>Peer</td><td>{}</td><td>{}</td>{}<td>{}</td><td>{}</td><td>{}</td></tr>'.format(\ alias_string(peer, peer_ids),\ str(int_id(peer)).rjust(8,'0'),\ CONFIG[ipsc]['PEERS'][peer]['IP'],\ active,\ stat['KEEP_ALIVES_SENT'],\ stat['KEEP_ALIVES_RECEIVED'],\ stat['KEEP_ALIVES_MISSED']) table += '</table><br>' return table
def peer_reg_reply(self, _peerid): if _peerid in self._peers.keys(): self._peers[_peerid]['STATUS']['CONNECTED'] = True self._logger.info('(%s) Registration Reply From: %s, %s:%s', self._system, int_id(_peerid), self._peers[_peerid]['IP'], self._peers[_peerid]['PORT'])
def de_register_peer(self, _peerid): # Iterate for the peer in our data if _peerid in self._peers.keys(): del self._peers[_peerid] self._logger.info('(%s) Peer De-Registration Requested for: %s', self._system, int_id(_peerid)) return else: self._logger.warning('(%s) Peer De-Registration Requested for: %s, but we don\'t have a listing for this peer', self._system, int_id(_peerid)) pass
def master_alive_reply(self, _peerid): self.reset_keep_alive(_peerid) self._master['STATUS']['KEEP_ALIVES_RECEIVED'] += 1 self._master['STATUS']['KEEP_ALIVE_RX_TIME'] = int(time()) self._logger.debug('(%s) Keep-Alive Reply (we sent the request) Received from the Master %s, %s:%s', self._system, int_id(_peerid), self._master['IP'], self._master['PORT'])
def group_voice(self, _src_sub, _dst_group, _ts, _end, _peerid, _data): # Check for ACL match, and return if the subscriber is not allowed if allow_sub(_src_sub) == False: self._logger.warning( '(%s) Group Voice Packet ***REJECTED BY ACL*** From: %s, IPSC Peer %s, Destination %s', self._system, int_id(_src_sub), int_id(_peerid), int_id(_dst_group)) return # Process the packet self._logger.debug( '(%s) Group Voice Packet Received From: %s, IPSC Peer %s, Destination %s', self._system, int_id(_src_sub), int_id(_peerid), int_id(_dst_group)) _burst_data_type = _data[ 30] # Determine the type of voice packet this is (see top of file for possible types) _seq_id = _data[5] now = time( ) # Mark packet arrival time -- we'll need this for call contention handling for rule in RULES[self._system]['GROUP_VOICE']: _target = rule[ 'DST_NET'] # Shorthand to reduce length and make it easier to read _status = systems[ _target].IPSC_STATUS # Shorthand to reduce length and make it easier to read # This is the primary rule match to determine if the call will be routed. if (rule['SRC_GROUP'] == _dst_group and rule['SRC_TS'] == _ts and rule['ACTIVE'] == True) and (self.BRIDGE == True or systems[_target].BRIDGE == True): # # BEGIN CONTENTION HANDLING # # If this is an inter-DMRlink trunk, this isn't necessary if RULES[self._system]['TRUNK'] == False: # The rules for each of the 4 "ifs" below are listed here for readability. The Frame To Send is: # From a different group than last RX from this IPSC, but it has been less than Group Hangtime # From a different group than last TX to this IPSC, but it has been less than Group Hangtime # From the same group as the last RX from this IPSC, but from a different subscriber, and it has been less than TS Clear Time # From the same group as the last TX to this IPSC, but from a different subscriber, and it has been less than TS Clear Time # The "continue" at the end of each means the next iteration of the for loop that tests for matching rules # if ((rule['DST_GROUP'] != _status[rule['DST_TS']]['RX_GROUP']) and ((now - _status[rule['DST_TS']]['RX_TIME']) < RULES[_target]['GROUP_HANGTIME'])): if _burst_data_type == BURST_DATA_TYPE['VOICE_HEAD']: self._logger.info( '(%s) Call not bridged to TGID%s, target active or in group hangtime: IPSC: %s, TS: %s, TGID: %s', self._system, int_id(rule['DST_GROUP']), _target, rule['DST_TS'], int_id(_status[rule['DST_TS']]['RX_GROUP'])) continue if ((rule['DST_GROUP'] != _status[rule['DST_TS']]['TX_GROUP']) and ((now - _status[rule['DST_TS']]['TX_TIME']) < RULES[_target]['GROUP_HANGTIME'])): if _burst_data_type == BURST_DATA_TYPE['VOICE_HEAD']: self._logger.info( '(%s) Call not bridged to TGID%s, target in group hangtime: IPSC: %s, TS: %s, TGID: %s', self._system, int_id(rule['DST_GROUP']), _target, rule['DST_TS'], int_id(_status[rule['DST_TS']]['TX_GROUP'])) continue if (rule['DST_GROUP'] == _status[rule['DST_TS']]['RX_GROUP']) and ( (now - _status[rule['DST_TS']]['RX_TIME']) < TS_CLEAR_TIME): if _burst_data_type == BURST_DATA_TYPE['VOICE_HEAD']: self._logger.info( '(%s) Call not bridged to TGID%s, matching call already active on target: IPSC: %s, TS: %s, TGID: %s', self._system, int_id(rule['DST_GROUP']), _target, rule['DST_TS'], int_id(_status[rule['DST_TS']]['RX_GROUP'])) continue if (rule['DST_GROUP'] == _status[rule['DST_TS']]['TX_GROUP']) and ( _src_sub != _status[rule['DST_TS']]['TX_SRC_SUB']) and ( (now - _status[rule['DST_TS']]['TX_TIME']) < TS_CLEAR_TIME): if _burst_data_type == BURST_DATA_TYPE['VOICE_HEAD']: self._logger.info( '(%s) Call not bridged for subscriber %s, call bridge in progress on target: IPSC: %s, TS: %s, TGID: %s SUB: %s', self._system, int_id(_src_sub), _target, rule['DST_TS'], int_id(_status[rule['DST_TS']]['TX_GROUP']), int_id(_status[rule['DST_TS']]['TX_SRC_SUB'])) continue # # END CONTENTION HANDLING # # # BEGIN FRAME FORWARDING # # Make a copy of the payload _tmp_data = _data # Re-Write the IPSC SRC to match the target network's ID _tmp_data = _tmp_data.replace( _peerid, self._CONFIG['SYSTEMS'][_target]['LOCAL']['RADIO_ID']) # Re-Write the destination Group ID _tmp_data = _tmp_data.replace(_dst_group, rule['DST_GROUP']) # Re-Write IPSC timeslot value _call_info = int_id(_data[17:18]) if rule['DST_TS'] == 1: _call_info &= ~(1 << 5) elif rule['DST_TS'] == 2: _call_info |= 1 << 5 _call_info = chr(_call_info) _tmp_data = _tmp_data[:17] + _call_info + _tmp_data[18:] # Re-Write DMR timeslot value # Determine if the slot is present, so we can translate if need be if _burst_data_type == BURST_DATA_TYPE[ 'SLOT1_VOICE'] or _burst_data_type == BURST_DATA_TYPE[ 'SLOT2_VOICE']: _slot_valid = True else: _slot_valid = False # Re-Write timeslot if necessary... if _slot_valid: if rule['DST_TS'] == 1: _burst_data_type = BURST_DATA_TYPE['SLOT1_VOICE'] elif rule['DST_TS'] == 1: _burst_data_type = BURST_DATA_TYPE['SLOT2_VOICE'] _tmp_data = _tmp_data[:30] + _burst_data_type + _tmp_data[ 31:] # Send the packet to all peers in the target IPSC systems[_target].send_to_ipsc(_tmp_data) # # END FRAME FORWARDING # # Set values for the contention handler to test next time there is a frame to forward _status[_ts]['TX_GROUP'] = rule['DST_GROUP'] _status[_ts]['TX_TIME'] = now _status[_ts]['TX_SRC_SUB'] = _src_sub # Mark the group and time that a packet was recieved for the contention handler to use later self.IPSC_STATUS[_ts]['RX_GROUP'] = _dst_group self.IPSC_STATUS[_ts]['RX_TIME'] = now # # BEGIN IN-BAND SIGNALING BASED ON TGID & VOICE TERMINATOR FRAME # # Activate/Deactivate rules based on group voice activity -- PTT or UA for you c-Bridge dorks. # This will ONLY work for symmetrical rules!!! # Action happens on key up if _burst_data_type == BURST_DATA_TYPE['VOICE_HEAD']: if self.last_seq_id != _seq_id: self.last_seq_id = _seq_id self.call_start = time() self._logger.info( '(%s) GROUP VOICE START: CallID: %s PEER: %s, SUB: %s, TS: %s, TGID: %s', self._system, int_id(_seq_id), int_id(_peerid), int_id(_src_sub), _ts, int_id(_dst_group)) # Action happens on un-key if _burst_data_type == BURST_DATA_TYPE['VOICE_TERM']: if self.last_seq_id == _seq_id: self.call_duration = time() - self.call_start self._logger.info( '(%s) GROUP VOICE END: CallID: %s PEER: %s, SUB: %s, TS: %s, TGID: %s Duration: %.2fs', self._system, int_id(_seq_id), int_id(_peerid), int_id(_src_sub), _ts, int_id(_dst_group), self.call_duration) else: self._logger.warning( '(%s) GROUP VOICE END WITHOUT MATCHING START: CallID: %s PEER: %s, SUB: %s, TS: %s, TGID: %s', self._system, int_id(_seq_id), int_id(_peerid), int_id(_src_sub), _ts, int_id(_dst_group), ) # Iterate the rules dictionary for rule in RULES[self._system]['GROUP_VOICE']: _target = rule['DST_NET'] # TGID matches a rule source, reset its timer if _ts == rule['SRC_TS'] and _dst_group == rule[ 'SRC_GROUP'] and ((rule['TO_TYPE'] == 'ON' and (rule['ACTIVE'] == True)) or (rule['TO_TYPE'] == 'OFF' and rule['ACTIVE'] == False)): rule['TIMER'] = now + rule['TIMEOUT'] self._logger.info( '(%s) Source group transmission match for rule \"%s\". Reset timeout to %s', self._system, rule['NAME'], rule['TIMER']) # Scan for reciprocal rules and reset their timers as well. for target_rule in RULES[_target]['GROUP_VOICE']: if target_rule['NAME'] == rule['NAME']: target_rule['TIMER'] = now + target_rule['TIMEOUT'] self._logger.info( '(%s) Reciprocal group transmission match for rule \"%s\" on IPSC \"%s\". Reset timeout to %s', self._system, target_rule['NAME'], _target, rule['TIMER']) # TGID matches an ACTIVATION trigger if _dst_group in rule['ON']: # Set the matching rule as ACTIVE rule['ACTIVE'] = True rule['TIMER'] = now + rule['TIMEOUT'] self._logger.info( '(%s) Primary Bridge Rule \"%s\" changed to state: %s', self._system, rule['NAME'], rule['ACTIVE']) # Set reciprocal rules for other IPSCs as ACTIVE for target_rule in RULES[_target]['GROUP_VOICE']: if target_rule['NAME'] == rule['NAME']: target_rule['ACTIVE'] = True target_rule['TIMER'] = now + target_rule['TIMEOUT'] self._logger.info( '(%s) Reciprocal Bridge Rule \"%s\" in IPSC \"%s\" changed to state: %s', self._system, target_rule['NAME'], _target, rule['ACTIVE']) # TGID matches an DE-ACTIVATION trigger if _dst_group in rule['OFF']: # Set the matching rule as ACTIVE rule['ACTIVE'] = False self._logger.info( '(%s) Bridge Rule \"%s\" changed to state: %s', self._system, rule['NAME'], rule['ACTIVE']) # Set reciprocal rules for other IPSCs as ACTIVE _target = rule['DST_NET'] for target_rule in RULES[_target]['GROUP_VOICE']: if target_rule['NAME'] == rule['NAME']: target_rule['ACTIVE'] = False self._logger.info( '(%s) Reciprocal Bridge Rule \"%s\" in IPSC \"%s\" changed to state: %s', self._system, target_rule['NAME'], _target, rule['ACTIVE'])
def process_peer_list(self, _data): # Create a temporary peer list to track who we should have in our list -- used to find old peers we should remove. _temp_peers = [] # Determine the length of the peer list for the parsing iterator _peer_list_length = int(ahex(_data[5:7]), 16) # Record the number of peers in the data structure... we'll use it later (11 bytes per peer entry) self._local['NUM_PEERS'] = _peer_list_length/11 self._logger.info('(%s) Peer List Received from Master: %s peers in this IPSC', self._system, self._local['NUM_PEERS']) # Iterate each peer entry in the peer list. Skip the header, then pull the next peer, the next, etc. for i in range(7, _peer_list_length +7, 11): # Extract various elements from each entry... _hex_radio_id = (_data[i:i+4]) _hex_address = (_data[i+4:i+8]) _ip_address = IPAddr(_hex_address) _hex_port = (_data[i+8:i+10]) _port = int(ahex(_hex_port), 16) _hex_mode = (_data[i+10:i+11]) # Add this peer to a temporary PeerID list - used to remove any old peers no longer with us _temp_peers.append(_hex_radio_id) # This is done elsewhere for the master too, so we use a separate function _decoded_mode = process_mode_byte(_hex_mode) # If this entry WAS already in our list, update everything except the stats # in case this was a re-registration with a different mode, flags, etc. if _hex_radio_id in self._peers.keys(): self._peers[_hex_radio_id]['IP'] = _ip_address self._peers[_hex_radio_id]['PORT'] = _port self._peers[_hex_radio_id]['MODE'] = _hex_mode self._peers[_hex_radio_id]['MODE_DECODE'] = _decoded_mode self._peers[_hex_radio_id]['FLAGS'] = '' self._peers[_hex_radio_id]['FLAGS_DECODE'] = '' self._logger.debug('(%s) Peer Updated: %s', self._system, self._peers[_hex_radio_id]) # If this entry was NOT already in our list, add it. if _hex_radio_id not in self._peers.keys(): self._peers[_hex_radio_id] = { 'IP': _ip_address, 'PORT': _port, 'MODE': _hex_mode, 'MODE_DECODE': _decoded_mode, 'FLAGS': '', 'FLAGS_DECODE': '', 'STATUS': { 'CONNECTED': False, 'KEEP_ALIVES_SENT': 0, 'KEEP_ALIVES_MISSED': 0, 'KEEP_ALIVES_OUTSTANDING': 0, 'KEEP_ALIVES_RECEIVED': 0, 'KEEP_ALIVE_RX_TIME': 0 } } self._logger.debug('(%s) Peer Added: %s', self._system, self._peers[_hex_radio_id]) # Finally, check to see if there's a peer already in our list that was not in this peer list # and if so, delete it. for peer in self._peers.keys(): if peer not in _temp_peers: self.de_register_peer(peer) self._logger.warning('(%s) Peer Deleted (not in new peer list): %s', self._system, int_id(peer))