Exemple #1
0
async def test_request_event():
    loop = asyncio.get_event_loop()
    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')

    server = OpenADRServer(vtn_id='myvtn',
                           requested_poll_freq=datetime.timedelta(seconds=1))
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)

    event_id = server.add_event(
        ven_id='ven123',
        signal_name='simple',
        signal_type='level',
        intervals=[{
            'dtstart':
            datetime.datetime.now(datetime.timezone.utc) +
            datetime.timedelta(seconds=4),
            'duration':
            datetime.timedelta(seconds=2),
            'signal_payload':
            1
        }],
        ramp_up_period=datetime.timedelta(seconds=2),
        callback=partial(event_callback))

    assert server.events['ven123'][0].event_descriptor.event_status == 'far'
    await server.run_async()
    await client.create_party_registration()
    message_type, message_payload = await client.request_event()
    assert message_type == 'oadrDistributeEvent'
    message_type, message_payload = await client.request_event()
    assert message_type == 'oadrDistributeEvent'
    await client.stop()
    await server.stop()
Exemple #2
0
async def test_ssl_certificates():
    loop = asyncio.get_event_loop()
    registration_future = loop.create_future()
    server = OpenADRServer(vtn_id='myvtn',
                           http_cert=VTN_CERT,
                           http_key=VTN_KEY,
                           http_ca_file=CA_CERT,
                           fingerprint_lookup=lookup_fingerprint)
    server.add_handler(
        'on_create_party_registration',
        partial(on_create_party_registration, future=registration_future))
    await server.run_async()
    await asyncio.sleep(1)
    # Run the client
    client = OpenADRClient(
        ven_name='myven',
        vtn_url='https://localhost:8080/OpenADR2/Simple/2.0b',
        cert=VEN_CERT,
        key=VEN_KEY,
        ca_file=CA_CERT,
        vtn_fingerprint=vtn_fingerprint)
    await client.run()

    # Wait for the registration to be triggered
    await registration_future

    await client.stop()
    await server.stop()
    await asyncio.sleep(0)
async def start_server():
    server = OpenADRServer(vtn_id=VTN_ID, http_port=SERVER_PORT)
    server.add_handler('on_create_party_registration',
                       _on_create_party_registration)
    await server.run_async()
    yield
    await server.stop()
Exemple #4
0
async def test_client_event_cleanup():
    now = datetime.datetime.now(datetime.timezone.utc)
    server = OpenADRServer(vtn_id='myvtn')
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)

    loop = asyncio.get_event_loop()
    event_1_callback_future = loop.create_future()
    event_2_callback_future = loop.create_future()
    server.add_event(ven_id='ven123',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[
                         objects.Interval(
                             dtstart=now,
                             duration=datetime.timedelta(seconds=1),
                             signal_payload=1)
                     ],
                     callback=event_1_callback_future)
    await server.run()

    client = OpenADRClient(
        ven_name='ven123',
        vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    client.add_handler('on_event', on_event_opt_in)
    await client.run()
    await asyncio.sleep(0.5)
    assert len(client.received_events) == 1

    await asyncio.sleep(0.5)
    await client._event_cleanup()
    assert len(client.received_events) == 0

    await server.stop()
    await client.stop()
async def test_ssl_certificates_wrong_fingerprint(caplog):
    loop = asyncio.get_event_loop()
    registration_future = loop.create_future()
    server = OpenADRServer(vtn_id='myvtn',
                           http_cert=VTN_CERT,
                           http_key=VTN_KEY,
                           http_ca_file=CA_CERT,
                           cert=VTN_CERT,
                           key=VTN_KEY,
                           fingerprint_lookup=lookup_fingerprint)
    server.add_handler('on_create_party_registration', partial(on_create_party_registration,
                                                               future=registration_future))
    await server.run_async()
    #await asyncio.sleep(1)
    # Run the client
    client = OpenADRClient(ven_name='myven',
                           vtn_url='https://localhost:8080/OpenADR2/Simple/2.0b',
                           cert=VEN_CERT,
                           key=VEN_KEY,
                           ca_file=CA_CERT,
                           vtn_fingerprint='00:11:22:33:44:55:66:77:88:99')
    await client.run()

    # Wait for the registration to be triggered
    result = await asyncio.wait_for(registration_future, 1.0)

    assert client.registration_id is None
    assert ("The certificate fingerprint was incorrect. Expected: 00:11:22:33:44:55:66:77:88:99; "
            "Received: 39:0F:7F:45:84:D6:24:49:FE:B7. Ignoring message.") in [rec.message for rec in caplog.records]

    await client.stop()
    await server.stop()
Exemple #6
0
async def test_server_warning_conflicting_poll_methods(caplog):
    caplog.set_level(logging.WARNING)
    enable_default_logging()
    logger = logging.getLogger('openleadr')
    logger.setLevel(logging.DEBUG)
    server = OpenADRServer(vtn_id='myvtn',
                           requested_poll_freq=timedelta(seconds=1))
    server.add_handler('on_poll', print)
    print("Running server")
    await server.run_async()
    await asyncio.sleep(0.1)
    server.add_event(ven_id='venid',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{
                         'dtstart': datetime.now(),
                         'duration': timedelta(seconds=10),
                         'signal_payload': 1.1
                     }],
                     target={'ven_id': 'venid'},
                     callback=print)
    assert (
        "You cannot use the add_event method after you assign your own on_poll "
        "handler. If you use your own on_poll handler, you are responsible for "
        "delivering events from that handler. If you want to use OpenLEADRs "
        "message queuing system, you should not assign an on_poll handler. "
        "Your Event will NOT be added.") in [
            record.msg for record in caplog.records
        ]
    await server.stop()
    await asyncio.sleep(0)
Exemple #7
0
async def test_cancel_event():
    async def opt_in_to_event(event, future=None):
        if future:
            future.set_result(True)
        return 'optIn'

    async def on_update_event(event, future=None):
        if future:
            future.set_result(event)
        return 'optIn'

    now = datetime.datetime.now(datetime.timezone.utc)
    server = OpenADRServer(vtn_id='myvtn',
                           requested_poll_freq=datetime.timedelta(seconds=1))
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)

    loop = asyncio.get_event_loop()
    event_1_callback_future = loop.create_future()
    event_id = server.add_event(
        ven_id='ven123',
        signal_name='simple',
        signal_type='level',
        intervals=[
            objects.Interval(dtstart=now,
                             duration=datetime.timedelta(seconds=60),
                             signal_payload=1)
        ],
        callback=event_1_callback_future,
        response_required='always')
    await server.run()

    client = OpenADRClient(
        ven_name='ven123',
        vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    client.add_handler('on_event', opt_in_to_event)
    cancel_future = loop.create_future()
    client.add_handler('on_update_event',
                       partial(on_update_event, future=cancel_future))
    await client.run()
    await event_1_callback_future
    server.cancel_event('ven123', event_id)

    result = await cancel_future
    assert utils.getmember(result,
                           'event_descriptor.event_status') == 'cancelled'

    response_type, response_payload = await client.request_event()
    assert response_type == 'oadrResponse'

    await client._event_cleanup()

    assert len(client.responded_events) == 0
    assert len(client.received_events) == 0

    await server.stop()
    await client.stop()
Exemple #8
0
async def test_incremental_reports():
    loop = asyncio.get_event_loop()
    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    collect_futures = [loop.create_future() for i in range(2)]
    client.add_report(callback=partial(collect_data_multi,
                                       futures=collect_futures),
                      report_specifier_id='myhistory',
                      measurement='voltage',
                      resource_id='mydevice',
                      sampling_rate=timedelta(seconds=2))

    server = OpenADRServer(vtn_id='myvtn')

    register_report_future = loop.create_future()
    update_report_future = loop.create_future()
    server.add_handler(
        'on_register_report',
        partial(on_register_report,
                bundling=2,
                futures=[register_report_future],
                receive_futures=[update_report_future]))

    party_future = loop.create_future()
    server.add_handler(
        'on_create_party_registration',
        partial(on_create_party_registration, future=party_future))

    loop.create_task(server.run_async())
    await asyncio.sleep(1)
    await client.run()
    print("Awaiting party future")
    await party_future

    print("Awaiting register report future")
    await register_report_future

    print("Awaiting first data collection future... ", end="")
    await collect_futures[0]
    print("check")

    await asyncio.sleep(1)
    print("Checking that the report was not yet sent... ", end="")
    assert update_report_future.done() is False
    print("check")
    print("Awaiting data collection second future... ", end="")
    await collect_futures[1]
    print("check")

    print("Awaiting report update future")
    result = await update_report_future
    assert len(result) == 2

    await server.stop()
    await client.stop()
    await asyncio.sleep(0)
def test_server_add_unknown_handler(caplog):
    server = OpenADRServer(vtn_id='myvtn')
    with pytest.raises(NameError) as err:
        server.add_handler('unknown_name', print)
    assert str(err.value) == (
        "Unknown handler 'unknown_name'. Correct handler names are: "
        "'on_created_event', 'on_request_event', 'on_register_report', "
        "'on_create_report', 'on_created_report', 'on_request_report', "
        "'on_update_report', 'on_poll', 'on_query_registration', "
        "'on_create_party_registration', 'on_cancel_party_registration'.")
Exemple #10
0
async def test_report_registration_with_status_report():
    """
    Test the registration of two reports with two r_ids each.
    """
    # Create a server
    logger = logging.getLogger('openleadr')
    logger.setLevel(logging.DEBUG)
    server = OpenADRServer(vtn_id='testvtn')
    server.add_handler('on_register_report', on_register_report)
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)

    # Create a client
    client = OpenADRClient(
        ven_name='myven',
        vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b',
    )

    # Add 4 reports
    client.add_report(callback=collect_data,
                      report_specifier_id='CurrentReport',
                      resource_id='Device001',
                      measurement='current',
                      unit='A')
    client.add_report(callback=collect_data,
                      report_specifier_id='CurrentReport',
                      resource_id='Device002',
                      measurement='current',
                      unit='A')
    client.add_report(callback=collect_data,
                      report_specifier_id='VoltageReport',
                      resource_id='Device001',
                      measurement='voltage',
                      unit='V')
    client.add_report(callback=collect_data,
                      report_specifier_id='VoltageReport',
                      resource_id='Device002',
                      measurement='voltage',
                      unit='V')
    client.add_report(callback=collect_status,
                      report_name='TELEMETRY_STATUS',
                      report_specifier_id='StatusReport',
                      resource_id='Device001')

    asyncio.create_task(server.run_async())
    await asyncio.sleep(1)
    # Register the client
    await client.create_party_registration()

    # Register the reports
    await client.register_reports(client.reports)
    assert len(client.report_requests) == 3
    assert len(server.services['report_service'].report_callbacks) == 5
    await client.stop()
    await server.stop()
Exemple #11
0
async def test_update_report_data_collection_mode_full():
    loop = asyncio.get_event_loop()

    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    data_collection_future = loop.create_future()
    client.add_report(callback=partial(collect_data_history,
                                       futures=[data_collection_future]),
                      resource_id='Device001',
                      measurement='power_real',
                      data_collection_mode='full',
                      sampling_rate=timedelta(seconds=1),
                      unit='W')

    report_register_future = loop.create_future()
    report_received_future = loop.create_future()
    party_registration_future = loop.create_future()
    server = OpenADRServer(vtn_id='myvtn')
    server.add_handler(
        'on_create_party_registration',
        partial(on_create_party_registration,
                future=party_registration_future))
    server.add_handler(
        'on_register_report',
        partial(on_register_report,
                bundling=2,
                futures=[report_register_future],
                receive_futures=[report_received_future]))

    await server.run_async()
    await asyncio.sleep(0.1)

    print(f"The time is now {datetime.now()}")
    t = time.time()
    wait_for = int(t / 2) * 2 + 2 - t
    await asyncio.sleep(wait_for)
    print(f"The time is now {datetime.now()}, running client")
    await client.run()

    await party_registration_future
    await report_register_future
    await asyncio.sleep(1)
    print(
        f"The time is now {datetime.now()}, checking if report was triggered")
    assert data_collection_future.done() is False

    print("Waiting for the data collection to occur")
    await data_collection_future

    print("Waiting for the report to be received")
    await report_received_future

    print("Done")
    await server.stop()
    await client.stop()
Exemple #12
0
async def test_raw_event():
    now = datetime.datetime.now(datetime.timezone.utc)
    server = OpenADRServer(vtn_id='myvtn')
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)
    event = objects.Event(
        event_descriptor=objects.EventDescriptor(
            event_id='event001',
            modification_number=0,
            event_status='far',
            market_context='http://marketcontext01'),
        event_signals=[
            objects.EventSignal(
                signal_id='signal001',
                signal_type='level',
                signal_name='simple',
                intervals=[
                    objects.Interval(dtstart=now,
                                     duration=datetime.timedelta(minutes=10),
                                     signal_payload=1)
                ]),
            objects.EventSignal(
                signal_id='signal002',
                signal_type='price',
                signal_name='ELECTRICITY_PRICE',
                intervals=[
                    objects.Interval(dtstart=now,
                                     duration=datetime.timedelta(minutes=10),
                                     signal_payload=1)
                ])
        ],
        targets=[objects.Target(ven_id='ven123')])
    loop = asyncio.get_event_loop()
    event_callback_future = loop.create_future()
    server.add_raw_event(ven_id='ven123',
                         event=event,
                         callback=partial(event_callback,
                                          future=event_callback_future))

    on_event_future = loop.create_future()
    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    client.add_handler('on_event',
                       partial(on_event_opt_in, future=on_event_future))

    await server.run_async()
    await client.run()
    event = await on_event_future
    assert len(event['event_signals']) == 2

    result = await event_callback_future
    assert result == 'optIn'

    await client.stop()
    await server.stop()
async def start_server():
    server = OpenADRServer(vtn_id=VTN_ID)
    server.add_handler('on_create_party_registration',
                       _on_create_party_registration)

    runner = web.AppRunner(server.app)
    await runner.setup()
    site = web.TCPSite(runner, 'localhost', SERVER_PORT)
    await site.start()
    yield
    await runner.cleanup()
async def start_server_with_signatures():
    server = OpenADRServer(vtn_id=VTN_ID,
                           cert=CERTFILE,
                           key=KEYFILE,
                           fingerprint_lookup=fingerprint_lookup,
                           http_port=SERVER_PORT)
    server.add_handler('on_create_party_registration',
                       _on_create_party_registration)
    await server.run_async()
    yield
    await server.stop()
async def test_throw_protocol_error(caplog):
    server = OpenADRServer(vtn_id=VTN_ID, http_port=SERVER_PORT)
    server.add_handler('on_create_party_registration', protocol_error_handler)
    await server.run_async()
    client = OpenADRClient(
        ven_name='myven',
        vtn_url=f'http://localhost:{SERVER_PORT}/OpenADR2/Simple/2.0b')
    await client.run()
    #await asyncio.sleep(0.5)
    await client.stop()
    await server.stop()
    assert 'We got a non-OK OpenADR response from the server: 450: OUT OF SEQUENCE' in caplog.messages
Exemple #16
0
async def start_server_with_signatures():
    server = OpenADRServer(vtn_id=VTN_ID,
                           cert=CERTFILE,
                           key=KEYFILE,
                           passphrase='openadr')
    server.add_handler('on_create_party_registration',
                       _on_create_party_registration)

    runner = web.AppRunner(server.app)
    await runner.setup()
    site = web.TCPSite(runner, 'localhost', SERVER_PORT)
    await site.start()
    yield
    await runner.cleanup()
Exemple #17
0
async def test_conformance_021():
    """
    If venID, vtnID, or eventID value is included in the payload, the receiving
    entity MUST validate that the ID value is as expected and generate an error
    if an unexpected value is received.
    Exception: A VEN MUST NOT generate an error upon receipt of a canceled
    event whose eventID is not previously known.
    """
    server = OpenADRServer(vtn_id='TestVTN', http_port=8001)
    server.add_handler('on_create_party_registration', on_create_party_registration)
    server.add_handler('on_poll', _on_poll)
    await server.run_async()

    client = OpenADRClient(ven_name="TestVEN",
                           vtn_url="http://localhost:8001/OpenADR2/Simple/2.0b")
    await client.create_party_registration()
    event = {'event_descriptor':
                {'event_id': generate_id(),
                 'modification_number': 0,
                 'modification_date': datetime.now(),
                 'priority': 0,
                 'market_context': 'MarketContext001',
                 'created_date_time': datetime.now(),
                 'event_status': enums.EVENT_STATUS.FAR,
                 'test_event': False,
                 'vtn_comment': 'No Comment'},
            'active_period':
                {'dtstart': datetime.now() + timedelta(minutes=30),
                 'duration': timedelta(minutes=30)},
            'event_signals':
                [{'intervals': [{'duration': timedelta(minutes=10),
                                 'signal_payload': 1},
                                {'duration': timedelta(minutes=10),
                                 'signal_payload': 2},
                                {'duration': timedelta(minutes=10),
                                 'signal_payload': 3}],
                  'signal_name': enums.SIGNAL_NAME.SIMPLE,
                  'signal_type': enums.SIGNAL_TYPE.DELTA,
                  'signal_id': generate_id(),
                  'current_value': 123
                }],
            'targets': [{'ven_id': '123'}]
        }
    add_event(ven_id=client.ven_id,
              event_id = event['event_descriptor']['event_id'],
              event=event)
    message_type, message_payload = await client.poll()
    assert message_type == 'oadrDistributeEvent'
    await client.stop()
    await server.stop()
async def test_server_handler_exception(caplog):
    server = OpenADRServer(vtn_id=VTN_ID, http_port=SERVER_PORT)
    server.add_handler('on_create_party_registration', problematic_handler)
    await server.run_async()
    client = OpenADRClient(
        ven_name='myven',
        vtn_url=f'http://localhost:{SERVER_PORT}/OpenADR2/Simple/2.0b')
    await client.run()
    #await asyncio.sleep(0.5)
    await client.stop()
    await server.stop()
    for message in caplog.messages:
        if message.startswith('Non-OK status 500 when performing a request'):
            break
    else:
        assert False
Exemple #19
0
async def test_message(message_type, message_payload):
    server = OpenADRServer(vtn_id='myvtn')
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)
    server.add_handler(
        'on_poll',
        partial(poll_responder,
                message_type=message_type,
                message_payload=message_payload))
    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    await server.run_async()
    await client.create_party_registration()
    response_type, response_payload = await client.poll()
    await server.stop()
    assert response_type == message_type
Exemple #20
0
async def test_register_historic_report():
    client = OpenADRClient(ven_name='myven',
                           vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    client.add_report(report_name='HISTORY_USAGE',
                      callback=get_historic_data,
                      measurement='voltage',
                      resource_id='Device001',
                      sampling_rate=timedelta(seconds=1))
    server = OpenADRServer(vtn_id='myvtn')
    server.add_handler('on_create_party_registration', on_create_party_registration)
    # server.add_handler('on_register_report', on_register_report_historic)
    await server.run()
    await client.run()
    assert len(server.registered_reports) == 1
    await client.stop()
    await server.stop()
Exemple #21
0
async def test_client_exception_event_handler(caplog):
    caplog.set_level(logging.WARNING)
    enable_default_logging()
    logger = logging.getLogger('openleadr')
    logger.setLevel(logging.DEBUG)
    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    client.add_handler('on_event', broken_on_event)
    server = OpenADRServer(vtn_id='myvtn',
                           requested_poll_freq=timedelta(seconds=1))
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)
    print("Running server")
    await server.run_async()
    await asyncio.sleep(0.1)
    print("Running client")
    await client.run()

    event_confirm_future = asyncio.get_event_loop().create_future()
    print("Adding event")
    server.add_event(ven_id='venid',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{
                         'dtstart': datetime.now(),
                         'duration': timedelta(seconds=10),
                         'signal_payload': 1.1
                     }],
                     target={'ven_id': 'venid'},
                     callback=partial(on_event_accepted,
                                      future=event_confirm_future))

    print("Waiting for a response to the event")
    result = await event_confirm_future
    assert result == 'optOut'

    err = KeyError("BOOM")
    assert (
        "Your on_event handler encountered an error. Will Opt Out of the event. "
        f"The error was {err.__class__.__name__}: {str(err)}") in [
            rec.message for rec in caplog.records
        ]
    await client.stop()
    await server.stop()
    await asyncio.sleep(0)
async def test_client_good_event_handler(caplog):
    caplog.set_level(logging.WARNING)
    logger = logging.getLogger('openleadr')
    logger.setLevel(logging.DEBUG)
    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    client.add_handler('on_event', good_on_event)
    server = OpenADRServer(vtn_id='myvtn',
                           requested_poll_freq=timedelta(seconds=1))
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)
    caplog.clear()
    print("Running server")
    await server.run_async()
    # await asyncio.sleep(0.1)
    print("Running client")
    await client.run()

    event_confirm_future = asyncio.get_event_loop().create_future()
    print("Adding event")
    server.add_event(ven_id='venid',
                     event_id='test_client_good_event_handler',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{
                         'dtstart': datetime.now(timezone.utc),
                         'duration': timedelta(seconds=1),
                         'signal_payload': 1.1
                     }],
                     target={'ven_id': 'venid'},
                     callback=partial(on_event_accepted,
                                      future=event_confirm_future))

    print("Waiting for a response to the event")
    result = await event_confirm_future
    assert result == 'optIn'
    print("-" * 80)
    print("THE CAPLOG RECORDS ARE:")
    print(caplog.records)
    print("-" * 80)
    assert len(caplog.records) == 0
    await client.stop()
    await server.stop()
    await asyncio.gather(*[t for t in asyncio.all_tasks()][1:])
async def test_client_warning_no_update_event_handler(caplog):
    caplog.set_level(logging.WARNING)
    logger = logging.getLogger('openleadr')
    logger.setLevel(logging.DEBUG)
    server = OpenADRServer(vtn_id='myvtn',
                           requested_poll_freq=timedelta(seconds=1))
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)
    event_accepted_future = asyncio.get_event_loop().create_future()
    server.add_event(ven_id='venid',
                     event_id='test_client_warning_no_update_event_handler',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{
                         'dtstart': datetime.now(timezone.utc),
                         'duration': timedelta(seconds=1),
                         'signal_payload': 1.1
                     }],
                     target={'ven_id': 'venid'},
                     callback=event_accepted_future)
    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    client.add_handler('on_event', good_on_event)
    print("Starting server")
    await server.run()
    await client.run()
    print("Waiting for first event to be accepted...")
    await event_accepted_future

    # Manually update the event
    server.events['venid'][0].event_descriptor.modification_number = 1
    server.events_updated['venid'] = True

    await asyncio.sleep(1)
    assert (
        "An Event was updated, but you don't have an on_updated_event handler configured. "
        "You should implement your own on_update_event handler. This handler receives "
        "an Event dict and should return either 'optIn' or 'optOut' based on your "
        "choice. Will re-use the previous opt status for this event_id for now"
    ) in [record.msg for record in caplog.records]
    await client.stop()
    await server.stop()
    await asyncio.gather(*[t for t in asyncio.all_tasks()][1:])
async def test_client_faulty_event_handler(caplog):
    caplog.set_level(logging.WARNING)
    logger = logging.getLogger('openleadr')
    logger.setLevel(logging.DEBUG)
    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    client.add_handler('on_event', faulty_on_event)
    server = OpenADRServer(vtn_id='myvtn',
                           requested_poll_freq=timedelta(seconds=1))
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)
    print("Running server")
    await server.run_async()
    # await asyncio.sleep(0.1)
    print("Running client")
    await client.run()

    event_confirm_future = asyncio.get_event_loop().create_future()
    print("Adding event")
    server.add_event(ven_id='venid',
                     event_id='test_client_faulty_event_handler',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{
                         'dtstart': datetime.now(timezone.utc),
                         'duration': timedelta(seconds=1),
                         'signal_payload': 1.1
                     }],
                     target={'ven_id': 'venid'},
                     callback=partial(on_event_accepted,
                                      future=event_confirm_future))

    print("Waiting for a response to the event")
    result = await event_confirm_future
    assert result == 'optOut'
    assert (
        "Your on_event or on_update_event handler must return 'optIn' or 'optOut'; "
        f"you supplied {None}. Please fix your on_event handler.") in [
            rec.message for rec in caplog.records
        ]
    await client.stop()
    await server.stop()
    await asyncio.gather(*[t for t in asyncio.all_tasks()][1:])
Exemple #25
0
async def test_client_no_event_handler(caplog):
    caplog.set_level(logging.WARNING)
    enable_default_logging()
    logger = logging.getLogger('openleadr')
    logger.setLevel(logging.DEBUG)
    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    server = OpenADRServer(vtn_id='myvtn',
                           requested_poll_freq=timedelta(seconds=1))
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)
    print("Running server")
    await server.run_async()
    await asyncio.sleep(0.1)
    print("Running client")
    await client.run()

    event_confirm_future = asyncio.get_event_loop().create_future()
    print("Adding event")
    server.add_event(ven_id='venid',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{
                         'dtstart': datetime.now(),
                         'duration': timedelta(seconds=10),
                         'signal_payload': 1.1
                     }],
                     target={'ven_id': 'venid'},
                     callback=partial(on_event_accepted,
                                      future=event_confirm_future))

    print("Waiting for a response to the event")
    result = await event_confirm_future
    assert result == 'optOut'
    assert (
        "You should implement your own on_event handler. This handler receives "
        "an Event dict and should return either 'optIn' or 'optOut' based on your "
        "choice. Will opt out of the event for now.") in [
            rec.message for rec in caplog.records
        ]
    await client.stop()
    await server.stop()
    await asyncio.sleep(0)
Exemple #26
0
async def test_internal_message_queue():
    loop = asyncio.get_event_loop()
    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    client.add_handler('on_event', on_event)
    server = OpenADRServer(vtn_id='myvtn',
                           requested_poll_freq=datetime.timedelta(seconds=1))
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)
    event_callback_future = loop.create_future()
    server.add_event(ven_id='ven123',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[{
                         'dtstart':
                         datetime.datetime.now(datetime.timezone.utc),
                         'duration':
                         datetime.timedelta(seconds=3),
                         'signal_payload':
                         1
                     }],
                     callback=partial(event_callback,
                                      future=event_callback_future))

    await server.run_async()
    #await asyncio.sleep(1)
    await client.run()
    #await asyncio.sleep(1)
    status = await event_callback_future
    assert status == 'optIn'

    message_type, message_payload = await asyncio.wait_for(client.poll(), 0.5)
    assert message_type == 'oadrResponse'

    message_type, message_payload = await asyncio.wait_for(client.poll(), 0.5)
    assert message_type == 'oadrResponse'

    #await asyncio.sleep(1)  # Wait for the event to be completed
    await client.stop()
    await server.stop()
Exemple #27
0
            'response_description': 'OK',
            'request_id': payload['request_id']
        },
        'ven_id':
        ven_id,
        'registration_id':
        registration_id,
        'profiles': [{
            'profile_name': '2.0b',
            'transports': {
                'transport_name': 'simpleHttp'
            }
        }],
        'requested_oadr_poll_freq':
        timedelta(seconds=10)
    }
    return 'oadrCreatedPartyRegistration', payload


server = OpenADRServer(vtn_id=VTN_ID, http_port=SERVER_PORT)
server.add_handler('on_create_party_registration',
                   _on_create_party_registration)
server.add_handler('on_poll', _on_poll)


@pytest.fixture
async def start_server():
    await server.run_async()
    yield
    await server.stop()
Exemple #28
0
async def test_multiple_events_in_queue():
    now = datetime.datetime.now(datetime.timezone.utc)
    server = OpenADRServer(vtn_id='myvtn')
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)

    loop = asyncio.get_event_loop()
    event_1_callback_future = loop.create_future()
    event_2_callback_future = loop.create_future()
    server.add_event(ven_id='ven123',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[
                         objects.Interval(
                             dtstart=now,
                             duration=datetime.timedelta(seconds=1),
                             signal_payload=1)
                     ],
                     callback=event_1_callback_future)

    await server.run()

    on_event_future = loop.create_future()
    client = OpenADRClient(
        ven_name='ven123',
        vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    await client.create_party_registration()
    response_type, response_payload = await client.request_event()
    assert response_type == 'oadrDistributeEvent'
    events = response_payload['events']
    assert len(events) == 1
    event_id = events[0]['event_descriptor']['event_id']
    request_id = response_payload['request_id']
    await client.created_event(request_id=request_id,
                               event_id=event_id,
                               opt_type='optIn',
                               modification_number=0)

    server.add_event(ven_id='ven123',
                     signal_name='simple',
                     signal_type='level',
                     intervals=[
                         objects.Interval(
                             dtstart=now + datetime.timedelta(seconds=1),
                             duration=datetime.timedelta(seconds=1),
                             signal_payload=1)
                     ],
                     callback=event_2_callback_future)
    response_type, response_payload = await client.request_event()
    assert response_type == 'oadrDistributeEvent'
    events = response_payload['events']

    # Assert that we still have two events in the response
    assert len(events) == 2

    # Wait one second and retrieve the events again
    await asyncio.sleep(1)
    response_type, response_payload = await client.request_event()
    assert response_type == 'oadrDistributeEvent'
    events = response_payload['events']
    assert len(events) == 2
    assert events[1]['event_descriptor']['event_status'] == 'completed'

    response_type, response_payload = await client.request_event()
    assert response_type == 'oadrDistributeEvent'
    events = response_payload['events']
    assert len(events) == 1
    await asyncio.sleep(1)

    response_type, response_payload = await client.request_event()
    assert response_type == 'oadrDistributeEvent'

    response_type, response_payload = await client.request_event()
    assert response_type == 'oadrResponse'

    await server.stop()
Exemple #29
0
async def test_event_external_polling_function():
    async def opt_in_to_event(event, future=None):
        if future:
            future.set_result(True)
        return 'optIn'

    async def on_update_event(event, future=None):
        if future:
            future.set_result(event)
        return 'optIn'

    async def on_poll(ven_id, future=None):
        if future and not future.done():
            future.set_result(True)
            return objects.Event(
                event_descriptor=objects.EventDescriptor(
                    event_id='event001',
                    modification_number=0,
                    event_status='far',
                    market_context='http://marketcontext01'),
                event_signals=[
                    objects.EventSignal(
                        signal_id='signal001',
                        signal_type='level',
                        signal_name='simple',
                        intervals=[
                            objects.Interval(
                                dtstart=now,
                                duration=datetime.timedelta(minutes=10),
                                signal_payload=1)
                        ]),
                    objects.EventSignal(
                        signal_id='signal002',
                        signal_type='price',
                        signal_name='ELECTRICITY_PRICE',
                        intervals=[
                            objects.Interval(
                                dtstart=now,
                                duration=datetime.timedelta(minutes=10),
                                signal_payload=1)
                        ])
                ],
                targets=[objects.Target(ven_id=ven_id)])
        else:
            print("Returning None")
            return None

    loop = asyncio.get_event_loop()
    now = datetime.datetime.now(datetime.timezone.utc)
    server = OpenADRServer(vtn_id='myvtn',
                           requested_poll_freq=datetime.timedelta(seconds=1))
    server.add_handler('on_create_party_registration',
                       on_create_party_registration)
    poll_fut = loop.create_future()
    server.add_handler('on_poll', partial(on_poll, future=poll_fut))
    await server.run()

    client = OpenADRClient(
        ven_name='ven123',
        vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')
    fut = loop.create_future()
    client.add_handler('on_event', partial(opt_in_to_event, future=fut))
    await client.run()
    await fut

    assert len(client.responded_events) == 1
    assert len(client.received_events) == 1

    await server.stop()
    await client.stop()
Exemple #30
0
async def test_update_reports():
    """
    Tests the timely delivery of requested reports
    """
    # Create a server
    logger = logging.getLogger('openleadr')
    logger.setLevel(logging.DEBUG)
    loop = asyncio.get_event_loop()
    server = OpenADRServer(vtn_id='testvtn')

    register_report_future_1 = loop.create_future()
    register_report_future_2 = loop.create_future()
    register_report_futures = [
        register_report_future_1, register_report_future_2
    ]

    receive_report_future_1 = loop.create_future()
    receive_report_future_2 = loop.create_future()
    receive_report_future_3 = loop.create_future()
    receive_report_future_4 = loop.create_future()
    receive_report_futures = [
        receive_report_future_1, receive_report_future_2,
        receive_report_future_3, receive_report_future_4
    ]
    server.add_handler(
        'on_register_report',
        partial(on_register_report,
                futures=register_report_futures,
                receive_futures=receive_report_futures))

    party_future = loop.create_future()
    server.add_handler(
        'on_create_party_registration',
        partial(on_create_party_registration, future=party_future))

    # Create a client
    client = OpenADRClient(
        ven_name='myven', vtn_url='http://localhost:8080/OpenADR2/Simple/2.0b')

    # Add 4 reports
    future_1 = loop.create_future()
    client.add_report(callback=partial(collect_data, future=future_1),
                      report_specifier_id='PowerReport',
                      resource_id='Device001',
                      measurement='power_real',
                      sampling_rate=timedelta(seconds=2),
                      unit='W')
    future_2 = loop.create_future()
    client.add_report(callback=partial(collect_data, future=future_2),
                      report_specifier_id='PowerReport',
                      resource_id='Device002',
                      measurement='power_real',
                      sampling_rate=timedelta(seconds=2),
                      unit='W')
    future_3 = loop.create_future()
    client.add_report(callback=partial(collect_data, future=future_3),
                      report_specifier_id='VoltageReport',
                      resource_id='Device001',
                      measurement='voltage',
                      sampling_rate=timedelta(seconds=2),
                      unit='V')
    future_4 = loop.create_future()
    client.add_report(callback=partial(collect_data, future=future_4),
                      report_specifier_id='VoltageReport',
                      resource_id='Device002',
                      measurement='voltage',
                      sampling_rate=timedelta(seconds=2),
                      unit='V')

    assert len(client.reports) == 2
    asyncio.create_task(server.run_async())
    await asyncio.sleep(1)

    # Run the client asynchronously
    print("Running the client")
    asyncio.create_task(client.run())

    print("Awaiting party future")
    await party_future

    print("Awaiting report futures")
    await asyncio.gather(register_report_future_1, register_report_future_2)
    await asyncio.sleep(0.1)
    assert len(server.services['report_service'].report_callbacks) == 4

    print("Awaiting data collection futures")
    await future_1
    await future_2
    await future_3
    await future_4

    print("Awaiting update report futures")
    await asyncio.gather(receive_report_future_1, receive_report_future_2,
                         receive_report_future_3, receive_report_future_4)
    print("Done gathering")

    assert receive_report_future_1.result()[0][1] == future_1.result()
    assert receive_report_future_2.result()[0][1] == future_2.result()
    assert receive_report_future_3.result()[0][1] == future_3.result()
    assert receive_report_future_4.result()[0][1] == future_4.result()

    await client.stop()
    await server.stop()