blob: 70636ea64a7e9d6d13413dbfb06f7fdbafb41ae7 [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
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080026import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070027import servo_interfaces
Todd Broche505b8d2011-03-21 18:19:54 -070028
29MAX_I2C_CLOCK_HZ = 100000
30
Todd Brochdbb09982011-10-02 07:14:26 -070031
Todd Broche505b8d2011-03-21 18:19:54 -070032class ServodError(Exception):
33 """Exception class for servod."""
34
35class Servod(object):
36 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070037 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070038 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070039 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070040 _USB_J3 = "usb_mux_sel1"
41 _USB_J3_TO_SERVO = "servo_sees_usbkey"
42 _USB_J3_TO_DUT = "dut_sees_usbkey"
43 _USB_J3_PWR = "prtctl4_pwren"
44 _USB_J3_PWR_ON = "on"
45 _USB_J3_PWR_OFF = "off"
Simran Basia9f41032012-05-11 14:21:58 -070046
J. Richard Barnettee2820552013-03-14 16:13:46 -070047 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080048 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -070049 """Servod constructor.
50
51 Args:
52 config: instance of SystemConfig containing all controls for
53 particular Servod invocation
54 vendor: usb vendor id of FTDI device
55 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070056 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070057 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -070058 version: String. Servo board version. Examples: servo_v1, servo_v2,
59 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080060 usbkm232: String. Optional. Path to USB-KM232 device which allow for
61 sending keyboard commands to DUTs that do not have built in
62 keyboards. Used in FAFT tests.
63 e.g. /dev/ttyUSB0
Todd Brochdbb09982011-10-02 07:14:26 -070064
65 Raises:
66 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070067 """
68 self._logger = logging.getLogger("Servod")
69 self._logger.debug("")
70 self._vendor = vendor
71 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070072 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070073 self._syscfg = config
74 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
75 # interfaces are mapped to
76 self._interface_list = []
77 # Dict of Dict to map control name, function name to to tuple (params, drv)
78 # Ex) _drv_dict[name]['get'] = (params, drv)
79 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070080 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -070081 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080082 self._usbkm232 = usbkm232
83
84 self._keyboard = self._init_keyboard_handler(self, self._board)
Todd Broche505b8d2011-03-21 18:19:54 -070085
Todd Brochdbb09982011-10-02 07:14:26 -070086 # Note, interface i is (i - 1) in list
87 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -070088 try:
89 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
90 except KeyError:
91 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070092
Simran Basia9ad25e2013-04-23 11:57:00 -070093 for i, interface in enumerate(interfaces):
94 is_ftdi_interface = False
95 if type(interface) is dict:
96 name = interface['name']
97 elif type(interface) is str:
98 # Its FTDI related interface
99 name = interface
100 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
101 is_ftdi_interface = True
102 else:
103 raise ServodError("Illegal interface type %s" % type(interface))
104
Todd Broch8a77a992012-01-27 09:46:08 -0800105 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -0700106 if is_ftdi_interface and i and \
107 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -0800108 self._product += 1
109 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
110 self._product)
111
Simran Basia9ad25e2013-04-23 11:57:00 -0700112 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -0700113 try:
114 func = getattr(self, '_init_%s' % name)
115 except AttributeError:
116 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -0700117 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -0700118 if isinstance(result, tuple):
119 self._interface_list.extend(result)
120 else:
121 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700122
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800123 def _init_keyboard_handler(self, servo, board=''):
124 """Initialize the correct keyboard handler for board.
125
126 @param servo: servo object.
127 @param board: string, board name.
128
129 """
130 if board == 'parrot':
131 return keyboard_handlers.ParrotHandler(servo)
132 elif board == 'stout':
133 return keyboard_handlers.StoutHandler(servo)
david90eaaef2014-05-29 13:20:59 +0800134 elif board in ('mccloud', 'monroe', 'panther', 'tricky', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800135 if self._usbkm232 is None:
Yusuf Mohsinally66844692014-05-22 10:37:52 -0700136 logging.warn("No device path specified for usbkm232 handler. Returning "
137 "the DefaultHandler, which is likely the wrong keyboard "
138 "handler for the board type specified.")
139 return keyboard_handlers.DefaultHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800140 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
141 else:
142 return keyboard_handlers.DefaultHandler(servo)
143
Todd Broch3ec8df02012-11-20 10:53:03 -0800144 def __del__(self):
145 """Servod deconstructor."""
146 for interface in self._interface_list:
147 del(interface)
148
Todd Brochb3048492012-01-15 21:52:41 -0800149 def _init_dummy(self, interface):
150 """Initialize dummy interface.
151
152 Dummy interface is just a mechanism to reserve that interface for non servod
153 interaction. Typically the interface will be managed by external
154 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
155 interfaces.
156
157 TODO(tbroch): Investigate merits of incorporating these third-party
158 interfaces into servod or creating a communication channel between them
159
160 Returns: None
161 """
162 return None
163
Simran Basie750a342013-03-12 13:45:26 -0700164 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700165 """Initialize gpio driver interface and open for use.
166
167 Args:
168 interface: interface number of FTDI device to use.
169
170 Returns:
171 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700172
173 Raises:
174 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700175 """
Todd Brochad034442011-05-25 15:05:29 -0700176 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
177 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700178 try:
179 fobj.open()
180 except ftdigpio.FgpioError as e:
181 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
182
Todd Broche505b8d2011-03-21 18:19:54 -0700183 return fobj
184
Aaron.Chuang88eff332014-07-31 08:32:00 +0800185 def _init_bb_adc(self, interface):
186 """Initalize beaglebone ADC interface."""
187 return bbadc.BBadc()
188
Simran Basie750a342013-03-12 13:45:26 -0700189 def _init_bb_gpio(self, interface):
190 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700191 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700192
193 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700194 """Initialize i2c interface and open for use.
195
196 Args:
197 interface: interface number of FTDI device to use
198
199 Returns:
200 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700201
202 Raises:
203 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700204 """
Todd Brochad034442011-05-25 15:05:29 -0700205 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
206 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700207 try:
208 fobj.open()
209 except ftdii2c.Fi2cError as e:
210 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
211
Todd Broche505b8d2011-03-21 18:19:54 -0700212 # Set the frequency of operation of the i2c bus.
213 # TODO(tbroch) make configureable
214 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700215
Todd Broche505b8d2011-03-21 18:19:54 -0700216 return fobj
217
Simran Basie750a342013-03-12 13:45:26 -0700218 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
219 def _init_bb_i2c(self, interface):
220 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700221 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700222
223 def _init_ftdi_uart(self, interface):
224 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700225
226 Note, the uart runs in a separate thread (pthreads). Users wishing to
227 interact with it will query control for the pty's pathname and connect
228 with there favorite console program. For example:
229 cu -l /dev/pts/22
230
231 Args:
232 interface: interface number of FTDI device to use
233
234 Returns:
235 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700236
237 Raises:
238 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700239 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700240 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
241 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700242 try:
243 fobj.run()
244 except ftdiuart.FuartError as e:
245 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
246
Todd Broch47c43f42011-05-26 15:11:31 -0700247 self._logger.info("%s" % fobj.get_pty())
248 return fobj
249
Simran Basie750a342013-03-12 13:45:26 -0700250 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
251 def _init_bb_uart(self, interface):
252 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700253 logging.debug('UART INTERFACE: %s', interface)
254 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700255
256 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700257 """Initialize special gpio + uart interface and open for use
258
259 Note, the uart runs in a separate thread (pthreads). Users wishing to
260 interact with it will query control for the pty's pathname and connect
261 with there favorite console program. For example:
262 cu -l /dev/pts/22
263
264 Args:
265 interface: interface number of FTDI device to use
266
267 Returns:
268 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700269
270 Raises:
271 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700272 """
Simran Basie750a342013-03-12 13:45:26 -0700273 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700274 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
275 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700276 try:
277 fuart.run()
278 except ftdiuart.FuartError as e:
279 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
280
Todd Broch888da782011-10-07 14:29:09 -0700281 self._logger.info("uart pty: %s" % fuart.get_pty())
282 return fgpio, fuart
283
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800284 def _camel_case(self, string):
285 output = ''
286 for s in string.split('_'):
287 if output:
288 output += s.capitalize()
289 else:
290 output = s
291 return output
292
Todd Broche505b8d2011-03-21 18:19:54 -0700293 def _get_param_drv(self, control_name, is_get=True):
294 """Get access to driver for a given control.
295
296 Note, some controls have different parameter dictionaries for 'getting' the
297 control's value versus 'setting' it. Boolean is_get distinguishes which is
298 being requested.
299
300 Args:
301 control_name: string name of control
302 is_get: boolean to determine
303
304 Returns:
305 tuple (param, drv) where:
306 param: param dictionary for control
307 drv: instance object of driver for particular control
308
309 Raises:
310 ServodError: Error occurred while examining params dict
311 """
312 self._logger.debug("")
313 # if already setup just return tuple from driver dict
314 if control_name in self._drv_dict:
315 if is_get and ('get' in self._drv_dict[control_name]):
316 return self._drv_dict[control_name]['get']
317 if not is_get and ('set' in self._drv_dict[control_name]):
318 return self._drv_dict[control_name]['set']
319
320 params = self._syscfg.lookup_control_params(control_name, is_get)
321 if 'drv' not in params:
322 self._logger.error("Unable to determine driver for %s" % control_name)
323 raise ServodError("'drv' key not found in params dict")
324 if 'interface' not in params:
325 self._logger.error("Unable to determine interface for %s" %
326 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700327 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700328
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800329 interface_id = params.get(
330 '%s_interface' % self._version, params['interface'])
331 if interface_id == 'servo':
332 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700333 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800334 index = int(interface_id) - 1
335 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700336
Todd Broche505b8d2011-03-21 18:19:54 -0700337 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
338 drv_pkg = imp.load_module('drv',
339 *imp.find_module('drv', servo_pkg.__path__))
340 drv_name = params['drv']
341 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800342 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700343 drv = drv_class(interface, params)
344 if control_name not in self._drv_dict:
345 self._drv_dict[control_name] = {}
346 if is_get:
347 self._drv_dict[control_name]['get'] = (params, drv)
348 else:
349 self._drv_dict[control_name]['set'] = (params, drv)
350 return (params, drv)
351
352 def doc_all(self):
353 """Return all documenation for controls.
354
355 Returns:
356 string of <doc> text in config file (xml) and the params dictionary for
357 all controls.
358
359 For example:
360 warm_reset :: Reset the device warmly
361 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
362 """
363 return self._syscfg.display_config()
364
365 def doc(self, name):
366 """Retreive doc string in system config file for given control name.
367
368 Args:
369 name: name string of control to get doc string
370
371 Returns:
372 doc string of name
373
374 Raises:
375 NameError: if fails to locate control
376 """
377 self._logger.debug("name(%s)" % (name))
378 if self._syscfg.is_control(name):
379 return self._syscfg.get_control_docstring(name)
380 else:
381 raise NameError("No control %s" %name)
382
Fang Deng90377712013-06-03 15:51:48 -0700383 def _switch_usbkey(self, mux_direction):
384 """Connect USB flash stick to either servo or DUT.
385
386 This function switches 'usb_mux_sel1' to provide electrical
387 connection between the USB port J3 and either servo or DUT side.
388
389 Switching the usb mux is accompanied by powercycling
390 of the USB stick, because it sometimes gets wedged if the mux
391 is switched while the stick power is on.
392
393 Args:
394 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
395 """
396 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
397 time.sleep(self._USB_POWEROFF_DELAY)
398 self.set(self._USB_J3, mux_direction)
399 time.sleep(self._USB_POWEROFF_DELAY)
400 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
401 if mux_direction == self._USB_J3_TO_SERVO:
402 time.sleep(self._USB_DETECTION_DELAY)
403
Simran Basia9f41032012-05-11 14:21:58 -0700404 def _get_usb_port_set(self):
405 """Gets a set of USB disks currently connected to the system
406
407 Returns:
408 A set of USB disk paths.
409 """
410 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
411 return set(["/dev/" + dev for dev in usb_set])
412
413 def _probe_host_usb_dev(self):
414 """Probe the USB disk device plugged in the servo from the host side.
415
416 Method can fail by:
417 1) Having multiple servos connected and returning incorrect /dev/sdX of
418 another servo.
419 2) Finding multiple /dev/sdX and returning None.
420
421 Returns:
422 USB disk path if one and only one USB disk path is found, otherwise None.
423 """
Fang Deng90377712013-06-03 15:51:48 -0700424 original_value = self.get(self._USB_J3)
425 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700426 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700427 if (original_usb_power == self._USB_J3_PWR_ON and
428 original_value != self._USB_J3_TO_DUT):
429 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700430 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700431
Fang Deng90377712013-06-03 15:51:48 -0700432 # Make the host able to see the USB disk.
433 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700434 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700435
Simran Basia9f41032012-05-11 14:21:58 -0700436 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700437 if original_value != self._USB_J3_TO_SERVO:
438 self._switch_usbkey(original_value)
439 if original_usb_power != self._USB_J3_PWR_ON:
440 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
441 time.sleep(self._USB_POWEROFF_DELAY)
442
Simran Basia9f41032012-05-11 14:21:58 -0700443 # Subtract the two sets to find the usb device.
444 diff_set = has_usb_set - no_usb_set
445 if len(diff_set) == 1:
446 return diff_set.pop()
447 else:
448 return None
449
450 def download_image_to_usb(self, image_path):
451 """Download image and save to the USB device found by probe_host_usb_dev.
452 If the image_path is a URL, it will download this url to the USB path;
453 otherwise it will simply copy the image_path's contents to the USB path.
454
455 Args:
456 image_path: path or url to the recovery image.
457
458 Returns:
459 True|False: True if process completed successfully, False if error
460 occurred.
461 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
462 comment at the end of set().
463 """
464 self._logger.debug("image_path(%s)" % image_path)
465 self._logger.debug("Detecting USB stick device...")
466 usb_dev = self._probe_host_usb_dev()
467 if not usb_dev:
468 self._logger.error("No usb device connected to servo")
469 return False
470
471 try:
472 if image_path.startswith(self._HTTP_PREFIX):
473 self._logger.debug("Image path is a URL, downloading image")
474 urllib.urlretrieve(image_path, usb_dev)
475 else:
476 shutil.copyfile(image_path, usb_dev)
477 except IOError as e:
478 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
479 e.strerror, e.errno)
480 return False
481 except urllib.ContentTooShortError:
482 self._logger.error("Failed to download URL: %s to USB device: %s",
483 image_path, usb_dev)
484 return False
485 except BaseException as e:
486 self._logger.error("Unexpected exception downloading %s to %s: %s",
487 image_path, usb_dev, str(e))
488 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800489 finally:
490 # We just plastered the partition table for a block device.
491 # Pass or fail, we mustn't go without telling the kernel about
492 # the change, or it will punish us with sporadic, hard-to-debug
493 # failures.
494 subprocess.call(["sync"])
495 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700496 return True
497
498 def make_image_noninteractive(self):
499 """Makes the recovery image noninteractive.
500
501 A noninteractive image will reboot automatically after installation
502 instead of waiting for the USB device to be removed to initiate a system
503 reboot.
504
505 Mounts partition 1 of the image stored on usb_dev and creates a file
506 called "non_interactive" so that the image will become noninteractive.
507
508 Returns:
509 True|False: True if process completed successfully, False if error
510 occurred.
511 """
512 result = True
513 usb_dev = self._probe_host_usb_dev()
514 if not usb_dev:
515 self._logger.error("No usb device connected to servo")
516 return False
517 # Create TempDirectory
518 tmpdir = tempfile.mkdtemp()
519 if tmpdir:
520 # Mount drive to tmpdir.
521 partition_1 = "%s1" % usb_dev
522 rc = subprocess.call(["mount", partition_1, tmpdir])
523 if rc == 0:
524 # Create file 'non_interactive'
525 non_interactive_file = os.path.join(tmpdir, "non_interactive")
526 try:
527 open(non_interactive_file, "w").close()
528 except IOError as e:
529 self._logger.error("Failed to create file %s : %s ( %d )",
530 non_interactive_file, e.strerror, e.errno)
531 result = False
532 except BaseException as e:
533 self._logger.error("Unexpected Exception creating file %s : %s",
534 non_interactive_file, str(e))
535 result = False
536 # Unmount drive regardless if file creation worked or not.
537 rc = subprocess.call(["umount", partition_1])
538 if rc != 0:
539 self._logger.error("Failed to unmount USB Device")
540 result = False
541 else:
542 self._logger.error("Failed to mount USB Device")
543 result = False
544
545 # Delete tmpdir. May throw exception if 'umount' failed.
546 try:
547 os.rmdir(tmpdir)
548 except OSError as e:
549 self._logger.error("Failed to remove temp directory %s : %s",
550 tmpdir, str(e))
551 return False
552 except BaseException as e:
553 self._logger.error("Unexpected Exception removing tempdir %s : %s",
554 tmpdir, str(e))
555 return False
556 else:
557 self._logger.error("Failed to create temp directory.")
558 return False
559 return result
560
Todd Broch352b4b22013-03-22 09:48:40 -0700561 def set_get_all(self, cmds):
562 """Set &| get one or more control values.
563
564 Args:
565 cmds: list of control[:value] to get or set.
566
567 Returns:
568 rv: list of responses from calling get or set methods.
569 """
570 rv = []
571 for cmd in cmds:
572 if ':' in cmd:
573 (control, value) = cmd.split(':')
574 rv.append(self.set(control, value))
575 else:
576 rv.append(self.get(cmd))
577 return rv
578
Todd Broche505b8d2011-03-21 18:19:54 -0700579 def get(self, name):
580 """Get control value.
581
582 Args:
583 name: name string of control
584
585 Returns:
586 Response from calling drv get method. Value is reformatted based on
587 control's dictionary parameters
588
589 Raises:
590 HwDriverError: Error occurred while using drv
591 """
592 self._logger.debug("name(%s)" % (name))
593 (param, drv) = self._get_param_drv(name)
594 try:
595 val = drv.get()
596 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800597 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700598 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700599 except AttributeError, error:
600 self._logger.error("Getting %s: %s" % (name, error))
601 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800602 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700603 self._logger.error("Getting %s" % (name))
604 raise
Todd Brochd6061672012-05-11 15:52:47 -0700605
Todd Broche505b8d2011-03-21 18:19:54 -0700606 def get_all(self, verbose):
607 """Get all controls values.
608
609 Args:
610 verbose: Boolean on whether to return doc info as well
611
612 Returns:
613 string creating from trying to get all values of all controls. In case of
614 error attempting access to control, response is 'ERR'.
615 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800616 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700617 for name in self._syscfg.syscfg_dict['control']:
618 self._logger.debug("name = %s" %name)
619 try:
620 value = self.get(name)
621 except Exception:
622 value = "ERR"
623 pass
624 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800625 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700626 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800627 rsp.append("%s:%s" % (name, value))
628 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700629
630 def set(self, name, wr_val_str):
631 """Set control.
632
633 Args:
634 name: name string of control
635 wr_val_str: value string to write. Can be integer, float or a
636 alpha-numerical that is mapped to a integer or float.
637
638 Raises:
639 HwDriverError: Error occurred while using driver
640 """
641 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
642 (params, drv) = self._get_param_drv(name, False)
643 wr_val = self._syscfg.resolve_val(params, wr_val_str)
644 try:
645 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800646 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700647 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
648 raise
649 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
650 # & client I still have to return something to appease the
651 # marshall/unmarshall
652 return True
653
Todd Brochd6061672012-05-11 15:52:47 -0700654 def hwinit(self, verbose=False):
655 """Initialize all controls.
656
657 These values are part of the system config XML files of the form
658 init=<value>. This command should be used by clients wishing to return the
659 servo and DUT its connected to a known good/safe state.
660
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800661 Note that initialization errors are ignored (as in some cases they could
662 be caused by DUT firmware deficiencies). This might need to be fine tuned
663 later.
664
Todd Brochd6061672012-05-11 15:52:47 -0700665 Args:
666 verbose: boolean, if True prints info about control initialized.
667 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800668
669 Returns:
670 This function is called across RPC and as such is expected to return
671 something unless transferring 'none' across is allowed. Hence adding a
672 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700673 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800674 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800675 try:
676 self.set(control_name, value)
677 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800678 self._logger.error("Problem initializing %s -> %s :: %s",
679 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700680 if verbose:
681 self._logger.info('Initialized %s to %s', control_name, value)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800682 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800683
Todd Broche505b8d2011-03-21 18:19:54 -0700684 def echo(self, echo):
685 """Dummy echo function for testing/examples.
686
687 Args:
688 echo: string to echo back to client
689 """
690 self._logger.debug("echo(%s)" % (echo))
691 return "ECH0ING: %s" % (echo)
692
J. Richard Barnettee2820552013-03-14 16:13:46 -0700693 def get_board(self):
694 """Return the board specified at startup, if any."""
695 return self._board
696
Simran Basia23c1392013-08-06 14:59:10 -0700697 def get_version(self):
698 """Get servo board version."""
699 return self._version
700
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800701 def power_long_press(self):
702 """Simulate a long power button press."""
703 # After a long power press, the EC may ignore the next power
704 # button press (at least on Alex). To guarantee that this
705 # won't happen, we need to allow the EC one second to
706 # collect itself.
707 self._keyboard.power_long_press()
708 return True
709
710 def power_normal_press(self):
711 """Simulate a normal power button press."""
712 self._keyboard.power_normal_press()
713 return True
714
715 def power_short_press(self):
716 """Simulate a short power button press."""
717 self._keyboard.power_short_press()
718 return True
719
720 def power_key(self, secs=''):
721 """Simulate a power button press.
722
723 Args:
724 secs: Time in seconds to simulate the keypress.
725 """
726 self._keyboard.power_key(secs)
727 return True
728
729 def ctrl_d(self, press_secs=''):
730 """Simulate Ctrl-d simultaneous button presses."""
731 self._keyboard.ctrl_d(press_secs)
732 return True
733
734 def ctrl_u(self):
735 """Simulate Ctrl-u simultaneous button presses."""
736 self._keyboard.ctrl_u()
737 return True
738
739 def ctrl_enter(self, press_secs=''):
740 """Simulate Ctrl-enter simultaneous button presses."""
741 self._keyboard.ctrl_enter(press_secs)
742 return True
743
744 def d_key(self, press_secs=''):
745 """Simulate Enter key button press."""
746 self._keyboard.d_key(press_secs)
747 return True
748
749 def ctrl_key(self, press_secs=''):
750 """Simulate Enter key button press."""
751 self._keyboard.ctrl_key(press_secs)
752 return True
753
754 def enter_key(self, press_secs=''):
755 """Simulate Enter key button press."""
756 self._keyboard.enter_key(press_secs)
757 return True
758
759 def refresh_key(self, press_secs=''):
760 """Simulate Refresh key (F3) button press."""
761 self._keyboard.refresh_key(press_secs)
762 return True
763
764 def ctrl_refresh_key(self, press_secs=''):
765 """Simulate Ctrl and Refresh (F3) simultaneous press.
766
767 This key combination is an alternative of Space key.
768 """
769 self._keyboard.ctrl_refresh_key(press_secs)
770 return True
771
772 def imaginary_key(self, press_secs=''):
773 """Simulate imaginary key button press.
774
775 Maps to a key that doesn't physically exist.
776 """
777 self._keyboard.imaginary_key(press_secs)
778 return True
779
Todd Brochdbb09982011-10-02 07:14:26 -0700780
Todd Broche505b8d2011-03-21 18:19:54 -0700781def test():
782 """Integration testing.
783
784 TODO(tbroch) Enhance integration test and add unittest (see mox)
785 """
786 logging.basicConfig(level=logging.DEBUG,
787 format="%(asctime)s - %(name)s - " +
788 "%(levelname)s - %(message)s")
789 # configure server & listen
790 servod_obj = Servod(1)
791 # 4 == number of interfaces on a FT4232H device
792 for i in xrange(4):
793 if i == 1:
794 # its an i2c interface ... see __init__ for details and TODO to make
795 # this configureable
796 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
797 else:
798 # its a gpio interface
799 servod_obj._interface_list[i].wr_rd(0)
800
801 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
802 allow_none=True)
803 server.register_introspection_functions()
804 server.register_multicall_functions()
805 server.register_instance(servod_obj)
806 logging.info("Listening on localhost port 9999")
807 server.serve_forever()
808
809if __name__ == "__main__":
810 test()
811
812 # simple client transaction would look like
813 """
814 remote_uri = 'http://localhost:9999'
815 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
816 send_str = "Hello_there"
817 print "Sent " + send_str + ", Recv " + client.echo(send_str)
818 """