blob: 4d489f286d75d495330d1d88072a29e949cd8bde [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:
Todd Brochb21d8042014-05-15 12:54:54 -070087 try:
88 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
89 except KeyError:
90 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070091
Simran Basia9ad25e2013-04-23 11:57:00 -070092 for i, interface in enumerate(interfaces):
93 is_ftdi_interface = False
94 if type(interface) is dict:
95 name = interface['name']
96 elif type(interface) is str:
97 # Its FTDI related interface
98 name = interface
99 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
100 is_ftdi_interface = True
101 else:
102 raise ServodError("Illegal interface type %s" % type(interface))
103
Todd Broch8a77a992012-01-27 09:46:08 -0800104 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -0700105 if is_ftdi_interface and i and \
106 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -0800107 self._product += 1
108 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
109 self._product)
110
Simran Basia9ad25e2013-04-23 11:57:00 -0700111 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -0700112 try:
113 func = getattr(self, '_init_%s' % name)
114 except AttributeError:
115 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -0700116 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -0700117 if isinstance(result, tuple):
118 self._interface_list.extend(result)
119 else:
120 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700121
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800122 def _init_keyboard_handler(self, servo, board=''):
123 """Initialize the correct keyboard handler for board.
124
125 @param servo: servo object.
126 @param board: string, board name.
127
128 """
129 if board == 'parrot':
130 return keyboard_handlers.ParrotHandler(servo)
131 elif board == 'stout':
132 return keyboard_handlers.StoutHandler(servo)
david90eaaef2014-05-29 13:20:59 +0800133 elif board in ('mccloud', 'monroe', 'panther', 'tricky', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800134 if self._usbkm232 is None:
Yusuf Mohsinally66844692014-05-22 10:37:52 -0700135 logging.warn("No device path specified for usbkm232 handler. Returning "
136 "the DefaultHandler, which is likely the wrong keyboard "
137 "handler for the board type specified.")
138 return keyboard_handlers.DefaultHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800139 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
140 else:
141 return keyboard_handlers.DefaultHandler(servo)
142
Todd Broch3ec8df02012-11-20 10:53:03 -0800143 def __del__(self):
144 """Servod deconstructor."""
145 for interface in self._interface_list:
146 del(interface)
147
Todd Brochb3048492012-01-15 21:52:41 -0800148 def _init_dummy(self, interface):
149 """Initialize dummy interface.
150
151 Dummy interface is just a mechanism to reserve that interface for non servod
152 interaction. Typically the interface will be managed by external
153 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
154 interfaces.
155
156 TODO(tbroch): Investigate merits of incorporating these third-party
157 interfaces into servod or creating a communication channel between them
158
159 Returns: None
160 """
161 return None
162
Simran Basie750a342013-03-12 13:45:26 -0700163 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700164 """Initialize gpio driver interface and open for use.
165
166 Args:
167 interface: interface number of FTDI device to use.
168
169 Returns:
170 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700171
172 Raises:
173 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700174 """
Todd Brochad034442011-05-25 15:05:29 -0700175 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
176 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700177 try:
178 fobj.open()
179 except ftdigpio.FgpioError as e:
180 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
181
Todd Broche505b8d2011-03-21 18:19:54 -0700182 return fobj
183
Simran Basie750a342013-03-12 13:45:26 -0700184 def _init_bb_gpio(self, interface):
185 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700186 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700187
188 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700189 """Initialize i2c interface and open for use.
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 Broche505b8d2011-03-21 18:19:54 -0700199 """
Todd Brochad034442011-05-25 15:05:29 -0700200 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
201 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700202 try:
203 fobj.open()
204 except ftdii2c.Fi2cError as e:
205 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
206
Todd Broche505b8d2011-03-21 18:19:54 -0700207 # Set the frequency of operation of the i2c bus.
208 # TODO(tbroch) make configureable
209 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700210
Todd Broche505b8d2011-03-21 18:19:54 -0700211 return fobj
212
Simran Basie750a342013-03-12 13:45:26 -0700213 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
214 def _init_bb_i2c(self, interface):
215 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700216 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700217
218 def _init_ftdi_uart(self, interface):
219 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700220
221 Note, the uart runs in a separate thread (pthreads). Users wishing to
222 interact with it will query control for the pty's pathname and connect
223 with there favorite console program. For example:
224 cu -l /dev/pts/22
225
226 Args:
227 interface: interface number of FTDI device to use
228
229 Returns:
230 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700231
232 Raises:
233 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700234 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700235 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
236 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700237 try:
238 fobj.run()
239 except ftdiuart.FuartError as e:
240 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
241
Todd Broch47c43f42011-05-26 15:11:31 -0700242 self._logger.info("%s" % fobj.get_pty())
243 return fobj
244
Simran Basie750a342013-03-12 13:45:26 -0700245 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
246 def _init_bb_uart(self, interface):
247 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700248 logging.debug('UART INTERFACE: %s', interface)
249 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700250
251 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700252 """Initialize special gpio + uart interface and open for use
253
254 Note, the uart runs in a separate thread (pthreads). Users wishing to
255 interact with it will query control for the pty's pathname and connect
256 with there favorite console program. For example:
257 cu -l /dev/pts/22
258
259 Args:
260 interface: interface number of FTDI device to use
261
262 Returns:
263 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700264
265 Raises:
266 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700267 """
Simran Basie750a342013-03-12 13:45:26 -0700268 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700269 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
270 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700271 try:
272 fuart.run()
273 except ftdiuart.FuartError as e:
274 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
275
Todd Broch888da782011-10-07 14:29:09 -0700276 self._logger.info("uart pty: %s" % fuart.get_pty())
277 return fgpio, fuart
278
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800279 def _camel_case(self, string):
280 output = ''
281 for s in string.split('_'):
282 if output:
283 output += s.capitalize()
284 else:
285 output = s
286 return output
287
Todd Broche505b8d2011-03-21 18:19:54 -0700288 def _get_param_drv(self, control_name, is_get=True):
289 """Get access to driver for a given control.
290
291 Note, some controls have different parameter dictionaries for 'getting' the
292 control's value versus 'setting' it. Boolean is_get distinguishes which is
293 being requested.
294
295 Args:
296 control_name: string name of control
297 is_get: boolean to determine
298
299 Returns:
300 tuple (param, drv) where:
301 param: param dictionary for control
302 drv: instance object of driver for particular control
303
304 Raises:
305 ServodError: Error occurred while examining params dict
306 """
307 self._logger.debug("")
308 # if already setup just return tuple from driver dict
309 if control_name in self._drv_dict:
310 if is_get and ('get' in self._drv_dict[control_name]):
311 return self._drv_dict[control_name]['get']
312 if not is_get and ('set' in self._drv_dict[control_name]):
313 return self._drv_dict[control_name]['set']
314
315 params = self._syscfg.lookup_control_params(control_name, is_get)
316 if 'drv' not in params:
317 self._logger.error("Unable to determine driver for %s" % control_name)
318 raise ServodError("'drv' key not found in params dict")
319 if 'interface' not in params:
320 self._logger.error("Unable to determine interface for %s" %
321 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700322 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700323
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800324 interface_id = params.get(
325 '%s_interface' % self._version, params['interface'])
326 if interface_id == 'servo':
327 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700328 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800329 index = int(interface_id) - 1
330 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700331
Todd Broche505b8d2011-03-21 18:19:54 -0700332 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
333 drv_pkg = imp.load_module('drv',
334 *imp.find_module('drv', servo_pkg.__path__))
335 drv_name = params['drv']
336 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800337 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700338 drv = drv_class(interface, params)
339 if control_name not in self._drv_dict:
340 self._drv_dict[control_name] = {}
341 if is_get:
342 self._drv_dict[control_name]['get'] = (params, drv)
343 else:
344 self._drv_dict[control_name]['set'] = (params, drv)
345 return (params, drv)
346
347 def doc_all(self):
348 """Return all documenation for controls.
349
350 Returns:
351 string of <doc> text in config file (xml) and the params dictionary for
352 all controls.
353
354 For example:
355 warm_reset :: Reset the device warmly
356 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
357 """
358 return self._syscfg.display_config()
359
360 def doc(self, name):
361 """Retreive doc string in system config file for given control name.
362
363 Args:
364 name: name string of control to get doc string
365
366 Returns:
367 doc string of name
368
369 Raises:
370 NameError: if fails to locate control
371 """
372 self._logger.debug("name(%s)" % (name))
373 if self._syscfg.is_control(name):
374 return self._syscfg.get_control_docstring(name)
375 else:
376 raise NameError("No control %s" %name)
377
Fang Deng90377712013-06-03 15:51:48 -0700378 def _switch_usbkey(self, mux_direction):
379 """Connect USB flash stick to either servo or DUT.
380
381 This function switches 'usb_mux_sel1' to provide electrical
382 connection between the USB port J3 and either servo or DUT side.
383
384 Switching the usb mux is accompanied by powercycling
385 of the USB stick, because it sometimes gets wedged if the mux
386 is switched while the stick power is on.
387
388 Args:
389 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
390 """
391 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
392 time.sleep(self._USB_POWEROFF_DELAY)
393 self.set(self._USB_J3, mux_direction)
394 time.sleep(self._USB_POWEROFF_DELAY)
395 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
396 if mux_direction == self._USB_J3_TO_SERVO:
397 time.sleep(self._USB_DETECTION_DELAY)
398
Simran Basia9f41032012-05-11 14:21:58 -0700399 def _get_usb_port_set(self):
400 """Gets a set of USB disks currently connected to the system
401
402 Returns:
403 A set of USB disk paths.
404 """
405 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
406 return set(["/dev/" + dev for dev in usb_set])
407
408 def _probe_host_usb_dev(self):
409 """Probe the USB disk device plugged in the servo from the host side.
410
411 Method can fail by:
412 1) Having multiple servos connected and returning incorrect /dev/sdX of
413 another servo.
414 2) Finding multiple /dev/sdX and returning None.
415
416 Returns:
417 USB disk path if one and only one USB disk path is found, otherwise None.
418 """
Fang Deng90377712013-06-03 15:51:48 -0700419 original_value = self.get(self._USB_J3)
420 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700421 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700422 if (original_usb_power == self._USB_J3_PWR_ON and
423 original_value != self._USB_J3_TO_DUT):
424 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700425 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700426
Fang Deng90377712013-06-03 15:51:48 -0700427 # Make the host able to see the USB disk.
428 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700429 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700430
Simran Basia9f41032012-05-11 14:21:58 -0700431 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700432 if original_value != self._USB_J3_TO_SERVO:
433 self._switch_usbkey(original_value)
434 if original_usb_power != self._USB_J3_PWR_ON:
435 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
436 time.sleep(self._USB_POWEROFF_DELAY)
437
Simran Basia9f41032012-05-11 14:21:58 -0700438 # Subtract the two sets to find the usb device.
439 diff_set = has_usb_set - no_usb_set
440 if len(diff_set) == 1:
441 return diff_set.pop()
442 else:
443 return None
444
445 def download_image_to_usb(self, image_path):
446 """Download image and save to the USB device found by probe_host_usb_dev.
447 If the image_path is a URL, it will download this url to the USB path;
448 otherwise it will simply copy the image_path's contents to the USB path.
449
450 Args:
451 image_path: path or url to the recovery image.
452
453 Returns:
454 True|False: True if process completed successfully, False if error
455 occurred.
456 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
457 comment at the end of set().
458 """
459 self._logger.debug("image_path(%s)" % image_path)
460 self._logger.debug("Detecting USB stick device...")
461 usb_dev = self._probe_host_usb_dev()
462 if not usb_dev:
463 self._logger.error("No usb device connected to servo")
464 return False
465
466 try:
467 if image_path.startswith(self._HTTP_PREFIX):
468 self._logger.debug("Image path is a URL, downloading image")
469 urllib.urlretrieve(image_path, usb_dev)
470 else:
471 shutil.copyfile(image_path, usb_dev)
472 except IOError as e:
473 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
474 e.strerror, e.errno)
475 return False
476 except urllib.ContentTooShortError:
477 self._logger.error("Failed to download URL: %s to USB device: %s",
478 image_path, usb_dev)
479 return False
480 except BaseException as e:
481 self._logger.error("Unexpected exception downloading %s to %s: %s",
482 image_path, usb_dev, str(e))
483 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800484 finally:
485 # We just plastered the partition table for a block device.
486 # Pass or fail, we mustn't go without telling the kernel about
487 # the change, or it will punish us with sporadic, hard-to-debug
488 # failures.
489 subprocess.call(["sync"])
490 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700491 return True
492
493 def make_image_noninteractive(self):
494 """Makes the recovery image noninteractive.
495
496 A noninteractive image will reboot automatically after installation
497 instead of waiting for the USB device to be removed to initiate a system
498 reboot.
499
500 Mounts partition 1 of the image stored on usb_dev and creates a file
501 called "non_interactive" so that the image will become noninteractive.
502
503 Returns:
504 True|False: True if process completed successfully, False if error
505 occurred.
506 """
507 result = True
508 usb_dev = self._probe_host_usb_dev()
509 if not usb_dev:
510 self._logger.error("No usb device connected to servo")
511 return False
512 # Create TempDirectory
513 tmpdir = tempfile.mkdtemp()
514 if tmpdir:
515 # Mount drive to tmpdir.
516 partition_1 = "%s1" % usb_dev
517 rc = subprocess.call(["mount", partition_1, tmpdir])
518 if rc == 0:
519 # Create file 'non_interactive'
520 non_interactive_file = os.path.join(tmpdir, "non_interactive")
521 try:
522 open(non_interactive_file, "w").close()
523 except IOError as e:
524 self._logger.error("Failed to create file %s : %s ( %d )",
525 non_interactive_file, e.strerror, e.errno)
526 result = False
527 except BaseException as e:
528 self._logger.error("Unexpected Exception creating file %s : %s",
529 non_interactive_file, str(e))
530 result = False
531 # Unmount drive regardless if file creation worked or not.
532 rc = subprocess.call(["umount", partition_1])
533 if rc != 0:
534 self._logger.error("Failed to unmount USB Device")
535 result = False
536 else:
537 self._logger.error("Failed to mount USB Device")
538 result = False
539
540 # Delete tmpdir. May throw exception if 'umount' failed.
541 try:
542 os.rmdir(tmpdir)
543 except OSError as e:
544 self._logger.error("Failed to remove temp directory %s : %s",
545 tmpdir, str(e))
546 return False
547 except BaseException as e:
548 self._logger.error("Unexpected Exception removing tempdir %s : %s",
549 tmpdir, str(e))
550 return False
551 else:
552 self._logger.error("Failed to create temp directory.")
553 return False
554 return result
555
Todd Broch352b4b22013-03-22 09:48:40 -0700556 def set_get_all(self, cmds):
557 """Set &| get one or more control values.
558
559 Args:
560 cmds: list of control[:value] to get or set.
561
562 Returns:
563 rv: list of responses from calling get or set methods.
564 """
565 rv = []
566 for cmd in cmds:
567 if ':' in cmd:
568 (control, value) = cmd.split(':')
569 rv.append(self.set(control, value))
570 else:
571 rv.append(self.get(cmd))
572 return rv
573
Todd Broche505b8d2011-03-21 18:19:54 -0700574 def get(self, name):
575 """Get control value.
576
577 Args:
578 name: name string of control
579
580 Returns:
581 Response from calling drv get method. Value is reformatted based on
582 control's dictionary parameters
583
584 Raises:
585 HwDriverError: Error occurred while using drv
586 """
587 self._logger.debug("name(%s)" % (name))
588 (param, drv) = self._get_param_drv(name)
589 try:
590 val = drv.get()
591 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800592 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700593 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700594 except AttributeError, error:
595 self._logger.error("Getting %s: %s" % (name, error))
596 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800597 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700598 self._logger.error("Getting %s" % (name))
599 raise
Todd Brochd6061672012-05-11 15:52:47 -0700600
Todd Broche505b8d2011-03-21 18:19:54 -0700601 def get_all(self, verbose):
602 """Get all controls values.
603
604 Args:
605 verbose: Boolean on whether to return doc info as well
606
607 Returns:
608 string creating from trying to get all values of all controls. In case of
609 error attempting access to control, response is 'ERR'.
610 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800611 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700612 for name in self._syscfg.syscfg_dict['control']:
613 self._logger.debug("name = %s" %name)
614 try:
615 value = self.get(name)
616 except Exception:
617 value = "ERR"
618 pass
619 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800620 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700621 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800622 rsp.append("%s:%s" % (name, value))
623 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700624
625 def set(self, name, wr_val_str):
626 """Set control.
627
628 Args:
629 name: name string of control
630 wr_val_str: value string to write. Can be integer, float or a
631 alpha-numerical that is mapped to a integer or float.
632
633 Raises:
634 HwDriverError: Error occurred while using driver
635 """
636 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
637 (params, drv) = self._get_param_drv(name, False)
638 wr_val = self._syscfg.resolve_val(params, wr_val_str)
639 try:
640 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800641 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700642 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
643 raise
644 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
645 # & client I still have to return something to appease the
646 # marshall/unmarshall
647 return True
648
Todd Brochd6061672012-05-11 15:52:47 -0700649 def hwinit(self, verbose=False):
650 """Initialize all controls.
651
652 These values are part of the system config XML files of the form
653 init=<value>. This command should be used by clients wishing to return the
654 servo and DUT its connected to a known good/safe state.
655
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800656 Note that initialization errors are ignored (as in some cases they could
657 be caused by DUT firmware deficiencies). This might need to be fine tuned
658 later.
659
Todd Brochd6061672012-05-11 15:52:47 -0700660 Args:
661 verbose: boolean, if True prints info about control initialized.
662 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800663
664 Returns:
665 This function is called across RPC and as such is expected to return
666 something unless transferring 'none' across is allowed. Hence adding a
667 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700668 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800669 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800670 try:
671 self.set(control_name, value)
672 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800673 self._logger.error("Problem initializing %s -> %s :: %s",
674 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700675 if verbose:
676 self._logger.info('Initialized %s to %s', control_name, value)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800677 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800678
Todd Broche505b8d2011-03-21 18:19:54 -0700679 def echo(self, echo):
680 """Dummy echo function for testing/examples.
681
682 Args:
683 echo: string to echo back to client
684 """
685 self._logger.debug("echo(%s)" % (echo))
686 return "ECH0ING: %s" % (echo)
687
J. Richard Barnettee2820552013-03-14 16:13:46 -0700688 def get_board(self):
689 """Return the board specified at startup, if any."""
690 return self._board
691
Simran Basia23c1392013-08-06 14:59:10 -0700692 def get_version(self):
693 """Get servo board version."""
694 return self._version
695
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800696 def power_long_press(self):
697 """Simulate a long power button press."""
698 # After a long power press, the EC may ignore the next power
699 # button press (at least on Alex). To guarantee that this
700 # won't happen, we need to allow the EC one second to
701 # collect itself.
702 self._keyboard.power_long_press()
703 return True
704
705 def power_normal_press(self):
706 """Simulate a normal power button press."""
707 self._keyboard.power_normal_press()
708 return True
709
710 def power_short_press(self):
711 """Simulate a short power button press."""
712 self._keyboard.power_short_press()
713 return True
714
715 def power_key(self, secs=''):
716 """Simulate a power button press.
717
718 Args:
719 secs: Time in seconds to simulate the keypress.
720 """
721 self._keyboard.power_key(secs)
722 return True
723
724 def ctrl_d(self, press_secs=''):
725 """Simulate Ctrl-d simultaneous button presses."""
726 self._keyboard.ctrl_d(press_secs)
727 return True
728
729 def ctrl_u(self):
730 """Simulate Ctrl-u simultaneous button presses."""
731 self._keyboard.ctrl_u()
732 return True
733
734 def ctrl_enter(self, press_secs=''):
735 """Simulate Ctrl-enter simultaneous button presses."""
736 self._keyboard.ctrl_enter(press_secs)
737 return True
738
739 def d_key(self, press_secs=''):
740 """Simulate Enter key button press."""
741 self._keyboard.d_key(press_secs)
742 return True
743
744 def ctrl_key(self, press_secs=''):
745 """Simulate Enter key button press."""
746 self._keyboard.ctrl_key(press_secs)
747 return True
748
749 def enter_key(self, press_secs=''):
750 """Simulate Enter key button press."""
751 self._keyboard.enter_key(press_secs)
752 return True
753
754 def refresh_key(self, press_secs=''):
755 """Simulate Refresh key (F3) button press."""
756 self._keyboard.refresh_key(press_secs)
757 return True
758
759 def ctrl_refresh_key(self, press_secs=''):
760 """Simulate Ctrl and Refresh (F3) simultaneous press.
761
762 This key combination is an alternative of Space key.
763 """
764 self._keyboard.ctrl_refresh_key(press_secs)
765 return True
766
767 def imaginary_key(self, press_secs=''):
768 """Simulate imaginary key button press.
769
770 Maps to a key that doesn't physically exist.
771 """
772 self._keyboard.imaginary_key(press_secs)
773 return True
774
Todd Brochdbb09982011-10-02 07:14:26 -0700775
Todd Broche505b8d2011-03-21 18:19:54 -0700776def test():
777 """Integration testing.
778
779 TODO(tbroch) Enhance integration test and add unittest (see mox)
780 """
781 logging.basicConfig(level=logging.DEBUG,
782 format="%(asctime)s - %(name)s - " +
783 "%(levelname)s - %(message)s")
784 # configure server & listen
785 servod_obj = Servod(1)
786 # 4 == number of interfaces on a FT4232H device
787 for i in xrange(4):
788 if i == 1:
789 # its an i2c interface ... see __init__ for details and TODO to make
790 # this configureable
791 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
792 else:
793 # its a gpio interface
794 servod_obj._interface_list[i].wr_rd(0)
795
796 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
797 allow_none=True)
798 server.register_introspection_functions()
799 server.register_multicall_functions()
800 server.register_instance(servod_obj)
801 logging.info("Listening on localhost port 9999")
802 server.serve_forever()
803
804if __name__ == "__main__":
805 test()
806
807 # simple client transaction would look like
808 """
809 remote_uri = 'http://localhost:9999'
810 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
811 send_str = "Hello_there"
812 print "Sent " + send_str + ", Recv " + client.echo(send_str)
813 """