client.py 39 KB

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