import socket import pickle import time import sys from influxdb import InfluxDBClient import yagmail class Conditions: def __init__(self): self.temperature = None self.air_humidity = None self.soil_humidity = None self.air_speed = None def calculate_dif(temp, percentage): temp.sort() if (temp[4] - temp[0]) / temp[0] >= percentage: return True else: return False def gmail_send(code): with open("gmail_credentials.txt") as f: data = f.readlines() username = data[0].strip('\n') password = data[1].strip('\n') receiver = data[2].strip('\n') yag = yagmail.SMTP(username, password) temperature_content = "Attention! Atmos weather device detected a radical change of temperature. Please check the enviroment." humidity_content = "Attention! Atmos weather device detected a radical change of air humidity. Please check the enviroment." subject = "Atmos Urgent Notification" if code == 1: yag.send(receiver, subject, temperature_content) else: yag.send(receiver, subject, humidity_content) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 3125 s.bind(('0.0.0.0', port)) print ('Socket binded to port 3125') s.listen(3) print ('socket is listening') c, addr = s.accept() print ('Got connection from ' + str(addr) + ' \n') client = InfluxDBClient(host='localhost', port=8086) databases = client.get_list_database() exists = False for i in databases: if('atmos' in i['name']): exists = True if(exists): client.switch_database('atmos') print("Switched to 'atmos' database\n") else: client.create_database('atmos') print("Created database 'atmos'\n") client.switch_database('atmos') received = 0 temperature_array = [] airhumidity_array = [] while True: unpickled_object = pickle.loads(c.recv(4096)) received += 1 temperature_array.append(unpickled_object.temperature) airhumidity_array.append(unpickled_object.air_humidity) if(received == 5 ): is_temp = calculate_dif(temperature_array, 0.4) is_hum = calculate_dif(airhumidity_array, -0.5) if is_temp: print("\nTemperature critical difference!!!") print("Will now send notification email.\n") gmail_send(1) if is_hum: print("\nHumidity critical difference!!!") print("Will now send notification email.\n") gmail_send(2) #resetting values temperature_array.clear() airhumidity_array.clear() received = 0 json_body = [ { "measurement": "tablePython", "tags": { "location": "Athens" }, "fields": { "temperature": str(int(unpickled_object.temperature)), "soil_humidity": str(int(unpickled_object.soil_humidity*100)), "air_humidity": str(int(unpickled_object.air_humidity*100)), "air_speed": str(unpickled_object.air_speed) } } ] client.write_points(json_body) print("Current temperature: " + str(int(unpickled_object.temperature)) + " Celcius") print("Current soil humidity: " + str(int(unpickled_object.soil_humidity*100)) + " %") print("Current air humidity: " + str(int(unpickled_object.air_humidity*100)) + "%") print("Current air speed: " + str(unpickled_object.air_speed) + " km/h\n") c.close()