Skip to content

Instantly share code, notes, and snippets.

@sundarsrst
Created April 28, 2021 02:00
Show Gist options
  • Save sundarsrst/cb3bab0cc21952bb62126844ed76cc23 to your computer and use it in GitHub Desktop.
Save sundarsrst/cb3bab0cc21952bb62126844ed76cc23 to your computer and use it in GitHub Desktop.
prabhat.py
import paho.mqtt.client as paho
import ssl, csv
from time import sleep
from random import uniform
import datetime
import random
import boto3
from datetime import datetime, timedelta
connflag = False
def on_connect(client, userdata, flags, rc): # func for making connection
global connflag
print("Connected to AWS")
connflag = True
#if connection is successful, rc value will be 0
print("Connection returned result: " + str(rc) )
#print(flags)
def on_message(client, userdata, msg): # Func for Sending msg
print(msg.topic+" "+str(msg.payload))
mqttc = paho.Client()
#create an mqtt client object
#attach call back function
mqttc.on_connect = on_connect
mqttc.on_message = on_message # assign on_message func
awshost = "a1x5074ceb3e27-ats.iot.us-east-1.amazonaws.com" # Endpoint
awsport = 8883 # Port no.
clientId = "aqi" # Thing_Name
thingName = "aqi" # Thing_Name
caPath = "AmazonRootCA1.pem.crt" #Amazon's certificate from Third party # Root_CA_Certificate_Name
certPath = "59820bc480-certificate.pem.crt" # <Thing_Name>.cert.pem.crt. Thing's certificate from Amazon
keyPath = "59820bc480-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
min_year=2019
max_year=datetime.now().year
start = datetime(min_year, 1, 1, 00, 00, 00)
years = max_year - min_year+1
end = start + timedelta(days=365 * years)
a = []
while 1:
sleep(1)
if connflag == True:
csv_columns = ['timeStamp','aqi']
# timeStamp = datetime.datetime.now()
random_date = start + (end - start) * random.random()
aqireading = uniform(5.0,500.0)
message = '{"timeStamp":'+'"'+str(random_date)+'",'+'"aqi":'+str(aqireading)+'}'
message1 = {"timeStamp": random_date, "aqi": aqireading}
a.append(message1)
csv_file = "aqicsv4.csv"
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns, lineterminator="\n")
writer.writeheader()
for data in a:
writer.writerow(data)
s3 = boto3.resource('s3')
s3.meta.client.upload_file('aqicsv4.csv', 'uploads3', 'aqicsv4.csv')
except IOError:
print("I/O error")
mqttc.publish("aqiTopic", message, 1)
print("msg sent: air quality index " + "%.2f" % aqireading )
else:
print("waiting for connection...")
# print(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment