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]
def init_channel(): channel = Serial(SERIAL_PORT, timeout=3) if not channel.isOpen(): channel.open() channel.flushInput() channel.flushOutput() return channel
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 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")
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)
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 init_channel(): channel = Serial(SERIAL_PORT, timeout=3) if not channel.isOpen(): channel.open() channel.flushInput() channel.flushOutput() return channel
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 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 clear_buffer(self): ''' Empties the current buffer and calls Serial.flushInput() Serial.flushOutput(). ''' self.buffer = '' Serial.flushInput() Serial.flushOutput()
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 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 ReadMidnite(): s = Serial("/dev/midnite", 9600) x = s s.flushOutput() s.flushInput() a = x.read(40) # sleep(0.5) return a
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
class AcmDevice: """Wrapper for accessing usb serial devices.""" def __init__(self, port, baud): self.__port = port self.__baud = baud self.__connection = Serial(port, baud, timeout=1) self.motd = "\n".join([line.strip() for line in self.__connection.readlines()]) self.__connection.timeout = 0 if not (self.__connection.readable() and self.__connection.writable()): raise IOError("Insufficient read/write permissions for port %s." % port) def disconnect(self, disconnected=False): """Close the serial connection.""" if not disconnected: self.__connection.flushOutput() self.__connection.close() def flush(self): """Empties the output buffer.""" self.__connection.flushOutput() def poll(self, wait_for_ok=True): """Poll the serial port for new data.""" buf = "" response = [] timeout = 1 while True: poll = self.__connection.readlines() if poll: for line in poll: buf += line if line.endswith("\n"): response.append(buf.strip()) buf = "" if response and response[-1].startswith("ok"): break elif not wait_for_ok: if timeout > 0: timeout -= 1 else: break if buf: response.append(buf.strip()) return tuple(response) def send(self, line): """Send a line of text to the serial port. Will automatically be terminated with a line end.""" self.__connection.write(line.strip() + "\n\r") def make_uuid(self, firmware_name): """Deterministically generatse a uuid from this connection. Used by firmware drivers if the firmware doesn't specify one through other means.""" namespace = uuid.uuid5(uuid.NAMESPACE_DNS, socket.getfqdn()) return uuid.uuid5(namespace, firmware_name+"@"+self.__port)
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 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))
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 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 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 passivebb(): '''Class to get the mean temperature from a Serial connection to Arduino Nano.''' def logtemps(self): logfile = os.path.join('Z:\\out\\tlogs', dt.datetime.now().strftime('%Y%m%d') + '_bb_targets.dat') tempheader = 'Arduino Nano readout of 2 x 4 DS18B20 temperature sensors of room-\n' tempheader += 'temperature blackbody target (T_rt) and hot blackbody target (T_ht).\n' tempheader += 'Plus one voltage readout of thermistor on hot blackbody target (V_ht)\n\n' tempheader += 'date time T_ht_left T_ht_right T_ht_bottom T_ht_top V_ht T_rt_topright T_rt_topleft T_rt_bottomleft T_rt_bottomright\n' self.gettemps() if not os.path.exists(logfile): with open(logfile, 'a') as f: f.write(tempheader) f.write(self._datetime.strftime('%Y%m%d %H:%M:%S ') + self.temperatures+'\n') else: with open(logfile, 'a') as f: f.write(self._datetime.strftime('%Y%m%d %H:%M:%S ')+self.temperatures+'\n') def gettemps(self): self.serial.flush() a = self.serial.read_all().splitlines() n = 0 try: n+=1 if len(a) > 0: a = a[-1] #print(a) self.temperatures = a.decode('utf-8') self._datetime = dt.datetime.now() n = 0 except: if n<10: sleep(0.5) self.gettemps() else: raise RuntimeError('Did not get response from Passice BB Arduino after '+str(n)+' tries...') def get_rt_temp(self): self.gettemps() return self._datetime.strftime('%Y%m%d %H:%M:%S ') + self.temperatures[29:] def get_ht_temp(self): self.gettemps() return self._datetime.strftime('%Y%m%d %H:%M:%S ') + self.temperatures[:28] def __init__(self, comport): self.comport = comport self.serial = Serial(self.comport) #self.serial.flushInput() self.serial.flushOutput() self.gettemps()
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"
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 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 send_command(ser: serial.Serial, command: str) -> Optional[str]: try: logging.debug("--- Opening Serial port... ---") ser.open() except Exception as e: logging.error("!!! ERR: Could not open serial port !!!") logging.error(str(e)) return None try: ser.flushInput() # flush input buffer, discarding all its contents # flush output buffer, aborting current output and discard all that is in buffer ser.flushOutput() encoded_command = command.encode('utf-8') logging.debug("Command: " + str(encoded_command)) xmodem_crc_func = crcmod.predefined.mkCrcFun('xmodem') # Print the command in hex command_hex = hex(xmodem_crc_func(encoded_command)) logging.debug("Command Hex: " + command_hex) # Print the command in hex without the 0x prefix command_hex_np = command_hex.replace("0x", "", 1) logging.debug("Command Hex NP: " + command_hex_np) command_crc = encoded_command + \ unhexlify(command_hex_np) + '\x0d'.encode('utf-8') # Print the CRC encoded command logging.debug("CRC Command: " + str(command_crc)) # Send the command through the serial port logging.debug("Sending command...") ser.write(command_crc) # Read the response logging.debug("Reading response...") response = str(ser.readline()) # Print the response logging.debug("Response: " + response) # Convert the response to hex response_hex = ':'.join(hex(ord(x))[2:] for x in response) # Print the response in hex logging.debug("Response hex: " + response_hex) ser.close() return response except Exception as e: logging.error("!!! ERR: Could not read inverter !!!") logging.error(str(e)) return None
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 rsend(device: serial.Serial, call): if device is None: return None try: device.flushInput() device.flushOutput() device.write(call) sleep(0.5) while device.inWaiting(): response = device.readline() print("Got data: " + str(response)) except Exception as e: print ("Communication interrupted " + str(e))
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") (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.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): self.serial = Serial(self.port, timeout = 1) self.serial.setBaudrate(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()
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 use_com_port(self, serial_number=None): """ 1) connect to the serial port in self.available_ports(N) 2) stops scanning if one is in progress 3) tries to set buffer size property objects that return a list of com ports that have DI245 in the description. Parameters ---------- serial_number :: str , optional serial number of the device as a string. If left blank the first avaialable DI245 will be selected. Returns ------- port :: ''serial.serialposix.Serial'' pyserial port object Examples -------- >>> port = driver.use_com_port(serial_number = '56671FE4A') >>> port Serial<id=0x3e18c30, open=True>(port='COM23', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=0.1, xonxoff=False, rtscts=True, dsrdtr=False) """ port_name = None if len(self.available_ports) != 0: if serial_number is not None: import serial.tools.list_ports devices = serial.tools.list_ports.comports() for device in devices: if device.serial_number == serial_number: port_name = device.device else: port_name = self.available_ports[0] if port_name is not None: port = Serial(port_name, baudrate=115200, rtscts=True, timeout=0.1) #self.stop_scan() port.flushInput() port.flushOutput() port.set_buffer_size(rx_size=409200) else: port = None return port
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 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")
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 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 Uart(object): def __init__(self, Port, Baudrate, TimeOut): self._serialPort = Serial(Port, Baudrate, timeout=TimeOut) if self._serialPort.isOpen() == False: self._serialPort.open() self._serialPort.flushInput() self._serialPort.flushOutput() def SendData(self, data): """ Send data to uart Data must be of type list of bytes """ outBuff = "".join(chr(x) for x in data) if self._serialPort.isOpen() == True: self._serialPort.write(outBuff) def GetData(self): """ Get data from buffer This will return a string """ return self._serialPort.read(32)
def connect(): #Initiate a connection print("initializing..") arduino = Serial('/dev/ttyACM0', 115200) #Read confirmation from Arduino print("Done initializing...") arduino.flushInput() arduino.flushOutput() arduino.flush() count = 0 try: while True: if count == 0: print('about to write..') arduino.write("H".encode('utf-8')) print('wrote..') count = count + 1 if arduino.inWaiting() > 0: #read the message from the Arduino print('about to read.') time.sleep(0.2) raw_message = str(arduino.read(1)) print('reading..') #remove EOL characters from string message = raw_message.rstrip() print(message) count = count + 1 if count >= 100: count = 0 print ("count " + str(count)) except: arduino.flushInput() arduino.flushOutput() arduino.flush() arduino.close() print('closed')
class TDS2024(TektronixScope): _idStr = 'TEKTRONIX,TDS 2024,0,CF:91.1CT FV:v4.12 TDS2CM:CMV:v1.04' def __init__(self, port='/dev/ttyS0', **kwD): self._port = port super(TDS2024, self).__init__(kwD) def connect(self): self.serial = Serial(self._port, 9600, timeout=None) self.read = self.serial.read self.readline = self.serial.readline self.write = self.serial.write def clear(self): cnt = 10 self.serial.timeout = 1 while 1: self.serial.sendBreak( ) # doesnt seem to handle if other stuff in the queue sleep(sleeptime) resp = self.readline() if resp == 'DCL\0\n': # should see: [68, 67, 76, 0, 10] # we may have another DCL in the queue because we've repeated if cnt == 9: resp = self.readline( ) # hangs here sometimes. put a timeout on it??? self.serial.flushInput() self.serial.flushOutput() if self._debug: print map(ord, resp) print break if self._debug: print 'X', print map(ord, resp) cnt = cnt - 1 if cnt == 0: raise ValueError('Serial port did not return DCL! (%s)' % resp) self.serial.timeout = None
def test_cp_simulator(cp_sim, kill_sims): del kill_sims s = Serial(cp_sim.tty, timeout=1.5) # Simulator should respond with @ iff we send it a ? s.flushInput() s.flushOutput() s.write(b"P?X?") assert s.read(1) == b"@", "Simulator signals CP mode" assert s.read(1) == b"@", "Simulator signals CP mode twice" # FIXME: Dummy simulator responds with #CMDER to every message s.write(b"#CMDSY\r\n") m = s.readline() assert m == b"#CMDOK\r\n", "CP simulator responds like a dummy FIXME" s.write(b"#CMDSY\r\n") m = s.readline() assert m == b"#CMDOK\r\n", "CP simulator responds like a dummy again FIXME" # Simulator should still respond with @ iff we send it a ? s.write(b"P?") assert s.read(1) == b"@", "Simulator still signals CP mode"
def fetch_data(): arduino = Serial("COM6", 9600) arduino.flushInput() arduino.flushOutput() data = arduino.readline() arduino.flushInput() arduino.flushOutput() data = arduino.readline() arduino.flushInput() arduino.flushOutput() data = arduino.readline() return data
class SerialDaemon(): """A wrapper class for Serial and DaemonContext with inet socket support. Creates a DaemonContext object and a Serial object using the passed arguments. Some arguments do not take effect after the daemon is started and hence can be altered anytime after initialization until it is started by calling <daemon>.start() Communication with the daemon is done on a port number specified during initialization (or anytime before start), defaulting to 57001. Data is decoded using the user specified encoding (default is UTF-8) and must be either exactly 'device', in which case the daemon will reply with the full path to the device file it is communicating with (serial_context.port), or it must be in the following format: <0-F><0-F0-F...0-F><data to be sent to device> where the first byte of data always signifies how many (base 16) bytes following it give the the number (base 16) of bytes that are to be read from device after the data is sent to it. 0 bytes are read if data[0] is 0 or is not a valid hex number. <data[0] number of bytes> + 1 are always discarded from the beginning of data. For example: 22F8921 sends 8921 to device and reads 2F (47) bytes of data X78192 sends 78192 to device and dos not read a reply 3A2G9130 sends 9130 to device BUT does not read a reply since A2G is not a valid hex number. Note that these 3 bytes are still discarded This class does not inherit from either DaemonContext or Serial. The only export method is start() used to run the daemon. Accepted options for the constructor: name :Default: ``None`` The name of the daemon, used for syslog and the default name of the pidfile and configuration files. Changes to this value after the daemon has started will only be reflected in syslog. config_file :Default: ``'/etc/<name>.conf'`` Configuration file used to set some of the hereby listed parameters. All but name, daemon_context and serial_context are supported. Reloading of the configuration without restarting is done by sending SIGHUP to the daemon but please note that changes to pidfile_path, socket_path and log_file require restart to take effect. The format is as follows: <option_name> = <option value> Option names are case-INsensitive and ``_`` may be replaced by ``-``. Spaces around ``=`` are optional and have no effect. Option values may optionally be enclosed in either single or double quotes. # and any text following it on the line are ignored. log_file :Default: ``/tmp/<name>.log`` Log file used to log exceptions during daemon run. pidfile_path :Default: ``'/var/run/<name>.pid'`` Path to the pidfile. A pidfile lock is created and passed to DaemonContext. Alternatively, you may pass a pid lockfile directly by setting <daemon>.daemon_context.pidfile to the lockfile after initialization but before start. Changing either of them after the daemon is started requires a restart. socket_path :Default: ``'/var/run/<name>.socket'`` Path for the unix daemon socket which the daemon will be listening on. Changing this after the daemon is started requires a restart. Also see documentation for serial.py. data_length :Default: ``1024`` Number of bytes to be read from the socket. This MUST be at least the number of bytes that have been sent, otherwise the remainder is read afterwards and is confused for a new packet. See above for details on the data format. data_encoding :Default: ``'utf-8'`` Valid encoding (accepted by the str.decode() and bytes() methods) for the data read from and sent to the socket. reply_length_strict :Default: ``False`` If True daemon will not send data read from device unless the length matches the expected reply length given as part of the data sent over the socket. See above for details on the data format. daemon_context :Default: ``None`` If this is not None, it must be a DaemonContext object and is used instead of creating a new one. All options relating to DaemoonContext are then ignored. serial_context :Default: ``None`` If this is not None, it must be a Serial object and is used instead of creating a new one. All options relating to Serial are then ignored. In addition to the above arguments, SerialDaemon accepts all arguments valid for DaemonContext and Serial and uses them to create the corresponding objects (unless daemon_context or serial_context are given) """ def __init__( self, name = 'seriald', config_file = 0, log_file = None, pidfile_path = 0, socket_path = 0, reply_length_strict = False, data_length = 1024, data_encoding = 'utf-8', daemon_context = None, serial_context = None, **kwargs ): self.name = name self.config_file = config_file if self.config_file == 0: self.config_file = '/etc/{name}.conf'.format(name = self.name) self.log_file = log_file # log file will be used even if user specified None if self.log_file is None: self.log_file = os.path.join( tempfile.gettempdir(), '{name}.log'.format( name = self.name)) self.pidfile_path = pidfile_path if self.pidfile_path == 0: self.pidfile_path = '/var/run/{name}.pid'.format(name = self.name) self.socket_path = socket_path if self.socket_path == 0: self.socket_path = '/var/run/{name}.socket'.format(name = self.name) self.reply_length_strict = reply_length_strict self.data_length = data_length self.data_encoding = data_encoding self.daemon_context = daemon_context if self.daemon_context is None: self.daemon_context = DaemonContext( signal_map = { signal.SIGHUP: self.__accept_signal, signal.SIGINT: self.__accept_signal, signal.SIGQUIT: self.__accept_signal, signal.SIGTERM: self.__accept_signal, } ) for attr in filter(lambda s: not s.startswith('_'), dir(self.daemon_context)): if kwargs.get(attr) is not None: setattr(self.daemon_context, attr, kwargs.get(attr)) self.serial_context = serial_context if self.serial_context is None: self.serial_context = Serial() for attr in filter(lambda s: not s.startswith('_'), dir(self.serial_context)): if kwargs.get(attr) is not None: setattr(self.serial_context, attr, kwargs.get(attr)) def __run(self): with open(self.log_file, 'a') as log_file: try: soc = None # flush doesn't work in daemon mode for ttyS? # close and reopen instead device = self.serial_context.port is_ttyS = True try: # is it a number? Serial defaults to /dev/ttyS? if so device += 0 except TypeError: # not a number, assume string try: if not device.startswith('/dev/ttyS'): raise AttributeError except AttributeError: # not a string or not a ttyS? device # assume flushing works is_ttyS = False else: device = '/dev/ttyS{num}'.format(num = device) while True: if not soc or soc.fileno() < 0: logsyslog(LOG_INFO, 'Waiting for connection') soc, soc_addr = self.socket.accept() logsyslog(LOG_INFO, ('Connected to {addr}').format( addr = soc_addr)) data = soc.recv(self.data_length).decode( self.data_encoding) if data == '': logsyslog(LOG_INFO, 'Closing connection') soc.close() continue elif data == 'device': logsyslog(LOG_INFO, 'Device path requested') try: soc.sendall(device.encode(self.data_encoding)) except ConnectionResetError: soc.close() continue logsyslog(LOG_INFO, 'Read from socket: {data}'.format( data = data)) reply_length_byte_length = 0 try: reply_length_byte_length = int(data[0], 16) reply_length = int( data[1 : reply_length_byte_length + 1], 16) except ValueError: reply_length = 0 data = data[reply_length_byte_length + 1:] if not self.serial_context.isOpen(): # first time in the loop logsyslog(LOG_INFO, 'Opening serial port') self.serial_context.open() logsyslog(LOG_INFO, 'Sending {data}'.format( data = data)) # discard any input or output self.serial_context.flushOutput() self.serial_context.flushInput() self.serial_context.write(data.encode(self.data_encoding)) if is_ttyS: self.serial_context.close() self.serial_context.open() else: self.serial_context.flush() logsyslog(LOG_INFO, ('Will read {length} bytes').format( length = reply_length)) if reply_length > 0: reply = self.serial_context.read(reply_length) reply_decoded = reply.decode(self.data_encoding) logsyslog(LOG_INFO, 'Received {data}'.format( data = reply_decoded)) if len(reply_decoded) == reply_length \ or not self.reply_length_strict: try: soc.sendall(reply) except ConnectionResetError: soc.close() continue except: traceback.print_exc(file = log_file) self.__stop() def __load_config(self): def reset_invalid_value(opt): logsyslog(LOG_ERR, ('{conf}: Invalid value for ' + '{option}').format( conf = self.config_file, option = opt)) return getattr(self, opt) conf = _openfile(self.config_file, 'r') if conf is not None: with conf: regex_pat = regex.compile(r"""\s* (?| (?P<option> reply_length_strict | data[-_]length | data[-_]encoding | log[-_]file | pidfile[-_]path | socket[-_]path ) \s* (?: =\s* )? (?| " (?P<value> [^"]+ ) " | ' (?P<value> [^']+ ) ' | (?P<value> [^#\r\n]+ ) ) ) """, regex.X|regex.I) line_num = 0 for line in conf: line_num += 1 if line.startswith('#'): continue match = regex_pat.match(line.strip()) if match: # translate the option name to the object's attribute opt = match.group('option').lower().replace('-', '_') if opt.endswith(('file', 'dir', 'path', 'encoding')): # value is a string val = match.group('value') elif opt == 'reply_length_strict': # value must be a boolean if val.lower() not in ['0', '1', 'false', 'true']: val = reset_invalid_value(opt) elif val.lower() in ['0', 'false']: val = False else: val = True else: # value must be numeric and positive val = int(match.group('value')) if val <= 0: val = reset_invalid_value(opt) setattr(self, opt, val) else: logsyslog(LOG_ERR, ('{conf}: Invalid syntax at line ' + '{line}').format( conf = self.config_file, line = line_num)) logsyslog(LOG_INFO, 'Loaded configuration from {conf}'.format( conf = self.config_file)) def start(self): """ Load config, daemonize, connect to serial port, listen on socket """ opensyslog(ident = self.name, facility = LOG_DAEMON) self.__load_config() if self.pidfile_path is not None: self.daemon_context.pidfile = lockfile.FileLock(self.pidfile_path) if _pidfile_isbusy(self.daemon_context.pidfile): logsyslog(LOG_ERR, 'Already running (pidfile is locked)') closesyslog() return if _socket_isbusy(self.socket_path): logsyslog(LOG_ERR, 'Already running (socket is in use)') closesyslog() return self.daemon_context.open() with _openfile(self.daemon_context.pidfile.path, 'w', fail = self.__stop) as file: file.write('{pid}'.format(pid = os.getpid())) # opening the serial port here doesn't work # open it in __run instead # self.serial_context.open() logsyslog(LOG_INFO, 'Started') self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.socket.bind(self.socket_path) self.socket.listen(1) logsyslog(LOG_INFO, ('Listening on socket {socket}').format( socket = self.socket_path)) self.__run() def __stop(self): pid = _get_pid(self.daemon_context.pidfile.path) if pid is None: return logsyslog(LOG_INFO, 'Stopping') os.remove(self.socket.getsockname()) os.remove(self.daemon_context.pidfile.path) self.socket.close() if self.serial_context.isOpen(): self.serial_context.close() self.daemon_context.close() try: os.kill(pid, signal.SIGKILL) except OSError: logsyslog(LOG_ERR, 'Could not stop process id {pid}'.format( pid = pid)) closesyslog() def __accept_signal(self, sig, frame): if sig == signal.SIGHUP: self.__load_config() else: logsyslog(LOG_INFO, 'Caught signal {sig}'.format(sig = sig)) self.__stop()
class Create: """Wrapper class for the iRobot Create""" def __init__(self, tty="/dev/ttyUSB0"): """constructor for the Create, takes in a single argument: the serial port""" self.timeout = 5 self.period = .07 self.runRef = [] self.packetRef = [] self.queueLock = Lock() self.queue = [] self.distanceLock = Lock() self.__distance = 0 self.angleLock = Lock() self.__angle = 0 self.port = Serial(tty, 57600, timeout=self.timeout) self.portLock = Lock() self.update = lambda: '' self.reset() def start(self): """Start the iCreate after initialization or reset.""" self.__sendNow(128, 128, 132, 140, 1, 5, 64, 16, 69, 16, 74, 16, 72, 40, 69, 60, 141, 1) sleep(1) self.send(139, 10, 0, 255) monitor = Monitor(self.runRef, self.packetRef, self, self.__read, self.__sendAll, self.__addDistance, self.__addAngle, self.update) monitor.start() sleep(1.5) def stop(self): """Stop the iCreate. Must be called before deletion of the iCreate object.""" self.runRef.append('quit') sleep(1) rh, rl = self.__convert(0) lh, ll = self.__convert(0) self.__sendNow(145, rh, rl, lh, ll) #emergency brake self.__sendNow(139, 0, 0, 255) def reset(self): """Reset the iCreate.""" self.runRef.append('quit') self.runRef = [] sleep(1) self.port.flushOutput() self.port.flushInput() self.__sendNow(128, 7) self.__read(128, True) #should have processed initialization self.port.flushInput() #ignore rest of input def __convert(self, num): return self.__highLow(self.__twos(num)) def __highLow(self, num): return num >> 8, num & 0xFF def __twos(self, num, bits=16): if (num >= 0): return num return 2**bits + num def send(self, *opcodes): self.queueLock.acquire() def lmbda(): self.__sendNow(*opcodes) self.queue.append(lmbda) self.queueLock.release() def __sendNow(self, *opcodes): self.portLock.acquire() format = "B" * len(opcodes) data = pack(format, *opcodes) self.port.write(data) self.portLock.release() def __sendAll(self): self.queueLock.acquire() self.__read(self.port.inWaiting()) for send in self.queue: send() self.queue = [] self.queueLock.release() def __read(self, num, block=False): self.portLock.acquire() if (block): self.port.timeout = None bytes = self.port.read(num) if (block): self.port.timeout = self.timeout self.portLock.release() return bytes def __getattr__(self, name): if (len(self.packetRef)): if (name in self.packetRef[0]): return self.packetRef[0][name] raise AttributeError, "no %s attribute" % (name) def __addDistance(self, num): self.distanceLock.acquire() self.__distance = self.__distance + num dis = self.__distance self.distanceLock.release() return dis def __addAngle(self, num): self.angleLock.acquire() self.__angle = self.__angle + num ang = self.__angle self.angleLock.release() return ang def clearDistance(self): self.distanceLock.acquire() self.__distance = 0 self.distanceLock.release() def clearAngle(self): self.angleLock.acquire() self.__angle = 0 self.angleLock.release() def clear(self): self.clearDistance() self.clearAngle() def __del__(self): self.port.close() def brake(self): """Stops the iCreate, takes no parameters""" self.tank(0, 0) def demo(self, num): """Takes a single parameter, the number of the demo to begin. "Running" demo -1 will stop the demo. After using this function the iCreate must be reset.""" if (num == -1): num = 255 self.send(136, num) def leds(self, play, advance, color, intensity): """Controls the LEDs. Parameters are play: boolean (play on/off), advance: boolean (advance on/off), color: 0-255 (how much red in the power light), and intensity: 0-255 (how bright should the power light be.""" if (play): play = 1 else: play = 0 if (advance): advance = 1 else: advance = 0 bits = play << 1 | advance << 3 self.send(139, bits, color, intensity) def storeSong(self, num, *song): """Store a song. First parameter is the song number, the remaming arguments are taken to be of the form: note, duration, note, duration, etc. See page 12 of the iRobot Create Open Interface Manual for numerical note definitions. Duration is interpreted as duration*1/64th of a second.""" if (len(song) > 32): song = song[:31] self.send(140, num, len(song) / 2, *song) def playSong(self, num): """Plays a song. Takes one parameter, the song number.""" if (not self.songPlaying): self.send(141, num) def tank(self, left, right): """Drive the iCreate like a tank (i.e. left throttle, right throttle). Takes two parameters: left and right throttle. Each can be between -500 and 500 representing mm/s.""" if (left < -500): left = -500 if (right < -500): right = -500 if (left > 500): left = 500 if (right > 500): right = 500 lh, ll = self.__convert(left) rh, rl = self.__convert(right) self.send(145, rh, rl, lh, ll) def forwardTurn(self, speed, radius): """Takes two parameters: speed and radius. Drives the iCreate at speed with enough of an angle that the iCreate will carve a circle with the given radius. Speed is in mm/s and can vary between -500 and 500. The radius can vary between -2000 and 2000 mm (with negative mm turning left).""" if (speed > 500): speed = 500 if (speed < -500): speed = -500 if (not (radius == 0x8000 or radius == 0x7FF or radius == 0xFFFF or radius == 0x001) and (radius > 2000 or radius < -2000)): if (radius > 2000): radius = 2000 if (radius < -2000): radius = -2000 vh, vl = self.__convert(speed) rh, rl = self.__convert(radius) self.send(137, vh, vl, rh, rl) def turn(self, speed): self.right(speed) def right(self, speed): """Takes in a parameter: speed and turns clockwise in place at speed mm/s.""" self.forwardTurn(speed, 0xFFFF) def left(self, speed): """Takes in a parameter: speed and turns counter-clockwise in place at speed mm/s.""" self.forwardTurn(speed, 0x0001)
class LaCrosse(object): sensors = {} _registry = {} _callback = None _serial = None _stopevent = None _thread = None def __init__(self, port, baud, timeout=2): """Initialize the Lacrosse device.""" self._port = port self._baud = baud self._timeout = timeout self._serial = Serial() self._callback_data = None def open(self): """Open the device.""" self._serial.port = self._port self._serial.baudrate = self._baud self._serial.timeout = self._timeout self._serial.open() self._serial.flushInput() self._serial.flushOutput() def close(self): """Close the device.""" self._stop_worker() self._serial.close() def start_scan(self): """Start scan task in background.""" self._start_worker() def _write_cmd(self, cmd): """Write a cmd.""" self._serial.write(cmd.encode()) @staticmethod def _parse_info(line): """ The output can be: - [LaCrosseITPlusReader.10.1s (RFM12B f:0 r:17241)] - [LaCrosseITPlusReader.10.1s (RFM12B f:0 t:10~3)] """ re_info = re.compile(r'\[(?P<name>\w+).(?P<ver>.*) ' + r'\((?P<rfm1name>\w+) (\w+):(?P<rfm1freq>\d+) ' + r'(?P<rfm1mode>.*)\)\]') info = { 'name': None, 'version': None, 'rfm1name': None, 'rfm1frequency': None, 'rfm1datarate': None, 'rfm1toggleinterval': None, 'rfm1togglemask': None, } match = re_info.match(line) if match: info['name'] = match.group('name') info['version'] = match.group('ver') info['rfm1name'] = match.group('rfm1name') info['rfm1frequency'] = match.group('rfm1freq') values = match.group('rfm1mode').split(':') if values[0] == 'r': info['rfm1datarate'] = values[1] elif values[0] == 't': toggle = values[1].split('~') info['rfm1toggleinterval'] = toggle[0] info['rfm1togglemask'] = toggle[1] return info def get_info(self): """Get current configuration info from 'v' command.""" re_info = re.compile(r'\[.*\]') self._write_cmd('v') while True: line = self._serial.readline() try: line = line.encode().decode('utf-8') except AttributeError: line = line.decode('utf-8') match = re_info.match(line) if match: return self._parse_info(line) def led_mode_state(self, state): """Set the LED mode. The LED state can be True or False. """ self._write_cmd('{}a'.format(int(state))) def set_frequency(self, frequency, rfm=1): """Set frequency in kHz. The frequency can be set in 5kHz steps. """ cmds = {1: 'f', 2: 'F'} self._write_cmd('{}{}'.format(frequency, cmds[rfm])) def set_datarate(self, rate, rfm=1): """Set datarate (baudrate).""" cmds = {1: 'r', 2: 'R'} self._write_cmd('{}{}'.format(rate, cmds[rfm])) def set_toggle_interval(self, interval, rfm=1): """Set the toggle interval.""" cmds = {1: 't', 2: 'T'} self._write_cmd('{}{}'.format(interval, cmds[rfm])) def set_toggle_mask(self, mode_mask, rfm=1): """Set toggle baudrate mask. The baudrate mask values are: 1: 17.241 kbps 2 : 9.579 kbps 4 : 8.842 kbps These values can be or'ed. """ cmds = {1: 'm', 2: 'M'} self._write_cmd('{}{}'.format(mode_mask, cmds[rfm])) def _start_worker(self): if self._thread is not None: return self._stopevent = threading.Event() self._thread = threading.Thread(target=self._refresh, args=()) self._thread.daemon = True self._thread.start() def _stop_worker(self): if self._stopevent is not None: self._stopevent.set() if self._thread is not None: self._thread.join() def _refresh(self): """Background refreshing thread.""" while not self._stopevent.isSet(): line = self._serial.readline() #this is for python2/python3 compatibility. Is there a better way? try: line = line.encode().decode('utf-8') except AttributeError: line = line.decode('utf-8') if LaCrosseSensor.re_reading.match(line): sensor = LaCrosseSensor(line) self.sensors[sensor.sensorid] = sensor if self._callback: self._callback(sensor, self._callback_data) if sensor.sensorid in self._registry: for cbs in self._registry[sensor.sensorid]: cbs[0](sensor, cbs[1]) def register_callback(self, sensorid, callback, user_data=None): """Register a callback for the specified sensor id.""" if sensorid not in self._registry: self._registry[sensorid] = list() self._registry[sensorid].append((callback, user_data)) def register_all(self, callback, user_data=None): """Register a callback for all sensors.""" self._callback = callback self._callback_data = user_data
class AsSerial(QThread): recv_msg = QtCore.pyqtSignal(str) toStr = lambda self,data: ''.join(['%c'%(c) for c in data]) def __init__(self,parent=None): super(QThread, self).__init__(parent) self.isCANMode=False self.cmd = AsCommand(self) def open(self, settings, start=True): self.__terminate = False if(settings['port'] == 'CAN'): self.isCANMode = True self.start() return (True, 'success') try: self.serial = Serial(settings['port'], settings['baund'], settings['bytesize'], settings['parity'], settings['stopbits'], settings['timeout']) self.serial.flushInput() self.serial.flushOutput() except: return (False, "%s"%(sys.exc_info()[1])) if(start == True): self.start() return (True, 'success') def runcmd(self,cmd,runNow=True): if(False == runNow): self.cmd.append(cmd) return True,None self.serial.flushOutput() self.serial.flushInput() if(cmd[-1] != '\n'): cmd += '\n' ercd = True result = '' reResult = re.compile(r'exit\((\d+)\)') for c in cmd: self.send(c) r = self.read() if(r != c): ercd = False result = 'bus error' break while(ercd): r = self.read(1, 5) if(r == None): ercd = False break result += r if('[AS] $' in result): result = result[:-6] if(reResult.search(result)): r = reResult.search(result).groups()[0] if(r != '0'): ercd = False else: ercd = False break return ercd, result def resetArduino(self): if(self.isCANMode): return self.serial.setDTR(0) time.sleep(0.1) self.serial.setDTR(1) def terminate(self): self.__terminate = True def send(self, data): if(self.isCANMode): index = 0 pdu=[] for d in data: pdu.append(ord(d)) index +=1 if(index == 8): ercd = can_write(0,0x701,pdu) if(False == ercd): print('Seial: send can message failed!') index = 0 pdu = [] if(index > 0): ercd = can_write(0,0x701,pdu) if(False == ercd): print('Seial: send can message failed!') return if(type(data) != bytes): data = data.encode('utf-8') self.serial.write(data) def read(self,length=1, timeout=0.1): result = bytes() t = time.time() while(len(result) <length): data = self.serial.read(1) if(len(data) == 0): continue else: result += data if((time.time()-t) > timeout): return None return self.toStr(result) def __recv(self): data, quit = bytes(), False if(self.isCANMode): data = '' while(True): if(self.__terminate): break if(len(self.cmd.cmdList)>0): break if(self.isCANMode): # default on CAN bus0, CANID 0x702 ercd,canid,d = can_read(0, 0x702) if(ercd): for b in d: data += '%c'%(b) if('%c'%(b) =='\n'): quit = True if(quit==True): break continue data = self.serial.read(1) if(len(data) == 0): continue while(True): n = self.serial.inWaiting() if( n > 0): data += self.serial.read(n) time.sleep(0.02) # data is this interval will be merged else: quit = True break if(quit==True): break return self.toStr(data) def close(self): if(self.isCANMode): return if self.serial.isOpen(): self.serial.close() def run(self): while(True): self.cmd.run() data = self.__recv() if(len(data) > 0): self.recv_msg.emit(data) if(self.isCANMode): return self.serial.close()
class DfuTransportSerial(): DEFAULT_BAUD_RATE = 57600 DEFAULT_FLOW_CONTROL = False DEFAULT_SERIAL_PORT_TIMEOUT = 1.0 # Timeout time on serial port read ACK_PACKET_TIMEOUT = 1.0 # Timeout time for for ACK packet received before reporting timeout through event system SEND_INIT_PACKET_WAIT_TIME = 1.0 # Time to wait before communicating with bootloader after init packet is sent SEND_START_DFU_WAIT_TIME = 2.0 # Time to wait before communicating with bootloader after start DFU packet is sent ## was 10 sec DFU_PACKET_MAX_SIZE = 512 # The DFU packet max size def __init__(self, com_port, baud_rate=DEFAULT_BAUD_RATE, flow_control=DEFAULT_FLOW_CONTROL, timeout=DEFAULT_SERIAL_PORT_TIMEOUT): self.com_port = com_port self.baud_rate = baud_rate self.flow_control = 1 if flow_control else 0 self.timeout = timeout self.serial_port = None """:type: serial.Serial """ def open(self): self.serial_port = Serial(port=self.com_port, baudrate=self.baud_rate, rtscts=self.flow_control, timeout=self.timeout) self.serial_port.flushInput() self.serial_port.flushOutput() self.serial_port.flush() def close(self): self.serial_port.close() def is_open(self): if self.serial_port is None: return False return self.serial_port.isOpen() def send_validate_firmware(self): super(DfuTransportSerial, self).send_validate_firmware() return True def send_init_packet(self,firmware): # super(DfuTransportSerial, self).send_init_packet(init_packet) init_packet = 'ffffffffffffffff0100feff' init_packet += binascii.hexlify(struct.pack('<H', crc16.calc_crc16(firmware, crc=0xffff))) init_packet = binascii.unhexlify(init_packet) frame = int32_to_bytes(DFU_INIT_PACKET) frame += init_packet frame += int16_to_bytes(0x0000) # Padding required packet = HciPacket(frame) self.send_packet(packet) time.sleep(DfuTransportSerial.SEND_INIT_PACKET_WAIT_TIME) def send_start_dfu(self, mode, softdevice_size=None, bootloader_size=None, app_size=None): # super(DfuTransportSerial, self).send_start_dfu(mode, softdevice_size, bootloader_size, app_size) frame = int32_to_bytes(DFU_START_PACKET) frame += int32_to_bytes(mode) frame += self.create_image_size_packet(softdevice_size, bootloader_size, app_size) packet = HciPacket(frame) self.send_packet(packet) time.sleep(DfuTransportSerial.SEND_START_DFU_WAIT_TIME) def send_activate_firmware(self): super(DfuTransportSerial, self).send_activate_firmware() def send_firmware(self, firmware): # super(DfuTransportSerial, self).send_firmware(firmware) def progress_percentage(part, whole): return int(100 * float(part)/float(whole)) frames = [] # self._send_event(DfuEvent.PROGRESS_EVENT, progress=0, done=False, log_message="") for i in range(0, len(firmware), DfuTransportSerial.DFU_PACKET_MAX_SIZE): data_packet = HciPacket(int32_to_bytes(DFU_DATA_PACKET) + firmware[i:i + DfuTransportSerial.DFU_PACKET_MAX_SIZE]) frames.append(data_packet) frames_count = len(frames) # Send firmware packets for count, pkt in enumerate(frames): self.send_packet(pkt) # self._send_event(DfuEvent.PROGRESS_EVENT, # log_message="", # progress=progress_percentage(count, frames_count), # done=False) # Send data stop packet frame = int32_to_bytes(DFU_STOP_DATA_PACKET) packet = HciPacket(frame) self.send_packet(packet) # self._send_event(DfuEvent.PROGRESS_EVENT, progress=100, done=False, log_message="") def send_packet(self, pkt): attempts = 0 last_ack = None packet_sent = False logger.debug("PC -> target: {0}".format(pkt)) print format(binascii.hexlify(pkt.data)) print "Sequence number HCI: " + str(HciPacket.sequence_number) while not packet_sent: self.serial_port.write(pkt.data) attempts += 1 time.sleep(0.2) ack = self.get_ack_nr() # print "attempts: " + str(attempts) if last_ack is None: print str(ack) break if ack == (last_ack + 1) % 8: last_ack = ack packet_sent = True if attempts > 3: raise Exception("Three failed tx attempts encountered on packet {0}".format(pkt.sequence_number)) def get_ack_nr(self): def is_timeout(start_time, timeout_sec): return not (datetime.now() - start_time <= timedelta(0, timeout_sec)) uart_buffer = '' start = datetime.now() while uart_buffer.count('\xC0') < 2: # Disregard first of the two C0 temp = self.serial_port.read(6) if temp: uart_buffer += temp print format(binascii.hexlify(uart_buffer)) if is_timeout(start, DfuTransportSerial.ACK_PACKET_TIMEOUT): # reset HciPacket numbering back to 0 HciPacket.sequence_number = 0 print "Timed out waiting for acknowledgement from device." # quit loop break # read until you get a new C0 # RESUME_WORK if len(uart_buffer) < 2: print "No data received on serial port. Not able to proceed." return logger.debug("PC <- target: {0}".format(binascii.hexlify(uart_buffer))) data = self.decode_esc_chars(uart_buffer) # Remove 0xC0 at start and beginning data = data[1:-1] # Extract ACK number from header return (data[0] >> 3) & 0x07 @staticmethod def decode_esc_chars(data): """Replace 0xDBDC with 0xCO and 0xDBDD with 0xDB""" result = [] data = bytearray(data) while len(data): char = data.pop(0) if char == 0xDB: char2 = data.pop(0) if char2 == 0xDC: result.append(0xC0) elif char2 == 0xDD: result.append(0xDB) else: raise Exception('Char 0xDB NOT followed by 0xDC or 0xDD') else: result.append(char) return result @staticmethod def create_image_size_packet(softdevice_size=0, bootloader_size=0, app_size=0): """ Creates an image size packet necessary for sending start dfu. @param softdevice_size: Size of SoftDevice firmware @type softdevice_size: int @param bootloader_size: Size of bootloader firmware @type softdevice_size: int @param app_size: Size of application firmware :return: The image size packet :rtype: str """ softdevice_size_packet = int32_to_bytes(softdevice_size) bootloader_size_packet = int32_to_bytes(bootloader_size) app_size_packet = int32_to_bytes(app_size) image_size_packet = softdevice_size_packet + bootloader_size_packet + app_size_packet return image_size_packet
if options.disk: # Simple copy to the mbed disk copy(bin, options.disk) if options.serial: # Import pyserial: https://pypi.python.org/pypi/pyserial from serial import Serial sleep(target.program_cycle_s()) serial = Serial(options.serial, timeout = 1) if options.baud: serial.setBaudrate(options.baud) serial.flushInput() serial.flushOutput() try: serial.sendBreak() except: # In linux a termios.error is raised in sendBreak and in setBreak. # The following setBreak() is needed to release the reset signal on the target mcu. try: serial.setBreak(False) except: pass while True: c = serial.read(512) sys.stdout.write(c) sys.stdout.flush()
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", metavar="PORT") parser.add_option("-d", "--disk", dest="disk", help="The target disk path", metavar="DISK_PATH") parser.add_option("-f", "--image-path", dest="image_path", help="Path with target's image", metavar="IMAGE_PATH") parser.add_option("-c", "--copy", dest="copy_method", help="Copy method selector", metavar="COPY_METHOD") parser.add_option("-C", "--program_cycle_s", dest="program_cycle_s", help="Program cycle sleep. Define how many seconds you want wait after copying bianry onto target", type="float", metavar="COPY_METHOD") parser.add_option("-t", "--timeout", dest="timeout", help="Timeout", metavar="TIMEOUT") parser.add_option("-r", "--reset", dest="forced_reset_type", help="Forces different type of reset") parser.add_option("-R", "--reset-timeout", dest="forced_reset_timeout", metavar="NUMBER", type="int", help="When forcing a reset using option -r you can set up after reset timeout in seconds") (self.options, _) = parser.parse_args() self.DEFAULT_RESET_TOUT = 0 self.DEFAULT_TOUT = 10 if self.options.port is None: raise Exception("The serial port of the target mbed have to be provided as command line arguments") # Options related to copy / reset mbed device self.port = self.options.port self.disk = self.options.disk self.image_path = self.options.image_path.strip('"') self.copy_method = self.options.copy_method self.program_cycle_s = float(self.options.program_cycle_s) self.serial = None self.serial_baud = 9600 self.serial_timeout = 1 self.timeout = self.DEFAULT_TOUT if self.options.timeout is None else self.options.timeout print 'MBED: Instrumentation: "%s" and disk: "%s"' % (self.port, self.disk) def init_serial_params(self, serial_baud=9600, serial_timeout=1): """ Initialize port parameters. This parameters will be used by self.init_serial() function to open serial port """ self.serial_baud = serial_baud self.serial_timeout = serial_timeout def init_serial(self, serial_baud=None, serial_timeout=None): """ Initialize serial port. Function will return error is port can't be opened or initialized """ # Overload serial port configuration from default to parameters' values if they are specified serial_baud = serial_baud if serial_baud is not None else self.serial_baud serial_timeout = serial_timeout if serial_timeout is not None else self.serial_timeout # Clear serial port if self.serial: self.serial.close() self.serial = None # We will pool for serial to be re-mounted if it was unmounted after device reset result = self.pool_for_serial_init(serial_baud, serial_timeout) # Blocking # Port can be opened if result: self.flush() return result def pool_for_serial_init(self, serial_baud, serial_timeout, pooling_loops=40, init_delay=0.5, loop_delay=0.25): """ Functions pools for serial port readiness """ result = True last_error = None # This loop is used to check for serial port availability due to # some delays and remounting when devices are being flashed with new software. for i in range(pooling_loops): sleep(loop_delay if i else init_delay) try: self.serial = Serial(self.port, baudrate=serial_baud, timeout=serial_timeout) except Exception as e: result = False last_error = "MBED: %s"% str(e) stdout.write('.') stdout.flush() else: print "...port ready!" result = True break if not result and last_error: print last_error return result def set_serial_timeout(self, timeout): """ Wraps self.mbed.serial object timeout property """ result = None if self.serial: self.serial.timeout = timeout result = True return result def serial_read(self, count=1): """ Wraps self.mbed.serial object read method """ result = None if self.serial: try: result = self.serial.read(count) except: result = None return result def serial_readline(self, timeout=5): """ Wraps self.mbed.serial object read method to read one line from serial port """ result = '' start = time() while (time() - start) < timeout: if self.serial: try: c = self.serial.read(1) result += c except Exception as e: print "MBED: %s"% str(e) result = None break if c == '\n': break return result def serial_write(self, write_buffer): """ Wraps self.mbed.serial object write method """ result = None if self.serial: try: result = self.serial.write(write_buffer) except: result = None return result def reset_timeout(self, timeout): """ Timeout executed just after reset command is issued """ for n in range(0, timeout): sleep(1) def reset(self): """ Calls proper reset plugin to do the job. Please refer to host_test_plugins functionality """ # Flush serials to get only input after reset self.flush() if self.options.forced_reset_type: result = host_tests_plugins.call_plugin('ResetMethod', self.options.forced_reset_type, disk=self.disk) else: result = host_tests_plugins.call_plugin('ResetMethod', 'default', serial=self.serial) # Give time to wait for the image loading reset_tout_s = self.options.forced_reset_timeout if self.options.forced_reset_timeout is not None else self.DEFAULT_RESET_TOUT self.reset_timeout(reset_tout_s) return result def copy_image(self, image_path=None, disk=None, copy_method=None): """ Closure for copy_image_raw() method. Method which is actually copying image to mbed """ # Set closure environment image_path = image_path if image_path is not None else self.image_path disk = disk if disk is not None else self.disk copy_method = copy_method if copy_method is not None else self.copy_method # Call proper copy method result = self.copy_image_raw(image_path, disk, copy_method) return result def copy_image_raw(self, image_path=None, disk=None, copy_method=None): """ Copy file depending on method you want to use. Handles exception and return code from shell copy commands. """ # image_path - Where is binary with target's firmware if copy_method is not None: # We override 'default' method with 'shell' method if copy_method == 'default': copy_method = 'shell' else: copy_method = 'shell' result = host_tests_plugins.call_plugin('CopyMethod', copy_method, image_path=image_path, destination_disk=disk, program_cycle_s=self.program_cycle_s) return result; def flush(self): """ Flush serial ports """ result = False if self.serial: self.serial.flushInput() self.serial.flushOutput() result = True return result
class Stk500v2(ispBase.IspBase): def __init__(self): self.serial = None self.seq = 1 self.last_addr = -1 self.progress_callback = None def connect(self, port = "COM22", speed = 115200): if self.serial is not None: self.close() try: self.serial = Serial(str(port), speed, timeout=1, writeTimeout=10000) except SerialException: raise ispBase.IspError("Failed to open serial port") except: raise ispBase.IspError("Unexpected error while connecting to serial port:" + port + ":" + str(sys.exc_info()[0])) self.seq = 1 #Reset the controller for n in range(0, 2): self.serial.setDTR(True) time.sleep(0.1) self.serial.setDTR(False) time.sleep(0.1) time.sleep(0.2) self.serial.flushInput() self.serial.flushOutput() if self.sendMessage([0x10, 0xc8, 0x64, 0x19, 0x20, 0x00, 0x53, 0x03, 0xac, 0x53, 0x00, 0x00]) != [0x10, 0x00]: self.close() raise ispBase.IspError("Failed to enter programming mode") self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00]) if self.sendMessage([0xEE])[1] == 0x00: self._has_checksum = True else: self._has_checksum = False self.serial.timeout = 5 def close(self): if self.serial is not None: self.serial.close() self.serial = None #Leave ISP does not reset the serial port, only resets the device, and returns the serial port after disconnecting it from the programming interface. # This allows you to use the serial port without opening it again. def leaveISP(self): if self.serial is not None: if self.sendMessage([0x11]) != [0x11, 0x00]: raise ispBase.IspError("Failed to leave programming mode") ret = self.serial self.serial = None return ret return None def isConnected(self): return self.serial is not None def hasChecksumFunction(self): return self._has_checksum def sendISP(self, data): recv = self.sendMessage([0x1D, 4, 4, 0, data[0], data[1], data[2], data[3]]) return recv[2:6] def writeFlash(self, flash_data): #Set load addr to 0, in case we have more then 64k flash we need to enable the address extension page_size = self.chip["pageSize"] * 2 flash_size = page_size * self.chip["pageCount"] Logger.log("d", "Writing flash") if flash_size > 0xFFFF: self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00]) else: self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00]) load_count = (len(flash_data) + page_size - 1) / page_size for i in range(0, int(load_count)): self.sendMessage([0x13, page_size >> 8, page_size & 0xFF, 0xc1, 0x0a, 0x40, 0x4c, 0x20, 0x00, 0x00] + flash_data[(i * page_size):(i * page_size + page_size)]) if self.progress_callback is not None: if self._has_checksum: self.progress_callback(i + 1, load_count) else: self.progress_callback(i + 1, load_count * 2) def verifyFlash(self, flash_data): if self._has_checksum: self.sendMessage([0x06, 0x00, (len(flash_data) >> 17) & 0xFF, (len(flash_data) >> 9) & 0xFF, (len(flash_data) >> 1) & 0xFF]) res = self.sendMessage([0xEE]) checksum_recv = res[2] | (res[3] << 8) checksum = 0 for d in flash_data: checksum += d checksum &= 0xFFFF if hex(checksum) != hex(checksum_recv): raise ispBase.IspError("Verify checksum mismatch: 0x%x != 0x%x" % (checksum & 0xFFFF, checksum_recv)) else: #Set load addr to 0, in case we have more then 64k flash we need to enable the address extension flash_size = self.chip["pageSize"] * 2 * self.chip["pageCount"] if flash_size > 0xFFFF: self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00]) else: self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00]) load_count = (len(flash_data) + 0xFF) / 0x100 for i in range(0, int(load_count)): recv = self.sendMessage([0x14, 0x01, 0x00, 0x20])[2:0x102] if self.progress_callback is not None: self.progress_callback(load_count + i + 1, load_count * 2) for j in range(0, 0x100): if i * 0x100 + j < len(flash_data) and flash_data[i * 0x100 + j] != recv[j]: raise ispBase.IspError("Verify error at: 0x%x" % (i * 0x100 + j)) def sendMessage(self, data): message = struct.pack(">BBHB", 0x1B, self.seq, len(data), 0x0E) for c in data: message += struct.pack(">B", c) checksum = 0 for c in message: checksum ^= c message += struct.pack(">B", checksum) try: self.serial.write(message) self.serial.flush() except SerialTimeoutException: raise ispBase.IspError("Serial send timeout") self.seq = (self.seq + 1) & 0xFF return self.recvMessage() def recvMessage(self): state = "Start" checksum = 0 while True: s = self.serial.read() if len(s) < 1: raise ispBase.IspError("Timeout") b = struct.unpack(">B", s)[0] checksum ^= b if state == "Start": if b == 0x1B: state = "GetSeq" checksum = 0x1B elif state == "GetSeq": state = "MsgSize1" elif state == "MsgSize1": msg_size = b << 8 state = "MsgSize2" elif state == "MsgSize2": msg_size |= b state = "Token" elif state == "Token": if b != 0x0E: state = "Start" else: state = "Data" data = [] elif state == "Data": data.append(b) if len(data) == msg_size: state = "Checksum" elif state == "Checksum": if checksum != 0: state = "Start" else: return 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") parser.add_option("-r", "--reset", dest="forced_reset_type", help="Forces different type of reset") parser.add_option( "-R", "--reset-timeout", dest="forced_reset_timeout", metavar="NUMBER", type="int", help="When forcing a reset using option -r you can set up after reset timeout in seconds", ) (self.options, _) = parser.parse_args() self.DEFAULT_RESET_TOUT = 2 self.DEFAULT_TOUT = 10 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 = self.DEFAULT_TOUT if self.options.timeout is None else self.options.timeout print 'Host test instrumentation on port: "%s" with serial: "%s"' % (self.port, self.disk) def init_serial(self, baud=9600, extra_baud=9600): """ Initialize serial port. Function will return error is port can't be opened or initialized """ result = True try: self.serial = Serial(self.port, timeout=1) except Exception as e: result = False # Port can be opened if result: 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() return result def serial_timeout(self, timeout): """ Wraps self.mbed.serial object timeout property """ result = None if self.serial: self.serial.timeout = timeout result = True return result def serial_read(self, count=1): """ Wraps self.mbed.serial object read method """ result = None if self.serial: try: result = self.serial.read(count) except: result = None return result def serial_write(self, write_buffer): """ Wraps self.mbed.serial object write method """ result = None if self.serial: try: result = self.serial.write(write_buffer) except: result = None return result def safe_sendBreak(self, serial): """ Wraps serial.sendBreak() to avoid serial::serialposix.py exception on Linux Traceback (most recent call last): File "make.py", line 189, in <module> serial.sendBreak() File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 511, in sendBreak termios.tcsendbreak(self.fd, int(duration/0.25)) error: (32, 'Broken pipe') """ result = True try: serial.sendBreak() except: # In linux a termios.error is raised in sendBreak and in setBreak. # The following setBreak() is needed to release the reset signal on the target mcu. try: serial.setBreak(False) except: result = False return result def touch_file(self, path): """ Touch file and set timestamp to items """ with open(path, "a"): os.utime(path, None) def reset_timeout(self, timeout): """ Timeout executed just after reset command is issued """ for n in range(0, timeout): sleep(1) def reset(self): """ Reset function. Supports 'standard' send break command via Mbed's CDC, also handles other reset modes. E.g. reset by touching file with specific file name: reboot.txt - startup from standby state, reboots when in run mode. shutdown.txt - shutdown from run mode reset.txt - reset FPGA during run mode """ if self.options.forced_reset_type and self.options.forced_reset_type.endswith(".txt"): reset_file_path = os.path.join(self.disk, self.options.forced_reset_type.lower()) self.touch_file(reset_file_path) else: self.safe_sendBreak(self.serial) # Instead of serial.sendBreak() # Give time to wait for the image loading reset_tout_s = ( self.options.forced_reset_timeout if self.options.forced_reset_timeout is not None else self.DEFAULT_RESET_TOUT ) self.reset_timeout(reset_tout_s) def flush(self): """ Flush serial ports """ self.serial.flushInput() self.serial.flushOutput() if self.extra_serial: self.extra_serial.flushInput() self.extra_serial.flushOutput()
#!/usr/bin/python import time from serial import Serial serial_port = Serial(0) if not serial_port.isOpen(): print "No se pudo habrir el puerto serial /dev/ttyS0 " serial_port.flushInput() serial_port.flushOutput() id = 0 while id < 128 : print "pruevo %d" % id query_str = ('%02x' % id ).decode('hex') serial_port.write(query_str) time.sleep(0.9) waiting = serial_port.inWaiting() if waiting : print "La placa con id %d %02x respondio" % (id,id) serial_port.read(waiting) id += 1
class Create: """Wrapper class for the iRobot Create""" def __init__(self, tty="/dev/ttyUSB0"): """constructor for the Create, takes in a single argument: the serial port""" self.timeout = 5 self.period = .07 self.runRef = [] self.packetRef = [] self.queueLock = Lock() self.queue = [] self.distanceLock = Lock() self.__distance = 0 self.angleLock = Lock() self.__angle = 0 self.port = Serial(tty, 57600, timeout= self.timeout) self.portLock = Lock() self.update = lambda : '' self.reset() def start(self): """Start the iCreate after initialization or reset.""" self.__sendNow(128,128,132,140,1,5,64,16,69,16,74,16,72,40,69,60,141,1) sleep(1) self.send(139,10,0,255) monitor = Monitor(self.runRef, self.packetRef, self, self.__read, self.__sendAll, self.__addDistance, self.__addAngle, self.update) monitor.start() sleep(1.5) def stop(self): """Stop the iCreate. Must be called before deletion of the iCreate object.""" self.runRef.append('quit') sleep(1) rh,rl = self.__convert(0) lh,ll = self.__convert(0) self.__sendNow(145,rh,rl,lh,ll) #emergency brake self.__sendNow(139,0,0,255) def reset(self): """Reset the iCreate.""" self.runRef.append('quit') self.runRef = [] sleep(1) self.port.flushOutput() self.port.flushInput() self.__sendNow(128,7) self.__read(128,True) #should have processed initialization self.port.flushInput() #ignore rest of input def __convert(self, num): return self.__highLow(self.__twos(num)) def __highLow(self, num): return num >> 8, num & 0xFF def __twos(self, num, bits=16): if (num >=0): return num return 2**bits+num def send(self, *opcodes): self.queueLock.acquire() def lmbda(): self.__sendNow(*opcodes) self.queue.append(lmbda) self.queueLock.release() def __sendNow(self, *opcodes): self.portLock.acquire() format = "B"*len(opcodes) data = pack(format, *opcodes) self.port.write(data) self.portLock.release() def __sendAll(self): self.queueLock.acquire() self.__read(self.port.inWaiting()) for send in self.queue: send() self.queue = [] self.queueLock.release() def __read(self,num,block=False): self.portLock.acquire() if (block): self.port.timeout = None bytes = self.port.read(num) if (block): self.port.timeout = self.timeout self.portLock.release() return bytes def __getattr__(self,name): if (len(self.packetRef)): if (name in self.packetRef[0]): return self.packetRef[0][name] raise AttributeError, "no %s attribute" % (name) def __addDistance(self,num): self.distanceLock.acquire() self.__distance = self.__distance + num dis = self.__distance self.distanceLock.release() return dis def __addAngle(self,num): self.angleLock.acquire() self.__angle = self.__angle + num ang = self.__angle self.angleLock.release() return ang def clearDistance(self): self.distanceLock.acquire() self.__distance = 0 self.distanceLock.release() def clearAngle(self): self.angleLock.acquire() self.__angle = 0 self.angleLock.release() def clear(self): self.clearDistance() self.clearAngle() def __del__(self): self.port.close() def brake(self): """Stops the iCreate, takes no parameters""" self.tank(0,0) def demo(self, num): """Takes a single parameter, the number of the demo to begin. "Running" demo -1 will stop the demo. After using this function the iCreate must be reset.""" if (num == -1): num = 255 # self.stop() self.brake() self.send(136,num) self.__sendAll() def leds(self,play,advance,color,intensity): """Controls the LEDs. Parameters are play: boolean (play on/off), advance: boolean (advance on/off), color: 0-255 (how much red in the power light), and intensity: 0-255 (how bright should the power light be.""" if (play): play = 1 else: play = 0 if (advance): advance = 1 else: advance = 0 bits = play << 1 | advance << 3 self.send(139,bits,color,intensity) def storeSong(self, num, *song): """Store a song. First parameter is the song number, the remaming arguments are taken to be of the form: note, duration, note, duration, etc. See page 12 of the iRobot Create Open Interface Manual for numerical note definitions. Duration is interpreted as duration*1/64th of a second.""" if (len(song) > 32): song = song[:31] self.send(140,num,len(song)/2,*song) def playSong(self,num): """Plays a song. Takes one parameter, the song number.""" if (not self.songPlaying): self.send(141,num) def tank(self,left,right): """Drive the iCreate like a tank (i.e. left throttle, right throttle). Takes two parameters: left and right throttle. Each can be between -500 and 500 representing mm/s. If either are outside of this range, both throttles will be linearly scaled to fit inside the range""" if abs(left) > 500 or abs(right) > 500: maxThrottle = max(abs(left),abs(right)) left = 500*left/maxThrottle right = 500*right/maxThrottle lh,ll = self.__convert(left) rh,rl = self.__convert(right) self.send(145,rh,rl,lh,ll) def forwardTurn(self,speed,radius): """Takes two parameters: speed and radius. Drives the iCreate at speed with enough of an angle that the iCreate will carve a circle with the given radius. Speed is in mm/s and can vary between -500 and 500. The radius can vary between -2000 and 2000 mm (with negative mm turning left).""" if (speed > 500): speed = 500 if (speed < -500): speed = -500 if (not (radius == 0x8000 or radius == 0x7FF or radius == 0xFFFF or radius == 0x001) and (radius > 2000 or radius < -2000)): if (radius > 2000): radius = 2000 if (radius < -2000): radius = -2000 vh,vl = self.__convert(speed) rh,rl = self.__convert(radius) self.send(137,vh,vl,rh,rl) def turn(self,speed): self.right(speed) def right(self,speed): """Takes in a parameter: speed and turns clockwise in place at speed mm/s.""" self.forwardTurn(speed,0xFFFF) def left(self,speed): """Takes in a parameter: speed and turns counter-clockwise in place at speed mm/s.""" self.forwardTurn(speed,0x0001)
if options.disk: # Simple copy to the mbed disk copy(bin_file, options.disk) if options.serial: # Import pyserial: https://pypi.python.org/pypi/pyserial from serial import Serial sleep(TARGET_MAP[mcu].program_cycle_s) serial = Serial(options.serial, timeout=1) if options.baud: serial.setBaudrate(options.baud) serial.flushInput() serial.flushOutput() try: serial.sendBreak() except: # In linux a termios.error is raised in sendBreak and in setBreak. # The following setBreak() is needed to release the reset signal on the target mcu. try: serial.setBreak(False) except: pass while True: c = serial.read(512) sys.stdout.write(c) sys.stdout.flush()
class FnordBus: #con = None #lock = None # These three variables hold a "bus color". The controller has the ability # to let all the lights on bus display this color. It is controlled via # the appropriate functions (setRGB, getRGB and update) red = 0 green = 0 blue = 0 lights = None def __init__(self, serial_port, doReset = True): self.con = Serial( port=serial_port, baudrate=19200, bytesize=EIGHTBITS, stopbits=STOPBITS_ONE ) self.con.open() self.lock = Lock() self.lights = [] # The controller creates individual FnordLight objects for each # FnordLight on the bus for x in range(LIGHTCOUNT): self.lights.append(FnordLight(self, x)) if doReset: self.reset() #=========================================================================== # resetBus # Resets the bus #=========================================================================== def reset(self): self.sync() self.stop() #=========================================================================== # getFnordLight # Returns a specific FnordLight from the bus #=========================================================================== def getFnordLight(self, number): return self.lights[number] #=========================================================================== # getFnordLights # Returns all FnordLights from the bus #=========================================================================== def getFnordLights(self): return self.lights #=========================================================================== # setRGB # Sets the "bus color" #=========================================================================== def setRGB(self, r, g, b): if DEBUG: print("setRGB1 (%s, %s, %s)") % (self.red, self.green, self.blue) self.red = r self.green = g self.blue = b if DEBUG: print("setRGB2 (%s, %s, %s)") % (self.red, self.green, self.blue) #=========================================================================== # getRGB # Return the current "bus color" #=========================================================================== def getRGB(self): if DEBUG: print("getRGB (%s, %s, %s)") % (self.red, self.green, self.blue) return (self.red, self.green, self.blue) #=========================================================================== # update # Instructs all FnordLights to fade to the current "bus color" #=========================================================================== def update(self): if DEBUG: print("update (%s, %s, %s)") % (self.red, self.green, self.blue) self.fade_rgb(255, self.red, self.green, self.blue) #=========================================================================== # flush # Flushes the serial buffer in order to write all the bytes out on the bus. #=========================================================================== def flush(self): self.con.flushInput() self.con.flushOutput() #=========================================================================== # sync # Send a sync signal on the bus #=========================================================================== def sync(self, addr = 0): self.lock.acquire() for x in range(15): self.con.write( chr(27) ) self.con.write( chr( int(addr) ) ) self.flush() self.lock.release() #=========================================================================== # zeros # Helper function to send zeros over the wire #=========================================================================== def zeros(self, count = 8): for x in range( int(count) ): self.con.write( chr(0) ) #=========================================================================== # fade_rgb # Fade the FnordLight no. addr to the color (r, g, b) with the optional # step and delay. #=========================================================================== def fade_rgb(self, addr, r, g, b, step = 5, delay = 0): self.lock.acquire() self.con.write( chr( int(addr) ) ) self.con.write(chr(1) ) self.con.write( chr( int(step) ) ) self.con.write( chr( int(delay) ) ) self.con.write( chr( int(r) ) ) self.con.write( chr( int(g) ) ) self.con.write( chr( int(b) ) ) self.zeros() self.flush() self.lock.release() #=========================================================================== # stop # Stop the fading on the whole bus if no addr is specified. #=========================================================================== def stop(self, addr = 255, fading = 1): self.lock.acquire() self.con.write( chr( int(addr) ) ) self.con.write( chr(8) ) self.con.write( chr( int(fading) ) ) self.zeros(12) self.flush() self.lock.release() #=========================================================================== # start_program # Starts a predefined program #=========================================================================== def start_program(self, addr, program, params): self.lock.acquire() self.con.write( chr( int(addr) ) ) self.con.write( chr(7) ) self.con.write( chr( int(program) ) ) chrcount = 12 - len(params) for param in params: self.con.write( chr( int(param) ) ) self.zeros(chrcount) self.flush() self.lock.release() #=========================================================================== # black # Fades the entire bus to black if no addr is specified. #=========================================================================== def black(self, addr = 255): self.fade_rgb(addr, 0, 0, 0)
def __init__(self): try: rospy.init_node('RiCTraffic') params = RiCParam() ser = Serial('/dev/%s' % params.getConPort()) ser.flushInput() ser.flushOutput() incomingHandler = IncomingHandler() input = ser output = SerialWriteHandler(ser, incomingHandler, input) data = [] toPrint = '' input.baudrate = 9600 incomingLength = 0 headerId = 0 devBuilder = DeviceBuilder(params, output, input, incomingHandler) gotHeaderStart = False gotHeaderDebug = False msgHandler = None server = None rospy.loginfo("Current version: %.2f" % VERSION) try: self.waitForConnection(output) if self.checkVer(input): input.timeout = None rospy.loginfo("Configuring devices...") devBuilder.createServos() devBuilder.createCLMotors() devBuilder.createDiff() devBuilder.createURF() devBuilder.createSwitchs() devBuilder.createIMU() devBuilder.createRelays() devBuilder.createGPS() devBuilder.createPPM() devBuilder.createOpenLoopMotors() devBuilder.createBattery() devBuilder.createOpenDiff() devBuilder.createDiffFour() devs = devBuilder.getDevs() devBuilder.sendFinishBuilding() input.timeout = None rospy.loginfo("Done, RiC Board is ready.") msgHandler = IncomingMsgHandler(devs, output) server = Server(devs, params) Thread(target=self.checkForSubscribers, args=(devs,)).start() Thread(target=msgHandler.run, args=()).start() while not rospy.is_shutdown(): if gotHeaderStart: if len(data) < 1: data.append(input.read()) incomingLength, headerId = incomingHandler.getIncomingHeaderSizeAndId(data) elif incomingLength >= 1: for i in range(1, incomingLength): data.append(input.read()) # print data msg = self.genData(data, headerId) if msg is not None: msgHandler.addMsg(msg) data = [] gotHeaderStart = False else: data = [] gotHeaderStart = False elif gotHeaderDebug: size = ord(input.read()) for i in xrange(size): toPrint += input.read() code = ord(input.read()) if code == INFO: rospy.loginfo(toPrint) elif code == ERROR: rospy.logerr(toPrint) elif code == WARRNING: rospy.logwarn(toPrint) toPrint = '' gotHeaderDebug = False else: checkHead = ord(input.read()) if checkHead == HEADER_START: gotHeaderStart = True elif checkHead == HEADER_DEBUG: gotHeaderDebug = True else: raise VersionError(NEED_TO_UPDATE) except KeyboardInterrupt: pass except VersionError: rospy.logerr("Can't load RiCBoard because the version don't mach please update the firmware.") except: pass finally: con = ConnectionResponse(False) output.writeAndWaitForAck(con.dataTosend(), RES_ID) ser.close() if msgHandler != None: msgHandler.close() except SerialException: rospy.logerr("Can't find RiCBoard, please check if its connected to the computer.")
class BtleThreadCollectionPoint(object): def __init__(self, clientEventHandler, btleConfig, loggingQueue, debugMode=False): # Logger self.loggingQueue = loggingQueue self.logger = ThreadsafeLogger(loggingQueue, __name__) self.btleConfig = btleConfig self.clientEventHandler = clientEventHandler self.debug = debugMode # define basic BGAPI parser self.bgapi_rx_buffer = [] self.bgapi_rx_expected_length = 0 def start(self): packet_mode = False # create BGLib object self.ble = BGLib() self.ble.packet_mode = packet_mode self.ble.debug = self.debug # add handler for BGAPI timeout condition (hopefully won't happen) self.ble.on_timeout += self.my_timeout # on busy hander self.ble.on_busy = self.on_busy # add handler for the gap_scan_response event self.ble.ble_evt_gap_scan_response += self.clientEventHandler # create serial port object and flush buffers self.logger.info( "Establishing serial connection to BLED112 on com port %s at baud rate %s" % (self.btleConfig['BtleDeviceId'], self.btleConfig['BtleDeviceBaudRate'])) self.serial = Serial(port=self.btleConfig['BtleDeviceId'], baudrate=self.btleConfig['BtleDeviceBaudRate'], timeout=1) self.serial.flushInput() self.serial.flushOutput() # disconnect if we are connected already self.ble.send_command(self.serial, self.ble.ble_cmd_connection_disconnect(0)) self.ble.check_activity(self.serial, 1) # stop advertising if we are advertising already self.ble.send_command(self.serial, self.ble.ble_cmd_gap_set_mode(0, 0)) self.ble.check_activity(self.serial, 1) # stop scanning if we are scanning already self.ble.send_command(self.serial, self.ble.ble_cmd_gap_end_procedure()) self.ble.check_activity(self.serial, 1) # set the TX # range 0 to 15 (real TX power from -23 to +3dBm) #self.ble.send_command(self.serial, self.ble.ble_cmd_hardware_set_txpower(self.btleConfig['btleDeviceTxPower'])) #self.ble.check_activity(self.serial,1) #ble_cmd_connection_update connection: 0 (0x00) interval_min: 30 (0x001e) interval_max: 46 (0x002e) latency: 0 (0x0000) timeout: 100 (0x0064) #interval_min 6-3200 #interval_man 6-3200 #latency 0-500 #timeout 10-3200 self.ble.send_command( self.serial, self.ble.ble_cmd_connection_update(0x00, 0x001e, 0x002e, 0x0000, 0x0064)) self.ble.check_activity(self.serial, 1) # set scan parameters #scan_interval 0x4 - 0x4000 #Scan interval defines the interval when scanning is re-started in units of 625us # Range: 0x4 - 0x4000 # Default: 0x4B (75ms) # After every scan interval the scanner will change the frequency it operates at # at it will cycle through all the three advertisements channels in a round robin # fashion. According to the Bluetooth specification all three channels must be # used by a scanner. # #scan_window 0x4 - 0x4000 # Scan Window defines how long time the scanner will listen on a certain # frequency and try to pick up advertisement packets. Scan window is defined # as units of 625us # Range: 0x4 - 0x4000 # Default: 0x32 (50 ms) # Scan windows must be equal or smaller than scan interval # If scan window is equal to the scan interval value, then the Bluetooth module # will be scanning at a 100% duty cycle. # If scan window is half of the scan interval value, then the Bluetooth module # will be scanning at a 50% duty cycle. # #active 1=active 0=passive # 1: Active scanning is used. When an advertisement packet is received the # Bluetooth stack will send a scan request packet to the advertiser to try and # read the scan response data. # 0: Passive scanning is used. No scan request is made. #self.ble.send_command(self.serial, self.ble.ble_cmd_gap_set_scan_parameters(0x4B,0x32,1)) self.ble.send_command( self.serial, self.ble.ble_cmd_gap_set_scan_parameters(0xC8, 0xC8, 0)) self.ble.check_activity(self.serial, 1) # start scanning now self.ble.send_command(self.serial, self.ble.ble_cmd_gap_discover(1)) self.ble.check_activity(self.serial, 1) # handler to notify of an API parser timeout condition def my_timeout(self, sender, args): self.logger.error( "BGAPI timed out. Make sure the BLE device is in a known/idle state." ) # might want to try the following lines to reset, though it probably # wouldn't work at this point if it's already timed out: self.ble.send_command(self.serial, self.ble.ble_cmd_system_reset(0)) self.ble.check_activity(self.serial, 1) self.ble.send_command(self.serial, self.ble.ble_cmd_gap_discover(1)) self.ble.check_activity(self.serial, 1) def on_busy(self, sender, args): self.logger.warn("BGAPI device is busy.") def scan(self): # check for all incoming data (no timeout, non-blocking) self.ble.check_activity(self.serial)
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") parser.add_option("-r", "--reset", dest="forced_reset_type", help="Forces different type of reset") parser.add_option("-R", "--reset-timeout", dest="forced_reset_timeout", metavar="NUMBER", type="int", help="When forcing a reset using option -r you can set up after reset timeout in seconds") (self.options, _) = parser.parse_args() self.DEFAULT_RESET_TOUT = 0 self.DEFAULT_TOUT = 10 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 = self.DEFAULT_TOUT if self.options.timeout is None else self.options.timeout print 'Host test instrumentation on port: "%s" and disk: "%s"' % (self.port, self.disk) def init_serial(self, baud=9600, extra_baud=9600): """ Initialize serial port. Function will return error is port can't be opened or initialized """ result = True try: self.serial = Serial(self.port, timeout=1) except Exception as e: result = False # Port can be opened if result: 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() return result def serial_timeout(self, timeout): """ Wraps self.mbed.serial object timeout property """ result = None if self.serial: self.serial.timeout = timeout result = True return result def serial_read(self, count=1): """ Wraps self.mbed.serial object read method """ result = None if self.serial: try: result = self.serial.read(count) except: result = None return result def serial_readline(self, timeout=5): """ Wraps self.mbed.serial object read method to read one line from serial port """ result = '' start = time() while (time() - start) < timeout: if self.serial: try: c = self.serial.read(1) result += c except: result = None break if c == '\n': break return result def serial_write(self, write_buffer): """ Wraps self.mbed.serial object write method """ result = None if self.serial: try: result = self.serial.write(write_buffer) except: result = None return result def touch_file(self, path): """ Touch file and set timestamp to items """ with open(path, 'a'): os.utime(path, None) def reset_timeout(self, timeout): """ Timeout executed just after reset command is issued """ for n in range(0, timeout): sleep(1) def reset(self): """ Calls proper reset plugin to do the job. Please refer to host_test_plugins functionality """ # Flush serials to get only input after reset self.flush() if self.options.forced_reset_type: host_tests_plugins.call_plugin('ResetMethod', self.options.forced_reset_type, disk=self.disk) else: host_tests_plugins.call_plugin('ResetMethod', 'default', serial=self.serial) # Give time to wait for the image loading reset_tout_s = self.options.forced_reset_timeout if self.options.forced_reset_timeout is not None else self.DEFAULT_RESET_TOUT self.reset_timeout(reset_tout_s) def flush(self): """ Flush serial ports """ if self.serial: self.serial.flushInput() self.serial.flushOutput() if self.extra_serial: self.extra_serial.flushInput() self.extra_serial.flushOutput()
class LaserRangeFinder: ''' This class represents and allows access to a Hukuyo URG-04LX Laser Range Finder. ''' def __init__(self, serial = '/dev/ttyACM0', baud_rate = '115200', start = 000, stop = 768, step = 00, config = None): if config: self.config = config self.serial_port = config['serial_port'] self.baud_rate = config['baud_rate'] self.start = config['start'] self.stop = config['stop'] self.step = config['step'] else: self.config = None self.serial_port = serial self.baud_rate = baud_rate self.start = start self.stop = stop self.step = step if enabled: self.serial = Serial() self.serial.port = self.serial_port self.serial.baud_rate = self.baud_rate self.serial.timeout = 1 try: self.serial.open() except Exception as e: log.error("Unabled to open the serial port %s: %s" % (self.serial_port, e)) #Threading self.monitor_event = Event() self.monitor = LaserMonitor(self) self.monitor.start() self.set_monitor_settings() #End __init__ def scan(self, start = None, stop = None, step = None): """ This function will scan from start to stop, returning a reading for every step number of scans. """ if not enabled: return if start is None: start = self.start if stop is None: stop = self.stop if step is None: step = self.step result = [] # Generate the command command = 'G'+start+stop+step+'\r' # Send the command self.serial.write(command) # Retrieve data # Burn the first two lines. self.serial.readline() self.serial.readline() line = self.serial.readline() # While there is no empty line return, ('\n'), continue processing data while (line != '\n'): # While we haven't reached the end of the line i = 0 while (line[i] != '\n'): dist = (ord(line[i]) - 48) << 6 i += 1 dist += ord(line[i]) - 48 i += 1 result.append(dist) line = self.serial.readline() # Return the resulting list of distances return result def check_for_obj(self): data = self.scan()[self.mstart:self.mstop] array = [self.mstart] array.extend(data) #datalog.info(toStringFormat('Sorter', 'Position', array)) for x in range(len(data)): if data[x] > self.mrange: data[x] = 0 potential_spikes = [] for x in range(1, len(data)): if abs(data[x] - data[x-1]) > self.mspike: potential_spikes.append(x) spikes = [] s1 = None for x in range(len(potential_spikes)-1): if potential_spikes[x+1] - potential_spikes[x] >= self.mwidth: if s1 is None: s1 = potential_spikes[x] else: spikes.append((s1, potential_spikes[x])) s1 = None if s1 != None: spikes.append((s1, potential_spikes[len(potential_spikes)-1])) s1 = None result = [] for x,y in spikes: mid = (x+y)/2 if data[mid-1] > 0: log.debug("Object from Laser (r, theta): %d, %d" % (data[mid-1], (mid+self.mstart-384)/3)) temp_r, temp_t = self.translate_to_robot(data[mid-1], mid+self.mstart-384) result.append((temp_r, temp_t)) return result def translate_to_robot(self, r, t): vlrx = 127.47 vlry = 120.65 t_r = math.radians(t/3) vloy = math.cos(t_r)*r vlox = math.sin(t_r)*r vrox = vlrx + vlox vroy = vlry + vloy # convert back to polar theta = math.atan(vrox/vroy) theta = math.degrees(theta) magnitude = math.sqrt(math.pow(vroy, 2) + math.pow(vrox, 2)) return magnitude, theta def set_monitor_settings(self, angle = 30, range = 600, spike = 50, width = 5): self.mstart = 384-(angle*3) self.mstop = 384+(angle*3) self.mrange = range self.mspike = spike self.mwidth = width def monitor_obstacles(self): self.monitor_event.set() def clear(self): """This function clears all input/output buffers from the serial device.""" if not enabled: return if self.serial.isOpen(): self.serial.flushOutput() self.serial.flushInput() def shutdown(self): log.info("Laser Range Finder shutting down.") if not enabled: return self.monitor.shutdown() self.monitor.join() if self.serial.isOpen(): self.serial.flushInput() self.serial.flushOutput() self.serial.close()
print ("Python is opening port:\n\tSerial(\"/dev/cu.SLAB_USBtoUART\", 1200)") serialPort.open() else: print ("Python sees that the port:\n\tSerial(\"/dev/cu.SLAB_USBtoUART\", 1200)\n\n\tis already open.") print ('Number of arguments:', len(sys.argv), 'arguments.') print 'Argument List:', str(sys.argv) argList = str(sys.argv) if (len(sys.argv) > 1): sendStr = sys.argv[1] else: sendStr = "null" serialPort.flushInput() serialPort.flushOutput() print("\nPython will attempt to send string: " + sendStr) byteData = bytes((sendStr, 'UTF-8')) byteData = bytes("sendStr, 'UTF-8'") byteData = sendStr.encode("UTF-8") byteArr = bytearray(sendStr) #serialPort.write("test") #numBytesSent = serialPort.write( byteData ) #numBytesSent = serialPort.write( sendStr ) numBytesSent = serialPort.write( byteArr ) time.sleep(8)//seconds #serialPort.flush() # bytesLeft = serialPort.outWaiting() # print bytesLeft # while ( bytesLeft > 0):