Example #1
2
def read_serial(ser: serial.Serial, q_out: queue.Queue, q_in: queue.Queue,
                stop_event: threading.Event):
    while (ser.isOpen()):
        if stop_event.is_set(): return
        if not q_in.empty():
            ser.write(q_in.get() + b'\n')
        q_out.put(bytestostr(ser.readline()))
Example #2
1
class SerialSensorReader(SensorReader):
	def __init__(self,commConfig,sensorName,rowType=(),rateSec=60,db=None,log=None):
		SensorReader.__init__(self,commConfig,sensorName,rowType,rateSec,db,log)
		self.eol = "\n"
		self.delimiterPattern = "\\S+"
		self.delimiter = " "
	def initSensor(self):
		from serial import Serial
		self.serialP = Serial(**self.commConfig) 
		self.resetSensor()
	def stopSensor(self):
		self.serialP.close()
	def getReadings(self):
		readings = []
		ts = str((int(time())/self.rateSec)*self.rateSec)
		while self.serialP.inWaiting():
			line = readlineR(self.serialP,self.eol)
			readings.append(self.delimiter.join([ts, line]))
		readings = [x for x in readings if x != None]
		return readings
	def toRow(self, reading):
		row = re.findall(self.delimiterPattern,reading.strip())
		row = [x.strip() for x in row]
		return row
	def resetSensor(self):
		print "Reseting Sensor:" + self.sensorName
		return readlineR(self.serialP,self.eol)
Example #3
0
 def __init__(self, *args, **kwargs):
     #ensure that a reasonable timeout is set
     timeout = kwargs.get('timeout',0.1)
     if timeout < 0.01: timeout = 0.1
     kwargs['timeout'] = timeout
     Serial.__init__(self, *args, **kwargs)
     self.buf = ''
Example #4
0
def main():

  print "Opening serial port"
  s = Serial(serial_port, serial_bauds);
  print "Reading first line from port"
  line = s.readline()
  print "Initializing communication"
  counter = 1
  # debug stuff
  # tic = time.time()
  log = open("/home/pi/vibration/log.csv", "a")

  while counter <= 1000:
    counter += 1
    line = s.readline()
    m = re.match(serial_pattern, line)
    try:
      log.write("\n" +  str(ts) + "," + str(counter) + "," + str(m.group(1)))
    except:
      log.write("\n" +  str(ts) + "," + str(counter) + "," + str("NaN"))

  # debug stuff
  # toc = time.time()
  # print(tic)
  # print(toc)
  log.close()
Example #5
0
 def run_host_test(self, target_name, port,
                   duration, verbose=False):
     """
     Functions resets target and grabs by timeouted pooling test log
     via serial port.
     Function assumes target is already flashed with proper 'test' binary.
     """
     output = ""
     # Prepare serial for receiving data from target
     baud = 9600
     serial = Serial(port, timeout=1)
     serial.setBaudrate(baud)
     flush_serial(serial)
     # Resetting target and pooling
     reset(target_name, serial, verbose=verbose)
     start_serial_timeour = time()
     try:
         while (time() - start_serial_timeour) < duration:
             test_output = serial.read(512)
             output += test_output
             flush_serial(serial)
             if '{end}' in output:
                 break
     except KeyboardInterrupt, _:
         print "CTRL+C break"
Example #6
0
 def __init__(self, port, baud):
     Serial.__init__(self)
     EventDispatcher.__init__(self)
     self.port = port
     self.baudrate = baud
     self.listeners = {}
     self.waiting = True
     self.detected = False
     self.readyMsg = ""
     self.repeatsWaiting = False
     self.messageEnd = b""
     self.inUse = False
     self.notFound = False
     self.connectionError = False
     self.lastSpeed = 1000
     self.statusRequest = False
     self.busy = False
     self._stopping = False
     self.connecting = True
     try:
         self.open()
     except SerialException as se:
         if os.name == "nt":
             if str(se).find('FileNotFoundError') >= 0:
                 self.notFound = True
                 self.dispatch('connection-error')
             elif str(se).find('PermissionError') >= 0:
                 self.inUse = True
         self.connectionError = True
         self.dispatch('connection-error')
         return
     detectThread = Thread(target=self.detectSetup)
     detectThread.start()
Example #7
0
class HashTagDisplay():
    def __init__(self, delay=5, debug=False):
        # duration in seconds to allow human to read display
        self.delay = delay
        # print messages to shell for debugging 
        self.debug = debug
        self.ser = Serial('/dev/ttyS0', baudrate=9600, timeout=1)

    def search(self, hashtag):
           # search for tweets with specified hashtag
           twitter_search = Twitter(domain="search.twitter.com")
           return twitter_search.search(q=hashtag)
    
    def display(self, results):
           # Display each tweet in the twitter search results
           for tweet in results.get('results'):
               msg = "@" + tweet.get('from_user') + ": " + tweet.get('text')
               #http://stackoverflow.com/questions/8689795/python-remove-non-ascii-characters-but-leave-periods-and-spaces
               msg = filter(lambda x: x in string.printable, msg)
               msg = re.sub('\s+',' ', msg)
               if self.debug == True:
                   print "msg: [" + msg + "]"
               for c in msg:
                   self.ser.write(c)
                   sleep(0.01)
               self.ser.write('\n');
               sleep(self.delay)
Example #8
0
class XBeeWriter(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.reset_input_buffer()
        self._serial.reset_output_buffer()
Example #9
0
    def available_ports():
        usb_serial_ports = filter(
            (lambda x: x.startswith('ttyUSB')),
            os.listdir('/dev'))

        ports = []
        for p in usb_serial_ports:
            ports.append(serial_for_url('/dev/'+p, do_not_open=True))


        """
        also check for old school serial ports, my hope is that this will enable
        both USB serial adapters and standard serial ports

        Scans COM1 through COM255 for available serial ports

        returns a list of available ports
        """
        for i in range(256):
            try:
                p = Serial(i)
                p.close()
                ports.append(p)
            except SerialException:
                pass

        return ports
Example #10
0
class SerialInstrument(object):

    def __init__(self, port, baud=19200):
        self.port = port
        self.baud = baud

    def read(self, num=None):
        if num:
            while self.instr.inWaiting() < num:
                pass
            return self.instr.read(num)
        while not self.instr.inWaiting():
            pass
        return self.instr.read()
        
    def write(self, data):
        self.instr.write(data)

    def __enter__(self):
        self.instr = Serial(self.port, self.baud)
        self.instr.open()
        return self

    def __exit__(self, type, value, tb):
        self.instr.close()
Example #11
0
    def testSendAndReceive4PortsLeader(self):
        """testSendAndReceive4Ports: Creates a PortLogger, serial objects that 
            connect to the PortLogger, and verifies that reads and writes work"""

        plogger = PortLogger(number_of_ports=4, rs485=True)
        serials = []
        for port_name in plogger.port_names():
            new_serial = Serial(port_name)
            new_serial.timeout = 1
            serials.append(new_serial)

        leader = serials[0]
        followers = serials[1:]

        self.assertEquals(len(followers), len(serials)-1)
        self.assertTrue(leader) #Check that leader is not None or []

        plogger.start()
        for port in followers:
            message = ''.join([chr(randint(32,127)) for _ in range(24)])
            port.write(message)
            for port2 in followers:
                recvd = port2.read(len(message))
                self.assertEqual('', recvd)
            recvd = leader.read(len(message))
            self.assertEquals(recvd, message)
        
        message = ''.join([chr(randint(32,127)) for _ in range(24)])
        leader.write(message)
        for port in followers:
            recvd = port.read(len(message))
            self.assertEquals(recvd, message)

        plogger.stop()
Example #12
0
    def testSendAndReceive2PortsLeader(self):
        """testSendAndReceive2PortsLeader: Creates a PortLogger, serial objects that 
            connect to the PortLogger, and verifies that reads and writes work.
            The portlogger uses the leader setup"""
        plogger= PortLogger(emulate=True, rs485=True )
        serials = []
        for port_name in plogger.port_names():
            new_serial = Serial(port_name)
            new_serial.timeout = 1
            serials.append(new_serial)

        plogger.start()

        message1 = "This is a test message"
        message2 = ''.join([chr(randint(32,127)) for _ in range(24)])
        serials[0].write(message1)
        recvd = serials[1].read(len(message1))
        self.assertEqual(message1, recvd)
        recvd = serials[0].read(len(message1))
        self.assertEqual('', recvd)
        

        serials[1].write(message2)
        recvd = serials[0].read(len(message2))
        self.assertEqual(message2, recvd)
        recvd = serials[1].read(len(message2))
        self.assertEqual('', recvd)
        
        plogger.stop()
class Copernicus(object):

    def __init__(self, port=None, baudrate=9600):
        self.serial = Serial(port, baudrate)

    def read(self):
        return ord(self.serial.read(1))

    def write(self, value):
        return self.serial.write(chr(value))

    def flush(self):
        self.serial.flushInput()

    def set_autoupdates(self, peripheral):
        self.write(autoupdate_codes[peripheral])

    def query(self, peripheral):
        self.write(query_codes[peripheral])

    def set_dashboard_angle(self, angle):
        if 0 <= angle <= 31:
            self.write(angle)
        else:
            ValueError("Dashboard angle out of range (0-31)")

    def reset_dashboard_angle(self):
        self.set_dashboard_angle(0)

    def led_on(self):
        self.write(33)

    def led_off(self):
        self.write(32)
    def connect(self, port , baud = 38400 , _timeout = 1):
        """
        Tries to connected to specified port, using given baudrate and timeout values
        @type port: number
        @param port: the port to be opened
        @type baud: number
        @param baud: the specified baudrate
        @type _timeout: number
        @param _timeout: the specified timeout value
        """
        LOGMSG("Connecting to base station ...")    
        try:
            self.serial = Serial(port,baud, timeout = _timeout)
        except serialutil.SerialException:
            LOGMSG ("Could not open port %d." %self.port)
            LOGMSG ("Retrying to reconnect in 5 seconds..." )
            time.sleep(5)
            LOGMSG("Reconnecting...")
            try:
                self.serial = Serial(port,baud, timeout = _timeout)
            except serialutil.SerialException:
                LOGMSG("Could not open port %d." %self.port)
                self.port = self.get_port("Maybe the PORT number is wrong? Please enter PORT number again: ");
                LOGMSG("Reconnecting...")
                try:
                    self.serial = Serial(port,baud, timeout= _timeout)
                except serialutil.SerialException:
                    LOGMSG ("Could not open port %d. " %self.port)
                    LOGMSG("Please check you configurations and PORT connections!")
                    self.close(1)

        LOGMSG("Serial connection established on port %d. Using baudrate %d and timeout %d" %(self.port, self.baud, self._timeout))
Example #15
0
class Connexion:
    """
    Manage the USB connexion.
    """

    def __init__(self, tty = "/dev/ttyACM0"):
        """
        Open a serial connexion on specified tty, with a 1152000
        baudrate.
        """
        try:
            self.serial = Serial(tty, baudrate = 115200)
        except SerialException:
            print("Can't open", tty)
            exit(1)

    def read(self):
        """ Read a line. """
        try:
            return self.serial.readline().decode("ascii", "ignore")
        except OSError:
            sleep(1)
            return self.read()

    def write(self, msg):
        """ Send a string. """
        self.serial.write(normalize("NFD", msg).encode("ascii", "ignore"))
Example #16
0
 def __init__(self, port=None, baudrate=None):
     if port == None:
         port = profile.getPreference("serial_port")
     if baudrate == None:
         baudrate = int(profile.getPreference("serial_baud"))
     self.serial = None
     if port == "AUTO":
         programmer = stk500v2.Stk500v2()
         for port in serialList():
             try:
                 print "Connecting to: %s %i" % (port, baudrate)
                 programmer.connect(port)
                 programmer.close()
                 time.sleep(1)
                 self.serial = Serial(port, baudrate, timeout=2)
                 break
             except ispBase.IspError as (e):
                 print "Error while connecting to %s %i" % (port, baudrate)
                 print e
                 pass
             except:
                 print "Unexpected error while connecting to serial port:" + port, sys.exc_info()[0]
         programmer.close()
     elif port == "VIRTUAL":
         self.serial = VirtualPrinter()
     else:
         try:
             self.serial = Serial(port, baudrate, timeout=2)
         except:
             print "Unexpected error while connecting to serial port:" + port, sys.exc_info()[0]
     print self.serial
Example #17
0
class Rubinstein(object):
    def __init__(self, port='/dev/ttyUSB0', baudrate=250000, timeout=0.25):
        self.serial = Serial(port=port, baudrate=baudrate, timeout=timeout)
        # FIXME don't know why initialization stops with this line
        while self.serial.readline() != 'echo:SD init fail\n':
            sleep(0.2)
        self.busy = False

    def command(self, cmd, timeout=float('inf')):
        # FIXME needs mutex!
        if self.busy or self.serial.read():
            raise RuntimeError("busy")
        self.busy = True
        self.serial.write("{}\n".format(cmd))
        response = ''
        start = time()
        while time() - start < timeout:
            sleep(0.2)
            line = self.serial.readline()
            if line == 'ok\n':
                # FIXME missing try/finally for busy=False
                self.busy = False
                return response
            if len(line) > 0:
                print line,
            response += line
        else:
            raise RuntimeError(
                "timeout when waiting for command {}".format(cmd))
    def testSendAndReceive2Ports(self):
        """testSendAndReceive2Ports: Creates a PortLogger, serial objects that 
            connect to the PortLogger, and verifies that reads and writes work"""
        from serial import Serial
        from random import randint
        plogger= PortLogger()
        serials = []
        for port_name in plogger.port_names():
            new_serial = Serial(port_name)
            new_serial.timeout = 1
            serials.append(new_serial)

        plogger.start()

        message1 = "This is a test message"
        message2 = ''.join([chr(randint(32,127)) for i in range(24)])
        serials[0].write(message1)
        recvd = serials[1].read(len(message1))
        self.assertEqual(message1, recvd)
        recvd = serials[0].read(len(message1))
        self.assertEqual('', recvd)
        

        serials[1].write(message2)
        recvd = serials[0].read(len(message2))
        self.assertEqual(message2, recvd)
        recvd = serials[1].read(len(message2))
        self.assertEqual('', recvd)
        
        plogger.stop()
Example #19
0
 def get_present(self):
     """
     Checks if RFID-RW-USB device is present.
     Returns True if so, False otherwise.
     """
     hmgr_if = dbus.Interface(self.bus.get_object(HAL_SERVICE, HAL_MGR_PATH),
                             HAL_MGR_IFACE)
     serialusb_devices = set(hmgr_if.FindDeviceStringMatch('serial.type',
                         'usb')) & set(hmgr_if.FindDeviceStringMatch(
                         'info.subsystem', 'tty'))
     for i in serialusb_devices:
         serialusb_if = dbus.Interface(self.bus.get_object(HAL_SERVICE, i), 
                                      HAL_DEV_IFACE)
         if serialusb_if.PropertyExists('info.parent'):
             parent_udi = str(serialusb_if.GetProperty('info.parent'))
             parent = dbus.Interface(self.bus.get_object(HAL_SERVICE,
                                     parent_udi), HAL_DEV_IFACE)
             if parent.PropertyExists('info.linux.driver') and \
             str(parent.GetProperty('info.linux.driver')) == 'ftdi_sio':
                 device = str(serialusb_if.GetProperty('linux.device_file'))
                 ser = Serial(device, 9600, timeout=0.1)
                 ser.read(100)
                 ser.write('v')
                 ser.write('e')
                 ser.write('r')
                 ser.write('\x0D')
                 resp = ser.read(4)
                 if resp[0:-1] in VERSIONS:
                     self.device = device
                     self.device_path = i
                     return True
     return False
Example #20
0
 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()
Example #21
0
class Arduino:
    def __init__(self, port, baud):
        self.serial = Serial(port, baud)
        time.sleep(2)

    def write_ints(self, *ints):
        self.serial.write(''.join(chr(i) for i in ints))
Example #22
0
def run(port, max_height=223, max_width=123):
    ser = Serial(port, 9600)
    prev = time()
    while True:
        line = ser.readline().rstrip('\n\r')
        data = line.split(',')

        if len(data) != 3:
            continue
        for i in range(3):
            try:
                data[i] = calibration * float(data[i])
            except ValueError:
                continue
        now = time()
        rate = 1 / (now - prev)
        ut = data[0]
        ul = data[1]
        ur = data[2]
        width = 0
        height = max_height - ut
        if not (ul > 120 and ur > 120):
            width = max_width - ul - ur
        #print '{:5.2f} {:5.2f} {:5.2f} {:5.2f} {:4.2f}'.format(height, ul, ur, width, rate)
        prev = now
Example #23
0
class GPS:

    def __init__(self, port_name, baud_rate, logger):
        self.logger = logger
        self.logger.write("Starting GPS Communications")
        self.serial = Serial(port_name, baud_rate)

        self.lat = 0
        self.long = 0

    def get_GPS(self):
        while (self.lat == 0.0):
            self.logger.write("Waiting for GPS")
            time.sleep(1)
        return (self.lat, self.long)

    def read_data(self):
        if self.serial.inWaiting() > 0:
            data = self.serial.readline().rstrip()
            if data[0:6] == "$GPRMC":
                fields = data.split(',')
                if fields[2] == 'A':
                  self.lat = int(fields[3][0:2]) + (float(fields[3][2:]) / 60.0) #ASSUMES TWO DIGIT LATITUDE
                  self.long = int(fields[5][0:3]) + (float(fields[5][3:]) / 60.0) #ASSUMES THREE DIGIT LONGITUDE
                else:
                  self.lat = 0.0
                  self.long = 0.0

    def close(self):
        self.serial.close()
Example #24
0
def main(argv):
    loglevels = [logging.CRITICAL, logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
    parser = argparse.ArgumentParser(argv)
    parser.add_argument('-v', '--verbosity', type=int, default=4,
                        help='set logging verbosity, 1=CRITICAL, 5=DEBUG')
    parser.add_argument('tty',
                        help='Serial port device file name')
    parser.add_argument('-b', '--baudrate', default=115200, type=int,
                        help='Serial port baudrate')
    args = parser.parse_args()
    # logging setup
    logging.basicConfig(level=loglevels[args.verbosity-1])

    # open serial port
    try:
        logging.debug("Open serial port %s, baud=%d", args.tty, args.baudrate)
        port = Serial(args.tty, args.baudrate, dsrdtr=0, rtscts=0, timeout=0.3)
    except IOError:
        logging.critical("error opening serial port", file=sys.stderr)
        sys.exit(2)

    try:
        app = rssi_plot()
        app.plot_rssi(port)
    except KeyboardInterrupt:
        port.close()
        sys.exit(2)
  def __init__(self, port, baudrate, wait_ready = True, timeout = True):
    
    # si le port n'est pas utilisé
    if port not in ARDUINO_PORTS:
      raise InvalidPort(port)
      
    # si le baudrate n'existe pas
    if baudrate not in Serial.BAUDRATES:
      raise InvalidBaudRate(baudrate)
    
    # on appel le constructeur parent
    Serial.__init__(self, port, baudrate, timeout = timeout)
    
    # connection start : temps de début de connexion
    self.connection_start = time()

    # on dort un petit moment
    if not isinstance(wait_ready, bool):
      time.sleep(wait_ready)
     
    # temps qu'on n'a pas de réponse on attend
    elif True:
      while not self.read():
        continue
       
      # temps nécéssaire pour obtenir la première connexion
      self.connection_first_answer = time() - self.connection_start
      print(self.connection_first_answer)
class AcquisitionThread(Thread):
    BAUDRATE = 57600
    START_CHARACTER = b's'
    PACKET_SIZE = 69

    def __init__(self, acquisition_queue):
        super(AcquisitionThread, self).__init__()
        self.acquisition_queue = acquisition_queue
        self.exit_flag = False

    def run(self):
        port_nb = serial_port()[0]
        self.device = Serial(port_nb, baudrate=self.BAUDRATE, timeout=0.2)
        while not self.exit_flag:
            c = self.device.read(1)
            if c == self.START_CHARACTER:
                while self.device.inWaiting() < self.PACKET_SIZE:
                    pass
                data = self.device.read(self.PACKET_SIZE)

                rocket_data = RocketData(data)
                # checksum_validated = rocket_data.validateCheckSum()
                checksum_validated = True
                if checksum_validated:
                    self.acquisition_queue.put(rocket_data)
        self.device.close()



    def stop(self):
        self.exit_flag = True
Example #27
0
    def __init__(self, port, baudrate=115200, reset=False):
        ConBase.__init__(self)

        try:
            self.serial = Serial(port, baudrate=baudrate, interCharTimeout=1)

            if reset:
                logging.info("Hard resetting device at port: %s" % port)

                self.serial.setDTR(True)
                time.sleep(0.25)
                self.serial.setDTR(False)

                self.serial.close()
                self.serial = Serial(port, baudrate=baudrate, interCharTimeout=1)

                while True:
                    time.sleep(2.0)
                    if not self.inWaiting():
                        break
                    self.serial.read(self.inWaiting())

        except Exception as e:
            logging.error(e)
            raise ConError(e)
Example #28
0
    def __init__(self, gui=None):

        if Printer.__single:
            raise RuntimeError('A Printer already exists')

        Printer.__single = self

        if gui:
            self.gui = gui
        else:
            self.gui = dddumbui.DumbGui()

        Serial.__init__(self)

        self.usbId = None

        # Command sequence number [1..255]
        self.lineNr = 1

        # The last (max. 256) commands sent, for command re-send
        self.lastCommands = {}

        # Retry counter on rx and tx errors
        self.rxErrors = 0
        self.txErrors = 0

        self.startTime = None

        self.curDirBits = 0
def uart1(portName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            ser = Serial(
                data,
                baudrate=9600,
                bytesize=8,
                parity='N',
                stopbits=1,
                timeout=None)
            while True:
                line = ser.readline(ser.inWaiting()).decode('utf-8')[:-2]
                if line:
                    t = line.split(",")
                    line2 = float(t[5])
                    if line2 > 0:
                        print(portName, line2)
                        if line == '520':
                            subprocess.call(["xte", "key Up"])
                        elif line == '620':
                            subprocess.call(["xte", "key Down"])
                        elif line == '110':
                            break
            ser.close()
Example #30
0
#!/usr/bin/python

import os
try:
    #os.remove('/home/pi/PiBits/MPU6050-Pi-Demo/acc_data.txt')
    #os.remove('/home/pi/gps.txt')
    pass
except:
    pass
from serial import Serial
from pynmea import nmea
import time
#Starting serial connection
serialPort = Serial("/dev/ttyAMA0", 9600, timeout=1)
#Check if port failed to open
if (serialPort.isOpen() == False):
    serialPort.open()

#Flush before receiving or sending any data
serialPort.flushInput()
serialPort.flushOutput()

#String as output
#serialPort.write('scaluza.com')
gpsData = ""
gpgga = nmea.GPGGA()
f1 = open('gps.txt', 'w+')
while True:

    #Check if there is any byte waiting on serial port
    if (serialPort.inWaiting() != 0):
Example #31
0
 def __init__(self, serport):
     self.decoder_state = SniffleDecoderState()
     self.ser = Serial(serport, 2000000)
     self.ser.write(b'@@@@@@@@\r\n') # command sync
     self.recv_cancelled = False
     self.rate_limiter = RateLimiter()
# Script for testing the recieve functionality of the Programm
import time
from serial import Serial
from config.ConfigReader import get_config

serial_config = get_config("../resources/SerialConfig.json")

# setting up the serial connection on COM Port 6 for testing purpose
ser = Serial("COM6", serial_config['baudrate'], serial_config['bytesize'],
             serial_config['parity'], serial_config['stopbits'],
             serial_config['timeout'])


# sends a command via the serial connection
# main purpose are AT commands
def send_at_command(command):
    ser.write(str.encode(command))
    time.sleep(0.1)


# used to send 'String' messages via AT+SEND
def send_message(message):
    send_at_command("AT+SEND=" + str(len(message)) + "\r\n")
    time.sleep(0.1)
    send_at_command(str(message) + "\r\n")


print("Ready to send data....")


def command_line():
Example #33
0
import gym
import serial.tools.list_ports
from serial import Serial


def fformat(float):
    return str("{:.2f}".format(float))


env = gym.make('MountainCar-v0')

print("Available serial ports:")
for i in serial.tools.list_ports.comports():
    print(i)

ser = Serial('COM11', baudrate=115200)  # open serial port
print("Selected port:")
print(ser.name)  # check which port was really used

while True:
    observation = env.reset()

    for step in range(300):
        # send observation to the device
        obs_str = ';'.join(map(fformat, observation))
        #For debug purposes
        #print("-> " + obs_str)
        obs_str = obs_str + "\n"
        ser.write(obs_str.encode())  # write a string

        #read action from the device
Example #34
0
 def on_reconnect_clicked(self):
     self.serial.close()
     self.serial = Serial(self.port)
     self.board_control_frame.set_serial(self.serial)
Example #35
0
class ConnectionFrame(Frame):

    BOARD_VALUE_SEGMENT14 = 1
    BOARD_VALUE_SEGMENT25 = 2

    board_names = {
        BOARD_VALUE_SEGMENT14: "14 segment board",
        BOARD_VALUE_SEGMENT25: "25 segment board"
    }

    def __init__(self, master, cnf={}, **kw):
        super().__init__(master, cnf, **kw)

        self.connecting_frame = Frame(self)
        self.connecting_frame.grid(row=1, column=1, padx=10, pady=10)
        Label(self.connecting_frame, text="Connection", font=header_font).grid(row=1)
        connecting_radiobutton_frame = Frame(self.connecting_frame)
        connecting_radiobutton_frame.grid(row=2, pady=10)
        self.board_var = IntVar()
        self.board_var.set(self.BOARD_VALUE_SEGMENT14)
        for i in self.board_names:
            Radiobutton(connecting_radiobutton_frame, text=self.board_names[i], variable=self.board_var, value=i,
                        font=radiobutton_font).pack()
        connecting_internal_frame = Frame(self.connecting_frame)
        connecting_internal_frame.grid(row=3, pady=(10, 0))
        self.listbox = Listbox(connecting_internal_frame, width=35, selectmode=SINGLE)
        self.listbox.grid(row=1, column=1)
        connecting_button_frame = Frame(connecting_internal_frame)
        connecting_button_frame.grid(row=1, column=2, padx=(15, 0))
        Button(connecting_button_frame, text="Connect", font=button_font, width=12,
               command=self.on_connect_clicked).grid(row=1)
        Button(connecting_button_frame, text="Search", font=button_font, width=12,
               command=self.on_search_clicked).grid(row=2)
        self.on_search_clicked()

        self.connect_control_frame = Frame(self)
        self.connect_control_frame.grid(row=1, column=1, padx=10, pady=10)
        self.connect_control_frame.grid_remove()
        self.connect_control_message = Message(self.connect_control_frame, font=text_font, width=200)
        self.connect_control_message.grid(row=1, column=1)
        connect_control_button_frame = Frame(self.connect_control_frame)
        connect_control_button_frame.grid(row=1, column=2, padx=(10, 0))
        Button(connect_control_button_frame, text="Reconnect", font=button_font, width=10,
               command=self.on_reconnect_clicked).grid(row=1, column=1)
        Button(connect_control_button_frame, text="Disconnect", font=button_font, width=10,
               command=self.on_disconnect_clicked).grid(row=2, column=1)

    def on_connect_clicked(self):
        self.port = self.listbox.get(ACTIVE)
        self.serial = Serial(self.port)
        self.connect_control_message['text'] = "Connected to " + self.port + " as to " + self.board_names[
            self.board_var.get()]
        self.connecting_frame.grid_remove()
        self.connect_control_frame.grid()
        value = self.board_var.get()
        if value is self.BOARD_VALUE_SEGMENT14:
            self.board_control_frame = board_controller.Segment14Frame(self.serial, self)
        elif value is self.BOARD_VALUE_SEGMENT25:
            self.board_control_frame = board_controller.CircleSegmentsOnTransistors(self.serial, 5, 5, self)
        self.board_control_frame.grid(row=2, column=1, padx=10, pady=10)

    def on_search_clicked(self):
        self.listbox.delete(0, END)
        port_strings = subprocess.check_output(['python', '-m', 'serial.tools.list_ports']).decode(
            'utf-8').strip().split()
        for i in range(len(port_strings)):
            self.listbox.insert(i, port_strings[i])

    def on_reconnect_clicked(self):
        self.serial.close()
        self.serial = Serial(self.port)
        self.board_control_frame.set_serial(self.serial)

    def on_disconnect_clicked(self):
        self.serial.close()
        self.board_control_frame.destroy()
        self.connect_control_frame.grid_remove()
        self.connecting_frame.grid()
Example #36
0
class ArduinoReader:
    def __init__(self):
        self.serial_port = Serial(port='/dev/ttyUSB0', baudrate=230400)
        self.newArduino = False
        self.threadsDieNow = False

    def findNb1Faibles(self, x):
        res = 0
        temp = x
        for i in range(0, 8):
            if temp & 1 == 1:
                res = res + 1
                temp = temp >> 1
            else:
                return res
        return res

    def findNb1Forts(self, x):
        res = 0
        temp = x
        for i in range(0, 8):
            if temp & 128 != 0:
                res = res + 1
                temp = temp << 1
            else:
                return res
        return res

    def calcMasque(self):
        res = 0
        for i in range(0, self.offset):
            res = res << 1 | 1
        self.masque = res

    def findBytes(self, x, y):
        res = x & self.masque
        res = res << (8 - self.offset)
        res = res | (y >> self.offset)
        return res

    def concat(self, faible, fort):
        return faible | (fort << 8)

    def continuousStart(self):
        """CALL THIS to start running forever."""
        self.t = threading.Thread(target=self.readUSB)
        self.t.start()

    def getArduino(self):
        return self.arduino

    def readUSB(self, forever=True):

        res = np.arange(0, 64)
        compteur = 0
        begin = True
        prevInInt = 0
        prevByte = 0

        while True:
            if self.threadsDieNow: break

            # reperer le premier caractere de debut et l'offset de decalage pour chaque octet
            while begin:
                if self.serial_port.inWaiting():

                    if prevInInt != 255:
                        inInt = int(binascii.hexlify(self.serial_port.read(1)),
                                    16)
                    else:
                        prevInInt = 0

                    nb1faibles = self.findNb1Faibles(prevInInt)
                    nb1forts = self.findNb1Forts(inInt)

                    self.offset = nb1faibles
                    if self.offset + nb1forts >= 8:

                        begin = False
                        self.calcMasque()

                    prevInInt = inInt

            if self.serial_port.inWaiting():

                inInt = int(binascii.hexlify(self.serial_port.read(1)), 16)

                curByte = self.findBytes(prevInInt, inInt)

                if compteur < 128:
                    if compteur % 2 == 1:
                        res[compteur / 2] = self.concat(prevByte, curByte) / 40
                    compteur = compteur + 1

                else:

                    compteur = 0

                    self.arduino = res
                    self.newArduino = True
                    begin = True

                prevByte = curByte
                prevInInt = inInt

                if forever == False:
                    break
Example #37
0
 def __init__(self):
     self.serial_port = Serial(port='/dev/ttyUSB0', baudrate=230400)
     self.newArduino = False
     self.threadsDieNow = False
Example #38
0
#!/usr/bin/env python3

from serial import Serial
import bitarray
import time

ser = Serial('/dev/ttyUSB0', 115200)

for i in range(1, 100):
    for a in range(0, 16):
        ser.write(b'\xcc')
        ser.write((1 << a).to_bytes(2, byteorder='big'))
        #ser.write(b.to_bytes(1, byteorder='big'))
        ser.write(b'\xff')
        print("Count: {} ".format(a))
        time.sleep(0.5)

    for a in range(0, 16):
        ser.write(b'\xcc')
        ser.write(((2**15) >> a).to_bytes(2, byteorder='big'))
        #ser.write(b.to_bytes(1, byteorder='big'))
        ser.write(b'\xff')
        print("Count: {} ".format(a))
        time.sleep(0.5)

for a in range(0, 256):
    for b in range(0, 256):
        ser.write(b'\xcc')
        ser.write(a.to_bytes(1, byteorder='big'))
        ser.write(b.to_bytes(1, byteorder='big'))
        ser.write(b'\xff')
Example #39
0
def main():
    """ The main function. """
    parser = argparse.ArgumentParser(
        description='Tool to bootload a power module.')
    parser.add_argument('--address',
                        dest='address',
                        type=int,
                        help='the address of the power module to bootload')
    parser.add_argument('--all',
                        dest='all',
                        action='store_true',
                        help='bootload all power modules')
    parser.add_argument('--file',
                        dest='file',
                        help='the filename of the hex file to bootload')
    parser.add_argument('--8',
                        dest='old',
                        action='store_true',
                        help='bootload for the 8-port power modules')
    parser.add_argument('--version',
                        dest='version',
                        action='store_true',
                        help='display the version of the power module(s)')
    parser.add_argument('--verbose',
                        dest='verbose',
                        action='store_true',
                        help='show the serial output')

    args = parser.parse_args()

    config = ConfigParser()
    config.read(constants.get_config_file())

    port = config.get('OpenMotics', 'power_serial')
    power_serial = RS485(Serial(port, 115200))
    power_communicator = PowerCommunicator(power_serial,
                                           None,
                                           time_keeper_period=0,
                                           verbose=args.verbose)
    power_communicator.start()

    if args.address or args.all:
        power_controller = PowerController(constants.get_power_database_file())
        power_modules = power_controller.get_power_modules()
        if args.all:
            for module_id in power_modules:
                module = power_modules[module_id]
                addr = module['address']
                if args.version:
                    print "E%d - Version: %s" % (
                        addr, version(addr, power_communicator))
                if args.file:
                    if args.old and module['version'] == POWER_API_8_PORTS:
                        bootload_8(addr,
                                   args.file,
                                   power_communicator,
                                   verbose=args.verbose)
                    elif not args.old and module[
                            'version'] == POWER_API_12_PORTS:
                        bootload_12(addr,
                                    args.file,
                                    power_communicator,
                                    verbose=args.verbose)

        else:
            addr = args.address
            modules = [
                module for module in power_modules.keys()
                if module['address'] == addr
            ]
            if len(modules) != 1:
                print 'ERROR: Could not determine energy module version. Aborting'
                sys.exit(1)
            if args.version:
                print "E%d - Version: %s" % (addr,
                                             version(addr, power_communicator))
            if args.file:
                if args.old and module['version'] == POWER_API_8_PORTS:
                    bootload_8(addr,
                               args.file,
                               power_communicator,
                               verbose=args.verbose)
                elif not args.old and module['version'] == POWER_API_12_PORTS:
                    bootload_12(addr,
                                args.file,
                                power_communicator,
                                verbose=args.verbose)

    else:
        parser.print_help()
Example #40
0
 def __init__(self, device, timeout=5):  # timeout in seconds
     self.device = Serial(device)
     self.read_timeout = timeout
     self.is_open = False
Example #41
0
class BTLEJackDevice(wireless.Device):
    '''
	This device allows to communicate with a BTLEJack Device in order to sniff Bluetooth Low Energy protocol.
	The corresponding interfaces are : ``microbitX`` (e.g. "microbit0")

	The following capabilities are actually supported :

	+-----------------------------------+----------------+
	| Capability			    | Available ?    |
	+===================================+================+
	| SCANNING                          | yes            |
	+-----------------------------------+----------------+
	| ADVERTISING                       | no             |
	+-----------------------------------+----------------+
	| SNIFFING_ADVERTISEMENTS           | yes            |
	+-----------------------------------+----------------+
	| SNIFFING_NEW_CONNECTION           | yes            |
	+-----------------------------------+----------------+
	| SNIFFING_EXISTING_CONNECTION      | yes            |
	+-----------------------------------+----------------+
	| JAMMING_CONNECTIONS               | yes            |
	+-----------------------------------+----------------+
	| JAMMING_ADVERTISEMENTS            | yes            |
	+-----------------------------------+----------------+
	| HIJACKING_CONNECTIONS             | yes            |
	+-----------------------------------+----------------+
	| INITIATING_CONNECTION             | no             |
	+-----------------------------------+----------------+
	| RECEIVING_CONNECTION              | no             |
	+-----------------------------------+----------------+
	| COMMUNICATING_AS_MASTER           | yes            |
	+-----------------------------------+----------------+
	| COMMUNICATING_AS_SLAVE            | no             |
	+-----------------------------------+----------------+
	| HCI_MONITORING                    | no             |
	+-----------------------------------+----------------+

	'''
    sharedMethods = [
        "getFirmwareVersion", "getDeviceIndex", "setCRCChecking", "setChannel",
        "getChannel", "sniffNewConnections", "sniffExistingConnections",
        "sniffAdvertisements", "jamAdvertisements",
        "disableAdvertisementsJamming", "setSweepingMode", "setScan",
        "setScanInterval", "getConnections", "switchConnection",
        "getCurrentConnection", "isConnected", "isSynchronized",
        "getCurrentHandle", "getAccessAddress", "getCrcInit", "getChannelMap",
        "getHopInterval", "getHopIncrement", "setJamming", "setHijacking"
    ]

    def setJamming(self, enable=True):
        '''
		This method allows to enable or disable the jamming mode.
	
		:param enable: boolean indicating if the jamming mode must be enabled or disabled
		:type enable: bool

		:Example:
		
			>>> device.setJamming(enable=True) # jamming mode enabled
			>>> device.setJamming(enable=False) # jamming mode disabled

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        self.jamming = enable

    def setHijacking(self, enable=True):
        '''
		This method allows to enable or disable the hijacking mode.
	
		:param enable: boolean indicating if the hijacking mode must be enabled or disabled
		:type enable: bool

		:Example:
		
			>>> device.setHijacking(enable=True) # hijacking mode enabled
			>>> device.setHijacking(enable=False) # hijacking mode disabled

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        self.hijacking = enable

    def getCurrentHandle(self):
        '''
		This method returns the connection Handle actually in use.
		If no connection is established, its value is equal to -1.

		:return: connection Handle
		:rtype: int

		.. warning::
		
			This method always returns 1, it allows to provides the same API as the HCI Device.

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        return 1

    def getConnections(self):
        '''
		This method returns a list of couple (connection handle / address) representing the connections actually established.
		A connection is described by a dictionary containing an handle and an access address : ``{"handle":1, "address":"0x12345678"}``

		:return: list of connections established
		:rtype: list of dict

		:Example:
			
			>>> device.getConnections()
			[{'handle':1, 'address':'0x12345678'}]

		.. warning::
		
			The connection handle is always 1, it allows to provides the same API as the HCI Device.

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        return [{
            "address": "0x{:08x}".format(self.accessAddress),
            "handle": 1
        }]

    def getCurrentConnection(self):
        '''
		This method returns the access address associated to the current connection. If no connection is established, it returns None.

		:return: access address of the current connection
		:rtype: str

		:Example:
		
			>>> device.getCurrentConnection()
			'0x12345678'
			
		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        return "0x{:08x}".format(self.accessAddress)

    def switchConnection(self, address):
        '''
		This method is provided in order to provide the same API as an HCI Device, it actually has no effects.

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        io.fail("Switching connection not allowed with BTLEJack Device !")

    def isConnected(self):
        '''
		This method returns a boolean indicating if a connection is actually established and hijacked.

		:return: boolean indicating if a connection is established and hijacked
		:rtype: bool

		:Example:
		
			>>> device.isConnected()
			True

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        return self.hijacked

    def isSynchronized(self):
        '''
		This method indicates if the sniffer is actually synchronized with a connection.

		:return: boolean indicating if the sniffer is synchronized
		:rtype: bool

		:Example:

			>>> device.isSynchronized()
			True

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        return self.synchronized

    @classmethod
    def findMicrobits(cls, index=None):
        '''
		This class method allows to find a specific BTLEJack device, by providing the device's index. 
		If no index is provided, it returns a list of every devices found.
		If no device has been found, None is returned.

		:param index: device's index
		:type index: int
		:return: string indicating the device
		:rtype: str

		:Example:
			
			>>> BTLEJackDevice.findMicrobits(0)
			'/dev/ttyACM0'
			>>> BTLEJackDevice.findMicrobits()
			['/dev/ttyACM0','/dev/ttyACM1']

		
		'''
        microbitList = [
            i[0] for i in comports()
            if (isinstance(i, tuple) and "VID:PID=0d28:0204" in port[-1]) or (
                i.vid == 0x0D28 and i.pid == 0x0204)
        ]
        if index is None:
            return microbitList
        else:
            try:
                microbit = microbitList[index]
            except IndexError:
                return None
            return microbit
        return None

    def __init__(self, interface):
        super().__init__(interface=interface)
        customPort = None
        if "microbit" == interface:
            self.index = 0
            self.interface = "microbit0"
        elif "microbit" == interface[:8]:
            if ":" in interface:
                fields = interface.split(":")
                customPort = fields[1]
                self.index = customPort
            else:
                self.index = int(interface.split("microbit")[1])
            self.interface = interface
        if not customPort:
            self.microbit = BTLEJackDevice.findMicrobits(self.index)
        else:
            self.microbit = customPort
        if self.microbit is not None:
            try:
                self.microbit = Serial(port=self.microbit,
                                       baudrate=115200,
                                       timeout=0)
                self.ready = False
                self._flush()
            except SerialException:
                io.fail("Serial communication not ready !")
                self.ready = False
                self.microbit = None
        else:
            io.fail("No btlejack device found !")
            self.ready = False

    def _enterListening(self):
        self.isListening = True

    def _exitListening(self):
        self.isListening = False

    def _isListening(self):
        return self.isListening

    def _cancelFollow(self):  # TODO
        pass

    def setChannel(self, channel=37):
        '''
		This method changes the channel actually in use by the provided channel.

		:param channel: new channel
		:type channel: int

		:Example:

			>>> device.getChannel()
			37
			>>> device.setChannel(channel=38)
			>>> device.getChannel()
			38

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        self.channel = channel

    def getChannel(self):
        '''
		This method returns the channel actually in use.

		:return: channel in use
		:rtype: int

		:Example:
			
			>>> device.getChannel()
			37
			>>> device.setChannel(channel=38)
			>>> device.getChannel()
			38

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        return self.channel

    def _flush(self):
        while self.microbit.in_waiting:
            self.microbit.read()

    def _flushCommandResponses(self):
        while not self.commandResponses.empty():
            self.commandResponses.get()

    def _internalCommand(self, cmd, noResponse=False):
        packet = BTLEJack_Hdr() / cmd
        self._flushCommandResponses()

        def getFunction():
            if not self._isListening() or self.commandResponses.empty():
                func = self._recv
            else:
                func = self.commandResponses.get
            return func

        self._send(packet)
        if not noResponse:

            getResponse = getFunction()
            response = getResponse()
            while response is None or response.packet_type == 4 or response.opcode != packet.opcode:
                getResponse = getFunction()
                response = getResponse()
            return response

    def _getFirmwareVersion(self):
        pkt = self._internalCommand(BTLEJack_Version_Command())
        return (pkt.major, pkt.minor)

    def _reset(self):
        self._internalCommand(BTLEJack_Reset_Command())

    def getFirmwareVersion(self):
        '''
		This method returns the firmware version of the current BTLEJack device.

		:return: firmware version as a tuple of (major, minor)
		:rtype: tuple of (int,int)

		:Example:
			
			>>> device.getFirmwareVersion()
			(3,14)

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.


		'''
        version = self._getFirmwareVersion()
        return version

    def getDeviceIndex(self):
        '''
		This method returns the index of the current BTLEJack device.

		:return: device's index
		:rtype: int

		:Example:
			
			>>> device.getDeviceIndex()
			0

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.


		'''
        return self.index

    def _send(self, packet):
        self.lock.acquire()
        self.microbit.write(raw(packet))
        self.lock.release()

    def send(self, packet):
        command = None
        if BTLE_DATA in packet:
            command = BTLEJack_Hdr() / BTLEJack_Send_Packet_Command(
                ble_payload=packet[BTLE_DATA:])
        if self.isConnected(
        ) and CtrlPDU in command.ble_payload and command.ble_payload.optcode == 0x02:
            self.hijacked = False
        if command is not None:
            self._send(raw(command))

    # New Connection Sniffing methods

    def sniffNewConnections(self, address="FF:FF:FF:FF:FF:FF", channel=None):
        '''
		This method starts the new connections sniffing mode.

		:param address: selected address - if not provided, no filter is applied (format : "1A:2B:3C:4D:5E:6F")
		:type address: str
		:param channel: selected channel - if not provided, channel 37 is selected
		:type channel: int

		:Example:

			>>> device.sniffNewConnections()
			>>> device.sniffNewConnections(channel=38)
			>>> device.sniffNewConnections(address="1A:2B:3C:4D:5E:6F")
			
		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        self.synchronized = False
        self.hijacked = False
        self.sniffingMode = BLESniffingMode.NEW_CONNECTION
        self.lastTarget = address
        self._sniffConnectionRequests(address=address, channel=channel)

    def _sniffConnectionRequests(self,
                                 address='FF:FF:FF:FF:FF:FF',
                                 channel=None):
        if channel is not None and not self.sweepingMode:
            self.setChannel(channel)

        self._internalCommand(
            BTLEJack_Sniff_Connection_Request_Command(
                address=address,
                channel=self.getChannel() if channel is None else channel))

    # Existing Connection Sniffing methods
    def sniffExistingConnections(self,
                                 accessAddress=None,
                                 crcInit=None,
                                 channelMap=None):
        '''
		This method starts the existing connections sniffing mode.

		:param accessAddress: selected Access Address - if not provided, the parameter is recovered
		:type address: int
		:param crcInit: selected CRCInit - if not provided, the parameter is recovered
		:type crcInit: int
		:param channelMap: selected Channel Map - if not provided, the parameter is recovered
		:type channelMap: int


		:Example:

			>>> device.sniffExistingConnections()
			>>> device.sniffExistingConnections(accessAddress=0xe5e296e9)
			>>> device.sniffExistingConnections(accessAddress=0xe5e296e9, crcInit=0x0bd54a)
			>>> device.sniffExistingConnections(accessAddress=0xe5e296e9, crcInit=0x0bd54a, channelMap=0x1fffffffff)
			
		.. warning::

			If no access address is provided, BTLEJack tries to get multiple candidate access addresses and select the most probable address.

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        self.hijacked = False
        self.synchronized = False
        self.sniffingMode = BLESniffingMode.EXISTING_CONNECTION
        if accessAddress is None:
            self._listAccessAddress()
        else:
            self._setAccessAddress(accessAddress)
            if crcInit is None:
                self._recoverFromAccessAddress(accessAddress)
            else:
                self._setCrcInit(crcInit)

                if channelMap is None:
                    self._recoverFromCrcInit(accessAddress, crcInit)
                else:
                    self._setChannelMap(channelMap)
                    self._recoverFromChannelMap(accessAddress, crcInit,
                                                channelMap)

    def _resetFilteringPolicy(self, policyType="blacklist"):
        policy = 0x00 if policyType == "blacklist" else 0x01
        self._internalCommand(
            BTLEJack_Advertisements_Command() /
            BTLEJack_Advertisements_Reset_Policy_Command(policy_type=policy))

    def _addFilteringRule(self, pattern=b"", mask=None, position=None):
        if position is None:
            position = 0xFF
        if mask is None:
            mask = len(pattern) * b"\xFF"
        self._internalCommand(BTLEJack_Advertisements_Command() /
                              BTLEJack_Advertisements_Add_Rule_Command() /
                              BTLEJack_Filtering_Rule(
                                  data=pattern, mask=mask, position=position))

    def sniffAdvertisements(self, address='FF:FF:FF:FF:FF:FF', channel=None):
        '''
		This method starts the advertisement sniffing mode.

		:param address: selected address - if not provided, no filter is applied (format : "1A:2B:3C:4D:5E:6F")
		:type address: str
		:param channel: selected channel - if not provided, channel 37 is selected
		:type channel: int

		:Example:

			>>> device.sniffAdvertisements()
			>>> device.sniffAdvertisements(channel=38)
			>>> device.sniffAdvertisements(address="1A:2B:3C:4D:5E:6F")

		.. warning::
		
			This method requires the custom Mirage Firmware in order to sniff advertisements.
				
		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        if self.customMirageFirmware:
            self.sniffingMode = BLESniffingMode.ADVERTISEMENT
            self.synchronized = False
            self.hijacked = False
            if channel is not None and not self.sweepingMode:
                self.setChannel(channel)

            if address.upper() == "FF:FF:FF:FF:FF:FF":
                self._resetFilteringPolicy("blacklist")
            else:
                self._resetFilteringPolicy("whitelist")
                target = bytes.fromhex(address.replace(":", ""))[::-1]
                self._addFilteringRule(pattern=target, position=2)

            self._internalCommand(
                BTLEJack_Advertisements_Command() /
                BTLEJack_Advertisements_Disable_Sniff_Command())
            self._internalCommand(
                BTLEJack_Advertisements_Command() /
                BTLEJack_Advertisements_Enable_Sniff_Command(
                    channel=self.getChannel() if channel is None else channel))
        else:
            io.fail(
                "Sniffing advertisements is not supported by BTLEJack firmware,"
                " a Custom Mirage Firmware is available.")

    def jamAdvertisements(self, pattern=b"", offset=0, channel=37):
        '''
		This method reactively jams advertisements according to the specified pattern, offset and channel provided.

		:param pattern: pattern contained in payload indicating that the packet must be jammed
		:type pattern: bytes
		:param offset: offset indicating the position of pattern in the payload
		:type offset: int
		:param channel: selected channel - if not provided, channel 37 is selected
		:type channel: int

		:Example:

			>>> target = "1A:2B:3C:4D:5E:6F"
			>>> pattern = bytes.fromhex(target.replace(":",""))[::-1]
			>>> device.jamAdvertisements(pattern=pattern,offset=2,channel=39) # jam the advertisements transmitted by 1A:2B:3C:4D:5E:6F on channel 39

		.. warning::
		
			This method requires the custom Mirage Firmware in order to jam advertisements.
				
		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        if self.customMirageFirmware:
            self.synchronized = False
            self.hijacked = False
            self.jammingEnabled = True
            if channel is not None:
                self.setChannel(channel)
            self._internalCommand(
                BTLEJack_Advertisements_Command() /
                BTLEJack_Advertisements_Enable_Jamming_Command(
                    offset=offset,
                    pattern=pattern,
                    channel=self.getChannel() if channel is None else channel))
        else:
            io.fail(
                "Jamming advertisements is not supported by BTLEJack firmware,"
                " a Custom Mirage Firmware is available.")

    def _listAccessAddress(self):
        io.info("Recovering access address ...")
        self._internalCommand(BTLEJack_Scan_Connections_Command())

    def _setAccessAddress(self, accessAddress=None):
        self.accessAddress = accessAddress

    def _setCrcInit(self, crcInit=None):
        self.crcInit = crcInit

    def _setChannelMap(self, channelMap=None):
        self.channelMap = channelMap

    def _setHopInterval(self, hopInterval=None):
        self.hopInterval = hopInterval

    def _getHopInterval(self):
        return self.hopInterval

    def _setHopIncrement(self, hopIncrement):
        self.hopIncrement = hopIncrement

    def _getHopIncrement(self):
        return self.hopIncrement

    def _getChannelMap(self):
        return self.channelMap

    def _getAccessAddress(self):
        return self.accessAddress

    def _getCrcInit(self):
        return self.crcInit

    def _updateCrcInit(self, crcInit=None):
        io.success("CRCInit successfully recovered : " +
                   "0x{:06x}".format(crcInit))
        self._setCrcInit(crcInit)
        self._recoverFromCrcInit()

    def _updateChannelMap(self, channelMap=None):
        io.success("Channel Map successfully recovered : " +
                   "0x{:10x}".format(channelMap))
        self._setChannelMap(channelMap)
        self._recoverFromChannelMap()

    def _updateHopInterval(self, hopInterval=None):
        io.success("Hop Interval successfully recovered : " + str(hopInterval))
        self._setHopInterval(hopInterval)
        io.info("Recovering Hop Increment ...")

    def _updateHopIncrement(self, hopIncrement=None):
        io.success("Hop Increment successfully recovered : " +
                   str(hopIncrement))
        self._setHopIncrement(hopIncrement)
        io.info("All parameters recovered, following connection ...")

    def _recoverFromAccessAddress(self, accessAddress):
        aa = accessAddress if accessAddress is not None else self._getAccessAddress(
        )
        io.info("Recovering CRCInit ...")
        self._reset()
        pkt = self._internalCommand(
            BTLEJack_Recover_Command() /
            BTLEJack_Recover_Connection_AA_Command(access_address=aa))

    def _recoverFromCrcInit(self, accessAddress=None, crcInit=None):
        aa = accessAddress if accessAddress is not None else self._getAccessAddress(
        )
        crcInit = crcInit if crcInit is not None else self._getCrcInit()
        io.info("Recovering ChannelMap ...")
        self._reset()
        pkt = self._internalCommand(BTLEJack_Recover_Command() /
                                    BTLEJack_Recover_Channel_Map_Command(
                                        access_address=aa, crc_init=crcInit))
        io.progress(0, total=36, suffix="0/36 channels")

    def _recoverFromChannelMap(self,
                               accessAddress=None,
                               crcInit=None,
                               channelMap=None):
        aa = accessAddress if accessAddress is not None else self._getAccessAddress(
        )
        crcInit = crcInit if crcInit is not None else self._getCrcInit()
        channelMap = channelMap if channelMap is not None else self._getChannelMap(
        )
        io.info("Recovering Hop Interval ...")
        self._reset()
        pkt = self._internalCommand(
            BTLEJack_Recover_Command() /
            BTLEJack_Recover_Hopping_Parameters_Command(
                access_address=aa, crc_init=crcInit, channel_map=channelMap))

    def _addCandidateAccessAddress(self,
                                   accessAddress=None,
                                   rssi=None,
                                   channel=None):
        io.info("Candidate access address found : " +
                "0x{:08x}".format(accessAddress) + " (rssi = -" + str(rssi) +
                "dBm / channel = " + str(channel) + ")")
        if accessAddress not in self.candidateAccessAddresses:
            self.candidateAccessAddresses[accessAddress] = {
                "hits": 1,
                "rssi": rssi,
                "channels": set([channel])
            }
        else:
            self.candidateAccessAddresses[accessAddress]["hits"] += 1
            self.candidateAccessAddresses[accessAddress]["channels"].add(
                channel)

        if self.candidateAccessAddresses[accessAddress]["hits"] >= 5:
            io.success("Access Address selected : " +
                       "0x{:08x}".format(accessAddress))
            self._setAccessAddress(accessAddress)
            self._recoverFromAccessAddress(accessAddress=accessAddress)

    def _recv(self):
        self.lock.acquire()
        if self.microbit is not None and self.microbit.in_waiting:
            self.receptionBuffer += self.microbit.read()
        self.lock.release()

        if len(self.receptionBuffer) > 0:
            try:
                start = self.receptionBuffer.index(0xBC)
                self.receptionBuffer = self.receptionBuffer[start:]

            except ValueError:
                self.receptionBuffer = b""

            if len(self.receptionBuffer) >= 4:
                size = struct.unpack('<H', self.receptionBuffer[2:4])[0]
                if len(self.receptionBuffer) >= size + 5:
                    #print(self.receptionBuffer[:size+5].hex())
                    pkt = BTLEJack_Hdr(self.receptionBuffer[:size + 5])
                    self.receptionBuffer = self.receptionBuffer[size + 5:]
                    return pkt
                else:
                    receptionBuffer = b""

        return None

    def disableAdvertisementsJamming(self):
        if self.jammingEnabled:
            self._internalCommand(
                BTLEJack_Advertisements_Command() /
                BTLEJack_Advertisements_Disable_Jamming_Command())

    def close(self):
        self.lock.acquire()
        self._stopSweepingThread()
        self.microbit.close()
        self.microbit = None
        self.lock.release()

    def isUp(self):
        return self.microbit is not None

    def setCRCChecking(self, enable=True):
        '''
		This method enables CRC Checking.
		
		:param enable: boolean indicating if CRC Checking must be enabled
		:type enable: bool

		:Example:
	
			>>> device.setCRCChecking(enable=True) # CRC Checking enabled
			>>> device.setCRCChecking(enable=False) # CRC Checking disabled

		.. warning::

			BTLEJack calculates the CRC directly in the firmware, so this command is ignored. It is present in order to provide a similar API to Ubertooth.
			
		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        self.crcEnabled = enable

    def setAccessAddress(self, accessAddress):
        '''
		This method sets the access address to use.
	
		:param accessAddress: new access address
		:type accessAddress: int

		:Example:

			>>> device.setAccessAddress(0xe5e296e9)


		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        self.accessAddress = accessAddress

    def getAccessAddress(self):
        '''
		This method returns the access address actually in use.
	
		:return: access address
		:rtype: int

		:Example:

			>>> hex(device.getAccessAddress())
			'0xe5e296e9'


		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        return self.accessAddress

    def getCrcInit(self):
        '''
		This method returns the CRCInit actually in use.
	
		:return: CRCInit
		:rtype: int

		:Example:

			>>> hex(device.getCrcInit())
			'0x0bd54a'

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        return self.crcInit

    def getChannelMap(self):
        '''
		This method returns the Channel Map actually in use.
	
		:return: Channel Map
		:rtype: int

		:Example:

			>>> hex(device.getChannelMap())
			'0x1fffffffff'

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.


		'''
        return self.channelMap

    def getHopInterval(self):
        '''
		This method returns the Hop Interval actually in use.
	
		:return: Hop Interval
		:rtype: int

		:Example:

			>>> device.getHopInterval()
			36

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.


		'''
        return self.hopInterval

    def getHopIncrement(self):
        '''
		This method returns the Hop Increment actually in use.
	
		:return: Hop Increment
		:rtype: int

		:Example:

			>>> device.getHopIncrement()
			11

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.


		'''
        return self.hopIncrement

    def restartSniffingMode(self):
        '''
		This method restarts the sniffing mode.

		:Example:
	
			>>> device.restartSniffingMode()

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.


		'''
        if self.sniffingMode == BLESniffingMode.NEW_CONNECTION:
            self.sniffNewConnections()
        else:
            self.sniffExistingConnections()

    def recv(self):
        self._enterListening()
        pkt = self._recv()
        self._exitListening()
        if pkt is not None:

            if self.customMirageFirmware and BTLEJack_Advertisement_Packet_Notification in pkt:
                timestamp = time.time()
                ts_sec = int(timestamp)
                ts_usec = int((timestamp - ts_sec) * 1000000)

                if pkt.crc_ok == 0x01:
                    io.success("CRC OK !")
                else:
                    io.fail("CRC not OK !")

                if pkt.crc_ok != 0x01 and self.crcEnabled:
                    return None

                return BTLE_PPI(btle_channel=pkt.channel,
                                btle_clkn_high=ts_sec,
                                btle_clk_100ns=ts_usec,
                                rssi_max=-pkt.rssi,
                                rssi_min=-pkt.rssi,
                                rssi_avg=-pkt.rssi,
                                rssi_count=1) / BTLE() / BTLE_ADV(
                                    pkt.ble_payload)
            if BTLEJack_Access_Address_Notification in pkt:
                self._addCandidateAccessAddress(
                    accessAddress=pkt.access_address,
                    rssi=pkt.rssi,
                    channel=pkt.channel)
            if BTLEJack_CRCInit_Notification in pkt:
                self._updateCrcInit(crcInit=pkt.crc_init)
            if BTLEJack_Channel_Map_Notification in pkt:
                self._updateChannelMap(channelMap=pkt.channel_map)
            if BTLEJack_Verbose_Response in pkt and b"c=" in pkt.message:
                currentChannel = pkt.message.decode('ascii').split("c=")[1]
                io.progress(int(currentChannel),
                            total=36,
                            suffix=str(currentChannel) + "/36 channels")
            if BTLEJack_Verbose_Response in pkt and b"ADV_JAMMED" in pkt.message:
                io.info("Advertisement jammed on channel #" +
                        str(self.getChannel()))
            if BTLEJack_Verbose_Response in pkt:
                io.info(pkt.message.decode('ascii'))
            if BTLEJack_Hop_Interval_Notification in pkt:
                self._updateHopInterval(pkt.hop_interval)
            if BTLEJack_Hop_Increment_Notification in pkt:
                self._updateHopIncrement(pkt.hop_increment)
                if self.hijacking:
                    self._internalCommand(
                        BTLEJack_Enable_Hijacking_Command(enabled=0x01))
                elif self.jamming:
                    self._internalCommand(
                        BTLEJack_Enable_Jamming_Command(enabled=0x01))
                self.synchronized = True

            if BTLEJack_Hijack_Status_Notification in pkt:
                self.hijacked = (pkt.status == 0x00)

            if BTLEJack_Nordic_Tap_Packet_Notification in pkt:
                timestamp = time.time()
                ts_sec = int(timestamp)
                ts_usec = int((timestamp - ts_sec) * 1000000)

                return BTLE_PPI(
                    btle_channel=pkt.channel,
                    btle_clkn_high=ts_sec,
                    btle_clk_100ns=ts_usec,
                    rssi_max=pkt.rssi,
                    rssi_min=pkt.rssi,
                    rssi_avg=pkt.rssi,
                    rssi_count=1) / BTLE(
                        access_addr=self.getAccessAddress()) / pkt.ble_payload
            elif BTLEJack_Connection_Request_Notification in pkt:
                self._setAccessAddress(
                    struct.unpack(">I", struct.pack("<I",
                                                    pkt.ble_payload.AA))[0])
                self._setCrcInit(
                    struct.unpack(
                        ">I", b"\x00" +
                        struct.pack('<I', pkt.ble_payload.crc_init)[:3])[0])
                self._setChannelMap(pkt.ble_payload.chM)
                self._setHopInterval(pkt.ble_payload.interval)
                self._setHopIncrement(pkt.ble_payload.hop)
                self.synchronized = True
                timestamp = time.time()
                ts_sec = int(timestamp)
                ts_usec = int((timestamp - ts_sec) * 1000000)

                return BTLE_PPI(btle_channel=self.channel,
                                btle_clkn_high=ts_sec,
                                btle_clk_100ns=ts_usec,
                                rssi_max=0,
                                rssi_min=0,
                                rssi_avg=0,
                                rssi_count=1) / BTLE() / BTLE_ADV(
                                    RxAdd=pkt.RxAdd,
                                    TxAdd=pkt.TxAdd,
                                    RFU=pkt.RFU,
                                    PDU_type=pkt.PDU_type) / pkt.ble_payload
            elif BTLEJack_Connection_Lost_Notification in pkt or pkt.packet_type == 0x4 and pkt.notification_type == 0x9:
                io.fail("Connection lost !")
                self._reset()
                self.restartSniffingMode()
                self._setAccessAddress(None)
                self._setCrcInit(None)
                self._setChannelMap(None)
                self._setHopInterval(None)
                self._setHopIncrement(None)
                self.hijacked = False
                self.synchronized = False
            else:
                self.commandResponses.put(pkt)
        else:
            utils.wait(seconds=0.0001)

    def setScanInterval(self, seconds=1):
        '''
		This method allows to provide the scan interval (in second).
	
		:param seconds: number of seconds to wait between two channels
		:type seconds: float

		:Example:

			>>> device.setScanInterval(seconds=1)

		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.


		'''
        self.scanInterval = seconds

    def _scanThread(self):
        self.sniffAdvertisements(channel=37)
        utils.wait(seconds=self.scanInterval)
        self.sniffAdvertisements(channel=38)
        utils.wait(seconds=self.scanInterval)
        self.sniffAdvertisements(channel=39)
        utils.wait(seconds=self.scanInterval)

    def setScan(self, enable=True):
        '''
		This method enables or disables the scanning mode. It allows to change the channel according to the scan interval parameter.

		:param enable: boolean indicating if the scanning mode must be enabled
		:type enable: bool

		:Example:

			>>> device.setScan(enable=True) # scanning mode enabled
 			>>> device.setScan(enable=False) # scanning mode disabled
		
		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''

        if enable:
            self.sniffAdvertisements()

            if self.scanThreadInstance is None:
                self.scanThreadInstance = wireless.StoppableThread(
                    target=self._scanThread)
                self.scanThreadInstance.start()
        else:
            self.scanThreadInstance.stop()
            self.scanThreadInstance = None

    def _sweepingThread(self):
        for channel in self.sweepingSequence:
            self.setChannel(channel=channel)
            if self.sniffingMode is not None:
                if self.sniffingMode == BLESniffingMode.ADVERTISEMENT:
                    self._internalCommand(
                        BTLEJack_Advertisements_Command() /
                        BTLEJack_Advertisements_Enable_Sniff_Command(
                            channel=channel),
                        noResponse=True)
                elif self.sniffingMode == BLESniffingMode.NEW_CONNECTION and not self.synchronized:
                    self._sniffConnectionRequests(address=self.lastTarget,
                                                  channel=channel)
            utils.wait(seconds=0.1)

    def _startSweepingThread(self):
        self._stopSweepingThread()
        self.sweepingThreadInstance = wireless.StoppableThread(
            target=self._sweepingThread)
        self.sweepingThreadInstance.start()

    def _stopSweepingThread(self):
        if self.sweepingThreadInstance is not None:
            self.sweepingThreadInstance.stop()
            self.sweepingThreadInstance = None

    def setSweepingMode(self, enable=True, sequence=[37, 38, 39]):
        '''
		This method allows to enable or disable the Sweeping mode. It allows to provide a subset of advertising channels to monitor sequentially.
	
		:param enable: boolean indicating if the Sweeping mode is enabled.
		:type enable: bool
		:param sequence: sequence of channels to use
		:type sequence: list of int

			
		.. note::

			This method is a **shared method** and can be called from the corresponding Emitters / Receivers.

		'''
        self.sweepingMode = enable
        if enable:
            self.sweepingSequence = sequence
            self._startSweepingThread()
        else:
            self._stopSweepingThread()

    def init(self):
        if self.microbit is not None:
            self._flush()
            self.setCRCChecking(True)
            self.scanThreadInstance = None
            self.isListening = False
            self.hijacking = False
            self.jamming = False
            self.customMirageFirmware = False
            self.receptionBuffer = b""
            self.lock = Lock()
            self.commandResponses = Queue()
            self.channel = 37
            self.accessAddress = None
            self.crcInit = None
            self.channelMap = None
            self.hopInterval = None
            self.hopIncrement = None
            self.sniffingMode = None
            self.hijacked = False
            self.synchronized = False
            self.jammingEnabled = True
            self.sweepingMode = False
            self.sweepingSequence = []
            self.sweepingThreadInstance = None
            self.lastTarget = "FF:FF:FF:FF:FF:FF"
            self.setScanInterval()
            self.candidateAccessAddresses = {}
            self.capabilities = [
                "SNIFFING_EXISTING_CONNECTION", "SNIFFING_NEW_CONNECTION",
                "HIJACKING_CONNECTIONS", "JAMMING_CONNECTIONS",
                "COMMUNICATING_AS_MASTER"
            ]
            try:
                (major, minor) = self._getFirmwareVersion()
                io.success("BTLEJack device " +
                           ("#" + str(self.index) if isinstance(
                               self.index, int) else str(self.index)) +
                           " successfully instantiated (firmware version : " +
                           str(major) + "." + str(minor) + ")")
                if major == 3 and minor == 14:
                    io.info(
                        "Custom Mirage Firmware used ! Advertisements sniffing and jamming will be supported."
                    )
                    self.capabilities += [
                        "SNIFFING_ADVERTISEMENTS", "SCANNING",
                        "JAMMING_ADVERTISEMENTS"
                    ]
                    self.customMirageFirmware = True
                self._reset()
                self.ready = True
            except:
                self.microbit = None
                self.ready = False
Example #42
0
class SerialFrame(SerialFrameUI):
    def __init__(self, parent=None):
        super(SerialFrame, self).__init__(parent)

        self.m_imgStat.SetBitmap(Img_inclosing.getBitmap())

        self.Ser = Serial()
        self.serialThread = SerialThread(self.Ser)

        # create a pubsub receiver
        pub.subscribe(self.on_txtMain_update, 'update')

    def on_txtMain_update(self, msg):
        self.m_txtMain.AppendText(msg.data)

    def on_btnSend_clicked(self, event):
        self.Ser.write(self.m_txtInput.GetValue())

    def on_btnClear_clicked(self, event):
        self.m_txtMain.Clear()

    def on_chkHEXShow_changed(self, event):
        s = self.m_txtMain.GetValue()
        if self.m_chkHEXShow.IsChecked():
            s = ''.join('%02X' % i for i in [ord(c) for c in s])
        else:
            s = ''.join([
                chr(int(i, 16))
                for i in [s[i * 2:i * 2 + 2] for i in range(0,
                                                            len(s) / 2)]
            ])
        self.m_txtMain.Clear()
        self.m_txtMain.SetValue(s)

    def on_cmbBaud_changled(self, event):
        self.Ser.setBaudrate(int(self.m_cmbBaud.GetValue()))

    def on_btnOpen_clicked(self, event):
        if not self.Ser.isOpen():
            try:
                self.Ser.timeout = 1
                self.Ser.xonxoff = 0
                self.Ser.port = self.m_cmbCOMX.GetValue()
                self.Ser.parity = self.m_cmbChek.GetValue()[0]
                self.Ser.baudrate = int(self.m_cmbBaud.GetValue())
                self.Ser.bytesize = int(self.m_cmbData.GetValue())
                self.Ser.stopbits = int(self.m_cmbStop.GetValue())
                self.Ser.open()
            except Exception as e:
                print('COMM Open Fail!!', e)
            else:
                self.m_btnOpen.SetLabel(u'关闭串口')
                self.m_imgStat.SetBitmap(Img_inopening.getBitmap())
        else:
            self.Ser.close()
            while self.Ser.isOpen():
                pass

            self.m_btnOpen.SetLabel(u'打开串口')
            self.m_imgStat.SetBitmap(Img_inclosing.getBitmap())

    def on_btnExtn_clicked(self, event):
        event.Skip()
Example #43
0
    def __init__(self, *args, **kwargs):
        # NEW BEHAVIOR: if no parameters given, output is written
        # to stdout, to be piped through 'lp -o raw' (old behavior
        # was to use default port & baud rate).
        baudrate = 19200
        if len(args) == 0:
            self.writeToStdout = True
        if len(args) == 1:
            # If only port is passed, use default baud rate.
            args = [args[0], baudrate]
        elif len(args) == 2:
            # If both passed, use those values.
            baudrate = args[1]

        # Firmware is assumed version 2.68.  Can override this
        # with the 'firmware=X' argument, where X is the major
        # version number * 100 + the minor version number (e.g.
        # pass "firmware=264" for version 2.64.
        self.firmwareVersion = kwargs.get('firmware', 268)

        if self.writeToStdout is False:
            # Calculate time to issue one byte to the printer.
            # 11 bits (not 8) to accommodate idle, start and
            # stop bits.  Idle time might be unnecessary, but
            # erring on side of caution here.
            self.byteTime = 11.0 / float(baudrate)

            Serial.__init__(self, *args, **kwargs)

            # Remainder of this method was previously in begin()

            # The printer can't start receiving data immediately
            # upon power up -- it needs a moment to cold boot
            # and initialize.  Allow at least 1/2 sec of uptime
            # before printer can receive data.
            self.timeoutSet(0.5)

            self.wake()
            self.reset()

            # Description of print settings from p. 23 of manual:
            # ESC 7 n1 n2 n3 Setting Control Parameter Command
            # Decimal: 27 55 n1 n2 n3
            # max heating dots, heating time, heating interval
            # n1 = 0-255 Max heat dots, Unit (8dots), Default: 7 (64 dots)
            # n2 = 3-255 Heating time, Unit (10us), Default: 80 (800us)
            # n3 = 0-255 Heating interval, Unit (10us), Default: 2 (20us)
            # The more max heating dots, the more peak current
            # will cost when printing, the faster printing speed.
            # The max heating dots is 8*(n1+1).  The more heating
            # time, the more density, but the slower printing
            # speed.  If heating time is too short, blank page
            # may occur.  The more heating interval, the more
            # clear, but the slower printing speed.

            heatTime = kwargs.get('heattime', self.defaultHeatTime)
            self.writeBytes(
                27,  # Esc
                55,  # 7 (print settings)
                11,  # Heat dots
                heatTime,  # Lib default
                40)  # Heat interval

            # Description of print density from p. 23 of manual:
            # DC2 # n Set printing density
            # Decimal: 18 35 n
            # D4..D0 of n is used to set the printing density.
            # Density is 50% + 5% * n(D4-D0) printing density.
            # D7..D5 of n is used to set the printing break time.
            # Break time is n(D7-D5)*250us.
            # (Unsure of default values -- not documented)

            printDensity = 10  # 100%
            printBreakTime = 2  # 500 uS

            self.writeBytes(
                18,  # DC2
                35,  # Print density
                (printBreakTime << 5) | printDensity)
            self.dotPrintTime = 0.03
            self.dotFeedTime = 0.0021
        else:
            self.reset()  # Inits some vars
Example #44
0
from serial import Serial
from time import *
ser = Serial("/dev/tty.usbserial-140", baudrate=115200)  #or whatever
with open('main.hex', 'rb') as openfileobject:
    for line in openfileobject:
        print(line.strip())
        ser.write(line.strip())
        ser.write(b'\r')
        sleep(0.01)
ser.write(b'0300R\r')
Example #45
0
 def __init__(self, *serial_device_parameters):
     self.serial_device = Serial(*serial_device_parameters, timeout=.5)
     init_serial(self.serial_device)
Example #46
0
#!/usr/bin/env python

import sys, os, time
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib_py'))

from serial import Serial

from dev import command_dev

s_port = command_dev
s_baud = 115200

ser = Serial(s_port, s_baud, timeout=5, writeTimeout=5)
#print s_port, s_baud

ser.write('R\n')
ser.flush()

print ser.readline()


Example #47
0
class TFmini(object):
    """
    TFMini - Micro LiDAR Module
    https://www.sparkfun.com/products/14577
    http://www.benewake.com/en/tfmini.html
    """
    NOHEADER = 1
    BADCHECKSUM = 2
    TOO_MANY_TRIES = 3
    DEC_MODE = 4
    STD_MODE = 5

    def __init__(self, port, mode=5, retry=25):
        self.serial = Serial()
        self.serial.port = port
        self.serial.baudrate = 115200
        self.serial.timeout = 0.005
        self.serial.open()
        self.retry = retry  # how many times will I retry to find the packet header
        self.mode = mode
        self.strength = -1

        if not self.serial.is_open:
            raise Exception("ERROR: couldn't open port: {}".format(port))

        self.setStdMode(self.mode)

    def setStdMode(self, mode):
        # do I need this?
        if mode == self.STD_MODE:
            cmd = [0x42, 0x57, 0x02, 0x00, 0x00, 0x00, 0x01,
                   0x06]  # hex - packet
        elif mode == self.DEC_MODE:
            cmd = [0x42, 0x57, 0x02, 0x00, 0x00, 0x00, 0x04,
                   0x06]  # dec - string
        else:
            raise Exception("ERROR: invalid mode {}".format(mode))

        self.mode = mode
        data = bytearray(cmd)
        data = bytes(data)
        self.serial.write(data)
        time.sleep(0.1)

    def __del__(self):
        self.close()

    def close(self):
        self.serial.close()

    def readString(self):
        self.serial.flushInput()
        tmp = []

        d = ' '
        while d != '\n':
            d = self.serial.read(1)
            tmp.append(d)
        try:
            tmp = tmp[:-2]  # get rid of \r\n
            ret = float(''.join(tmp))
        except:
            ret = None
        return ret

    def readPacket(self):
        # it looks like it streams data, so no command to measure needed
        self.serial.flushInput()

        # find header
        a, b = ' ', ' '
        tmp = []
        count = self.retry
        while True:
            tmp.append(a)
            a = b
            b = self.serial.read(1)
            if len(a) > 0 and len(b) > 0:
                if ord(a) == 0x59 and ord(b) == 0x59:
                    # print('found header')
                    break
            if count == 0:
                # print('nothing:', tmp)
                # print('str', ''.join(tmp))
                return None
            count -= 1

        raw = self.serial.read(7)
        # build a packet (array) of ints
        pkt = [ord(a), ord(b)] + list(map(ord, raw))
        # print('pkt', pkt)
        try:
            ret = self.processPkt(pkt)
        except Exception as e:
            # print('bad')
            print(e)
            ret = None
        return ret

    def read(self):
        """
        This is the main read() function. The others are automagically selected
        based off the mode the sensor was set too.
        STD Mode: return (dist, strength, quality)
        DEC Mode: return range in meters
        """
        if self.mode == self.STD_MODE:
            ret = self.readPacket()
        elif self.mode == self.DEC_MODE:
            ret = self.readString()
        else:
            raise Exception('ERROR: read() invalid mode {}'.format(self.mode))

        # weed out stupid returns ... strings can give crazy numbers
        if ret > 12.0 or ret < 0.3:
            ret = None

        return ret

    def processPkt(self, pkt):
        """
        packet = [0x59, 0x59, distL, distH, strL, strH, reserved, integration time, checksum]

        Note: the integration time always seems to be 0
        """
        # turn string data into array of bytes
        # pkt = list(map(ord, pkt))
        if len(pkt) != 9:
            raise Exception("ERROR: packet size {} != 9".format(len(pkt)))

        # check header
        if pkt[0] != 0x59 or pkt[1] != 0x59:
            raise Exception("ERROR: bad header in packet")

        # calculate checksum
        cs = sum(pkt[:8])
        cs &= 0xff
        # print('cs', cs, pkt[8])

        if pkt[8] != cs:
            print('cs', cs, pkt[8])
            raise Exception("ERROR: bad checksum in packet")

        # print('L {} H {}'.format(pkt[2], pkt[3]))
        dist = (pkt[2] + (pkt[3] << 8)) / 100
        self.strength = pkt[4] + (pkt[5] << 8)
        # q    = pkt[7]

        # print('ans',dist, st, q)

        return dist
Example #48
0
class Device(object):
    def __init__(self, **kwargs):
        self.steps_per_unit = STEPS_PER_INCH
        self.pen_up_position = PEN_UP_POSITION
        self.pen_up_speed = PEN_UP_SPEED
        self.pen_up_delay = PEN_UP_DELAY
        self.pen_down_position = PEN_DOWN_POSITION
        self.pen_down_speed = PEN_DOWN_SPEED
        self.pen_down_delay = PEN_DOWN_DELAY
        self.acceleration = ACCELERATION
        self.max_velocity = MAX_VELOCITY
        self.corner_factor = CORNER_FACTOR
        self.jog_acceleration = JOG_ACCELERATION
        self.jog_max_velocity = JOG_MAX_VELOCITY

        for k, v in kwargs.items():
            setattr(self, k, v)

        self.error = (0, 0) # accumulated step error

        port = find_port()
        if port is None:
            raise Exception('cannot find axidraw device')
        self.serial = Serial(port, timeout=1)
        self.configure()

    def configure(self):
        servo_min = 7500
        servo_max = 28000
        pen_up_position = self.pen_up_position / 100
        pen_up_position = int(
            servo_min + (servo_max - servo_min) * pen_up_position)
        pen_down_position = self.pen_down_position / 100
        pen_down_position = int(
            servo_min + (servo_max - servo_min) * pen_down_position)
        self.command('SC', 4, pen_up_position)
        self.command('SC', 5, pen_down_position)
        self.command('SC', 11, int(self.pen_up_speed * 5))
        self.command('SC', 12, int(self.pen_down_speed * 5))

    def close(self):
        self.serial.close()

    def make_planner(self, jog=False):
        a = self.acceleration
        vmax = self.max_velocity
        cf = self.corner_factor
        if jog:
            a = self.jog_acceleration
            vmax = self.jog_max_velocity
        return Planner(a, vmax, cf)

    def readline(self):
        return self.serial.readline().strip()

    def command(self, *args):
        line = ','.join(map(str, args))
        self.serial.write(line + '\r')
        return self.readline()

    # higher level functions
    def move(self, dx, dy):
        self.run_path([(0, 0), (dx, dy)])

    def goto(self, x, y, jog=True):
        # TODO: jog if pen up
        px, py = self.read_position()
        self.run_path([(px, py), (x, y)], jog)

    def home(self):
        self.goto(0, 0, True)

    # misc commands
    def version(self):
        return self.command('V')

    # motor functions
    def enable_motors(self):
        m = MICROSTEPPING_MODE
        return self.command('EM', m, m)

    def disable_motors(self):
        return self.command('EM', 0, 0)

    def motor_status(self):
        return self.command('QM')

    def zero_position(self):
        return self.command('CS')

    def read_position(self):
        response = self.command('QS')
        self.readline()
        a, b = map(int, response.split(','))
        a /= self.steps_per_unit
        b /= self.steps_per_unit
        y = (a - b) / 2
        x = y + b
        return x, y

    def stepper_move(self, duration, a, b):
        return self.command('XM', duration, a, b)

    def wait(self):
        while '1' in self.motor_status():
            time.sleep(0.01)

    def run_plan(self, plan):
        step_ms = TIMESLICE_MS
        step_s = step_ms / 1000
        t = 0
        while t < plan.t:
            i1 = plan.instant(t)
            i2 = plan.instant(t + step_s)
            d = i2.p.sub(i1.p)
            ex, ey = self.error
            ex, sx = modf(d.x * self.steps_per_unit + ex)
            ey, sy = modf(d.y * self.steps_per_unit + ey)
            self.error = ex, ey
            self.stepper_move(step_ms, int(sx), int(sy))
            t += step_s
        # self.wait()

    def run_path(self, path, jog=False):
        planner = self.make_planner(jog)
        plan = planner.plan(path)
        self.run_plan(plan)

    def run_drawing(self, drawing, progress=True):
        print('number of paths : %d' % len(drawing.paths))
        print('pen down length : %g' % drawing.down_length)
        print('pen up length   : %g' % drawing.up_length)
        print('total length    : %g' % drawing.length)
        print('drawing bounds  : %s' % str(drawing.bounds))
        self.pen_up()
        position = (0, 0)
        bar = Bar(drawing.length, enabled=progress)
        for path in drawing.paths:
            jog = [position, path[0]]
            self.run_path(jog, jog=True)
            bar.increment(path_length(jog))
            self.pen_down()
            self.run_path(path)
            self.pen_up()
            position = path[-1]
            bar.increment(path_length(path))
        bar.done()
        self.run_path([position, (0, 0)], jog=True)

    def plan_drawing(self, drawing):
        result = []
        planner = self.make_planner()
        for path in drawing.all_paths:
            result.append(planner.plan(path))
        return result

    # pen functions
    def pen_up(self):
        delta = abs(self.pen_up_position - self.pen_down_position)
        duration = int(1000 * delta / self.pen_up_speed)
        delay = max(0, duration + self.pen_up_delay)
        return self.command('SP', 1, delay)

    def pen_down(self):
        delta = abs(self.pen_up_position - self.pen_down_position)
        duration = int(1000 * delta / self.pen_down_speed)
        delay = max(0, duration + self.pen_down_delay)
        return self.command('SP', 0, delay)
Example #49
0
from serial import Serial
import sys


def sendcommand(s, cmd):
    s.write(cmd)
    s.write(b'\r')

    lines = []

    while True:
        line = s.readline()

        if line.startswith(b'ok:'):
            break

        if line.startswith(b'error:'):
            raise RuntimeError(line.split(b':')[1].strip())

        lines.append(line)

    return lines


with Serial(sys.argv[1], timeout=10) as s:
    print(sendcommand(s, b'ver'))
    print(sendcommand(s, b'id'))
Example #50
0
import cv2
import numpy as np
import video
from serial import Serial
import time


ser = Serial('/dev/ttyUSB0', baudrate=9600, timeout=1) # подключаемся к Arduino



edge = 35 # рамки условного центра изо6ражения
panAngle = 90 # начальное положение сервопривода 1 
tiltAngle = 90 # начальное положение сервопривода 2

        
def ObjectPosition (x, y): # функция вывода в консоль координат центра цели
    print ("[INFO] Object Center coordenates at X0 = {0} and Y0 =  {1}".format(x, y))

        
def ServoPosition (x, y): # функция управления сервоприводами
    global panAngle
    global tiltAngle
    if (x < width/2 - edge):
        panAngle += 1
        if panAngle > 170:
            panAngle = 170
        ser.write(bytearray([85, panAngle,180 - tiltAngle]))
        
    if (x > width/2 + edge):
        panAngle -= 1
Example #51
0
class UBXStreamer:
    """
    UBXStreamer class.
    """
    def __init__(self, port, baudrate, timeout=5):
        """
        Constructor.
        """

        self._serial_object = None
        self._serial_thread = None
        self._ubxreader = None
        self._connected = False
        self._reading = False
        self._port = port
        self._baudrate = baudrate
        self._timeout = timeout

    def __del__(self):
        """
        Destructor.
        """

        self.stop_read_thread()
        self.disconnect()

    def connect(self):
        """
        Open serial connection.
        """

        try:
            self._serial_object = Serial(self._port,
                                         self._baudrate,
                                         timeout=self._timeout)
            self._ubxreader = UBXReader(BufferedReader(self._serial_object),
                                        False)
            self._connected = True
        except (SerialException, SerialTimeoutException) as err:
            print(f"Error connecting to serial port {err}")

    def disconnect(self):
        """
        Close serial connection.
        """

        if self._connected and self._serial_object:
            try:
                self._serial_object.close()
            except (SerialException, SerialTimeoutException) as err:
                print(f"Error disconnecting from serial port {err}")
        self._connected = False

    def start_read_thread(self):
        """
        Start the serial reader thread.
        """

        if self._connected:
            self._reading = True
            self._serial_thread = Thread(target=self._read_thread, daemon=True)
            self._serial_thread.start()

    def stop_read_thread(self):
        """
        Stop the serial reader thread.
        """

        if self._serial_thread is not None:
            self._reading = False

    def send(self, data):
        """
        Send data to serial connection.
        """

        self._serial_object.write(data)

    def flush(self):
        """
        Flush input buffer
        """

        self._serial_object.reset_input_buffer()

    def waiting(self):
        """
        Check if any messages remaining in the input buffer
        """

        return self._serial_object.in_waiting

    def _read_thread(self):
        """
        THREADED PROCESS
        Reads and parses UBX message data from stream
        """

        while self._reading and self._serial_object:
            if self._serial_object.in_waiting:
                try:
                    (_, parsed_data) = self._ubxreader.read()
                    if parsed_data:
                        print(parsed_data)
                except (
                        ube.UBXStreamError,
                        ube.UBXMessageError,
                        ube.UBXTypeError,
                        ube.UBXParseError,
                ) as err:
                    print(f"Something went wrong {err}")
                    continue

    def poll_uart(self, layer=0):
        """
        Poll the current BBR UART1/2 configuration
        """

        position = 0
        keys = ["CFG_UART1_BAUDRATE", "CFG_UART2_BAUDRATE"]
        msg = UBXMessage.config_poll(layer, position, keys)
        ubp.send(msg.serialize())

    def set_uart(self, layers=1):
        """
        Set the current BBR UART1/2 configuration
        """

        transaction = 0
        cfgData = [("CFG_UART1_BAUDRATE", 115200),
                   ("CFG_UART2_BAUDRATE", 57600)]
        msg = UBXMessage.config_set(layers, transaction, cfgData)
        ubp.send(msg.serialize())

    def unset_uart(self, layers=1):
        """
        Unset (del) the current BBR UART1/2 configuration
        """

        transaction = 0
        keys = ["CFG_UART1_BAUDRATE", "CFG_UART2_BAUDRATE"]
        msg = UBXMessage.config_del(layers, transaction, keys)
        ubp.send(msg.serialize())
Example #52
0
import time

from serialPort import serial_ports
from serial import Serial

s_port: str = serial_ports()
if s_port:
    print(s_port + ' will be used')
else:
    print('No serial port found')
    exit()

s = Serial(s_port, 9600, timeout=1)

while True:
    s.write(b'T')
    res = s.readline()
    if res:
        try:
            temp = float(res)
            print(temp)
            time.sleep(1)

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            raise
Example #53
0
        screen.blit(ftext, frect)
        center_y += font.get_linesize()


def draw_ebar(start, time, duration, botleft, color):
    effpercent = 100 - 100 * (time - start) / duration
    effrect = pygame.Rect(0, 0, effpercent, 10)
    effrect.bottomleft = botleft
    pygame.draw.rect(screen, color, effrect)


ports = [p for p in list_ports.grep(sys.argv[1])]
if not ports:
    raise IOError("Port " + sys.argv[1] + " not found!")
else:
    serial = Serial(ports[0][0], 19200)

pygame.init()

info = pygame.display.Info()
size = w, h = info.current_w, info.current_h
screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
pygame.display.set_caption("Space Battle")
srect = screen.get_rect()

pygame.mouse.set_visible(0)

ship = SpaceShip("resources/img/ship.png", [randint(0, w), randint(0, h)])
ship.rect = ship.rect.clamp(srect)
enemies = []
Example #54
0
                if endByte == PKG_END:
                    return data
                else:
                    print('package error!')
                    return False
    except:
        print 'read error!'
        return False


#---------------------------------------------------
#---------------------------------------------------
#MAIN
#---------------------------------------------------
#serial communication parameters
serialRobot = Serial()  #new object
#Linux
#serialRobot.port = '/dev/ttyUSB0' #Port number or ID
#Windows
serialRobot.port = 'COM3'  #Port number or ID
serialRobot.baud = 9600  #baud rate
#---------------------------------------------------
#opens the serial port
serialRobot.open()
#---------------------------------------------------
#decides which action should be sent to the robot
action = input('0: set position, 1: get position, 4: LED on, 5: LED off | ')
#----------------------------------------------------------------------------------
#ACTION 1: Set position of a servo
if (action == AX_SETPOSITION):
    #inputs
Example #55
0
class SniffleHW:
    def __init__(self, serport):
        self.decoder_state = SniffleDecoderState()
        self.ser = Serial(serport, 2000000)
        self.ser.write(b'@@@@@@@@\r\n') # command sync
        self.recv_cancelled = False
        self.rate_limiter = RateLimiter()

    def _send_cmd(self, cmd_byte_list):
        b0 = (len(cmd_byte_list) + 3) // 3
        cmd = bytes([b0, *cmd_byte_list])
        msg = b64encode(cmd) + b'\r\n'
        self.rate_limiter.do_cmd()
        self.ser.write(msg)

    def cmd_chan_aa_phy(self, chan=37, aa=0x8E89BED6, phy=0, crci=0x555555):
        if not (0 <= chan <= 39):
            raise ValueError("Channel must be between 0 and 39")
        if not (0 <= phy <= 2):
            raise ValueError("PHY must be 0 (1M), 1 (2M), or 2 (coded)")
        self._send_cmd([0x10, *list(pack("<BLBL", chan, aa, phy, crci))])

    def cmd_pause_done(self, pause_when_done=False):
        if pause_when_done:
            self._send_cmd([0x11, 0x01])
        else:
            self._send_cmd([0x11, 0x00])

    def cmd_rssi(self, rssi=-80):
        self._send_cmd([0x12, rssi & 0xFF])

    def cmd_mac(self, mac_byte_list=None, hop3=True):
        if mac_byte_list is None:
            self._send_cmd([0x13])
        else:
            if len(mac_byte_list) != 6:
                raise ValueError("MAC must be 6 bytes!")
            self._send_cmd([0x13, *mac_byte_list])
            if hop3:
                # hop with advertisements between 37/38/39
                # unnecessary/detrimental with extended advertising
                self._send_cmd([0x14])

    def cmd_follow(self, enable=True):
        if enable:
            self._send_cmd([0x15, 0x01])
        else:
            self._send_cmd([0x15, 0x00])

    def cmd_auxadv(self, enable=True):
        if enable:
            self._send_cmd([0x16, 0x01])
        else:
            self._send_cmd([0x16, 0x00])

    def cmd_reset(self):
        self._send_cmd([0x17])

    def cmd_marker(self):
        self._send_cmd([0x18])

    # for master or slave modes
    def cmd_transmit(self, llid, pdu):
        if not (0 <= llid <= 3):
            raise ValueError("Out of bounds LLID")
        if len(pdu) > 255:
            raise ValueError("Too long PDU")
        self._send_cmd([0x19, llid, len(pdu), *pdu])

    def cmd_connect(self, peerAddr, llData, is_random=True):
        if len(peerAddr) != 6:
            raise ValueError("Invalid peer address")
        if len(llData) != 22:
            raise ValueError("Invalid LLData")
        self._send_cmd([0x1A, 1 if is_random else 0, *peerAddr, *llData])

    def cmd_setaddr(self, addr, is_random=True):
        if len(addr) != 6:
            raise ValueError("Invalid MAC address")
        self._send_cmd([0x1B, 1 if is_random else 0, *addr])

    def cmd_advertise(self, advData, scanRspData):
        if len(advData) > 31:
            raise ValueError("advData too long!")
        if len(scanRspData) > 31:
            raise ValueError("scanRspData too long!")
        paddedAdvData = [len(advData), *advData] + [0]*(31 - len(advData))
        paddedScnData = [len(scanRspData), *scanRspData] + [0]*(31 - len(scanRspData))
        self._send_cmd([0x1C, *paddedAdvData, *paddedScnData])

    def cmd_adv_interval(self, intervalMs):
        if not (20 < intervalMs < 0xFFFF):
            raise ValueError("Advertising interval out of bounds")
        self._send_cmd([0x1D, intervalMs & 0xFF, intervalMs >> 8])

    def cmd_irk(self, irk=None, hop3=True):
        if irk is None:
            self._send_cmd([0x1E])
        elif len(irk) != 16:
            raise ValueError("Invalid IRK length!")
        else:
            self._send_cmd([0x1E, *irk])
            if hop3:
                self._send_cmd([0x14])

    def recv_msg(self):
        got_msg = False
        while not got_msg:
            pkt = self.ser.readline()
            try:
                data = b64decode(pkt.rstrip())
            except BAError as e:
                print(str(pkt, encoding='ascii').rstrip())
                print("Ignoring message:", e, file=stderr)
                continue
            got_msg = True

        if self.recv_cancelled:
            self.recv_cancelled = False
            return -1, None, b''

        # msg type, msg body
        return data[0], data[1:], pkt

    def recv_and_decode(self):
        mtype, mbody, pkt = self.recv_msg()
        try:
            if mtype == 0x10:
                return PacketMessage(mbody, self.decoder_state)
            elif mtype == 0x11:
                return DebugMessage(mbody)
            elif mtype == 0x12:
                return MarkerMessage(mbody, self.decoder_state)
            elif mtype == 0x13:
                return StateMessage(mbody, self.decoder_state)
            elif mtype == -1:
                return None # receive cancelled
            else:
                raise SniffleHWPacketError("Unknown message type 0x%02X!" % mtype)
        except BaseException as e:
            print(str(pkt, encoding='ascii').rstrip())
            print("Ignoring message:", e, file=stderr)
            print_exc()
            return None

    def cancel_recv(self):
        self.recv_cancelled = True
        self.ser.cancel_read()

    def mark_and_flush(self):
        # use marker to zero time, flush every packet before marker
        # also tolerate errors from incomplete lines in UART buffer
        self.cmd_marker()
        while True:
            try:
                msg = self.recv_and_decode()
            except SniffleHWPacketError:
                print("WARNING: invalid message during flush, ignoring...")
                continue
            if isinstance(msg, MarkerMessage):
                break

    def random_addr(self):
        # generate a random static address, set it
        addr = [randint(0, 255) for i in range(6)]
        addr[5] |= 0xC0 # make it static
        self.cmd_setaddr(bytes(addr))

    # automatically generate sane LLData
    def initiate_conn(self, peerAddr, is_random=True):
        llData = []

        # access address
        llData.extend([randint(0, 255) for i in range(4)])

        # initial CRC
        llData.extend([randint(0, 255) for i in range(3)])

        # WinSize, WinOffset, Interval, Latency, Timeout
        llData.append(3)
        llData.extend(pack("<H", randint(5, 15)))
        llData.extend(pack("<H", 24))
        llData.extend(pack("<H", 1))
        llData.extend(pack("<H", 50))

        # Channel Map
        llData.extend([0xFF, 0xFF, 0xFF, 0xFF, 0x1F])

        # Hop, SCA = 0
        llData.append(randint(5, 16))

        self.cmd_connect(peerAddr, bytes(llData), is_random)

        # return the access address
        return unpack("<L", bytes(llData[:4]))[0]
Example #56
0
def sqImport(tId):
    '''if tId == 0:
            while 1:
                rc = 0
                while rc == 0:
                    rc = mqttc.loop()
                print("rc: " + str(rc))'''

    if tId == 1:
        while 1:
            global app
            global MainWindow
            app = QtWidgets.QApplication(sys.argv)
            MainWindow = QtWidgets.QMainWindow()
            ui = Ui_MainWindow()
            ui.setupUi(MainWindow)
            MainWindow.show()
            sys.exit(app.exec_())
    if tId == 2:
        #import pyautogui
        from serial import Serial
        port = 'COM53'
        baudrate = 115200
        ser = Serial(port, baudrate)
        from pymouse import PyMouse
        #pyautogui.PAUSE = 2.5
        push = 1
        counter = 0
        m = PyMouse()
        max_v = 13
        centre = max_v / 2
        threshold = max_v / 4
        j = m.position()[0]
        k = m.position()[1]
        mainv = [0, 0, 0]

        def C_value(this_value, centre):
            reading = this_value * max_v / 1024
            center = centre
            distance = reading - center
            if abs(distance) < threshold:
                distance = 0
            return distance

        while 1:
            try:
                while True:
                    value = ser.readline().decode()
                    #chop(value)
                    #value2=int(value[4:7])
                    #button=int(value[8:9])
                    '''print(mainv[0])
                  print(mainv[1])
                  print(mainv[2])'''
                    x = int(value.split('-')[1])
                    y = int(value.split('-')[0])
                    push = int(value.split('-')[2])
                    #x_max = m.screen_size()[0]
                    #y_max = m.screen_size()[1]
                    x_new = int(C_value(x, centre))
                    y_new = int(C_value(y, centre))
                    #print(x_new,y_new,push)
                    m.move(j + x_new, k + y_new)
                    j = m.position()[0]
                    k = m.position()[1]
                    if push == 0:
                        counter = 1
                    if counter - push == 0:
                        m.click(j + x_new, k + y_new)
                        counter = 0
            except:
                print('Error')
Example #57
0
class Stk500v2(ispBase.IspBase):
    def __init__(self):
        self.serial = None
        self.seq = 1
        self.lastAddr = -1
        self.progressCallback = 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 as e:
            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
        flashSize = page_size * self.chip['pageCount']
        print("Writing flash")
        if flashSize > 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)):
            recv = 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.progressCallback is not None:
                if self._has_checksum:
                    self.progressCallback(i + 1, load_count)
                else:
                    self.progressCallback(i + 1, load_count * 2)

    def verifyFlash(self, flashData):
        if self._has_checksum:
            self.sendMessage([
                0x06, 0x00, (len(flashData) >> 17) & 0xFF,
                (len(flashData) >> 9) & 0xFF, (len(flashData) >> 1) & 0xFF
            ])
            res = self.sendMessage([0xEE])
            checksum_recv = res[2] | (res[3] << 8)
            checksum = 0
            for d in flashData:
                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
            flashSize = self.chip['pageSize'] * 2 * self.chip['pageCount']
            if flashSize > 0xFFFF:
                self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00])
            else:
                self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00])

            loadCount = (len(flashData) + 0xFF) / 0x100
            for i in range(0, int(loadCount)):
                recv = self.sendMessage([0x14, 0x01, 0x00, 0x20])[2:0x102]
                if self.progressCallback is not None:
                    self.progressCallback(loadCount + i + 1, loadCount * 2)
                for j in range(0, 0x100):
                    if i * 0x100 + j < len(flashData) and flashData[
                            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
            #print(hex(b))
            if state == 'Start':
                if b == 0x1B:
                    state = 'GetSeq'
                    checksum = 0x1B
            elif state == 'GetSeq':
                state = 'MsgSize1'
            elif state == 'MsgSize1':
                msgSize = b << 8
                state = 'MsgSize2'
            elif state == 'MsgSize2':
                msgSize |= b
                state = 'Token'
            elif state == 'Token':
                if b != 0x0E:
                    state = 'Start'
                else:
                    state = 'Data'
                    data = []
            elif state == 'Data':
                data.append(b)
                if len(data) == msgSize:
                    state = 'Checksum'
            elif state == 'Checksum':
                if checksum != 0:
                    state = 'Start'
                else:
                    return data
Example #58
0
            endV = vertex
            minEnd = endDist

    return startV, endV







if __name__ == "__main__":
	yegGraph, location = load_edmonton_graph('edmonton-roads-2.0.1.txt')
	cost = CostDistance(location)

	with Serial("/dev/ttyACM0", baudrate = 9600, timeout = 1) as ser:
		while True:
            # infinite loop that echoes all messages from
            # the arduino to the terminal
			line = ser.readline()
			line_string = line.decode("ASCII")
			stripped = line_string.rstrip("\r\n")
			print(stripped)

			if not stripped:
    			#timeout and restart loop
				continue

			elif stripped[0] == 'R':
				request = stripped.split()
				print(request)
    def __init__(self, name, port, baudrate, config):
        ConnectorPrimitive.__init__(self, name)
        self.port = port
        self.baudrate = int(baudrate)
        self.read_timeout = 0.01  # 10 milli sec
        self.write_timeout = 5
        self.config = config
        self.target_id = self.config.get('target_id', None)
        self.mcu = self.config.get('mcu', None)
        self.polling_timeout = config.get('polling_timeout', 60)
        self.forced_reset_timeout = config.get('forced_reset_timeout', 1)
        self.skip_reset = config.get('skip_reset', False)
        self.serial = None

        # Assume the provided serial port is good. Don't attempt to use the
        # target_id to re-discover the serial port, as the board may not be a
        # fully valid DAPLink-compatable or Mbed Enabled board (it may be
        # missing a mount point). Do not attempt to check if the serial port
        # for given target_id changed. We will attempt to open the port and
        # pass the already opened port object (not name) to the reset plugin.
        serial_port = None
        if self.port is not None:
            # A serial port was provided.
            # Don't pass in the target_id, so that no change in serial port via
            # auto-discovery happens.
            self.logger.prn_inf("using specified port '%s'" % (self.port))
            serial_port = HostTestPluginBase().check_serial_port_ready(
                self.port, target_id=None, timeout=self.polling_timeout)
        else:
            # No serial port was provided.
            # Fallback to auto-discovery via target_id.
            self.logger.prn_inf("getting serial port via mbedls)")
            serial_port = HostTestPluginBase().check_serial_port_ready(
                self.port,
                target_id=self.target_id,
                timeout=self.polling_timeout)

        if serial_port is None:
            raise ConnectorPrimitiveException("Serial port not ready!")

        if serial_port != self.port:
            # Serial port changed for given targetID
            self.logger.prn_inf("serial port changed from '%s to '%s')" %
                                (self.port, serial_port))
            self.port = serial_port

        startTime = time.time()
        self.logger.prn_inf(
            "serial(port=%s, baudrate=%d, read_timeout=%s, write_timeout=%d)" %
            (self.port, self.baudrate, self.read_timeout, self.write_timeout))
        while time.time() - startTime < self.polling_timeout:
            try:
                # TIMEOUT: While creating Serial object timeout is delibrately passed as 0. Because blocking in Serial.read
                # impacts thread and mutliprocess functioning in Python. Hence, instead in self.read() s delay (sleep()) is
                # inserted to let serial buffer collect data and avoid spinning on non blocking read().
                self.serial = Serial(self.port,
                                     baudrate=self.baudrate,
                                     timeout=0,
                                     write_timeout=self.write_timeout)
            except SerialException as e:
                self.serial = None
                self.LAST_ERROR = "connection lost, serial.Serial(%s, %d, %d, %d): %s" % (
                    self.port, self.baudrate, self.read_timeout,
                    self.write_timeout, str(e))
                self.logger.prn_err(str(e))
                self.logger.prn_err("Retry after 1 sec until %s seconds" %
                                    self.polling_timeout)
            else:
                if not self.skip_reset:
                    self.reset_dev_via_serial(delay=self.forced_reset_timeout)
                break
            time.sleep(1)
def list_ports():
    """ Lists serial port names

        :raises EnvironmentError:
            On unsupported or unknown platforms
        :returns:
            A list of the serial ports available on the system
    """
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = Serial(port)
            s.close()
            result.append(port)
        except (OSError, SerialException):
            pass
    return result