Advertisement
Masoko

Air Pollution Check api.luftdaten.info

Dec 1st, 2017
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.62 KB | None | 0 0
  1. import urllib.request, json, csv, os, web
  2. from collections import deque
  3. from dateutil import parser
  4. from datetime import datetime
  5.  
  6.  
  7. #configuration
  8. alert_value = 150
  9. station_id = "5690"
  10. api_url = "http://api.luftdaten.info/v1/sensor/"
  11. csv_path = os.path.dirname(os.path.realpath(__file__))+"/"+"air_data_" + station_id + ".csv"
  12.  
  13. # configure smtp server for sending mail
  14. web.config.smtp_server = 'smtp.gmail.com'
  15. web.config.smtp_port = 587
  16. web.config.smtp_username = 'xxxx@gmail.com'
  17. web.config.smtp_password = 'xxxxxxx'
  18. web.config.smtp_starttls = True
  19.  
  20. #Notification recipients
  21.  
  22. email_list = []
  23. email_list.append("jeleff@gmail.com")
  24.  
  25. #read air data from joson and get average values
  26. def get_air_data(station_id):
  27.     p1, p2 = [],[]
  28.     with urllib.request.urlopen(api_url+station_id) as url:
  29.         data = json.loads(url.read().decode())
  30.         for results in data:
  31.            
  32.             timestamp = results['timestamp']
  33.             if 'sensordatavalues' in results:
  34.                 for readings in results['sensordatavalues']:
  35.  
  36.                     if readings['value_type'] == 'P1':
  37.                         p1.append(float(readings['value']))
  38.                        
  39.                     elif readings['value_type'] == 'P2':
  40.                         p2.append(float(readings['value']))                    
  41.                
  42.     return int(sum(p1)/len(p1)),  int(sum(p2)/len(p2)),timestamp
  43.  
  44. # Save the air data to csv
  45. def write_to_csv(p1,p2,timestamp):
  46.     with open(csv_path,"a") as csv_file:
  47.         csv_app = csv.writer(csv_file)
  48.         csv_app.writerow([p1,p2,timestamp])
  49.        
  50. # Read the last record from csv and get last alert date
  51. def get_last_row(csv_filename):
  52.     with open(csv_filename, 'r') as f:
  53.         try:
  54.             lastrow = deque(csv.reader(f), 1)[0]
  55.         except IndexError:  # empty file
  56.             lastrow = None
  57.         return lastrow[2]
  58.        
  59. #Check if there was an alert today
  60. def alert_today(adate):
  61.     if (datetime.today() - adate).days == 0:
  62.         return True
  63.     else:
  64.         return False
  65.  
  66. #Send email notification
  67. def send_message(message): #sends emails to email_list
  68.     for recipient in email_list:
  69.         web.sendmail(web.config.smtp_username, recipient,"Air Polution Alert", message, headers={'Content-Type':'text/html;charset=utf-8'})
  70.  
  71.        
  72. if __name__ == '__main__':
  73.     p1, p2, timestamp = get_air_data(station_id)
  74.     print(p1,p2)
  75.  
  76.     if p1 > alert_value or p2 > alert_value:
  77.         print('We need to send an alert')
  78.    
  79.         # Get last alert date from the last record in the csv file
  80.         last_alert_date = get_last_row(csv_path)
  81.         # Check if there was an alert today
  82.         if alert_today(parser.parse(last_alert_date)):
  83.             print('There was an alert today')
  84.         else:
  85.             print('No alert today')
  86.             send_message("P1 = "+str(p1)+"\r\n P2 = " + str(p2))
  87.             write_to_csv(p1,p2,timestamp)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement