-
Notifications
You must be signed in to change notification settings - Fork 1
/
namespaces.py
102 lines (78 loc) · 2.53 KB
/
namespaces.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import re
from serial import SerialTimeoutException
import bowler
class Namespace(object):
_ORG = "(.*?)"
_LIB = "(.*?)(?:\.\*)?"
_VER = "(\d*\.\d*)"
_ID_RE = "{org}\.{lib};(?:{ver};)?;".format(org=_ORG,lib=_LIB,ver=_VER)
def __init__(self, dyio, index):
self._dyio = dyio
self.index = index
self.org,self.lib,self.ver,self.name = None,None,None,None
@staticmethod
def parse_id(id):
match = re.match(Namespace._ID_RE,id)
org,lib,ver = match.groups()
name = "{org}.{lib}".format(org=org,lib=lib)
return org,lib,ver,name
def send(self, func, args=[], priority=31, state=False, async=False, encrypted=False):
datagram = bowler.build_datagram(self._dyio.mac,func,args,priority,state,async,encrypted,self.index)
bowler.send_datagram(self._dyio.port,datagram)
# RETURN: func, args, priority, state, async, dir, encrypted
def receive(self):
return bowler.receive_datagram(self._dyio.port)
class BcsCore(Namespace):
def __init__(self, dyio):
Namespace.__init__(self,dyio,0)
id = self.get_namespace_id(0)
self.org,self.lib,self.ver,self.name = Namespace.parse_id(id)
def ping(self):
self.send("_png")
try:
func,args,priority,state,async,dir,encrypted = self.receive()
# self.receive()
except SerialTimeoutException:
return False
return True
def count_namespaces(self):
self.send("_nms")
func,args,priority,state,async,dir,encrypted = self.receive()
return bytes_to_int(args)
def get_namespace_id(self, index):
self.send("_nms",[index])
func,args,priority,state,async,dir,encrypted = self.receive()
return str(args)
def init_core(dyio):
global core
core = BcsCore(dyio)
# type("NAME", (Namespace,), {"__init__": lambda self,**kwargs: self.__dict__.update(kwargs)})
def count(dyio):
return core.count_namespaces()
def _ns_to_class_name(ns):
cls_name = ns[0].upper()
index = 1
old_index = 1
while '.' in ns[old_index:]:
index = ns.find('.',old_index)
cls_name += ns[old_index:index] + ns[index+1].upper()
old_index = index+2
return cls_name + ns[old_index:]
def get(dyio, index):
if index==0:
return core
else:
def __init__(self, dyio, index):
Namespace.__init__(self,dyio,index)
self.org = org
self.lib = lib
self.ver = ver
self.name = name
funcs = {"__init__":__init__}
ns_id = core.get_namespace_id(index)
org,lib,ver,name = Namespace.parse_id(ns_id)
cls_name = _ns_to_class_name(name)
ns = type(cls_name, (Namespace,), funcs)
return ns(dyio,index)
def bytes_to_int(bytearr):
return int("".join(["{:0>2}".format(byte) for byte in bytearray(bytearr)]),16)