lundi 29 août 2016

Wireless alarm with a Raspberry Pi with python

Script 'Alarme.py' launched by the daemon


this file is an infinity loop. We wait for receive RF433's signal.

 #!/usr/bin/env python  
 # coding: utf-8  
 import time  
 from datetime import datetime,timedelta  
 from SendSms import SendSMS  
 from SendMail import Send  
 from ReceiveRF433 import Receive  
 from DBAlarmeState import Select,Update  
 from PlanningDB import GetPlanningDB  
 """ DATA RECEIVE """  
 def sendAlarme(message):  
      SendSMS(message)  
      Send("your.mail@gmail.com",message)       
 def SelectHourPlanning():  
      #get planing from base  
      planning=GetPlanningDB()  
      heure=time.localtime().tm_hour+2  
      mydate=datetime.now()  
      jour=mydate.weekday()  
      #print "Planning hour %s" %heure  
      #print "Planning set to %s" %planning[jour*24+heure]  
      return planning[jour*24+heure]  
 def StartAlarmeRF433():  
      #timer  
      period=timedelta(minutes=1)  
      next_time = datetime.now() + period  
      #Init RF433 pin 2  
      R=Receive()  
      R.init()  
      while True:  
           try:       
                if R.available():  
                     data= R.getReceivedValue()  
                     if data==55064 : #replace by your code  
                       #door opened  
                          #print "Door opened"  
                          #print Select()  
                          if next_time<datetime.now() and SelectHourPlanning()=="1" and Select()==1 :  
                               sendAlarme("Alarm door openede")  
                               next_time=2*period+datetime.now()                                
                     if data==5316 :  
                          #other sensor  
                          if next_time<datetime.now() and SelectHourPlanning()=="1" and Select()==1 :  
                               sendAlarme("Alarm sensor 2")  
                               next_time=2*period+datetime.now()  
                     #print "Code : %d" % data  
                     #reset  
                     R.resetAvailable()  
                     continue  
           except KeyboardInterrupt:  
                break          
 StartAlarmeRF433()  

few words about the source code : When alarm is fired, we look if alarm is enable and if the planning's user is enable too.

The user's planning is get by 'GetPnnangDB.py'.

the function 'SelectHourPlanning()' return 1 is enable, 0 is disable. We look the current time if it is inside of the range of user's planning.

the function 'Select()' return state of Alarm 1 on, 0 is off

SendAlarme(message) send a mail and a sms.

A tips here ' period=timedelta(minutes=1)', to avoid too many signals, the program is waiting one minut before send a new alarm.

DBAlarmeState.py

 #!/usr/bin/python  
 # -*- coding: utf-8 -*-  
 import MySQLdb as mdb  
 import sys  
 def Insert(_date,_Status):  
      try:  
           con = mdb.connect('localhost', 'youLogin', 'yourPassword', 'ALARME');  
           stringSQL = "INSERT INTO AlarmeState(date,Status) VALUES (\'%s\',%d)" % (_date,_Status)  
           print stringSQL  
           with con:  
            cure = con.cursor()  
            cure.execute(stringSQL)  
      except mdb.Error, e:  
        print "Error %d: %s" % (e.args[0],e.args[1])  
        sys.exit(1)  
      finally:    
        if con:    
          con.close()  
 def Update(_date,_Status):  
      try:  
           con = mdb.connect('localhost','youLogin', 'yourPassword', 'ALARME');  
           stringSQL = "UPDATE AlarmeState SET date=\'%s\', Status=%d;" % (_date,_Status)  
           print stringSQL  
           with con:  
            cure = con.cursor()  
            cure.execute(stringSQL)  
      except mdb.Error, e:  
        print "Error %d: %s" % (e.args[0],e.args[1])  
        sys.exit(1)  
      finally:    
        if con:    
          con.close()  
 def Select():  
      try:  
           con = mdb.connect('localhost','youLogin', 'yourPassword', 'ALARME');  
           stringSQL = "SELECT Status FROM AlarmeState"  
           #print stringSQL  
           with con:  
            cure = con.cursor()  
            cure.execute(stringSQL)  
            _res= cure.fetchone()[0]  
      except mdb.Error, e:  
        print "Error %d: %s" % (e.args[0],e.args[1])  
        sys.exit(1)  
      finally:    
        if con:    
          con.close()  
      return _res  

PlanningDB.py

 #!/usr/bin/python  
 # -*- coding: utf-8 -*-  
 import MySQLdb as mdb  
 import sys  
 def GetPlanningDB():  
      try:  
          con = mdb.connect('localhost', 'youLogin', 'yourPassword', 'ALARME');  
           stringSQL ="SELECT Semaine FROM Plannings where PlanningName like 'alarme';"  
           #print stringSQL  
           with con:  
          cure = con.cursor()  
          cure.execute(stringSQL)  
          _res= cure.fetchone()[0]  
     except mdb.Error, e:  
       print "Error %d: %s" % (e.args[0],e.args[1])  
       sys.exit(1)  
     finally:  
       if con:  
         con.close()  
      return _res;  
 #print GetPlanningDB()  
in the next part we will see the web site !

Wireless alarm with a Raspberry Pi with python

Create the database

In order to store alarms we need a table called 'Sensors' (time, kind of sensor and so on...). And the user need to make the configuration of this alarms. So we need 2 other tables, the first one 'AlarmeState' for stored the state of the alarm (switch on or off ) and the second 'Plannings' for the planning's alarm of a week template.

All python's files to build the database :

  • After connected to mysql, create the database "ALARME" and user ('XXXX'@'localhost') :

    mysql> create database ALARME;

    mysql> CREATE USER 'yourLogin'@'localhost' IDENTIFIED BY 'yourPassword';

    mysql> GRANT ALL PRIVILEGES ON * . * TO 'yourLogin'@'localhost'

  • Install python lib to access mysql :

    sudo apt-get install python-mysqldb

  • create tables with python

    - python CreateAlarmeDB.py

     #!/usr/bin/python  
     # -*- coding: utf-8 -*-  
     import MySQLdb as mdb  
     import sys  
     try:  
          con = mdb.connect('localhost', 'yourLogin', 'yourPassword', 'ALARME');  
          with con:  
           cur = con.cursor()  
           cur.execute("DROP TABLE IF EXISTS Sensors")  
           cur.execute("CREATE TABLE Sensors(Id INT PRIMARY KEY AUTO_INCREMENT, \  
          Date DATETIME, Heure TIME,SensorName VARCHAR(25), \  
          SensorValue REAL, \  
          Status INT)")  
     except mdb.Error, e:  
       print "Error %d: %s" % (e.args[0],e.args[1])  
       sys.exit(1)  
     finally:    
       if con:    
         con.close()  
    

    - python CreatePlanningDB.py

     #!/usr/bin/python  
     # -*- coding: utf-8 -*-  
     import MySQLdb as mdb  
     import sys  
     try:  
          con = mdb.connect('localhost',  'yourLogin', 'yourPassword', 'ALARME');  
          with con:  
           cur = con.cursor()  
           cur.execute("DROP TABLE IF EXISTS Plannings")  
           cur.execute("CREATE TABLE Plannings(Id INT PRIMARY KEY AUTO_INCREMENT, \  
          PlanningName VARCHAR(25), \  
          Semaine VARCHAR(180))")  
     except mdb.Error, e:  
       print "Error %d: %s" % (e.args[0],e.args[1])  
       sys.exit(1)  
     finally:    
       if con:    
         con.close()  
    

    - python CreateTableState.py

     #!/usr/bin/python  
     # -*- coding: utf-8 -*-  
     import MySQLdb as mdb  
     import sys  
     try:  
          con = mdb.connect('localhost',  'yourLogin', 'yourPassword', 'ALARME');  
          with con:  
           cur = con.cursor()  
           cur.execute("DROP TABLE IF EXISTS AlarmeState")  
           cur.execute("CREATE TABLE AlarmeState(Id INT PRIMARY KEY AUTO_INCREMENT, \  
          Date DATETIME,Status INT)")  
     except mdb.Error, e:  
       print "Error %d: %s" % (e.args[0],e.args[1])  
       sys.exit(1)  
     finally:    
       if con:    
         con.close()  
    
  • Insert Data for the first time :

    python /ScriptPython/InsertDataAlarmeState.py

     #!/usr/bin/python  
     # -*- coding: utf-8 -*-  
     import MySQLdb as mdb  
     import sys  
     def Insert(_date,_Status):  
          try:  
               con = mdb.connect('localhost', 'yourLogin', 'yourPassword', 'ALARME');  
               stringSQL = "INSERT INTO AlarmeState(date,Status) VALUES (\'%s\',%d)" % (_date,_Status)  
               print stringSQL  
               with con:  
                cure = con.cursor()  
                cure.execute(stringSQL)  
          except mdb.Error, e:  
            print "Error %d: %s" % (e.args[0],e.args[1])  
            sys.exit(1)  
          finally:    
            if con:    
              con.close()  
     Insert('2015-12-07',1)  
     print "ok alarme on"  
    

    python /ScriptPython/InsertDataPlanningDB.py

     #!/usr/bin/python  
     # -*- coding: utf-8 -*-  
     import MySQLdb as mdb  
     import sys  
     try:  
         con = mdb.connect('localhost', 'yourLogin', 'yourPassword', 'ALARME');  
         with con:  
          cur = con.cursor()  
          cur.execute("INSERT INTO Plannings (PlanningName,Semaine) VALUES  (\'000000000000000000000000\',\'L\');");  
          cur.execute("INSERT INTO Plannings (PlanningName,Semaine) VALUES  (\'000000000000000000000000\',\'M\');");  
          cur.execute("INSERT INTO Plannings (PlanningName,Semaine) VALUES  (\'000000000000000000000000\',\'W\');");  
          cur.execute("INSERT INTO Plannings (PlanningName,Semaine) VALUES  (\'000000000000000000000000\',\'J\');");  
          cur.execute("INSERT INTO Plannings (PlanningName,Semaine) VALUES  (\'000000000000000000000000\',\'V\');");  
          cur.execute("INSERT INTO Plannings (PlanningName,Semaine) VALUES  (\'000000000000000000000000\',\'S\');");  
          cur.execute("INSERT INTO Plannings (PlanningName,Semaine) VALUES  (\'000000000000000000000000\',\'D\');");  
     except mdb.Error, e:  
       print "Error %d: %s" % (e.args[0],e.args[1])  
       sys.exit(1)  
     finally:  
       if con:  
         con.close()  
    
The database is ready to use !