Example #1
0
def test_battery_generator_policy():
    import asyncio
    from aizero.device_resource import DeviceManager, DeviceResource
    from aizero.device_resource import TimeOfUsePolicy
    from aizero.time_of_use_resource import Modes
    from aizero.resource import Resource

    Resource.clearResources()

    fake_time_of_use = Resource("TimeOfUse", variables=["mode"])
    fake_time_of_use.set_value("mode", Modes.on_peak)

    fake_power_device = DeviceResource("FakeGeneratorPowerControl")

    fake_capacity = Resource("BatteryCapacity", ["capacity"])

    fake_capacity.set_value("capacity", 100)

    device_manager = DeviceManager(power_source="BatteryGenerator")

    generator = BatteryGenerator("BatteryGenerator",
                                 power_generation=1000,
                                 power_control_device=fake_power_device.name,
                                 battery_capacity_resource=fake_capacity.name)

    generator.set_runtime_policy([TimeOfUsePolicy(Modes.off_peak)])

    # give manager a chance to grab the power source
    asyncio.get_event_loop().run_until_complete(asyncio.sleep(1))

    fake_power_device.stop()
    assert not generator.running()

    fake_time_of_use.set_value("mode", Modes.off_peak)

    device_manager.process_managed_devices()

    assert generator.running()

    fake_time_of_use.set_value("mode", Modes.on_peak)

    device_manager.process_managed_devices()

    assert not generator.running()

    fake_power_device.run()
    assert generator.running()

    fake_power_device.stop()
    assert not generator.running()
Example #2
0
def test_time_of_use_policy():
    Resource.clearResources()

    from aizero.time_of_use_resource import Modes

    dm = DeviceManager(max_power_budget=800, debug=True)

    fake_time_of_use = Resource("TimeOfUse", variables=["mode"])
    fake_time_of_use.set_value("mode", Modes.on_peak)

    device = DeviceResource("fake_device", 100)
    device.set_runtime_policy([TimeOfUsePolicy(Modes.off_peak)])

    device.run()

    assert device.running()

    dm.process_managed_devices()

    assert not device.running()

    fake_time_of_use.set_value("mode", Modes.off_peak)

    dm.process_managed_devices()

    assert device.running()
Example #3
0
def test_occupancy_policy():
    Resource.clearResources()
    device_manager = DeviceManager(max_power_budget=800)

    occupancy_resource = Resource(
        "SomeOccupancyThing", variables=["occupancy"])

    occupancy_resource.setValue("occupancy", True)

    off_policy = OffIfUnoccupied(occupancy_resource.name)

    dev1 = DeviceResource("dev1", power_usage=100,
                          device_manager=device_manager.name,
                          runtime_policy=[off_policy])

    dev1.run()

    device_manager.process_managed_devices()

    assert dev1.running(), "Device should be running"

    occupancy_resource.setValue("occupancy", False)

    assert off_policy.occupancy.value is False

    device_manager.process_managed_devices()

    assert not dev1.running(), "Device should not be running"

    occupancy_resource.setValue("occupancy", True)

    device_manager.process_managed_devices()

    assert not dev1.running(), "Device should not be running"
Example #4
0
def test_subscribe():

    Resource.clearResources()

    received = False

    publisher = Resource("publisher234523453", ["foo"])
    publisher.export_mqtt()

    subscriber = MqttResource(
        "publisher_sub",
        "localhost", ["foo"],
        variable_mqtt_map={"foo": "publisher234523453/foo"})

    received = subscriber.subscribe2("foo")

    loop = asyncio.get_event_loop()

    loop.run_until_complete(publisher.mqtt_wrapper.wait_until_connected())

    publisher.set_value("foo", '12345')

    loop.run_until_complete(asyncio.sleep(1))

    assert received.value == '12345'
Example #5
0
def test_topic_converter():

    # we need to do this because we will be creating the resources
    # again with the same names clear from previous tests...
    Resource.clearResources()

    import time

    broker = "127.0.0.1"

    @mqtt_topic_converter("ResourcePublisher/foo")
    def convert_int(value):
        return int(value)

    publisher = MqttWrapper(Resource("ResourcePublisher", ["foo"]),
                            broker,
                            retain_msgs=False)

    resource = MqttResource("Test2Resource",
                            broker, ["foo"],
                            variable_mqtt_map={"foo": "ResourcePublisher/foo"})

    loop = asyncio.get_event_loop()

    loop.run_until_complete(resource.wait_until_connected())
    loop.run_until_complete(publisher.wait_until_connected())

    publisher.resource.setValue("foo", 1)

    asyncio.get_event_loop().run_until_complete(asyncio.sleep(10))

    assert resource.getValue("foo") == 1
Example #6
0
def test_mqtt_wrapper():

    # we need to do this because we will be creating the resources
    # again with the same names. clear from previous tests...
    Resource.clearResources()

    import time

    broker = "127.0.0.1"

    resource = MqttResource("Test1Resource", broker, ["Test1Resource2/foo"])

    publisher = MqttWrapper(Resource("Test1Resource2", ["foo"]),
                            broker,
                            retain_msgs=False)

    loop = asyncio.get_event_loop()

    loop.run_until_complete(resource.wait_until_connected())
    loop.run_until_complete(publisher.wait_until_connected())

    publisher.resource.setValue("foo", "bar")

    asyncio.get_event_loop().run_until_complete(asyncio.sleep(10))

    assert resource.getValue("Test1Resource2/foo") == "bar"

    publisher.resource.setValue("foo", "bar2")

    asyncio.get_event_loop().run_until_complete(asyncio.sleep(10))

    assert resource.getValue("Test1Resource2/foo") == "bar2"
Example #7
0
def main():

    # setup a fake occupancy sensor. Normally, this would come from an ecobee
    # device or from a camera resource... anything that has an "occupancy"
    # property.

    fake_occupancy = Resource("Office Occupancy Sensor", ["occupancy"])

    # generate lots of fake data:
    for i in range(100):
        occupied = random.choice([True, False])
        fake_occupancy.set_value("occupancy", occupied)

    # We don't have a power source, so we'll just set the max budget manually:
    DeviceManager(max_power_budget=1000)

    # our predictor will use train and run using the "GlobalOccupancy" resource
    occupancy_predictor = OccupancyPredictorResource(
        name="FakeOccupancyPredictor", occupancy_resource=fake_occupancy.name)

    kasa_devices = discover_devices()

    for device in kasa_devices:
        policies = [OffIfUnoccupied(occupancy_predictor.name)]

        device.set_runtime_policy(policies)

    # run the mainloop
    asyncio.get_event_loop().run_forever()
Example #8
0
def test_manager_multiple_power_sources():

    Resource.clearResources()

    ps1 = Resource("PowerSource1", ["available_power"])
    ps2 = Resource("PowerSource2", ["available_power"])

    dm = DeviceManager(power_source=[ps1.name, ps2.name])

    asyncio.get_event_loop().run_until_complete(asyncio.sleep(1))

    ps1.set_value("available_power", 10)
    ps2.set_value("available_power", 5)

    assert dm.available_power == 15

    ps1.set_value("available_power", 0)
    ps2.set_value("available_power", 0)

    assert dm.available_power == 0
Example #9
0
def test_manager_default_power_source():
    Resource.clearResources()

    ps1 = Resource("SolarPower", ["available_power"])
    ps1.set_value("available_power", 0)

    dm = DeviceManager()

    asyncio.get_event_loop().run_until_complete(asyncio.sleep(1))

    assert dm.available_power == 0

    ps1.set_value("available_power", 1000)

    assert dm.available_power == 1000
Example #10
0
def test_use_current_time_resource():
    current_time_resource = Resource("CurrentTimeResource", ["datetime"])

    current_time_resource.setValue("datetime", datetime(2017, 1, 1, 12))

    night_time = NightTime()

    night_time.process()

    assert night_time.is_day()

    current_time_resource.setValue("datetime", datetime(2017, 1, 1, 23))

    night_time.process()

    assert not night_time.is_day()
Example #11
0
def test_delayed_publish():

    publisher = Resource("publisher", ["foo"])
    publisher.export_mqtt()

    subscriber = MqttResource("publisher_sub",
                              "localhost", ["foo"],
                              variable_mqtt_map={"foo": "publisher/foo"})

    publisher.setValue("foo", "bar")

    assert subscriber.getValue("foo") is None

    loop = asyncio.get_event_loop()

    loop.run_until_complete(publisher.mqtt_wrapper.wait_until_connected())

    assert subscriber.getValue("foo") == "bar"
Example #12
0
def publish_time():
    sys_time_resource = Resource("Date", ["datetime", "datetime_utc"])

    while True:
        time_str = subprocess.check_output(["date", "-I", "seconds"],
                                           shell=True)

        time_str = time_str.decode('utf-8').replace("\n", "")

        sys_time_resource.setValue("datetime", time_str)

        time_str = subprocess.check_output(["date", "-I", "seconds", "-u"],
                                           shell=True)

        time_str = time_str.decode('utf-8').replace("\n", "")

        sys_time_resource.setValue("datetime_utc", time_str)

        yield from asyncio.sleep(60)
Example #13
0
def test_battery_generator():
    import asyncio
    from aizero.device_resource import DeviceManager, DeviceResource
    from aizero.resource import Resource

    device_manager = DeviceManager(power_source="BatteryGenerator")

    fake_capacity = Resource("BatteryCapacity", ["capacity"])

    fake_capacity.set_value("capacity", 0)

    fake_battery_control = DeviceResource("FakeControl")

    generator = BatteryGenerator(
        "BatteryGenerator",
        power_generation=1000,
        power_control_device=fake_battery_control.name,
        battery_capacity_resource=fake_capacity.name)

    # give manager a chance to grab the power source
    asyncio.get_event_loop().run_until_complete(asyncio.sleep(1))

    assert not generator.run()

    device_manager.process_managed_devices()

    assert not fake_battery_control.running()

    fake_capacity.set_value("capacity", 50)

    assert generator.run()
    assert fake_battery_control.running()

    assert generator.get_value("available_power") == 1000

    assert generator.stop()
    assert generator.get_value("available_power") == 0
Example #14
0
def test_multi_decorator_topic_converter():
    import time
    import json

    Resource.clearResources()

    broker = "127.0.0.1"

    @mqtt_topic_converter("Test1Resource2/foo")
    @mqtt_topic_converter("Test1Resource3/baz")
    def convert_int(value):
        return int(value)

    @mqtt_topic_converter("Test1Resource4/some_json")
    def convert_json(value):
        return json.loads(value)

    # we need to do this because we will be creating the resources
    # again with the same names clear from previous tests...
    Resource.clearResources()

    publisher = MqttWrapper(Resource("Test1Resource2", ["foo"]),
                            broker,
                            retain_msgs=False)
    publisher2 = MqttWrapper(Resource("Test1Resource3", ["baz"]),
                             broker,
                             retain_msgs=False)
    publisher3 = MqttWrapper(Resource("Test1Resource4", ["some_json"]),
                             broker,
                             retain_msgs=False)

    resource = MqttResource("Test1Resource",
                            broker, ["foo", "baz", "some_json"],
                            variable_mqtt_map={
                                "foo": "Test1Resource2/foo",
                                "baz": "Test1Resource3/baz",
                                "some_json": "Test1Resource4/some_json"
                            })

    loop = asyncio.get_event_loop()

    loop.run_until_complete(publisher.wait_until_connected())
    loop.run_until_complete(publisher2.wait_until_connected())
    loop.run_until_complete(publisher3.wait_until_connected())
    loop.run_until_complete(resource.wait_until_connected())

    publisher.resource.setValue("foo", 1)
    publisher2.resource.setValue("baz", 1)
    publisher3.resource.setValue("some_json", '{"foo" : 1}')

    loop.run_until_complete(asyncio.sleep(5))

    assert resource.getValue("foo") == 1
    assert resource.getValue("baz") == 1
    assert resource.getValue("some_json")["foo"] == 1

    # Test dict object auto-json conversion:
    publisher3.resource.setValue("some_json", {"foo": 2})

    loop.run_until_complete(asyncio.sleep(5))

    assert resource.getValue("some_json")["foo"] == 2