blob: bb646ab8b8a8a4c5e779fa5259c46793115b26df [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
Danny Chan662b6022015-11-04 17:34:53 -080063 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
64 e.g. '/dev/ttyUSB0' or 'atmega'
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
Todd Brochdbb09982011-10-02 07:14:26 -070084 # Note, interface i is (i - 1) in list
85 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -070086 try:
87 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
88 except KeyError:
89 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070090
Simran Basia9ad25e2013-04-23 11:57:00 -070091 for i, interface in enumerate(interfaces):
92 is_ftdi_interface = False
93 if type(interface) is dict:
94 name = interface['name']
95 elif type(interface) is str:
96 # Its FTDI related interface
97 name = interface
98 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
99 is_ftdi_interface = True
100 else:
101 raise ServodError("Illegal interface type %s" % type(interface))
102
Todd Broch8a77a992012-01-27 09:46:08 -0800103 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -0700104 if is_ftdi_interface and i and \
105 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -0800106 self._product += 1
107 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
108 self._product)
109
Simran Basia9ad25e2013-04-23 11:57:00 -0700110 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -0700111 try:
112 func = getattr(self, '_init_%s' % name)
113 except AttributeError:
114 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -0700115 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -0700116 if isinstance(result, tuple):
117 self._interface_list.extend(result)
118 else:
119 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700120
Danny Chan662b6022015-11-04 17:34:53 -0800121 # Init keyboard after all the intefaces are up.
122 self._keyboard = self._init_keyboard_handler(self, self._board)
123
124
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800125 def _init_keyboard_handler(self, servo, board=''):
126 """Initialize the correct keyboard handler for board.
127
128 @param servo: servo object.
129 @param board: string, board name.
130
131 """
132 if board == 'parrot':
133 return keyboard_handlers.ParrotHandler(servo)
134 elif board == 'stout':
135 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800136 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800137 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
Jason Simmonse5cccd12015-08-25 16:05:25 -0700138 'sumo', 'tidus', 'tricky', 'veyron_mickey', 'veyron_rialto',
139 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800140 if self._usbkm232 is None:
Yusuf Mohsinally66844692014-05-22 10:37:52 -0700141 logging.warn("No device path specified for usbkm232 handler. Returning "
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800142 "the MatrixKeyboardHandler, which is likely the wrong "
143 "keyboard handler for the board type specified.")
144 return keyboard_handlers.MatrixKeyboardHandler(servo)
Danny Chan662b6022015-11-04 17:34:53 -0800145 if self._usbkm232 == 'atmega':
146 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800147 self.set('atmega_rst', 'on')
148 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800149 self._usbkm232 = self.get('atmega_pty')
150 self.set('atmega_baudrate', '9600')
151 self.set('atmega_bits', 'eight')
152 self.set('atmega_parity', 'none')
153 self.set('atmega_sbits', 'one')
154 self.set('usb_mux_sel4', 'on')
Nick Sanders78423782015-11-09 14:28:19 -0800155 # Allow atmega bootup time.
156 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800157 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800158 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
159 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800160 # The following boards don't use Chrome EC.
161 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
162 return keyboard_handlers.MatrixKeyboardHandler(servo)
163 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800164
Todd Broch3ec8df02012-11-20 10:53:03 -0800165 def __del__(self):
166 """Servod deconstructor."""
167 for interface in self._interface_list:
168 del(interface)
169
Todd Brochb3048492012-01-15 21:52:41 -0800170 def _init_dummy(self, interface):
171 """Initialize dummy interface.
172
173 Dummy interface is just a mechanism to reserve that interface for non servod
174 interaction. Typically the interface will be managed by external
175 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
176 interfaces.
177
178 TODO(tbroch): Investigate merits of incorporating these third-party
179 interfaces into servod or creating a communication channel between them
180
181 Returns: None
182 """
183 return None
184
Simran Basie750a342013-03-12 13:45:26 -0700185 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700186 """Initialize gpio driver interface and open for use.
187
188 Args:
189 interface: interface number of FTDI device to use.
190
191 Returns:
192 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700193
194 Raises:
195 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700196 """
Todd Brochad034442011-05-25 15:05:29 -0700197 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
198 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700199 try:
200 fobj.open()
201 except ftdigpio.FgpioError as e:
202 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
203
Todd Broche505b8d2011-03-21 18:19:54 -0700204 return fobj
205
Aaron.Chuang88eff332014-07-31 08:32:00 +0800206 def _init_bb_adc(self, interface):
207 """Initalize beaglebone ADC interface."""
208 return bbadc.BBadc()
209
Simran Basie750a342013-03-12 13:45:26 -0700210 def _init_bb_gpio(self, interface):
211 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700212 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700213
214 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700215 """Initialize i2c interface and open for use.
216
217 Args:
218 interface: interface number of FTDI device to use
219
220 Returns:
221 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700222
223 Raises:
224 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700225 """
Todd Brochad034442011-05-25 15:05:29 -0700226 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
227 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700228 try:
229 fobj.open()
230 except ftdii2c.Fi2cError as e:
231 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
232
Todd Broche505b8d2011-03-21 18:19:54 -0700233 # Set the frequency of operation of the i2c bus.
234 # TODO(tbroch) make configureable
235 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700236
Todd Broche505b8d2011-03-21 18:19:54 -0700237 return fobj
238
Simran Basie750a342013-03-12 13:45:26 -0700239 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
240 def _init_bb_i2c(self, interface):
241 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700242 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700243
Rong Changc6c8c022014-08-11 14:07:11 +0800244 def _init_dev_i2c(self, interface):
245 """Initalize Linux i2c-dev interface."""
246 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
247
Simran Basie750a342013-03-12 13:45:26 -0700248 def _init_ftdi_uart(self, interface):
249 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700250
251 Note, the uart runs in a separate thread (pthreads). Users wishing to
252 interact with it will query control for the pty's pathname and connect
253 with there favorite console program. For example:
254 cu -l /dev/pts/22
255
256 Args:
257 interface: interface number of FTDI device to use
258
259 Returns:
260 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700261
262 Raises:
263 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700264 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700265 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
266 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700267 try:
268 fobj.run()
269 except ftdiuart.FuartError as e:
270 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
271
Todd Broch47c43f42011-05-26 15:11:31 -0700272 self._logger.info("%s" % fobj.get_pty())
273 return fobj
274
Simran Basie750a342013-03-12 13:45:26 -0700275 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
276 def _init_bb_uart(self, interface):
277 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700278 logging.debug('UART INTERFACE: %s', interface)
279 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700280
281 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700282 """Initialize special gpio + uart interface and open for use
283
284 Note, the uart runs in a separate thread (pthreads). Users wishing to
285 interact with it will query control for the pty's pathname and connect
286 with there favorite console program. For example:
287 cu -l /dev/pts/22
288
289 Args:
290 interface: interface number of FTDI device to use
291
292 Returns:
293 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700294
295 Raises:
296 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700297 """
Simran Basie750a342013-03-12 13:45:26 -0700298 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700299 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
300 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700301 try:
302 fuart.run()
303 except ftdiuart.FuartError as e:
304 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
305
Todd Broch888da782011-10-07 14:29:09 -0700306 self._logger.info("uart pty: %s" % fuart.get_pty())
307 return fgpio, fuart
308
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800309 def _camel_case(self, string):
310 output = ''
311 for s in string.split('_'):
312 if output:
313 output += s.capitalize()
314 else:
315 output = s
316 return output
317
Todd Broche505b8d2011-03-21 18:19:54 -0700318 def _get_param_drv(self, control_name, is_get=True):
319 """Get access to driver for a given control.
320
321 Note, some controls have different parameter dictionaries for 'getting' the
322 control's value versus 'setting' it. Boolean is_get distinguishes which is
323 being requested.
324
325 Args:
326 control_name: string name of control
327 is_get: boolean to determine
328
329 Returns:
330 tuple (param, drv) where:
331 param: param dictionary for control
332 drv: instance object of driver for particular control
333
334 Raises:
335 ServodError: Error occurred while examining params dict
336 """
337 self._logger.debug("")
338 # if already setup just return tuple from driver dict
339 if control_name in self._drv_dict:
340 if is_get and ('get' in self._drv_dict[control_name]):
341 return self._drv_dict[control_name]['get']
342 if not is_get and ('set' in self._drv_dict[control_name]):
343 return self._drv_dict[control_name]['set']
344
345 params = self._syscfg.lookup_control_params(control_name, is_get)
346 if 'drv' not in params:
347 self._logger.error("Unable to determine driver for %s" % control_name)
348 raise ServodError("'drv' key not found in params dict")
349 if 'interface' not in params:
350 self._logger.error("Unable to determine interface for %s" %
351 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700352 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700353
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800354 interface_id = params.get(
355 '%s_interface' % self._version, params['interface'])
356 if interface_id == 'servo':
357 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700358 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800359 index = int(interface_id) - 1
360 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700361
Todd Broche505b8d2011-03-21 18:19:54 -0700362 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
363 drv_pkg = imp.load_module('drv',
364 *imp.find_module('drv', servo_pkg.__path__))
365 drv_name = params['drv']
366 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800367 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700368 drv = drv_class(interface, params)
369 if control_name not in self._drv_dict:
370 self._drv_dict[control_name] = {}
371 if is_get:
372 self._drv_dict[control_name]['get'] = (params, drv)
373 else:
374 self._drv_dict[control_name]['set'] = (params, drv)
375 return (params, drv)
376
377 def doc_all(self):
378 """Return all documenation for controls.
379
380 Returns:
381 string of <doc> text in config file (xml) and the params dictionary for
382 all controls.
383
384 For example:
385 warm_reset :: Reset the device warmly
386 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
387 """
388 return self._syscfg.display_config()
389
390 def doc(self, name):
391 """Retreive doc string in system config file for given control name.
392
393 Args:
394 name: name string of control to get doc string
395
396 Returns:
397 doc string of name
398
399 Raises:
400 NameError: if fails to locate control
401 """
402 self._logger.debug("name(%s)" % (name))
403 if self._syscfg.is_control(name):
404 return self._syscfg.get_control_docstring(name)
405 else:
406 raise NameError("No control %s" %name)
407
Fang Deng90377712013-06-03 15:51:48 -0700408 def _switch_usbkey(self, mux_direction):
409 """Connect USB flash stick to either servo or DUT.
410
411 This function switches 'usb_mux_sel1' to provide electrical
412 connection between the USB port J3 and either servo or DUT side.
413
414 Switching the usb mux is accompanied by powercycling
415 of the USB stick, because it sometimes gets wedged if the mux
416 is switched while the stick power is on.
417
418 Args:
419 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
420 """
421 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
422 time.sleep(self._USB_POWEROFF_DELAY)
423 self.set(self._USB_J3, mux_direction)
424 time.sleep(self._USB_POWEROFF_DELAY)
425 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
426 if mux_direction == self._USB_J3_TO_SERVO:
427 time.sleep(self._USB_DETECTION_DELAY)
428
Simran Basia9f41032012-05-11 14:21:58 -0700429 def _get_usb_port_set(self):
430 """Gets a set of USB disks currently connected to the system
431
432 Returns:
433 A set of USB disk paths.
434 """
435 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
436 return set(["/dev/" + dev for dev in usb_set])
437
438 def _probe_host_usb_dev(self):
439 """Probe the USB disk device plugged in the servo from the host side.
440
441 Method can fail by:
442 1) Having multiple servos connected and returning incorrect /dev/sdX of
443 another servo.
444 2) Finding multiple /dev/sdX and returning None.
445
446 Returns:
447 USB disk path if one and only one USB disk path is found, otherwise None.
448 """
Fang Deng90377712013-06-03 15:51:48 -0700449 original_value = self.get(self._USB_J3)
450 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700451 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700452 if (original_usb_power == self._USB_J3_PWR_ON and
453 original_value != self._USB_J3_TO_DUT):
454 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700455 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700456
Fang Deng90377712013-06-03 15:51:48 -0700457 # Make the host able to see the USB disk.
458 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700459 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700460
Simran Basia9f41032012-05-11 14:21:58 -0700461 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700462 if original_value != self._USB_J3_TO_SERVO:
463 self._switch_usbkey(original_value)
464 if original_usb_power != self._USB_J3_PWR_ON:
465 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
466 time.sleep(self._USB_POWEROFF_DELAY)
467
Simran Basia9f41032012-05-11 14:21:58 -0700468 # Subtract the two sets to find the usb device.
469 diff_set = has_usb_set - no_usb_set
470 if len(diff_set) == 1:
471 return diff_set.pop()
472 else:
473 return None
474
475 def download_image_to_usb(self, image_path):
476 """Download image and save to the USB device found by probe_host_usb_dev.
477 If the image_path is a URL, it will download this url to the USB path;
478 otherwise it will simply copy the image_path's contents to the USB path.
479
480 Args:
481 image_path: path or url to the recovery image.
482
483 Returns:
484 True|False: True if process completed successfully, False if error
485 occurred.
486 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
487 comment at the end of set().
488 """
489 self._logger.debug("image_path(%s)" % image_path)
490 self._logger.debug("Detecting USB stick device...")
491 usb_dev = self._probe_host_usb_dev()
492 if not usb_dev:
493 self._logger.error("No usb device connected to servo")
494 return False
495
496 try:
497 if image_path.startswith(self._HTTP_PREFIX):
498 self._logger.debug("Image path is a URL, downloading image")
499 urllib.urlretrieve(image_path, usb_dev)
500 else:
501 shutil.copyfile(image_path, usb_dev)
502 except IOError as e:
503 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
504 e.strerror, e.errno)
505 return False
506 except urllib.ContentTooShortError:
507 self._logger.error("Failed to download URL: %s to USB device: %s",
508 image_path, usb_dev)
509 return False
510 except BaseException as e:
511 self._logger.error("Unexpected exception downloading %s to %s: %s",
512 image_path, usb_dev, str(e))
513 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800514 finally:
515 # We just plastered the partition table for a block device.
516 # Pass or fail, we mustn't go without telling the kernel about
517 # the change, or it will punish us with sporadic, hard-to-debug
518 # failures.
519 subprocess.call(["sync"])
520 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700521 return True
522
523 def make_image_noninteractive(self):
524 """Makes the recovery image noninteractive.
525
526 A noninteractive image will reboot automatically after installation
527 instead of waiting for the USB device to be removed to initiate a system
528 reboot.
529
530 Mounts partition 1 of the image stored on usb_dev and creates a file
531 called "non_interactive" so that the image will become noninteractive.
532
533 Returns:
534 True|False: True if process completed successfully, False if error
535 occurred.
536 """
537 result = True
538 usb_dev = self._probe_host_usb_dev()
539 if not usb_dev:
540 self._logger.error("No usb device connected to servo")
541 return False
542 # Create TempDirectory
543 tmpdir = tempfile.mkdtemp()
544 if tmpdir:
545 # Mount drive to tmpdir.
546 partition_1 = "%s1" % usb_dev
547 rc = subprocess.call(["mount", partition_1, tmpdir])
548 if rc == 0:
549 # Create file 'non_interactive'
550 non_interactive_file = os.path.join(tmpdir, "non_interactive")
551 try:
552 open(non_interactive_file, "w").close()
553 except IOError as e:
554 self._logger.error("Failed to create file %s : %s ( %d )",
555 non_interactive_file, e.strerror, e.errno)
556 result = False
557 except BaseException as e:
558 self._logger.error("Unexpected Exception creating file %s : %s",
559 non_interactive_file, str(e))
560 result = False
561 # Unmount drive regardless if file creation worked or not.
562 rc = subprocess.call(["umount", partition_1])
563 if rc != 0:
564 self._logger.error("Failed to unmount USB Device")
565 result = False
566 else:
567 self._logger.error("Failed to mount USB Device")
568 result = False
569
570 # Delete tmpdir. May throw exception if 'umount' failed.
571 try:
572 os.rmdir(tmpdir)
573 except OSError as e:
574 self._logger.error("Failed to remove temp directory %s : %s",
575 tmpdir, str(e))
576 return False
577 except BaseException as e:
578 self._logger.error("Unexpected Exception removing tempdir %s : %s",
579 tmpdir, str(e))
580 return False
581 else:
582 self._logger.error("Failed to create temp directory.")
583 return False
584 return result
585
Todd Broch352b4b22013-03-22 09:48:40 -0700586 def set_get_all(self, cmds):
587 """Set &| get one or more control values.
588
589 Args:
590 cmds: list of control[:value] to get or set.
591
592 Returns:
593 rv: list of responses from calling get or set methods.
594 """
595 rv = []
596 for cmd in cmds:
597 if ':' in cmd:
598 (control, value) = cmd.split(':')
599 rv.append(self.set(control, value))
600 else:
601 rv.append(self.get(cmd))
602 return rv
603
Todd Broche505b8d2011-03-21 18:19:54 -0700604 def get(self, name):
605 """Get control value.
606
607 Args:
608 name: name string of control
609
610 Returns:
611 Response from calling drv get method. Value is reformatted based on
612 control's dictionary parameters
613
614 Raises:
615 HwDriverError: Error occurred while using drv
616 """
617 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700618 if name == 'serialname':
619 if self._serialname:
620 return self._serialname
621 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700622 (param, drv) = self._get_param_drv(name)
623 try:
624 val = drv.get()
625 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800626 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700627 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700628 except AttributeError, error:
629 self._logger.error("Getting %s: %s" % (name, error))
630 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800631 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700632 self._logger.error("Getting %s" % (name))
633 raise
Todd Brochd6061672012-05-11 15:52:47 -0700634
Todd Broche505b8d2011-03-21 18:19:54 -0700635 def get_all(self, verbose):
636 """Get all controls values.
637
638 Args:
639 verbose: Boolean on whether to return doc info as well
640
641 Returns:
642 string creating from trying to get all values of all controls. In case of
643 error attempting access to control, response is 'ERR'.
644 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800645 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700646 for name in self._syscfg.syscfg_dict['control']:
647 self._logger.debug("name = %s" %name)
648 try:
649 value = self.get(name)
650 except Exception:
651 value = "ERR"
652 pass
653 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800654 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700655 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800656 rsp.append("%s:%s" % (name, value))
657 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700658
659 def set(self, name, wr_val_str):
660 """Set control.
661
662 Args:
663 name: name string of control
664 wr_val_str: value string to write. Can be integer, float or a
665 alpha-numerical that is mapped to a integer or float.
666
667 Raises:
668 HwDriverError: Error occurred while using driver
669 """
670 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
671 (params, drv) = self._get_param_drv(name, False)
672 wr_val = self._syscfg.resolve_val(params, wr_val_str)
673 try:
674 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800675 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700676 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
677 raise
678 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
679 # & client I still have to return something to appease the
680 # marshall/unmarshall
681 return True
682
Todd Brochd6061672012-05-11 15:52:47 -0700683 def hwinit(self, verbose=False):
684 """Initialize all controls.
685
686 These values are part of the system config XML files of the form
687 init=<value>. This command should be used by clients wishing to return the
688 servo and DUT its connected to a known good/safe state.
689
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800690 Note that initialization errors are ignored (as in some cases they could
691 be caused by DUT firmware deficiencies). This might need to be fine tuned
692 later.
693
Todd Brochd6061672012-05-11 15:52:47 -0700694 Args:
695 verbose: boolean, if True prints info about control initialized.
696 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800697
698 Returns:
699 This function is called across RPC and as such is expected to return
700 something unless transferring 'none' across is allowed. Hence adding a
701 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700702 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800703 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800704 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700705 # Workaround for bug chrome-os-partner:42349. Without this check, the
706 # gpio will briefly pulse low if we set it from high to high.
707 if self.get(control_name) != value:
708 self.set(control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800709 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800710 self._logger.error("Problem initializing %s -> %s :: %s",
711 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700712 if verbose:
713 self._logger.info('Initialized %s to %s', control_name, value)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800714 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800715
Todd Broche505b8d2011-03-21 18:19:54 -0700716 def echo(self, echo):
717 """Dummy echo function for testing/examples.
718
719 Args:
720 echo: string to echo back to client
721 """
722 self._logger.debug("echo(%s)" % (echo))
723 return "ECH0ING: %s" % (echo)
724
J. Richard Barnettee2820552013-03-14 16:13:46 -0700725 def get_board(self):
726 """Return the board specified at startup, if any."""
727 return self._board
728
Simran Basia23c1392013-08-06 14:59:10 -0700729 def get_version(self):
730 """Get servo board version."""
731 return self._version
732
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800733 def power_long_press(self):
734 """Simulate a long power button press."""
735 # After a long power press, the EC may ignore the next power
736 # button press (at least on Alex). To guarantee that this
737 # won't happen, we need to allow the EC one second to
738 # collect itself.
739 self._keyboard.power_long_press()
740 return True
741
742 def power_normal_press(self):
743 """Simulate a normal power button press."""
744 self._keyboard.power_normal_press()
745 return True
746
747 def power_short_press(self):
748 """Simulate a short power button press."""
749 self._keyboard.power_short_press()
750 return True
751
752 def power_key(self, secs=''):
753 """Simulate a power button press.
754
755 Args:
756 secs: Time in seconds to simulate the keypress.
757 """
758 self._keyboard.power_key(secs)
759 return True
760
761 def ctrl_d(self, press_secs=''):
762 """Simulate Ctrl-d simultaneous button presses."""
763 self._keyboard.ctrl_d(press_secs)
764 return True
765
766 def ctrl_u(self):
767 """Simulate Ctrl-u simultaneous button presses."""
768 self._keyboard.ctrl_u()
769 return True
770
771 def ctrl_enter(self, press_secs=''):
772 """Simulate Ctrl-enter simultaneous button presses."""
773 self._keyboard.ctrl_enter(press_secs)
774 return True
775
776 def d_key(self, press_secs=''):
777 """Simulate Enter key button press."""
778 self._keyboard.d_key(press_secs)
779 return True
780
781 def ctrl_key(self, press_secs=''):
782 """Simulate Enter key button press."""
783 self._keyboard.ctrl_key(press_secs)
784 return True
785
786 def enter_key(self, press_secs=''):
787 """Simulate Enter key button press."""
788 self._keyboard.enter_key(press_secs)
789 return True
790
791 def refresh_key(self, press_secs=''):
792 """Simulate Refresh key (F3) button press."""
793 self._keyboard.refresh_key(press_secs)
794 return True
795
796 def ctrl_refresh_key(self, press_secs=''):
797 """Simulate Ctrl and Refresh (F3) simultaneous press.
798
799 This key combination is an alternative of Space key.
800 """
801 self._keyboard.ctrl_refresh_key(press_secs)
802 return True
803
804 def imaginary_key(self, press_secs=''):
805 """Simulate imaginary key button press.
806
807 Maps to a key that doesn't physically exist.
808 """
809 self._keyboard.imaginary_key(press_secs)
810 return True
811
Todd Brochdbb09982011-10-02 07:14:26 -0700812
Todd Broche505b8d2011-03-21 18:19:54 -0700813def test():
814 """Integration testing.
815
816 TODO(tbroch) Enhance integration test and add unittest (see mox)
817 """
818 logging.basicConfig(level=logging.DEBUG,
819 format="%(asctime)s - %(name)s - " +
820 "%(levelname)s - %(message)s")
821 # configure server & listen
822 servod_obj = Servod(1)
823 # 4 == number of interfaces on a FT4232H device
824 for i in xrange(4):
825 if i == 1:
826 # its an i2c interface ... see __init__ for details and TODO to make
827 # this configureable
828 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
829 else:
830 # its a gpio interface
831 servod_obj._interface_list[i].wr_rd(0)
832
833 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
834 allow_none=True)
835 server.register_introspection_functions()
836 server.register_multicall_functions()
837 server.register_instance(servod_obj)
838 logging.info("Listening on localhost port 9999")
839 server.serve_forever()
840
841if __name__ == "__main__":
842 test()
843
844 # simple client transaction would look like
845 """
846 remote_uri = 'http://localhost:9999'
847 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
848 send_str = "Hello_there"
849 print "Sent " + send_str + ", Recv " + client.echo(send_str)
850 """