blob: a8496939ff7d4a3b11ed05474fa8e904c8b2c8b5 [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.
97 """
Todd Brochad034442011-05-25 15:05:29 -070098 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
99 self._serialname)
Todd Broche505b8d2011-03-21 18:19:54 -0700100 fobj.open()
101 return fobj
102
103 def _init_i2c(self, interface):
104 """Initialize i2c interface and open for use.
105
106 Args:
107 interface: interface number of FTDI device to use
108
109 Returns:
110 Instance object of interface
111 """
Todd Brochad034442011-05-25 15:05:29 -0700112 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
113 self._serialname)
Todd Broche505b8d2011-03-21 18:19:54 -0700114 fobj.open()
115 # Set the frequency of operation of the i2c bus.
116 # TODO(tbroch) make configureable
117 fobj.setclock(MAX_I2C_CLOCK_HZ)
118 return fobj
119
Todd Broch47c43f42011-05-26 15:11:31 -0700120 def _init_uart(self, interface):
121 """Initialize uart inteface and open for use
122
123 Note, the uart runs in a separate thread (pthreads). Users wishing to
124 interact with it will query control for the pty's pathname and connect
125 with there favorite console program. For example:
126 cu -l /dev/pts/22
127
128 Args:
129 interface: interface number of FTDI device to use
130
131 Returns:
132 Instance object of interface
133 """
134 fobj = ftdiuart.Fuart(self._vendor, self._product, interface)
135 fobj.run()
136 self._logger.info("%s" % fobj.get_pty())
137 return fobj
138
Todd Broch888da782011-10-07 14:29:09 -0700139 def _init_gpiouart(self, interface):
140 """Initialize special gpio + uart interface 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 objects of interface
152 """
153 fgpio = self._init_gpio(interface)
154 fuart = ftdiuart.Fuart(self._vendor, self._product, interface, fgpio._fc)
155 fuart.run()
156 self._logger.info("uart pty: %s" % fuart.get_pty())
157 return fgpio, fuart
158
Todd Broche505b8d2011-03-21 18:19:54 -0700159 def _get_param_drv(self, control_name, is_get=True):
160 """Get access to driver for a given control.
161
162 Note, some controls have different parameter dictionaries for 'getting' the
163 control's value versus 'setting' it. Boolean is_get distinguishes which is
164 being requested.
165
166 Args:
167 control_name: string name of control
168 is_get: boolean to determine
169
170 Returns:
171 tuple (param, drv) where:
172 param: param dictionary for control
173 drv: instance object of driver for particular control
174
175 Raises:
176 ServodError: Error occurred while examining params dict
177 """
178 self._logger.debug("")
179 # if already setup just return tuple from driver dict
180 if control_name in self._drv_dict:
181 if is_get and ('get' in self._drv_dict[control_name]):
182 return self._drv_dict[control_name]['get']
183 if not is_get and ('set' in self._drv_dict[control_name]):
184 return self._drv_dict[control_name]['set']
185
186 params = self._syscfg.lookup_control_params(control_name, is_get)
187 if 'drv' not in params:
188 self._logger.error("Unable to determine driver for %s" % control_name)
189 raise ServodError("'drv' key not found in params dict")
190 if 'interface' not in params:
191 self._logger.error("Unable to determine interface for %s" %
192 control_name)
193
194 raise ServodError("'interface' key not found in params dict")
195 index = int(params['interface']) - 1
196 interface = self._interface_list[index]
197 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
198 drv_pkg = imp.load_module('drv',
199 *imp.find_module('drv', servo_pkg.__path__))
200 drv_name = params['drv']
201 drv_module = getattr(drv_pkg, drv_name)
202 drv_class = getattr(drv_module, drv_name)
203 drv = drv_class(interface, params)
204 if control_name not in self._drv_dict:
205 self._drv_dict[control_name] = {}
206 if is_get:
207 self._drv_dict[control_name]['get'] = (params, drv)
208 else:
209 self._drv_dict[control_name]['set'] = (params, drv)
210 return (params, drv)
211
212 def doc_all(self):
213 """Return all documenation for controls.
214
215 Returns:
216 string of <doc> text in config file (xml) and the params dictionary for
217 all controls.
218
219 For example:
220 warm_reset :: Reset the device warmly
221 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
222 """
223 return self._syscfg.display_config()
224
225 def doc(self, name):
226 """Retreive doc string in system config file for given control name.
227
228 Args:
229 name: name string of control to get doc string
230
231 Returns:
232 doc string of name
233
234 Raises:
235 NameError: if fails to locate control
236 """
237 self._logger.debug("name(%s)" % (name))
238 if self._syscfg.is_control(name):
239 return self._syscfg.get_control_docstring(name)
240 else:
241 raise NameError("No control %s" %name)
242
243 def get(self, name):
244 """Get control value.
245
246 Args:
247 name: name string of control
248
249 Returns:
250 Response from calling drv get method. Value is reformatted based on
251 control's dictionary parameters
252
253 Raises:
254 HwDriverError: Error occurred while using drv
255 """
256 self._logger.debug("name(%s)" % (name))
257 (param, drv) = self._get_param_drv(name)
258 try:
259 val = drv.get()
260 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800261 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700262 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700263 except AttributeError, error:
264 self._logger.error("Getting %s: %s" % (name, error))
265 raise
Todd Broche505b8d2011-03-21 18:19:54 -0700266 except drv.hw_driver.HwDriverError:
267 self._logger.error("Getting %s" % (name))
268 raise
269 def get_all(self, verbose):
270 """Get all controls values.
271
272 Args:
273 verbose: Boolean on whether to return doc info as well
274
275 Returns:
276 string creating from trying to get all values of all controls. In case of
277 error attempting access to control, response is 'ERR'.
278 """
279 rsp = ""
280 for name in self._syscfg.syscfg_dict['control']:
281 self._logger.debug("name = %s" %name)
282 try:
283 value = self.get(name)
284 except Exception:
285 value = "ERR"
286 pass
287 if verbose:
288 rsp += "GET %s = %s :: %s\n" % (name, value, self.doc(name))
289 else:
290 rsp += "%s:%s\n" % (name, value)
291 return rsp
292
293 def set(self, name, wr_val_str):
294 """Set control.
295
296 Args:
297 name: name string of control
298 wr_val_str: value string to write. Can be integer, float or a
299 alpha-numerical that is mapped to a integer or float.
300
301 Raises:
302 HwDriverError: Error occurred while using driver
303 """
Todd Broch7a91c252012-02-03 12:37:45 -0800304 if name == 'sleep':
305 time.sleep(float(wr_val_str))
306 return True
307
Todd Broche505b8d2011-03-21 18:19:54 -0700308 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
309 (params, drv) = self._get_param_drv(name, False)
310 wr_val = self._syscfg.resolve_val(params, wr_val_str)
311 try:
312 drv.set(wr_val)
313 except drv.hw_driver.HwDriverError:
314 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
315 raise
316 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
317 # & client I still have to return something to appease the
318 # marshall/unmarshall
319 return True
320
321 def echo(self, echo):
322 """Dummy echo function for testing/examples.
323
324 Args:
325 echo: string to echo back to client
326 """
327 self._logger.debug("echo(%s)" % (echo))
328 return "ECH0ING: %s" % (echo)
329
Todd Brochdbb09982011-10-02 07:14:26 -0700330
Todd Broche505b8d2011-03-21 18:19:54 -0700331def test():
332 """Integration testing.
333
334 TODO(tbroch) Enhance integration test and add unittest (see mox)
335 """
336 logging.basicConfig(level=logging.DEBUG,
337 format="%(asctime)s - %(name)s - " +
338 "%(levelname)s - %(message)s")
339 # configure server & listen
340 servod_obj = Servod(1)
341 # 4 == number of interfaces on a FT4232H device
342 for i in xrange(4):
343 if i == 1:
344 # its an i2c interface ... see __init__ for details and TODO to make
345 # this configureable
346 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
347 else:
348 # its a gpio interface
349 servod_obj._interface_list[i].wr_rd(0)
350
351 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
352 allow_none=True)
353 server.register_introspection_functions()
354 server.register_multicall_functions()
355 server.register_instance(servod_obj)
356 logging.info("Listening on localhost port 9999")
357 server.serve_forever()
358
359if __name__ == "__main__":
360 test()
361
362 # simple client transaction would look like
363 """
364 remote_uri = 'http://localhost:9999'
365 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
366 send_str = "Hello_there"
367 print "Sent " + send_str + ", Recv " + client.echo(send_str)
368 """