test_message_conversion.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. # SPDX-License-Identifier: Apache-2.0
  2. # Copyright 2020 Contributors to OpenLEADR
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. from openleadr.utils import generate_id, group_targets_by_type
  13. from openleadr.messaging import create_message, parse_message, validate_xml_schema
  14. from openleadr import enums
  15. from pprint import pprint
  16. from termcolor import colored
  17. from datetime import datetime, timezone, timedelta
  18. import pytest
  19. from pprint import pprint, pformat
  20. from lxml import etree
  21. from dataclasses import asdict
  22. import re
  23. DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
  24. def create_dummy_event(ven_id):
  25. """
  26. Creates a dummy event
  27. """
  28. now = datetime.now(timezone.utc)
  29. event_id = generate_id()
  30. active_period = {"dtstart": (now + timedelta(minutes=1)),
  31. "duration": timedelta(minutes=9)}
  32. event_descriptor = {"event_id": event_id,
  33. "modification_number": 1,
  34. "modification_date_time": now,
  35. "priority": 1,
  36. "market_context": "http://MarketContext1",
  37. "created_date_time": now,
  38. "event_status": "near",
  39. "test_event": False,
  40. "vtn_comment": "This is an event"}
  41. event_signals = [{"intervals": [{"duration": timedelta(minutes=1), "uid": 0, "signal_payload": 8.0},
  42. {"duration": timedelta(minutes=1), "uid": 1, "signal_payload": 10.0},
  43. {"duration": timedelta(minutes=1), "uid": 2, "signal_payload": 12.0},
  44. {"duration": timedelta(minutes=1), "uid": 3, "signal_payload": 14.0},
  45. {"duration": timedelta(minutes=1), "uid": 4, "signal_payload": 16.0},
  46. {"duration": timedelta(minutes=1), "uid": 5, "signal_payload": 18.0},
  47. {"duration": timedelta(minutes=1), "uid": 6, "signal_payload": 20.0},
  48. {"duration": timedelta(minutes=1), "uid": 7, "signal_payload": 10.0},
  49. {"duration": timedelta(minutes=1), "uid": 8, "signal_payload": 20.0}],
  50. "signal_name": "LOAD_CONTROL",
  51. "signal_type": "x-loadControlCapacity",
  52. "signal_id": generate_id(),
  53. "measurement": {"name": "voltage",
  54. "description": "Voltage",
  55. "unit": "V",
  56. "scale": "none"},
  57. "current_value": 0.0}]
  58. event_targets = [{"ven_id": 'VEN001'}, {"ven_id": 'VEN002'}]
  59. event = {'active_period': active_period,
  60. 'event_descriptor': event_descriptor,
  61. 'event_signals': event_signals,
  62. 'targets': event_targets,
  63. 'targets_by_type': group_targets_by_type(event_targets),
  64. 'response_required': 'always'}
  65. return event
  66. reports = [{'report_id': generate_id(),
  67. 'duration': timedelta(seconds=3600),
  68. 'report_descriptions': [{'r_id': generate_id(),
  69. 'report_subject': {'end_device_asset': {'mrid': 'meter001'}},
  70. 'report_data_source': {'resource_id': 'resource001'},
  71. 'report_type': 'usage',
  72. 'measurement': asdict(measurement),
  73. 'reading_type': 'Direct Read',
  74. 'market_context': 'http://MarketContext1',
  75. 'sampling_rate': {'min_period': timedelta(seconds=10), 'max_period': timedelta(seconds=30), 'on_change': False}} for measurement in enums.MEASUREMENTS.values],
  76. 'report_specifier_id': generate_id(),
  77. 'report_name': 'METADATA_HISTORY_USAGE',
  78. 'report_request_id': None,
  79. 'created_date_time': datetime.now(timezone.utc)}]
  80. for report in reports:
  81. for rd in report['report_descriptions']:
  82. rd['measurement'].pop('acceptable_units')
  83. rd['measurement'].pop('ns')
  84. if rd['measurement']['power_attributes'] is None:
  85. rd['measurement'].pop('power_attributes')
  86. if rd['measurement']['scale'] is None:
  87. rd['measurement'].pop('scale')
  88. if rd['measurement']['pulse_factor'] is None:
  89. rd['measurement'].pop('pulse_factor')
  90. testcases = [
  91. ('oadrCanceledOpt', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, opt_id=generate_id())),
  92. ('oadrCanceledPartyRegistration', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, registration_id=generate_id(), ven_id='123ABC')),
  93. ('oadrCanceledReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}])),
  94. ('oadrCanceledReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}], ven_id='123ABC')),
  95. ('oadrCancelOpt', dict(request_id=generate_id(), ven_id='123ABC', opt_id=generate_id())),
  96. ('oadrCancelPartyRegistration', dict(request_id=generate_id(), ven_id='123ABC', registration_id=generate_id())),
  97. ('oadrCancelReport', dict(request_id=generate_id(), ven_id='123ABC', report_request_id=generate_id(), report_to_follow=True)),
  98. ('oadrCreatedEvent', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  99. event_responses=[{'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(), 'event_id': generate_id(), 'modification_number': 1, 'opt_type': 'optIn'},
  100. {'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(), 'event_id': generate_id(), 'modification_number': 1, 'opt_type': 'optIn'},
  101. {'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(), 'event_id': generate_id(), 'modification_number': 1, 'opt_type': 'optIn'}],
  102. ven_id='123ABC')),
  103. ('oadrCreatedReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}], ven_id='123ABC')),
  104. ('oadrCreatedEvent', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  105. event_responses=[{'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(),
  106. 'event_id': generate_id(),
  107. 'modification_number': 1,
  108. 'opt_type': 'optIn'},
  109. {'response_code': 200, 'response_description': 'OK', 'request_id': generate_id(),
  110. 'event_id': generate_id(),
  111. 'modification_number': 1,
  112. 'opt_type': 'optOut'}],
  113. ven_id='123ABC')),
  114. ('oadrCreatedPartyRegistration', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  115. registration_id=generate_id(),
  116. ven_id='123ABC',
  117. profiles=[{'profile_name': '2.0b',
  118. 'transports': [{'transport_name': 'simpleHttp'}]}],
  119. vtn_id='VTN123')),
  120. ('oadrCreatedReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, pending_reports=[{'request_id': generate_id()}, {'request_id': generate_id()}])),
  121. ('oadrCreateOpt', dict(opt_id=generate_id(),
  122. opt_type='optIn',
  123. opt_reason='participating',
  124. created_date_time=datetime.now(timezone.utc),
  125. request_id=generate_id(),
  126. event_id=generate_id(),
  127. modification_number=1,
  128. targets=[{'ven_id': '123ABC'}],
  129. targets_by_type=group_targets_by_type([{'ven_id': '123ABC'}]),
  130. ven_id='VEN123')),
  131. ('oadrCreatePartyRegistration', dict(request_id=generate_id(), ven_id='123ABC', profile_name='2.0b', transport_name='simpleHttp', transport_address='http://localhost', report_only=False, xml_signature=False, ven_name='test', http_pull_model=True)),
  132. ('oadrCreateReport', dict(request_id=generate_id(),
  133. ven_id='123ABC',
  134. report_requests=[{'report_request_id': 'd2b7bade5f',
  135. 'report_specifier': {'granularity': timedelta(seconds=900),
  136. 'report_back_duration': timedelta(seconds=900),
  137. 'report_interval': {'dtstart': datetime(2019, 11, 19, 11, 0, 18, 672768, tzinfo=timezone.utc),
  138. 'duration': timedelta(seconds=7200)},
  139. 'report_specifier_id': '9c8bdc00e7',
  140. 'specifier_payloads': [{'r_id': 'd6e2e07485',
  141. 'reading_type': 'Direct Read'}]}}])),
  142. ('oadrDistributeEvent', dict(request_id=generate_id(), response={'request_id': 123, 'response_code': 200, 'response_description': 'OK'}, events=[create_dummy_event(ven_id='123ABC')], vtn_id='VTN123')),
  143. ('oadrDistributeEvent', dict(request_id=generate_id(), response={'request_id': 123, 'response_code': 200, 'response_description': 'OK'}, events=[create_dummy_event(ven_id='123ABC'), create_dummy_event(ven_id='123ABC')], vtn_id='VTN123')),
  144. ('oadrPoll', dict(ven_id='123ABC')),
  145. ('oadrQueryRegistration', dict(request_id=generate_id())),
  146. ('oadrRegisteredReport', dict(ven_id='VEN123', response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()},
  147. report_requests=[{'report_request_id': generate_id(),
  148. 'report_specifier': {'report_specifier_id': generate_id(),
  149. 'granularity': timedelta(minutes=15),
  150. 'report_back_duration': timedelta(minutes=15),
  151. 'report_interval': {'dtstart': datetime.now(timezone.utc),
  152. 'duration': timedelta(hours=2)},
  153. 'specifier_payloads': [{'r_id': generate_id(),
  154. 'reading_type': 'Direct Read'}]}},
  155. {'report_request_id': generate_id(),
  156. 'report_specifier': {'report_specifier_id': generate_id(),
  157. 'granularity': timedelta(minutes=15),
  158. 'report_back_duration': timedelta(minutes=15),
  159. 'report_interval': {'dtstart': datetime.now(timezone.utc),
  160. 'duration': timedelta(hours=2)},
  161. 'specifier_payloads': [{'r_id': generate_id(),
  162. 'reading_type': 'Direct Read'}]}}])),
  163. ('oadrRequestEvent', dict(request_id=generate_id(), ven_id='123ABC')),
  164. ('oadrRequestReregistration', dict(ven_id='123ABC')),
  165. ('oadrRegisterReport', dict(request_id=generate_id(), reports=[{'report_id': generate_id(),
  166. 'report_descriptions': [{
  167. 'r_id': generate_id(),
  168. 'report_subject': {'end_device_asset': {'mrid': 'meter001'}},
  169. 'report_data_source': {'resource_id': '123ABC'},
  170. 'report_type': 'reading',
  171. 'reading_type': 'Direct Read',
  172. 'market_context': 'http://localhost',
  173. 'sampling_rate': {'min_period': timedelta(minutes=1), 'max_period': timedelta(minutes=1), 'on_change': True}}],
  174. 'report_request_id': generate_id(),
  175. 'report_specifier_id': generate_id(),
  176. 'report_name': 'HISTORY_USAGE',
  177. 'created_date_time': datetime.now(timezone.utc)}],
  178. ven_id='123ABC',
  179. report_request_id=generate_id())),
  180. ('oadrRegisterReport', {'request_id': '8a4f859883', 'reports': [{'report_id': generate_id(),
  181. 'duration': timedelta(seconds=7200),
  182. 'report_descriptions': [{'r_id': generate_id(),
  183. 'report_data_source': {'resource_id': 'resource1'},
  184. 'report_type': 'x-resourceStatus',
  185. 'reading_type': 'x-notApplicable',
  186. 'market_context': 'http://MarketContext1',
  187. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}],
  188. 'report_request_id': generate_id(),
  189. 'report_specifier_id': '789ed6cd4e_telemetry_status',
  190. 'report_name': 'METADATA_TELEMETRY_STATUS',
  191. 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)},
  192. {'report_id': generate_id(),
  193. 'duration': timedelta(seconds=7200),
  194. 'report_descriptions': [{'r_id': 'resource1_energy',
  195. 'report_data_source': {'resource_id': 'resource1'},
  196. 'report_type': 'usage',
  197. 'measurement': {'name': 'energyReal',
  198. 'description': 'RealEnergy',
  199. 'ns': 'power',
  200. 'unit': 'Wh',
  201. 'scale': 'n'},
  202. 'reading_type': 'Direct Read',
  203. 'market_context': 'http://MarketContext1',
  204. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}},
  205. {'r_id': 'resource1_power',
  206. 'report_data_source': {'resource_id': 'resource1'},
  207. 'report_type': 'usage',
  208. 'measurement': {'name': 'powerReal',
  209. 'description': 'RealPower',
  210. 'ns': 'power',
  211. 'unit': 'W',
  212. 'scale': 'n',
  213. 'power_attributes': {'hertz': 50, 'voltage': 230, 'ac': True}},
  214. 'reading_type': 'Direct Read',
  215. 'market_context': 'http://MarketContext1',
  216. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}],
  217. 'report_request_id': generate_id(),
  218. 'report_specifier_id': '789ed6cd4e_telemetry_usage',
  219. 'report_name': 'METADATA_TELEMETRY_USAGE',
  220. 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)},
  221. {'report_id': generate_id(),
  222. 'duration': timedelta(seconds=7200),
  223. 'report_descriptions': [{'r_id': 'resource1_energy',
  224. 'report_data_source': {'resource_id': 'resource1'},
  225. 'report_type': 'usage',
  226. 'measurement': {'name': 'energyReal',
  227. 'description': 'RealEnergy',
  228. 'ns': 'power',
  229. 'unit': 'Wh',
  230. 'scale': 'n'},
  231. 'reading_type': 'Direct Read',
  232. 'market_context': 'http://MarketContext1',
  233. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}},
  234. {'r_id': 'resource1_power',
  235. 'report_data_source': {'resource_id': 'resource1'},
  236. 'report_type': 'usage',
  237. 'measurement': {'name': 'powerReal',
  238. 'description': 'RealPower',
  239. 'ns': 'power',
  240. 'unit': 'W',
  241. 'scale': 'n',
  242. 'power_attributes': {'hertz': 50, 'voltage': 230, 'ac': True}},
  243. 'reading_type': 'Direct Read',
  244. 'market_context': 'http://MarketContext1',
  245. 'sampling_rate': {'min_period': timedelta(seconds=60), 'max_period': timedelta(seconds=60), 'on_change': False}}],
  246. 'report_request_id': generate_id(),
  247. 'report_specifier_id': '789ed6cd4e_history_usage',
  248. 'report_name': 'METADATA_HISTORY_USAGE',
  249. 'created_date_time': datetime(2019, 11, 20, 15, 4, 52, 638621, tzinfo=timezone.utc)}], 'ven_id': 's3cc244ee6'}),
  250. ('oadrRegisterReport', {'ven_id': 'ven123', 'request_id': generate_id(), 'reports': reports}),
  251. ('oadrResponse', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, ven_id='123ABC')),
  252. ('oadrResponse', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': None}, ven_id='123ABC')),
  253. ('oadrUpdatedReport', dict(response={'response_code': 200, 'response_description': 'OK', 'request_id': generate_id()}, ven_id='123ABC', cancel_report={'request_id': generate_id(), 'report_request_id': [generate_id(), generate_id(), generate_id()], 'report_to_follow': False, 'ven_id': '123ABC'})),
  254. ('oadrUpdateReport', dict(request_id=generate_id(), reports=[{'report_id': generate_id(),
  255. 'report_name': enums.REPORT_NAME.values[0],
  256. 'created_date_time': datetime.now(timezone.utc),
  257. 'report_request_id': generate_id(),
  258. 'report_specifier_id': generate_id(),
  259. 'report_descriptions': [{'r_id': generate_id(),
  260. 'report_subject': {'end_device_asset': {'mrid': 'meter001'}},
  261. 'report_data_source': {'resource_id': '123ABC'},
  262. 'report_type': enums.REPORT_TYPE.values[0],
  263. 'reading_type': enums.READING_TYPE.values[0],
  264. 'market_context': 'http://localhost',
  265. 'sampling_rate': {'min_period': timedelta(minutes=1),
  266. 'max_period': timedelta(minutes=2),
  267. 'on_change': False}}
  268. ]}], ven_id='123ABC'))
  269. ]
  270. @pytest.mark.parametrize('message_type,data', testcases)
  271. def test_message(message_type, data):
  272. # file = open('representations.rst', 'a')
  273. # print(f".. _{message_type}:", file=file)
  274. # print("", file=file)
  275. # print(message_type, file=file)
  276. # print("="*len(message_type), file=file)
  277. # print("", file=file)
  278. # print("OpenADR payload:", file=file)
  279. # print("", file=file)
  280. # print(".. code-block:: xml", file=file)
  281. # print(" ", file=file)
  282. message = create_message(message_type, **data)
  283. # message = re.sub(r"\s\s+","",message)
  284. # message = message.replace("\n","")
  285. # xml_lines = etree.tostring(etree.fromstring(message.replace('\n', '').encode('utf-8')), pretty_print=True).decode('utf-8').splitlines()
  286. # for line in xml_lines:
  287. # print(" " + line, file=file)
  288. # print("", file=file)
  289. # print("OpenLEADR representation:", file=file)
  290. # print(" ", file=file)
  291. # print(".. code-block:: python3", file=file)
  292. # print(" ", file=file)
  293. validate_xml_schema(message)
  294. parsed = parse_message(message)[1]
  295. # dict_lines = pformat(parsed).splitlines()
  296. # for line in dict_lines:
  297. # print(" " + line, file=file)
  298. # print("", file=file)
  299. # print("", file=file)
  300. if message_type == 'oadrRegisterReport':
  301. for report in data['reports']:
  302. for rd in report['report_descriptions']:
  303. if 'measurement' in rd:
  304. rd['measurement'].pop('ns')
  305. if message_type == 'oadrDistributeEvent':
  306. for event in data['events']:
  307. for signal in event['event_signals']:
  308. if 'measurement' in signal:
  309. signal['measurement'].pop('ns')
  310. assert parsed == data