blob: b0ba2ab1fd4ebdf0118ef67165b3f515a6c8aba3 [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
Aaron.Chuang88eff332014-07-31 08:32:00 +080018import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070019import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070020import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070021import bbuart
Todd Broche505b8d2011-03-21 18:19:54 -070022import ftdigpio
23import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070024import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070025import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080026import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080027import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070028import servo_interfaces
Todd Broche505b8d2011-03-21 18:19:54 -070029
30MAX_I2C_CLOCK_HZ = 100000
31
Todd Brochdbb09982011-10-02 07:14:26 -070032
Todd Broche505b8d2011-03-21 18:19:54 -070033class ServodError(Exception):
34 """Exception class for servod."""
35
36class Servod(object):
37 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070038 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070039 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070040 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070041 _USB_J3 = "usb_mux_sel1"
42 _USB_J3_TO_SERVO = "servo_sees_usbkey"
43 _USB_J3_TO_DUT = "dut_sees_usbkey"
44 _USB_J3_PWR = "prtctl4_pwren"
45 _USB_J3_PWR_ON = "on"
46 _USB_J3_PWR_OFF = "off"
Simran Basia9f41032012-05-11 14:21:58 -070047
J. Richard Barnettee2820552013-03-14 16:13:46 -070048 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080049 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -070050 """Servod constructor.
51
52 Args:
53 config: instance of SystemConfig containing all controls for
54 particular Servod invocation
55 vendor: usb vendor id of FTDI device
56 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070057 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070058 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -070059 version: String. Servo board version. Examples: servo_v1, servo_v2,
60 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080061 usbkm232: String. Optional. Path to USB-KM232 device which allow for
62 sending keyboard commands to DUTs that do not have built in
63 keyboards. Used in FAFT tests.
64 e.g. /dev/ttyUSB0
Todd Brochdbb09982011-10-02 07:14:26 -070065
66 Raises:
67 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070068 """
69 self._logger = logging.getLogger("Servod")
70 self._logger.debug("")
71 self._vendor = vendor
72 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070073 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070074 self._syscfg = config
75 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
76 # interfaces are mapped to
77 self._interface_list = []
78 # Dict of Dict to map control name, function name to to tuple (params, drv)
79 # Ex) _drv_dict[name]['get'] = (params, drv)
80 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070081 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -070082 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080083 self._usbkm232 = usbkm232
84
85 self._keyboard = self._init_keyboard_handler(self, self._board)
Todd Broche505b8d2011-03-21 18:19:54 -070086
Todd Brochdbb09982011-10-02 07:14:26 -070087 # Note, interface i is (i - 1) in list
88 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -070089 try:
90 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
91 except KeyError:
92 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070093
Simran Basia9ad25e2013-04-23 11:57:00 -070094 for i, interface in enumerate(interfaces):
95 is_ftdi_interface = False
96 if type(interface) is dict:
97 name = interface['name']
98 elif type(interface) is str:
99 # Its FTDI related interface
100 name = interface
101 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
102 is_ftdi_interface = True
103 else:
104 raise ServodError("Illegal interface type %s" % type(interface))
105
Todd Broch8a77a992012-01-27 09:46:08 -0800106 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -0700107 if is_ftdi_interface and i and \
108 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -0800109 self._product += 1
110 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
111 self._product)
112
Simran Basia9ad25e2013-04-23 11:57:00 -0700113 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -0700114 try:
115 func = getattr(self, '_init_%s' % name)
116 except AttributeError:
117 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -0700118 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -0700119 if isinstance(result, tuple):
120 self._interface_list.extend(result)
121 else:
122 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700123
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800124 def _init_keyboard_handler(self, servo, board=''):
125 """Initialize the correct keyboard handler for board.
126
127 @param servo: servo object.
128 @param board: string, board name.
129
130 """
131 if board == 'parrot':
132 return keyboard_handlers.ParrotHandler(servo)
133 elif board == 'stout':
134 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800135 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800136 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
137 'sumo', 'tidus', 'tricky', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800138 if self._usbkm232 is None:
Yusuf Mohsinally66844692014-05-22 10:37:52 -0700139 logging.warn("No device path specified for usbkm232 handler. Returning "
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800140 "the MatrixKeyboardHandler, which is likely the wrong "
141 "keyboard handler for the board type specified.")
142 return keyboard_handlers.MatrixKeyboardHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800143 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
144 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800145 # The following boards don't use Chrome EC.
146 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
147 return keyboard_handlers.MatrixKeyboardHandler(servo)
148 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800149
Todd Broch3ec8df02012-11-20 10:53:03 -0800150 def __del__(self):
151 """Servod deconstructor."""
152 for interface in self._interface_list:
153 del(interface)
154
Todd Brochb3048492012-01-15 21:52:41 -0800155 def _init_dummy(self, interface):
156 """Initialize dummy interface.
157
158 Dummy interface is just a mechanism to reserve that interface for non servod
159 interaction. Typically the interface will be managed by external
160 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
161 interfaces.
162
163 TODO(tbroch): Investigate merits of incorporating these third-party
164 interfaces into servod or creating a communication channel between them
165
166 Returns: None
167 """
168 return None
169
Simran Basie750a342013-03-12 13:45:26 -0700170 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700171 """Initialize gpio driver interface and open for use.
172
173 Args:
174 interface: interface number of FTDI device to use.
175
176 Returns:
177 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700178
179 Raises:
180 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700181 """
Todd Brochad034442011-05-25 15:05:29 -0700182 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
183 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700184 try:
185 fobj.open()
186 except ftdigpio.FgpioError as e:
187 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
188
Todd Broche505b8d2011-03-21 18:19:54 -0700189 return fobj
190
Aaron.Chuang88eff332014-07-31 08:32:00 +0800191 def _init_bb_adc(self, interface):
192 """Initalize beaglebone ADC interface."""
193 return bbadc.BBadc()
194
Simran Basie750a342013-03-12 13:45:26 -0700195 def _init_bb_gpio(self, interface):
196 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700197 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700198
199 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700200 """Initialize i2c interface and open for use.
201
202 Args:
203 interface: interface number of FTDI device to use
204
205 Returns:
206 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700207
208 Raises:
209 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700210 """
Todd Brochad034442011-05-25 15:05:29 -0700211 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
212 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700213 try:
214 fobj.open()
215 except ftdii2c.Fi2cError as e:
216 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
217
Todd Broche505b8d2011-03-21 18:19:54 -0700218 # Set the frequency of operation of the i2c bus.
219 # TODO(tbroch) make configureable
220 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700221
Todd Broche505b8d2011-03-21 18:19:54 -0700222 return fobj
223
Simran Basie750a342013-03-12 13:45:26 -0700224 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
225 def _init_bb_i2c(self, interface):
226 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700227 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700228
Rong Changc6c8c022014-08-11 14:07:11 +0800229 def _init_dev_i2c(self, interface):
230 """Initalize Linux i2c-dev interface."""
231 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
232
Simran Basie750a342013-03-12 13:45:26 -0700233 def _init_ftdi_uart(self, interface):
234 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700235
236 Note, the uart runs in a separate thread (pthreads). Users wishing to
237 interact with it will query control for the pty's pathname and connect
238 with there favorite console program. For example:
239 cu -l /dev/pts/22
240
241 Args:
242 interface: interface number of FTDI device to use
243
244 Returns:
245 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700246
247 Raises:
248 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700249 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700250 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
251 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700252 try:
253 fobj.run()
254 except ftdiuart.FuartError as e:
255 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
256
Todd Broch47c43f42011-05-26 15:11:31 -0700257 self._logger.info("%s" % fobj.get_pty())
258 return fobj
259
Simran Basie750a342013-03-12 13:45:26 -0700260 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
261 def _init_bb_uart(self, interface):
262 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700263 logging.debug('UART INTERFACE: %s', interface)
264 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700265
266 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700267 """Initialize special gpio + uart interface and open for use
268
269 Note, the uart runs in a separate thread (pthreads). Users wishing to
270 interact with it will query control for the pty's pathname and connect
271 with there favorite console program. For example:
272 cu -l /dev/pts/22
273
274 Args:
275 interface: interface number of FTDI device to use
276
277 Returns:
278 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700279
280 Raises:
281 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700282 """
Simran Basie750a342013-03-12 13:45:26 -0700283 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700284 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
285 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700286 try:
287 fuart.run()
288 except ftdiuart.FuartError as e:
289 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
290
Todd Broch888da782011-10-07 14:29:09 -0700291 self._logger.info("uart pty: %s" % fuart.get_pty())
292 return fgpio, fuart
293
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800294 def _camel_case(self, string):
295 output = ''
296 for s in string.split('_'):
297 if output:
298 output += s.capitalize()
299 else:
300 output = s
301 return output
302
Todd Broche505b8d2011-03-21 18:19:54 -0700303 def _get_param_drv(self, control_name, is_get=True):
304 """Get access to driver for a given control.
305
306 Note, some controls have different parameter dictionaries for 'getting' the
307 control's value versus 'setting' it. Boolean is_get distinguishes which is
308 being requested.
309
310 Args:
311 control_name: string name of control
312 is_get: boolean to determine
313
314 Returns:
315 tuple (param, drv) where:
316 param: param dictionary for control
317 drv: instance object of driver for particular control
318
319 Raises:
320 ServodError: Error occurred while examining params dict
321 """
322 self._logger.debug("")
323 # if already setup just return tuple from driver dict
324 if control_name in self._drv_dict:
325 if is_get and ('get' in self._drv_dict[control_name]):
326 return self._drv_dict[control_name]['get']
327 if not is_get and ('set' in self._drv_dict[control_name]):
328 return self._drv_dict[control_name]['set']
329
330 params = self._syscfg.lookup_control_params(control_name, is_get)
331 if 'drv' not in params:
332 self._logger.error("Unable to determine driver for %s" % control_name)
333 raise ServodError("'drv' key not found in params dict")
334 if 'interface' not in params:
335 self._logger.error("Unable to determine interface for %s" %
336 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700337 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700338
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800339 interface_id = params.get(
340 '%s_interface' % self._version, params['interface'])
341 if interface_id == 'servo':
342 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700343 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800344 index = int(interface_id) - 1
345 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700346
Todd Broche505b8d2011-03-21 18:19:54 -0700347 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
348 drv_pkg = imp.load_module('drv',
349 *imp.find_module('drv', servo_pkg.__path__))
350 drv_name = params['drv']
351 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800352 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700353 drv = drv_class(interface, params)
354 if control_name not in self._drv_dict:
355 self._drv_dict[control_name] = {}
356 if is_get:
357 self._drv_dict[control_name]['get'] = (params, drv)
358 else:
359 self._drv_dict[control_name]['set'] = (params, drv)
360 return (params, drv)
361
362 def doc_all(self):
363 """Return all documenation for controls.
364
365 Returns:
366 string of <doc> text in config file (xml) and the params dictionary for
367 all controls.
368
369 For example:
370 warm_reset :: Reset the device warmly
371 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
372 """
373 return self._syscfg.display_config()
374
375 def doc(self, name):
376 """Retreive doc string in system config file for given control name.
377
378 Args:
379 name: name string of control to get doc string
380
381 Returns:
382 doc string of name
383
384 Raises:
385 NameError: if fails to locate control
386 """
387 self._logger.debug("name(%s)" % (name))
388 if self._syscfg.is_control(name):
389 return self._syscfg.get_control_docstring(name)
390 else:
391 raise NameError("No control %s" %name)
392
Fang Deng90377712013-06-03 15:51:48 -0700393 def _switch_usbkey(self, mux_direction):
394 """Connect USB flash stick to either servo or DUT.
395
396 This function switches 'usb_mux_sel1' to provide electrical
397 connection between the USB port J3 and either servo or DUT side.
398
399 Switching the usb mux is accompanied by powercycling
400 of the USB stick, because it sometimes gets wedged if the mux
401 is switched while the stick power is on.
402
403 Args:
404 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
405 """
406 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
407 time.sleep(self._USB_POWEROFF_DELAY)
408 self.set(self._USB_J3, mux_direction)
409 time.sleep(self._USB_POWEROFF_DELAY)
410 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
411 if mux_direction == self._USB_J3_TO_SERVO:
412 time.sleep(self._USB_DETECTION_DELAY)
413
Simran Basia9f41032012-05-11 14:21:58 -0700414 def _get_usb_port_set(self):
415 """Gets a set of USB disks currently connected to the system
416
417 Returns:
418 A set of USB disk paths.
419 """
420 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
421 return set(["/dev/" + dev for dev in usb_set])
422
423 def _probe_host_usb_dev(self):
424 """Probe the USB disk device plugged in the servo from the host side.
425
426 Method can fail by:
427 1) Having multiple servos connected and returning incorrect /dev/sdX of
428 another servo.
429 2) Finding multiple /dev/sdX and returning None.
430
431 Returns:
432 USB disk path if one and only one USB disk path is found, otherwise None.
433 """
Fang Deng90377712013-06-03 15:51:48 -0700434 original_value = self.get(self._USB_J3)
435 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700436 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700437 if (original_usb_power == self._USB_J3_PWR_ON and
438 original_value != self._USB_J3_TO_DUT):
439 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700440 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700441
Fang Deng90377712013-06-03 15:51:48 -0700442 # Make the host able to see the USB disk.
443 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700444 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700445
Simran Basia9f41032012-05-11 14:21:58 -0700446 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700447 if original_value != self._USB_J3_TO_SERVO:
448 self._switch_usbkey(original_value)
449 if original_usb_power != self._USB_J3_PWR_ON:
450 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
451 time.sleep(self._USB_POWEROFF_DELAY)
452
Simran Basia9f41032012-05-11 14:21:58 -0700453 # Subtract the two sets to find the usb device.
454 diff_set = has_usb_set - no_usb_set
455 if len(diff_set) == 1:
456 return diff_set.pop()
457 else:
458 return None
459
460 def download_image_to_usb(self, image_path):
461 """Download image and save to the USB device found by probe_host_usb_dev.
462 If the image_path is a URL, it will download this url to the USB path;
463 otherwise it will simply copy the image_path's contents to the USB path.
464
465 Args:
466 image_path: path or url to the recovery image.
467
468 Returns:
469 True|False: True if process completed successfully, False if error
470 occurred.
471 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
472 comment at the end of set().
473 """
474 self._logger.debug("image_path(%s)" % image_path)
475 self._logger.debug("Detecting USB stick device...")
476 usb_dev = self._probe_host_usb_dev()
477 if not usb_dev:
478 self._logger.error("No usb device connected to servo")
479 return False
480
481 try:
482 if image_path.startswith(self._HTTP_PREFIX):
483 self._logger.debug("Image path is a URL, downloading image")
484 urllib.urlretrieve(image_path, usb_dev)
485 else:
486 shutil.copyfile(image_path, usb_dev)
487 except IOError as e:
488 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
489 e.strerror, e.errno)
490 return False
491 except urllib.ContentTooShortError:
492 self._logger.error("Failed to download URL: %s to USB device: %s",
493 image_path, usb_dev)
494 return False
495 except BaseException as e:
496 self._logger.error("Unexpected exception downloading %s to %s: %s",
497 image_path, usb_dev, str(e))
498 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800499 finally:
500 # We just plastered the partition table for a block device.
501 # Pass or fail, we mustn't go without telling the kernel about
502 # the change, or it will punish us with sporadic, hard-to-debug
503 # failures.
504 subprocess.call(["sync"])
505 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700506 return True
507
508 def make_image_noninteractive(self):
509 """Makes the recovery image noninteractive.
510
511 A noninteractive image will reboot automatically after installation
512 instead of waiting for the USB device to be removed to initiate a system
513 reboot.
514
515 Mounts partition 1 of the image stored on usb_dev and creates a file
516 called "non_interactive" so that the image will become noninteractive.
517
518 Returns:
519 True|False: True if process completed successfully, False if error
520 occurred.
521 """
522 result = True
523 usb_dev = self._probe_host_usb_dev()
524 if not usb_dev:
525 self._logger.error("No usb device connected to servo")
526 return False
527 # Create TempDirectory
528 tmpdir = tempfile.mkdtemp()
529 if tmpdir:
530 # Mount drive to tmpdir.
531 partition_1 = "%s1" % usb_dev
532 rc = subprocess.call(["mount", partition_1, tmpdir])
533 if rc == 0:
534 # Create file 'non_interactive'
535 non_interactive_file = os.path.join(tmpdir, "non_interactive")
536 try:
537 open(non_interactive_file, "w").close()
538 except IOError as e:
539 self._logger.error("Failed to create file %s : %s ( %d )",
540 non_interactive_file, e.strerror, e.errno)
541 result = False
542 except BaseException as e:
543 self._logger.error("Unexpected Exception creating file %s : %s",
544 non_interactive_file, str(e))
545 result = False
546 # Unmount drive regardless if file creation worked or not.
547 rc = subprocess.call(["umount", partition_1])
548 if rc != 0:
549 self._logger.error("Failed to unmount USB Device")
550 result = False
551 else:
552 self._logger.error("Failed to mount USB Device")
553 result = False
554
555 # Delete tmpdir. May throw exception if 'umount' failed.
556 try:
557 os.rmdir(tmpdir)
558 except OSError as e:
559 self._logger.error("Failed to remove temp directory %s : %s",
560 tmpdir, str(e))
561 return False
562 except BaseException as e:
563 self._logger.error("Unexpected Exception removing tempdir %s : %s",
564 tmpdir, str(e))
565 return False
566 else:
567 self._logger.error("Failed to create temp directory.")
568 return False
569 return result
570
Todd Broch352b4b22013-03-22 09:48:40 -0700571 def set_get_all(self, cmds):
572 """Set &| get one or more control values.
573
574 Args:
575 cmds: list of control[:value] to get or set.
576
577 Returns:
578 rv: list of responses from calling get or set methods.
579 """
580 rv = []
581 for cmd in cmds:
582 if ':' in cmd:
583 (control, value) = cmd.split(':')
584 rv.append(self.set(control, value))
585 else:
586 rv.append(self.get(cmd))
587 return rv
588
Todd Broche505b8d2011-03-21 18:19:54 -0700589 def get(self, name):
590 """Get control value.
591
592 Args:
593 name: name string of control
594
595 Returns:
596 Response from calling drv get method. Value is reformatted based on
597 control's dictionary parameters
598
599 Raises:
600 HwDriverError: Error occurred while using drv
601 """
602 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700603 if name == 'serialname':
604 if self._serialname:
605 return self._serialname
606 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700607 (param, drv) = self._get_param_drv(name)
608 try:
609 val = drv.get()
610 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800611 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700612 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700613 except AttributeError, error:
614 self._logger.error("Getting %s: %s" % (name, error))
615 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800616 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700617 self._logger.error("Getting %s" % (name))
618 raise
Todd Brochd6061672012-05-11 15:52:47 -0700619
Todd Broche505b8d2011-03-21 18:19:54 -0700620 def get_all(self, verbose):
621 """Get all controls values.
622
623 Args:
624 verbose: Boolean on whether to return doc info as well
625
626 Returns:
627 string creating from trying to get all values of all controls. In case of
628 error attempting access to control, response is 'ERR'.
629 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800630 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700631 for name in self._syscfg.syscfg_dict['control']:
632 self._logger.debug("name = %s" %name)
633 try:
634 value = self.get(name)
635 except Exception:
636 value = "ERR"
637 pass
638 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800639 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700640 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800641 rsp.append("%s:%s" % (name, value))
642 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700643
644 def set(self, name, wr_val_str):
645 """Set control.
646
647 Args:
648 name: name string of control
649 wr_val_str: value string to write. Can be integer, float or a
650 alpha-numerical that is mapped to a integer or float.
651
652 Raises:
653 HwDriverError: Error occurred while using driver
654 """
655 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
656 (params, drv) = self._get_param_drv(name, False)
657 wr_val = self._syscfg.resolve_val(params, wr_val_str)
658 try:
659 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800660 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700661 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
662 raise
663 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
664 # & client I still have to return something to appease the
665 # marshall/unmarshall
666 return True
667
Todd Brochd6061672012-05-11 15:52:47 -0700668 def hwinit(self, verbose=False):
669 """Initialize all controls.
670
671 These values are part of the system config XML files of the form
672 init=<value>. This command should be used by clients wishing to return the
673 servo and DUT its connected to a known good/safe state.
674
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800675 Note that initialization errors are ignored (as in some cases they could
676 be caused by DUT firmware deficiencies). This might need to be fine tuned
677 later.
678
Todd Brochd6061672012-05-11 15:52:47 -0700679 Args:
680 verbose: boolean, if True prints info about control initialized.
681 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800682
683 Returns:
684 This function is called across RPC and as such is expected to return
685 something unless transferring 'none' across is allowed. Hence adding a
686 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700687 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800688 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800689 try:
690 self.set(control_name, value)
691 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800692 self._logger.error("Problem initializing %s -> %s :: %s",
693 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700694 if verbose:
695 self._logger.info('Initialized %s to %s', control_name, value)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800696 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800697
Todd Broche505b8d2011-03-21 18:19:54 -0700698 def echo(self, echo):
699 """Dummy echo function for testing/examples.
700
701 Args:
702 echo: string to echo back to client
703 """
704 self._logger.debug("echo(%s)" % (echo))
705 return "ECH0ING: %s" % (echo)
706
J. Richard Barnettee2820552013-03-14 16:13:46 -0700707 def get_board(self):
708 """Return the board specified at startup, if any."""
709 return self._board
710
Simran Basia23c1392013-08-06 14:59:10 -0700711 def get_version(self):
712 """Get servo board version."""
713 return self._version
714
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800715 def power_long_press(self):
716 """Simulate a long power button press."""
717 # After a long power press, the EC may ignore the next power
718 # button press (at least on Alex). To guarantee that this
719 # won't happen, we need to allow the EC one second to
720 # collect itself.
721 self._keyboard.power_long_press()
722 return True
723
724 def power_normal_press(self):
725 """Simulate a normal power button press."""
726 self._keyboard.power_normal_press()
727 return True
728
729 def power_short_press(self):
730 """Simulate a short power button press."""
731 self._keyboard.power_short_press()
732 return True
733
734 def power_key(self, secs=''):
735 """Simulate a power button press.
736
737 Args:
738 secs: Time in seconds to simulate the keypress.
739 """
740 self._keyboard.power_key(secs)
741 return True
742
743 def ctrl_d(self, press_secs=''):
744 """Simulate Ctrl-d simultaneous button presses."""
745 self._keyboard.ctrl_d(press_secs)
746 return True
747
748 def ctrl_u(self):
749 """Simulate Ctrl-u simultaneous button presses."""
750 self._keyboard.ctrl_u()
751 return True
752
753 def ctrl_enter(self, press_secs=''):
754 """Simulate Ctrl-enter simultaneous button presses."""
755 self._keyboard.ctrl_enter(press_secs)
756 return True
757
758 def d_key(self, press_secs=''):
759 """Simulate Enter key button press."""
760 self._keyboard.d_key(press_secs)
761 return True
762
763 def ctrl_key(self, press_secs=''):
764 """Simulate Enter key button press."""
765 self._keyboard.ctrl_key(press_secs)
766 return True
767
768 def enter_key(self, press_secs=''):
769 """Simulate Enter key button press."""
770 self._keyboard.enter_key(press_secs)
771 return True
772
773 def refresh_key(self, press_secs=''):
774 """Simulate Refresh key (F3) button press."""
775 self._keyboard.refresh_key(press_secs)
776 return True
777
778 def ctrl_refresh_key(self, press_secs=''):
779 """Simulate Ctrl and Refresh (F3) simultaneous press.
780
781 This key combination is an alternative of Space key.
782 """
783 self._keyboard.ctrl_refresh_key(press_secs)
784 return True
785
786 def imaginary_key(self, press_secs=''):
787 """Simulate imaginary key button press.
788
789 Maps to a key that doesn't physically exist.
790 """
791 self._keyboard.imaginary_key(press_secs)
792 return True
793
Todd Brochdbb09982011-10-02 07:14:26 -0700794
Todd Broche505b8d2011-03-21 18:19:54 -0700795def test():
796 """Integration testing.
797
798 TODO(tbroch) Enhance integration test and add unittest (see mox)
799 """
800 logging.basicConfig(level=logging.DEBUG,
801 format="%(asctime)s - %(name)s - " +
802 "%(levelname)s - %(message)s")
803 # configure server & listen
804 servod_obj = Servod(1)
805 # 4 == number of interfaces on a FT4232H device
806 for i in xrange(4):
807 if i == 1:
808 # its an i2c interface ... see __init__ for details and TODO to make
809 # this configureable
810 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
811 else:
812 # its a gpio interface
813 servod_obj._interface_list[i].wr_rd(0)
814
815 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
816 allow_none=True)
817 server.register_introspection_functions()
818 server.register_multicall_functions()
819 server.register_instance(servod_obj)
820 logging.info("Listening on localhost port 9999")
821 server.serve_forever()
822
823if __name__ == "__main__":
824 test()
825
826 # simple client transaction would look like
827 """
828 remote_uri = 'http://localhost:9999'
829 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
830 send_str = "Hello_there"
831 print "Sent " + send_str + ", Recv " + client.echo(send_str)
832 """