blob: a11aff4769560ade883b31ea1d7237a5ebf88eac [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 Brochb4701132012-04-25 09:04:39 -070073 for control_name, value in self._syscfg.hwinit():
74 self.set(control_name, value)
75 self._logger.info('Initialized %s to %s', control_name, value)
76
Todd Brocha9c74692012-01-24 22:54:22 -080077
Todd Brochb3048492012-01-15 21:52:41 -080078 def _init_dummy(self, interface):
79 """Initialize dummy interface.
80
81 Dummy interface is just a mechanism to reserve that interface for non servod
82 interaction. Typically the interface will be managed by external
83 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
84 interfaces.
85
86 TODO(tbroch): Investigate merits of incorporating these third-party
87 interfaces into servod or creating a communication channel between them
88
89 Returns: None
90 """
91 return None
92
Todd Broche505b8d2011-03-21 18:19:54 -070093 def _init_gpio(self, interface):
94 """Initialize gpio driver interface and open for use.
95
96 Args:
97 interface: interface number of FTDI device to use.
98
99 Returns:
100 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700101
102 Raises:
103 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700104 """
Todd Brochad034442011-05-25 15:05:29 -0700105 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
106 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700107 try:
108 fobj.open()
109 except ftdigpio.FgpioError as e:
110 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
111
Todd Broche505b8d2011-03-21 18:19:54 -0700112 return fobj
113
114 def _init_i2c(self, interface):
115 """Initialize i2c interface and open for use.
116
117 Args:
118 interface: interface number of FTDI device to use
119
120 Returns:
121 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700122
123 Raises:
124 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700125 """
Todd Brochad034442011-05-25 15:05:29 -0700126 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
127 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700128 try:
129 fobj.open()
130 except ftdii2c.Fi2cError as e:
131 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
132
Todd Broche505b8d2011-03-21 18:19:54 -0700133 # Set the frequency of operation of the i2c bus.
134 # TODO(tbroch) make configureable
135 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700136
Todd Broche505b8d2011-03-21 18:19:54 -0700137 return fobj
138
Todd Broch47c43f42011-05-26 15:11:31 -0700139 def _init_uart(self, interface):
140 """Initialize uart inteface and open for use
141
142 Note, the uart runs in a separate thread (pthreads). Users wishing to
143 interact with it will query control for the pty's pathname and connect
144 with there favorite console program. For example:
145 cu -l /dev/pts/22
146
147 Args:
148 interface: interface number of FTDI device to use
149
150 Returns:
151 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700152
153 Raises:
154 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700155 """
156 fobj = ftdiuart.Fuart(self._vendor, self._product, interface)
Todd Broch6de9dc62012-04-09 15:23:53 -0700157 try:
158 fobj.run()
159 except ftdiuart.FuartError as e:
160 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
161
Todd Broch47c43f42011-05-26 15:11:31 -0700162 self._logger.info("%s" % fobj.get_pty())
163 return fobj
164
Todd Broch888da782011-10-07 14:29:09 -0700165 def _init_gpiouart(self, interface):
166 """Initialize special gpio + uart interface and open for use
167
168 Note, the uart runs in a separate thread (pthreads). Users wishing to
169 interact with it will query control for the pty's pathname and connect
170 with there favorite console program. For example:
171 cu -l /dev/pts/22
172
173 Args:
174 interface: interface number of FTDI device to use
175
176 Returns:
177 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700178
179 Raises:
180 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700181 """
182 fgpio = self._init_gpio(interface)
183 fuart = ftdiuart.Fuart(self._vendor, self._product, interface, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700184 try:
185 fuart.run()
186 except ftdiuart.FuartError as e:
187 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
188
Todd Broch888da782011-10-07 14:29:09 -0700189 self._logger.info("uart pty: %s" % fuart.get_pty())
190 return fgpio, fuart
191
Todd Broche505b8d2011-03-21 18:19:54 -0700192 def _get_param_drv(self, control_name, is_get=True):
193 """Get access to driver for a given control.
194
195 Note, some controls have different parameter dictionaries for 'getting' the
196 control's value versus 'setting' it. Boolean is_get distinguishes which is
197 being requested.
198
199 Args:
200 control_name: string name of control
201 is_get: boolean to determine
202
203 Returns:
204 tuple (param, drv) where:
205 param: param dictionary for control
206 drv: instance object of driver for particular control
207
208 Raises:
209 ServodError: Error occurred while examining params dict
210 """
211 self._logger.debug("")
212 # if already setup just return tuple from driver dict
213 if control_name in self._drv_dict:
214 if is_get and ('get' in self._drv_dict[control_name]):
215 return self._drv_dict[control_name]['get']
216 if not is_get and ('set' in self._drv_dict[control_name]):
217 return self._drv_dict[control_name]['set']
218
219 params = self._syscfg.lookup_control_params(control_name, is_get)
220 if 'drv' not in params:
221 self._logger.error("Unable to determine driver for %s" % control_name)
222 raise ServodError("'drv' key not found in params dict")
223 if 'interface' not in params:
224 self._logger.error("Unable to determine interface for %s" %
225 control_name)
226
227 raise ServodError("'interface' key not found in params dict")
228 index = int(params['interface']) - 1
229 interface = self._interface_list[index]
230 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
231 drv_pkg = imp.load_module('drv',
232 *imp.find_module('drv', servo_pkg.__path__))
233 drv_name = params['drv']
234 drv_module = getattr(drv_pkg, drv_name)
235 drv_class = getattr(drv_module, drv_name)
236 drv = drv_class(interface, params)
237 if control_name not in self._drv_dict:
238 self._drv_dict[control_name] = {}
239 if is_get:
240 self._drv_dict[control_name]['get'] = (params, drv)
241 else:
242 self._drv_dict[control_name]['set'] = (params, drv)
243 return (params, drv)
244
245 def doc_all(self):
246 """Return all documenation for controls.
247
248 Returns:
249 string of <doc> text in config file (xml) and the params dictionary for
250 all controls.
251
252 For example:
253 warm_reset :: Reset the device warmly
254 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
255 """
256 return self._syscfg.display_config()
257
258 def doc(self, name):
259 """Retreive doc string in system config file for given control name.
260
261 Args:
262 name: name string of control to get doc string
263
264 Returns:
265 doc string of name
266
267 Raises:
268 NameError: if fails to locate control
269 """
270 self._logger.debug("name(%s)" % (name))
271 if self._syscfg.is_control(name):
272 return self._syscfg.get_control_docstring(name)
273 else:
274 raise NameError("No control %s" %name)
275
276 def get(self, name):
277 """Get control value.
278
279 Args:
280 name: name string of control
281
282 Returns:
283 Response from calling drv get method. Value is reformatted based on
284 control's dictionary parameters
285
286 Raises:
287 HwDriverError: Error occurred while using drv
288 """
289 self._logger.debug("name(%s)" % (name))
290 (param, drv) = self._get_param_drv(name)
291 try:
292 val = drv.get()
293 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800294 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700295 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700296 except AttributeError, error:
297 self._logger.error("Getting %s: %s" % (name, error))
298 raise
Todd Broche505b8d2011-03-21 18:19:54 -0700299 except drv.hw_driver.HwDriverError:
300 self._logger.error("Getting %s" % (name))
301 raise
302 def get_all(self, verbose):
303 """Get all controls values.
304
305 Args:
306 verbose: Boolean on whether to return doc info as well
307
308 Returns:
309 string creating from trying to get all values of all controls. In case of
310 error attempting access to control, response is 'ERR'.
311 """
312 rsp = ""
313 for name in self._syscfg.syscfg_dict['control']:
314 self._logger.debug("name = %s" %name)
315 try:
316 value = self.get(name)
317 except Exception:
318 value = "ERR"
319 pass
320 if verbose:
321 rsp += "GET %s = %s :: %s\n" % (name, value, self.doc(name))
322 else:
323 rsp += "%s:%s\n" % (name, value)
324 return rsp
325
326 def set(self, name, wr_val_str):
327 """Set control.
328
329 Args:
330 name: name string of control
331 wr_val_str: value string to write. Can be integer, float or a
332 alpha-numerical that is mapped to a integer or float.
333
334 Raises:
335 HwDriverError: Error occurred while using driver
336 """
Todd Broch7a91c252012-02-03 12:37:45 -0800337 if name == 'sleep':
338 time.sleep(float(wr_val_str))
339 return True
340
Todd Broche505b8d2011-03-21 18:19:54 -0700341 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
342 (params, drv) = self._get_param_drv(name, False)
343 wr_val = self._syscfg.resolve_val(params, wr_val_str)
344 try:
345 drv.set(wr_val)
346 except drv.hw_driver.HwDriverError:
347 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
348 raise
349 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
350 # & client I still have to return something to appease the
351 # marshall/unmarshall
352 return True
353
354 def echo(self, echo):
355 """Dummy echo function for testing/examples.
356
357 Args:
358 echo: string to echo back to client
359 """
360 self._logger.debug("echo(%s)" % (echo))
361 return "ECH0ING: %s" % (echo)
362
Todd Brochdbb09982011-10-02 07:14:26 -0700363
Todd Broche505b8d2011-03-21 18:19:54 -0700364def test():
365 """Integration testing.
366
367 TODO(tbroch) Enhance integration test and add unittest (see mox)
368 """
369 logging.basicConfig(level=logging.DEBUG,
370 format="%(asctime)s - %(name)s - " +
371 "%(levelname)s - %(message)s")
372 # configure server & listen
373 servod_obj = Servod(1)
374 # 4 == number of interfaces on a FT4232H device
375 for i in xrange(4):
376 if i == 1:
377 # its an i2c interface ... see __init__ for details and TODO to make
378 # this configureable
379 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
380 else:
381 # its a gpio interface
382 servod_obj._interface_list[i].wr_rd(0)
383
384 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
385 allow_none=True)
386 server.register_introspection_functions()
387 server.register_multicall_functions()
388 server.register_instance(servod_obj)
389 logging.info("Listening on localhost port 9999")
390 server.serve_forever()
391
392if __name__ == "__main__":
393 test()
394
395 # simple client transaction would look like
396 """
397 remote_uri = 'http://localhost:9999'
398 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
399 send_str = "Hello_there"
400 print "Sent " + send_str + ", Recv " + client.echo(send_str)
401 """