blob: fec57d5af53e0eec7d7f6e441cab4d7d32089a12 [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
Todd Broche505b8d2011-03-21 18:19:54 -070018import ftdigpio
19import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070020import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070021import ftdiuart
Simran Basie750a342013-03-12 13:45:26 -070022import servo_interfaces
Todd Broche505b8d2011-03-21 18:19:54 -070023
24MAX_I2C_CLOCK_HZ = 100000
25
Todd Brochdbb09982011-10-02 07:14:26 -070026
Todd Broche505b8d2011-03-21 18:19:54 -070027class ServodError(Exception):
28 """Exception class for servod."""
29
30class Servod(object):
31 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070032 _USB_DETECTION_DELAY = 10
33 _HTTP_PREFIX = "http://"
34
J. Richard Barnettee2820552013-03-14 16:13:46 -070035 def __init__(self, config, vendor, product, serialname=None,
36 interfaces=None, board=""):
Todd Broche505b8d2011-03-21 18:19:54 -070037 """Servod constructor.
38
39 Args:
40 config: instance of SystemConfig containing all controls for
41 particular Servod invocation
42 vendor: usb vendor id of FTDI device
43 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070044 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070045 interfaces: list of strings of interface types the server will instantiate
46
47 Raises:
48 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070049 """
50 self._logger = logging.getLogger("Servod")
51 self._logger.debug("")
52 self._vendor = vendor
53 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070054 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070055 self._syscfg = config
56 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
57 # interfaces are mapped to
58 self._interface_list = []
59 # Dict of Dict to map control name, function name to to tuple (params, drv)
60 # Ex) _drv_dict[name]['get'] = (params, drv)
61 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070062 self._board = board
Todd Broche505b8d2011-03-21 18:19:54 -070063
Todd Brochdbb09982011-10-02 07:14:26 -070064 # Note, interface i is (i - 1) in list
65 if not interfaces:
Simran Basie750a342013-03-12 13:45:26 -070066 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070067
68 for i, name in enumerate(interfaces):
Todd Broch8a77a992012-01-27 09:46:08 -080069 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
70 if i and ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
71 self._product += 1
72 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
73 self._product)
74
Todd Brochdbb09982011-10-02 07:14:26 -070075 self._logger.info("Initializing FTDI interface %d to %s", i + 1, name)
76 try:
77 func = getattr(self, '_init_%s' % name)
78 except AttributeError:
79 raise ServodError("Unable to locate init for interface %s" % name)
Todd Brocha9c74692012-01-24 22:54:22 -080080 result = func((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1)
Todd Broch888da782011-10-07 14:29:09 -070081 if isinstance(result, tuple):
82 self._interface_list.extend(result)
83 else:
84 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -070085
Todd Broch3ec8df02012-11-20 10:53:03 -080086 def __del__(self):
87 """Servod deconstructor."""
88 for interface in self._interface_list:
89 del(interface)
90
Todd Brochb3048492012-01-15 21:52:41 -080091 def _init_dummy(self, interface):
92 """Initialize dummy interface.
93
94 Dummy interface is just a mechanism to reserve that interface for non servod
95 interaction. Typically the interface will be managed by external
96 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
97 interfaces.
98
99 TODO(tbroch): Investigate merits of incorporating these third-party
100 interfaces into servod or creating a communication channel between them
101
102 Returns: None
103 """
104 return None
105
Simran Basie750a342013-03-12 13:45:26 -0700106 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700107 """Initialize gpio driver interface and open for use.
108
109 Args:
110 interface: interface number of FTDI device to use.
111
112 Returns:
113 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700114
115 Raises:
116 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700117 """
Todd Brochad034442011-05-25 15:05:29 -0700118 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
119 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700120 try:
121 fobj.open()
122 except ftdigpio.FgpioError as e:
123 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
124
Todd Broche505b8d2011-03-21 18:19:54 -0700125 return fobj
126
Simran Basie750a342013-03-12 13:45:26 -0700127 # TODO (sbasi) crbug.com/187488 - Implement BBgpio.
128 def _init_bb_gpio(self, interface):
129 """Initalize beaglebone gpio interface."""
130 pass
131
132 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700133 """Initialize i2c interface and open for use.
134
135 Args:
136 interface: interface number of FTDI device to use
137
138 Returns:
139 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700140
141 Raises:
142 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700143 """
Todd Brochad034442011-05-25 15:05:29 -0700144 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
145 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700146 try:
147 fobj.open()
148 except ftdii2c.Fi2cError as e:
149 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
150
Todd Broche505b8d2011-03-21 18:19:54 -0700151 # Set the frequency of operation of the i2c bus.
152 # TODO(tbroch) make configureable
153 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700154
Todd Broche505b8d2011-03-21 18:19:54 -0700155 return fobj
156
Simran Basie750a342013-03-12 13:45:26 -0700157 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
158 def _init_bb_i2c(self, interface):
159 """Initalize beaglebone i2c interface."""
160 pass
161
162 def _init_ftdi_uart(self, interface):
163 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700164
165 Note, the uart runs in a separate thread (pthreads). Users wishing to
166 interact with it will query control for the pty's pathname and connect
167 with there favorite console program. For example:
168 cu -l /dev/pts/22
169
170 Args:
171 interface: interface number of FTDI device to use
172
173 Returns:
174 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700175
176 Raises:
177 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700178 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700179 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
180 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700181 try:
182 fobj.run()
183 except ftdiuart.FuartError as e:
184 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
185
Todd Broch47c43f42011-05-26 15:11:31 -0700186 self._logger.info("%s" % fobj.get_pty())
187 return fobj
188
Simran Basie750a342013-03-12 13:45:26 -0700189 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
190 def _init_bb_uart(self, interface):
191 """Initalize beaglebone uart interface."""
192 pass
193
194 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700195 """Initialize special gpio + uart interface and open for use
196
197 Note, the uart runs in a separate thread (pthreads). Users wishing to
198 interact with it will query control for the pty's pathname and connect
199 with there favorite console program. For example:
200 cu -l /dev/pts/22
201
202 Args:
203 interface: interface number of FTDI device to use
204
205 Returns:
206 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700207
208 Raises:
209 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700210 """
Simran Basie750a342013-03-12 13:45:26 -0700211 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700212 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
213 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700214 try:
215 fuart.run()
216 except ftdiuart.FuartError as e:
217 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
218
Todd Broch888da782011-10-07 14:29:09 -0700219 self._logger.info("uart pty: %s" % fuart.get_pty())
220 return fgpio, fuart
221
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800222 def _camel_case(self, string):
223 output = ''
224 for s in string.split('_'):
225 if output:
226 output += s.capitalize()
227 else:
228 output = s
229 return output
230
Todd Broche505b8d2011-03-21 18:19:54 -0700231 def _get_param_drv(self, control_name, is_get=True):
232 """Get access to driver for a given control.
233
234 Note, some controls have different parameter dictionaries for 'getting' the
235 control's value versus 'setting' it. Boolean is_get distinguishes which is
236 being requested.
237
238 Args:
239 control_name: string name of control
240 is_get: boolean to determine
241
242 Returns:
243 tuple (param, drv) where:
244 param: param dictionary for control
245 drv: instance object of driver for particular control
246
247 Raises:
248 ServodError: Error occurred while examining params dict
249 """
250 self._logger.debug("")
251 # if already setup just return tuple from driver dict
252 if control_name in self._drv_dict:
253 if is_get and ('get' in self._drv_dict[control_name]):
254 return self._drv_dict[control_name]['get']
255 if not is_get and ('set' in self._drv_dict[control_name]):
256 return self._drv_dict[control_name]['set']
257
258 params = self._syscfg.lookup_control_params(control_name, is_get)
259 if 'drv' not in params:
260 self._logger.error("Unable to determine driver for %s" % control_name)
261 raise ServodError("'drv' key not found in params dict")
262 if 'interface' not in params:
263 self._logger.error("Unable to determine interface for %s" %
264 control_name)
265
266 raise ServodError("'interface' key not found in params dict")
267 index = int(params['interface']) - 1
268 interface = self._interface_list[index]
269 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
270 drv_pkg = imp.load_module('drv',
271 *imp.find_module('drv', servo_pkg.__path__))
272 drv_name = params['drv']
273 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800274 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700275 drv = drv_class(interface, params)
276 if control_name not in self._drv_dict:
277 self._drv_dict[control_name] = {}
278 if is_get:
279 self._drv_dict[control_name]['get'] = (params, drv)
280 else:
281 self._drv_dict[control_name]['set'] = (params, drv)
282 return (params, drv)
283
284 def doc_all(self):
285 """Return all documenation for controls.
286
287 Returns:
288 string of <doc> text in config file (xml) and the params dictionary for
289 all controls.
290
291 For example:
292 warm_reset :: Reset the device warmly
293 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
294 """
295 return self._syscfg.display_config()
296
297 def doc(self, name):
298 """Retreive doc string in system config file for given control name.
299
300 Args:
301 name: name string of control to get doc string
302
303 Returns:
304 doc string of name
305
306 Raises:
307 NameError: if fails to locate control
308 """
309 self._logger.debug("name(%s)" % (name))
310 if self._syscfg.is_control(name):
311 return self._syscfg.get_control_docstring(name)
312 else:
313 raise NameError("No control %s" %name)
314
Simran Basia9f41032012-05-11 14:21:58 -0700315 def _get_usb_port_set(self):
316 """Gets a set of USB disks currently connected to the system
317
318 Returns:
319 A set of USB disk paths.
320 """
321 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
322 return set(["/dev/" + dev for dev in usb_set])
323
324 def _probe_host_usb_dev(self):
325 """Probe the USB disk device plugged in the servo from the host side.
326
327 Method can fail by:
328 1) Having multiple servos connected and returning incorrect /dev/sdX of
329 another servo.
330 2) Finding multiple /dev/sdX and returning None.
331
332 Returns:
333 USB disk path if one and only one USB disk path is found, otherwise None.
334 """
335 original_value = self.get("usb_mux_sel1")
336 # Make the host unable to see the USB disk.
337 if original_value != "dut_sees_usbkey":
338 self.set("usb_mux_sel1", "dut_sees_usbkey")
339 time.sleep(self._USB_DETECTION_DELAY)
340
341 no_usb_set = self._get_usb_port_set()
342 # Make the host able to see the USB disk.
343 self.set("usb_mux_sel1", "servo_sees_usbkey")
344 time.sleep(self._USB_DETECTION_DELAY)
345
346 has_usb_set = self._get_usb_port_set()
347 # Back to its original value.
348 if original_value != "servo_sees_usbkey":
349 self.set("usb_mux_sel1", original_value)
350 time.sleep(self._USB_DETECTION_DELAY)
351 # Subtract the two sets to find the usb device.
352 diff_set = has_usb_set - no_usb_set
353 if len(diff_set) == 1:
354 return diff_set.pop()
355 else:
356 return None
357
358 def download_image_to_usb(self, image_path):
359 """Download image and save to the USB device found by probe_host_usb_dev.
360 If the image_path is a URL, it will download this url to the USB path;
361 otherwise it will simply copy the image_path's contents to the USB path.
362
363 Args:
364 image_path: path or url to the recovery image.
365
366 Returns:
367 True|False: True if process completed successfully, False if error
368 occurred.
369 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
370 comment at the end of set().
371 """
372 self._logger.debug("image_path(%s)" % image_path)
373 self._logger.debug("Detecting USB stick device...")
374 usb_dev = self._probe_host_usb_dev()
375 if not usb_dev:
376 self._logger.error("No usb device connected to servo")
377 return False
378
379 try:
380 if image_path.startswith(self._HTTP_PREFIX):
381 self._logger.debug("Image path is a URL, downloading image")
382 urllib.urlretrieve(image_path, usb_dev)
383 else:
384 shutil.copyfile(image_path, usb_dev)
385 except IOError as e:
386 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
387 e.strerror, e.errno)
388 return False
389 except urllib.ContentTooShortError:
390 self._logger.error("Failed to download URL: %s to USB device: %s",
391 image_path, usb_dev)
392 return False
393 except BaseException as e:
394 self._logger.error("Unexpected exception downloading %s to %s: %s",
395 image_path, usb_dev, str(e))
396 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800397 finally:
398 # We just plastered the partition table for a block device.
399 # Pass or fail, we mustn't go without telling the kernel about
400 # the change, or it will punish us with sporadic, hard-to-debug
401 # failures.
402 subprocess.call(["sync"])
403 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700404 return True
405
406 def make_image_noninteractive(self):
407 """Makes the recovery image noninteractive.
408
409 A noninteractive image will reboot automatically after installation
410 instead of waiting for the USB device to be removed to initiate a system
411 reboot.
412
413 Mounts partition 1 of the image stored on usb_dev and creates a file
414 called "non_interactive" so that the image will become noninteractive.
415
416 Returns:
417 True|False: True if process completed successfully, False if error
418 occurred.
419 """
420 result = True
421 usb_dev = self._probe_host_usb_dev()
422 if not usb_dev:
423 self._logger.error("No usb device connected to servo")
424 return False
425 # Create TempDirectory
426 tmpdir = tempfile.mkdtemp()
427 if tmpdir:
428 # Mount drive to tmpdir.
429 partition_1 = "%s1" % usb_dev
430 rc = subprocess.call(["mount", partition_1, tmpdir])
431 if rc == 0:
432 # Create file 'non_interactive'
433 non_interactive_file = os.path.join(tmpdir, "non_interactive")
434 try:
435 open(non_interactive_file, "w").close()
436 except IOError as e:
437 self._logger.error("Failed to create file %s : %s ( %d )",
438 non_interactive_file, e.strerror, e.errno)
439 result = False
440 except BaseException as e:
441 self._logger.error("Unexpected Exception creating file %s : %s",
442 non_interactive_file, str(e))
443 result = False
444 # Unmount drive regardless if file creation worked or not.
445 rc = subprocess.call(["umount", partition_1])
446 if rc != 0:
447 self._logger.error("Failed to unmount USB Device")
448 result = False
449 else:
450 self._logger.error("Failed to mount USB Device")
451 result = False
452
453 # Delete tmpdir. May throw exception if 'umount' failed.
454 try:
455 os.rmdir(tmpdir)
456 except OSError as e:
457 self._logger.error("Failed to remove temp directory %s : %s",
458 tmpdir, str(e))
459 return False
460 except BaseException as e:
461 self._logger.error("Unexpected Exception removing tempdir %s : %s",
462 tmpdir, str(e))
463 return False
464 else:
465 self._logger.error("Failed to create temp directory.")
466 return False
467 return result
468
Todd Broche505b8d2011-03-21 18:19:54 -0700469 def get(self, name):
470 """Get control value.
471
472 Args:
473 name: name string of control
474
475 Returns:
476 Response from calling drv get method. Value is reformatted based on
477 control's dictionary parameters
478
479 Raises:
480 HwDriverError: Error occurred while using drv
481 """
482 self._logger.debug("name(%s)" % (name))
483 (param, drv) = self._get_param_drv(name)
484 try:
485 val = drv.get()
486 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800487 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700488 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700489 except AttributeError, error:
490 self._logger.error("Getting %s: %s" % (name, error))
491 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800492 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700493 self._logger.error("Getting %s" % (name))
494 raise
Todd Brochd6061672012-05-11 15:52:47 -0700495
Todd Broche505b8d2011-03-21 18:19:54 -0700496 def get_all(self, verbose):
497 """Get all controls values.
498
499 Args:
500 verbose: Boolean on whether to return doc info as well
501
502 Returns:
503 string creating from trying to get all values of all controls. In case of
504 error attempting access to control, response is 'ERR'.
505 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800506 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700507 for name in self._syscfg.syscfg_dict['control']:
508 self._logger.debug("name = %s" %name)
509 try:
510 value = self.get(name)
511 except Exception:
512 value = "ERR"
513 pass
514 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800515 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700516 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800517 rsp.append("%s:%s" % (name, value))
518 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700519
520 def set(self, name, wr_val_str):
521 """Set control.
522
523 Args:
524 name: name string of control
525 wr_val_str: value string to write. Can be integer, float or a
526 alpha-numerical that is mapped to a integer or float.
527
528 Raises:
529 HwDriverError: Error occurred while using driver
530 """
Todd Broch7a91c252012-02-03 12:37:45 -0800531 if name == 'sleep':
532 time.sleep(float(wr_val_str))
533 return True
534
Todd Broche505b8d2011-03-21 18:19:54 -0700535 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
536 (params, drv) = self._get_param_drv(name, False)
537 wr_val = self._syscfg.resolve_val(params, wr_val_str)
538 try:
539 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800540 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700541 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
542 raise
543 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
544 # & client I still have to return something to appease the
545 # marshall/unmarshall
546 return True
547
Todd Brochd6061672012-05-11 15:52:47 -0700548 def hwinit(self, verbose=False):
549 """Initialize all controls.
550
551 These values are part of the system config XML files of the form
552 init=<value>. This command should be used by clients wishing to return the
553 servo and DUT its connected to a known good/safe state.
554
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800555 Note that initialization errors are ignored (as in some cases they could
556 be caused by DUT firmware deficiencies). This might need to be fine tuned
557 later.
558
Todd Brochd6061672012-05-11 15:52:47 -0700559 Args:
560 verbose: boolean, if True prints info about control initialized.
561 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800562
563 Returns:
564 This function is called across RPC and as such is expected to return
565 something unless transferring 'none' across is allowed. Hence adding a
566 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700567 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800568 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800569 try:
570 self.set(control_name, value)
571 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800572 self._logger.error("Problem initializing %s -> %s :: %s",
573 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700574 if verbose:
575 self._logger.info('Initialized %s to %s', control_name, value)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800576 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800577
Todd Broche505b8d2011-03-21 18:19:54 -0700578 def echo(self, echo):
579 """Dummy echo function for testing/examples.
580
581 Args:
582 echo: string to echo back to client
583 """
584 self._logger.debug("echo(%s)" % (echo))
585 return "ECH0ING: %s" % (echo)
586
J. Richard Barnettee2820552013-03-14 16:13:46 -0700587 def get_board(self):
588 """Return the board specified at startup, if any."""
589 return self._board
590
Todd Brochdbb09982011-10-02 07:14:26 -0700591
Todd Broche505b8d2011-03-21 18:19:54 -0700592def test():
593 """Integration testing.
594
595 TODO(tbroch) Enhance integration test and add unittest (see mox)
596 """
597 logging.basicConfig(level=logging.DEBUG,
598 format="%(asctime)s - %(name)s - " +
599 "%(levelname)s - %(message)s")
600 # configure server & listen
601 servod_obj = Servod(1)
602 # 4 == number of interfaces on a FT4232H device
603 for i in xrange(4):
604 if i == 1:
605 # its an i2c interface ... see __init__ for details and TODO to make
606 # this configureable
607 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
608 else:
609 # its a gpio interface
610 servod_obj._interface_list[i].wr_rd(0)
611
612 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
613 allow_none=True)
614 server.register_introspection_functions()
615 server.register_multicall_functions()
616 server.register_instance(servod_obj)
617 logging.info("Listening on localhost port 9999")
618 server.serve_forever()
619
620if __name__ == "__main__":
621 test()
622
623 # simple client transaction would look like
624 """
625 remote_uri = 'http://localhost:9999'
626 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
627 send_str = "Hello_there"
628 print "Sent " + send_str + ", Recv " + client.echo(send_str)
629 """