blob: 4707a2df52eb4470f4489f56c22267a613e6146e [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
Todd Broch7a91c252012-02-03 12:37:45 -08008import time
Todd Broche505b8d2011-03-21 18:19:54 -07009
10# TODO(tbroch) deprecate use of relative imports
Todd Broche505b8d2011-03-21 18:19:54 -070011import ftdigpio
12import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070013import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070014import ftdiuart
Todd Broche505b8d2011-03-21 18:19:54 -070015
16MAX_I2C_CLOCK_HZ = 100000
17
Todd Brochdbb09982011-10-02 07:14:26 -070018
Todd Broche505b8d2011-03-21 18:19:54 -070019class ServodError(Exception):
20 """Exception class for servod."""
21
22class Servod(object):
23 """Main class for Servo debug/controller Daemon."""
Todd Brochdbb09982011-10-02 07:14:26 -070024 def __init__(self, config, vendor, product, serialname=None, interfaces=None):
Todd Broche505b8d2011-03-21 18:19:54 -070025 """Servod constructor.
26
27 Args:
28 config: instance of SystemConfig containing all controls for
29 particular Servod invocation
30 vendor: usb vendor id of FTDI device
31 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070032 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070033 interfaces: list of strings of interface types the server will instantiate
34
35 Raises:
36 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070037 """
38 self._logger = logging.getLogger("Servod")
39 self._logger.debug("")
40 self._vendor = vendor
41 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070042 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070043 self._syscfg = config
44 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
45 # interfaces are mapped to
46 self._interface_list = []
47 # Dict of Dict to map control name, function name to to tuple (params, drv)
48 # Ex) _drv_dict[name]['get'] = (params, drv)
49 self._drv_dict = {}
50
Todd Brochdbb09982011-10-02 07:14:26 -070051 # Note, interface i is (i - 1) in list
52 if not interfaces:
53 interfaces = ftdi_common.INTERFACE_DEFAULTS[vendor][product]
54
55 for i, name in enumerate(interfaces):
Todd Broch8a77a992012-01-27 09:46:08 -080056 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
57 if i and ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
58 self._product += 1
59 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
60 self._product)
61
Todd Brochdbb09982011-10-02 07:14:26 -070062 self._logger.info("Initializing FTDI interface %d to %s", i + 1, name)
63 try:
64 func = getattr(self, '_init_%s' % name)
65 except AttributeError:
66 raise ServodError("Unable to locate init for interface %s" % name)
Todd Brocha9c74692012-01-24 22:54:22 -080067 result = func((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1)
Todd Broch888da782011-10-07 14:29:09 -070068 if isinstance(result, tuple):
69 self._interface_list.extend(result)
70 else:
71 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -070072
Todd Brocha9c74692012-01-24 22:54:22 -080073
Todd Brochb3048492012-01-15 21:52:41 -080074 def _init_dummy(self, interface):
75 """Initialize dummy interface.
76
77 Dummy interface is just a mechanism to reserve that interface for non servod
78 interaction. Typically the interface will be managed by external
79 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
80 interfaces.
81
82 TODO(tbroch): Investigate merits of incorporating these third-party
83 interfaces into servod or creating a communication channel between them
84
85 Returns: None
86 """
87 return None
88
Todd Broche505b8d2011-03-21 18:19:54 -070089 def _init_gpio(self, interface):
90 """Initialize gpio driver interface and open for use.
91
92 Args:
93 interface: interface number of FTDI device to use.
94
95 Returns:
96 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -070097
98 Raises:
99 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700100 """
Todd Brochad034442011-05-25 15:05:29 -0700101 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
102 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700103 try:
104 fobj.open()
105 except ftdigpio.FgpioError as e:
106 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
107
Todd Broche505b8d2011-03-21 18:19:54 -0700108 return fobj
109
110 def _init_i2c(self, interface):
111 """Initialize i2c interface and open for use.
112
113 Args:
114 interface: interface number of FTDI device to use
115
116 Returns:
117 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700118
119 Raises:
120 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700121 """
Todd Brochad034442011-05-25 15:05:29 -0700122 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
123 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700124 try:
125 fobj.open()
126 except ftdii2c.Fi2cError as e:
127 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
128
Todd Broche505b8d2011-03-21 18:19:54 -0700129 # Set the frequency of operation of the i2c bus.
130 # TODO(tbroch) make configureable
131 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700132
Todd Broche505b8d2011-03-21 18:19:54 -0700133 return fobj
134
Todd Broch47c43f42011-05-26 15:11:31 -0700135 def _init_uart(self, interface):
136 """Initialize uart inteface and open for use
137
138 Note, the uart runs in a separate thread (pthreads). Users wishing to
139 interact with it will query control for the pty's pathname and connect
140 with there favorite console program. For example:
141 cu -l /dev/pts/22
142
143 Args:
144 interface: interface number of FTDI device to use
145
146 Returns:
147 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700148
149 Raises:
150 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700151 """
152 fobj = ftdiuart.Fuart(self._vendor, self._product, interface)
Todd Broch6de9dc62012-04-09 15:23:53 -0700153 try:
154 fobj.run()
155 except ftdiuart.FuartError as e:
156 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
157
Todd Broch47c43f42011-05-26 15:11:31 -0700158 self._logger.info("%s" % fobj.get_pty())
159 return fobj
160
Todd Broch888da782011-10-07 14:29:09 -0700161 def _init_gpiouart(self, interface):
162 """Initialize special gpio + uart interface and open for use
163
164 Note, the uart runs in a separate thread (pthreads). Users wishing to
165 interact with it will query control for the pty's pathname and connect
166 with there favorite console program. For example:
167 cu -l /dev/pts/22
168
169 Args:
170 interface: interface number of FTDI device to use
171
172 Returns:
173 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700174
175 Raises:
176 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700177 """
178 fgpio = self._init_gpio(interface)
179 fuart = ftdiuart.Fuart(self._vendor, self._product, interface, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700180 try:
181 fuart.run()
182 except ftdiuart.FuartError as e:
183 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
184
Todd Broch888da782011-10-07 14:29:09 -0700185 self._logger.info("uart pty: %s" % fuart.get_pty())
186 return fgpio, fuart
187
Todd Broche505b8d2011-03-21 18:19:54 -0700188 def _get_param_drv(self, control_name, is_get=True):
189 """Get access to driver for a given control.
190
191 Note, some controls have different parameter dictionaries for 'getting' the
192 control's value versus 'setting' it. Boolean is_get distinguishes which is
193 being requested.
194
195 Args:
196 control_name: string name of control
197 is_get: boolean to determine
198
199 Returns:
200 tuple (param, drv) where:
201 param: param dictionary for control
202 drv: instance object of driver for particular control
203
204 Raises:
205 ServodError: Error occurred while examining params dict
206 """
207 self._logger.debug("")
208 # if already setup just return tuple from driver dict
209 if control_name in self._drv_dict:
210 if is_get and ('get' in self._drv_dict[control_name]):
211 return self._drv_dict[control_name]['get']
212 if not is_get and ('set' in self._drv_dict[control_name]):
213 return self._drv_dict[control_name]['set']
214
215 params = self._syscfg.lookup_control_params(control_name, is_get)
216 if 'drv' not in params:
217 self._logger.error("Unable to determine driver for %s" % control_name)
218 raise ServodError("'drv' key not found in params dict")
219 if 'interface' not in params:
220 self._logger.error("Unable to determine interface for %s" %
221 control_name)
222
223 raise ServodError("'interface' key not found in params dict")
224 index = int(params['interface']) - 1
225 interface = self._interface_list[index]
226 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
227 drv_pkg = imp.load_module('drv',
228 *imp.find_module('drv', servo_pkg.__path__))
229 drv_name = params['drv']
230 drv_module = getattr(drv_pkg, drv_name)
231 drv_class = getattr(drv_module, drv_name)
232 drv = drv_class(interface, params)
233 if control_name not in self._drv_dict:
234 self._drv_dict[control_name] = {}
235 if is_get:
236 self._drv_dict[control_name]['get'] = (params, drv)
237 else:
238 self._drv_dict[control_name]['set'] = (params, drv)
239 return (params, drv)
240
241 def doc_all(self):
242 """Return all documenation for controls.
243
244 Returns:
245 string of <doc> text in config file (xml) and the params dictionary for
246 all controls.
247
248 For example:
249 warm_reset :: Reset the device warmly
250 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
251 """
252 return self._syscfg.display_config()
253
254 def doc(self, name):
255 """Retreive doc string in system config file for given control name.
256
257 Args:
258 name: name string of control to get doc string
259
260 Returns:
261 doc string of name
262
263 Raises:
264 NameError: if fails to locate control
265 """
266 self._logger.debug("name(%s)" % (name))
267 if self._syscfg.is_control(name):
268 return self._syscfg.get_control_docstring(name)
269 else:
270 raise NameError("No control %s" %name)
271
272 def get(self, name):
273 """Get control value.
274
275 Args:
276 name: name string of control
277
278 Returns:
279 Response from calling drv get method. Value is reformatted based on
280 control's dictionary parameters
281
282 Raises:
283 HwDriverError: Error occurred while using drv
284 """
285 self._logger.debug("name(%s)" % (name))
286 (param, drv) = self._get_param_drv(name)
287 try:
288 val = drv.get()
289 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800290 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700291 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700292 except AttributeError, error:
293 self._logger.error("Getting %s: %s" % (name, error))
294 raise
Todd Broche505b8d2011-03-21 18:19:54 -0700295 except drv.hw_driver.HwDriverError:
296 self._logger.error("Getting %s" % (name))
297 raise
298 def get_all(self, verbose):
299 """Get all controls values.
300
301 Args:
302 verbose: Boolean on whether to return doc info as well
303
304 Returns:
305 string creating from trying to get all values of all controls. In case of
306 error attempting access to control, response is 'ERR'.
307 """
308 rsp = ""
309 for name in self._syscfg.syscfg_dict['control']:
310 self._logger.debug("name = %s" %name)
311 try:
312 value = self.get(name)
313 except Exception:
314 value = "ERR"
315 pass
316 if verbose:
317 rsp += "GET %s = %s :: %s\n" % (name, value, self.doc(name))
318 else:
319 rsp += "%s:%s\n" % (name, value)
320 return rsp
321
322 def set(self, name, wr_val_str):
323 """Set control.
324
325 Args:
326 name: name string of control
327 wr_val_str: value string to write. Can be integer, float or a
328 alpha-numerical that is mapped to a integer or float.
329
330 Raises:
331 HwDriverError: Error occurred while using driver
332 """
Todd Broch7a91c252012-02-03 12:37:45 -0800333 if name == 'sleep':
334 time.sleep(float(wr_val_str))
335 return True
336
Todd Broche505b8d2011-03-21 18:19:54 -0700337 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
338 (params, drv) = self._get_param_drv(name, False)
339 wr_val = self._syscfg.resolve_val(params, wr_val_str)
340 try:
341 drv.set(wr_val)
342 except drv.hw_driver.HwDriverError:
343 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
344 raise
345 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
346 # & client I still have to return something to appease the
347 # marshall/unmarshall
348 return True
349
350 def echo(self, echo):
351 """Dummy echo function for testing/examples.
352
353 Args:
354 echo: string to echo back to client
355 """
356 self._logger.debug("echo(%s)" % (echo))
357 return "ECH0ING: %s" % (echo)
358
Todd Brochdbb09982011-10-02 07:14:26 -0700359
Todd Broche505b8d2011-03-21 18:19:54 -0700360def test():
361 """Integration testing.
362
363 TODO(tbroch) Enhance integration test and add unittest (see mox)
364 """
365 logging.basicConfig(level=logging.DEBUG,
366 format="%(asctime)s - %(name)s - " +
367 "%(levelname)s - %(message)s")
368 # configure server & listen
369 servod_obj = Servod(1)
370 # 4 == number of interfaces on a FT4232H device
371 for i in xrange(4):
372 if i == 1:
373 # its an i2c interface ... see __init__ for details and TODO to make
374 # this configureable
375 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
376 else:
377 # its a gpio interface
378 servod_obj._interface_list[i].wr_rd(0)
379
380 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
381 allow_none=True)
382 server.register_introspection_functions()
383 server.register_multicall_functions()
384 server.register_instance(servod_obj)
385 logging.info("Listening on localhost port 9999")
386 server.serve_forever()
387
388if __name__ == "__main__":
389 test()
390
391 # simple client transaction would look like
392 """
393 remote_uri = 'http://localhost:9999'
394 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
395 send_str = "Hello_there"
396 print "Sent " + send_str + ", Recv " + client.echo(send_str)
397 """