示例#1
0
def main():

    args = validateInput()
    serial = initSerial(args['SerialPort'], args['BaudRate'])
    freq = int(struct.unpack('h', serial.read(2))[0])
    scriptTime = int(freq * args['ExecTime'])

    timeCounter = 0
    while (timeCounter <= scriptTime or scriptTime == 0):
        timeCounter += 1
        try:
            dataLen = int(struct.unpack('B', serial.read(1))[0])
            rawData = serial.read(dataLen)
            data = struct.unpack(STRUCT_DATA, rawData)
            # Arquivo de log
            dataFile = open(args['FileName'], 'a')
            dataFileBin = open(args['FileName'] + 'bin', 'ab')
            dataFile.write(
                str(data[0]) + "\t" + str(data[1]) + "\t" + str(data[2]) +
                "\n")
            dataFileBin.write(rawData)
            dataFile.close()
            dataFileBin.close()

        except KeyboardInterrupt:
            break

    serial.close()
示例#2
0
def start_bootloader():
    '''Starts bootloader
		:returns:
			True if bootloader mode entered, False if failed
	'''
    print("start")
    C = [0x55, 0x55, ord('J'), ord('I'), 0x00]
    crc = calc_crc(
        C[2:4] +
        [0x00])  # for some reason must add a payload byte to get correct CRC
    crc_msb = (crc & 0xFF00) >> 8
    crc_lsb = (crc & 0x00FF)
    C.insert(len(C), crc_msb)
    C.insert(len(C), crc_lsb)
    serial.write(C)
    print(C)
    time.sleep(2)  # must wait for boot loader to be ready
    R = serial.read(5)
    print(R)
    if R[0] == 85 and R[1] == 85:
        #packet_type =  '{0:1c}'.format(R[2]) + '{0:1c}'.format(R[3])
        packet_type = R[2] + R[3]
        if packet_type == 'JI':
            serial.read(R[4] + 2)
            print('bootloader ready')
            time.sleep(2)
            if boot_mode == 0:
                print('resync with device')
                time.sleep(2)
            return True
        else:
            return False
    else:
        return False
def send_command(serial,
                 command,
                 human,
                 expected_response=None,
                 crlf=True,
                 waittime=1000):
    '''Sends a command to the device.'''

    # flush the read buffer
    serial.read(serial.inWaiting())

    print human
    print "<<< " + command
    serial.write(command)
    if crlf:
        serial.write("\r\n")

    time.sleep(waittime / 1000)

    if expected_response:
        n = max([serial.inWaiting(), len(expected_response)])
        #print n
        data = serial.read(n)
        #print data
        if expected_response in data:
            print ">>> OK"
        else:
            print "<<< " + command
            print ">>> ERROR: " + data
示例#4
0
def find_packet(serial):
    if hex(ord(serial.read())) == START_IOPACKET:
        lengthMSB = ord(serial.read())
        lengthLSB = ord(serial.read())
        length = (lengthLSB + (lengthMSB << 8)) + 1
        return serial.read(length)
    else:
        return None
def read_response(serial):
    hdr_len = 3
    header = np.frombuffer(serial.read(hdr_len), dtype=np.uint8)

    pl_len = header[-1]
    payload = np.frombuffer(serial.read(pl_len), dtype=np.uint8)

    response = np.concatenate((header, payload))

    print response
示例#6
0
def receive_frame (serial):
    raw_data = b''
    raw_byte = serial.read ()
    if raw_byte == STX:
        while raw_byte:
            raw_data += raw_byte
            raw_byte = serial.read ()
    else:
        raw_data += raw_byte
    return raw_data
示例#7
0
 def write(self, data, half_duplex=None):
     if half_duplex is None:
         half_duplex = self.half_duplex
     serial = self.serial
     data = self.encode(data)
     cnt = serial.write(data)
     serial.flush()
     if half_duplex:
         # Clean RX buffer in case of half duplex
         #   All written data is read into RX buffer
         serial.read(cnt)
示例#8
0
def getPosition(serial, device, channel):
    """ Accesses the position of a channel using the pololu protocol.
    SERIAL is the serial device the maestro is attached to.
    DEVICE is the maestro device number. (default 12)
    CHANNEL is the channel to sample.

    When the channel is an analog channel, it reports a value [0...1023].
    """
    serial.write(chr(0xAA))
    serial.write(chr(device))
    serial.write(chr(0x10))
    serial.write(chr(channel))
    return ord(serial.read(1)) + 256 * ord(serial.read(1))
def get_position(serial, channel, device=12):
    """ Accesses the position of a channel using the pololu protocol.
    SERIAL is the serial device the maestro is attached to.
    DEVICE is the maestro device number. (default 12)
    CHANNEL is the channel to sample.

    When the channel is an analog channel, it reports a value [0...1023].
    """
    serial.write(chr(0xAA))
    serial.write(chr(device))
    serial.write(chr(0x10))
    serial.write(chr(channel))
    return ord(serial.read(1)) + (ord(serial.read(1)) << 8)
示例#10
0
 def recv(self, serial):
     buffer = ''
     aux = ''
     while len(str(aux.encode('hex'))) == 0:
         aux = serial.read()
     while len(str(aux.encode('hex'))) > 0:
         buffer += aux
         aux = serial.read()
     serial.flushInput()
     print "    ENCODED: %s" % buffer
     buffer = b64decode(buffer)
     print "    ENCRYPTED: %s" % buffer.encode('hex')
     return buffer
示例#11
0
	def recv(self,serial):
		buffer = ''
		aux = ''
		while len(str(aux.encode('hex'))) == 0:
			aux = serial.read()
		while len(str(aux.encode('hex'))) > 0:
			buffer += aux
			aux = serial.read()
		serial.flushInput()
		print "    ENCODED: %s" % buffer
		buffer = b64decode ( buffer )
		print "    ENCRYPTED: %s" % buffer.encode('hex')
		return buffer
示例#12
0
  def read_from(self, serial):
    self.cmd.extend(serial.read(3))

    if self.cmd[_IDX_STX] != _STX:
      raise MalformedCommand(_IDX_STX, _STX, self.cmd[_IDX_STX])

    # the length includes prelude and appendix, which are six bytes total.
    if self.length > 6:
      self.cmd.extend(serial.read(self.length - 6))

    self.cmd.extend(serial.read(3))

    if self.cmd[_IDX_ETX] != _ETX:
      raise MalformedCommand(_IDX_ETX, _ETX, self.cmd[_IDX_ETX])
示例#13
0
	def xmodem_send(self, serial, file):
		length = len(file.read()) / 128
		file.seek(0, 0)
		i = 1
		t, anim = 0, '|/-\\'
		serial.setTimeout(1)
		while 1:
			if serial.read(1) != NAK:
				t = t + 1
				print anim[t%len(anim)],'\r',
				if t == 60 : return False
			else:
				break

		p = 1
		s = file.read(128)
		while s:
			s = s + '\xFF'*(128 - len(s))
			chk = 0
			for c in s:
				chk+=ord(c)
			while 1:
				serial.write(SOH)
				serial.write(chr(p))
				serial.write(chr(255 - p))
				serial.write(s)
				serial.write(chr(chk%256))
				serial.flush()

				answer = serial.read(1)
				if  answer == NAK: continue
				if  answer == ACK: break
				return False
			s = file.read(128)
			p = (p + 1)%256
			
			# update progressbar
			progress = (100*i) / float(length)
			self.p["value"] = progress
			self.label2["text"] = str(round(progress, 2))+'%'
			self.win.update_idletasks()
			i += 1
			
		serial.write(EOT)
		if progress == 100:
			self.win.destroy()
			return True
		else:
			return False
示例#14
0
 def avarage(self, event):
     prom = 0x01
     dlg = wx.TextEntryDialog(self, 'Cual es el Promedio?:',
                              'PROMEDIO')  # you display a dialog entry
     dlg.SetValue("0")
     if dlg.ShowModal() == wx.ID_OK:
         promedio = int(dlg.GetValue())
         print "PROMEDIO %i" % promedio
     dlg.Destroy()
     serial = serial_x(commNumber)
     serial.write('P')
     serial.write(promedio)
     print(serial.read(2))
     prom = serial.read(1)
     print prom
示例#15
0
def send_data(data, read_byte):  ##  sending data to herkulex Servo
    length = len(data) + 5
    data.insert(0, length)
    csm1 = checksum1(data)
    csm2 = checksum2(csm1)
    data.insert(0, 0xFF)
    data.insert(1, 0xFF)
    data.insert(5, csm1)
    data.insert(6, csm2)
    #print data

    stringtosend = ""
    for i in range(len(data)):
        byteformat = '%02X' % data[i]
        stringtosend = stringtosend + "\\x" + byteformat

    try:

        serial.write(stringtosend.decode('string-escape'))
        t = 13
        if (read_byte != 0):  ##reading data from servo ACK
            rxdata = serial.read(t)

        return rxdata
    except:
        return -1
示例#16
0
def readSensor(serial): 
    try:
        # request data   21 
        serial.flushInput()
        serial.write('90 232'.encode('utf8'))
        serial.write('90 223'.encode('utf8'))
        serial.write('90 203'.encode('utf8'))
        #print(ser.out_waiting)
        msg_b = serial.read(8)
        encoded = str(base64.b16encode(msg_b))
        encoded = encoded.replace("b'","")
        encoded = encoded.replace("'","")
        B = read_hex(encoded)
        #print(B)
        return B

    except (Exception,KeyboardInterrupt) as e:
        print('sensor communication broke down')
        print(str(e))
        serial.flushInput()
        time.sleep(0.2)
        serial.flushOutput()
        time.sleep(0.2)
        
        serial.close() # Only executes once the loop exits
        sys.exit()
示例#17
0
def read_from_port(serial):
    alldata = ""
    dlen = 0
    while stopFlag:
        data = serial.read(256)
        if len(data) != 0:
            alldata = alldata + data

        if (dlen > 0) and (len(alldata) > 0):
            print alldata[0]
            alldata = alldata[1:]
            dlen = dlen - 1

        elif (len(alldata) > 2):
            if alldata[0] == '\xAB' and alldata[1] == '\xAD':
                dlen = ord(alldata[2])
                if dlen <= (len(alldata) - 3):
                    print "receive data:" + alldata[3:3 + dlen]
                    dlen = 0
                    alldata = alldata[3 + dlen:]
                else:
                    dlen -= (len(alldata) - 3)
                    print "receive data:" + alldata[3:]
                    alldata = ""
            elif alldata[0] == '\xAB' and alldata[1] == '\xA5':
                print "send data success len:" + str(ord(alldata[2]))
                #skip 3 bytes
                alldata = alldata[3:]
            else:
                #skip one byte and continue
                alldata = alldata[1:]
示例#18
0
def Main(args):
    global port
    if len(args) != 2:
        print("Invalid input arguments")
        return 1

    serial.port = args[1]
    serial.baudrate = 115200
    serial.timeout = 3
    serial.open()

    input("Press enter to send data...")
    
    nCmdsGood = 0

    print("Starting upload on " + args[1] + "...")
    while True:
        cmd = bytes([ (0x80 if ((nCmdsGood % 5) == 0) else 0) | (0x01 if ((nCmdsGood % 3) == 0) else 0), 0 ])
        serial.write(cmd)
        resp = serial.read(len(cmd))
        if len(resp) > 0:
            if resp == cmd:
                nCmdsGood += 1
            print(resp)
        else:
            print("Waited too long.")
            break

    input("Press enter to close serial port...")

    serial.close()
    print("Done!")
示例#19
0
def read_speed(motor_num):
	if (motor_num == 1):
		board_num = 0x80
		command = 30
		serial = ser_x80
	elif (motor_num == 2):
		board_num = 0x81
		command = 30
		serial = ser_x81
	elif (motor_num == 3):
		board_num = 0x80
		command = 31  ## OK, this is seriously a major WTF here. I need to see if the board is wired wrong or something.
		serial = ser_x80
	data = []
	serial.write(chr(board_num))
	serial.write(chr(command)) 
	for i in range(6):
		data.append(serial.read())


	speed = (data[0].encode("hex")) + (data[1].encode("hex")) + (data[2].encode("hex")) + (data[3].encode("hex"))
	speed = int(speed, 16)
	if ((ord(data[4]) == 1) and (speed != 0)):
		speed = ~(0xffffffff - speed) + 1
	rotations_per_second = float(speed) * 125 / 8192 	
	return rotations_per_second
示例#20
0
def read_from_port(serial):
	while True:
		#print ("teste")
		dado=serial.read(64)
		if(len(dado)>0):
			p=":".join("{:02x}".format(ord(c)) for c in dado)
			print "rcv "+p
示例#21
0
def readsen177(serial):
	'''
	Read data from SEN0177 by serial port and return list of all measured values
	'''
	try:
		dane=serial.read(32)
		#concentration of PM1.0, ug/m3
		PM1=readbit(dane,4)
		#concentration of PM2.5, ug/m3
		PM25=readbit(dane,6)
		#concentration of PM10.0, ug/m3
		PM10=readbit(dane,8)

		#the number of particulate of diameter above 0.3um in 0.1 liters of air
		bin1=readbit(dane,16)
		#the number of particulate of diameter above 0.5um in 0.1 liters of air
		bin2=readbit(dane,18)
		#the number of particulate of diameter above 1.0um in 0.1 liters of air
		bin3=readbit(dane,20)
		#the number of particulate of diameter above 2.5um in 0.1 liters of air
		bin4=readbit(dane,22)
		#the number of particulate of diameter above 5.0um in 0.1 liters of air
		bin5=readbit(dane,24)
		#the number of particulate of diameter above 10.0um in 0.1 liters of air
		bin6=readbit(dane,26)
                ser.flushInput()
                ser.flushOutput()
		return [PM1,PM25,PM10,bin1,bin2,bin3,bin4,bin5,bin6,int(checkval(dane)==readbit(dane,30))]

	except Exception as e:
		print ("PM data read error: {}".format(e))
		return 1
示例#22
0
    def openbci_id(self, serial):
        """

        When automatically detecting port, parse the serial return for the "OpenBCI" ID.

        """
        line = ''

        #
        # Wait for device to send data
        #
        # time.sleep(2)

        if serial.inWaiting():
            line = ''
            c = ''
            # Look for end sequence $$$
            while '$$$' not in line:
                c = serial.read().decode(
                    'utf-8', errors='replace'
                )  # we're supposed to get UTF8 text, but the board might behave otherwise
                line += c
            if "OpenBCI" in line:
                return True
        return False
示例#23
0
def read_reply(serial, count):
    if (verbose_mode):
        print("Waiting data...")
    r = serial.read(count)
    if (verbose_mode):
        print("Read: %d: %s" % (len(r),r))
    return r
示例#24
0
def readSerial(threadName, delay):
    s = ""
    while True:
        if serial.inWaiting() != 0:
            c = serial.read()

            if (c == 'U'):
                global relock
                relock = 1
            if (c == 'S' or c == 'I'):
                global sendPin
                sendPin = 1

            if (c == '\n'):
                print "[%7s] %s" % (threadName, s)
                #                if(s == "Enter Pin:"):
                #                    print "in sendpin"
                #                    global sendPin
                #                    sendPin = 1
                if (s == "Unlocked"):
                    print "In unlocked"
                    global relock
                    relock = 1
                s = ""
            else:
                s += c
        else:
            time.sleep(0.01)
示例#25
0
def dlt645_read_time(serial,addr,data_tag):
    #print 'dlt645_read_time ...'
    try:
        cmd2 = '\xfe\xfe\xfe\xfe' + encode_dlt645(addr,0x11,4,data_tag)
        serial.write(cmd2)
        time.sleep(0.5)
        resp = ''
        c = ''
        i = 0
        while c != '\x16' and i < SERIAL_TIMEOUT_CNT:
            c = serial.read(1)
            if len(c) > 0:
                resp += c
            else:
                print '.'
                i += 1
            
        if i >= SERIAL_TIMEOUT_CNT:
            return -1,0
            
        resp1 = dlt_645_rm_fe(resp)    
        ret,addr,data,ctl = decode_dlt645(resp1)
        #print data.encode('hex')
        # need to convert to Unix time stamp
        if ret == 0 and len(data) >= 7:
            list1 =  list(bcd2digits(data[4:7]))
            str1 = ''.join(str(e) for e in list1)
            return ret,str1
        else:
            return -1,0
    except:
        print 'dlt645_read_data exception!'
        return -1,0
示例#26
0
    def openbci_id(self, serial):
        """
        When automatically detecting port, parse the serial return for the "OpenBCI" ID.
        """
        line = ''
        # # Wait for device to send data
        # if self.openBCIFirmwareVersion == 'v1':
        #     serial.timeout = 1.0 #wait for 1 s for each character in read

        time.sleep(2)

        res = False

        if serial.inWaiting():
            line = ''
            c = ''
            # Look for end sequence $$$
            timeouted = False
            while ('$$$' not in line) and not timeouted:
                c = serial.read()
                if c == '':
                    timeouted = True
                line += c.decode('utf-8')
            if "OpenBCI" in line:
                res = True

        # if self.openBCIFirmwareVersion == 'v1':
        #     serial.timeout = self.timeout  # reset timeout to default
        return res
示例#27
0
 def recv(self, serial):
     #sleep(0.01)
     data = serial.read(100)
     # sleep(0.02)
     #
     # print(data)
     return data
def readSensor(serial): 
    try:
        # request data   21 
        serial.flushInput()
        string = "5A E8 5A DF 5A CB" #Long range - Fast mode - Start periodic readout
        
        cmd_bytes = bytearray.fromhex(string)
        
        ser.write(cmd_bytes)
        
        msg_b = serial.read(8)
        encoded = str(base64.b16encode(msg_b))
        encoded = encoded.replace("b'","")
        encoded = encoded.replace("'","")
        B = read_hex(encoded)
        #print(B)
        return B

    except KeyboardInterrupt:
        print("User interrupt encountered. Exiting...")
        time.sleep(3)
        serial.flushInput()
        serial.flushOutput()
        serial.close()
        sys.exit()
    except:
        # for all other kinds of error, but not specifying which one
        print("Device disconnected")
        time.sleep(3)
        serial.flushInput()
        serial.flushOutput()
        serial.close()
        sys.exit()
 def run(self):    # Main loop of thread
     try:
         while True:
             for device in self.devices:
                 serial = self.devices[device]["serial"]
                 ch = b''
                 data_from_device = b''
                 while ch != b'\n':
                     try:
                         try:
                             ch = serial.read(1)    # Reading data from serial
                         except AttributeError as e:
                             if serial is None:
                                 self.__connect_to_devices()    # if port not found - try to connect to it
                                 raise e
                         data_from_device = data_from_device + ch
                     except Exception as e:
                         log.exception(e)
                         continue
                 try:
                     converted_data = self.devices[device]['converter'].convert(self.devices[device]['device_config'], data_from_device)
                     self.__gateway.send_to_storage(self.get_name(), converted_data)
                     time.sleep(.1)
                 except Exception as e:
                     log.exception(e)
                     self.close()
                     raise e
             if not self.connected:
                 break
     except Exception as e:
         log.exception(e)
示例#30
0
    def reader(self, serial, color):
        """loop and copy serial->console"""
        first = True
        try:

            line = []

            while self.alive:
                data = serial.read(1)
                if not data:
                    continue

                # don't print a NULL if it's the first character we
                # read.  This hides startup/port-opening glitches with
                # some serial devices.
                if self.suppress_read_firstnull and first and data == "\0":
                    first = False
                    continue
                first = False

                if color != self.last_color:
                    self.last_color = color
                    sys.stdout.write(color)

                line.append(data)
                if data == "\r":
                    # if len(data) > 1:

                    if line != ["\r"]:
                        try:
                            msg = MkMsg.createFromData(line)
                            # if ((msg.command == 'o') or (msg.command == 'O')):
                            print time.strftime("%X") + str(msg)
                        except Exception, e:

                            print e, line
                    line = []
                    # sys.stdout.write("".join(line))
                    # sys.stdout.write("\n")

                # if (self.raw or
                #     (ord(data) >= 32 and ord(data) < 128) or
                #     data == '\r' or data == '\n' or data == '\t'):
                #     if self.add_cr and data == '\n':
                #         sys.stdout.write('\r' + data)
                #     else:
                #         sys.stdout.write(data)
                # else:
                #     sys.stdout.write('\\x'+("0"+hex(ord(data))[2:])[-2:])

                sys.stdout.flush()

        except Exception as e:
            sys.stdout.write(color)
            sys.stdout.flush()
            traceback.print_exc()
            sys.stdout.write(self.color.reset)
            sys.stdout.flush()
            self.console.cleanup()
            os._exit(1)
示例#31
0
def read_data(serial):
    '''
		Function for recieve data from serial port.
		Parameters
			serial		serial.Serial instance.
		Return
			list		list of int for data recieved. Empty list if not
						recieve any thing.
	'''
    if serial is None:
        return []
    PACKAGE = []
    try:
        if not serial.is_open:
            pass
            # rospy.logwarn("Serial port is not open.")
        elif serial.is_open:
            # print serial.inWaiting()
            while serial.inWaiting():
                PACKAGE.append(ord(serial.read()))
            if len(PACKAGE) > 0:
                # rospy.logdebug("RECIEVE<< "+str(PACKAGE))
                rospy.logdebug(str(len(PACKAGE)))
    except Exception as e:
        rospy.logerr("cannot recieve data from serial port" + str(e))
    finally:
        return PACKAGE
示例#32
0
    def getPacket(self, outputPacket):
        # Will halt while buffer is being used
        while (self.BufferUsed == True):
            sleep(2.0 / 1000)  # Wait 2Msec

        # Lock the buffer untill we are finished
        self.BufferUsed = True
        # We know we will always have a constant 2 bits of header
        softStorage = outputSerial.read(2)
        if softStorage[0] != 0x50 or softStorage[1] != 0xAF:
            NAKReply_Und.send(self.outputSerial)
            return False
            # We assume that the new two bits will be correct and we dont have to garbage collect

        # Another 3 bits of header info (cmd1, cmd2, length), not super important we keep the header
        softStorage = outputSerial.read(3)
        outputPacket.setCMD1(softStorage[0])
        outputPacket.setCMD2(softStorage[1])

        # Grab the next Length of data
        storageLength = softStorage[2]
        softStorage = serial.read(storageLength)
        for dataVar in softStorage:
            outputPacket.addData(dataVar)

        # Make sure to unlock the buffer so other programs can use it
        BufferUsed = False

        return True
示例#33
0
def serial_read():
	global port, serial, isDone, mainMenu, playing, gameOver, speed, char
	while not isDone:
		try:
			value = serial.read()
			if mainMenu:
				if value == 'y':
					char.lastHundred = int(char.distXTraveled/100)
					mainMenu = False
					playing = True
			if playing:
				if value == 'r':
					char.updateComm('right')
				if value == 'l':
					char.updateComm('left')	
				if value == 'j':
					char.updateComm('jump')
				if value == 'y':
					speed = min(max_speed, speed + 0.005)
				if value == 'n':
					speed = max(min_speed, speed - 0.001)
			print value

		except:
			continue
示例#34
0
def read_from_port(serial):
    alldata = ""
    dlen = 0
    while stopFlag:
        data = serial.read(256)
        if len(data) != 0:
            alldata = alldata + data

        if (dlen > 0) and (len(alldata) > 0):
            print alldata[0]
            alldata = alldata[1:]
            dlen = dlen - 1

        elif(len(alldata) > 2):
            if alldata[0] == '\xAB' and alldata[1] == '\xAD':
                dlen = ord(alldata[2])
                if dlen <= (len(alldata) - 3):
                    print "receive data:" + alldata[3:3+dlen]
                    dlen = 0
                    alldata = alldata[3+dlen:]
                else:
                    dlen -= (len(alldata) - 3)
                    print "receive data:" + alldata[3:]
                    alldata = ""
            elif alldata[0] == '\xAB' and alldata[1] == '\xA5':
                print "send data success len:" + str(ord(alldata[2]))
                #skip 3 bytes
                alldata = alldata[3:]
            else:
                #skip one byte and continue
                alldata = alldata[1:]
示例#35
0
def dlt645_get_addr(serial):
    #print 'dlt645_get_addr ...'
    try:
        #cmd2 = '\xfe\xfe\xfe\xfe\x68\xaa\xaa\xaa\xaa\xaa\xaa\x68\x13\x00\xdf\x16'
        cmd2 = '\xfe\xfe\xfe\xfe' + encode_dlt645('\xaa\xaa\xaa\xaa\xaa\xaa',0x13,0,'')

        serial.write(cmd2)
        time.sleep(0.5)
        resp = ''
        c = ''
        i = 0
        while c != '\x16' and i < SERIAL_TIMEOUT_CNT:
            c = serial.read(1)
            if len(c) > 0:
                resp += c
            else:
                print '.'
                i += 1
        
        if i >= SERIAL_TIMEOUT_CNT:
            return -1,0
        
        resp1 = dlt_645_rm_fe(resp)

        #print 'resp1:',resp1

        ret,addr,data,ctl = decode_dlt645(resp1)
        if ret == 0:
            return ret,addr
            
        
    except:
        print 'dlt645_get_addr exception!'
        return -1,''
示例#36
0
    def _send_and_wait_for_ack(self, packet, serial):
        ack = 0
        MAX_RETRIES = 1  # no more than 9

        while ack != 0x06 and int(chr(packet[4])) < MAX_RETRIES:
            serial.write(packet)
            ack = serial.read(1)

            # This violates the principle that we do high level
            # client-side and low level posbox-side but the retry
            # counter is always in a fixed position in the high level
            # message so it's safe to do it. Also it would be a pain
            # to have to throw this all the way back to js just so it
            # can increment the retry counter and then try again.
            packet[4] += 1

            if ack:
                ack = ord(ack)
            else:
                _logger.warning("did not get ACK, retrying...")
                ack = 0

        if ack == 0x06:
            return True
        else:
            _logger.error(
                "retried " + str(MAX_RETRIES) +
                " times without receiving ACK, is blackbox properly connected?"
            )
            return False
示例#37
0
def readSensor(serial):
    try:
        # request data   21
        serial.flushInput()
        string = "5A E8 5A DF 5A CB"  #Long range - Fast mode - Start periodic readout

        cmd_bytes = bytearray.fromhex(string)

        ser.write(cmd_bytes)

        msg_b = serial.read(8)
        encoded = str(base64.b16encode(msg_b))
        encoded = encoded.replace("b'", "")
        encoded = encoded.replace("'", "")
        B = read_hex(encoded)
        #print(B)
        return B

    except (Exception, KeyboardInterrupt) as e:
        print('sensor communication broke down')
        print(str(e))
        serial.flushInput()
        time.sleep(0.2)
        serial.flushOutput()
        time.sleep(0.2)

        serial.close()  # Only executes once the loop exits
        sys.exit()
示例#38
0
def write_block(buf, data_len, addr):
    '''Executed WA command to write a block of new app code into memory
	'''
    print(data_len, addr)
    C = [0x55, 0x55, ord('W'), ord('A'), data_len + 5]
    addr_3 = (addr & 0xFF000000) >> 24
    addr_2 = (addr & 0x00FF0000) >> 16
    addr_1 = (addr & 0x0000FF00) >> 8
    addr_0 = (addr & 0x000000FF)
    C.insert(len(C), addr_3)
    C.insert(len(C), addr_2)
    C.insert(len(C), addr_1)
    C.insert(len(C), addr_0)
    C.insert(len(C), data_len)
    for i in range(data_len):
        #C.insert(len(C), ord(buf[i]))
        C.insert(len(C), buf[i])
    crc = calc_crc(C[2:C[4] + 5])
    crc_msb = int((crc & 0xFF00) >> 8)
    crc_lsb = int((crc & 0x00FF))
    C.insert(len(C), crc_msb)
    C.insert(len(C), crc_lsb)
    status = 0
    while (status == 0):
        serial.write(C)
        test = []
        for ele in C:
            test.insert(len(test), hex(ele))
        #print test
        #print len(C)
        #print('percent: {:.2%}'.format(addr/fs_len))
        print("upload progress: %.3f%%" % (float(addr) / float(fs_len) * 100))
        if addr == 0:
            sleep(8)
        else:
            #sleep(0.01)
            sleep(0.01)
        R = serial.read(12)  #longer response
        #test = ord(R[0])
        status = 1
        #print R[2]
        #print R[3]
        if len(R) > 1 and (R[0]) == 85 and (R[1]) == 85:
            #packet_type =  '{0:1c}'.format(R[2]) + '{0:1c}'.format(R[3])
            #packet_type = R[2] + R[3]
            #print(packet_type)
            packet_type = '{0:1c}'.format(R[2]) + '{0:1c}'.format(R[3])
            if packet_type == 'WA':
                status = 1
            else:
                sys.exit()
                print('retry 1')
                status = 0
        else:
            print(len(R))
            print(R)
            #self.reset_buffer()
            sleep(1)
            print('no packet')
            sys.exit()
示例#39
0
def read_serial(serial, sensors):
    """
    TODO: Upgrade to a class
    :param serial:
    :param sensors:
    :return:
    """

    while True:

        # Read strings line by line
        # ser_bytes = ser.readline()
        # line = ser_bytes[0:len(ser_bytes) - 2].decode("ascii")
        # sensors = parse_serial_line(line)
        # print(f"\r {sensors}", end="")
        # ser.flushInput()

        # Read by bytes
        counter = serial.in_waiting  # count the number of bytes of the serial port
        bytes_to_read = 5
        if counter > bytes_to_read - 1:
            bytes_serial = serial.read(bytes_to_read)
            # ser.reset_input_buffer()  # reset buffer

            sensor_index, sensor_reading = read_sensor_package(bytes_serial)

            if sensor_index >= 0:
                if sensor_index not in sensors:
                    sensors[sensor_index] = SMA(2)
                if sensor_reading > 0:
                    sensors[sensor_index].append(sensor_reading)
示例#40
0
    def _send_and_wait_for_ack(self, packet, serial):
        ack = 0
        MAX_RETRIES = 1

        while ack != 0x06 and int(chr(packet[4])) < MAX_RETRIES:
            serial.write(packet)
            ack = serial.read(1)

            # This violates the principle that we do high level
            # client-side and low level posbox-side but the retry
            # counter is always in a fixed position in the high level
            # message so it's safe to do it. Also it would be a pain
            # to have to throw this all the way back to js just so it
            # can increment the retry counter and then try again.
            packet = packet[:4] + str(int(packet[4]) + 1) + packet[5:]

            if ack:
                ack = ord(ack)
            else:
                _logger.warning("did not get ACK, retrying...")
                ack = 0

        if ack == 0x06:
            return True
        else:
            _logger.error("retried " + str(MAX_RETRIES) + " times without receiving ACK, is blackbox properly connected?")
            return False
def read_float(serial):
    """
    helper function to read a float from the serial port
    """
    #convert from little endian(Razor) to big endian
    hex_array = reversed([chr(ord(serial.read(1))) for i in range(4)])
    hex_string = ''.join(hex_array)
    return struct.unpack('>f', hex_string)[0]
示例#42
0
文件: api.py 项目: jffng/007-digi-xlr
	def send(self, serial, response_length):
		serial.write(self.frame)
		try:
			if self.parameter:
				response = serial.read(response_length)
				response = binascii.hexlify(response)
				response = response[-4:-2]
				return responseType[response]
			else:
				response = serial.read(response_length)
				response = binascii.hexlify(response)
				status = response[-6:-4]
				data = response[-4:-2]
				data = int(data,16)
				return [ responseType[status], data ]
		except KeyError:
			return 'Invalid response from remote radio'
示例#43
0
def modem_terminal(serial,string,timeout):
	serial.flushInput()
	serial.write(string)
	while timeout>0:
		if serial.inWaiting()>0:
			sys.stdout.write(serial.read(serial.inWaiting()))
		time.sleep(0.001)
		timeout=timeout-1
	print ""
示例#44
0
def recv(serial):
	while True:
		data = serial.read(30)
		if data == '':
			continue
		else:
			break
		sleep(1)
	return data
示例#45
0
文件: api.py 项目: jffng/007-digi-xlr
	def send(self, serial, response_length):
		serial.write(self.frame)
		try:
			response = serial.read(response_length)
			response = binascii.hexlify(response)
			response = response[-4:-2]
			return responseType[response]
		except KeyError:
			return 'Invalid response from remote radio'
示例#46
0
 def setDH1():
     serial.write(b'\x41\x54\x44\x48\x31\x33\x41\x32\x30\x30\x0D\x0A')
     time.sleep(1)
     resp = ""
     while (serial.inWaiting() > 0):
         data = serial.read()
         resp += data
         if '\x4F\x4B\x0D' in resp:
                 print "Set DH to Router1"
                 break
示例#47
0
文件: api.py 项目: jffng/007-digi-xlr
	def send(self, serial, response_length):
		serial.write(self.frame)
		try:
			response = serial.read(response_length)
			response = binascii.hexlify(response)
			status = response[-8:-6]
			data = response[-6:-2]
			return [ responseType[status], data ]
		except KeyError:
			return 'Invalid response from remote radio'
示例#48
0
def _serial_write_and_read_HX(serial, value, read_len):
    retValue = [0 for x in range(read_len)]
    serial.write(value)

    time.sleep(0.2)
    for iIndex in range(read_len):
        tmp = serial.read(1)

        retValue[iIndex] = hex(ord(tmp))

    return retValue
def main():
    while True:
        text = raw_input("Enter text to send to Arduino ")
        if not text:
            continue

        arduino.write(text)
        print("Sent %s to arduino " % text)
        time.sleep(1)

        result = serial.read()
示例#50
0
 def exitCommandMode():
     serial.write(b'\x41\x54\x43\x4E\x0D\x0A')
     time.sleep(1)
     resp = ""
     while (serial.inWaiting() > 0):
         data = serial.read()
         resp += data
         if '\x4F\x4B\x0D' in resp:
                 print "Exit Command Mode"
                 break
     return 0
示例#51
0
def serial_read(num_bytes):
    if not hasattr(serial_read, "warned"):
        serial_read.warned = False
    data = serial.read(num_bytes)
    if len(data) != num_bytes:
        serial_read.warned = True
        print "*** Error reading Scorbot-ER III serial port"
        print "*** Is the cable plugged in and the control box powered on?"
    else:
        serial_read.warned = False
    return data
示例#52
0
 def setDL2():
     serial.write(b'\x41\x54\x44\x4C\x34\x30\x45\x38\x33\x33\x46\x31\x0D\x0A')
     time.sleep(1)
     resp = ""
     while (serial.inWaiting() > 0):
         data = serial.read()
         resp += data
         if '\x4F\x4B\x0D' in resp:
                 print "Set DL to Router2"
                 break
     return 0
示例#53
0
def readSerialPort():
    isOpen = serial.isOpen()
    if(isOpen) :
        print 'COM4 serial port is opened!'

    fmt = '!3h'
    while(1):
        header = ord(serial.read())
        if(header != 0x88 or header == -1):
            continue
        header = ord(serial.read())
        if(header != 0xAF or header == -1):
            continue
        header = ord(serial.read())
        if(header != 0x1C or header == -1):
            continue

        content = serial.read(29)
        roll,pitch,yaw = struct.unpack_from(fmt,content,18)

        print pitch / 100.0 , roll / 100.0,yaw / 10.0
示例#54
0
def lineFromSerial(serial):
    global serialBuffer
    serialBuffer = serialBuffer + serial.read(serial.inWaiting())
    if '\n' in serialBuffer:
        lines = serialBuffer.partition('\n') # returns 3-tuple with line, separator, rest
        if(lines[1] == ''):
            # separator not found, first element is incomplete line
            serialBuffer = lines[0]
            return None
        else:
            serialBuffer = lines[2]
            return lines[0]
示例#55
0
 def writeSetting():
     serial.write(b'\x41\x54\x57\x52\x0D\x0A')
     time.sleep(1)
     resp = ""
     while (serial.inWaiting() > 0):
         
         data = serial.read()
         resp += data
         if '\x4F\x4B\x0D' in resp:
                 print "Write Setting "
                 break
     return 0
示例#56
0
 def accesssCommandMode():
     print "in func"
     serial.write(b'\x2B\x2B\x2B')
     time.sleep(1)
     resp = ""
     while (serial.inWaiting() > 0):
         data = serial.read()
         resp += data
         if '\x4F\x4B\x0D' in resp:
                 print "In Command Mode"
                 break
     return 0
示例#57
0
def print_input(serial):
    code = 0
    state = 0
    crc = 0
    data_expected_length = 0
    data_received_length = 0
    data_buffer = bytes()

    while True:
        data = serial.read()

        if (state == 0):
            if (data == PACKET_HEADER1):
                state += 1
                print("got header1")
        elif (state == 1):
            if (data == PACKET_HEADER2):
                state += 1
                print("got header2")
            else:
                state = 0
        elif (state == 2):
            code = data
            crc ^= ord(data)
            state += 1
        elif (state == 3):
            data_expected_length = ord(data)
            crc ^= ord(data)
            state += 1
        elif (state == 4):
            data_expected_length |= (ord(data) << 8)
            crc ^= ord(data)
            state += 1
            print("data length: {}".format(data_expected_length))
        elif (state == 5):
            data_buffer += data
            crc ^= ord(data)
            data_received_length += 1
            if (data_received_length >= data_expected_length):
                state += 1
        elif (state == 6):
            if (bytes([crc]) == data):
                print("crc correct!")
                update_imu_data(struct.unpack("< ffffff", data_buffer))
            else:
                print("calc crc: {}".format(bytes([crc])))
                print("got crc: {}".format(data))
                print("crc bad!")
            state = 0
            crc = 0
            data_expected_length = 0
            data_received_length = 0
            data_buffer = bytes()
def readSerial(threadName, delay):
    s = ""
    while not Quit:
        if serial.inWaiting() != 0:
            c = serial.read()
            if (c == '\n'):
                print "[%7s] %s" % (threadName, s)
                s =""
            else:
                s += c
        else:
            time.sleep(0.01)