Exemplo n.º 1
0
 def _send(self, device, command):
   result = {"completed": False, "request": {}}
   try:
     if device == "LR":
       port = "1"
       protocol = "FR"
     elif device == "BR":
       port = "2"
       protocol = "LG"
     else:
       port = "3"
       protocol = "FR"
     cmd = "sendir,1:" + port + "," + self._commands[protocol][command]
     result["request"]["command"] = cmd
     if self._ready:
       try:
         s = socket.socket()
         s.settimeout(5)
         s.connect((self._ip_address, self._port))
         s.send(cmd + "\r")
         response = s.recv(1024)
         s.close()
         result["completed"] = True
         result["response"] = str(response)
       except Exception, e:
         CloudLog.error(self._component, "Error when sending command", e)
     else:
Exemplo n.º 2
0
 def _start(self):
     if self.running is False:
         self.running = True
         try:
             self._thread = thread.start_new_thread(self._runLoop, (None, ))
         except Exception, e:
             CloudLog.error(self._component, "Unable to start run loop", e)
Exemplo n.º 3
0
def search(ip_address, port, strings):
    component = "UDPListener:Search"
    waitTime = 9
    try:

        CloudLog.log(component, "Listening on " + ip_address + ":" + str(port))
        udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # Allow applications reuse the same port
        udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Join the mulitcast group
        ip_mreq = struct.pack('4sl', socket.inet_aton(ip_address),
                              socket.INADDR_ANY)
        udp_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                              ip_mreq)

        # Leave the mulitcast group
        # udp_socket.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, ip_mreq)
        udp_socket.bind((ip_address, port))
        udp_socket.settimeout(waitTime)
        searchLoop = True
        stopTime = datetime.now() + timedelta(seconds=waitTime * 10)
    except Exception, e:
        CloudLog.error(component, "Unable to open multicast socket", e)
        searchLoop = False
Exemplo n.º 4
0
  def _runLoop(self, params):
    while self._run:
      current_time = int(datetime.now().strftime('%s')) * 1000
      # Read the outside temperature
      try:
        if ((current_time - self.outside["last_updated"]) > (self._outside_config["interval"] * 1000)) and self._outside_config["enabled"]:
          conn = httplib.HTTPConnection("api.wunderground.com")
          url = "/api/[KEY]/conditions/q/" + self._outside_config["location"] + ".json"
          conn.request("GET", url.replace("[KEY]", Keys.WEATHERBUG))
          r1 = conn.getresponse()
          w = json.loads(r1.read())
          conn.close()
          self.outside["temperature"] = int(w.get("current_observation").get("temp_f"))
          self.outside["last_updated"] = current_time
          #CloudLog.track("TEMPERATURE_OUTSIDE", str(self.outside["temperature"]))
      except Exception, e:
        CloudLog.error(self._component, "Error reading outside temperature", e)

      # Read the inside temperature
      try:
        if ((current_time - self.inside["last_updated"]) > (self._inside_config["interval"] * 1000)) and self._inside_config["enabled"]:
          lines = self._readTemperatureSensor()
          while lines[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines = self._readTemperatureSensor()
          equals_pos = lines[1].find('t=')
          if equals_pos != -1:
            temp_string = lines[1][equals_pos+2:]
            temp_c = float(temp_string) / 1000.0
            temp_f = temp_c * 9.0 / 5.0 + 32.0
          self.inside["temperature"] = temp_f
          self.inside["last_updated"] = current_time
          #CloudLog.track("TEMPERATURE_INSIDE", str(self.inside["temperature"]))
      except Exception, e:
        CloudLog.error(self._component, "Error reading inside temperature", e)
Exemplo n.º 5
0
 def start(self):
   if self._run is False:
     self._run = True
     try:
       thread.start_new_thread(self._runLoop, (None,))
     except Exception, e:
       CloudLog.error(self._component, "Unable to start temperature loop.", e)
Exemplo n.º 6
0
 def _startAnnounce(self):
   if self._threadAnnounce is None:
     try:
       CloudLog.log(self._component + ":StartAnnounce", "Starting UDP Announcer")
       self._threadAnnounce = thread.start_new_thread(self._runAnnounceLoop, (None,))
     except Exception, e:
       CloudLog.error(self._component, "Unable to start announce loop", e)
Exemplo n.º 7
0
 def _disconnectClient(self, client):
     try:
         if client is not None:
             client.disconnect(send_close=True)
     except Exception, e:
         CloudLog.error(self._component,
                        "Error disconnecting from Harmony Bridge", e)
Exemplo n.º 8
0
 def __init__(self, ip_address, port):
     CloudLog.log(self._component, "Initializing.")
     self._ip_address = ip_address
     self._port = port
     with open("config.json", "r") as text_file:
         results = text_file.read()
     self._commands = json.loads(results)
Exemplo n.º 9
0
 def _startListen(self):
   if self._threadListen is None:
     try:
       CloudLog.log(self._component + ":StartListen", "Starting UDP Listener")
       self._thread = thread.start_new_thread(self._runListenLoop, (None,))
     except Exception, e:
       CloudLog.error(self._component, "Unable to start listen loop", e)
Exemplo n.º 10
0
 def __init__(self, ip_address, port):
   CloudLog.log(self._component, "Initializing.")
   self._ip_address = ip_address
   self._port = port
   with open("config.json", "r") as text_file:
     results = text_file.read()
   self._commands = json.loads(results)
Exemplo n.º 11
0
 def _start(self):
   if self.running is False:
     self.running = True
     try:
       self._thread = thread.start_new_thread(self._runLoop, (None,))
     except Exception, e:
       CloudLog.error(self._component, "Unable to start run loop", e)
Exemplo n.º 12
0
 def _send(self, device, command):
     result = {"completed": False, "request": {}}
     try:
         if device == "LR":
             port = "1"
             protocol = "FR"
         elif device == "BR":
             port = "2"
             protocol = "LG"
         else:
             port = "3"
             protocol = "FR"
         cmd = "sendir,1:" + port + "," + self._commands[protocol][command]
         result["request"]["command"] = cmd
         if self._ready:
             try:
                 s = socket.socket()
                 s.settimeout(5)
                 s.connect((self._ip_address, self._port))
                 s.send(cmd + "\r")
                 response = s.recv(1024)
                 s.close()
                 result["completed"] = True
                 result["response"] = str(response)
             except Exception, e:
                 CloudLog.error(self._component,
                                "Error when sending command", e)
         else:
Exemplo n.º 13
0
 def _runLoop(self, params):
   CloudLog.log(self._component, "Running.")
   if self.unread is None:
     self.unread = 0
   while self.running:
     try:
       if self._controller.state == "HOME":
         output = Popen(['lynx', '-source', 'https://www.google.com/voice/request/unread'], stdout=PIPE)
         response = output.stdout.read()
         response = json.loads(response)
         previous_count = self.unread
         self.unread = int(response["unreadCounts"]["all"])
         if self.unread > previous_count:
           cmd = self._settings["cmd_new"]
           self._controller.executeCommandByName(cmd)
         elif self.unread == 0 and previous_count > 0:
           cmd = self._settings["cmd_zero"]
           self._controller.executeCommandByName(cmd)
         interval = self._settings["interval"]
       else:
         interval = self._settings["interval"] * 2
     except Exception, e:
       cmd = self._settings["cmd_error"]
       self._controller.executeCommandByName(cmd)
       if interval < self._settings["interval"] * 10:
         interval += self._interval
     time.sleep(interval)
Exemplo n.º 14
0
 def _push(self):
     try:
         status = self._controller.status()
         status["user_key"] = Keys.APPENGINE_USER
         content = json.dumps(status)
         self._query("POST", "/set/status", content)
     except Exception, e:
         CloudLog.error(self._component, "Error pushing system status.", e)
Exemplo n.º 15
0
 def _push(self):
   try:
     status = self._controller.status()
     status["user_key"] = Keys.APPENGINE_USER
     content = json.dumps(status)
     self._query("POST", "/set/status", content)
   except Exception, e:
     CloudLog.error(self._component, "Error pushing system status.", e)
Exemplo n.º 16
0
def play(file_name):
  try:
    if file_name is not None:
      cmd = "mplayer -ao alsa -really-quiet -noconsolecontrols "
      call(cmd+file_name, shell=True)
      CloudLog.debug("SoundSystem", file_name)
  except Exception, e:
    CloudLog.error("SoundSystem.Play", "Error playing sound", e)
Exemplo n.º 17
0
    def __init__(self, connection_settings=None):
        CloudLog.log(self._component, "Initializing.")
        if connection_settings is None:
            connection_settings = self._find()

        if connection_settings is not None:
            self._ip_address = connection_settings["ip"]
            self._port = connection_settings["port"]
            self._uuid = connection_settings["uuid"]
Exemplo n.º 18
0
    def __init__(self, connection_settings=None):
        CloudLog.log(self._component, "Initializing.")
        if connection_settings is None:
            connection_settings = self._find()

        if connection_settings is not None:
            self._ip_address = connection_settings["ip"]
            self._port = connection_settings["port"]
            self._uuid = connection_settings["uuid"]
Exemplo n.º 19
0
 def __init__(self, controller):
     CloudLog.log(self._component, "Initializing.")
     self._controller = controller
     try:
         import RPIO
         self._start()
     except Exception, e:
         self.state = "NO_RPIO"
         CloudLog.error(self._component, "RPIO is unavailable.", e)
Exemplo n.º 20
0
 def __init__(self, controller):
   CloudLog.log(self._component, "Initializing.")
   self._controller = controller
   try:
     import RPIO
     self._start()
   except Exception, e:
     self.state = "NO_RPIO"
     CloudLog.error(self._component, "RPIO is unavailable.", e)
Exemplo n.º 21
0
 def _readTemperatureSensor(self):
   try:
     f = open(self._inside_config["sensor_path"], 'r')
     lines = f.readlines()
     f.close()
     return lines
   except Exception, e:
     CloudLog.error(self._component, "Unable to read indoor temperature sensor", e)
     return ""
Exemplo n.º 22
0
 def _startListen(self):
     if self._threadListen is None:
         try:
             CloudLog.log(self._component + ":StartListen",
                          "Starting UDP Listener")
             self._thread = thread.start_new_thread(self._runListenLoop,
                                                    (None, ))
         except Exception, e:
             CloudLog.error(self._component, "Unable to start listen loop",
                            e)
Exemplo n.º 23
0
 def __init__(self, ip_address, port):
     CloudLog.log(self._component, "Initializing.")
     self._ip_address = ip_address
     self._port = port
     try:
         import RPIO
         self.state = "READY"
     except Exception, e:
         self.state = "NO_RPIO"
         CloudLog.error(self._component, "RPIO is unavailable.", e)
Exemplo n.º 24
0
 def status(self):
     result = {"completed": False, "request": {}}
     result["request"]["command"] = "/status"
     if self._ready:
         try:
             response = self._phue.get_api()
             result["completed"] = True
             result["response"] = response
         except Exception, e:
             CloudLog.error(self._component, "Error calling phue", e)
Exemplo n.º 25
0
 def status(self):
   result = {"completed": False, "request": {}}
   result["request"]["command"] = "/status"
   if self._ready:
     try:
       response = self._phue.get_api()
       result["completed"] = True
       result["response"] = response
     except Exception, e:
       CloudLog.error(self._component, "Error calling phue", e)
Exemplo n.º 26
0
 def set_temp(self, device, temperature):
     try:
         temperature = int(temperature)
         if temperature >= 60 and temperature <= 75:
             self._send(device, str(temperature))
             self._status[device] = temperature
         else:
             CloudLog.error(self._component, "Cannot change temp.")
     except:
         CloudLog.error(self._component, "Temp out of range")
Exemplo n.º 27
0
 def get_activity_name(self, activity_id):
     try:
         if activity_id is None:
             return "NONE"
         for act_name, act_id in self.harmony_activities.iteritems():
             if str(act_id) == str(activity_id):
                 return str(act_name)
         return "UNKNOWN"
     except Exception, e:
         CloudLog.error(self._component, "Error getting activity name.", e)
Exemplo n.º 28
0
 def _startAnnounce(self):
     if self._threadAnnounce is None:
         try:
             CloudLog.log(self._component + ":StartAnnounce",
                          "Starting UDP Announcer")
             self._threadAnnounce = thread.start_new_thread(
                 self._runAnnounceLoop, (None, ))
         except Exception, e:
             CloudLog.error(self._component,
                            "Unable to start announce loop", e)
Exemplo n.º 29
0
 def __init__(self, ip_address, port):
   CloudLog.log(self._component, "Initializing.")
   self._ip_address = ip_address
   self._port = port
   try:
     import RPIO
     self.state = "READY"
   except Exception, e:
     self.state = "NO_RPIO"
     CloudLog.error(self._component, "RPIO is unavailable.", e)
Exemplo n.º 30
0
 def set_temp(self, device, temperature):
   try:
     temperature = int(temperature)
     if temperature >= 60 and temperature <= 75:
       self._send(device, str(temperature))
       self._status[device] = temperature
     else:
       CloudLog.error(self._component, "Cannot change temp.")
   except:
     CloudLog.error(self._component, "Temp out of range")
Exemplo n.º 31
0
 def _announce(self, state):
     try:
         CloudLog.track("CLOSET_DOOR", state)
         cmd = {"command": "CLOSET", "modifier": None}
         if state == "CLOSED":
             cmd["modifier"] = "Off"
         sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
         sock.sendto(json.dumps(cmd), (self._ip_address, self._port))
         sock.close()
     except Exception, e:
         CloudLog.error(self._component, "Announce", e)
Exemplo n.º 32
0
 def _runListenLoop(self, params):
   udp_socket = None
   try:
     ip = "192.168.1.201"
     port = 9557
     udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     udp_socket.bind((ip, port))
   except Exception, e:
     self._running = False
     udp_socket = None
     CloudLog.error(self._component, "Error opening socket", e)
Exemplo n.º 33
0
 def _announce(self, state):
   try:
     CloudLog.track("CLOSET_DOOR", state)
     cmd = {"command": "CLOSET", "modifier": None}
     if state == "CLOSED":
       cmd["modifier"] = "Off"
     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     sock.sendto(json.dumps(cmd), (self._ip_address, self._port))
     sock.close()
   except Exception, e:
     CloudLog.error(self._component, "Announce", e)
Exemplo n.º 34
0
 def sendCommand(self, lights, command):
   result = {"completed": False, "request": {}}
   result["request"]["lights"] = lights
   result["request"]["command"] = command
   if self._ready:
     try:
       response = self._phue.set_light(lights, command)
       result["completed"] = True
       result["response"] = response
     except Exception, e:
       CloudLog.error(self._component, "Error calling phue", e)
Exemplo n.º 35
0
 def sendCommand(self, lights, command):
     result = {"completed": False, "request": {}}
     result["request"]["lights"] = lights
     result["request"]["command"] = command
     if self._ready:
         try:
             response = self._phue.set_light(lights, command)
             result["completed"] = True
             result["response"] = response
         except Exception, e:
             CloudLog.error(self._component, "Error calling phue", e)
Exemplo n.º 36
0
 def _runLoop(self, params):
     CloudLog.log(self._component, "Running.")
     while self.running:
         try:
             self._controller.executeCommandByName("TEST")
             interval = 10
         except Exception, e:
             CloudLog.error(self._component, "Error in run loop", e)
             if interval < self._interval * 10:
                 interval += self._interval
         time.sleep(interval)
Exemplo n.º 37
0
 def _runListenLoop(self, params):
     udp_socket = None
     try:
         ip = "192.168.1.201"
         port = 9557
         udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
         udp_socket.bind((ip, port))
     except Exception, e:
         self._running = False
         udp_socket = None
         CloudLog.error(self._component, "Error opening socket", e)
Exemplo n.º 38
0
 def _runAnnounceLoop(self, params):
   udp_socket = None
   try:
     port = 9337
     ip = "239.2.2.4"
     udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     udp_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 4)
     udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
   except Exception, e:
     udp_socket = None
     CloudLog.error(self._component, "Error opening announce multicast socket", e)
Exemplo n.º 39
0
 def _runLoop(self, params):
   CloudLog.log(self._component, "Running.")
   while self.running:
     try:
       self._controller.executeCommandByName("TEST")
       interval = 10
     except Exception, e:
       CloudLog.error(self._component, "Error in run loop", e)
       if interval < self._interval * 10:
         interval += self._interval
     time.sleep(interval)
Exemplo n.º 40
0
 def change_temp(self, device, dir):
     try:
         new_temp = self._status[device]
         new_temp = int(new_temp)
         if dir.upper() == "UP":
             new_temp = new_temp + 1
         else:
             new_temp = new_temp - 1
         print("NewTemp", new_temp)
         self.set_temp(device, str(new_temp))
     except:
         CloudLog.error(self._component, "Cannot change temp.")
Exemplo n.º 41
0
 def change_temp(self, device, dir):
   try:
     new_temp = self._status[device]
     new_temp = int(new_temp)
     if dir.upper() == "UP":
       new_temp = new_temp + 1
     else:
       new_temp = new_temp - 1
     print ("NewTemp", new_temp)
     self.set_temp(device, str(new_temp))
   except:
     CloudLog.error(self._component, "Cannot change temp.")
Exemplo n.º 42
0
 def currentActivity(self):
     result = {"completed": False, "request": {}}
     result["request"]["command"] = "/currentActivity"
     client = self._getClient()
     if client:
         try:
             response = client.get_current_activity()
             result["completed"] = True
             result["response"] = response
         except Exception, e:
             CloudLog.error(self._component, "Unable to get current activity", e)
             result["error"] = str(e)
         finally:
Exemplo n.º 43
0
 def startActivity(self, activity_id):
     result = {"completed": False, "request": {}}
     result["request"]["activity_id"] = activity_id
     client = self._getClient()
     if client:
         try:
             response = client.start_activity(activity_id)
             result["completed"] = True
             result["response"] = response
         except Exception, e:
             CloudLog.error(self._component, "Unable to start activity", e)
             result["error"] = str(e)
         finally:
Exemplo n.º 44
0
 def _runAnnounceLoop(self, params):
     udp_socket = None
     try:
         port = 9337
         ip = "239.2.2.4"
         udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
         udp_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL,
                               4)
         udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
     except Exception, e:
         udp_socket = None
         CloudLog.error(self._component,
                        "Error opening announce multicast socket", e)
Exemplo n.º 45
0
 def startActivity(self, activity_id):
     result = {"completed": False, "request": {}}
     result["request"]["activity_id"] = activity_id
     client = self._getClient()
     if client:
         try:
             response = client.start_activity(activity_id)
             result["completed"] = True
             result["response"] = response
         except Exception, e:
             CloudLog.error(self._component, "Unable to start activity", e)
             result["error"] = str(e)
         finally:
Exemplo n.º 46
0
 def getConfig(self):
     result = {"completed": False, "request": {}}
     result["request"]["command"] = "/getConfig"
     client = self._getClient()
     if client:
         try:
             response = self._client.get_config()
             result["completed"] = True
             result["response"] = response
         except Exception, e:
             CloudLog.error(self._component, "Unable to get config", e)
             result["error"] = str(e)
         finally:
Exemplo n.º 47
0
 def getConfig(self):
     result = {"completed": False, "request": {}}
     result["request"]["command"] = "/getConfig"
     client = self._getClient()
     if client:
         try:
             response = self._client.get_config()
             result["completed"] = True
             result["response"] = response
         except Exception, e:
             CloudLog.error(self._component, "Unable to get config", e)
             result["error"] = str(e)
         finally:
Exemplo n.º 48
0
 def _runLoop(self, params):
   CloudLog.log(self._component, "Running.")
   while self.running:
     try:
       if self._settings["push"]:
         self._push()
       if self._settings["pull"]:
         self._pull()
       interval = self._settings["interval"]
     except Exception, e:
       CloudLog.error(self._component, "Error in run loop", e)
       if interval < self._interval * 10:
         interval += self._interval
     time.sleep(interval)
Exemplo n.º 49
0
 def _runLoop(self, params):
   CloudLog.log(self._component, "Running.")
   interval = self._settings["interval"]
   if self.unread is None:
     self.unread = 0
   while self.running:
     try:
       if self._controller.state == "HOME":
         output = Popen(['lynx', '-source', 'https://www.google.com/voice/request/unread'], stdout=PIPE)
         response = None
         response = output.stdout.read()
         response = json.loads(response)
         previous_count = self.unread
         self.unread = int(response["unreadCounts"]["all"])
         if self.unread > previous_count:
           cmd = self._settings["cmd_new"]
           self._controller.executeCommandByName(cmd)
         elif self.unread == 0 and previous_count > 0:
           cmd = self._settings["cmd_zero"]
           self._controller.executeCommandByName(cmd)
         interval = self._settings["interval"]
       else:
         interval = self._settings["interval"] * 2
       response = None
       error = None
     except ValueError, e:
       CloudLog.error(self._component, "Error parsing response", e)
       response = str(response)
       if len(response) > 512:
         response = response[:512] + "..."
       CloudLog.log(self._component, response)
       error = "Value"
     except Exception, e:
       CloudLog.error(self._component, "Error in run loop", e)
       error = "Unknown"
Exemplo n.º 50
0
 def currentActivity(self):
     result = {"completed": False, "request": {}}
     result["request"]["command"] = "/currentActivity"
     client = self._getClient()
     if client:
         try:
             response = client.get_current_activity()
             result["completed"] = True
             result["response"] = response
         except Exception, e:
             CloudLog.error(self._component,
                            "Unable to get current activity", e)
             result["error"] = str(e)
         finally:
Exemplo n.º 51
0
 def _runLoop(self, params):
     CloudLog.log(self._component, "Running.")
     while self.running:
         try:
             if self._settings["push"]:
                 self._push()
             if self._settings["pull"]:
                 self._pull()
             interval = self._settings["interval"]
         except Exception, e:
             CloudLog.error(self._component, "Error in run loop", e)
             if interval < self._interval * 10:
                 interval += self._interval
         time.sleep(interval)
Exemplo n.º 52
0
 def _runListenLoop(self, params):
   udp_socket = None
   try:
     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     s.connect(("google.com",80))
     ip = s.getsockname()[0]
     s.close()
     port = 9557
     udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     udp_socket.bind((ip, port))
   except Exception, e:
     self._running = False
     udp_socket = None
     CloudLog.error(self._component, "Error opening socket", e)
Exemplo n.º 53
0
 def save(self):
     try:
         CloudLog.log(self._component, "Saving config file.")
         new_config = {}
         new_config["config"] = self.settings
         new_config["ac_commands"] = self.ac_commands
         new_config["light_recipes"] = self.light_recipes
         new_config["harmony_activities"] = self.harmony_activities
         new_config["commands"] = self.commands
         result = json.dumps(new_config)
         with open(self._config_file, "w") as text_file:
             text_file.write(result)
     except Exception, e:
         CloudLog.error(self._component, "Error saving config file.", e)
Exemplo n.º 54
0
 def _query(self, method, url, content):
     try:
         headers = {}
         headers["Content-Type"] = "application/json"
         headers["Accept"] = "*/*"
         conn = httplib.HTTPSConnection(
             "petele-home-automation.appspot.com")
         conn.request(method, url, content, headers)
         response = conn.getresponse()
         if response.status != 200:
             CloudLog.error(self._component, "Query response was not 200.")
         result = response.read()
         conn.close()
         return result
     except Exception, e:
         CloudLog.error(self._component,
                        "Exception performing Cloud query.", e)