blob: ba464cdbedc5f12e4e622c386ec99b46c2c446b0 [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
Fang Deng90377712013-06-03 15:51:48 -070036 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070037 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070038 _USB_J3 = "usb_mux_sel1"
39 _USB_J3_TO_SERVO = "servo_sees_usbkey"
40 _USB_J3_TO_DUT = "dut_sees_usbkey"
41 _USB_J3_PWR = "prtctl4_pwren"
42 _USB_J3_PWR_ON = "on"
43 _USB_J3_PWR_OFF = "off"
Simran Basia9f41032012-05-11 14:21:58 -070044
J. Richard Barnettee2820552013-03-14 16:13:46 -070045 def __init__(self, config, vendor, product, serialname=None,
46 interfaces=None, board=""):
Todd Broche505b8d2011-03-21 18:19:54 -070047 """Servod constructor.
48
49 Args:
50 config: instance of SystemConfig containing all controls for
51 particular Servod invocation
52 vendor: usb vendor id of FTDI device
53 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070054 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070055 interfaces: list of strings of interface types the server will instantiate
56
57 Raises:
58 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070059 """
60 self._logger = logging.getLogger("Servod")
61 self._logger.debug("")
62 self._vendor = vendor
63 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070064 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070065 self._syscfg = config
66 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
67 # interfaces are mapped to
68 self._interface_list = []
69 # Dict of Dict to map control name, function name to to tuple (params, drv)
70 # Ex) _drv_dict[name]['get'] = (params, drv)
71 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070072 self._board = board
Todd Broche505b8d2011-03-21 18:19:54 -070073
Todd Brochdbb09982011-10-02 07:14:26 -070074 # Note, interface i is (i - 1) in list
75 if not interfaces:
Simran Basie750a342013-03-12 13:45:26 -070076 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070077
Simran Basia9ad25e2013-04-23 11:57:00 -070078 for i, interface in enumerate(interfaces):
79 is_ftdi_interface = False
80 if type(interface) is dict:
81 name = interface['name']
82 elif type(interface) is str:
83 # Its FTDI related interface
84 name = interface
85 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
86 is_ftdi_interface = True
87 else:
88 raise ServodError("Illegal interface type %s" % type(interface))
89
Todd Broch8a77a992012-01-27 09:46:08 -080090 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -070091 if is_ftdi_interface and i and \
92 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -080093 self._product += 1
94 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
95 self._product)
96
Simran Basia9ad25e2013-04-23 11:57:00 -070097 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -070098 try:
99 func = getattr(self, '_init_%s' % name)
100 except AttributeError:
101 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -0700102 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -0700103 if isinstance(result, tuple):
104 self._interface_list.extend(result)
105 else:
106 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700107
Todd Broch3ec8df02012-11-20 10:53:03 -0800108 def __del__(self):
109 """Servod deconstructor."""
110 for interface in self._interface_list:
111 del(interface)
112
Todd Brochb3048492012-01-15 21:52:41 -0800113 def _init_dummy(self, interface):
114 """Initialize dummy interface.
115
116 Dummy interface is just a mechanism to reserve that interface for non servod
117 interaction. Typically the interface will be managed by external
118 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
119 interfaces.
120
121 TODO(tbroch): Investigate merits of incorporating these third-party
122 interfaces into servod or creating a communication channel between them
123
124 Returns: None
125 """
126 return None
127
Simran Basie750a342013-03-12 13:45:26 -0700128 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700129 """Initialize gpio driver interface and open for use.
130
131 Args:
132 interface: interface number of FTDI device to use.
133
134 Returns:
135 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700136
137 Raises:
138 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700139 """
Todd Brochad034442011-05-25 15:05:29 -0700140 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
141 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700142 try:
143 fobj.open()
144 except ftdigpio.FgpioError as e:
145 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
146
Todd Broche505b8d2011-03-21 18:19:54 -0700147 return fobj
148
Simran Basie750a342013-03-12 13:45:26 -0700149 def _init_bb_gpio(self, interface):
150 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700151 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700152
153 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700154 """Initialize i2c interface and open for use.
155
156 Args:
157 interface: interface number of FTDI device to use
158
159 Returns:
160 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700161
162 Raises:
163 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700164 """
Todd Brochad034442011-05-25 15:05:29 -0700165 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
166 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700167 try:
168 fobj.open()
169 except ftdii2c.Fi2cError as e:
170 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
171
Todd Broche505b8d2011-03-21 18:19:54 -0700172 # Set the frequency of operation of the i2c bus.
173 # TODO(tbroch) make configureable
174 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700175
Todd Broche505b8d2011-03-21 18:19:54 -0700176 return fobj
177
Simran Basie750a342013-03-12 13:45:26 -0700178 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
179 def _init_bb_i2c(self, interface):
180 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700181 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700182
183 def _init_ftdi_uart(self, interface):
184 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700185
186 Note, the uart runs in a separate thread (pthreads). Users wishing to
187 interact with it will query control for the pty's pathname and connect
188 with there favorite console program. For example:
189 cu -l /dev/pts/22
190
191 Args:
192 interface: interface number of FTDI device to use
193
194 Returns:
195 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700196
197 Raises:
198 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700199 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700200 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
201 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700202 try:
203 fobj.run()
204 except ftdiuart.FuartError as e:
205 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
206
Todd Broch47c43f42011-05-26 15:11:31 -0700207 self._logger.info("%s" % fobj.get_pty())
208 return fobj
209
Simran Basie750a342013-03-12 13:45:26 -0700210 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
211 def _init_bb_uart(self, interface):
212 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700213 logging.debug('UART INTERFACE: %s', interface)
214 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700215
216 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700217 """Initialize special gpio + uart interface and open for use
218
219 Note, the uart runs in a separate thread (pthreads). Users wishing to
220 interact with it will query control for the pty's pathname and connect
221 with there favorite console program. For example:
222 cu -l /dev/pts/22
223
224 Args:
225 interface: interface number of FTDI device to use
226
227 Returns:
228 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700229
230 Raises:
231 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700232 """
Simran Basie750a342013-03-12 13:45:26 -0700233 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700234 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
235 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700236 try:
237 fuart.run()
238 except ftdiuart.FuartError as e:
239 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
240
Todd Broch888da782011-10-07 14:29:09 -0700241 self._logger.info("uart pty: %s" % fuart.get_pty())
242 return fgpio, fuart
243
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800244 def _camel_case(self, string):
245 output = ''
246 for s in string.split('_'):
247 if output:
248 output += s.capitalize()
249 else:
250 output = s
251 return output
252
Todd Broche505b8d2011-03-21 18:19:54 -0700253 def _get_param_drv(self, control_name, is_get=True):
254 """Get access to driver for a given control.
255
256 Note, some controls have different parameter dictionaries for 'getting' the
257 control's value versus 'setting' it. Boolean is_get distinguishes which is
258 being requested.
259
260 Args:
261 control_name: string name of control
262 is_get: boolean to determine
263
264 Returns:
265 tuple (param, drv) where:
266 param: param dictionary for control
267 drv: instance object of driver for particular control
268
269 Raises:
270 ServodError: Error occurred while examining params dict
271 """
272 self._logger.debug("")
273 # if already setup just return tuple from driver dict
274 if control_name in self._drv_dict:
275 if is_get and ('get' in self._drv_dict[control_name]):
276 return self._drv_dict[control_name]['get']
277 if not is_get and ('set' in self._drv_dict[control_name]):
278 return self._drv_dict[control_name]['set']
279
280 params = self._syscfg.lookup_control_params(control_name, is_get)
281 if 'drv' not in params:
282 self._logger.error("Unable to determine driver for %s" % control_name)
283 raise ServodError("'drv' key not found in params dict")
284 if 'interface' not in params:
285 self._logger.error("Unable to determine interface for %s" %
286 control_name)
287
288 raise ServodError("'interface' key not found in params dict")
289 index = int(params['interface']) - 1
290 interface = self._interface_list[index]
291 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
292 drv_pkg = imp.load_module('drv',
293 *imp.find_module('drv', servo_pkg.__path__))
294 drv_name = params['drv']
295 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800296 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700297 drv = drv_class(interface, params)
298 if control_name not in self._drv_dict:
299 self._drv_dict[control_name] = {}
300 if is_get:
301 self._drv_dict[control_name]['get'] = (params, drv)
302 else:
303 self._drv_dict[control_name]['set'] = (params, drv)
304 return (params, drv)
305
306 def doc_all(self):
307 """Return all documenation for controls.
308
309 Returns:
310 string of <doc> text in config file (xml) and the params dictionary for
311 all controls.
312
313 For example:
314 warm_reset :: Reset the device warmly
315 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
316 """
317 return self._syscfg.display_config()
318
319 def doc(self, name):
320 """Retreive doc string in system config file for given control name.
321
322 Args:
323 name: name string of control to get doc string
324
325 Returns:
326 doc string of name
327
328 Raises:
329 NameError: if fails to locate control
330 """
331 self._logger.debug("name(%s)" % (name))
332 if self._syscfg.is_control(name):
333 return self._syscfg.get_control_docstring(name)
334 else:
335 raise NameError("No control %s" %name)
336
Fang Deng90377712013-06-03 15:51:48 -0700337 def _switch_usbkey(self, mux_direction):
338 """Connect USB flash stick to either servo or DUT.
339
340 This function switches 'usb_mux_sel1' to provide electrical
341 connection between the USB port J3 and either servo or DUT side.
342
343 Switching the usb mux is accompanied by powercycling
344 of the USB stick, because it sometimes gets wedged if the mux
345 is switched while the stick power is on.
346
347 Args:
348 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
349 """
350 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
351 time.sleep(self._USB_POWEROFF_DELAY)
352 self.set(self._USB_J3, mux_direction)
353 time.sleep(self._USB_POWEROFF_DELAY)
354 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
355 if mux_direction == self._USB_J3_TO_SERVO:
356 time.sleep(self._USB_DETECTION_DELAY)
357
Simran Basia9f41032012-05-11 14:21:58 -0700358 def _get_usb_port_set(self):
359 """Gets a set of USB disks currently connected to the system
360
361 Returns:
362 A set of USB disk paths.
363 """
364 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
365 return set(["/dev/" + dev for dev in usb_set])
366
367 def _probe_host_usb_dev(self):
368 """Probe the USB disk device plugged in the servo from the host side.
369
370 Method can fail by:
371 1) Having multiple servos connected and returning incorrect /dev/sdX of
372 another servo.
373 2) Finding multiple /dev/sdX and returning None.
374
375 Returns:
376 USB disk path if one and only one USB disk path is found, otherwise None.
377 """
Fang Deng90377712013-06-03 15:51:48 -0700378 original_value = self.get(self._USB_J3)
379 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700380 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700381 if (original_usb_power == self._USB_J3_PWR_ON and
382 original_value != self._USB_J3_TO_DUT):
383 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700384 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700385
Fang Deng90377712013-06-03 15:51:48 -0700386 # Make the host able to see the USB disk.
387 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700388 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700389
Simran Basia9f41032012-05-11 14:21:58 -0700390 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700391 if original_value != self._USB_J3_TO_SERVO:
392 self._switch_usbkey(original_value)
393 if original_usb_power != self._USB_J3_PWR_ON:
394 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
395 time.sleep(self._USB_POWEROFF_DELAY)
396
Simran Basia9f41032012-05-11 14:21:58 -0700397 # Subtract the two sets to find the usb device.
398 diff_set = has_usb_set - no_usb_set
399 if len(diff_set) == 1:
400 return diff_set.pop()
401 else:
402 return None
403
404 def download_image_to_usb(self, image_path):
405 """Download image and save to the USB device found by probe_host_usb_dev.
406 If the image_path is a URL, it will download this url to the USB path;
407 otherwise it will simply copy the image_path's contents to the USB path.
408
409 Args:
410 image_path: path or url to the recovery image.
411
412 Returns:
413 True|False: True if process completed successfully, False if error
414 occurred.
415 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
416 comment at the end of set().
417 """
418 self._logger.debug("image_path(%s)" % image_path)
419 self._logger.debug("Detecting USB stick device...")
420 usb_dev = self._probe_host_usb_dev()
421 if not usb_dev:
422 self._logger.error("No usb device connected to servo")
423 return False
424
425 try:
426 if image_path.startswith(self._HTTP_PREFIX):
427 self._logger.debug("Image path is a URL, downloading image")
428 urllib.urlretrieve(image_path, usb_dev)
429 else:
430 shutil.copyfile(image_path, usb_dev)
431 except IOError as e:
432 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
433 e.strerror, e.errno)
434 return False
435 except urllib.ContentTooShortError:
436 self._logger.error("Failed to download URL: %s to USB device: %s",
437 image_path, usb_dev)
438 return False
439 except BaseException as e:
440 self._logger.error("Unexpected exception downloading %s to %s: %s",
441 image_path, usb_dev, str(e))
442 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800443 finally:
444 # We just plastered the partition table for a block device.
445 # Pass or fail, we mustn't go without telling the kernel about
446 # the change, or it will punish us with sporadic, hard-to-debug
447 # failures.
448 subprocess.call(["sync"])
449 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700450 return True
451
452 def make_image_noninteractive(self):
453 """Makes the recovery image noninteractive.
454
455 A noninteractive image will reboot automatically after installation
456 instead of waiting for the USB device to be removed to initiate a system
457 reboot.
458
459 Mounts partition 1 of the image stored on usb_dev and creates a file
460 called "non_interactive" so that the image will become noninteractive.
461
462 Returns:
463 True|False: True if process completed successfully, False if error
464 occurred.
465 """
466 result = True
467 usb_dev = self._probe_host_usb_dev()
468 if not usb_dev:
469 self._logger.error("No usb device connected to servo")
470 return False
471 # Create TempDirectory
472 tmpdir = tempfile.mkdtemp()
473 if tmpdir:
474 # Mount drive to tmpdir.
475 partition_1 = "%s1" % usb_dev
476 rc = subprocess.call(["mount", partition_1, tmpdir])
477 if rc == 0:
478 # Create file 'non_interactive'
479 non_interactive_file = os.path.join(tmpdir, "non_interactive")
480 try:
481 open(non_interactive_file, "w").close()
482 except IOError as e:
483 self._logger.error("Failed to create file %s : %s ( %d )",
484 non_interactive_file, e.strerror, e.errno)
485 result = False
486 except BaseException as e:
487 self._logger.error("Unexpected Exception creating file %s : %s",
488 non_interactive_file, str(e))
489 result = False
490 # Unmount drive regardless if file creation worked or not.
491 rc = subprocess.call(["umount", partition_1])
492 if rc != 0:
493 self._logger.error("Failed to unmount USB Device")
494 result = False
495 else:
496 self._logger.error("Failed to mount USB Device")
497 result = False
498
499 # Delete tmpdir. May throw exception if 'umount' failed.
500 try:
501 os.rmdir(tmpdir)
502 except OSError as e:
503 self._logger.error("Failed to remove temp directory %s : %s",
504 tmpdir, str(e))
505 return False
506 except BaseException as e:
507 self._logger.error("Unexpected Exception removing tempdir %s : %s",
508 tmpdir, str(e))
509 return False
510 else:
511 self._logger.error("Failed to create temp directory.")
512 return False
513 return result
514
Todd Broch352b4b22013-03-22 09:48:40 -0700515 def set_get_all(self, cmds):
516 """Set &| get one or more control values.
517
518 Args:
519 cmds: list of control[:value] to get or set.
520
521 Returns:
522 rv: list of responses from calling get or set methods.
523 """
524 rv = []
525 for cmd in cmds:
526 if ':' in cmd:
527 (control, value) = cmd.split(':')
528 rv.append(self.set(control, value))
529 else:
530 rv.append(self.get(cmd))
531 return rv
532
Todd Broche505b8d2011-03-21 18:19:54 -0700533 def get(self, name):
534 """Get control value.
535
536 Args:
537 name: name string of control
538
539 Returns:
540 Response from calling drv get method. Value is reformatted based on
541 control's dictionary parameters
542
543 Raises:
544 HwDriverError: Error occurred while using drv
545 """
546 self._logger.debug("name(%s)" % (name))
547 (param, drv) = self._get_param_drv(name)
548 try:
549 val = drv.get()
550 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800551 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700552 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700553 except AttributeError, error:
554 self._logger.error("Getting %s: %s" % (name, error))
555 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800556 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700557 self._logger.error("Getting %s" % (name))
558 raise
Todd Brochd6061672012-05-11 15:52:47 -0700559
Todd Broche505b8d2011-03-21 18:19:54 -0700560 def get_all(self, verbose):
561 """Get all controls values.
562
563 Args:
564 verbose: Boolean on whether to return doc info as well
565
566 Returns:
567 string creating from trying to get all values of all controls. In case of
568 error attempting access to control, response is 'ERR'.
569 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800570 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700571 for name in self._syscfg.syscfg_dict['control']:
572 self._logger.debug("name = %s" %name)
573 try:
574 value = self.get(name)
575 except Exception:
576 value = "ERR"
577 pass
578 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800579 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700580 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800581 rsp.append("%s:%s" % (name, value))
582 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700583
584 def set(self, name, wr_val_str):
585 """Set control.
586
587 Args:
588 name: name string of control
589 wr_val_str: value string to write. Can be integer, float or a
590 alpha-numerical that is mapped to a integer or float.
591
592 Raises:
593 HwDriverError: Error occurred while using driver
594 """
Todd Broch7a91c252012-02-03 12:37:45 -0800595 if name == 'sleep':
596 time.sleep(float(wr_val_str))
597 return True
598
Todd Broche505b8d2011-03-21 18:19:54 -0700599 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
600 (params, drv) = self._get_param_drv(name, False)
601 wr_val = self._syscfg.resolve_val(params, wr_val_str)
602 try:
603 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800604 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700605 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
606 raise
607 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
608 # & client I still have to return something to appease the
609 # marshall/unmarshall
610 return True
611
Todd Brochd6061672012-05-11 15:52:47 -0700612 def hwinit(self, verbose=False):
613 """Initialize all controls.
614
615 These values are part of the system config XML files of the form
616 init=<value>. This command should be used by clients wishing to return the
617 servo and DUT its connected to a known good/safe state.
618
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800619 Note that initialization errors are ignored (as in some cases they could
620 be caused by DUT firmware deficiencies). This might need to be fine tuned
621 later.
622
Todd Brochd6061672012-05-11 15:52:47 -0700623 Args:
624 verbose: boolean, if True prints info about control initialized.
625 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800626
627 Returns:
628 This function is called across RPC and as such is expected to return
629 something unless transferring 'none' across is allowed. Hence adding a
630 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700631 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800632 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800633 try:
634 self.set(control_name, value)
635 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800636 self._logger.error("Problem initializing %s -> %s :: %s",
637 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700638 if verbose:
639 self._logger.info('Initialized %s to %s', control_name, value)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800640 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800641
Todd Broche505b8d2011-03-21 18:19:54 -0700642 def echo(self, echo):
643 """Dummy echo function for testing/examples.
644
645 Args:
646 echo: string to echo back to client
647 """
648 self._logger.debug("echo(%s)" % (echo))
649 return "ECH0ING: %s" % (echo)
650
J. Richard Barnettee2820552013-03-14 16:13:46 -0700651 def get_board(self):
652 """Return the board specified at startup, if any."""
653 return self._board
654
Todd Brochdbb09982011-10-02 07:14:26 -0700655
Todd Broche505b8d2011-03-21 18:19:54 -0700656def test():
657 """Integration testing.
658
659 TODO(tbroch) Enhance integration test and add unittest (see mox)
660 """
661 logging.basicConfig(level=logging.DEBUG,
662 format="%(asctime)s - %(name)s - " +
663 "%(levelname)s - %(message)s")
664 # configure server & listen
665 servod_obj = Servod(1)
666 # 4 == number of interfaces on a FT4232H device
667 for i in xrange(4):
668 if i == 1:
669 # its an i2c interface ... see __init__ for details and TODO to make
670 # this configureable
671 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
672 else:
673 # its a gpio interface
674 servod_obj._interface_list[i].wr_rd(0)
675
676 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
677 allow_none=True)
678 server.register_introspection_functions()
679 server.register_multicall_functions()
680 server.register_instance(servod_obj)
681 logging.info("Listening on localhost port 9999")
682 server.serve_forever()
683
684if __name__ == "__main__":
685 test()
686
687 # simple client transaction would look like
688 """
689 remote_uri = 'http://localhost:9999'
690 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
691 send_str = "Hello_there"
692 print "Sent " + send_str + ", Recv " + client.echo(send_str)
693 """