blob: fedb90302e0fbb8917c41b0ee4eb3fbddcb34ed8 [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
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080025import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070026import servo_interfaces
Todd Broche505b8d2011-03-21 18:19:54 -070027
28MAX_I2C_CLOCK_HZ = 100000
29
Todd Brochdbb09982011-10-02 07:14:26 -070030
Todd Broche505b8d2011-03-21 18:19:54 -070031class ServodError(Exception):
32 """Exception class for servod."""
33
34class Servod(object):
35 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070036 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070037 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070038 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070039 _USB_J3 = "usb_mux_sel1"
40 _USB_J3_TO_SERVO = "servo_sees_usbkey"
41 _USB_J3_TO_DUT = "dut_sees_usbkey"
42 _USB_J3_PWR = "prtctl4_pwren"
43 _USB_J3_PWR_ON = "on"
44 _USB_J3_PWR_OFF = "off"
Simran Basia9f41032012-05-11 14:21:58 -070045
J. Richard Barnettee2820552013-03-14 16:13:46 -070046 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080047 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -070048 """Servod constructor.
49
50 Args:
51 config: instance of SystemConfig containing all controls for
52 particular Servod invocation
53 vendor: usb vendor id of FTDI device
54 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070055 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070056 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -070057 version: String. Servo board version. Examples: servo_v1, servo_v2,
58 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080059 usbkm232: String. Optional. Path to USB-KM232 device which allow for
60 sending keyboard commands to DUTs that do not have built in
61 keyboards. Used in FAFT tests.
62 e.g. /dev/ttyUSB0
Todd Brochdbb09982011-10-02 07:14:26 -070063
64 Raises:
65 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070066 """
67 self._logger = logging.getLogger("Servod")
68 self._logger.debug("")
69 self._vendor = vendor
70 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070071 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070072 self._syscfg = config
73 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
74 # interfaces are mapped to
75 self._interface_list = []
76 # Dict of Dict to map control name, function name to to tuple (params, drv)
77 # Ex) _drv_dict[name]['get'] = (params, drv)
78 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070079 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -070080 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080081 self._usbkm232 = usbkm232
82
83 self._keyboard = self._init_keyboard_handler(self, self._board)
Todd Broche505b8d2011-03-21 18:19:54 -070084
Todd Brochdbb09982011-10-02 07:14:26 -070085 # Note, interface i is (i - 1) in list
86 if not interfaces:
Simran Basie750a342013-03-12 13:45:26 -070087 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070088
Simran Basia9ad25e2013-04-23 11:57:00 -070089 for i, interface in enumerate(interfaces):
90 is_ftdi_interface = False
91 if type(interface) is dict:
92 name = interface['name']
93 elif type(interface) is str:
94 # Its FTDI related interface
95 name = interface
96 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
97 is_ftdi_interface = True
98 else:
99 raise ServodError("Illegal interface type %s" % type(interface))
100
Todd Broch8a77a992012-01-27 09:46:08 -0800101 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -0700102 if is_ftdi_interface and i and \
103 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -0800104 self._product += 1
105 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
106 self._product)
107
Simran Basia9ad25e2013-04-23 11:57:00 -0700108 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -0700109 try:
110 func = getattr(self, '_init_%s' % name)
111 except AttributeError:
112 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -0700113 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -0700114 if isinstance(result, tuple):
115 self._interface_list.extend(result)
116 else:
117 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700118
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800119 def _init_keyboard_handler(self, servo, board=''):
120 """Initialize the correct keyboard handler for board.
121
122 @param servo: servo object.
123 @param board: string, board name.
124
125 """
126 if board == 'parrot':
127 return keyboard_handlers.ParrotHandler(servo)
128 elif board == 'stout':
129 return keyboard_handlers.StoutHandler(servo)
130 elif board == 'panther':
131 if self._usbkm232 is None:
132 raise Exception("No device specified when "
133 "initializing usbkm232 keyboard handler")
134 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
135 else:
136 return keyboard_handlers.DefaultHandler(servo)
137
Todd Broch3ec8df02012-11-20 10:53:03 -0800138 def __del__(self):
139 """Servod deconstructor."""
140 for interface in self._interface_list:
141 del(interface)
142
Todd Brochb3048492012-01-15 21:52:41 -0800143 def _init_dummy(self, interface):
144 """Initialize dummy interface.
145
146 Dummy interface is just a mechanism to reserve that interface for non servod
147 interaction. Typically the interface will be managed by external
148 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
149 interfaces.
150
151 TODO(tbroch): Investigate merits of incorporating these third-party
152 interfaces into servod or creating a communication channel between them
153
154 Returns: None
155 """
156 return None
157
Simran Basie750a342013-03-12 13:45:26 -0700158 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700159 """Initialize gpio driver interface and open for use.
160
161 Args:
162 interface: interface number of FTDI device to use.
163
164 Returns:
165 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700166
167 Raises:
168 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700169 """
Todd Brochad034442011-05-25 15:05:29 -0700170 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
171 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700172 try:
173 fobj.open()
174 except ftdigpio.FgpioError as e:
175 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
176
Todd Broche505b8d2011-03-21 18:19:54 -0700177 return fobj
178
Simran Basie750a342013-03-12 13:45:26 -0700179 def _init_bb_gpio(self, interface):
180 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700181 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700182
183 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700184 """Initialize i2c interface and open for use.
185
186 Args:
187 interface: interface number of FTDI device to use
188
189 Returns:
190 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700191
192 Raises:
193 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700194 """
Todd Brochad034442011-05-25 15:05:29 -0700195 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
196 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700197 try:
198 fobj.open()
199 except ftdii2c.Fi2cError as e:
200 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
201
Todd Broche505b8d2011-03-21 18:19:54 -0700202 # Set the frequency of operation of the i2c bus.
203 # TODO(tbroch) make configureable
204 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700205
Todd Broche505b8d2011-03-21 18:19:54 -0700206 return fobj
207
Simran Basie750a342013-03-12 13:45:26 -0700208 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
209 def _init_bb_i2c(self, interface):
210 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700211 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700212
213 def _init_ftdi_uart(self, interface):
214 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700215
216 Note, the uart runs in a separate thread (pthreads). Users wishing to
217 interact with it will query control for the pty's pathname and connect
218 with there favorite console program. For example:
219 cu -l /dev/pts/22
220
221 Args:
222 interface: interface number of FTDI device to use
223
224 Returns:
225 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700226
227 Raises:
228 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700229 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700230 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
231 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700232 try:
233 fobj.run()
234 except ftdiuart.FuartError as e:
235 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
236
Todd Broch47c43f42011-05-26 15:11:31 -0700237 self._logger.info("%s" % fobj.get_pty())
238 return fobj
239
Simran Basie750a342013-03-12 13:45:26 -0700240 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
241 def _init_bb_uart(self, interface):
242 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700243 logging.debug('UART INTERFACE: %s', interface)
244 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700245
246 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700247 """Initialize special gpio + uart interface and open for use
248
249 Note, the uart runs in a separate thread (pthreads). Users wishing to
250 interact with it will query control for the pty's pathname and connect
251 with there favorite console program. For example:
252 cu -l /dev/pts/22
253
254 Args:
255 interface: interface number of FTDI device to use
256
257 Returns:
258 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700259
260 Raises:
261 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700262 """
Simran Basie750a342013-03-12 13:45:26 -0700263 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700264 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
265 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700266 try:
267 fuart.run()
268 except ftdiuart.FuartError as e:
269 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
270
Todd Broch888da782011-10-07 14:29:09 -0700271 self._logger.info("uart pty: %s" % fuart.get_pty())
272 return fgpio, fuart
273
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800274 def _camel_case(self, string):
275 output = ''
276 for s in string.split('_'):
277 if output:
278 output += s.capitalize()
279 else:
280 output = s
281 return output
282
Todd Broche505b8d2011-03-21 18:19:54 -0700283 def _get_param_drv(self, control_name, is_get=True):
284 """Get access to driver for a given control.
285
286 Note, some controls have different parameter dictionaries for 'getting' the
287 control's value versus 'setting' it. Boolean is_get distinguishes which is
288 being requested.
289
290 Args:
291 control_name: string name of control
292 is_get: boolean to determine
293
294 Returns:
295 tuple (param, drv) where:
296 param: param dictionary for control
297 drv: instance object of driver for particular control
298
299 Raises:
300 ServodError: Error occurred while examining params dict
301 """
302 self._logger.debug("")
303 # if already setup just return tuple from driver dict
304 if control_name in self._drv_dict:
305 if is_get and ('get' in self._drv_dict[control_name]):
306 return self._drv_dict[control_name]['get']
307 if not is_get and ('set' in self._drv_dict[control_name]):
308 return self._drv_dict[control_name]['set']
309
310 params = self._syscfg.lookup_control_params(control_name, is_get)
311 if 'drv' not in params:
312 self._logger.error("Unable to determine driver for %s" % control_name)
313 raise ServodError("'drv' key not found in params dict")
314 if 'interface' not in params:
315 self._logger.error("Unable to determine interface for %s" %
316 control_name)
317
318 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700319
320 version_specific_interface = params.get('%s_interface' % self._version,
321 None)
322 if version_specific_interface:
323 index = int(version_specific_interface) - 1
324 self._logger.debug('Overriding interface for control: %s on servo board '
325 'version: %s, using interface %d.', control_name,
326 self._version, index)
327 else:
328 index = int(params['interface']) - 1
329
Todd Broche505b8d2011-03-21 18:19:54 -0700330 interface = self._interface_list[index]
331 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
332 drv_pkg = imp.load_module('drv',
333 *imp.find_module('drv', servo_pkg.__path__))
334 drv_name = params['drv']
335 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800336 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700337 drv = drv_class(interface, params)
338 if control_name not in self._drv_dict:
339 self._drv_dict[control_name] = {}
340 if is_get:
341 self._drv_dict[control_name]['get'] = (params, drv)
342 else:
343 self._drv_dict[control_name]['set'] = (params, drv)
344 return (params, drv)
345
346 def doc_all(self):
347 """Return all documenation for controls.
348
349 Returns:
350 string of <doc> text in config file (xml) and the params dictionary for
351 all controls.
352
353 For example:
354 warm_reset :: Reset the device warmly
355 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
356 """
357 return self._syscfg.display_config()
358
359 def doc(self, name):
360 """Retreive doc string in system config file for given control name.
361
362 Args:
363 name: name string of control to get doc string
364
365 Returns:
366 doc string of name
367
368 Raises:
369 NameError: if fails to locate control
370 """
371 self._logger.debug("name(%s)" % (name))
372 if self._syscfg.is_control(name):
373 return self._syscfg.get_control_docstring(name)
374 else:
375 raise NameError("No control %s" %name)
376
Fang Deng90377712013-06-03 15:51:48 -0700377 def _switch_usbkey(self, mux_direction):
378 """Connect USB flash stick to either servo or DUT.
379
380 This function switches 'usb_mux_sel1' to provide electrical
381 connection between the USB port J3 and either servo or DUT side.
382
383 Switching the usb mux is accompanied by powercycling
384 of the USB stick, because it sometimes gets wedged if the mux
385 is switched while the stick power is on.
386
387 Args:
388 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
389 """
390 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
391 time.sleep(self._USB_POWEROFF_DELAY)
392 self.set(self._USB_J3, mux_direction)
393 time.sleep(self._USB_POWEROFF_DELAY)
394 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
395 if mux_direction == self._USB_J3_TO_SERVO:
396 time.sleep(self._USB_DETECTION_DELAY)
397
Simran Basia9f41032012-05-11 14:21:58 -0700398 def _get_usb_port_set(self):
399 """Gets a set of USB disks currently connected to the system
400
401 Returns:
402 A set of USB disk paths.
403 """
404 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
405 return set(["/dev/" + dev for dev in usb_set])
406
407 def _probe_host_usb_dev(self):
408 """Probe the USB disk device plugged in the servo from the host side.
409
410 Method can fail by:
411 1) Having multiple servos connected and returning incorrect /dev/sdX of
412 another servo.
413 2) Finding multiple /dev/sdX and returning None.
414
415 Returns:
416 USB disk path if one and only one USB disk path is found, otherwise None.
417 """
Fang Deng90377712013-06-03 15:51:48 -0700418 original_value = self.get(self._USB_J3)
419 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700420 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700421 if (original_usb_power == self._USB_J3_PWR_ON and
422 original_value != self._USB_J3_TO_DUT):
423 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700424 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700425
Fang Deng90377712013-06-03 15:51:48 -0700426 # Make the host able to see the USB disk.
427 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700428 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700429
Simran Basia9f41032012-05-11 14:21:58 -0700430 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700431 if original_value != self._USB_J3_TO_SERVO:
432 self._switch_usbkey(original_value)
433 if original_usb_power != self._USB_J3_PWR_ON:
434 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
435 time.sleep(self._USB_POWEROFF_DELAY)
436
Simran Basia9f41032012-05-11 14:21:58 -0700437 # Subtract the two sets to find the usb device.
438 diff_set = has_usb_set - no_usb_set
439 if len(diff_set) == 1:
440 return diff_set.pop()
441 else:
442 return None
443
444 def download_image_to_usb(self, image_path):
445 """Download image and save to the USB device found by probe_host_usb_dev.
446 If the image_path is a URL, it will download this url to the USB path;
447 otherwise it will simply copy the image_path's contents to the USB path.
448
449 Args:
450 image_path: path or url to the recovery image.
451
452 Returns:
453 True|False: True if process completed successfully, False if error
454 occurred.
455 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
456 comment at the end of set().
457 """
458 self._logger.debug("image_path(%s)" % image_path)
459 self._logger.debug("Detecting USB stick device...")
460 usb_dev = self._probe_host_usb_dev()
461 if not usb_dev:
462 self._logger.error("No usb device connected to servo")
463 return False
464
465 try:
466 if image_path.startswith(self._HTTP_PREFIX):
467 self._logger.debug("Image path is a URL, downloading image")
468 urllib.urlretrieve(image_path, usb_dev)
469 else:
470 shutil.copyfile(image_path, usb_dev)
471 except IOError as e:
472 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
473 e.strerror, e.errno)
474 return False
475 except urllib.ContentTooShortError:
476 self._logger.error("Failed to download URL: %s to USB device: %s",
477 image_path, usb_dev)
478 return False
479 except BaseException as e:
480 self._logger.error("Unexpected exception downloading %s to %s: %s",
481 image_path, usb_dev, str(e))
482 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800483 finally:
484 # We just plastered the partition table for a block device.
485 # Pass or fail, we mustn't go without telling the kernel about
486 # the change, or it will punish us with sporadic, hard-to-debug
487 # failures.
488 subprocess.call(["sync"])
489 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700490 return True
491
492 def make_image_noninteractive(self):
493 """Makes the recovery image noninteractive.
494
495 A noninteractive image will reboot automatically after installation
496 instead of waiting for the USB device to be removed to initiate a system
497 reboot.
498
499 Mounts partition 1 of the image stored on usb_dev and creates a file
500 called "non_interactive" so that the image will become noninteractive.
501
502 Returns:
503 True|False: True if process completed successfully, False if error
504 occurred.
505 """
506 result = True
507 usb_dev = self._probe_host_usb_dev()
508 if not usb_dev:
509 self._logger.error("No usb device connected to servo")
510 return False
511 # Create TempDirectory
512 tmpdir = tempfile.mkdtemp()
513 if tmpdir:
514 # Mount drive to tmpdir.
515 partition_1 = "%s1" % usb_dev
516 rc = subprocess.call(["mount", partition_1, tmpdir])
517 if rc == 0:
518 # Create file 'non_interactive'
519 non_interactive_file = os.path.join(tmpdir, "non_interactive")
520 try:
521 open(non_interactive_file, "w").close()
522 except IOError as e:
523 self._logger.error("Failed to create file %s : %s ( %d )",
524 non_interactive_file, e.strerror, e.errno)
525 result = False
526 except BaseException as e:
527 self._logger.error("Unexpected Exception creating file %s : %s",
528 non_interactive_file, str(e))
529 result = False
530 # Unmount drive regardless if file creation worked or not.
531 rc = subprocess.call(["umount", partition_1])
532 if rc != 0:
533 self._logger.error("Failed to unmount USB Device")
534 result = False
535 else:
536 self._logger.error("Failed to mount USB Device")
537 result = False
538
539 # Delete tmpdir. May throw exception if 'umount' failed.
540 try:
541 os.rmdir(tmpdir)
542 except OSError as e:
543 self._logger.error("Failed to remove temp directory %s : %s",
544 tmpdir, str(e))
545 return False
546 except BaseException as e:
547 self._logger.error("Unexpected Exception removing tempdir %s : %s",
548 tmpdir, str(e))
549 return False
550 else:
551 self._logger.error("Failed to create temp directory.")
552 return False
553 return result
554
Todd Broch352b4b22013-03-22 09:48:40 -0700555 def set_get_all(self, cmds):
556 """Set &| get one or more control values.
557
558 Args:
559 cmds: list of control[:value] to get or set.
560
561 Returns:
562 rv: list of responses from calling get or set methods.
563 """
564 rv = []
565 for cmd in cmds:
566 if ':' in cmd:
567 (control, value) = cmd.split(':')
568 rv.append(self.set(control, value))
569 else:
570 rv.append(self.get(cmd))
571 return rv
572
Todd Broche505b8d2011-03-21 18:19:54 -0700573 def get(self, name):
574 """Get control value.
575
576 Args:
577 name: name string of control
578
579 Returns:
580 Response from calling drv get method. Value is reformatted based on
581 control's dictionary parameters
582
583 Raises:
584 HwDriverError: Error occurred while using drv
585 """
586 self._logger.debug("name(%s)" % (name))
587 (param, drv) = self._get_param_drv(name)
588 try:
589 val = drv.get()
590 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800591 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700592 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700593 except AttributeError, error:
594 self._logger.error("Getting %s: %s" % (name, error))
595 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800596 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700597 self._logger.error("Getting %s" % (name))
598 raise
Todd Brochd6061672012-05-11 15:52:47 -0700599
Todd Broche505b8d2011-03-21 18:19:54 -0700600 def get_all(self, verbose):
601 """Get all controls values.
602
603 Args:
604 verbose: Boolean on whether to return doc info as well
605
606 Returns:
607 string creating from trying to get all values of all controls. In case of
608 error attempting access to control, response is 'ERR'.
609 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800610 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700611 for name in self._syscfg.syscfg_dict['control']:
612 self._logger.debug("name = %s" %name)
613 try:
614 value = self.get(name)
615 except Exception:
616 value = "ERR"
617 pass
618 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800619 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700620 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800621 rsp.append("%s:%s" % (name, value))
622 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700623
624 def set(self, name, wr_val_str):
625 """Set control.
626
627 Args:
628 name: name string of control
629 wr_val_str: value string to write. Can be integer, float or a
630 alpha-numerical that is mapped to a integer or float.
631
632 Raises:
633 HwDriverError: Error occurred while using driver
634 """
Todd Broch7a91c252012-02-03 12:37:45 -0800635 if name == 'sleep':
636 time.sleep(float(wr_val_str))
637 return True
638
Todd Broche505b8d2011-03-21 18:19:54 -0700639 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
640 (params, drv) = self._get_param_drv(name, False)
641 wr_val = self._syscfg.resolve_val(params, wr_val_str)
642 try:
643 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800644 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700645 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
646 raise
647 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
648 # & client I still have to return something to appease the
649 # marshall/unmarshall
650 return True
651
Todd Brochd6061672012-05-11 15:52:47 -0700652 def hwinit(self, verbose=False):
653 """Initialize all controls.
654
655 These values are part of the system config XML files of the form
656 init=<value>. This command should be used by clients wishing to return the
657 servo and DUT its connected to a known good/safe state.
658
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800659 Note that initialization errors are ignored (as in some cases they could
660 be caused by DUT firmware deficiencies). This might need to be fine tuned
661 later.
662
Todd Brochd6061672012-05-11 15:52:47 -0700663 Args:
664 verbose: boolean, if True prints info about control initialized.
665 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800666
667 Returns:
668 This function is called across RPC and as such is expected to return
669 something unless transferring 'none' across is allowed. Hence adding a
670 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700671 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800672 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800673 try:
674 self.set(control_name, value)
675 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800676 self._logger.error("Problem initializing %s -> %s :: %s",
677 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700678 if verbose:
679 self._logger.info('Initialized %s to %s', control_name, value)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800680 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800681
Todd Broche505b8d2011-03-21 18:19:54 -0700682 def echo(self, echo):
683 """Dummy echo function for testing/examples.
684
685 Args:
686 echo: string to echo back to client
687 """
688 self._logger.debug("echo(%s)" % (echo))
689 return "ECH0ING: %s" % (echo)
690
J. Richard Barnettee2820552013-03-14 16:13:46 -0700691 def get_board(self):
692 """Return the board specified at startup, if any."""
693 return self._board
694
Simran Basia23c1392013-08-06 14:59:10 -0700695 def get_version(self):
696 """Get servo board version."""
697 return self._version
698
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800699 def power_long_press(self):
700 """Simulate a long power button press."""
701 # After a long power press, the EC may ignore the next power
702 # button press (at least on Alex). To guarantee that this
703 # won't happen, we need to allow the EC one second to
704 # collect itself.
705 self._keyboard.power_long_press()
706 return True
707
708 def power_normal_press(self):
709 """Simulate a normal power button press."""
710 self._keyboard.power_normal_press()
711 return True
712
713 def power_short_press(self):
714 """Simulate a short power button press."""
715 self._keyboard.power_short_press()
716 return True
717
718 def power_key(self, secs=''):
719 """Simulate a power button press.
720
721 Args:
722 secs: Time in seconds to simulate the keypress.
723 """
724 self._keyboard.power_key(secs)
725 return True
726
727 def ctrl_d(self, press_secs=''):
728 """Simulate Ctrl-d simultaneous button presses."""
729 self._keyboard.ctrl_d(press_secs)
730 return True
731
732 def ctrl_u(self):
733 """Simulate Ctrl-u simultaneous button presses."""
734 self._keyboard.ctrl_u()
735 return True
736
737 def ctrl_enter(self, press_secs=''):
738 """Simulate Ctrl-enter simultaneous button presses."""
739 self._keyboard.ctrl_enter(press_secs)
740 return True
741
742 def d_key(self, press_secs=''):
743 """Simulate Enter key button press."""
744 self._keyboard.d_key(press_secs)
745 return True
746
747 def ctrl_key(self, press_secs=''):
748 """Simulate Enter key button press."""
749 self._keyboard.ctrl_key(press_secs)
750 return True
751
752 def enter_key(self, press_secs=''):
753 """Simulate Enter key button press."""
754 self._keyboard.enter_key(press_secs)
755 return True
756
757 def refresh_key(self, press_secs=''):
758 """Simulate Refresh key (F3) button press."""
759 self._keyboard.refresh_key(press_secs)
760 return True
761
762 def ctrl_refresh_key(self, press_secs=''):
763 """Simulate Ctrl and Refresh (F3) simultaneous press.
764
765 This key combination is an alternative of Space key.
766 """
767 self._keyboard.ctrl_refresh_key(press_secs)
768 return True
769
770 def imaginary_key(self, press_secs=''):
771 """Simulate imaginary key button press.
772
773 Maps to a key that doesn't physically exist.
774 """
775 self._keyboard.imaginary_key(press_secs)
776 return True
777
Todd Brochdbb09982011-10-02 07:14:26 -0700778
Todd Broche505b8d2011-03-21 18:19:54 -0700779def test():
780 """Integration testing.
781
782 TODO(tbroch) Enhance integration test and add unittest (see mox)
783 """
784 logging.basicConfig(level=logging.DEBUG,
785 format="%(asctime)s - %(name)s - " +
786 "%(levelname)s - %(message)s")
787 # configure server & listen
788 servod_obj = Servod(1)
789 # 4 == number of interfaces on a FT4232H device
790 for i in xrange(4):
791 if i == 1:
792 # its an i2c interface ... see __init__ for details and TODO to make
793 # this configureable
794 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
795 else:
796 # its a gpio interface
797 servod_obj._interface_list[i].wr_rd(0)
798
799 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
800 allow_none=True)
801 server.register_introspection_functions()
802 server.register_multicall_functions()
803 server.register_instance(servod_obj)
804 logging.info("Listening on localhost port 9999")
805 server.serve_forever()
806
807if __name__ == "__main__":
808 test()
809
810 # simple client transaction would look like
811 """
812 remote_uri = 'http://localhost:9999'
813 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
814 send_str = "Hello_there"
815 print "Sent " + send_str + ", Recv " + client.echo(send_str)
816 """