|
#!/usr/bin/python3 |
|
|
|
"""ESP8266 serial port communication test / notes""" |
|
|
|
from serial import Serial |
|
from time import sleep |
|
import codecs |
|
|
|
# Serial port device where the ESP8266 is connected |
|
PORT = "/dev/ttyUSB1" |
|
|
|
# From http://www.esp8266.com/wiki/doku.php?id=getting-started-with-the-esp8266 |
|
# First, your board might talk at any of several baud rates. The ones to try |
|
# first are 9600 and 115200. Then 57600 and/or 76800 (38400 * 2). Note the noise |
|
# when you reset the device (pull the RST pin to ground) is typically some bootup |
|
# messages at 76800. But there should be a ”ready“ message at the selected baud |
|
# rate if your UART Rx is wired correctly. |
|
BAUD = 9600 |
|
BOOT_BAUD = 115200 |
|
|
|
|
|
def send(port, data): |
|
"""Write data to the given serial port. `data` will be interpreted as an |
|
utf-8 string and encoded as a bytes array, terminated with '\\r\\n'. |
|
This blocks until all data has been send. |
|
""" |
|
n = port.write(data.encode("utf-8")+b"\r\n") |
|
port.flush() |
|
return n |
|
|
|
|
|
def receive(port, pause=0.1): |
|
"""Wait a bit and receive data from `port`.""" |
|
sleep(pause) |
|
x = port.in_waiting |
|
res = b"" |
|
while x: |
|
res += port.read(x) |
|
sleep(pause) |
|
x = port.in_waiting |
|
return res |
|
|
|
|
|
def errorbytes2hexstr(e): |
|
"""Handler for UnicodeDecodeError convert bytes to python style string of |
|
hex numbers (every number representing one byte prefixed with '\\x'. |
|
""" |
|
data = e.object[e.start:e.end] |
|
res = "" |
|
for b in data: |
|
res += "\\x" + "{:02x}".format(b).upper() |
|
|
|
return (res, e.end) |
|
|
|
|
|
codecs.register_error('errorbytes2hexstr', errorbytes2hexstr) |
|
|
|
def printlines(data): |
|
string = data.decode('ascii', 'errorbytes2hexstr') |
|
for line in string.splitlines(): |
|
print("> {}".format(line)) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
port = Serial(port=PORT, baudrate=BAUD) |
|
port.reset_output_buffer() |
|
|
|
print("PINGING esp8266...") |
|
send(port, "AT") # pinging esp8266 |
|
printlines(receive(port)) |
|
|
|
print("\nRESETTING esp8266...") |
|
send(port, "AT+RST") # reset esp8266 |
|
printlines(receive(port, pause=0.03)) |
|
port.baudrate = BOOT_BAUD |
|
sleep(2) # esp8266 needs some time for booting |
|
printlines(receive(port)) |
|
port.baudrate = BAUD |
|
|
|
print("\nASKING FOR MODE...") |
|
send(port, "AT+CWMODE?"); # query esp8266's mode |
|
printlines(receive(port)) |
|
|
|
port.close() |