peterhinch / micropython-mqtt

A 'resilient' asynchronous MQTT driver. Recovers from WiFi and broker outages.
MIT License
582 stars 127 forks source link

await client.connect() error in documented tutorial #15

Closed RobinMosedale closed 5 years ago

RobinMosedale commented 5 years ago

https://www.raspberrypi.org/forums/viewtopic.php?f=32&t=243760 refers.

"async def main(client): await client.connect() n=0 " fails with syntax error:-

"import asyncmqtttest.py Traceback (most recent call last): File "", line 1, in File "asyncmqtttest.py", line 39 SyntaxError: invalid syntax"

Not good enough to post unvalidated code or faulty undocumented implementation.

peterhinch commented 5 years ago

I cannot replicate this fault. The code posted does not produce a syntax error here.

rroemhild commented 5 years ago

I can confirm that your code has no syntax error. You'll get this error when you run your code with python2, because python2 has no await keyword but that's the only syntax problem I can see.

peterhinch commented 5 years ago

This library is intended to run under MicroPython on a microcontroller with WiFi capability: namely ESP8266, ESP32 or Pyboard D.

RobinMosedale commented 5 years ago

It is micropython on esp32, with the modules loaded as indicated in your guide.

I’ll double check versions of modules later

From: Peter Hinch Sent: Saturday, July 20, 2019 11:00 AM To: peterhinch/micropython-mqtt Cc: RobinMosedale ; Author Subject: Re: [peterhinch/micropython-mqtt] await client.connect() error in documented tutorial (#15)

This library is intended to run under MicroPython on a microcontroller with WiFi capability: namely ESP8266, ESP32 or Pyboard D.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.

Regards Robin

RobinMosedale commented 5 years ago

Peter,

thank you for your time.

It seems a hard syntax error on mine

The only module that supports a version number is the os via import etc:- os sysname=esp32 release 1.10.0 version v1.10-311ge38c68310-dirty

none of the other modules support reporting versions either using upip or via a version object

machine is umachine socket is usocket network is network here is uasyncio:-

help(uasyncio) object <module 'uasyncio' from '/lib/uasyncio/init.py'> is of type module log -- None IOWrite -- <class 'IOWrite'> select -- <module 'uselect'> Task -- <function Task at 0x3ffc49b0> IORead -- <class 'IORead'> PollEventLoop -- <class 'PollEventLoop'> ensure_future -- <function ensure_future at 0x3ffc4980> StreamReader -- <class 'StreamReader'> IOReadDone -- <class 'IOReadDone'> uerrno -- <module 'uerrno'> open_connection -- start_server -- EventLoop -- <class 'EventLoop'> StopLoop -- <class 'StopLoop'> ucollections -- <module 'ucollections'> StreamWriter -- <class 'StreamWriter'> time -- <module 'utime'> uasyncio -- <module 'uasyncio' from '/lib/uasyncio/init.py'> cancel -- <function cancel at 0x3ffc47d0> sleep -- utimeq -- <module 'utimeq'> sleep_ms -- <SleepMs object at 3ffc47b0> CancelledError -- <class 'CancelledError'> file -- /lib/uasyncio/init.py SysCall1 -- <class 'SysCall1'> wait_for_ms -- TimeoutError -- <class 'TimeoutError'> _socket -- <module 'usocket'> SleepMs -- <class 'SleepMs'> set_debug -- <function set_debug at 0x3ffc3990> SysCall -- <class 'SysCall'> coroutine -- <function coroutine at 0x3ffc4850> DEBUG -- 0 name -- uasyncio IOWriteDone -- <class 'IOWriteDone'> type_gen -- <class 'generator'> core -- <module 'uasyncio.core' from '/lib/uasyncio/core.py'> path -- /lib/uasyncio wait_for -- <function wait_for at 0x3ffc4840> TimeoutObj -- <class 'TimeoutObj'> get_event_loop -- <function get_event_loop at 0x3ffc4860>

MPY: soft reboot MicroPython v1.10-331-ge38c68310-dirty on 2019-05-09; ESP32 module with ESP32 Type "help()" for more information.

uasyncio was installed via:- repl>> import upip upip install(‘micropython-asyncio’) upip isntall(‘micropython-pkg_resources’)

So there is no ‘await’ object/function. If you look at the code in my module you’ll see as you’re perfectly aware 1 await functions. the error is not reported in the previous definition:-

“async def conn_hann(client): await client.subscribe('testTopic',1)”

but points to the one in the second definition:-

“async def main(client): await client.connect() n=0 while True: await asyncio.sleep(5) print('publish',n)

If the wifi is down the following will pause for the duration.

            await client.publish('result','{}'.format(n),qos=1)
            n +=1”

BUT ALL OF THAT IS NONESENSE, there’s no await function definition.

So I suspect that I have a uasyncio which is renegade.

Could you please advise where I might download and safely install the relevent file variants for achieving the desired reult, Peter

Thank you Robin

Here is the module

from machine import Pin import socket import sys import network import time

internalled=Pin(2,Pin.OUT) externalled=Pin(4,Pin.OUT)

station=network.WLAN(network.STA_IF) station.active(True) station.connect("TP-LINK_EB850C", "arthurfrabb") while (not (station.isconnected())): print("waiting to Connect") print (station.ifconfig()) time.sleep(1) station.ifconfig() pin2.on() time.sleep(1) pin4.on() pin2.off() Time.sleep(1) print ("Connected") pin4.off()

from mqtt_as import MQTTClient from config import config import uasyncio as asyncio SERVER='192.168.1.241'

def callback(topic,msg): print((topic,msg))

async def conn_hann(client): await client.subscribe('testTopic',1)

async def main(client): await client.connect() n=0 while True: await asyncio.sleep(5) print('publish',n)

If the wifi is down the following will pause for the duration.

            await client.publish('result','{}'.format(n),qos=1)
            n +=1

config['subs_cb'] = callback config['connect_coro'] = conn_han config['server'] = SERVER

MQTTClient.DEBUG = True #Optional: print diagnostic messages client=MQTTClient(config) loop=asyncio.get.event_loop() try: loop.run_until_complete(main(client)) finally: client.close() #Prevent LmacRxBlk:1 errors

From: Peter Hinch Sent: Saturday, July 20, 2019 11:00 AM To: peterhinch/micropython-mqtt Cc: RobinMosedale ; Author Subject: Re: [peterhinch/micropython-mqtt] await client.connect() error in documented tutorial (#15)

This library is intended to run under MicroPython on a microcontroller with WiFi capability: namely ESP8266, ESP32 or Pyboard D.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.

Regards Robin

peterhinch commented 5 years ago

I think you are right and you have a uasyncio version issue.

I suggest you use the latest release build (V1.11) of firmware here for a board with no SPIRAM or here if you have SPIRAM. These builds have uasyncio ready installed. Firmware installation instructions are here.

RobinMosedale commented 5 years ago

Thank you Peter, that’s kind.

I’ll report back. Robin

From: Peter Hinch Sent: Sunday, July 21, 2019 9:04 AM To: peterhinch/micropython-mqtt Cc: RobinMosedale ; Author Subject: Re: [peterhinch/micropython-mqtt] await client.connect() error in documented tutorial (#15)

I think you are right and you have a uasyncio version issue.

I suggest you use the latest release build (V1.11) of firmware here for a board with no SPIRAM or here if you have SPIRAM. These builds have uasyncio ready installed. Firmware installation instructions are here.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.

Regards Robin

RobinMosedale commented 5 years ago

Clean erase reburn with your link copied program across “/home/pi/micropython> repl Entering REPL. Use Control-X to exit.

MicroPython v1.11 on 2019-05-29; ESP32 module with ESP32 Type "help()" for more information.

import asyncmqtttest.py I (469185) phy: phy_version: 4007, 9c6b43b, Jan 11 2019, 16:45:07, 0, 0 waiting to Connect ('0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0') waiting to Connect ('0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0') waiting to Connect ('0.0.0.0', '0.0.0.0', '0.0.0.0', '192.168.1.254') Connected Traceback (most recent call last): File "", line 1, in File "asyncmqtttest.py", line 28, in File "mqtt_as.py", line 13, in ImportError: no module named 'uasyncio”"

Usyncio is supposed to be included in the base build, isn’t it?

Robin

From: Peter Hinch Sent: Sunday, July 21, 2019 9:04 AM To: peterhinch/micropython-mqtt Cc: RobinMosedale ; Author Subject: Re: [peterhinch/micropython-mqtt] await client.connect() error in documented tutorial (#15)

I think you are right and you have a uasyncio version issue.

I suggest you use the latest release build (V1.11) of firmware here for a board with no SPIRAM or here if you have SPIRAM. These builds have uasyncio ready installed. Firmware installation instructions are here.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.

Regards Robin

RobinMosedale commented 5 years ago

The pyboard looks like this:- /home/pi/micropython/async_mqtt> ls /pyboard asyncmqtttest.py config.py mqtt_as.py
boot.py ledflash.py
/home/pi/micropython/async_mqtt>

RobinMosedale commented 5 years ago

help('modules') main framebuf socket upip _boot gc ssl upip_utarfile _onewire hashlib struct upysh _thread heapq sys urandom _webrepl inisetup time ure apa106 io ubinascii urequests array json ucollections uselect binascii machine ucryptolib usocket btree math uctypes ussl builtins micropython uerrno ustruct cmath neopixel uhashlib utime collections network uhashlib utimeq dht ntptime uheapq uwebsocket ds18x20 onewire uio uzlib errno os ujson webrepl esp random umqtt/robust webrepl_setup esp32 re umqtt/simple websocket_helper flashbdev select uos zlib Plus any modules on the filesystem

peterhinch commented 5 years ago

Sorry, Robin. I was wrong about uasyncio being pre-installed: evidently it is not on ESP32.

I have just gone through the following procedure with an ESP32 reference board (no SPIRAM).

import upip
upip.install('micropython-uasyncio')

In the mqtt_as directory I edited config.py for my WiFi and broker credentials (my broker is a Pi running mosquitto).

I then copied the following files to the ESP32:

At the REPL I then ran

import range

This ran correctly.

I suggest you follow these steps to establish a working system, then start to develop your own application.

As a general point I would let the mqtt_as library perform the connection (as per the examples) rather than coding your own explicit connection routine, which is duplicating existing functionality.

I hope this helps.

RobinMosedale commented 5 years ago

As to upip syntax, I'd never have guessed that. All flavour of various formats in micropython website and not any indication of which applies to which version. Strangely, my original syntax worked, but no longer.

peterhinch commented 5 years ago

Are you sure you had a working internet connection? Alas the error messages from upip are unhelpful.

upip changed with version 1.11. Prior to that version it would install library modules which required the Pycopy fork of MicroPython. The new version will install compatible versions if they exist. This probably explains why you were having problems, and you need to be sure that any incompatible libraries are removed.

So I suggest you uninstall everything (or erase flash, as I did), then copy my instructions above. It worked here and I can see no reason why it shouldn't work for you.

RobinMosedale commented 5 years ago

Many thanks Peter. Although I'd erased and reinstalled the v1.11 there were errors. So rather than the plain v1.11 there following was installed on a clean board esp32-20190722-v1.11-167-g331c224e0.bin (latest) Happy to say, wifi connected upip worked as desired, and your files copied across AND Success range program works fine with my Mosquitto publishing on Pi3.

So very many thanks for your patience. Now building on this to experiment with asynchronous routines

Robin