server.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. .. _server:
  2. ======
  3. Server
  4. ======
  5. If you are implementing an OpenADR Server ("Virtual Top Node") using OpenLEADR, read this page.
  6. .. _server_example:
  7. 1-minute VTN example
  8. ====================
  9. Here's an example of a server that accepts registrations from a VEN named
  10. 'ven_123', requests all reports that it offers, and creates an Event for this
  11. VEN.
  12. .. code-block:: python3
  13. import asyncio
  14. from datetime import datetime, timezone, timedelta
  15. from openleadr import OpenADRServer, enable_default_logging
  16. from functools import partial
  17. enable_default_logging()
  18. async def on_create_party_registration(registration_info):
  19. """
  20. Inspect the registration info and return a ven_id and registration_id.
  21. """
  22. if registration_info['ven_name'] == 'ven123':
  23. ven_id = 'ven_id_123'
  24. registration_id = 'reg_id_123'
  25. return ven_id, registration_id
  26. else:
  27. return False
  28. async def on_register_report(ven_id, resource_id, measurement, unit, scale,
  29. min_sampling_interval, max_sampling_interval):
  30. """
  31. Inspect a report offering from the VEN and return a callback and sampling interval for receiving the reports.
  32. """
  33. callback = partial(on_update_report, ven_id=ven_id, resource_id=resource_id, measurement=measurement)
  34. sampling_interval = min_sampling_interval
  35. return callback, sampling_interval
  36. async def on_update_report(data, ven_id, resource_id, measurement):
  37. """
  38. Callback that receives report data from the VEN and handles it.
  39. """
  40. for time, value in data:
  41. print(f"Ven {ven_id} reported {measurement} = {value} at time {time} for resource {resource_id}")
  42. async def event_response_callback(ven_id, event_id, opt_type):
  43. """
  44. Callback that receives the response from a VEN to an Event.
  45. """
  46. print(f"VEN {ven_id} responded to Event {event_id} with: {opt_type}")
  47. # Create the server object
  48. server = OpenADRServer(vtn_id='myvtn')
  49. # Add the handler for client (VEN) registrations
  50. server.add_handler('on_create_party_registration', on_create_party_registration)
  51. # Add the handler for report registrations from the VEN
  52. server.add_handler('on_register_report', on_register_report)
  53. # Add a prepared event for a VEN that will be picked up when it polls for new messages.
  54. server.add_event(ven_id='ven_id_123',
  55. signal_name='simple',
  56. signal_type='level',
  57. intervals=[{'dtstart': datetime(2021, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
  58. 'duration': timedelta(minutes=10),
  59. 'signal_payload': 1}],
  60. callback=event_response_callback)
  61. # Run the server on the asyncio event loop
  62. loop = asyncio.get_event_loop()
  63. loop.create_task(server.run())
  64. loop.run_forever()
  65. Read on for more details!
  66. .. _server_registration:
  67. Registration
  68. ============
  69. If a client (VEN) wants to register for the first time, it will go through a Registration procedure.
  70. .. admonition:: Implementation Checklist
  71. 1. Create a handler that decides what to do with new registrations, based on their registration info.
  72. The client will send a :ref:`oadrQueryRegistration` message. The server will respond with a :ref:`oadrCreatedPartyRegistration` message containing a list of its capabilities, notably the implemented OpenADR protocol versions and the available Transport Mechanisms (HTTP and/or XMPP).
  73. The client will then usually send a :ref:`oadrCreatePartyRegistration` message, in which it registers to a specific OpenADR version and Transport Method. The server must then decide what it wants to do with this registration.
  74. In the case that the registration is accepted, the VTN will generate a venID and a RegistrationID for this VEN and respond with a :ref:`oadrCreatedPartyRegistration` message.
  75. In your application, when a VEN sends a :ref:`oadrCreatePartyRegistration` request, it will call your ``on_create_party_registration`` handler. This handler must somehow look up what to do with this request, and respond with a ``ven_id, registration_id`` tuple.
  76. Example implementation:
  77. .. code-block:: python3
  78. from openleadr.utils import generate_id
  79. async def on_create_party_registration(payload):
  80. ven_name = payload['ven_name']
  81. # Check whether or not this VEN is allowed to register
  82. result = await database.query("""SELECT COUNT(*)
  83. FROM vens
  84. WHERE ven_name = ?""",
  85. (payload['ven_name'],))
  86. if result == 1:
  87. # Generate an ID for this registration
  88. ven_id = generate_id()
  89. registration_id = generate_id()
  90. # Store the registration in a database (pseudo-code)
  91. await database.query("""UPDATE vens
  92. SET ven_id = ?
  93. registration_id = ?
  94. WHERE ven_name = ?""",
  95. (ven_id, registration_id, ven_name))
  96. # Return the registration ID.
  97. # This will be put into the correct form by the OpenADRServer.
  98. return ven_id, registration_id
  99. .. _server_events:
  100. Events
  101. ======
  102. The server (VTN) is expected to know when it needs to inform the clients (VENs) of certain events that they must respond to. This could be a predicted shortage or overage of available power in a certain electricity grid area, for example.
  103. The easiest way to supply events to a VEN is by using OpenLEADR's built-in message queing system. You simply add an event for a ven using the ``server.add_event`` method. You supply the ven_id for which the event is required, as well as the ``signal_name``, ``signal_type``, ``intervals`` and ``targets``. This will build an event object with a single signal for a VEN. If you need more flexibility, you can alternatively construct the event dictionary yourself and supply it directly to the ``add_raw_event`` method.
  104. The VEN can decide whether to opt in or opt out of the event. To be notified of their opt status, you supply a callback handler which will be called when the VEN has responded to the event request.
  105. .. code-block:: python3
  106. from openleadr import OpenADRServer
  107. from functools import partial
  108. from datetime import datetime, timezzone
  109. async def event_callback(ven_id, event_id, opt_status):
  110. print(f"VEN {ven_id} responded {opt_status} to event {event_id}")
  111. server = OpenADRServer(vtn_id='myvtn')
  112. event_id = server.add_event(ven_id='ven123',
  113. signal_name='simple',
  114. signal_type='level',
  115. intervals=[{'dtstart': datetime(2020. 1, 1, 12, 0, 0, tzinfo=timezone.utc),
  116. 'signal_payload': 1},
  117. {'dtstart': datetime(2020. 1, 1, 12, 15, 0, tzinfo=timezone.utc),
  118. 'signal_payload': 0}],
  119. target=[{'resource_id': 'Device001'}],
  120. callback=event_callback)
  121. Alternatively, you can use the handy constructors in ``openleadr.objects`` to format parts of the event:
  122. .. code-block:: python3
  123. from openleadr import OpenADRServer
  124. from openleadr.objects import Target, Interval
  125. from datetime import datetime, timezone
  126. from functools import partial
  127. async def event_callback(ven_id, event_id, opt_status):
  128. print(f"VEN {ven_id} responded {opt_status} to event {event_id}")
  129. server = OpenADRServer(vtn_id='myvtn')
  130. event_id = server.add_event(ven_id='ven123',
  131. signal_name='simple',
  132. signal_type='level',
  133. intervals=[Interval(dtstart=datetime(2020, 1, 1, 12, 15, 0, tzinfo=timezone.utc),
  134. signal_payload=0),
  135. Interval(dtstart=datetime(2020, 1, 1, 12, 15, 0, tzinfo=timezone.utc),
  136. signal_payload=1)]
  137. target=[Target(resource_id='Device001')],
  138. callback=event_callback)
  139. If you want to add a "raw" event directly, you can use this example as a guid:
  140. .. code-block:: python3
  141. from openleadr import OpenADRServer
  142. from openleadr.objects import Event, EventDescriptor, EventSignal, Target, Interval
  143. from datetime import datetime, timezone
  144. from functools import partial
  145. async def event_callback(ven_id, event_id, opt_status):
  146. print(f"VEN {ven_id} responded {opt_status} to event {event_id}")
  147. server = OpenADRServer(vtn_id='myvtn')
  148. event = Event(event_descriptor=EventDescriptor(event_id='event001',
  149. modification_number=0,
  150. event_status='far',
  151. market_context='http://marketcontext01'),
  152. event_signals=[EventSignal(signal_id='signal001',
  153. signal_type='level',
  154. signal_name='simple',
  155. intervals=[Interval(dtstart=now,
  156. duration=datetime.timedelta(minutes=10),
  157. signal_payload=1)]),
  158. EventSignal(signal_id='signal002',
  159. signal_type='price',
  160. signal_name='ELECTRICITY_PRICE',
  161. intervals=[Interval(dtstart=now,
  162. duration=datetime.timedelta(minutes=10),
  163. signal_payload=1)])],
  164. targets=[objects.Target(ven_id='ven123')])
  165. server.add_raw_event(ven_id='ven123', event=event, callback=event_callback)
  166. If you want to add an event and wait for the response in a single coroutine, you can pass an asyncio Future instead of a function or coroutine as the callback argument:
  167. .. code-block:: python3
  168. import asyncio
  169. ...
  170. async def generate_event():
  171. loop = asyncio.get_event_loop()
  172. opt_status_future = loop.create_future()
  173. server.add_event(..., callback=opt_status_future)
  174. opt_status = await opt_status_future
  175. print(f"The opt status for this event is {opt_status}")
  176. A word on event targets
  177. -----------------------
  178. The Target of your Event is an indication for the VEN which resources or devices should be affected. You can supply the target of the event in serveral ways:
  179. - Assigning the ``target`` parameter with a single ``objects.Target`` object.
  180. - Assigning the ``targets`` parameter with a list of ``objects.Target`` objects.
  181. - Assigning the ``targets_by_type`` parameters with a dict, that lists targets grouped by their type, like this:
  182. .. code-block:: python3
  183. server.add_event(...
  184. targets_by_type={'resource_id': ['resource01', 'resource02'],
  185. 'group_id': ['group01', 'group02']}
  186. )
  187. If you dont assign any Target, the target will be set to the ``ven_id`` that you specified.
  188. .. _server_reports:
  189. Reports
  190. =======
  191. Please see the :ref:`reporting` section.
  192. .. _server_implement:
  193. Things you should implement
  194. ===========================
  195. You should implement the following handlers:
  196. - ``on_create_party_registration(registration_info)``
  197. - ``on_register_report(ven_id, resource_id, measurement, unit, scale, min_sampling_interval, max_sampling_interval)``
  198. Optionally:
  199. - ``on_poll(ven_id)``; only if you don't want to use the internal message queue.
  200. .. _server_signing_messages:
  201. Signing Messages
  202. ================
  203. The OpenLEADR can sign your messages and validate incoming messages. For some background, see the :ref:`message_signing`.
  204. Example implementation:
  205. .. code-block:: python3
  206. from openleadr import OpenADRServr
  207. def fingerprint_lookup(ven_id):
  208. # Look up the certificate fingerprint that is associated with this VEN.
  209. fingerprint = database.lookup('certificate_fingerprint').where(ven_id=ven_id) # Pseudo code
  210. return fingerprint
  211. server = OpenADRServer(vtn_id='MyVTN',
  212. cert='/path/to/cert.pem',
  213. key='/path/to/private/key.pem',
  214. passphrase='mypassphrase',
  215. fingerprint_lookup=fingerprint_lookup)
  216. The VEN's fingerprint should be obtained from the VEN outside of OpenADR.
  217. .. _server_message_handlers:
  218. Message Handlers
  219. ================
  220. Your server has to deal with the different OpenADR messages. The way this works is that OpenLEADR will expose certain modules at the appropriate endpoints (like /oadrPoll and /EiRegister), and figure out what type of message is being sent. It will then call your handler with the contents of the message that are relevant for you to handle. This section provides an overview with examples for the different kinds of messages that you can expect and what should be returned.
  221. .. _server_on_register_report:
  222. on_register_report
  223. ------------------
  224. The VEN informs you which reports it has available. If you want to periodically receive any of these reports, you should return a list of the r_ids that you want to receive.
  225. Signature:
  226. .. code-block:: python3
  227. async def on_register_report(ven_id, resource_id, measurement, unit, scale,
  228. min_sampling_interval, max_sampling_interval):
  229. # If we want this report:
  230. return (callback, requested_sampling_interval)
  231. # or
  232. return None
  233. .. _server_on_query_registration:
  234. on_query_registration
  235. ---------------------
  236. A prospective VEN is requesting information about your VTN, like the versions and transports you support. You should not implement this handler and let OpenLEADR handle this response.
  237. .. _server_on_create_party_registration:
  238. on_create_party_registration
  239. ----------------------------
  240. The VEN tries to register with you. You will receive a registration_info dict that contains, among other things, a field `ven_name` which is how the VEN identifies itself. If the VEN is accepted, you return a ``ven_id, registration_id`` tuple. If not, return ``False``:
  241. .. code-block:: python3
  242. async def on_create_party_registration(registration_info):
  243. ven_name = registration_info['ven_name']
  244. ...
  245. if ven_is_known:
  246. return ven_id, registration_id
  247. else
  248. return None
  249. During this step, the VEN probably does not have a ``venID`` yet. If they connected using a secure TLS connection, the ``registration_info`` dict will contain the fingerprint of the public key that was used for this connection (``registration_info['fingerprint']``). Your ``on_create_party_registration`` handler should check this fingerprint value against a value that you received offline, to be sure that the ven with this venName is the correct VEN.
  250. .. _server_on_cancel_party_registration:
  251. on_cancel_party_registration
  252. ----------------------------
  253. The VEN informs you that they are cancelling their registration and no longer wish to be contacted by you.
  254. You should deregister the VEN internally, and return `None`.
  255. Return: ``None``
  256. .. _server_on_poll:
  257. on_poll
  258. -------
  259. You only need to implement this if you don't want to use the automatic internal message queue. If you add this handler to the server, the internal message queue will be automatically disabled.
  260. The VEN is requesting the next message that you have for it. You should return a tuple of message_type and message_payload as a dict. If there is no message for the VEN, you should return `None`.
  261. Signature:
  262. .. code-block:: python3
  263. async def on_poll(ven_id):
  264. ...
  265. return message_type, message_payload
  266. If you implement your own on_poll handler, you should also include your own ``on_created_event`` handler that retrieves the opt status for a distributed event.
  267. .. _server_on_created_event:
  268. on_created_event
  269. ----------------
  270. You only need to implement this if you don't want to use the automatic internal message queue. Otherwise, you supply a per-event callback function when you add the event to the internal queue.
  271. Signature:
  272. .. code-block:: python3
  273. async def on_created_event(ven_id, event_id, opt_status):
  274. print("Ven {ven_id} returned {opt_status} for event {event_id}")
  275. # return None