Guest User

Untitled

a guest
Apr 30th, 2016
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.48 KB | None | 0 0
  1. import time
  2. import datetime
  3. import socket
  4. import requests
  5. import mysql.connector
  6. from os import *
  7. import subprocess
  8.  
  9.  
  10. GLOBALPORT = 1234
  11. GETSTATUS = "GET_STATUS"
  12. CHANGESTATUS = "CHANGE_STATUS"
  13. DEVICEADDED = "DEVICE_ADDED"
  14. DEVICEDELETED = "DEVICE_DELETED"
  15.  
  16.  
  17. def sendArduinoData(sensor, data):
  18.     '''This function sends a message to the Arduino'''
  19.     #TODO: add expeptions hendaling
  20.     try:
  21.         my_soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  22.     except socket.error as msg:
  23.         my_soc = None
  24.     try:
  25.         my_soc.sendto(data,(sensor.ip,sensor.port))
  26.     except socket.error as msg:
  27.         my_soc.close()
  28.         my_soc = None
  29.     my_soc.close()
  30.  
  31. def receiveArduinoData(sensor):
  32.     '''This function receives message from the Arduino'''
  33.     try:
  34.         my_soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  35.     except socket.error as msg:
  36.         my_soc = None
  37.     try:
  38.         my_soc.bind(('0.0.0.0', 1234))
  39.         (reply, addr) = my_soc.recvfrom(128)
  40.     except socket.error as msg:
  41.         my_soc.close()
  42.         my_soc = None
  43.  
  44.     my_soc.close()
  45.     return reply
  46.  
  47. def getCurrStatus(sensor):
  48.     '''This function returns the currect status of the Arduino'''
  49.     #TODO change to UDP using existing functions
  50.     #TODO: add expeptions hendaling
  51.     sendArduinoData(sensor, sensor.BuildCommandString(GETSTATUS))
  52.     data = receiveArduinoData(sensor)
  53.     return data
  54.  
  55. '''This class is the father class for all the next classes'''
  56. class ArduinoSensor:
  57.     ip = "192.168.43.57"
  58.     port = GLOBALPORT
  59.     id = None
  60.     room = None
  61.     currStatus = None
  62.     option = None
  63.     #TODO: id and staff... from design VV
  64.  
  65.     def __init__(self, ip, port, id, room, currStatus = None, option = None): #TODO +whats above VV
  66.         self.ip = ip
  67.         self.port = port
  68.         self.id = id
  69.         self.room = room  
  70.         self.currStatus = currStatus
  71.         self.option = option
  72.        
  73.  
  74.  
  75. class IrTransmitSensor(ArduinoSensor):
  76.     def __init__(self, ip, port, id, room, currStatus, option):
  77.         ArduinoSensor.__init__(self,ip, port, id, room, currStatus, option)
  78.  
  79.     def buildCommandString(self,data):
  80.         return data
  81.  
  82. class DoorSensor(ArduinoSensor):
  83.     def __init__(self, ip, port, id, room, currStatus, option):
  84.         ArduinoSensor.__init__(self,ip, port, id, room, currStatus, option)
  85.  
  86.     def buildCommandString(self, data):
  87.         return data
  88.    
  89.     def isClosed(self): #TODO: add expeptions hendaling
  90.         Closed = getCurrStatus(self)
  91.         if Closed == "True":
  92.             return True
  93.         elif Closed == "False":
  94.             return False
  95.         else:
  96.             return "Error"
  97.  
  98. class TemperatureSensor(ArduinoSensor):
  99.     def __init__(self, ip, port, id, room, currStatus, option):
  100.         return super(TemperatureSensor, self).__init__(ip, port, id, room, currStatus, option)
  101.  
  102.     def buildCommandString(data):
  103.         return data
  104.  
  105. class Switch(ArduinoSensor):
  106.     def __init__(self, ip, port, id, room, currStatus, option):
  107.         ArduinoSensor.__init__(self,ip, port, id, room, currStatus, option)
  108.  
  109.     def buildCommandString(data):
  110.         msg="Switch."
  111.         if data == "on":
  112.             msg += "True"
  113.         elif data == "off":
  114.             msg += "False"
  115.         else:
  116.             msg += "ERROR"
  117.         return msg
  118.  
  119. class Tilt(ArduinoSensor):
  120.     def __init__(self, ip, port, id, room, currStatus, option):
  121.         return super(Tilt, self).__init__(ip, port, id, room, currStatus, option)
  122.  
  123.     def buildCommandString(data):
  124.         return data
  125.  
  126. def sendMsgToDB(data):
  127.     '''This function sends messages to the DB'''
  128.     try:
  129.         DB = mysql.connector.connect(user='ADMIN', password='ADMIN', host='localhost', database='pym')
  130.         sql = DB.cursor()
  131.         currTime = str(datetime.datetime.now())
  132.         msg = "INSERT INTO msg (MsgID, surce, dest, date, content) VALUES ('NULL', 'server', 'web', '"+currTime+"', '"+data+"');"
  133.         print msg
  134.         sql.execute(msg)
  135.         DB.commit()
  136.         sql.close()
  137.         DB.close()
  138.     except mysql.connector.Error as err:
  139.         print("Something went wrong: {}".format(err))
  140.  
  141. def receiveMsgFromDB():
  142.     '''This function receives messages from the DB'''
  143.     try:
  144.         DB = mysql.connector.connect(user='ADMIN', password='ADMIN', host='localhost', database='pym')
  145.         sql = DB.cursor()
  146.         msg = """SELECT `MsgID`, `content` FROM `msg` WHERE `dest`='server' ;"""
  147.         sql.execute(msg)
  148.         data = {}
  149.         for (MsgID, content) in sql:
  150.             data["{}".format(MsgID)] = "{}".format(content)
  151.         msg = "DELETE FROM `msg` WHERE `dest` = server;"
  152.         sql.execute(msg)
  153.         DB.commit()
  154.         sql.close()
  155.         DB.close()
  156.     except mysql.connector.Error as err:
  157.         print("Something went wrong: {}".format(err))
  158.     return data
  159.  
  160. def changeStatInDB(id,stat):
  161.     '''This function changes the status of a device in the DB'''
  162.     try:
  163.         DB = mysql.connector.connect(user='ADMIN', password='ADMIN', host='localhost', database='pym')
  164.         sql = DB.cursor()
  165.         msg = "UPDATE `device` SET `DEV_stat` = '"+stat+"' WHERE `device`.`DEV_ID` = "+id+";"
  166.         sql.execute(msg)
  167.         DB.commit()
  168.         sql.close()
  169.         DB.close()
  170.     except mysql.connector.Error as err:
  171.         print("Something went wrong: {}".format(err))
  172.  
  173. def getNewDeviceInfoFromDB():
  174.     '''This function receiving all the information about a new device from the DB'''
  175.     try:
  176.         DB = mysql.connector.connect(user='ADMIN', password='ADMIN', host='localhost', database='pym')
  177.         sql = DB.cursor()
  178.         msg = "SELECT * FROM device;"
  179.         sql.execute(msg)
  180.         '''for (DEV_ID, DEV_Type, DEV_loction, DEV_options) in sql:
  181.            data["{}".format(DEV_ID)] = "{}.{}.{}.{}".format(DEV_ID, DEV_Type, DEV_loction, DEV_options)
  182.            #data["{}".format(DEV_ID)] = data["{}".format(DEV_ID)].split('.')'''
  183.         data = sql.fetchone()[0]
  184.         print data
  185.         sql.close()
  186.         DB.close()
  187.     except mysql.connector.Error as err:
  188.         print("Something went wrong: {}".format(err))
  189.     return data
  190.  
  191. def main():
  192.     '''this is the main function of the project. Have fun runnig it'''
  193.     print "Starting server"
  194.     sensors = {}
  195.     #sensors = {1:DoorSensor("192.168.43.143", GLOBALPORT, "1", "1", True,"passive")}
  196.     #while True:
  197.     """result = sendArduinoData(sensor, sensor.buildCommandString("7000"))
  198.    print result #Prints what the server has sent to the arduino
  199.    print receiveArduinoData(sensor) #Prints what the server received from the Arduino
  200.    print sensor.isClosed()"""
  201.     #sendMsgToDB("hello") #sends the Msg to the DB
  202.     while True:
  203.         msg = receiveMsgFromDB() #receives Msg from the DB
  204.         Keys = msg.keys()
  205.         if Keys > 0:
  206.             Keys.sort()
  207.         else:
  208.             continue
  209.         for i in Keys:
  210.             msg[i] = msg[i].split('.')
  211.         for i in Keys:
  212.             if msg[i][0] == CHANGESTATUS:
  213.                 sendArduinoData(sensors[msg[i][1]],sensors[msg[i][1]].buildCommandString(msg[i][2]))
  214.                 changeStatInDB(msg[i][1],msg[i][2])
  215.                 DBMsg = "ANSWER."+msg[i][1]+".OK"
  216.                 sendMsgToDB(DBMsg)
  217.             elif msg[i][0] == GETSTATUS:
  218.                 stat = getCurrStatus(sensors[msg[i][1]])
  219.                 DBMsg = "ANSWER."+msg[i][1]+stat
  220.                 sendMsgToDB(DBMsg)
  221.             elif msg[i][0] == DEVICEADDED:
  222.                 newSensor = getNewDeviceInfoFromDB()
  223.                 if newSensor[1] == "IR_sensor":
  224.                     sensors[newSensor[0]] = IrTransmitSensor(None,GLOBALPORT,newSensor[0],newSensor[2],None,newSensor[3])
  225.                 elif newSensor[1] == "Door_sensor":
  226.                     sensors[newSensor[0]] = DoorSensor(None,GLOBALPORT,newSensor[0],newSensor[2],None,newSensor[3])
  227.                 elif newSensor[1] == "Relay_modul":
  228.                     sensors[newSensor[0]] = Switch("10.0.0.10",GLOBALPORT,newSensor[0],newSensor[2],None,newSensor[3])
  229.                 elif newSensor[1] == "Temperature_sensor":
  230.                     sensors[newSensor[0]] = TemperatureSensor(None,GLOBALPORT,newSensor[0],newSensor[2],None,newSensor[3])
  231.                 elif newSensor[1] == "Tilt_Sensor":
  232.                     sensors[newSensor[0]] = Tilt(None,GLOBALPORT,newSensor[0],newSensor[2],None,newSensor[3])
  233.             elif msg[i][0] == DEVICEDELETED:
  234.                 del sensors[msag[i][1]]
  235.         time.sleep(3) #Waits 3 seconds
  236.  
  237. if __name__ == "__main__":
  238.     main()
Add Comment
Please, Sign In to add comment