blob: 7e812b1e412e237a18e10d199c4545604b982c6e [file] [log] [blame]
Todd Broche505b8d2011-03-21 18:19:54 -07001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""Servo Server."""
5import imp
6import logging
7import SimpleXMLRPCServer
8
9# TODO(tbroch) deprecate use of relative imports
Todd Broche505b8d2011-03-21 18:19:54 -070010import ftdigpio
11import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070012import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070013import ftdiuart
Todd Broche505b8d2011-03-21 18:19:54 -070014
15MAX_I2C_CLOCK_HZ = 100000
16
Todd Brochdbb09982011-10-02 07:14:26 -070017
Todd Broche505b8d2011-03-21 18:19:54 -070018class ServodError(Exception):
19 """Exception class for servod."""
20
21class Servod(object):
22 """Main class for Servo debug/controller Daemon."""
Todd Brochdbb09982011-10-02 07:14:26 -070023 def __init__(self, config, vendor, product, serialname=None, interfaces=None):
Todd Broche505b8d2011-03-21 18:19:54 -070024 """Servod constructor.
25
26 Args:
27 config: instance of SystemConfig containing all controls for
28 particular Servod invocation
29 vendor: usb vendor id of FTDI device
30 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070031 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070032 interfaces: list of strings of interface types the server will instantiate
33
34 Raises:
35 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070036 """
37 self._logger = logging.getLogger("Servod")
38 self._logger.debug("")
39 self._vendor = vendor
40 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070041 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070042 self._syscfg = config
43 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
44 # interfaces are mapped to
45 self._interface_list = []
46 # Dict of Dict to map control name, function name to to tuple (params, drv)
47 # Ex) _drv_dict[name]['get'] = (params, drv)
48 self._drv_dict = {}
49
Todd Brochdbb09982011-10-02 07:14:26 -070050 # Note, interface i is (i - 1) in list
51 if not interfaces:
52 interfaces = ftdi_common.INTERFACE_DEFAULTS[vendor][product]
53
54 for i, name in enumerate(interfaces):
55 self._logger.info("Initializing FTDI interface %d to %s", i + 1, name)
56 try:
57 func = getattr(self, '_init_%s' % name)
58 except AttributeError:
59 raise ServodError("Unable to locate init for interface %s" % name)
Todd Broch888da782011-10-07 14:29:09 -070060 result = func(i + 1)
61 if isinstance(result, tuple):
62 self._interface_list.extend(result)
63 else:
64 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -070065
Todd Brochb3048492012-01-15 21:52:41 -080066 def _init_dummy(self, interface):
67 """Initialize dummy interface.
68
69 Dummy interface is just a mechanism to reserve that interface for non servod
70 interaction. Typically the interface will be managed by external
71 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
72 interfaces.
73
74 TODO(tbroch): Investigate merits of incorporating these third-party
75 interfaces into servod or creating a communication channel between them
76
77 Returns: None
78 """
79 return None
80
Todd Broche505b8d2011-03-21 18:19:54 -070081 def _init_gpio(self, interface):
82 """Initialize gpio driver interface and open for use.
83
84 Args:
85 interface: interface number of FTDI device to use.
86
87 Returns:
88 Instance object of interface.
89 """
Todd Brochad034442011-05-25 15:05:29 -070090 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
91 self._serialname)
Todd Broche505b8d2011-03-21 18:19:54 -070092 fobj.open()
93 return fobj
94
95 def _init_i2c(self, interface):
96 """Initialize i2c interface and open for use.
97
98 Args:
99 interface: interface number of FTDI device to use
100
101 Returns:
102 Instance object of interface
103 """
Todd Brochad034442011-05-25 15:05:29 -0700104 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
105 self._serialname)
Todd Broche505b8d2011-03-21 18:19:54 -0700106 fobj.open()
107 # Set the frequency of operation of the i2c bus.
108 # TODO(tbroch) make configureable
109 fobj.setclock(MAX_I2C_CLOCK_HZ)
110 return fobj
111
Todd Broch47c43f42011-05-26 15:11:31 -0700112 def _init_uart(self, interface):
113 """Initialize uart inteface and open for use
114
115 Note, the uart runs in a separate thread (pthreads). Users wishing to
116 interact with it will query control for the pty's pathname and connect
117 with there favorite console program. For example:
118 cu -l /dev/pts/22
119
120 Args:
121 interface: interface number of FTDI device to use
122
123 Returns:
124 Instance object of interface
125 """
126 fobj = ftdiuart.Fuart(self._vendor, self._product, interface)
127 fobj.run()
128 self._logger.info("%s" % fobj.get_pty())
129 return fobj
130
Todd Broch888da782011-10-07 14:29:09 -0700131 def _init_gpiouart(self, interface):
132 """Initialize special gpio + uart interface and open for use
133
134 Note, the uart runs in a separate thread (pthreads). Users wishing to
135 interact with it will query control for the pty's pathname and connect
136 with there favorite console program. For example:
137 cu -l /dev/pts/22
138
139 Args:
140 interface: interface number of FTDI device to use
141
142 Returns:
143 Instance objects of interface
144 """
145 fgpio = self._init_gpio(interface)
146 fuart = ftdiuart.Fuart(self._vendor, self._product, interface, fgpio._fc)
147 fuart.run()
148 self._logger.info("uart pty: %s" % fuart.get_pty())
149 return fgpio, fuart
150
Todd Broche505b8d2011-03-21 18:19:54 -0700151 def _get_param_drv(self, control_name, is_get=True):
152 """Get access to driver for a given control.
153
154 Note, some controls have different parameter dictionaries for 'getting' the
155 control's value versus 'setting' it. Boolean is_get distinguishes which is
156 being requested.
157
158 Args:
159 control_name: string name of control
160 is_get: boolean to determine
161
162 Returns:
163 tuple (param, drv) where:
164 param: param dictionary for control
165 drv: instance object of driver for particular control
166
167 Raises:
168 ServodError: Error occurred while examining params dict
169 """
170 self._logger.debug("")
171 # if already setup just return tuple from driver dict
172 if control_name in self._drv_dict:
173 if is_get and ('get' in self._drv_dict[control_name]):
174 return self._drv_dict[control_name]['get']
175 if not is_get and ('set' in self._drv_dict[control_name]):
176 return self._drv_dict[control_name]['set']
177
178 params = self._syscfg.lookup_control_params(control_name, is_get)
179 if 'drv' not in params:
180 self._logger.error("Unable to determine driver for %s" % control_name)
181 raise ServodError("'drv' key not found in params dict")
182 if 'interface' not in params:
183 self._logger.error("Unable to determine interface for %s" %
184 control_name)
185
186 raise ServodError("'interface' key not found in params dict")
187 index = int(params['interface']) - 1
188 interface = self._interface_list[index]
189 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
190 drv_pkg = imp.load_module('drv',
191 *imp.find_module('drv', servo_pkg.__path__))
192 drv_name = params['drv']
193 drv_module = getattr(drv_pkg, drv_name)
194 drv_class = getattr(drv_module, drv_name)
195 drv = drv_class(interface, params)
196 if control_name not in self._drv_dict:
197 self._drv_dict[control_name] = {}
198 if is_get:
199 self._drv_dict[control_name]['get'] = (params, drv)
200 else:
201 self._drv_dict[control_name]['set'] = (params, drv)
202 return (params, drv)
203
204 def doc_all(self):
205 """Return all documenation for controls.
206
207 Returns:
208 string of <doc> text in config file (xml) and the params dictionary for
209 all controls.
210
211 For example:
212 warm_reset :: Reset the device warmly
213 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
214 """
215 return self._syscfg.display_config()
216
217 def doc(self, name):
218 """Retreive doc string in system config file for given control name.
219
220 Args:
221 name: name string of control to get doc string
222
223 Returns:
224 doc string of name
225
226 Raises:
227 NameError: if fails to locate control
228 """
229 self._logger.debug("name(%s)" % (name))
230 if self._syscfg.is_control(name):
231 return self._syscfg.get_control_docstring(name)
232 else:
233 raise NameError("No control %s" %name)
234
235 def get(self, name):
236 """Get control value.
237
238 Args:
239 name: name string of control
240
241 Returns:
242 Response from calling drv get method. Value is reformatted based on
243 control's dictionary parameters
244
245 Raises:
246 HwDriverError: Error occurred while using drv
247 """
248 self._logger.debug("name(%s)" % (name))
249 (param, drv) = self._get_param_drv(name)
250 try:
251 val = drv.get()
252 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800253 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700254 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700255 except AttributeError, error:
256 self._logger.error("Getting %s: %s" % (name, error))
257 raise
Todd Broche505b8d2011-03-21 18:19:54 -0700258 except drv.hw_driver.HwDriverError:
259 self._logger.error("Getting %s" % (name))
260 raise
261 def get_all(self, verbose):
262 """Get all controls values.
263
264 Args:
265 verbose: Boolean on whether to return doc info as well
266
267 Returns:
268 string creating from trying to get all values of all controls. In case of
269 error attempting access to control, response is 'ERR'.
270 """
271 rsp = ""
272 for name in self._syscfg.syscfg_dict['control']:
273 self._logger.debug("name = %s" %name)
274 try:
275 value = self.get(name)
276 except Exception:
277 value = "ERR"
278 pass
279 if verbose:
280 rsp += "GET %s = %s :: %s\n" % (name, value, self.doc(name))
281 else:
282 rsp += "%s:%s\n" % (name, value)
283 return rsp
284
285 def set(self, name, wr_val_str):
286 """Set control.
287
288 Args:
289 name: name string of control
290 wr_val_str: value string to write. Can be integer, float or a
291 alpha-numerical that is mapped to a integer or float.
292
293 Raises:
294 HwDriverError: Error occurred while using driver
295 """
296 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
297 (params, drv) = self._get_param_drv(name, False)
298 wr_val = self._syscfg.resolve_val(params, wr_val_str)
299 try:
300 drv.set(wr_val)
301 except drv.hw_driver.HwDriverError:
302 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
303 raise
304 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
305 # & client I still have to return something to appease the
306 # marshall/unmarshall
307 return True
308
309 def echo(self, echo):
310 """Dummy echo function for testing/examples.
311
312 Args:
313 echo: string to echo back to client
314 """
315 self._logger.debug("echo(%s)" % (echo))
316 return "ECH0ING: %s" % (echo)
317
Todd Brochdbb09982011-10-02 07:14:26 -0700318
Todd Broche505b8d2011-03-21 18:19:54 -0700319def test():
320 """Integration testing.
321
322 TODO(tbroch) Enhance integration test and add unittest (see mox)
323 """
324 logging.basicConfig(level=logging.DEBUG,
325 format="%(asctime)s - %(name)s - " +
326 "%(levelname)s - %(message)s")
327 # configure server & listen
328 servod_obj = Servod(1)
329 # 4 == number of interfaces on a FT4232H device
330 for i in xrange(4):
331 if i == 1:
332 # its an i2c interface ... see __init__ for details and TODO to make
333 # this configureable
334 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
335 else:
336 # its a gpio interface
337 servod_obj._interface_list[i].wr_rd(0)
338
339 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
340 allow_none=True)
341 server.register_introspection_functions()
342 server.register_multicall_functions()
343 server.register_instance(servod_obj)
344 logging.info("Listening on localhost port 9999")
345 server.serve_forever()
346
347if __name__ == "__main__":
348 test()
349
350 # simple client transaction would look like
351 """
352 remote_uri = 'http://localhost:9999'
353 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
354 send_str = "Hello_there"
355 print "Sent " + send_str + ", Recv " + client.echo(send_str)
356 """