Hi everyone,
I am building an IoT project to send some sensor data to a server. Presently I am using a DHT11 for temperature data. I'll expand later to include more sensors. So for this project, I have got my hands on an arduino UNO, a DHT11 and an esp8266 module.
I want to send this data to the server using mqtt protocol with SSL.
Presently I am using my uno to read data from DHT and print it on serial. Here's the code for that
#include <dht.h> // Include library
#define outPin 8 // Defines pin number to which the sensor is connected
dht DHT; // Creates a DHT object
void setup() {
Serial.begin(9600);
}
void loop() {
int readData = DHT.read11(outPin);
float t = DHT.temperature; // Read temperature
float h = DHT.humidity; // Read humidity
Serial.println(t);
delay(2000); // wait two seconds
}
and I have made a python code to read data from the serial and write send it through mqtt. here's the code:
import random
from paho.mqtt import client as mqtt_client
import json
import serial
from time import sleep
broker = 'something.something.com'
port = 8883
topic = 'dataset'
client_id = f'python-mqtt-{random.randint(0, 1000)}'
username = 'username'
password = 'password'
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
# Set Connecting Client ID
client = mqtt_client.Client(client_id)
# Set CA certificate
client.tls_set(ca_certs='certificate.crt')
client.username_pw_set(username, password)
client.on_connect = on_connect
client.connect(broker, port)
return client
def publish(client):
arduino = serial.Serial('COM4', 9800, timeout=1)
sleep(2)
while True:
data=arduino.readline()
if data:
data=data.decode().strip()
#print(data)
dict={"sensor_id": 52647892, #some random int for now
"data": {"temp":float(data)},
"time": "14:30",
"month": f"2023-06-22"}
print(dict)
json_data=json.dumps(dict)
result = client.publish(topic, json_data)
if result[0] == 0:
print(f"published")
else:
print(f"Failed to send message to topic {topic}")
def run():
client = connect_mqtt()
client.loop_start()
publish(client)
if __name__ == '__main__':
run()
I have a file that contains the SSL certificate that this code is using. This thing works perfectly, the data is going to the server properly. I came up with this methodology (of sending data through serial and then through python) as the esp was still on its way. now the esp has been delivered.
I want to wire my esp8266 module to my arduino uno and then send data through it to my mqtt server using SSL certificate. I have to have use this sever only and it will not work without this SSL certificate. I searched on the internet but couldn't find anything. I saw tutorials using nodemcu directly but I have already ordered these and even if I order the nodemcu it will take some time to arrive (I am short on time). Can anyone help on how can I do this with the UNO and esp8266 module that I currently have?
Thanks for the help