From 77c20412a8a28a6fd018b1d26202fd230329cd64 Mon Sep 17 00:00:00 2001 From: iabdalkader Date: Thu, 12 Sep 2019 00:13:59 +0200 Subject: [PATCH] Update MQTT publish example and add MQTT subscribe example. --- .../14-WiFi-Shield/{mqtt.py => mqtt_pub.py} | 7 ++-- scripts/examples/14-WiFi-Shield/mqtt_sub.py | 37 +++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) rename scripts/examples/14-WiFi-Shield/{mqtt.py => mqtt_pub.py} (69%) create mode 100644 scripts/examples/14-WiFi-Shield/mqtt_sub.py diff --git a/scripts/examples/14-WiFi-Shield/mqtt.py b/scripts/examples/14-WiFi-Shield/mqtt_pub.py similarity index 69% rename from scripts/examples/14-WiFi-Shield/mqtt.py rename to scripts/examples/14-WiFi-Shield/mqtt_pub.py index 03c60b327..8a67afd85 100644 --- a/scripts/examples/14-WiFi-Shield/mqtt.py +++ b/scripts/examples/14-WiFi-Shield/mqtt_pub.py @@ -1,11 +1,12 @@ # MQTT Example. -# This example shows how to use the MQTT library. +# This example shows how to use the MQTT library to publish to a topic. # # 1) Copy the mqtt.py library to OpenMV storage. -# 2) Install the mosquitto client on PC and run the following command: +# 2) Run this script on the OpenMV camera. +# 3) Install the mosquitto client on PC and run the following command: # mosquitto_sub -h test.mosquitto.org -t "openmv/test" -v # -# Note: If the mosquitto broker is down (OSError -12) try a different one (ex: broker.hivemq.com) +# NOTE: If the mosquitto broker is unreachable, try another broker (For example: broker.hivemq.com) import time, network from mqtt import MQTTClient diff --git a/scripts/examples/14-WiFi-Shield/mqtt_sub.py b/scripts/examples/14-WiFi-Shield/mqtt_sub.py new file mode 100644 index 000000000..f9bdada77 --- /dev/null +++ b/scripts/examples/14-WiFi-Shield/mqtt_sub.py @@ -0,0 +1,37 @@ +# MQTT Example. +# This example shows how to use the MQTT library to subscribe to a topic. +# +# 1) Copy the mqtt.py library to OpenMV storage. +# 2) Run this script on the OpenMV camera. +# 3) Install the mosquitto client on PC and run the following command: +# mosquitto_pub -t "openmv/test" -m "Hello World!" -h test.mosquitto.org -p 1883 +# +# NOTE: If the mosquitto broker is unreachable, try another broker (For example: broker.hivemq.com) +import time, network +from mqtt import MQTTClient + +SSID='' # Network SSID +KEY='' # Network key + +# Init wlan module and connect to network +print("Trying to connect... (may take a while)...") + +wlan = network.WINC() +wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK) + +# We should have a valid IP now via DHCP +print(wlan.ifconfig()) + +client = MQTTClient("openmv", "test.mosquitto.org", port=1883) +client.connect() + +def callback(topic, msg): + print(topic, msg) + +# must set callback first +client.set_callback(callback) +client.subscribe("openmv/test") + +while (True): + client.check_msg() # poll for messages. + time.sleep(1000)