blob: 6719f2815fe0b52157c44243c8f5720be4984f52 [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
Aseda Aboagyea4922212015-11-20 15:19:08 -080022import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070023import ftdigpio
24import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070025import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070026import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080027import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080028import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070029import servo_interfaces
Todd Broche505b8d2011-03-21 18:19:54 -070030
Aseda Aboagyea4922212015-11-20 15:19:08 -080031
Todd Broche505b8d2011-03-21 18:19:54 -070032MAX_I2C_CLOCK_HZ = 100000
33
Todd Brochdbb09982011-10-02 07:14:26 -070034
Todd Broche505b8d2011-03-21 18:19:54 -070035class ServodError(Exception):
36 """Exception class for servod."""
37
38class Servod(object):
39 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070040 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070041 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070042 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070043 _USB_J3 = "usb_mux_sel1"
44 _USB_J3_TO_SERVO = "servo_sees_usbkey"
45 _USB_J3_TO_DUT = "dut_sees_usbkey"
46 _USB_J3_PWR = "prtctl4_pwren"
47 _USB_J3_PWR_ON = "on"
48 _USB_J3_PWR_OFF = "off"
Simran Basia9f41032012-05-11 14:21:58 -070049
J. Richard Barnettee2820552013-03-14 16:13:46 -070050 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080051 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -070052 """Servod constructor.
53
54 Args:
55 config: instance of SystemConfig containing all controls for
56 particular Servod invocation
57 vendor: usb vendor id of FTDI device
58 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070059 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070060 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -070061 version: String. Servo board version. Examples: servo_v1, servo_v2,
62 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080063 usbkm232: String. Optional. Path to USB-KM232 device which allow for
64 sending keyboard commands to DUTs that do not have built in
Danny Chan662b6022015-11-04 17:34:53 -080065 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
66 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -070067
68 Raises:
69 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070070 """
71 self._logger = logging.getLogger("Servod")
72 self._logger.debug("")
73 self._vendor = vendor
74 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070075 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070076 self._syscfg = config
77 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
78 # interfaces are mapped to
79 self._interface_list = []
80 # Dict of Dict to map control name, function name to to tuple (params, drv)
81 # Ex) _drv_dict[name]['get'] = (params, drv)
82 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070083 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -070084 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080085 self._usbkm232 = usbkm232
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']
Aseda Aboagyea4922212015-11-20 15:19:08 -080097 # Store interface index for those that care about it.
98 interface['index'] = i
Simran Basia9ad25e2013-04-23 11:57:00 -070099 elif type(interface) is str:
Simran Basia9ad25e2013-04-23 11:57:00 -0700100 name = interface
Aseda Aboagyea4922212015-11-20 15:19:08 -0800101 # It's a FTDI related interface.
Simran Basia9ad25e2013-04-23 11:57:00 -0700102 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
103 is_ftdi_interface = True
104 else:
105 raise ServodError("Illegal interface type %s" % type(interface))
106
Todd Broch8a77a992012-01-27 09:46:08 -0800107 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -0700108 if is_ftdi_interface and i and \
109 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -0800110 self._product += 1
111 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
112 self._product)
113
Simran Basia9ad25e2013-04-23 11:57:00 -0700114 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -0700115 try:
116 func = getattr(self, '_init_%s' % name)
117 except AttributeError:
118 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -0700119 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -0700120 if isinstance(result, tuple):
121 self._interface_list.extend(result)
122 else:
123 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700124
Danny Chan662b6022015-11-04 17:34:53 -0800125
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800126 def _init_keyboard_handler(self, servo, board=''):
127 """Initialize the correct keyboard handler for board.
128
129 @param servo: servo object.
130 @param board: string, board name.
131
132 """
133 if board == 'parrot':
134 return keyboard_handlers.ParrotHandler(servo)
135 elif board == 'stout':
136 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800137 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800138 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
Jason Simmonse5cccd12015-08-25 16:05:25 -0700139 'sumo', 'tidus', 'tricky', 'veyron_mickey', 'veyron_rialto',
140 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800141 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800142 logging.info("No device path specified for usbkm232 handler. Use "
143 "the servo atmega chip to handle.")
144 self._usbkm232 = 'atmega'
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')
Nick Sandersbc836282015-12-08 21:19:23 -0800148 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800149 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800150 self._usbkm232 = self.get('atmega_pty')
151 self.set('atmega_baudrate', '9600')
152 self.set('atmega_bits', 'eight')
153 self.set('atmega_parity', 'none')
154 self.set('atmega_sbits', 'one')
155 self.set('usb_mux_sel4', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800156 self.set('usb_mux_oe4', 'on')
Nick Sanders78423782015-11-09 14:28:19 -0800157 # Allow atmega bootup time.
158 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800159 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800160 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
161 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800162 # The following boards don't use Chrome EC.
163 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
164 return keyboard_handlers.MatrixKeyboardHandler(servo)
165 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800166
Todd Broch3ec8df02012-11-20 10:53:03 -0800167 def __del__(self):
168 """Servod deconstructor."""
169 for interface in self._interface_list:
170 del(interface)
171
Todd Brochb3048492012-01-15 21:52:41 -0800172 def _init_dummy(self, interface):
173 """Initialize dummy interface.
174
175 Dummy interface is just a mechanism to reserve that interface for non servod
176 interaction. Typically the interface will be managed by external
177 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
178 interfaces.
179
180 TODO(tbroch): Investigate merits of incorporating these third-party
181 interfaces into servod or creating a communication channel between them
182
183 Returns: None
184 """
185 return None
186
Simran Basie750a342013-03-12 13:45:26 -0700187 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700188 """Initialize gpio driver interface and open for use.
189
190 Args:
191 interface: interface number of FTDI device to use.
192
193 Returns:
194 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700195
196 Raises:
197 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700198 """
Todd Brochad034442011-05-25 15:05:29 -0700199 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
200 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700201 try:
202 fobj.open()
203 except ftdigpio.FgpioError as e:
204 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
205
Todd Broche505b8d2011-03-21 18:19:54 -0700206 return fobj
207
Aaron.Chuang88eff332014-07-31 08:32:00 +0800208 def _init_bb_adc(self, interface):
209 """Initalize beaglebone ADC interface."""
210 return bbadc.BBadc()
211
Simran Basie750a342013-03-12 13:45:26 -0700212 def _init_bb_gpio(self, interface):
213 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700214 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700215
216 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700217 """Initialize i2c interface and open for use.
218
219 Args:
220 interface: interface number of FTDI device to use
221
222 Returns:
223 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700224
225 Raises:
226 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700227 """
Todd Brochad034442011-05-25 15:05:29 -0700228 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
229 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700230 try:
231 fobj.open()
232 except ftdii2c.Fi2cError as e:
233 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
234
Todd Broche505b8d2011-03-21 18:19:54 -0700235 # Set the frequency of operation of the i2c bus.
236 # TODO(tbroch) make configureable
237 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700238
Todd Broche505b8d2011-03-21 18:19:54 -0700239 return fobj
240
Simran Basie750a342013-03-12 13:45:26 -0700241 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
242 def _init_bb_i2c(self, interface):
243 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700244 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700245
Rong Changc6c8c022014-08-11 14:07:11 +0800246 def _init_dev_i2c(self, interface):
247 """Initalize Linux i2c-dev interface."""
248 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
249
Simran Basie750a342013-03-12 13:45:26 -0700250 def _init_ftdi_uart(self, interface):
251 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700252
253 Note, the uart runs in a separate thread (pthreads). Users wishing to
254 interact with it will query control for the pty's pathname and connect
255 with there favorite console program. For example:
256 cu -l /dev/pts/22
257
258 Args:
259 interface: interface number of FTDI device to use
260
261 Returns:
262 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700263
264 Raises:
265 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700266 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700267 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
268 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700269 try:
270 fobj.run()
271 except ftdiuart.FuartError as e:
272 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
273
Todd Broch47c43f42011-05-26 15:11:31 -0700274 self._logger.info("%s" % fobj.get_pty())
275 return fobj
276
Simran Basie750a342013-03-12 13:45:26 -0700277 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
278 def _init_bb_uart(self, interface):
279 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700280 logging.debug('UART INTERFACE: %s', interface)
281 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700282
283 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700284 """Initialize special gpio + uart interface and open for use
285
286 Note, the uart runs in a separate thread (pthreads). Users wishing to
287 interact with it will query control for the pty's pathname and connect
288 with there favorite console program. For example:
289 cu -l /dev/pts/22
290
291 Args:
292 interface: interface number of FTDI device to use
293
294 Returns:
295 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700296
297 Raises:
298 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700299 """
Simran Basie750a342013-03-12 13:45:26 -0700300 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700301 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
302 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700303 try:
304 fuart.run()
305 except ftdiuart.FuartError as e:
306 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
307
Todd Broch888da782011-10-07 14:29:09 -0700308 self._logger.info("uart pty: %s" % fuart.get_pty())
309 return fgpio, fuart
310
Aseda Aboagyea4922212015-11-20 15:19:08 -0800311 def _init_ec3po_uart(self, interface):
312 """Initialize EC-3PO console interpreter interface.
313
314 Args:
315 interface: A dictionary representing the interface.
316
317 Returns:
318 An EC3PO object representing the EC-3PO interface or None if there's no
319 interface for the USB PD UART.
320 """
321 vid = self._vendor
322 pid = self._product
323 # The current PID might be incremented if there are multiple FTDI.
324 # Therefore, try rewinding the PID back one if we don't find the base PID in
325 # the SERVO_ID_DEFAULTS
326 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
327 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
328 pid -= 1
329 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
330
331 # Servo V2 / V3 should have the interface indicies in the same spot.
332 if ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
333 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
334 # Determine if it's a PD interface or just main EC console.
335 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
336 try:
337 # Obtain the raw EC UART PTY and create the EC-3PO interface.
338 raw_ec_uart = self.get('raw_usbpd_uart_pty')
339 except NameError:
340 # This overlay doesn't have a USB PD MCU, so skip init.
341 self._logger.info('No PD MCU UART.')
342 return None
343 except AttributeError:
344 # This overlay has no get method for the interface so skip init.
345 self._logger.warn('No interface for PD MCU UART.')
Aseda Aboagyec24a3882016-03-15 12:37:56 -0700346 self._logger.warn('Usually, this happens because the interface is set'
347 ' incorrectly. If you\'re overriding an existing'
348 ' interface, be sure to update the interface lists'
349 ' for your board at the end of '
350 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800351 return None
352
353 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
354 raw_ec_uart = self.get('raw_ec_uart_pty')
355
356 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
357 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
358 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
359 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
360 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
361 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
362 raw_ec_uart = self.get('raw_ec_uart_pty')
363
364 else:
365 raise ServodError(('Unexpected EC-3PO interface!'
366 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
367
368 return ec3po_interface.EC3PO(raw_ec_uart)
369
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800370 def _camel_case(self, string):
371 output = ''
372 for s in string.split('_'):
373 if output:
374 output += s.capitalize()
375 else:
376 output = s
377 return output
378
Todd Broche505b8d2011-03-21 18:19:54 -0700379 def _get_param_drv(self, control_name, is_get=True):
380 """Get access to driver for a given control.
381
382 Note, some controls have different parameter dictionaries for 'getting' the
383 control's value versus 'setting' it. Boolean is_get distinguishes which is
384 being requested.
385
386 Args:
387 control_name: string name of control
388 is_get: boolean to determine
389
390 Returns:
391 tuple (param, drv) where:
392 param: param dictionary for control
393 drv: instance object of driver for particular control
394
395 Raises:
396 ServodError: Error occurred while examining params dict
397 """
398 self._logger.debug("")
399 # if already setup just return tuple from driver dict
400 if control_name in self._drv_dict:
401 if is_get and ('get' in self._drv_dict[control_name]):
402 return self._drv_dict[control_name]['get']
403 if not is_get and ('set' in self._drv_dict[control_name]):
404 return self._drv_dict[control_name]['set']
405
406 params = self._syscfg.lookup_control_params(control_name, is_get)
407 if 'drv' not in params:
408 self._logger.error("Unable to determine driver for %s" % control_name)
409 raise ServodError("'drv' key not found in params dict")
410 if 'interface' not in params:
411 self._logger.error("Unable to determine interface for %s" %
412 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700413 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700414
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800415 interface_id = params.get(
416 '%s_interface' % self._version, params['interface'])
417 if interface_id == 'servo':
418 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700419 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800420 index = int(interface_id) - 1
421 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700422
Todd Broche505b8d2011-03-21 18:19:54 -0700423 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
424 drv_pkg = imp.load_module('drv',
425 *imp.find_module('drv', servo_pkg.__path__))
426 drv_name = params['drv']
427 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800428 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700429 drv = drv_class(interface, params)
430 if control_name not in self._drv_dict:
431 self._drv_dict[control_name] = {}
432 if is_get:
433 self._drv_dict[control_name]['get'] = (params, drv)
434 else:
435 self._drv_dict[control_name]['set'] = (params, drv)
436 return (params, drv)
437
438 def doc_all(self):
439 """Return all documenation for controls.
440
441 Returns:
442 string of <doc> text in config file (xml) and the params dictionary for
443 all controls.
444
445 For example:
446 warm_reset :: Reset the device warmly
447 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
448 """
449 return self._syscfg.display_config()
450
451 def doc(self, name):
452 """Retreive doc string in system config file for given control name.
453
454 Args:
455 name: name string of control to get doc string
456
457 Returns:
458 doc string of name
459
460 Raises:
461 NameError: if fails to locate control
462 """
463 self._logger.debug("name(%s)" % (name))
464 if self._syscfg.is_control(name):
465 return self._syscfg.get_control_docstring(name)
466 else:
467 raise NameError("No control %s" %name)
468
Fang Deng90377712013-06-03 15:51:48 -0700469 def _switch_usbkey(self, mux_direction):
470 """Connect USB flash stick to either servo or DUT.
471
472 This function switches 'usb_mux_sel1' to provide electrical
473 connection between the USB port J3 and either servo or DUT side.
474
475 Switching the usb mux is accompanied by powercycling
476 of the USB stick, because it sometimes gets wedged if the mux
477 is switched while the stick power is on.
478
479 Args:
480 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
481 """
482 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
483 time.sleep(self._USB_POWEROFF_DELAY)
484 self.set(self._USB_J3, mux_direction)
485 time.sleep(self._USB_POWEROFF_DELAY)
486 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
487 if mux_direction == self._USB_J3_TO_SERVO:
488 time.sleep(self._USB_DETECTION_DELAY)
489
Simran Basia9f41032012-05-11 14:21:58 -0700490 def _get_usb_port_set(self):
491 """Gets a set of USB disks currently connected to the system
492
493 Returns:
494 A set of USB disk paths.
495 """
496 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
497 return set(["/dev/" + dev for dev in usb_set])
498
499 def _probe_host_usb_dev(self):
500 """Probe the USB disk device plugged in the servo from the host side.
501
502 Method can fail by:
503 1) Having multiple servos connected and returning incorrect /dev/sdX of
504 another servo.
505 2) Finding multiple /dev/sdX and returning None.
506
507 Returns:
508 USB disk path if one and only one USB disk path is found, otherwise None.
509 """
Fang Deng90377712013-06-03 15:51:48 -0700510 original_value = self.get(self._USB_J3)
511 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700512 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700513 if (original_usb_power == self._USB_J3_PWR_ON and
514 original_value != self._USB_J3_TO_DUT):
515 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700516 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700517
Fang Deng90377712013-06-03 15:51:48 -0700518 # Make the host able to see the USB disk.
519 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700520 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700521
Simran Basia9f41032012-05-11 14:21:58 -0700522 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700523 if original_value != self._USB_J3_TO_SERVO:
524 self._switch_usbkey(original_value)
525 if original_usb_power != self._USB_J3_PWR_ON:
526 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
527 time.sleep(self._USB_POWEROFF_DELAY)
528
Simran Basia9f41032012-05-11 14:21:58 -0700529 # Subtract the two sets to find the usb device.
530 diff_set = has_usb_set - no_usb_set
531 if len(diff_set) == 1:
532 return diff_set.pop()
533 else:
534 return None
535
536 def download_image_to_usb(self, image_path):
537 """Download image and save to the USB device found by probe_host_usb_dev.
538 If the image_path is a URL, it will download this url to the USB path;
539 otherwise it will simply copy the image_path's contents to the USB path.
540
541 Args:
542 image_path: path or url to the recovery image.
543
544 Returns:
545 True|False: True if process completed successfully, False if error
546 occurred.
547 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
548 comment at the end of set().
549 """
550 self._logger.debug("image_path(%s)" % image_path)
551 self._logger.debug("Detecting USB stick device...")
552 usb_dev = self._probe_host_usb_dev()
553 if not usb_dev:
554 self._logger.error("No usb device connected to servo")
555 return False
556
557 try:
558 if image_path.startswith(self._HTTP_PREFIX):
559 self._logger.debug("Image path is a URL, downloading image")
560 urllib.urlretrieve(image_path, usb_dev)
561 else:
562 shutil.copyfile(image_path, usb_dev)
563 except IOError as e:
564 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
565 e.strerror, e.errno)
566 return False
567 except urllib.ContentTooShortError:
568 self._logger.error("Failed to download URL: %s to USB device: %s",
569 image_path, usb_dev)
570 return False
571 except BaseException as e:
572 self._logger.error("Unexpected exception downloading %s to %s: %s",
573 image_path, usb_dev, str(e))
574 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800575 finally:
576 # We just plastered the partition table for a block device.
577 # Pass or fail, we mustn't go without telling the kernel about
578 # the change, or it will punish us with sporadic, hard-to-debug
579 # failures.
580 subprocess.call(["sync"])
581 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700582 return True
583
584 def make_image_noninteractive(self):
585 """Makes the recovery image noninteractive.
586
587 A noninteractive image will reboot automatically after installation
588 instead of waiting for the USB device to be removed to initiate a system
589 reboot.
590
591 Mounts partition 1 of the image stored on usb_dev and creates a file
592 called "non_interactive" so that the image will become noninteractive.
593
594 Returns:
595 True|False: True if process completed successfully, False if error
596 occurred.
597 """
598 result = True
599 usb_dev = self._probe_host_usb_dev()
600 if not usb_dev:
601 self._logger.error("No usb device connected to servo")
602 return False
603 # Create TempDirectory
604 tmpdir = tempfile.mkdtemp()
605 if tmpdir:
606 # Mount drive to tmpdir.
607 partition_1 = "%s1" % usb_dev
608 rc = subprocess.call(["mount", partition_1, tmpdir])
609 if rc == 0:
610 # Create file 'non_interactive'
611 non_interactive_file = os.path.join(tmpdir, "non_interactive")
612 try:
613 open(non_interactive_file, "w").close()
614 except IOError as e:
615 self._logger.error("Failed to create file %s : %s ( %d )",
616 non_interactive_file, e.strerror, e.errno)
617 result = False
618 except BaseException as e:
619 self._logger.error("Unexpected Exception creating file %s : %s",
620 non_interactive_file, str(e))
621 result = False
622 # Unmount drive regardless if file creation worked or not.
623 rc = subprocess.call(["umount", partition_1])
624 if rc != 0:
625 self._logger.error("Failed to unmount USB Device")
626 result = False
627 else:
628 self._logger.error("Failed to mount USB Device")
629 result = False
630
631 # Delete tmpdir. May throw exception if 'umount' failed.
632 try:
633 os.rmdir(tmpdir)
634 except OSError as e:
635 self._logger.error("Failed to remove temp directory %s : %s",
636 tmpdir, str(e))
637 return False
638 except BaseException as e:
639 self._logger.error("Unexpected Exception removing tempdir %s : %s",
640 tmpdir, str(e))
641 return False
642 else:
643 self._logger.error("Failed to create temp directory.")
644 return False
645 return result
646
Todd Broch352b4b22013-03-22 09:48:40 -0700647 def set_get_all(self, cmds):
648 """Set &| get one or more control values.
649
650 Args:
651 cmds: list of control[:value] to get or set.
652
653 Returns:
654 rv: list of responses from calling get or set methods.
655 """
656 rv = []
657 for cmd in cmds:
658 if ':' in cmd:
659 (control, value) = cmd.split(':')
660 rv.append(self.set(control, value))
661 else:
662 rv.append(self.get(cmd))
663 return rv
664
Todd Broche505b8d2011-03-21 18:19:54 -0700665 def get(self, name):
666 """Get control value.
667
668 Args:
669 name: name string of control
670
671 Returns:
672 Response from calling drv get method. Value is reformatted based on
673 control's dictionary parameters
674
675 Raises:
676 HwDriverError: Error occurred while using drv
677 """
678 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700679 if name == 'serialname':
680 if self._serialname:
681 return self._serialname
682 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700683 (param, drv) = self._get_param_drv(name)
684 try:
685 val = drv.get()
686 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800687 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700688 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700689 except AttributeError, error:
690 self._logger.error("Getting %s: %s" % (name, error))
691 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800692 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700693 self._logger.error("Getting %s" % (name))
694 raise
Todd Brochd6061672012-05-11 15:52:47 -0700695
Todd Broche505b8d2011-03-21 18:19:54 -0700696 def get_all(self, verbose):
697 """Get all controls values.
698
699 Args:
700 verbose: Boolean on whether to return doc info as well
701
702 Returns:
703 string creating from trying to get all values of all controls. In case of
704 error attempting access to control, response is 'ERR'.
705 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800706 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700707 for name in self._syscfg.syscfg_dict['control']:
708 self._logger.debug("name = %s" %name)
709 try:
710 value = self.get(name)
711 except Exception:
712 value = "ERR"
713 pass
714 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800715 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700716 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800717 rsp.append("%s:%s" % (name, value))
718 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700719
720 def set(self, name, wr_val_str):
721 """Set control.
722
723 Args:
724 name: name string of control
725 wr_val_str: value string to write. Can be integer, float or a
726 alpha-numerical that is mapped to a integer or float.
727
728 Raises:
729 HwDriverError: Error occurred while using driver
730 """
731 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
732 (params, drv) = self._get_param_drv(name, False)
733 wr_val = self._syscfg.resolve_val(params, wr_val_str)
734 try:
735 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800736 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700737 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
738 raise
739 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
740 # & client I still have to return something to appease the
741 # marshall/unmarshall
742 return True
743
Todd Brochd6061672012-05-11 15:52:47 -0700744 def hwinit(self, verbose=False):
745 """Initialize all controls.
746
747 These values are part of the system config XML files of the form
748 init=<value>. This command should be used by clients wishing to return the
749 servo and DUT its connected to a known good/safe state.
750
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800751 Note that initialization errors are ignored (as in some cases they could
752 be caused by DUT firmware deficiencies). This might need to be fine tuned
753 later.
754
Todd Brochd6061672012-05-11 15:52:47 -0700755 Args:
756 verbose: boolean, if True prints info about control initialized.
757 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800758
759 Returns:
760 This function is called across RPC and as such is expected to return
761 something unless transferring 'none' across is allowed. Hence adding a
762 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700763 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800764 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800765 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700766 # Workaround for bug chrome-os-partner:42349. Without this check, the
767 # gpio will briefly pulse low if we set it from high to high.
768 if self.get(control_name) != value:
769 self.set(control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800770 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800771 self._logger.error("Problem initializing %s -> %s :: %s",
772 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700773 if verbose:
774 self._logger.info('Initialized %s to %s', control_name, value)
Nick Sandersbc836282015-12-08 21:19:23 -0800775
776 # Init keyboard after all the intefaces are up.
777 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800778 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800779
Todd Broche505b8d2011-03-21 18:19:54 -0700780 def echo(self, echo):
781 """Dummy echo function for testing/examples.
782
783 Args:
784 echo: string to echo back to client
785 """
786 self._logger.debug("echo(%s)" % (echo))
787 return "ECH0ING: %s" % (echo)
788
J. Richard Barnettee2820552013-03-14 16:13:46 -0700789 def get_board(self):
790 """Return the board specified at startup, if any."""
791 return self._board
792
Simran Basia23c1392013-08-06 14:59:10 -0700793 def get_version(self):
794 """Get servo board version."""
795 return self._version
796
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800797 def power_long_press(self):
798 """Simulate a long power button press."""
799 # After a long power press, the EC may ignore the next power
800 # button press (at least on Alex). To guarantee that this
801 # won't happen, we need to allow the EC one second to
802 # collect itself.
803 self._keyboard.power_long_press()
804 return True
805
806 def power_normal_press(self):
807 """Simulate a normal power button press."""
808 self._keyboard.power_normal_press()
809 return True
810
811 def power_short_press(self):
812 """Simulate a short power button press."""
813 self._keyboard.power_short_press()
814 return True
815
816 def power_key(self, secs=''):
817 """Simulate a power button press.
818
819 Args:
820 secs: Time in seconds to simulate the keypress.
821 """
822 self._keyboard.power_key(secs)
823 return True
824
825 def ctrl_d(self, press_secs=''):
826 """Simulate Ctrl-d simultaneous button presses."""
827 self._keyboard.ctrl_d(press_secs)
828 return True
829
830 def ctrl_u(self):
831 """Simulate Ctrl-u simultaneous button presses."""
832 self._keyboard.ctrl_u()
833 return True
834
835 def ctrl_enter(self, press_secs=''):
836 """Simulate Ctrl-enter simultaneous button presses."""
837 self._keyboard.ctrl_enter(press_secs)
838 return True
839
840 def d_key(self, press_secs=''):
841 """Simulate Enter key button press."""
842 self._keyboard.d_key(press_secs)
843 return True
844
845 def ctrl_key(self, press_secs=''):
846 """Simulate Enter key button press."""
847 self._keyboard.ctrl_key(press_secs)
848 return True
849
850 def enter_key(self, press_secs=''):
851 """Simulate Enter key button press."""
852 self._keyboard.enter_key(press_secs)
853 return True
854
855 def refresh_key(self, press_secs=''):
856 """Simulate Refresh key (F3) button press."""
857 self._keyboard.refresh_key(press_secs)
858 return True
859
860 def ctrl_refresh_key(self, press_secs=''):
861 """Simulate Ctrl and Refresh (F3) simultaneous press.
862
863 This key combination is an alternative of Space key.
864 """
865 self._keyboard.ctrl_refresh_key(press_secs)
866 return True
867
868 def imaginary_key(self, press_secs=''):
869 """Simulate imaginary key button press.
870
871 Maps to a key that doesn't physically exist.
872 """
873 self._keyboard.imaginary_key(press_secs)
874 return True
875
Todd Brochdbb09982011-10-02 07:14:26 -0700876
Todd Broche505b8d2011-03-21 18:19:54 -0700877def test():
878 """Integration testing.
879
880 TODO(tbroch) Enhance integration test and add unittest (see mox)
881 """
882 logging.basicConfig(level=logging.DEBUG,
883 format="%(asctime)s - %(name)s - " +
884 "%(levelname)s - %(message)s")
885 # configure server & listen
886 servod_obj = Servod(1)
887 # 4 == number of interfaces on a FT4232H device
888 for i in xrange(4):
889 if i == 1:
890 # its an i2c interface ... see __init__ for details and TODO to make
891 # this configureable
892 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
893 else:
894 # its a gpio interface
895 servod_obj._interface_list[i].wr_rd(0)
896
897 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
898 allow_none=True)
899 server.register_introspection_functions()
900 server.register_multicall_functions()
901 server.register_instance(servod_obj)
902 logging.info("Listening on localhost port 9999")
903 server.serve_forever()
904
905if __name__ == "__main__":
906 test()
907
908 # simple client transaction would look like
909 """
910 remote_uri = 'http://localhost:9999'
911 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
912 send_str = "Hello_there"
913 print "Sent " + send_str + ", Recv " + client.echo(send_str)
914 """