47 lines
1.9 KiB
Python
47 lines
1.9 KiB
Python
#!/usr/bin/env python3
|
|
import logging
|
|
import argparse
|
|
from m2m.nbiot import factory
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
def run_mqtt_demo(port):
|
|
module = factory('BG95', port, baudrate=115200)
|
|
|
|
with module:
|
|
# 1. Initialization
|
|
module.radio_on()
|
|
module.activate_pdp_context(context_id=1)
|
|
|
|
# 2. Upload Certificates (Assume they are locally available)
|
|
# module.upload_file("ca.crt", b"-----BEGIN CERTIFICATE-----\n...")
|
|
|
|
# 3. Configure SSL Context
|
|
module.ssl_configure(ssl_ctx_id=0, cacert="ca.crt")
|
|
|
|
# 4. Configure MQTT to use SSL Context 0
|
|
module.set_qcfg("mqtt/ssl", 1) # Specific QCFG for some firmwares
|
|
module.mqtt_configure(client_idx=0, keepalive=120)
|
|
|
|
# 5. Connect to Broker
|
|
print(f"Connecting to MQTT Broker via {port}...")
|
|
if module.mqtt_open(client_idx=0, host="your-iot-endpoint.amazonaws.com", port=8883) == 0:
|
|
if module.mqtt_connect(client_idx=0, client_id="my_device_01") == 0:
|
|
print("Connected! Publishing data...")
|
|
|
|
# 6. Publish data
|
|
module.mqtt_publish(client_idx=0, msg_id=1, qos=1, retain=0,
|
|
topic="sensors/temperature", message='{"value": 24.5}')
|
|
|
|
module.mqtt_subscribe(client_idx=0, msg_id=2, topic="commands/#", qos=1)
|
|
print("Subscribed to commands/#. Waiting for messages...")
|
|
|
|
# Poll for 10 seconds to catch incoming MQTT messages via URC
|
|
for _ in range(10):
|
|
module.poll(1.0)
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser(description="Run MQTT demo.")
|
|
parser.add_argument("port", nargs="?", default="/dev/ttyUSB0", help="Serial port (e.g. /dev/ttyUSB0 or MOCK)")
|
|
args = parser.parse_args()
|
|
run_mqtt_demo(args.port)
|