Initialize the MQTT connection.
Subscribe to a specified topic and publish messages via MQTT.
In a loop, generate a random number as the counter value, and if the counter value differs from the previous one, publish it to the specified topic.
The program will display the current counter value, the messages from the subscribed topic, and the MQTT connection status.
from m5stack import *
from m5ui import *
from uiflow import *
from comx.cat1 import CAT1
setScreenColor(0x222222)
cat_topic = None
cat_msg = None
counter = None
previous = None
import random
def cat_mqtt_cb(cat_mq_topic, cat_mq_payload):
global cat_topic, cat_msg, counter, previous, cat
cat_topic = cat_mq_topic
cat_msg = cat_mq_payload
label5.setText(str(cat_topic))
label7.setText(str(cat_msg))
pass
print('Start Mqtt')
counter = 0
previous = 0
cat = CAT1(tx=17, rx=16)
cat.mqtt_to_connect('mqtt.m5stack.com', 1883, 'mqtt_m9', '', '', 120)
if cat.is_connect_mqtt():
print('Connected Mqtt')
while not (cat.mqtt_subscribe('SubTopic', cat_mqtt_cb, 0)):
cat.mqtt_unsubscribe('SubTopic')
print('Success Subscribe')
while True:
cat.mqtt_poll()
if counter != previous:
cat.mqtt_publish('PubTopic', str(counter), 0)
previous = counter
if cat.is_connect_mqtt():
print('Connected Mqtt')
counter = random.randint(100000, 999999)
print((str('counter:') + str(counter)))
wait_ms(2)
cat.get_gprs_network_registration()
cat.get_network_registration()
cat.get_single_quality()
cat.check_status()
cat.enable_PDP_context()
cat.get_ezdata(ezdata_get_IklJVcb, 'GCJ3Ic5h2eXnzV3rT3bBXvrncCaJnART', '')
cat.remove_ezdata('GCJ3Ic5h2eXnzV3rT3bBXvrncCaJnART', '')
cat.set_ezdata('GCJ3Ic5h2eXnzV3rT3bBXvrncCaJnART', '', '', 0)
cat.get_CCID()
cat.get_IMEI()
cat.http_get('')
cat.http_post('', 'application/json', '')
cat.http_terminate()
CAT1(tx=17, rx=16)
cat.is_connect_mqtt()
cat.mqtt_to_connect('mqtt.m5stack.com', 1883, '', '', '', 120
)
cat.mqtt_disconnect()
cat.mqtt_poll()
cat.mqtt_publish('', '', 0)
cat.mqtt_subscribe('', cat_mqtt_cb, 0)
def cat_mqtt_cb(cat_mq_topic, cat_mq_payload):
global ezdata_value1, cat_topic, cat_msg, cat
cat_topic = cat_mq_topic
cat_msg = cat_mq_payload
pass
cat_topic
represents the topic, and cat_msg
represents the received message.cat.mqtt_unsubscribe('')
cat.poweroff()
cat.reset()
cat.set_command_echo_mode(0)