Skip to content

Instantly share code, notes, and snippets.

@sundarsrst
Created April 28, 2021 15:16
Show Gist options
  • Save sundarsrst/6060cee8d6a5f79df7056badfbe7286e to your computer and use it in GitHub Desktop.
Save sundarsrst/6060cee8d6a5f79df7056badfbe7286e to your computer and use it in GitHub Desktop.
import paho.mqtt.client as paho
import ssl
from time import sleep
from random import uniform
import datetime
import json
import random
from randmac import RandMac
# timeStamp = datetime.datetime.now()
# geyserMessage = {
# "timeStamp":"",
# "temperature":"",
# }
connflag = False
topicc = 'mytemperatureTopic'
clienttopic = 'mytemperatureReceiveTopic'
a = 'On'
b = 'Off'
def on_connect(client, userdata, flags, rc): # func for making connection
global connflag
print("Connected to AWS")
connflag = True
print("Connection returned result: " + str(rc) )
def on_message(client, userdata, msg): # Func for Sending msg
print(msg.topic+" "+str(msg.payload))
# def subscribe(client):
# def on_message(client, userdata, msg):
# print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
# client.subscribe(clienttopic)
# client.on_message = on_message
mqttc = paho.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message # assign on_message func
awshost = "a3fuo8k656sxt0-ats.iot.us-east-1.amazonaws.com" # Endpoint
awsport = 8883 # Port no.
clientId = "myThing3" # Thing_Name
thingName = "myThing3" # Thing_Name
caPath = "AmazonRootCA1.pem.crt" # Root_CA_Certificate_Name
certPath = "2f8006193d-certificate.pem.crt" # <Thing_Name>.cert.pem.crt. Thing's certificate from Amazon
keyPath = "2f8006193d-private.pem.key" # <Thing_Name>.private.key Thing's private key from Amazon
mqttc.tls_set(ca_certs=caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None) # pass parameters
mqttc.connect(awshost, awsport, keepalive=60) # connect to aws server
mqttc.loop_start() # Start the loop
while 1:
#sleep(300)
#sleep(5)
if connflag == True:
# macid = RandMac()
timeStamp = datetime.datetime.now()
macid = "a2:66:d6:6e:7d:96"
tempreading = int(uniform(20,100))
flameStatus = random.choice([a, b])
gasStatus = random.choice([a, b])
errorStatus = int(uniform(5,15))
message = '{"timeStamp":'+'"'+str(timeStamp)+'",'+'"macid":'+'"'+str(macid)+'",'+'"temperature":'+str(tempreading)+', "errorStatus":'+str(errorStatus)+', "gasStatus":'+'"'+str(gasStatus)+'","flameStatus":'+'"'+str(flameStatus)+'"}'
# message = '{"macid":'+'"'+str(macid)+'",'+'"temperature":'+str(tempreading)+', "errorStatus":'+str(errorStatus)+', "gasStatus":'+'"'+str(gasStatus)+'","flameStatus":'+'"'+str(flameStatus)+'"}'
mqttc.publish(topicc, message, 1)
print(f"msg sent: temperature : {tempreading}" )
else:
print("waiting for connection...")
mqttc.subscribe(clienttopic, qos=1) #receive messages from lambda | subscribe to iot topic
sleep(300)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment