sender.py
Code: Select all
import network
import espnow
import utime
peer = b'\x08:\xf2\xab\xe2\x0c' # test receiver STA-mode
e = espnow.ESPNow()
e.active(True)
w0 = network.WLAN(network.STA_IF)
w0.active(True) # set channel will fail unless Active>
w0.connect('HUAWEI-E8231-7bd5', 'my_password')
while not w0.isconnected(): # wait until connected...
utime.sleep(1)
print ('connected')
w0.config(ps_mode=network.WIFI_PS_NONE) # disable power saving
e.add_peer(peer)
if not e.send(peer, b'Water tank level alarm', True):
print ('Msg send failed')
else:
print ('Msg send succeeded')
print('Send me messages at:', w0.config('mac'))
# shut-down, so that a CTRL-D in rshell works
w0.disconnect()
w0.active(False)
e.active(False)
Code: Select all
# receiver.py for ESPNow testing.
import network
import espnow
import utime
import machine
import my_umail
from mail_functions import send_alarm
CYCLE_TIME = 60 # seconds
REBOOT_DELAY = 5 # seconds
remote_mac = b'x!\x84{\xde\x80' # STA-mode
def reboot(delay = REBOOT_DELAY):
# print a message and give time for user to pre-empt reboot
# in case we are in a (battery consuming) boot loop
print (f'Rebooting device in {delay} seconds (Ctrl-C to es>
# or just machine.deepsleep(delay) or lightsleep()
utime.sleep(delay)
machine.reset()
try:
print ('you have 5 seconds to do Ctrl-C if you want to edi>
utime.sleep(5)
e0 = espnow.ESPNow()
e0.active(True)
w0 = network.WLAN(network.STA_IF)
w0.active(True)
w0.connect('HUAWEI-E8231-7bd5', 'my_password')
while not w0.isconnected(): # Wait until connected
print ('trying to connect')
utime.sleep(1)
w0.config(ps_mode=network.WIFI_PS_NONE) # ..then disable power saving
print (w0.config('mac'))
# these functions generate exceptions on error - always return None>
e0.config(timeout = (CYCLE_TIME) * 1000)
e0.add_peer(remote_mac)
except KeyboardInterrupt as err:
raise err # use Ctrl-C to exit to micropython repl
except Exception as err:
print ('Error initialising espnow:', err)
reboot()
while True:
try:
print ('waiting for a msg from the remote')
for mac, msg in e0:
print (str(mac))
if mac == remote_mac:
msg = msg.decode('utf-8')
print (msg)
# send_alarm(msg)
break # out of the while loop!!
elif mac == None:
print ('no peers found')
utime.sleep(5)
break
else:
print ('Recv from {}: "{}"'.format(mac, msg))
utime.sleep(5)
break
except KeyboardInterrupt as err:
raise err # use Ctrl-C to exit to micropython repl
except Exception as err:
# all other exceptions cause a reboot
print ('Error during execution:', err)
reboot()
Code: Select all
w0 = network.WLAN(network.STA_IF)
w0.active(True) # set channel will fail unless Active>
w0.connect('HUAWEI-E8231-7bd5', 'my_password')
while not w0.isconnected(): # wait until connected...
utime.sleep(1)
print ('connected')
w0.config(ps_mode=network.WIFI_PS_NONE) # disable power saving