def render_GET(self, request):
     if('v' in request.args and 'r' in request.args):
         r=int(request.args['r'][0])
         v=int(request.args['v'][0])
         if(r>0 and r<9 and (v==0 or v==1)):
             msk=1<<(r-1)
             if (v==1):cmd=0x11
             if (v==0):cmd=0x12
             data=packet(cmd,msk,0x00,0x00)
             SerialPort.write(port,data)
             print ">"+pk2str(data)
         else:
             print "r or v out of range"
     else:
         print "r or v missing"
     request.setHeader("content-type", "application/json")
     return ">"+pk2str(data)
Esempio n. 2
0
 def render_GET(self, request):
     if ('v' in request.args and 'r' in request.args):
         r = int(request.args['r'][0])
         v = int(request.args['v'][0])
         if (r > 0 and r < 9 and (v == 0 or v == 1)):
             msk = 1 << (r - 1)
             if (v == 1): cmd = 0x11
             if (v == 0): cmd = 0x12
             data = packet(cmd, msk, 0x00, 0x00)
             SerialPort.write(port, data)
             print ">" + pk2str(data)
         else:
             print "r or v out of range"
     else:
         print "r or v missing"
     request.setHeader("content-type", "application/json")
     return json.dumps([Relay, Sensor])
Esempio n. 3
0
 def writeMessage(self, message):
     print "Writing message:   " + message
     writeData = HexToByte(message)
     global ser
     try:
         ser.write(writeData)
     except:
         try:
             ser = SerialPort(serproto, "/dev/ttyUSB0", reactor, 19200)
             ser.write(writeData)
         except:
             raise
     self.bytesWritten += len(writeData)
     self.messageWritten = message
     self.timer = threading.Timer(4.0, self.timeout)
     self.timer.start()
     self.d = defer.Deferred()
     return self.d
Esempio n. 4
0
class Radio(object):
    def connect(self, port):
        self.serial = SerialPort(RadioReceiverProtocol(self), port, reactor, baudrate=57600)
        self.serial.flushInput()

    def __init__(self):
        self.listeners = []
        self.serial = None

    def send(self, packet):
        data = array.array('B', packet.encode()).tostring()
        print 'tx:', packet
        if self.serial is not None:
            self.serial.write(data)

    def gotPacket(self, packet):
        print 'rx:', packet
        for l in self.listeners:
            l(packet)
Esempio n. 5
0
class SerialConnection(Connection):
    #: Connection settings
    port = Unicode('/dev/ttyUSB0').tag(config=True)
    ports = List()
    baudrate = Int(115200).tag(config=True)

    #: Actual connection
    serial_port = Instance(SerialPort)

    def is_available(self):
        self.ports = comports()
        self.name = self._default_name()
        return bool(self.ports)

    def _default_name(self):
        for port in self.ports:
            if port.device == self.port:
                return str(port)
        return self.port

    @observe('port')
    def _refresh_name(self, change):
        self.name = self._default_name()

    def connect(self, protocol):
        d = Deferred()

        def do_connect():
            try:
                self.serial_port = SerialPort(protocol,
                                              self.port,
                                              reactor,
                                              baudrate=self.baudrate)
                d.callback(True)
                log.debug("{} connected!".format(self.port))
            except Exception as e:
                d.callback(e)

        deferred_call(do_connect)
        return d

    def write(self, message):
        if self.serial_port is None:
            return 0
        return self.serial_port.write(message)

    def disconnect(self):
        """ """
        s = self.serial_port
        if s:
            log.debug("{} disconnected!".format(self.port))
            s.loseConnection()
            self.serial_port = None
Esempio n. 6
0
def serial_init(port='/dev/ttyUSB0', baudrate=115200):
    logging.debug('About to open port {0}'.format(port))
    s = SerialPort(EchoProtocol(port, 1000), port, reactor, baudrate=baudrate)
    s.write('\r\nHello ...\r\n'.encode('utf8'))
Esempio n. 7
0
class Sparki(object):

    ##
    #
    #
    def __init__(self, port):

        self._sensor_observers = {
            'range': [None],
            'accelerometer': [None],
            'error': [self._message_error],
            'overflow': [self._overflow_error]
        }
        self._sensor_codes = {
            'r': 'range',
            'a': 'accelerometer',
            'e': 'error',
            'o': 'overflow'
        }

        self._port = port
        self._protocol = SparkiProtocol()
        self._protocol.setLineCallback(self._handleMessage)
        self._ser = SerialPort(self._protocol,
                               self._port,
                               reactor,
                               baudrate=9600)
        self._reactor_thread = Thread(target=reactor.run, args=(False, ))
        self._reactor_thread.daemon = True
        self._reactor_thread.start()

    ##
    #
    #
    def shutdown(self):
        reactor.stop()

    ##
    #
    #
    def send(self, message):
        try:
            self._ser.write(message)
        except:
            raise

    ##
    #
    #
    def sendMotorVO(self, lin_vel, ang_vel):
        message = "U V " + str(lin_vel) + " " + str(ang_vel) + "\n"
        self.send(message)

    ##
    #
    #
    def addSensorCallback(self, sensor, callback):
        self._sensor_observers[sensor].append(callback)

    ##
    #
    #
    def _handleMessage(self, data):
        output = data.split()
        for observer in self._sensor_observers[self._sensor_codes[output[0]]]:
            if observer is not None:
                observer(output[1:])

    ##
    #
    #
    def _message_error(self):
        print "Submitted bad serial message to Sparki"

    ##
    #
    #
    def _overflow_error(self):
        print "Sparki receive buffer overflow"
 def render_GET(self, request):
     data=packet(0x18,0x00,0x00,0x00)
     SerialPort.write(port,data)
     request.setHeader("content-type", "application/json")
     request.setHeader("Cache-Control", "no-cache")
     return json.dumps([Relay,Sensor])
Esempio n. 9
0
class SerialNodesController(object):
    def __init__(self, oNodeControl):
        self._NodeControl = oNodeControl
        # TODO generic alert state dictionary
        self._PIR1Alerting = False
        self._PIR2Alerting = False
        self._ResetState = 10
        self._LDRLightStateValue = 400
        if self._NodeControl.nodeProps.has_option('ldr-reporting',
                                                  'state-value'):
            self._LDRLightStateValue = self._NodeControl.nodeProps.getint(
                'ldr-reporting', 'state-value')

        # list all serial ports: python -m serial.tools.list_ports
        self._connectSerialPort()

    def _connectSerialPort(self):
        self.Close()
        myProtocol = SerialNodesProtocol(self._NodeControl,
                                         OnReceive=self.OnMsgReceive)
        self._serialPort = SerialPort(myProtocol,
                                      self._NodeControl.nodeProps.get(
                                          'serialnodes', 'serialport'),
                                      reactor,
                                      baudrate=9600,
                                      bytesize=serial.EIGHTBITS,
                                      parity=serial.PARITY_NONE)
        sleep(1)

    def OnMsgReceive(self, RecMsg):
        myNodeID = self._NodeControl.nodeProps.get('system', 'nodeId')
        if str(RecMsg.ToAdress) == myNodeID:
            # for this node
            if int(RecMsg.Function) == 1:
                # PIR alert garage
                if not self._PIR1Alerting:
                    self._PIR1Alerting = True
                    self._NodeControl.MQTTPublish(sTopic="garage/pirevent",
                                                  sValue="ON",
                                                  iQOS=0,
                                                  bRetain=False)
                    reactor.callLater(self._ResetState,
                                      self.ResetPIR1State,
                                      topic="garage/pirevent")
            elif int(RecMsg.Function) == 2:
                # PIR alert Werkkamer
                if not self._PIR2Alerting:
                    self._PIR2Alerting = True
                    self._NodeControl.MQTTPublish(sTopic="werkkamer/pirevent",
                                                  sValue="ON",
                                                  iQOS=0,
                                                  bRetain=False)
                    reactor.callLater(self._ResetState,
                                      self.ResetPIR2State,
                                      topic="werkkamer/pirevent")
            elif int(RecMsg.Function) == 3:
                # LDR garage
                if int(RecMsg.MsgValue) > self._LDRLightStateValue:
                    self._NodeControl.MQTTPublish(sTopic="garage/ldrevent",
                                                  sValue="ON",
                                                  iQOS=0,
                                                  bRetain=False)
                elif int(RecMsg.MsgValue) < self._LDRLightStateValue:
                    self._NodeControl.MQTTPublish(sTopic="garage/ldrevent",
                                                  sValue="OFF",
                                                  iQOS=0,
                                                  bRetain=False)
            elif int(RecMsg.Function) == 4:
                # LDR Garage zolder
                if int(RecMsg.MsgValue) > self._LDRLightStateValue:
                    self._NodeControl.MQTTPublish(
                        sTopic="garagezolder/ldrevent",
                        sValue="ON",
                        iQOS=0,
                        bRetain=False)
                elif int(RecMsg.MsgValue) < self._LDRLightStateValue:
                    self._NodeControl.MQTTPublish(
                        sTopic="garagezolder/ldrevent",
                        sValue="OFF",
                        iQOS=0,
                        bRetain=False)

    def ResetPIR1State(self, topic):
        self._PIR1Alerting = False
        self._NodeControl.MQTTPublish(sTopic="garage/pirevent",
                                      sValue="OFF",
                                      iQOS=0,
                                      bRetain=False)

    def ResetPIR2State(self, topic):
        self._PIR2Alerting = False
        self._NodeControl.MQTTPublish(sTopic="werkkamer/pirevent",
                                      sValue="OFF",
                                      iQOS=0,
                                      bRetain=False)

    def SendMessage(self, sSerialMessage):
        try:
            self._serialPort.write(sSerialMessage)
            sleep(0.1)
            return True
        except Exception, exp:
            print traceback.format_exc()
            self._NodeControl.log.error("SendMessage error: %s." %
                                        traceback.format_exc())
            return False
class SerialNodesController(object):
    def __init__(self, oNodeControl):
        self._NodeControl = oNodeControl
        self._AfterPIREvent = None
        self._ResetState = 10

        # list all serial ports: python -m serial.tools.list_ports
        self._connectSerialPort()
        l = task.LoopingCall(self.eCheckLights)
        l.start(300)

    def _connectSerialPort(self):
        self.Close()
        myProtocol = SerialNodesProtocol(self._NodeControl,
                                         OnReceive=self.OnMsgReceive)
        self._serialPort = SerialPort(myProtocol,
                                      self._NodeControl.nodeProps.get(
                                          'serialnodes', 'serialport'),
                                      reactor,
                                      baudrate=9600,
                                      bytesize=serial.EIGHTBITS,
                                      parity=serial.PARITY_NONE)
        sleep(1)

    def eCheckLights(self):
        if self._AfterPIREvent is None:
            self.setNormalState()

    def OnMsgReceive(self, RecMsg):
        myNodeID = '112'  # self._NodeControl.nodeProps.get('system', 'nodeId')
        if str(RecMsg.ToAdress) == myNodeID:
            # for this node
            if int(RecMsg.Function) == 1:
                # PIR alert
                if self._AfterPIREvent is None:
                    self._NodeControl.MQTTPublish(sTopic="overloop/pirevent",
                                                  sValue="ON",
                                                  iQOS=0,
                                                  bRetain=False)
                    reactor.callLater(self._ResetState,
                                      self.ResetState,
                                      topic="overloop/pirevent")
                    if ARMED:
                        RGBColors.sendEffectScheme(self, self._NodeControl,
                                                   752, RGBColors.EFFECT_ALERT)
                    elif astro_functions.isDusk(self._NodeControl):
                        RGBColors.sendEffectScheme(
                            self, self._NodeControl, 752,
                            RGBColors.EFFECT_SILENT_NIGHT_WAVE)
                    else:
                        RGBColors.sendRGBValue(self, self._NodeControl, 752,
                                               RGBColors.FRIENDLYHELLO)
                    self._AfterPIREvent = reactor.callLater(
                        10, self.afterPIREvent)

    def afterPIREvent(self):
        reactor.callFromThread(self.switchToNoneAlertState)

    def ResetState(self, topic):
        self._NodeControl.MQTTPublish(sTopic=topic,
                                      sValue="OFF",
                                      iQOS=0,
                                      bRetain=False)

    def switchToNoneAlertState(self):
        self._AfterPIREvent = None
        self._connectSerialPort()
        self.setNormalState()

    def setNormalState(self):
        if astro_functions.isDusk(self._NodeControl):
            self._NodeControl.log.debug('Dusk: setting quit nights lights')
            RGBColors.sendColorScheme(self, self._NodeControl, 752,
                                      RGBColors.COLORSCHEME_QUITNIGHT_01)
        else:
            self._NodeControl.log.debug('Daytime: switch lights off')
            RGBColors.sendRGBValue(self, self._NodeControl, 752,
                                   RGBColors.ALLOFF)

    def SendMessage(self, sSerialMessage):
        try:
            self._serialPort.write(sSerialMessage)
            sleep(0.1)
            return True
        except Exception, exp:
            print traceback.format_exc()
            self._NodeControl.log.error("SendMessage error: %s." %
                                        traceback.format_exc())
            return False
Esempio n. 11
0
class SerialNodesController(object):
    def __init__(self, oNodeControl):
        self._NodeControl = oNodeControl
        # list all serial ports: python -m serial.tools.list_ports
        self._ResetState = 10
        self._connectSerialPort()

    def _connectSerialPort(self):
        self.Close()
        myProtocol = SerialNodesProtocol(self._NodeControl,
                                         OnReceive=self.OnMsgReceive)
        self._serialPort = SerialPort(myProtocol,
                                      self._NodeControl.nodeProps.get(
                                          'serialnodes', 'serialport'),
                                      reactor,
                                      baudrate=9600,
                                      bytesize=serial.EIGHTBITS,
                                      parity=serial.PARITY_NONE)
        self._NodeControl.log.debug(
            'Serial port: %s open.' %
            self._NodeControl.nodeProps.get('serialnodes', 'serialport'))
        sleep(1)

    def OnMsgReceive(self, RecMsg):
        myNodeID = '999'  # self._NodeControl.nodeProps.get('system', 'nodeId')

        if str(RecMsg.ToAdress) == myNodeID:
            # for this node
            if ((int(RecMsg.Function) == 1) and (int(RecMsg.MsgValue) == 1)):
                self._NodeControl.log.debug("Deuropen signal (keypad)")
                self.doOpenDoor()
                self._NodeControl.MQTTPublish(sTopic="deur/keyopen",
                                              sValue="ON",
                                              iQOS=0,
                                              bRetain=False)
                reactor.callLater(self._ResetState,
                                  self.ResetState,
                                  topic="deur/keyopen")
            elif ((int(RecMsg.Function) == 2) and (int(RecMsg.MsgValue) == 1)):
                self._NodeControl.log.debug("Deuropen signal (RFID)")
                self.doOpenDoor()
                self._NodeControl.MQTTPublish(sTopic="deur/rfidopen",
                                              sValue="ON",
                                              iQOS=0,
                                              bRetain=False)
                reactor.callLater(self._ResetState,
                                  self.ResetState,
                                  topic="deur/rfidopen")
            elif ((int(RecMsg.Function) == 3) and (int(RecMsg.MsgValue) == 1)):
                self._NodeControl.log.debug("Deurbel signal.")
                self._NodeControl.MQTTPublish(sTopic="deur/ring",
                                              sValue="ON",
                                              iQOS=0,
                                              bRetain=False)
                reactor.callLater(self._ResetState,
                                  self.ResetState,
                                  topic="deur/ring")
            elif ((int(RecMsg.Function) == 4) and (int(RecMsg.MsgValue) == 1)):
                self._NodeControl.log.debug("Tampering Keypad")
                self._NodeControl.MQTTPublish(sTopic="tampering/keypad",
                                              sValue="ON",
                                              iQOS=0,
                                              bRetain=False)
            elif ((int(RecMsg.Function) == 4) and (int(RecMsg.MsgValue) == 0)):
                reactor.callLater(self._ResetState,
                                  self.ResetState,
                                  topic="tampering/keypad")

    def ResetState(self, topic):
        self._NodeControl.MQTTPublish(sTopic=topic,
                                      sValue="OFF",
                                      iQOS=0,
                                      bRetain=False)

    def SendMessage(self, sSerialMessage):
        try:
            self._serialPort.write(sSerialMessage)
            sleep(0.1)
            return True
        except Exception as exp:
            print(traceback.format_exc())
            self._NodeControl.log.error("SendMessage error: %s." %
                                        traceback.format_exc())
            return False

    def Close(self):
        try:
            self._serialPort.loseConnection()
            self._serialPort = None
        except:
            pass

    def doOpenDoor(self):
        if self._NodeControl.nodeProps.has_option('dooropener', 'active') and\
                self._NodeControl.nodeProps.getboolean('dooropener', 'active'):
            idoorUnlockTime = 5
            if self._NodeControl.nodeProps.has_option('dooropener',
                                                      'unlockTime'):
                idoorUnlockTime = float(
                    self._NodeControl.nodeProps.get('dooropener',
                                                    'unlockTime'))
            self._NodeControl.log.debug("Door opening")
            wiringpi.digitalWrite(17, 1)
            self._NodeControl.log.debug("Door opening done")
            reactor.callLater(idoorUnlockTime, self.releaseDoorLockEvent)

    def releaseDoorLockEvent(self):
        self._NodeControl.log.debug("releaseDoorLockEvent")
        wiringpi.digitalWrite(17, 0)
        self._NodeControl.log.debug("Deur GPIO 17 off")
Esempio n. 12
0
class WAMP_Component(ApplicationSession):
    """
    RPi WAMP application component.
    """

    # The Queue-Object is an threadsafe FIFO Buffer.
    # Operations like put and get are atomic
    # this queue holds all incomming complete Frames
    frameInBuffer = Queue(50)

    # this queue holds the ordered config requests
    antwortQueue = Queue(50)

    # what ist deque? = double-ended queue. it's a thread-safe ringbuffer
    # this deque holds the errors as string
    logQueue = deque([], 200)

    # hier werden die messungen gespeichert
    messCSVDictList = []
    messCSVDictList_lock = threading.Lock()

    # to ensure that we have a thead-safe write function, we need that look
    serialWrite_lock = threading.Lock()

    isSerialConnected = False

    # GSV-6CPU RX bufferoverflow prevention
    actTime = None
    lastTime = datetime.now()

    # ready falg
    sys_ready = False

    # cleanup here
    def onLeave(self, details):
        try:
            self.serialPort.stopReading()
        except Exception:
            pass
        try:
            self.serialPort.reactor.stop()
        except Exception:
            pass
        if self.router.isAlive():
            self.router.stop()
            # wait max 1 Sec.
            self.router.join(1.0)

    @inlineCallbacks
    def onJoin(self, details):
        port = self.config.extra['port']
        baudrate = self.config.extra['baudrate']

        # install signal handler
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)

        self.toWAMP_logger = Log_WAMP_Handler(self, self.logQueue)
        self.toWAMP_logger.addFilter(NoHTTP_GetFilter())
        logging.getLogger('serial2ws').addHandler(self.toWAMP_logger)


        # first of all, register the getErrors Function
        yield self.register(self.getLog, u"de.me_systeme.gsv.getLog")
        yield self.register(self.getIsSerialConnected, u"de.me_systeme.gsv.getIsSerialConnected")

        # create an router object/thread
        self.router = FrameRouter(self, self.frameInBuffer, self.antwortQueue)

        # create GSV6 Serial-Protocol-Object
        serialProtocol = GSV_6Protocol(self, self.frameInBuffer, self.antwortQueue)

        logging.getLogger('serial2ws.WAMP_Component').debug(
            'About to open serial port {0} [{1} baud] ..'.format(port, baudrate))

        # try to init Serial-Connection
        try:
            self.serialPort = SerialPort(serialProtocol, port, reactor, baudrate=baudrate)
            self.isSerialConnected = True
        except Exception as e:
            logging.getLogger('serial2ws.WAMP_Component').critical('Could not open serial port: {0}. exit!'.format(e))
            os.kill(os.getpid(), signal.SIGTERM)
        else:
            # when erial-init okay -> start FrameRouter
            self.router.start()

    def __exit__(self):
        logging.getLogger('serial2ws.WAMP_Component').trace('Exit.')

    def __del__(self):
        logging.getLogger('serial2ws.WAMP_Component').trace('del.')

    def getLog(self):
        return list(self.logQueue)

    sendCounter = 0

    def writeAntwort(self, data, functionName, args=None):
        # okay this function have to be atomic
        # we protect it with a lock!
        self.serialWrite_lock.acquire()
        self.actTime = datetime.now()
        diffTime = self.actTime - self.lastTime
        if diffTime.days <= 0 and diffTime.seconds <= 2:
            if (diffTime.seconds == 0 and diffTime.microseconds < 4000):
                self.sendCounter += 1
                if self.sendCounter >= 8:
                    self.sendCounter = 0
                    logging.getLogger('serial2ws.WAMP_Component').debug(
                        "serialWait, prevent GSV-6CPU RX Buffer overflow")
                    sleep(0.2)  # Time in seconds
            else:
                self.sendCounter = 0
        try:
            self.antwortQueue.put_nowait({functionName: args})
            self.serialPort.write(str(data))
            logging.getLogger('serial2ws.WAMP_Component').debug(
                '[serialWrite] Data: ' + ' '.join(format(z, '02x') for z in data))
        except NameError:
            logging.getLogger('serial2ws.WAMP_Component').debug('[WAMP_Component] serialport not openend')
        finally:
            self.lastTime = datetime.now()
            self.serialWrite_lock.release()

    def write(self, data):
        # okay this function have to be atomic
        # we protect it with a lock!
        self.serialWrite_lock.acquire()
        try:
            self.serialPort.write(str(data))
            logging.getLogger('serial2ws.WAMP_Component').debug(
                '[serialWrite] Data: ' + ' '.join(format(z, '02x') for z in data))
        except NameError:
            logging.getLogger('serial2ws.WAMP_Component').debug('serialport not openend')
        finally:
            self.serialWrite_lock.release()

    def getIsSerialConnected(self):
        return self.isSerialConnected

    def lostSerialConnection(self, errorMessage):
        logging.getLogger('serial2ws.WAMP_Component').critical("Lost SerialConnection: " + errorMessage)
        self.isSerialConnected = False
        # not implemented at web-frontend
        self.publish(u"de.me_systeme.gsv.onSystemGoingDown")
        # shut down app
        os.kill(os.getpid(), signal.SIGTERM)

    def signal_handler(self, signal, frame):
        if signal == 15:
            self.stopMeasurement()
        logger = logging.getLogger('serial2ws')
        logger.removeHandler(self.toWAMP_logger)
        logger.info('received SIGNAL, going down.')
        self.disconnect()

    def stopMeasurement(self):
        data = self.router.gsv6.buildStopTransmission()
        logging.getLogger('serial2ws.WAMP_Component').warning('Sending stop Message to GSV-Modul')
        self.write(data)
        self.router.writeCSVdata()
Esempio n. 13
0
class IridiumSimulator(Thread):
	def __init__(self, comPort, moIP, moPort, mtPort, delay):
		Thread.__init__(self)
		self.udpMavlink = mavlink.MAVLink(0)
		self.serialMavlink = mavlink.MAVLink(0)
		self.udpRx = []
		self.serialRx = None
		self.ipLock = Lock()
		self.serialLock = Lock()
		self.ipTransport = None
		self.status = SatcomStatus.idle
		self.serialTime = 0
		self.delay = delay
		self.terminate = False
		# serial interface to PX4
		self.serialInterface = SerialPort(PX4UartInterface(self.receivedPX4), comPort, reactor, baudrate = 115200)
		self.serialInterface.flushInput()
		self.serialInterface.flushOutput()
		# enpoint for sending MO messages from PX to the relay
		self.relayMoEndpoint = TCP4ClientEndpoint(reactor, moIP, moPort)
		# enpoint receiving MT messages coming from the relay
		self.relayMtEndpoint = TCP4ServerEndpoint(reactor, mtPort)
		self.relayMtEndpoint.listen(relay.IridiumMtReceiverFactory(self.receivedRelay))


	def run(self):
		while not self.terminate:
			self.serialLock.acquire()

			if self.serialTime + self.delay <= time():
				if self.status == SatcomStatus.sending:
					self.sendMsgToPX4(0x01, chr(0x00))
					self.ipLock.acquire()
					# prepare and send an iridium message
					try:
						m = self.udpMavlink.decode(self.serialRx[8:])
						if m is not None:
							msgId = m.get_msgId()
							print '<-- PX4 {0} ({1})'.format(mavlink.mavlink_map[msgId].name, msgId)
					except Exception as e:
						print '<-- PX4 ' + str(e)
					moMsgData = self.prepareMoMessage(self.serialRx)
					prot = relay.IridiumMoSender(moMsgData)
					connectProtocol(self.relayMoEndpoint, prot)
					self.ipLock.release()
					#print 'SEND RQ: complete'
					self.status = SatcomStatus.idle

				elif self.status == SatcomStatus.receiving:
					if len(self.udpRx) != 0:
						self.ipLock.acquire()
						msg = self.udpRx.pop(0)

						try:
							m = self.udpMavlink.decode(msg)
						except Exception as e:
							print e
							m = None

						if m is not None:
							msgId = m.get_msgId()
							print 'QGC --> {0} ({1})'.format(mavlink.mavlink_map[msgId].name, msgId)
							self.sendMsgToPX4(0x02, chr(0x00) + msg)
						else:
							self.sendMsgToPX4(0x02, chr(0x2F))  # no msg

						self.ipLock.release()
						#print 'RCV RQ: complete'
					else:
						self.sendMsgToPX4(0x02, chr(0x2F))  # no msg
						#print 'RCV RQ: no msg'

					self.status = SatcomStatus.idle

			self.serialLock.release()

			sleep(0.1)


	def receivedPX4(self, msg):
		# send msg
		if msg.id == 0x01:
			self.satcomSendRequest(msg.data)

		# retrieve msg
		if msg.id == 0x02:
			self.satcomReceiveRequest()

		# check network status
		if msg.id == 0x05:
			self.satcomGetNetworkStatus()

		# check signal strength
		if msg.id == 0x06:
			self.satcomGetSignalStrength()


	def receivedRelay(self, msg):
		# print 'MT MSG CALLBACK'
		for ie in msg.ieList:
			# print 'IE: {0}: {1}'.format(ie.id, ie.name)
			if ie.name == 'MT Payload IE':
				# print ie.payload
				try:
					#m = self.udpMavlink.decode(ie.payload)
					#if m is not None:
						# print 'MT mavlink msg ID {0}'.format(m.get_msgId())
						self.ipLock.acquire()
						self.udpRx.append(ie.payload)
						self.ipLock.release()
				except:
					pass



	def prepareMoMessage(self, mavlinkMsg):
		msg = iridium.IridiumMessage()

		header = iridium.MoHeaderIe()
		header.autoId = 123
		header.imei = bytearray([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE])
		header.sessionStatus = iridium.MoHeaderIe.SessionStatus.SUCCESSFUL
		header.momsn = 1
		header.mtmsn = 2
		header.timeOfSession = 100000
		header.prepareRaw()
		msg.ieList.append(header)

		payload = iridium.MoPayloadIe()
		payload.payload = mavlinkMsg
		payload.prepareRaw()
		msg.ieList.append(payload)

		msg.prepareRaw()

		return msg.rawData



	def satcomSendRequest(self, msgData):
		self.serialLock.acquire()

		if self.status == SatcomStatus.idle:
			#print 'SEND RQ: pending'
			self.status = SatcomStatus.sending
			self.serialTime = time()

			scsHeader = bytearray()
			packetLen = len(msgData) + 8
			scsHeader.append(packetLen / 256)
			scsHeader.append(packetLen % 256)
			scsHeader.append(2) # PX4 packet
			scsHeader += bytearray(5) # 5 empty bytes - only used when sending images

			self.serialRx = scsHeader + msgData

		else:
			print 'SEND RQ: busy <<<<<<<<<<<<<<<<<<<<<<<'   # THIS SHOULD NOT HAPPEN - PX4 SATCOM DRIVER SHOULD WAIT FOR PREVIOUS COMMAND REPLY
			self.sendMsgToPX4(0x01, chr(0x01))

		self.serialLock.release()


	def satcomReceiveRequest(self):
		self.serialLock.acquire()

		if self.status == SatcomStatus.idle:
			#print 'RCV RQ: pending'
			self.status = SatcomStatus.receiving
			self.serialTime = time()

		else:
			print 'RCV RQ: busy <<<<<<<<<<<<<<<<<<<<<<<'    # THIS SHOULD NOT HAPPEN - PX4 SATCOM DRIVER SHOULD WAIT FOR PREVIOUS COMMAND REPLY
			self.sendMsgToPX4(0x02, chr(0x01))

		self.serialLock.release()


	def satcomGetNetworkStatus(self):
		self.serialLock.acquire()

		self.sendMsgToPX4(0x05, chr(0x00) + chr(0x01))

		self.serialLock.release()


	def satcomGetSignalStrength(self):
		self.serialLock.acquire()

		self.sendMsgToPX4(0x06, chr(0x00) + chr(0x05))

		self.serialLock.release()


	def sendMsgToPX4(self, id, data):
		msg = [0x5B, 0, 0, 0]
		msg[1] = (id)
		msg[2] = (len(data)/256)
		msg[3] = (len(data)%256)
		msg += data
		data = bytes(bytearray(msg))
		self.serialInterface.write(data)
Esempio n. 14
0
class WAMP_Component(ApplicationSession):
    """
    RPi WAMP application component.
    """

    # The Queue-Object is an threadsafe FIFO Buffer.
    # Operations like put and get are atomic
    # this queue holds all incomming complete Frames
    frameInBuffer = Queue(50)

    # this queue holds the ordered config requests
    antwortQueue = Queue(50)

    # what ist deque? = double-ended queue. it's a thread-safe ringbuffer
    # this deque holds the errors as string
    logQueue = deque([], 200)

    # hier werden die messungen gespeichert
    messCSVDictList = []
    messCSVDictList_lock = threading.Lock()

    # to ensure that we have a thead-safe write function, we need that look
    serialWrite_lock = threading.Lock()

    isSerialConnected = False

    # GSV-6CPU RX bufferoverflow prevention
    actTime = None
    lastTime = datetime.now()

    # ready falg
    sys_ready = False

    # cleanup here
    def onLeave(self, details):
        try:
            self.serialPort.stopReading()
        except Exception:
            pass
        try:
            self.serialPort.reactor.stop()
        except Exception:
            pass
        if self.router.isAlive():
            self.router.stop()
            # wait max 1 Sec.
            self.router.join(1.0)

    @inlineCallbacks
    def onJoin(self, details):
        port = self.config.extra['port']
        baudrate = self.config.extra['baudrate']

        # install signal handler
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)

        self.toWAMP_logger = Log_WAMP_Handler(self, self.logQueue)
        self.toWAMP_logger.addFilter(NoHTTP_GetFilter())
        logging.getLogger('serial2ws').addHandler(self.toWAMP_logger)

        # first of all, register the getErrors Function
        yield self.register(self.getLog, u"de.me_systeme.gsv.getLog")
        yield self.register(self.getIsSerialConnected,
                            u"de.me_systeme.gsv.getIsSerialConnected")

        # create an router object/thread
        self.router = FrameRouter(self, self.frameInBuffer, self.antwortQueue)

        # create GSV6 Serial-Protocol-Object
        serialProtocol = GSV_6Protocol(self, self.frameInBuffer,
                                       self.antwortQueue)

        logging.getLogger('serial2ws.WAMP_Component').debug(
            'About to open serial port {0} [{1} baud] ..'.format(
                port, baudrate))

        # try to init Serial-Connection
        try:
            self.serialPort = SerialPort(serialProtocol,
                                         port,
                                         reactor,
                                         baudrate=baudrate)
            self.isSerialConnected = True
        except Exception as e:
            logging.getLogger('serial2ws.WAMP_Component').critical(
                'Could not open serial port: {0}. exit!'.format(e))
            os.kill(os.getpid(), signal.SIGTERM)
        else:
            # when erial-init okay -> start FrameRouter
            self.router.start()

    def __exit__(self):
        logging.getLogger('serial2ws.WAMP_Component').trace('Exit.')

    def __del__(self):
        logging.getLogger('serial2ws.WAMP_Component').trace('del.')

    def getLog(self):
        return list(self.logQueue)

    sendCounter = 0

    def writeAntwort(self, data, functionName, args=None):
        # okay this function have to be atomic
        # we protect it with a lock!
        self.serialWrite_lock.acquire()
        self.actTime = datetime.now()
        diffTime = self.actTime - self.lastTime
        if diffTime.days <= 0 and diffTime.seconds <= 2:
            if (diffTime.seconds == 0 and diffTime.microseconds < 4000):
                self.sendCounter += 1
                if self.sendCounter >= 8:
                    self.sendCounter = 0
                    logging.getLogger('serial2ws.WAMP_Component').debug(
                        "serialWait, prevent GSV-6CPU RX Buffer overflow")
                    sleep(0.2)  # Time in seconds
            else:
                self.sendCounter = 0
        try:
            self.antwortQueue.put_nowait({functionName: args})
            self.serialPort.write(str(data))
            logging.getLogger('serial2ws.WAMP_Component').debug(
                '[serialWrite] Data: ' +
                ' '.join(format(z, '02x') for z in data))
        except NameError:
            logging.getLogger('serial2ws.WAMP_Component').debug(
                '[WAMP_Component] serialport not openend')
        finally:
            self.lastTime = datetime.now()
            self.serialWrite_lock.release()

    def write(self, data):
        # okay this function have to be atomic
        # we protect it with a lock!
        self.serialWrite_lock.acquire()
        try:
            self.serialPort.write(str(data))
            logging.getLogger('serial2ws.WAMP_Component').debug(
                '[serialWrite] Data: ' +
                ' '.join(format(z, '02x') for z in data))
        except NameError:
            logging.getLogger('serial2ws.WAMP_Component').debug(
                'serialport not openend')
        finally:
            self.serialWrite_lock.release()

    def getIsSerialConnected(self):
        return self.isSerialConnected

    def lostSerialConnection(self, errorMessage):
        logging.getLogger('serial2ws.WAMP_Component').critical(
            "Lost SerialConnection: " + errorMessage)
        self.isSerialConnected = False
        # not implemented at web-frontend
        self.publish(u"de.me_systeme.gsv.onSystemGoingDown")
        # shut down app
        os.kill(os.getpid(), signal.SIGTERM)

    def signal_handler(self, signal, frame):
        if signal == 15:
            self.stopMeasurement()
        logger = logging.getLogger('serial2ws')
        logger.removeHandler(self.toWAMP_logger)
        logger.info('received SIGNAL, going down.')
        self.disconnect()

    def stopMeasurement(self):
        data = self.router.gsv6.buildStopTransmission()
        logging.getLogger('serial2ws.WAMP_Component').warning(
            'Sending stop Message to GSV-Modul')
        self.write(data)
        self.router.writeCSVdata()
Esempio n. 15
0
 def render_GET(self, request):
     data = packet(0x18, 0x00, 0x00, 0x00)
     SerialPort.write(port, data)
     request.setHeader("content-type", "application/json")
     request.setHeader("Cache-Control", "no-cache")
     return json.dumps([Relay, Sensor])