gtermors

homewizardapi.py

Mar 17th, 2014
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.24 KB | None | 0 0
  1. import sys
  2.  
  3. import inspect
  4. import json
  5. import os.path
  6. import socket
  7. import time
  8. import urllib2
  9. import ConfigParser
  10. from datetime import datetime, timedelta
  11.  
  12. class HomeWizard(object):
  13.     hwHost       = ''
  14.     hwPort       = ''
  15.     hwPassword   = ''
  16.     hwBaseURL    = ''
  17.    
  18.     responseHttp    = ''
  19.     responseJson    = ''
  20.     responseStatus  = ''
  21.     responseSuccess = False
  22.  
  23.     getStatusJson = ''
  24.     getSensorJson = ''
  25.  
  26.     #Constructor
  27.     def __init__(self):
  28.         pass
  29.  
  30.     # Date/Time Functions
  31.    
  32.     # Get DateTime from Time, with the current date
  33.     def todayAt(self, hr, min=0, sec=0, micros=0):
  34.         now = datetime.now()
  35.         return now.replace(hour=hr, minute=min, second=sec, microsecond=micros)
  36.  
  37.     # Get DateTime from StringTime
  38.     def getDateTimeFromStr(self, stringTime):
  39.         tmpTime = time.strptime(stringTime,'%H:%M')
  40.         tmpDateTime = self.todayAt(tmpTime[3], tmpTime[4])
  41.  
  42.         if tmpDateTime > datetime.now():
  43.             tmpDateTime = tmpDateTime - timedelta(days=1)
  44.         return tmpDateTime
  45.  
  46.     # Read Config
  47.     def readconfig(self):
  48.         config = ConfigParser.ConfigParser(allow_no_value=True)
  49.  
  50.         sourcePath = os.path.dirname(inspect.getsourcefile(self.readconfig))
  51.         hwConfigFile = os.path.join(sourcePath,'homewizard.cfg')
  52.  
  53.         #Check if ConfigFile exists
  54.         if not os.path.isfile(hwConfigFile):
  55.             configExists = False
  56.             print '\nERROR: Missing HomeWizard configfile\n'
  57.         else:
  58.             configExists = True
  59.  
  60.         #Read Config
  61.         if configExists:
  62.             config.read(hwConfigFile)
  63.  
  64.             try:
  65.                 self.hwHost       = config.get('HomeWizard', 'hwHost')
  66.                 self.hwPort       = config.get('HomeWizard', 'hwPort')
  67.                 self.hwPassword   = config.get('HomeWizard', 'hwPassword')
  68.                 self.hwBaseURL    = 'http://' + self.hwHost + ':' + self.hwPort + '/' + self.hwPassword
  69.             except ConfigParser.NoOptionError, err:
  70.                     print '\nERROR: Could not parse config file\n'
  71.  
  72.         if self.hwHost and self.hwPort and self.hwPassword:    
  73.             configRead = True
  74.         else:
  75.             configRead = False
  76.  
  77.         return configExists and configRead
  78.        
  79.     # Handshake
  80.     def handshake(self):
  81.         try:
  82.            self.responseHttp = urllib2.urlopen('http://' + self.hwHost + ':' + self.hwPort + '/handshake/html5/1/0', None, 5)
  83.         except urllib2.HTTPError, err:
  84.             print '\nERROR: Handshake HTTP Error'
  85.             print 'Code  : ' + str(err.code)
  86.             print 'Reason: ' + err.reason + '\n'
  87.         except urllib2.URLError, err:
  88.             print '\nERROR: Handshake URL Error'
  89.             print 'Reason: ' + str(err.reason) + '\n'
  90.         except socket.timeout, err:
  91.             print '\nERROR: Handshake Socket Timeout'
  92.  
  93.         if self.responseHttp:    
  94.             self.responseJson = json.load(self.responseHttp)
  95.    
  96.             self.responseStatus = self.responseJson['status']
  97.             homewizard  = self.responseJson['response']['homewizard']
  98.             handshakeok = self.responseStatus == 'ok' and homewizard == 'yes'
  99.  
  100.             if not handshakeok:
  101.                 print '\nERROR: HomeWizard handshake failure\n'
  102.            
  103.             return handshakeok
  104.         else:
  105.             return False
  106.    
  107.     # Send cmd to HomeWizard
  108.     def hwCmd (self, cmd):
  109.         try:
  110.            self.responseHttp = urllib2.urlopen(self.hwBaseURL + cmd, None, 5)
  111.         except urllib2.HTTPError, err:
  112.             print '\nERROR: hwCmd HTTP Error'
  113.             print 'Code  : ' + str(err.code)
  114.             print 'Reason: ' + err.reason + '\n'
  115.         except urllib2.URLError, err:
  116.             print '\nERROR: hwCmd URL Error'
  117.             print 'Reason: ' + str(err.reason) + '\n'
  118.         except socket.timeout, err:
  119.             print '\nERROR: hwCmd Socket Timeout'
  120.  
  121.         if self.responseHttp:    
  122.             self.responseJson = json.load(self.responseHttp)
  123.    
  124.             self.responseStatus  = self.responseJson['status']
  125.             self.responseSuccess = self.responseStatus == 'ok'
  126.    
  127.             return self.responseSuccess
  128.         else:
  129.             return False
  130.  
  131.     # Get Status
  132.     def getStatus (self):
  133.         cmd = '/get-status'
  134.         success = self.hwCmd(cmd)
  135.    
  136.         if success:
  137.           self.getStatusJson = self.responseJson
  138.         else:
  139.           self.getStatusJson = ''
  140.  
  141.         return success
  142.  
  143.     # Check Status
  144.     def checkStatus (self):
  145.         # Execute getStatus if statusinfo isn't present
  146.  
  147.         if not self.getStatusJson:
  148.             success = self.getStatus()
  149.         else:
  150.             success = True
  151.  
  152.         return success
  153.    
  154.     # Get Sensors
  155.     def getSensors (self):
  156.         cmd = '/get-sensor'
  157.         success = self.hwCmd(cmd)
  158.    
  159.         if success:
  160.           self.getSensorJson = self.responseJson
  161.         else:
  162.           self.getSensorJson = ''
  163.  
  164.         return success
  165.    
  166.     # Switch Status
  167.     def switchStatus (self, switchID):
  168.         # Check if statusinfo is present
  169.         success = self.checkStatus()
  170.  
  171.         # Get Switch Status
  172.         if success:
  173.             switches     = self.responseJson['response']['switches']
  174.             switch       = [sw for sw in switches if sw['id']==switchID][0]
  175.             switchStatus = switch['status']
  176.             switchOn     = switchStatus == 'on'
  177.    
  178.             return success, switchOn
  179.         else:
  180.             return False, False
  181.    
  182.     # SwitchOn a HomeWizard Switch
  183.     def switchOn (self, switchID):
  184.         cmd = '/sw/' + str(switchID) + '/on'
  185.         success = self.hwCmd(cmd)
  186.         return success
  187.    
  188.     # SwitchOff a HomeWizard Switch
  189.     def switchOff (self, switchID):
  190.         cmd = '/sw/' + str(switchID) + '/off'
  191.         success = self.hwCmd(cmd)
  192.         return success
  193.    
  194.     # Switch Status
  195.     def sensorStatus (self, sensorID):
  196.         # Check if statusinfo is present
  197.         success = self.checkStatus()
  198.  
  199.         # Get Sensor Status
  200.         if success:
  201.             sensors        = self.responseJson['response']['kakusensors']
  202.             sensor         = [sw for sw in sensors if sw['id']==sensorID][0]
  203.             sensorStatus   = sensor['status']
  204.             sensorTimeStr  = sensor['timestamp']
  205.             sensorOn       = sensorStatus == 'yes'
  206.  
  207.             sensorDateTime = self.getDateTimeFromStr(sensorTimeStr)
  208.            
  209.             return success, sensorOn, sensorTimeStr, sensorDateTime
  210.         else:
  211.             return False, False, '00:00', datetime(1901,1,1,0,0,0,0)
  212.  
  213.     # EnergyLink Day Values
  214.     def energylinkDay (self):
  215.         cmd = '/el/graph/0/day'
  216.         success = self.hwCmd(cmd)
  217.  
  218.         if success:
  219.             return success, self.responseJson['response']
  220.         else:
  221.             return success, ''
  222.  
  223.     # Get Thermometer Temperature
  224.     def thermoGetTemp (self, thermometerID):
  225.         # Check if statusinfo is present
  226.         success = self.checkStatus()
  227.  
  228.         # Get Temp
  229.         if success:
  230.             thermometers    = self.responseJson['response']['thermometers']
  231.             thermometer     = [sw for sw in thermometers if sw['id']==thermometerID][0]
  232.             thermoTemp      = thermometer['te']
  233.  
  234.             return success, thermoTemp
  235.         else:
  236.             return success, 0
  237.            
  238.     # HeatLink Set Temp
  239.     def heatlinkSetTemp (self, temperature, minutes):
  240.         cmd = '/hl/0/settarget/' + str(temperature)
  241.  
  242.         if minutes > 0:
  243.             cmd = cmd + '/' + str(minutes)
  244.  
  245.         success = self.hwCmd(cmd)
  246.         return success
  247.  
  248.     # HeatLink Get Temp
  249.     def heatlinkGetTemp (self):
  250.         # Check if statusinfo is present
  251.         success = self.checkStatus()
  252.  
  253.         # Get Sensor Status
  254.         if success:
  255.             heatlinks           = self.responseJson['response']['heatlinks']
  256.             heatlink            = [sw for sw in heatlinks if sw['id']==0][0]
  257.             hlRoomTemp          = heatlink['rte']
  258.             hlTempHeatlink      = heatlink['tte']
  259.             hlTempThermostat    = heatlink['rsp']
  260.  
  261.             return success, hlRoomTemp, hlTempHeatlink, hlTempThermostat
  262.         else:
  263.             return success, 0, 0, 0
Advertisement
Add Comment
Please, Sign In to add comment