Advertisement
Guest User

Untitled

a guest
Jan 28th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.50 KB | None | 0 0
  1. #######################################################################
  2. # security.py - Monitors a Mosquitto MQTT queue for security events
  3. # from an array of secufity sensors, detects critical changes in those
  4. # sensor values, and injects alarms into an io.adafruit.com queue.
  5. #
  6. # Note: The hardware to do this is already developed (Feather Huzzah
  7. # ESP8266 with NodeCMU), along with the Lua software to run on
  8. # the ESP8266. The next development steps are:
  9. # - write this python program
  10. # - write the If This Then That interface to do notifications
  11. #
  12. # Note two: The implementation uses normally-closed reed switches
  13. # from China. If you use normally open switches, you'll have to
  14. # edit this code to invert the tests for the values coming from
  15. # the sensors.
  16. #
  17. # Philip R. Moyer
  18. # Adafruit
  19. # May 2016
  20. #
  21. # This code is released under a BSD liense and is in the public domain.
  22. # Any redistribution must include the above header.
  23. #######################################################################
  24.  
  25. ########################
  26. # Libraries
  27. ########################
  28.  
  29. import os
  30. import string
  31. import paho.mqtt.client as mqtt
  32. #import Adafruit_IO
  33. import time
  34.  
  35. ########################
  36. # Globals
  37. ########################
  38.  
  39. # -- Change these as needed for your installatin --
  40.  
  41. localBroker = "10.1.2.87"  # Local MQTT broker
  42. localPort = 1883  # Local MQTT port
  43. localUser = "YOUR_MQTT_USERID"  # Local MQTT user
  44. localPass = "YOUR_MQTT_PASSWORD"  # Local MQTT password
  45. localTopic = "test"  # Local MQTT topic to monitor
  46. localTimeOut = 120  # Local MQTT session timeout
  47.  
  48. #adafruitUser = "YOUR_ADAFRUIT_IO_USERID"  # Adafruit.IO user ID
  49. #adafruitKey = "YOUR_ADAFRUIT_IO_KEY"  # Adafruit.IO user key
  50. #adafruitTopic = "alarms"  # Adafruit.IO alarm topic
  51.  
  52. # -- You should not need to change anything below this line --
  53.  
  54. #sensorList = {}  # List of sensor objects
  55.  
  56.  
  57. ########################
  58. # Classes and Methods
  59. ########################
  60.  
  61. class sensor():
  62.     def __init__(self):
  63.         self.name = ""  # Name of sensor in MQTT
  64.         self.humanName = ""  # Human-meaningful name (e.g., "front door")
  65.         self.lastSeen = 0  # Number of seconds since the sensor was last seen
  66.         self.state = "unknown"  # State of the object: unknown, open, or closed
  67.  
  68.     def setState(self, newState):
  69.         self.state = newState
  70.  
  71.     def getState(self):
  72.         return self.state
  73.  
  74.     def resetHeartbeat(self):
  75.         self.lastSeen = 0
  76.  
  77.     def setname(self, newName, humanName):
  78.         self.name = newName
  79.         self.humanName = humanName
  80.  
  81.     def getname(self):
  82.         return self.humanName
  83.  
  84.     def checkState(self, newState):
  85.         if ("unknown" == self.state):
  86.             self.state = newState
  87.             return 0
  88.         else:
  89.             if (newState != self.state):
  90.                 self.state = newState
  91.                 if ("closed" == self.state):
  92.                     return -1
  93.                 else:
  94.                     return 1
  95.         return 0
  96.  
  97.  
  98. class sensorList():
  99.     def __init__(self):
  100.         self.sensorList = {}
  101.  
  102.     def addSensor(self, sensorName, humanName):
  103.         self.sensorList[sensorName] = sensor()
  104.         self.sensorList[sensorName].setname(sensorName, humanName)
  105.  
  106.     def getSensorName(self, sensorID):
  107.         return self.sensorList[sensorID].getname()
  108.  
  109.     def sensorState(self, sensorID, monitorState):
  110.         rv = self.sensorList[sensorID].checkState(monitorState)
  111.         if (0 != rv):
  112.             # State changed!
  113.             if (0 > rv):
  114.                 outBuf = "INFO " + self.getSensorName(sensorID) + " " + monitorState
  115.                 print(outBuf)
  116.             else:
  117.                 outBuf = "ALARM " + self.getSensorName(sensorID) + " " + monitorState
  118.                 print(outBuf)
  119.                 print("Initiating connection to Adafruit.IO")
  120.                 #AIOclient = Adafruit_IO.MQTTClient(adafruitUser, adafruitKey)
  121.                 print("Setting callbacks for Adafruit.IO")
  122.                 #AIOclient.on_connect = AIOconnected
  123.                 #AIOclient.on_disconnect = AIOdisconnected
  124.                 #AIOclient.on_message = AIOmessage
  125.                 print("Connecting to Adafruit.IO")
  126.                 #AIOclient.connect()
  127.                 time.sleep(5)
  128.                 print("Publishing outBuf")
  129.                 # AIOclient.publish("alarms", outBuf)
  130.                 #AIOclient.publish("alarms", outBuf)
  131.                 print("Disconnecting")
  132.                 #AIOclient.disconnect()
  133.  
  134.  
  135. ########################
  136. # Functions
  137. ########################
  138.  
  139. # Callback functions for Adafruit.IO connections
  140. def AIOconnected(client):
  141.     # client.subscribe('alarms')
  142.     print("Connected to Adafruit.IO")
  143.  
  144.  
  145. def AIOdisconnected(client):
  146.     print("adafruit.io client disconnected!")
  147.  
  148.  
  149. def AIOmessage(client, feed_id, payload):
  150.     print("adafruit.io received ", payload)
  151.  
  152.  
  153. # returnState takes a numeric voltage value from the sensor and
  154. # returns the state of the monitored device. With a voltage divider
  155. # that uses a 1M ohm R1 and a 470K ohm R2, the "closed" state returns
  156. # 1024 and the open state returns between 1 and 40.
  157.  
  158. def returnState(inVal):
  159.     if (1000 < inVal):
  160.         return "closed"
  161.     if (100 > inVal):
  162.         return "open"
  163.     else:
  164.         return "unknown"
  165.  
  166.  
  167. ########################
  168. # Main
  169. ########################
  170.  
  171. if "__main__" == __name__:
  172.     # Set timer
  173.  
  174.     sensList = sensorList()
  175.     sensList.addSensor("security_001", "front door")
  176.  
  177.  
  178.     # The callback for when the client receives a CONNACK response from the server.
  179.     def on_connect(client, userdata, flags, rc):
  180.         print("Connected with result code " + str(rc))
  181.  
  182.         # Subscribing in on_connect() means that if we lose the connection and
  183.         # reconnect then subscriptions will be renewed.
  184.         client.subscribe("test")
  185.  
  186.     # The callback for when a PUBLISH message is received from the server.
  187.     def on_message(client, userdata, msg):
  188.         print msg.payload
  189.         try:
  190.             (sensorID, sensorVoltage) = string.split(msg.payload)
  191.         except:
  192.             pass
  193.             #sensorVoltage = string.atoi(sensorVoltage)
  194.         #sensorName = sensList.getSensorName(sensorID)
  195.         #    sensList.sensorState(sensorID, returnState(sensorVoltage))
  196.  
  197.  
  198.  
  199.     # print(sensorName+" "+returnState(sensorVoltage))
  200.  
  201.     client = mqtt.Client("p4")
  202.     client.on_connect = on_connect
  203.     client.on_message = on_message
  204.  
  205.     client.connect(localBroker, localPort, localTimeOut)
  206.  
  207.     # Blocking call that processes network traffic, dispatches callbacks and
  208.     # handles reconnecting.
  209.     # Other loop*() functions are available that give a threaded interface and a
  210.     # manual interface.
  211.     client.loop_forever()
  212.  
  213.     quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement