def initGRIMM(dst_folder, device='/dev/ttyUSB0'): SerialPort(GRIMMcontrolFactory(dst_folder=dst_folder).buildProtocol(None), device, reactor, baudrate='9600', xonxoff=True)
def connect(self): config = self.config self.device_path = config.port try: #: Save a reference self.protocol.transport = self #: Make the wrapper self._protocol = RawFdProtocol(self, self.protocol) self.connection = SerialPort(self._protocol, config.port, reactor, baudrate=config.baudrate, bytesize=config.bytesize, parity=SERIAL_PARITIES[config.parity], stopbits=config.stopbits, xonxoff=config.xonxoff, rtscts=config.rtscts) # Twisted is missing this if config.dsrdtr: try: self.connection._serial.dsrdtr = True except AttributeError as e: log.warning("{} | dsrdtr is not supported {}".format( config.port, e)) log.debug("{} | opened".format(config.port)) except Exception as e: #: Make sure to log any issues as these tracebacks can get #: squashed by twisted log.error("{} | {}".format(config.port, traceback.format_exc())) raise
def attach_serial_protocol(device, test=False): """ Returns C{device} with a reference to the protocol's instance """ from vmc.common.protocol import SIMCardConnection from vmc.common.middleware import SIMCardConnAdapter if not test: # Use the adapter that device specifies if device.custom.adapter: adapter_klass = device.custom.adapter else: adapter_klass = SIMCardConnAdapter log.msg("ADAPTING %s to %s" % (device, adapter_klass)) sconn = adapter_klass(device) else: # We can only test SIMCardConnection as SIMCardConnAdapter uses # delayed calls sconn = SIMCardConnection(device) port = device.has_two_ports() and device.cport or device.dport # keep a reference to the SerialPort, in case we need to stop it or # something device.sport = SerialPort(sconn, port, reactor, baudrate=device.baudrate) device.sconn = sconn return device
def boot_dbus(serial_mode, addr, session_bus, timesync, no_clock): if session_bus: bus = dbus.SessionBus() else: bus = dbus.SystemBus() name = dbus.service.BusName(DBUS_SERVICE, bus=bus) protocol = CBusProtocolHandler() api = CBusService(name, protocol) if serial_mode: SerialPort(protocol, addr, reactor, baudrate=9600) else: point = TCP4ClientEndpoint(reactor, addr[0], int(addr[1])) d = point.connect(CBusProtocolHandlerFactory(protocol)) # setup time loop if applicable if timesync > 0: # in ten seconds, start timesync loop # TODO: have this fire after the connection is established instead reactor.callLater(10, protocol.timesync, timesync) if no_clock: protocol.on_clock_request = lambda x: None """mainloop = gobject.MainLoop()
def connect(self): try: config = self.config #: Save a reference self.protocol.transport = self #: Make the wrapper self._protocol = InkcutProtocol(self, self.protocol) self.connection = SerialPort( self._protocol, config.port, reactor, baudrate=config.baudrate, bytesize=config.bytesize, parity=SERIAL_PARITIES[config.parity], stopbits=config.stopbits, xonxoff=config.xonxoff, rtscts=config.rtscts ) log.debug("{} | opened".format(self.config.port)) except Exception as e: #: Make sure to log any issues as these tracebacks can get #: squashed by twisted log.error("{} | {}".format( self.config.port, traceback.format_exc() )) raise
def StartSerialServer(context, identity=None, framer=ModbusAsciiFramer, **kwargs): ''' Helper method to start the Modbus Async Serial server :param context: The server data context :param identify: The server identity to use (default empty) :param framer: The framer to use (default ModbusAsciiFramer) :param port: The serial port to attach to :param baudrate: The baud rate to use for the serial device :param console: A flag indicating if you want the debug console :param ignore_missing_slaves: True to not send errors on a request to a missing slave ''' from twisted.internet import reactor from twisted.internet.serialport import SerialPort port = kwargs.get('port', '/dev/ttyS0') baudrate = kwargs.get('baudrate', Defaults.Baudrate) console = kwargs.get('console', False) _logger.info("Starting Modbus Serial Server on %s" % port) factory = ModbusServerFactory(context, framer, identity, **kwargs) if console: InstallManagementConsole({'factory': factory}) protocol = factory.buildProtocol(None) SerialPort.getHost = lambda self: port # hack for logging SerialPort(protocol, port, reactor, baudrate) reactor.run(installSignalHandlers=_is_main_thread())
def open_serial_driver(self, p_pyhouse_obj, p_controller_obj): """ @param p_pyhouse_obj: is the entire PyHouse Data @param p_controller_obj: is the controller information for the serial controller we are opening. @return: the serial driver pointer """ l_serial = None p_controller_obj._Data = bytearray() l_baud = p_controller_obj.Interface.Baud l_host = p_controller_obj.Interface.Host.lower() l_port = p_controller_obj.Interface.Port l_computer = p_pyhouse_obj.Computer.Name.lower() l_name = p_controller_obj.Name if l_host != l_computer: LOG.warn('Device "{}" is on another computer "{}". This is "{}" - Ignored.'.format(l_name, l_host, l_computer)) return False # LOG.debug('Serial Interface {}'.format(PrettyFormatAny.form(p_controller_obj, 'Controller', 160))) try: l_serial = SerialPort( SerialProtocol(p_pyhouse_obj, p_controller_obj), # Factory l_port, p_pyhouse_obj._Twisted.Reactor, baudrate=l_baud) p_controller_obj.Interface._DriverApi = self # LOG.info("Opened Device:{}, Port:{}, Serial:{}".format(p_controller_obj.Name, l_port, l_serial)) # LOG.debug('Serial:{}'.format(l_serial)) # LOG.debug(PrettyFormatAny.form(l_serial, 'Serial')) # LOG.debug('Baud:{}'.format(l_baud)) except Exception as e_err: LOG.error("ERROR - Open failed for Device:{}, Port:{}\n\t{}".format( p_controller_obj.Name, p_controller_obj.Interface.Port, e_err)) LOG.debug(PrettyFormatAny.form(p_controller_obj, 'Controller')) self.m_serial = l_serial return l_serial
def start_arduino(self): if self.arduino_port: port = self.arduino_port baudrate = 9600 log.info("Opening Arduino on port: %s" % port) main_controller.arduino = SerialPort(ArduinoController(), port, reactor, baudrate)
def StartSerialServer(context, identity=None, framer=ModbusAsciiFramer, **kwargs): """ Helper method to start the Modbus Async Serial server :param context: The server data context :param identify: The server identity to use (default empty) :param framer: The framer to use (default ModbusAsciiFramer) :param port: The serial port to attach to :param baudrate: The baud rate to use for the serial device :param console: A flag indicating if you want the debug console """ from twisted.internet import reactor from twisted.internet.serialport import SerialPort port = kwargs.get('port', '/dev/ttyS0') baudrate = kwargs.get('baudrate', Defaults.Baudrate) console = kwargs.get('console', False) _logger.info("Starting Modbus Serial Server on " + str(port)) factory = ModbusServerFactory(context, framer, identity) if console: InstallManagementConsole({'factory': factory}) protocol = factory.buildProtocol(None) SerialPort.getHost = lambda self: port # hack for logging SerialPort(protocol, port, reactor, baudrate) reactor.run()
def connect(self, protocol_factory): protocol = protocol_factory.buildProtocol(None) try: SerialPort(protocol, self.__port, self.__reactor, **self.__serial_kwargs) return defer.succeed(protocol) except SerialException as e: # The documentation says we should produce a ConnectError, but doing so would be discarding information and doesn't appear to matter. TODO: Do it anyway and copy the info. return defer.fail(e)
def open(self, widget, data=None): try: self.serial = SerialPort(self.ir, self.entry_device.get_text(), reactor, baudrate=int(self.entry_baud.get_text())) except serial.SerialException as e: self.console_write("[ERROR] %s\r\n" % str(e))
def main(): from twisted.internet import reactor root = Root() port = SerialPort(root.teensyProtocol, teensyPort, reactor, baudrate=9600) stdio.StandardIO(root.ioProtocol) reactor.run()
def run(protocol, port, baudrate): SerialPort( protocol, port, reactor, baudrate=baudrate ) reactor.run(installSignalHandlers=False)
def open(cls, port, group): controller = cls() serial = SerialPort(baudrate=19200, deviceNameOrPortNumber=port, protocol=controller, reactor=reactor) controller.setSerial(serial) controller.setGroup(group) return controller
def reconnect(): if line_protocol.connected: return try: #SerialPort(line_protocol, '/dev/ttyACM0', reactor, 9600) # linux SerialPort(line_protocol, '/dev/tty.usbmodem14101', reactor, 9600) # OS X except: reactor.callLater(1.0, reconnect) # in case that one fails raise
def __init__(self, oNodeControl): if oNodeControl.nodeProps.has_option('smartmeter', 'serialport'): SerialPort(SmartMeterProtocol(oNodeControl), oNodeControl.nodeProps.get('smartmeter', 'serialport'), reactor, bytesize=SEVENBITS, parity=PARITY_EVEN) else: oNodeControl.log.warning("missing config param: smartmeter | serialport.")
def __init__(self): self.screen = pygame.display.set_mode((320, 240)) self.imgbuf = ['\0' * 320] * 120 self.tick = LoopingCall(self.game_tick) self.tick.start(1.0 / 15) # desired FPS # Set up anything else twisted here, like listening sockets self.ov7670 = OV7670Test() self.serial = SerialPort(self.ov7670, 5, reactor, baudrate=921600) self.serial.app = self
def __init__(self, hal, device='/dev/denon', outlet=None): """default device is /dev/denon""" self.mutedVolume = None # never close because the Denon sends events # by its own if it is operated by other means (IR, front knobs) self.surroundIdx = 0 self.lastSurroundTime = None Serializer.__init__(self, hal, outlet) self.__port = SerialPort(self, device, reactor)
def __init__(self, factory, comm_port, baud): self.factory = factory self.comm_port = comm_port self.baud = baud if self.factory.serial_port is None: # Create a Serial Port device to read in serial data self.factory.serial_port = SerialPort(SerialDevice(self, self), comm_port, reactor, baudrate=baud) logger.debug('Serial Port started')
def Connect(self): self.object['hw'] = SerialPort(self, self._devname, self.object['daemon']._reactor, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity, stopbits=self.stopbits, timeout=self.timeout)
def __init__(self, factory, comm_port, baud): self.factory = factory # Create a Serial Port device to read in serial data self.serial_port = SerialPort(SerialDevice(self, self), comm_port, reactor, baudrate=baud) print('Serial Port Thread started')
def do_connect(): try: conn = SerialPort(protocol, self.port.device, reactor, baudrate=self.baudrate) d.callback(conn) except Exception as e: log.error(e) d.callback(e)
def start(self): SerialPort(self, reactor=reactor, **{ "deviceNameOrPortNumber": self.options["port"], "baudrate": self.options["baud"], "parity": self.options["parity"], "rtscts": 1 if self.options["rtscts"] else 0, "xonxoff": 1 if self.options["xonxoff"] else 0, })
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)
def reopen(self): ''' Tries to reestablish a serial link in case of HW issues ''' print(dir(self.serial)) self.serial = SerialPort(baudrate=self.baud, deviceNameOrPortNumber=self.port, protocol=self, reactor=self.reactor)
def errLineReceived(self, line): if 'starting data transfer loop' in line: os.system('chmod 777 /dev/ttyUSB0') self.serialPort = SerialPort(basic.LineReceiver(), '/dev/ttyToUSB', reactor, timeout=3) self.loop = LoopingCall(writeToSerialPort, self.serialPort, self.emulator) self.loop.start(2)
def main(): parser = argparse.ArgumentParser() # Positional parser.add_argument( "serial_port", help="Serial/COM port connected to the Bluegiga device.") # Optional parser.add_argument("-v", "--verbose", action="store_true", help="Verbose log output") subparsers = parser.add_subparsers(dest='subparser_name', help='sub-command help') parser_devinfo = subparsers.add_parser('devinfo', help='Get device information') parser_bonds = subparsers.add_parser('bonds', help='Access bonds') parser_bonds.add_argument("--delete-all", action="store_true", help="Delete all bonds") parser_ps = subparsers.add_parser( 'ps', help='Access the device persistent store') parser_ps.add_argument( "action", help="Persistent store action (dump, clear, delete, defrag, save)") parser_connections = subparsers.add_parser( 'connections', help='Get status of active connections') parser_reset = subparsers.add_parser('reset', help='Reset device') parser_reset.add_argument( "--dfu", action="store_true", help="Boot into Device Firmware Update (DFU) mode") args = parser.parse_args() if args.verbose: log.startLogging(sys.stderr, setStdout=False) protocol = AppProtocol() try: port = SerialPort(protocol, args.serial_port, reactor, baudrate=256000) except serial.SerialException as err: sys.stderr.write("Error opening serial port: {}".format(err)) sys.exit(1) bgtool_run(protocol, args) reactor.run()
def connectToSerialPort(self): devices = glob.glob('/dev/ttyUSB*') if len(devices) > 0: log('Started reading oximeter at %s' % devices[0]) self.oximeterReader.reset(OximeterStatus.CABLE_DISCONNECTED, 'got connection') self.serialPort = SerialPort(self.oximeterReader, devices[0], self.reactor, timeout=3) self.loop.stop()
def startReceiving(self): self.tag = raw_input('Enter a label: ') try : self.ser = SerialPort(self.prot, self.port, reactor, baudrate=self.baud) except : self.ser = None balance_logger.error("Could not connect to serial port %s at %d baud" % (self.port, self.baud)) self.time = time.time() self.getWeightLoop = LoopingCall(self.getWeight) self.getWeightLoop.start(self.printInterval)
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)