|
| 1 | +# SPDX-FileCopyrightText: 2024 Liz Clark for Adafruit Industries |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +import time |
| 6 | +import serial |
| 7 | +from Adafruit_IO import MQTTClient |
| 8 | + |
| 9 | +# Configuration |
| 10 | +com_port = 'COM123' # Adjust this to your COM port |
| 11 | +baud_rate = 115200 |
| 12 | +FEED_ID = 'pixel-feed' |
| 13 | +# Set to your Adafruit IO key. |
| 14 | +# Remember, your key is a secret, |
| 15 | +# so make sure not to publish it when you publish this code! |
| 16 | +ADAFRUIT_IO_KEY = 'your-aio-key' |
| 17 | + |
| 18 | +# Set to your Adafruit IO username. |
| 19 | +# (go to https://accounts.adafruit.com to find your username) |
| 20 | +ADAFRUIT_IO_USERNAME = 'your-aio-username' |
| 21 | + |
| 22 | +print("Connecting to Adafruit IO...") |
| 23 | + |
| 24 | +# Initialize the serial connection |
| 25 | +ser = serial.Serial(com_port, baud_rate) |
| 26 | + |
| 27 | +# Define callback functions |
| 28 | +def connected(client): |
| 29 | + client.subscribe(FEED_ID) |
| 30 | +# pylint: disable=unused-argument, consider-using-sys-exit |
| 31 | +def subscribe(client, userdata, mid, granted_qos): |
| 32 | + # This method is called when the client subscribes to a new feed. |
| 33 | + print(f"Subscribed to {FEED_ID}") |
| 34 | + |
| 35 | +def disconnected(client): |
| 36 | + print('Disconnected from Adafruit IO!') |
| 37 | + exit(1) |
| 38 | + |
| 39 | +def message(client, feed_id, payload): |
| 40 | + print(f'Feed {feed_id} received new value: {payload}') |
| 41 | + color_value = payload.strip().replace('#', '0x') # Replace # with 0x |
| 42 | + ser.write(color_value.encode()) # Send the color value to the serial port |
| 43 | + |
| 44 | +# Initialize the Adafruit IO MQTT client |
| 45 | +mqtt_client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) |
| 46 | + |
| 47 | +# Setup the callback functions |
| 48 | +mqtt_client.on_connect = connected |
| 49 | +mqtt_client.on_disconnect = disconnected |
| 50 | +mqtt_client.on_message = message |
| 51 | +mqtt_client.on_subscribe = subscribe |
| 52 | + |
| 53 | +# Connect to Adafruit IO |
| 54 | +mqtt_client.connect() |
| 55 | + |
| 56 | +# Start a background thread to listen for MQTT messages |
| 57 | +mqtt_client.loop_blocking() |
| 58 | + |
| 59 | +# Keep the script running |
| 60 | +while True: |
| 61 | + try: |
| 62 | + time.sleep(1) |
| 63 | + except KeyboardInterrupt: |
| 64 | + print('Script interrupted by user') |
| 65 | + break |
| 66 | + |
| 67 | +# Close the serial connection when done |
| 68 | +ser.close() |
0 commit comments