class Controlador(threading.Thread): def __init__(self): threading.Thread.__init__(self) self._idle = True try: self.serial = Serial('/dev/rfcomm0', 19200, timeout = 0.1) except Exception as e: raise Exception("Error al inicializar puerto: " + str(e)) self.serial.flushInput() # Para limpiar el buffer de entrada de la compu. self.start() def isIdle(self): return self._idle def run(self): while True: if self.serial.inWaiting() > 0 and self.serial.read().encode('hex') == "55": self._idle = True time.sleep(0.2) def hacerEfecto(self,idEfecto): if idEfecto != None: self._idle = False self.serial.write(chr(idEfecto)) print "[Mensaje del Controlador]: Despache el efecto Id ",idEfecto," a la nube" else: print "No hay definido un mapeo para el evento solicitado"
def clear_buffer(self): ''' Empties the current buffer and calls Serial.flushInput() Serial.flushOutput(). ''' self.buffer = '' Serial.flushInput() Serial.flushOutput()
def init_channel(): channel = Serial(SERIAL_PORT, timeout=3) if not channel.isOpen(): channel.open() channel.flushInput() channel.flushOutput() return channel
class Serial(threading.Thread): PARITIES = [serial.PARITY_NONE, serial.PARITY_EVEN, serial.PARITY_ODD] BYTESIZES = [8, 7, 6, 5] STOPBITSES = [1, 1.5, 2] SIG_NEWDATA = "SIG_NEWDATA" SIG_RECVEXCEPTION = "SIG_RECVEXCEPTION" def __init__(self): threading.Thread.__init__(self) # self.setDaemon(True) self.qtobj = QObject() self.__terminate = False @classmethod def getActivePorts(self): """获取当前活动的串口列表""" return [devInfo[0] for devInfo in list(stlp.comports())] def open(self, settings): try: self.serial = PySerial(settings["port"], settings["baund"], settings["bytesize"], settings["parity"], settings["stopbits"], settings["timeout"]) self.serial.flushInput() self.serial.flushOutput() except Exception, msg: return False, msg.__str__() return True, "success"
def run(command): global protocolSettings global databaseSettings global usefix if command == "list": listPorts() elif command == "read": debug("Reading sequence") process(read(usefix)) elif command == "defaults": listDefaults() elif command == "jobread": debug("Starting endless read") global serialSettings global job job = True serial = None try: serial = Serial(port=serialSettings["port"], baudrate=serialSettings["baudrate"]) debug("flushing") serial.flushInput() serial.flushOutput() while True: debug("Reading sequence (job)") process(read(usefix, serial)) sleep(float(databaseSettings["wait"])) finally: if serial is not None and serial.isOpen(): serial.close() else: log("Unknown command: " + command)
def Send(self,p): ser = Serial(self.port,baudrate=self.rate,timeout = 5) print "Opend serial channel to %s" % self.port #ser = Serial("/dev/tty.usbserial-A9007KPc",baudrate=115200,timeout = 5) if not ser: print "Failed to create the serial channel" return N = len(p) try: print "Attempting to send %d bytes" % N #nSent = ser.write(p) #ser.flushInput() #ser.flushOutput() print "Sending.." nSent = 2 ser.flushInput() for x in range(0,N): ser.write(p[x]) #ser.flushOutput() #if nSent != N: # print "nBbyte not equal to count in. %d != %d" % (nSent, N) except: print "Failed to send data.." ser.close()
class SerialPortChannel(Channel): def __init__(self, path: str, baud=115200, wait: bool = False): #self.ch = Serial(path, baud, timeout=5) repeat = True while repeat: if not wait: repeat = False try: self.ch = Serial(path, baud) repeat = False if wait: time.sleep(0.5) except SerialException as ex: if not wait: raise ex def write(self, data: bytes): self.ch.write(data) def read(self, size=1): return self.ch.read(size) def write_read(self, data: bytes, size=1): self.write(data) return self.read(size) def flush_input(self): self.ch.flushInput()
class Radio: "Kenwood THF7E Radio interface" def __init__(self): self.radio = Serial(port="/dev/tty.usbserial", timeout=3, baudrate=9600) # self.radio = Serial( port='/dev/ttyUSB0',timeout=3,baudrate=9600 ) self.last_cmd = "" def receive(self): buffer = "" while True: buffer = buffer + self.radio.read(self.radio.inWaiting()) if "\r" in buffer: lines = buffer.split("\r") last_received = lines.pop(0) buffer = "\r".join(lines) if self.last_cmd in last_received: break if "N" in last_received: break return last_received def send(self, cmd, args): self.last_cmd = cmd self.radio.write("\r") self.radio.write(cmd + " " + args + "\r") self.radio.flushInput()
class SerialPort(object): def __init__(self, port): self.port = port self._connect_serial(port) def disconnect(self): """Close the serial port an disconnect from the station.""" try: self._serial.close() except: pass def reconnect(self): """Close the serial port and reopen again.""" self.disconnect() self._connect_serial(self.port) def send(self, data): self._serial.write(data) self._serial.flush() def _connect_serial(self, port, timeout=None): """Connect to SI Reader. @param port: serial port """ self._serial = Serial(port, baudrate=38400, timeout=timeout) # flush possibly available input self._serial.flushInput() self._serial.flushOutput()
class Mbed: def __init__(self, portname, baud): # super().__init__(portname, baud) self.mbed = Serial(portname, baud) """ def mbedWrite(self, cmd, farray): a = [] for i in farray: a.append(int(i)) # print(a) buf = [0xfe, 0xef, cmd, len(farray)] + a # [ser.write(i.to_bytes(1, byteorder='little')) for i in buf] self.flushInput() self.flushOutput() [self.write(chr(i)) for i in buf] """ def mbedWrite(self, cmd, farray): a = [] for i in farray: a.append(int(i)) print(a) buf = [0xfe, 0xef, cmd, len(farray)] + a # [ser.write(i.to_bytes(1, byteorder='little')) for i in buf] self.mbed.flushInput() self.mbed.flushOutput() [self.mbed.write(chr(i)) for i in buf]
class tarjetaTOC(): ''' Clase de comunicacion con la tarjeta mediante puerto serial. ''' def __init__(self, controlador): ''' Constructor de la clase ''' self.puerto = "/dev/ttyS0" self.BAUDS = "9600" self.TIMEOUT = 1 self.serial = Serial(port=self.puerto, baudrate=self.BAUDS, bytesize=8, stopbits=1, timeout=self.TIMEOUT, dsrdtr=False, rtscts=True) self.cerrar_puerto() def abrir_puerto(self): try: self.serial.open() #time.sleep(2) except: print "Error de apertura de puerto" def cerrar_puerto(self): self.serial.close() def desconectar(self): self.cerrar_puerto() def escribir_datos(self, datos): # Escribe datos en el puerto self.serial.flushOutput() self.serial.write(datos) print "Escribio" def crear_datos_simulador(self): pass def leer_datos(self): recv = self.serial.readline() if len(recv) >= 5: self.serial.flushInput() return recv else: return (recv) def enviar_comando(self, comando): # Envia un comando y espera a que se reciba respuesta self.abrir_puerto() self.escribir_datos(comando) recv = self.leer_datos() self.cerrar_puerto() return recv
def run(): print("INIT") ser = Serial('COM8', 9600, timeout=3) time.sleep(3) print("Serial is open: " + str(ser.isOpen())) array = DataArrays() loc = "null" while (True): for msg in SateliteMensagem.objects.order_by("-id")[:1]: if not (msg.enviado): print(msg.criacao) print(msg.update) print(msg.datalog) loc2 = "D" + msg.datalog + "\n" ser.flushInput() print(loc2) msg.enviado = True msg.save() print(msg.enviado) ser.write(loc2.encode()) loc = msg.enviado ser.flushOutput() line = ser.readline() print("line" + line.decode("utf-8")) print(loc) if line.decode("utf-8") and loc == line.decode("utf-8"): lineForm = line.decode("utf-8") print(lineForm) array.populate(lineForm)
class Copernicus(object): def __init__(self, port=None, baudrate=9600): self.serial = Serial(port, baudrate) def read(self): return ord(self.serial.read(1)) def write(self, value): return self.serial.write(chr(value)) def flush(self): self.serial.flushInput() def set_autoupdates(self, peripheral): self.write(autoupdate_codes[peripheral]) def query(self, peripheral): self.write(query_codes[peripheral]) def set_dashboard_angle(self, angle): if 0 <= angle <= 31: self.write(angle) else: ValueError("Dashboard angle out of range (0-31)") def reset_dashboard_angle(self): self.set_dashboard_angle(0) def led_on(self): self.write(33) def led_off(self): self.write(32)
class BusPirate(Board): def __init__(self, dev, baudrate): Board.__init__(self, dev, baudrate) self.serial = Serial(self.dev, self.baud, timeout=2) self._init_bus_pirate() def _init_bus_pirate(self): '''Try to put the bus pirate into bitbang mode.''' # hardware reset self.serial.write(b"\xff") sleep(1) # enter bitbang mode self.serial.flushInput() for _ in range(25): serial.write(b"\x00") sleep(0.2) if serial.inWaiting(): bbio1 = serial.read(5) if bbio1 == "BBIO1": break else: raise BoardInitError
def test_nmea_simulator(nmea_sim, kill_sims): del kill_sims s = Serial(nmea_sim.tty, timeout=1.5) # Simulator should respond with P iff we send it a P s.flushInput() s.flushOutput() s.write(b"XP?P") assert s.read(1) == b"P", "Simulator signals NMEA mode" assert s.read(1) == b"P", "Simulator signals NMEA mode twice" # Simulator should be sending NMEA dummy messages m = s.readline() assert m.startswith(b"$GPLL") and m.endswith( b"\r\n"), "Simulator sends NMEA message" m = s.readline() assert m.startswith(b"$GPLL") and m.endswith( b"\r\n"), "Simulator keeps sending NMEA messages" m = s.readline() assert m.startswith(b"$GPLL") and m.endswith( b"\r\n"), "Simulator keeps sending NMEA messages still" # Simulator should still respond with P iff we send it a P s.write(b"P?") assert s.read(1) == b"P", "Simulator still signals NMEA mode"
class serio: def __init__(self, line, baud, tracefile=None): self.__s = Serial(line, baud, timeout=None) if tracefile: self.__trace = open(tracefile, 'w') self.flush_buffers() def trace(self, line): self.__trace.write(line + '\n') self.__trace.flush() def tx(self, cmd): #cmd = cmd + '\r\n' self.trace(">>> %r"%cmd) self.__s.write(cmd) def peekbuffer(self, tmo=0): self.__s.setTimeout(tmo) ret = self.rx() self.__s.setTimeout(None) return ret def rx(self): ret = self.__s.readline() if ret[-1:] == '\n': ret = ret[:-1] if ret[-1:] == '\r': ret = ret[:-1] self.trace("<<< %r"%ret) return ret def flush_buffers(self): self.__s.flushInput() self.__s.flushOutput() self.trace("--- flushed buffers")
class Arduino: def __init__(self, serialport): """Takes the string of the serial port and connects to that port, binding the Arduino object to it. """ print('Instanciado Arduino dispositivo %s' % serialport) try: self.serialport = Serial(serialport, 9600) self.error = False self.id = None except: self.error = True self.id = -666 raise def read_byte(self, block=False): """Lee un byte. Si block=True lee con espera activa hasta que exista algún byte que leer, porque no funciona sin espera activa. """ if block == False and self.serialport.inWaiting() < 1: return None return self.serialport.read(1); def read_until(self, until): buffer = [] while buffer[-1] != until: if self.serialport.inWaiting() < 1: return buffer buffer += self.serialport.read(1); return buffer def write(self, str): return self.serialport.write(str) def write_byte(self, byte): return self.serialport.write(chr(byte)) def get_id(self): if self.error: return self.id if self.id != None: return self.id # Consume all bytes for this query self.serialport.flushInput() print 'Lendo o ID..' while self.id == None: self.write_byte(QUERY_IDENT) self.id = self.serialport.read(1) self.id = ord(self.id) self.serialport.flush() self.serialport.flushInput() return self.id
class GenericHXTTY(object): """ Serial communication for Standard Horizon HX maritime radios """ def __init__(self, tty, timeout=2): """ Serial connection class for HX870 handsets :param tty: str TTY device to use :param timeout: float default timeout for serial """ self.tty = tty logger.debug(f"Connecting to {tty}") self.default_timeout = timeout self.s = Serial(tty, timeout=timeout) self.s.flushInput() self.s.flushOutput() def write(self, data): logger.debug("OUT: %s" % repr(data)) return self.s.write(data) def read(self, *args, **kwargs): result = self.s.read(*args, **kwargs) logger.debug(" IN: %s", repr(result)) if len(result) == 0: raise TimeoutError(f"{self.tty} read() timeout") return result def read_all(self): result = self.s.read_all() if len(result) == 0: raise TimeoutError(f"{self.tty} read_all() timeout") logger.debug(" IN: %s", repr(result)) return result def read_line(self, *args, **kwargs): result = self.s.readline(*args, **kwargs) if len(result) == 0: raise TimeoutError(f"{self.tty} read_line() timeout") logger.debug(" IN: %s", repr(result)) return result def available(self): return self.s.in_waiting def flush_input(self): if self.s.in_waiting > 0: logger.warning( f"{self.tty} flushing {self.s.in_waiting} bytes from input buffer" ) return self.s.flushInput() def flush_output(self): if self.s.out_waiting > 0: logger.warning( f"{self.tty} flushing {self.s.out_waiting} bytes from output buffer" ) return self.s.flushOutput()
def initialize_serial_port(): global serial_port, uart_logger serial_port = Serial("/dev/ttyAMA0", 57600) if serial_port.isOpen() is False: serial_port.open() serial_port.flushInput() serial_port.flushOutput() uart_logger = AB_Log.get_logger('UART')
def ReadMate3(): s = Serial("/dev/outback", 19200) x = s s.flushOutput() s.flushInput() a = x.read(80) # sleep(0.5) return a
def ReadMidnite(): s = Serial("/dev/midnite", 9600) x = s s.flushOutput() s.flushInput() a = x.read(40) # sleep(0.5) return a
def main(): ## open up serial connection ## open web socket ## read/parse serial --> will be receiving "{node},{delay (ms)},{hr},{rr},{temp}" ## send parsed serial data via web socket ## receive alarm states, ages via web socket ## send alarm states, ages via serial ## wait some amount of time -- do it again while True: if int(sys.argv[1]) == 0: exp_str = "" while True: try: # ser = Serial('/dev/ttyACM0', 9600, timeout=1) ser = Serial('/dev/ttyS3', 9600, timeout=1) ser.flushInput() serial_data = ser.readline() serial_string = serial_data.decode("utf-8") exp_str = serial_string.replace("\n", "") exp_str = exp_str.replace("\r", "") exp_array = exp_str.split(",") print(exp_str); # we need to further ensure we have what we want --> specify the length of this string if len(exp_array) != 5: go_on = False elif len(exp_array[0]) <= 2 and len(exp_array[0]) > 0 and (len(exp_array[2]) == 5 or len(exp_array[2]) == 6) and \ (len(exp_array[3]) == 4 or len(exp_array[3]) == 5) and len(exp_array[4]) == 5: print(exp_array) break except: print("Some Exception") elif int(sys.argv[1]) == 1: # serial simulation serial_array = [random.randint(1,4), random.uniform(1000,10000), random.uniform(50,100), random.uniform(12,15), \ random.uniform(36, 39)] exp_str = ",".join(str(round(e,1)) for e in serial_array) elif int(sys.argv[1]) == 2: return 0 else: return 1 # open zmq port to communication with other programs context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://localhost:5556") sent_data = exp_str socket.send_string(sent_data) received_data = socket.recv_string() print(received_data) to_serial = received_data.encode("utf-8") if int(sys.argv[1]) == 0: ser.write(to_serial) time.sleep(1)
def FlushSerialBuffer(env, port): s = Serial(env.subst(port)) s.flushInput() s.setDTR(False) s.setRTS(False) sleep(0.1) s.setDTR(True) s.setRTS(True) s.close()
def reset_serialport(port): s = Serial(port) s.flushInput() s.setDTR(False) s.setRTS(False) sleep(0.1) s.setDTR(True) s.setRTS(True) s.close()
def check_connections(self): for device in self.__devices: connection = self.__devices[device].get_connection() if connection is None: connection = Serial(device, 19200, stopbits=1, bytesize=8) connection.flushInput() self.__devices[device].set_connection(connection) elif not connection.isOpen(): connection.open()
def send(device: serial.Serial, call): if device is None: return None try: device.flushInput() device.flushOutput() device.write(call) except Exception as e: print("Error" + str(e))
def discover(self, pump_id=None): """Finds the serial ports for the specified pump controller id number. uses self.available_ports class property to get all potential serial ports. Then submits the identification command. If the query return corrrect string and the id matches self.pump_id, the tested port will be assigned to self.port of the syringe pump driver class. Parameters ---------- Returns ------- port :: Serial Examples -------- >>> driver.port = driver.discover() """ from serial import Serial from sys import version_info if pump_id is None: pump_id = self.pump_id available_ports = self.available_ports port = None for port_name in self.available_ports: try: debug("Trying self.port %s..." % port_name) port = Serial(port_name, timeout=2) port.close() except: available_ports.pop(available_ports.index(port_name)) debug("available ports {}...".format(available_ports)) for port_name in available_ports: debug("Trying port %s..." % port_name) port = Serial(port_name, timeout=2) port.baudrate = 9600 port.timeout = 2 port.flushInput() port.flushOutput() full_reply = self.query(command=b"/1?80\r", port=port) if len(full_reply) != 0: debug("port %r: full_reply %r" % (port_name, full_reply)) reply = full_reply[3:][:-3] status = reply[0:1] received_pump_id = int(reply[3:4].decode('Latin-1')) debug("self.ports %r: full_reply %r, status %r, pump_id %r" % (port_name, full_reply, status, pump_id)) else: received_pump_id = 0 debug("port %r: full_reply %r" % (port_name, full_reply)) if received_pump_id == pump_id: # get pump id for new_pump info("self.port %r: found pump %r" % (port_name, pump_id)) break else: port.close() port = None debug("closing the serial connection") return port
def grbl_init(): try: arduinoName = arduinosniffer.findArduinoName() s = Serial(arduinoName, 9600) s.write("\r\r") sleep(2) s.flushInput() return s except ConnectionError as e: print "An error has occured.\n Check the arduino connection and the arduino.\n"
class Core: def __init__(self, port, baud=9600): self.serial = Serial(port, baudrate=baud, dsrdtr=True) self.serial.flushInput() def _send(self, message): self.serial.write(('%s\n' % message).encode('latin-1')) def stepper(self, channel, steps, speed=10, direction=Direction.forward): self._send('STEP %d %d %d %s' % (channel, steps, speed, direction.value)) time.sleep(.005) serial_data = self.serial.readline().strip() return serial_data == b'OK.' def external_stepper(self, channel, steps, speed=10, direction=Direction.forward): self._send('EXSTEP %d %d %d %s' % (channel, steps, speed, direction.value)) time.sleep(.005) serial_data = self.serial.readline().strip() return serial_data == b'OK.' def servo(self, channel, angle): self._send('SERVO %d %d' % (channel, angle)) time.sleep(.005) serial_data = self.serial.readline().strip() return serial_data == b'OK.' def digital(self, channel, state): self._send('DIGITAL %d %s' % (channel, state.value)) time.sleep(.005) serial_data = self.serial.readline().strip() return serial_data == b'OK.' def get_temp(self): self._send('TEMP?') time.sleep(.005) serial_data = self.serial.readline().strip() return float(serial_data) def get_distance(self): self._send('DIST?') time.sleep(.005) serial_data = self.serial.readline().strip() return float(serial_data)
class Mbed: """ Base class for a host driven test """ def __init__(self): parser = OptionParser() parser.add_option("-m", "--micro", dest="micro", help="The target microcontroller ", metavar="MICRO") parser.add_option("-p", "--port", dest="port", help="The serial port of the target mbed (ie: COM3)", metavar="PORT") parser.add_option("-d", "--disk", dest="disk", help="The target disk path", metavar="DISK_PATH") parser.add_option("-t", "--timeout", dest="timeout", help="Timeout", metavar="TIMEOUT") parser.add_option("-e", "--extra", dest="extra", help="Extra serial port (used by some tests)", metavar="EXTRA") (self.options, _) = parser.parse_args() if self.options.port is None: raise Exception("The serial port of the target mbed have to be provided as command line arguments") self.port = self.options.port self.disk = self.options.disk self.extra_port = self.options.extra self.extra_serial = None self.serial = None self.timeout = 10 if self.options.timeout is None else self.options.timeout print 'Mbed: "%s" "%s"' % (self.port, self.disk) def init_serial(self, baud=9600, extra_baud=9600): self.serial = Serial(self.port, timeout = 1) self.serial.setBaudrate(baud) if self.extra_port: self.extra_serial = Serial(self.extra_port, timeout = 1) self.extra_serial.setBaudrate(extra_baud) self.flush() def reset(self): self.serial.sendBreak() # Give time to wait for the image loading sleep(2) def flush(self): self.serial.flushInput() self.serial.flushOutput() if self.extra_serial: self.extra_serial.flushInput() self.extra_serial.flushOutput()
class PySerialTransport(): """ Implementation of a transport using PySerial """ def __init__(self, port, debug=False): self.serial = Serial(port, 38400, timeout=0.1) self.debug = debug def receive_blocking(self): """ Wait until a packet is received and return with an RFXtrxEvent """ while True: data = self.serial.read() if (len(data) > 0): if data == '\x00': continue pkt = bytearray(data) data = self.serial.read(pkt[0]) pkt.extend(bytearray(data)) if self.debug: print("Recv: " + " ".join("0x{0:02x}".format(x) for x in pkt)) return self.parse(pkt) @staticmethod def parse(data): """ Parse the given data and return an RFXtrxEvent """ pkt = lowlevel.parse(data) if pkt is not None: if isinstance(pkt, lowlevel.SensorPacket): return SensorEvent(pkt) elif isinstance(pkt, lowlevel.Status): return StatusEvent(pkt) else: return ControlEvent(pkt) def send(self, data): """ Send the given packet """ if isinstance(data, bytearray): pkt = data elif isinstance(data, str) or isinstance(data, bytes): pkt = bytearray(data) else: raise ValueError("Invalid type") if self.debug: print ("Send: " + " ".join("0x{0:02x}".format(x) for x in pkt)) self.serial.write(pkt) def reset(self): """ Reset the RFXtrx """ self.send(b'\x0D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') sleep(0.3) # Should work with 0.05, but not for me self.serial.flushInput() self.send(b'\x0D\x00\x00\x01\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00') return self.receive_blocking()
class ArduinoWatcher(object): ''' A simple iterator wrapper around reading from an arduino. For this we simply use a serial line reader. ''' def __init__(self, *args, **kwargs): ''' Initializes a new instance of the TinyosWatcher :param port: The serial port to read from :param baudrate: The baudrate to read with ''' self.client = Serial(**kwargs) def __iter__(self): ''' Returns an instance of the current iterator :returns: The iterator instance ''' self.client.flushInput() # clear backed up data return self def __parse(self, packet): ''' A helper method to parse the packet :param packet: The packet to decode :returns: The decoded packet ''' result = None packet = packet.replace('\r\n', '') message = dict(p.split(':') for p in packet.split(',')) message_type = message.get('type', None) try: #_logger.debug("device message: " + packet) if message_type == ArduinoTraumaMessage.Type: result = ArduinoTraumaMessage.decode(message) elif message_type == ArduinoHistoryMessage.Type: result = ArduinoHistoryMessage.decode(message) except Exception: pass #blah for now return result def close(self): ''' Close the underlying watcher handle ''' self.client.close() def next(self): ''' Returns the next value from the iterator :returns: The next value of the iterator ''' packet = self.client.readline() # technically doesn't read a line... return self.__parse(packet)
def setup(): global serialPort print "start setup" serialPort = Serial("/dev/ttyUSB0", 9600, timeout=2) if (serialPort.isOpen() == False): try: serialPort.open() except: print "Couldnt' open serial port" serialPort.flushInput() serialPort.flushOutput() print "complete setup"
class Hoverboard: def __init__(self, com): self.com = Serial(port=com, baudrate=115000, timeout=0) self.com.flushInput() self.com.flushOutput() self.sendSpeed(0, 0, False) self.msgs=[] self.rxbuffer=[] def sendMsg(self, msg): buffer=[0xAA,len(msg)]+msg buffer+=[xor(buffer)] self.com.write(''.join([chr(x) for x in buffer])) def sendSpeed(self, m1 , m2, enabled=True): if m1<0: m1+=0xffff if m2<0: m2+=0xffff self.sendMsg([(m1>>8)&0xff, m1&0xff, (m2>>8)&0xff, m2&0xff, 1 if enabled else 0 ]) def processchar(self, c): self.rxbuffer.append(c) while self.rxbuffer and self.rxbuffer[0]!=0xAA: self.rxbuffer.pop(0) if len(self.rxbuffer)>=2 and len(self.rxbuffer)>=3+self.rxbuffer[1]: msg=self.rxbuffer[:2+self.rxbuffer[1]] self.rxbuffer=self.rxbuffer[2+self.rxbuffer[1]:] mxor=self.rxbuffer.pop(0) cxor=xor(msg) return msg[2:], cxor == mxor return [], False def readMsg(self): for c in self.com.read(): msg, xok=self.processchar(ord(c)) if msg: if xok: self.msgs.append(msg) else: print("incomplete msg", msg) if self.msgs: return self.msgs.pop(0) else: return None def drive(self, s1, s2, t): for i in range(int(t/0.1)): self.sendSpeed(s1, s2, enabled = True) print(h.readMsg()) sleep(0.1)
def _serial_init(self): if not self._dummy_mode: print("No sync or port closed: initializing UART") self._ser = None init = Serial(port=self._port, baudrate=UnoDriver._serial_baud) init.setDTR(False) sleep(0.25) init.flushInput() init.setDTR(True) sleep(0.5) # wait for arduino to become ready to receive config self._ser = init self._send_apply_config(self._last_config)
class SerialBase: RESPONSE_TIME_LIMIT = 10 # seconds TIMEOUT = 5 # minutes def __init__(self, port, baudrate=115200, bytesize=EIGHTBITS): self.port = port self.baudrate = baudrate self.bytesize = bytesize self.serial: Serial = None self.time_since_last_call = datetime.now() self.most_recent_data = None def open(self): if self.serial is None: self.serial = Serial(port=self.port, baudrate=self.baudrate, write_timeout=0, bytesize=self.bytesize) elif not self.serial.is_open: self.serial.open() def close(self): if self.serial is not None and self.serial.is_open: self.serial.close() def send(self, identifier: SerialIdentifier, data_bytearray: bytearray = bytearray(0)): numToPad = EXPECTED_SEND_SIZE - 1 - len(data_bytearray) bytes_to_send = to_bytes( bytes([identifier.value]) + data_bytearray + bytearray([0] * numToPad)) self.serial.write(bytes_to_send) def check_timeout(self): if self.time_since_last_call - datetime.now() > timedelta( minutes=SerialBase.TIMEOUT): return False else: return True def await_data(self): for i in range(SerialBase.RESPONSE_TIME_LIMIT): if self.serial.inWaiting() == EXPECTED_RETURN_SIZE: data = self.serial.read(EXPECTED_RETURN_SIZE) print("data read: " + data.hex()) data = SerialTranslator.from_data(data) self.most_recent_data = data self.serial.flushInput() break time.sleep(1)
def open_serial(self, ard_no, PortNo, baudrate): if PortNo =='': sys.exit("Arduino Not Found !!") else: tempPort = Serial(PortNo, baudrate) # assign the port to a temp Port with tempPort: # This is done to reset the port if something is holding it. tempPort.setDTR(False) sleep(1) tempPort.flushInput() tempPort.setDTR(True) # with keyword closes the open port as well self.__port = Serial(PortNo, baudrate) # Open the port with the port ID and the Baud rate sleep(2) # self.__checkfirmware() # Cuurently commented out return self.__port
def from_port(cls, port='/dev/ttyUSB0') -> 'IrSerial': """ create instance from device port :returns: created instance """ conn = Serial(baudrate=9600, dsrdtr=None, xonxoff=None) conn.port = port conn.open() conn.flushInput() sleep(2) return IrSerial(conn)
class LX16A: def __init__(self,Port="COM5",Baudrate=115200, Timeout= 0.001): self.serial = Serial(Port,baudrate=Baudrate,timeout=Timeout) self.serial.setDTR(1);self.TX_DELAY_TIME = 0.00002 self.Header = struct.pack("<BB",0x55,0x55) def sendPacket(self,packet): packet1=bytearray(packet);sum=0 for a in packet1: sum=sum+a fullPacket = bytearray(self.Header + packet + struct.pack("<B",(~sum) & 0xff)) self.serial.write(fullPacket); sleep(self.TX_DELAY_TIME) def sendReceivePacket(self,packet,receiveSize): t_id = pa cket[0];t_command = packet[2] self.serial.flushInput();self.serial.timeout=0.1;self.sendPacket(packet) r_packet = self.serial.read(receiveSize+3); return r_packet def motorOrServo(self,id,motorMode,MotorSpeed): packet = struct.pack("<BBBBBh",id,7,29,motorMode,0,MotorSpeed) self.sendPacket(packet)# motorMode 1=motor MotorSpeed=rate, 2=servo def moveServo(self,id,position,rate=1000): packet = struct.pack("<BBBHH",id,7,1,position,rate) self.sendPacket(packet) # Move servo 0-1000, rate(ms) 0-30000(slow) def readPosition( self,id): packet = struct.pack("<BBB",id,3,28) rpacket = self.sendReceivePacket(packet,5) s = struct.unpack("<BBBBBhB",rpacket);return s[5] def LoadUnload(self,id,mode): packet = struct.pack("<BBBB",id,4,31,mode) self.sendPacket(packet)#Activate motor 0=OFF 1 =Active def setID(self,id,newid):# change the ID of servo packet = struct.pack("<BBBB",id,4,13,newid) self.sendPacket(packet) def moveservos(self,speed,n, s1,s2,s3,s4,s5,s6): self.moveServo(1,n[0]+s1,speed);self.moveServo(2,n[1]+s2,speed) self.moveServo(3,n[2]+s3,speed);self.moveServo(4,n[3]+s4,speed) self.moveServo(5,n[4]+s5,speed);self.moveServo(6,n[5]+s6,speed) def readservosABS(self): m=[0]*6 for a in range(0,6): m[a]= self.readPosition(a+1) return m def readservos(self, c): m=[0]*6 for a in range(0,6): m[a]= self.readPosition(a+1)-c[a] return m def servosoff(self): for a in range(1,7): self.LoadUnload(a,0) def servoson(self): for a in range(1,7): self.LoadUnload(a,1) def close(self): self.serial.close()
class MySerial(object): def __init__(self): # threading.Thread.__init__(self) self.__terminate = False def open(self, settings): try: self.serial = Serial(settings["port"], settings["baudrate"], settings["bytesize"], settings["parity"], settings["stopbits"], settings["timeout"]) self.serial.flushInput() self.serial.flushOutput() except Exception, msg: return False, msg.message.decode("gbk") return True, "success"
class SerialCommunicate(): def __init__(self): self.__terminate = False self.serial = Serial() def open(self, settings): try: self.serial = Serial(settings["port"], settings["baund"], settings["bytesize"], settings["parity"], settings["stopbits"], settings["timeout"]) self.serial.flushInput() self.serial.flushOutput() except Exception, msg: return False, msg.message.decode("gbk") return True, "success"
def testAirContent(): print("Gas sensors warming up for 20 seconds...") arduinoSerial = Serial(USB_PORT, BAUD_RATE) arduinoSerial.flushInput() serialSent = False i = 0 while not serialSent: if arduinoSerial.inWaiting() > 0: output = arduinoSerial.read(1) print(ord(output)) i = i + 1 if (i == 2): serialSent = True return "Success"
class UArm: def __init__(self, config): for port in comports(): if port.vid == 0x2341 and port.pid == 0x0042: self.serial = Serial(port.device, 115200, timeout=0) break else: raise IOError("UArm not found") time.sleep(2) self.offset = np.array(config['offset']) self.x_bound = np.array(config['x_bound']) self.y_bound = np.array(config['y_bound']) self.stowed = config['stowed'] self.z_floor = config['z_floor'] self.read_data = bytes() self.last_pos = None self.active = False def update(self, arm_pos): if arm_pos is not None: pos = list((arm_pos - self.offset) * -1000) + [self.z_floor] else: pos = self.stowed if pos != self.last_pos: x_ok = (pos[0] > self.x_bound[0] and pos[0] < self.x_bound[1]) y_ok = (pos[1] > self.y_bound[0] and pos[1] < self.y_bound[1]) if pos == self.stowed or (x_ok and y_ok): #print(f"Arm position {pos}") self.active = True gcode = f"G01 X{pos[0]} Y{pos[1]} Z{pos[2]} F20.00\n" print(gcode) self.serial.flushInput() self.serial.write(bytes(gcode, 'ascii')) else: print(f"Arm position {pos} out of bounds") self.last_pos = pos elif self.active: self.read_data += self.serial.read() if b'ok\n' in self.read_data: self.read_data = bytes() self.active = False return self.active
def main(): if int(sys.argv[1]) == 0: ser = Serial('/dev/ttyACM0', 9600, timeout=1) ser.flushInput() serial_data = ser.readline() serial_string = serial_data.decode("utf-8") print(serial_data) elif int(sys.argv[1]) == 1: # serial simulation serial_array = [random.randint(1,4), random.uniform(1000,10000), random.uniform(50,100), random.uniform(12,15), \ random.uniform(36, 39)] serial = ",".join(str(round(e, 1)) for e in serial_array) elif int(sys.argv[1]) == 2: return 0 else: return 1
class MySerial(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.qtobj = QObject() self.__terminate = False def open(self, settings): try: self.serial = Serial(settings["port"], settings["baund"], settings["bytesize"], settings["parity"], settings["stopbits"], settings["timeout"]) self.serial.flushInput() self.serial.flushOutput() except Exception, msg: return False, msg.message.decode("gbk") return True, "success"
def _set_associations(self, transaction): """ Finds all the serial ports, and sends a probe string. The keyword that is returned is that arduino's keyword """ self.ok_to_associate = True keywords = transaction.command_args #dictionary for the various serial connections with their associated keywords self.connections = {} #get all the ports ports = [port[0] for port in list_ports.comports()] #trim the bluetooth ports for p in ports[:]: if "bluetooth" in p.lower(): ports.remove(p) #make a connection to each port, and if successful, send the config signal for p in ports: try: connection = Serial(p, 19200) sleep(4) #TODO find for reliable way of getting this? connection.flushInput() connection.write("probe") sleep(1) keyword = connection.read(connection.inWaiting()).rstrip() if (keyword == "failed"): transaction.log(info="Probe signal failed to %s" % p) except SerialException: transaction.log(info="Serial connection failure to %s" % p) if keyword in keywords: self.connections[keyword] = connection elif keyword == "": pass else: transaction.log( info="Unexpected keyword \"%s\" received from arduino board" % keyword) transaction.process(success=True)
class DataTransfer(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.qtobj = QObject() self.__terminate = True def open(self, settings): try: self.serial = Serial(settings["port"], settings["baud"], settings["bytesize"], settings["parity"], settings["stopbits"], settings["timeout"]) self.serial.flushInput() self.serial.flushOutput() except Exception, msg: return False, msg.message.decode("gbk") if self.serial._isOpen: return True
def _set_associations(self, transaction): """ Finds all the serial ports, and sends a probe string. The keyword that is returned is that arduino's keyword """ self.ok_to_associate = True keywords = transaction.command_args #dictionary for the various serial connections with their associated keywords self.connections = {} #get all the ports ports = [port[0] for port in list_ports.comports()] #trim the bluetooth ports for p in ports[:]: if "bluetooth" in p.lower(): ports.remove(p) #make a connection to each port, and if successful, send the config signal for p in ports: try: connection = Serial(p, 19200) sleep(4) #TODO find for reliable way of getting this? connection.flushInput() connection.write("probe") sleep(1) keyword = connection.read(connection.inWaiting()).rstrip() if(keyword == "failed"): transaction.log(info = "Probe signal failed to %s" %p) except SerialException: transaction.log(info = "Serial connection failure to %s" %p) if keyword in keywords: self.connections[keyword] = connection elif keyword == "": pass else: transaction.log(info = "Unexpected keyword \"%s\" received from arduino board" % keyword) transaction.process(success = True)
class Ivizion(): def __init__(self, port='/dev/ttyS1', write_timeout=0, timeout=0.02): self.ser = Serial() self.ser.port = port self.ser.baudrate = 9600 self.ser.bytesize = EIGHTBITS self.ser.parity = PARITY_EVEN self.ser.stopbits = STOPBITS_ONE self.ser.writeTimeout = write_timeout self.ser.timeout = timeout def connect(self): try: self.ser.open() except Exception as e: print(("error open serial port: " + str(e))) def is_connected(self): return self.ser.isOpen() def disconnect(self): if self.is_connected(): self.ser.close() def in_waiting(self): return self.ser.inWaiting() def flush_io(self): self.ser.flushInput() self.ser.flushOutput() def send(self, bytelist): self.ser.write(bytelist) sleep(.2) def recipe(self, byte_amount=1): out = '' while self.in_waiting() > 0: out += self.ser.read(byte_amount) if out: return out.encode('hex') else: return 'Null'
def main(tty): global _temp basedir = os.path.dirname(sys.argv[0]) lookup = np.flipud(np.loadtxt(os.path.join(basedir, "therm_lookup.csv"), delimiter=",")) _temp = sp.interpolate.interp1d(lookup[:, 1] * 1000, lookup[:, 0], kind="cubic") s = Serial(tty, baudrate=115200, rtscts=True, timeout=0) s.flushInput() s.write("\rstop\rinfo 0\r") s.write("\r".join(["", "asc", "slist 0 x0", "slist 1 x1", "slist 2 x8", ""])) s.write("start\r") sleep(1) s.flushInput() try: while True: sleep(1) read(s) finally: s.write("stop\r") s.close()
def main(): global serial, MIN_Y, MAX_Y, MIN_X, MAX_X if not len(sys.argv) == 3: print 'Wrong args' sys.exit(0) RES_X = int(sys.argv[1]) if RES_X < 0: data = Rasterizer() points = data.get_lines(sys.argv[2], MIN_X, MAX_X, MIN_Y, MAX_Y) else: data = Vectorizer() points = data.get_polygons(sys.argv[2], RES_X, MIN_X, MAX_X, MIN_Y, MAX_Y) serial = Serial(SERIAL_PORT, BAUD) serial.flushInput() serial.flushOutput() print 'Waiting for MCU' # Wait until the mcu sends a byte, signaling it's ready serial.read(1) print 'Starting transmission' count = 1 for cur_p in points: next_x = cur_p[0] next_y = cur_p[1] next_z = cur_p[2] data = struct.pack('<ffb', next_x, next_y, next_z); send_wait_ack(data) print 'Sent point %d of %d\n' %(count, len(points)) count += 1 # Send end of transmission send_wait_ack(END_DATA) raw_input("press enter to continue")
def attribuer(): print("Détection des lecteurs présents...") #liste les chemins trouvés dans /dev sources = os.popen('ls -1 /dev/ttyUSB* 2> /dev/null').readlines() sources.extend(os.popen('ls -1 /dev/ttyACM* 2> /dev/null').readlines()) for k in range(len(sources)): sources[k] = sources[k].replace("\n","") series = {} for source in sources: serie = Serial(source, Serie.baudrate, timeout=0.1) #vide le buffer série coté pc serie.flushInput() #clean buffer et récupération de l'identifiant serie.write(bytes("@0:ping\r","utf-8")) #il faut parfois vider quelques lignes du buffer tentatives = 0 rep = "" while (len(rep)<2 or not rep[0] == "@") and tentatives < Serie.nb_tentatives: rep = Serie._clean_string(str(serie.readline(),"utf-8")) tentatives += 1 time.sleep(0.1) if tentatives < Serie.nb_tentatives: #enregistrement du périphérique series[int(rep[1])] = source #évacuation du prompt serie.readline() #cloture serie.close() if not series: raise Exception("Aucune Redbee trouvée sur la série !") return series
class Sensor: def __init__(self): self.serialPort = Serial("/dev/ttyAMA0", 4800, timeout=3) def check_temp(self, reps): mean = float() hits = 0 for x in range(reps): try: mean += self.get_value() hits += 1 time.sleep(0.001) except TypeError: continue return int(round(mean / hits)) def get_value(self): if not self.serialPort.isOpen(): self.serialPort.open() self.serialPort.flushInput() self.serialPort.flushOutput() self.serialPort.write("TEMP\r") string = "" while 1: new = self.serialPort.readline(self.serialPort.inWaiting()) if "\n" in new: break else: string += new try: string = string.replace("VALUE", "") value = float(string) value * 10 - 1024 value *= 322 value /= 1000 value -= 50 except ValueError: print string return "False" return value
class PySerialTransport(RFXtrxTransport): """ Implementation of a transport using PySerial """ def __init__(self, port, debug=False): self.serial = Serial(port, 38400, timeout=0.1) self.debug = debug def receive_blocking(self): """ Wait until a packet is received and return with an RFXtrxEvent """ while True: data = self.serial.read() if len(data) > 0: pkt = bytearray(data) data = self.serial.read(pkt[0]) pkt.extend(bytearray(data)) if self.debug: logger.debug("Recv: " + " ".join("0x{0:02x}".format(x) for x in pkt)) return self.parse(pkt) def send(self, data): """ Send the given packet """ if isinstance(data, bytearray): pkt = data elif isinstance(data, str) or isinstance(data, bytes): pkt = bytearray(data) else: raise ValueError("Invalid type") if self.debug: logger.debug("Send: " + " ".join("0x{0:02x}".format(x) for x in pkt)) self.serial.write(pkt) def reset(self): """ Reset the RFXtrx """ self.send("\x0D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") sleep(0.3) # Should work with 0.05, but not for me self.serial.flushInput() self.send("\x0D\x00\x00\x01\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00") # self.send('\x0D\x00\x00\x03\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00') return self.receive_blocking()