blob: ff8f23435d09909ccc76efb696d29fb539bb2f28 [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
Nick Sanders97bc4462016-01-04 15:37:31 -080030import stm32gpio
31import stm32i2c
32import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070033
Aseda Aboagyea4922212015-11-20 15:19:08 -080034
Todd Broche505b8d2011-03-21 18:19:54 -070035MAX_I2C_CLOCK_HZ = 100000
36
Todd Brochdbb09982011-10-02 07:14:26 -070037
Todd Broche505b8d2011-03-21 18:19:54 -070038class ServodError(Exception):
39 """Exception class for servod."""
40
41class Servod(object):
42 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070043 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070044 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070045 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070046 _USB_J3 = "usb_mux_sel1"
47 _USB_J3_TO_SERVO = "servo_sees_usbkey"
48 _USB_J3_TO_DUT = "dut_sees_usbkey"
49 _USB_J3_PWR = "prtctl4_pwren"
50 _USB_J3_PWR_ON = "on"
51 _USB_J3_PWR_OFF = "off"
Simran Basia9f41032012-05-11 14:21:58 -070052
J. Richard Barnettee2820552013-03-14 16:13:46 -070053 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080054 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -070055 """Servod constructor.
56
57 Args:
58 config: instance of SystemConfig containing all controls for
59 particular Servod invocation
60 vendor: usb vendor id of FTDI device
61 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070062 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070063 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -070064 version: String. Servo board version. Examples: servo_v1, servo_v2,
65 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080066 usbkm232: String. Optional. Path to USB-KM232 device which allow for
67 sending keyboard commands to DUTs that do not have built in
Danny Chan662b6022015-11-04 17:34:53 -080068 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
69 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -070070
71 Raises:
72 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070073 """
74 self._logger = logging.getLogger("Servod")
75 self._logger.debug("")
76 self._vendor = vendor
77 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070078 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070079 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -070080 # Hold the last image path so we can reduce downloads to the usb device.
81 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -070082 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
83 # interfaces are mapped to
84 self._interface_list = []
85 # Dict of Dict to map control name, function name to to tuple (params, drv)
86 # Ex) _drv_dict[name]['get'] = (params, drv)
87 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070088 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -070089 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080090 self._usbkm232 = usbkm232
Todd Brochdbb09982011-10-02 07:14:26 -070091 # Note, interface i is (i - 1) in list
92 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -070093 try:
94 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
95 except KeyError:
96 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070097
Simran Basia9ad25e2013-04-23 11:57:00 -070098 for i, interface in enumerate(interfaces):
99 is_ftdi_interface = False
100 if type(interface) is dict:
101 name = interface['name']
Aseda Aboagyea4922212015-11-20 15:19:08 -0800102 # Store interface index for those that care about it.
103 interface['index'] = i
Kevin Cheng5c667212016-07-07 10:58:04 -0700104 elif type(interface) is str and interface != 'dummy':
Simran Basia9ad25e2013-04-23 11:57:00 -0700105 name = interface
Aseda Aboagyea4922212015-11-20 15:19:08 -0800106 # It's a FTDI related interface.
Simran Basia9ad25e2013-04-23 11:57:00 -0700107 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
108 is_ftdi_interface = True
Kevin Cheng5c667212016-07-07 10:58:04 -0700109 elif type(interface) is str and interface == 'dummy':
110 # 'dummy' reserves the interface for future use. Typically the
111 # interface will be managed by external third-party tools like
112 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
113 # it serves as a placeholder for servo micro interfaces.
114 self._interface_list.append(None)
115 continue
Simran Basia9ad25e2013-04-23 11:57:00 -0700116 else:
117 raise ServodError("Illegal interface type %s" % type(interface))
118
Todd Broch8a77a992012-01-27 09:46:08 -0800119 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -0700120 if is_ftdi_interface and i and \
121 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -0800122 self._product += 1
123 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
124 self._product)
125
Simran Basia9ad25e2013-04-23 11:57:00 -0700126 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -0700127 try:
128 func = getattr(self, '_init_%s' % name)
129 except AttributeError:
130 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -0700131 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -0700132 if isinstance(result, tuple):
133 self._interface_list.extend(result)
134 else:
135 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700136
Danny Chan662b6022015-11-04 17:34:53 -0800137
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800138 def _init_keyboard_handler(self, servo, board=''):
139 """Initialize the correct keyboard handler for board.
140
141 @param servo: servo object.
142 @param board: string, board name.
143
144 """
145 if board == 'parrot':
146 return keyboard_handlers.ParrotHandler(servo)
147 elif board == 'stout':
148 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800149 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800150 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
Jason Simmonse5cccd12015-08-25 16:05:25 -0700151 'sumo', 'tidus', 'tricky', 'veyron_mickey', 'veyron_rialto',
ren kuobf62ddd2016-06-24 11:55:43 +0800152 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800153 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800154 logging.info("No device path specified for usbkm232 handler. Use "
155 "the servo atmega chip to handle.")
156 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800157 if self._usbkm232 == 'atmega':
158 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800159 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800160 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800161 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800162 self._usbkm232 = self.get('atmega_pty')
163 self.set('atmega_baudrate', '9600')
164 self.set('atmega_bits', 'eight')
165 self.set('atmega_parity', 'none')
166 self.set('atmega_sbits', 'one')
167 self.set('usb_mux_sel4', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800168 self.set('usb_mux_oe4', 'on')
Nick Sanders78423782015-11-09 14:28:19 -0800169 # Allow atmega bootup time.
170 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800171 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800172 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
173 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800174 # The following boards don't use Chrome EC.
175 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
176 return keyboard_handlers.MatrixKeyboardHandler(servo)
177 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800178
Todd Broch3ec8df02012-11-20 10:53:03 -0800179 def __del__(self):
180 """Servod deconstructor."""
181 for interface in self._interface_list:
182 del(interface)
183
Kevin Cheng042f4932016-07-19 10:46:00 -0700184 def _init_ftdi_dummy(self, interface):
185 """Dummy interface for ftdi devices.
186
187 This is a dummy function specifically for ftdi devices to not initialize
188 anything but to help pad the interface list.
189
190 Returns:
191 None.
192 """
193 return None
194
Simran Basie750a342013-03-12 13:45:26 -0700195 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700196 """Initialize gpio driver interface and open for use.
197
198 Args:
199 interface: interface number of FTDI device to use.
200
201 Returns:
202 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700203
204 Raises:
205 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700206 """
Todd Brochad034442011-05-25 15:05:29 -0700207 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
208 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700209 try:
210 fobj.open()
211 except ftdigpio.FgpioError as e:
212 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
213
Todd Broche505b8d2011-03-21 18:19:54 -0700214 return fobj
215
Nick Sanders97bc4462016-01-04 15:37:31 -0800216 def _init_stm32_uart(self, interface):
217 """Initialize stm32 uart interface and open for use
218
219 Note, the uart runs in a separate thread. Users wishing to
220 interact with it will query control for the pty's pathname and connect
221 with their favorite console program. For example:
222 cu -l /dev/pts/22
223
224 Args:
225 interface: dict of interface parameters.
226
227 Returns:
228 Instance object of interface
229
230 Raises:
231 ServodError: Raised on init failure.
232 """
233 self._logger.info("Suart: interface: %s" % interface)
Kevin Cheng71a046f2016-06-13 16:37:58 -0700234 sobj = stm32uart.Suart(self._vendor, self._product, interface['interface'],
235 self._serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800236
237 try:
238 sobj.run()
239 except stm32uart.SuartError as e:
240 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
241
242 self._logger.info("%s" % sobj.get_pty())
243 return sobj
244
245 def _init_stm32_gpio(self, interface):
246 """Initialize stm32 gpio interface.
247 Args:
248 interface: interface number of stm32 device to use.
249
250 Returns:
251 Instance object of interface
252
253 Raises:
254 SgpioError: Raised on init failure.
255 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700256 interface_number = interface
257 # Interface could be a dict.
258 if type(interface) is dict:
259 interface_number = interface['interface']
260 self._logger.info("Sgpio: interface: %s" % interface_number)
261 return stm32gpio.Sgpio(self._vendor, self._product, interface_number,
262 self._serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800263
264 def _init_stm32_i2c(self, interface):
265 """Initialize stm32 USB to I2C bridge interface and open for use
266
267 Args:
268 interface: USB interface number of stm32 device to use
269
270 Returns:
271 Instance object of interface.
272
273 Raises:
274 Si2cError: Raised on init failure.
275 """
276 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800277 port = interface.get('port', 0)
278 return stm32i2c.Si2cBus(self._vendor, self._product,
Kevin Cheng71a046f2016-06-13 16:37:58 -0700279 interface['interface'], port=port, serialname=self._serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800280
Aaron.Chuang88eff332014-07-31 08:32:00 +0800281 def _init_bb_adc(self, interface):
282 """Initalize beaglebone ADC interface."""
283 return bbadc.BBadc()
284
Simran Basie750a342013-03-12 13:45:26 -0700285 def _init_bb_gpio(self, interface):
286 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700287 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700288
289 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700290 """Initialize i2c interface and open for use.
291
292 Args:
293 interface: interface number of FTDI device to use
294
295 Returns:
296 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700297
298 Raises:
299 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700300 """
Todd Brochad034442011-05-25 15:05:29 -0700301 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
302 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700303 try:
304 fobj.open()
305 except ftdii2c.Fi2cError as e:
306 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
307
Todd Broche505b8d2011-03-21 18:19:54 -0700308 # Set the frequency of operation of the i2c bus.
309 # TODO(tbroch) make configureable
310 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700311
Todd Broche505b8d2011-03-21 18:19:54 -0700312 return fobj
313
Simran Basie750a342013-03-12 13:45:26 -0700314 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
315 def _init_bb_i2c(self, interface):
316 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700317 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700318
Rong Changc6c8c022014-08-11 14:07:11 +0800319 def _init_dev_i2c(self, interface):
320 """Initalize Linux i2c-dev interface."""
321 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
322
Simran Basie750a342013-03-12 13:45:26 -0700323 def _init_ftdi_uart(self, interface):
324 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700325
326 Note, the uart runs in a separate thread (pthreads). Users wishing to
327 interact with it will query control for the pty's pathname and connect
328 with there favorite console program. For example:
329 cu -l /dev/pts/22
330
331 Args:
332 interface: interface number of FTDI device to use
333
334 Returns:
335 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700336
337 Raises:
338 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700339 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700340 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
341 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700342 try:
343 fobj.run()
344 except ftdiuart.FuartError as e:
345 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
346
Todd Broch47c43f42011-05-26 15:11:31 -0700347 self._logger.info("%s" % fobj.get_pty())
348 return fobj
349
Simran Basie750a342013-03-12 13:45:26 -0700350 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
351 def _init_bb_uart(self, interface):
352 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700353 logging.debug('UART INTERFACE: %s', interface)
354 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700355
356 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700357 """Initialize special gpio + uart interface and open for use
358
359 Note, the uart runs in a separate thread (pthreads). Users wishing to
360 interact with it will query control for the pty's pathname and connect
361 with there favorite console program. For example:
362 cu -l /dev/pts/22
363
364 Args:
365 interface: interface number of FTDI device to use
366
367 Returns:
368 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700369
370 Raises:
371 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700372 """
Simran Basie750a342013-03-12 13:45:26 -0700373 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700374 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
375 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700376 try:
377 fuart.run()
378 except ftdiuart.FuartError as e:
379 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
380
Todd Broch888da782011-10-07 14:29:09 -0700381 self._logger.info("uart pty: %s" % fuart.get_pty())
382 return fgpio, fuart
383
Aseda Aboagyea4922212015-11-20 15:19:08 -0800384 def _init_ec3po_uart(self, interface):
385 """Initialize EC-3PO console interpreter interface.
386
387 Args:
388 interface: A dictionary representing the interface.
389
390 Returns:
391 An EC3PO object representing the EC-3PO interface or None if there's no
392 interface for the USB PD UART.
393 """
394 vid = self._vendor
395 pid = self._product
396 # The current PID might be incremented if there are multiple FTDI.
397 # Therefore, try rewinding the PID back one if we don't find the base PID in
398 # the SERVO_ID_DEFAULTS
399 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
400 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
401 pid -= 1
402 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
403
Nick Sanders97bc4462016-01-04 15:37:31 -0800404 if 'raw_pty' in interface:
405 # We have specified an explicit target for this ec3po.
406 raw_uart_name = interface['raw_pty']
407 raw_ec_uart = self.get(raw_uart_name)
408
Aseda Aboagyea4922212015-11-20 15:19:08 -0800409 # Servo V2 / V3 should have the interface indicies in the same spot.
Nick Sanders97bc4462016-01-04 15:37:31 -0800410 elif ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
Aseda Aboagyea4922212015-11-20 15:19:08 -0800411 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
412 # Determine if it's a PD interface or just main EC console.
413 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
414 try:
415 # Obtain the raw EC UART PTY and create the EC-3PO interface.
416 raw_ec_uart = self.get('raw_usbpd_uart_pty')
417 except NameError:
418 # This overlay doesn't have a USB PD MCU, so skip init.
419 self._logger.info('No PD MCU UART.')
420 return None
421 except AttributeError:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700422 # This overlay has no get method for the interface so skip init. For
423 # servo v2, it's common for interfaces to be overridden such as
424 # reusing JTAG pins for the PD MCU UART instead. Therefore, print an
425 # error message indicating that the interface might be set
426 # incorrectly.
427 if (vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS:
428 self._logger.warn('No interface for PD MCU UART.')
429 self._logger.warn('Usually, this happens because the interface is '
430 'set incorrectly. If you\'re overriding an '
431 'existing interface, be sure to update the '
432 'interface lists for your board at the end of '
433 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800434 return None
435
436 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
437 raw_ec_uart = self.get('raw_ec_uart_pty')
438
439 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
440 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
441 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
442 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
443 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
444 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
445 raw_ec_uart = self.get('raw_ec_uart_pty')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800446 else:
447 raise ServodError(('Unexpected EC-3PO interface!'
448 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
449
450 return ec3po_interface.EC3PO(raw_ec_uart)
451
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800452 def _camel_case(self, string):
453 output = ''
454 for s in string.split('_'):
455 if output:
456 output += s.capitalize()
457 else:
458 output = s
459 return output
460
Todd Broche505b8d2011-03-21 18:19:54 -0700461 def _get_param_drv(self, control_name, is_get=True):
462 """Get access to driver for a given control.
463
464 Note, some controls have different parameter dictionaries for 'getting' the
465 control's value versus 'setting' it. Boolean is_get distinguishes which is
466 being requested.
467
468 Args:
469 control_name: string name of control
470 is_get: boolean to determine
471
472 Returns:
473 tuple (param, drv) where:
474 param: param dictionary for control
475 drv: instance object of driver for particular control
476
477 Raises:
478 ServodError: Error occurred while examining params dict
479 """
480 self._logger.debug("")
481 # if already setup just return tuple from driver dict
482 if control_name in self._drv_dict:
483 if is_get and ('get' in self._drv_dict[control_name]):
484 return self._drv_dict[control_name]['get']
485 if not is_get and ('set' in self._drv_dict[control_name]):
486 return self._drv_dict[control_name]['set']
487
488 params = self._syscfg.lookup_control_params(control_name, is_get)
489 if 'drv' not in params:
490 self._logger.error("Unable to determine driver for %s" % control_name)
491 raise ServodError("'drv' key not found in params dict")
492 if 'interface' not in params:
493 self._logger.error("Unable to determine interface for %s" %
494 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700495 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700496
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800497 interface_id = params.get(
498 '%s_interface' % self._version, params['interface'])
499 if interface_id == 'servo':
500 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700501 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800502 index = int(interface_id) - 1
503 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700504
Todd Broche505b8d2011-03-21 18:19:54 -0700505 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
506 drv_pkg = imp.load_module('drv',
507 *imp.find_module('drv', servo_pkg.__path__))
508 drv_name = params['drv']
509 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800510 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700511 drv = drv_class(interface, params)
512 if control_name not in self._drv_dict:
513 self._drv_dict[control_name] = {}
514 if is_get:
515 self._drv_dict[control_name]['get'] = (params, drv)
516 else:
517 self._drv_dict[control_name]['set'] = (params, drv)
518 return (params, drv)
519
520 def doc_all(self):
521 """Return all documenation for controls.
522
523 Returns:
524 string of <doc> text in config file (xml) and the params dictionary for
525 all controls.
526
527 For example:
528 warm_reset :: Reset the device warmly
529 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
530 """
531 return self._syscfg.display_config()
532
533 def doc(self, name):
534 """Retreive doc string in system config file for given control name.
535
536 Args:
537 name: name string of control to get doc string
538
539 Returns:
540 doc string of name
541
542 Raises:
543 NameError: if fails to locate control
544 """
545 self._logger.debug("name(%s)" % (name))
546 if self._syscfg.is_control(name):
547 return self._syscfg.get_control_docstring(name)
548 else:
549 raise NameError("No control %s" %name)
550
Fang Deng90377712013-06-03 15:51:48 -0700551 def _switch_usbkey(self, mux_direction):
552 """Connect USB flash stick to either servo or DUT.
553
554 This function switches 'usb_mux_sel1' to provide electrical
555 connection between the USB port J3 and either servo or DUT side.
556
557 Switching the usb mux is accompanied by powercycling
558 of the USB stick, because it sometimes gets wedged if the mux
559 is switched while the stick power is on.
560
561 Args:
562 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
563 """
564 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
565 time.sleep(self._USB_POWEROFF_DELAY)
566 self.set(self._USB_J3, mux_direction)
567 time.sleep(self._USB_POWEROFF_DELAY)
568 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
569 if mux_direction == self._USB_J3_TO_SERVO:
570 time.sleep(self._USB_DETECTION_DELAY)
571
Simran Basia9f41032012-05-11 14:21:58 -0700572 def _get_usb_port_set(self):
573 """Gets a set of USB disks currently connected to the system
574
575 Returns:
576 A set of USB disk paths.
577 """
578 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
579 return set(["/dev/" + dev for dev in usb_set])
580
581 def _probe_host_usb_dev(self):
582 """Probe the USB disk device plugged in the servo from the host side.
583
584 Method can fail by:
585 1) Having multiple servos connected and returning incorrect /dev/sdX of
586 another servo.
587 2) Finding multiple /dev/sdX and returning None.
588
589 Returns:
590 USB disk path if one and only one USB disk path is found, otherwise None.
591 """
Fang Deng90377712013-06-03 15:51:48 -0700592 original_value = self.get(self._USB_J3)
593 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700594 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700595 if (original_usb_power == self._USB_J3_PWR_ON and
596 original_value != self._USB_J3_TO_DUT):
597 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700598 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700599
Fang Deng90377712013-06-03 15:51:48 -0700600 # Make the host able to see the USB disk.
601 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700602 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700603
Simran Basia9f41032012-05-11 14:21:58 -0700604 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700605 if original_value != self._USB_J3_TO_SERVO:
606 self._switch_usbkey(original_value)
607 if original_usb_power != self._USB_J3_PWR_ON:
608 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
609 time.sleep(self._USB_POWEROFF_DELAY)
610
Simran Basia9f41032012-05-11 14:21:58 -0700611 # Subtract the two sets to find the usb device.
612 diff_set = has_usb_set - no_usb_set
613 if len(diff_set) == 1:
614 return diff_set.pop()
615 else:
616 return None
617
618 def download_image_to_usb(self, image_path):
619 """Download image and save to the USB device found by probe_host_usb_dev.
620 If the image_path is a URL, it will download this url to the USB path;
621 otherwise it will simply copy the image_path's contents to the USB path.
622
623 Args:
624 image_path: path or url to the recovery image.
625
626 Returns:
627 True|False: True if process completed successfully, False if error
628 occurred.
629 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
630 comment at the end of set().
631 """
632 self._logger.debug("image_path(%s)" % image_path)
633 self._logger.debug("Detecting USB stick device...")
634 usb_dev = self._probe_host_usb_dev()
635 if not usb_dev:
636 self._logger.error("No usb device connected to servo")
637 return False
638
Kevin Cheng9071ed92016-06-21 14:37:54 -0700639 # Let's check if we downloaded this last time and if so assume the image is
640 # still on the usb device and return True.
641 if self._image_path == image_path:
642 self._logger.debug("Image already on USB device, skipping transfer")
643 return True
644
Simran Basia9f41032012-05-11 14:21:58 -0700645 try:
646 if image_path.startswith(self._HTTP_PREFIX):
647 self._logger.debug("Image path is a URL, downloading image")
648 urllib.urlretrieve(image_path, usb_dev)
649 else:
650 shutil.copyfile(image_path, usb_dev)
651 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700652 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700653 e.strerror, e.errno)
654 return False
655 except urllib.ContentTooShortError:
656 self._logger.error("Failed to download URL: %s to USB device: %s",
657 image_path, usb_dev)
658 return False
659 except BaseException as e:
660 self._logger.error("Unexpected exception downloading %s to %s: %s",
661 image_path, usb_dev, str(e))
662 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800663 finally:
664 # We just plastered the partition table for a block device.
665 # Pass or fail, we mustn't go without telling the kernel about
666 # the change, or it will punish us with sporadic, hard-to-debug
667 # failures.
668 subprocess.call(["sync"])
669 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700670 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700671 return True
672
673 def make_image_noninteractive(self):
674 """Makes the recovery image noninteractive.
675
676 A noninteractive image will reboot automatically after installation
677 instead of waiting for the USB device to be removed to initiate a system
678 reboot.
679
680 Mounts partition 1 of the image stored on usb_dev and creates a file
681 called "non_interactive" so that the image will become noninteractive.
682
683 Returns:
684 True|False: True if process completed successfully, False if error
685 occurred.
686 """
687 result = True
688 usb_dev = self._probe_host_usb_dev()
689 if not usb_dev:
690 self._logger.error("No usb device connected to servo")
691 return False
692 # Create TempDirectory
693 tmpdir = tempfile.mkdtemp()
694 if tmpdir:
695 # Mount drive to tmpdir.
696 partition_1 = "%s1" % usb_dev
697 rc = subprocess.call(["mount", partition_1, tmpdir])
698 if rc == 0:
699 # Create file 'non_interactive'
700 non_interactive_file = os.path.join(tmpdir, "non_interactive")
701 try:
702 open(non_interactive_file, "w").close()
703 except IOError as e:
704 self._logger.error("Failed to create file %s : %s ( %d )",
705 non_interactive_file, e.strerror, e.errno)
706 result = False
707 except BaseException as e:
708 self._logger.error("Unexpected Exception creating file %s : %s",
709 non_interactive_file, str(e))
710 result = False
711 # Unmount drive regardless if file creation worked or not.
712 rc = subprocess.call(["umount", partition_1])
713 if rc != 0:
714 self._logger.error("Failed to unmount USB Device")
715 result = False
716 else:
717 self._logger.error("Failed to mount USB Device")
718 result = False
719
720 # Delete tmpdir. May throw exception if 'umount' failed.
721 try:
722 os.rmdir(tmpdir)
723 except OSError as e:
724 self._logger.error("Failed to remove temp directory %s : %s",
725 tmpdir, str(e))
726 return False
727 except BaseException as e:
728 self._logger.error("Unexpected Exception removing tempdir %s : %s",
729 tmpdir, str(e))
730 return False
731 else:
732 self._logger.error("Failed to create temp directory.")
733 return False
734 return result
735
Todd Broch352b4b22013-03-22 09:48:40 -0700736 def set_get_all(self, cmds):
737 """Set &| get one or more control values.
738
739 Args:
740 cmds: list of control[:value] to get or set.
741
742 Returns:
743 rv: list of responses from calling get or set methods.
744 """
745 rv = []
746 for cmd in cmds:
747 if ':' in cmd:
748 (control, value) = cmd.split(':')
749 rv.append(self.set(control, value))
750 else:
751 rv.append(self.get(cmd))
752 return rv
753
Todd Broche505b8d2011-03-21 18:19:54 -0700754 def get(self, name):
755 """Get control value.
756
757 Args:
758 name: name string of control
759
760 Returns:
761 Response from calling drv get method. Value is reformatted based on
762 control's dictionary parameters
763
764 Raises:
765 HwDriverError: Error occurred while using drv
766 """
767 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700768 if name == 'serialname':
769 if self._serialname:
770 return self._serialname
771 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700772 (param, drv) = self._get_param_drv(name)
773 try:
774 val = drv.get()
775 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800776 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700777 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700778 except AttributeError, error:
779 self._logger.error("Getting %s: %s" % (name, error))
780 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800781 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700782 self._logger.error("Getting %s" % (name))
783 raise
Todd Brochd6061672012-05-11 15:52:47 -0700784
Todd Broche505b8d2011-03-21 18:19:54 -0700785 def get_all(self, verbose):
786 """Get all controls values.
787
788 Args:
789 verbose: Boolean on whether to return doc info as well
790
791 Returns:
792 string creating from trying to get all values of all controls. In case of
793 error attempting access to control, response is 'ERR'.
794 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800795 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700796 for name in self._syscfg.syscfg_dict['control']:
797 self._logger.debug("name = %s" %name)
798 try:
799 value = self.get(name)
800 except Exception:
801 value = "ERR"
802 pass
803 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800804 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700805 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800806 rsp.append("%s:%s" % (name, value))
807 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700808
809 def set(self, name, wr_val_str):
810 """Set control.
811
812 Args:
813 name: name string of control
814 wr_val_str: value string to write. Can be integer, float or a
815 alpha-numerical that is mapped to a integer or float.
816
817 Raises:
818 HwDriverError: Error occurred while using driver
819 """
820 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
821 (params, drv) = self._get_param_drv(name, False)
822 wr_val = self._syscfg.resolve_val(params, wr_val_str)
823 try:
824 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800825 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700826 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
827 raise
828 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
829 # & client I still have to return something to appease the
830 # marshall/unmarshall
831 return True
832
Todd Brochd6061672012-05-11 15:52:47 -0700833 def hwinit(self, verbose=False):
834 """Initialize all controls.
835
836 These values are part of the system config XML files of the form
837 init=<value>. This command should be used by clients wishing to return the
838 servo and DUT its connected to a known good/safe state.
839
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800840 Note that initialization errors are ignored (as in some cases they could
841 be caused by DUT firmware deficiencies). This might need to be fine tuned
842 later.
843
Todd Brochd6061672012-05-11 15:52:47 -0700844 Args:
845 verbose: boolean, if True prints info about control initialized.
846 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800847
848 Returns:
849 This function is called across RPC and as such is expected to return
850 something unless transferring 'none' across is allowed. Hence adding a
851 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700852 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800853 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800854 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700855 # Workaround for bug chrome-os-partner:42349. Without this check, the
856 # gpio will briefly pulse low if we set it from high to high.
857 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700858 self.set(control_name, value)
859 if verbose:
860 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800861 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800862 self._logger.error("Problem initializing %s -> %s :: %s",
863 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -0800864
865 # Init keyboard after all the intefaces are up.
866 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800867 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800868
Todd Broche505b8d2011-03-21 18:19:54 -0700869 def echo(self, echo):
870 """Dummy echo function for testing/examples.
871
872 Args:
873 echo: string to echo back to client
874 """
875 self._logger.debug("echo(%s)" % (echo))
876 return "ECH0ING: %s" % (echo)
877
J. Richard Barnettee2820552013-03-14 16:13:46 -0700878 def get_board(self):
879 """Return the board specified at startup, if any."""
880 return self._board
881
Simran Basia23c1392013-08-06 14:59:10 -0700882 def get_version(self):
883 """Get servo board version."""
884 return self._version
885
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800886 def power_long_press(self):
887 """Simulate a long power button press."""
888 # After a long power press, the EC may ignore the next power
889 # button press (at least on Alex). To guarantee that this
890 # won't happen, we need to allow the EC one second to
891 # collect itself.
892 self._keyboard.power_long_press()
893 return True
894
895 def power_normal_press(self):
896 """Simulate a normal power button press."""
897 self._keyboard.power_normal_press()
898 return True
899
900 def power_short_press(self):
901 """Simulate a short power button press."""
902 self._keyboard.power_short_press()
903 return True
904
905 def power_key(self, secs=''):
906 """Simulate a power button press.
907
908 Args:
909 secs: Time in seconds to simulate the keypress.
910 """
911 self._keyboard.power_key(secs)
912 return True
913
914 def ctrl_d(self, press_secs=''):
915 """Simulate Ctrl-d simultaneous button presses."""
916 self._keyboard.ctrl_d(press_secs)
917 return True
918
Victor Dodone539cea2016-03-29 18:50:17 -0700919 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800920 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -0700921 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800922 return True
923
924 def ctrl_enter(self, press_secs=''):
925 """Simulate Ctrl-enter simultaneous button presses."""
926 self._keyboard.ctrl_enter(press_secs)
927 return True
928
929 def d_key(self, press_secs=''):
930 """Simulate Enter key button press."""
931 self._keyboard.d_key(press_secs)
932 return True
933
934 def ctrl_key(self, press_secs=''):
935 """Simulate Enter key button press."""
936 self._keyboard.ctrl_key(press_secs)
937 return True
938
939 def enter_key(self, press_secs=''):
940 """Simulate Enter key button press."""
941 self._keyboard.enter_key(press_secs)
942 return True
943
944 def refresh_key(self, press_secs=''):
945 """Simulate Refresh key (F3) button press."""
946 self._keyboard.refresh_key(press_secs)
947 return True
948
949 def ctrl_refresh_key(self, press_secs=''):
950 """Simulate Ctrl and Refresh (F3) simultaneous press.
951
952 This key combination is an alternative of Space key.
953 """
954 self._keyboard.ctrl_refresh_key(press_secs)
955 return True
956
957 def imaginary_key(self, press_secs=''):
958 """Simulate imaginary key button press.
959
960 Maps to a key that doesn't physically exist.
961 """
962 self._keyboard.imaginary_key(press_secs)
963 return True
964
Todd Brochdbb09982011-10-02 07:14:26 -0700965
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200966 def sysrq_x(self, press_secs=''):
967 """Simulate Alt VolumeUp X simultaneous press.
968
969 This key combination is the kernel system request (sysrq) x.
970 """
971 self._keyboard.sysrq_x(press_secs)
972 return True
973
974
Todd Broche505b8d2011-03-21 18:19:54 -0700975def test():
976 """Integration testing.
977
978 TODO(tbroch) Enhance integration test and add unittest (see mox)
979 """
980 logging.basicConfig(level=logging.DEBUG,
981 format="%(asctime)s - %(name)s - " +
982 "%(levelname)s - %(message)s")
983 # configure server & listen
984 servod_obj = Servod(1)
985 # 4 == number of interfaces on a FT4232H device
986 for i in xrange(4):
987 if i == 1:
988 # its an i2c interface ... see __init__ for details and TODO to make
989 # this configureable
990 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
991 else:
992 # its a gpio interface
993 servod_obj._interface_list[i].wr_rd(0)
994
995 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
996 allow_none=True)
997 server.register_introspection_functions()
998 server.register_multicall_functions()
999 server.register_instance(servod_obj)
1000 logging.info("Listening on localhost port 9999")
1001 server.serve_forever()
1002
1003if __name__ == "__main__":
1004 test()
1005
1006 # simple client transaction would look like
1007 """
1008 remote_uri = 'http://localhost:9999'
1009 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1010 send_str = "Hello_there"
1011 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1012 """