-
Notifications
You must be signed in to change notification settings - Fork 22
/
pycgminer.py
53 lines (43 loc) · 1.4 KB
/
pycgminer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import socket
import json
class CgminerAPI(object):
""" Cgminer RPC API wrapper. """
def __init__(self, host='localhost', port=4028):
self.data = {}
self.host = host
self.port = port
def command(self, command, arg=None):
""" Initialize a socket connection,
send a command (a json encoded dict) and
receive the response (and decode it).
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((self.host, self.port))
payload = {"command": command}
if arg is not None:
# Parameter must be converted to basestring (no int)
payload.update({'parameter': unicode(arg)})
sock.send(json.dumps(payload))
received = self._receive(sock)
finally:
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return json.loads(received[:-1])
def _receive(self, sock, size=4096):
msg = ''
while 1:
chunk = sock.recv(size)
if chunk:
msg += chunk
else:
break
return msg
def __getattr__(self, attr):
""" Allow us to make command calling methods.
>>> cgminer = CgminerAPI()
>>> cgminer.summary()
"""
def out(arg=None):
return self.command(attr, arg)
return out