├── .gitattributes ├── .gitignore ├── images ├── freeHeap.png ├── pubandsub.png └── publishSubscribe.png ├── pubAndSub.py ├── publishAdafruit.py ├── readme.md └── subscribeAdafruit.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask instance folder 57 | instance/ 58 | 59 | # Scrapy stuff: 60 | .scrapy 61 | 62 | # Sphinx documentation 63 | docs/_build/ 64 | 65 | # PyBuilder 66 | target/ 67 | 68 | # IPython Notebook 69 | .ipynb_checkpoints 70 | 71 | # pyenv 72 | .python-version 73 | 74 | # celery beat schedule file 75 | celerybeat-schedule 76 | 77 | # dotenv 78 | .env 79 | 80 | # virtualenv 81 | venv/ 82 | ENV/ 83 | 84 | # Spyder project settings 85 | .spyderproject 86 | 87 | # Rope project settings 88 | .ropeproject 89 | 90 | # ========================= 91 | # Operating System Files 92 | # ========================= 93 | 94 | # OSX 95 | # ========================= 96 | 97 | .DS_Store 98 | .AppleDouble 99 | .LSOverride 100 | 101 | # Thumbnails 102 | ._* 103 | 104 | # Files that might appear in the root of a volume 105 | .DocumentRevisions-V100 106 | .fseventsd 107 | .Spotlight-V100 108 | .TemporaryItems 109 | .Trashes 110 | .VolumeIcon.icns 111 | 112 | # Directories potentially created on remote AFP share 113 | .AppleDB 114 | .AppleDesktop 115 | Network Trash Folder 116 | Temporary Items 117 | .apdisk 118 | 119 | # Windows 120 | # ========================= 121 | 122 | # Windows image file caches 123 | Thumbs.db 124 | ehthumbs.db 125 | 126 | # Folder config file 127 | Desktop.ini 128 | 129 | # Recycle Bin used on file shares 130 | $RECYCLE.BIN/ 131 | 132 | # Windows Installer files 133 | *.cab 134 | *.msi 135 | *.msm 136 | *.msp 137 | 138 | # Windows shortcuts 139 | *.lnk 140 | -------------------------------------------------------------------------------- /images/freeHeap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miketeachman/micropython-adafruit-mqtt-esp8266/7b356ba86945c87ff0b9883da7fdf344755b7560/images/freeHeap.png -------------------------------------------------------------------------------- /images/pubandsub.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miketeachman/micropython-adafruit-mqtt-esp8266/7b356ba86945c87ff0b9883da7fdf344755b7560/images/pubandsub.png -------------------------------------------------------------------------------- /images/publishSubscribe.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miketeachman/micropython-adafruit-mqtt-esp8266/7b356ba86945c87ff0b9883da7fdf344755b7560/images/publishSubscribe.png -------------------------------------------------------------------------------- /pubAndSub.py: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | # Copyright (c) 2019 Mike Teachman 3 | # https://opensource.org/licenses/MIT 4 | # 5 | # Example MicroPython and CircuitPython code showing how to use the MQTT protocol with Adafruit IO, to 6 | # publish and subscribe on the same device 7 | # 8 | # Tested using the releases: 9 | # ESP8266 10 | # MicroPython 1.9.3 11 | # MicroPython 1.9.4 12 | # MicroPython 1.10 13 | # CircuitPython 2.3.1 (needs addition of CircuitPython specific umqtt module) 14 | # CircuitPython 3.0.0 (needs addition of CircuitPython specific umqtt module) 15 | # ESP32 16 | # MicroPython 1.9.4 (needs addition of MicroPython umqtt module) 17 | # MicroPython 1.10 18 | # 19 | # Tested using the following boards: 20 | # Adafruit Feather HUZZAH ESP8266 21 | # Adafruit Feather HUZZAH ESP32 22 | # WeMos D1 Mini 23 | # 24 | # User configuration parameters are indicated with "ENTER_". 25 | 26 | import network 27 | import time 28 | from umqtt.robust import MQTTClient 29 | import os 30 | import gc 31 | import sys 32 | 33 | # the following function is the callback which is 34 | # called when subscribed data is received 35 | def cb(topic, msg): 36 | print('Subscribe: Received Data: Topic = {}, Msg = {}\n'.format(topic, msg)) 37 | free_heap = int(str(msg,'utf-8')) 38 | 39 | # WiFi connection information 40 | WIFI_SSID = '' 41 | WIFI_PASSWORD = '' 42 | 43 | # turn off the WiFi Access Point 44 | ap_if = network.WLAN(network.AP_IF) 45 | ap_if.active(False) 46 | 47 | # connect the device to the WiFi network 48 | wifi = network.WLAN(network.STA_IF) 49 | wifi.active(True) 50 | wifi.connect(WIFI_SSID, WIFI_PASSWORD) 51 | 52 | # wait until the device is connected to the WiFi network 53 | MAX_ATTEMPTS = 20 54 | attempt_count = 0 55 | while not wifi.isconnected() and attempt_count < MAX_ATTEMPTS: 56 | attempt_count += 1 57 | time.sleep(1) 58 | 59 | if attempt_count == MAX_ATTEMPTS: 60 | print('could not connect to the WiFi network') 61 | sys.exit() 62 | 63 | # create a random MQTT clientID 64 | random_num = int.from_bytes(os.urandom(3), 'little') 65 | mqtt_client_id = bytes('client_'+str(random_num), 'utf-8') 66 | 67 | # connect to Adafruit IO MQTT broker using unsecure TCP (port 1883) 68 | # 69 | # To use a secure connection (encrypted) with TLS: 70 | # set MQTTClient initializer parameter to "ssl=True" 71 | # Caveat: a secure connection uses about 9k bytes of the heap 72 | # (about 1/4 of the micropython heap on the ESP8266 platform) 73 | ADAFRUIT_IO_URL = b'io.adafruit.com' 74 | ADAFRUIT_USERNAME = b'' 75 | ADAFRUIT_IO_KEY = b'' 76 | ADAFRUIT_IO_FEEDNAME = b'freeHeap' 77 | 78 | client = MQTTClient(client_id=mqtt_client_id, 79 | server=ADAFRUIT_IO_URL, 80 | user=ADAFRUIT_USERNAME, 81 | password=ADAFRUIT_IO_KEY, 82 | ssl=False) 83 | 84 | try: 85 | client.connect() 86 | except Exception as e: 87 | print('could not connect to MQTT server {}{}'.format(type(e).__name__, e)) 88 | sys.exit() 89 | 90 | # publish free heap statistics to Adafruit IO using MQTT 91 | # subscribe to the same feed 92 | # 93 | # format of feed name: 94 | # "ADAFRUIT_USERNAME/feeds/ADAFRUIT_IO_FEEDNAME" 95 | mqtt_feedname = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_FEEDNAME), 'utf-8') 96 | client.set_callback(cb) 97 | client.subscribe(mqtt_feedname) 98 | PUBLISH_PERIOD_IN_SEC = 10 99 | SUBSCRIBE_CHECK_PERIOD_IN_SEC = 0.5 100 | accum_time = 0 101 | while True: 102 | try: 103 | # Publish 104 | if accum_time >= PUBLISH_PERIOD_IN_SEC: 105 | free_heap_in_bytes = gc.mem_free() 106 | print('Publish: freeHeap = {}'.format(free_heap_in_bytes)) 107 | client.publish(mqtt_feedname, 108 | bytes(str(free_heap_in_bytes), 'utf-8'), 109 | qos=0) 110 | accum_time = 0 111 | 112 | # Subscribe. Non-blocking check for a new message. 113 | client.check_msg() 114 | 115 | time.sleep(SUBSCRIBE_CHECK_PERIOD_IN_SEC) 116 | accum_time += SUBSCRIBE_CHECK_PERIOD_IN_SEC 117 | except KeyboardInterrupt: 118 | print('Ctrl-C pressed...exiting') 119 | client.disconnect() 120 | sys.exit() -------------------------------------------------------------------------------- /publishAdafruit.py: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | # Copyright (c) 2019 Mike Teachman 3 | # https://opensource.org/licenses/MIT 4 | # 5 | # Example MicroPython and CircuitPython code showing how to use the MQTT protocol to 6 | # publish data to an Adafruit IO feed 7 | # 8 | # Tested using the releases: 9 | # ESP8266 10 | # MicroPython 1.9.3 11 | # MicroPython 1.9.4 12 | # MicroPython 1.10 13 | # CircuitPython 2.3.1 (needs addition of CircuitPython specific umqtt module) 14 | # CircuitPython 3.0.0 (needs addition of CircuitPython specific umqtt module) 15 | # ESP32 16 | # MicroPython 1.9.4 (needs addition of MicroPython umqtt module) 17 | # MicroPython 1.10 18 | # 19 | # Tested using the following boards: 20 | # Adafruit Feather HUZZAH ESP8266 21 | # Adafruit Feather HUZZAH ESP32 22 | # WeMos D1 Mini 23 | # 24 | # User configuration parameters are indicated with "ENTER_". 25 | 26 | import network 27 | import time 28 | from umqtt.robust import MQTTClient 29 | import os 30 | import gc 31 | import sys 32 | 33 | # WiFi connection information 34 | WIFI_SSID = '' 35 | WIFI_PASSWORD = '' 36 | 37 | # turn off the WiFi Access Point 38 | ap_if = network.WLAN(network.AP_IF) 39 | ap_if.active(False) 40 | 41 | # connect the device to the WiFi network 42 | wifi = network.WLAN(network.STA_IF) 43 | wifi.active(True) 44 | wifi.connect(WIFI_SSID, WIFI_PASSWORD) 45 | 46 | # wait until the device is connected to the WiFi network 47 | MAX_ATTEMPTS = 20 48 | attempt_count = 0 49 | while not wifi.isconnected() and attempt_count < MAX_ATTEMPTS: 50 | attempt_count += 1 51 | time.sleep(1) 52 | 53 | if attempt_count == MAX_ATTEMPTS: 54 | print('could not connect to the WiFi network') 55 | sys.exit() 56 | 57 | # create a random MQTT clientID 58 | random_num = int.from_bytes(os.urandom(3), 'little') 59 | mqtt_client_id = bytes('client_'+str(random_num), 'utf-8') 60 | 61 | # connect to Adafruit IO MQTT broker using unsecure TCP (port 1883) 62 | # 63 | # To use a secure connection (encrypted) with TLS: 64 | # set MQTTClient initializer parameter to "ssl=True" 65 | # Caveat: a secure connection uses about 9k bytes of the heap 66 | # (about 1/4 of the micropython heap on the ESP8266 platform) 67 | ADAFRUIT_IO_URL = b'io.adafruit.com' 68 | ADAFRUIT_USERNAME = b'' 69 | ADAFRUIT_IO_KEY = b'' 70 | ADAFRUIT_IO_FEEDNAME = b'freeHeap' 71 | 72 | client = MQTTClient(client_id=mqtt_client_id, 73 | server=ADAFRUIT_IO_URL, 74 | user=ADAFRUIT_USERNAME, 75 | password=ADAFRUIT_IO_KEY, 76 | ssl=False) 77 | try: 78 | client.connect() 79 | except Exception as e: 80 | print('could not connect to MQTT server {}{}'.format(type(e).__name__, e)) 81 | sys.exit() 82 | 83 | # publish free heap statistics to Adafruit IO using MQTT 84 | # 85 | # format of feed name: 86 | # "ADAFRUIT_USERNAME/feeds/ADAFRUIT_IO_FEEDNAME" 87 | mqtt_feedname = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_FEEDNAME), 'utf-8') 88 | PUBLISH_PERIOD_IN_SEC = 10 89 | while True: 90 | try: 91 | free_heap_in_bytes = gc.mem_free() 92 | client.publish(mqtt_feedname, 93 | bytes(str(free_heap_in_bytes), 'utf-8'), 94 | qos=0) 95 | time.sleep(PUBLISH_PERIOD_IN_SEC) 96 | except KeyboardInterrupt: 97 | print('Ctrl-C pressed...exiting') 98 | client.disconnect() 99 | sys.exit() -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # MQTT protocol with Adafruit IO using MicroPython and CircuitPython 2 | MicroPython and CircuitPython examples showing how to use the [MQTT](http://mqtt.org/faq) protocol with 3 | the [Adafruit IO](https://io.adafruit.com) cloud service. The example code shows how a 4 | [Heap](https://docs.micropython.org/en/latest/pyboard/reference/constrained.html#the-heap) statistic 5 | (free heap size in bytes) can be used with MQTT at Adafruit IO. This heap statistic provides a convenient means 6 | to show the MQTT capabilities. The implementation can be changed to use MQTT Publish/Subscribe with sensor data or any other 7 | data. 8 | 9 | Three example code files: 10 | 1. Publish the free heap statistics to Adafruit IO 11 | 1. Subscribe to the free heap statistics from Adafruit IO 12 | 1. Publish and Subscribe in the same program 13 | 14 | ![publish/subscribe](images/publishSubscribe.png) 15 | 16 | ### Hardware Support 17 | * example code tested with 3 boards 18 | * Adafruit Feather HUZZAH ESP8266 19 | * Adafruit Feather HUZZAH ESP32 20 | * WeMos D1 Mini 21 | 22 | ### Adafruit IO configuration 23 | 1. Create an Adafruit IO account at [Adafruit IO](https://io.adafruit.com) and sign in 24 | 1. Gather the following Adafruit IO information 25 | * AIO Key (select "View AIO Key" in Adafruit IO) 26 | * Adafruit UserName (shown on the same page as the AIO Key) 27 | 28 | ## Publishing data to Adafruit IO feeds 29 | 30 | #### Usage 31 | 1. Install the UMQTT Package (if needed) 32 | See section below **Installing UMQTT Package** 33 | 1. Configure parameters in file **publishAdafruit.py"** 34 | * 35 | * 36 | * 37 | * 38 | 1. Copy the file _publishAdafruit.py_ to your device, using [ampy](https://github.com/adafruit/ampy), [rshell](https://github.com/dhylands/rshell), [webrepl](http://micropython.org/webrepl/) 39 | ``` 40 | $ ampy -pCOMx -d1 put publishAdafruit.py main.py 41 | ``` 42 | 4. Reset the board 43 | 1. Navigate to Adafruit IO to see if a new feed has been created called "freeHeap" 44 | 1. In the example code freeHeap data is published every 10s 45 | 1. Make a dashboard to better visualize the free space on the heap 46 | 47 | ![free heap plot](images/freeHeap.png) 48 | 49 | ## Subscribing to Adafruit IO feeds 50 | 51 | #### Usage 52 | 1. Install the UMQTT Package (if needed) 53 | See section below **Installing UMQTT Package** 54 | 1. Configure parameters in file **subscribeAdafruit.py"** 55 | * 56 | * 57 | * 58 | * 59 | 1. Copy the file _subscribeAdafruit.py_ to your device, using [ampy](https://github.com/adafruit/ampy), [rshell](https://github.com/dhylands/rshell), [webrepl](http://micropython.org/webrepl/) 60 | ``` 61 | $ ampy -pCOMx -d1 put subscribeAdafruit.py main.py 62 | ``` 63 | 4. Configure a 2nd device to publish the freeHeap data (see above) 64 | 1. Reset the board 65 | 1. Connect to the REPL with Putty (or simlar) to observe subscribed feed data being received (every 10s in the example code) 66 | 67 | ## Publishing and Subscribing on the same device 68 | The file _pubAndSub.py_ shows how a single device can both publish and subscribe. The method of Subscribing changes 69 | in this example. The non-blocking call client.check_msg() is used rather than the blocking call 70 | client.wait_msg(). The debug print output shows the subscription receiving the published data. 71 | 72 | ![publish and subscribe](images/pubandsub.png) 73 | 74 | --- 75 | 76 | ### Limitations 77 | * CircuitPython 3.0.0 will continually reset if a secure data connection is enabled 78 | 79 | ### Tested with these MicroPython Releases 80 | * MicroPython 1.9.3 81 | * MicroPython 1.9.4 82 | * MicroPython 1.10 83 | 84 | ### Tested with these CircuitPython Releases 85 | * CircuitPython 2.3.1 86 | * CircuitPython 3.0.0 87 | 88 | ### Recommended Tools for Windows 89 | * Adafruit Ampy to copy files to the filesystem 90 | * install version 1.0.3 or newer which has the -d option (use **-d1** to avoid USB connection issues in Windows) 91 | * Putty to interact with the REPL 92 | * set Serial speed to 115200 and Flow control to None 93 | 94 | ## Installing UMQTT Package 95 | The example code requires the MicroPython MQTT (UMQTT) Package. Some firmware releases have this package built-in, others don't. 96 | 97 | | Firmware Release | umqtt built-in? | GitHub Library | 98 | | ------------- |:-------------:| :-----:| 99 | | MicroPython 1.9.3 for ESP8266 | Yes | n/a | 100 | | MicroPython 1.9.4 for ESP8266 | Yes | n/a | 101 | | MicroPython 1.10 for ESP8266 | Yes | n/a | 102 | | MicroPython 1.9.4 for ESP32 | **No** | [Micropython lib](https://github.com/micropython/micropython-lib) | 103 | | MicroPython 1.10 for ESP32 | Yes | n/a | 104 | | CircuitPython 2.3.1 for ESP8266 | **No** |[CircuitPython lib](https://github.com/MikeTeachman/micropython-lib) | 105 | | CircuitPython 3.0.0 for ESP8266 | **No** | [CircuitPython lib](https://github.com/MikeTeachman/micropython-lib) | 106 | 107 | ##### How to install the UMQTT package (if "No" is indicated in the table above) 108 | 1. Navigate to the GitHub library indicated in the table 109 | 1. Select the "Clone or download" button 110 | 1. Select "Download ZIP" 111 | 1. Extract the ZIP. Should see folder called "micropython-lib-master" 112 | 1. Two files need to be copied to the MicroPython filesystem 113 | * micropython-lib-master\umqtt.robust\umqtt\simple.py 114 | * micropython-lib-master\umqtt.robust\umqtt\robust.py 115 | 116 | Copy these two files to the MicroPython filesystem with the directory structure shown below. 117 | 118 | ``` 119 | boot.py 120 | lib 121 | | 122 | umqtt 123 | simple.py 124 | robust.py 125 | ``` 126 | 127 | Example with Ampy: 128 | ``` 129 | >ampy -pCOM27 -d1 ls 130 | boot.py 131 | >ampy -pCOM27 -d1 mkdir lib 132 | >ampy -pCOM27 -d1 mkdir lib/umqtt 133 | >ampy -pCOM27 -d1 put simple.py lib/umqtt/simple.py 134 | >ampy -pCOM27 -d1 put robust.py lib/umqtt/robust.py 135 | >ampy -pCOM27 -d1 ls 136 | boot.py 137 | lib 138 | >ampy -pCOM27 -d1 ls lib 139 | umqtt 140 | >ampy -pCOM27 -d1 ls lib/umqtt 141 | simple.py 142 | robust.py 143 | ``` 144 | ##### Validating the UMQTT package install 145 | From the REPL (using Putty, etc) execute the following commands and observe similar output 146 | ``` 147 | >>> from umqtt.robust import MQTTClient 148 | 149 | >>> dir(MQTTClient) 150 | ['reconnect', 'log', 'publish', '__module__', 'wait_msg', 'delay', '__qualname__', 'DELAY', 'DEBUG'] 151 | ``` 152 | 153 | If you see this result you have successfully installed the umqtt package. :tada: :relieved: 154 | 155 | -------------------------------------------------------------------------------- /subscribeAdafruit.py: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | # Copyright (c) 2019 Mike Teachman 3 | # https://opensource.org/licenses/MIT 4 | # 5 | # Example MicroPython and CircuitPython code showing how to use the MQTT protocol to 6 | # subscribe to an Adafruit IO feed 7 | # 8 | # Tested using the releases: 9 | # ESP8266 10 | # MicroPython 1.9.3 11 | # MicroPython 1.9.4 12 | # MicroPython 1.10 13 | # CircuitPython 2.3.1 (needs addition of CircuitPython specific umqtt module) 14 | # CircuitPython 3.0.0 (needs addition of CircuitPython specific umqtt module) 15 | # ESP32 16 | # MicroPython 1.9.4 (needs addition of MicroPython umqtt module) 17 | # MicroPython 1.10 18 | # 19 | # Tested using the following boards: 20 | # Adafruit Feather HUZZAH ESP8266 21 | # Adafruit Feather HUZZAH ESP32 22 | # WeMos D1 Mini 23 | # 24 | # User configuration parameters are indicated with "ENTER_". 25 | 26 | import network 27 | import time 28 | from umqtt.robust import MQTTClient 29 | import os 30 | import sys 31 | 32 | # the following function is the callback which is 33 | # called when subscribed data is received 34 | def cb(topic, msg): 35 | print('Received Data: Topic = {}, Msg = {}'.format(topic, msg)) 36 | free_heap = int(str(msg,'utf-8')) 37 | print('free heap size = {} bytes'.format(free_heap)) 38 | 39 | # WiFi connection information 40 | WIFI_SSID = '' 41 | WIFI_PASSWORD = '' 42 | 43 | # turn off the WiFi Access Point 44 | ap_if = network.WLAN(network.AP_IF) 45 | ap_if.active(False) 46 | 47 | # connect the device to the WiFi network 48 | wifi = network.WLAN(network.STA_IF) 49 | wifi.active(True) 50 | wifi.connect(WIFI_SSID, WIFI_PASSWORD) 51 | 52 | # wait until the device is connected to the WiFi network 53 | MAX_ATTEMPTS = 20 54 | attempt_count = 0 55 | while not wifi.isconnected() and attempt_count < MAX_ATTEMPTS: 56 | attempt_count += 1 57 | time.sleep(1) 58 | 59 | if attempt_count == MAX_ATTEMPTS: 60 | print('could not connect to the WiFi network') 61 | sys.exit() 62 | 63 | # create a random MQTT clientID 64 | random_num = int.from_bytes(os.urandom(3), 'little') 65 | mqtt_client_id = bytes('client_'+str(random_num), 'utf-8') 66 | 67 | # connect to Adafruit IO MQTT broker using unsecure TCP (port 1883) 68 | # 69 | # To use a secure connection (encrypted) with TLS: 70 | # set MQTTClient initializer parameter to "ssl=True" 71 | # Caveat: a secure connection uses about 9k bytes of the heap 72 | # (about 1/4 of the micropython heap on the ESP8266 platform) 73 | ADAFRUIT_IO_URL = b'io.adafruit.com' 74 | ADAFRUIT_USERNAME = b'' 75 | ADAFRUIT_IO_KEY = b'' 76 | ADAFRUIT_IO_FEEDNAME = b'freeHeap' 77 | 78 | client = MQTTClient(client_id=mqtt_client_id, 79 | server=ADAFRUIT_IO_URL, 80 | user=ADAFRUIT_USERNAME, 81 | password=ADAFRUIT_IO_KEY, 82 | ssl=False) 83 | 84 | try: 85 | client.connect() 86 | except Exception as e: 87 | print('could not connect to MQTT server {}{}'.format(type(e).__name__, e)) 88 | sys.exit() 89 | 90 | mqtt_feedname = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_FEEDNAME), 'utf-8') 91 | client.set_callback(cb) 92 | client.subscribe(mqtt_feedname) 93 | 94 | # following two lines is an Adafruit-specific implementation of the Publish "retain" feature 95 | # which allows a Subscription to immediately receive the last Published value for a feed, 96 | # even if that value was Published two hours ago. 97 | # Described in the Adafruit IO blog, April 22, 2018: https://io.adafruit.com/blog/ 98 | mqtt_feedname_get = bytes('{:s}/get'.format(mqtt_feedname), 'utf-8') 99 | client.publish(mqtt_feedname_get, '\0') 100 | 101 | # wait until data has been Published to the Adafruit IO feed 102 | while True: 103 | try: 104 | client.wait_msg() 105 | except KeyboardInterrupt: 106 | print('Ctrl-C pressed...exiting') 107 | client.disconnect() 108 | sys.exit() --------------------------------------------------------------------------------