blob: 5205d351c785cf938a8cddd6c9b48f1ed7ab4fcd [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,
Simran Basia23c1392013-08-06 14:59:10 -070046 interfaces=None, board="", version=None):
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
Simran Basia23c1392013-08-06 14:59:10 -070056 version: String. Servo board version. Examples: servo_v1, servo_v2,
57 servo_v2_r0, servo_v3
Todd Brochdbb09982011-10-02 07:14:26 -070058
59 Raises:
60 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070061 """
62 self._logger = logging.getLogger("Servod")
63 self._logger.debug("")
64 self._vendor = vendor
65 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070066 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070067 self._syscfg = config
68 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
69 # interfaces are mapped to
70 self._interface_list = []
71 # Dict of Dict to map control name, function name to to tuple (params, drv)
72 # Ex) _drv_dict[name]['get'] = (params, drv)
73 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070074 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -070075 self._version = version
Todd Broche505b8d2011-03-21 18:19:54 -070076
Todd Brochdbb09982011-10-02 07:14:26 -070077 # Note, interface i is (i - 1) in list
78 if not interfaces:
Simran Basie750a342013-03-12 13:45:26 -070079 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070080
Simran Basia9ad25e2013-04-23 11:57:00 -070081 for i, interface in enumerate(interfaces):
82 is_ftdi_interface = False
83 if type(interface) is dict:
84 name = interface['name']
85 elif type(interface) is str:
86 # Its FTDI related interface
87 name = interface
88 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
89 is_ftdi_interface = True
90 else:
91 raise ServodError("Illegal interface type %s" % type(interface))
92
Todd Broch8a77a992012-01-27 09:46:08 -080093 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -070094 if is_ftdi_interface and i and \
95 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -080096 self._product += 1
97 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
98 self._product)
99
Simran Basia9ad25e2013-04-23 11:57:00 -0700100 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -0700101 try:
102 func = getattr(self, '_init_%s' % name)
103 except AttributeError:
104 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -0700105 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -0700106 if isinstance(result, tuple):
107 self._interface_list.extend(result)
108 else:
109 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700110
Todd Broch3ec8df02012-11-20 10:53:03 -0800111 def __del__(self):
112 """Servod deconstructor."""
113 for interface in self._interface_list:
114 del(interface)
115
Todd Brochb3048492012-01-15 21:52:41 -0800116 def _init_dummy(self, interface):
117 """Initialize dummy interface.
118
119 Dummy interface is just a mechanism to reserve that interface for non servod
120 interaction. Typically the interface will be managed by external
121 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
122 interfaces.
123
124 TODO(tbroch): Investigate merits of incorporating these third-party
125 interfaces into servod or creating a communication channel between them
126
127 Returns: None
128 """
129 return None
130
Simran Basie750a342013-03-12 13:45:26 -0700131 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700132 """Initialize gpio driver interface and open for use.
133
134 Args:
135 interface: interface number of FTDI device to use.
136
137 Returns:
138 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700139
140 Raises:
141 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700142 """
Todd Brochad034442011-05-25 15:05:29 -0700143 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
144 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700145 try:
146 fobj.open()
147 except ftdigpio.FgpioError as e:
148 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
149
Todd Broche505b8d2011-03-21 18:19:54 -0700150 return fobj
151
Simran Basie750a342013-03-12 13:45:26 -0700152 def _init_bb_gpio(self, interface):
153 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700154 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700155
156 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700157 """Initialize i2c interface and open for use.
158
159 Args:
160 interface: interface number of FTDI device to use
161
162 Returns:
163 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700164
165 Raises:
166 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700167 """
Todd Brochad034442011-05-25 15:05:29 -0700168 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
169 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700170 try:
171 fobj.open()
172 except ftdii2c.Fi2cError as e:
173 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
174
Todd Broche505b8d2011-03-21 18:19:54 -0700175 # Set the frequency of operation of the i2c bus.
176 # TODO(tbroch) make configureable
177 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700178
Todd Broche505b8d2011-03-21 18:19:54 -0700179 return fobj
180
Simran Basie750a342013-03-12 13:45:26 -0700181 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
182 def _init_bb_i2c(self, interface):
183 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700184 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700185
186 def _init_ftdi_uart(self, interface):
187 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700188
189 Note, the uart runs in a separate thread (pthreads). Users wishing to
190 interact with it will query control for the pty's pathname and connect
191 with there favorite console program. For example:
192 cu -l /dev/pts/22
193
194 Args:
195 interface: interface number of FTDI device to use
196
197 Returns:
198 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700199
200 Raises:
201 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700202 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700203 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
204 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700205 try:
206 fobj.run()
207 except ftdiuart.FuartError as e:
208 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
209
Todd Broch47c43f42011-05-26 15:11:31 -0700210 self._logger.info("%s" % fobj.get_pty())
211 return fobj
212
Simran Basie750a342013-03-12 13:45:26 -0700213 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
214 def _init_bb_uart(self, interface):
215 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700216 logging.debug('UART INTERFACE: %s', interface)
217 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700218
219 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700220 """Initialize special gpio + uart interface and open for use
221
222 Note, the uart runs in a separate thread (pthreads). Users wishing to
223 interact with it will query control for the pty's pathname and connect
224 with there favorite console program. For example:
225 cu -l /dev/pts/22
226
227 Args:
228 interface: interface number of FTDI device to use
229
230 Returns:
231 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700232
233 Raises:
234 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700235 """
Simran Basie750a342013-03-12 13:45:26 -0700236 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700237 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
238 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700239 try:
240 fuart.run()
241 except ftdiuart.FuartError as e:
242 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
243
Todd Broch888da782011-10-07 14:29:09 -0700244 self._logger.info("uart pty: %s" % fuart.get_pty())
245 return fgpio, fuart
246
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800247 def _camel_case(self, string):
248 output = ''
249 for s in string.split('_'):
250 if output:
251 output += s.capitalize()
252 else:
253 output = s
254 return output
255
Todd Broche505b8d2011-03-21 18:19:54 -0700256 def _get_param_drv(self, control_name, is_get=True):
257 """Get access to driver for a given control.
258
259 Note, some controls have different parameter dictionaries for 'getting' the
260 control's value versus 'setting' it. Boolean is_get distinguishes which is
261 being requested.
262
263 Args:
264 control_name: string name of control
265 is_get: boolean to determine
266
267 Returns:
268 tuple (param, drv) where:
269 param: param dictionary for control
270 drv: instance object of driver for particular control
271
272 Raises:
273 ServodError: Error occurred while examining params dict
274 """
275 self._logger.debug("")
276 # if already setup just return tuple from driver dict
277 if control_name in self._drv_dict:
278 if is_get and ('get' in self._drv_dict[control_name]):
279 return self._drv_dict[control_name]['get']
280 if not is_get and ('set' in self._drv_dict[control_name]):
281 return self._drv_dict[control_name]['set']
282
283 params = self._syscfg.lookup_control_params(control_name, is_get)
284 if 'drv' not in params:
285 self._logger.error("Unable to determine driver for %s" % control_name)
286 raise ServodError("'drv' key not found in params dict")
287 if 'interface' not in params:
288 self._logger.error("Unable to determine interface for %s" %
289 control_name)
290
291 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700292
293 version_specific_interface = params.get('%s_interface' % self._version,
294 None)
295 if version_specific_interface:
296 index = int(version_specific_interface) - 1
297 self._logger.debug('Overriding interface for control: %s on servo board '
298 'version: %s, using interface %d.', control_name,
299 self._version, index)
300 else:
301 index = int(params['interface']) - 1
302
Todd Broche505b8d2011-03-21 18:19:54 -0700303 interface = self._interface_list[index]
304 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
305 drv_pkg = imp.load_module('drv',
306 *imp.find_module('drv', servo_pkg.__path__))
307 drv_name = params['drv']
308 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800309 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700310 drv = drv_class(interface, params)
311 if control_name not in self._drv_dict:
312 self._drv_dict[control_name] = {}
313 if is_get:
314 self._drv_dict[control_name]['get'] = (params, drv)
315 else:
316 self._drv_dict[control_name]['set'] = (params, drv)
317 return (params, drv)
318
319 def doc_all(self):
320 """Return all documenation for controls.
321
322 Returns:
323 string of <doc> text in config file (xml) and the params dictionary for
324 all controls.
325
326 For example:
327 warm_reset :: Reset the device warmly
328 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
329 """
330 return self._syscfg.display_config()
331
332 def doc(self, name):
333 """Retreive doc string in system config file for given control name.
334
335 Args:
336 name: name string of control to get doc string
337
338 Returns:
339 doc string of name
340
341 Raises:
342 NameError: if fails to locate control
343 """
344 self._logger.debug("name(%s)" % (name))
345 if self._syscfg.is_control(name):
346 return self._syscfg.get_control_docstring(name)
347 else:
348 raise NameError("No control %s" %name)
349
Fang Deng90377712013-06-03 15:51:48 -0700350 def _switch_usbkey(self, mux_direction):
351 """Connect USB flash stick to either servo or DUT.
352
353 This function switches 'usb_mux_sel1' to provide electrical
354 connection between the USB port J3 and either servo or DUT side.
355
356 Switching the usb mux is accompanied by powercycling
357 of the USB stick, because it sometimes gets wedged if the mux
358 is switched while the stick power is on.
359
360 Args:
361 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
362 """
363 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
364 time.sleep(self._USB_POWEROFF_DELAY)
365 self.set(self._USB_J3, mux_direction)
366 time.sleep(self._USB_POWEROFF_DELAY)
367 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
368 if mux_direction == self._USB_J3_TO_SERVO:
369 time.sleep(self._USB_DETECTION_DELAY)
370
Simran Basia9f41032012-05-11 14:21:58 -0700371 def _get_usb_port_set(self):
372 """Gets a set of USB disks currently connected to the system
373
374 Returns:
375 A set of USB disk paths.
376 """
377 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
378 return set(["/dev/" + dev for dev in usb_set])
379
380 def _probe_host_usb_dev(self):
381 """Probe the USB disk device plugged in the servo from the host side.
382
383 Method can fail by:
384 1) Having multiple servos connected and returning incorrect /dev/sdX of
385 another servo.
386 2) Finding multiple /dev/sdX and returning None.
387
388 Returns:
389 USB disk path if one and only one USB disk path is found, otherwise None.
390 """
Fang Deng90377712013-06-03 15:51:48 -0700391 original_value = self.get(self._USB_J3)
392 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700393 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700394 if (original_usb_power == self._USB_J3_PWR_ON and
395 original_value != self._USB_J3_TO_DUT):
396 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700397 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700398
Fang Deng90377712013-06-03 15:51:48 -0700399 # Make the host able to see the USB disk.
400 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700401 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700402
Simran Basia9f41032012-05-11 14:21:58 -0700403 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700404 if original_value != self._USB_J3_TO_SERVO:
405 self._switch_usbkey(original_value)
406 if original_usb_power != self._USB_J3_PWR_ON:
407 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
408 time.sleep(self._USB_POWEROFF_DELAY)
409
Simran Basia9f41032012-05-11 14:21:58 -0700410 # Subtract the two sets to find the usb device.
411 diff_set = has_usb_set - no_usb_set
412 if len(diff_set) == 1:
413 return diff_set.pop()
414 else:
415 return None
416
417 def download_image_to_usb(self, image_path):
418 """Download image and save to the USB device found by probe_host_usb_dev.
419 If the image_path is a URL, it will download this url to the USB path;
420 otherwise it will simply copy the image_path's contents to the USB path.
421
422 Args:
423 image_path: path or url to the recovery image.
424
425 Returns:
426 True|False: True if process completed successfully, False if error
427 occurred.
428 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
429 comment at the end of set().
430 """
431 self._logger.debug("image_path(%s)" % image_path)
432 self._logger.debug("Detecting USB stick device...")
433 usb_dev = self._probe_host_usb_dev()
434 if not usb_dev:
435 self._logger.error("No usb device connected to servo")
436 return False
437
438 try:
439 if image_path.startswith(self._HTTP_PREFIX):
440 self._logger.debug("Image path is a URL, downloading image")
441 urllib.urlretrieve(image_path, usb_dev)
442 else:
443 shutil.copyfile(image_path, usb_dev)
444 except IOError as e:
445 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
446 e.strerror, e.errno)
447 return False
448 except urllib.ContentTooShortError:
449 self._logger.error("Failed to download URL: %s to USB device: %s",
450 image_path, usb_dev)
451 return False
452 except BaseException as e:
453 self._logger.error("Unexpected exception downloading %s to %s: %s",
454 image_path, usb_dev, str(e))
455 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800456 finally:
457 # We just plastered the partition table for a block device.
458 # Pass or fail, we mustn't go without telling the kernel about
459 # the change, or it will punish us with sporadic, hard-to-debug
460 # failures.
461 subprocess.call(["sync"])
462 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700463 return True
464
465 def make_image_noninteractive(self):
466 """Makes the recovery image noninteractive.
467
468 A noninteractive image will reboot automatically after installation
469 instead of waiting for the USB device to be removed to initiate a system
470 reboot.
471
472 Mounts partition 1 of the image stored on usb_dev and creates a file
473 called "non_interactive" so that the image will become noninteractive.
474
475 Returns:
476 True|False: True if process completed successfully, False if error
477 occurred.
478 """
479 result = True
480 usb_dev = self._probe_host_usb_dev()
481 if not usb_dev:
482 self._logger.error("No usb device connected to servo")
483 return False
484 # Create TempDirectory
485 tmpdir = tempfile.mkdtemp()
486 if tmpdir:
487 # Mount drive to tmpdir.
488 partition_1 = "%s1" % usb_dev
489 rc = subprocess.call(["mount", partition_1, tmpdir])
490 if rc == 0:
491 # Create file 'non_interactive'
492 non_interactive_file = os.path.join(tmpdir, "non_interactive")
493 try:
494 open(non_interactive_file, "w").close()
495 except IOError as e:
496 self._logger.error("Failed to create file %s : %s ( %d )",
497 non_interactive_file, e.strerror, e.errno)
498 result = False
499 except BaseException as e:
500 self._logger.error("Unexpected Exception creating file %s : %s",
501 non_interactive_file, str(e))
502 result = False
503 # Unmount drive regardless if file creation worked or not.
504 rc = subprocess.call(["umount", partition_1])
505 if rc != 0:
506 self._logger.error("Failed to unmount USB Device")
507 result = False
508 else:
509 self._logger.error("Failed to mount USB Device")
510 result = False
511
512 # Delete tmpdir. May throw exception if 'umount' failed.
513 try:
514 os.rmdir(tmpdir)
515 except OSError as e:
516 self._logger.error("Failed to remove temp directory %s : %s",
517 tmpdir, str(e))
518 return False
519 except BaseException as e:
520 self._logger.error("Unexpected Exception removing tempdir %s : %s",
521 tmpdir, str(e))
522 return False
523 else:
524 self._logger.error("Failed to create temp directory.")
525 return False
526 return result
527
Todd Broch352b4b22013-03-22 09:48:40 -0700528 def set_get_all(self, cmds):
529 """Set &| get one or more control values.
530
531 Args:
532 cmds: list of control[:value] to get or set.
533
534 Returns:
535 rv: list of responses from calling get or set methods.
536 """
537 rv = []
538 for cmd in cmds:
539 if ':' in cmd:
540 (control, value) = cmd.split(':')
541 rv.append(self.set(control, value))
542 else:
543 rv.append(self.get(cmd))
544 return rv
545
Todd Broche505b8d2011-03-21 18:19:54 -0700546 def get(self, name):
547 """Get control value.
548
549 Args:
550 name: name string of control
551
552 Returns:
553 Response from calling drv get method. Value is reformatted based on
554 control's dictionary parameters
555
556 Raises:
557 HwDriverError: Error occurred while using drv
558 """
559 self._logger.debug("name(%s)" % (name))
560 (param, drv) = self._get_param_drv(name)
561 try:
562 val = drv.get()
563 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800564 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700565 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700566 except AttributeError, error:
567 self._logger.error("Getting %s: %s" % (name, error))
568 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800569 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700570 self._logger.error("Getting %s" % (name))
571 raise
Todd Brochd6061672012-05-11 15:52:47 -0700572
Todd Broche505b8d2011-03-21 18:19:54 -0700573 def get_all(self, verbose):
574 """Get all controls values.
575
576 Args:
577 verbose: Boolean on whether to return doc info as well
578
579 Returns:
580 string creating from trying to get all values of all controls. In case of
581 error attempting access to control, response is 'ERR'.
582 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800583 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700584 for name in self._syscfg.syscfg_dict['control']:
585 self._logger.debug("name = %s" %name)
586 try:
587 value = self.get(name)
588 except Exception:
589 value = "ERR"
590 pass
591 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800592 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700593 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800594 rsp.append("%s:%s" % (name, value))
595 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700596
597 def set(self, name, wr_val_str):
598 """Set control.
599
600 Args:
601 name: name string of control
602 wr_val_str: value string to write. Can be integer, float or a
603 alpha-numerical that is mapped to a integer or float.
604
605 Raises:
606 HwDriverError: Error occurred while using driver
607 """
Todd Broch7a91c252012-02-03 12:37:45 -0800608 if name == 'sleep':
609 time.sleep(float(wr_val_str))
610 return True
611
Todd Broche505b8d2011-03-21 18:19:54 -0700612 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
613 (params, drv) = self._get_param_drv(name, False)
614 wr_val = self._syscfg.resolve_val(params, wr_val_str)
615 try:
616 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800617 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700618 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
619 raise
620 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
621 # & client I still have to return something to appease the
622 # marshall/unmarshall
623 return True
624
Todd Brochd6061672012-05-11 15:52:47 -0700625 def hwinit(self, verbose=False):
626 """Initialize all controls.
627
628 These values are part of the system config XML files of the form
629 init=<value>. This command should be used by clients wishing to return the
630 servo and DUT its connected to a known good/safe state.
631
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800632 Note that initialization errors are ignored (as in some cases they could
633 be caused by DUT firmware deficiencies). This might need to be fine tuned
634 later.
635
Todd Brochd6061672012-05-11 15:52:47 -0700636 Args:
637 verbose: boolean, if True prints info about control initialized.
638 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800639
640 Returns:
641 This function is called across RPC and as such is expected to return
642 something unless transferring 'none' across is allowed. Hence adding a
643 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700644 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800645 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800646 try:
647 self.set(control_name, value)
648 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800649 self._logger.error("Problem initializing %s -> %s :: %s",
650 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700651 if verbose:
652 self._logger.info('Initialized %s to %s', control_name, value)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800653 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800654
Todd Broche505b8d2011-03-21 18:19:54 -0700655 def echo(self, echo):
656 """Dummy echo function for testing/examples.
657
658 Args:
659 echo: string to echo back to client
660 """
661 self._logger.debug("echo(%s)" % (echo))
662 return "ECH0ING: %s" % (echo)
663
J. Richard Barnettee2820552013-03-14 16:13:46 -0700664 def get_board(self):
665 """Return the board specified at startup, if any."""
666 return self._board
667
Simran Basia23c1392013-08-06 14:59:10 -0700668 def get_version(self):
669 """Get servo board version."""
670 return self._version
671
Todd Brochdbb09982011-10-02 07:14:26 -0700672
Todd Broche505b8d2011-03-21 18:19:54 -0700673def test():
674 """Integration testing.
675
676 TODO(tbroch) Enhance integration test and add unittest (see mox)
677 """
678 logging.basicConfig(level=logging.DEBUG,
679 format="%(asctime)s - %(name)s - " +
680 "%(levelname)s - %(message)s")
681 # configure server & listen
682 servod_obj = Servod(1)
683 # 4 == number of interfaces on a FT4232H device
684 for i in xrange(4):
685 if i == 1:
686 # its an i2c interface ... see __init__ for details and TODO to make
687 # this configureable
688 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
689 else:
690 # its a gpio interface
691 servod_obj._interface_list[i].wr_rd(0)
692
693 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
694 allow_none=True)
695 server.register_introspection_functions()
696 server.register_multicall_functions()
697 server.register_instance(servod_obj)
698 logging.info("Listening on localhost port 9999")
699 server.serve_forever()
700
701if __name__ == "__main__":
702 test()
703
704 # simple client transaction would look like
705 """
706 remote_uri = 'http://localhost:9999'
707 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
708 send_str = "Hello_there"
709 print "Sent " + send_str + ", Recv " + client.echo(send_str)
710 """