client.py 41 KB

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