class JYMCU(object): """JY-MCU Bluetooth serial device driver. This is simply a light UART wrapper with addition AT command methods to customize the device.""" def __init__(self, uart, baudrate): """ uart = uart #1-6, baudrate must match what is set on the JY-MCU. Needs to be a #1-C. """ self._uart = UART(uart, baudrate) def __del__(self): self._uart.deinit() def any(self): return self._uart.any() def write(self, astring): return self._uart.write(astring) def writechar(self, achar): self._uart.writechar(achar) def read(self, num=None): return self._uart.read(num) def readline(self): return self._uart.readline() def readchar(self): return self._uart.readchar() def readall(self): return self._uart.readall() def readinto(self, buf, count=None): return self._uart.readinto(buf, count) def _cmd(self, cmd): """ Send AT command, wait a bit then return result string. """ self._uart.write("AT+" + cmd) udelay(500) return self.readline() def baudrate(self, rate): """ Set the baud rate. Needs to be #1-C. """ return self._cmd("BAUD" + str(rate)) def name(self, name): """ Set the name to show up on the connecting device. """ return self._cmd("NAME" + name) def pin(self, pin): """ Set the given 4 digit numeric pin. """ return self._cmd("PIN" + str(pin)) def version(self): return self._cmd("VERSION") def setrepl(self): repl_uart(self._uart)
class NBIOT(): def __init__(self,uart_port,uart_baud): self.nbiot = UART(uart_port,uart_baud,read_buf_len = 256) def read(self): info = self.nbiot.read() try: info = info.decode() except (UnicodeError,AttributeError): return -1 return info def readline(self): info = self.nbiot.readline() try: info = info.decode() except (UnicodeError,AttributeError): return -1 return info def check_sim(self): self.nbiot.write("AT+CIMI\r\n") time.sleep(3) rebound = self.readline() iccid = self.readline() neglect = self.readline() state = self.readline() return str(iccid),str(state) def check_csq(self): self.nbiot.write("AT+CESQ\r\n") time.sleep(3) rebound = self.readline() cesq = self.readline() neglect = self.readline() state = self.readline() return int(cesq[7:9]),str(state) def create_socket(self): self.nbiot.write("AT+QIOPEN=1,0,\"TCP\",\"115.236.36.53\",506,1234,1\r\n") time.sleep(5) info = self.read() return info def close_socket(self): self.nbiot.write("AT+QICLOSE=0\r\n") time.sleep(5) info = self.read() return info
class mppt: def __init__(self, port, baud=19200): self.port = UART(port, baud) self.data = {"here": 1} def getdata(self): while self.port.any() > 0: try: dataline = self.port.readline() out = dataline.decode('UTF8') split = ure.match("^(\w*)(\s*)(\w*)", out) #self.data[split.group(1)] = split.group(3) except Exception as e: pass return self.data
class JYMCU(object): """JY-MCU Bluetooth serial device driver. This is simply a light UART wrapper with addition AT command methods to customize the device.""" def __init__( self, uart, baudrate ): """ uart = uart #1-6, baudrate must match what is set on the JY-MCU. Needs to be a #1-C. """ self._uart = UART(uart, baudrate) def __del__( self ) : self._uart.deinit() def any( self ) : return self._uart.any() def write( self, astring ) : return self._uart.write(astring) def writechar( self, achar ) : self._uart.writechar(achar) def read( self, num = None ) : return self._uart.read(num) def readline( self ) : return self._uart.readline() def readchar( self ) : return self._uart.readchar() def readall( self ) : return self._uart.readall() def readinto( self, buf, count = None ) : return self._uart.readinto(buf, count) def _cmd( self, cmd ) : """ Send AT command, wait a bit then return result string. """ self._uart.write("AT+" + cmd) udelay(500) return self.readline() def baudrate( self, rate ) : """ Set the baud rate. Needs to be #1-C. """ return self._cmd("BAUD" + str(rate)) def name( self, name ) : """ Set the name to show up on the connecting device. """ return self._cmd("NAME" + name) def pin( self, pin ) : """ Set the given 4 digit numeric pin. """ return self._cmd("PIN" + str(pin)) def version( self ) : return self._cmd("VERSION") def setrepl( self ) : repl_uart(self._uart)
class NBIOT(): def __init__(self,uart_port,uart_baud): self.nbiot = UART(uart_port,uart_baud,read_buf_len = 256) def read(self): info = self.nbiot.read() try: info = info.decode() except (UnicodeError,AttributeError): return -1 return info def readline(self): info = self.nbiot.readline() try: info = info.decode() except (UnicodeError,AttributeError): return -1 return info def check_sim(self): self.nbiot.write("AT+CIMI\r\n") time.sleep(3) rebound = self.readline() iccid = self.readline() neglect = self.readline() state = self.readline() return str(iccid),str(state) def check_csq(self): self.nbiot.write("AT+CESQ\r\n") time.sleep(3) rebound = self.readline() cesq = self.readline() neglect = self.readline() state = self.readline() return int(cesq[7:9]),str(state)
from pyb import UART import network import socket if __name__ == "__main__": nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3) nic.connect('Joi', 'deadbeef') while not nic.isconnected(): pyb.delay(50) print(nic.ifconfig()) uart = UART(1, 9600) addr = ('192.168.1.242', 9999) while True: s = socket.socket() s.connect(addr) s.send(b"Hello\r\n") while True: try: incoming = "" incoming = s.recv(1024) uart.write("%s\r"%incoming.decode().strip()) while uart.any(): serialdata = uart.readline() s.send("%s\n"%serialdata.decode().strip()) except: print("error") break s.close()
# main.py -- put your code here! import pyb import time from pyb import UART uart = UART(1, 115200) uart.init(115200, bits=8, parity=None, stop=1) usb = pyb.USB_VCP() while True: try: msg = uart.readline() #usb.write((msg + "\r\n")) print(msg + "\r\n") except KeyboardInterrupt: exit(0) except: pass
class NBIOT(): def __init__(self, uart_port, uart_baud): self.modbus = MODBUS() self.nbiot = UART(uart_port, uart_baud, read_buf_len=256) def read(self): info = self.nbiot.read() try: info = info.decode() except (UnicodeError, AttributeError): return -1 return info def readline(self): info = self.nbiot.readline() try: info = info.decode() except (UnicodeError, AttributeError): return -1 return info def check_sim(self): self.nbiot.write("AT+CIMI\r\n") time.sleep(3) rebound = self.readline() neglect = self.readline() neglect = self.readline() iccid = self.readline() neglect = self.readline() info = self.readline() return str(iccid), str(info) def create_socket(self): self.nbiot.write( "AT+QIOPEN=1,0,\"TCP\",\"115.236.36.53\",506,1234,1\r\n") time.sleep(5) info = self.read() return info def close_socket(self): self.nbiot.write("AT+QICLOSE=0\r\n") time.sleep(5) info = self.read() return info def tcp_send(self, load_info): cell_info = load_info[0] sonic_info = load_info[1] operator_info = load_info[2] info = self.modbus.getpack(cell_info, sonic_info, operator_info) len_info = len(info) message = 'AT+QISEND=0,' + str(len_info) + ',' + info + '\r\n' self.nbiot.write(message) time.sleep(10) rebound = self.readline() state = self.readline() neglect = self.readline() send_state = self.readline() neglect = self.readline() return str(state), str(send_state) def tcp_receive(self, time_delay=30): time.sleep(time_delay) neglect = self.readline() info = self.readline() info = info[0:len(info) - 1] return info def tcp_process(self, info): self.close_socket() time.sleep(3) self.close_socket() print("MINIC THE SENDING") while (1): self.modbus.iccid, get_state = self.check_sim() if (get_state.find('OK') != -1): print("CHECK SIM OK") break while (1): get_state = str(self.create_socket()) if (get_state.find('OK') != -1): if (get_state.find('QIOPEN') != -1): print("OPEN TCP OK") break while (1): state, send_state = self.tcp_send(info) if (state.find('OK') != -1 and send_state.find('SEND OK') != -1): print("SENDING OK") break print("TIME DELAY FOR RX") rx_message = self.tcp_receive() print("TASK COMPLETE") while (1): get_state = str(self.close_socket()) if (get_state.find('OK') != -1): print("CLOSE TCP OK") break return rx_message
from pyb import Pin, Timer, ExtInt, UART, Servo import time u = UART(3, 9600) ss = Pin(Pin.cpu.A13, Pin.OUT) from car import * import re, time cmds = { 'back': back2, 'forward': forward2, 'stop': stop, 'add': add, 'dec': dec, } ss.value(0) def jdytest(): print("jdytest") for s in ('BAUD', 'RFID', 'DVID', 'RFC'): u.write('AT+' + s + '\r\n') while not u.any(): pass print(u.read()) jdytest() u.write('AT+CLSSA0\r\n') time.sleep(2) print(u.read()) ss.value(1) print(ss.value()) while (1):
functions = { 0: stop, 1: view_template, 2: take_snap, 3: save_snap_as_template, 4: get_stats } """ while(True): sensor.snapshot()""" #if (int(pin7.value()) == 0): if (False): while (True): cmd = uart.readline() if (cmd != None): print("CMD: " + str(int(cmd))) functions[int(cmd)]() """if(int(pin7.value()) == 1): break""" else: k = 0 template = image.Image(template_path_pgm, copy_to_fb=False) while (True): img = sensor.snapshot() r = img.find_template(template, 0.70, step=4, search=SEARCH_EX) if r: led.on() time.sleep(100) led.off()
import time import pyb from pyb import UART uart = UART(6, 9600) uart.init(9600, bits=8, parity=None, stop=1) filename = "gpsData.txt" uart.write("$PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*2C\r\n") i = 0 while i < 30: if uart.any() > 0: file = open(filename, "a") line = uart.readline() line = line.decode( "utf-8") #ser.readline returns a binary, convert to string file.write(line) file.flush() i = i + 1 file.close() pyb.LED(1).on() pyb.LED(2).on() pyb.LED(3).on() pyb.LED(4).on()
# print("Enable Response[%d]: %s"%(len(response),response)); # Test loop of sending trigger and reading the line (ends in newline) # for that response. If we picked the binary format packet with our # format command we would not use readline() we would read the # specified number of bytes in the binary protocol like frame = uart.read(9); # and then parse that based on the manual. while (True): command = bytes(b'\x5A\x04\x04\x62') # Trigger detection command uart.write(command) # Send the trigger over the UART # If we were going to do image processing at the same time we would do it # here while the UART is receiving characters in the background... that way # we can get the data from the TF-LIDAR while we're running our image processing # and then use it once we're done and the loop runs as fast as possible. # Do Image processing stuff... # Read the lidar since it has had time for characters to come over the serial port. lidar_frame = uart.readline() # Read until the newline character (we picked text format with newline above) # Send out our results. print("Frame: %s" % lidar_frame) # Print the line we got back for this frame. # Delay to control the rate... pyb.delay(30) # Wait a while...
def initializeAntenna(): global uart uart = UART(1, currentBaud) uart.init(currentBaud, bits=8, parity=None, stop=1) time.sleep(0.5) print("Antenna Initial STATUS") uart.write("AT") print(uart.readline()) uart.write("AT+RB") print(uart.readline()) uart.write("AT+RC") print(uart.readline()) uart.write("AT+RF") print(uart.readline()) uart.write("AT+RP") print(uart.readline()) print("\r\n\n\n") print("SENDING CONFIG") print("\r\n") uart.write("AT+B" + antennaConfig["baud"]) uart.write("AT+C" + antennaConfig["channel"]) uart.write("AT+P" + antennaConfig["power"]) uart.write("AT+F" + antennaConfig["fu"]) print("\r\nDONE") print("Antenna Final STATUS") uart.write("AT") print(uart.readline()) uart.write("AT+RB") print(uart.readline()) uart.write("AT+RC") print(uart.readline()) uart.write("AT+RF") print(uart.readline()) uart.write("AT+RP") print(uart.readline()) time.sleep(0.5) baudBaseString = "AT+B" desiredBaud = 9600 uart.write(baudBaseString + str(desiredBaud)) print(uart.readline())
def cirSensor(): #色环识别初始化 sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.HQVGA) sensor.skip_frames(time=5000) sensor.set_auto_gain(False) # must be turned off for color tracking sensor.set_auto_whitebal(False) # must be turned off for color tracking #sensor.set_auto_exposure(False, 7000) while (True): clock.tick() # Track elapsed milliseconds between snapshots(). if uart.any(): #如果接收到数据,小灯闪烁并变蓝 led.off() getrx = uart.readline() #接收到的数据保存到getrx time.sleep(150) #延时150ms led = pyb.LED(2) led.on() img = sensor.snapshot() # 从感光芯片获得一张图像 #img.lens_corr(strength = 1.8, zoom = 1.0) # 镜头畸变矫正 blobs = img.find_blobs([green_threshold, red_threshold, blue_threshold], roi=(50, 10, 300, 300), x_stride=25, y_stride=50, area_threshold=8000) if getrx == b'2': #如果接收到0x32,执行二维码扫描 if ii == 0: led.off() #小灯闪烁并变绿一次 time.sleep(150) led = pyb.LED(1)
uart.write("AT+RB") print(uart.readline()) uart.write("AT+RC") print(uart.readline()) uart.write("AT+RF") print(uart.readline()) uart.write("AT+RP") print(uart.readline()) time.sleep(0.5) baudBaseString = "AT+B" desiredBaud = 9600 uart.write(baudBaseString + str(desiredBaud)) print(uart.readline()) initializeAntenna() while 1: try: recv = uart.readline() usb.write(recv) except KeyboardInterrupt: break except: # usb.write("\r\n\n\n") continue
print(uart1.write(b'123') == 3) print(uart0.read(1) == b'1') print(uart0.read(2) == b'23') print(uart0.read() == b'') uart0.write(b'123') buf = bytearray(3) print(uart1.readinto(buf, 1) == 1) print(buf) print(uart1.readinto(buf) == 2) print(buf) uart0.write(b'1234567890') pyb.delay(2) # because of the fifo interrupt levels print(uart1.any() == 10) print(uart1.readline() == b'1234567890') print(uart1.any() == 0) uart0.write(b'1234567890') print(uart1.readall() == b'1234567890') # tx only mode uart0 = UART(0, 1000000, pins=('GP12', None)) print(uart0.write(b'123456') == 6) print(uart1.read() == b'123456') print(uart1.write(b'123') == 3) print(uart0.read() == b'') # rx only mode uart0 = UART(0, 1000000, pins=(None, 'GP13')) print(uart0.write(b'123456') == 6)
from pyb import UART, LED import utime, gc # init UART uart = UART(3, 9600) #Use UART 3 in pybaord uart.init(9600, bits=8, parity=None, stop=1, timeout=100) #init servo servo_x = pyb.Servo(4) servo_y = pyb.Servo(3) #variables temp_x = [40] * 3 temp_y = [70] * 3 ear_val = 60 speed = 100 while (True): val = uart.readline() if val != None: val = val.decode( 'utf-8') # reads in and decode uart data from bytes to floats. val = val[:-1] val = val.split('|') print(val) if len(val) != 3 or val[0] == '' or val[1] == '' or val[2] == '': continue temp_x.append( 80 - int(val[0])) # x mounts in the head - up-and-down movement servo_x.angle(sum(temp_x) / len(temp_x)) temp_x.pop(0) temp_y.append(110 - int(val[1])) # y is horizontal sweeping servo_y.angle(sum(temp_y) / len(temp_y))
step2 = test2 & 0x0F chordnr2 = (test2 >> 4) & 0x07 countvalue2 = int(16.5 * (2**chordnr2 - 1) + (step2 * (2**chordnr2))) countvalue = int(16.5 * (2**chordnr - 1) + (step * (2**chordnr))) r = (countvalue2 / countvalue) lux = countvalue * 0.46 * (2.718281828**(-3.13 * r)) lux = round(lux) print(lux) lux = str(lux) d.set_line(0) d.set_string("Light:") d.set_line(1) d.set_string(lux + " lux") pyb.delay(2000) #ser.write(bytes(lux.encode('ascii'))) x = ser.readline().decode('ascii').strip() print(x) d.set_line(0) d.set_string("Date and time:") d.set_line(1) d.set_string(x) pyb.delay(2000) temp1 = adc.read() jannite = (temp1 / 4095) * 3.3 vastus = (jannite * 1780) / (3.3 - jannite) lampo = int(((vastus - 1922) / 78) * 5 + 20) celsius = str(lampo) + " C" d.set_line(0) d.set_string("Temperature:") d.set_line(1) d.set_string(celsius)
print(uart0.read(2) == b'23') print(uart0.read() == b'') uart0.write(b'123') buf = bytearray(3) print(uart1.readinto(buf, 1) == 1) print(buf) print(uart1.readinto(buf) == 2) print(buf) # try initializing without the id uart0 = UART(baudrate=1000000, pins=uart_pins[0][0]) uart0.write(b'1234567890') pyb.delay(2) # because of the fifo interrupt levels print(uart1.any() == 10) print(uart1.readline() == b'1234567890') print(uart1.any() == 0) uart0.write(b'1234567890') print(uart1.readall() == b'1234567890') # tx only mode uart0 = UART(0, 1000000, pins=('GP12', None)) print(uart0.write(b'123456') == 6) print(uart1.read() == b'123456') print(uart1.write(b'123') == 3) print(uart0.read() == b'') # rx only mode uart0 = UART(0, 1000000, pins=(None, 'GP13')) print(uart0.write(b'123456') == 6)
filteredZ = filterToolkit.filter2(filteredZ, rawZ, 0.2) # uart.write(" - x:%.1f y:%.1f z:%.1f" % (filteredX,filteredY,filteredZ)) # uart.write(" - x:%.1f y:%.1f z:%.1f" % (filteredX,filteredY,filteredZ)) roll, pitch = calcPitchAndRoll(filteredX, filteredY, filteredZ) # uart.write("roll:%.1f pitch:%.1f\r\n" % (roll,pitch)) # uart.write("roll:%.1f pitch:%.1f\r\n" % (roll,pitch)) if (roll >= 0): chLeft.pulse_width_percent(int(roll / 2)) chRight.pulse_width_percent(0) else: chRight.pulse_width_percent(int(-roll / 2)) chLeft.pulse_width_percent(0) if (pitch >= 0): chDown.pulse_width_percent(int(pitch / 2)) chUp.pulse_width_percent(0) else: chUp.pulse_width_percent(int(-pitch / 2)) chDown.pulse_width_percent(0) if (cycleCounter - cycleCounterPrev) >= 100: cycleCounterPrev = cycleCounter message = uart.readline() if message != None: print(message) if message == b'roll\n': uart.write("%.1f" % roll) elif message == b'pitch\n': uart.write("%.1f" % pitch)
from pyb import UART import network import socket if __name__ == "__main__": nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3) nic.connect('Joi', 'deadbeef') while not nic.isconnected(): pyb.delay(50) print(nic.ifconfig()) uart = UART(1, 9600) addr = ('192.168.1.242', 9999) while True: s = socket.socket() s.connect(addr) s.send(b"Hello\r\n") while True: try: incoming = "" incoming = s.recv(1024) uart.write("%s\r" % incoming.decode().strip()) while uart.any(): serialdata = uart.readline() s.send("%s\n" % serialdata.decode().strip()) except: print("error") break s.close()
class frc_lidar: def __init__(self): # Always pass UART 3 for the UART number for your OpenMV Cam. self.uart = UART(3); # This initializes the UART paramters: 115200 bits/second, 8 bits/byte, no parity, 1 stop. # Wait for 80ms for data to start when reading and up to 20ms between characters before # we timeout on reading. self.uart.init(115200, bits=8, parity=None, stop=1, timeout_char=20, timeout=80); # First we have to stop it from talking so we can send commands # and understand what it says back. # Disable output command: self.command = bytes(b'\x5A\x05\x07\x00\x66'); self.uart.write(self.command); self.uart.read(); #print("Disable Command: %s"%command); #uart.write(command); #response = uart.read(); #print("Disable Response[%d]: %s"%(len(response),response)); # Manal synchronizing with device # # Wait 1/4 second for it to shut up, so we can get synchronized with what it is # sending to us. pyb.delay(250); # Delay is in milliseconds. # Read everything we've got in the UART buffer so far and ignore it...because # it is just a jumble of stuff we don't know where the frames begin or end. self.response = self.uart.read(); # Now Read Version Info: Now we know that the next response will be to this command. self.command = bytes(b'\x5A\x04\x01\x5F'); self.uart.write(self.command); self.uart.read(); #print("Version Command: %s"%command); #uart.write(command); # Read back response: #response = uart.read(); #print("Version Response[%d]: %s"%(len(response), response)); # Set the format of data to be text (easily parsed): # We could send another command to set the binary format and then # we would receive packets of 9 bytes for each reading. self.command = bytes(b'\x5A\x05\x05\x02\x66'); self.uart.write(self.command); self.uart.read(); #print("Format Command: %s"%command); #uart.write(command); # Read back response: #response = uart.read(); #print("Format Response[%d]: %s"%(len(response),response)); # Set the rate to zero so we trigger it to capture and can sync with # other things we do in the OpenMV. It will respond when we ask so # we can't get out of sync with it. self.command = bytes(b'\x5A\x06\x03\x00\x00\x63'); self.uart.write(self.command); self.uart.read(); # print("Rate Command: %s"%command); # uart.write(command); # response = uart.read(); # print("Rate Response[%d]: %s"%(len(response),response)); # Enable output again now that we're ready: self.command = bytes(b'\x5A\x05\x07\x01\x67'); self.uart.write(self.command); self.uart.read(); # print("Enable Command: %s"%command); # uart.write(command); # response = uart.read(5); # print("Enable Response[%d]: %s"%(len(response),response)); def readLidar(self): self.command = bytes(b'\x5A\x04\x04\x62'); # Trigger detection command self.uart.write(self.command); # Send the trigger over the UART # If we were going to do image processing at the same time we would do it # here while the UART is receiving characters in the background... that way # we can get the data from the TF-LIDAR while we're running our image processing # and then use it once we're done and the loop runs as fast as possible. # Do Image processing stuff... # Read the lidar since it has had time for characters to come over the serial port. self.lidar_frame = self.uart.readline(); # Read until the newline character (we picked text format with newline above) return self.lidar_frame
reason=upower.why() # motivo dell'uscita da low power mode. # see upower.py module documentation. uart.write(str(reason) +'\n') #reason='ALARM_B' # solo per debug try: if reason=='X1': verde.on() pyb.delay(3) verde.off() uart.write('ready'+'\n') # uscito da standby - standby exit. while test==0: inBuffer_rx="" if uart.any(): inBuffer_rx=uart.readline() print(inBuffer_rx) inBuffer_chr="" if inBuffer_rx!='': inBuffer_chr=inBuffer_rx.decode() if inBuffer_chr=='connecting': print('connecting') uart.write('sono connesso!'+'\n') # uscito da standby - standby exit. restore_data() sa=leggi_sonda_a() pkl['in_sonda_a']=int(sa) sb=leggi_sonda_b() pkl['in_sonda_b']=int(sb) uart.write(str(pkl)+'\n') # invia dati a host - send data to host.
from pyb import UART import time u2 = UART(4, 115200) while True: s = u2.readline()[0:8].decode('utf-8') time.sleep_ms(500) print('当前时间:', s)
class ESP8266(object): def __init__(self, uart=1, baud_rate=115200): """Initialize this module. uart may be an integer or an instance of pyb.UART. baud_rate can be used to set the Baud rate for the serial communication.""" if uart: if type(uart) is int: self.uart = UART(uart, baud_rate) elif type(uart) is UART: self.uart = uart else: raise Exception( "Argument 'uart' must be an integer or pyb.UART object!") else: raise Exception("Argument uart must not be 'None'!") def _send_command(self, cmd, timeout=0, debug=False): """Send a command to the ESP8266 module over UART and return the output. After sending the command there is a 1 second timeout while waiting for an anser on UART. For long running commands (like AP scans) there is an additional 3 seconds grace period to return results over UART. Raises an CommandError if an error occurs and an CommandFailure if a command fails to execute.""" if debug: start = micros() cmd_output = [] okay = False if cmd == '' or cmd == b'': raise CommandError("Unknown command '" + cmd + "'!") # AT commands must be finalized with an '\r\n' cmd += '\r\n' if debug: print("%8i - TX: %s" % (elapsed_micros(start), str(cmd))) self.uart.write(cmd) # wait at maximum one second for a command reaction cmd_timeout = 100 while cmd_timeout > 0: if self.uart.any(): cmd_output.append(self.uart.readline()) if debug: print("%8i - RX: %s" % (elapsed_micros(start), str(cmd_output[-1]))) if cmd_output[-1].rstrip() == b'OK': if debug: print("%8i - 'OK' received!" % (elapsed_micros(start))) okay = True delay(10) cmd_timeout -= 1 if cmd_timeout == 0 and len(cmd_output) == 0: if debug == True: print("%8i - RX timeout of answer after sending AT command!" % (elapsed_micros(start))) else: print("RX timeout of answer after sending AT command!") # read output if present while self.uart.any(): cmd_output.append(self.uart.readline()) if debug: print("%8i - RX: %s" % (elapsed_micros(start), str(cmd_output[-1]))) if cmd_output[-1].rstrip() == b'OK': if debug: print("%8i - 'OK' received!" % (elapsed_micros(start))) okay = True # handle output of AT command if len(cmd_output) > 0: if cmd_output[-1].rstrip() == b'ERROR': raise CommandError('Command error!') elif cmd_output[-1].rstrip() == b'OK': okay = True elif not okay: # some long running commands do not return OK in case of success # and/or take some time to yield all output. if timeout == 0: cmd_timeout = 300 else: if debug: print("%8i - Using RX timeout of %i ms" % (elapsed_micros(start), timeout)) cmd_timeout = timeout / 10 while cmd_timeout > 0: delay(10) if self.uart.any(): cmd_output.append(self.uart.readline()) if debug: print("%8i - RX: %s" % (elapsed_micros(start), str(cmd_output[-1]))) if cmd_output[-1].rstrip() == b'OK': okay = True break elif cmd_output[-1].rstrip() == b'FAIL': raise CommandFailure() cmd_timeout -= 1 if not okay and cmd_timeout == 0 and debug: print("%8i - RX-Timeout occured and no 'OK' received!" % (elapsed_micros(start))) return cmd_output @classmethod def _join_args(cls, *args, debug=True): """Joins all given arguments as the ESP8266 needs them for the argument string in a 'set' type command. Strings must be quoted using '"' and no spaces outside of quoted srrings are allowed.""" while type(args[0]) is tuple: if len(args) == 1: args = args[0] if debug: print(args) str_args = [] for arg in args: if type(arg) is str: str_args.append('"' + arg + '"') elif type(arg) is bytes: str_args.append(arg.decode()) elif type(arg) is bool: str_args.append(str(int(arg))) else: str_args.append(str(arg)) if debug: print(str_args) return ','.join(str_args).encode() @classmethod def _parse_accesspoint_str(cls, ap_str): """Parse an accesspoint string description into a hashmap containing its parameters. Returns None if string could not be split into 3 or 5 fields.""" if type(ap_str) is str: ap_str = ap_str.encode() ap_params = ap_str.split(b',') if len(ap_params) == 5: (enc_mode, ssid, rssi, mac, channel) = ap_params ap = { 'encryption_protocol': int(enc_mode), 'ssid': ssid, 'rssi': int(rssi), 'mac': mac, 'channel': int(channel) } elif len(ap_params) == 3: (enc_mode, ssid, rssi) = ap_params ap = { 'encryption_protocol': int(enc_mode), 'ssid': ssid, 'rssi': int(rssi), } else: ap = None return ap ''' @classmethod def _parse_station_ip(string) if type(string) is str: return string else: return None ''' def _query_command(self, cmd, timeout=0, debug=False): """Sends a 'query' type command and return the relevant output line, containing the queried parameter.""" return self._send_command(cmd + b'?', timeout=timeout, debug=debug)[1].rstrip() def _set_command(self, cmd, *args, timeout=0, debug=False): """Send a 'set' type command and return all lines of the output which are not command echo and status codes. This type of AT command usually does not return output except the echo and 'OK' or 'ERROR'. These are not returned by this method. So usually the result of this methid must be an empty list!""" return self._send_command(cmd + b'=' + ESP8266._join_args(args, debug=debug), timeout=timeout, debug=debug)[1:-2] def _execute_command(self, cmd, timeout=0, debug=False): """Send an 'execute' type command and return all lines of the output which are not command echo and status codes.""" return self._send_command(cmd, timeout=timeout, debug=debug)[1:-2] def test(self, debug=False): """Test the AT command interface.""" return self._execute_command(CMDS_GENERIC['TEST_AT'], debug=debug) == [] def version(self, debug=False): """Test the AT command interface.""" return self._execute_command(CMDS_GENERIC['VERSION_INFO'], debug=debug) == [] def reset(self, debug=False): """Reset the module and read the boot message. ToDo: Interpret the boot message and do something reasonable with it, if possible.""" boot_log = [] if debug: start = micros() self._execute_command(CMDS_GENERIC['RESET'], debug=debug) # wait for module to boot and messages appearing on self.uart timeout = 300 while not self.uart.any() and timeout > 0: delay(10) timeout -= 1 if debug and timeout == 0: print("%8i - RX timeout occured!" % (elapsed_micros(start))) # wait for messages to finish timeout = 300 while timeout > 0: if self.uart.any(): boot_log.append(self.uart.readline()) if debug: print("%8i - RX: %s" % (elapsed_micros(start), str(boot_log[-1]))) delay(20) timeout -= 1 if debug and timeout == 0: print("%8i - RTimeout occured while waiting for module to boot!" % (elapsed_micros(start))) return boot_log[-1].rstrip() == b'ready' def get_mode(self): """Returns the mode the ESP WIFI is in: 1: station mode 2: accesspoint mode 3: accesspoint and station mode Check the hashmap esp8266.WIFI_MODES for a name lookup. Raises an UnknownWIFIModeError if the mode was not a valid or unknown. """ mode = int(self._query_command(CMDS_WIFI['MODE']).split(b':')[1]) if mode in WIFI_MODES.keys(): return mode else: raise UnknownWIFIModeError("Mode '%s' not known!" % mode) def set_mode(self, mode, debug=False): """Set the given WIFI mode. Raises UnknownWIFIModeError in case of unknown mode.""" if mode not in WIFI_MODES.keys(): raise UnknownWIFIModeError("Mode '%s' not known!" % mode) return self._set_command(CMDS_WIFI['MODE'], mode, debug=debug) def get_accesspoint(self, debug=False): """Read the SSID of the currently joined access point. The SSID 'No AP' tells us that we are not connected to an access point!""" answer = self._query_command(CMDS_WIFI["CONNECT"], debug=debug) #print("Answer: " + str(answer)) if answer == b'No AP': result = None else: result = answer.split(b'+' + CMDS_WIFI['CONNECT'][3:] + b':')[1][1:-1] return result def connect(self, ssid, psk, debug=False): """Tries to connect to a WIFI network using the given SSID and pre shared key (PSK). Uses a 20 second timeout for the connect command. Bugs: AT firmware v0.21 has a bug to only join a WIFI which SSID is 10 characters long.""" self._set_command(CMDS_WIFI['CONNECT'], ssid, psk, debug=debug, timeout=20000) def disconnect(self, debug=False): """Tries to connect to a WIFI network using the given SSID and pre shared key (PSK).""" return self._execute_command(CMDS_WIFI['DISCONNECT'], debug=debug) == [] @classmethod def _parse_list_ap_results(cls, ap_scan_results): aps = [] for ap in ap_scan_results: try: ap_str = ap.rstrip().split(CMDS_WIFI['LIST_APS'][-4:] + b':')[1].decode()[1:-1] except IndexError: # Catching this exception means the line in scan result # was probably rubbish continue # parsing the ap_str may not work because of rubbish strings # returned from the AT command. None is returned in this case. ap = ESP8266._parse_accesspoint_str(ap_str) if ap: aps.append(ap) return aps def list_all_accesspoints(self, debug=False): """List all available access points. TODO: The IoT AT firmware 0.9.5 seems to sporadically yield rubbish or mangled AP-strings. Check needed!""" return ESP8266._parse_list_ap_results( self._execute_command(CMDS_WIFI['LIST_APS'], debug=debug)) def list_accesspoints(self, *args): """List accesspoint matching the parameters given by the argument list. The arguments may be of the types string or integer. Strings can describe MAC adddresses or SSIDs while the integers refer to channel names.""" return ESP8266._parse_list_ap_results( self._set_command(CMDS_WIFI['LIST_APS'], args)) def set_accesspoint_config(self, ssid, password, channel, encrypt_proto, debug=False): """Configure the parameters for the accesspoint mode. The module must be in access point mode for this to work. After setting the parameters the module is reset to activate them. The password must be at least 8 characters long up to a maximum of 64 characters. WEP is not allowed to be an encryption protocol. Raises CommandFailure in case the WIFI mode is not set to mode 2 (access point) or 3 (access point and station) or the WIFI parameters are not valid.""" if self.get_mode() not in (2, 3): raise CommandFailure('WIFI not set to an access point mode!') if type(ssid) is not str: raise CommandFailure('SSID must be of type str!') if type(password) is not str: raise CommandFailure('Password must be of type str!') if len(password) > 64 or len(password) < 8: raise CommandFailure('Wrong password length (8..64)!') if channel not in range(1, 15) and type(channel) is not int: raise CommandFailure('Invalid WIFI channel!') if encrypt_proto not in (0, 2, 3, 4) or type(encrypt_proto) is not int: raise CommandFailure('Invalid encryption protocol!') self._set_command(CMDS_WIFI['AP_SET_PARAMS'], ssid, password, channel, encrypt_proto, debug=debug) self.reset() def get_accesspoint_config(self): """Reads the current access point configuration. The module must be in an acces point mode to work. Returns a hashmap containing the access point parameters. Raises CommandFailure in case of wrong WIFI mode set.""" if self.get_mode() not in (2, 3): raise CommandFailure('WIFI not set to an access point mode!') (ssid, password, channel, encryption_protocol) = self._query_command( CMDS_WIFI['AP_SET_PARAMS'], debug=False).split(b':')[1].split(b',') return { 'ssid': ssid, 'password': password, 'channel': int(channel), 'encryption_protocol': int(encryption_protocol) } def list_stations(self): """List IPs of stations which are connected to the access point. ToDo: Parse result and return python list of IPs (as str).""" return self._execute_command(CMDS_WIFI['AP_LIST_STATIONS'], debug=False) def set_dhcp_config(self, mode, status, debug=False): """Set the DHCP configuration for a specific mode. Oddities: The mode seems not to be the WIFI mode known from the methods set_mode() and get_mode(). The mode are as follows according to the Esspressif documentation: 0: access point (softAP) 1: station 2: access point and station The second argument (status) is strange as well: 0: enable 1: disable """ # Invert status to make the call to this methid reasonable. if type(status) is int: status = bool(status) if type(status) is bool: status = not status return self._set_command(CMDS_WIFI['DHCP_CONFIG'], mode, status, debug=debug) def set_autoconnect(self, autoconnect, debug=False): """Set if the module should connnect to an access point on startup.""" return self._set_command(CMDS_WIFI['SET_AUTOCONNECT'], autoconnect, debug=debug) def get_station_ip(self, debug=False): """get the IP address of the module in station mode. The IP address must be given as a string. No check on the correctness of the IP address is made.""" return self._query_command(CMDS_WIFI['SET_STATION_IP'], debug=debug) def set_station_ip(self, ip_str, debug=False): """Set the IP address of the module in station mode. The IP address must be given as a string. No check on the correctness of the IP address is made.""" return self._set_command(CMDS_WIFI['SET_STATION_IP'], ip_str, debug=debug) def get_accesspoint_ip(self, debug=False): """get the IP address of the module in access point mode. The IP address must be given as a string. No check on the correctness of the IP address is made.""" return self._query_command(CMDS_WIFI['SET_AP_IP'], debug=debug) def set_accesspoint_ip(self, ip_str, debug=False): """Set the IP address of the module in access point mode. The IP address must be given as a string. No check on the correctness of the IP address is made.""" return self._set_command(CMDS_WIFI['SET_AP_IP'], ip_str, debug=debug) def get_connection_status(self): """Get connection information. ToDo: Parse returned data and return python data structure.""" return self._execute_command(CMDS_IP['STATUS']) def start_connection(self, protocol, dest_ip, dest_port, debug=False): """Start a TCP or UDP connection. ToDo: Implement MUX mode. Currently only single connection mode is supported!""" self._set_command(CMDS_IP['START'], protocol, dest_ip, dest_port, debug=debug) def send(self, data, debug=False): """Send data over the current connection.""" self._set_command(CMDS_IP['SEND'], len(data), debug=debug) print(b'>' + data) self.uart.write(data) def ping(self, destination, debug=False): """Ping the destination address or hostname.""" return self._set_command(CMDS_IP['PING'], destination, debug=debug)
#create switch object big_red_button = Switch() big_red_button.callback(start) finished = False ######################### # Main Loop # ######################### while finished == False: #While loop that loops forever if hc12.any(): data = hc12.readline() data = data.decode('utf-8') dataArray = data.split(',') #Split it into an array called dataArray if dataArray[0] == 'end': green.off() sleep(0.5) green.on() sleep(0.5) green.off() finished == True elif len(dataArray) == 6: tagx = dataArray[0] temp = dataArray[1] pres = dataArray[2]
# simple test of reading UART 1 on Pico from pyb import UART # speed is set in ucenter for uart1probably 115200? ser = UART(1,9600) # hopefully read nmea header while 1: s = ser.readline() print s
class RaspberryPi: rx_raw_line = b'' tx_raw_line = b'' rx_split = b'#' tx_split = b'*' us100 = collections.OrderedDict() us100['us1'] = None us100['us2'] = None us100['us3'] = None us100['us4'] = None data = collections.OrderedDict() data['us100'] = us100 data['scale'] = {'weight': None, 'offset': None} data['hall'] = None result = {'code': 401, 'data': {}, 'msg': ''} task = {'id': None, 'result': result} def __init__(self, port): self.uart = UART(port, 921600) # TX PA9 RX PA10 self.uart.init(921600, bits=8, parity=None, stop=1, timeout=0, read_buf_len=512) def __repr__(self): print(self.uart) return 'STM32 & RaspberryPi Communication via Uart' def writeline(self, data): result = json.dumps(data).encode('utf-8', 'strict') self.tx_raw_line = b'%s%s%d\r\n' % (result, self.tx_split, binascii.crc32(result)) self.uart.write(self.tx_raw_line) def write_task_result(self): self.writeline(data=self.task) def parseData(self, data): if 'id' and 'func' and 'kwargs' in data: if self.task['id'] == data['id']: self.write_task_result() else: self.result.clear() self.task['id'] = data['id'] return data['func'], data['kwargs'] def readline(self): if self.uart.any(): self.rx_raw_line = self.uart.readline() if self.rx_raw_line.rfind(self.rx_split) > 0: raw = self.rx_raw_line.rsplit(self.rx_split, 1) crc32 = int(raw[1].replace(b'\r\n', b'')) if crc32 == binascii.crc32(raw[0]): result = json.loads(raw[0].decode('utf-8', 'strict')) return self.parseData(result) print(self.rx_raw_line)
def find_max(blobs):#return the max blob max_size=0 for blob in blobs: if blob.pixels() > max_size: max_blob=blob max_size = blob.pixels() return max_blob def send_data_packet(x, y):#串口发送函数定义 temp = struct.pack("<bbii", #格式为俩个字符俩个整型 0xAA, #帧头1 0xAE, #帧头2 int(x), # up sample by 4 #数据1 int(y)) # up sample by 4 #数据2 uart.write(temp) #串口发送 print(x,y) def compareBlob(blob1,blob2):#比较色块后返回最大值 tmp = blob1.pixels() - blob2.pixels() if tmp == 0: return 0; elif tmp > 0: return 1; else: return -1; threshold_index = 0 #红绿蓝色环阈值 objthresholds=[(42, 76, 5, 35, -3, 88), (53, 66, -23, -5, 17, -5), (49, 61, -12, 18, -27, -3)] graythreshold=[(100,255)]#二值化阈值 sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.skip_frames(time = 1000) sensor.set_auto_gain(False) # must be turned off for color tracking sensor.set_auto_whitebal(False) # must be turned off for color tracking clock = time.clock() A=7 #串口接收执行代码初始值 i= 1 #二维码发送触发代码值初始值 r=0 red_threshold_01 = (29, 47, 50, 72, 34, 57)#红色色块阈值 green_threshold_01=(18, 72, -60, -26, 16, 43)#绿色色块阈值 blue_threshold_01=(8, 58, -17, 23, -54, -16) #蓝色色块阈值 uart =UART(3,115200) while(True): clock.tick() img = sensor.snapshot() if( uart.any() ): print("range: mm ") r=uart.readline() print(r) if r==b'1': A=1 print('A=1') if r==b'2': A=2 print('A=2') if r==b'3': A=3 print('A=3') if r==b'4': A=4 print('A=4') if r==b'5': A=5 print('A=5') if r==b'6': A=6 print('A=6') if r==b'7': A=7 print('A=6') #else: # A=0 if i==1:#二维码识别 img.lens_corr(1.8) # strength of 1.8 is good for the 2.8mm lens. for code in img.find_qrcodes(): print(code.payload()) led = pyb.LED(1) led.on() output_str=code.payload() uart.write(output_str+'\r\n') #print('send:',output_str) led.off() i=1 if(A==1):#红色色块识别 blobs1= img.find_blobs([red_threshold_01],area_threshold=150) if blobs1: #如果找到了目标颜色 led = pyb.LED(1) led.on() max_blob=find_max(blobs1) print('sum :', len(blobs1)) img.draw_rectangle(max_blob.rect()) img.draw_cross(max_blob.cx(), max_blob.cy()) send_data_packet(max_blob.cx()-120,max_blob.cy()-160) led.off() #output_str=json.dumps([max_blob.cx(),max_blob.cy()]) #方式2 print('send red blob') #uart.write(output_str+'\r\n') if(A==2):#绿色色块识别 blobs2=img.find_blobs([green_threshold_01],area_threshold=150) if blobs2: led = pyb.LED(2) led.on() #如果找到了目标颜色 max_blob=find_max(blobs2) print('sum :', len(blobs2)) img.draw_rectangle(max_blob.rect()) img.draw_cross(max_blob.cx(), max_blob.cy()) send_data_packet(max_blob.cx()-120,max_blob.cy()-160) led.off() #output_str=json.dumps([max_blob.cx(),max_blob.cy()]) #方式2 print('send green blob') if(A==3):#蓝色色块识别 blobs3=img.find_blobs([blue_threshold_01],area_threshold=150) if blobs3: led = pyb.LED(3) led.on() #如果找到了目标颜色 max_blob=find_max(blobs3) #print('sum :', len(blobs3)) img.draw_rectangle(max_blob.rect()) img.draw_cross(max_blob.cx(), max_blob.cy()) send_data_packet(max_blob.cx()-120,max_blob.cy()-160) led.off() #output_str=json.dumps([max_blob.cx(),max_blob.cy()]) #方式2 print('send blue blob') if(A==4):#红色色环识别 img.binary([objthresholds[0]]) img.dilate(2) blobs=img.find_blobs(graythreshold,pixels_threshold=2525,area_threashold=1600,merge=True) if blobs: led = pyb.LED(1) led.on() bigBlob=blobs[0] #print('1') for blob in blobs: if compareBlob(bigBlob,blob) == -1: bigBlob=blob img.draw_rectangle(bigBlob.rect()) #print(bigBlob.cx(),bigBlob.cy()) #output_str="[%d,%d]" % (bigBlob.cx(),bigBlob.cy()) #output_str=json.dumps([judge(bigBlob.cx()),judge(bigBlob.cy()),bigBlob.cx(),bigBlob.cy()]) #uart.write(output_str+'\r\n') send_data_packet(bigBlob.cx()-120,bigBlob.cy()-160) led.off() #print('you send:',bigBlob.cx()-120) #uart.write(data_out) if(A==5):#绿色色环识别 img.binary([objthresholds[1]]) img.bilateral(2, color_sigma=0.1, space_sigma=1) img.dilate(3) blobs=img.find_blobs(graythreshold,pixels_threshold=2025,area_threashold=1600,merge=True) if len(blobs)==1: led = pyb.LED(2) led.on() bigBlob=blobs[0] for blob in blobs: if compareBlob(bigBlob,blob)==-1: bigBlob=blob img.draw_rectangle(bigBlob.rect()) #output_str=json.dumps([judge(bigBlob.cx()),judge(bigBlob.cy()),bigBlob.cx(),bigBlob.cy()]) send_data_packet(bigBlob.cx()-120,bigBlob.cy()-160) led.off() # uart.write(data_out) #print(data_out) if(A==6):#蓝色色环识别 img.binary([objthresholds[2]]) img.bilateral(2, color_sigma=0.1, space_sigma=1) img.dilate(3) blobs=img.find_blobs(graythreshold,pixels_threshold=2025,area_threashold=1600,merge=True) if len(blobs)==1: led = pyb.LED(2) led.on() bigBlob=blobs[0] for blob in blobs: if compareBlob(bigBlob,blob)==-1: bigBlob=blob img.draw_rectangle(bigBlob.rect()) #output_str=json.dumps([judge(bigBlob.cx()),judge(bigBlob.cy()),bigBlob.cx(),bigBlob.cy()]) send_data_packet(bigBlob.cx()-120,bigBlob.cy()-160) led.off() # uart.write(data_out) #print(data_out) if(A==7):#红绿蓝三色块顺序识别 blobs1= img.find_blobs([red_threshold_01],area_threshold=150) blobs2=img.find_blobs([green_threshold_01],area_threshold=150) blobs3=img.find_blobs([blue_threshold_01],area_threshold=150) #if max_blob1.cx()< max_blob2.cx() < max_blob3.cx(): #print('sadf') if blobs1 and blobs2 and blobs3: max_blob1=find_max(blobs1) img.draw_cross(max_blob1.cx(), max_blob1.cy()) max_blob2=find_max(blobs2) img.draw_cross(max_blob2.cx(), max_blob2.cy()) max_blob3=find_max(blobs3) img.draw_cross(max_blob3.cx(), max_blob3.cy()) led = pyb.LED(3) led.on() if max_blob1.cx()< max_blob2.cx() < max_blob3.cx(): output_str="[%d]" % (123) #方式1 uart.write(output_str+'\r\n') if max_blob1.cx() < max_blob3.cx() < max_blob2.cx(): output_str="[%d]" % (132) #方式1 #uart.write('132') uart.write(output_str+'\r\n') if max_blob2.cx() < max_blob1.cx() < max_blob3.cx(): output_str="[%d]" % (213) #方式1 #uart.write('213') uart.write(output_str+'\r\n') if max_blob2.cx()< max_blob3.cx() < max_blob1.cx(): #uart.write('231') output_str="[%d]" % (231) #方式1 uart.write(output_str+'\r\n') if max_blob3.cx() < max_blob2.cx() < max_blob1.cx(): #uart.write('321') output_str="[%d]" % (321) #方式1 uart.write(output_str+'\r\n') if max_blob3.cx()< max_blob1.cx() < max_blob2.cx(): output_str="[%d]" % (312) #uart.write('312') uart.write(output_str+'\r\n') led.off() # uart.write(data_out) #print(clock.fps())
for blob in img.find_blobs([thresholds[threshold_index]], pixels_threshold=200, area_threshold=200, merge=True): # These values depend on the blob not being circular - otherwise they will be shaky. if blob.elongation() > 1: img.draw_edges(blob.min_corners(), color=(255, 0, 0)) img.draw_line(blob.major_axis_line(), color=(0, 255, 0)) img.draw_line(blob.minor_axis_line(), color=(0, 0, 255)) # These values are stable all the time. img.draw_rectangle(blob.rect()) img.draw_cross(blob.cx(), blob.cy()) # Note - the blob rotation is unique to 0-180 only. img.draw_keypoints( [(blob.cx(), blob.cy(), int(math.degrees(blob.rotation())))], size=20) output_str = "[%d,%d]\n" % (blob.cx(), blob.cy()) uart.write(output_str) print(output_str) ch = uart.readline() if ch == b'd': led_Red.on() led_Green.on() led_Blue.on() if ch == b'e': led_Red.off() led_Green.off() led_Blue.off()
def get_gps(): uart = UART(6, 9600) print(uart.readline()) pyb.LED(3).on()
class NBIOT(): def __init__(self, uart_port, uart_baud, retry_time, time_delay): self.modbus = MODBUS() self.nbiot = UART(uart_port,uart_baud,read_buf_len = 512) self.retry_time = retry_time self.time_delay = time_delay def _decode(self,info): try: info = info.decode() except (UnicodeError,AttributeError): return -1 return info def read(self): info = self.nbiot.read() return self._decode(info) def readline(self): info = self.nbiot.readline() return self._decode(info) def clear_buff(self): self.read() def check_sim(self): self.nbiot.write("AT+CIMI\r\n") time.sleep(1) rebound = self.readline() iccid = self.readline() neglect = self.readline() state = self.readline() return iccid,state def check_emei(self): self.nbiot.write("AT+CGSN=1\r\n") time.sleep(1) rebound = self.readline() emei = self.readline() neglect = self.readline() state = self.readline() return emei def check_csq(self): self.nbiot.write("AT+CESQ\r\n") time.sleep(1) rebound = self.readline() cesq = self.readline() neglect = self.readline() state = self.readline() return int(cesq[7:9]),str(state) def create_socket(self): self.nbiot.write("AT+QIOPEN=1,0,\"TCP\",\"115.236.36.53\",506,1234,1\r\n") time.sleep(5) info = self.read() return info def close_socket(self): self.nbiot.write("AT+QICLOSE=0\r\n") time.sleep(5) info = self.read() return info def tcp_receive(self,time_delay = 10): time.sleep(time_delay) rebound = self.readline() nb_state = self.readline() neglect = self.readline() send_state = self.readline() neglect = self.readline() recv_state = self.readline() message = self.nbiot.read() rec_flag = 0 if(rebound != -1): print(rebound[0:len(rebound)-1]) if(nb_state != -1): print(nb_state[0:len(nb_state)-1]) if(send_state != -1): print(send_state[0:len(send_state)-1]) if(recv_state != -1): print(recv_state[0:len(recv_state)-1]) print(message) if(message != -1 and message != None): raw = self.tcp_message(message) print(raw) else: rec_flag = 1 return info,rec_flag def tcp_message(self,message): raw_data = '' for i in range(len(message)): num = int(message[i]) raw_data += str(self.modbus.getid(num))[6:8] return raw_data def tcp_check(self): cur_retry_time = self.retry_time flag = 0 print("SENDING CHECK") while(1): iccid,get_state = str(self.check_sim()) if(get_state.find('OK') != -1): print("CHECK SIM OK") flag = 1 break while(cur_retry_time > 0): cur_retry_time -= 1 get_state = str(self.create_socket()) if(get_state.find('OK') != -1): if(get_state.find('QIOPEN') != -1): print("OPEN TCP OK") flag = 2 break else: time.sleep(self.time_delay) return flag def tcp_test(self): self.close_socket() self.clear_buff() open_state = self.create_socket() print(open_state) self.clear_buff() self.nbiot.write("AT+QISENDEX=0,16,FEFE00000058250400092F0800000A0D\r\n") time.sleep(10) while(1): info,rec_flag = self.tcp_receive() if rec_flag == 1: break else: self.clear_buff() operate_code = info[12:14] if operate_code == '22': info = self.back_signup() self.tcp_send(info) elif operate_code == '10': pass time.sleep(5) self.clear_buff() self.close_socket() self.clear_buff() def tcp_send(self,info): total_len = len(info) real_info = 'AT+QISENDEX=0,' + str(total_len) + str(info) + '\r\n' self.nbiot.write(real_info) def back_signup(self): hex_id = config.id_number hex_iccid = '' hex_emei = '' hex_csq = '' operater_code = 'A214' iccid,_ = self.check_sim() if(iccid != -1): iccid = iccid[0:len(iccid)-2] delta = 20 - len(iccid) for i in range(delta): hex_iccid += '0' for i in range(len(iccid)): hex_iccid += iccid[i] self.clear_buff() emei = self.check_emei() if(emei != -1): emei = iccid[7:len(emei)-2] delta = 10 - len(emei) for i in range(delta): hex_emei += '0' for i in range(len(emei)): hex_emei += emei[i] self.clear_buff() csq,_ = self.check_csq() csq = str(csq) delta = 4 - len(csq) for i in range(delta): hex_csq += '0' for i in range(len(csq)): hex_csq += csq[i] self.clear_buff() info = self.modbus.head + hex_id + operater_code + hex_iccid + hex_emei + hex_csq + self.modbus.tail print(info) time.sleep(5) return info def back_setid(self,info): id_info = info[16:24] config.update_id(id_info)
class NBIOT(): def __init__(self, uart_port, uart_baud, retry_time, time_delay): self.modbus = MODBUS() self.nbiot = UART(uart_port,uart_baud,read_buf_len = 512) self.retry_time = retry_time self.time_delay = time_delay def read(self): info = self.nbiot.read() try: info = info.decode() except (UnicodeError,AttributeError): return -1 return info def readline(self): info = self.nbiot.readline() try: info = info.decode() except (UnicodeError,AttributeError): return -1 return info def clear_buff(self): self.read() def check_sim(self): self.nbiot.write("AT+CIMI\r\n") time.sleep(3) rebound = self.readline() iccid = self.readline() neglect = self.readline() state = self.readline() return str(iccid),str(state) def check_csq(self): self.nbiot.write("AT+CESQ\r\n") time.sleep(3) rebound = self.readline() cesq = self.readline() neglect = self.readline() state = self.readline() return int(cesq[7:9]),str(state) def create_socket(self): self.nbiot.write("AT+QIOPEN=1,0,\"TCP\",\"115.236.36.53\",506,1234,1\r\n") time.sleep(5) # rebound = self.readline() # state = self.readline() # neglect = self.readline() # open_state = self.readline() info = self.read() return info def close_socket(self): ''' Close TCP Socket For 5 seconds to read all buffer. ''' self.nbiot.write("AT+QICLOSE=0\r\n") time.sleep(5) info = self.read() return info def tcp_receive(self,time_delay = 20): time.sleep(time_delay) info = self.read() return info def tcp_message(self,message): raw_data = '' for i in range(len(message)): num = int(message[i]) raw_data += str(self.modbus.getid(num))[6:8] return raw_data def tcp_check(self): cur_retry_time = self.retry_time flag = 0 print("SENDING CHECK") while(1): iccid,get_state = str(self.check_sim()) if(get_state.find('OK') != -1): print("CHECK SIM OK") flag = 1 break while(cur_retry_time > 0): cur_retry_time -= 1 get_state = str(self.create_socket()) if(get_state.find('OK') != -1): if(get_state.find('QIOPEN') != -1): print("OPEN TCP OK") flag = 2 break else: time.sleep(self.time_delay) return flag def tcp_test(self): self.close_socket() self.clear_buff() open_state = self.create_socket() print(open_state) self.clear_buff() self.nbiot.write("AT+QISENDEX=0,16,FEFE00000058250400092F0800000A0D\r\n") time.sleep(10) rebound = self.readline() nb_state = self.readline() neglect = self.readline() send_state = self.readline() neglect = self.readline() recv_state = self.readline() messgae = self.nbiot.read() if(rebound != -1): print(rebound[0:len(rebound)-1]) if(nb_state != -1): print(nb_state[0:len(nb_state)-1]) if(send_state != -1): print(send_state[0:len(send_state)-1]) if(recv_state != -1): print(recv_state[0:len(recv_state)-1]) print(messgae) if(messgae != -1): raw = self.tcp_message(messgae) print(raw) self.clear_buff() self.close_socket() self.clear_buff()
# Object tracking with keypoints example. # Show the camera an object and then run the script. A set of keypoints will be extracted # once and then tracked in the following frames. If you want a new set of keypoints re-run # the script. NOTE: see the docs for arguments to tune find_keypoints and match_keypoints. import sensor, time, image, utime from pyb import UART from pyb import LED #initial the uarm led = LED(3) # Blue led led.toggle() #initial the uart uart = UART(3, 115200) #get the command first, since the arm should change the communication port from main uart to second port flag = uart.readline() while (flag != b'ok\n'): flag = uart.readline() utime.sleep_ms(100) print(flag) #print("done") #set the uarm to the default position utime.sleep_ms(500) uart.write("G0 X250 Y0 Z") uart.write("160 F15000\r\n") utime.sleep_ms(8000) #finish the initialization
# -------------------------------------------------- INIT #initial the uarm led_err = LED(1) #red led_ok = LED(2) # green led_start = LED(3) # Blue led led_start.toggle() if MODE == "arm": #initial the uart uart = UART(3, 115200) #test if the connection is active by a status query uart.write("P2500\r\n") utime.sleep_ms(100) response = uart.readline() if response != b'ok\n': # wait for the arm to get ready (probably needs to switch active uart, send "M2500" command to it from outside) while(response != b'ok\n'): print(response) response = uart.readline() utime.sleep_ms(100) print("RX:" + str(response)) if CAM_POS == "horizontal": start_z = 160 else: start_z = 100 # in vertical pos we need space to move up. #set the uarm to the default position