Fixed node id handling and discovery
[cerebrum.git] / pylibcerebrum / ganglion.py
blobac5a3b19de5cad90394c5b602a69bc8dcc9e89bf
1 #!/usr/bin/env python3
3 #Copyright (C) 2012 jaseg <s@jaseg.de>
5 #This program is free software; you can redistribute it and/or
6 #modify it under the terms of the GNU General Public License
7 #version 3 as published by the Free Software Foundation.
9 import json
10 import struct
11 try:
12 import lzma
13 except:
14 import pylzma as lzma
15 import time
16 import serial
17 from pylibcerebrum.NotifyList import NotifyList
18 from pylibcerebrum.timeout_exception import TimeoutException
20 """Call RPC functions on serially connected devices over the Cerebrum protocol."""
22 class Ganglion(object):
23 """Proxy class for calling remote methods on hardware connected through a serial port using the Cerebrum protocol"""
25 # NOTE: the device config is *not* the stuff from the config "dev" section but
26 #read from the device. It can also be found in that [devicename].config.json
27 #file created by the code generator
28 def __init__(self, node_id, jsonconfig=None, ser=None):
29 """Ganglion constructor
31 Keyword arguments:
32 device -- the device file to connect to
33 baudrate -- the baudrate to use (default 115200)
34 The other keyword arguments are for internal use only.
36 """
37 object.__setattr__(self, '_ser', ser)
38 object.__setattr__(self, 'node_id', node_id)
39 if not jsonconfig:
40 # get a config
41 i=0
42 while True:
43 try:
44 jsonconfig = self._read_config()
45 time.sleep(0.1)
46 break
47 except TimeoutException as e:
48 print('Timeout', e)
49 except ValueError as e:
50 print('That device threw some nasty ValueError\'ing JSON!', e)
51 i += 1
52 if i > 20:
53 raise serial.serialutil.SerialException('Could not connect, giving up after 20 tries')
54 # populate the object
55 object.__setattr__(self, 'members', {})
56 for name, member in jsonconfig.get('members', {}).items():
57 self.members[name] = Ganglion(node_id, jsonconfig=member, ser=self._ser)
58 object.__setattr__(self, 'properties', {})
59 for name, prop in jsonconfig.get('properties', {}).items():
60 self.properties[name] = (prop['id'], prop['fmt'], prop.get('access', 'rw'))
61 object.__setattr__(self, 'functions', {})
62 for name, func in jsonconfig.get('functions', {}).items():
63 def proxy_method(*args):
64 return self._callfunc(func["id"], func.get("args", ""), args, func.get("returns", ""))
65 self.functions[name] = proxy_method
66 object.__setattr__(self, 'type', jsonconfig.get('type', None))
67 object.__setattr__(self, 'config', { k: v for k,v in jsonconfig.items() if not k in ['members', 'properties', 'functions'] })
69 def __iter__(self):
70 """Construct an iterator to iterate over *all* (direct or not) child nodes of this node."""
71 return GanglionIter(self)
73 def _read_config(self):
74 """Fetch the device configuration descriptor from the device."""
75 with self._ser as s:
76 s.write(b'\\#' + struct.pack(">H", self.node_id) + b'\x00\x00\x00\x00')
77 (clen,) = struct.unpack(">H", s.read(2))
78 cbytes = s.read(clen)
79 #decide whether cbytes contains lzma or json depending on the first byte (which is used as a magic here)
80 if cbytes[0] is ord('#'):
81 return json.JSONDecoder().decode(str(lzma.decompress(cbytes[1:]), "utf-8"))
82 else:
83 return json.JSONDecoder().decode(str(cbytes, "utf-8"))
85 def _callfunc(self, fid, argsfmt, args, retfmt):
86 """Call a function on the device by id, directly passing argument/return format parameters."""
87 # Make a list out of the arguments if they are none
88 if not (isinstance(args, tuple) or isinstance(args, list)):
89 args = [args]
90 with self._ser as s:
91 # Send the encoded data
92 cmd = b'\\#' + struct.pack(">HHH", self.node_id, fid, struct.calcsize(argsfmt)) + struct.pack(argsfmt, *args)
93 s.write(cmd)
94 # payload length
95 (clen,) = struct.unpack(">H", s.read(2))
96 # payload data
97 cbytes = s.read(clen)
98 if clen != struct.calcsize(retfmt):
99 # CAUTION! This error is thrown not because the user supplied a wrong value but because the device answered in an unexpected manner.
100 # FIXME raise an error here or let the whole operation just fail in the following struct.unpack?
101 raise AttributeError("Device response format problem: Length mismatch: {} != {}".format(clen, struct.calcsize(retfmt)))
102 rv = struct.unpack(retfmt, cbytes)
103 # Try to interpret the return value in a useful manner
104 if len(rv) == 0:
105 return None
106 elif len(rv) == 1:
107 return rv[0]
108 else:
109 return list(rv)
111 def __dir__(self):
112 """Get a list of all attributes of this object. This includes virtual Cerebrum stuff like members, properties and functions."""
113 return list(self.members.keys()) + list(self.properties.keys()) + list(self.functions.keys()) + list(self.__dict__.keys())
115 # Only now add the setattr magic method so it does not interfere with the above code
116 def __setattr__(self, name, value):
117 """Magic method to set an attribute. This one even handles remote Cerebrum properties."""
118 #check if the name is a known property
119 if name in self.properties:
120 #call the property's Cerebrum setter function
121 varid, varfmt, access = self.properties[name]
122 if not "w" in access:
123 raise TypeError("{} is a read-only property".format(name))
124 return self._callfunc(varid+1, varfmt, value, "")
125 #if the above code falls through, do a normal __dict__ lookup.
126 self.__dict__[name] = value
129 def __getattr__(self, name):
130 """Magic method to get an attribute of this object, considering Cerebrum members, properties and functions.
132 At this point a hierarchy is imposed upon the members/properties/functions that is not present in the implementation:
134 Between a member, a property and a function of the same name the member will be preferred over the property and the property will be preferred over the function. If you should manage to make device have such colliding names, consider using _callfunc(...) directly.
137 if name in self.members:
138 return self.members[name]
140 if name in self.properties:
141 def cb(newx):
142 self.__setattr__(name, newx)
143 varid, varfmt, access = self.properties[name]
144 rv = self._callfunc(varid, "", (), varfmt)
145 # If the return value is a list, construct an auto-updating thingy from it.
146 if isinstance(rv, list):
147 return NotifyList(rv, callbacks=[cb])
148 else:
149 return rv
151 if name in self.functions:
152 return self.functions[name]
154 #If all of the above falls through...
155 raise AttributeError(name)
157 class GanglionIter:
158 """Iterator class for ganglions that recursively iterates over all (direct or indirect) child nodes of a given Ganglion"""
160 def __init__(self, g):
161 self.g = g
162 self.keyiter = g.members.__iter__()
163 self.miter = None
165 def __iter__(self):
166 return self
168 def __next__(self):
169 try:
170 return self.miter.__next__()
171 except StopIteration:
172 pass
173 except AttributeError:
174 pass
175 foo = self.g.__getattr__(self.keyiter.__next__())
176 self.miter = foo.__iter__()
177 return foo