Ejemplo n.º 1
0
 def __init__(self, config):
     self.__config = config
     self.__event = Event()
     provider = AwsProvider(self.__config)
     self.__shadow = provider.get_shadow_handle()
     self.__lights = Lights(self.__config)
     self.__lights.register(self, self.update)
     logger.debug("Shadow Handle is {}".format(self.__shadow))
Ejemplo n.º 2
0
    def test_singleton(self):
        a = Lights(self.config)
        b = Lights(self.config)

        leds = {
            "green": "on"
        }
        a.toogle(leds)

        astate = a.get_state()
        bstate = b.get_state()

        self.assertEqual(astate, bstate)
Ejemplo n.º 3
0
class Service:
    __shadow = {}
    __state = {}
    __lights = {}

    def __init__(self, config):
        self.__config = config
        self.__event = Event()
        provider = AwsProvider(self.__config)
        self.__shadow = provider.get_shadow_handle()
        self.__lights = Lights(self.__config)
        self.__lights.register(self, self.update)
        logger.debug("Shadow Handle is {}".format(self.__shadow))

    # {"version":5,"timestamp":1554580866,"state":{"green":"off"},"metadata":{"green":{"timestamp":1554580866}}}
    def __delta_callback(self, payload, responseStatus, token):
        logger.debug("Delta Callback payload is {}".format(payload))
        current = json.loads(payload)
        # Process the desired state first to see if we can set the LEDs to the correct state
        for key in current["state"]:
            logger.debug("Delta state item is {}".format(key))
            # Check if led or not
            if key == 'lights':
                self.__lights.toogle(current["state"][key])
            if key == 'polling':
                self.__config["sensor"]["polling"] = current["state"][key]
                self.update("polling", self.__config["sensor"]["polling"])

    def __updated_callback(self, payload, responseStatus, token):
        logger.debug("Updated Callback payload is {}".format(payload))

    # {"state":{"desired":{"welcome":"aws-iot",
    # "lights":{"green":"on","yellow":"off","red":"off"}},
    # "reported":{"welcome":"aws-iot"},
    # "delta":{"lights":{"green":"on","yellow":"off","red":"off"}}},
    # "metadata":{"desired":{"welcome":{"timestamp":1554635548},
    # "lights":{"green":{"timestamp":1554635548},"yellow":{"timestamp":1554635548},"red":{"timestamp":1554635548}}},
    # "reported":{"welcome":{"timestamp":1554635548}}},
    # "version":15,"timestamp":1554635569,"clientToken":"4c826256-a9ee-4270-ada8-b9104c8ea7fb"}
    def __get_callback(self, payload, responseStatus, token):
        logger.debug("Get Callback status is {} payload is {}".format(
            responseStatus, payload))
        current = json.loads(payload)
        # Process the desired state first to see if we can set the LEDs to the correct state
        for key in current["state"]["desired"]:
            logger.debug("Desired state item is {}".format(key))
            # Check if led or not
            if key == 'lights':
                self.__lights.toogle(current["state"]["desired"][key])
            if key == 'polling':
                self.__config["sensor"]["polling"] = current["state"]["desired"][key]
                self.update("polling", self.__config["sensor"]["polling"])

    def start(self):
        self.__shadow.shadowRegisterDeltaCallback(self.__delta_callback)
        self.__shadow.shadowGet(self.__get_callback, 30)

    def stop(self):
        self.__shadow.shadowUnregisterDeltaCallback()

    def update(self, event, message):
        logger.debug(
            "Event [{}] was published with [{}] message".format(event, message))
        led = None
        reported = {}
        reported["state"] = {}
        reported["state"]["reported"] = {}

        if event == "sensors":
            reported["state"]["reported"]["sensors"] = {
                    "temperature": message["temperature"],
                    "humidity": message["humidity"],
                    "cpu_temp": message["cpu_temp"]
                }
            
            if message["cpu_temp"] > 40:
                led = {
                    "green": "on"
                }
                if message["cpu_temp"] > 65:
                    led["yellow"] = 'on'
                if message["cpu_temp"] > 80:
                    led["red"] = 'on'
            if led is not None:
                reported["state"]["reported"]["lights"] = led
                reported["state"]["desired"] = {
                    "lights": led
                }

        if event == "polling":
            reported["state"]["reported"]["polling"] = message

        if event == "lights":
            reported["state"]["reported"]["lights"] = message

        reported["state"]["reported"]["updated"] = (str(datetime.now())).split('.')[0]

        j = json.dumps(reported)
        logger.debug("Publishing to Shadow [{}]".format(j))
        self.__shadow.shadowUpdate(j, self.__updated_callback, 30)
        if led is not None:
            self.__lights.toogle(led)
Ejemplo n.º 4
0
def startup(argv):
    try:
        opts, _ = getopt.getopt(argv, "hc:s:", ["config=", "sensors="])
    except getopt.GetoptError:
        print("error: runner.py -c <config_file>")
        sys.exit(2)

    if len(opts) == 0:
        print("missing configuration file:  runner.py -c <config_file>")
        sys.exit(2)

    config_file = ""
    publish_temp = True
    for opt, arg in opts:
        if opt == '-h':
            print("runner.py -c <config_file>")
            sys.exit()
        if opt in ('-c', '--config'):
            config_file = arg
        if opt in ('-s', '--sensors'):
            publish_temp = True if arg.lower() in ('on', 'yes') else False

    config_reader = Reader(config_file)
    config = config_reader.read()

    numeric_level = getattr(logging, config["logging"]["level"].upper(), None)
    logging.basicConfig(
        level=numeric_level,
        format="%(asctime)s - %(name)s - %(levelname)s - [%(message)s]")
    logger = logging.getLogger("Demo Telemetry")
    logFormatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s")

    fileHandler = logging.FileHandler(config["logging"]["location"])
    fileHandler.setFormatter(logFormatter)
    fileHandler.setLevel(logging.ERROR)

    logger.info("Starting Demo")
    logger.info("Logging Level is set to {}".format(
        config["logging"]["level"]))
    logger.info(
        "Publishing Sensors is {}".format("ON" if publish_temp else "OFF"))

    shadow = Service(config)
    lights = Lights(config)
    lights.register(shadow)
    lights.subscribe()

    sensor = Sensor(config)

    if publish_temp:
        sensor.register(shadow)
        sensor.start()
    shadow.start()
    logger.info("To Exit press <enter>")
    input()
    if publish_temp:
        sensor.stop()
    lights.unsubscribe()
    shadow.stop()
    logger.info("Completed the demo!")
Ejemplo n.º 5
0
 def test_publish(self):
     lights = Lights(self.config)
     lights.register(Subscriber(self))
     leds = {
         "green": "on"
     }
     lights.toogle(leds)
     time.sleep(1)
     self.assertEqual(lights.get_dispatch_count(), 1)
     leds = {
         "green": "on"
     }
     lights.toogle(leds)
     time.sleep(1)
     self.assertEqual(lights.get_dispatch_count(), 2)
     leds = {
         "green": "on",
         "yellow": "blink"
     }
     lights.toogle(leds)
     time.sleep(1)
     self.assertEqual(lights.get_dispatch_count(), 3)
     leds = {
         "green": "off",
         "yellow": "off"
     }
     lights.toogle(leds)
     self.assertEqual(lights.get_dispatch_count(), 4)
Ejemplo n.º 6
0
 def test_subscribe(self):
     lights = Lights(self.config)
     lights.subscribe()
     state = lights.get_state()
     lights.unsubscribe()
     self.assertEqual(len(state.keys()), 3)
Ejemplo n.º 7
0
 def test_get_state(self):
     lights = Lights(self.config)
     state = lights.get_state()
     self.assertEqual(len(state.keys()), 3)