Пример #1
0
    def __init__(self):
        '''
        Load initial RFXtrx configuration from rfxtrx.conf
        '''   
        config_file = config_to_location('rfxtrx.conf')
        
        config = ConfigParser.RawConfigParser()
        config.read(os.path.join(config_file))
        self.port = config.get("serial", "port")

        # Get broker information (ZeroMQ)
        self.coordinator_host = config.get("coordinator", "host")
        self.coordinator_port = config.getint("coordinator", "port")
        
        self.loglevel = config.get('general', 'loglevel')
        self.id = config.get('general', 'id')

        callbacks = {'custom': self.cb_custom}
        self.pluginapi = pluginapi.PluginAPI(self.id, 'RFXtrx', 
                                             broker_host=self.coordinator_host, 
                                             broker_port=self.coordinator_port, **callbacks)
        
        log = Logging("RFXtrx", console=True)
        log.set_level(self.loglevel)
        
        self.protocol = RFXtrxProtocol(self, log) 
        myserial = SerialPort (self.protocol, self.port, reactor)
        myserial.setBaudRate(38400)
        reactor.run(installSignalHandlers=0)
        return True
Пример #2
0
def main():
    # start logging - this must come after AriUtils is imported
    print 'starting logger'
    log.startLogging(sys.stdout)
    
    if (len(sys.argv)<2):
        printout(vtype.kError,
                 'First argument is USB usbdevice (i.e. "/dev/ttyACM0")')
        sys.exit()
    else:
        usbdevice = sys.argv[1]

    infn = ''
    if (len(sys.argv)>2):
        infn = sys.argv[2]

    inext = splitFilenameExt(infn)[1]
    if ( (inext != 'dat') and (inext!='DAT') and (inext!='') and
         (inext != 'bin') and (inext!='BIN') ):
        print 'Need binary input file. Got [{0}]'.format(infn)
        sys.exit()

    usbFactory = protocol.Factory()
    usbFactory.protocol = AriUSBStationProtocol
    usbAriProtocol = usbFactory.buildProtocol(None)

    from twisted.internet import reactor
    
    port = SerialPort(usbAriProtocol, usbdevice, reactor, baud)
    # reset signal
    printout(vtype.kInfo,"Resetting MBED...")
    port.sendBreak()
    port.sendBreak()
    reactor.callWhenRunning(startupMsg)
    reactor.run()
Пример #3
0
class IoService(service.Service):
    name = "ioservice"
    def __init__(self, port, speed=115200):
        self.port = port
        self.speed = speed
    
    def startService(self):
        log.msg(system='IoService', format="service starting")
        self.protocol = IoProtocol(self)
        log.msg(system='IoService', format="opening serial port %(port)s", port=self.port)
        self.serial = SerialPort(self.protocol, self.port, reactor, baudrate=self.speed)
        self.lcd = Lcd(self)
        self.sonar = Sonar(self)
        self.protocol.register_callback(0x01, self.onHandshake)
        self.protocol.register_callback(0xee, self.onIoError)
        service.Service.startService(self)

    def stopService(self):
        log.msg(system='IoService', format="service stopping")
        self.serial.loseConnection()
        service.Service.stopService(self)

    def onHandshake(self, data):
        log.msg(system='IoService', format="Controller is alive") 
        self.parent.triggerEvent('IO_HANDSHAKE')

    def onIoError(self, data):
        log.msg(system='IoService', format="Controller error, code %(code)#x", code=data[0])
        self.parent.triggerEvent('IO_ERROR', data[0])
Пример #4
0
class SP(object):

    """A Calvin serialport object"""

    def __init__(self, devicename, baudrate, bytesize, parity, stopbits, timeout, xonxoff, rtscts, trigger, actor_id):
        self._trigger  = trigger
        self._actor_id = actor_id
        self._port      = SerialPort(
            RawProtocol(self),
            devicename,
            reactor,
            baudrate,
            bytesize,
            parity,
            stopbits,
            timeout,
            xonxoff,
            rtscts)

    def trigger(self):
        self._trigger(actor_ids=[self._actor_id])

    def write(self, data):
        fdesc.writeToFD(self._port.fileno(), data)

    def read(self):
        data = self._port.protocol.data
        self._port.protocol.data = b""
        return data

    def hasData(self):
        return len(self._port.protocol.data)

    def close(self):
        self._port.loseConnection()
Пример #5
0
        def __init__(self, framer, *args, **kwargs):
            ''' Setup the client and start listening on the serial port

            :param factory: The factory to build clients with
            '''
            self.decoder = ClientDecoder()
            proto_cls = kwargs.pop("proto_cls", None)
            proto = SerialClientFactory(framer, proto_cls).buildProtocol()
            SerialPort.__init__(self, proto, *args, **kwargs)
Пример #6
0
    def start(self):
        '''
        Function that starts the JeeLabs plug-in. It handles the creation 
        of the plugin connection and connects to the specified serial port.
        '''
        self.pluginapi = PluginAPI(plugin_id=self.id, plugin_type='Jeelabs', logging=self.logging,
                                   broker_ip=self.broker_host, broker_port=self.broker_port,
                                   username=self.broker_user, password=self.broker_pass, vhost=self.broker_vhost)
        
        protocol = JeelabsProtocol(self) 
        myserial = SerialPort (protocol, self.port, reactor)
        myserial.setBaudRate(57600)      

        reactor.run(installSignalHandlers=0)
        return True
Пример #7
0
 def connect(self):
     try:
         self.serialport = SerialPort(self.protocol, self.port, self.reactor,
                                      *self.args, **self.kwargs)
         self.resetDelay()
     except SerialException:
         self.connectionFailed(Failure())
Пример #8
0
 def start(self):
     '''
     Function that starts the CM11 plug-in. It handles the creation 
     of the plugin connection and connects to the specified serial port.
     '''
     
     #FIXME: Error when serial port does not exist or cannot be opened
     try:
         myserial = SerialPort (self.protocol, self.port, reactor)
         myserial.setBaudRate(4800)      
         self.reactor = reactor
     
         reactor.run(installSignalHandlers=0)
         return(True)
     except:
         log.msg("Error opening serial port %s (%s)" % (self.port, sys.exc_info()[1]))
         return(False)
 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)
Пример #10
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
Пример #11
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)
Пример #12
0
 def startService(self):
     log.msg(system='DriveService', format="service starting")
     self.protocol = DriveProtocol(self)
     log.msg(system='DriveService', format="opening serial port %(port)s", port=self.port)
     self.serial = SerialPort(self.protocol, self.port, reactor, baudrate=self.speed)
     self.protocol.register_callback(0x01, self._onHandshake)
     self.protocol.register_callback(0x41, self._onReceiveCalibration)
     self.protocol.register_callback(0x42, self._onReceiveStatus)
     self.protocol.register_callback(0xee, self._onDriveError)
     service.Service.startService(self)
Пример #13
0
 def startService(self):
     log.msg(system='IoService', format="service starting")
     self.protocol = IoProtocol(self)
     log.msg(system='IoService', format="opening serial port %(port)s", port=self.port)
     self.serial = SerialPort(self.protocol, self.port, reactor, baudrate=self.speed)
     self.lcd = Lcd(self)
     self.sonar = Sonar(self)
     self.protocol.register_callback(0x01, self.onHandshake)
     self.protocol.register_callback(0xee, self.onIoError)
     service.Service.startService(self)
Пример #14
0
 def make_serial_connection(self):
     """
     Creates the serial connection to the port specified by the instance's
     _serial_port variable and sets the instance's _serial_transport variable
     to the twisted.internet.serialport.SerialPort instance.
     """
     self._serial_transport = SerialPort(self, self._serial_port, reactor,
                                         baudrate=2400, bytesize=8,
                                         parity='N', stopbits=1, timeout=5,
                                         xonxoff=0, rtscts=0)
Пример #15
0
class ReconnectingSerialPort(Reconnector):
    """ A class for serial port connection that will retry the connection
        if the connection fails
    """

    def __init__(self, reactor, protocol, port, *args, **kwargs):
        Reconnector.__init__(self, reactor)
        self.protocol = protocol
        self.port = port
        self.args = args
        self.kwargs = kwargs
        self.serialport = None


    def connect(self):
        try:
            self.serialport = SerialPort(self.protocol, self.port, self.reactor,
                                         *self.args, **self.kwargs)
            self.resetDelay()
        except SerialException:
            self.connectionFailed(Failure())


    def connectionLost(self, reason):
        self.serialport = None
        self.retry()


    def connectionFailed(self, reason):
        self.serialport = None
        self.retry()


    def loseConnection(self, *args, **kwargs):
        ''' Lose connection to the serial port '''
        self.stopTrying()
        if self.serialport:
            self.serialport.loseConnection(*args, **kwargs)
Пример #16
0
 def __init__(self, devicename, baudrate, bytesize, parity, stopbits, timeout, xonxoff, rtscts, trigger, actor_id):
     self._trigger  = trigger
     self._actor_id = actor_id
     self._port      = SerialPort(
         RawProtocol(self),
         devicename,
         reactor,
         baudrate,
         bytesize,
         parity,
         stopbits,
         timeout,
         xonxoff,
         rtscts)
Пример #17
0
class KetiDriver(SmapDriver):
    CHANNELS = [('temperature', 'C', 'double'),
                ('humidity', '%RH', 'double'),
                ('light', 'lx', 'long'),
                ('pir', '#', 'long'),
                ('co2', 'ppm', 'long')]
    
    def setup(self, opts):
        self.port = opts.get('SerialPort', '/dev/ttyrd00')
        self.baud = int(opts.get('BaudRate', 115200))
        self.namespace = opts.get('Namespace', None)
        if self.namespace: self.namespace = uuid.UUID(self.namespace)

    def uuid(self, serial_id, channel):
        # create consistent uuids for data based on the serial id
        key = serial_id + '-' + channel
        if self.namespace:
            return uuid.uuid5(self.namespace, key)
        else:
            return SmapDriver.uuid(self, key)

    def start(self):
        self.serial = SerialPort(KetiMoteReceiver(self), self.port,
                                 reactor, baudrate=self.baud)

    def stop(self):
        return self.serial.loseConnection()

    def create_channels(self, msg):
        if not self.get_collection('/' + str(msg['node_id'])):
            for (name, unit, dtype) in self.CHANNELS:
                self.add_timeseries('/' + str(msg['node_id']) + '/' + name,
                                    self.uuid(msg['serial_id'], name),
                                    unit, data_type=dtype)
            self.set_metadata('/' + str(msg['node_id']), {
                'Metadata/Instrument/PartNumber': str(msg['node_id']),
                'Metadata/Instrument/SerialNumber': ':'.join(map(lambda x: hex(ord(x))[2:],
                                                                msg['serial_id']))
                })

    def dataReceived(self, msg):
        self.create_channels(msg)
        for (name, _, __) in self.CHANNELS:
            if name in msg:
                self._add('/' + str(msg['node_id']) + '/' + name,
                          msg[name])
Пример #18
0
    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()
Пример #19
0
 def connectionLost(self, reason):
     SerialPort.connectionLost(self, reason)
     self.protocol.connectionLost(reason)
Пример #20
0
class AqiMonitor(service.Service):
    '''
    AQI monitor service.

    '''
    name = 'aqi_monitor'

    sensor_reconnect_timeout = 5

    def __init__(self,
                 aqi_storage,
                 sensor_device,
                 sensor_baudrate,
                 poll_period,
                 debug=False):
        self.debug = debug
        self.sensor = None
        self.sensor_device = sensor_device
        self.sensor_baudrate = sensor_baudrate
        self.poll_period = poll_period
        self.pm_timestamp = None
        self.pm_25 = None
        self.pm_10 = None
        self.aqi_storage = aqi_storage
        self.listeners = []

    def startService(self):
        self._bot = self.parent.getServiceNamed(TelegramBot.name)
        reactor.callLater(0, self.connect_sensor)  # @UndefinedVariable

    def add_listener(self, listener):
        if listener not in self.listeners:
            self.listeners.append(listener)

    def connect_sensor(self):
        self.sensor = Sds011(self, debug=self.debug)
        try:
            self.serial_port = SerialPort(self.sensor,
                                          self.sensor_device,
                                          reactor,
                                          baudrate=self.sensor_baudrate)
            self.serial_port.flushInput()
        except SerialException as se:
            log.error("Can't connect to sensor: %s" % se)
            reactor.callLater(
                self.sensor_reconnect_timeout,  # @UndefinedVariable
                self.connect_sensor)

    @defer.inlineCallbacks
    def init_sensor(self):
        yield self.sensor.query_data()
        period = yield self.sensor.set_working_period(self.poll_period)
        if self.debug:
            log.debug("Sensor initialized, poll period set to %d minute(s)" %
                      period)

    def sensor_connected(self):
        log.info("Connected to sensor")
        reactor.callLater(1, self.init_sensor)  # @UndefinedVariable

    def sensor_disconnected(self, reason):
        log.warn("Disconnected from sensor, reason: %r" % reason)
        reactor.callLater(self.sensor_reconnect_timeout,
                          self.connect_sensor)  # @UndefinedVariable

    def sensor_data(self, pm_25, pm_10):
        if pm_25 <= 0 or pm_10 <= 0:  # could be at sensor startup
            log.warn("Ignore invalid sensor data: PM2.5: %.1f, PM10: %.1f" %
                     (pm_25, pm_10))
            return
        log.info("Sensor data received, PM2.5: %.1f, PM10: %.1f" %
                 (pm_25, pm_10))
        self.pm_25 = pm_25
        self.pm_10 = pm_10
        self.pm_timestamp = time.time()
        self.aqi_storage.add_pm_data(int(self.pm_timestamp), pm_25, pm_10)
        for listener in self.listeners:
            try:
                listener.pm_data_updated(pm_25, pm_10, self.aqi)
            except Exception:
                log.failure("Can't notify PM data listener {listener}",
                            listener=listener)

    @property
    def sensor_firmware_version(self):
        if self.sensor is None or not self.sensor.connected:
            raise SensorDisconnected(
                "Can't get sensor firmware version: sensor not connected")
        return self.sensor.get_firmware_version()

    @staticmethod
    def to_aqi_level(aqi):
        if aqi <= 50:
            return 0  # Good
        elif aqi <= 100:
            return 1  # Moderate
        elif aqi <= 150:
            return 2  # Unhealthy for Sensitive Groups
        elif aqi <= 200:
            return 3  # Unhealthy
        elif aqi <= 300:
            return 4  # Very Unhealthy
        return 5  # Hazardous

    @property
    def aqi_level(self):
        if self.pm_timestamp is None:
            return None
        return self.to_aqi_level(self.aqi)

    @property
    def aqi(self):
        if self.pm_timestamp is None:
            return None
        return aqi_calc.to_aqi([(aqi_calc.POLLUTANT_PM25, self.pm_25),
                                (aqi_calc.POLLUTANT_PM10, self.pm_10)])

    @property
    def pm(self):
        return self.pm_25, self.pm_10
Пример #21
0
 def connect(self, protocol_factory):
     protocol = protocol_factory.buildProtocol(None)
     SerialPort(protocol, self.__port, self.__reactor,
                **self.__serial_kwargs)
     return defer.succeed(protocol)
Пример #22
0
class DriveService(service.Service):
    name = "driveservice"
    def __init__(self, port, speed=115200):
        self.port = port
        self.speed = speed
        self.cal_x_cur = 0
        self.cal_y_cur = 0
        self.cal_x_eeprom = 0
        self.cal_y_eeprom = 0

    def startService(self):
        log.msg(system='DriveService', format="service starting")
        self.protocol = DriveProtocol(self)
        log.msg(system='DriveService', format="opening serial port %(port)s", port=self.port)
        self.serial = SerialPort(self.protocol, self.port, reactor, baudrate=self.speed)
        self.protocol.register_callback(0x01, self._onHandshake)
        self.protocol.register_callback(0x41, self._onReceiveCalibration)
        self.protocol.register_callback(0x42, self._onReceiveStatus)
        self.protocol.register_callback(0xee, self._onDriveError)
        service.Service.startService(self)
    
    def stopService(self):
        log.msg(system='DriveService', format="service stopping")
        self.serial.loseConnection()
        service.Service.stopService(self)

    def setMode(self, mode):
        self.protocol.cmd_mode(mode)

    def directJoystick(self, xpos, ypos):
        self.protocol.cmd_joystick(xpos, ypos)

    def setCalibration(self, xvalue, yvalue):
        self.protocol.cmd_calibrate_set(xvalue, yvalue)

    def storeCalibration(self):
        self.protocol.cmd_calibrate_store()

    def driveSelect(self, enable):
        self.protocol.cmd_driveselect(enable)

    def stop(self):
        self.protocol.cmd_joystick(0, 0)

    def estop(self):
        self.protocol.cmd_estop()

    def reset(self):
        self.protocol.cmd_reset()

    def getCalibration(self):
        self.protocol.req_calibration()
        self.calibration_d = defer.Deferred()
        return self.calibration_d

    def _onHandshake(self, data):
        log.msg(system='DriveService', format="Controller is alive")
        self.parent.triggerEvent('DRV_HANDSHAKE')

    def _onDriveError(self, data):
        log.msg(system='DriveService', format="Controller error, code %(code)#x", code=data[0])
        self.parent.triggerEvent('DRV_ERROR', data[0])

    def _onReceiveStatus(self, data):
        status = data[0];
        xpos = data[1];
        ypos = data[2];
        xval = data[3];
        yval = data[4];
        self.parent.triggerEvent('DRV_STATUS', status, xpos, ypos, xval, yval)

    def _onReceiveCalibration(self, data):
        log.msg(system='DriveService', format="receivied calibration values")
        calibration = {}
        calibration['current_x'] = data[0]
        calibration['current_y'] = data[1]
        calibration['eeprom_x'] = data[2]
        calibration['eeprom_y'] = data[3]
        self.cal_x_cur = data[0]
        self.cal_y_cur = data[1]
        self.cal_x_eeprom = data[2]
        self.cal_y_eeprom = data[3]
        if self.calibration_d is not None:
            self.calibration_d.callback(calibration)
            self.calibration_d = None
Пример #23
0
# Handler for Test Relay Status REST event
class TestRelay(resource.Resource):
    isLeaf = True

    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])


# REST Router tree
if __name__ == "__main__":
    root = static.File(".")
    root.indexNames = ['index.html']
root.putChild("set", SetRelay())
root.putChild("test", TestRelay())

# HTTP Server construct and start
factory = server.Site(root)
reactor.listenTCP(port, factory)

# Serial construct and start
port = SerialPort(SerLog(), serdev, reactor, baudrate=baud)

# Start event driven process
print "Reactor ready"
reactor.run()
Пример #24
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")
Пример #25
0
    SERVER_WS_PORT = 8000
    SERVER_HTTP_PORT = 9000
    SERVER_HTTP_RESOURCES = 'web'
    bridge = Bridge()

    log.startLogging(sys.stdout)

    # websocket setup
    wsAddress = 'wss://%s:%d' % (SERVER_IP, SERVER_WS_PORT)
    contextFactory = ssl.DefaultOpenSSLContextFactory(
        '/etc/apache2/ssl/localhost.key', '/etc/apache2/ssl/localhost.crt')
    wsfactory = BridgedWebSocketServerFactory(wsAddress, False, False, bridge)
    wsfactory.protocol = WebSocketServer
    reactor.listenSSL(SERVER_WS_PORT, wsfactory, contextFactory)

    # http setup
    webdir = os.path.abspath(SERVER_HTTP_RESOURCES)
    site = Site(File(webdir))
    site.protocol = autobahn.twisted.resource.HTTPChannelHixie76Aware
    reactor.listenTCP(SERVER_HTTP_PORT, site)

    usbclient = USBClient(bridge)

    print('About to open serial port {0} [{1} baud] ..'.format(port, baudrate))
    try:
        SerialPort(usbclient, port, reactor, baudrate=baudrate)
    except Exception as e:
        print('Could not open serial port: {0}'.format(e))

    reactor.run()
Пример #26
0
 def startService(self):
   self.serialProtocol = SerialProtocol(self.parentService)
   self.serial = SerialPort(self.serialProtocol, '/dev/ttyATH0', reactor, baudrate=9600)
Пример #27
0
 def connectionLost(self, reason):
     SerialPort.connectionLost(self, reason)
     self.protocol.connectionLost(reason)
Пример #28
0
# -*- coding: utf-8 -*-
import serial
from twisted.internet import reactor
from twisted.internet.serialport import SerialPort

from device import DevicePirit
from commands import PrintActivizationReportEKLZCommand

# http://www.1c.ru/news/info.jsp?id=12122
# http://erpandcrm.ru/sbis_presto_userguide.ru/10/otkritie_smeni.htm

p = SerialPort(DevicePirit(),
               '/dev/ttyUSB0',
               reactor,
               baudrate=57600,
               bytesize=8,
               parity=serial.PARITY_NONE,
               stopbits=serial.STOPBITS_ONE)
p.pirit_password = '******'

c = PrintActivizationReportEKLZCommand().start()


def pr(x, y=None):
    print '321'
    print x, y


c.addCallback(lambda x: pr(x))
c.addErrback(lambda x: pr('!', x))
reactor.run()
#!/usr/bin/python
import glob
from twisted.internet import reactor
from twisted.internet.serialport import SerialPort
from ProcessProtocolUtils import TerminalEchoProcessProtocol

devices = glob.glob('/dev/ttyUSB*')
SerialPort(TerminalEchoProcessProtocol(), devices[0], reactor, timeout=3)

reactor.run()
Пример #30
0
 def start(self):
     self.serial = SerialPort(KetiMoteReceiver(self),
                              self.port,
                              reactor,
                              baudrate=self.baud)
Пример #31
0
                log.msg('Serial Call: Not available.')
        elif sensor[:2].upper() == 'OW':
            try:
                log.msg('OneWire: Initiating sensor...')
                oprot = task.LoopingCall(wsMcuFactory.owProtocol.owConnected)
                oprot.start(timeoutow)
            except:
                log.msg('OneWire: Not available.')
        else:
            try:
                log.msg('%s: Attempting to open port %s [%d baud]...' %
                        (sensor, port, baudrate))
                if sensor.startswith('KER'):
                    serialPort = SerialPort(protocol,
                                            port,
                                            reactor,
                                            baudrate=baudrate,
                                            bytesize=SEVENBITS,
                                            parity=PARITY_EVEN)
                else:
                    serialPort = SerialPort(protocol,
                                            port,
                                            reactor,
                                            baudrate=baudrate)
                    log.msg('%s: Port %s [%d baud] connected' %
                            (sensor, port, baudrate))
            except:
                log.msg('%s: Port %s [%d baud] not available' %
                        (sensor, port, baudrate))

    ## create embedded web server for static files
    ##
Пример #32
0
        elif self._state == 1:
            self.assignch()

        elif self._state == 2:
            self.setrf()

        elif self._state == 3:
            self.setchperiod()

        elif self._state == 4:
            self.setchid()

        elif self._state == 5:
            self.opench()

        elif self._state == 6:
            pass #self.sendStr('aaaaaaaa')
            
        if self._state < 6:
            self._state += 1


proto = ANT(debug=False)
if len(sys.argv) < 2:
    print "useage: %s COM_PORT_NUMBER_OR_SERIAL_DEVICE" % sys.argv[0]
    sys.exit(1)

port = SerialPort(proto, sys.argv[1], reactor)
port.setBaudRate(4800)
reactor.run()
Пример #33
0
 def start(self):
     self.serial = SerialPort(KetiMoteReceiver(self), self.port,
                              reactor, baudrate=self.baud)
Пример #34
0
def get_serial(name, path):
    protocol = MrlcommProtocol(name)
    SerialPort(protocol, path, reactor=reactor, baudrate=115200),
    return protocol
Пример #35
0
    )
    parser.add_option(
        '-t',
        '--tcp-pci',
        dest='tcp_pci',
        default=None,
        help=
        'IP address and TCP port where the PCI is located (CNI).  Either this or -s must be specified.'
    )

    option, args = parser.parse_args()

    log.startLogging(sys.stdout)

    protocol = PCIProtocol()
    if option.serial_pci and option.tcp_pci:
        parser.error(
            'Both serial and TCP CBus PCI addresses were specified!  Use only one...'
        )
    elif option.serial_pci:
        SerialPort(protocol, option.serial_pci, reactor, baudrate=9600)
    elif option.tcp_pci:
        addr = option.tcp_pci.split(':', 2)
        point = TCP4ClientEndpoint(reactor, addr[0], int(addr[1]))
        d = point.connect(CBusProtocolHandlerFactory(protocol))
    else:
        parser.error(
            'No CBus PCI address was specified!  (See -s or -t option)')

    reactor.run()
Пример #36
0
        log.msg("RIGHT")

    def up_right(self):
        log.msg("right")

    def move(self, x, y):
        log.msg("(%d,%d)" % (x, y))


if __name__ == '__main__':
    from twisted.internet import reactor
    from twisted.internet.serialport import SerialPort
    o = Options()
    try:
        o.parseOptions()
    except usage.UsageError, errortext:
        print "%s: %s" % (sys.argv[0], errortext)
        print "%s: Try --help for usage details." % (sys.argv[0])
        raise SystemExit, 1

    logFile = sys.stdout
    if o.opts['outfile']:
        logFile = o.opts['outfile']
    log.startLogging(logFile)

    SerialPort(McFooMouse(),
               o.opts['port'],
               reactor,
               baudrate=int(o.opts['baudrate']))
    reactor.run()
Пример #37
0
            btn1, pot1 = data[0:2]

            # if button pressed, or analog value > 400, turn on LED
            if btn1 or pot1 > 400:
                self.transport.write("1\n")
            else:
                self.transport.write("0\n")


if __name__ == '__main__':

    # import Twisted reactor
    #
    if sys.platform == 'win32':
        # on Windows, we need to use the following reactor for serial support
        # http://twistedmatrix.com/trac/ticket/3802
        #
        from twisted.internet import win32eventreactor
        win32eventreactor.install()

    from twisted.internet import reactor
    print("Using Twisted reactor {0}".format(reactor.__class__))

    # create instance of out serial protocol
    serial_proto = MySerialBridge()

    # create serial port: adjust for serial device / baudrate
    serial_port = SerialPort(serial_proto, SERIAL_PORT, reactor, baudrate=SERIAL_BAUDRATE)

    reactor.run()
Пример #38
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()
Пример #39
0
 def connect(self, port):
     self.serial = SerialPort(RadioReceiverProtocol(self), port, reactor, baudrate=57600)
     self.serial.flushInput()
Пример #40
0
                command = parts[1]
                parameter = parts[2]
                print "[Option = ", option, ", Command = ", command, ", Parameter = ", parameter, "]"
                reactor.callFromThread(self.send,
                                       'remote_at',
                                       frame_id='A',
                                       dest_addr_long=dest_addr,
                                       dest_addr='\xFF\xFE',
                                       options=option.decode('hex'),
                                       command=command,
                                       parameter=parameter.decode('hex'))
            else:
                print "INVALID END OF FRAME"


s = SerialPort(ZBHandler(escaped=False), ZB_PORT, reactor, ZB_SPEED)


################################################################################
# Send data to all TCP + Websocket clients.
################################################################################
def broadcastToClients(data, source=None, timestamp=False):

    if timestamp:
        data = strftime("%Y-%m-%d %H:%M:%S").encode('utf8') + ": " + data

    for client in TCPClients:
        if client != source:
            client.transport.write(data)
    for client in WebSockClients:
        if client != source:
Пример #41
0
def main() -> None:
    """
    Connect to MRI scanner and button box. Start network comms.
    """
    # Fetch command-line options.
    parser = argparse.ArgumentParser(
        prog="camcops_mri_scanner_server",  # name the user will use to call it
        description="CamCOPS MRI scanner/button box interface server.")
    parser.add_argument("--port",
                        type=int,
                        default=3233,
                        help="TCP port for network communications")
    # ... Suboptimal, but this is the Whisker port number

    parser.add_argument("--mri_serialdev",
                        type=str,
                        default="/dev/cu.Bluetooth-Serial-1",
                        help=("Device to talk to MRI scanner "
                              "(e.g. Linux /dev/XXX; Windows COM4)"))
    parser.add_argument("--mri_baudrate",
                        type=int,
                        default=19200,
                        help="MRI scanner: baud rate (e.g. 19200)")
    parser.add_argument("--mri_bytesize",
                        type=int,
                        default=EIGHTBITS,
                        help="MRI scanner: number of bits (e.g. 8)")
    parser.add_argument("--mri_parity",
                        type=str,
                        default=PARITY_NONE,
                        help="MRI scanner: parity (e.g. N)")
    parser.add_argument("--mri_stopbits",
                        type=int,
                        default=STOPBITS_ONE,
                        help="MRI scanner: stop bits (e.g. 1)")
    parser.add_argument("--mri_xonxoff",
                        type=int,
                        default=0,
                        help="MRI scanner: use XON/XOFF (0 or 1)")
    parser.add_argument("--mri_rtscts",
                        type=int,
                        default=0,
                        help="MRI scanner: use RTS/CTS (0 or 1)")

    parser.add_argument("--bb_serialdev",
                        type=str,
                        default="/dev/cu.Bluetooth-Serial-2",
                        help=("Device to talk to button box "
                              "(e.g. Linux /dev/YYY; Windows COM5)"))
    parser.add_argument("--bb_baudrate",
                        type=int,
                        default=19200,
                        help="Button box: baud rate (e.g. 19200)")
    parser.add_argument("--bb_bytesize",
                        type=int,
                        default=EIGHTBITS,
                        help="Button box: number of bits (e.g. 8)")
    parser.add_argument("--bb_parity",
                        type=str,
                        default=PARITY_NONE,
                        help="Button box: parity (e.g. N)")
    parser.add_argument("--bb_stopbits",
                        type=int,
                        default=STOPBITS_ONE,
                        help="Button box: stop bits (e.g. 1)")
    parser.add_argument("--bb_xonxoff",
                        type=int,
                        default=0,
                        help="Button box: use XON/XOFF (0 or 1)")
    parser.add_argument("--bb_rtscts",
                        type=int,
                        default=0,
                        help="Button box: use RTS/CTS (0 or 1)")

    args = parser.parse_args()

    tcpfactory = TabletServerProtocolFactory()

    logger.info("MRI scanner: starting serial comms on device {dev} "
                "({baud} bps, {b}{p}{s})".format(dev=args.mri_serialdev,
                                                 baud=args.mri_baudrate,
                                                 b=args.mri_bytesize,
                                                 p=args.mri_parity,
                                                 s=args.mri_stopbits))
    SerialPort(protocol=MRIProtocol(tcpfactory),
               deviceNameOrPortNumber=args.mri_serialdev,
               reactor=reactor,
               baudrate=args.mri_baudrate,
               bytesize=args.mri_bytesize,
               parity=args.mri_parity,
               stopbits=args.mri_stopbits,
               xonxoff=args.mri_xonxoff,
               rtscts=args.mri_rtscts)

    logger.info("Response button box: starting serial comms on device {dev} "
                "({baud} bps, {b}{p}{s})".format(dev=args.bb_serialdev,
                                                 baud=args.bb_baudrate,
                                                 b=args.bb_bytesize,
                                                 p=args.bb_parity,
                                                 s=args.bb_stopbits))
    SerialPort(protocol=ButtonBoxProtocol(tcpfactory),
               deviceNameOrPortNumber=args.bb_serialdev,
               reactor=reactor,
               baudrate=args.bb_baudrate,
               bytesize=args.bb_bytesize,
               parity=args.bb_parity,
               stopbits=args.bb_stopbits,
               xonxoff=args.bb_xonxoff,
               rtscts=args.bb_rtscts)

    logger.info("Starting keyboard input")

    # Keyboard: method 1
    # StandardIO(StubbornlyLineBasedKeyboardProtocol(tcpfactory))

    # Keyboard: method 2
    k = KeyboardPoller(tcpfactory)
    lc = LoopingCall(k.tick)
    lc.start(KEYBOARD_TICK_S)

    logger.info("Starting network comms on port {}".format(args.port))
    logger.debug('To debug, try: "telnet localhost {}"'.format(args.port))
    reactor.listenTCP(args.port, tcpfactory)
    reactor.run()
Пример #42
0
class InstProtocol2200087(Protocol):
    """
    This is a twisted protocol which handles serial communications with
    2200087 multimeters. This protocol exists and operates within the context
    of a twisted reactor. Applications themselves built on twisted should be
    able to simply import this protocol (or its factory).

    If you would like the protocol to produce datapoints in a different format,
    this protocol should be sub-classed in order to do so. The changes necessary
    would likely begin in this class's frame_recieved() function.

    Synchronous / non-twisted applications should use the InstInterface2200087
    class instead. The InstInterface2200087 class accepts a parameter to specify
    which protocol factory to use, in case you intend to subclass this protocol.

    :param port: Port on which the device is connected. Default '/dev/ttyUSB0'.
    :type port: str
    :param buffer_size: Length of the point buffer in the protocol. Default 100.
    :type buffer_size: int

    """
    def __init__(self, port, buffer_size=100):
        self._buffer = ""
        self._frame_size = 14
        self._point_buffer_size = buffer_size
        self.point_buffer = None
        self.reset_buffer()
        self._serial_port = port
        self._serial_transport = None
        self._frame_processor = process_chunk

    def reset_buffer(self):
        """
        Resets the point buffer. Any data presently within it will be lost.
        """
        self.point_buffer = deque(maxlen=self._point_buffer_size)

    def make_serial_connection(self):
        """
        Creates the serial connection to the port specified by the instance's
        _serial_port variable and sets the instance's _serial_transport variable
        to the twisted.internet.serialport.SerialPort instance.
        """
        self._serial_transport = SerialPort(self, self._serial_port, reactor,
                                            baudrate=2400, bytesize=8,
                                            parity='N', stopbits=1, timeout=5,
                                            xonxoff=0, rtscts=0)

    def break_serial_connection(self):
        """
        Calls loseConnection() on the instance's _serial_transport object.
        """
        self._serial_transport.loseConnection()

    def connectionMade(self):
        """
        This function is called by twisted when a connection to the serial
        transport is successfully opened.
        """
        pass

    def connectionLost(self, reason=connectionDone):
        """
        This function is called by twisted when the connection to the
        serial transport is lost.
        """
        print "Lost Connection to Device"
        print reason

    def dataReceived(self, data):
        """
        This function is called by twisted when new bytes are received by the
        serial transport.

        This data is appended to the protocol's framing buffer, _buffer, and
        when the length of the buffer is longer than the frame size, that many
        bytes are pulled out of the start of the buffer and frame_recieved is
        called with the frame.

        This function also performs the initial frame synchronization by
        dumping any bytes in the beginning of the buffer which aren't the
        first byte of the frame. In its steady state, the protocol framing
        buffer will always have the beginning of a frame as the first element.

        :param data: The data bytes received
        :type data: str

        """
        self._buffer += data
        while len(self._buffer) and self._buffer[0].encode('hex')[0] != '1':
            self._buffer = self._buffer[1:]
        while len(self._buffer) >= self._frame_size:
            self.frame_received(self._buffer[0:self._frame_size])
            self._buffer = self._buffer[self._frame_size:]

    def frame_received(self, frame):
        """
        This function is called by data_received when a full frame is received
        by the serial transport and the protocol.

        This function recasts the frame into the format used by the serialDecoder
        and then uses that module to process the frame into the final string. This
        string is then appended to the protocol's point buffer.

        This string is treated as a fully processed datapoint for the purposes
        of this module.

        :param frame: The full frame representing a single data point
        :type frame: str

        """
        frame = [byte.encode('hex') for byte in frame]
        chunk = ' '.join(frame)
        point = self._frame_processor(chunk)
        self.point_buffer.append(point)

    def latest_point(self, flush=True):
        """
        This function can be called to obtain the latest data point from the
        protocol's point buffer. The intended use of this function is to allow
        random reads from the DMM. Such a typical application will want to
        discard all the older data points (including the one returned), which
        it can do with flush=True.

        This function should only be called when there is data already in the
        protocol buffer, which can be determined using data_available().

        This is a twisted protocol function, and should not be called directly
        by synchronous / non-twisted code. Instead, its counterpart in the
        InstInterface object should be used.

        :param flush: Whether to flush all the older data points.
        :type flush: bool
        :return: Latest Data Point as processed by the serialDecoder
        :rtype: str

        """
        rval = self.point_buffer[-1]
        if flush is True:
            self.point_buffer.clear()
        return rval

    def next_point(self):
        """
        This function can be called to obtain the next data point from the
        protocol's point buffer. The intended use of this function is to allow
        continuous streaming reads from the DMM. Such a typical application will
        want to pop the element from the left of the point buffer, which is what
        this function does.

        This function should only be called when there is data already in the
        protocol buffer, which can be determined using data_available().

        This is a twisted protocol function, and should not be called directly
        by synchronous / non-twisted code. Instead, its counterpart in the
        InstInterface object should be used.

        :return: Next Data Point in the point buffer as processed by the serialDecoder
        :rtype: str

        """
        return self.point_buffer.popleft()

    def next_chunk(self):
        """
        This function can be called to obtain a copy of the protocol's point
        buffer with all but the latest point in protocol's point buffer. The
        intended use of this function is to allow continuous streaming reads
        from the DMM. Such a typical application will want to pop the elements
        from the left of the point buffer, which is what this function does.

        This function should only be called when there is data already in the
        protocol buffer, which can be determined using data_available().

        This is a twisted protocol function, and should not be called directly
        by synchronous / non-twisted code. Instead, its counterpart in the
        InstInterface object should be used.

        :return: Copy of point_buffer with all but the latest_point
        :rtype: deque
        """
        rval = self.point_buffer
        self.point_buffer = deque([rval.pop()], maxlen=self._point_buffer_size)
        return rval

    def data_available(self):
        """
        This function can be called to read the number of data points waiting in
        the protocol's point buffer.

        This is a twisted protocol function, and should not be called directly
        by synchronous / non-twisted code. Instead, its counterpart in the
        InstInterface object should be used.

        :return: Number of points waiting in the protocol's point buffer
        :rtype: int

        """
        return len(self.point_buffer)
Пример #43
0
      sys.exit(1)

   baudrate = int(o.opts['baudrate'])
   port = int(o.opts['port'])
   webport = int(o.opts['webport'])
   wsurl = o.opts['wsurl']

   ## start Twisted log system
   ##
   log.startLogging(sys.stdout)

   ## create Serial2Ws gateway factory
   ##
   wsMcuFactory = WsMcuFactory(wsurl)
   listenWS(wsMcuFactory)

   ## create serial port and serial port protocol
   ##
   log.msg('About to open serial port %d [%d baud] ..' % (port, baudrate))
   serialPort = SerialPort(wsMcuFactory.mcuProtocol, port, reactor, baudrate = baudrate)

   ## create embedded web server for static files
   ##
   webdir = File(".")
   web = Site(webdir)
   reactor.listenTCP(webport, web)

   ## start Twisted reactor ..
   ##
   reactor.run()
Пример #44
0
    def clientConnectionFailed(self, connector,reason):
        print "connection failed you not connected to the internet.", reason


#====================================================================
#---------------| FACTORY PROTOCOL CLASS |
#====================================================================
class CommandRxFactory(Factory):

    protocol = CommandRx

    def __init__(self):
        self.client_list = []
        print "CommandRX stuff ???."


if __name__ == '__main__':

    tcpfactory = CommandRxFactory()
    SerialPort(Arduclient(tcpfactory), '/dev/ttyUSB0', reactor, baudrate='9600')
    reactor.listenTCP(8001, tcpfactory)

    netdata = CommandRx()
    db = Alarm_DB()
    db.Select_Alarm_table()
    db. Select_Lights_table()
    arduino = Arduclient(Protocol)
    reactor.run()

Пример #45
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()
Пример #46
0
 def __init__(self):
     self.HTTPsetup = server.Site(HTTPserver())
     reactor.listenTCP(5000, HTTPsetup)
     SerialPort(USBclient(), '/dev/ttyACM0', reactor, baudrate='57600')
     thread.start_new_thread(reactor.run, ())
Пример #47
0
from twisted.internet import protocol, reactor
from twisted.internet.serialport import SerialPort
from twisted.protocols import basic


class DeviceADCP(basic.LineReceiver):
    def connectionMade(self):
        print('Connection made!')
        #self.sendString('CSHOW\n')

    def connectionLost(self, reason):
        self.factory.clients.remove(self)
        print('Connection lost')

    def dataReceived(self, data):
        print("Response: {0}", format(data))


SerialPort(DeviceADCP(),
           '/dev/cu.usbserial-FTYNODPO',
           reactor,
           baudrate=115200)
reactor.run()
Пример #48
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)
Пример #49
0
    try:
        o.parseOptions()
    except usage.UsageError as errortext:
        print '%s: %s' % (sys.argv[0], errortext)
        print '%s: Try --help for usage details.' % (sys.argv[0])
        raise SystemExit(1)

    logFile = o.opts['outfile']
    if logFile is None:
        logFile = sys.stdout
    log.startLogging(logFile)

    if o.opts['zodiac']:
        from twisted.protocols.gps.rockwell import Zodiac as GPSProtocolBase
        baudrate = 9600
    else:
        from twisted.protocols.gps.nmea import NMEAReceiver as GPSProtocolBase
        baudrate = 4800

    class GPSTest(GPSProtocolBase, GPSFixLogger):
        pass

    if o.opts['baudrate']:
        baudrate = int(o.opts['baudrate'])

    port = o.opts['port']
    log.msg('Attempting to open %s at %dbps as a %s device' %
            (port, baudrate, GPSProtocolBase.__name__))
    s = SerialPort(GPSTest(), o.opts['port'], reactor, baudrate=baudrate)
    reactor.run()
Пример #50
0
    global proto
    proto = ZigBee(callback=receive, escaped=True)
    proto.red = False
    proto.green = False

    def show(data, comment='broadcast'):
        log.debug('{desc} frame: {data})', desc=comment, data=data)

    def stop_monitor():
        log.debug('Stop Monitoring...')
        g = proto.remote_at(dest_addr_long=dest_addr_long,
                            command=b'IR',
                            parameter=b'\x00')
        g.addCallback(show, 'IR set')

    def test():
        print('start')
#         d = proto.remote_at(dest_addr_long=dest_addr_long, command=b'NI')
#         d.addCallback(show, 'NI Response')
#         e = proto.remote_at(dest_addr_long=dest_addr_long, command=b'IS')
#         e.addCallback(show, 'IS Response')
#         f = proto.remote_at(dest_addr_long=dest_addr_long,
#                             command=b'IR', parameter=b'\x02\x00')
#         f.addCallback(show, 'IR set')

    f = SerialPort(proto, '/dev/ttyACM0', reactor, baudrate=57600)
    reactor.callWhenRunning(test)  # @UndefinedVariable
    reactor.callLater(30, reactor.stop)  # @UndefinedVariable
    #     reactor.callLater(28, stop_monitor)  # @UndefinedVariable
    reactor.run()  # @UndefinedVariable
Пример #51
0
from atom.ws import WSRouterFactory

from atom.web import MainElement

app = Klein()


@app.route('/')
def home(request, name=''):
    return MainElement(name)


@app.route('/static/', branch=True)
def static(request):
    return File("./static")


from txws import WebSocketFactory
from twisted.internet import reactor

wsFactory = WSRouterFactory()
usbClient = USBRouterProtocol()

reactor.listenTCP(5600, WebSocketFactory(wsFactory))

SerialPort(usbClient, '/dev/ttyUSB0', reactor, baudrate='9600')

wsFactory.setSrcClients(usbClient.getClients())

resource = app.resource
 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])
class BioharnessProtocol(LineReceiver):
    message_ids = {
        "ecg": 0x16,
        "breathing": 0x15,
        "acceleration": 0x1E,
        "rr": 0x19,
        "summary": 0xBD,
        "life_sign": 0xA4,
    }

    stream_states = {"ON": 1, "OFF": 0}

    columns_of_streams = {
        "summary": SummaryMessage._fields,
        "breathing": SignalSample._fields,
        "ecg": SignalSample._fields,
        "rr": SignalSample._fields,
        "acceleration": AccelerationSignalSample._fields,
    }

    def __init__(self, processing_proxy, port, reactor):
        self.rr_buffer = deque(maxlen=1024)
        self.processing_proxy = processing_proxy
        self.port = port
        self.reactor = reactor
        self.serial = None

    def send_device_command(self, message_id, payload):
        message_frame = create_message_frame(message_id, payload)
        logging.info(
            "Bioharness - sending a command to the device: msg_id : %s, Payload : %s"
            % (message_id, payload))
        self.transport.write(message_frame)

    def set_stream_state(self, stream_id, state):
        self.send_device_command(self.message_ids[stream_id],
                                 [self.stream_states[state]])

    def disable_lifesign_timeout(self):
        self.send_device_command(self.message_ids["life_sign"], [0, 0, 0, 0])

    def set_summary_packet_transmit_interval_to_one_second(self):
        self.send_device_command(self.message_ids["summary"], [1, 0])

    def send_initialization_commands(self):
        self.set_stream_state("ecg", "ON")
        self.set_stream_state("breathing", "ON")
        self.set_stream_state("acceleration", "OFF")
        self.set_stream_state("rr", "ON")
        self.disable_lifesign_timeout()
        self.set_summary_packet_transmit_interval_to_one_second()

    def default_signal_waveform_handler(self, signal_packet, start_new_stream):
        samples_iterator = SignalPacketIterator(
            signal_packet).iterate_timed_samples()
        for signal_sample in samples_iterator:
            self.logger_of_stream[signal_sample.type].write_tuple_to_log_file(
                signal_sample)

            # send data for processing
            if signal_sample.type == 'rr':
                self.rr_buffer.append(signal_sample.sample)
                if len(self.rr_buffer) == self.rr_buffer.maxlen:
                    self.send_data_for_processing("rr_buffer",
                                                  list(self.rr_buffer),
                                                  signal_sample.timestamp)

                    #empty buffer partially
                    for _i in range(0, 18):  #self.rr_buffer.maxlen/12):
                        self.rr_buffer.popleft()

    def display_status_flags(self, summary_packet):
        if (summary_packet.heart_rate_unreliable
                or summary_packet.respiration_rate_unreliable) or (
                    summary_packet.hrv_unreliable
                    or summary_packet.button_pressed):
            logging.warn(
                "Bioharness - Heart Rate:%s ; Breathing Rate:%s ; HRV:%s" %
                ((not summary_packet.heart_rate_unreliable),
                 (not summary_packet.respiration_rate_unreliable),
                 (not summary_packet.hrv_unreliable)))

    def default_event_callback(self, summary_packet):
        self.display_status_flags(summary_packet)
        self.logger_of_stream["summary"].write_tuple_to_log_file(
            summary_packet)

        # send data for processing
        self.send_data_for_processing("respiration_rate",
                                      [summary_packet.respiration_rate],
                                      summary_packet.timestamp)

    def send_data_for_processing(self, type, value, timestamp):
        data = {"type": type}
        data["timestamp"] = timestamp
        data["value"] = value
        self.processing_proxy.notifyAll(data)

    def set_event_callbacks(self, callbacks=None):
        if callbacks is None: callbacks = [self.default_event_callback]
        self.event_callbacks = callbacks

    def set_waveform_callbacks(self, callbacks=None):
        if callbacks is None:
            callbacks = [self.default_signal_waveform_handler]
        self.waveform_callbacks = callbacks

    def set_data_loggers(self, logger_of_stream):
        self.logger_of_stream = logger_of_stream

    def connectionMade(self):
        # Setting the protocol to handle raw data rather than just lines
        self.setRawMode()

        # Sending commands to enable relevant streams and summary messages
        self.send_initialization_commands()

        self.signal_packet_handler_bh = BioHarnessPacketHandler(
            self.waveform_callbacks, self.event_callbacks)
        self.payload_parser = MessagePayloadParser(
            [self.signal_packet_handler_bh.handle_packet])
        self.message_parser = MessageFrameParser(
            self.payload_parser.handle_message)

    def rawDataReceived(self, data):
        if not data: return

        for byte in data:
            self.message_parser.parse_data(byte)

    def set_serial(self, serial):
        self.serial = serial

    def connectionLost(self, reason):
        logging.error("Bioharness - Lost connection (%s)" % reason)
        logging.info("Bioharness - Reconnecting in 5 seconds...")
        self.serial._serial.close()
        self.retry = self.reactor.callLater(5, self.reconnect)

    def reconnect(self):
        try:
            if self.serial is None:
                self.serial = SerialPort(self,
                                         self.port,
                                         self.reactor,
                                         baudrate=115200)
            else:
                self.serial.__init__(self,
                                     self.port,
                                     self.reactor,
                                     baudrate=115200)
            logging.info("Bioharness - Reconnected")

        except:
            logging.error("Bioharness - Error opening serial port %s (%s)" %
                          (self.port, sys.exc_info()[1]))
            logging.info("Bioharness - Reconnecting in 5 seconds...")
            self.retry = self.reactor.callLater(5, self.reconnect)
Пример #54
0
			else:	
				GPIO.output(18, True)	
				GPIO.output(23, True)	
				GPIO.output(24, True)	
				GPIO.output(25, True)	

			print "co2 : " + str(ppm) + " ppm" 

			data = {
				"metric": macAddr+"_co2",
				"timestamp": time.time(),
				"value": ppm,
				"tags": {
					"host": "raspberry"
				}
			}
			ret = requests.post(url, data=json.dumps(data))
			print ret.text
			time.sleep(5)
		except:
			print "error"
			pass
			sys.stdout.flush()


if __name__ == '__main__':
	setup()

	SerialPort(BridgeProtocol(), "/dev/ttyAMA0", reactor, baudrate=38400)
	reactor.run()
Пример #55
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])