client.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 xmltodict
  16. import random
  17. import aiohttp
  18. from pyopenadr.utils import new_request_id, peek, generate_id
  19. from pyopenadr.messaging import create_message, parse_message
  20. from pyopenadr import enums
  21. from datetime import datetime, timedelta, timezone
  22. from http import HTTPStatus
  23. from apscheduler.schedulers.asyncio import AsyncIOScheduler
  24. import asyncio
  25. from asyncio import iscoroutine
  26. MEASURANDS = {'power_real': 'power_quantity',
  27. 'power_reactive': 'power_quantity',
  28. 'power_apparent': 'power_quantity',
  29. 'energy_real': 'energy_quantity',
  30. 'energy_reactive': 'energy_quantity',
  31. 'energy_active': 'energy_quantity'}
  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):
  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. """
  44. self.ven_name = ven_name
  45. self.vtn_url = vtn_url
  46. self.ven_id = None
  47. self.poll_frequency = None
  48. self.debug = debug
  49. self.reports = {} # Mapping of all available reports from the VEN
  50. self.report_requests = {} # Mapping of the reports requested by the VTN
  51. self.report_schedulers = {} # Mapping between reportRequestIDs and our internal report schedulers
  52. self.scheduler = AsyncIOScheduler()
  53. self.client_session = aiohttp.ClientSession()
  54. async def run(self):
  55. """
  56. Run the client in full-auto mode.
  57. """
  58. if not hasattr(self, 'on_event') or not hasattr(self, 'on_report'):
  59. raise NotImplementedError("You must implement both the on_event and and_report functions or coroutines.")
  60. await self.create_party_registration()
  61. if not self.ven_id:
  62. print("No VEN ID received from the VTN, aborting registration.")
  63. return
  64. if self.reports:
  65. await self.register_report()
  66. # Set up automatic polling
  67. if self.poll_frequency.total_seconds() < 60:
  68. cron_second = f"*/{self.poll_frequency.seconds}"
  69. cron_minute = "*"
  70. cron_hour = "*"
  71. elif self.poll_frequency.total_seconds() < 3600:
  72. cron_second = "0"
  73. cron_minute = f'*/{int(self.poll_frequency.total_seconds() / 60)}'
  74. cron_hour = "*"
  75. elif self.poll_frequency.total_seconds() < 86400:
  76. cron_second = "0"
  77. cron_minute = "0"
  78. cron_hour = f'*/{int(self.poll_frequency.total_seconds() / 3600)}'
  79. elif self.poll_frequency.total_seconds() > 86400:
  80. print("Polling with intervals of more than 24 hours is not supported.")
  81. return
  82. self.scheduler.add_job(self._poll, trigger='cron', second=cron_second, minute=cron_minute, hour=cron_hour)
  83. self.scheduler.start()
  84. def add_report(self, callable, report_id, report_name, reading_type, report_type,
  85. sampling_rate, resource_id, measurand, unit, scale="none",
  86. power_ac=True, power_hertz=50, power_voltage=230, market_context=None):
  87. """
  88. Add a new reporting capability to the client.
  89. :param callable callable: A callable or coroutine that will fetch the value for a specific report. This callable will be passed the report_id and the r_id of the requested value.
  90. :param str report_id: A unique identifier for this report.
  91. :param str report_name: An OpenADR name for this report (one of pyopenadr.enums.REPORT_NAME)
  92. :param str reading_type: An OpenADR reading type (found in pyopenadr.enums.READING_TYPE)
  93. :param str report_type: An OpenADR report type (found in pyopenadr.enums.REPORT_TYPE)
  94. :param datetime.timedelta sampling_rate: The sampling rate for the measurement.
  95. :param resource_id: A specific name for this resource within this report.
  96. :param str unit: The unit for this measurement.
  97. """
  98. if report_name not in enums.REPORT_NAME.values:
  99. raise ValueError(f"{report_name} is not a valid report_name. Valid options are {', '.join(enums.REPORT_NAME.values)}.")
  100. if reading_type not in enums.READING_TYPE.values:
  101. raise ValueError(f"{reading_type} is not a valid reading_type. Valid options are {', '.join(enums.READING_TYPE.values)}.")
  102. if report_type not in enums.REPORT_TYPE.values:
  103. raise ValueError(f"{report_type} is not a valid report_type. Valid options are {', '.join(enums.REPORT_TYPE.values)}.")
  104. if measurand not in MEASURANDS:
  105. raise ValueError(f"{measurand} is not a valid measurand. Valid options are 'power_real', 'power_reactive', 'power_apparent', 'energy_real', 'energy_reactive', 'energy_active', 'energy_quantity', 'voltage'")
  106. if scale not in enums.SI_SCALE_CODE.values:
  107. raise ValueError(f"{scale} is not a valid scale. Valid options are {', '.join(enums.SI_SCALE_CODE.values)}")
  108. report_description = {'market_context': market_context,
  109. 'r_id': resource_id,
  110. 'reading_type': reading_type,
  111. 'report_type': report_type,
  112. 'sampling_rate': {'max_period': sampling_rate,
  113. 'min_period': sampling_rate,
  114. 'on_change': False},
  115. measurand: {'item_description': measurand,
  116. 'item_units': unit,
  117. 'si_scale_code': scale}}
  118. if 'power' in measurand:
  119. report_description[measurand]['power_attributes'] = {'ac': power_ac, 'hertz': power_hertz, 'voltage': power_voltage}
  120. if report_id in self.reports:
  121. report = self.reports[report_id]['report_descriptions'].append(report_description)
  122. else:
  123. report = {'callable': callable,
  124. 'created_date_time': datetime.now(timezone.utc),
  125. 'report_id': report_id,
  126. 'report_name': report_name,
  127. 'report_request_id': generate_id(),
  128. 'report_specifier_id': report_id + "_" + report_name.lower(),
  129. 'report_descriptions': [report_description]}
  130. self.reports[report_id] = report
  131. self.report_ids[resource_id] = {'item_base': measurand}
  132. async def query_registration(self):
  133. """
  134. Request information about the VTN.
  135. """
  136. request_id = new_request_id()
  137. service = 'EiRegisterParty'
  138. message = create_message('oadrQueryRegistration', request_id=request_id)
  139. response_type, response_payload = await self._perform_request(service, message)
  140. return response_type, response_payload
  141. async def create_party_registration(self, http_pull_model=True, xml_signature=False,
  142. report_only=False, profile_name='2.0b',
  143. transport_name='simpleHttp', transport_address=None, ven_id=None):
  144. """
  145. Take the neccessary steps to register this client with the server.
  146. :param bool http_pull_model: Whether to use the 'pull' model for HTTP.
  147. :param bool xml_signature: Whether to sign each XML message.
  148. :param bool report_only: Whether or not this is a reporting-only client which does not deal with Events.
  149. :param str profile_name: Which OpenADR profile to use.
  150. :param str transport_name: The transport name to use. Either 'simpleHttp' or 'xmpp'.
  151. :param str transport_address: Which public-facing address the server should use to communicate.
  152. :param str ven_id: The ID for this VEN. If you leave this blank, a VEN_ID will be assigned by the VTN.
  153. """
  154. request_id = new_request_id()
  155. service = 'EiRegisterParty'
  156. payload = {'ven_name': self.ven_name,
  157. 'http_pull_model': http_pull_model,
  158. 'xml_signature': xml_signature,
  159. 'report_only': report_only,
  160. 'profile_name': profile_name,
  161. 'transport_name': transport_name,
  162. 'transport_address': transport_address}
  163. if ven_id:
  164. payload['ven_id'] = ven_id
  165. message = create_message('oadrCreatePartyRegistration', request_id=new_request_id(), **payload)
  166. response_type, response_payload = await self._perform_request(service, message)
  167. if response_payload['response']['response_code'] != 200:
  168. status_code = response_payload['response']['response_code']
  169. status_description = response_payload['response']['response_description']
  170. print(f"Got error on Create Party Registration: {status_code} {status_description}")
  171. return
  172. self.ven_id = response_payload['ven_id']
  173. self.poll_frequency = response_payload['requested_oadr_poll_freq']
  174. print(f"VEN is now registered with ID {self.ven_id}")
  175. print(f"The polling frequency is {self.poll_frequency}")
  176. return response_type, response_payload
  177. async def cancel_party_registration(self):
  178. raise NotImplementedError("Cancel Registration is not yet implemented")
  179. async def request_event(self, reply_limit=1):
  180. """
  181. Request the next Event from the VTN, if it has any.
  182. """
  183. payload = {'request_id': new_request_id(),
  184. 'ven_id': self.ven_id,
  185. 'reply_limit': reply_limit}
  186. message = create_message('oadrRequestEvent', **payload)
  187. service = 'EiEvent'
  188. response_type, response_payload = await self._perform_request(service, message)
  189. return response_type, response_payload
  190. async def created_event(self, request_id, event_id, opt_type, modification_number=1):
  191. """
  192. Inform the VTN that we created an event.
  193. """
  194. service = 'EiEvent'
  195. payload = {'ven_id': self.ven_id,
  196. 'response': {'response_code': 200,
  197. 'response_description': 'OK',
  198. 'request_id': request_id},
  199. 'event_responses': [{'response_code': 200,
  200. 'response_description': 'OK',
  201. 'request_id': request_id,
  202. 'event_id': event_id,
  203. 'modification_number': modification_number,
  204. 'opt_type': opt_type}]}
  205. message = create_message('oadrCreatedEvent', **payload)
  206. response_type, response_payload = await self._perform_request(service, message)
  207. return response_type, response_payload
  208. async def register_report(self):
  209. """
  210. Tell the VTN about our reporting capabilities.
  211. """
  212. request_id = generate_id()
  213. payload = {'request_id': generate_id(),
  214. 'ven_id': self.ven_id,
  215. 'reports': self.reports}
  216. service = 'EiReport'
  217. message = create_message('oadrRegisterReport', **payload)
  218. response_type, response_payload = await self._perform_request(service, message)
  219. # Remember which reports the VTN is interested in
  220. return response_type, response_payload
  221. async def created_report(self):
  222. pass
  223. async def poll(self):
  224. """
  225. Request the next available message from the Server. This coroutine is called automatically.
  226. """
  227. service = 'OadrPoll'
  228. message = create_message('oadrPoll', ven_id=self.ven_id)
  229. response_type, response_payload = await self._perform_request(service, message)
  230. return response_type, response_payload
  231. async def update_report(self, report_id, resource_id=None):
  232. """
  233. Calls the previously registered report callable, and send the result as a message to the VTN.
  234. """
  235. if not resource_id:
  236. resource_ids = self.reports[report_id]['report_descriptions'].keys()
  237. elif isinstance(resource_id, str):
  238. resource_ids = [resource_id]
  239. else:
  240. resource_ids = resource_id
  241. value = self.reports[report_id]['callable'](resource_id)
  242. if iscoroutine(value):
  243. value = await value
  244. report_type = self.reports[report_id][resource_id]['report_type']
  245. for measurand in MEASURAND:
  246. if measurand in self.reports[report_id][resource_id]:
  247. item_base = measurand
  248. break
  249. report = {'report_id': report_id,
  250. 'report_descriptions': {resource_id: {MEASURANDS[measurand]: {'quantity': value,
  251. measurand: self.reports[report_id][resource_id][measurand]},
  252. 'report_type': self.reports[report_id][resource_id]['report_type'],
  253. 'reading_type': self.reports[report_id][resource_id]['reading_type']}},
  254. 'report_name': self.report['report_id']['report_name'],
  255. 'report_request_id': self.reports['report_id']['report_request_id'],
  256. 'report_specifier_id': self.report['report_id']['report_specifier_id'],
  257. 'created_date_time': datetime.now(timezone.utc)}
  258. service = 'EiReport'
  259. message = create_message('oadrUpdateReport', report)
  260. response_type, response_payload = self._perform_request(service, message)
  261. # We might get a oadrCancelReport message in this thing:
  262. if 'cancel_report' in response.payload:
  263. print("TODO: cancel this report")
  264. async def _perform_request(self, service, message):
  265. if self.debug:
  266. print(f"Client is sending {message}")
  267. url = f"{self.vtn_url}/{service}"
  268. async with self.client_session.post(url, data=message) as req:
  269. if req.status != HTTPStatus.OK:
  270. raise Exception(f"Received non-OK status in request: {req.status}")
  271. content = await req.read()
  272. if self.debug:
  273. print(content.decode('utf-8'))
  274. return parse_message(content)
  275. async def _on_event(self, message):
  276. if self.debug:
  277. print("ON_EVENT")
  278. result = self.on_event(message)
  279. if iscoroutine(result):
  280. result = await result
  281. if self.debug:
  282. print(f"Now responding with {result}")
  283. request_id = message['request_id']
  284. event_id = message['events'][0]['event_descriptor']['event_id']
  285. await self.created_event(request_id, event_id, result)
  286. return
  287. async def _on_report(self, message):
  288. result = self.on_report(message)
  289. if iscoroutine(result):
  290. result = await result
  291. return result
  292. async def _poll(self):
  293. response_type, response_payload = await self.poll()
  294. if response_type == 'oadrResponse':
  295. print("No events or reports available")
  296. return
  297. if response_type == 'oadrRequestReregistration':
  298. result = await self.create_party_registration()
  299. if response_type == 'oadrDistributeEvent':
  300. result = await self._on_event(response_payload)
  301. elif response_type == 'oadrUpdateReport':
  302. result = await self._on_report(response_payload)
  303. else:
  304. print(f"No handler implemented for message type {response_type}, ignoring.")
  305. await self._poll()