Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import datetime
- import socket
- import requests
- import mysql.connector
- from os import *
- import subprocess
- GLOBALPORT = 1234
- GETSTATUS = "GET_STATUS"
- CHANGESTATUS = "CHANGE_STATUS"
- DEVICEADDED = "DEVICE_ADDED"
- DEVICEDELETED = "DEVICE_DELETED"
- def sendArduinoData(sensor, data):
- '''This function sends a message to the Arduino'''
- #TODO: add expeptions hendaling
- try:
- my_soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- except socket.error as msg:
- my_soc = None
- try:
- my_soc.sendto(data,(sensor.ip,sensor.port))
- except socket.error as msg:
- my_soc.close()
- my_soc = None
- my_soc.close()
- def receiveArduinoData(sensor):
- '''This function receives message from the Arduino'''
- try:
- my_soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- except socket.error as msg:
- my_soc = None
- try:
- my_soc.bind(('0.0.0.0', 1234))
- (reply, addr) = my_soc.recvfrom(128)
- except socket.error as msg:
- my_soc.close()
- my_soc = None
- my_soc.close()
- return reply
- def getCurrStatus(sensor):
- '''This function returns the currect status of the Arduino'''
- #TODO change to UDP using existing functions
- #TODO: add expeptions hendaling
- sendArduinoData(sensor, sensor.BuildCommandString(GETSTATUS))
- data = receiveArduinoData(sensor)
- return data
- '''This class is the father class for all the next classes'''
- class ArduinoSensor:
- ip = "192.168.43.57"
- port = GLOBALPORT
- id = None
- room = None
- currStatus = None
- option = None
- #TODO: id and staff... from design VV
- def __init__(self, ip, port, id, room, currStatus = None, option = None): #TODO +whats above VV
- self.ip = ip
- self.port = port
- self.id = id
- self.room = room
- self.currStatus = currStatus
- self.option = option
- class IrTransmitSensor(ArduinoSensor):
- def __init__(self, ip, port, id, room, currStatus, option):
- ArduinoSensor.__init__(self,ip, port, id, room, currStatus, option)
- def buildCommandString(self,data):
- return data
- class DoorSensor(ArduinoSensor):
- def __init__(self, ip, port, id, room, currStatus, option):
- ArduinoSensor.__init__(self,ip, port, id, room, currStatus, option)
- def buildCommandString(self, data):
- return data
- def isClosed(self): #TODO: add expeptions hendaling
- Closed = getCurrStatus(self)
- if Closed == "True":
- return True
- elif Closed == "False":
- return False
- else:
- return "Error"
- class TemperatureSensor(ArduinoSensor):
- def __init__(self, ip, port, id, room, currStatus, option):
- return super(TemperatureSensor, self).__init__(ip, port, id, room, currStatus, option)
- def buildCommandString(data):
- return data
- class Switch(ArduinoSensor):
- def __init__(self, ip, port, id, room, currStatus, option):
- ArduinoSensor.__init__(self,ip, port, id, room, currStatus, option)
- def buildCommandString(data):
- msg="Switch."
- if data == "on":
- msg += "True"
- elif data == "off":
- msg += "False"
- else:
- msg += "ERROR"
- return msg
- class Tilt(ArduinoSensor):
- def __init__(self, ip, port, id, room, currStatus, option):
- return super(Tilt, self).__init__(ip, port, id, room, currStatus, option)
- def buildCommandString(data):
- return data
- def sendMsgToDB(data):
- '''This function sends messages to the DB'''
- try:
- DB = mysql.connector.connect(user='ADMIN', password='ADMIN', host='localhost', database='pym')
- sql = DB.cursor()
- currTime = str(datetime.datetime.now())
- msg = "INSERT INTO msg (MsgID, surce, dest, date, content) VALUES ('NULL', 'server', 'web', '"+currTime+"', '"+data+"');"
- print msg
- sql.execute(msg)
- DB.commit()
- sql.close()
- DB.close()
- except mysql.connector.Error as err:
- print("Something went wrong: {}".format(err))
- def receiveMsgFromDB():
- '''This function receives messages from the DB'''
- try:
- DB = mysql.connector.connect(user='ADMIN', password='ADMIN', host='localhost', database='pym')
- sql = DB.cursor()
- msg = """SELECT `MsgID`, `content` FROM `msg` WHERE `dest`='server' ;"""
- sql.execute(msg)
- data = {}
- for (MsgID, content) in sql:
- data["{}".format(MsgID)] = "{}".format(content)
- msg = "DELETE FROM `msg` WHERE `dest` = server;"
- sql.execute(msg)
- DB.commit()
- sql.close()
- DB.close()
- except mysql.connector.Error as err:
- print("Something went wrong: {}".format(err))
- return data
- def changeStatInDB(id,stat):
- '''This function changes the status of a device in the DB'''
- try:
- DB = mysql.connector.connect(user='ADMIN', password='ADMIN', host='localhost', database='pym')
- sql = DB.cursor()
- msg = "UPDATE `device` SET `DEV_stat` = '"+stat+"' WHERE `device`.`DEV_ID` = "+id+";"
- sql.execute(msg)
- DB.commit()
- sql.close()
- DB.close()
- except mysql.connector.Error as err:
- print("Something went wrong: {}".format(err))
- def getNewDeviceInfoFromDB():
- '''This function receiving all the information about a new device from the DB'''
- try:
- DB = mysql.connector.connect(user='ADMIN', password='ADMIN', host='localhost', database='pym')
- sql = DB.cursor()
- msg = "SELECT * FROM device;"
- sql.execute(msg)
- '''for (DEV_ID, DEV_Type, DEV_loction, DEV_options) in sql:
- data["{}".format(DEV_ID)] = "{}.{}.{}.{}".format(DEV_ID, DEV_Type, DEV_loction, DEV_options)
- #data["{}".format(DEV_ID)] = data["{}".format(DEV_ID)].split('.')'''
- data = sql.fetchone()[0]
- print data
- sql.close()
- DB.close()
- except mysql.connector.Error as err:
- print("Something went wrong: {}".format(err))
- return data
- def main():
- '''this is the main function of the project. Have fun runnig it'''
- print "Starting server"
- sensors = {}
- #sensors = {1:DoorSensor("192.168.43.143", GLOBALPORT, "1", "1", True,"passive")}
- #while True:
- """result = sendArduinoData(sensor, sensor.buildCommandString("7000"))
- print result #Prints what the server has sent to the arduino
- print receiveArduinoData(sensor) #Prints what the server received from the Arduino
- print sensor.isClosed()"""
- #sendMsgToDB("hello") #sends the Msg to the DB
- while True:
- msg = receiveMsgFromDB() #receives Msg from the DB
- Keys = msg.keys()
- if Keys > 0:
- Keys.sort()
- else:
- continue
- for i in Keys:
- msg[i] = msg[i].split('.')
- for i in Keys:
- if msg[i][0] == CHANGESTATUS:
- sendArduinoData(sensors[msg[i][1]],sensors[msg[i][1]].buildCommandString(msg[i][2]))
- changeStatInDB(msg[i][1],msg[i][2])
- DBMsg = "ANSWER."+msg[i][1]+".OK"
- sendMsgToDB(DBMsg)
- elif msg[i][0] == GETSTATUS:
- stat = getCurrStatus(sensors[msg[i][1]])
- DBMsg = "ANSWER."+msg[i][1]+stat
- sendMsgToDB(DBMsg)
- elif msg[i][0] == DEVICEADDED:
- newSensor = getNewDeviceInfoFromDB()
- if newSensor[1] == "IR_sensor":
- sensors[newSensor[0]] = IrTransmitSensor(None,GLOBALPORT,newSensor[0],newSensor[2],None,newSensor[3])
- elif newSensor[1] == "Door_sensor":
- sensors[newSensor[0]] = DoorSensor(None,GLOBALPORT,newSensor[0],newSensor[2],None,newSensor[3])
- elif newSensor[1] == "Relay_modul":
- sensors[newSensor[0]] = Switch("10.0.0.10",GLOBALPORT,newSensor[0],newSensor[2],None,newSensor[3])
- elif newSensor[1] == "Temperature_sensor":
- sensors[newSensor[0]] = TemperatureSensor(None,GLOBALPORT,newSensor[0],newSensor[2],None,newSensor[3])
- elif newSensor[1] == "Tilt_Sensor":
- sensors[newSensor[0]] = Tilt(None,GLOBALPORT,newSensor[0],newSensor[2],None,newSensor[3])
- elif msg[i][0] == DEVICEDELETED:
- del sensors[msag[i][1]]
- time.sleep(3) #Waits 3 seconds
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment