Exemple #1
0
def main():
    dump_to_file('=======================================\n')
    list_ports()
    filepath_list = read_all('kanzhitongxue/neg')
    with serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=5) as ser:
        res = test_feature_all(filepath_list, ser, cb=dump_feature_to_file)
    np.save('output.npy', res)
Exemple #2
0
def init_serial():
    global s1, s2, chirp

    list_ports()

    port = input("enter port:")
    s1 = dev(port)
    port = input("enter port:")
    s2 = dev(port)

    freq_start = 20000
    freq_stop = 20000
    pulse_width = 5e-3
    update_params_on_device(freq_start, freq_stop, pulse_width)
  def __init__(self, port=DEFAULT_PORT, baud=DEFAULT_BAUD, use_ftdi=False, print_unhandled=False):
    self.print_unhandled = print_unhandled
    self.unhandled_bytes = 0
    self.callbacks = {}
    if use_ftdi:
      import pylibftdi
      self.ser = pylibftdi.Device()
      self.ser.baudrate = baud
    else:
      import serial
      try:
        self.ser = serial.Serial(port, baud, timeout=1)
        print "Opened serial device '%s'" % port 
      except serial.SerialException:
        print
        print "Serial device '%s' not found" % port
        print
        print "The following serial devices were detected:"
        print
        for p in list_ports():
          p_name, p_desc, _ = p
          if p_desc == p_name:
            print "\t%s" % p_name
          else:
            print "\t%s (%s)" % (p_name, p_desc)
        sys.exit(1)

    # Delay then flush the buffer to make sure the receive buffer starts empty.
    time.sleep(0.5)
    self.ser.flush()

    self.lt = ListenerThread(self, print_unhandled)
    self.lt.start()
def main():

    print("""
    1. Enter Arduino COM_PORT
    2. List COM_PORT(s) (under devlopment)
    3. View log file
    4. Quit
    """)

    while True:

        if keyboard.is_pressed('1'):
            print('\n')
            logging.info("User started function: start_comm")
            com_port = input("Enter com_port: " + "COM6")
            start_comm(com_port)
        elif keyboard.is_pressed('2'):
            print('\n')
            logging.info("User started function: list_port")
            print(list_ports())
        elif keyboard.is_pressed('3'):
            print('\n')
            logging.info("User started function: view_log")
            view_log()
        elif keyboard.is_pressed('4'):
            print('\n')
            logging.info("User started function: quit()")
            quit()
def execute(command=None):
    try:
        ser = list_ports()
    except:
        print('Initialise - Failed')
        ser.close()
        return
    try:
        # res = command_check(command)
        #     print('\t'+'Available Commands:')
        #     print('\t'*2+'SHOW DEGREE          : RETURN VALUES OF EACH SERVO')
        #     print('\t'*2+'HELP                 : HELP LIST')
        #     print('\t'*2+'QUIT                 : QUIT SCRIPT' )
        #     print('\t'*2+'SET %SETVO %DEGREE   : SET DEGREE OF A SERVO DIRECTLY; e.g. SET F 45 ')
        #     print('\t'*2+'ADD %SETVO %DEGREE   : ADD DEGREE OF A SERVO; e.g. ADD F 10 ')
        #     print('\t'*2+'MINUS %SETVO %DEGREE : MINUS DEGREE OF A SERVO; e.g. MINUS F 10 ')
        ser.write(command.encode())
        s = ser.readlines(40)
        # if type(s) == str:
        #     print('\t'+s.decode('utf-8'))
        # else:
        #     for i in range(len(s)):
        #         print('\t'+s[i].decode('utf-8'))
        #     print()
    except:
        print('ERROR!')
        ser.close()
    command = None
    ser.close()
Exemple #6
0
def find_port(filters=DEFAULT_PORT_FILTERS, excluded_ports=[], ports=None):
    """Find a port by the provided filter predicates in order of preference."""
    if ports is None:
        ports = list_ports()
    for filter in filters:
        for (device, properties) in ports.items():
            if filter(properties) and (device not in excluded_ports):
                return (device, properties)
Exemple #7
0
def main():
    parser = argparse.ArgumentParser(
        description='Read the given Arduino serial port')
    parser.add_argument('--log_level',
                        action='store',
                        default='DEBUG',
                        help='Logging level')
    parser.add_argument('--port',
                        action='store',
                        default='/dev/ttyUSB0',
                        help='port')
    parser.add_argument('--baud',
                        action='store',
                        default='115200',
                        help='baud')
    parser.add_argument('--list',
                        action='store_true',
                        help='List the available ports (default)')
    parser.add_argument('--test',
                        action='store_true',
                        help='Verify an AUnit test')
    parser.add_argument('--monitor',
                        action='store_true',
                        help='Monitor the serial port')
    parser.add_argument('--eof',
                        action='store',
                        default='',
                        help='End of File string')
    parser.add_argument('--timeout',
                        action='store',
                        default=TIMEOUT_ON_IDLE,
                        help='End of File string')
    args = parser.parse_args()

    # Configure logging.
    logging.basicConfig(level=args.log_level,
                        format=LOG_FORMAT,
                        datefmt=DATE_FORMAT)

    if args.monitor:
        monitor(args.port, args.baud, args.eof, args.timeout)
    elif args.test:
        validate_test(args.port, args.baud, args.timeout)
    else:
        list_ports()
Exemple #8
0
 def atualizarUSB(self, button):
     self.comboBox.destroy()
     self.comboBox = Gtk.ComboBox.new_with_model(list_ports())
     renderer = Gtk.CellRendererText()
     self.comboBox.set_active(0)
     self.comboBox.pack_start(renderer, True)
     self.comboBox.add_attribute(renderer, 'text', 1)
     self.sensor.attach(self.comboBox, 0, 2, 2, 1)
     win.show_all()
Exemple #9
0
def all_set_init():  # 获得初始数据给Robot类
    print('Initialising...')
    try:
        ser = list_ports()
        # ser = initialize()
        print('Initialised')
    except:
        print('Initialise - Failed')
        ser.close()
        return
    command = "SHOW DEGREE"
    # command = "SET A 45"
    ser.write(command.encode())
    s = ser.readlines(40)
    nums = re.findall(r"\d+", s[1])
    nums = map(int, nums)  # 将list转化为int
    return ser, nums
Exemple #10
0
def execute(command=None):    
    print('Initialising...')
    try:
        #ser = initialize()
        ser = list_ports()
        print('Initialised')
    except:
        print('Initialise - Failed')
        ser.close()
        return 
    while True:
        try:
            if command == None:
                command = raw_input('BRobot: ') 
            else:
                pass
            res = command_check(command)
            if res == 'Command ERROR':
                print('\t' + res)
                print('Try type "HELP"')
                command = None
                continue
            elif res == 'HELP':
                print('\t'+'Available Commands:')
                print('\t'*2+'SHOW DEGREE          : RETURN VALUES OF EACH SERVO')
                print('\t'*2+'HELP                 : HELP LIST')
                print('\t'*2+'QUIT                 : QUIT SCRIPT' )
                print('\t'*2+'SET %SETVO %DEGREE   : SET DEGREE OF A SERVO DIRECTLY; e.g. SET F 45 ')
                print('\t'*2+'ADD %SETVO %DEGREE   : ADD DEGREE OF A SERVO; e.g. ADD F 10 ')
                print('\t'*2+'MINUS %SETVO %DEGREE : MINUS DEGREE OF A SERVO; e.g. MINUS F 10 ')
            elif res == 'QUIT':
                break
            else:
                ser.write(command.encode())    
                s = ser.readlines(40)
                if type(s) == str:
                    print('\t'+s.decode('utf-8'))
                else:
                    for i in range(len(s)):
                        print('\t'+s[i].decode('utf-8'))
                    print()
        except:
            print('ERROR!')
            ser.close()
        command = None
    ser.close()
Exemple #11
0
    def connect(self):
        self.close()

        ports = list_ports()

        if len(ports) <= 0:
            return False

        try:
            self.obj = serial.Serial(port=ports[0], baudrate=self.baud)

            if not self.connected():
                self.close()
                return False

            return True

        except Exception as error:
            print(error)
            return False
def json_handle_portslist(*msg):

    try:
        ports = list_ports()
        ports.append("dummy")  # always add dummy for testing

        json = {
            'jsonrpc': '2.0',
            'id': 6,
            'method': "serial-ports-list",
            'params': {
                'time': time() * 1000,
                'message': ports
            }
        }
    except Exception as e:
        # TODO: fix this to be a real error type so it gets sent to the clients properly
        Logger.log("e", "could not get serial ports list: {}".format(repr(e)))
        raise ValueError("could not get  serial ports list: {}".format(
            repr(e)))

    return json
Exemple #13
0
    def __init__(self,
                 port=DEFAULT_PORT,
                 baud=DEFAULT_BAUD,
                 use_ftdi=False,
                 print_unhandled=False):
        self.print_unhandled = print_unhandled
        self.unhandled_bytes = 0
        self.callbacks = {}
        self.global_callbacks = []
        if use_ftdi:
            import pylibftdi
            self.ser = pylibftdi.Device()
            self.ser.baudrate = baud
        else:
            import serial
            try:
                self.ser = serial.Serial(port, baud, timeout=1)
            except serial.SerialException:
                print
                print "Serial device '%s' not found" % port
                print
                print "The following serial devices were detected:"
                print
                for p in list_ports():
                    p_name, p_desc, _ = p
                    if p_desc == p_name:
                        print "\t%s" % p_name
                    else:
                        print "\t%s (%s)" % (p_name, p_desc)
                sys.exit(1)

        # Delay then flush the buffer to make sure the receive buffer starts empty.
        time.sleep(0.5)
        self.ser.flush()

        self.lt = ListenerThread(self, print_unhandled)
        self.lt.start()
Exemple #14
0
def main():
    # create argparse object - set automatic help to false
    parser = argparse.ArgumentParser(add_help=False)
    
    # add arguments to parse 
    parser.add_argument("-h", "--help", action="store_true")
    parser.add_argument("-v", "--version", help="",action="store_true")    
    parser.add_argument("-p", "--port", help="")
    parser.add_argument("-m", "--message", help="")
    parser.add_argument("-t", "--timeout", help="", type=float)
    parser.add_argument("-l", "--list", help="",action="store_true")
    parser.add_argument("-q", "--quiet", help="",action="store_true")
    
    # parse arguments
    args = parser.parse_args()
    
    # if --help / -h print help and exit
    if args.help:
        print_help()
        sys.exit(0)
        
    if args.list:
        list_ports()
        sys.exit(0)
    
    # if --version / -v print version information and exit
    if args.version:
        print_version()
        sys.exit(0)
    
    else:
        # if --message / -m ...
        if args.message:
            # set test message 
            msg = args.message
        else:
            msg = "D"
        
        #if --timeout / -t ...
        if args.timeout:
            # set timeout
            tout = args.timeout
        else:
            tout = 1
        
        #if --port / -p ...   
        if args.port:
            pserie = args.port
        else:
            pserie = '/dev/ttyUSB0'

    # try to open port
    # if not possible lists available ports
    try:
        ser = serial.Serial(pserie, timeout=tout)
    except serial.serialutil.SerialException, mensaje:
        print mensaje
        print "Could not open port..."

        list_ports()
        
        raise SystemExit
Exemple #15
0
    def __init__(self):
        Gtk.Window.__init__(self,
                            title="Seguidor de Linha - Robot Arena 2020.2")
        self.set_border_width(10)

        self.maing = Gtk.Grid()
        self.maing.set_column_spacing(50)
        self.maing.set_row_spacing(25)
        self.add(self.maing)

        # SENSOR ---------------------------------
        self.sensor = Gtk.Grid()
        self.sensor.set_column_spacing(10)
        self.sensor.set_row_spacing(10)
        self.maing.attach(self.sensor, 0, 1, 1, 1)

        self.label = Gtk.Label()
        self.label.set_markup("<big>Sensor</big>")
        self.label.set_justify(Gtk.Justification.CENTER)
        self.sensor.attach(self.label, 0, 0, 2, 1)

        self.conlabel = Gtk.Label()
        self.conlabel.set_markup(
            '<span foreground="red"><big><b>Desconectado</b></big></span>')
        self.conlabel.set_justify(Gtk.Justification.CENTER)
        self.sensor.attach(self.conlabel, 0, 1, 2, 1)

        self.comboBox = Gtk.ComboBox.new_with_model(list_ports())
        renderer = Gtk.CellRendererText()
        self.comboBox.set_active(0)
        self.comboBox.pack_start(renderer, True)
        self.comboBox.add_attribute(renderer, 'text', 1)
        self.sensor.attach(self.comboBox, 0, 2, 2, 1)

        self.button = Gtk.Button.new_with_mnemonic("Atualizar")
        self.button.connect("clicked", self.atualizarUSB)
        self.sensor.attach(self.button, 0, 3, 1, 1)

        self.button = Gtk.Button.new_with_mnemonic("Conectar")
        self.button.connect("clicked", self.conectarUSB)
        self.sensor.attach(self.button, 1, 3, 1, 1)

        # GRID ---------------------------------
        self.grid = Gtk.Grid()
        self.grid.set_column_spacing(2)
        self.grid.set_row_spacing(10)
        self.maing.attach(self.grid, 1, 1, 1, 1)

        img = Gtk.Image.new_from_file('./logo.png')
        self.grid.attach(img, 0, 1, 3, 1)

        self.nome = Gtk.Label()
        self.nome.set_markup(
            '<big><b><span foreground="red">Selecione um competidor</span></b></big>'
        )
        self.nome.set_justify(Gtk.Justification.CENTER)
        self.grid.attach(self.nome, 0, 2, 5, 1)

        self.tempo1 = Gtk.Label()
        self.tempo1.set_markup("1ª Tentativa\n<big><b>- s</b></big>")
        self.tempo1.set_justify(Gtk.Justification.CENTER)
        self.grid.attach(self.tempo1, 0, 4, 1, 1)

        self.button = Gtk.Button.new_with_mnemonic("Autorizar")
        self.button.connect("clicked", self.autorizar, 1)
        self.grid.attach(self.button, 0, 5, 1, 1)

        self.button = Gtk.Button.new_with_mnemonic("Resetar")
        self.button.connect("clicked", self.resetar, 1)
        self.grid.attach(self.button, 0, 6, 1, 1)

        self.tempo2 = Gtk.Label()
        self.tempo2.set_markup("2ª Tentativa\n<big><b>- s</b></big>")
        self.tempo2.set_justify(Gtk.Justification.CENTER)
        self.grid.attach(self.tempo2, 1, 4, 1, 1)

        self.button = Gtk.Button.new_with_mnemonic("Autorizar")
        self.button.connect("clicked", self.autorizar, 2)
        self.grid.attach(self.button, 1, 5, 1, 1)

        self.button = Gtk.Button.new_with_mnemonic("Resetar")
        self.button.connect("clicked", self.resetar, 2)
        self.grid.attach(self.button, 1, 6, 1, 1)

        self.tempo3 = Gtk.Label()
        self.tempo3.set_markup("3ª Tentativa\n<big><b>- s</b></big>")
        self.tempo3.set_justify(Gtk.Justification.CENTER)
        self.grid.attach(self.tempo3, 2, 4, 1, 1)

        self.button = Gtk.Button.new_with_mnemonic("Autorizar")
        self.button.connect("clicked", self.autorizar, 3)
        self.grid.attach(self.button, 2, 5, 1, 1)

        self.button = Gtk.Button.new_with_mnemonic("Resetar")
        self.button.connect("clicked", self.resetar, 3)
        self.grid.attach(self.button, 2, 6, 1, 1)

        # SCORE ---------------------------------
        self.score = Gtk.Grid()
        self.score.set_column_spacing(2)
        self.score.set_row_spacing(10)
        self.maing.attach(self.score, 2, 1, 1, 1)

        self.label = Gtk.Label()
        self.label.set_markup("<big>Placar</big>")
        self.label.set_justify(Gtk.Justification.CENTER)
        self.score.attach(self.label, 0, 0, 3, 1)

        self.entry = Gtk.Entry()
        self.score.attach(self.entry, 0, 1, 2, 1)

        self.button = Gtk.Button.new_with_mnemonic("Adicionar")
        self.button.connect("clicked", self.addChallenger)
        self.score.attach(self.button, 2, 1, 1, 1)

        # SPONSORS ---------------------------------
        self.sponsors = Gtk.Grid()
        self.sponsors.set_column_spacing(2)
        self.sponsors.set_row_spacing(2)
        self.maing.attach(self.sponsors, 0, 2, 1, 3)

        self.label = Gtk.Label()
        self.label.set_markup("<big>Patrocinadores</big>")
        self.label.set_justify(Gtk.Justification.CENTER)
        self.sponsors.attach(self.label, 0, 1, 3, 1)

        # Variáveis
        self.tentativa = 0
        self.start = 0
        self.threadID = 0
        self.Trig = False
        self.selectedIndex = 0
        self.t = math.inf
        self.selected = []
Exemple #16
0
                                 action='store_true',
                                 help='Parse the training SES site')

    # Use headless browser
    parser.add_argument(
        '--headless',
        action='store_true',
        default=False,
        help='Use headless browser instead of popping a Firefox window')

    return parser.parse_args()


if __name__ == "__main__":
    """ This is executed when run from the command line """
    args = parseinput()
    if args.live:
        livesite = True
    if args.training:
        livesite = False

    # allows the operator to verify the speaker is working
    print('Saying speaker test...')
    #sayText('This is the S E S Rollout speaker test message!')

    # List available serial ports
    list_ports()

    #monitor_jobs_api(livesite)
    monitor_jobs_selenium(livesite, args.headless)
Exemple #17
0
def main(argv):
    port = 1
    baud = 115200
    outputfile = 'log'
    print 'CommTool V0.3'
    try:
        opts, args = getopt.getopt(argv,"hlp:o:b:",["help","list","port=","baudrate=","output="])
    except getopt.GetoptError:
        print 'Wrong arguments, try: python logtool.py -h'
        sys.exit(2)

    #parse the parameters input form console
    for opt, arg in opts:
        # print opt, args #debug only  
        if opt in ("-h", "--help"):
            print 'Usage: python logtool.py [OPTION]... [FILE]...'
            print 'python logtool.py -p <port> -b <baudrate> -o <logfile>'
            print 'If the <args> are not set, the default values are used:'
            print 'port = 1, baudrate = 115200, logfile = log.log'
            print 'Example: '
            print 'python logtool.py -p 2'
            print 'python logtool.py -p 1 -b 9600'
            print 'python logtool.py -p 1 -b 9600 -o mylog.log'
            print ''
            print 'Mandatory arguments to long options are mandatory for short options too.'
            print '-p, --port                       Uart port number'
            print '-b, --baudrate                   Baudrate for selected port'
            print '-o, --output                     Output file for storing the log'
            print '-h, --help                       Help doc'
            print '-l, --list                       List avaliable com ports'
            print ''
            #print 'python -m serial.tools.list_ports    --show the avaliable uart ports'
            sys.exit()
        elif opt in ("-p", "--port"):
            port = string.atoi(arg)
            if port < 0:
                print 'Port number error'
                sys.exit()
        elif opt in ("-b", "--baudrate"):
            baud = string.atoi(arg)
            print 'baud', baud
        elif opt in ("-o", "--output"):
            outputfile = arg + "_COM" + str(port) + ".log"
        elif opt in ("-l", "--list"):
			#print(serial_ports())
			list_ports()
        else:
            print 'Wrong pararmeters, try: python logtool.py -h'

    print 'Ctrl+C to exit'

    logger = logging.getLogger('LOG')
    logger.setLevel(logging.DEBUG)
    # create file handler which logs even debug messages
    fh = logging.FileHandler(outputfile)
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    # create formatter and add it to the handlers
    #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    formatter = logging.Formatter('%(asctime)s - %(message)s')
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    # add the handlers to logger
    logger.addHandler(ch)
    logger.addHandler(fh)

    console_color = Color()

    # 'application' code
    #logger.debug('debug message')
    #logger.info('info message')
    #logger.warn('warn message')
    #logger.error('error message')
    #logger.critical('critical message')

    try:
        ser = serial.Serial(port-1, baud, timeout=0)
        #print ser
    except:
        print 'Can\'t open uart', port
        sys.exit()

    toogle_color = False
    try:
        while True:
            start_time = datetime.now()
            cur_time = start_time
            last_time = start_time
            s = ''
            while True:
                cur_time = datetime.now()
                num = ser.inWaiting()
                if num > 0:
                    last_time = cur_time    
                    s += ser.read(num)
                else:
                    idle_time = cur_time - last_time
                    time.sleep(0.001)
                    if idle_time.microseconds > 10000:
                        break
            if s != '':
                if not toogle_color:
                    toogle_color = True
                    console_color.set_cmd_color(FOREGROUND_GREEN | FOREGROUND_INTENSITY)
                    logger.info(s)
                else:
                    toogle_color = False
                    console_color.reset_color()
                    logger.info(s)
                # console_color.print_green_text(start_time)
                # print s
    except:
        print 'Ctrl+C pressed'
    ser.close()
    console_color.reset_color()
    print 'Exit'
Exemple #18
0
    
args = parser.parse_args()
#convert our hex strings to ints
args.address = int(args.address,16)
args.offset = int(args.offset,16)

SERIAL_TIMEOUT = 10 #seconds
try:
    ser = serial.Serial(args.com, args.speed, timeout=SERIAL_TIMEOUT)
except serial.serialutil.SerialException:
    print("Error: Serial port is not valid, please select a valid port")
    sys.exit(1)

if args.cmd == 'write':
    write_eeprom(False)
elif args.cmd == 'write_paged':
    write_eeprom(True)
elif args.cmd == 'read':
    read_eeprom()
elif args.cmd == 'dump':
    dump_file()
elif args.cmd == 'verify':
    verify()
elif args.cmd == 'unlock':
    unlock();
elif args.cmd == 'list':
    list_ports()
    
ser.close()
sys.exit(0)
Exemple #19
0
import serial.tools.list_ports

# https://pythonhosted.org/pyserial/shortintro.html#opening-serial-ports

#SERIAL_PORT = '/dev/ttyAMA0'
SERIAL_RATE = 9600


def list_ports():
    list = serial.tools.list_ports.comports()
    connected = []
    for element in list:
        connected.append(element.device)
    print("Connected COM ports: " + str(connected))
    return connected


def main(connected):
    print(connected)
    ser = serial.Serial(connected, SERIAL_RATE)
    while True:
        # using ser.readline() assumes each line contains a single reading
        # sent using Serial.println() on the Arduino
        reading = ser.readline().decode('utf-8')
        # reading is a string...do whatever you want from here
        print(reading)


if __name__ == "__main__":
    connected = list_ports()
    main(connected)
Exemple #20
0
      time.sleep(delay)
    self.last_send = msg
    try:
      #self.com.write(msg + self.newline)
      #self.com.write(str(msg).encode())
      self.com.write(msg)
      return True
    except:
      self.error |= ERROR_SEND
      return False

  def receive(self):
    try:
      self.last_recv = self.com.readline()
      return self.last_recv
    except:
      self.error |= ERROR_RECV
      return ''

  def close(self):
    try:
      self.com.close()
      return True
    except:
      self.error |= ERROR_CLOSE
      return False

if __name__ == '__main__':  
  print('List of available ports')
  print( list_ports())
 def refresh_ports(self):
     self.port_list.clear()
     self.port_list.addItems([row[0] for row in list_ports()])
     self.port_list.setCurrentIndex(self.port_list.count()-1)
Exemple #22
0
def build_iterator():
    config_df = get_config()
    port_df = list_ports()
    config_df = config_df.merge(port_df,how='left',left_on='arduino_id', right_on='serial_number')
    config_df['environmental_value'] = np.nan
    return(config_df)
Exemple #23
0
def main():

    global quiet
    global color

    parser = argparse.ArgumentParser(description='Python Serial Monitor %s' %
                                     VERSION)

    parser.add_argument("-p",
                        "--port",
                        default="/dev/ttyACM0",
                        help="Serial port")

    parser.add_argument("-b",
                        "--baudrate",
                        type=int,
                        default=9600,
                        help="Serial baudrate")

    parser.add_argument(
        "-l",
        "--log",
        default=None,
        help="If a file is given, also write the received data to this log")

    parser.add_argument("-f",
                        "--format",
                        default='raw',
                        choices=['raw', 'line', 'hex', 'hexascii'],
                        help="Output format")

    parser.add_argument(
        "-w",
        "--wait",
        default=False,
        action="store_true",
        help="If given serial port is not available, wait until it shows up")

    parser.add_argument("-c",
                        "--color",
                        default=False,
                        action="store_true",
                        help="Use color for output")

    parser.add_argument("-t",
                        "--timestamp",
                        default=False,
                        action="store_true",
                        help="Add a timestamp to each line")

    parser.add_argument(
        "-q",
        "--quiet",
        default=False,
        action="store_true",
        help="Print nothing but serial log (no status or error messages)")

    parser.add_argument(
        "--hexbytes",
        default=16,
        type=int,
        help="Number of bytes displayed in each line when HEX format is choosen"
    )

    parser.add_argument("--listjson",
                        default=False,
                        action="store_true",
                        help="List of available serial ports in JSON format")

    parser.add_argument("--list",
                        default=False,
                        action="store_true",
                        help="List of available serial ports")

    parser.add_argument(
        "--persist",
        default=False,
        action="store_true",
        help="Restart and try to reconnect if serial connection drops")

    parser.add_argument("--version",
                        default=False,
                        action="store_true",
                        help="Print version")

    args = parser.parse_args()

    quiet = args.quiet
    color = args.color

    if args.version:
        print("Python Serial Monitor %s" % VERSION)
        exit(0)

    if args.listjson:

        print(json.dumps(list_ports()))
        exit(0)

    if args.list:

        print("")
        print("Available serial ports:")

        for p in list_ports()["ports"]:
            print(" * % -20s: %s" % (p["device"], p["description"]))

        print("")

        exit(0)

    clear_screen()

    xprint("Trying to connect to %s" % args.port)

    dots = False

    while True:
        istream = open_port(args.port, args.baudrate)

        if istream is not None or not args.wait:
            break

        if not quiet:
            sys.stdout.write(".")
            sys.stdout.flush()
        dots = True
        time.sleep(0.5)

    if dots:
        xprint("")

    if istream is not None:
        xprint("Successfully connected")
    else:
        xprint("Failed to connect", True)
        exit(1)

    ostream = sys.stdout
    reader = SerialReader(istream)

    if args.format == 'line':

        writer = LineWriter(ostream)

    elif args.format == 'hex':

        writer = HexWriter(ostream)
        writer.max_length = args.hexbytes
        writer.write_ascii = False

    elif args.format == 'hexascii':

        writer = HexWriter(ostream)
        writer.max_length = args.hexbytes
        writer.write_ascii = True

    else:

        writer = RawWriter(ostream)

    writer.add_timestamp = args.timestamp
    writer.with_color = args.color

    if args.log is not None:
        try:
            writer.log_stream = open(args.log, "w+")
        except Exception as e:
            xprint("Failed to open logfile: %s" % e, True)
            exit(1)

    monitor = Monitor(reader, writer)

    try:
        monitor.monitor()
    except serial.serialutil.SerialException:
        xprint("")
        xprint("*** He's dead, Jim! ***", True)
        xprint("")
        if args.persist:
            os.execve(sys.executable, [sys.executable] + sys.argv, os.environ)
        else:
            exit(1)
    except KeyboardInterrupt:
        if args.persist:
            xprint("")
            os.execve(sys.executable, [sys.executable] + sys.argv, os.environ)
        else:
            xprint("")
        return self.receive()  # Return response

    def close(self):
        try:
            self.com.close()
            return True
        except:
            self.error |= ERROR_CLOSE
            return False

    def parse_int(self, int_str):
        try:
            return int(int_str)
        except:
            self.error |= ERROR_PARSE
            return None

    def parse_float(self, float_str):
        try:
            return float(float_str)
        except Exception as e:
            print 'error [%s]' % float_str, e
            self.error |= ERROR_PARSE
            return None


if __name__ == '__main__':

    print 'List of available ports'
    print list_ports()
Exemple #25
0
            phrase += " : "
        elif i != len(token_list) - 1 and token_list[i + 1][0] == "TYPE":
            phrase += token_list[i][1]
        elif i != len(token_list) - 1:
            phrase += token_list[i][1]
            phrase += ", "
        else:
            phrase += token_list[i][1]
    phrase += "\n"
    return phrase


if __name__ == "__main__":
    if len(sys.argv) >= 2 and type(sys.argv[1]) is str:
        # Recuperation des ports utilises
        connected_ports = list_ports()
        # Ouverture du port utilise si existant
        if len(connected_ports) >= 0:  # En realite >= 1
            #~ ser = serial.Serial(connected_ports[0], 9600, timeout=1)
            print("Port list : " + str(connected_ports))
            # Partie Lecture de fichier
            # Deux modes disponibles : lecture d'une trame ou lecture de plusieurs trames (-m)
            if len(sys.argv) >= 3 and sys.argv[1] == "-m":
                fp = open(sys.argv[2])
                str_list = []
                for line in fp:
                    str_list.append(line)
                fp.close()
                print(str_list)
                for data in str_list:
                    # Analyse lexicale