blob: 9b964fae48e665e4f270588028f1b2c5e10de994 [file] [log] [blame]
Simran Basia9f41032012-05-11 14:21:58 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Todd Broche505b8d2011-03-21 18:19:54 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""Servo Server."""
Simran Basia9f41032012-05-11 14:21:58 -07005import fnmatch
Todd Broche505b8d2011-03-21 18:19:54 -07006import imp
7import logging
Simran Basia9f41032012-05-11 14:21:58 -07008import os
9import shutil
Todd Broche505b8d2011-03-21 18:19:54 -070010import SimpleXMLRPCServer
Simran Basia9f41032012-05-11 14:21:58 -070011import subprocess
12import tempfile
Todd Broch7a91c252012-02-03 12:37:45 -080013import time
Simran Basia9f41032012-05-11 14:21:58 -070014import urllib
Todd Broche505b8d2011-03-21 18:19:54 -070015
16# TODO(tbroch) deprecate use of relative imports
Vic Yangbe6cf262012-09-10 10:40:56 +080017from drv.hw_driver import HwDriverError
Simran Basia9ad25e2013-04-23 11:57:00 -070018import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070019import bbgpio
Todd Broche505b8d2011-03-21 18:19:54 -070020import ftdigpio
21import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070022import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070023import ftdiuart
Simran Basie750a342013-03-12 13:45:26 -070024import servo_interfaces
Todd Broche505b8d2011-03-21 18:19:54 -070025
26MAX_I2C_CLOCK_HZ = 100000
27
Todd Brochdbb09982011-10-02 07:14:26 -070028
Todd Broche505b8d2011-03-21 18:19:54 -070029class ServodError(Exception):
30 """Exception class for servod."""
31
32class Servod(object):
33 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070034 _USB_DETECTION_DELAY = 10
35 _HTTP_PREFIX = "http://"
36
J. Richard Barnettee2820552013-03-14 16:13:46 -070037 def __init__(self, config, vendor, product, serialname=None,
38 interfaces=None, board=""):
Todd Broche505b8d2011-03-21 18:19:54 -070039 """Servod constructor.
40
41 Args:
42 config: instance of SystemConfig containing all controls for
43 particular Servod invocation
44 vendor: usb vendor id of FTDI device
45 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070046 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070047 interfaces: list of strings of interface types the server will instantiate
48
49 Raises:
50 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070051 """
52 self._logger = logging.getLogger("Servod")
53 self._logger.debug("")
54 self._vendor = vendor
55 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070056 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070057 self._syscfg = config
58 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
59 # interfaces are mapped to
60 self._interface_list = []
61 # Dict of Dict to map control name, function name to to tuple (params, drv)
62 # Ex) _drv_dict[name]['get'] = (params, drv)
63 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070064 self._board = board
Todd Broche505b8d2011-03-21 18:19:54 -070065
Todd Brochdbb09982011-10-02 07:14:26 -070066 # Note, interface i is (i - 1) in list
67 if not interfaces:
Simran Basie750a342013-03-12 13:45:26 -070068 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070069
Simran Basia9ad25e2013-04-23 11:57:00 -070070 for i, interface in enumerate(interfaces):
71 is_ftdi_interface = False
72 if type(interface) is dict:
73 name = interface['name']
74 elif type(interface) is str:
75 # Its FTDI related interface
76 name = interface
77 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
78 is_ftdi_interface = True
79 else:
80 raise ServodError("Illegal interface type %s" % type(interface))
81
Todd Broch8a77a992012-01-27 09:46:08 -080082 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -070083 if is_ftdi_interface and i and \
84 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -080085 self._product += 1
86 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
87 self._product)
88
Simran Basia9ad25e2013-04-23 11:57:00 -070089 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -070090 try:
91 func = getattr(self, '_init_%s' % name)
92 except AttributeError:
93 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -070094 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -070095 if isinstance(result, tuple):
96 self._interface_list.extend(result)
97 else:
98 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -070099
Todd Broch3ec8df02012-11-20 10:53:03 -0800100 def __del__(self):
101 """Servod deconstructor."""
102 for interface in self._interface_list:
103 del(interface)
104
Todd Brochb3048492012-01-15 21:52:41 -0800105 def _init_dummy(self, interface):
106 """Initialize dummy interface.
107
108 Dummy interface is just a mechanism to reserve that interface for non servod
109 interaction. Typically the interface will be managed by external
110 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
111 interfaces.
112
113 TODO(tbroch): Investigate merits of incorporating these third-party
114 interfaces into servod or creating a communication channel between them
115
116 Returns: None
117 """
118 return None
119
Simran Basie750a342013-03-12 13:45:26 -0700120 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700121 """Initialize gpio driver interface and open for use.
122
123 Args:
124 interface: interface number of FTDI device to use.
125
126 Returns:
127 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700128
129 Raises:
130 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700131 """
Todd Brochad034442011-05-25 15:05:29 -0700132 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
133 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700134 try:
135 fobj.open()
136 except ftdigpio.FgpioError as e:
137 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
138
Todd Broche505b8d2011-03-21 18:19:54 -0700139 return fobj
140
Simran Basie750a342013-03-12 13:45:26 -0700141 def _init_bb_gpio(self, interface):
142 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700143 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700144
145 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700146 """Initialize i2c interface and open for use.
147
148 Args:
149 interface: interface number of FTDI device to use
150
151 Returns:
152 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700153
154 Raises:
155 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700156 """
Todd Brochad034442011-05-25 15:05:29 -0700157 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
158 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700159 try:
160 fobj.open()
161 except ftdii2c.Fi2cError as e:
162 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
163
Todd Broche505b8d2011-03-21 18:19:54 -0700164 # Set the frequency of operation of the i2c bus.
165 # TODO(tbroch) make configureable
166 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700167
Todd Broche505b8d2011-03-21 18:19:54 -0700168 return fobj
169
Simran Basie750a342013-03-12 13:45:26 -0700170 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
171 def _init_bb_i2c(self, interface):
172 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700173 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700174
175 def _init_ftdi_uart(self, interface):
176 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700177
178 Note, the uart runs in a separate thread (pthreads). Users wishing to
179 interact with it will query control for the pty's pathname and connect
180 with there favorite console program. For example:
181 cu -l /dev/pts/22
182
183 Args:
184 interface: interface number of FTDI device to use
185
186 Returns:
187 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700188
189 Raises:
190 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700191 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700192 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
193 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700194 try:
195 fobj.run()
196 except ftdiuart.FuartError as e:
197 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
198
Todd Broch47c43f42011-05-26 15:11:31 -0700199 self._logger.info("%s" % fobj.get_pty())
200 return fobj
201
Simran Basie750a342013-03-12 13:45:26 -0700202 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
203 def _init_bb_uart(self, interface):
204 """Initalize beaglebone uart interface."""
205 pass
206
207 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700208 """Initialize special gpio + uart interface and open for use
209
210 Note, the uart runs in a separate thread (pthreads). Users wishing to
211 interact with it will query control for the pty's pathname and connect
212 with there favorite console program. For example:
213 cu -l /dev/pts/22
214
215 Args:
216 interface: interface number of FTDI device to use
217
218 Returns:
219 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700220
221 Raises:
222 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700223 """
Simran Basie750a342013-03-12 13:45:26 -0700224 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700225 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
226 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700227 try:
228 fuart.run()
229 except ftdiuart.FuartError as e:
230 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
231
Todd Broch888da782011-10-07 14:29:09 -0700232 self._logger.info("uart pty: %s" % fuart.get_pty())
233 return fgpio, fuart
234
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800235 def _camel_case(self, string):
236 output = ''
237 for s in string.split('_'):
238 if output:
239 output += s.capitalize()
240 else:
241 output = s
242 return output
243
Todd Broche505b8d2011-03-21 18:19:54 -0700244 def _get_param_drv(self, control_name, is_get=True):
245 """Get access to driver for a given control.
246
247 Note, some controls have different parameter dictionaries for 'getting' the
248 control's value versus 'setting' it. Boolean is_get distinguishes which is
249 being requested.
250
251 Args:
252 control_name: string name of control
253 is_get: boolean to determine
254
255 Returns:
256 tuple (param, drv) where:
257 param: param dictionary for control
258 drv: instance object of driver for particular control
259
260 Raises:
261 ServodError: Error occurred while examining params dict
262 """
263 self._logger.debug("")
264 # if already setup just return tuple from driver dict
265 if control_name in self._drv_dict:
266 if is_get and ('get' in self._drv_dict[control_name]):
267 return self._drv_dict[control_name]['get']
268 if not is_get and ('set' in self._drv_dict[control_name]):
269 return self._drv_dict[control_name]['set']
270
271 params = self._syscfg.lookup_control_params(control_name, is_get)
272 if 'drv' not in params:
273 self._logger.error("Unable to determine driver for %s" % control_name)
274 raise ServodError("'drv' key not found in params dict")
275 if 'interface' not in params:
276 self._logger.error("Unable to determine interface for %s" %
277 control_name)
278
279 raise ServodError("'interface' key not found in params dict")
280 index = int(params['interface']) - 1
281 interface = self._interface_list[index]
282 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
283 drv_pkg = imp.load_module('drv',
284 *imp.find_module('drv', servo_pkg.__path__))
285 drv_name = params['drv']
286 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800287 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700288 drv = drv_class(interface, params)
289 if control_name not in self._drv_dict:
290 self._drv_dict[control_name] = {}
291 if is_get:
292 self._drv_dict[control_name]['get'] = (params, drv)
293 else:
294 self._drv_dict[control_name]['set'] = (params, drv)
295 return (params, drv)
296
297 def doc_all(self):
298 """Return all documenation for controls.
299
300 Returns:
301 string of <doc> text in config file (xml) and the params dictionary for
302 all controls.
303
304 For example:
305 warm_reset :: Reset the device warmly
306 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
307 """
308 return self._syscfg.display_config()
309
310 def doc(self, name):
311 """Retreive doc string in system config file for given control name.
312
313 Args:
314 name: name string of control to get doc string
315
316 Returns:
317 doc string of name
318
319 Raises:
320 NameError: if fails to locate control
321 """
322 self._logger.debug("name(%s)" % (name))
323 if self._syscfg.is_control(name):
324 return self._syscfg.get_control_docstring(name)
325 else:
326 raise NameError("No control %s" %name)
327
Simran Basia9f41032012-05-11 14:21:58 -0700328 def _get_usb_port_set(self):
329 """Gets a set of USB disks currently connected to the system
330
331 Returns:
332 A set of USB disk paths.
333 """
334 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
335 return set(["/dev/" + dev for dev in usb_set])
336
337 def _probe_host_usb_dev(self):
338 """Probe the USB disk device plugged in the servo from the host side.
339
340 Method can fail by:
341 1) Having multiple servos connected and returning incorrect /dev/sdX of
342 another servo.
343 2) Finding multiple /dev/sdX and returning None.
344
345 Returns:
346 USB disk path if one and only one USB disk path is found, otherwise None.
347 """
348 original_value = self.get("usb_mux_sel1")
349 # Make the host unable to see the USB disk.
350 if original_value != "dut_sees_usbkey":
351 self.set("usb_mux_sel1", "dut_sees_usbkey")
352 time.sleep(self._USB_DETECTION_DELAY)
353
354 no_usb_set = self._get_usb_port_set()
355 # Make the host able to see the USB disk.
356 self.set("usb_mux_sel1", "servo_sees_usbkey")
357 time.sleep(self._USB_DETECTION_DELAY)
358
359 has_usb_set = self._get_usb_port_set()
360 # Back to its original value.
361 if original_value != "servo_sees_usbkey":
362 self.set("usb_mux_sel1", original_value)
363 time.sleep(self._USB_DETECTION_DELAY)
364 # Subtract the two sets to find the usb device.
365 diff_set = has_usb_set - no_usb_set
366 if len(diff_set) == 1:
367 return diff_set.pop()
368 else:
369 return None
370
371 def download_image_to_usb(self, image_path):
372 """Download image and save to the USB device found by probe_host_usb_dev.
373 If the image_path is a URL, it will download this url to the USB path;
374 otherwise it will simply copy the image_path's contents to the USB path.
375
376 Args:
377 image_path: path or url to the recovery image.
378
379 Returns:
380 True|False: True if process completed successfully, False if error
381 occurred.
382 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
383 comment at the end of set().
384 """
385 self._logger.debug("image_path(%s)" % image_path)
386 self._logger.debug("Detecting USB stick device...")
387 usb_dev = self._probe_host_usb_dev()
388 if not usb_dev:
389 self._logger.error("No usb device connected to servo")
390 return False
391
392 try:
393 if image_path.startswith(self._HTTP_PREFIX):
394 self._logger.debug("Image path is a URL, downloading image")
395 urllib.urlretrieve(image_path, usb_dev)
396 else:
397 shutil.copyfile(image_path, usb_dev)
398 except IOError as e:
399 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
400 e.strerror, e.errno)
401 return False
402 except urllib.ContentTooShortError:
403 self._logger.error("Failed to download URL: %s to USB device: %s",
404 image_path, usb_dev)
405 return False
406 except BaseException as e:
407 self._logger.error("Unexpected exception downloading %s to %s: %s",
408 image_path, usb_dev, str(e))
409 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800410 finally:
411 # We just plastered the partition table for a block device.
412 # Pass or fail, we mustn't go without telling the kernel about
413 # the change, or it will punish us with sporadic, hard-to-debug
414 # failures.
415 subprocess.call(["sync"])
416 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700417 return True
418
419 def make_image_noninteractive(self):
420 """Makes the recovery image noninteractive.
421
422 A noninteractive image will reboot automatically after installation
423 instead of waiting for the USB device to be removed to initiate a system
424 reboot.
425
426 Mounts partition 1 of the image stored on usb_dev and creates a file
427 called "non_interactive" so that the image will become noninteractive.
428
429 Returns:
430 True|False: True if process completed successfully, False if error
431 occurred.
432 """
433 result = True
434 usb_dev = self._probe_host_usb_dev()
435 if not usb_dev:
436 self._logger.error("No usb device connected to servo")
437 return False
438 # Create TempDirectory
439 tmpdir = tempfile.mkdtemp()
440 if tmpdir:
441 # Mount drive to tmpdir.
442 partition_1 = "%s1" % usb_dev
443 rc = subprocess.call(["mount", partition_1, tmpdir])
444 if rc == 0:
445 # Create file 'non_interactive'
446 non_interactive_file = os.path.join(tmpdir, "non_interactive")
447 try:
448 open(non_interactive_file, "w").close()
449 except IOError as e:
450 self._logger.error("Failed to create file %s : %s ( %d )",
451 non_interactive_file, e.strerror, e.errno)
452 result = False
453 except BaseException as e:
454 self._logger.error("Unexpected Exception creating file %s : %s",
455 non_interactive_file, str(e))
456 result = False
457 # Unmount drive regardless if file creation worked or not.
458 rc = subprocess.call(["umount", partition_1])
459 if rc != 0:
460 self._logger.error("Failed to unmount USB Device")
461 result = False
462 else:
463 self._logger.error("Failed to mount USB Device")
464 result = False
465
466 # Delete tmpdir. May throw exception if 'umount' failed.
467 try:
468 os.rmdir(tmpdir)
469 except OSError as e:
470 self._logger.error("Failed to remove temp directory %s : %s",
471 tmpdir, str(e))
472 return False
473 except BaseException as e:
474 self._logger.error("Unexpected Exception removing tempdir %s : %s",
475 tmpdir, str(e))
476 return False
477 else:
478 self._logger.error("Failed to create temp directory.")
479 return False
480 return result
481
Todd Broch352b4b22013-03-22 09:48:40 -0700482 def set_get_all(self, cmds):
483 """Set &| get one or more control values.
484
485 Args:
486 cmds: list of control[:value] to get or set.
487
488 Returns:
489 rv: list of responses from calling get or set methods.
490 """
491 rv = []
492 for cmd in cmds:
493 if ':' in cmd:
494 (control, value) = cmd.split(':')
495 rv.append(self.set(control, value))
496 else:
497 rv.append(self.get(cmd))
498 return rv
499
Todd Broche505b8d2011-03-21 18:19:54 -0700500 def get(self, name):
501 """Get control value.
502
503 Args:
504 name: name string of control
505
506 Returns:
507 Response from calling drv get method. Value is reformatted based on
508 control's dictionary parameters
509
510 Raises:
511 HwDriverError: Error occurred while using drv
512 """
513 self._logger.debug("name(%s)" % (name))
514 (param, drv) = self._get_param_drv(name)
515 try:
516 val = drv.get()
517 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800518 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700519 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700520 except AttributeError, error:
521 self._logger.error("Getting %s: %s" % (name, error))
522 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800523 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700524 self._logger.error("Getting %s" % (name))
525 raise
Todd Brochd6061672012-05-11 15:52:47 -0700526
Todd Broche505b8d2011-03-21 18:19:54 -0700527 def get_all(self, verbose):
528 """Get all controls values.
529
530 Args:
531 verbose: Boolean on whether to return doc info as well
532
533 Returns:
534 string creating from trying to get all values of all controls. In case of
535 error attempting access to control, response is 'ERR'.
536 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800537 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700538 for name in self._syscfg.syscfg_dict['control']:
539 self._logger.debug("name = %s" %name)
540 try:
541 value = self.get(name)
542 except Exception:
543 value = "ERR"
544 pass
545 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800546 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700547 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800548 rsp.append("%s:%s" % (name, value))
549 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700550
551 def set(self, name, wr_val_str):
552 """Set control.
553
554 Args:
555 name: name string of control
556 wr_val_str: value string to write. Can be integer, float or a
557 alpha-numerical that is mapped to a integer or float.
558
559 Raises:
560 HwDriverError: Error occurred while using driver
561 """
Todd Broch7a91c252012-02-03 12:37:45 -0800562 if name == 'sleep':
563 time.sleep(float(wr_val_str))
564 return True
565
Todd Broche505b8d2011-03-21 18:19:54 -0700566 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
567 (params, drv) = self._get_param_drv(name, False)
568 wr_val = self._syscfg.resolve_val(params, wr_val_str)
569 try:
570 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800571 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700572 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
573 raise
574 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
575 # & client I still have to return something to appease the
576 # marshall/unmarshall
577 return True
578
Todd Brochd6061672012-05-11 15:52:47 -0700579 def hwinit(self, verbose=False):
580 """Initialize all controls.
581
582 These values are part of the system config XML files of the form
583 init=<value>. This command should be used by clients wishing to return the
584 servo and DUT its connected to a known good/safe state.
585
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800586 Note that initialization errors are ignored (as in some cases they could
587 be caused by DUT firmware deficiencies). This might need to be fine tuned
588 later.
589
Todd Brochd6061672012-05-11 15:52:47 -0700590 Args:
591 verbose: boolean, if True prints info about control initialized.
592 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800593
594 Returns:
595 This function is called across RPC and as such is expected to return
596 something unless transferring 'none' across is allowed. Hence adding a
597 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700598 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800599 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800600 try:
601 self.set(control_name, value)
602 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800603 self._logger.error("Problem initializing %s -> %s :: %s",
604 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700605 if verbose:
606 self._logger.info('Initialized %s to %s', control_name, value)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800607 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800608
Todd Broche505b8d2011-03-21 18:19:54 -0700609 def echo(self, echo):
610 """Dummy echo function for testing/examples.
611
612 Args:
613 echo: string to echo back to client
614 """
615 self._logger.debug("echo(%s)" % (echo))
616 return "ECH0ING: %s" % (echo)
617
J. Richard Barnettee2820552013-03-14 16:13:46 -0700618 def get_board(self):
619 """Return the board specified at startup, if any."""
620 return self._board
621
Todd Brochdbb09982011-10-02 07:14:26 -0700622
Todd Broche505b8d2011-03-21 18:19:54 -0700623def test():
624 """Integration testing.
625
626 TODO(tbroch) Enhance integration test and add unittest (see mox)
627 """
628 logging.basicConfig(level=logging.DEBUG,
629 format="%(asctime)s - %(name)s - " +
630 "%(levelname)s - %(message)s")
631 # configure server & listen
632 servod_obj = Servod(1)
633 # 4 == number of interfaces on a FT4232H device
634 for i in xrange(4):
635 if i == 1:
636 # its an i2c interface ... see __init__ for details and TODO to make
637 # this configureable
638 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
639 else:
640 # its a gpio interface
641 servod_obj._interface_list[i].wr_rd(0)
642
643 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
644 allow_none=True)
645 server.register_introspection_functions()
646 server.register_multicall_functions()
647 server.register_instance(servod_obj)
648 logging.info("Listening on localhost port 9999")
649 server.serve_forever()
650
651if __name__ == "__main__":
652 test()
653
654 # simple client transaction would look like
655 """
656 remote_uri = 'http://localhost:9999'
657 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
658 send_str = "Hello_there"
659 print "Sent " + send_str + ", Recv " + client.echo(send_str)
660 """