Advertisement
Guest User

Untitled

a guest
May 2nd, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.88 KB | None | 0 0
  1. #!/usr/bin/env python2.7
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import smtplib
  5. import time, datetime
  6. from time import strftime
  7. import MySQLdb
  8. import RPi.GPIO as GPIO
  9. import sys  
  10. import random
  11.  
  12. alerted = 0
  13. higalerted = 0
  14.  
  15. os.system('modprobe w1-gpio')
  16. os.system('modprobe w1-therm')
  17.  
  18. def temp_raw():
  19.     f = open('/sys/bus/w1/devices/28-0000059dfde7/w1_slave','r')
  20.     lines = f.readlines()
  21.     f.close()
  22.     return lines
  23.  
  24. def read_temp():
  25.     lines = temp_raw()
  26.     while lines[0].strip()[-3:] != 'YES':
  27.         time.sleep(0.2)
  28.         lines = temp_raw()
  29.     temp_output = lines[1].find('t=')
  30.     if temp_output != -1:
  31.         temp_string = lines[1].strip()[temp_output+2:]
  32.         temp_c = float(temp_string) / 1000.0
  33.         temp_f = temp_c * 9.0 / 5.0 + 32.0
  34.     return temp_c, temp_f
  35.  
  36. def mysql_datetime():
  37.     t = datetime.datetime.now()
  38.     day = t.day
  39.     month = t.month
  40.     year = t.year
  41.     hour = t.hour+1
  42.     minute = t.minute
  43.     dtime = "%d-%02d-%02d %02d:%02d:00" % (year,month,day,hour,minute)
  44.     return dtime
  45.    
  46. def plaintime():
  47.     t = datetime.datetime.now()
  48.     minute = t.minute
  49.     if t.hour > 11:
  50.         if t.hour > 12:
  51.             hour = t.hour - 12
  52.         else:
  53.             hour = t.hour
  54.         return "%d:%02dpm" % (hour, minute)
  55.     else:
  56.         if t.hour  == 0:
  57.             hour = 12
  58.         else:
  59.             hour = t.hour
  60.         return "%d:%02dam" % (hour, minute)
  61.    
  62. def temp_post():
  63.     temps = read_temp()
  64.     tempc = temps[0]            #temps[0] reads Celcius value, temps[1] reads fahrenheit
  65.     temp = "%3.1f" % tempc
  66.     ptime = plaintime()
  67.     datetime = mysql_datetime()
  68.     conn = MySQLdb.connect(host="localhost",user="pytemp",passwd="celcius",db="roomtemp")
  69.     cur = conn.cursor()
  70.     sql = ("""INSERT INTO roomtemp.temperatures (datetime,plaintime,temp) VALUES (%s,%s,%s)""", (datetime,ptime,temp))
  71.     try:
  72.         cur.execute(*sql)
  73.         conn.commit()
  74.     except:
  75.         conn.rollback()
  76.  
  77. def sendalert(emailbody):
  78.         SMTP_SERVER = ''
  79.         SMTP_PORT = 587
  80.         EMAIL_USERNAME = ''
  81.         EMAIL_PASSWORD = '' #CAUTION: This is stored in plain text!
  82.  
  83.         recipient = ''
  84.         subject = 'SERVER ROOM TEMPERATURE ALERT'
  85.  
  86.         emailText = emailbody
  87.  
  88.         headers = ["From: " + EMAIL_USERNAME, "Subject: " + subject, "To: " + recipient, "MIME-Version: 1.0", "Content-Type: text/html"]
  89.         headers = "\r\n".join(headers)
  90.  
  91.         session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
  92.  
  93.         session.ehlo()
  94.         session.starttls()
  95.         session.ehlo
  96.  
  97.         session.login(EMAIL_USERNAME, EMAIL_PASSWORD)
  98.  
  99.         session.sendmail(EMAIL_USERNAME, recipient, headers + "\r\n\r\n" + emailText)
  100.         session.quit()
  101.  
  102. def alerttest():
  103.     global alerted
  104.     global highalerted
  105.     alerted()
  106.     temps = read_temp()
  107.     temp = temps[0]
  108.     nowtemp="Current temperature is %2.2f degrees C" % temp
  109.  
  110.     if highalerted == 0:
  111.         if temp > 25:
  112.             sethighalerted(1)          
  113.             message = "Temperature in server room is over 25 degrees! "+temptext
  114.             sendalert(message)
  115.         else:
  116.             sethighalerted(0)
  117.     else:
  118.         if temp > 25:
  119.             sethighalerted(1)          
  120.         else:
  121.             sethighalerted(0)      
  122.  
  123.     rows = []
  124.     db = MySQLdb.connect(host="localhost", user="pytemp", passwd="celcius", db="roomtemp")
  125.     cur = db.cursor()
  126.     cur.execute("SELECT temp FROM roomtemp.temperatures order by id desc limit 30")
  127.     for row in cur.fetchall():
  128.         newrow = row[0]
  129.         rows.append( newrow )
  130.     if temp > 18:
  131.         if alerted == 0:
  132.             if (rows[0] - 2.99) > rows[29]:
  133.                 message = "Temperature in the server room has risen 3 degrees in 1 hour".nowtemp
  134.                 sendalert(message)
  135.                 setalerted(1)
  136.             elif (rows[0] - 2.49) > rows[24]:
  137.                 message = "Temperature in the server room has risen 2.5 degrees in 50 minutes".nowtemp
  138.                 sendalert(message)
  139.                 setalerted(1)
  140.             elif (rows[0] - 1.99) > rows[19]:
  141.                 message = "Temperature in the server room has risen 2 degrees in 40 minutes".nowtemp
  142.                 sendalert(message)
  143.                 setalerted(1)
  144.             elif (rows[0] - 1.49) > rows[14]:
  145.                 message = "Temperature in the server room has risen 1.5 degrees in 30 minutes".nowtemp
  146.                 sendalert(message)
  147.                 setalerted(1)  
  148.             elif (rows[0] - 0.99) > rows[9]:
  149.                 message = "Temperature in the server room has risen 1 degree in 20 minutes".nowtemp
  150.                 sendalert(message)
  151.                 setalerted(1)
  152.             elif (rows[0] - 0.49) > rows[4]:
  153.                 message = "Temperature in the server room has risen 0.5 degrees in 10 minutes".nowtemp
  154.                 sendalert(message)
  155.                 setalerted(1)
  156.             else:
  157.                 setalerted(0)
  158.         else:
  159.             if (rows[0] - 2.99) > rows[29]:
  160.                 setalerted(1)
  161.             elif (rows[0] - 2.49) > rows[24]:
  162.                 setalerted(1)
  163.             elif (rows[0] - 1.99) > rows[19]:
  164.                 setalerted(1)
  165.             elif (rows[0] - 1.49) > rows[14]:
  166.                 setalerted(1)  
  167.             elif (rows[0] - 0.99) > rows[9]:
  168.                 setalerted(1)
  169.             elif (rows[0] - 0.49) > rows[4]:
  170.                 setalerted(1)
  171.             else:
  172.                 setalerted(0)
  173.     db.close()
  174.    
  175. def alerted():
  176.     global alerted
  177.     global highalerted
  178.     db = MySQLdb.connect(host="localhost", user="pytemp", passwd="celcius", db="roomtemp")
  179.     cur = db.cursor()
  180.     cur.execute("select yes_no from alerted order by ID desc limit 1")
  181.     alerted = cur.fetchone()[0]
  182.     cur.execute("select yes_no from highalerted order by ID desc limit 1")
  183.     highalerted = cur.fetchone()[0]
  184.     db.close()
  185.  
  186.  
  187.  
  188. def setalerted(value):
  189.     conn = MySQLdb.connect(host="localhost",user="pytemp",passwd="celcius",db="roomtemp")
  190.     cur = conn.cursor()
  191.     sql = ("""INSERT INTO roomtemp.alerted (yes_no) VALUES (%s)""", (value))
  192.     try:
  193.         cur.execute(*sql)
  194.         conn.commit()
  195.     except:
  196.         conn.rollback()
  197.  
  198. def sethighalerted(value):
  199.     conn = MySQLdb.connect(host="localhost",user="pytemp",passwd="celcius",db="roomtemp")
  200.     cur = conn.cursor()
  201.     sql = ("""INSERT INTO roomtemp.highalerted (yes_no) VALUES (%s)""", (value))
  202.     try:
  203.         cur.execute(*sql)
  204.         conn.commit()
  205.     except:
  206.         conn.rollback()
  207.  
  208. #temp_post()
  209. #alerttest()
  210. testmessage = "This is a test message, nothing to worry about!"
  211. #sendalert(testmessage)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement