nodetool.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # This file is part of DarkFi (https://dark.fi)
  2. #
  3. # Copyright (C) 2020-2023 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 asyncio, json, random, sys
  18. class JsonRpc:
  19. async def start(self, server, port):
  20. reader, writer = await asyncio.open_connection(server, port)
  21. self.reader = reader
  22. self.writer = writer
  23. async def stop(self):
  24. self.writer.close()
  25. await self.writer.wait_closed()
  26. async def _make_request(self, method, params):
  27. ident = random.randint(0, 2**16)
  28. print(ident)
  29. request = {
  30. "jsonrpc": "2.0",
  31. "method": method,
  32. "params": params,
  33. "id": ident
  34. }
  35. message = json.dumps(request) + "\n"
  36. self.writer.write(message.encode())
  37. await self.writer.drain()
  38. data = await self.reader.readline()
  39. message = data.decode()
  40. response = json.loads(message)
  41. print(response)
  42. return "hello"
  43. #return response["result"]
  44. async def ping(self):
  45. return await self._make_request("ping", [])
  46. async def dnet_switch(self, state):
  47. return await self._make_request("dnet.switch", [state])
  48. async def dnet_subscribe_events(self):
  49. return await self._make_request("dnet.subscribe_events", [])
  50. #async def dnet_info(self):
  51. # return await self._make_request("dnet_info", [])
  52. async def main(argv):
  53. rpc = JsonRpc()
  54. await rpc.start("localhost", 26660)
  55. await rpc.dnet_switch(True)
  56. await rpc.dnet_subscribe_events()
  57. while True:
  58. data = await rpc.reader.readline()
  59. #print(await rpc.dnet_info())
  60. await rpc.dnet_switch(False)
  61. await rpc.stop()
  62. asyncio.run(main(sys.argv))