예제 #1
0
    def onConfigureMessage(self, managerConfig):
        self.readLocalConfig()
        idToName2 = {}
        for adaptor in managerConfig["adaptors"]:
            adtID = adaptor["id"]
            if adtID not in self.devices:
                # Because managerConfigure may be re-called if devices are added
                name = adaptor["name"]
                friendly_name = adaptor["friendly_name"]
                self.cbLog(
                    "debug", "managerConfigure app. Adaptor id: " + adtID +
                    " name: " + name + " friendly_name: " + friendly_name)
                idToName2[adtID] = friendly_name
                self.idToName[adtID] = friendly_name.replace(" ", "_")
                self.devices.append(adtID)
        self.client = CbClient(self.id, CID, 5)
        self.client.onClientMessage = self.onClientMessage
        self.client.sendMessage = self.sendMessage
        self.client.cbLog = self.cbLog
        self.client.loadSaved()
        for a in idToName2:
            self.medicine[a] = Medicine(self.bridge_id, idToName2[a])
            self.medicine[a].cbLog = self.cbLog
            self.medicine[a].client = self.client
            self.medicine[a].setIDs(self.bridge_id, self.idToName)
            if a in self.gotSensor:  # Caters for adaptors responding before the manager
                self.medicine[a].gotSensor = True
                self.gotSensor.remove(a)

        self.setState("starting")
 def onConfigureMessage(self, managerConfig):
     self.readLocalConfig()
     idToName2 = {}
     for adaptor in managerConfig["adaptors"]:
         adtID = adaptor["id"]
         if adtID not in self.devices:
             # Because managerConfigure may be re-called if devices are added
             name = adaptor["name"]
             friendly_name = adaptor["friendly_name"]
             self.cbLog("debug", "managerConfigure app. Adaptor id: " +  adtID + " name: " + name + " friendly_name: " + friendly_name)
             idToName2[adtID] = friendly_name
             self.idToName[adtID] = friendly_name.replace(" ", "_")
             self.devices.append(adtID)
     self.client = CbClient(self.id, CID, 5)
     self.client.onClientMessage = self.onClientMessage
     self.client.sendMessage = self.sendMessage
     self.client.cbLog = self.cbLog
     self.client.loadSaved()
     self.nightWander.bridge_id = self.bridge_id
     self.nightWander.cbLog = self.cbLog
     self.nightWander.client = self.client
     self.nightWander.setIDs(self.bridge_id, self.idToName)
     self.nightWander.saveFile = CB_CONFIG_DIR + self.id + ".savestate"
     self.nightWander.loadSaved()
     self.nightWander.reportEnds()
     self.setState("starting")
예제 #3
0
    def onConfigureMessage(self, managerConfig):
        self.readLocalConfig()
        idToName2 = {}
        for adaptor in managerConfig["adaptors"]:
            adtID = adaptor["id"]
            if adtID not in self.devices:
                # Because managerConfigure may be re-called if devices are added
                name = adaptor["name"]
                friendly_name = adaptor["friendly_name"]
                self.cbLog("debug", "managerConfigure app. Adaptor id: " +  adtID + " name: " + name + " friendly_name: " + friendly_name)
                idToName2[adtID] = friendly_name
                self.idToName[adtID] = friendly_name.replace(" ", "_")
                self.devices.append(adtID)
        self.client = CbClient(self.id, CID, 5)
        self.client.onClientMessage = self.onClientMessage
        self.client.sendMessage = self.sendMessage
        self.client.cbLog = self.cbLog
        self.client.loadSaved()
        for a in idToName2:
            self.medicine[a] = Medicine(self.bridge_id, idToName2[a])
            self.medicine[a].cbLog = self.cbLog
            self.medicine[a].client = self.client
            self.medicine[a].setIDs(self.bridge_id, self.idToName)
            if a in self.gotSensor:  # Caters for adaptors responding before the manager
                self.medicine[a].gotSensor = True
                self.gotSensor.remove(a)

        self.setState("starting")
예제 #4
0
 def onConfigureMessage(self, managerConfig):
     #self.readLocalConfig()
     self.client = CbClient(self.id, CID, 3)
     self.client.onClientMessage = self.onClientMessage
     self.client.sendMessage = self.sendMessage
     self.client.cbLog = self.cbLog
     self.saveFile = CB_CONFIG_DIR + self.id + ".savestate"
     self.loadSaved()
     reactor.callLater(CHECK_INTERVAL, self.checkConnected)
     self.setState("starting")
예제 #5
0
 def onConfigureMessage(self, managerConfig):
     for adaptor in managerConfig["adaptors"]:
         adtID = adaptor["id"]
         if adtID not in self.devices:
             # Because managerConfigure may be re-called if devices are added
             name = adaptor["name"]
             friendly_name = adaptor["friendly_name"]
             #self.cbLog("debug", "managerConfigure app. Adaptor id: " +  adtID + " name: " + name + " friendly_name: " + friendly_name)
             self.idToName[adtID] = friendly_name.replace(" ", "_")
             self.devices.append(adtID)
     self.readLocalConfig()
     self.enableState = EnableState() 
     self.enableState.cbLog = self.cbLog
     self.enableState.id = self.id
     self.enableState.sendMessage = self.sendMessage
     self.client = CbClient(self.id, CID, 5)
     self.client.onClientMessage = self.onClientMessage
     self.client.sendMessage = self.sendMessage
     self.client.cbLog = self.cbLog
     self.client.loadSaved()
     self.setState("starting")
 def onConfigureMessage(self, managerConfig):
     self.readLocalConfig()
     idToName2 = {}
     for adaptor in managerConfig["adaptors"]:
         adtID = adaptor["id"]
         if adtID not in self.devices:
             # Because managerConfigure may be re-called if devices are added
             name = adaptor["name"]
             friendly_name = adaptor["friendly_name"]
             self.cbLog("debug", "managerConfigure app. Adaptor id: " +  adtID + " name: " + name + " friendly_name: " + friendly_name)
             idToName2[adtID] = friendly_name
             self.idToName[adtID] = friendly_name.replace(" ", "_")
             self.devices.append(adtID)
     self.client = CbClient(self.id, CID, 100)
     self.client.onClientMessage = self.onClientMessage
     self.client.sendMessage = self.sendMessage
     self.client.cbLog = self.cbLog
     self.client.loadSaved()
     self.dm.initAddress(self.bridge_id, self.idToName)
     self.dm.cbLog = self.cbLog
     self.dm.client = self.client
     self.setState("starting")
예제 #7
0
class App(CbApp):
    def __init__(self, argv):
        self.appClass = "monitor"
        self.state = "stopped"
        self.status = "ok"
        self.devices = []
        self.idToName = {} 
        self.entryExit = EntryExit()
        #CbApp.__init__ MUST be called
        CbApp.__init__(self, argv)

    def setState(self, action):
        if action == "clear_error":
            self.state = "running"
        else:
            self.state = action
        msg = {"id": self.id,
               "status": "state",
               "state": self.state}
        self.sendManagerMessage(msg)

    def onConcMessage(self, message):
        #self.cbLog("debug", "onConcMessage, message: " + str(json.dumps(message, indent=4)))
        if "status" in message:
            if message["status"] == "ready":
                # Do this after we have established communications with the concentrator
                msg = {
                    "m": "req_config",
                    "d": self.id
                }
                self.client.send(msg)
        self.client.receive(message)

    def onClientMessage(self, message):
        self.cbLog("debug", "onClientMessage, message: " + str(json.dumps(message, indent=4)))
        global config
        if "config" in message:
            if "warning" in message["config"]:
                self.cbLog("warning", "onClientMessage: " + str(json.dumps(message["config"], indent=4)))
            else:
                try:
                    newConfig = message["config"]
                    copyConfig = config.copy()
                    copyConfig.update(newConfig)
                    if copyConfig != config or not os.path.isfile(CONFIG_FILE):
                        self.cbLog("debug", "onClientMessage. Updating config from client message")
                        config = copyConfig.copy()
                        with open(CONFIG_FILE, 'w') as f:
                            json.dump(config, f)
                        self.cbLog("info", "Config updated")
                        self.readLocalConfig()
                        # With a new config, send init message to all connected adaptors
                        for i in self.adtInstances:
                            init = {
                                "id": self.id,
                                "appClass": self.appClass,
                                "request": "init"
                            }
                            self.sendMessage(init, i)
                except Exception as ex:
                    self.cbLog("warning", "onClientMessage, could not write to file. Type: " + str(type(ex)) + ", exception: " +  str(ex.args))

    def onAdaptorData(self, message):
        #self.cbLog("debug", "onAdaptorData, message: " + str(json.dumps(message, indent=4)))
        if message["characteristic"] == "binary_sensor":
            self.entryExit.onChange(message["id"], message["timeStamp"], message["data"])

    def onAdaptorService(self, message):
        self.cbLog("debug", "onAdaptorService, message: " + str(json.dumps(message, indent=4)))
        if self.state == "starting":
            self.setState("running")
        serviceReq = []
        for p in message["service"]:
            if p["characteristic"] == "binary_sensor":
                if "type" in p:
                    if p["type"] == "pir":
                        self.entryExit.pirID = message["id"]
                        serviceReq.append({"characteristic": "binary_sensor", "interval": 0})
                    else:
                        self.entryExit.magID = message["id"]
                        serviceReq.append({"characteristic": "binary_sensor", "interval": 0})
                else:
                    self.entryExit.magID = message["id"]
                    serviceReq.append({"characteristic": "binary_sensor", "interval": 0})
        msg = {"id": self.id,
               "request": "service",
               "service": serviceReq}
        self.sendMessage(msg, message["id"])
        self.cbLog("debug", "onAdaptorService, response: " + str(json.dumps(msg, indent=4)))

    def readLocalConfig(self):
        global config
        try:
            with open(CONFIG_FILE, 'r') as f:
                newConfig = json.load(f)
                self.cbLog("debug", "Read local config")
                config.update(newConfig)
        except Exception as ex:
            self.cbLog("warning", "Local config does not exist or file is corrupt. Exception: " + str(type(ex)) + str(ex.args))
        self.cbLog("debug", "Config: " + str(json.dumps(config, indent=4)))

    def onConfigureMessage(self, managerConfig):
        self.readLocalConfig()
        idToName2 = {}
        for adaptor in managerConfig["adaptors"]:
            adtID = adaptor["id"]
            if adtID not in self.devices:
                # Because managerConfigure may be re-called if devices are added
                name = adaptor["name"]
                friendly_name = adaptor["friendly_name"]
                self.cbLog("debug", "managerConfigure app. Adaptor id: " +  adtID + " name: " + name + " friendly_name: " + friendly_name)
                idToName2[adtID] = friendly_name
                self.idToName[adtID] = friendly_name.replace(" ", "_")
                self.devices.append(adtID)
        self.client = CbClient(self.id, CID, 5)
        self.client.onClientMessage = self.onClientMessage
        self.client.sendMessage = self.sendMessage
        self.client.cbLog = self.cbLog
        self.client.loadSaved()
        self.entryExit.client = self.client
        self.entryExit.cbLog = self.cbLog
        self.entryExit.setIDs(self.bridge_id, self.idToName)
        self.setState("starting")
예제 #8
0
class App(CbApp):
    def __init__(self, argv):
        self.appClass = "control"
        self.state = "stopped"
        self.sensorsID = [] 
        self.onSensors = []
        self.devices = []
        self.idToName = {} 
        self.lastTrigger = 0
        reactor.callLater(10, self.resetSensors)
        # Super-class init must be called
        CbApp.__init__(self, argv)

    def setState(self, action):
        self.state = action
        msg = {"id": self.id,
               "status": "state",
               "state": self.state}
        self.sendManagerMessage(msg)

    def resetSensors(self):
        if time.time() - self.lastTrigger > config["ignore_time"]:
            self.onSensors = []
        reactor.callLater(10, self.resetSensors)

    def readLocalConfig(self):
        global config
        try:
            with open(CONFIG_FILE, 'r') as f:
                newConfig = json.load(f)
                self.cbLog("debug", "Read local config")
                config.update(newConfig)
        except Exception as ex:
            self.cbLog("warning", "Local config does not exist or file is corrupt. Exception: " + str(type(ex)) + str(ex.args))
        self.cbLog("debug", "Config: " + str(json.dumps(config, indent=4)))

    def onConcMessage(self, message):
        #self.cbLog("debug", "onConcMessage, message: " + str(json.dumps(message, indent=4)))
        if "status" in message:
            if message["status"] == "ready":
                # Do this after we have established communications with the concentrator
                msg = {
                    "m": "req_config",
                    "d": self.id
                }
                self.client.send(msg)
        self.client.receive(message)

    def onClientMessage(self, message):
        #self.cbLog("debug", "onClientMessage, message: " + str(json.dumps(message, indent=4)))
        global config
        if "config" in message:
            if "warning" in message["config"]:
                self.cbLog("warning", "onClientMessage: " + str(json.dumps(message["config"], indent=4)))
            else:
                try:
                    newConfig = message["config"]
                    copyConfig = config.copy()
                    copyConfig.update(newConfig)
                    if copyConfig != config or not os.path.isfile(CONFIG_FILE):
                        self.cbLog("debug", "onClientMessage. Updating config from client message")
                        config = copyConfig.copy()
                        with open(CONFIG_FILE, 'w') as f:
                            json.dump(config, f)
                        #self.cbLog("info", "Config updated")
                        self.readLocalConfig()
                        # With a new config, send init message to all connected adaptors
                        for i in self.adtInstances:
                            init = {
                                "id": self.id,
                                "appClass": self.appClass,
                                "request": "init"
                            }
                            self.sendMessage(init, i)
                except Exception as ex:
                    self.cbLog("warning", "onClientMessage, could not write to file. Type: " + str(type(ex)) + ", exception: " +  str(ex.args))

    def onAdaptorService(self, message):
        #self.cbLog("debug", "onAdaptorService. message: " + str(message))
        sensor = False
        switch = False
        buttons = False
        binary_sensor = False
        number_buttons = False
        for p in message["service"]:
            if p["characteristic"] == "buttons":
                buttons = True
            if p["characteristic"] == "number_buttons":
                number_buttons = True
            if p["characteristic"] == "switch":
                switch = True
            if p["characteristic"] == "binary_sensor":
                binary_sensor = True
        if switch and binary_sensor:
            binary_sensor = False  # Don't trigger on an indicator device
        if buttons:
            self.sensorsID.append(message["id"])
            req = {"id": self.id,
                   "request": "service",
                   "service": [
                                 {"characteristic": "buttons",
                                  "interval": 0
                                 }
                              ]
                  }
            self.sendMessage(req, message["id"])
        if number_buttons:
            self.sensorsID.append(message["id"])
            req = {"id": self.id,
                   "request": "service",
                   "service": [
                                 {"characteristic": "number_buttons",
                                  "interval": 0
                                 }
                              ]
                  }
            self.sendMessage(req, message["id"])
        if binary_sensor:
            self.sensorsID.append(message["id"])
            req = {"id": self.id,
                   "request": "service",
                   "service": [
                                 {"characteristic": "binary_sensor",
                                  "interval": 0
                                 }
                              ]
                  }
            self.sendMessage(req, message["id"])
        if switch:
            self.enableState.setSwitch(message["id"])
        self.setState("running")

    def onAdaptorData(self, message):
        #self.cbLog("debug", "onAdaptorData. message: " + str(message))
        if message["id"] in self.sensorsID:
            if message["characteristic"] == "buttons":
                if message["data"]["rightButton"] == 1:
                    self.enableState.enable(True)
                elif message["data"]["leftButton"] == 1:
                    self.enableState.enable(False)
                self.cbLog("debug", "onAdaptorData. alarm: " + str(self.enableState.isEnabled()))
            elif message["characteristic"] == "number_buttons":
                for m in message["data"].keys():
                    if m == "1":
                        self.enableState.enable(True)
                    elif m == "3":
                        self.enableState.enable(False)
                self.cbLog("debug", "onAdaptorData. alarm: " + str(self.enableState.isEnabled()))
            elif message["characteristic"] == "binary_sensor":
                if self.enableState.isEnabled() and message["data"] == "on":
                    if not message["id"] in self.onSensors:
                        now = time.time()
                        self.lastTrigger = now
                        self.onSensors.append(message["id"])
                        active = []
                        for a in self.onSensors:
                            active.append(self.idToName[a])
                        msg = {"m": "alert",
                               "a": "Intruder detected by " + str(", ".join(active)) + " at " + nicetime(now),
                               "t": now
                        }
                        self.client.send(msg)
                #self.cbLog("debug", "onSensors: " + str(self.onSensors))

    def onConfigureMessage(self, managerConfig):
        for adaptor in managerConfig["adaptors"]:
            adtID = adaptor["id"]
            if adtID not in self.devices:
                # Because managerConfigure may be re-called if devices are added
                name = adaptor["name"]
                friendly_name = adaptor["friendly_name"]
                #self.cbLog("debug", "managerConfigure app. Adaptor id: " +  adtID + " name: " + name + " friendly_name: " + friendly_name)
                self.idToName[adtID] = friendly_name.replace(" ", "_")
                self.devices.append(adtID)
        self.readLocalConfig()
        self.enableState = EnableState() 
        self.enableState.cbLog = self.cbLog
        self.enableState.id = self.id
        self.enableState.sendMessage = self.sendMessage
        self.client = CbClient(self.id, CID, 5)
        self.client.onClientMessage = self.onClientMessage
        self.client.sendMessage = self.sendMessage
        self.client.cbLog = self.cbLog
        self.client.loadSaved()
        self.setState("starting")
class App(CbApp):
    def __init__(self, argv):
        self.appClass = "monitor"
        self.state = "stopped"
        self.status = "ok"
        self.accel = []
        self.gyro = []
        self.magnet = []
        self.temp = []
        self.irTemp = []
        self.buttons = []
        self.humidity = []
        self.binary = []
        self.luminance = []
        self.power = []
        self.battery = []
        self.connected = []
        self.devices = []
        self.idToName = {} 
        self.dm = DataManager()
        #CbApp.__init__ MUST be called
        CbApp.__init__(self, argv)

    def setState(self, action):
        if action == "clear_error":
            self.state = "running"
        else:
            self.state = action
        msg = {"id": self.id,
               "status": "state",
               "state": self.state}
        self.sendManagerMessage(msg)

    def onStop(self):
        self.client.save()

    def onConcMessage(self, message):
        #self.cbLog("debug", "onConcMessage, message: " + str(json.dumps(message, indent=4)))
        if "status" in message:
            if message["status"] == "ready":
                # Do this after we have established communications with the concentrator
                msg = {
                    "m": "req_config",
                    "d": self.id
                }
                self.client.send(msg)
        self.client.receive(message)

    def onClientMessage(self, message):
        self.cbLog("debug", "onClientMessage, message: " + str(json.dumps(message, indent=4)))
        global config
        if "config" in message:
            if "warning" in message["config"]:
                self.cbLog("warning", "onClientMessage: " + str(json.dumps(message["config"], indent=4)))
            else:
                try:
                    newConfig = message["config"]
                    copyConfig = config.copy()
                    copyConfig.update(newConfig)
                    if copyConfig != config or not os.path.isfile(CONFIG_FILE):
                        self.cbLog("debug", "onClientMessage. Updating config from client message")
                        config = copyConfig.copy()
                        with open(CONFIG_FILE, 'w') as f:
                            json.dump(config, f)
                        self.cbLog("info", "Config updated")
                        self.readLocalConfig()
                        # With a new config, send init message to all connected adaptors
                        for i in self.adtInstances:
                            init = {
                                "id": self.id,
                                "appClass": self.appClass,
                                "request": "init"
                            }
                            self.sendMessage(init, i)
                except Exception as ex:
                    self.cbLog("warning", "onClientMessage, could not write to file. Type: " + str(type(ex)) + ", exception: " +  str(ex.args))

    def onAdaptorData(self, message):
        #self.cbLog("debug", "onadaptorData, message: " + str(json.dumps(message, indent=4)))
        if not timeCorrect():
            self.cbLog("info", "Data not processed as time is not correct")
            return 
        if message["characteristic"] == "acceleration":
            for a in self.accel:
                if a.id == self.idToName[message["id"]]: 
                    a.processAccel(message)
                    break
        elif message["characteristic"] == "temperature":
            for t in self.temp:
                if t.id == self.idToName[message["id"]]:
                    t.processTemp(message)
                    break
        elif message["characteristic"] == "ir_temperature":
            for t in self.irTemp:
                if t.id == self.idToName[message["id"]]:
                    t.processIrTemp(message)
                    break
        elif message["characteristic"] == "gyro":
            for g in self.gyro:
                if g.id == self.idToName[message["id"]]:
                    g.processGyro(message)
                    break
        elif message["characteristic"] == "magnetometer":
            for g in self.magnet:
                if g.id == self.idToName[message["id"]]:
                    g.processMagnet(message)
                    break
        elif message["characteristic"] == "buttons":
            for b in self.buttons:
                if b.id == self.idToName[message["id"]]:
                    b.processButtons(message)
                    break
        elif message["characteristic"] == "humidity":
            for b in self.humidity:
                if b.id == self.idToName[message["id"]]:
                    b.processHumidity(message)
                    break
        elif message["characteristic"] == "binary_sensor":
            for b in self.binary:
                if b.id == self.idToName[message["id"]]:
                    b.processBinary(message)
                    break
        elif message["characteristic"] == "power":
            for b in self.power:
                if b.id == self.idToName[message["id"]]:
                    b.processPower(message)
                    break
        elif message["characteristic"] == "battery":
            self.cbLog("debug", "Battery, message: " + str(message))
            for b in self.battery:
                if b.id == self.idToName[message["id"]]:
                    b.processBattery(message)
                    break
        elif message["characteristic"] == "connected":
            self.cbLog("debug", "Connected, message: " + str(message))
            for b in self.connected:
                if b.id == self.idToName[message["id"]]:
                    b.processConnected(message)
                    break
        elif message["characteristic"] == "luminance":
            for b in self.luminance:
                if b.id == self.idToName[message["id"]]:
                    b.processLuminance(message)
                    break

    def onAdaptorService(self, message):
        self.cbLog("debug", "onAdaptorService, message: " + str(json.dumps(message, indent=4)))
        if self.state == "starting":
            self.setState("running")
        serviceReq = []
        for p in message["service"]:
            # Based on services offered & whether we want to enable them
            if p["characteristic"] == "temperature":
                if config["temperature"]:
                    self.temp.append(TemperatureMeasure((self.idToName[message["id"]])))
                    self.temp[-1].dm = self.dm
                    self.temp[-1].cbLog = self.cbLog
                    serviceReq.append({"characteristic": "temperature",
                                       "interval": config["temperature_polling_interval"]})
            elif p["characteristic"] == "ir_temperature":
                if config["irtemperature"]:
                    self.irTemp.append(IrTemperatureMeasure(self.idToName[message["id"]]))
                    self.irTemp[-1].dm = self.dm
                    serviceReq.append({"characteristic": "ir_temperature",
                                       "interval": config["temperature_polling_interval"]})
            elif p["characteristic"] == "acceleration":
                if config["accel"]:
                    self.accel.append(Accelerometer((self.idToName[message["id"]])))
                    serviceReq.append({"characteristic": "acceleration",
                                       "interval": config["accel_polling_interval"]})
                    self.accel[-1].dm = self.dm
            elif p["characteristic"] == "gyro":
                if config["gyro"]:
                    self.gyro.append(Gyro(self.idToName[message["id"]]))
                    self.gyro[-1].dm = self.dm
                    serviceReq.append({"characteristic": "gyro",
                                       "interval": config["gyro_polling_interval"]})
            elif p["characteristic"] == "magnetometer":
                if config["magnet"]:
                    self.magnet.append(Magnet(self.idToName[message["id"]]))
                    self.magnet[-1].dm = self.dm
                    serviceReq.append({"characteristic": "magnetometer",
                                       "interval": config["magnet_polling_interval"]})
            elif p["characteristic"] == "buttons":
                if config["buttons"]:
                    self.buttons.append(Buttons(self.idToName[message["id"]]))
                    self.buttons[-1].dm = self.dm
                    serviceReq.append({"characteristic": "buttons",
                                       "interval": 0})
            elif p["characteristic"] == "humidity":
                if config["humidity"]:
                    self.humidity.append(Humid(self.idToName[message["id"]]))
                    self.humidity[-1].dm = self.dm
                    self.humidity[-1].cbLog = self.cbLog
                    serviceReq.append({"characteristic": "humidity",
                                       "interval": config["humidity_polling_interval"]})
            elif p["characteristic"] == "binary_sensor":
                if config["binary"]:
                    self.binary.append(Binary(self.idToName[message["id"]]))
                    self.binary[-1].dm = self.dm
                    self.binary[-1].cbLog = self.cbLog
                    serviceReq.append({"characteristic": "binary_sensor",
                                       "interval": 0})
            elif p["characteristic"] == "power":
                if config["power"]:
                    self.power.append(Power(self.idToName[message["id"]]))
                    self.power[-1].dm = self.dm
                    serviceReq.append({"characteristic": "power",
                                       "interval": config["power_polling_interval"]})
            elif p["characteristic"] == "battery":
                if config["battery"]:
                    self.battery.append(Battery(self.idToName[message["id"]]))
                    self.battery[-1].dm = self.dm
                    serviceReq.append({"characteristic": "battery",
                                       "interval": config["battery_polling_interval"]})
            elif p["characteristic"] == "connected":
                if config["connected"]:
                    self.connected.append(Connected(self.idToName[message["id"]]))
                    self.connected[-1].dm = self.dm
                    serviceReq.append({"characteristic": "connected",
                                       "interval": 0})
            elif p["characteristic"] == "luminance":
                if config["luminance"]:
                    self.luminance.append(Luminance(self.idToName[message["id"]]))
                    self.luminance[-1].dm = self.dm
                    self.luminance[-1].cbLog = self.cbLog
                    serviceReq.append({"characteristic": "luminance",
                                       "interval": config["luminance_polling_interval"]})
        msg = {"id": self.id,
               "request": "service",
               "service": serviceReq}
        self.sendMessage(msg, message["id"])

    def readLocalConfig(self):
        global config
        try:
            with open(CONFIG_FILE, 'r') as f:
                newConfig = json.load(f)
                self.cbLog("debug", "Read local config")
                config.update(newConfig)
        except Exception as ex:
            self.cbLog("warning", "Local config does not exist or file is corrupt. Exception: " + str(type(ex)) + str(ex.args))
        self.cbLog("debug", "Config: " + str(json.dumps(config, indent=4)))

    def onConfigureMessage(self, managerConfig):
        self.readLocalConfig()
        idToName2 = {}
        for adaptor in managerConfig["adaptors"]:
            adtID = adaptor["id"]
            if adtID not in self.devices:
                # Because managerConfigure may be re-called if devices are added
                name = adaptor["name"]
                friendly_name = adaptor["friendly_name"]
                self.cbLog("debug", "managerConfigure app. Adaptor id: " +  adtID + " name: " + name + " friendly_name: " + friendly_name)
                idToName2[adtID] = friendly_name
                self.idToName[adtID] = friendly_name.replace(" ", "_")
                self.devices.append(adtID)
        self.client = CbClient(self.id, CID, 100)
        self.client.onClientMessage = self.onClientMessage
        self.client.sendMessage = self.sendMessage
        self.client.cbLog = self.cbLog
        self.client.loadSaved()
        self.dm.initAddress(self.bridge_id, self.idToName)
        self.dm.cbLog = self.cbLog
        self.dm.client = self.client
        self.setState("starting")
예제 #10
0
class App(CbApp):
    def __init__(self, argv):
        self.appClass = "monitor"
        self.state = "stopped"
        self.status = "ok"
        self.devices = []
        self.idToName = {}
        self.medicine = {}
        self.gotSensor = []
        #CbApp.__init__ MUST be called
        CbApp.__init__(self, argv)

    def setState(self, action):
        if action == "clear_error":
            self.state = "running"
        else:
            self.state = action
        msg = {"id": self.id, "status": "state", "state": self.state}
        self.sendManagerMessage(msg)

    def onConcMessage(self, message):
        #self.cbLog("debug", "onConcMessage, message: " + str(json.dumps(message, indent=4)))
        if "status" in message:
            if message["status"] == "ready":
                # Do this after we have established communications with the concentrator
                msg = {"m": "req_config", "d": self.id}
                self.client.send(msg)
        self.client.receive(message)

    def onClientMessage(self, message):
        self.cbLog(
            "debug",
            "onClientMessage, message: " + str(json.dumps(message, indent=4)))
        global config
        if "config" in message:
            if "warning" in message["config"]:
                self.cbLog(
                    "warning", "onClientMessage: " +
                    str(json.dumps(message["config"], indent=4)))
            else:
                try:
                    newConfig = message["config"]
                    copyConfig = config.copy()
                    copyConfig.update(newConfig)
                    if copyConfig != config or not os.path.isfile(CONFIG_FILE):
                        self.cbLog(
                            "debug",
                            "onClientMessage. Updating config from client message"
                        )
                        config = copyConfig.copy()
                        with open(CONFIG_FILE, 'w') as f:
                            json.dump(config, f)
                        self.cbLog("info", "Config updated")
                        self.readLocalConfig()
                        # With a new config, send init message to all connected adaptors
                        for i in self.adtInstances:
                            init = {
                                "id": self.id,
                                "appClass": self.appClass,
                                "request": "init"
                            }
                            self.sendMessage(init, i)
                except Exception as ex:
                    self.cbLog(
                        "warning",
                        "onClientMessage, could not write to file. Type: " +
                        str(type(ex)) + ", exception: " + str(ex.args))

    def onAdaptorData(self, message):
        #self.cbLog("debug", "onAdaptorData, message: " + str(json.dumps(message, indent=4)))
        try:
            if message["characteristic"] == "acceleration":
                self.medicine[message["id"]].onChange(message["timeStamp"], [
                    message["data"]["x"], message["data"]["y"],
                    message["data"]["z"]
                ])
        except Exception as ex:
            self.cbLog(
                "warning", "onAdaptorData problem. Exception: " +
                str(type(ex)) + str(ex.args))

    def onAdaptorService(self, message):
        #self.cbLog("debug", "onAdaptorService, message: " + str(json.dumps(message, indent=4)))
        try:
            if self.state == "starting":
                self.setState("running")
            serviceReq = []
            for p in message["service"]:
                if p["characteristic"] == "acceleration":
                    if self.medicine[message["id"]]:
                        self.medicine[message["id"]].gotSensor = True
                    else:
                        self.gotSensor.append(message["id"])
                    serviceReq.append({
                        "characteristic": "acceleration",
                        "interval": 2
                    })
            msg = {"id": self.id, "request": "service", "service": serviceReq}
            self.sendMessage(msg, message["id"])
            self.cbLog(
                "debug", "onAdaptorService, response: " +
                str(json.dumps(msg, indent=4)))
        except Exception as ex:
            self.cbLog(
                "warning", "onAdaptorServices problem. Exception: " +
                str(type(ex)) + str(ex.args))

    def readLocalConfig(self):
        global config
        try:
            with open(CONFIG_FILE, 'r') as f:
                newConfig = json.load(f)
                self.cbLog("debug", "Read local config")
                config.update(newConfig)
        except Exception as ex:
            self.cbLog(
                "warning",
                "Local config does not exist or file is corrupt. Exception: " +
                str(type(ex)) + str(ex.args))
        self.cbLog("debug", "Config: " + str(json.dumps(config, indent=4)))

    def onConfigureMessage(self, managerConfig):
        self.readLocalConfig()
        idToName2 = {}
        for adaptor in managerConfig["adaptors"]:
            adtID = adaptor["id"]
            if adtID not in self.devices:
                # Because managerConfigure may be re-called if devices are added
                name = adaptor["name"]
                friendly_name = adaptor["friendly_name"]
                self.cbLog(
                    "debug", "managerConfigure app. Adaptor id: " + adtID +
                    " name: " + name + " friendly_name: " + friendly_name)
                idToName2[adtID] = friendly_name
                self.idToName[adtID] = friendly_name.replace(" ", "_")
                self.devices.append(adtID)
        self.client = CbClient(self.id, CID, 5)
        self.client.onClientMessage = self.onClientMessage
        self.client.sendMessage = self.sendMessage
        self.client.cbLog = self.cbLog
        self.client.loadSaved()
        for a in idToName2:
            self.medicine[a] = Medicine(self.bridge_id, idToName2[a])
            self.medicine[a].cbLog = self.cbLog
            self.medicine[a].client = self.client
            self.medicine[a].setIDs(self.bridge_id, self.idToName)
            if a in self.gotSensor:  # Caters for adaptors responding before the manager
                self.medicine[a].gotSensor = True
                self.gotSensor.remove(a)

        self.setState("starting")