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:
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)
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
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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"]
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)
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 ""
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)
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)
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)
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")
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)
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)
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)
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)
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)
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)
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)
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.")
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.")
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:
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:
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:
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)
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"
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)
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)
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)