Multiple sensor publishing via MQTT

In a separate (old) thread I found the workaround for email/sms flooding that occurs with triggers on the cayenne dashboard (code from the solution below). I have implemented this successfully for one sensor - but I have multiple sensors on a raspberry pi - (all reporting on the Cayenne dashboard). I also already have a different MQTT script publishing another calculated value every few minutes to the BYOD dashboard.

Being new to MQTT - all the examples seem to explain publishing the status change (or value) of a single sensor per script. Can someone point me to any examples or resources on how to publish multiple sensors from the same script?

type or paste code here

#!/usr/bin/env python
import cayenne.client
import time
import logging
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(40, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 10 to be an input pin and set initial value to be pulled low (off)

# Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
MQTT_USERNAME  = "xxx"
MQTT_PASSWORD  = "xxx"
MQTT_CLIENT_ID = "xxx"

TRIGGER_CHANNEL = 2  #Virtual channel for publishing the trigger value.
i=0
timestamp = 0

# The callback for when a message is received from Cayenne.
def on_message(message):    
    print("message received: " + str(message))
    # If there is an error processing the message return an error string, otherwise return nothing.

client = cayenne.client.CayenneMQTTClient()
client.on_message = on_message
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, loglevel=logging.INFO)
# For a secure connection use port 8883 when calling client.begin:
# client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883, loglevel=logging.INFO)

previousState = -1
currentState = -1

while True:
    client.loop()
    if (time.time() > timestamp + 5):
        currentState =  GPIO.input(40)
        print(currentState)
        if (currentState != previousState):
                client.virtualWrite(TRIGGER_CHANNEL, currentState, "digital_sensor", "d")
                previousState = currentState
        timestamp = time.time()

you need to use the below code if it is a sensor value

    global crossed_threshold
    if (((sensor_value >= threshold) and not send_below_threshold) or ((sensor_value < threshold) and send_below_threshold)):
        if not crossed_threshold:
            client.virtualWrite(trigger_channel, 1, "digital_sensor", "d")
            crossed_threshold = True
    else:
        client.virtualWrite(trigger_channel, 0, "digital_sensor", "d")
        crossed_threshold = False

if you want to digital status like the code above then just check for the state change.

1 Like