messaging.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 xmltodict
  13. from jinja2 import Environment, PackageLoader, select_autoescape
  14. from .utils import *
  15. from .signature import *
  16. from .preflight import preflight_message
  17. def parse_message(data):
  18. """
  19. Parse a message and distill its usable parts. Returns a message type and payload.
  20. """
  21. message_dict = xmltodict.parse(data, process_namespaces=True, namespaces=NAMESPACES)
  22. message_type, message_payload = message_dict['oadrPayload']['oadrSignedObject'].popitem()
  23. return message_type, normalize_dict(message_payload)
  24. def create_message(message_type, **message_payload):
  25. """
  26. This creates an OpenADR message. This consists
  27. """
  28. preflight_message(message_type, message_payload)
  29. signed_object = indent_xml(TEMPLATES.get_template(f'{message_type}.xml').render(**message_payload))
  30. signature = create_signature(signed_object)
  31. envelope = TEMPLATES.get_template('oadrPayload.xml')
  32. msg = envelope.render(template=f'{message_type}',
  33. signature=signature,
  34. signed_object=signed_object)
  35. return msg
  36. # Settings for jinja2
  37. TEMPLATES = Environment(loader=PackageLoader('pyopenadr', 'templates'))
  38. TEMPLATES.filters['datetimeformat'] = datetimeformat
  39. TEMPLATES.filters['timedeltaformat'] = timedeltaformat
  40. TEMPLATES.filters['booleanformat'] = booleanformat
  41. # Settings for xmltodict
  42. NAMESPACES = {
  43. 'http://docs.oasis-open.org/ns/energyinterop/201110': None,
  44. 'http://openadr.org/oadr-2.0b/2012/07': None,
  45. 'urn:ietf:params:xml:ns:icalendar-2.0': None,
  46. 'http://docs.oasis-open.org/ns/energyinterop/201110/payloads': None,
  47. 'http://docs.oasis-open.org/ns/emix/2011/06': None,
  48. 'urn:ietf:params:xml:ns:icalendar-2.0:stream': None,
  49. 'http://docs.oasis-open.org/ns/emix/2011/06/power': None,
  50. 'http://docs.oasis-open.org/ns/emix/2011/06/siscale': None,
  51. 'http://www.w3.org/2000/09/xmldsig#': None,
  52. 'http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties': None
  53. }