Example #1
0
 def _make_server(self, icsconfig):
     """ Creates a self.server object based on the icsconfig
     @param icsconfig Configuration information about this interface
     @returns An RTU Server object
     """
     serial = Serial()
     serial.port = icsconfig['port']
     serial.baudrate = icsconfig['baudrate']
     serial.open()
     server = modbus_rtu.RtuServer(serial)
     return server
Example #2
0
    def doMove(self, move):
        print("Armcontroller is doing move")

        serial = Serial('/dev/ttyUSB0')
        serial.baudrate = 9600

        try:
            serial.write('x')
        except Exception as e:
            print "An error occured"
            print e
Example #3
0
 def _make_server(self, icsconfig):
     """ Creates a self.server object based on the icsconfig
     @param icsconfig Configuration information about this interface
     @returns An RTU Server object
     """
     serial = Serial()
     serial.port = icsconfig['port']
     serial.baudrate = icsconfig['baudrate']
     serial.open()
     server = modbus_rtu.RtuServer(serial)
     server.set_verbose(True) #BRFIX
     modbus_tk.hooks.install_hook('modbus_rtu.RtuServer.before_write', 
                                     self._delay_hook_B) #BRDEBUG
     return server
Example #4
0
    def run(self):
        Logger.log("d", "Auto detect baud rate started.")
        timeout = 3
        tries = 2

        programmer = Stk500v2()
        serial = None
        try:
            programmer.connect(self._serial_port)
            serial = programmer.leaveISP()
        except:
            programmer.close()

        for retry in range(tries):
            for baud_rate in self._all_baud_rates:
                Logger.log("d", "Checking {serial} if baud rate {baud_rate} works".format(serial= self._serial_port, baud_rate = baud_rate))

                if serial is None:
                    try:
                        serial = Serial(str(self._serial_port), baud_rate, timeout = timeout, writeTimeout = timeout)
                    except SerialException as e:
                        Logger.logException("w", "Unable to create serial")
                        continue
                else:
                    # We already have a serial connection, just change the baud rate.
                    try:
                        serial.baudrate = baud_rate
                    except:
                        continue
                sleep(1.5)  # Ensure that we are not talking to the boot loader. 1.5 seconds seems to be the magic number
                successful_responses = 0

                serial.write(b"\n")  # Ensure we clear out previous responses
                serial.write(b"M105\n")

                timeout_time = time() + timeout

                while timeout_time > time():
                    line = serial.readline()
                    if b"ok T:" in line:
                        successful_responses += 1
                        if successful_responses >= 3:
                            self.setResult(baud_rate)
                            return

                    serial.write(b"M105\n")
            sleep(15) # Give the printer some time to init and try again.
        self.setResult(None)  # Unable to detect the correct baudrate.
Example #5
0
 def run(self):
     port = Serial()
     port.baudrate = 115200
     port.parity = 'N'
     port.rtscts = False
     port.xonxoff = True
     port.port = 0
     port.open()
     sys.stdout = port
     print >>sys.stderr, 'reading from serial port'
     while 1:
         line = ''
         while 1:
             ch = port.read(1)
             line += ch
             print >>sys.stderr, 'got character %s from serial' % (ch)
             if ch == '\n':
                 break
         print >>sys.stderr, 'got line', line
         server.process_request(SerialRequest(line,port), 'COM1')
    def push(self, items):
        """
        Function that prints the passed arguments using a connected
        cash register. It handles the serial communication, raising
        an exception if something goes wrong.
        """
        try:
            # define the serial port
            conn = Serial()
            conn.port = settings.SERIAL_PORT
            conn.baudrate = settings.SERIAL_BAUDRATE
            conn.xonxoff = settings.SERIAL_XONXOFF
            conn.timeout = settings.SERIAL_TIMEOUT

            # create a cash register with a serial connection handler
            register = SaremaX1(settings.REGISTER_NAME, connection=conn)

            # prepare and send cash register commands
            register.sell_products(items)
            register.send()
        except SerialException:
            raise CashRegisterNotReady
Example #7
0
File: upload.py Project: dag10/ino
    def upload_serial(self, board, protocol, port):
      if not os.path.exists(port):
          raise Abort("%s doesn't exist. Is Arduino connected?" % port)

      # send a hangup signal when the last process closes the tty
      file_switch = '-f' if platform.system() == 'Darwin' else '-F'
      ret = subprocess.call([self.e['stty'], file_switch, port, 'hupcl'])
      if ret:
          raise Abort("stty failed")

      # pulse on DTR
      try:
          s = Serial(port, 115200)
      except SerialException as e:
          raise Abort(str(e))
      s.setDTR(False)
      sleep(0.1)
      s.setDTR(True)
      s.close()

      # Need to do a little dance for Leonardo and derivatives:
      # open then close the port at the magic baudrate (usually 1200 bps) first
      # to signal to the sketch that it should reset into bootloader. after doing
      # this wait a moment for the bootloader to enumerate. On Windows, also must
      # deal with the fact that the COM port number changes from bootloader to
      # sketch.
      touch_port = \
              board['upload'].get('use_1200bps_touch') == 'true' or \
              board['upload']['protocol'] == 'avr109'

      if touch_port:
          new_port = None
          before = self.e.list_serial_ports()
          if port in before:
              ser = Serial()
              ser.port = port
              ser.baudrate = 1200
              ser.open()
              ser.close()

              # Scanning for available ports seems to open the port or
              # otherwise assert DTR, which would cancel the WDT reset if
              # it happened within 250 ms. So we wait until the reset should
              # have already occured before we start scanning.
              if platform.system() != 'Darwin':
                  sleep(0.3)

          elapsed = 0
          enum_delay = 0.25
          while elapsed < 10:
              now = self.e.list_serial_ports()
              diff = list(set(now) - set(before))
              if diff:
                  new_port = diff[0]
                  break

              before = now
              sleep(enum_delay)
              elapsed += enum_delay

          if not new_port:
              raise Abort("Couldn’t find a board on the selected port. "
                          "Check that you have the correct port selected. "
                          "If it is correct, try pressing the board's reset "
                          "button after initiating the upload.")

          port = new_port

      # call avrdude to upload .hex
      subprocess.call([
          self.e['avrdude'],
          '-C', self.e['avrdude.conf'],
          '-p', board['build']['mcu'],
          '-P', port,
          '-c', protocol,
          '-b', board['upload']['speed'],
          '-D',
          '-U', 'flash:w:%s:i' % self.e['hex_path'],
      ])
    def _establish_connection(self, port):
        """
        Helper method to be used by the BoardCommunicator only to connect to the
        arduino board. Tells the arduino to home upon connection.
        """
        
        cxn = Serial()
        cxn.baudrate = 115200
        
        self._logger.log("Connecting to arduino board at %s" %port)
        cxn.port = port
        
        #Attempt to connect at the previously stored port.
        try:
            cxn.open()
        except (SerialException, OSError):
            cxn.close()
            self._logger.log("Failed connection to stored port %s" %port)
            
        if cxn.isOpen():
            sleep(3)
            
            while cxn.inWaiting() > 0:
                cxn.read()
            
            #Send the handshake message
            cxn.write("connection")
            sleep(3)
            msg = cxn.read(cxn.inWaiting()).strip()
            
            self._logger.log("Handshake string received from arduino: %r" %msg)
            
            if msg == "main":
                self._logger.log("Main Arduino control unit found at port %s"
                                  %port)
                self._connection = cxn
                
                if self.send("h") == 0:
                    self._logger.log("Homing of camera successful")
                    return
                else: 
                    self._logger.log("Homing failed upon connection")
                    raise SerialException("Homing Error, please check machine")
                
            else:
                self._logger.log("Connection at port %s was not the Arduino" +
                                 " control unit")
                cxn.close()
        
        #If the stored port fails, search available ports, trying the handshake
        #at each one
        else:
            self._logger.log("Searching available ports for the Arduino "
                             "control unit")
            cxn.close()
            
            for searched_port in list_ports.comports():
                cxn.port = searched_port[0]
                
                try:
                    cxn.open()
                except (SerialException, OSError):
                    self._logger.log("Failed connection to searched port %s" 
                                     %searched_port[0])
            
                if cxn.isOpen():
                    sleep(3)
                    
                    while cxn.inWaiting() > 0:
                        cxn.read()
                        
                    cxn.write("connection")
                    sleep(3)
                    msg = cxn.read(cxn.inWaiting()).strip()
                    
                    self._logger.log("Handshake string received from arduino: %r" %msg)
                    
                    if msg == "main":
                        self._logger.log("Main Arduino control unit found at port %s"
                                         %searched_port[0])
                        self._connection = cxn
                        utils.update_config_dict("CameraCommunicator", 
                                            dict(arduino_port = searched_port[0]))

                        if self.send("h") == 0:
                            self._logger.log("Homing of camera successful")
                            return
                        else: 
                            self._logger.log("Homing failed upon connection")
                            raise SerialException("Homing Error, please check machine")
                    
                    else:
                        self._logger.log(("Connection at port %s was not the Arduino" +
                                         " control unit") %searched_port[0])
                        cxn.close()
                        
        if self._connection is None:
            self._logger.log("Did not connect to the Arduino Board after " +
                                                        "searching all ports")
            raise SerialException("Did not connect to the Arduino Board")
Example #9
0
    def doFlashTasmota(self, room: str, espType: str, siteId: str):
        port = self.findUSBPort(timeout=60)
        if port:
            self.MqttManager.say(text=self.TalkManager.randomTalk(
                'usbDeviceFound', module='AliceCore'),
                                 client=siteId)
            try:
                mac = ESPLoader.detect_chip(port=port, baud=115200).read_mac()
                mac = '%s' % (':'.join(map(lambda x: '%02x' % x, mac)))
                cmd = list()
                cmd.append('--port')
                cmd.append(port)
                cmd.append('--baud')
                cmd.append('115200')
                cmd.append('--after')
                cmd.append('no_reset')
                cmd.append('write_flash')
                cmd.append('--flash_mode')
                cmd.append('dout')
                cmd.append('0x00000')
                cmd.append('sonoff.bin')
                cmd.append('--erase-all')
                esptool.main(cmd)
            except Exception as e:
                self._logger.error(
                    f'[{self.name}] Something went wrong flashing esp device: {e}'
                )
                self.MqttManager.say(text=self.TalkManager.randomTalk(
                    'espFailed', module='AliceCore'),
                                     client=siteId)
                self._broadcastFlag.clear()
                return
        else:
            self.MqttManager.say(text=self.TalkManager.randomTalk(
                'noESPFound', module='AliceCore'),
                                 client=siteId)
            self._broadcastFlag.clear()
            return

        self._logger.info(f'[{self.name}] Tasmota flash done')
        self.MqttManager.say(text=self.TalkManager.randomTalk(
            'espFlashedUnplugReplug', module='AliceCore'),
                             client=siteId)
        found = self.findUSBPort(timeout=60)
        if found:
            self.MqttManager.say(text=self.TalkManager.randomTalk(
                'espFoundReadyForConf', module='AliceCore'),
                                 client=siteId)
            time.sleep(10)
            uid = self._getFreeUID(mac)
            tasmotaConfigs = TasmotaConfigs(deviceType=espType, uid=uid)
            confs = tasmotaConfigs.getBacklogConfigs(room)
            if not confs:
                self._logger.error(
                    f'[{self.name}] Something went wrong getting tasmota configuration'
                )
                self.MqttManager.say(text=self.TalkManager.randomTalk(
                    'espFailed', module='AliceCore'),
                                     client=siteId)
            else:
                serial = Serial()
                serial.baudrate = 115200
                serial.port = port
                serial.open()

                try:
                    for group in confs:
                        cmd = ';'.join(group['cmds'])
                        if len(group['cmds']) > 1:
                            cmd = f'Backlog {cmd}'

                        arr = list()
                        if len(cmd) > 50:
                            while len(cmd) > 50:
                                arr.append(cmd[:50])
                                cmd = cmd[50:]
                            arr.append(f'{cmd}\r\n')
                        else:
                            arr.append(f'{cmd}\r\n')

                        for piece in arr:
                            serial.write(piece.encode())
                            self._logger.info('[{}] Sent {}'.format(
                                self.name, piece.replace('\r\n', '')))
                            time.sleep(0.5)

                        time.sleep(group['waitAfter'])

                    serial.close()
                    self._logger.info(
                        f'[{self.name}] Tasmota flashing and configuring done')
                    self.MqttManager.say(text=self.TalkManager.randomTalk(
                        'espFlashingDone', module='AliceCore'),
                                         client=siteId)
                    self.addNewDevice(espType, room, uid)
                    self._broadcastFlag.clear()

                except Exception as e:
                    self._logger.error(
                        f'[{self.name}] Something went wrong writting configuration to esp device: {e}'
                    )
                    self.MqttManager.say(text=self.TalkManager.randomTalk(
                        'espFailed', module='AliceCore'),
                                         client=siteId)
                    self._broadcastFlag.clear()
                    serial.close()
        else:
            self.MqttManager.say(text=self.TalkManager.randomTalk(
                'espFailed', module='AliceCore'),
                                 client=siteId)
            self._broadcastFlag.clear()
            return
Example #10
0
from serial import Serial
import json
import requests

arduino = Serial()
arduino.baudrate = 9600
arduino.port = 'COM3'
arduino.open()

def getdata():
    count = 0
    data = ''
    while count < 5:
        data += str(arduino.readline())
        count += 1

    print(data)
    listof=data.split("\\r\\n")
    print(listof)
    realdata= listof[2].split(';')
    print(realdata)
    return realdata


if __name__ == "__main__":
    ipadress = 'http://neofinder.tech:5000/api/iot_data'
    iptoken = 'http://neofinder.tech:5000/api/iot_auth' 
    listinfo = getdata()
    iddevice=listinfo[0]
    lat=listinfo[1]
    lon=listinfo[2]
Example #11
0
  b = array('B',[0]*2)
  pack_into('H',b,0,crc)
  return b
PORT =  argv[1]   
UNIT = int(argv[2])
FC = int(argv[3])
ADD = int(argv[4])
LEN = int(argv[5])
lLEN = LEN & 0x00FF
mLEN = LEN >> 8
if (FC < 3): BYT = (lambda x: x/8 if (x%8==0) else x/8+1)(LEN)    #Round off the no. of bytes
else: BYT = LEN*2
lADD = ADD & 0x00FF
mADD = (ADD & 0xFF00)>>8
s = Serial('/dev/'+PORT, timeout=0.5)
s.baudrate = 9600
s.parity = "E"
s.databits = 8
s.stopbits = 1
s.handshake = "none"
s.datatype = "raw"
cmd = array('B', [UNIT,FC,mADD,lADD,mLEN,lLEN])
cmd.extend(CRC(cmd))
#lcrc = crc & 0x00FF
#mcrc = (crc & 0xFF00)>>8
#cmd = array('B', [UNIT,FC,mADD,lADD,mLEN,lLEN,lcrc,mcrc]) 
while 1:
  s.write(cmd)
  print cmd
  sleep(1)
  read = s.read(255)
Example #12
0
UPDATE_10_sec=  "$PMTK220,10000*2F\r\n" #Update Every 10 Seconds
UPDATE_5_sec=  "$PMTK220,5000*1B\r\n"   #Update Every 5 Seconds  
UPDATE_1_sec=  "$PMTK220,1000*1F\r\n"   #Update Every One Second
UPDATE_200_msec=  "$PMTK220,200*2C\r\n" #Update Every 200 Milliseconds
#This set is used to set the rate the GPS takes measurements
MEAS_10_sec = "$PMTK300,10000,0,0,0,0*2C\r\n" #Measure every 10 seconds
MEAS_5_sec = "$PMTK300,5000,0,0,0,0*18\r\n"   #Measure every 5 seconds
MEAS_1_sec = "$PMTK300,1000,0,0,0,0*1C\r\n"   #Measure once a second
MEAS_200_msec= "$PMTK300,200,0,0,0,0*2F\r\n"  #Meaure 5 times a second
#Set the Baud Rate of GPS
BAUD_57600 = "$PMTK251,57600*2C\r\n"          #Set Baud Rate at 57600
BAUD_9600 ="$PMTK251,9600*17\r\n"             #Set 9600 Baud Rate

serialPort.write(BAUD_57600)
time.sleep(1)
serialPort.baudrate = 57600
serialPort.write(UPDATE_200_msec)
time.sleep(1)
serialPort.write(MEAS_200_msec)
time.sleep(1)

serialPort.flushInput()
serialPort.flushOutput()

serialPort.close()

subprocess.call(['gpsctl', '-c', '0.2'])

print "done"

gpsd = None #seting the global variable
class Parser():
    #Initializes fields in the class
    #contains a serial object for receiving
    #data from the radio module
    def __init__(self, dict={}):

        #self.ser._baudrate=115200
        #number of items left in queue
        self.ser = Serial()
        self.dataItemsAvailable = 0
        self.dataDict = dict

    def open_port(self, portName):
        '''
        Opens serial port which was initialized with given name
        -For windows, name will be like 'COM4' or 'COM5'
        -For pi, the name will be something like '/dev/tty.usbserial'
        @param: portName the name of the serial port to be opened
        @return: a boolean indicating whether the port was 
                opened successfully or not
        '''
        try:
            self.ser = Serial(portName, timeout=2,
                              baudrate=baudrate)  #open serial port
            self.ser.reset_input_buffer()
            self.is_open = True
            if (not self.input.closed):
                self.input.close()
        except:
            print "Going into file mode"
            #TESTING FOR NOW
            self.input = open(inputFile, "r")
            self.ser.close()
            self.is_open = False
            #raise IllegalSerialAccess("No serial port with name: " + portName)
        self.output = open(outputFile, "w")

        #returns whether or not the port is open
        return self.ser.isOpen()

    def update(self):
        '''
            Checks If data is waiting in the serial port
            then, if it is, parses it and adds it to the data queues
            @requires: serial port is open.
            @raise IllegalStateException: if the serial port is not open 
        '''

        temp = self.input.readline().strip()

        timestamp = time.time()

        if len(temp) > 0:
            #write input to output file
            self.output.write(temp + " " + time.asctime(time.localtime()) +
                              "\n")
            self.output.flush()

            #Parse the input
            parsed_output = self.parse_string_multiple(temp)

            if parsed_output != None:
                for data_string in parsed_output:
                    if (data_string[0] == '$'):  #check if its a gps string
                        str_vec = data_string.split(",")
                        # check which kind of gps string
                        if (str_vec[0] == "$GPRMC"):
                            #assert(len(str_vec) == 12)
                            if (str_vec[2] != 'A'):  # not a valid gps read
                                continue
                            lat = str_vec[3]
                            if (str_vec[4] == 'S'):
                                lat *= -1
                            lon = str_vec[5]
                            if (str_vec[6] == 'E'):
                                lon *= -1
                        elif (str_vec[0] == "$GPGGA"):
                            #assert(len(str_vec) == 15)
                            if (str_vec[2] != 'A'):  # not a valid gps read
                                continue
                            lat = str_vec[3]
                            if (str_vec[4] == 'S'):
                                lat *= -1
                            lon = str_vec[5]
                            if (str_vec[6] == 'E'):
                                lon *= -1
                        else:
                            print "Unknown GPS token: " + str_vec[0]
                            continue

                        # Add the data to the Queues
                        self.add_to_queue('LA', lat)
                        self.add_to_queue('LO', lon)

                    elif (data_string[0] == '!'):  #check if it's data
                        #take away the side markers
                        data_string = re.sub('[!;]', '', data_string)
                        #split down middle
                        vals = data_string.split(':')

                        #ONLY TO DEAL WITH ERROR WITH SPACE ERROR
                        if (len(vals) == 1):
                            vals = data_string.split(' ')

                        type = vals[0]
                        #create a tuple of the data type and the timestamp
                        measurement = (vals[1], timestamp)

                        if (vals[1] == '6.24B'):
                            print "stop"

                        #Add the measurement to the queue
                        self.add_to_queue(type, measurement)
                    else:
                        print "Unrecognized string: " + data_string

    def is_empty(self, queue):
        return len(queue) == 0

    def parse_string(self, string):
        '''
            Parses string of data
            @param: takes in a string of the form "'NAME+ID':'double'"
            @return: returns a dictionary of data 
            names and their values or None if data 
            cannot be extracted
        '''
        #Should check for multiple data points?
        type, measurement = string.strip().split(":")
        return type[1:], measurement[:-1]

    def parse_string_multiple(self, string):
        '''
            Parses an input to make a list of well formed
            data values.
            @requires string is not None
            @param takes in a string of multiple data values which are 
            concatenated and of the form !X:DATAXXXXX;
            @return: A list of strings of the form !TYPE:DATA; Returns
            None if no usable data points could be parsed
        '''
        string = string.strip()
        parse_list = re.findall(regex, string)
        temp = re.findall(gpsregex, string)
        parse_list += temp

        if (parse_list == []):
            return None

        return parse_list

    def add_to_queue(self, dataType, value):
        '''
            Adds a value to the end of the queue for the given name
            @param: takes in the name of the queue to be added to and a value
            @modifies: if the queueName is not None and is not in the dictionary 
            of queues, add it to the dictionary and update;
        '''
        if not self.dataDict.has_key(dataType):
            #add empty queue of new data type
            temp = {dataType: deque([])}
            self.dataDict.update(temp)
        if (value != None):
            self.dataDict.get(dataType).append(value)
            self.dataItemsAvailable += 1

    def is_available(self):
        '''
            Says whether or not a queue has at least on element available
            @return: returns a boolean indicating whether or not any of the 
            queues in the dictionary contain at least one value
        '''
        return self.dataItemsAvailable > 0

    def get(self, dataType):
        '''
            Gets the first value in the queue of the given Name
            @param: takes in the name of a data type for which the user wants
            to receive data.
            @return: if the name is not None and is in the dictionary, returns
            the first value in the queue converted to a float if there exists 
            one. Otherwise, return None
            @deprecated: Use get_data_tuple instead.
        '''
        if (self.dataDict.get(dataType) == None
                or self.is_empty(self.dataDict.get(dataType))):
            return None
        else:
            data = self.dataDict.get(dataType).pop()
            self.dataItemsAvailable -= 1

            return float(data[0])

    def get_data_tuple(self, dataType):
        '''
            Gets the first value in the queue of the given Name
            @param: takes in the name of a data type for which the user wants
            to receive data.
            @return: if the name is not None and is in the dictionary, return
            the first object in the queue if there exists one.
            Otherwise, return None
        '''
        if (self.dataDict.get(dataType) == None
                or self.is_empty(self.dataDict.get(dataType))):
            return None
        else:
            data = self.dataDict.get(dataType).pop()
            self.dataItemsAvailable -= 1
            return data

    def close(self):
        print "Clean Up"
        try:
            self.ser.close()
        except:
            print "Serial is not open"
        try:
            self.output.close()
        except:
            print "Output is not open"
        try:
            self.input.close()
        except:
            print "input closed"

    def change_baudrate(self, new_rate):
        self.ser.baudrate(new_rate)
Example #14
0
__author__ = 'greyexpert'

import struct
from time import sleep
from serial import Serial
from protocol import Protocol

ser = Serial()
ser.port = "/dev/tty.usbmodemfd1331"
ser.baudrate = 155200

arduino = Protocol(ser)
arduino.start()

channel, data = arduino.waitForPackage()  # Wait for initial package

# Blinking
for x in range(10):
    sleep(1)
    arduino.send(1, struct.pack("B", x % 2))

sleep(1)  # Sleep 1 second before exit
Example #15
0
from serial import Serial

ser = Serial('/dev/ttyS0')
ser.baudrate = 100000


def parse():
	while ser.readable():
	    byte = ser.read(1)
	    print(hex(byte[0]))

parse()


'''
    def parse(self):
        # reset the parser state if too much time has elapsed
        self.calculate_sbus_time()
        if self._sbus_time > SBUSConsts.SBUS_TIMEOUT_MS:
            self._parse_state = 0
            
        header = SBUSConsts.SBUS_HEADER[0]
        mask = SBUSConsts.SBUS2_MASK[0]
        footer = SBUSConsts.SBUS_FOOTER[0]
        footer2 = SBUSConsts.SBUS2_FOOTER[0]

        # see if serial data is available
        while self._ser.readable():
            self._sbus_time = 0
            self._cur_byte = self._ser.read(1)
Example #16
0
                      dest="enable",
                      default=False,
                      help="output enable")

    (options, args) = parser.parse_args()

    if options.voltage and options.voltageDac:
        sys.stderr.write("-v and -o conflicts")
        raise SystemExit(1)

    if options.current and options.currentDac:
        sys.stderr.write("-i and -u conflicts")
        raise SystemExit(1)

    labpidserial = Serial()
    labpidserial.baudrate = 115200
    labpidserial.port = options.port
    labpidserial.timeout = 0.5  #make sure that the alive event can be checked from time to time

    labpidserial.open()
    labpid = Labpid(bus=labpidserial)
    ps = TwoChannelPowersupply(labpid, 0)

    if options.channel > 3 or options.channel < 1:
        labpidserial.close()
        sys.stderr.write("Invalid Channel\n")

    if options.voltage:
        sys.stdout.write("Voltage %f\n" % options.voltage)
        ps.setVoltage(options.channel, options.voltage)
Example #17
0
#**********************Программа******************************************

from serial import Serial, SerialException, EIGHTBITS, PARITY_NONE

import time

import logging
logger = logging.getLogger(__name__)
logging.basicConfig(filename='cmplr.log', filemode='w', level=logging.DEBUG)

SERIAL_PORT = 'COM7'
SERIAL_SPEED = 9600
ser = Serial()
ser.port = SERIAL_PORT
ser.baudrate = SERIAL_SPEED
ser.bytesize = EIGHTBITS  #number of bits per bytes
ser.timeout = 1  #non-block read
ser.writeTimeout = 2  #timeout for write
ser.xonxoff = False  #disable software flow control
ser.rtscts = False  #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False  #disable hardware (DSR/DTR) flow control

try:
    """
         Пытаемся открыть серийный порт
      """
    ser.open()

except SerialException as e:
Example #18
0
from serial import Serial
import math
from time import sleep
from colorsys import rgb_to_hls

SERIAL_PORT = "/dev/ttyACM0"
BAUD_RATE = 9600
TOTAL_LEDS = 12
PRIMARY_RADIUS = 250
LED_RADIUS = 40
WINDOW_SIZE = 600
TAU = 2 * math.pi

ser = Serial()
ser.port = SERIAL_PORT
ser.baudrate = BAUD_RATE

def get_colour():
    return "#" + ser.read(3).hex()

def get_start_signal():
    signal = b""
    zeros = 0
    while zeros < 3:
        signal = ser.read()
        if signal == b"\0":
            zeros += 1
        else:
            zeros = 0

root = Tk()
Example #19
0
if ((len(argv)<2) or (argv[1]=='?') or (argv[1]=='--help')): 
  print "---usage: python "+argv[0]+" port"
  exit()
stop = False
read = False
msg = ""
bd = [115200,9600,1200]
fr = ord('0')
to = ord('z') + 1
for i in range(fr,to):
	msg = msg + chr(i)
def clean(s):
  s.flushInput()
  s.flushOutput()
try:
  ser = Serial('/dev/'+argv[1], timeout=0.5)
  for i in range(3):
    ser.baudrate = bd[i]
    print "\nAt baudrate %s:\n Writing: %s" %(bd[i],msg)
    ser.write(msg)
    read = ser.read(to-fr)
    if (read != msg):
      print "\nError in loopback, check hardware connection, jumper terminals 2 & 3 and repeat the test\n"
      clean(ser)
      exit()
    else: print " Reading: %s" %read
  print "\nLoopBack Test Done Successfully\n" 
  clean(ser)
except SerialException:
  print argv[1],": port does not exist"
  exit()
Example #20
0
def main():
    # DEBUG port ('/dev/ttyUSB3', 'COM6', etc.), typically the last one.
    port = sys.argv[1]

    # Recovery directory (recovery protocol version 2).
    recovery_dir = sys.argv[2]

    # Device capabilities file (with matching device id).
    device_caps = sys.argv[3]

    recovery_1bl      = os.path.join(recovery_dir, "recovery-1bl-rtm.bin")
    recovery_runtime  = os.path.join(recovery_dir, "recovery-runtime.bin")
    recovery_manifest = os.path.join(recovery_dir, "recovery.imagemanifest")

    # XXX: These sizes are hardcoded in the 'ServerMessageType.ImageRequestAck'
    # messages below.
    assert_file_size(device_caps, 0x188)
    assert_file_size(recovery_runtime, 0xeda4)
    assert_file_size(recovery_manifest, 0x5d8)

    timeout = 2

    serial = Serial(
        port=port,
        baudrate=115200,
        parity=PARITY_NONE,
        bytesize=8,
        stopbits=1,
        rtscts=0,
        timeout=timeout)

    # Check that the board is in recovery mode.
    # If you open the port directly and hit the RESET button, you should see:
    # RECOVERY
    # 0000362000008A01020A00008FC8C833
    # CCC
    #
    # 'C's mean that this is XMODEM with CRC-16 and the receiver is ready to
    # receive data.
    # http://web.mit.edu/6.115/www/amulet/xmodem.htm

    serial.timeout = 10
    output = read(serial, 10)
    serial.timeout = timeout

    # If you're getting an error here:
    # - the board is not in recovery mode
    # - you connected too early, try again
    # - something is wrong with the serial port (try opening it in ExtraPutty,
    #   it supports XMODEM too).
    assert b"CC" in output

    # Send the recovery 1BL over XMODEM.
    print(yellow("[<] Sending recovery 1BL"))
    stream = open(recovery_1bl, "rb")
    xmodem_send(serial, stream, timeout)

    # Output: b'+GOOD\r\n'
    readline(serial)

    # Output: b'[1BL] BOOT: INIT\r\n'
    # or
    # Output: b'[1BL] BOOT: 28030000/00000010/07000000\r\n'
    # The postcode (the last three numbers) might be different.
    #
    # In C# code: 'WaitForRecoveryBoot', 'VerifyBootMessage', 'DeviceResponses'.
    readline(serial)

    # Output: b'\x02\x89\x02\x01\x02\x85\x02\x01\x01\x01\x81006fe629beb69fc3bb06cf8494ccc25461f597aae076aa0d1f9b49656d60b63557becad65b338a1a5b4104f769649aaa35340eca1f1899df610305506cd7bee8\x03\xbe\x03\x00 (repeated)'
    #
    # Format:
    # \x02\x89\x02\x01\x02\x85\x02\x01\x01\x01\x81
    # 006...bee8 -- Device ID
    # \x03\xbe\x03
    # \x00 -- end of packet
    #
    # COBS uses the NULL byte as the packet delimiter.
    # Decoded: b'\x89\x00\x01\x00\x85\x00\x01\x00\x00\x00006fe629beb69fc3bb06cf8494ccc25461f597aae076aa0d1f9b49656d60b63557becad65b338a1a5b4104f769649aaa35340eca1f1899df610305506cd7bee8\x00\xbe\x03'
    #
    # Format:
    # \x89\x00 -- packet size (137, little-endian)
    # \x01\x00 -- ClientMessageType.Initialization (1, little-endian)
    # \x85\x00 -- data size (133, little-endian)
    # \x01\x00\x00\x00 -- version (1, little-endian)
    # 006...bee8 -- Device ID
    # \x00  -- NULL terminator
    # \xbe\x03 -- unk (probably CRC-16).
    output, leftovers = read_decode(serial)

    # In C# code: 'ServerMessageType', 'ControlProtocol'.
    #
    # Format (case for payload length == 0):
    # The array that CRC-16 is calculated on:
    # 04 00 a0 00 00 00
    # \x04\x00 -- size
    # \xa0\x00 -- ServerMessageType.InitializationAck (0x00A0)
    # \x00\x00 -- end of the message.
    #
    # CRC-16 value: 0xecd7.
    #
    # The final array should be:
    # 02 04 02 a0 01 01 03 d7 ec 00
    # last \x00 -- packet delimiter.
    #
    # b"\x02\x04\x02\xa0\x01\x01\x03\xd7\xec\x00"
    write_encode(serial, b"\xa0\x00\x00\x00")

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent
    # \x01\x00 -- payload size (1, little-endian)
    # \x01 -- RecoveryEventType.BLInitializationComplete
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x0b\x00\x01\x00\x01"

    # Format:
    # \t\x00 -- ClientMessageType.LogConfigQuery (0x0009)
    # \x00\x00 -- payload size (0, little-endian)
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\t\x00\x00\x00"

    # Sending: b'\x02\x05\x02\xa3\x02\x01\x01\x03!\x8a\x00'
    #
    # In C# code: 'BuildResponse', 'SimpleAckResponse'.
    # Format:
    # \xa3\x00 -- ServerMessageType.SimpleQueryAck (0x00a3)
    # \x01\x00 -- payload size (1, little-endian)
    # \x00     -- ackResponse (0 or 1)
    # XXX: Try sending 1 here as ackResponse.
    write_encode(serial, b"\xa3\x00\x01\x00\x00")

    # In C# code: class 'RequestFileBase'.
    #
    # Format:
    # \x04\x00 -- ClientMessageType.ImageRequestCapability (0x0004)
    # \x08\x00 -- payload size (8, little-endian)
    # \x00\x00\x00\x00 -- index?
    # \xff\xff\xff\xff -- file size?
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x04\x00\x08\x00\x00\x00\x00\x00\xff\xff\xff\xff"

    # Format:
    # \xa4\x00 -- ServerMessageType.ImageRequestAck (0x00a4)
    # \x0c\x00 -- payload size (12, little-endian)
    # \x00\x00\x00\x00 -- start index?
    # \x88\x01\x00\x00 -- send size?
    # \x88\x01\x00\x00 -- total size?
    write_encode(
        serial,
        (b"\xa4\x00" +
         b"\x0c\x00" +
         b"\x00\x00\x00\x00" +
         b"\x88\x01\x00\x00" +
         b"\x88\x01\x00\x00"))

    # Send device capabilities over XMODEM.
    print(yellow("[<] Sending device capabilities"))
    stream = open(device_caps, "rb")
    xmodem_send(serial, stream, timeout)

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent (0x000b)
    # \x01\x00 -- payload size (1, little-endian)
    # \x02 -- RecoveryEventType.BLCapabilityImageReceived
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x0b\x00\x01\x00\x02"

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent (0x000b)
    # \x01\x00 -- payload size (1, little-endian)
    # \x03 -- RecoveryEventType.BLCapabilityImageLoaded
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x0b\x00\x01\x00\x03"

    # Format:
    # \x07\x00 -- ClientMessageType.ImageRequestByFilename
    # \x1d\x00 -- size (29, little-endian)
    # \x00\x00\x00\x00 -- index?
    # \xff\xff\xff\xff -- file size?
    # recovery-runtime.bin -- filename
    # \x00 -- terminator
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x07\x00\x1d\x00\x00\x00\x00\x00\xff\xff\xff\xffrecovery-runtime.bin\x00"

    # Format:
    # \xa4\x00 -- ServerMessageType.ImageRequestAck (0x00a4)
    # \x0c\x00 -- payload size (12, little-endian)
    # \x00\x00\x00\x00 -- start index?
    # \xa4\xed\x00\x00 -- send size?
    # \xa4\xed\x00\x00 -- total size?
    write_encode(
        serial,
        (b"\xa4\x00"
         b"\x0c\x00"
         b"\x00\x00\x00\x00"
         b"\xa4\xed\x00\x00"
         b"\xa4\xed\x00\x00"))

    # Send the recovery runtime over XMODEM.
    print(yellow("[<] Sending recovery runtime"))
    stream = open(recovery_runtime, "rb")
    xmodem_send(serial, stream, timeout)

    # Format:
    # \t\x00 -- ClientMessageType.LogConfigQuery (0x0009)
    # \x00\x00 -- payload size (0, little-endian)
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\t\x00\x00\x00"

    # Format:
    # \xa3\x00 -- ServerMessageType.SimpleQueryAck (0x00a3)
    # \x01\x00 -- payload size (1, little-endian)
    # \x00     -- ackResponse (0 or 1)
    write_encode(serial, b"\xa3\x00\x01\x00\x00")

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent (0x000b)
    # \x01\x00 -- payload size (1, little-endian)
    # \x06 -- RecoveryEventType.RABootComplete
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x0b\x00\x01\x00\x06"

    # Format:
    # \x03\x00 -- ClientMessageType.BaudrateSwitchQuery (0x0003)
    # \x00\x00 -- payload size (0, little-endian)
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x03\x00\x00\x00"

    # Format:
    # \xa3\x00 -- ServerMessageType.SimpleQueryAck (0x00a3)
    # \x01\x00 -- payload size (1, little-endian)
    # \x01     -- ackResponse (0 or 1)
    #
    # Baudrate settings:
    # {
    #   PortMode.Bootloader,
    #   new SerialPortConfiguration()
    #   {
    #     BaudRate = 115200,
    #     Parity = Parity.None,
    #     DataBits = 8,
    #     StopBits = StopBits.One,
    #     Handshake = Handshake.None
    #   }
    # },
    # {
    #   PortMode.ImagingMt3620,
    #   new SerialPortConfiguration()
    #   {
    #     BaudRate = 3000000,
    #     Parity = Parity.None,
    #     DataBits = 8,
    #     StopBits = StopBits.One,
    #     Handshake = Handshake.RequestToSend
    #   }
    # },
    # {
    #   PortMode.ImagingMt3620LowSpeed,
    #   new SerialPortConfiguration()
    #   {
    #     BaudRate = 115200,
    #     Parity = Parity.None,
    #     DataBits = 8,
    #     StopBits = StopBits.One,
    #     Handshake = Handshake.RequestToSend
    #   }
    # }
    # write_encode(serial, b"\xa3\x00\x01\x00\x01")  # XXX: doesn't work
    write_encode(serial, b"\xa3\x00\x01\x00\x00")

    # serial.baudrate = 3000000  # XXX: doesn't work
    serial.baudrate = 115200
    serial.parity = PARITY_NONE
    serial.bytesize = 8
    serial.stopbits = 1
    serial.rtscts = 1

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent (0x000b)
    # \x01\x00 -- payload size (1, little-endian)
    # \x07     -- RecoveryEventType.RAEraseFlashStarted
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x0b\x00\x01\x00\x07"

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent (0x000b)
    # \x01\x00 -- payload size (1, little-endian)
    # \x08     -- RecoveryEventType.RAEraseFlashComplete
    print("[i] Waiting for flash erase to complete")
    while True:
        try:
            output, leftovers = smart_decode(serial, leftovers)
            break
        except EmptyOutputError:
            continue
    assert output == b"\x0b\x00\x01\x00\x08"

    # Format:
    # \x07\x00 -- ClientMessageType.ImageRequestByFilename
    # \x1f\x00 -- size (31, little-endian)
    # \x00\x00\x00\x00 -- index?
    # \xff\xff\xff\xff -- file size?
    # recovery.imagemanifest -- filename
    # \x00 -- terminator
    output, leftovers = smart_decode(serial, leftovers)
    assert output == b"\x07\x00\x1f\x00\x00\x00\x00\x00\xff\xff\xff\xffrecovery.imagemanifest\x00"

    # Format:
    # \xa4\x00 -- ServerMessageType.ImageRequestAck (0x00a4)
    # \x0c\x00 -- payload size (12, little-endian)
    # \x00\x00\x00\x00 -- start index?
    # \xd8\x05\x00\x00 -- send size?
    # \xd8\x05\x00\x00 -- total size?
    write_encode(
        serial,
        (b"\xa4\x00" +
         b"\x0c\x00" +
         b"\x00\x00\x00\x00" +
         b"\xd8\x05\x00\x00" +
         b"\xd8\x05\x00\x00"))

    # Send the recovery manifest over XMODEM.
    print(yellow("[<] Sending recovery manifest"))
    stream = open(recovery_manifest, "rb")
    xmodem_send(serial, stream, timeout)

    # Format:
    # \x0b\x00 -- ClientMessageType.RecoveryEvent
    # \x01\x00 -- payload size (1, little-endian)
    # \x09 -- RecoveryEventType.RAManifestReceived
    output, leftovers = smart_decode(serial, leftovers)
    assert output ==  b"\x0b\x00\x01\x00\t"
 def addDevice(self, device):
     tty = Serial(device, 9600)
     tty.baudrate = 115200
     endPointWrapper = EndPointWrapper(tty, self.switchEventQueue)
     endPointWrapper.ensureID()
     self.endPoints[endPointWrapper.id] = endPointWrapper
__author__ = 'paweber'

from Crc import CRCCCITT
from serial import Serial

# Board connection
board = Serial("COM11")
board.baudrate = 115200

#crc calculator
crcCalculator = CRCCCITT()

packetLength = 13;

# Header
preamble = 0x55
version = 0x01

# Modes
mode = {}
mode['read'] = 0x00
mode['write'] = 0x01
mode['conn check'] = 0x02
mode['ack'] = 0x03

# Channels
channel = {}
channel['none'] = 0x00
channel['one'] = 0x01
channel['two'] = 0x02
channel['three'] = 0x03
Example #23
0
from serial import Serial
# connect just computer port to wavemeter using RS232 adapter
# not used for arduino

ser = Serial()
ser.port = 'COM7'
ser.baudrate = 19200
ser.open()
print(ser.is_open)

#ser.write(b"*IDN?\n")
#ser.write("*IDN?\n".encode())
# end of line (EOL) character is \n
#print(ser.read(39)) # number of bytes, if larger than output will run loop

### Communicating read and write no matter how long ###
ser.write(b":READ:POWer:WAVelength?\n")
ser_bytes = ser.readline()
decoded_bytes = ser_bytes[0:len(ser_bytes) - 1].decode()
print(decoded_bytes)

ser.write(b"*IDN?\n")
ser_bytes2 = ser.readline()
decoded_bytes2 = ser_bytes2[0:len(ser_bytes2) - 1].decode()
print(decoded_bytes2)

### Loop ###
while True:
    try:
        ser.write(b":READ:POWer:WAVelength?\n")
        ser_bytes = ser.readline()
    def run(self) -> None:
        Logger.log("d", "Auto detect baud rate started.")
        wait_response_timeouts = [3, 15, 30]
        wait_bootloader_times = [1.5, 5, 15]
        write_timeout = 3
        read_timeout = 3
        tries = 2

        programmer = Stk500v2()
        serial = None
        try:
            programmer.connect(self._serial_port)
            serial = programmer.leaveISP()
        except ispBase.IspError:
            programmer.close()

        for retry in range(tries):
            for baud_rate in self._all_baud_rates:
                if retry < len(wait_response_timeouts):
                    wait_response_timeout = wait_response_timeouts[retry]
                else:
                    wait_response_timeout = wait_response_timeouts[-1]
                if retry < len(wait_bootloader_times):
                    wait_bootloader = wait_bootloader_times[retry]
                else:
                    wait_bootloader = wait_bootloader_times[-1]
                Logger.log(
                    "d",
                    "Checking {serial} if baud rate {baud_rate} works. Retry nr: {retry}. Wait timeout: {timeout}"
                    .format(serial=self._serial_port,
                            baud_rate=baud_rate,
                            retry=retry,
                            timeout=wait_response_timeout))

                if serial is None:
                    try:
                        serial = Serial(str(self._serial_port),
                                        baud_rate,
                                        timeout=read_timeout,
                                        writeTimeout=write_timeout)
                    except SerialException:
                        Logger.logException("w", "Unable to create serial")
                        continue
                else:
                    # We already have a serial connection, just change the baud rate.
                    try:
                        serial.baudrate = baud_rate
                    except ValueError:
                        continue
                sleep(
                    wait_bootloader
                )  # Ensure that we are not talking to the boot loader. 1.5 seconds seems to be the magic number
                successful_responses = 0

                serial.write(b"\n")  # Ensure we clear out previous responses
                serial.write(b"M105\n")

                start_timeout_time = time()
                timeout_time = time() + wait_response_timeout

                while timeout_time > time():
                    line = serial.readline()
                    if b"ok" in line and b"T:" in line:
                        successful_responses += 1
                        if successful_responses >= 1:
                            self.setResult(baud_rate)
                            Logger.log(
                                "d",
                                "Detected baud rate {baud_rate} on serial {serial} on retry {retry} with after {time_elapsed:0.2f} seconds."
                                .format(serial=self._serial_port,
                                        baud_rate=baud_rate,
                                        retry=retry,
                                        time_elapsed=time() -
                                        start_timeout_time))
                            serial.close(
                            )  # close serial port so it can be opened by the USBPrinterOutputDevice
                            return

                    serial.write(b"M105\n")
            sleep(15)  # Give the printer some time to init and try again.
        self.setResult(None)  # Unable to detect the correct baudrate.
Example #25
0
    def _establish_connection(self, port):
        """
        Helper method to be used by the BoardCommunicator only to connect to the
        arduino board. Tells the arduino to home upon connection.
        """

        cxn = Serial()
        cxn.baudrate = 115200

        self._logger.log("Connecting to arduino board at %s" % port)
        cxn.port = port

        #Attempt to connect at the previously stored port.
        try:
            cxn.open()
        except (SerialException, OSError):
            cxn.close()
            self._logger.log("Failed connection to stored port %s" % port)

        if cxn.isOpen():
            sleep(3)

            while cxn.inWaiting() > 0:
                cxn.read()

            #Send the handshake message
            cxn.write("connection")
            sleep(3)
            msg = cxn.read(cxn.inWaiting()).strip()

            self._logger.log("Handshake string received from arduino: %r" %
                             msg)

            if msg == "main":
                self._logger.log("Main Arduino control unit found at port %s" %
                                 port)
                self._connection = cxn

                if self.send("h") == 0:
                    self._logger.log("Homing of camera successful")
                    return
                else:
                    self._logger.log("Homing failed upon connection")
                    raise SerialException("Homing Error, please check machine")

            else:
                self._logger.log("Connection at port %s was not the Arduino" +
                                 " control unit")
                cxn.close()

        #If the stored port fails, search available ports, trying the handshake
        #at each one
        else:
            self._logger.log("Searching available ports for the Arduino "
                             "control unit")
            cxn.close()

            for searched_port in list_ports.comports():
                cxn.port = searched_port[0]

                try:
                    cxn.open()
                except (SerialException, OSError):
                    self._logger.log("Failed connection to searched port %s" %
                                     searched_port[0])

                if cxn.isOpen():
                    sleep(3)

                    while cxn.inWaiting() > 0:
                        cxn.read()

                    cxn.write("connection")
                    sleep(3)
                    msg = cxn.read(cxn.inWaiting()).strip()

                    self._logger.log(
                        "Handshake string received from arduino: %r" % msg)

                    if msg == "main":
                        self._logger.log(
                            "Main Arduino control unit found at port %s" %
                            searched_port[0])
                        self._connection = cxn
                        utils.update_config_dict(
                            "CameraCommunicator",
                            dict(arduino_port=searched_port[0]))

                        if self.send("h") == 0:
                            self._logger.log("Homing of camera successful")
                            return
                        else:
                            self._logger.log("Homing failed upon connection")
                            raise SerialException(
                                "Homing Error, please check machine")

                    else:
                        self._logger.log(
                            ("Connection at port %s was not the Arduino" +
                             " control unit") % searched_port[0])
                        cxn.close()

        if self._connection is None:
            self._logger.log("Did not connect to the Arduino Board after " +
                             "searching all ports")
            raise SerialException("Did not connect to the Arduino Board")
# David Chatting - github.com/davidchatting/Approximate
# MIT License - Copyright (c) February 2021
#
# Adapted from: http://www.mikeburdis.com/wp/notes/plotting-serial-port-data-using-python-and-matplotlib/

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import numpy as np
import random
from serial import Serial

#initialize serial port
ser = Serial()
ser.port = '/dev/tty.SLAB_USBtoUART' #ESP32 serial port
ser.baudrate = 9600
ser.timeout = 10 #specify timeout when using readline()
ser.open()
if ser.is_open==True:
    # Create figure for plotting
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    xs = []
    ys = []

    # This function is called periodically from FuncAnimation
    def animate(i, xs, ys):
        line=ser.readline().strip()
        line_as_list = line.split(b'\t')

        if len(line_as_list)==52:
Example #27
0
import sys
import pynmea2
from serial import Serial

ser = Serial()
ser.baudrate = 9600
ser.port = '/dev/ttyUSB0'

ser.open()
   
if not ser.isOpen():
   print("Unable to open serial port!")
   raise SystemExit
   
reader = pynmea2.NMEAStreamReader()
   
while True:
   raw = ser.readline()
   if raw[0] == 36:
      gps = raw.decode("ascii") 
      msg = pynmea2.parse(gps)
      print("MSG: {0}/{1}".format(msg.talker, msg.sentence_type))
Example #28
0
    def run(self, args):
        self.discover()
        port = args.serial_port or self.e.guess_serial_port()
        board = self.e.board_model(args.board_model)

        protocol = board['upload']['protocol']
        if protocol == 'stk500':
            # if v1 is not specifid explicitly avrdude will
            # try v2 first and fail
            protocol = 'stk500v1'

        if not os.path.exists(port):
            raise Abort("%s doesn't exist. Is Arduino connected?" % port)

        # send a hangup signal when the last process closes the tty
        file_switch = '-f' if platform.system() == 'Darwin' else '-F'
        ret = subprocess.call([self.e['stty'], file_switch, port, 'hupcl'])
        if ret:
            raise Abort("stty failed")

        # pulse on DTR
        try:
            s = Serial(port, 115200)
        except SerialException as e:
            raise Abort(str(e))
        s.setDTR(False)
        sleep(0.1)
        s.setDTR(True)
        s.close()

        # Need to do a little dance for Leonardo and derivatives:
        # open then close the port at the magic baudrate (usually 1200 bps) first
        # to signal to the sketch that it should reset into bootloader. after doing
        # this wait a moment for the bootloader to enumerate. On Windows, also must
        # deal with the fact that the COM port number changes from bootloader to
        # sketch.
        if board['bootloader']['path'] == "caterina":
            caterina_port = None
            before = self.e.list_serial_ports()
            if port in before:
                ser = Serial()
                ser.port = port
                ser.baudrate = 1200
                ser.open()
                ser.close()

                # Scanning for available ports seems to open the port or
                # otherwise assert DTR, which would cancel the WDT reset if
                # it happened within 250 ms. So we wait until the reset should
                # have already occured before we start scanning.
                if platform.system() != 'Darwin':
                    sleep(0.3)

            elapsed = 0
            enum_delay = 0.25
            while elapsed < 10:
                now = self.e.list_serial_ports()
                diff = list(set(now) - set(before))
                if diff:
                    caterina_port = diff[0]
                    break

                before = now
                sleep(enum_delay)
                elapsed += enum_delay

            if caterina_port == None:
                raise Abort("Couldn’t find a Leonardo on the selected port. "
                            "Check that you have the correct port selected. "
                            "If it is correct, try pressing the board's reset "
                            "button after initiating the upload.")

            port = caterina_port

        # call avrdude to upload .hex
        subprocess.call([
            self.e['avrdude'],
            '-C', self.e['avrdude.conf'],
            '-p', board['build']['mcu'],
            '-P', port,
            '-c', protocol,
            '-b', board['upload']['speed'],
            '-D',
            '-U', 'flash:w:%s:i' % self.e['hex_path'],
        ])
Example #29
0
    def run(self, args):
        self.discover(args.board_model)
        board = self.e.board_model(args.board_model)

        if args.board_model.startswith('teensy'):
            post_compile = self.e[board['build']['post_compile_script']]
            reboot = self.e[board['upload']['avrdude_wrapper']]
            # post_compile script requires:
            #  .hex filename w/o the extension
            filename = os.path.splitext(self.e.hex_filename)[0]
            #  full path to directory with the compiled .hex file 
            fullpath = os.path.realpath(self.e.build_dir)
            #  full path to the tools directory
            tooldir = self.e.find_arduino_dir('', ['hardware', 'tools'])
            subprocess.call([
                post_compile,
                '-file=' + filename,
                '-path=' + fullpath, 
                '-tools=' + tooldir
            ])
            # reboot to complete the upload
            # NOTE: this will warn the user if they need to press the reset button
            subprocess.call([
                reboot
            ])
            exit(0)

        port = args.serial_port or self.e.guess_serial_port()
        protocol = board['upload']['protocol']
        if protocol == 'stk500':
            # if v1 is not specifid explicitly avrdude will
            # try v2 first and fail
            protocol = 'stk500v1'

        if not os.path.exists(port):
            raise Abort("%s doesn't exist. Is Arduino connected?" % port)

        # send a hangup signal when the last process closes the tty
        file_switch = '-f' if platform.system() == 'Darwin' else '-F'
        ret = subprocess.call([self.e['stty'], file_switch, port, 'hupcl'])
        if ret:
            raise Abort("stty failed")

        # pulse on DTR
        try:
            s = Serial(port, 115200)
        except SerialException as e:
            raise Abort(str(e))
        s.setDTR(False)
        sleep(0.1)
        s.setDTR(True)
        s.close()

        # Need to do a little dance for Leonardo and derivatives:
        # open then close the port at the magic baudrate (usually 1200 bps) first
        # to signal to the sketch that it should reset into bootloader. after doing
        # this wait a moment for the bootloader to enumerate. On Windows, also must
        # deal with the fact that the COM port number changes from bootloader to
        # sketch.
        touch_port = \
                board['upload'].get('use_1200bps_touch') == 'true' or \
                board['upload']['protocol'] == 'avr109'

        if touch_port:
            new_port = None
            before = self.e.list_serial_ports()
            if port in before:
                ser = Serial()
                ser.port = port
                ser.baudrate = 1200
                ser.open()
                ser.close()

                # Scanning for available ports seems to open the port or
                # otherwise assert DTR, which would cancel the WDT reset if
                # it happened within 250 ms. So we wait until the reset should
                # have already occured before we start scanning.
                if platform.system() != 'Darwin':
                    sleep(0.3)

            elapsed = 0
            enum_delay = 0.25
            while elapsed < 10:
                now = self.e.list_serial_ports()
                diff = list(set(now) - set(before))
                if diff:
                    new_port = diff[0]
                    break

                before = now
                sleep(enum_delay)
                elapsed += enum_delay

            if not new_port:
                raise Abort("Couldn’t find a board on the selected port. "
                            "Check that you have the correct port selected. "
                            "If it is correct, try pressing the board's reset "
                            "button after initiating the upload.")

            port = new_port

        # call avrdude to upload .hex
        subprocess.call([
            self.e['avrdude'],
            '-C', self.e['avrdude.conf'],
            '-p', board['build']['mcu'],
            '-P', port,
            '-c', protocol,
            '-b', board['upload']['speed'],
            '-D',
            '-U', 'flash:w:%s:i' % self.e['hex_path'],
        ])
Example #30
0
    def run(self) -> None:
        Logger.log("d", "Auto detect baud rate started.")
        wait_response_timeouts = [3, 15, 30]
        wait_bootloader_times = [1.5, 5, 15]
        write_timeout = 3
        read_timeout = 3
        tries = 2

        programmer = Stk500v2()
        serial = None
        try:
            programmer.connect(self._serial_port)
            serial = programmer.leaveISP()
        except ispBase.IspError:
            programmer.close()

        for retry in range(tries):
            for baud_rate in self._all_baud_rates:
                if retry < len(wait_response_timeouts):
                    wait_response_timeout = wait_response_timeouts[retry]
                else:
                    wait_response_timeout = wait_response_timeouts[-1]
                if retry < len(wait_bootloader_times):
                    wait_bootloader = wait_bootloader_times[retry]
                else:
                    wait_bootloader = wait_bootloader_times[-1]
                Logger.log("d", "Checking {serial} if baud rate {baud_rate} works. Retry nr: {retry}. Wait timeout: {timeout}".format(
                    serial = self._serial_port, baud_rate = baud_rate, retry = retry, timeout = wait_response_timeout))

                if serial is None:
                    try:
                        serial = Serial(str(self._serial_port), baud_rate, timeout = read_timeout, writeTimeout = write_timeout)
                    except SerialException:
                        Logger.logException("w", "Unable to create serial")
                        continue
                else:
                    # We already have a serial connection, just change the baud rate.
                    try:
                        serial.baudrate = baud_rate
                    except ValueError:
                        continue
                sleep(wait_bootloader)  # Ensure that we are not talking to the boot loader. 1.5 seconds seems to be the magic number
                successful_responses = 0

                serial.write(b"\n")  # Ensure we clear out previous responses
                serial.write(b"M105\n")

                start_timeout_time = time()
                timeout_time = time() + wait_response_timeout

                while timeout_time > time():
                    line = serial.readline()
                    if b"ok " in line and b"T:" in line:
                        successful_responses += 1
                        if successful_responses >= 3:
                            self.setResult(baud_rate)
                            Logger.log("d", "Detected baud rate {baud_rate} on serial {serial} on retry {retry} with after {time_elapsed:0.2f} seconds.".format(
                                serial = self._serial_port, baud_rate = baud_rate, retry = retry, time_elapsed = time() - start_timeout_time))
                            serial.close() # close serial port so it can be opened by the USBPrinterOutputDevice
                            return

                    serial.write(b"M105\n")
            sleep(15)  # Give the printer some time to init and try again.
        self.setResult(None)  # Unable to detect the correct baudrate.
Example #31
0
__author__ = 'greyexpert'

import struct
from time import sleep
from serial import Serial
from protocol import Protocol

ser = Serial()
ser.port = "/dev/tty.usbmodemfd1331"
ser.baudrate = 155200

arduino = Protocol(ser)
arduino.start()

channel, data = arduino.waitForPackage() # Wait for initial package

# Blinking
for x in range(10):
    sleep(1)
    arduino.send(1, struct.pack("B", x % 2))

sleep(1) # Sleep 1 second before exit
Example #32
0
# !/usr/bin/env python3
# _*_ coding: utf-8 _*_
# create on 2017.3.1
# author:fan

import struct
import binascii
import time
from serial import Serial  # 导入模块
t = Serial('com2')  # 创建Serial实例
t.baudrate = 115200  # 设置参数(参数设置请以实际为准)
t.bytesize = 7
t.stopbits = 1
t.parity = 'E'

print('''
            com = %s
      baud_rate = %d
      data_size = %d
         parity = %s
      stop_bits = %d''' %
      (t.port, t.baudrate, t.bytesize, t.parity, t.stopbits))


def watch_com(read_size=4, write_data='ff', sleep_time=0.1):
    i = 0
    while i < 10:
        i += 1
        if i == 32767:
            i = 0
        time.sleep(sleep_time)
print('Connect to Arduino:\t', arduino)
print('Connect to Steve:\t', stev)
print()
print('Trying to activate all possible Connections:')

if arduino:
    com_ports_red = com_ports[:-1]
    for i, val in enumerate(com_ports_red):
        if not con_ard_enable:
            try:
                'Serial-Objekt instanziieren'
                device = Serial()
                'Port festlegen'
                device.port = com_ports[i]
                'Baudrate festlegen'
                device.baudrate = 115200
                'Timeout festlegen'
                device.timeout = 1

                device.open()

                con_ard_enable = True
                print('Connected to Arduino by', com_ports[i], '.')
            except SerialException:
                print('Connection to Arduino by ', com_ports[i],
                      ' not possible, trying ', com_ports[i + 1], '.')

    if not con_ard_enable:
        try:
            i = i + 1
            'Serial-Objekt instanziieren'
Example #34
0
"""
@object: Implementation of a serial server to retrieve and back up data
         and metadata from a prototype as part of a dual-screen smartphone 
         experience.
@author: PECCHIOLI Mathieu
"""
# IMPORT LIBRAIRIES
from serial import Serial
from Package.package_serial import decode, readMetadata
from os import system

# SETTING UP SERIAL PORTS
ast1 = Serial()
ast2 = Serial()
ast1.baudrate = 9600
ast2.baudrate = 9600
ast1.port = '/dev/ttyACM0'
ast2.port = '/dev/ttyACM1'

# OPEN SERIAL PORTS
ast1.open()
ast2.open()

# RUNNING
system('clear')
print("SERVER STARTED\n\n")
while True:
    # READ SERIAL PORT 1
    while ast1.in_waiting:
        data = ast1.read(1).decode('utf-8')
        if data == '$':
Example #35
0
def main(argv):
    port = 8000
    configfile = None
    logfile = None

    i = 1
    while i < len(argv):
        if argv[i] in ["-c", "-C", "--config-file"]:
            configfile = argv[i + 1]
            i += 1
        elif argv[i] in ["-l", "-L", "--log-file"]:
            logfile = argv[i + 1]
            i += 1
        elif argv[i] in ["-h", "-H", "--help"]:
            displayHelp()
        elif argv[i] in ["-d", "--debug"]:
            setDebug()
        else:
            try:
                port = int(argv[i])
            except ValueError:
                displayHelp()
        i += 1

    if logfile:
        logToFile(logfile)

    info("Starting XBee %s" % VERSION)

    # setup serial
    serial = Serial()
    serial.port = '/dev/ttyAMA0'
    serial.baudrate = 9600
    serial.timeout = 1
    serial.writeTimeout = 1
    serial.open()

    # disregard any pending data in xbee buffer
    serial.flushInput()

    # force to show xbee boot menu
    time.sleep(.5)
    serial.writelines("\r")
    time.sleep(.5)

    # read menu
    while serial.inWaiting() > 0:
        debug("%s" % serial.readline())

    # trigger bypass automatically
    serial.writelines("B")

    # post startup message to other XBee's and at stdout
    #serial.writelines("RPi #1 is up and running.\r\n")
    info("RPi #1 is up and running.")

    try:
        while True:
            waitToSend = True

            # read a line from XBee and convert it from b'xxx\r\n' to xxx and send to webiopi
            while serial.inWaiting() > 0:
                try:
                    line = serial.readline().decode('utf-8').strip('\n\r')
                    if line:
                        waitToSend = False
                        debug("Received: %s" % line)
                        try:
                            client = PiHttpClient("127.0.0.1")
                            macro = Macro(client, "setCarInfo")
                            macro.call(line.replace(",", "%2C"))
                        except:
                            exception("setting car info failed!")

                except KeyboardInterrupt:
                    raise
                except Exception as e:
                    exception(e)
                    time.sleep(1.)

            try:
                time.sleep(1.)

                client = PiHttpClient("127.0.0.1")
                macro = Macro(client, "getPitInfo")
                data = macro.call()
                if data:
                    debug("Sending: %s" % data)
                    serial.writelines(data + "\n")

            except KeyboardInterrupt:
                raise
            except Exception as e:
                exception(e)
                time.sleep(1.)

    except KeyboardInterrupt:
        info("*** Ctrl-C keyboard interrupt ***")
Example #36
0
def main(argv):
	port = 8000
	configfile = None
	logfile = None

	i = 1
	while i < len(argv):
		if argv[i] in ["-c", "-C", "--config-file"]:
			configfile = argv[i+1]
			i+=1
		elif argv[i] in ["-l", "-L", "--log-file"]:
			logfile = argv[i+1]
			i+=1
		elif argv[i] in ["-h", "-H", "--help"]:
			displayHelp()
		elif argv[i] in ["-d", "--debug"]:
			setDebug()
		else:
			try:
				port = int(argv[i])
			except ValueError:
				displayHelp()
		i+=1

	if logfile:
		logToFile(logfile)

	info("Starting XBee %s" % VERSION)

	# setup serial
	serial = Serial()
	serial.port = '/dev/ttyAMA0'
	serial.baudrate = 9600
	serial.timeout = 1
	serial.writeTimeout = 1
	serial.open()

	# disregard any pending data in xbee buffer
	serial.flushInput()

	# force to show xbee boot menu
	time.sleep(.5)
	serial.writelines("\r")
	time.sleep(.5)

	# read menu
	while serial.inWaiting() > 0:
		debug("%s" % serial.readline())

	# trigger bypass automatically
	serial.writelines("B")

	# post startup message to other XBee's and at stdout
	#serial.writelines("RPi #1 is up and running.\r\n")
	info("RPi #1 is up and running.")

	try:
		while True:
			waitToSend = True

			# read a line from XBee and convert it from b'xxx\r\n' to xxx and send to webiopi
			while serial.inWaiting() > 0:
				try:
					line = serial.readline().decode('utf-8').strip('\n\r')
					if line:
						waitToSend = False
						debug("Received: %s" % line)
						try:
							client = PiHttpClient("127.0.0.1")
							macro = Macro(client, "setCarInfo")
							macro.call(line.replace(",", "%2C"))
						except:
							exception("setting car info failed!")

				except KeyboardInterrupt:
					raise
				except Exception as e:
					exception(e)
					time.sleep(1.)

			try:
				time.sleep(1.)

				client = PiHttpClient("127.0.0.1")
				macro = Macro(client, "getPitInfo")
				data = macro.call()
				if data:
					debug("Sending: %s" % data)
					serial.writelines(data + "\n")

			except KeyboardInterrupt:
				raise
			except Exception as e:
				exception(e)
				time.sleep(1.)

	except KeyboardInterrupt:
		info("*** Ctrl-C keyboard interrupt ***")
PORT = argv[1]
UNIT = int(argv[2])
FC = int(argv[3])
ADD = int(argv[4])
LEN = int(argv[5])
lLEN = LEN & 0x00FF
mLEN = LEN >> 8
if (FC < 3):
    BYT = (lambda x: x / 8
           if (x % 8 == 0) else x / 8 + 1)(LEN)  #Round off the no. of bytes
else:
    BYT = LEN * 2
lADD = ADD & 0x00FF
mADD = (ADD & 0xFF00) >> 8
s = Serial('/dev/' + PORT, timeout=0.5)
s.baudrate = 9600
s.parity = "E"
s.databits = 8
s.stopbits = 1
s.handshake = "none"
s.datatype = "raw"
cmd = array('B', [UNIT, FC, mADD, lADD, mLEN, lLEN])
cmd.extend(CRC(cmd))
#lcrc = crc & 0x00FF
#mcrc = (crc & 0xFF00)>>8
#cmd = array('B', [UNIT,FC,mADD,lADD,mLEN,lLEN,lcrc,mcrc])
while 1:
    s.write(cmd)
    print cmd
    sleep(1)
    read = s.read(255)
Example #38
0
    minutes = seconds // 60
    seconds %= 60
    goal = current + timedelta(hours=hours, minutes=minutes, seconds=seconds)

if not sameday and current.day == goal.day:
    goal += timedelta(hours=24)
    hours += 24

print("Alarm Set To:", goal)
print("Which is in...")
print(hours // 24, "days,")
print(hours % 24, "hours,")
print(minutes, "minutes,")
print(seconds, "seconds")

half_days = hours // 12
hours %= 12

seconds = (seconds << 2) | 1
minutes = (minutes << 2) | 2
hours = (hours << 4) | 8
half_days = (half_days << 5) | 16

ser = Serial()
ser.port = port
ser.baudrate = baud
ser.setDTR(False)
ser.open()
ser.write(bytes([seconds, minutes, hours, half_days, 128]))
ser.close()
Example #39
0
import struct
import time
from serial import Serial

ser = Serial()
ser.port = 'COM8'
ser.baudrate = 115200
ser.timeout = 0.5
ser.dtr = 0
ser.open()
print("Is Serial Port Open:", ser.isOpen())

var = struct.pack('<BBHHHHHHHdddHHdddHHdHHH', 69,7,1,60,120,250,150,10,200,3.5,2,2.4,5,200,2.5,1.9,2.4,10,8,2,20,120,0)  # B for unsigned char, takes an int
                                                                                                                                # d for double, takes a float
                                                                                                                                # < for little-endian, as programmed on FRDM board thru Simulink
print("To send (in binary): ", var)
print("Size of string representation is {}.".format(struct.calcsize('<BBB')))
#print("To send (in decimal): ", struct.unpack('<BBB',var))
#var = struct.unpack('<BBB',var)
print("send1",ser.write(var))   


#time.sleep(1)
var = struct.pack('<BBHHHHHHHdddHHdddHHdHHH', 69,21,1,60,120,250,150,10,200,3.5,2,2.4,5,200,2.5,1.9,2.4,10,8,2,20,120,0)
ser.write(var)
#time.sleep(1)
print("reading...")
values = ser.read(100)
print(values)

print("Done")
Example #40
0
    def run(self, args):
        self.discover()
        port = args.serial_port or self.e.guess_serial_port()
        board = self.e.board_model(args.board_model)

        protocol = board["upload"]["protocol"]
        if protocol == "stk500":
            # if v1 is not specifid explicitly avrdude will
            # try v2 first and fail
            protocol = "stk500v1"

        if not os.path.exists(port):
            raise Abort("%s doesn't exist. Is Arduino connected?" % port)

        # send a hangup signal when the last process closes the tty
        file_switch = "-f" if platform.system() == "Darwin" else "-F"
        ret = subprocess.call([self.e["stty"], file_switch, port, "hupcl"])
        if ret:
            raise Abort("stty failed")

        # pulse on DTR
        try:
            s = Serial(port, 115200)
        except SerialException as e:
            raise Abort(str(e))
        s.setDTR(False)
        sleep(0.1)
        s.setDTR(True)
        s.close()

        # Need to do a little dance for Leonardo and derivatives:
        # open then close the port at the magic baudrate (usually 1200 bps) first
        # to signal to the sketch that it should reset into bootloader. after doing
        # this wait a moment for the bootloader to enumerate. On Windows, also must
        # deal with the fact that the COM port number changes from bootloader to
        # sketch.
        if board["bootloader"]["path"] == "caterina":
            caterina_port = None
            before = self.e.list_serial_ports()
            if port in before:
                # The reset code was only working intermittently...
                # This is very kludgy, but works to force a reset by
                # opening and closing the port repeatedly at 1200 baud
                # until an exception is caught
                ser = Serial()
                ser.port = port
                ser.baudrate = 1200

                reset_attempts_remaining = 10
                while reset_attempts_remaining > 0:
                    reset_attempts_remaining -= 1
                    try:
                        ser.open()
                        ser.close()
                        sleep(0.3)
                    except:
                        # Exception means reset is in progress
                        attemptsRemaining = 0
                    else:
                        if reset_attempts_remaining == 0:
                            print "Could not force reset"

                # Scanning for available ports seems to open the port or
                # otherwise assert DTR, which would cancel the WDT reset if
                # it happened within 250 ms. So we wait until the reset should
                # have already occured before we start scanning.
                if platform.system() != "Darwin":
                    sleep(0.3)

            elapsed = 0
            enum_delay = 0.25
            while elapsed < 10:
                now = self.e.list_serial_ports()
                diff = list(set(now) - set(before))
                if diff:
                    caterina_port = diff[0]
                    break

                before = now
                sleep(enum_delay)
                elapsed += enum_delay

            if caterina_port == None:
                raise Abort(
                    "Couldn’t find a Leonardo on the selected port. "
                    "Check that you have the correct port selected. "
                    "If it is correct, try pressing the board's reset "
                    "button after initiating the upload."
                )

            port = caterina_port

        # call avrdude to upload .hex
        subprocess.call(
            [
                self.e["avrdude"],
                "-C",
                self.e["avrdude.conf"],
                "-p",
                board["build"]["mcu"],
                "-P",
                port,
                "-c",
                protocol,
                "-b",
                board["upload"]["speed"],
                "-D",
                "-U",
                "flash:w:%s:i" % self.e["hex_path"],
            ]
        )
import numpy as np

image = cv2.imread("tornado.jpg",0)
#image= np.array(ima,dtype = )
print(image.dtype)
rows,cols = image.shape

print(rows)
print(cols)
print(image)

image.flatten()
print(len(image))

serialPort = Serial("/dev/ttyUSB0", timeout=10)
serialPort.baudrate=input("Enter Baudrate :")
if (serialPort.isOpen() == False):
    serialPort.open()

outStr = ''
inStr = ''

serialPort.flushInput()
serialPort.flushOutput()

#for i, a in enumerate(range(33, 126)):
# outStr += chr(a)
#outStr=input("Enter data to be transmitted: ")
#outStr=outStr.encode()
serialPort.setRTS(1)
Example #42
0
File: upload.py Project: smil2k/ino
    def run(self, args):
        self.discover()
        board = self.e.board_model(args.board_model)

        protocol = board['upload']['protocol']
        serialProgrammer = protocol != 'dapa'

        if protocol == 'stk500':
            # if v1 is not specifid explicitly avrdude will
            # try v2 first and fail
            protocol = 'stk500v1'

	if serialProgrammer:
            port = args.serial_port or self.e.guess_serial_port()
	else:
	    port = args.serial_port or self.e.guess_par_port()

        if not os.path.exists(port):
            raise Abort("%s doesn't exist. Is Arduino connected?" % port)

	if serialProgrammer:
            # send a hangup signal when the last process closes the tty
            file_switch = '-f' if platform.system() == 'Darwin' else '-F'
            ret = subprocess.call([self.e['stty'], file_switch, port, 'hupcl'])
            if ret:
                raise Abort("stty failed")
            # pulse on DTR
            try:
               s = Serial(port, 115200)
            except SerialException as e:
               raise Abort(str(e))
 
            s.setDTR(False)
            sleep(0.1)
            s.setDTR(True)
            s.close()

        # Need to do a little dance for Leonardo and derivatives:
        # open then close the port at the magic baudrate (usually 1200 bps) first
        # to signal to the sketch that it should reset into bootloader. after doing
        # this wait a moment for the bootloader to enumerate. On Windows, also must
        # deal with the fact that the COM port number changes from bootloader to
        # sketch.
        if board['bootloader']['path'] == "caterina":
            caterina_port = None
            before = self.e.list_serial_ports()
            if port in before:
                ser = Serial()
                ser.port = port
                ser.baudrate = 1200
                ser.open()
                ser.close()

                # Scanning for available ports seems to open the port or
                # otherwise assert DTR, which would cancel the WDT reset if
                # it happened within 250 ms. So we wait until the reset should
                # have already occured before we start scanning.
                if platform.system() != 'Darwin':
                    sleep(0.3)

            elapsed = 0
            enum_delay = 0.25
            while elapsed < 10:
                now = self.e.list_serial_ports()
                diff = list(set(now) - set(before))
                if diff:
                    caterina_port = diff[0]
                    break

                before = now
                sleep(enum_delay)
                elapsed += enum_delay

            if caterina_port == None:
                raise Abort("Couldn’t find a Leonardo on the selected port. "
                            "Check that you have the correct port selected. "
                            "If it is correct, try pressing the board's reset "
                            "button after initiating the upload.")

            port = caterina_port


        processArgs=[
            self.e['avrdude'],
            '-C', self.e['avrdude.conf'],
            '-p', board['build']['mcu'],
            '-P', port,
            '-c', protocol,
            '-U', 'flash:w:%s:i' % self.e['hex_path'],]

        if serialProgrammer:
            processargs.append('-D')
            if 'speed' in board['upload']:
                processArgs.extend(['-b', board['upload']['speed']])
        else:
            if 'speed' in board['upload']:
                processArgs.extend(['-i', board['upload']['speed']])

        # call avrdude to upload .hex
        subprocess.call( processArgs )
def main():
    args = parse_arguments()

    images = scan_for_images(args.folder)
    if len(images) == 0:
        print('Error: found no jpeg images in "%s".' % args.folder)
        sys.exit(1)
    print('Found %d images.' % len(images))

    serial = Serial(args.port)
    serial.baudrate = args.baudrate
    print('Opened serial port %s.' % serial.name)
    
    print('Interval between pictures is %d seconds.' % args.interval)

    width = 0
    height = 0

    # display random pictures
    while True:
        time.sleep(args.interval)

        if width == 0:
            # connect to the Arduino and obtain screen size
            serial.write('C')
            width = int(serial.readline())
            height = int(serial.readline())
            print('Display is %dx%d.' % (width, height))

        image = random.choice(images)
        print('Uploading "%s"...' % image)
        upload_image(image, serial, (width, height))