Example #1
0
def find_hifive():
    """
    Returns a tuple representation of the port and serial number for a
    connected HiFive device. If no device is connected the tuple will be
    (None, None).
    """
    # TODO rm repetitions of funcs or rewrite
    ports = list_serial_ports()
    hifive_ports = [
        port for port in ports if 'VID:PID=1366:1061' in port[2].upper()
        or 'VID:PID=0D28:0204' in port[2].upper()
    ]

    for port in hifive_ports:

        serial = Serial(port[0], SERIAL_BAUD_RATE, timeout=1, parity="N")
        try:
            serial.write(b"\r\x01")
            flush_to_msg(serial, RAW_REPL_MSG)
            return port[0], port.serial_number
        except Exception:
            flush(serial)
            continue

    return None, None
Example #2
0
def find_pyb():
    ports = list_serial_ports()
    # riven, add pyb serial access
    for port in ports:
        if "VID:PID=F055:9800" in port[2].upper():
            return (port[0], port.serial_number)
    return (None, None)
def find_ubtrobot():
    """
    Finds the port to which the device is connected.
    https://github.com/mu-editor/mu/blob/803153f661097260206ed2b7cc9a1e71b564d7c3/mu/contrib/microfs.py#L44
    """
    ports = list_serial_ports()
    target_port = None
    if (platform.system() == "Darwin"):
        for port in ports:
            if "Alpha1_" in port[0]:
                target_port = port[0]

    if platform.system() == "Windows":
        # 分别处理win7和win10 没必要 platform.release()

        # win7会存贮之前的连接信息
        win_ports = []
        for port in ports:
            # ServiceGUID
            # 00010039_PID win7需要这个
            if ("00001101-0000-1000-8000-00805f9b34fb"
                    in port[2].lower()) and ("00010039_pid"
                                             in port[2].lower()):
                # 找到最大的(for 循环默认从小到大吗),旧的port会被系统留着
                win_ports.append(str(port[0]))
        target_port = sorted(win_ports)[-1]  # 选择最大的

    if platform.system() == "Linux":
        target_port = find_linux_port()

    return target_port
Example #4
0
def getPort(device=None, deviceVID=None):
    devices = setup()
    if device != None:
        device = device.upper()
        try:
            name = devices[device]
        except:
            if deviceVID != None:
                devices[device] = deviceVID.upper()
            else:
                return None

    elif deviceVID == None:
        return None

    if deviceVID != None:
        name = deviceVID

    export(devices)

    ports = list_serial_ports()
    for port in ports:
        if name in port[2].upper():
            return port[0]

    return None
Example #5
0
 def update_ports(self):
     ports = [i[0] for i in list_serial_ports()]
     message = self.extensionInstance.message_template()
     message["payload"]["content"] = {
         "ports": ports,
     }
     self.extensionInstance.publish(message)
     return "ok"
Example #6
0
def enumerate_irises():
    """Return a generator to iterate over all connected iris devices."""
    serial_ports = list_serial_ports()
    for port in serial_ports:
        # These VIDs and PIDs are the ones used by Arduino Micros
        # They need to be changed for the production version!
        if port.vid == 0x2341 and port.pid == 0x8037:
            yield port
Example #7
0
def find_microbit():
    """
    Finds the port to which the device is connected.
    """
    ports = list_serial_ports()
    for port in ports:
        if "VID:PID=0D28:0204" in port[2].upper():
            return port[0]
    return None
Example #8
0
def find_microbit():
    """
    Finds the port to which the device is connected.
    """
    ports = list_serial_ports()
    for port in ports:
        if "VID:PID=0D28:0204" in port[2].upper():
            return port[0]
    return None
def find_ardiuno():
    """
    Finds the port to which the device is connected.
    https://github.com/mu-editor/mu/blob/803153f661097260206ed2b7cc9a1e71b564d7c3/mu/contrib/microfs.py#L44
    window用户需要按照发现服务
    """
    ports = list_serial_ports()
    for port in ports:
        if 'VID:PID=1A86:7523' in port[2].upper():
            return port[0]
def find_ubtrobot():
    """
    Finds the port to which the device is connected.
    https://github.com/mu-editor/mu/blob/803153f661097260206ed2b7cc9a1e71b564d7c3/mu/contrib/microfs.py#L44
    """
    ports = list_serial_ports()
    for port in ports:
        if "Alpha1_E566" in port[0]:
            return port[0]
    return None
Example #11
0
def find_microbit():
    """
    Finds the port to which the device is connected.
    """
    ports = list_serial_ports()
    for port in ports:
        # Use the vendor and product ID to identify the micro:bit.
        if "VID:PID=0D28:0204" in port[2].upper():
            return port[0]
    return None
Example #12
0
def find_microbit():
    """
    Returns a tuple representation of the port and serial number for a
    connected micro:bit device. If no device is connected the tuple will be
    (None, None).
    """
    ports = list_serial_ports()
    for port in ports:
        if "VID:PID=0D28:0204" in port[2].upper():
            return (port[0], port.serial_number)
    return (None, None)
Example #13
0
def find_microbit():
    """
    Returns a tuple representation of the port and serial number for a
    connected micro:bit device. If no device is connected the tuple will be
    (None, None).
    """
    ports = list_serial_ports()
    for port in ports:
        if "VID:PID=0D28:0204" in port[2].upper():
            return (port[0], port.serial_number)
    return (None, None)
Example #14
0
def find_microbit():
    """
    Finds the port to which the device is connected.
    """
    ports = list_serial_ports()
    for port in ports:
        # Modification from original microfs.py below:
        if "VID:PID=1366" in port[2].upper():
        # End modification above.
            return port[0]
    return None
 def refreshPorts(self):
     """
     Scan the available serial ports for Pixel Kits and update the combo
     box that list them.
     """
     ports = list_serial_ports()
     # Filter the ports by Pixel Kit's vendor and product ids.
     rpks = list(
         filter(lambda port: (port.vid, port.pid) == (0x0403, 0x6015),
                ports))
     # Reset the combo box
     self.comboSerialPorts.clear()
     self.comboSerialPorts.addItem('Select serial port...')
     self.comboSerialPorts.setCurrentIndex(0)
     # Add ports to the combo box and update its looks
     for port in rpks:
         self.comboSerialPorts.addItem(port.device)
     self.comboSerialPorts.repaint()
def guess_port():
    """
    From https://github.com/ntoll/microrepl
    Returns the port for the first micro:bit found connected to the computer
    running this script. If no micro:bit is found, returns None.
    """
    ports = list_serial_ports()
    platform = sys.platform
    if platform.startswith("linux"):
        for port in ports:
            if "VID:PID=0D28:0204" in port[2].upper():
                return port[0]
    elif platform.startswith("darwin"):
        for port in ports:
            if "VID:PID=0D28:0204" in port[2].upper():
                return port[0]
    elif platform.startswith("win"):
        for port in ports:
            if "VID:PID=0D28:0204" in port[2].upper():
                return port[0]
    return None
Example #17
0
def connected_microbits():
    """
    Based on code from https://github.com/ntoll/microrepl
    Returns a list of connected micro:bit port addresses (format is system
    dependent).
    """
    ports = list_serial_ports()
    platform = sys.platform
    results = []
    if platform.startswith("linux"):
        for port in ports:
            if "VID:PID=0D28:0204" in port[2].upper():
                results.append(port[0])
    elif platform.startswith("darwin"):
        for port in ports:
            if "VID:PID=0D28:0204" in port[2].upper():
                results.append(port[0])
    elif platform.startswith("win"):
        for port in ports:
            if "VID:PID=0D28:0204" in port[2].upper():
                results.append(port[0])
    return results
Example #18
0
def connected_microbits():
    """
    Based on code from https://github.com/ntoll/microrepl
    Returns a list of connected micro:bit port addresses (format is system
    dependent).
    """
    ports = list_serial_ports()
    platform = sys.platform
    results = []
    if platform.startswith("linux"):
        for port in ports:
            if "VID:PID=0D28:0204" in port[2].upper():
                results.append(port[0])
    elif platform.startswith("darwin"):
        for port in ports:
            if "VID:PID=0D28:0204" in port[2].upper():
                results.append(port[0])
    elif platform.startswith("win"):
        for port in ports:
            if "VID:PID=0D28:0204" in port[2].upper():
                results.append(port[0])
    return results
 def find_device(self):
     ports = list_serial_ports()
     for port in ports:
         if "VID:PID=10C4:EA60" in port[2].upper():
             return port[0]
     return None
Example #20
0
 def serial_loop(self):
     while self.running:
         logging.info("Scanning serial ports...")
         try:
             for port in list_serial_ports():
                 logging.info("Attempting connection with " + port.name)
                 if self.serialPort is not None:
                     self.serialPort.close()
                     self.serialPort = None
                 try:
                     # Su Linux forse bisogna aggiungere `rtscts=True, dsrdtr=True, exclusive=True`
                     self.serialPort = serial.Serial(port=port.device,
                                                     baudrate=115200,
                                                     timeout=2)
                 except:
                     logging.warning(port.name + " unavailable.")
                     self.serialPort = None
                     continue
                 time.sleep(1)
                 self.serialPort.write(">C\n".encode('utf-8'))
                 time.sleep(0.5)
                 start_time = time.time()
                 interval_time = time.time()
                 serial_retry = True
                 while self.running and serial_retry:
                     response = self.serialPort.readline().decode(
                         "utf-8").replace("\n", "").replace("\r", "")
                     now = time.time()
                     if response == "":
                         if (now - start_time) >= 10.0:
                             logging.info("No answer from " + port.name)
                             self.serialPort.close()
                             self.serialPort = None
                             serial_retry = False
                         elif (now - interval_time) >= 1.0:
                             logging.info("Retrying serial ping")
                             self.serialPort.write(">C\n".encode('utf-8'))
                             interval_time = now
                     else:
                         logging.info("Board replied \"" + response + "\"")
                         if response[1:] == ROVER_UUID:
                             logging.info(port.device + " connected.")
                             self.serial_println(">E0")  # Motors OFF
                             self.motor_power_on = False
                             self.socket_broadcast(
                                 {"setMotorsPowered": self.motor_power_on})
                             # TODO(Marco): velocità solo per provare
                             self.serial_println(">V200")
                             self.serialConnected = True
                             while self.running:
                                 try:
                                     msg = self.serial_read_line()
                                     if msg is None:
                                         time.sleep(0.3)
                                     elif msg[0] == "L":
                                         logging.info("Serial log: " + msg)
                                     elif msg[0] == "A":
                                         array = get_array_from_message(msg)
                                         if array is not None:
                                             logging.info(
                                                 "Accelerometer data " +
                                                 str(array))
                                             self.socket_broadcast(
                                                 {"updateAccel": array})
                                     elif msg[0] == "G":
                                         array = get_array_from_message(msg)
                                         if array is not None:
                                             logging.info(
                                                 "Gyroscope data " +
                                                 str(array))
                                             self.socket_broadcast(
                                                 {"updateGyro": array})
                                     elif msg[0] == "M":
                                         current, target = msg[1:-1].split(
                                             "%")
                                         if current != "nan" and target != "nan":
                                             array = [
                                                 float(current),
                                                 float(target)
                                             ]
                                             logging.info("Compass data " +
                                                          str(array))
                                             self.socket_broadcast(
                                                 {"updateCompass": array})
                                     elif msg[0] == "B":
                                         battery = float(msg[1:-1])
                                         logging.info("Battery level: " +
                                                      str(battery))
                                         self.socket_broadcast(
                                             {"updateBattery": battery})
                                     elif msg[0] == "T":
                                         temp = float(msg[1:-1])
                                         logging.info("IMU temperature: " +
                                                      str(temp))
                                         self.socket_broadcast(
                                             {"updateIMUTemp": temp})
                                     elif msg[0] == "D":
                                         dist = float(msg[1:-1])
                                         logging.info("Distance: " +
                                                      str(dist))
                                         self.socket_broadcast(
                                             {"updateDistance": dist})
                                     else:
                                         logging.warning(
                                             "Unknown message: " + msg)
                                 except UnicodeDecodeError:
                                     logging.warning(
                                         "Corrupted serial message.")
                                 except (IndexError, ValueError):
                                     logging.warning("Parsing error.")
                         elif (now - start_time) >= 10.0:
                             logging.info("No answer from " + port.name)
                             self.serialPort.close()
                             self.serialPort = None
                             serial_retry = False
                         elif (now - interval_time) >= 1.0:
                             logging.info("Retrying serial ping")
                             self.serialPort.write(">C\n".encode('utf-8'))
                             interval_time = now
         except SerialException:
             logging.error("Arduino is now disconnected!")
             if self.serialPort is not None:
                 self.serialPort.close()
                 self.serialPort = None
         except:
             logging.exception(
                 "Unexpected error, Arduino is now disconnected!")
             if self.serialPort is not None:
                 self.serialPort.close()
                 self.serialPort = None
         time.sleep(2)
     logging.info("Serial loop stopped")
Example #21
0
 def list_ports(self):
     return [i[0] for i in list_serial_ports()]