pastebin - collaborative debugging tool
micropython.kpaste.net RSS


AT Commands v0.001
Posted by Anonymous on Sat 28th May 2022 02:33
raw | new post

  1. # this code turns micropython into a AT command set interpreter on uart1
  2.  
  3. import os
  4. import time
  5. import machine
  6. import random
  7.  
  8. swVersion = "+AT Commands on MicroPython v0.001"
  9. print("uart1 9600 bps test")
  10. print(os.uname())
  11.  
  12. uart = machine.UART(1, 9600)                         # init with given baudrate
  13. #uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters
  14.  
  15. uart.write('I am pi pico running '+str(os.uname())+"\r\n")   # write the 3 characters
  16.  
  17. serialBuffer = bytearray(512)
  18. serialBufferPointer = 0
  19. serialBufferLen = len(serialBuffer)
  20.  
  21. incomingCommand = ""
  22.  
  23.  
  24. knownCommands = {
  25. "+ID":"id",
  26. "+INFO":"info",
  27. "+CCLK":"cclk",
  28. "+NVRAM_":"nvram", #at+nvram22=01 02 03 04 nv ram starting at byte 22 will be 1,2,3,4
  29. "+NVRAM__":"nvram", #at+nvram22? or at+nvram22=? should return value at byte 22
  30. "+NVRAM___":"nvram",
  31. "+NVDUMP":"nvdump",
  32. "+RAND":"make_rand",
  33. "?":"help"
  34. }
  35.  
  36. def help(arguments):
  37.     uartWriter("+Known Commands")
  38.     for oneCommand in knownCommands:
  39.         uartWriter(oneCommand)
  40.  
  41. def make_rand(arguments):
  42.     uartWriter("+Arguments["+arguments+"]")
  43.     uartWriter(arguments[1:])
  44.     maxValue = getInt(arguments)
  45.     uartWriter("+MaxValue = "+str(maxValue))
  46.     uartWriter("+MinValue = 0")
  47.     uartWriter("+Rand = "+ str(random.randint(0, maxValue)))
  48.  
  49.     return True
  50.  
  51. def id(arguments):
  52.     global uart, swVersion
  53.     print("id requested"+str(arguments))
  54.     uartWriter(swVersion)
  55.     return True
  56.  
  57. def info(arguments):
  58.     print("info requested")
  59.     uartWriter("Is this the info you want?")
  60.     return True
  61.  
  62. def cclk(arguments):
  63.     print("time requested")
  64.     timeNow = "+" + str(time.ticks_us())
  65.     uartWriter(timeNow)
  66.     return True
  67.  
  68.  
  69. #####################
  70. def hexDumpStr(theStr):
  71.     #print("hexdump_type",type(theStr))
  72.     for character in theStr:
  73.         print(hex(ord(character)),end='')
  74.     print()
  75.    
  76. def getInt(inStrVal):
  77.     #hexDumpStr(inStrVal)
  78.     retInt = -1
  79.     try:
  80.         retInt = int((inStrVal))
  81.     except:
  82.         retInt = -1
  83.         print("Error converting Int["+str(inStrVal)+"]")
  84.     return retInt
  85.  
  86. def serialBufferToString():
  87.     global serialBuffer, serialBufferPointer
  88.     returnValue = ""
  89.     i = 0
  90.     for i in range(0,serialBufferPointer):
  91.         # print("i",i,"=",chr(serialBuffer[i]))
  92.         returnValue += chr(serialBuffer[i])
  93.     return returnValue.upper()
  94.        
  95. def serialBufferFlush():
  96.     global serialBuffer, serialBufferPointer
  97.     i = 0
  98.     while i < len(serialBuffer):
  99.         serialBuffer[i] = 0x00
  100.         i += 1
  101.     serialBufferPointer = 0
  102.  
  103. def parseIncomingTry(theCommand):
  104.     retV = False
  105.     try:
  106.         retV = parseIncoming(theCommand)
  107.     except:
  108.         print("Error processing incoming")
  109.         return False
  110.     return retV
  111.  
  112. def parseIncoming(theCommand):
  113.     global knownCommands
  114.     #print("type_theCommand",type(theCommand))
  115.  
  116.     if (len(theCommand)<3):
  117.         return False
  118.     #print ("theCommand["+theCommand+"]")
  119.    
  120.     aMatch = 0
  121.     doCommand=""
  122.     arguments=""
  123.    
  124.     for i in knownCommands:
  125.         #print("i=",i,"func=",knownCommands[i])
  126.         aMatch = compareCommand(i,theCommand)
  127.         if (aMatch >= 1):
  128.             doCommand = knownCommands[i]
  129.             if (len(i)+1 >= len(theCommand) ):
  130.                     arguments=""
  131.             else:
  132.                 arguments = theCommand[len(i)+3:]
  133.                 arguments = arguments.rstrip()
  134.                 if (aMatch == 2):
  135.                     arguments = theCommand
  136.             #print("command Match",i,"doCommand",doCommand,"aMatch",aMatch)
  137.     if len(doCommand) > 0:
  138.         globals()[doCommand](arguments)
  139.     else:
  140.         print("ERROR")
  141.         return False
  142.    
  143.     return True
  144.  
  145. def compareCommand(needle,haystack):
  146.     # _ underscore is a wildcard for numeric values
  147.     retV = 0
  148.     wildCardMatch = 0
  149.     #print("needle:",needle)
  150.     #print("haystack:",haystack)
  151.     startPos = 2 # ignore the AT and any space
  152.     #print("startPos:",startPos)
  153.     compareLen = len(needle)
  154.     #print("compareLen",compareLen)
  155.     for i in range(0,compareLen):
  156.         #print("i=",i)
  157.         if (i+startPos >= len(haystack)):
  158.             haystackChar = "*"
  159.         else:
  160.             haystackChar = haystack[i+startPos]
  161.         needleChar = needle[i]
  162.         #print("needleChar["+needleChar+"] haystackChar["+haystackChar+"]")
  163.         if ( needleChar == haystackChar):
  164.             retV = retV +1
  165.             #print("hit")
  166.         else:
  167.             #print("hs["+haystack[i+startPos]+"]")
  168.             if (needle[i]=='_' and haystackChar.isdigit() ): #  >='0' and haystackChar <='9'):
  169.                 retV = retV + 1
  170.                 wildCardMatch = 1
  171.  
  172.     #print("compareLen",compareLen,"retV",retV)
  173.     if (compareLen==retV):
  174.         retV=1
  175.     else:
  176.         retV=0
  177.  
  178.     if (retV == 1) and (wildCardMatch ==1):
  179.         retV = 2
  180.        
  181.     return retV
  182.  
  183. #def processCommand(inCommand):
  184. #    procCmdRet = "OK\r\n"
  185. #    return procCmdRet
  186.  
  187. def uartWriter(inStr):
  188.     global uart
  189.     uart.write(str(inStr))
  190.     uart.write("\r\n")
  191.    
  192.  
  193. print(swVersion)
  194. uartWriter("+BOOT")
  195. uartWriter(swVersion)
  196. uartWriter("OK")
  197.  
  198.  
  199. while True:
  200.     while uart.any():
  201.         inByte = uart.read(1)
  202.         serialBuffer[serialBufferPointer] = inByte[0]
  203.         serialBufferPointer += 1
  204.         if (inByte[0] == 0x0D or serialBufferPointer >= serialBufferLen):
  205.             uart.write("\r\n") # flush output to terminal
  206.             print("") # flush local output
  207.             #print("==============CR============")
  208.             #incomingCommand = serialBuffer.decode()
  209.             incomingCommand = serialBufferToString()
  210.             serialBufferFlush()
  211.             #print("incoming Command["+incomingCommand+"]")
  212.             #procCmdRet = processCommand(incomingCommand)
  213.            
  214.             #procCmdRet = parseIncoming(incomingCommand)
  215.             procCmdRet = parseIncomingTry(incomingCommand)
  216.             if (procCmdRet == 1):
  217.                 uart.write("OK\r\n")
  218.             else:
  219.                 uart.write("ERROR\r\n")
  220.            
  221.          
  222.         print(chr(inByte[0]),end='')
  223.         #print("type inByte",type(inByte),"hex",hex(inByte[0]))
  224.         uart.write(chr(inByte[0]))
  225.         #print("serialBuffer",serialBuffer)

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with {%HIGHLIGHT}




All content is user-submitted.
The administrators of this site (kpaste.net) are not responsible for their content.
Abuse reports should be emailed to us at