Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import urllib.request, json, csv, os, web
- from collections import deque
- from dateutil import parser
- from datetime import datetime
- #configuration
- alert_value = 150
- station_id = "5690"
- api_url = "http://api.luftdaten.info/v1/sensor/"
- csv_path = os.path.dirname(os.path.realpath(__file__))+"/"+"air_data_" + station_id + ".csv"
- # configure smtp server for sending mail
- web.config.smtp_server = 'smtp.gmail.com'
- web.config.smtp_port = 587
- web.config.smtp_username = 'xxxx@gmail.com'
- web.config.smtp_password = 'xxxxxxx'
- web.config.smtp_starttls = True
- #Notification recipients
- email_list = []
- email_list.append("jeleff@gmail.com")
- #read air data from joson and get average values
- def get_air_data(station_id):
- p1, p2 = [],[]
- with urllib.request.urlopen(api_url+station_id) as url:
- data = json.loads(url.read().decode())
- for results in data:
- timestamp = results['timestamp']
- if 'sensordatavalues' in results:
- for readings in results['sensordatavalues']:
- if readings['value_type'] == 'P1':
- p1.append(float(readings['value']))
- elif readings['value_type'] == 'P2':
- p2.append(float(readings['value']))
- return int(sum(p1)/len(p1)), int(sum(p2)/len(p2)),timestamp
- # Save the air data to csv
- def write_to_csv(p1,p2,timestamp):
- with open(csv_path,"a") as csv_file:
- csv_app = csv.writer(csv_file)
- csv_app.writerow([p1,p2,timestamp])
- # Read the last record from csv and get last alert date
- def get_last_row(csv_filename):
- with open(csv_filename, 'r') as f:
- try:
- lastrow = deque(csv.reader(f), 1)[0]
- except IndexError: # empty file
- lastrow = None
- return lastrow[2]
- #Check if there was an alert today
- def alert_today(adate):
- if (datetime.today() - adate).days == 0:
- return True
- else:
- return False
- #Send email notification
- def send_message(message): #sends emails to email_list
- for recipient in email_list:
- web.sendmail(web.config.smtp_username, recipient,"Air Polution Alert", message, headers={'Content-Type':'text/html;charset=utf-8'})
- if __name__ == '__main__':
- p1, p2, timestamp = get_air_data(station_id)
- print(p1,p2)
- if p1 > alert_value or p2 > alert_value:
- print('We need to send an alert')
- # Get last alert date from the last record in the csv file
- last_alert_date = get_last_row(csv_path)
- # Check if there was an alert today
- if alert_today(parser.parse(last_alert_date)):
- print('There was an alert today')
- else:
- print('No alert today')
- send_message("P1 = "+str(p1)+"\r\n P2 = " + str(p2))
- write_to_csv(p1,p2,timestamp)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement