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