blob: b4b85aa33da814d6dc1ea0723eda2de018513c88 [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")
292 index = int(params['interface']) - 1
293 interface = self._interface_list[index]
294 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
295 drv_pkg = imp.load_module('drv',
296 *imp.find_module('drv', servo_pkg.__path__))
297 drv_name = params['drv']
298 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800299 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700300 drv = drv_class(interface, params)
301 if control_name not in self._drv_dict:
302 self._drv_dict[control_name] = {}
303 if is_get:
304 self._drv_dict[control_name]['get'] = (params, drv)
305 else:
306 self._drv_dict[control_name]['set'] = (params, drv)
307 return (params, drv)
308
309 def doc_all(self):
310 """Return all documenation for controls.
311
312 Returns:
313 string of <doc> text in config file (xml) and the params dictionary for
314 all controls.
315
316 For example:
317 warm_reset :: Reset the device warmly
318 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
319 """
320 return self._syscfg.display_config()
321
322 def doc(self, name):
323 """Retreive doc string in system config file for given control name.
324
325 Args:
326 name: name string of control to get doc string
327
328 Returns:
329 doc string of name
330
331 Raises:
332 NameError: if fails to locate control
333 """
334 self._logger.debug("name(%s)" % (name))
335 if self._syscfg.is_control(name):
336 return self._syscfg.get_control_docstring(name)
337 else:
338 raise NameError("No control %s" %name)
339
Fang Deng90377712013-06-03 15:51:48 -0700340 def _switch_usbkey(self, mux_direction):
341 """Connect USB flash stick to either servo or DUT.
342
343 This function switches 'usb_mux_sel1' to provide electrical
344 connection between the USB port J3 and either servo or DUT side.
345
346 Switching the usb mux is accompanied by powercycling
347 of the USB stick, because it sometimes gets wedged if the mux
348 is switched while the stick power is on.
349
350 Args:
351 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
352 """
353 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
354 time.sleep(self._USB_POWEROFF_DELAY)
355 self.set(self._USB_J3, mux_direction)
356 time.sleep(self._USB_POWEROFF_DELAY)
357 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
358 if mux_direction == self._USB_J3_TO_SERVO:
359 time.sleep(self._USB_DETECTION_DELAY)
360
Simran Basia9f41032012-05-11 14:21:58 -0700361 def _get_usb_port_set(self):
362 """Gets a set of USB disks currently connected to the system
363
364 Returns:
365 A set of USB disk paths.
366 """
367 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
368 return set(["/dev/" + dev for dev in usb_set])
369
370 def _probe_host_usb_dev(self):
371 """Probe the USB disk device plugged in the servo from the host side.
372
373 Method can fail by:
374 1) Having multiple servos connected and returning incorrect /dev/sdX of
375 another servo.
376 2) Finding multiple /dev/sdX and returning None.
377
378 Returns:
379 USB disk path if one and only one USB disk path is found, otherwise None.
380 """
Fang Deng90377712013-06-03 15:51:48 -0700381 original_value = self.get(self._USB_J3)
382 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700383 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700384 if (original_usb_power == self._USB_J3_PWR_ON and
385 original_value != self._USB_J3_TO_DUT):
386 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700387 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700388
Fang Deng90377712013-06-03 15:51:48 -0700389 # Make the host able to see the USB disk.
390 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700391 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700392
Simran Basia9f41032012-05-11 14:21:58 -0700393 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700394 if original_value != self._USB_J3_TO_SERVO:
395 self._switch_usbkey(original_value)
396 if original_usb_power != self._USB_J3_PWR_ON:
397 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
398 time.sleep(self._USB_POWEROFF_DELAY)
399
Simran Basia9f41032012-05-11 14:21:58 -0700400 # Subtract the two sets to find the usb device.
401 diff_set = has_usb_set - no_usb_set
402 if len(diff_set) == 1:
403 return diff_set.pop()
404 else:
405 return None
406
407 def download_image_to_usb(self, image_path):
408 """Download image and save to the USB device found by probe_host_usb_dev.
409 If the image_path is a URL, it will download this url to the USB path;
410 otherwise it will simply copy the image_path's contents to the USB path.
411
412 Args:
413 image_path: path or url to the recovery image.
414
415 Returns:
416 True|False: True if process completed successfully, False if error
417 occurred.
418 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
419 comment at the end of set().
420 """
421 self._logger.debug("image_path(%s)" % image_path)
422 self._logger.debug("Detecting USB stick device...")
423 usb_dev = self._probe_host_usb_dev()
424 if not usb_dev:
425 self._logger.error("No usb device connected to servo")
426 return False
427
428 try:
429 if image_path.startswith(self._HTTP_PREFIX):
430 self._logger.debug("Image path is a URL, downloading image")
431 urllib.urlretrieve(image_path, usb_dev)
432 else:
433 shutil.copyfile(image_path, usb_dev)
434 except IOError as e:
435 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
436 e.strerror, e.errno)
437 return False
438 except urllib.ContentTooShortError:
439 self._logger.error("Failed to download URL: %s to USB device: %s",
440 image_path, usb_dev)
441 return False
442 except BaseException as e:
443 self._logger.error("Unexpected exception downloading %s to %s: %s",
444 image_path, usb_dev, str(e))
445 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800446 finally:
447 # We just plastered the partition table for a block device.
448 # Pass or fail, we mustn't go without telling the kernel about
449 # the change, or it will punish us with sporadic, hard-to-debug
450 # failures.
451 subprocess.call(["sync"])
452 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700453 return True
454
455 def make_image_noninteractive(self):
456 """Makes the recovery image noninteractive.
457
458 A noninteractive image will reboot automatically after installation
459 instead of waiting for the USB device to be removed to initiate a system
460 reboot.
461
462 Mounts partition 1 of the image stored on usb_dev and creates a file
463 called "non_interactive" so that the image will become noninteractive.
464
465 Returns:
466 True|False: True if process completed successfully, False if error
467 occurred.
468 """
469 result = True
470 usb_dev = self._probe_host_usb_dev()
471 if not usb_dev:
472 self._logger.error("No usb device connected to servo")
473 return False
474 # Create TempDirectory
475 tmpdir = tempfile.mkdtemp()
476 if tmpdir:
477 # Mount drive to tmpdir.
478 partition_1 = "%s1" % usb_dev
479 rc = subprocess.call(["mount", partition_1, tmpdir])
480 if rc == 0:
481 # Create file 'non_interactive'
482 non_interactive_file = os.path.join(tmpdir, "non_interactive")
483 try:
484 open(non_interactive_file, "w").close()
485 except IOError as e:
486 self._logger.error("Failed to create file %s : %s ( %d )",
487 non_interactive_file, e.strerror, e.errno)
488 result = False
489 except BaseException as e:
490 self._logger.error("Unexpected Exception creating file %s : %s",
491 non_interactive_file, str(e))
492 result = False
493 # Unmount drive regardless if file creation worked or not.
494 rc = subprocess.call(["umount", partition_1])
495 if rc != 0:
496 self._logger.error("Failed to unmount USB Device")
497 result = False
498 else:
499 self._logger.error("Failed to mount USB Device")
500 result = False
501
502 # Delete tmpdir. May throw exception if 'umount' failed.
503 try:
504 os.rmdir(tmpdir)
505 except OSError as e:
506 self._logger.error("Failed to remove temp directory %s : %s",
507 tmpdir, str(e))
508 return False
509 except BaseException as e:
510 self._logger.error("Unexpected Exception removing tempdir %s : %s",
511 tmpdir, str(e))
512 return False
513 else:
514 self._logger.error("Failed to create temp directory.")
515 return False
516 return result
517
Todd Broch352b4b22013-03-22 09:48:40 -0700518 def set_get_all(self, cmds):
519 """Set &| get one or more control values.
520
521 Args:
522 cmds: list of control[:value] to get or set.
523
524 Returns:
525 rv: list of responses from calling get or set methods.
526 """
527 rv = []
528 for cmd in cmds:
529 if ':' in cmd:
530 (control, value) = cmd.split(':')
531 rv.append(self.set(control, value))
532 else:
533 rv.append(self.get(cmd))
534 return rv
535
Todd Broche505b8d2011-03-21 18:19:54 -0700536 def get(self, name):
537 """Get control value.
538
539 Args:
540 name: name string of control
541
542 Returns:
543 Response from calling drv get method. Value is reformatted based on
544 control's dictionary parameters
545
546 Raises:
547 HwDriverError: Error occurred while using drv
548 """
549 self._logger.debug("name(%s)" % (name))
550 (param, drv) = self._get_param_drv(name)
551 try:
552 val = drv.get()
553 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800554 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700555 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700556 except AttributeError, error:
557 self._logger.error("Getting %s: %s" % (name, error))
558 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800559 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700560 self._logger.error("Getting %s" % (name))
561 raise
Todd Brochd6061672012-05-11 15:52:47 -0700562
Todd Broche505b8d2011-03-21 18:19:54 -0700563 def get_all(self, verbose):
564 """Get all controls values.
565
566 Args:
567 verbose: Boolean on whether to return doc info as well
568
569 Returns:
570 string creating from trying to get all values of all controls. In case of
571 error attempting access to control, response is 'ERR'.
572 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800573 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700574 for name in self._syscfg.syscfg_dict['control']:
575 self._logger.debug("name = %s" %name)
576 try:
577 value = self.get(name)
578 except Exception:
579 value = "ERR"
580 pass
581 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800582 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700583 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800584 rsp.append("%s:%s" % (name, value))
585 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700586
587 def set(self, name, wr_val_str):
588 """Set control.
589
590 Args:
591 name: name string of control
592 wr_val_str: value string to write. Can be integer, float or a
593 alpha-numerical that is mapped to a integer or float.
594
595 Raises:
596 HwDriverError: Error occurred while using driver
597 """
Todd Broch7a91c252012-02-03 12:37:45 -0800598 if name == 'sleep':
599 time.sleep(float(wr_val_str))
600 return True
601
Todd Broche505b8d2011-03-21 18:19:54 -0700602 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
603 (params, drv) = self._get_param_drv(name, False)
604 wr_val = self._syscfg.resolve_val(params, wr_val_str)
605 try:
606 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800607 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700608 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
609 raise
610 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
611 # & client I still have to return something to appease the
612 # marshall/unmarshall
613 return True
614
Todd Brochd6061672012-05-11 15:52:47 -0700615 def hwinit(self, verbose=False):
616 """Initialize all controls.
617
618 These values are part of the system config XML files of the form
619 init=<value>. This command should be used by clients wishing to return the
620 servo and DUT its connected to a known good/safe state.
621
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800622 Note that initialization errors are ignored (as in some cases they could
623 be caused by DUT firmware deficiencies). This might need to be fine tuned
624 later.
625
Todd Brochd6061672012-05-11 15:52:47 -0700626 Args:
627 verbose: boolean, if True prints info about control initialized.
628 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800629
630 Returns:
631 This function is called across RPC and as such is expected to return
632 something unless transferring 'none' across is allowed. Hence adding a
633 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700634 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800635 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800636 try:
637 self.set(control_name, value)
638 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800639 self._logger.error("Problem initializing %s -> %s :: %s",
640 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700641 if verbose:
642 self._logger.info('Initialized %s to %s', control_name, value)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800643 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800644
Todd Broche505b8d2011-03-21 18:19:54 -0700645 def echo(self, echo):
646 """Dummy echo function for testing/examples.
647
648 Args:
649 echo: string to echo back to client
650 """
651 self._logger.debug("echo(%s)" % (echo))
652 return "ECH0ING: %s" % (echo)
653
J. Richard Barnettee2820552013-03-14 16:13:46 -0700654 def get_board(self):
655 """Return the board specified at startup, if any."""
656 return self._board
657
Simran Basia23c1392013-08-06 14:59:10 -0700658 def get_version(self):
659 """Get servo board version."""
660 return self._version
661
Todd Brochdbb09982011-10-02 07:14:26 -0700662
Todd Broche505b8d2011-03-21 18:19:54 -0700663def test():
664 """Integration testing.
665
666 TODO(tbroch) Enhance integration test and add unittest (see mox)
667 """
668 logging.basicConfig(level=logging.DEBUG,
669 format="%(asctime)s - %(name)s - " +
670 "%(levelname)s - %(message)s")
671 # configure server & listen
672 servod_obj = Servod(1)
673 # 4 == number of interfaces on a FT4232H device
674 for i in xrange(4):
675 if i == 1:
676 # its an i2c interface ... see __init__ for details and TODO to make
677 # this configureable
678 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
679 else:
680 # its a gpio interface
681 servod_obj._interface_list[i].wr_rd(0)
682
683 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
684 allow_none=True)
685 server.register_introspection_functions()
686 server.register_multicall_functions()
687 server.register_instance(servod_obj)
688 logging.info("Listening on localhost port 9999")
689 server.serve_forever()
690
691if __name__ == "__main__":
692 test()
693
694 # simple client transaction would look like
695 """
696 remote_uri = 'http://localhost:9999'
697 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
698 send_str = "Hello_there"
699 print "Sent " + send_str + ", Recv " + client.echo(send_str)
700 """