blob: 071e1f7a63eae51059627c19304cd9afee7ca516 [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
Kevin Cheng16304d12016-07-08 11:56:55 -070030import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080031import stm32gpio
32import stm32i2c
33import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070034
Aseda Aboagyea4922212015-11-20 15:19:08 -080035
Todd Broche505b8d2011-03-21 18:19:54 -070036MAX_I2C_CLOCK_HZ = 100000
37
Todd Brochdbb09982011-10-02 07:14:26 -070038
Todd Broche505b8d2011-03-21 18:19:54 -070039class ServodError(Exception):
40 """Exception class for servod."""
41
42class Servod(object):
43 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070044 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070045 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070046 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070047 _USB_J3 = "usb_mux_sel1"
48 _USB_J3_TO_SERVO = "servo_sees_usbkey"
49 _USB_J3_TO_DUT = "dut_sees_usbkey"
50 _USB_J3_PWR = "prtctl4_pwren"
51 _USB_J3_PWR_ON = "on"
52 _USB_J3_PWR_OFF = "off"
Simran Basia9f41032012-05-11 14:21:58 -070053
J. Richard Barnettee2820552013-03-14 16:13:46 -070054 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080055 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -070056 """Servod constructor.
57
58 Args:
59 config: instance of SystemConfig containing all controls for
60 particular Servod invocation
61 vendor: usb vendor id of FTDI device
62 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070063 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070064 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -070065 version: String. Servo board version. Examples: servo_v1, servo_v2,
66 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080067 usbkm232: String. Optional. Path to USB-KM232 device which allow for
68 sending keyboard commands to DUTs that do not have built in
Danny Chan662b6022015-11-04 17:34:53 -080069 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
70 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -070071
72 Raises:
73 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070074 """
75 self._logger = logging.getLogger("Servod")
76 self._logger.debug("")
77 self._vendor = vendor
78 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070079 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070080 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -070081 # Hold the last image path so we can reduce downloads to the usb device.
82 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -070083 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
84 # interfaces are mapped to
85 self._interface_list = []
86 # Dict of Dict to map control name, function name to to tuple (params, drv)
87 # Ex) _drv_dict[name]['get'] = (params, drv)
88 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070089 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -070090 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080091 self._usbkm232 = usbkm232
Todd Brochdbb09982011-10-02 07:14:26 -070092 # Note, interface i is (i - 1) in list
93 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -070094 try:
95 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
96 except KeyError:
97 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070098
Simran Basia9ad25e2013-04-23 11:57:00 -070099 for i, interface in enumerate(interfaces):
100 is_ftdi_interface = False
101 if type(interface) is dict:
102 name = interface['name']
Aseda Aboagyea4922212015-11-20 15:19:08 -0800103 # Store interface index for those that care about it.
104 interface['index'] = i
Kevin Cheng5c667212016-07-07 10:58:04 -0700105 elif type(interface) is str and interface != 'dummy':
Simran Basia9ad25e2013-04-23 11:57:00 -0700106 name = interface
Aseda Aboagyea4922212015-11-20 15:19:08 -0800107 # It's a FTDI related interface.
Simran Basia9ad25e2013-04-23 11:57:00 -0700108 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
109 is_ftdi_interface = True
Kevin Cheng5c667212016-07-07 10:58:04 -0700110 elif type(interface) is str and interface == 'dummy':
111 # 'dummy' reserves the interface for future use. Typically the
112 # interface will be managed by external third-party tools like
113 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
114 # it serves as a placeholder for servo micro interfaces.
115 self._interface_list.append(None)
116 continue
Simran Basia9ad25e2013-04-23 11:57:00 -0700117 else:
118 raise ServodError("Illegal interface type %s" % type(interface))
119
Todd Broch8a77a992012-01-27 09:46:08 -0800120 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -0700121 if is_ftdi_interface and i and \
122 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -0800123 self._product += 1
124 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
125 self._product)
126
Simran Basia9ad25e2013-04-23 11:57:00 -0700127 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -0700128 try:
129 func = getattr(self, '_init_%s' % name)
130 except AttributeError:
131 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -0700132 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -0700133 if isinstance(result, tuple):
134 self._interface_list.extend(result)
135 else:
136 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700137
Kevin Cheng16304d12016-07-08 11:56:55 -0700138 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800139
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800140 def _init_keyboard_handler(self, servo, board=''):
141 """Initialize the correct keyboard handler for board.
142
143 @param servo: servo object.
144 @param board: string, board name.
145
146 """
147 if board == 'parrot':
148 return keyboard_handlers.ParrotHandler(servo)
149 elif board == 'stout':
150 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800151 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800152 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
Jason Simmonse5cccd12015-08-25 16:05:25 -0700153 'sumo', 'tidus', 'tricky', 'veyron_mickey', 'veyron_rialto',
ren kuobf62ddd2016-06-24 11:55:43 +0800154 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800155 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800156 logging.info("No device path specified for usbkm232 handler. Use "
157 "the servo atmega chip to handle.")
158 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800159 if self._usbkm232 == 'atmega':
160 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800161 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800162 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800163 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800164 self._usbkm232 = self.get('atmega_pty')
165 self.set('atmega_baudrate', '9600')
166 self.set('atmega_bits', 'eight')
167 self.set('atmega_parity', 'none')
168 self.set('atmega_sbits', 'one')
169 self.set('usb_mux_sel4', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800170 self.set('usb_mux_oe4', 'on')
Nick Sanders78423782015-11-09 14:28:19 -0800171 # Allow atmega bootup time.
172 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800173 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800174 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
175 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800176 # The following boards don't use Chrome EC.
177 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
178 return keyboard_handlers.MatrixKeyboardHandler(servo)
179 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800180
Todd Broch3ec8df02012-11-20 10:53:03 -0800181 def __del__(self):
182 """Servod deconstructor."""
183 for interface in self._interface_list:
184 del(interface)
185
Kevin Cheng042f4932016-07-19 10:46:00 -0700186 def _init_ftdi_dummy(self, interface):
187 """Dummy interface for ftdi devices.
188
189 This is a dummy function specifically for ftdi devices to not initialize
190 anything but to help pad the interface list.
191
192 Returns:
193 None.
194 """
195 return None
196
Simran Basie750a342013-03-12 13:45:26 -0700197 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700198 """Initialize gpio driver interface and open for use.
199
200 Args:
201 interface: interface number of FTDI device to use.
202
203 Returns:
204 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700205
206 Raises:
207 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700208 """
Todd Brochad034442011-05-25 15:05:29 -0700209 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
210 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700211 try:
212 fobj.open()
213 except ftdigpio.FgpioError as e:
214 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
215
Todd Broche505b8d2011-03-21 18:19:54 -0700216 return fobj
217
Nick Sanders97bc4462016-01-04 15:37:31 -0800218 def _init_stm32_uart(self, interface):
219 """Initialize stm32 uart interface and open for use
220
221 Note, the uart runs in a separate thread. Users wishing to
222 interact with it will query control for the pty's pathname and connect
223 with their favorite console program. For example:
224 cu -l /dev/pts/22
225
226 Args:
227 interface: dict of interface parameters.
228
229 Returns:
230 Instance object of interface
231
232 Raises:
233 ServodError: Raised on init failure.
234 """
235 self._logger.info("Suart: interface: %s" % interface)
Kevin Cheng71a046f2016-06-13 16:37:58 -0700236 sobj = stm32uart.Suart(self._vendor, self._product, interface['interface'],
237 self._serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800238
239 try:
240 sobj.run()
241 except stm32uart.SuartError as e:
242 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
243
244 self._logger.info("%s" % sobj.get_pty())
245 return sobj
246
247 def _init_stm32_gpio(self, interface):
248 """Initialize stm32 gpio interface.
249 Args:
250 interface: interface number of stm32 device to use.
251
252 Returns:
253 Instance object of interface
254
255 Raises:
256 SgpioError: Raised on init failure.
257 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700258 interface_number = interface
259 # Interface could be a dict.
260 if type(interface) is dict:
261 interface_number = interface['interface']
262 self._logger.info("Sgpio: interface: %s" % interface_number)
263 return stm32gpio.Sgpio(self._vendor, self._product, interface_number,
264 self._serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800265
266 def _init_stm32_i2c(self, interface):
267 """Initialize stm32 USB to I2C bridge interface and open for use
268
269 Args:
270 interface: USB interface number of stm32 device to use
271
272 Returns:
273 Instance object of interface.
274
275 Raises:
276 Si2cError: Raised on init failure.
277 """
278 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800279 port = interface.get('port', 0)
280 return stm32i2c.Si2cBus(self._vendor, self._product,
Kevin Cheng71a046f2016-06-13 16:37:58 -0700281 interface['interface'], port=port, serialname=self._serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800282
Aaron.Chuang88eff332014-07-31 08:32:00 +0800283 def _init_bb_adc(self, interface):
284 """Initalize beaglebone ADC interface."""
285 return bbadc.BBadc()
286
Simran Basie750a342013-03-12 13:45:26 -0700287 def _init_bb_gpio(self, interface):
288 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700289 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700290
291 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700292 """Initialize i2c interface and open for use.
293
294 Args:
295 interface: interface number of FTDI device to use
296
297 Returns:
298 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700299
300 Raises:
301 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700302 """
Todd Brochad034442011-05-25 15:05:29 -0700303 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
304 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700305 try:
306 fobj.open()
307 except ftdii2c.Fi2cError as e:
308 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
309
Todd Broche505b8d2011-03-21 18:19:54 -0700310 # Set the frequency of operation of the i2c bus.
311 # TODO(tbroch) make configureable
312 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700313
Todd Broche505b8d2011-03-21 18:19:54 -0700314 return fobj
315
Simran Basie750a342013-03-12 13:45:26 -0700316 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
317 def _init_bb_i2c(self, interface):
318 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700319 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700320
Rong Changc6c8c022014-08-11 14:07:11 +0800321 def _init_dev_i2c(self, interface):
322 """Initalize Linux i2c-dev interface."""
323 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
324
Simran Basie750a342013-03-12 13:45:26 -0700325 def _init_ftdi_uart(self, interface):
326 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700327
328 Note, the uart runs in a separate thread (pthreads). Users wishing to
329 interact with it will query control for the pty's pathname and connect
330 with there favorite console program. For example:
331 cu -l /dev/pts/22
332
333 Args:
334 interface: interface number of FTDI device to use
335
336 Returns:
337 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700338
339 Raises:
340 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700341 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700342 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
343 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700344 try:
345 fobj.run()
346 except ftdiuart.FuartError as e:
347 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
348
Todd Broch47c43f42011-05-26 15:11:31 -0700349 self._logger.info("%s" % fobj.get_pty())
350 return fobj
351
Simran Basie750a342013-03-12 13:45:26 -0700352 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
353 def _init_bb_uart(self, interface):
354 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700355 logging.debug('UART INTERFACE: %s', interface)
356 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700357
358 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700359 """Initialize special gpio + uart interface and open for use
360
361 Note, the uart runs in a separate thread (pthreads). Users wishing to
362 interact with it will query control for the pty's pathname and connect
363 with there favorite console program. For example:
364 cu -l /dev/pts/22
365
366 Args:
367 interface: interface number of FTDI device to use
368
369 Returns:
370 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700371
372 Raises:
373 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700374 """
Simran Basie750a342013-03-12 13:45:26 -0700375 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700376 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
377 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700378 try:
379 fuart.run()
380 except ftdiuart.FuartError as e:
381 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
382
Todd Broch888da782011-10-07 14:29:09 -0700383 self._logger.info("uart pty: %s" % fuart.get_pty())
384 return fgpio, fuart
385
Aseda Aboagyea4922212015-11-20 15:19:08 -0800386 def _init_ec3po_uart(self, interface):
387 """Initialize EC-3PO console interpreter interface.
388
389 Args:
390 interface: A dictionary representing the interface.
391
392 Returns:
393 An EC3PO object representing the EC-3PO interface or None if there's no
394 interface for the USB PD UART.
395 """
396 vid = self._vendor
397 pid = self._product
398 # The current PID might be incremented if there are multiple FTDI.
399 # Therefore, try rewinding the PID back one if we don't find the base PID in
400 # the SERVO_ID_DEFAULTS
401 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
402 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
403 pid -= 1
404 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
405
Nick Sanders97bc4462016-01-04 15:37:31 -0800406 if 'raw_pty' in interface:
407 # We have specified an explicit target for this ec3po.
408 raw_uart_name = interface['raw_pty']
409 raw_ec_uart = self.get(raw_uart_name)
410
Aseda Aboagyea4922212015-11-20 15:19:08 -0800411 # Servo V2 / V3 should have the interface indicies in the same spot.
Nick Sanders97bc4462016-01-04 15:37:31 -0800412 elif ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
Aseda Aboagyea4922212015-11-20 15:19:08 -0800413 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
414 # Determine if it's a PD interface or just main EC console.
415 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
416 try:
417 # Obtain the raw EC UART PTY and create the EC-3PO interface.
418 raw_ec_uart = self.get('raw_usbpd_uart_pty')
419 except NameError:
420 # This overlay doesn't have a USB PD MCU, so skip init.
421 self._logger.info('No PD MCU UART.')
422 return None
423 except AttributeError:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700424 # This overlay has no get method for the interface so skip init. For
425 # servo v2, it's common for interfaces to be overridden such as
426 # reusing JTAG pins for the PD MCU UART instead. Therefore, print an
427 # error message indicating that the interface might be set
428 # incorrectly.
429 if (vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS:
430 self._logger.warn('No interface for PD MCU UART.')
431 self._logger.warn('Usually, this happens because the interface is '
432 'set incorrectly. If you\'re overriding an '
433 'existing interface, be sure to update the '
434 'interface lists for your board at the end of '
435 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800436 return None
437
438 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
439 raw_ec_uart = self.get('raw_ec_uart_pty')
440
441 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
442 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
443 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
444 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
445 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
446 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
447 raw_ec_uart = self.get('raw_ec_uart_pty')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800448 else:
449 raise ServodError(('Unexpected EC-3PO interface!'
450 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
451
452 return ec3po_interface.EC3PO(raw_ec_uart)
453
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800454 def _camel_case(self, string):
455 output = ''
456 for s in string.split('_'):
457 if output:
458 output += s.capitalize()
459 else:
460 output = s
461 return output
462
Todd Broche505b8d2011-03-21 18:19:54 -0700463 def _get_param_drv(self, control_name, is_get=True):
464 """Get access to driver for a given control.
465
466 Note, some controls have different parameter dictionaries for 'getting' the
467 control's value versus 'setting' it. Boolean is_get distinguishes which is
468 being requested.
469
470 Args:
471 control_name: string name of control
472 is_get: boolean to determine
473
474 Returns:
475 tuple (param, drv) where:
476 param: param dictionary for control
477 drv: instance object of driver for particular control
478
479 Raises:
480 ServodError: Error occurred while examining params dict
481 """
482 self._logger.debug("")
483 # if already setup just return tuple from driver dict
484 if control_name in self._drv_dict:
485 if is_get and ('get' in self._drv_dict[control_name]):
486 return self._drv_dict[control_name]['get']
487 if not is_get and ('set' in self._drv_dict[control_name]):
488 return self._drv_dict[control_name]['set']
489
490 params = self._syscfg.lookup_control_params(control_name, is_get)
491 if 'drv' not in params:
492 self._logger.error("Unable to determine driver for %s" % control_name)
493 raise ServodError("'drv' key not found in params dict")
494 if 'interface' not in params:
495 self._logger.error("Unable to determine interface for %s" %
496 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700497 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700498
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800499 interface_id = params.get(
500 '%s_interface' % self._version, params['interface'])
501 if interface_id == 'servo':
502 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700503 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800504 index = int(interface_id) - 1
505 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700506
Todd Broche505b8d2011-03-21 18:19:54 -0700507 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
508 drv_pkg = imp.load_module('drv',
509 *imp.find_module('drv', servo_pkg.__path__))
510 drv_name = params['drv']
511 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800512 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700513 drv = drv_class(interface, params)
514 if control_name not in self._drv_dict:
515 self._drv_dict[control_name] = {}
516 if is_get:
517 self._drv_dict[control_name]['get'] = (params, drv)
518 else:
519 self._drv_dict[control_name]['set'] = (params, drv)
520 return (params, drv)
521
522 def doc_all(self):
523 """Return all documenation for controls.
524
525 Returns:
526 string of <doc> text in config file (xml) and the params dictionary for
527 all controls.
528
529 For example:
530 warm_reset :: Reset the device warmly
531 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
532 """
533 return self._syscfg.display_config()
534
535 def doc(self, name):
536 """Retreive doc string in system config file for given control name.
537
538 Args:
539 name: name string of control to get doc string
540
541 Returns:
542 doc string of name
543
544 Raises:
545 NameError: if fails to locate control
546 """
547 self._logger.debug("name(%s)" % (name))
548 if self._syscfg.is_control(name):
549 return self._syscfg.get_control_docstring(name)
550 else:
551 raise NameError("No control %s" %name)
552
Fang Deng90377712013-06-03 15:51:48 -0700553 def _switch_usbkey(self, mux_direction):
554 """Connect USB flash stick to either servo or DUT.
555
556 This function switches 'usb_mux_sel1' to provide electrical
557 connection between the USB port J3 and either servo or DUT side.
558
559 Switching the usb mux is accompanied by powercycling
560 of the USB stick, because it sometimes gets wedged if the mux
561 is switched while the stick power is on.
562
563 Args:
564 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
565 """
566 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
567 time.sleep(self._USB_POWEROFF_DELAY)
568 self.set(self._USB_J3, mux_direction)
569 time.sleep(self._USB_POWEROFF_DELAY)
570 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
571 if mux_direction == self._USB_J3_TO_SERVO:
572 time.sleep(self._USB_DETECTION_DELAY)
573
Simran Basia9f41032012-05-11 14:21:58 -0700574 def _get_usb_port_set(self):
575 """Gets a set of USB disks currently connected to the system
576
577 Returns:
578 A set of USB disk paths.
579 """
580 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
581 return set(["/dev/" + dev for dev in usb_set])
582
583 def _probe_host_usb_dev(self):
584 """Probe the USB disk device plugged in the servo from the host side.
585
586 Method can fail by:
587 1) Having multiple servos connected and returning incorrect /dev/sdX of
588 another servo.
589 2) Finding multiple /dev/sdX and returning None.
590
591 Returns:
592 USB disk path if one and only one USB disk path is found, otherwise None.
593 """
Fang Deng90377712013-06-03 15:51:48 -0700594 original_value = self.get(self._USB_J3)
595 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700596 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700597 if (original_usb_power == self._USB_J3_PWR_ON and
598 original_value != self._USB_J3_TO_DUT):
599 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700600 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700601
Fang Deng90377712013-06-03 15:51:48 -0700602 # Make the host able to see the USB disk.
603 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700604 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700605
Simran Basia9f41032012-05-11 14:21:58 -0700606 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700607 if original_value != self._USB_J3_TO_SERVO:
608 self._switch_usbkey(original_value)
609 if original_usb_power != self._USB_J3_PWR_ON:
610 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
611 time.sleep(self._USB_POWEROFF_DELAY)
612
Simran Basia9f41032012-05-11 14:21:58 -0700613 # Subtract the two sets to find the usb device.
614 diff_set = has_usb_set - no_usb_set
615 if len(diff_set) == 1:
616 return diff_set.pop()
617 else:
618 return None
619
620 def download_image_to_usb(self, image_path):
621 """Download image and save to the USB device found by probe_host_usb_dev.
622 If the image_path is a URL, it will download this url to the USB path;
623 otherwise it will simply copy the image_path's contents to the USB path.
624
625 Args:
626 image_path: path or url to the recovery image.
627
628 Returns:
629 True|False: True if process completed successfully, False if error
630 occurred.
631 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
632 comment at the end of set().
633 """
634 self._logger.debug("image_path(%s)" % image_path)
635 self._logger.debug("Detecting USB stick device...")
636 usb_dev = self._probe_host_usb_dev()
637 if not usb_dev:
638 self._logger.error("No usb device connected to servo")
639 return False
640
Kevin Cheng9071ed92016-06-21 14:37:54 -0700641 # Let's check if we downloaded this last time and if so assume the image is
642 # still on the usb device and return True.
643 if self._image_path == image_path:
644 self._logger.debug("Image already on USB device, skipping transfer")
645 return True
646
Simran Basia9f41032012-05-11 14:21:58 -0700647 try:
648 if image_path.startswith(self._HTTP_PREFIX):
649 self._logger.debug("Image path is a URL, downloading image")
650 urllib.urlretrieve(image_path, usb_dev)
651 else:
652 shutil.copyfile(image_path, usb_dev)
653 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700654 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700655 e.strerror, e.errno)
656 return False
657 except urllib.ContentTooShortError:
658 self._logger.error("Failed to download URL: %s to USB device: %s",
659 image_path, usb_dev)
660 return False
661 except BaseException as e:
662 self._logger.error("Unexpected exception downloading %s to %s: %s",
663 image_path, usb_dev, str(e))
664 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800665 finally:
666 # We just plastered the partition table for a block device.
667 # Pass or fail, we mustn't go without telling the kernel about
668 # the change, or it will punish us with sporadic, hard-to-debug
669 # failures.
670 subprocess.call(["sync"])
671 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700672 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700673 return True
674
675 def make_image_noninteractive(self):
676 """Makes the recovery image noninteractive.
677
678 A noninteractive image will reboot automatically after installation
679 instead of waiting for the USB device to be removed to initiate a system
680 reboot.
681
682 Mounts partition 1 of the image stored on usb_dev and creates a file
683 called "non_interactive" so that the image will become noninteractive.
684
685 Returns:
686 True|False: True if process completed successfully, False if error
687 occurred.
688 """
689 result = True
690 usb_dev = self._probe_host_usb_dev()
691 if not usb_dev:
692 self._logger.error("No usb device connected to servo")
693 return False
694 # Create TempDirectory
695 tmpdir = tempfile.mkdtemp()
696 if tmpdir:
697 # Mount drive to tmpdir.
698 partition_1 = "%s1" % usb_dev
699 rc = subprocess.call(["mount", partition_1, tmpdir])
700 if rc == 0:
701 # Create file 'non_interactive'
702 non_interactive_file = os.path.join(tmpdir, "non_interactive")
703 try:
704 open(non_interactive_file, "w").close()
705 except IOError as e:
706 self._logger.error("Failed to create file %s : %s ( %d )",
707 non_interactive_file, e.strerror, e.errno)
708 result = False
709 except BaseException as e:
710 self._logger.error("Unexpected Exception creating file %s : %s",
711 non_interactive_file, str(e))
712 result = False
713 # Unmount drive regardless if file creation worked or not.
714 rc = subprocess.call(["umount", partition_1])
715 if rc != 0:
716 self._logger.error("Failed to unmount USB Device")
717 result = False
718 else:
719 self._logger.error("Failed to mount USB Device")
720 result = False
721
722 # Delete tmpdir. May throw exception if 'umount' failed.
723 try:
724 os.rmdir(tmpdir)
725 except OSError as e:
726 self._logger.error("Failed to remove temp directory %s : %s",
727 tmpdir, str(e))
728 return False
729 except BaseException as e:
730 self._logger.error("Unexpected Exception removing tempdir %s : %s",
731 tmpdir, str(e))
732 return False
733 else:
734 self._logger.error("Failed to create temp directory.")
735 return False
736 return result
737
Todd Broch352b4b22013-03-22 09:48:40 -0700738 def set_get_all(self, cmds):
739 """Set &| get one or more control values.
740
741 Args:
742 cmds: list of control[:value] to get or set.
743
744 Returns:
745 rv: list of responses from calling get or set methods.
746 """
747 rv = []
748 for cmd in cmds:
749 if ':' in cmd:
750 (control, value) = cmd.split(':')
751 rv.append(self.set(control, value))
752 else:
753 rv.append(self.get(cmd))
754 return rv
755
Todd Broche505b8d2011-03-21 18:19:54 -0700756 def get(self, name):
757 """Get control value.
758
759 Args:
760 name: name string of control
761
762 Returns:
763 Response from calling drv get method. Value is reformatted based on
764 control's dictionary parameters
765
766 Raises:
767 HwDriverError: Error occurred while using drv
768 """
769 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700770 if name == 'serialname':
771 if self._serialname:
772 return self._serialname
773 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700774 (param, drv) = self._get_param_drv(name)
775 try:
776 val = drv.get()
777 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800778 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700779 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700780 except AttributeError, error:
781 self._logger.error("Getting %s: %s" % (name, error))
782 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800783 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700784 self._logger.error("Getting %s" % (name))
785 raise
Todd Brochd6061672012-05-11 15:52:47 -0700786
Todd Broche505b8d2011-03-21 18:19:54 -0700787 def get_all(self, verbose):
788 """Get all controls values.
789
790 Args:
791 verbose: Boolean on whether to return doc info as well
792
793 Returns:
794 string creating from trying to get all values of all controls. In case of
795 error attempting access to control, response is 'ERR'.
796 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800797 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700798 for name in self._syscfg.syscfg_dict['control']:
799 self._logger.debug("name = %s" %name)
800 try:
801 value = self.get(name)
802 except Exception:
803 value = "ERR"
804 pass
805 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800806 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700807 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800808 rsp.append("%s:%s" % (name, value))
809 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700810
811 def set(self, name, wr_val_str):
812 """Set control.
813
814 Args:
815 name: name string of control
816 wr_val_str: value string to write. Can be integer, float or a
817 alpha-numerical that is mapped to a integer or float.
818
819 Raises:
820 HwDriverError: Error occurred while using driver
821 """
822 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
823 (params, drv) = self._get_param_drv(name, False)
824 wr_val = self._syscfg.resolve_val(params, wr_val_str)
825 try:
826 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800827 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700828 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
829 raise
830 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
831 # & client I still have to return something to appease the
832 # marshall/unmarshall
833 return True
834
Todd Brochd6061672012-05-11 15:52:47 -0700835 def hwinit(self, verbose=False):
836 """Initialize all controls.
837
838 These values are part of the system config XML files of the form
839 init=<value>. This command should be used by clients wishing to return the
840 servo and DUT its connected to a known good/safe state.
841
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800842 Note that initialization errors are ignored (as in some cases they could
843 be caused by DUT firmware deficiencies). This might need to be fine tuned
844 later.
845
Todd Brochd6061672012-05-11 15:52:47 -0700846 Args:
847 verbose: boolean, if True prints info about control initialized.
848 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800849
850 Returns:
851 This function is called across RPC and as such is expected to return
852 something unless transferring 'none' across is allowed. Hence adding a
853 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700854 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800855 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800856 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700857 # Workaround for bug chrome-os-partner:42349. Without this check, the
858 # gpio will briefly pulse low if we set it from high to high.
859 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700860 self.set(control_name, value)
861 if verbose:
862 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800863 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800864 self._logger.error("Problem initializing %s -> %s :: %s",
865 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -0800866
867 # Init keyboard after all the intefaces are up.
868 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800869 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800870
Todd Broche505b8d2011-03-21 18:19:54 -0700871 def echo(self, echo):
872 """Dummy echo function for testing/examples.
873
874 Args:
875 echo: string to echo back to client
876 """
877 self._logger.debug("echo(%s)" % (echo))
878 return "ECH0ING: %s" % (echo)
879
J. Richard Barnettee2820552013-03-14 16:13:46 -0700880 def get_board(self):
881 """Return the board specified at startup, if any."""
882 return self._board
883
Simran Basia23c1392013-08-06 14:59:10 -0700884 def get_version(self):
885 """Get servo board version."""
886 return self._version
887
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800888 def power_long_press(self):
889 """Simulate a long power button press."""
890 # After a long power press, the EC may ignore the next power
891 # button press (at least on Alex). To guarantee that this
892 # won't happen, we need to allow the EC one second to
893 # collect itself.
894 self._keyboard.power_long_press()
895 return True
896
897 def power_normal_press(self):
898 """Simulate a normal power button press."""
899 self._keyboard.power_normal_press()
900 return True
901
902 def power_short_press(self):
903 """Simulate a short power button press."""
904 self._keyboard.power_short_press()
905 return True
906
907 def power_key(self, secs=''):
908 """Simulate a power button press.
909
910 Args:
911 secs: Time in seconds to simulate the keypress.
912 """
913 self._keyboard.power_key(secs)
914 return True
915
916 def ctrl_d(self, press_secs=''):
917 """Simulate Ctrl-d simultaneous button presses."""
918 self._keyboard.ctrl_d(press_secs)
919 return True
920
Victor Dodone539cea2016-03-29 18:50:17 -0700921 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800922 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -0700923 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800924 return True
925
926 def ctrl_enter(self, press_secs=''):
927 """Simulate Ctrl-enter simultaneous button presses."""
928 self._keyboard.ctrl_enter(press_secs)
929 return True
930
931 def d_key(self, press_secs=''):
932 """Simulate Enter key button press."""
933 self._keyboard.d_key(press_secs)
934 return True
935
936 def ctrl_key(self, press_secs=''):
937 """Simulate Enter key button press."""
938 self._keyboard.ctrl_key(press_secs)
939 return True
940
941 def enter_key(self, press_secs=''):
942 """Simulate Enter key button press."""
943 self._keyboard.enter_key(press_secs)
944 return True
945
946 def refresh_key(self, press_secs=''):
947 """Simulate Refresh key (F3) button press."""
948 self._keyboard.refresh_key(press_secs)
949 return True
950
951 def ctrl_refresh_key(self, press_secs=''):
952 """Simulate Ctrl and Refresh (F3) simultaneous press.
953
954 This key combination is an alternative of Space key.
955 """
956 self._keyboard.ctrl_refresh_key(press_secs)
957 return True
958
959 def imaginary_key(self, press_secs=''):
960 """Simulate imaginary key button press.
961
962 Maps to a key that doesn't physically exist.
963 """
964 self._keyboard.imaginary_key(press_secs)
965 return True
966
Todd Brochdbb09982011-10-02 07:14:26 -0700967
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200968 def sysrq_x(self, press_secs=''):
969 """Simulate Alt VolumeUp X simultaneous press.
970
971 This key combination is the kernel system request (sysrq) x.
972 """
973 self._keyboard.sysrq_x(press_secs)
974 return True
975
976
Todd Broche505b8d2011-03-21 18:19:54 -0700977def test():
978 """Integration testing.
979
980 TODO(tbroch) Enhance integration test and add unittest (see mox)
981 """
982 logging.basicConfig(level=logging.DEBUG,
983 format="%(asctime)s - %(name)s - " +
984 "%(levelname)s - %(message)s")
985 # configure server & listen
986 servod_obj = Servod(1)
987 # 4 == number of interfaces on a FT4232H device
988 for i in xrange(4):
989 if i == 1:
990 # its an i2c interface ... see __init__ for details and TODO to make
991 # this configureable
992 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
993 else:
994 # its a gpio interface
995 servod_obj._interface_list[i].wr_rd(0)
996
997 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
998 allow_none=True)
999 server.register_introspection_functions()
1000 server.register_multicall_functions()
1001 server.register_instance(servod_obj)
1002 logging.info("Listening on localhost port 9999")
1003 server.serve_forever()
1004
1005if __name__ == "__main__":
1006 test()
1007
1008 # simple client transaction would look like
1009 """
1010 remote_uri = 'http://localhost:9999'
1011 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1012 send_str = "Hello_there"
1013 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1014 """