server.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. from aiohttp import web
  13. from pyopenadr.service import EventService, PollService, RegistrationService, ReportService, OptService
  14. class OpenADRServer:
  15. _MAP = {'on_created_event': EventService,
  16. 'on_request_event': EventService,
  17. 'on_register_report': ReportService,
  18. 'on_create_report': ReportService,
  19. 'on_created_report': ReportService,
  20. 'on_request_report': ReportService,
  21. 'on_update_report': ReportService,
  22. 'on_poll': PollService,
  23. 'on_query_registration': RegistrationService,
  24. 'on_create_party_registration': RegistrationService,
  25. 'on_cancel_party_registration': RegistrationService}
  26. def __init__(self, vtn_id):
  27. self.app = web.Application()
  28. self.services = {'event_service': EventService(vtn_id),
  29. 'report_service': ReportService(vtn_id),
  30. 'poll_service': PollService(vtn_id),
  31. 'opt_service': OptService(vtn_id),
  32. 'registration_service': RegistrationService(vtn_id)}
  33. self.app.add_routes([web.post(f"/OpenADR2/Simple/2.0b/{s.__service_name__}", s.handler) for s in self.services.values()])
  34. self.__setattr__ = self.add_handler
  35. def run(self):
  36. """
  37. Starts the asyncio-loop and runs the server in it. This function is
  38. blocking. For other ways to run the server in a more flexible context,
  39. please refer to the `aiohttp documentation
  40. <https://docs.aiohttp.org/en/stable/web_advanced.html#aiohttp-web-app-runners>`_.
  41. """
  42. web.run_app(self.app)
  43. def add_handler(self, name, func):
  44. """
  45. Add a handler to the OpenADRServer.
  46. """
  47. print("Called add_handler", name, func)
  48. if name in self._MAP:
  49. setattr(self._MAP[name], name, staticmethod(func))
  50. else:
  51. raise NameError(f"Unknown handler {name}. Correct handler names are: {self._MAP.keys()}")