def __init__(self, port='/dev/usb/ttyUSB0', baudrate=9600, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS): """Initialize the connection to the device""" SerialConnection.__init__(self, port, baudrate, parity, bytesize)
def loadtoipm(src, BAUD, PORT): pmfeatures_file = PATH_TO_PYMITE + '/src/platform/stm32f2/pmfeatures.py' pmfeatures = pmImgCreator.PmImgCreator(pmfeatures_file) code = compile(src, '', "exec") img = pmfeatures.co_to_str(code) print len(img) conn = SerialConnection(PORT, BAUD) conn.write(img) return ''.join([c for c in conn.read()])
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 __init__(self): QObject.__init__(self) # Serial connection self.serial = SerialConnection() self.serial.set_port(0) self.serial.message_received.connect(self._onMessageReceived) # Board status object self.boardStatus = BoardStatus() # Board settings object self.fmuSettings = FmuSettings() # Status reader self.statusReaderThread = None self.statusReaderIsAlive = False self.statusReaderUpdateInterval = 0.25 # Update interval in seconds # Indicates if new data from the board was received #self.hasNewData = False self._logger = Logger()
def __init__(self, _number, _max): self._number = _number self._max = _max # Don't call update here def request(self, x): print("{} was requested.".format(x)) def update(self): while True: print("Spawned {} of {}".format(self._number, self._max)) sleep(2) if __name__ == '__main__': ''' spawn = Spawn(1, 1) # Create the object as normal p = multiprocessing.Process(target=methodcaller("update"), args=(spawn,)) # Run the loop in the process p.start() while True: sleep(1.5) spawn.request(2) # Now you can reference the "spawn" ''' device = SC() p = multiprocessing.Process(target=methodcaller("ReadData"), args=(device, )) # Run the loop in the process p.start() while True: sleep(1.5) device.SendData('0003')
class _FMUManager(QObject): """ This class manages the communication with the controller, e.g. the connection, status updates, etc. """ # Update interval in ms UPDATE_INTERVAL = 1000 # This signals is emitted when the board status was updated board_status_updated = pyqtSignal() # This signal is emitted when the board settings are updated board_settings_updated = pyqtSignal() # This signal is emitted when a new data object message was received data_object_received = pyqtSignal() def __init__(self): QObject.__init__(self) # Serial connection self.serial = SerialConnection() self.serial.set_port(0) self.serial.message_received.connect(self._onMessageReceived) # Board status object self.boardStatus = BoardStatus() # Board settings object self.fmuSettings = FmuSettings() # Status reader self.statusReaderThread = None self.statusReaderIsAlive = False self.statusReaderUpdateInterval = 0.25 # Update interval in seconds # Indicates if new data from the board was received #self.hasNewData = False self._logger = Logger() def connect(self, port=0): """Connects to the flight controller""" self.serial.connect() # Start reading the board status self._startStatusReader() # Read once the board settings self.updateBoardSettings() def disconnect(self): """Disconnects from the flight controller""" # Stop the status reader self._stopStatusReader() # Disconnects self.serial.disconnect() def set_serial_port(self, port): self.serial.set_port(port) def connected(self): return self.serial.connected def setUpdateInterval(seld, interval): pass def _startStatusReader(self): """ Starts the status readers. """ # Already started? if self.statusReaderIsAlive: return # Create thread and start reading the board status self.statusReaderIsAlive = True self.statusReaderThread = threading.Thread(target=self._statusReader) self.statusReaderThread.setDaemon = True self.statusReaderThread.start() def _stopStatusReader(self): """ Stops the status reader. """ if not self.statusReaderIsAlive: return self.statusReaderIsAlive = False #time.sleep(self.statusReaderUpdateInterval) self.statusReaderThread.join() def _statusReader(self): """ Sends status requests to the flight controller board. """ while self.statusReaderIsAlive: #self._logger.debug("Sending new status query") message = GetBoardStatusMessage() self.serial.writeMessage(message) #self.updateBoardSettings() time.sleep(self.statusReaderUpdateInterval) def _onMessageReceived(self): """ Callback method which is called when a new messages was received by the serial connection. """ try: messages = list(get_all_from_queue(self.serial.messageQueue)) #message = self.serial.messageQueue.get(False) #if message[0] is None: # return #if message[0].commandType == CommandTypes.GET_BOARD_STATUS: # self._updateStatus(message[0], message[1]) #elif message[0].commandType == CommandTypes.GET_BOARD_SETTINGS: # self._onBoardSettingsUpdated(message[0], message[1]) if len(messages) > 0: #self._logger.debug("New status response received") for message in messages: if message[0] is None: continue if message[0].commandType == CommandTypes.GET_BOARD_STATUS: self._updateStatus(message[0], message[1]) elif message[0].commandType == CommandTypes.GET_BOARD_SETTINGS: self._onBoardSettingsUpdated(message[0], message[1]) elif message[0].commandType == CommandTypes.DEBUG_INT_VALUES: self.boardStatus.updateFromMessage(message[0], message[1]) # Emit signal self.board_status_updated.emit() elif message[0].commandType == CommandTypes.DEBUG_FLOAT_VALUES: self.boardStatus.updateFromMessage(message[0], message[1]) # Emit signal self.board_status_updated.emit() elif message[0].commandType == CommandTypes.DEBUG_STRING_MESSAGE: self.boardStatus.updateFromMessage(message[0], message[1]) # Emit signal self.board_status_updated.emit() else: self.data_object_received.emit() except StopIteration: return def _updateStatus(self, message, timestamp): """ Updates the board status with the received data from the serial connection. """ self.boardStatus.updateFromMessage(message, timestamp) #self.boardStatus.printStatus() # Emit signal self.board_status_updated.emit() def _onBoardSettingsUpdated(self, message, timestamp): """Called when an board settings (0x0020) message was received. The board settings will be updated with the received message.""" self.fmuSettings.updateFromMessage(message, timestamp) # Emit signal self.board_settings_updated.emit() ########################################### ## Output channels (servo, engine) methods ########################################### def setServoPos(self, servo_nr=1, pos=0): """Moves the specified servo to the given position.""" message = ServoPositionMessage(servo_nr, pos) self.serial.writeMessage(message) def getServoPos(self, servo_nr=1): pass ########################################### ## Board settings methods ########################################### def updateBoardSettings(self): """Sends an update board settings message.""" message = GetBoardSettingsMessage() self.serial.writeMessage(message) def saveBoardSettings(self): """Saves all firmware settings to the flash memory.""" message = SaveSettingsMessage() self.serial.writeMessage(message) def setPIDRollCoefficients(self, p_fac, i_fac, d_fac, i_limit): message = SetRollPIDCoefficientsMessage(p_fac, i_fac, d_fac, i_limit) self.serial.writeMessage(message) def setPIDPitchCoefficients(self, p_fac, i_fac, d_fac, i_limit): message = SetPitchPIDCoefficientsMessage(p_fac, i_fac, d_fac, i_limit) self.serial.writeMessage(message) def setPIDYawCoefficients(self, p_fac, i_fac, d_fac, i_limit): message = SetYawPIDCoefficientsMessage(p_fac, i_fac, d_fac, i_limit) self.serial.writeMessage(message) def setDcmRollCoefficients(self, p_factor, i_factor): message = SetDcmRollCoefficientsMessage(p_factor, i_factor) self.serial.writeMessage(message) def setDcmPitchCoefficients(self, p_factor, i_factor): message = SetDcmPitchCoefficientsMessage(p_factor, i_factor) self.serial.writeMessage(message) def setDcmYawCoefficients(self, p_factor, i_factor): message = SetDcmYawCoefficientsMessage(p_factor, i_factor) self.serial.writeMessage(message)
from payload import * import threading import time import sys import struct from Timer import * def quit(): print 'Exiting...' sys.exit() try: databuffer = [] serial = SerialConnection() print "Serial created" serial.connect("/dev/tty.usbserial-FTG90JQK") print "Serial Connected..." print "Removing nulls" serial.removeInitialNulls() print "NULLS REMOVED" counter = -1 while True: #a = raw_input() counter += 1 if counter > 255: counter = 0 #senddata = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00'
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()
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 __init__(self, file_path='/dev/serial0', baudrate=115200): SerialConnection.__init__(self, file_path=file_path, baudrate=baudrate) self.serial_connection = None
return False except: return True print sys.argv try: fakePacket = False if len(sys.argv) == 2: fakePacket = True databuffer = [] isReady = False printNulls = True sendStars = True serial = SerialConnection() print "Serial created" serial.connect("/dev/ttyUSB0") print "Serial Connected..." socketConnection = SocketConnection() print "Socket created" if(socketConnection.connectAsSender()): threading.Thread(target = sendLoop).start() threading.Thread(target = getInput).start() print 'Thread started'
global printAll while True: p = raw_input() if(p == 'q'): global serial serial.close() sys.exit(0) printAll = not printAll def logData(data): global dataBuffer dataBuffer.append(data) print data dataBuffer = [] serial = SerialConnection() serial.connect("/dev/tty.usbserial-FTG90JQK") printAll = False threading.Thread(target = getMode).start() threading.Thread(target = sender).start() while True: var = serial.readline() if printAll: logData(var) else: if var[:6] == "$GPGGA": parts = var.split(",") if(parts[2] != "" and parts[4] != ""): lat = float(parts[2]) if parts[3] == "S": lat = -lat
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')
class MainWindow(Frame): """ MainWindow is the main window of the application. """ def __init__(self, parent: Tk, gs_manager, *args, **kwargs): """ Constructor. Parameters ---------- parent : Tk Tkinter parent gs_manager : GroundStation Instance of current GroundStation *args Tkinter frame arguments, forwarded to superclass **kwargs Tkinter frame argument names, forwarded to superclass """ super(MainWindow, self).__init__(parent, *args, **kwargs) self._gs_manager = gs_manager self.logger = logging.getLogger() parent.protocol('WM_DELETE_WINDOW', self.__on_close__) self.s = None self.connected = False self.recording = False self.is_receiving = False self.update_plot = False self.num_packets_bad = 0 self.num_packets_good = 0 self._root = parent self._root.title("ARIS Groundstation") if sys.platform.startswith('win'): self._root.state("zoomed") self._root.wm_iconbitmap("aris.ico") else: self._root.state('normal') self._root.grid_rowconfigure(1, weight=1) self._root.grid_columnconfigure(1, weight=1) self.current_velocity = 0 self.current_altitude = 0 self.__setup__() def __setup__(self): """ Setup main window """ # ============================================================================================================== # Menu Bar # ============================================================================================================== self.menubar = tk.Menu(self._root) self._root.config(menu=self.menubar) self.file_menu = tk.Menu(self.menubar, tearoff=0) self.connection_menu = tk.Menu(self.menubar, tearoff=0) self.plot_menu = tk.Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="File", menu=self.file_menu) self.menubar.add_cascade(label="Connection", menu=self.connection_menu) self.menubar.add_cascade(label='Live plot', menu=self.plot_menu) self.file_menu.add_command(label="New", command=self.donothing) self.file_menu.add_command(label="Open", command=self.donothing) self.file_menu.add_command(label="Save", command=self.donothing) self.file_menu.add_command(label="Save as...", command=self.donothing) self.file_menu.add_separator() self.file_menu.add_command(label="Exit", command=self._root.quit) self.connection_menu.add_command(label="Serial connection", command=self.connection_window) self.connection_menu.add_command(label='Start reception', command=self.start_reception) self.connection_menu.add_command(label='Stop reception', command=self.stop_reception) # self.plotmenu.add_command(label='Settings', command=self.plot_setting_window) self.plot_menu.add_command(label='Start live plot', command=self.start_plot) self.plot_menu.add_command(label='Stop live plot', command=self.stop_plot) # ============================================================================================================== # create subframes # ============================================================================================================== self.frame_upper = tk.Frame(self._root, width=500, height=100) self.frame_lower = tk.Frame(self._root, width=150, height=100) self.frame_upper_left = tk.LabelFrame(self.frame_upper, text='Commands', font=6, width=10, height=100) self.frame_upper_middle = tk.LabelFrame(self.frame_upper, text='Velocity [m/s]', font=6, width=500, height=100) self.frame_upper_right = tk.LabelFrame(self.frame_upper, text='Altitude [m]', font=6, width=500, height=100) # ============================================================================================================== # create plots # ============================================================================================================== canvas_left = Canvas(self.frame_upper_middle, width=80, height=80) canvas_left.pack(side='left', fill='both', expand=True) self.canvas_left = FigureCanvasTkAgg(fig_velocity, canvas_left) self.canvas_left.draw() self.canvas_left.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) canvas_right = Canvas(self.frame_upper_right, width=80, height=80) canvas_right.pack(side='left', fill='both', expand=True) self.canvas_right = FigureCanvasTkAgg(fig_altitude, canvas_right) self.canvas_right.draw() self.canvas_right.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) # ============================================================================================================== # add separator lines # ============================================================================================================== self.sep1 = ttk.Separator(self._root, orient="horizontal") self.sep2 = ttk.Separator(self.frame_lower, orient="vertical") # ============================================================================================================== # add frame for recording # ============================================================================================================== self.frame_recording = tk.LabelFrame(self.frame_upper_left, text='Recording', width=40, height=10) self.label_file_name = tk.Label(self.frame_recording, text='file name') self.button_start_rec = tk.Button(self.frame_recording, text='Start', font=4, command=self.start_recording) self.button_stop_rec = tk.Button(self.frame_recording, text='Stop', font=4, command=self.stop_recording) self.entry_name = tk.Entry(self.frame_recording) # ============================================================================================================== # add frame for commands # ============================================================================================================== self.frame_command = tk.LabelFrame(self.frame_upper_left, text='Commands', width=40, height=10) self.button_sensor = tk.Button(self.frame_command, text='EST Reset', width=10, command=lambda: self.send_command('sensor')) self.button_airbrake = tk.Button(self.frame_command, text='Airbrake Test', width=10, command=lambda: self.send_command('airbrake')) self.button_sf = tk.Button(self.frame_command, text='High Sampling', width=10, command=lambda: self.send_command('frequency')) self.button_buzzer = tk.Button(self.frame_command, text='Buzzer', width=10, command=lambda: self.send_command('buzzer')) self.button_disable = tk.Button(self.frame_command, text='Disable Lock', width=10, command=lambda: self.send_command('disable')) # ============================================================================================================== # add log frame # ============================================================================================================== self.frame_log = tk.LabelFrame(self.frame_upper_left, text='Log', width=10, height=20) # ============================================================================================================== # add sensorboard frame # ============================================================================================================== self.frame_sb = tk.LabelFrame(self.frame_lower, text='Sensorboard data', font=6, width=250, height=75) self.label_sb_val = [] for i in range(len(sb_names)): self.label_sb_val.append(tk.Label(self.frame_sb, text="--------", borderwidth=2, relief="sunken", width=10)) self.label_sb_name = [] for i in range(len(sb_names)): self.label_sb_name.append(tk.Label(self.frame_sb, text=sb_names[i])) self.sep1_sb = ttk.Separator(self.frame_sb, orient='vertical') # self.sep2_sb = ttk.Separator(self.frame_sb, orient='vertical') # ============================================================================================================== # add GPS frame # ============================================================================================================== self.frame_gps = tk.LabelFrame(self.frame_lower, text='GPS', font=6, width=200, height=75) self.label_gps_val = [] self.label_gps_name = [] for i in range(len(gps_names)): self.label_gps_val.append(tk.Label(self.frame_gps, text='--------', borderwidth=2, relief='sunken', width=10)) self.label_gps_name.append(tk.Label(self.frame_gps, text=gps_names[i])) for i in range(len(gps_names)): self.label_gps_name[i].grid(row=i, column=0, sticky='W') self.label_gps_val[i].grid(row=i, column=1, padx=10) # ============================================================================================================== # add RF frame # ============================================================================================================== self.frame_rf = tk.LabelFrame(self.frame_lower, text='RF', font=6, width=100, height=75) self.label_rf_val = [] self.label_rf_name = [] for i in range(len(rf_names)): self.label_rf_val.append(tk.Label(self.frame_rf, text='--------', borderwidth=2, relief='sunken', width=10)) self.label_rf_name.append(tk.Label(self.frame_rf, text=rf_names[i])) for i in range(len(rf_names)): self.label_rf_name[i].grid(row=i, column=0, sticky='W') self.label_rf_val[i].grid(row=i, column=1, padx=10) # ============================================================================================================== # add battery monitoring frame # ============================================================================================================== self.frame_battery = tk.LabelFrame(self.frame_lower, text='Power', font=6, width=100, height=75) self.label_battery_val = [] self.label_battery_names = [] for i in range(len(battery_names)): self.label_battery_val.append(tk.Label(self.frame_battery, text='--------', borderwidth=2, relief='sunken', width=15)) self.label_battery_names.append(tk.Label(self.frame_battery, text=battery_names[i])) if i == 0: self.label_battery_names[i].grid(row=i, column=0, padx=(20, 0), pady=(10, 0), sticky='W') self.label_battery_val[i].grid(row=i, column=1, padx=10, pady=(10, 0)) else: self.label_battery_names[i].grid(row=i, column=0, padx=(20, 0), sticky='W') self.label_battery_val[i].grid(row=i, column=1, padx=10) # ============================================================================================================== # add FSM frame # ============================================================================================================== self.frame_fsm = tk.LabelFrame(self.frame_lower, text='FSM data', font=6, width=200, height=75) self.label_fsm_val = [] self.label_fsm_names = [] for i in range(len(fsm_names)): self.label_fsm_val.append(tk.Label(self.frame_fsm, text='--------', borderwidth=2, relief='sunken', width=15)) self.label_fsm_names.append(tk.Label(self.frame_fsm, text=fsm_names[i])) if i == 0: self.label_fsm_names[i].grid(row=i, column=0, padx=(20, 0), pady=(10, 0), sticky='W') self.label_fsm_val[i].grid(row=i, column=1, padx=10, pady=(10, 0)) else: self.label_fsm_names[i].grid(row=i, column=0, padx=(20, 0), sticky='W') self.label_fsm_val[i].grid(row=i, column=1, padx=10) # ============================================================================================================== # pack/grid all elements # ============================================================================================================== self.frame_upper.pack(side="top", fill="both", expand=True) self.sep1.pack(side="top", fill="both") self.frame_lower.pack(side="top", fill="both", expand=True) self.frame_upper_left.pack(side='left', fill='both', expand=True, pady=(0, 10)) self.frame_upper_middle.pack(side='left', fill='both', expand=True, pady=(0, 10)) self.frame_upper_right.pack(side='left', fill='both', expand=True, pady=(0, 10)) self.frame_recording.pack(side='top', fill='both', expand=True) self.frame_command.pack(side='top', fill='both', expand=True) self.frame_log.pack(side='top', fill='both', expand=True) st = scrolledtext.ScrolledText(self.frame_log, state='disabled', width=40, height=20) st.configure(font='TkFixedFont') st.grid(row=0, column=0) self.button_airbrake.grid(row=0, column=0, padx=5) self.button_sensor.grid(row=0, column=1, padx=5) self.button_sf.grid(row=0, column=2, padx=5) self.button_buzzer.grid(row=1, column=0, padx=5) self.button_disable.grid(row=1, column=1, padx=5) self.logger.addHandler(LoggingHandler(st)) self.frame_sb.pack(side="left", fill="both", expand=True, padx=5, pady=10) # self.sep2.pack(side="left", fill="both") self.frame_gps.pack(side="left", fill="both", expand=True, padx=5, pady=10) self.frame_rf.pack(side="left", fill="both", expand=True, padx=5, pady=10) self.frame_battery.pack(side="left", fill="both", expand=True, padx=5, pady=10) self.frame_fsm.pack(side="left", fill="both", expand=True, padx=5, pady=10) self.label_file_name.grid(row=0, column=0, pady=20, padx=20) self.entry_name.grid(row=0, column=1, pady=20) self.button_start_rec.grid(row=1, column=0) self.button_stop_rec.grid(row=1, column=1) self.entry_name.delete(0, 'end') self.entry_name.insert(0, 'recording.csv') self.label_sb_name[0].grid(row=0, column=0, pady=(10, 0), sticky='W') self.label_sb_name[1].grid(row=1, column=0, sticky='W') self.label_sb_name[2].grid(row=0, column=3, pady=(10, 0), sticky='W') self.label_sb_name[3].grid(row=1, column=3, sticky='W') self.label_sb_name[4].grid(row=2, column=3, sticky='W') self.label_sb_name[5].grid(row=3, column=3, sticky='W') self.label_sb_name[6].grid(row=4, column=3, sticky='W') self.label_sb_name[7].grid(row=5, column=3, sticky='W') self.sep1_sb.grid(row=0, column=2, rowspan=6, sticky='ns') # self.sep2_sb.grid(row=0, column=5, rowspan=3, sticky='ns') self.label_sb_val[0].grid(row=0, column=1, padx=10, pady=(10, 0)) self.label_sb_val[1].grid(row=1, column=1, padx=10) self.label_sb_val[2].grid(row=0, column=4, padx=10, pady=(10, 0)) self.label_sb_val[3].grid(row=1, column=4, padx=10) self.label_sb_val[4].grid(row=2, column=4, padx=10) self.label_sb_val[5].grid(row=3, column=4, padx=10) self.label_sb_val[6].grid(row=4, column=4, padx=10) self.label_sb_val[7].grid(row=5, column=4, padx=10) def send_command(self, command): """ Called when user presses one of the control buttons Parameters ---------- command : str needs to be one of the following commands: sensor, airbrake, frequency """ if self.s.serialConnection is not None: answer = messagebox.askquestion('Warning', dict_command_msg.get(command)) if answer == 'yes': self.s.send(command) else: self.logger.info('Command aborted.') else: messagebox.showinfo('Info', 'Serial connection is not established.') def __on_close__(self): """ Called when user closes the application. """ if self.s is not None: self.s.close() self.connected = False self.update_plot = False self._root.destroy() def start_reception(self): """ Starts reading data from serial line if the serial connection is established. """ if self.connected: self.s.read_serial_start() else: messagebox.showinfo('Info', 'Serial connection is not established.') def stop_reception(self): """ Stops reading data from serial line. Stops also live plot and recording. """ if self.connected: self.s.isRun = False if self.update_plot: self.update_plot = False self.logger.info('Live plot stopped.') if self.recording: self.recording = False self.logger.info('Recording stopped.') self.logger.info('Stopped receiving data') def start_recording(self): """ Starts recording data to csv file. """ self.file_name = self.entry_name.get() if not self.connected: messagebox.showinfo('Warning', 'Serial connection is not established yet. Cannot start recording.') elif self.file_name[-4:] != '.csv': messagebox.showinfo('Warning', 'Invalid filename. Needs to end on .csv') elif os.path.exists(self.file_name): answer = messagebox.askquestion('Warning', 'File already exists. Continue overwriting?') if answer == 'yes': with open(self.file_name, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(list(get_measurement_names())[1:]) self.recording = True self.logger.info('Started recording.') else: with open(self.file_name, 'a') as outfile: writer = csv.writer(outfile) writer.writerow(list(get_measurement_names())[1:]) self.recording = True self.logger.info('Started recording.') def stop_recording(self): """ Stops recording data. """ self.recording = False self.logger.info('Stopped recording.') def donothing(self): filewin = tk.Toplevel(self._root) button = tk.Button(filewin, text="Do nothing button") button.pack() def start_plot(self): """ Starts live plot. """ if self.is_receiving: self.update_plot = True self.update_canvas() self.logger.info('Live plot started') else: messagebox.showinfo('Info', 'Data reception needs to be started first.') def stop_plot(self): """ Stops live plot. """ self.update_plot = False self.logger.info('Live plot stopped.') def update_canvas(self): """ Updates canvas which contains the live plots. """ velocity_data.append(self.current_velocity) altitude_data.append(self.current_altitude) sub_velocity.clear() sub_altitude.clear() sub_velocity.plot(velocity_data) sub_altitude.plot(altitude_data) self.canvas_left.draw() self.canvas_right.draw() if self.update_plot: self.frame_upper_middle.after(100, self.update_canvas) def connection_window(self): """ Opens the serial connection settings window. """ self.root2 = tk.Toplevel(self._root) self.root2.title('Xbee serial connection setting') self.root2.geometry('{}x{}'.format(400, 200)) self.frame1 = tk.LabelFrame(self.root2, text='Settings') self.frame2 = tk.LabelFrame(self.root2, text='Available ports') self.label_available_ports = tk.Label(self.frame2, text=available_ports()) self.label_port = tk.Label(self.frame1, text='Port') self.label_baud = tk.Label(self.frame1, text='Baud rate') self.entry1 = tk.Entry(self.frame1) self.entry2 = tk.Entry(self.frame1) self.button_connect = tk.Button(self.frame1, text='Connect', command=self.connect_xbee) self.frame1.pack(side="left", fill="both", expand=True, padx=5, pady=5) self.frame2.pack(side="left", fill="both", expand=True, padx=5, pady=5) self.label_available_ports.grid(row=0, column=0) self.label_port.grid(row=0, column=0, padx=(10, 0)) self.label_baud.grid(row=1, column=0, padx=(10, 0)) self.entry1.grid(row=0, column=1) self.entry2.grid(row=1, column=1) self.button_connect.grid(row=3, column=0, columnspan=2, pady=10) self.entry1.delete(0, 'end') if sys.platform.startswith('win'): self.entry1.insert(0, 'COM6') else: self.entry1.insert(0, '/dev/ttyUSB0') self.entry2.delete(0, 'end') self.entry2.insert(0, 115200) 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 update_rf_frame(self): """ Updates the values in the rf frame """ self.label_rf_val[0].config(text=self.num_packets_good + self.num_packets_bad) self.label_rf_val[1].config(text=self.num_packets_bad) self.label_rf_val[2].config(text=self.num_packets_good) def update_values(self, data): """ Updates the values in the main window and the data for live plots. Parameters ---------- data : list contains the newest data received from the Xbee module. """ # print(len(data)) # print(data) self.is_receiving = True if data == 0: for i in range(len(self.label_sb_val)): self.label_sb_val[i].config(text='-----') for i in range(len(self.label_gps_val)): self.label_gps_val[i].config(text='-----') for i in range(len(self.label_battery_val)): self.label_battery_val[i].config(text='-----') for i in range(len(self.label_fsm_val)): self.label_fsm_val[i].config(text='-----') else: data = data[1:] sb_data = data[:len_sb] battery_data = data[len_sb:len_sb + len_battery] gps_data = data[len_sb + len_battery:len_sb + len_battery + len_gps] fsm_data = data[len_sb + len_gps + len_battery:len_sb + len_gps + len_battery + len_fsm] gps_time = str(gps_data[0] + 2) + ':' + str(gps_data[1]) + ':' + str(gps_data[2]) tmp = ['0'] * (len_gps - 4) tmp[0] = gps_time tmp[1] = gps_data[3] gps_lat_fmt = f'{gps_data[4]}.{gps_data[5]}' gps_lon_fmt = f'{gps_data[6]}.{gps_data[7]}' tmp[2] = gps_lat_fmt tmp[3] = gps_lon_fmt tmp[4:] = gps_data[8:] gps_data = tmp # sb data scaling sb_data[1] = sb_data[1] / 100 sb_data[2:5] = map(lambda x: x / 32.8, sb_data[2:5]) sb_data[5:] = map(lambda x: x / 1024 * 9.81, sb_data[5:]) sb_data[2:] = [f'{x:.2f}' for x in sb_data[2:]] # battery data scaling battery_data[0] = battery_data[0] / 1000 # fsm data scaling fsm_data[0] = fsm_data[0] / 1000 fsm_data[1] = fsm_data[1] / 1000 fsm_data[2] = fsm_data[2] / 10 fsm_data[4] = fsm_data[4] / 1000 for i in range(len(self.label_sb_val)): self.label_sb_val[i].config(text=sb_data[i]) for i in range(len(self.label_gps_val)): self.label_gps_val[i].config(text=gps_data[i]) for i in range(len(self.label_battery_val)): self.label_battery_val[i].config(text=battery_data[i]) for i in range(len(self.label_fsm_val)): if i != 3 and i != 5: self.label_fsm_val[i].config(text=fsm_data[i]) # print(fsm_data) if fsm_data[3] < 128: if fsm_data[3] in range(len(flight_phase)): self.label_fsm_val[3].config(text=flight_phase[fsm_data[3]]) else: self.label_fsm_val[3].config(text=fsm_data[3]) self.label_fsm_val[5].config(text='off') else: fsm_data[3] = 128 - fsm_data[3] if fsm_data[3] in range(len(flight_phase)): self.label_fsm_val[3].config(text=flight_phase[fsm_data[3]]) else: self.label_fsm_val[3].config(text=fsm_data[3]) self.label_fsm_val[5].config(text='on') if self.recording: with open(self.file_name, 'a') as outfile: writer = csv.writer(outfile) writer.writerow(data[:-3]) self.current_altitude = fsm_data[0] self.current_velocity = fsm_data[1]
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 serialConnectionFunction(): serialConnection = SerialConnection() serialConnection.setup_connection() yield serialConnection