client.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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. import asyncio
  13. import inspect
  14. import logging
  15. import ssl
  16. import sys
  17. import random
  18. from datetime import datetime, timedelta, timezone
  19. from functools import partial
  20. from http import HTTPStatus
  21. import aiohttp
  22. from lxml.etree import XMLSyntaxError
  23. from signxml.exceptions import InvalidSignature
  24. from apscheduler.schedulers.asyncio import AsyncIOScheduler
  25. from openleadr import enums, objects, errors
  26. from openleadr.messaging import create_message, parse_message, \
  27. validate_xml_schema, validate_xml_signature
  28. from openleadr import utils
  29. logger = logging.getLogger('openleadr')
  30. class OpenADRClient:
  31. """
  32. Main client class. Most of these methods will be called automatically, but
  33. you can always choose to call them manually.
  34. """
  35. def __init__(self, ven_name, vtn_url, debug=False, cert=None, key=None,
  36. passphrase=None, vtn_fingerprint=None, show_fingerprint=True, ca_file=None,
  37. allow_jitter=True):
  38. """
  39. Initializes a new OpenADR Client (Virtual End Node)
  40. :param str ven_name: The name for this VEN
  41. :param str vtn_url: The URL of the VTN (Server) to connect to
  42. :param bool debug: Whether or not to print debugging messages
  43. :param str cert: The path to a PEM-formatted Certificate file to use
  44. for signing messages.
  45. :param str key: The path to a PEM-formatted Private Key file to use
  46. for signing messages.
  47. :param str fingerprint: The fingerprint for the VTN's certificate to
  48. verify incomnig messages
  49. :param str show_fingerprint: Whether to print your own fingerprint
  50. on startup. Defaults to True.
  51. :param str ca_file: The path to the PEM-formatted CA file for validating the VTN server's
  52. certificate.
  53. """
  54. self.ven_name = ven_name
  55. if vtn_url.endswith("/"):
  56. vtn_url = vtn_url[:-1]
  57. self.vtn_url = vtn_url
  58. self.ven_id = None
  59. self.registration_id = None
  60. self.poll_frequency = None
  61. self.vtn_fingerprint = vtn_fingerprint
  62. self.debug = debug
  63. self.reports = []
  64. self.report_callbacks = {} # Holds the callbacks for each specific report
  65. self.report_requests = [] # Keep track of the report requests from the VTN
  66. self.incomplete_reports = {} # Holds reports that are being populated over time
  67. self.pending_reports = asyncio.Queue() # Holds reports that are waiting to be sent
  68. self.scheduler = AsyncIOScheduler()
  69. self.client_session = None
  70. self.report_queue_task = None
  71. self.received_events = {} # Holds the events that we received.
  72. self.responded_events = {} # Holds the events that we already saw.
  73. self.cert_path = cert
  74. self.key_path = key
  75. self.passphrase = passphrase
  76. self.ca_file = ca_file
  77. self.allow_jitter = allow_jitter
  78. if cert and key:
  79. with open(cert, 'rb') as file:
  80. cert = file.read()
  81. with open(key, 'rb') as file:
  82. key = file.read()
  83. if show_fingerprint:
  84. print("")
  85. print("*" * 80)
  86. print("Your VEN Certificate Fingerprint is ".center(80))
  87. print(f"{utils.certificate_fingerprint(cert).center(80)}".center(80))
  88. print("Please deliver this fingerprint to the VTN.".center(80))
  89. print("You do not need to keep this a secret.".center(80))
  90. print("*" * 80)
  91. print("")
  92. self._create_message = partial(create_message,
  93. cert=cert,
  94. key=key,
  95. passphrase=passphrase)
  96. async def run(self):
  97. """
  98. Run the client in full-auto mode.
  99. """
  100. # if not hasattr(self, 'on_event'):
  101. # raise NotImplementedError("You must implement on_event.")
  102. self.loop = asyncio.get_event_loop()
  103. await self.create_party_registration()
  104. if not self.ven_id:
  105. logger.error("No VEN ID received from the VTN, aborting.")
  106. await self.stop()
  107. return
  108. if self.reports:
  109. await self.register_reports(self.reports)
  110. self.report_queue_task = self.loop.create_task(self._report_queue_worker())
  111. await self._poll()
  112. # Set up automatic polling
  113. if self.poll_frequency > timedelta(hours=24):
  114. logger.warning("Polling with intervals of more than 24 hours is not supported. "
  115. "Will use 24 hours as the logging interval.")
  116. self.poll_frequency = timedelta(hours=24)
  117. cron_config = utils.cron_config(self.poll_frequency, randomize_seconds=self.allow_jitter)
  118. self.scheduler.add_job(self._poll,
  119. trigger='cron',
  120. **cron_config)
  121. self.scheduler.add_job(self._event_cleanup,
  122. trigger='interval',
  123. seconds=300)
  124. self.scheduler.start()
  125. async def stop(self):
  126. """
  127. Cleanly stops the client. Run this coroutine before closing your event loop.
  128. """
  129. if self.scheduler.running:
  130. self.scheduler.shutdown()
  131. if self.report_queue_task:
  132. self.report_queue_task.cancel()
  133. if sys.version_info.minor > 8:
  134. delayed_call_tasks = [task for task in asyncio.all_tasks() if task.get_name().startswith('DelayedCall')]
  135. for task in delayed_call_tasks:
  136. task.cancel()
  137. await self.client_session.close()
  138. await asyncio.sleep(0)
  139. def add_handler(self, handler, callback):
  140. """
  141. Add a callback for the given situation
  142. """
  143. if handler not in ('on_event', 'on_update_event'):
  144. logger.error("'handler' must be either on_event or on_update_event")
  145. return
  146. setattr(self, handler, callback)
  147. def add_report(self, callback, resource_id, measurement=None,
  148. data_collection_mode='incremental',
  149. report_specifier_id=None, r_id=None,
  150. report_name=enums.REPORT_NAME.TELEMETRY_USAGE,
  151. reading_type=enums.READING_TYPE.DIRECT_READ,
  152. report_type=enums.REPORT_TYPE.READING, sampling_rate=None, data_source=None,
  153. scale="none", unit=None, power_ac=True, power_hertz=50, power_voltage=230,
  154. market_context=None, end_device_asset_mrid=None, report_data_source=None):
  155. """
  156. Add a new reporting capability to the client.
  157. :param callable callback: A callback or coroutine that will fetch the value for a specific
  158. report. This callback will be passed the report_id and the r_id
  159. of the requested value.
  160. :param str resource_id: A specific name for this resource within this report.
  161. :param str measurement: The quantity that is being measured (openleadr.enums.MEASUREMENTS).
  162. Optional for TELEMETRY_STATUS reports.
  163. :param str data_collection_mode: Whether you want the data to be collected incrementally
  164. or at once. If the VTN requests the sampling interval to be
  165. higher than the reporting interval, this setting determines
  166. if the callback should be called at the sampling rate (with
  167. no args, assuming it returns the current value), or at the
  168. reporting interval (with date_from and date_to as keyword
  169. arguments). Choose 'incremental' for the former case, or
  170. 'full' for the latter case.
  171. :param str report_specifier_id: A unique identifier for this report. Leave this blank for a
  172. random generated id, or fill it in if your VTN depends on
  173. this being a known value, or if it needs to be constant
  174. between restarts of the client.
  175. :param str r_id: A unique identifier for a datapoint in a report. The same remarks apply as
  176. for the report_specifier_id.
  177. :param str report_name: An OpenADR name for this report (one of openleadr.enums.REPORT_NAME)
  178. :param str reading_type: An OpenADR reading type (found in openleadr.enums.READING_TYPE)
  179. :param str report_type: An OpenADR report type (found in openleadr.enums.REPORT_TYPE)
  180. :param datetime.timedelta sampling_rate: The sampling rate for the measurement.
  181. :param str unit: The unit for this measurement.
  182. :param boolean power_ac: Whether the power is AC (True) or DC (False).
  183. Only required when supplying a power-related measurement.
  184. :param int power_hertz: Grid frequency of the power.
  185. Only required when supplying a power-related measurement.
  186. :param int power_voltage: Voltage of the power.
  187. Only required when supplying a power-related measurement.
  188. :param str market_context: The Market Context that this report belongs to.
  189. :param str end_device_asset_mrid: the Meter ID for the end device that is measured by this report.
  190. :param report_data_source: A (list of) target(s) that this report is related to.
  191. """
  192. # Verify input
  193. if report_name not in enums.REPORT_NAME.values and not report_name.startswith('x-'):
  194. raise ValueError(f"{report_name} is not a valid report_name. Valid options are "
  195. f"{', '.join(enums.REPORT_NAME.values)}",
  196. " or any name starting with 'x-'.")
  197. if reading_type not in enums.READING_TYPE.values and not reading_type.startswith('x-'):
  198. raise ValueError(f"{reading_type} is not a valid reading_type. Valid options are "
  199. f"{', '.join(enums.READING_TYPE.values)}"
  200. " or any name starting with 'x-'.")
  201. if report_type not in enums.REPORT_TYPE.values and not report_type.startswith('x-'):
  202. raise ValueError(f"{report_type} is not a valid report_type. Valid options are "
  203. f"{', '.join(enums.REPORT_TYPE.values)}"
  204. " or any name starting with 'x-'.")
  205. if scale not in enums.SI_SCALE_CODE.values:
  206. raise ValueError(f"{scale} is not a valid scale. Valid options are "
  207. f"{', '.join(enums.SI_SCALE_CODE.values)}")
  208. if sampling_rate is None:
  209. sampling_rate = objects.SamplingRate(min_period=timedelta(seconds=10),
  210. max_period=timedelta(hours=24),
  211. on_change=False)
  212. elif isinstance(sampling_rate, timedelta):
  213. sampling_rate = objects.SamplingRate(min_period=sampling_rate,
  214. max_period=sampling_rate,
  215. on_change=False)
  216. if data_collection_mode not in ('incremental', 'full'):
  217. raise ValueError("The data_collection_mode should be 'incremental' or 'full'.")
  218. if data_collection_mode == 'full':
  219. args = inspect.signature(callback).parameters
  220. if not ('date_from' in args and 'date_to' in args and 'sampling_interval' in args):
  221. raise TypeError("Your callback function must accept the 'date_from', 'date_to' "
  222. "and 'sampling_interval' arguments if used "
  223. "with data_collection_mode 'full'.")
  224. # Determine the correct item name, item description and unit
  225. if report_name == 'TELEMETRY_STATUS':
  226. item_base = None
  227. elif isinstance(measurement, objects.Measurement):
  228. item_base = measurement
  229. elif isinstance(measurement, dict):
  230. utils.validate_report_measurement_dict(measurement)
  231. power_attributes = object.PowerAttributes(**measurement.get('power_attributes')) or None
  232. item_base = objects.Measurement(name=measurement['name'],
  233. description=measurement['description'],
  234. unit=measurement['unit'],
  235. scale=measurement.get('scale'),
  236. power_attributes=power_attributes)
  237. elif measurement.upper() in enums.MEASUREMENTS.members:
  238. item_base = enums.MEASUREMENTS[measurement.upper()]
  239. else:
  240. item_base = objects.Measurement(name='customUnit',
  241. description=measurement,
  242. unit=unit,
  243. scale=scale)
  244. if report_name != 'TELEMETRY_STATUS' and scale is not None:
  245. if item_base.scale is not None:
  246. if scale in enums.SI_SCALE_CODE.values:
  247. item_base.scale = scale
  248. else:
  249. raise ValueError("The 'scale' argument must be one of '{'. ',join(enums.SI_SCALE_CODE.values)}")
  250. # Check if unit is compatible
  251. if unit is not None and unit != item_base.unit and unit not in item_base.acceptable_units:
  252. logger.warning(f"The supplied unit {unit} for measurement {measurement} "
  253. f"will be ignored, {item_base.unit} will be used instead. "
  254. f"Allowed units for this measurement are: "
  255. f"{', '.join(item_base.acceptable_units)}")
  256. # Get or create the relevant Report
  257. if report_specifier_id:
  258. report = utils.find_by(self.reports,
  259. 'report_name', report_name,
  260. 'report_specifier_id', report_specifier_id)
  261. else:
  262. report = utils.find_by(self.reports, 'report_name', report_name)
  263. if not report:
  264. report_specifier_id = report_specifier_id or utils.generate_id()
  265. report = objects.Report(created_date_time=datetime.now(),
  266. report_name=report_name,
  267. report_specifier_id=report_specifier_id,
  268. data_collection_mode=data_collection_mode)
  269. self.reports.append(report)
  270. # Add the new report description to the report
  271. target = objects.Target(resource_id=resource_id)
  272. r_id = utils.generate_id()
  273. report_description = objects.ReportDescription(r_id=r_id,
  274. reading_type=reading_type,
  275. report_data_source=target,
  276. report_subject=target,
  277. report_type=report_type,
  278. sampling_rate=sampling_rate,
  279. measurement=item_base,
  280. market_context=market_context)
  281. self.report_callbacks[(report.report_specifier_id, r_id)] = callback
  282. report.report_descriptions.append(report_description)
  283. return report_specifier_id, r_id
  284. ###########################################################################
  285. # #
  286. # POLLING METHODS #
  287. # #
  288. ###########################################################################
  289. async def poll(self):
  290. """
  291. Request the next available message from the Server. This coroutine is called automatically.
  292. """
  293. service = 'OadrPoll'
  294. message = self._create_message('oadrPoll', ven_id=self.ven_id)
  295. response_type, response_payload = await self._perform_request(service, message)
  296. return response_type, response_payload
  297. ###########################################################################
  298. # #
  299. # REGISTRATION METHODS #
  300. # #
  301. ###########################################################################
  302. async def query_registration(self):
  303. """
  304. Request information about the VTN.
  305. """
  306. request_id = utils.generate_id()
  307. service = 'EiRegisterParty'
  308. message = self._create_message('oadrQueryRegistration', request_id=request_id)
  309. response_type, response_payload = await self._perform_request(service, message)
  310. return response_type, response_payload
  311. async def create_party_registration(self, http_pull_model=True, xml_signature=False,
  312. report_only=False, profile_name='2.0b',
  313. transport_name='simpleHttp', transport_address=None,
  314. ven_id=None):
  315. """
  316. Take the neccessary steps to register this client with the server.
  317. :param bool http_pull_model: Whether to use the 'pull' model for HTTP.
  318. :param bool xml_signature: Whether to sign each XML message.
  319. :param bool report_only: Whether or not this is a reporting-only client
  320. which does not deal with Events.
  321. :param str profile_name: Which OpenADR profile to use.
  322. :param str transport_name: The transport name to use. Either 'simpleHttp' or 'xmpp'.
  323. :param str transport_address: Which public-facing address the server should use
  324. to communicate.
  325. :param str ven_id: The ID for this VEN. If you leave this blank,
  326. a VEN_ID will be assigned by the VTN.
  327. """
  328. request_id = utils.generate_id()
  329. service = 'EiRegisterParty'
  330. payload = {'ven_name': self.ven_name,
  331. 'http_pull_model': http_pull_model,
  332. 'xml_signature': xml_signature,
  333. 'report_only': report_only,
  334. 'profile_name': profile_name,
  335. 'transport_name': transport_name,
  336. 'transport_address': transport_address}
  337. if ven_id:
  338. payload['ven_id'] = ven_id
  339. message = self._create_message('oadrCreatePartyRegistration',
  340. request_id=request_id,
  341. **payload)
  342. response_type, response_payload = await self._perform_request(service, message)
  343. if response_type is None:
  344. return
  345. if response_payload['response']['response_code'] != 200:
  346. status_code = response_payload['response']['response_code']
  347. status_description = response_payload['response']['response_description']
  348. logger.error(f"Got error on Create Party Registration: "
  349. f"{status_code} {status_description}")
  350. return
  351. self.ven_id = response_payload['ven_id']
  352. self.registration_id = response_payload['registration_id']
  353. self.poll_frequency = response_payload.get('requested_oadr_poll_freq',
  354. timedelta(seconds=10))
  355. logger.info(f"VEN is now registered with ID {self.ven_id}")
  356. logger.info(f"The polling frequency is {self.poll_frequency}")
  357. return response_type, response_payload
  358. async def cancel_party_registration(self):
  359. raise NotImplementedError("Cancel Registration is not yet implemented")
  360. ###########################################################################
  361. # #
  362. # EVENT METHODS #
  363. # #
  364. ###########################################################################
  365. async def request_event(self, reply_limit=1):
  366. """
  367. Request the next Event from the VTN, if it has any.
  368. """
  369. payload = {'request_id': utils.generate_id(),
  370. 'ven_id': self.ven_id,
  371. 'reply_limit': reply_limit}
  372. message = self._create_message('oadrRequestEvent', **payload)
  373. service = 'EiEvent'
  374. response_type, response_payload = await self._perform_request(service, message)
  375. return response_type, response_payload
  376. async def created_event(self, request_id, event_id, opt_type, modification_number=1):
  377. """
  378. Inform the VTN that we created an event.
  379. """
  380. service = 'EiEvent'
  381. payload = {'ven_id': self.ven_id,
  382. 'response': {'response_code': 200,
  383. 'response_description': 'OK',
  384. 'request_id': request_id},
  385. 'event_responses': [{'response_code': 200,
  386. 'response_description': 'OK',
  387. 'request_id': request_id,
  388. 'event_id': event_id,
  389. 'modification_number': modification_number,
  390. 'opt_type': opt_type}]}
  391. message = self._create_message('oadrCreatedEvent', **payload)
  392. response_type, response_payload = await self._perform_request(service, message)
  393. ###########################################################################
  394. # #
  395. # REPORTING METHODS #
  396. # #
  397. ###########################################################################
  398. async def register_reports(self, reports):
  399. """
  400. Tell the VTN about our reports. The VTN miht respond with an
  401. oadrCreateReport message that tells us which reports are to be sent.
  402. """
  403. request_id = utils.generate_id()
  404. payload = {'request_id': request_id,
  405. 'ven_id': self.ven_id,
  406. 'reports': reports,
  407. 'report_request_id': 0}
  408. service = 'EiReport'
  409. message = self._create_message('oadrRegisterReport', **payload)
  410. response_type, response_payload = await self._perform_request(service, message)
  411. # Handle the subscriptions that the VTN is interested in.
  412. if 'report_requests' in response_payload:
  413. for report_request in response_payload['report_requests']:
  414. await self.create_report(report_request)
  415. message_type = 'oadrCreatedReport'
  416. message_payload = {}
  417. return message_type, message_payload
  418. async def create_report(self, report_request):
  419. """
  420. Add the requested reports to the reporting mechanism.
  421. This is called when the VTN requests reports from us.
  422. :param report_request dict: The oadrReportRequest dict from the VTN.
  423. """
  424. # Get the relevant variables from the report requests
  425. report_request_id = report_request['report_request_id']
  426. report_specifier_id = report_request['report_specifier']['report_specifier_id']
  427. report_back_duration = report_request['report_specifier'].get('report_back_duration')
  428. granularity = report_request['report_specifier']['granularity']
  429. # Check if this report actually exists
  430. report = utils.find_by(self.reports, 'report_specifier_id', report_specifier_id)
  431. if not report:
  432. logger.error(f"A non-existant report with report_specifier_id "
  433. f"{report_specifier_id} was requested.")
  434. return False
  435. # Check and collect the requested r_ids for this report
  436. requested_r_ids = []
  437. for specifier_payload in report_request['report_specifier']['specifier_payloads']:
  438. r_id = specifier_payload['r_id']
  439. # Check if the requested r_id actually exists
  440. rd = utils.find_by(report.report_descriptions, 'r_id', r_id)
  441. if not rd:
  442. logger.error(f"A non-existant report with r_id {r_id} "
  443. f"inside report with report_specifier_id {report_specifier_id} "
  444. f"was requested.")
  445. continue
  446. # Check if the requested measurement exists and if the correct unit is requested
  447. if 'measurement' in specifier_payload:
  448. measurement = specifier_payload['measurement']
  449. if measurement['description'] != rd.measurement.description:
  450. logger.error(f"A non-matching measurement description for report with "
  451. f"report_request_id {report_request_id} and r_id {r_id} was given "
  452. f"by the VTN. Offered: {rd.measurement.description}, "
  453. f"requested: {measurement['description']}")
  454. continue
  455. if measurement['unit'] != rd.measurement.unit:
  456. logger.error(f"A non-matching measurement unit for report with "
  457. f"report_request_id {report_request_id} and r_id {r_id} was given "
  458. f"by the VTN. Offered: {rd.measurement.unit}, "
  459. f"requested: {measurement['unit']}")
  460. continue
  461. if granularity is not None:
  462. if not rd.sampling_rate.min_period <= granularity <= rd.sampling_rate.max_period:
  463. logger.error(f"An invalid sampling rate {granularity} was requested for report "
  464. f"with report_specifier_id {report_specifier_id} and r_id {r_id}. "
  465. f"The offered sampling rate was between "
  466. f"{rd.sampling_rate.min_period} and "
  467. f"{rd.sampling_rate.max_period}")
  468. continue
  469. else:
  470. # If no granularity is specified, set it to the lowest sampling rate.
  471. granularity = rd.sampling_rate.max_period
  472. requested_r_ids.append(r_id)
  473. callback = partial(self.update_report, report_request_id=report_request_id)
  474. reporting_interval = report_back_duration or granularity
  475. job = self.scheduler.add_job(func=callback,
  476. trigger='cron',
  477. **utils.cron_config(reporting_interval))
  478. self.report_requests.append({'report_request_id': report_request_id,
  479. 'report_specifier_id': report_specifier_id,
  480. 'report_back_duration': report_back_duration,
  481. 'r_ids': requested_r_ids,
  482. 'granularity': granularity,
  483. 'job': job})
  484. async def create_single_report(self, report_request):
  485. """
  486. Create a single report in response to a request from the VTN.
  487. """
  488. async def update_report(self, report_request_id):
  489. """
  490. Call the previously registered report callback and send the result as a message to the VTN.
  491. """
  492. logger.debug(f"Running update_report for {report_request_id}")
  493. report_request = utils.find_by(self.report_requests, 'report_request_id', report_request_id)
  494. granularity = report_request['granularity']
  495. report_back_duration = report_request['report_back_duration']
  496. report_specifier_id = report_request['report_specifier_id']
  497. report = utils.find_by(self.reports, 'report_specifier_id', report_specifier_id)
  498. data_collection_mode = report.data_collection_mode
  499. if report_request_id in self.incomplete_reports:
  500. logger.debug("We were already compiling this report")
  501. outgoing_report = self.incomplete_reports[report_request_id]
  502. else:
  503. logger.debug("There is no report in progress")
  504. outgoing_report = objects.Report(report_request_id=report_request_id,
  505. report_specifier_id=report.report_specifier_id,
  506. report_name=report.report_name,
  507. intervals=[])
  508. intervals = outgoing_report.intervals or []
  509. if data_collection_mode == 'full':
  510. if report_back_duration is None:
  511. report_back_duration = granularity
  512. date_to = datetime.now(timezone.utc)
  513. date_from = date_to - max(report_back_duration, granularity)
  514. for r_id in report_request['r_ids']:
  515. report_callback = self.report_callbacks[(report_specifier_id, r_id)]
  516. result = report_callback(date_from=date_from,
  517. date_to=date_to,
  518. sampling_interval=granularity)
  519. if asyncio.iscoroutine(result):
  520. result = await result
  521. for dt, value in result:
  522. report_payload = objects.ReportPayload(r_id=r_id, value=value)
  523. intervals.append(objects.ReportInterval(dtstart=dt,
  524. report_payload=report_payload))
  525. else:
  526. for r_id in report_request['r_ids']:
  527. report_callback = self.report_callbacks[(report_specifier_id, r_id)]
  528. result = report_callback()
  529. if asyncio.iscoroutine(result):
  530. result = await result
  531. if isinstance(result, (int, float)):
  532. result = [(datetime.now(timezone.utc), result)]
  533. for dt, value in result:
  534. logger.info(f"Adding {dt}, {value} to report")
  535. report_payload = objects.ReportPayload(r_id=r_id, value=value)
  536. intervals.append(objects.ReportInterval(dtstart=dt,
  537. report_payload=report_payload))
  538. outgoing_report.intervals = intervals
  539. logger.info(f"The number of intervals in the report is now {len(outgoing_report.intervals)}")
  540. # Figure out if the report is complete after this sampling
  541. if data_collection_mode == 'incremental' and report_back_duration is not None\
  542. and report_back_duration > granularity:
  543. report_interval = report_back_duration.total_seconds()
  544. sampling_interval = granularity.total_seconds()
  545. expected_len = len(report_request['r_ids']) * int(report_interval / sampling_interval)
  546. if len(outgoing_report.intervals) == expected_len:
  547. logger.info("The report is now complete with all the values. Will queue for sending.")
  548. if self.allow_jitter:
  549. delay = random.uniform(0, min(30, report_interval / 2))
  550. if sys.version_info.minor >= 8:
  551. name = {'name': f'DelayedCall-OutgoingReport-{utils.generate_id()}'}
  552. else:
  553. name = {}
  554. self.loop.create_task(utils.delayed_call(func=self.pending_reports.put(outgoing_report),
  555. delay=delay), **name)
  556. else:
  557. await self.pending_reports.put(self.incomplete_reports.pop(report_request_id))
  558. else:
  559. logger.debug("The report is not yet complete, will hold until it is.")
  560. self.incomplete_reports[report_request_id] = outgoing_report
  561. else:
  562. logger.info("Report will be sent now.")
  563. if self.allow_jitter:
  564. delay = random.uniform(0, min(30, granularity.total_seconds() / 2))
  565. if sys.version_info.minor >= 8:
  566. name = {'name': f'DelayedCall-OutgoingReport-{utils.generate_id()}'}
  567. else:
  568. name = {}
  569. self.loop.create_task(utils.delayed_call(func=self.pending_reports.put(outgoing_report),
  570. delay=delay), **name)
  571. else:
  572. await self.pending_reports.put(outgoing_report)
  573. async def cancel_report(self, payload):
  574. """
  575. Cancel this report.
  576. """
  577. async def _report_queue_worker(self):
  578. """
  579. A Queue worker that pushes out the pending reports.
  580. """
  581. while True:
  582. report = await self.pending_reports.get()
  583. service = 'EiReport'
  584. message = self._create_message('oadrUpdateReport', reports=[report])
  585. try:
  586. response_type, response_payload = await self._perform_request(service, message)
  587. except Exception as err:
  588. logger.error(f"Unable to send the report to the VTN. Error: {err}")
  589. else:
  590. if 'cancel_report' in response_payload:
  591. await self.cancel_report(response_payload['cancel_report'])
  592. ###########################################################################
  593. # #
  594. # PLACEHOLDER #
  595. # #
  596. ###########################################################################
  597. async def on_event(self, event):
  598. """
  599. Placeholder for the on_event handler.
  600. """
  601. logger.warning("You should implement your own on_event handler. This handler receives "
  602. "an Event dict and should return either 'optIn' or 'optOut' based on your "
  603. "choice. Will opt out of the event for now.")
  604. return 'optOut'
  605. async def on_update_event(self, event):
  606. """
  607. Placeholder for the on_update_event handler.
  608. """
  609. logger.warning("You should implement your own on_update_event handler. This handler receives "
  610. "an Event dict and should return either 'optIn' or 'optOut' based on your "
  611. "choice. Will re-use the previous opt status for this event_id for now")
  612. if event['event_descriptor']['event_id'] in self.events:
  613. return self.responded_events['event_id']
  614. async def on_register_report(self, report):
  615. """
  616. Placeholder for the on_register_report handler.
  617. """
  618. ###########################################################################
  619. # #
  620. # LOW LEVEL #
  621. # #
  622. ###########################################################################
  623. async def _perform_request(self, service, message):
  624. await self._ensure_client_session()
  625. logger.debug(f"Client is sending {message}")
  626. url = f"{self.vtn_url}/{service}"
  627. try:
  628. async with self.client_session.post(url, data=message) as req:
  629. content = await req.read()
  630. if req.status != HTTPStatus.OK:
  631. logger.warning(f"Non-OK status {req.status} when performing a request to {url} "
  632. f"with data {message}: {req.status} {content.decode('utf-8')}")
  633. return None, {}
  634. logger.debug(content.decode('utf-8'))
  635. except aiohttp.client_exceptions.ClientConnectorError as err:
  636. # Could not connect to server
  637. logger.error(f"Could not connect to server with URL {self.vtn_url}:")
  638. logger.error(f"{err.__class__.__name__}: {str(err)}")
  639. return None, {}
  640. except Exception as err:
  641. logger.error(f"Request error {err.__class__.__name__}:{err}")
  642. return None, {}
  643. try:
  644. tree = validate_xml_schema(content)
  645. if self.vtn_fingerprint:
  646. validate_xml_signature(tree)
  647. message_type, message_payload = parse_message(content)
  648. except XMLSyntaxError as err:
  649. logger.warning(f"Incoming message did not pass XML schema validation: {err}")
  650. return None, {}
  651. except errors.FingerprintMismatch as err:
  652. logger.warning(err)
  653. return None, {}
  654. except InvalidSignature:
  655. logger.warning("Incoming message had invalid signature, ignoring.")
  656. return None, {}
  657. except Exception as err:
  658. logger.error(f"The incoming message could not be parsed or validated: {err}")
  659. return None, {}
  660. if 'response' in message_payload and 'response_code' in message_payload['response']:
  661. if message_payload['response']['response_code'] != 200:
  662. logger.warning("We got a non-OK OpenADR response from the server: "
  663. f"{message_payload['response']['response_code']}: "
  664. f"{message_payload['response']['response_description']}")
  665. return message_type, message_payload
  666. async def _on_event(self, message):
  667. logger.debug("The VEN received an event")
  668. events = message['events']
  669. try:
  670. results = []
  671. for event in message['events']:
  672. event_id = event['event_descriptor']['event_id']
  673. event_status = event['event_descriptor']['event_status']
  674. modification_number = event['event_descriptor']['modification_number']
  675. if event_id in self.received_events:
  676. if self.received_events[event_id]['event_descriptor']['modification_number'] == modification_number:
  677. # Re-submit the same opt type as we already had previously
  678. result = self.responded_events[event_id]
  679. else:
  680. # Wait for the result of the on_update_event handler
  681. result = self.on_update_event(event)
  682. else:
  683. # Wait for the result of the on_event
  684. self.received_events[event_id] = event
  685. result = self.on_event(event)
  686. if asyncio.iscoroutine(result):
  687. result = await result
  688. results.append(result)
  689. if event_status == 'completed':
  690. self.responded_events.pop(event_id)
  691. else:
  692. self.responded_events[event_id] = result
  693. for i, result in enumerate(results):
  694. if result not in ('optIn', 'optOut') and events[i]['response_required'] == 'always':
  695. logger.error("Your on_event or on_update_event handler must return 'optIn' or 'optOut'; "
  696. f"you supplied {result}. Please fix your on_event handler.")
  697. results[i] = 'optOut'
  698. except Exception as err:
  699. logger.error("Your on_event handler encountered an error. Will Opt Out of the event. "
  700. f"The error was {err.__class__.__name__}: {str(err)}")
  701. results = ['optOut'] * len(events)
  702. event_responses = [{'response_code': 200,
  703. 'response_description': 'OK',
  704. 'opt_type': results[i],
  705. 'request_id': message['request_id'],
  706. 'modification_number': 1,
  707. 'event_id': events[i]['event_descriptor']['event_id']}
  708. for i, event in enumerate(events)
  709. if event['response_required'] == 'always'
  710. and not utils.determine_event_status(event['active_period']) == 'completed']
  711. if len(event_responses) > 0:
  712. response = {'response_code': 200,
  713. 'response_description': 'OK',
  714. 'request_id': message['request_id']}
  715. message = self._create_message('oadrCreatedEvent',
  716. response=response,
  717. event_responses=event_responses,
  718. ven_id=self.ven_id)
  719. service = 'EiEvent'
  720. response_type, response_payload = await self._perform_request(service, message)
  721. logger.info(response_type, response_payload)
  722. else:
  723. logger.info("Not sending any event responses, because a response was not required/allowed by the VTN.")
  724. async def _event_cleanup(self):
  725. """
  726. Periodic task that will clean up completed events in our memory.
  727. """
  728. print("Checking for stale events")
  729. for event in list(self.received_events):
  730. if utils.determine_event_status(self.received_events[event]['active_period']) == 'completed':
  731. logger.debug(f"Removing event {event} because it is completed.")
  732. self.received_events.pop(event)
  733. async def _poll(self):
  734. logger.debug("Now polling for new messages")
  735. response_type, response_payload = await self.poll()
  736. if response_type is None:
  737. return
  738. if response_type == 'oadrResponse':
  739. logger.debug("No events or reports available")
  740. return
  741. if response_type == 'oadrRequestReregistration':
  742. logger.info("The VTN required us to re-register. Calling the registration procedure.")
  743. await self.create_party_registration()
  744. if response_type == 'oadrDistributeEvent':
  745. if len(response_payload['events']) > 0:
  746. await self._on_event(response_payload)
  747. elif response_type == 'oadrUpdateReport':
  748. await self._on_report(response_payload)
  749. elif response_type == 'oadrCreateReport':
  750. if 'report_requests' in response_payload:
  751. for report_request in response_payload['report_requests']:
  752. await self.create_report(report_request)
  753. elif response_type == 'oadrRegisterReport':
  754. if 'reports' in response_payload and len(response_payload['reports']) > 0:
  755. for report in response_payload['reports']:
  756. await self.register_report(report)
  757. else:
  758. logger.warning(f"No handler implemented for incoming message "
  759. f"of type {response_type}, ignoring.")
  760. # Immediately poll again, because there might be more messages
  761. await self._poll()
  762. async def _ensure_client_session(self):
  763. if not self.client_session:
  764. headers = {'content-type': 'application/xml'}
  765. if self.cert_path:
  766. ssl_context = ssl.create_default_context(cafile=self.ca_file,
  767. purpose=ssl.Purpose.CLIENT_AUTH)
  768. ssl_context.load_cert_chain(self.cert_path, self.key_path, self.passphrase)
  769. ssl_context.check_hostname = False
  770. connector = aiohttp.TCPConnector(ssl=ssl_context)
  771. self.client_session = aiohttp.ClientSession(connector=connector, headers=headers)
  772. else:
  773. self.client_session = aiohttp.ClientSession(headers=headers)