def on_btn_device_release(self, btn):
        device_name = btn.text

        if platform == 'android':
            device = usb.get_usb_device(device_name)
            if not device:
                raise SerialException(
                    "Device {} not present!".format(device_name))
            if not usb.has_usb_permission(device):
                usb.request_usb_permission(device)
                return
            self.serial_port = serial4a.get_serial_port(device_name,
                                                        9600,
                                                        8,
                                                        'N',
                                                        1,
                                                        timeout=1)
        else:
            self.serial_port = Serial(device_name, 9600, 8, 'N', 1, timeout=1)

        if self.serial_port.is_open and not self.read_thread:
            self.read_thread = threading.Thread(target=self.read_msg_thread)
            self.read_thread.start()

        self.uiDict['sm'].current = 'screen_test'
Exemplo n.º 2
0
 def connect(self, port):
     try:
         if platform in ['windows', 'linux']:
             self.conn = serial.Serial(port, baudrate=self.serialComParameters['baudrate'],
                                       parity=self.serialComParameters['parity'],
                                       stopbits=self.serialComParameters['stopbits'])
         elif platform == 'android':
             device = usb.get_usb_device(port)
             if not device:
                 raise SerialException(
                     "No device {}".format(port)
                 )
             if not usb.has_usb_permission(device):
                 usb.request_usb_permission(device)
                 return False
             self.conn = serial4a.get_serial_port(
                 port,
                 self.serialComParameters['baudrate'],
                 8,
                 self.serialComParameters['parity'],
                 self.serialComParameters['stopbits'],
                 timeout=1
             )
         self.connected = True
         return True
     except SerialException:
         self.connected = False
         return False
Exemplo n.º 3
0
 def connect(self):
     """Connect to the Arduino
             return values:
                 True: connection ok
                 False: Failed to connect
                 None: Permissions asked, has to retry"""
     if self._port is None:
         return False
     if platform == 'android':
         if not usb.has_usb_permission(self.android_device):
             usb.request_usb_permission(self.android_device)
             return None
         self.__serial_connection = serial4a.get_serial_port(
             self._port, self._baudrate, 8, 'N', 1)
         if self.__serial_connection and self.__serial_connection.is_open:
             self.__d("Serial: Connected")
             return True
     else:
         self.__serial_connection = Serial(self._port,
                                           baudrate=self._baudrate)
         if self.__serial_connection.is_open:
             self.__d("Serial: Connected")
             return True
     self.__serial_connection = None
     self._port = None
     return False
Exemplo n.º 4
0
    def open(self):
        '''Open the serial port.
        
        When the serial port is instantiated, it will try to open automatically.
        '''
        self.close()

        device = usb.get_usb_device(self.portstr)
        if not device:
            raise SerialException("Device not present {}".format(self.portstr))

        if not usb.has_usb_permission(device):
            usb.request_usb_permission(device)
            return

        connection = usb.get_usb_manager().openDevice(device)
        if not connection:
            raise SerialException("Failed to open device!")

        self._device = device
        self._connection = connection

        raw_descriptors = self._connection.getRawDescriptors()
        self._bcd_device = raw_descriptors[12] + raw_descriptors[13] * 256

        for i in range(self._device.getInterfaceCount()):
            if i == 0:
                self._interface = self._device.getInterface(i)
            if not self._connection.claimInterface(
                    self._device.getInterface(i), True):
                raise SerialException(
                    "Could not claim interface {}.".format(i))

        self._index = self._interface.getId() + 1

        for i in range(self._interface.getEndpointCount()):
            ep = self._interface.getEndpoint(i)
            if (
                (ep.getDirection() == usb.UsbConstants.USB_DIR_IN) \
                and (ep.getType() == usb.UsbConstants.USB_ENDPOINT_XFER_INT)
            ):
                self._control_endpoint = ep
            elif (
                (ep.getDirection() == usb.UsbConstants.USB_DIR_IN) \
                and (ep.getType() == usb.UsbConstants.USB_ENDPOINT_XFER_BULK)
            ):
                self._read_endpoint = ep
            elif (
                (ep.getDirection() == usb.UsbConstants.USB_DIR_OUT) \
                and (ep.getType() == usb.UsbConstants.USB_ENDPOINT_XFER_BULK)
            ):
                self._write_endpoint = ep

        # Check that all endpoints are good
        if None in [self._write_endpoint, self._read_endpoint]:
            raise SerialException("Could not establish all endpoints!")

        self.is_open = True
        self._reconfigure_port()
Exemplo n.º 5
0
    def open(self, port):
        if port:
            try:
                self.device = serial4a.get_serial_port(
                    port,
                    115200,   # Baudrate
                    8,      # Number of data bits(5, 6, 7 or 8)
                    'N',    # Parity('N', 'E', 'O', 'M' or 'S')
                    1)      # Number of stop bits(1, 1.5 or 2)

                if not usb.has_usb_permission(self.device):
                    usb.request_usb_permission(self.device)
                    return
            except:
                print('Failed to open Serial device')
        else:
            try:
                self.device = serial4a.get_serial_port(
                    usb_device_list[0].getDeviceName(),
                    115200,   # Baudrate
                    8,      # Number of data bits(5, 6, 7 or 8)
                    'N',    # Parity('N', 'E', 'O', 'M' or 'S')
                    1)      # Number of stop bits(1, 1.5 or 2)

                if not usb.has_usb_permission(self.device):
                    usb.request_usb_permission(self.device)
                    return
            except:
                print('Failed to open Serial device')

        if self.device is not None:
            self.connected.set()
            return self.device
        else:
            print('failed to open SerialLink')
            raise LinkOpenException
Exemplo n.º 6
0
    def open(self, port=None, speed=115200):
        """ Find and open the communication port where the Arduino is connected.
        Generate the reset sequence with the DTR / RTS pins.
        Send the sync command to verify that there is a valid bootloader.

        :param port: serial port identifier (example: ttyUSB0 or COM1). None for automatic board search.
        :type port: str
        :param speed: comunication baurate.
        :type speed: int
        :return: True when the serial port was opened and the connection to the board was established.
        :rtype: bool
        """
        if not port:
            port = self._find_device_port()

        if not port:
            return False
        else:
            if OS_ANDROID:
                device = usb.get_usb_device(port)
                if not usb.has_usb_permission(device):
                    usb.request_usb_permission(device)
                    return
                self.device = serial4a.get_serial_port(port,
                                                       speed,
                                                       8,
                                                       'N',
                                                       1,
                                                       timeout=1)

                if self.device:
                    self.device.USB_READ_TIMEOUT_MILLIS = 1000
            else:
                self.device = serial.Serial(port, speed, 8, 'N', 1, timeout=1)

        self.port = port
        ''' Clear DTR and RTS to unload the RESET capacitor of the Arduino boards'''
        self.device.dtr = True
        self.device.rts = True
        time.sleep(1 / 20)
        ''' Set DTR and RTS back to high '''
        self.device.dtr = False
        self.device.rts = False
        time.sleep(1 / 20)
        """Discards bytes generated by the initialization sequence."""
        self.device.reset_input_buffer()
        return True
Exemplo n.º 7
0
    def open(self):
        """Open the serial port.

        When the serial port is instantiated, it will try to open automatically.
        """
        self.close()

        device = usb.get_usb_device(self.portstr)
        if not device:
            raise SerialException("Device not present {}".format(self.portstr))

        if not usb.has_usb_permission(device):
            usb.request_usb_permission(device)
            return

        connection = usb.get_usb_manager().openDevice(device)
        if not connection:
            raise SerialException("Failed to open device!")

        self._device = device
        self._connection = connection

        if self._device.getInterfaceCount() == 1:
            # Device might be castrated ACM device. Try single interface logic.
            self._open_single_interface()
        else:
            # Try default interface logic.
            self._open_interface()

        # Check that all endpoints are good
        if None in [
                self._control_endpoint, self._write_endpoint,
                self._read_endpoint
        ]:
            raise SerialException("Could not establish all endpoints!")

        self.is_open = True
        self._set_dtr_rts(self._dtr_state, self._rts_state)
        self._reconfigure_port()
Exemplo n.º 8
0
    def on_btn_device_release(self, btn):
        device_name = btn.text

        if platform == 'android':
            device = usb.get_usb_device(device_name)
            if not device:
                raise SerialException(
                    "Device {} not present!".format(device_name))
            if not usb.has_usb_permission(device):
                usb.request_usb_permission(device)
                return
            self.serial_port = serial4a.get_serial_port(device_name,
                                                        9600,
                                                        8,
                                                        'N',
                                                        1,
                                                        timeout=0.03)
        else:
            self.serial_port = Serial(device_name,
                                      9600,
                                      8,
                                      'N',
                                      1,
                                      timeout=0.03)

        if self.serial_port.is_open and not self.read_thread:
            #self.read_thread = threading.Thread(target = self.read_msg_thread)
            self.read_thread = threading.Thread(target=self.recieve)
            self.read_thread.start()
            #from kivy.clock import Clock
            #Clock.schedule_interval(self.my_callback, 0.1)
        else:
            print("Exception")

        #self.uiDict['sm'].current = 'screen_test'
        self.uiDict['sm'].switch_to(self.uiDict['sm'].tab_list[1])
Exemplo n.º 9
0
 def open(self):
     '''Open the serial port.
     
     When the serial port is instantiated, it will try to open automatically.
     '''
     self.close()
     
     device = usb.get_usb_device(self.portstr)
     if not device:
         raise SerialException("Device not present {}".format(self.portstr))
     
     if not usb.has_usb_permission(device):
         usb.request_usb_permission(device)
         return
         
     connection = usb.get_usb_manager().openDevice(device)
     if not connection:
         raise SerialException("Failed to open device!")
         
     self._device = device
     self._connection = connection
     
     for i in range(self._device.getInterfaceCount()):
         if not self._connection.claimInterface(
             self._device.getInterface(i),
             True
         ):
             raise SerialException("Could not claim interface {}.".format(i))
     
     self._interface = self._device.getInterface(
         self._device.getInterfaceCount() - 1
     )
     
     for i in range(self._interface.getEndpointCount()):
         ep = self._interface.getEndpoint(i)
         if (
             (ep.getDirection() == usb.UsbConstants.USB_DIR_IN) \
             and (ep.getType() == usb.UsbConstants.USB_ENDPOINT_XFER_INT)
         ):
             self._control_endpoint = ep
         elif (
             (ep.getDirection() == usb.UsbConstants.USB_DIR_IN) \
             and (ep.getType() == usb.UsbConstants.USB_ENDPOINT_XFER_BULK)
         ):
             self._read_endpoint = ep
         elif (
             (ep.getDirection() == usb.UsbConstants.USB_DIR_OUT) \
             and (ep.getType() == usb.UsbConstants.USB_ENDPOINT_XFER_BULK)
         ):
             self._write_endpoint = ep  
             
     # Check that all endpoints are good
     if None in [self._write_endpoint, self._read_endpoint]:
         raise SerialException("Could not establish all endpoints!")
     
     # Enable UART
     self._ctrl_transfer_out(self.CP210X_IFC_ENABLE, self.UART_ENABLE)
     # Set Baud Div
     self._ctrl_transfer_out(
         self.CP210X_SET_BAUDDIV,
         self.BAUD_RATE_GEN_FREQ / self.DEFAULT_BAUDRATE
     )
     
     self.is_open = True
     
     # Set DTR and RTS
     self.dtr = True
     self.rts = True
     
     self._reconfigure_port()
Exemplo n.º 10
0
    def open(self):
        '''Open the serial port.
        
        When the serial port is instantiated, it will try to open automatically.
        '''
        self.close()

        device = usb.get_usb_device(self.portstr)
        if not device:
            raise SerialException("Device not present {}".format(self.portstr))

        if not usb.has_usb_permission(device):
            usb.request_usb_permission(device)
            return

        connection = usb.get_usb_manager().openDevice(device)
        if not connection:
            raise SerialException("Failed to open device!")

        self._device = device
        self._connection = connection

        for i in range(self._device.getInterfaceCount()):
            if not self._connection.claimInterface(
                    self._device.getInterface(i), True):
                raise SerialException(
                    "Could not claim interface {}.".format(i))

        self._interface = self._device.getInterface(
            self._device.getInterfaceCount() - 1)

        for i in range(self._interface.getEndpointCount()):
            ep = self._interface.getEndpoint(i)
            if (
                (ep.getDirection() == usb.UsbConstants.USB_DIR_IN) \
                and (ep.getType() == usb.UsbConstants.USB_ENDPOINT_XFER_INT)
            ):
                self._control_endpoint = ep
            elif (
                (ep.getDirection() == usb.UsbConstants.USB_DIR_IN) \
                and (ep.getType() == usb.UsbConstants.USB_ENDPOINT_XFER_BULK)
            ):
                self._read_endpoint = ep
            elif (
                (ep.getDirection() == usb.UsbConstants.USB_DIR_OUT) \
                and (ep.getType() == usb.UsbConstants.USB_ENDPOINT_XFER_BULK)
            ):
                self._write_endpoint = ep

        # Check that all endpoints are good
        if None in [
                self._control_endpoint, self._read_endpoint,
                self._write_endpoint
        ]:
            raise SerialException("Could not establish all endpoints!")

        if self._device.getDeviceClass() == usb.UsbConstants.USB_CLASS_COMM:
            self._device_type = self.DEVICE_TYPE_0
        else:
            raw_descriptors = self._connection.getRawDescriptors()
            max_packet_size_0 = raw_descriptors[7]
            if max_packet_size_0 == 64:
                self._device_type = self.DEVICE_TYPE_HX
            elif (
                self._device.getDeviceClass() == \
                usb.UsbConstants.USB_CLASS_PER_INTERFACE
                or self._device.getDeviceClass() == \
                usb.UsbConstants.USB_CLASS_VENDOR_SPEC
            ):
                self._device_type = self.DEVICE_TYPE_1
            else:
                # Unknown device sub type, assume DEVICE_TYPE_HX.
                self._device_type = self.DEVICE_TYPE_HX

        self._init_device()
        self.is_open = True
        self._set_dtr_rts(self._dtr_state, self._rts_state)
        self._reconfigure_port()
 def do_start_stop_toggle(self):
     if not self.reading_thread_enabled:
         # to open the serial port, start a reading thread, and schedule a drawing timer
         selected_device = self.ids.device_list.get_first_selected_device_name(
         )
         if selected_device is not None:
             try:
                 if platform == 'android':
                     device = usb.get_usb_device(selected_device)
                     if not device:
                         raise SerialException(
                             "Device {} not present!".format(
                                 selected_device))
                     if not usb.has_usb_permission(device):
                         if self.is_asking_permission != True:
                             self.is_asking_permission = True
                             usb.request_usb_permission(device)
                         Clock.schedule_once(
                             lambda dt: self.do_start_stop_toggle(), 0.5)
                         return
                     self.is_asking_permission = False
                     self.serial_port = serial4a.get_serial_port(
                         selected_device,
                         App.get_running_app().config.getint(
                             'communication', 'baud_rate'),
                         App.get_running_app().config.getint(
                             'communication', 'data_bits'),
                         App.get_running_app().config.get(
                             'communication', 'parity'),
                         float(App.get_running_app().config.get(
                             'communication', 'stop_bits')),
                         timeout=1)
                 else:
                     self.serial_port = Serial(
                         selected_device,
                         App.get_running_app().config.getint(
                             'communication', 'baud_rate'),
                         App.get_running_app().config.getint(
                             'communication', 'data_bits'),
                         App.get_running_app().config.get(
                             'communication', 'parity'),
                         float(App.get_running_app().config.get(
                             'communication', 'stop_bits')),
                         timeout=1)
             except SerialException:
                 self.popup_a_notification(
                     "The selected device can not be configured.\r\nPlease check the permissions and close me!"
                 )
             if self.serial_port is not None and self.serial_port.is_open and not self.read_thread:
                 self.serial_port.reset_input_buffer()
                 self.read_thread = threading.Thread(
                     target=self.read_serial_msg_thread)
                 self.reading_thread_enabled = True
                 self.read_thread.start()
                 # Since there is a queue to adjust inconsistent throughputs, we can set a small time interval to check if sampes exist in queue .
                 Clock.schedule_interval(self.draw_waveform, 1 / 50.)
                 self.ids.toggle_button.text = "Stop acquisition"
         else:
             self.popup_a_notification("No device selected. Close me!")
     else:
         # to unschedule the drawing timer and stop the reading thread
         self.reset_plots()
         Clock.unschedule(self.draw_waveform)
         self.reading_thread_enabled = False
         with self.port_thread_lock:
             self.serial_port.close()
         self.read_thread.join()
         self.read_thread = None
         self.ids.toggle_button.text = "Start acquisition"