blob: cfdbbe2c9206e6e9b58b25e3614efdc680643793 [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
Simran Basi949309b2013-05-31 15:12:15 -070020import bbuart
Todd Broche505b8d2011-03-21 18:19:54 -070021import ftdigpio
22import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070023import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070024import ftdiuart
Simran Basie750a342013-03-12 13:45:26 -070025import servo_interfaces
Todd Broche505b8d2011-03-21 18:19:54 -070026
27MAX_I2C_CLOCK_HZ = 100000
28
Todd Brochdbb09982011-10-02 07:14:26 -070029
Todd Broche505b8d2011-03-21 18:19:54 -070030class ServodError(Exception):
31 """Exception class for servod."""
32
33class Servod(object):
34 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070035 _USB_DETECTION_DELAY = 10
36 _HTTP_PREFIX = "http://"
37
J. Richard Barnettee2820552013-03-14 16:13:46 -070038 def __init__(self, config, vendor, product, serialname=None,
39 interfaces=None, board=""):
Todd Broche505b8d2011-03-21 18:19:54 -070040 """Servod constructor.
41
42 Args:
43 config: instance of SystemConfig containing all controls for
44 particular Servod invocation
45 vendor: usb vendor id of FTDI device
46 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070047 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070048 interfaces: list of strings of interface types the server will instantiate
49
50 Raises:
51 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070052 """
53 self._logger = logging.getLogger("Servod")
54 self._logger.debug("")
55 self._vendor = vendor
56 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070057 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070058 self._syscfg = config
59 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
60 # interfaces are mapped to
61 self._interface_list = []
62 # Dict of Dict to map control name, function name to to tuple (params, drv)
63 # Ex) _drv_dict[name]['get'] = (params, drv)
64 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070065 self._board = board
Todd Broche505b8d2011-03-21 18:19:54 -070066
Todd Brochdbb09982011-10-02 07:14:26 -070067 # Note, interface i is (i - 1) in list
68 if not interfaces:
Simran Basie750a342013-03-12 13:45:26 -070069 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070070
Simran Basia9ad25e2013-04-23 11:57:00 -070071 for i, interface in enumerate(interfaces):
72 is_ftdi_interface = False
73 if type(interface) is dict:
74 name = interface['name']
75 elif type(interface) is str:
76 # Its FTDI related interface
77 name = interface
78 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
79 is_ftdi_interface = True
80 else:
81 raise ServodError("Illegal interface type %s" % type(interface))
82
Todd Broch8a77a992012-01-27 09:46:08 -080083 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -070084 if is_ftdi_interface and i and \
85 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -080086 self._product += 1
87 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
88 self._product)
89
Simran Basia9ad25e2013-04-23 11:57:00 -070090 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -070091 try:
92 func = getattr(self, '_init_%s' % name)
93 except AttributeError:
94 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -070095 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -070096 if isinstance(result, tuple):
97 self._interface_list.extend(result)
98 else:
99 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700100
Todd Broch3ec8df02012-11-20 10:53:03 -0800101 def __del__(self):
102 """Servod deconstructor."""
103 for interface in self._interface_list:
104 del(interface)
105
Todd Brochb3048492012-01-15 21:52:41 -0800106 def _init_dummy(self, interface):
107 """Initialize dummy interface.
108
109 Dummy interface is just a mechanism to reserve that interface for non servod
110 interaction. Typically the interface will be managed by external
111 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
112 interfaces.
113
114 TODO(tbroch): Investigate merits of incorporating these third-party
115 interfaces into servod or creating a communication channel between them
116
117 Returns: None
118 """
119 return None
120
Simran Basie750a342013-03-12 13:45:26 -0700121 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700122 """Initialize gpio driver interface and open for use.
123
124 Args:
125 interface: interface number of FTDI device to use.
126
127 Returns:
128 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700129
130 Raises:
131 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700132 """
Todd Brochad034442011-05-25 15:05:29 -0700133 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
134 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700135 try:
136 fobj.open()
137 except ftdigpio.FgpioError as e:
138 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
139
Todd Broche505b8d2011-03-21 18:19:54 -0700140 return fobj
141
Simran Basie750a342013-03-12 13:45:26 -0700142 def _init_bb_gpio(self, interface):
143 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700144 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700145
146 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700147 """Initialize i2c interface and open for use.
148
149 Args:
150 interface: interface number of FTDI device to use
151
152 Returns:
153 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700154
155 Raises:
156 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700157 """
Todd Brochad034442011-05-25 15:05:29 -0700158 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
159 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700160 try:
161 fobj.open()
162 except ftdii2c.Fi2cError as e:
163 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
164
Todd Broche505b8d2011-03-21 18:19:54 -0700165 # Set the frequency of operation of the i2c bus.
166 # TODO(tbroch) make configureable
167 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700168
Todd Broche505b8d2011-03-21 18:19:54 -0700169 return fobj
170
Simran Basie750a342013-03-12 13:45:26 -0700171 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
172 def _init_bb_i2c(self, interface):
173 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700174 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700175
176 def _init_ftdi_uart(self, interface):
177 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700178
179 Note, the uart runs in a separate thread (pthreads). Users wishing to
180 interact with it will query control for the pty's pathname and connect
181 with there favorite console program. For example:
182 cu -l /dev/pts/22
183
184 Args:
185 interface: interface number of FTDI device to use
186
187 Returns:
188 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700189
190 Raises:
191 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700192 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700193 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
194 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700195 try:
196 fobj.run()
197 except ftdiuart.FuartError as e:
198 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
199
Todd Broch47c43f42011-05-26 15:11:31 -0700200 self._logger.info("%s" % fobj.get_pty())
201 return fobj
202
Simran Basie750a342013-03-12 13:45:26 -0700203 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
204 def _init_bb_uart(self, interface):
205 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700206 logging.debug('UART INTERFACE: %s', interface)
207 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700208
209 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700210 """Initialize special gpio + uart interface and open for use
211
212 Note, the uart runs in a separate thread (pthreads). Users wishing to
213 interact with it will query control for the pty's pathname and connect
214 with there favorite console program. For example:
215 cu -l /dev/pts/22
216
217 Args:
218 interface: interface number of FTDI device to use
219
220 Returns:
221 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700222
223 Raises:
224 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700225 """
Simran Basie750a342013-03-12 13:45:26 -0700226 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700227 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
228 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700229 try:
230 fuart.run()
231 except ftdiuart.FuartError as e:
232 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
233
Todd Broch888da782011-10-07 14:29:09 -0700234 self._logger.info("uart pty: %s" % fuart.get_pty())
235 return fgpio, fuart
236
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800237 def _camel_case(self, string):
238 output = ''
239 for s in string.split('_'):
240 if output:
241 output += s.capitalize()
242 else:
243 output = s
244 return output
245
Todd Broche505b8d2011-03-21 18:19:54 -0700246 def _get_param_drv(self, control_name, is_get=True):
247 """Get access to driver for a given control.
248
249 Note, some controls have different parameter dictionaries for 'getting' the
250 control's value versus 'setting' it. Boolean is_get distinguishes which is
251 being requested.
252
253 Args:
254 control_name: string name of control
255 is_get: boolean to determine
256
257 Returns:
258 tuple (param, drv) where:
259 param: param dictionary for control
260 drv: instance object of driver for particular control
261
262 Raises:
263 ServodError: Error occurred while examining params dict
264 """
265 self._logger.debug("")
266 # if already setup just return tuple from driver dict
267 if control_name in self._drv_dict:
268 if is_get and ('get' in self._drv_dict[control_name]):
269 return self._drv_dict[control_name]['get']
270 if not is_get and ('set' in self._drv_dict[control_name]):
271 return self._drv_dict[control_name]['set']
272
273 params = self._syscfg.lookup_control_params(control_name, is_get)
274 if 'drv' not in params:
275 self._logger.error("Unable to determine driver for %s" % control_name)
276 raise ServodError("'drv' key not found in params dict")
277 if 'interface' not in params:
278 self._logger.error("Unable to determine interface for %s" %
279 control_name)
280
281 raise ServodError("'interface' key not found in params dict")
282 index = int(params['interface']) - 1
283 interface = self._interface_list[index]
284 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
285 drv_pkg = imp.load_module('drv',
286 *imp.find_module('drv', servo_pkg.__path__))
287 drv_name = params['drv']
288 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800289 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700290 drv = drv_class(interface, params)
291 if control_name not in self._drv_dict:
292 self._drv_dict[control_name] = {}
293 if is_get:
294 self._drv_dict[control_name]['get'] = (params, drv)
295 else:
296 self._drv_dict[control_name]['set'] = (params, drv)
297 return (params, drv)
298
299 def doc_all(self):
300 """Return all documenation for controls.
301
302 Returns:
303 string of <doc> text in config file (xml) and the params dictionary for
304 all controls.
305
306 For example:
307 warm_reset :: Reset the device warmly
308 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
309 """
310 return self._syscfg.display_config()
311
312 def doc(self, name):
313 """Retreive doc string in system config file for given control name.
314
315 Args:
316 name: name string of control to get doc string
317
318 Returns:
319 doc string of name
320
321 Raises:
322 NameError: if fails to locate control
323 """
324 self._logger.debug("name(%s)" % (name))
325 if self._syscfg.is_control(name):
326 return self._syscfg.get_control_docstring(name)
327 else:
328 raise NameError("No control %s" %name)
329
Simran Basia9f41032012-05-11 14:21:58 -0700330 def _get_usb_port_set(self):
331 """Gets a set of USB disks currently connected to the system
332
333 Returns:
334 A set of USB disk paths.
335 """
336 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
337 return set(["/dev/" + dev for dev in usb_set])
338
339 def _probe_host_usb_dev(self):
340 """Probe the USB disk device plugged in the servo from the host side.
341
342 Method can fail by:
343 1) Having multiple servos connected and returning incorrect /dev/sdX of
344 another servo.
345 2) Finding multiple /dev/sdX and returning None.
346
347 Returns:
348 USB disk path if one and only one USB disk path is found, otherwise None.
349 """
350 original_value = self.get("usb_mux_sel1")
351 # Make the host unable to see the USB disk.
352 if original_value != "dut_sees_usbkey":
353 self.set("usb_mux_sel1", "dut_sees_usbkey")
354 time.sleep(self._USB_DETECTION_DELAY)
355
356 no_usb_set = self._get_usb_port_set()
357 # Make the host able to see the USB disk.
358 self.set("usb_mux_sel1", "servo_sees_usbkey")
359 time.sleep(self._USB_DETECTION_DELAY)
360
361 has_usb_set = self._get_usb_port_set()
362 # Back to its original value.
363 if original_value != "servo_sees_usbkey":
364 self.set("usb_mux_sel1", original_value)
365 time.sleep(self._USB_DETECTION_DELAY)
366 # Subtract the two sets to find the usb device.
367 diff_set = has_usb_set - no_usb_set
368 if len(diff_set) == 1:
369 return diff_set.pop()
370 else:
371 return None
372
373 def download_image_to_usb(self, image_path):
374 """Download image and save to the USB device found by probe_host_usb_dev.
375 If the image_path is a URL, it will download this url to the USB path;
376 otherwise it will simply copy the image_path's contents to the USB path.
377
378 Args:
379 image_path: path or url to the recovery image.
380
381 Returns:
382 True|False: True if process completed successfully, False if error
383 occurred.
384 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
385 comment at the end of set().
386 """
387 self._logger.debug("image_path(%s)" % image_path)
388 self._logger.debug("Detecting USB stick device...")
389 usb_dev = self._probe_host_usb_dev()
390 if not usb_dev:
391 self._logger.error("No usb device connected to servo")
392 return False
393
394 try:
395 if image_path.startswith(self._HTTP_PREFIX):
396 self._logger.debug("Image path is a URL, downloading image")
397 urllib.urlretrieve(image_path, usb_dev)
398 else:
399 shutil.copyfile(image_path, usb_dev)
400 except IOError as e:
401 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
402 e.strerror, e.errno)
403 return False
404 except urllib.ContentTooShortError:
405 self._logger.error("Failed to download URL: %s to USB device: %s",
406 image_path, usb_dev)
407 return False
408 except BaseException as e:
409 self._logger.error("Unexpected exception downloading %s to %s: %s",
410 image_path, usb_dev, str(e))
411 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800412 finally:
413 # We just plastered the partition table for a block device.
414 # Pass or fail, we mustn't go without telling the kernel about
415 # the change, or it will punish us with sporadic, hard-to-debug
416 # failures.
417 subprocess.call(["sync"])
418 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700419 return True
420
421 def make_image_noninteractive(self):
422 """Makes the recovery image noninteractive.
423
424 A noninteractive image will reboot automatically after installation
425 instead of waiting for the USB device to be removed to initiate a system
426 reboot.
427
428 Mounts partition 1 of the image stored on usb_dev and creates a file
429 called "non_interactive" so that the image will become noninteractive.
430
431 Returns:
432 True|False: True if process completed successfully, False if error
433 occurred.
434 """
435 result = True
436 usb_dev = self._probe_host_usb_dev()
437 if not usb_dev:
438 self._logger.error("No usb device connected to servo")
439 return False
440 # Create TempDirectory
441 tmpdir = tempfile.mkdtemp()
442 if tmpdir:
443 # Mount drive to tmpdir.
444 partition_1 = "%s1" % usb_dev
445 rc = subprocess.call(["mount", partition_1, tmpdir])
446 if rc == 0:
447 # Create file 'non_interactive'
448 non_interactive_file = os.path.join(tmpdir, "non_interactive")
449 try:
450 open(non_interactive_file, "w").close()
451 except IOError as e:
452 self._logger.error("Failed to create file %s : %s ( %d )",
453 non_interactive_file, e.strerror, e.errno)
454 result = False
455 except BaseException as e:
456 self._logger.error("Unexpected Exception creating file %s : %s",
457 non_interactive_file, str(e))
458 result = False
459 # Unmount drive regardless if file creation worked or not.
460 rc = subprocess.call(["umount", partition_1])
461 if rc != 0:
462 self._logger.error("Failed to unmount USB Device")
463 result = False
464 else:
465 self._logger.error("Failed to mount USB Device")
466 result = False
467
468 # Delete tmpdir. May throw exception if 'umount' failed.
469 try:
470 os.rmdir(tmpdir)
471 except OSError as e:
472 self._logger.error("Failed to remove temp directory %s : %s",
473 tmpdir, str(e))
474 return False
475 except BaseException as e:
476 self._logger.error("Unexpected Exception removing tempdir %s : %s",
477 tmpdir, str(e))
478 return False
479 else:
480 self._logger.error("Failed to create temp directory.")
481 return False
482 return result
483
Todd Broch352b4b22013-03-22 09:48:40 -0700484 def set_get_all(self, cmds):
485 """Set &| get one or more control values.
486
487 Args:
488 cmds: list of control[:value] to get or set.
489
490 Returns:
491 rv: list of responses from calling get or set methods.
492 """
493 rv = []
494 for cmd in cmds:
495 if ':' in cmd:
496 (control, value) = cmd.split(':')
497 rv.append(self.set(control, value))
498 else:
499 rv.append(self.get(cmd))
500 return rv
501
Todd Broche505b8d2011-03-21 18:19:54 -0700502 def get(self, name):
503 """Get control value.
504
505 Args:
506 name: name string of control
507
508 Returns:
509 Response from calling drv get method. Value is reformatted based on
510 control's dictionary parameters
511
512 Raises:
513 HwDriverError: Error occurred while using drv
514 """
515 self._logger.debug("name(%s)" % (name))
516 (param, drv) = self._get_param_drv(name)
517 try:
518 val = drv.get()
519 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800520 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700521 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700522 except AttributeError, error:
523 self._logger.error("Getting %s: %s" % (name, error))
524 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800525 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700526 self._logger.error("Getting %s" % (name))
527 raise
Todd Brochd6061672012-05-11 15:52:47 -0700528
Todd Broche505b8d2011-03-21 18:19:54 -0700529 def get_all(self, verbose):
530 """Get all controls values.
531
532 Args:
533 verbose: Boolean on whether to return doc info as well
534
535 Returns:
536 string creating from trying to get all values of all controls. In case of
537 error attempting access to control, response is 'ERR'.
538 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800539 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700540 for name in self._syscfg.syscfg_dict['control']:
541 self._logger.debug("name = %s" %name)
542 try:
543 value = self.get(name)
544 except Exception:
545 value = "ERR"
546 pass
547 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800548 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700549 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800550 rsp.append("%s:%s" % (name, value))
551 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700552
553 def set(self, name, wr_val_str):
554 """Set control.
555
556 Args:
557 name: name string of control
558 wr_val_str: value string to write. Can be integer, float or a
559 alpha-numerical that is mapped to a integer or float.
560
561 Raises:
562 HwDriverError: Error occurred while using driver
563 """
Todd Broch7a91c252012-02-03 12:37:45 -0800564 if name == 'sleep':
565 time.sleep(float(wr_val_str))
566 return True
567
Todd Broche505b8d2011-03-21 18:19:54 -0700568 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
569 (params, drv) = self._get_param_drv(name, False)
570 wr_val = self._syscfg.resolve_val(params, wr_val_str)
571 try:
572 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800573 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700574 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
575 raise
576 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
577 # & client I still have to return something to appease the
578 # marshall/unmarshall
579 return True
580
Todd Brochd6061672012-05-11 15:52:47 -0700581 def hwinit(self, verbose=False):
582 """Initialize all controls.
583
584 These values are part of the system config XML files of the form
585 init=<value>. This command should be used by clients wishing to return the
586 servo and DUT its connected to a known good/safe state.
587
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800588 Note that initialization errors are ignored (as in some cases they could
589 be caused by DUT firmware deficiencies). This might need to be fine tuned
590 later.
591
Todd Brochd6061672012-05-11 15:52:47 -0700592 Args:
593 verbose: boolean, if True prints info about control initialized.
594 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800595
596 Returns:
597 This function is called across RPC and as such is expected to return
598 something unless transferring 'none' across is allowed. Hence adding a
599 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700600 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800601 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800602 try:
603 self.set(control_name, value)
604 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800605 self._logger.error("Problem initializing %s -> %s :: %s",
606 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700607 if verbose:
608 self._logger.info('Initialized %s to %s', control_name, value)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800609 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800610
Todd Broche505b8d2011-03-21 18:19:54 -0700611 def echo(self, echo):
612 """Dummy echo function for testing/examples.
613
614 Args:
615 echo: string to echo back to client
616 """
617 self._logger.debug("echo(%s)" % (echo))
618 return "ECH0ING: %s" % (echo)
619
J. Richard Barnettee2820552013-03-14 16:13:46 -0700620 def get_board(self):
621 """Return the board specified at startup, if any."""
622 return self._board
623
Todd Brochdbb09982011-10-02 07:14:26 -0700624
Todd Broche505b8d2011-03-21 18:19:54 -0700625def test():
626 """Integration testing.
627
628 TODO(tbroch) Enhance integration test and add unittest (see mox)
629 """
630 logging.basicConfig(level=logging.DEBUG,
631 format="%(asctime)s - %(name)s - " +
632 "%(levelname)s - %(message)s")
633 # configure server & listen
634 servod_obj = Servod(1)
635 # 4 == number of interfaces on a FT4232H device
636 for i in xrange(4):
637 if i == 1:
638 # its an i2c interface ... see __init__ for details and TODO to make
639 # this configureable
640 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
641 else:
642 # its a gpio interface
643 servod_obj._interface_list[i].wr_rd(0)
644
645 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
646 allow_none=True)
647 server.register_introspection_functions()
648 server.register_multicall_functions()
649 server.register_instance(servod_obj)
650 logging.info("Listening on localhost port 9999")
651 server.serve_forever()
652
653if __name__ == "__main__":
654 test()
655
656 # simple client transaction would look like
657 """
658 remote_uri = 'http://localhost:9999'
659 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
660 send_str = "Hello_there"
661 print "Sent " + send_str + ", Recv " + client.echo(send_str)
662 """