Last active
January 15, 2025 18:45
-
-
Save MichaelBell/ace44a6d793f2bddd7bee87e19313c75 to your computer and use it in GitHub Desktop.
Simple MQTT monitoring script using BME280 and LTE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from umqtt.simple import MQTTClient | |
| from secrets import MQTT_SERVER, MQTT_USER, MQTT_PASS | |
| import machine | |
| import time | |
| import ntptime | |
| import gc | |
| from breakout_bme280 import BreakoutBME280 | |
| from pimoroni_i2c import PimoroniI2C | |
| PINS_BREAKOUT_GARDEN = {"sda": 4, "scl": 5} | |
| i2c = PimoroniI2C(**PINS_BREAKOUT_GARDEN) | |
| bme = BreakoutBME280(i2c) | |
| reading = bme.read() | |
| print(reading) | |
| time.sleep(20) | |
| log_file = open("log.txt", "a") | |
| # Test reception e.g. with: | |
| # mosquitto_sub -t foo_topic | |
| import lte | |
| import json | |
| import ssl | |
| MOBILE_APN = "iot.1nce.net" | |
| # Slower clock to save some power | |
| machine.freq(48000000) | |
| con = lte.LTE(MOBILE_APN) | |
| con.start_ppp() | |
| print("PPP Connected") | |
| ntptime.settime() | |
| ltime = time.localtime() | |
| log_file.write(f"{ltime[3]:02d}:{ltime[4]:02d} Starting\n") | |
| try: | |
| while True: | |
| try: | |
| reading = bme.read() | |
| ltime = time.localtime() | |
| log_file.write(f"{ltime[3]:02d}:{ltime[4]:02d} Sending: {reading}...") | |
| c = MQTTClient(client_id="Clipper", server=MQTT_SERVER, user=MQTT_USER, password=MQTT_PASS, keepalive=30, ssl=ssl) | |
| c.connect() | |
| log_file.write(" connected...") | |
| c.publish(b"bme", json.dumps(reading)) | |
| c.disconnect() | |
| log_file.write(" done.\n") | |
| except Exception as e: | |
| log_file.write(" failed.\n") | |
| log_file.write(f"Exception: {type(e)}: {e}\n") | |
| if isinstance(e, KeyboardInterrupt): | |
| raise | |
| log_file.flush() | |
| c = None | |
| gc.collect() | |
| #time.sleep(600) | |
| time.sleep(300) | |
| finally: | |
| log_file.write("Disconnecting\n") | |
| log_file.close() | |
| print("Disconnecting...") | |
| con.stop_ppp() | |
| print("Done!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment