Untitled


SUBMITTED BY: Guest

DATE: Nov. 1, 2013, 11:05 p.m.

FORMAT: Python

SIZE: 1.7 kB

HITS: 893

  1. ## This class talks with CGMiner RPC deamons.
  2. ## All congratz to Thomas Sileo for his class
  3. ## Source : http://thomassileo.com/blog/2013/09/17/playing-with-python-and-cgminer-rpc-api/
  4. class CgminerAPI(object):
  5. """ Cgminer RPC API wrapper. """
  6. def __init__(self, host='localhost', port=4028):
  7. self.data = {}
  8. self.host = host
  9. self.port = port
  10. def command(self, command, arg=None):
  11. """ Initialize a socket connection,
  12. send a command (a json encoded dict) and
  13. receive the response (and decode it).
  14. """
  15. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  16. try:
  17. sock.connect((self.host, self.port))
  18. sock.settimeout(2)
  19. payload = {"command": command}
  20. if arg is not None:
  21. # Parameter must be converted to basestring (no int)
  22. payload.update({'parameter': unicode(arg)})
  23. sock.send(json.dumps(payload))
  24. received = self._receive(sock)
  25. finally:
  26. sock.shutdown(socket.SHUT_RDWR)
  27. sock.close()
  28. return json.loads(received[:-1])
  29. def _receive(self, sock, size=4096):
  30. msg = ''
  31. while 1:
  32. chunk = sock.recv(size)
  33. if chunk:
  34. msg += chunk
  35. else:
  36. break
  37. return msg
  38. def __getattr__(self, attr):
  39. def out(arg=None):
  40. return self.command(attr, arg)
  41. return out

comments powered by Disqus