-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterface.py
80 lines (72 loc) · 2.8 KB
/
interface.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""A file containing all of our interfaces.
Currently contains only Stats interface
"""
from redis import Redis
from redis.exceptions import ConnectionError
import time
__all__ = ['Stats']
class Stats(object):
"""Stats interface"""
r = Redis()
# XXX: Trying out the connection. A better way must be implemented to handle
# the redis server
try:
r.ping()
except ConnectionError:
print("Warning: Could not connect to redis server! Run setup() to configure")
# Default channel:
_c = 'statistics'
# XXX: This class reuses assert isinstance checks - there should be a better
# way to error handling!
@classmethod
def register(self, addr, timestamp=None):
"""Publishes a message to register the issuer"""
if not timestamp:
timestamp = time.time()
else:
assert isinstance(timestamp, float), 'parameter :time must be float'
self._publish(addr, 'register', timestamp)
@classmethod
def set_count(self, addr, op, value=1):
"""Publishes a message containg issuers' address, increase operation and value.
:addr -> string1
:op -> string, either 'recv', 'success' or 'error'
:value -> int,string, either int, '+' or '-'
"""
ops = ['recv', 'success', 'error']
if op not in ops: raise ValueError('Invalid value for parameter :op')
if value == "+": value = 1
elif value == "-": value = -1
assert isinstance(value, int), 'parameter :value must be integer'
self._publish(addr, op, value)
@classmethod
def set_time(self, addr, op, timestamp=None):
"""Publishes a message containg issuers' address, time operation and timestamp.
:addr -> string1
:op -> string, either 't_open' or 't_close'
:time -> float, should be time.time()
"""
ops = ['t_open','t_close']
if op not in ops: raise ValueError('Invalid value for parameter :op')
if not timestamp: timestamp = time.time()
else: assert isinstance(timestamp, float), 'parameter :time must be float'
self._publish(addr, op, timestamp)
@classmethod
def _publish(self, addr, op, value):
"""Helper method to prepare and publish the message"""
msg = "{} {} {}".format(str(addr), op, value)
try:
self.r.publish(self._c, msg)
except ConnectionError as err:
print("Connection Error: Could not publish message")
@classmethod
def set_channel(self, channel):
"""Sets the class channel for statistics"""
assert isinstance(channel, str), ':channel should be a string'
channel.strip()
if len(channel.split()) > 1: raise ValueError('Invalid value for :channel')
self._c = channel
@classmethod
def get_channel(self):
"""Used to retreive current class channel"""
return self._c