def test_oadr_event(): event = objects.Event( event_descriptor=objects.EventDescriptor( event_id=1, modification_number=0, market_context='MarketContext1', event_status=enums.EVENT_STATUS.NEAR), active_period=objects.ActivePeriod(dtstart=datetime.now(), duration=timedelta(minutes=10)), event_signals=[ objects.EventSignal(intervals=[ objects.Interval(dtstart=datetime.now(), duration=timedelta(minutes=5), uid=0, signal_payload=1), objects.Interval(dtstart=datetime.now(), duration=timedelta(minutes=5), uid=1, signal_payload=2) ], targets=[objects.Target(ven_id='1234')], signal_name=enums.SIGNAL_NAME.LOAD_CONTROL, signal_type=enums.SIGNAL_TYPE.LEVEL, signal_id=1, current_value=0) ], targets=[objects.Target(ven_id='1234')]) response = objects.Response(response_code=200, response_description='OK', request_id='1234') msg = create_message('oadrDistributeEvent', response=response, events=[event]) message_type, message_payload = parse_message(msg)
def test_oadr_event_targets_and_targets_by_type_invalid(): with pytest.raises(ValueError): event = objects.Event( event_descriptor=objects.EventDescriptor( event_id=1, modification_number=0, market_context='MarketContext1', event_status=enums.EVENT_STATUS.NEAR), active_period=objects.ActivePeriod(dtstart=datetime.now(), duration=timedelta(minutes=10)), event_signals=[ objects.EventSignal(intervals=[ objects.Interval(dtstart=datetime.now(), duration=timedelta(minutes=5), uid=0, signal_payload=1), objects.Interval(dtstart=datetime.now(), duration=timedelta(minutes=5), uid=1, signal_payload=2) ], targets=[objects.Target(ven_id='1234')], signal_name=enums.SIGNAL_NAME.LOAD_CONTROL, signal_type=enums.SIGNAL_TYPE.LEVEL, signal_id=1, current_value=0) ], targets=[objects.Target(ven_id='ven456')], targets_by_type={'ven_id': ['ven123']}) msg = create_message('oadrDistributeEvent', events=[event]) validate_xml_schema(ensure_bytes(msg)) message_type, message_payload = parse_message(msg)
def test_event_signal_with_grouped_targets(): event_signal = objects.EventSignal( intervals=[ objects.Interval(dtstart=datetime.now(timezone.utc), duration=timedelta(minutes=10), signal_payload=1) ], signal_name='simple', signal_type='level', signal_id='signal123', targets_by_type={'ven_id': ['ven123', 'ven456']}) assert event_signal.targets == [ objects.Target(ven_id='ven123'), objects.Target(ven_id='ven456') ]
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
def test_oadr_event_no_targets(): with pytest.raises(ValueError): event = objects.Event( event_descriptor=objects.EventDescriptor( event_id=1, modification_number=0, market_context='MarketContext1', event_status=enums.EVENT_STATUS.NEAR), active_period=objects.ActivePeriod(dtstart=datetime.now(), duration=timedelta(minutes=10)), event_signals=[ objects.EventSignal(intervals=[ objects.Interval(dtstart=datetime.now(), duration=timedelta(minutes=5), uid=0, signal_payload=1), objects.Interval(dtstart=datetime.now(), duration=timedelta(minutes=5), uid=1, signal_payload=2) ], targets=[objects.Target(ven_id='1234')], signal_name=enums.SIGNAL_NAME.LOAD_CONTROL, signal_type=enums.SIGNAL_TYPE.LEVEL, signal_id=1, current_value=0) ])
def test_oadr_report(): report = objects.Report( created_date_time=datetime.now(), duration=timedelta(hours=1), report_specifier_id='id001', report_descriptions=[ objects.ReportDescription( r_id='report001', market_context='market001', reading_type=enums.READING_TYPE.DIRECT_READ, report_subject=objects.Target(), report_data_source=objects.Target(resource_id='resource001'), report_type=enums.REPORT_TYPE.READING, sampling_rate=timedelta(seconds=10), measurement=enums.MEASUREMENTS.VOLTAGE) ], report_name=enums.REPORT_NAME.HISTORY_USAGE)
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()
def test_event_signal_with_incongruent_targets(): with pytest.raises(ValueError): event_signal = objects.EventSignal( intervals=[ objects.Interval(dtstart=datetime.now(timezone.utc), duration=timedelta(minutes=10), signal_payload=1) ], signal_name='simple', signal_type='level', signal_id='signal123', targets=[objects.Target(ven_id='ven123')], targets_by_type={'ven_id': ['ven123', 'ven456']})
def add_report(self, callback, resource_id, measurement, data_collection_mode='incremental', report_specifier_id=None, r_id=None, report_name=enums.REPORT_NAME.TELEMETRY_USAGE, reading_type=enums.READING_TYPE.DIRECT_READ, report_type=enums.REPORT_TYPE.READING, sampling_rate=None, data_source=None, scale="none", unit=None, power_ac=True, power_hertz=50, power_voltage=230, market_context=None): """ Add a new reporting capability to the client. :param callable callback: A callback or coroutine that will fetch the value for a specific report. This callback will be passed the report_id and the r_id of the requested value. :param str resource_id: A specific name for this resource within this report. :param str measurement: The quantity that is being measured (openleadr.enums.MEASUREMENTS). :param str data_collection_mode: Whether you want the data to be collected incrementally or at once. If the VTN requests the sampling interval to be higher than the reporting interval, this setting determines if the callback should be called at the sampling rate (with no args, assuming it returns the current value), or at the reporting interval (with date_from and date_to as keyword arguments). Choose 'incremental' for the former case, or 'full' for the latter case. :param str report_specifier_id: A unique identifier for this report. Leave this blank for a random generated id, or fill it in if your VTN depends on this being a known value, or if it needs to be constant between restarts of the client. :param str r_id: A unique identifier for a datapoint in a report. The same remarks apply as for the report_specifier_id. :param str report_name: An OpenADR name for this report (one of openleadr.enums.REPORT_NAME) :param str reading_type: An OpenADR reading type (found in openleadr.enums.READING_TYPE) :param str report_type: An OpenADR report type (found in openleadr.enums.REPORT_TYPE) :param datetime.timedelta sampling_rate: The sampling rate for the measurement. :param str unit: The unit for this measurement. """ # Verify input if report_name not in enums.REPORT_NAME.values and not report_name.startswith('x-'): raise ValueError(f"{report_name} is not a valid report_name. Valid options are " f"{', '.join(enums.REPORT_NAME.values)}", " or any name starting with 'x-'.") if reading_type not in enums.READING_TYPE.values and not reading_type.startswith('x-'): raise ValueError(f"{reading_type} is not a valid reading_type. Valid options are " f"{', '.join(enums.READING_TYPE.values)}" " or any name starting with 'x-'.") if report_type not in enums.REPORT_TYPE.values and not report_type.startswith('x-'): raise ValueError(f"{report_type} is not a valid report_type. Valid options are " f"{', '.join(enums.REPORT_TYPE.values)}" " or any name starting with 'x-'.") if scale not in enums.SI_SCALE_CODE.values: raise ValueError(f"{scale} is not a valid scale. Valid options are " f"{', '.join(enums.SI_SCALE_CODE.values)}") if sampling_rate is None: sampling_rate = objects.SamplingRate(min_period=timedelta(seconds=10), max_period=timedelta(hours=24), on_change=False) elif isinstance(sampling_rate, timedelta): sampling_rate = objects.SamplingRate(min_period=sampling_rate, max_period=sampling_rate, on_change=False) if data_collection_mode not in ('incremental', 'full'): raise ValueError("The data_collection_mode should be 'incremental' or 'full'.") if data_collection_mode == 'full': args = inspect.signature(callback).parameters if not ('date_from' in args and 'date_to' in args and 'sampling_interval' in args): raise TypeError("Your callback function must accept the 'date_from', 'date_to' " "and 'sampling_interval' arguments if used " "with data_collection_mode 'full'.") # Determine the correct item name, item description and unit if isinstance(measurement, objects.Measurement): item_base = measurement elif measurement.upper() in enums.MEASUREMENTS.members: item_base = enums.MEASUREMENTS[measurement.upper()] else: item_base = objects.Measurement(item_name='customUnit', item_description=measurement, item_units=unit, si_scale_code=scale) if scale is not None: if scale in enums.SI_SCALE_CODE.values: item_base.si_scale_code = scale else: raise ValueError("The 'scale' argument must be one of '{'. ',join(enums.SI_SCALE_CODE.values)}") # Check if unit is compatible if unit is not None and unit != item_base.item_units \ and unit not in item_base.acceptable_units: logger.warning(f"The supplied unit {unit} for measurement {measurement} " f"will be ignored, {item_base.item_units} will be used instead." f"Allowed units for this measurement are: " f"{', '.join(item_base.acceptable_units)}") # Get or create the relevant Report if report_specifier_id: report = find_by(self.reports, 'report_name', report_name, 'report_specifier_id', report_specifier_id) else: report = find_by(self.reports, 'report_name', report_name) if not report: report_specifier_id = report_specifier_id or generate_id() report = objects.Report(created_date_time=datetime.now(), report_name=report_name, report_specifier_id=report_specifier_id, data_collection_mode=data_collection_mode) self.reports.append(report) # Add the new report description to the report target = objects.Target(resource_id=resource_id) r_id = generate_id() report_description = objects.ReportDescription(r_id=r_id, reading_type=reading_type, report_data_source=target, report_subject=target, report_type=report_type, sampling_rate=sampling_rate, measurement=item_base, market_context='Market01') self.report_callbacks[(report.report_specifier_id, r_id)] = callback report.report_descriptions.append(report_description)