Skip to content

Instantly share code, notes, and snippets.

@mapkyca
Last active December 18, 2015 12:29
Show Gist options
  • Save mapkyca/5783618 to your computer and use it in GitHub Desktop.
Save mapkyca/5783618 to your computer and use it in GitHub Desktop.
A modification of my earlier security.py which gives an example of how such a security tool could interact with the Home.API application.
import piface.pfio
import time
import sys
import syslog
import json
import urllib
import httplib
class SecurityIndicator:
""" A switch and LED link: Displays light when switch is closed """
def __init__(self, pin_pair, label):
self.pin_pair = pin_pair
self.label = label
self.laststatus = ""
self.poll()
def poll(self):
if piface.pfio.digital_read(self.pin_pair) == 1:
if self.laststatus != 'closed':
piface.pfio.digital_write(self.pin_pair, 1)
self.log(self.label + ' is CLOSED')
self.laststatus = 'closed'
self.sendupdate = 1
else:
if self.laststatus != 'open':
piface.pfio.digital_write(self.pin_pair, 0)
self.log(self.label + ' is OPEN')
self.laststatus = 'open'
self.sendupdate = 1
def log(self, message):
# Echo message
print(message + ' at ' + time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()))
# And for good measure, log entry to auth log
syslog.syslog(syslog.LOG_AUTH | syslog.LOG_INFO, message)
def main(argv):
# Configure API endpoint
home_api = 'home.api'
endpoint = '/api/security/distw/update.json'
piface.pfio.init()
# Initialise our indicator switches
indicators = ['Front Door', 'Study window', 'Study door', 'Bedroom Window', 'Back door', 'Living room window', 'Kitchen window', 'Bathroom window']
indicator_obj = [];
cnt = 0
for switch in indicators:
indicator_obj.append(SecurityIndicator(cnt, switch))
cnt = cnt + 1
# Loop and check indicators
while True:
sendupdate = 0
# Poll, and see if we need to send updates
for indicator in indicator_obj:
indicator.poll()
if indicator.sendupdate == 1:
sendupdate = 1
# Do we need to send an update?
if sendupdate == 1:
packet = {}
for indicator in indicator_obj:
packet[indicator.label] = indicator.laststatus
indicator.sendupdate = 0
conn = httplib.HTTPConnection(home_api)
conn.request('POST', endpoint, json.dumps(packet))
conn.close()
time.sleep(0.05)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment