forked from ebroder/python-zephyr
/
zephyr.py
73 lines (53 loc) · 1.56 KB
/
zephyr.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
import _zephyr as _z
import os
import sys
from _zephyr import receive, ZNotice
__inited = False
is_py3 = sys.version_info.major >= 3
def init():
global __inited
if not __inited:
_z.initialize()
_z.openPort()
_z.cancelSubs()
__inited = True
def realm():
return _z.realm().decode('utf-8')
class Subscriptions(set):
"""
A set of <class, instance, recipient> tuples representing the
tuples that have been subbed to
Since subscriptions are shared across the entire process, this
class is a singleton
"""
def __new__(cls):
if not '_instance' in cls.__dict__:
cls._instance = super(Subscriptions, cls).__new__(cls)
init()
return cls._instance
def __del__(self):
_z.cancelSubs()
def _fixTuple(self, item):
if len(item) != 3:
raise TypeError('item is not a zephyr subscription tuple')
item = list(item)
if item[2].startswith('*'):
item[2] = item[2][1:]
if '@' not in item[2]:
item[2] += '@%s' % realm()
if is_py3:
item = [bytes(i, "utf-8") for i in item]
print(item)
return tuple(item)
def add(self, item):
item = self._fixTuple(item)
if item in self:
return
_z.sub(*item)
super(Subscriptions, self).add(item)
def remove(self, item):
item = self._fixTuple(item)
if item not in self:
raise KeyError(item)
_z.unsub(*item)
super(Subscriptions, self).remove(item)