Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
import paho.mqtt.client as mqtt
import random
import time
from datetime import date, datetime
import json
# define client
client = mqtt.Client("temperature")
# connect to the broker on an appropriate port
client.connect("broker.hivemq.com", 1883)
# infinite loop to generate data from fake sensor devices
while True:
# 1 tempurature sensor
Temperature = random.randint(5, 30) # gives random temperature number
status = True # This will tell us if the sensor is On or Off
day = date.today() # date function call
clock = datetime.now() # time function calls
time_time = datetime.time(clock) # The exact time stamp
# store all data into array 'data'
data = [Temperature, status, str(day), str(time_time)]
# encode array 'data' into json data format to send it through topic
data_encoded = json.dumps(data)
# publish data to topics and print
client.publish("cartrax/temperature_sensor/data", data_encoded)
# print message with data, time and date to check if it is published
print("Just published: id- " + str(Temperature) + "; status- " + str(status) + "; day- " + str(day) + "; time- " + str(time_time) +
" to topic: 'cartrax/temperature_sensor/data'\n")
# publish new entry between 3 and 10 seconds
time.sleep(3)