def connect_xbee(self): """ Tries to establish serial connection. """ port_name = self.entry1.get() baud_rate = int(self.entry2.get()) self.s = SerialConnection(self, port_name, baud_rate) if not self.s.start_connection(): messagebox.showerror('Error', "Could not establish serial connection.") else: self.connected = True self.root2.destroy()
def shutDownDevice(): try: ser = SerialConnection().getSerialConnection( '9600' , 'none', '1', '8') command = 'FA1000060001020001' crc = ModbusLib.get_modbus_crc( bytearray.fromhex( command ) ) command = command+crc print('UPS command', command) commandResp = ModbusCommandSender().sendCommand( ser, command, 'RTU' ) if commandResp: print('UPS written successfully') else: print('Error writing to UPS') try: subprocess.call( 'shutdown now', shell=True ) except Exception as e: self.LOG.error( 'Error shutting down: %s', e ) except Exception as e: print('Error writing to UPS', e)
def rcProcess(state, lock, rate_q, change_q): """Provide work with rc serial port :param state: current system state :param lock: lock for global variables :param rate_q: queue with video rate value :param change_q: queue with video change flag """ state_list = [1, 2, 3, 5] rc_ser = SerialConnection(device_name='RC', device_id='1411') # Create rc serial connection flag = True prev_rate = 0 while True: if state.value in state_list: if state.value == 1: # Wait for start command flag = True if rc_ser.ser.inWaiting() > 0: msg = rc_ser.getData() if b'1000' in msg: lock.acquire() state.value = 2 lock.release() elif state.value == 2: # Check special commands if rc_ser.ser.inWaiting() > 0: msg = rc_ser.getData() if b'5000' in msg: # Quest timeout command lock.acquire() state.value = 8 lock.release() elif b'6000' in msg: # Quest trouble end lock.acquire() state.value = 4 lock.release() elif state.value == 3: # Check special commands if rc_ser.ser.inWaiting() > 0: msg = rc_ser.getData() if b'5000' in msg: lock.acquire() state.value = 8 lock.release() elif b'6000' in msg: lock.acquire() state.value = 4 lock.release() # Send data from Arduino if not (rate_q.empty()): # Send new video rate value rate = rate_q.get() if not (prev_rate == rate) and (rate % 0.2 == 0): rc_ser.sendData(msg=rate, flag=True) prev_rate = rate if not (change_q.empty()): # Send message about sub video if change_q.get(): rc_ser.sendData(msg=b'2000') elif state.value == 5: if flag: # Send end command rc_ser.sendData(msg=b'4000') flag = False # Check special command if rc_ser.ser.inWaiting() > 0: msg = rc_ser.getData() if b'5000' in msg: lock.acquire() state.value = 8 lock.release()
def inoProcess(state, lock, rate_q_rc, change_q_rc, rate_q_pi, change_q_pi, min_val, max_val): """Provide work with arduino serial port :param state: current system state :param lock: lock for global variables :param rate_q_rc: queue with video rate value for rc :param change_q_rc: queue with video change flag for rc :param rate_q_pi: queue with video rate value for pi :param change_q_pi: queue with video change flag for pi :param min_val: minimum available video rate value :param max_val: maximum available video rate value """ state_list = [2, 3, 4, 8] ino_ser = SerialConnection( device_name='Arduino', device_id='1733') # Create arduino serial connection prev_rate = min_val while True: if state.value in state_list: if state.value == 2: # Send start command to Arduino ino_ser.sendData(msg=b'S') lock.acquire() state.value = 3 lock.release() if state.value == 3: # Get data from Arduino if ino_ser.ser.inWaiting() > 0: msg = ino_ser.getData() if not (b'None' in msg): if b'Change' in msg: change_q_rc.put(True) change_q_pi.put(True) elif b'Up' in msg: rate = setFrameTime(True, min_val, max_val, prev_rate) if not (prev_rate == rate): rate_q_pi.put(rate) rate_q_rc.put(rate) prev_rate = rate else: rate = setFrameTime(False, min_val, max_val, prev_rate) if not (prev_rate == rate): rate_q_pi.put(rate) rate_q_rc.put(rate) prev_rate = rate if state.value == 4: # Send end command to Arduino ino_ser.sendData(msg=b'E') if ino_ser.getResponse(): lock.acquire() state.value = 5 lock.release() if state.value == 8: # Send timeout command to Arduino ino_ser.sendData(msg=b'T') prev_rate = min_val if ino_ser.getResponse(): lock.acquire() state.value = 1 lock.release()
self.getcommand() if (self.data == 'X'): break print ('Stopping surrogate...') sur = Surrogator(sock) fps = Fps() fps.tic() ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d-%H-%M-%S') connection = SerialConnection(portname=portname) motor = MotorCortex(connection = connection) # Connect remotely to any client that is waiting for sensor loggers. sensorimotor = SensorimotorCortex(connection,'sensorimotor',24) sensorimotor.init() sensorimotor.start() sensorimotor.sensorlocalburst=1000 sensorimotor.sensorburst=100 sensorimotor.updatefreq=10 sensorimotor.cleanbuffer() connection.send(b'AE010') connection.send(b'AB100') def terminate(): print('Stopping ShinkeyBot')
def queryModbusDevices( self ): modbusDevList = ModbusDeviceList().getModbusDeviceList() modbusResponseList = [] index = 0 print('No of modbus devices: ', modbusDevList) for modbusDevice in modbusDevList: print('Modbus Device ', modbusDevice) ser = None try: print('here1') connectionType = modbusDevice.get( ModbusConsts.CONN_TYPE ) if connectionType is None: continue if connectionType == ModbusConsts.CONN_RTU: print('here2') connParams = modbusDevice.get( ModbusConsts.CONN_PARAMS ) print('here2.1') modbusConfig = ModbusDeviceConfig().getModbusConfig( modbusDevice.get( ModbusConsts.DEVICE_TYPE ) ) print('here2.2') self.LOG.debug(modbusConfig.get(ModbusConsts.QUERY_PARAMS)) print('here2.3') try: print('here3') ser = SerialConnection().getSerialConnection( connParams.get( ModbusConsts.BAUDRATE ) , connParams.get( ModbusConsts.PARITY ), connParams.get( ModbusConsts.STOP_BITS ), connParams.get( ModbusConsts.BYTE_SIZE )) except Exception as e3: self.LOG.error( 'Error Getting Serial connection: %s', e3 ) modbusResp = ModbusRtuAcquisition().queryDevice( int(connParams.get( ModbusConsts.SLAVE_ID )), ser, modbusConfig.get( ModbusConsts.QUERY_PARAMS ), index, connectionType ) print('here4') modbusResp[ModbusConsts.DEVICE_TYPE] = modbusDevice.get( ModbusConsts.DEVICE_TYPE ) modbusResp[ModbusConsts.SLAVE_ID] = connParams.get( ModbusConsts.SLAVE_ID ) modbusResp[ModbusConsts.DEVICE_CATEGORY] = modbusDevice.get( ModbusConsts.DEVICE_CATEGORY ) modbusResp[ModbusConsts.DEVICE_ID] = modbusDevice.get( ModbusConsts.DEVICE_ID ) if modbusDevice.get( ModbusConsts.TCS_DATA ) is not None: modbusResp[ModbusConsts.TCS_DATA] = modbusDevice.get( ModbusConsts.TCS_DATA ) modbusResponseList.append( modbusResp ) elif connectionType == ModbusConsts.CONN_TCP: pass elif connectionType == ModbusConsts.CONN_RTU_TCP: pass elif connectionType == ModbusConsts.CONN_RTU_LORA: connParams = modbusDevice.get( ModbusConsts.CONN_PARAMS ) modbusConfig = ModbusDeviceConfig().getModbusConfig( modbusDevice.get( ModbusConsts.DEVICE_TYPE ) ) self.LOG.debug(modbusConfig.get(ModbusConsts.QUERY_PARAMS)) try: ser = LoraConnection().getLoraConnection( connParams.get( ModbusConsts.BAUDRATE ), connParams.get( ModbusConsts.PARITY ), connParams.get( ModbusConsts.STOP_BITS ), connParams.get( ModbusConsts.BYTE_SIZE )) except Exception as e3: self.LOG.error( 'Error Getting LoRa Serial connection: %s', e3 ) modbusResp = ModbusRtuAcquisition().queryDevice( int(connParams.get( ModbusConsts.SLAVE_ID )), ser, modbusConfig.get( ModbusConsts.QUERY_PARAMS ), index ) modbusResp[ModbusConsts.DEVICE_TYPE] = modbusDevice.get( ModbusConsts.DEVICE_TYPE ) modbusResp[ModbusConsts.SLAVE_ID] = connParams.get( ModbusConsts.SLAVE_ID ) modbusResp[ModbusConsts.DEVICE_CATEGORY] = modbusDevice.get( ModbusConsts.DEVICE_CATEGORY ) modbusResp[ModbusConsts.DEVICE_ID] = modbusDevice.get( ModbusConsts.DEVICE_ID ) if modbusDevice.get( ModbusConsts.TCS_DATA ) is not None: modbusResp[ModbusConsts.TCS_DATA] = modbusDevice.get( ModbusConsts.TCS_DATA ) modbusResponseList.append( modbusResp ) elif connectionType == ModbusConsts.CONN_TYPE_SLAVE_RS485: connParams = modbusDevice.get( ModbusConsts.CONN_PARAMS ) try: ser = SerialConnection().getSerialConnection( connParams.get( ModbusConsts.BAUDRATE ), connParams.get( ModbusConsts.PARITY ), connParams.get( ModbusConsts.STOP_BITS ), connParams.get( ModbusConsts.BYTE_SIZE )) except Exception as e3: self.LOG.error( 'Error Getting Serial connection: %s', e3 ) try: modbusResp = ModbusSlaveCardAcquisition().querySlaveCard( modbusDevice, ser, index ) modbusResp[ModbusConsts.DEVICE_TYPE] = modbusDevice.get( ModbusConsts.DEVICE_TYPE ) modbusResp[ModbusConsts.SLAVE_ID] = connParams.get( ModbusConsts.SLAVE_ID ) modbusResp[ModbusConsts.DEVICE_CATEGORY] = modbusDevice.get( ModbusConsts.DEVICE_CATEGORY ) modbusResp[ModbusConsts.DEVICE_ID] = modbusDevice.get( ModbusConsts.DEVICE_ID ) modbusResponseList.append( modbusResp ) except Exception as e: print(e) elif connectionType == ModbusConsts.CONN_TYPE_SLAVE_LORA: print('Querying Lora Slave') connParams = modbusDevice.get( ModbusConsts.CONN_PARAMS ) try: ser = LoraConnection().getLoraConnection( connParams.get( ModbusConsts.BAUDRATE ), connParams.get( ModbusConsts.PARITY ), connParams.get( ModbusConsts.STOP_BITS ), connParams.get( ModbusConsts.BYTE_SIZE )) except Exception as e3: self.LOG.error( 'Error Getting LoRa Serial connection: %s', e3 ) modbusResp = ModbusSlaveCardAcquisition().querySlaveCard( modbusDevice, ser, index ) modbusResp[ModbusConsts.DEVICE_TYPE] = modbusDevice.get( ModbusConsts.DEVICE_TYPE ) modbusResp[ModbusConsts.SLAVE_ID] = connParams.get( ModbusConsts.SLAVE_ID ) modbusResp[ModbusConsts.DEVICE_CATEGORY] = modbusDevice.get( ModbusConsts.DEVICE_CATEGORY ) modbusResp[ModbusConsts.DEVICE_ID] = modbusDevice.get( ModbusConsts.DEVICE_ID ) modbusResponseList.append(modbusResp) else: self.LOG.warn( 'Connection Type not supported: %s', connectionType ) except Exception as e2: self.LOG.error( 'Error querying the Modbus device: %s', e2 ) index += 1 mDecoder = ModbusDecoder() decodedData = mDecoder.decodeModbusData( modbusResponseList ) print("Decoded Data: ",decodedData) try: decodedData = AlarmProcessor().processAlarms( decodedData, modbusDevice.get( ModbusConsts.DEVICE_TYPE ) ) except Exception as e: self.LOG.error( 'Error processing alarms: %s', e ) InputDataQueue.modbusDataQueue.put_nowait( decodedData )
def main(): imei = None mc = MainConfig().getConfig() #GsmUtility.resetModem() try: subprocess.call('hwclock -f /dev/rtc1 -s', shell=True) except Exception as e: self.LOG.error('Error syncing time: %s', e) try: imei = GsmUtility.getGsmImeiNumber() except Exception as e: print(e) try: ser = SerialConnection().getSerialConnection( connParams.get(ModbusConsts.BAUDRATE), connParams.get(ModbusConsts.PARITY), connParams.get(ModbusConsts.STOP_BITS), connParams.get(ModbusConsts.BYTE_SIZE)) command = 'FA0600060001' crc = ModbusLib.get_modbus_crc(bytearray.fromhex(command)) command = command + crc print('UPS command', command) commandResp = ModbusCommandSender().sendCommand(ser, command, 'RTU') if commandResp: print('UPS written successfully') else: print('Error writing to UPS') except Exception as e: print('Error writing to UPS', e) GsmUtility.ImeiNumber = '0123456789' if imei is None else imei Status.deviceId = '0123456789' if mc.get( Constants.DEVICE_ID) is None else mc.get(Constants.DEVICE_ID) try: with open('/fw/DataLogger/app/version.info', 'r') as f: Status.fwVersion = f.readline() Status.fwVersion = Status.fwVersion.strip() except Exception as e: print('Error reading Firmware version: %s', e) recordTime = str( datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d %H:%M:%S')) payload_type = 'xml' if mc.get(Constants.PAYLOAD_TYPE) is None else mc.get( Constants.PAYLOAD_TYPE) if payload_type == Constants.PAYLOAD_TYPE_XML: initialRecord = '<GATEWAY_ID V=\'' + str( Status.deviceId ) + '\'>' + '<DT V=\'' + recordTime + '\'>' + '<FW_VERSION V=\'' + str( Status.fwVersion) + '\'/></DT></GATEWAY_ID>' elif payload_type == Constants.PAYLOAD_TYPE_JSON: initialRecord = {} initialRecord['gateway_id'] = Status.deviceId initialRecord['dt'] = recordTime initialRecord['fw_version'] = Status.fwVersion initialRecord['imei'] = GsmUtility.ImeiNumber initialRecord = json.dumps(initialRecord) else: initialRecord = '<GATEWAY_ID V=\'' + str( Status.deviceId ) + '\'>' + '<DT V=\'' + recordTime + '\'>' + '<FW_VERSION V=\'' + str( Status.fwVersion) + '\'/></DT></GATEWAY_ID>' pq = PayloadQueue() pq.appendPayload(initialRecord) Status.modbusDevStatus = [0] * len( ModbusDeviceList().getModbusDeviceList()) print('No of modbus devices ', len(ModbusDeviceList().getModbusDeviceList())) GPIO.setmode(GPIO.BOARD) GPIO.setup(15, GPIO.OUT) GPIO.setup(22, GPIO.OUT) GPIO.output(22, GPIO.HIGH) time.sleep(5) GPIO.setup(8, GPIO.OUT) GPIO.output(8, GPIO.HIGH) time.sleep(5) try: channel = mc.get(Constants.LORA_CHANNEL) channel = 23 if channel is None else channel result = LoraUtility.setChannel(channel) print('Lora Channel Result: ', result) except Exception as e: print(e) GPIO.output(8, GPIO.LOW) # Start the process monitor thread pm = ProcessMonitor.ProcessMonitor() pm.start() interval = int(mc.get(Constants.PERIODIC_INTERVAL)) curtime = time.time() timeToSleep = interval - (curtime % interval) time.sleep(timeToSleep) # Start the PeriodicTimer pt = PeriodicTimer.PeriodicTimer() pt.start() time.sleep(1) # Start the modbus data acquisition service modbusDataService = ModbusDataService.ModbusDataService() modbusDataService.start() # Start the payload construction service messageComposer = MessageComposer.MessageComposer() messageComposer.start() # Start the Message sending service messageSender = MessageSender.MessageSender() messageSender.start() # Start the LED thread ledt = LedStatus.LedStatus() ledt.start() # Wait for the threads to complete while True: if Status.stop: MessageSender.stop = True MessageComposer.stop = True ModbusDataService.stop = True PeriodicTimer.stop = True ProcessMonitor.stop = True time.sleep( int(MainConfig().getConfig().get(Constants.PERIODIC_INTERVAL))) break else: time.sleep( int(MainConfig().getConfig().get(Constants.PERIODIC_INTERVAL)))
# streamData is an Observable to connect the raw stream from connection to downstream observers streamData = ObservableString() messages = ObservableArray() frames = ObservableArray() state = ObservableDict() outputConnection = None if len(inFile) > 0: print(f'using {inFile} as source') connection = FileReader(inFile) else: port = args.port print(f'using {port} as source') connection = SerialConnection(port) outputConnection = connection timeout = float(args.timeout) # connection will read from either sourcse # messageParser will chop the stream into separate messages messageParser = MessageParser(PentairProtocol.RECORD_SEPARATOR, messages) # connect messageParser as an oberver of streamData streamData.addObserver(messageParser) protocol = PentairProtocol() frameParser = FrameParser(frames, protocol) messages.addObserver(frameParser)
def serialConnectionFunction(): serialConnection = SerialConnection() serialConnection.setup_connection() yield serialConnection