esp32 python上位機(命令列)
阿新 • • 發佈:2021-10-19
import os import sys import tty import termios import serial import serial.tools.list_ports class ser_conf: def port_choose(self): port_list = list(serial.tools.list_ports.comports()) if len(port_list)!=0: print(type(port_list)) print(len(port_list)) for p in port_list: print(p.device) port = input("please choose which port to open:\n") print(port) # port = int(port) print(port_list[int(port)].device) print(type(port_list[int(port)].device)) return port_list[int(port)].device #return p.device print("can't find port!\n") return False class str_conf: def get_str(self): # 類裡的函式不加self會報錯 cmd = input("please input cmd:\n") len_str = len(cmd) return cmd,len_str def which_str(self): tuple = self.get_str() print("string is %s,len is %d\n" %(tuple[0],tuple[1])) # 輸出字串和格式化字串之間不能有逗號 if __name__ == '__main__': #sudo chmod 666 /dev/ttyUSB0 ser_conf = ser_conf() ser = serial.Serial(ser_conf.port_choose(),115200) str_conf=str_conf() if (ser.isOpen): print(ser.port) string="" while True: #string=string.join(str(ser.read())) string=string.join('%s' %ser.readline()) print(string) if "which ssid choose" in string: cmd = input("please choose ssid:\n") ser.write(cmd.encode()) elif "print password" in string: cmd = input("please input password\n") ser.write(cmd.encode()) elif "got ip" in string: ser.close() print("serial has closed\n") string='' #str_conf.which_str()