rpc.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # This file is part of DarkFi (https://dark.fi)
  2. #
  3. # Copyright (C) 2020-2026 Dyne.org foundation
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import json
  18. import random
  19. import asyncio
  20. class JsonRpc:
  21. async def start(self, server, port):
  22. reader, writer = await asyncio.open_connection(server, port, limit=1024 ** 3)
  23. self.reader = reader
  24. self.writer = writer
  25. async def stop(self):
  26. self.writer.close()
  27. await self.writer.wait_closed()
  28. async def _make_request(self, method, params):
  29. ident = random.randint(0, 2**16)
  30. #print(ident)
  31. request = {
  32. "jsonrpc": "2.0",
  33. "method": method,
  34. "params": params,
  35. "id": ident,
  36. }
  37. message = json.dumps(request) + "\n"
  38. self.writer.write(message.encode())
  39. await self.writer.drain()
  40. data = await self.reader.readline()
  41. message = data.decode().strip()
  42. response = json.loads(message)
  43. #print(response)
  44. return response
  45. async def _subscribe(self, method, params):
  46. ident = random.randint(0, 2**16)
  47. request = {
  48. "jsonrpc": "2.0",
  49. "method": method,
  50. "params": params,
  51. "id": ident,
  52. }
  53. message = json.dumps(request) + "\n"
  54. self.writer.write(message.encode())
  55. await self.writer.drain()
  56. #print("Subscribed")
  57. async def ping(self):
  58. return await self._make_request("ping", [])
  59. async def deg_switch(self, state):
  60. return await self._make_request("deg.switch", [state])
  61. async def deg_subscribe_events(self):
  62. return await self._subscribe("deg.subscribe_events", [])