MQTT messages from Python not being published to AWS IoT Core / Amazon Timestream

170 Views Asked by At

I am working to send messages from an Arduino board (connected to DHT11 sensor and IR breakbeam) to AWS IoT Core. It seems that messages are being published, but the messages are not showing up in my AWS account. I have a rule set up that will send data from IoT Core to an Amazon Timestream table.

I am new to MQTT and IoT, so any help would be much appreciated.

Here is the documentation I used to set up the project:

AWS Build a Digital Twin

I am reading a DHT11 sensor and IR breakbeam sensor in Arduino and printing results in the serial. Here is the code for this:

#include "DHT.h"

#define SENSORPIN 10
#define DHTPIN 4
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);
int sensorState = 0;

void setup() {
  pinMode(SENSORPIN, INPUT);
  digitalWrite(SENSORPIN, HIGH); // turn on the pullup
  
  Serial.begin(9600);

  Serial.println(F("DHTxx test!"));
  dht.begin();
}

void loop() {
  sensorState = digitalRead(SENSORPIN);
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
   // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  Serial.print(h);
  Serial.print(",");
  Serial.print(t);
  Serial.print(",");
  Serial.println(sensorState);
  delay(2000);
}

I am then reading these messages from the serial in Python and attempting to send it to AWS using an MQTT protocol. Here is the code for this:

import random
import paho.mqtt.client as mqtt
import json
import serial
from time import sleep

broker = "{endpoint}.amazonaws.com"
port = 8883
topic = 'my/topic'
client_id = f'python-mqtt-{random.randint(0, 1000)}'
root_ca_path = 'rootCA.pem'
cert_path = 'device-cert.pem.crt'
key_path = 'private.pem.key'

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print(f"Failed to connect, return code {rc}")

    # Set Connecting Client ID
    client = mqtt.Client(client_id)
    # Set CA certificate, client certificate, and private key
    client.tls_set(ca_certs=root_ca_path, certfile=cert_path, keyfile=key_path)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def publish(client):
    arduino = serial.Serial('COM3', 9600, timeout=1)
    sleep(2)
    while True:
        data = arduino.readline()
        if data:
            data = data.decode().strip()
            values = data.split(',')
            if len(values) == 3:
                temperature = float(values[0])
                humidity = float(values[1])
                occupant = float(values[2])

                dict_data = {
                    "temperature": temperature,
                    "humidity": humidity,
                    "desk_state": occupant
                }
                print(dict_data)
                json_data = json.dumps(dict_data)
                result = client.publish(topic, json_data)
                if result.rc == mqtt.MQTT_ERR_SUCCESS:
                    print("Published")
                else:
                    print(f"Failed to send message to topic {topic}")

                sleep(2)

def run():
    client = connect_mqtt()
    client.loop_start()
    publish(client)

if __name__ == '__main__':
    run()

When I run this code, I receive the following output, which insinuates that messages are being published successfully:

Connected to MQTT Broker! {'temperature': 60.0, 'humidity': 23.4, 'desk_state': 1.0} Published Connected to MQTT Broker! {'temperature': 60.0, 'humidity': 23.4, 'desk_state': 1.0} Published Connected to MQTT Broker! {'temperature': 60.0, 'humidity': 23.4, 'desk_state': 1.0} Published

However, no messages are showing up in Amazon Timestream, and no errors are logged in Amazon Cloudwatch. I have also tried using the AWSIOTPythonSDK.MQTTLib library, but with an identical result.

Any ideas on where an error could be occurring?

0

There are 0 best solutions below