Permalink
Cannot retrieve contributors at this time
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?
Cartrax/Temperature_Sensor.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
36 lines (28 sloc)
1.27 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |