def openbci_id(self, serial): 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') line += c if "OpenBCI" in line: return True 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
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 ""
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 ""
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)
def getGPS(): out = '' ynDATA = False dataE1, dataE2, dataE3, dataE4 = 0, 0, 0, 0 dataN1, dataN2, dataN3, dataN4 = 0, 0, 0, 0 try: while (serial.inWaiting()): out = str(serial.readline().decode('utf-8')) except: pass if out != '': gpsdata = out.split(",") print(out) if (gpsdata[0] == "$GPGGA"): dataE = gpsdata[4] dataN = gpsdata[2] if (len(dataE) >= 10): dataE1, dataE2, dataE3, dataE4 = dataE[:3], dataE[3:5], dataE[ 6:8], dataE[8:10] ynDATA = True if (len(dataN) >= 9): dataN1, dataN2, dataN3, dataN4 = dataN[:2], dataN[2:4], dataN[ 5:7], dataN[7:9] gpsE = "E {}-{}-{}-{}".format(dataE1, dataE2, dataE3, dataE4) gpsN = "N {}-{}-{}-{}".format(dataN1, dataN2, dataN3, dataN4) print(gpsE, gpsN) return ynDATA, gpsE, gpsN
def getGPS(): out = '' ynDATA = False dataE1, dataE2 = 0.0, 0.0 dataN1, dataN2 = 0.0, 0.0 gpsE, gpsN = 0.0, 0.0 str_gpsE, str_gpsN = "", "" try: while (serial.inWaiting()): out = str(serial.readline().decode('utf-8')) except: pass if out != '': gpsdata = out.split(",") #print(out) if (gpsdata[0] == "$GPRMC"): dataE = gpsdata[5] dataN = gpsdata[3] if (len(dataE) >= 10): dataE1, dataE2 = float(dataE[:3]), float(dataE[3:]) gpsE = round(dataE1 + dataE2 / 60, 4) ynDATA = True if (len(dataN) >= 9): dataN1, dataN2 = float(dataN[:2]), float(dataN[2:]) gpsN = round(dataN1 + dataN2 / 60, 4) str_gpsE = str(gpsE) str_gpsN = str(gpsN) #print(gpsE, gpsN) return ynDATA, str_gpsE, str_gpsN
def receiveresponse(): response = bytearray() bytes = bytearray(4) while serial.inWaiting() > 0: readinto(bytes) response.append(fromjura(bytes)) return response
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
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
def readBytes(self, count: object, array: object = False, write: object = False, filename: object = ""): serial = self._serialGet( ) # получить данные из COMPORT в данный момент i = 0 writeFile = "" while i < count + 18: if i <= 18: myData = serial.readline() i += 1 continue if (serial.inWaiting() > 0): print(serial.readline()) myData = serial.readline().decode("utf-8") if len(myData) < 5: continue print([myData, self.getTupleValues(myData)][array]) writeFile += myData i += 1 if write: self.serialWrite(filename, writeFile)
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
def cmdx(serial, command, timeout=2, retry=2): ''' send command to zigbee router and wait for response serial : serial device command : command line timeout : wait time return : the response list from zigbee router ''' ret = [] ind = 0 # if time out and can't receive data, the retry while ind < retry: ind += 1 serial.write(command) n = 0 # wait for a while and record all the response while n < timeout*1: time.sleep(0.01) n += 1 count = serial.inWaiting() if count > 0: recv = ser.read(count) ser.flushInput() ret.append(recv) if len(ret) > 0: break return ret
def ReadEEprom(serial, cnt=0): global Conf if cnt > 3: return None cnt += 1 # TO DO: add interval for average by sensor serial.write(bytes("e")) # require eeprom info sleep(2) serial.write(bytes("e")) # Spec advises 2 X e nr = 0 eeprom = { 'sn': '0' } while serial.inWaiting(): if nr > 25: break nr += 1 try: line = serial.readline() line = str(line.strip().decode('ascii')) if '=' in line: line = line.split('=') eeprom[line[0].lower().strip()] = line[1].lower().strip() elif ', ' in line: line = line[0].split(',') if len(line) == 11: # len(Conf['dataFlds']) measurement data try: eeprom['gas'] = Conf['fields'][Conf['serials'].index( line[0])] eeprom['sn'] = line[0] eeprom['serial_number'] = line[0] except: pass continue except: break sleep(0.5) sleep(0.5) while serial.inWaiting(): serial.readline() # empty remaining input sleep(0.5) if (not len(eeprom)) or (not 'gas' in eeprom.keys()): return ReadEEprom(serial, cnt=cnt) if Conf['debug']: for key in eeprom.keys(): MyLogger.log( modulename, 'INFO', 'Spec sensor eeprom %s: %s' % (key, eeprom[key].upper())) return eeprom
def soft_reset(self): serial = self.board.serial serial.write(COMMAND_CTRL_C) time.sleep(0.1) serial.write(COMMAND_CTRL_C) n = serial.inWaiting() while n > 0: serial.read(n) n = serial.inWaiting() time.sleep(0.1) serial.write(COMMAND_CTRL_D) data = self.board.read_until(1, b'soft reboot\r\n') if not data.endswith(b'soft reboot\r\n'): raise BoardException('could not soft_reset')
def recv(serial): while True: count = serial.inWaiting() if count != 0: data = serial.read(count) serial.flushInput() sleep(0.1) return data
def main(): parser = argparse.ArgumentParser(description='HTTP Server') parser.add_argument('port', type=int, help='Listening port for HTTP Server') parser.add_argument('ip', help='HTTP Server IP') args = parser.parse_args() server = HTTPServer((args.ip, args.port), HTTPRequestHandler) print('HTTP Server Running...........') # server.serve_forever() threading.Thread(target=server.serve_forever).start() loop = asyncio.get_event_loop() # sim = sim_vehicle() loop.run_until_complete(get_pose()) pp = [] for i in range(10): pp.append([i, i * 2]) sim.add_path(pp) print(sim.get_path()) #28H 测距定位使能:0:不测距 1 单次测量 2 持续测量 3 单 次自动输出 4 持续自动输出 # client = ModbusClient(method='rtu', port='COM1', timeout=1, baudrate=115200) # client.connect() # client.write_register(0x28, 2) serial = serial.Serial("COM3", 115200) serial.open() serial.write( [0x01, 0x10, 0x00, 0x28, 0x00, 0x01, 0x02, 0x00, 0x02, 0x21, 0xB9]) n = serial.inWaiting() time.sleep(0.1) serial.read(n) while True: #0x2C标签X坐标,0x2D Y坐标 # request = client.read_input_registers(0x2C, 2) # request = client.read_holding_registers(0x2C, 2) n2 = serial.inWaiting() serial.write([0x01, 0x03, 0x00, 0x2A, 0x00, 0x0D, 0xA5, 0xC7]) time.sleep(0.1) rec_data = serial.read(n2) rec_data[7:9] position[0] = request.registers[0] position[1] = request.registers[1] print('positon: x {}, y{}'.format(positon[0], positon[1])) time.sleep(0.1)
def write_serial(self, command, *args, **kwargs): hex = self.COMMANDS[command] % kwargs if DEBUG: print 'writing to serialport: %s %s' % (command, hex) serial.write(Utilities.hex2chr(hex)) #time.sleep(2) if DEBUG: print 'waiting at serialport: %i' % serial.inWaiting()
def RX_data(serial): try: if serial.inWaiting() > 0: result = serial.read(1) RX = ord(result) return RX except: attempts = attempts + 1 print("Serial Not Open ", attempts) return 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
def rpi2_usart_recv(serial,lenght): buffers = '' while True: FIFO_len = serial.inWaiting() # print "Waiting data:",FIFO_len if lenght <= FIFO_len: buffers = serial.read(FIFO_len) # serial.flushInput() break return buffers
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
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
def inner(self): try: if not serial.isOpen(): if not serial.open(): # self.error.emit("can't not open %s,error code:%d"%(serial.portName(),serial.error())) return if serial.inWaiting() == 0: return data = bytes() requestData = bytes() # print('wait:',serial.in_waiting) requestData = serial.read(serial.inWaiting()) hexData = ' '.join('{:02x}'.format(x) for x in requestData) self.request.emit(hexData) # else: # self.timeout.emit("Wait read ready timeout %s"%(QTime.currentTime().toString())) except TypeError as e: print('Got Error', e)
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]
def readSerial(threadName, delay): s = "" while True: if serial.inWaiting() != 0: c = serial.read() if (c == '\n'): print "[%7s] %s" % (threadName, s) s = "" else: s += c else: time.sleep(0.01)
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)
def recv(serial): print('2') data = '' while serial.inWaiting() > 0: print(serial.inWaiting()) print('3') # data += str(serial.read(15)) # ok 要配合timeout 使用, 否则要传入已知 的 size # data += str(serial.readline()) # ok 要配合timeout 使用 # data += str(serial.readlines()) # ok 要配合timeout 使用 # data += str(serial.readall()) # ok 要配合timeout 使用 data += str(serial.read_all()) # ok 要配合timeout 使用 print("************************************") #print(serial.read(13)) print('准备打印data') # data = str(serial.read(19)) print(data) print('data:%s' % data) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") return data
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
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
def RX_data(serial): try: if serial.inWaiting() > 0: result = serial.read(1) RX = ord(result) return RX else: print('rx error') return 0 except: return 0 pass
def recv(serial): data = '' sleep(1) while True: while serial.inWaiting() > 0: data += (serial.read(1)).decode() if data == '': continue else: break print('slave computer info: ') print(data) return data
def ReceiveData(serial): tmp_wait = serial.inWaiting() if tmp_wait == 0: print('no data') return '' data = serial.read(tmp_wait) data_hex = data.hex() data_str = '' for i in range(len(data_hex)): data_str += data_hex[i] if i % 2 == 1: data_str += ' ' return data_str.strip().upper()
def ASK_Slave(serial, cmd_data): global recv_data, recv_n global abs_path timeout_count = 0 timeout_total = 0 print 'recv_n', recv_n print 'recv_data_B', recv_data while True: print "Motor is moving: ", timeout_count, " times" time.sleep(0.5) recv_n = serial.inWaiting() print cmd_data, '&& recv_n:', recv_n if recv_n >= 2: recv_data = serial.read(recv_n) print recv_n, ' && ', recv_data serial.flushInput() if 'OK' in recv_data and cmd_data[0] in recv_data: print 'recv_data_A', recv_data, '+', recv_n print 'Moving Finished.' recv_n = 0 recv_data = 'N' serial.flushOutput() time.sleep(0.5) # 1 # Journal = open(abs_path,'a') # Journal.write(cmd_data[0] + "->") # Journal.close() break else: print "Wrong Control,Break!" recv_n = 0 recv_data = 'N' serial.flushOutput() timeout_count += 1 if timeout_count >= 600: print "No response Slave,Repeat send cmd please." serial.write(cmd_data) timeout_total += timeout_count timeout_count = 0 Journal = open(abs_path, 'a') if timeout_total <= 600: Journal.write("\nSlave No response for CMD:" + cmd_data[0] + " " + str(timeout_total) + " times,Repeat Send CMD...\n") else: Journal.write("\nSlave No response for CMD:" + cmd_data[0] + " " + str(timeout_total) + " times,Shutdown System...\n") Journal.write("System died at: " + Get_time_str(':') + '.\n') os.system('sudo shudown -h now') Journal.close()
def RX_data(serial): global Temp_count try: if serial.inWaiting() > 0: result = serial.read(1) RX = ord(result) return RX else: return 0 except: Temp_count = Temp_count + 1 print("Serial Not Open " + str(Temp_count)) return 0 pass
def bcc_off(serial): global f serial.write(bytes.fromhex('A3 3A 00 01 01 00')) while True: flag = 0 while serial.inWaiting() > 0: data = serial.readline() print(data, len(data)) if data[:6] == b'\xA3\x3A\x00\x01\x00\x01': print("bcc off") flag = 1 break if flag == 1: break
def test(serial,expecting,timeout=30): tStart = time.time() while(1): if serial.inWaiting(): time.sleep(.01) c = serial.read(1) if c == expecting[0]: expecting = expecting[1:] print repr(c), if expecting == "": return True if time.time()-tStart > timeout: return False return False
def read_data(serial): print "read data %d" % exitflag #try: alldata = "" while exitflag == 0: #data = serial.readline() count = serial.inWaiting() if count > 0: data = serial.read(count) if data == "\n": alldata += data print alldata, alldata = "" else: alldata += data
def openbci_id(self, serial): line = '' # Espera a que el dispositivo envíe datos time.sleep(2) if serial.inWaiting(): line = '' c = '' # Busca la secuencia de fin '$$$' while '$$$' not in line: c = serial.read().decode('utf-8') line += c if "OpenBCI" in line: return True return False
def recieve_message(self): readMsg = '' serial.flushInput() time.sleep(4) orig_time = time.time() while((time.time()-orig_time) < 5 ): readMsg = serial.read(serial.inWaiting()) #print("test") time.sleep(1) if readMsg != '': break else: raise("problem in recieving message") self.logger("Recieving package %s" % readMsg) return readMsg
def openbci_id(serial): """ When automatically detecting port, parse the serial return for the "OpenBCI" ID. """ line = '' #Wait for device to send data time.sleep(2) c = '' if serial.inWaiting(): c = serial.read().decode('utf-8') if len(c) > 0: print(len(c)) return True return False
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') line += c if "OpenBCI" in line: return True return False
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
def reader(self, alive, q, serial, callback): while alive: try: data = serial.read(1) #read one, blocking n = serial.inWaiting() #look if there is more if n: data = data + serial.read(n) #and get as much as possible if data: if data[3] == '\x08': interrupt = self.decodefun(data) callback_process = Process(target=callback, args=[interrupt[1]]) callback_process.start() #callbackthread = threading.Thread(target=self.callback, args=[interrupt[1]]) #callbackthread.start() else: q.put(data) #self.outq.put(data) except: errmsg("UPER API: serial port reading error.") #raise APIError("Serial port reading error.") alive = False break
def lineFromSerial(serial): global serialBuffer inWaiting = None newData = None try: inWaiting = serial.inWaiting() if inWaiting > 0: newData = serial.read(inWaiting) except (IOError, OSError, serial.SerialException) as e: logMessage('Serial Error: {0})'.format(str(e))) return if newData: serialBuffer = serialBuffer + newData if '\n' in serialBuffer: lines = serialBuffer.partition('\n') # returns 3-tuple with line, separator, rest if(lines[1] == ''): # '\n' not found, first element is incomplete line serialBuffer = lines[0] return None else: # complete line received, [0] is complete line [1] is separator [2] is the rest serialBuffer = lines[2] return util.asciiToUnicode(lines[0])
''' A silly python program to test the daily-voc app. ''' import serial import time serial = serial.Serial('/dev/ttyUSB0', 9600, timeout=1) ack = '\x01\x01\x04\x0c\x44\x96\x60\x00\x41\xc7\x33\x33\x41\x8c\x00\x00\x22\x53' while True: while serial.inWaiting() < 1: continue time.sleep(0.1) r = serial.read(8) serial.flushOutput() s = 'Rx: ' + ' '.join([hex(ord(i)) for i in r]).replace('0x', '') print s time.sleep(0.2) s = 'Tx: ' + ' '.join([hex(ord(i)) for i in ack]).replace('0x', '') print s serial.write(ack)
def serRead(threadName, delay): if serial.inWaiting() > 0: msg = serial.readline() print ("[Arduino | %s] serRead > %s" %(time.ctime(time.time()), msg)) parse_msg(msg) real_delay_call(serRead, delay, threadName, delay)
def check_package(self, package, status=None, count = None): #read_message = '' #test time.sleep(4) read_message = serial.read(serial.inWaiting()) if read_message == '': orig_time = time.time() while((time.time()-orig_time)<6): if read_message == '': print("read again") time.sleep(2) read_message = serial.read(serial.inWaiting()) else: break if read_message == '': while (count != None) and (count < 3): count = count + 1 print("resend") #rebreak the package resend = self.decode_package(package) #transmit and repackage repackage = self.transmit_package(resend['reciever'], resend['data_type'], resend['payload']) try: self.check_package(package, None, count) except: pass else: raise Exception("boo") #orig_time = time.time() #while((read_message == '') & ((orig_time-time.time())<5)): # read_message = self.recieve_message() #if read_message == '': # raise "Problem in sending" confirm_package = self.decode_package(read_message) original_package = self.decode_package(package) if confirm_package['sender'] != original_package['reciever']: print("Error in Sender INIT Path") else: print("Sender Match") if original_package['data_type'] == '0000': if confirm_package['data_type'] != '0001': print("Error in Data Type INIT Path") elif confirm_package['payload'] != original_package['payload']: print("Error in Payload INIT Path") else: print("Go INIT Path") package = self.transmit_package(original_package['reciever'], '0010', '') #try: self.check_package(package) #except: # pass elif original_package['data_type'] == '0010': if confirm_package['data_type'] != '0011': print("Error in Data Type Confirm Path") else: print ("Go Confirm Path") elif original_package['data_type'] == '0100': if confirm_package['data_type'] != '0101': print("Error in Data Type Status") else: if confirm_package['payload'] == '0'.zfill(24): print("Changing Run Status") status(False)
def picture640x480(): serial = serial.Serial("/dev/ttyO1", baudrate=38400) # Initialize camera """ (SYSTEM_RESET command) """ serial.write(b'\x56\x00\x26\x00') resp = "" time.sleep(1) while(serial.inWaiting() > 0): data = serial.read() resp += data if "Init end\r\n" in resp: print "Ready" break # Set image size to 640 x 480 """ according to the command manual 0x54 corresponds with DOWNSIZE_STATUS Everything looks like it might refer to DOWNSIZE_SIZE, 0x53. The return code fits exactly with it. PROBABLY MISTAKEN TODO inspect this more carefully. """ serial.write(b'\x56\x00\x54\x01\x00') resp = "" time.sleep(1) while (serial.inWaiting() > 0): data = serial.read() resp += data if b'\x76\x00\x54\x00\x00' in resp: print "Size set" break # Take picture """ FBUF_CTRL: control frame buffer register particularly this instruction stop the current frame. 0x56+serial number+0x36+0x01+control flag(1 byte) """ serial.write(b'\x56\x00\x36\x01\x00') resp = "" time.sleep(2) while(serial.inWaiting() > 0): data = serial.read() resp += data if b'\x76\x00\x36\x00\x00' in resp: print "Picture taken" break elif b'\x76\x00\x36\x03\x00' in resp: # Error raise Exception("Error at FBUF_CTRL") #Get JPG size """ GET_FBUF_LEN: get byte-lengths inFBUF 0x56+serial number+0x34+0x01+FBUF type(1 byte) """ serial.write(b'\x56\x00\x34\x01\x00') resp = "" time.sleep(1) while(serial.inWaiting() > 0): data = serial.read() resp += data if b'\x76\x00\x34\x00\x04\x00\x00' in resp: msb = serial.read() lsb = serial.read() print "Image file size: %d bytes" % (ord(msb) << 8 | ord(lsb)) # Write image to file """ READ_FBUF: read image data from FBUF 0x56+serial number+0x32+0x0C+FBUF type(1 byte)+control mode(1 byte) +starting address(4 bytes)+data-length(4 bytes)+delay(2 bytes) """ serial.write(b'\x56\x00\x32\x0C\x00\x0A\x00\x00\x00\x00\x00\x00%c%c\x00\x0A' % (msb,lsb)) time.sleep(5) now = datetime.datetime.now() filename = "%d.%02d.%02d.%02d.%02d.%02d.jpg" % \ (now.year,now.month,now.day,now.hour,now.minute,now.second) resp = serial.read(size=5) if b'\x76\x00\x32\x00\x00' in resp: with open("/tmp/" + filename, 'wb') as f: while(serial.inWaiting() > 0): data = serial.read() f.write('%c' % data) print "Image written to /tmp/%s" % (filename) # send the image through ssh comando = "scp /tmp/%s [email protected]:~/Desktop" % (filename) os.system(comando)
if '\x4F\x4B\x0D' in resp: print "Exit Command Mode" break return 0 # Initialize camera serial = serial.Serial("/dev/ttyUSB0", baudrate=38400,timeout=0.2) serial.write(b'\x56\x00\x26\x00') resp = "" time.sleep(1) while (serial.inWaiting() > 0): data = serial.read() resp += data if '\x76\x00\x26\x00' in resp: print "Ready" break # Set image size to 640 x 480 #serial.write(b'\x56\x00\x54\x01\x00') # Set image size to 640 x 480 #serial.write(b'\x56\x00\x54\x01\x00') serial.flushInput() serial.flushOutput()
try: print >>sys.stderr, 'waiting to receive message' data, address = sock.recvfrom(4096) print data if data == 'start': # Connect with serial port try: serial = serial.Serial('/dev/ttyAMA0', baudrate=9600, timeout=3) except: print 'error opening serial port' resp = '' fileName = '' date = '' try: while True: while (serial.inWaiting() > 0): resp += serial.read() if '\r\n' in resp: if '$GPRMC' in resp: data = resp.split(',') # Status, V=Navigation receiver warning A=Valid if data[2] == 'A': # Get time hour = data[1][0:2] min = data[1][2:4] sec = data[1][4:6] mil = data[1][7:10] time = '%s%s%s%s' % (hour, min, sec, mil) # Get date day = data[9][0:2] month = data[9][2:4]
"id": 0 } send = { "data": "", "key" : key } print "Reading file..." f = open("helpers.txt", "r+") for line in f: line = line.replace("\n", "") data = line.split(", ") helpers.append([data[0], data[1]]) f.close() print "Done. Ready to scan." while True: if serial.inWaiting() > 0: read_result = serial.read(12) rfid = format(read_result.decode(encoding="utf-8")) if len(rfid) == 12: rfid = rfid[1:11] print("Read card " + rfid) for student in helpers: if(rfid == student[0]): print "You are " + student[1] send_data["id"] = student[1] send["data"] = json.dumps(send_data) print requests.post(url, data=send).text else: print("Misread card") print("Please wait for 1 second..."); time.sleep(1)
def writeserial(command, *args, **kwargs): hex = COMMANDS[command] % kwargs print 'writing to serialport ' + hex serial.write(hex2chr(hex)) # time.sleep(2) print 'waiting at serialport: %i' % serial.inWaiting()
import serial import sys # Connect with serial port try: serial = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=3) except: print "error opening serial port" resp = "" try: while True: while serial.inWaiting() > 0: resp += serial.read() if "\r\n" in resp: if "$GPRMC" in resp: data = resp.split(",") # Status, V=Navigation receiver warning A=Valid if data[2] == "A": # Get time hour = data[1][0:2] min = data[1][2:4] sec = data[1][4:6] mil = data[1][7:10] string = "%s:%s:%s.%s" % (hour, min, sec, mil) else: string = "no signal" print string resp = "" except:
def arduinoRead(serial): while True: time.sleep(2) t, v = [], [] data = serial.read(serial.inWaiting()) sample = data.split('\n') del sample[-1] for line in sample: values = line.split() values = map(int, values) # print "SIZE: ", len(values) # print "t val 0: ", values[0] # print "v val 1: ", values[1] # append if there are both values, otherwise it breaks if len(values) == 2: t.append(values[0]) v.append(values[1]) # if values[0] and values[1]: # t.append(values[0]) # v.append(values[1]) vSmooth = gaussSmooth(v); # print v # print vSmooth # print "v size and type: ", len(v), type(v) # print "vSmooth size and type: ", len(vSmooth), type(vSmooth) # vNp = np.array(v) # maximaV = argrelextrema(vNp, np.greater) # print maximaV # customMaximaV = maxima(v) # print customMaximaV smoothMaxima = maxima(vSmooth) # print smoothMaxima bpm, ibi = sampleStats(smoothMaxima, t) vStd = np.std(v) print "standard deviation: ", vStd status = 0 #0: not a good pulse. 1: good pulse. stdThresholdLow = 25; stdThresholdHigh = 400; if vStd > stdThresholdLow and vStd < stdThresholdHigh and bpm > 20 and ibi < 3000: status = 1 print "SAMPLE BPM: ", bpm print "PULSE STATUS: ", status epochTime = time.time() fullStats[0].append(t[-1]) fullStats[1].append(epochTime) fullStats[2].append(bpm) fullStats[3].append(ibi) fullStats[4].append(status) # print fullStats writeFile.write(str(t[-1]) + "\t" + str(epochTime) + "\t" + str(bpm) + "\t" + str(ibi) + "\t" + str(status) + "\n");
def rfidFlush(serial): serial.read(serial.inWaiting()) serial.flushInput()