blob: a3d5b7709eccc9f1d508dfe12c2de647492b1282 [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
Simran Basie750a342013-03-12 13:45:26 -0700184 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700185 """Initialize gpio driver interface and open for use.
186
187 Args:
188 interface: interface number of FTDI device to use.
189
190 Returns:
191 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700192
193 Raises:
194 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700195 """
Todd Brochad034442011-05-25 15:05:29 -0700196 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
197 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700198 try:
199 fobj.open()
200 except ftdigpio.FgpioError as e:
201 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
202
Todd Broche505b8d2011-03-21 18:19:54 -0700203 return fobj
204
Nick Sanders97bc4462016-01-04 15:37:31 -0800205 def _init_stm32_uart(self, interface):
206 """Initialize stm32 uart interface and open for use
207
208 Note, the uart runs in a separate thread. Users wishing to
209 interact with it will query control for the pty's pathname and connect
210 with their favorite console program. For example:
211 cu -l /dev/pts/22
212
213 Args:
214 interface: dict of interface parameters.
215
216 Returns:
217 Instance object of interface
218
219 Raises:
220 ServodError: Raised on init failure.
221 """
222 self._logger.info("Suart: interface: %s" % interface)
Kevin Cheng71a046f2016-06-13 16:37:58 -0700223 sobj = stm32uart.Suart(self._vendor, self._product, interface['interface'],
224 self._serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800225
226 try:
227 sobj.run()
228 except stm32uart.SuartError as e:
229 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
230
231 self._logger.info("%s" % sobj.get_pty())
232 return sobj
233
234 def _init_stm32_gpio(self, interface):
235 """Initialize stm32 gpio interface.
236 Args:
237 interface: interface number of stm32 device to use.
238
239 Returns:
240 Instance object of interface
241
242 Raises:
243 SgpioError: Raised on init failure.
244 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700245 interface_number = interface
246 # Interface could be a dict.
247 if type(interface) is dict:
248 interface_number = interface['interface']
249 self._logger.info("Sgpio: interface: %s" % interface_number)
250 return stm32gpio.Sgpio(self._vendor, self._product, interface_number,
251 self._serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800252
253 def _init_stm32_i2c(self, interface):
254 """Initialize stm32 USB to I2C bridge interface and open for use
255
256 Args:
257 interface: USB interface number of stm32 device to use
258
259 Returns:
260 Instance object of interface.
261
262 Raises:
263 Si2cError: Raised on init failure.
264 """
265 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800266 port = interface.get('port', 0)
267 return stm32i2c.Si2cBus(self._vendor, self._product,
Kevin Cheng71a046f2016-06-13 16:37:58 -0700268 interface['interface'], port=port, serialname=self._serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800269
Aaron.Chuang88eff332014-07-31 08:32:00 +0800270 def _init_bb_adc(self, interface):
271 """Initalize beaglebone ADC interface."""
272 return bbadc.BBadc()
273
Simran Basie750a342013-03-12 13:45:26 -0700274 def _init_bb_gpio(self, interface):
275 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700276 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700277
278 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700279 """Initialize i2c interface and open for use.
280
281 Args:
282 interface: interface number of FTDI device to use
283
284 Returns:
285 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700286
287 Raises:
288 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700289 """
Todd Brochad034442011-05-25 15:05:29 -0700290 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
291 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700292 try:
293 fobj.open()
294 except ftdii2c.Fi2cError as e:
295 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
296
Todd Broche505b8d2011-03-21 18:19:54 -0700297 # Set the frequency of operation of the i2c bus.
298 # TODO(tbroch) make configureable
299 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700300
Todd Broche505b8d2011-03-21 18:19:54 -0700301 return fobj
302
Simran Basie750a342013-03-12 13:45:26 -0700303 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
304 def _init_bb_i2c(self, interface):
305 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700306 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700307
Rong Changc6c8c022014-08-11 14:07:11 +0800308 def _init_dev_i2c(self, interface):
309 """Initalize Linux i2c-dev interface."""
310 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
311
Simran Basie750a342013-03-12 13:45:26 -0700312 def _init_ftdi_uart(self, interface):
313 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700314
315 Note, the uart runs in a separate thread (pthreads). Users wishing to
316 interact with it will query control for the pty's pathname and connect
317 with there favorite console program. For example:
318 cu -l /dev/pts/22
319
320 Args:
321 interface: interface number of FTDI device to use
322
323 Returns:
324 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700325
326 Raises:
327 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700328 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700329 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
330 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700331 try:
332 fobj.run()
333 except ftdiuart.FuartError as e:
334 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
335
Todd Broch47c43f42011-05-26 15:11:31 -0700336 self._logger.info("%s" % fobj.get_pty())
337 return fobj
338
Simran Basie750a342013-03-12 13:45:26 -0700339 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
340 def _init_bb_uart(self, interface):
341 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700342 logging.debug('UART INTERFACE: %s', interface)
343 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700344
345 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700346 """Initialize special gpio + uart interface and open for use
347
348 Note, the uart runs in a separate thread (pthreads). Users wishing to
349 interact with it will query control for the pty's pathname and connect
350 with there favorite console program. For example:
351 cu -l /dev/pts/22
352
353 Args:
354 interface: interface number of FTDI device to use
355
356 Returns:
357 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700358
359 Raises:
360 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700361 """
Simran Basie750a342013-03-12 13:45:26 -0700362 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700363 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
364 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700365 try:
366 fuart.run()
367 except ftdiuart.FuartError as e:
368 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
369
Todd Broch888da782011-10-07 14:29:09 -0700370 self._logger.info("uart pty: %s" % fuart.get_pty())
371 return fgpio, fuart
372
Aseda Aboagyea4922212015-11-20 15:19:08 -0800373 def _init_ec3po_uart(self, interface):
374 """Initialize EC-3PO console interpreter interface.
375
376 Args:
377 interface: A dictionary representing the interface.
378
379 Returns:
380 An EC3PO object representing the EC-3PO interface or None if there's no
381 interface for the USB PD UART.
382 """
383 vid = self._vendor
384 pid = self._product
385 # The current PID might be incremented if there are multiple FTDI.
386 # Therefore, try rewinding the PID back one if we don't find the base PID in
387 # the SERVO_ID_DEFAULTS
388 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
389 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
390 pid -= 1
391 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
392
Nick Sanders97bc4462016-01-04 15:37:31 -0800393 if 'raw_pty' in interface:
394 # We have specified an explicit target for this ec3po.
395 raw_uart_name = interface['raw_pty']
396 raw_ec_uart = self.get(raw_uart_name)
397
Aseda Aboagyea4922212015-11-20 15:19:08 -0800398 # Servo V2 / V3 should have the interface indicies in the same spot.
Nick Sanders97bc4462016-01-04 15:37:31 -0800399 elif ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
Aseda Aboagyea4922212015-11-20 15:19:08 -0800400 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
401 # Determine if it's a PD interface or just main EC console.
402 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
403 try:
404 # Obtain the raw EC UART PTY and create the EC-3PO interface.
405 raw_ec_uart = self.get('raw_usbpd_uart_pty')
406 except NameError:
407 # This overlay doesn't have a USB PD MCU, so skip init.
408 self._logger.info('No PD MCU UART.')
409 return None
410 except AttributeError:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700411 # This overlay has no get method for the interface so skip init. For
412 # servo v2, it's common for interfaces to be overridden such as
413 # reusing JTAG pins for the PD MCU UART instead. Therefore, print an
414 # error message indicating that the interface might be set
415 # incorrectly.
416 if (vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS:
417 self._logger.warn('No interface for PD MCU UART.')
418 self._logger.warn('Usually, this happens because the interface is '
419 'set incorrectly. If you\'re overriding an '
420 'existing interface, be sure to update the '
421 'interface lists for your board at the end of '
422 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800423 return None
424
425 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
426 raw_ec_uart = self.get('raw_ec_uart_pty')
427
428 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
429 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
430 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
431 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
432 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
433 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
434 raw_ec_uart = self.get('raw_ec_uart_pty')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800435 else:
436 raise ServodError(('Unexpected EC-3PO interface!'
437 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
438
439 return ec3po_interface.EC3PO(raw_ec_uart)
440
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800441 def _camel_case(self, string):
442 output = ''
443 for s in string.split('_'):
444 if output:
445 output += s.capitalize()
446 else:
447 output = s
448 return output
449
Todd Broche505b8d2011-03-21 18:19:54 -0700450 def _get_param_drv(self, control_name, is_get=True):
451 """Get access to driver for a given control.
452
453 Note, some controls have different parameter dictionaries for 'getting' the
454 control's value versus 'setting' it. Boolean is_get distinguishes which is
455 being requested.
456
457 Args:
458 control_name: string name of control
459 is_get: boolean to determine
460
461 Returns:
462 tuple (param, drv) where:
463 param: param dictionary for control
464 drv: instance object of driver for particular control
465
466 Raises:
467 ServodError: Error occurred while examining params dict
468 """
469 self._logger.debug("")
470 # if already setup just return tuple from driver dict
471 if control_name in self._drv_dict:
472 if is_get and ('get' in self._drv_dict[control_name]):
473 return self._drv_dict[control_name]['get']
474 if not is_get and ('set' in self._drv_dict[control_name]):
475 return self._drv_dict[control_name]['set']
476
477 params = self._syscfg.lookup_control_params(control_name, is_get)
478 if 'drv' not in params:
479 self._logger.error("Unable to determine driver for %s" % control_name)
480 raise ServodError("'drv' key not found in params dict")
481 if 'interface' not in params:
482 self._logger.error("Unable to determine interface for %s" %
483 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700484 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700485
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800486 interface_id = params.get(
487 '%s_interface' % self._version, params['interface'])
488 if interface_id == 'servo':
489 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700490 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800491 index = int(interface_id) - 1
492 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700493
Todd Broche505b8d2011-03-21 18:19:54 -0700494 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
495 drv_pkg = imp.load_module('drv',
496 *imp.find_module('drv', servo_pkg.__path__))
497 drv_name = params['drv']
498 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800499 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700500 drv = drv_class(interface, params)
501 if control_name not in self._drv_dict:
502 self._drv_dict[control_name] = {}
503 if is_get:
504 self._drv_dict[control_name]['get'] = (params, drv)
505 else:
506 self._drv_dict[control_name]['set'] = (params, drv)
507 return (params, drv)
508
509 def doc_all(self):
510 """Return all documenation for controls.
511
512 Returns:
513 string of <doc> text in config file (xml) and the params dictionary for
514 all controls.
515
516 For example:
517 warm_reset :: Reset the device warmly
518 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
519 """
520 return self._syscfg.display_config()
521
522 def doc(self, name):
523 """Retreive doc string in system config file for given control name.
524
525 Args:
526 name: name string of control to get doc string
527
528 Returns:
529 doc string of name
530
531 Raises:
532 NameError: if fails to locate control
533 """
534 self._logger.debug("name(%s)" % (name))
535 if self._syscfg.is_control(name):
536 return self._syscfg.get_control_docstring(name)
537 else:
538 raise NameError("No control %s" %name)
539
Fang Deng90377712013-06-03 15:51:48 -0700540 def _switch_usbkey(self, mux_direction):
541 """Connect USB flash stick to either servo or DUT.
542
543 This function switches 'usb_mux_sel1' to provide electrical
544 connection between the USB port J3 and either servo or DUT side.
545
546 Switching the usb mux is accompanied by powercycling
547 of the USB stick, because it sometimes gets wedged if the mux
548 is switched while the stick power is on.
549
550 Args:
551 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
552 """
553 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
554 time.sleep(self._USB_POWEROFF_DELAY)
555 self.set(self._USB_J3, mux_direction)
556 time.sleep(self._USB_POWEROFF_DELAY)
557 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
558 if mux_direction == self._USB_J3_TO_SERVO:
559 time.sleep(self._USB_DETECTION_DELAY)
560
Simran Basia9f41032012-05-11 14:21:58 -0700561 def _get_usb_port_set(self):
562 """Gets a set of USB disks currently connected to the system
563
564 Returns:
565 A set of USB disk paths.
566 """
567 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
568 return set(["/dev/" + dev for dev in usb_set])
569
570 def _probe_host_usb_dev(self):
571 """Probe the USB disk device plugged in the servo from the host side.
572
573 Method can fail by:
574 1) Having multiple servos connected and returning incorrect /dev/sdX of
575 another servo.
576 2) Finding multiple /dev/sdX and returning None.
577
578 Returns:
579 USB disk path if one and only one USB disk path is found, otherwise None.
580 """
Fang Deng90377712013-06-03 15:51:48 -0700581 original_value = self.get(self._USB_J3)
582 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700583 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700584 if (original_usb_power == self._USB_J3_PWR_ON and
585 original_value != self._USB_J3_TO_DUT):
586 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700587 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700588
Fang Deng90377712013-06-03 15:51:48 -0700589 # Make the host able to see the USB disk.
590 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700591 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700592
Simran Basia9f41032012-05-11 14:21:58 -0700593 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700594 if original_value != self._USB_J3_TO_SERVO:
595 self._switch_usbkey(original_value)
596 if original_usb_power != self._USB_J3_PWR_ON:
597 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
598 time.sleep(self._USB_POWEROFF_DELAY)
599
Simran Basia9f41032012-05-11 14:21:58 -0700600 # Subtract the two sets to find the usb device.
601 diff_set = has_usb_set - no_usb_set
602 if len(diff_set) == 1:
603 return diff_set.pop()
604 else:
605 return None
606
607 def download_image_to_usb(self, image_path):
608 """Download image and save to the USB device found by probe_host_usb_dev.
609 If the image_path is a URL, it will download this url to the USB path;
610 otherwise it will simply copy the image_path's contents to the USB path.
611
612 Args:
613 image_path: path or url to the recovery image.
614
615 Returns:
616 True|False: True if process completed successfully, False if error
617 occurred.
618 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
619 comment at the end of set().
620 """
621 self._logger.debug("image_path(%s)" % image_path)
622 self._logger.debug("Detecting USB stick device...")
623 usb_dev = self._probe_host_usb_dev()
624 if not usb_dev:
625 self._logger.error("No usb device connected to servo")
626 return False
627
Kevin Cheng9071ed92016-06-21 14:37:54 -0700628 # Let's check if we downloaded this last time and if so assume the image is
629 # still on the usb device and return True.
630 if self._image_path == image_path:
631 self._logger.debug("Image already on USB device, skipping transfer")
632 return True
633
Simran Basia9f41032012-05-11 14:21:58 -0700634 try:
635 if image_path.startswith(self._HTTP_PREFIX):
636 self._logger.debug("Image path is a URL, downloading image")
637 urllib.urlretrieve(image_path, usb_dev)
638 else:
639 shutil.copyfile(image_path, usb_dev)
640 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700641 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700642 e.strerror, e.errno)
643 return False
644 except urllib.ContentTooShortError:
645 self._logger.error("Failed to download URL: %s to USB device: %s",
646 image_path, usb_dev)
647 return False
648 except BaseException as e:
649 self._logger.error("Unexpected exception downloading %s to %s: %s",
650 image_path, usb_dev, str(e))
651 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800652 finally:
653 # We just plastered the partition table for a block device.
654 # Pass or fail, we mustn't go without telling the kernel about
655 # the change, or it will punish us with sporadic, hard-to-debug
656 # failures.
657 subprocess.call(["sync"])
658 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700659 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700660 return True
661
662 def make_image_noninteractive(self):
663 """Makes the recovery image noninteractive.
664
665 A noninteractive image will reboot automatically after installation
666 instead of waiting for the USB device to be removed to initiate a system
667 reboot.
668
669 Mounts partition 1 of the image stored on usb_dev and creates a file
670 called "non_interactive" so that the image will become noninteractive.
671
672 Returns:
673 True|False: True if process completed successfully, False if error
674 occurred.
675 """
676 result = True
677 usb_dev = self._probe_host_usb_dev()
678 if not usb_dev:
679 self._logger.error("No usb device connected to servo")
680 return False
681 # Create TempDirectory
682 tmpdir = tempfile.mkdtemp()
683 if tmpdir:
684 # Mount drive to tmpdir.
685 partition_1 = "%s1" % usb_dev
686 rc = subprocess.call(["mount", partition_1, tmpdir])
687 if rc == 0:
688 # Create file 'non_interactive'
689 non_interactive_file = os.path.join(tmpdir, "non_interactive")
690 try:
691 open(non_interactive_file, "w").close()
692 except IOError as e:
693 self._logger.error("Failed to create file %s : %s ( %d )",
694 non_interactive_file, e.strerror, e.errno)
695 result = False
696 except BaseException as e:
697 self._logger.error("Unexpected Exception creating file %s : %s",
698 non_interactive_file, str(e))
699 result = False
700 # Unmount drive regardless if file creation worked or not.
701 rc = subprocess.call(["umount", partition_1])
702 if rc != 0:
703 self._logger.error("Failed to unmount USB Device")
704 result = False
705 else:
706 self._logger.error("Failed to mount USB Device")
707 result = False
708
709 # Delete tmpdir. May throw exception if 'umount' failed.
710 try:
711 os.rmdir(tmpdir)
712 except OSError as e:
713 self._logger.error("Failed to remove temp directory %s : %s",
714 tmpdir, str(e))
715 return False
716 except BaseException as e:
717 self._logger.error("Unexpected Exception removing tempdir %s : %s",
718 tmpdir, str(e))
719 return False
720 else:
721 self._logger.error("Failed to create temp directory.")
722 return False
723 return result
724
Todd Broch352b4b22013-03-22 09:48:40 -0700725 def set_get_all(self, cmds):
726 """Set &| get one or more control values.
727
728 Args:
729 cmds: list of control[:value] to get or set.
730
731 Returns:
732 rv: list of responses from calling get or set methods.
733 """
734 rv = []
735 for cmd in cmds:
736 if ':' in cmd:
737 (control, value) = cmd.split(':')
738 rv.append(self.set(control, value))
739 else:
740 rv.append(self.get(cmd))
741 return rv
742
Todd Broche505b8d2011-03-21 18:19:54 -0700743 def get(self, name):
744 """Get control value.
745
746 Args:
747 name: name string of control
748
749 Returns:
750 Response from calling drv get method. Value is reformatted based on
751 control's dictionary parameters
752
753 Raises:
754 HwDriverError: Error occurred while using drv
755 """
756 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700757 if name == 'serialname':
758 if self._serialname:
759 return self._serialname
760 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700761 (param, drv) = self._get_param_drv(name)
762 try:
763 val = drv.get()
764 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800765 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700766 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700767 except AttributeError, error:
768 self._logger.error("Getting %s: %s" % (name, error))
769 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800770 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700771 self._logger.error("Getting %s" % (name))
772 raise
Todd Brochd6061672012-05-11 15:52:47 -0700773
Todd Broche505b8d2011-03-21 18:19:54 -0700774 def get_all(self, verbose):
775 """Get all controls values.
776
777 Args:
778 verbose: Boolean on whether to return doc info as well
779
780 Returns:
781 string creating from trying to get all values of all controls. In case of
782 error attempting access to control, response is 'ERR'.
783 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800784 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700785 for name in self._syscfg.syscfg_dict['control']:
786 self._logger.debug("name = %s" %name)
787 try:
788 value = self.get(name)
789 except Exception:
790 value = "ERR"
791 pass
792 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800793 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700794 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800795 rsp.append("%s:%s" % (name, value))
796 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700797
798 def set(self, name, wr_val_str):
799 """Set control.
800
801 Args:
802 name: name string of control
803 wr_val_str: value string to write. Can be integer, float or a
804 alpha-numerical that is mapped to a integer or float.
805
806 Raises:
807 HwDriverError: Error occurred while using driver
808 """
809 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
810 (params, drv) = self._get_param_drv(name, False)
811 wr_val = self._syscfg.resolve_val(params, wr_val_str)
812 try:
813 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800814 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700815 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
816 raise
817 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
818 # & client I still have to return something to appease the
819 # marshall/unmarshall
820 return True
821
Todd Brochd6061672012-05-11 15:52:47 -0700822 def hwinit(self, verbose=False):
823 """Initialize all controls.
824
825 These values are part of the system config XML files of the form
826 init=<value>. This command should be used by clients wishing to return the
827 servo and DUT its connected to a known good/safe state.
828
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800829 Note that initialization errors are ignored (as in some cases they could
830 be caused by DUT firmware deficiencies). This might need to be fine tuned
831 later.
832
Todd Brochd6061672012-05-11 15:52:47 -0700833 Args:
834 verbose: boolean, if True prints info about control initialized.
835 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800836
837 Returns:
838 This function is called across RPC and as such is expected to return
839 something unless transferring 'none' across is allowed. Hence adding a
840 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700841 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800842 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800843 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700844 # Workaround for bug chrome-os-partner:42349. Without this check, the
845 # gpio will briefly pulse low if we set it from high to high.
846 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700847 self.set(control_name, value)
848 if verbose:
849 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800850 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800851 self._logger.error("Problem initializing %s -> %s :: %s",
852 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -0800853
854 # Init keyboard after all the intefaces are up.
855 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800856 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800857
Todd Broche505b8d2011-03-21 18:19:54 -0700858 def echo(self, echo):
859 """Dummy echo function for testing/examples.
860
861 Args:
862 echo: string to echo back to client
863 """
864 self._logger.debug("echo(%s)" % (echo))
865 return "ECH0ING: %s" % (echo)
866
J. Richard Barnettee2820552013-03-14 16:13:46 -0700867 def get_board(self):
868 """Return the board specified at startup, if any."""
869 return self._board
870
Simran Basia23c1392013-08-06 14:59:10 -0700871 def get_version(self):
872 """Get servo board version."""
873 return self._version
874
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800875 def power_long_press(self):
876 """Simulate a long power button press."""
877 # After a long power press, the EC may ignore the next power
878 # button press (at least on Alex). To guarantee that this
879 # won't happen, we need to allow the EC one second to
880 # collect itself.
881 self._keyboard.power_long_press()
882 return True
883
884 def power_normal_press(self):
885 """Simulate a normal power button press."""
886 self._keyboard.power_normal_press()
887 return True
888
889 def power_short_press(self):
890 """Simulate a short power button press."""
891 self._keyboard.power_short_press()
892 return True
893
894 def power_key(self, secs=''):
895 """Simulate a power button press.
896
897 Args:
898 secs: Time in seconds to simulate the keypress.
899 """
900 self._keyboard.power_key(secs)
901 return True
902
903 def ctrl_d(self, press_secs=''):
904 """Simulate Ctrl-d simultaneous button presses."""
905 self._keyboard.ctrl_d(press_secs)
906 return True
907
Victor Dodone539cea2016-03-29 18:50:17 -0700908 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800909 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -0700910 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800911 return True
912
913 def ctrl_enter(self, press_secs=''):
914 """Simulate Ctrl-enter simultaneous button presses."""
915 self._keyboard.ctrl_enter(press_secs)
916 return True
917
918 def d_key(self, press_secs=''):
919 """Simulate Enter key button press."""
920 self._keyboard.d_key(press_secs)
921 return True
922
923 def ctrl_key(self, press_secs=''):
924 """Simulate Enter key button press."""
925 self._keyboard.ctrl_key(press_secs)
926 return True
927
928 def enter_key(self, press_secs=''):
929 """Simulate Enter key button press."""
930 self._keyboard.enter_key(press_secs)
931 return True
932
933 def refresh_key(self, press_secs=''):
934 """Simulate Refresh key (F3) button press."""
935 self._keyboard.refresh_key(press_secs)
936 return True
937
938 def ctrl_refresh_key(self, press_secs=''):
939 """Simulate Ctrl and Refresh (F3) simultaneous press.
940
941 This key combination is an alternative of Space key.
942 """
943 self._keyboard.ctrl_refresh_key(press_secs)
944 return True
945
946 def imaginary_key(self, press_secs=''):
947 """Simulate imaginary key button press.
948
949 Maps to a key that doesn't physically exist.
950 """
951 self._keyboard.imaginary_key(press_secs)
952 return True
953
Todd Brochdbb09982011-10-02 07:14:26 -0700954
Todd Broche505b8d2011-03-21 18:19:54 -0700955def test():
956 """Integration testing.
957
958 TODO(tbroch) Enhance integration test and add unittest (see mox)
959 """
960 logging.basicConfig(level=logging.DEBUG,
961 format="%(asctime)s - %(name)s - " +
962 "%(levelname)s - %(message)s")
963 # configure server & listen
964 servod_obj = Servod(1)
965 # 4 == number of interfaces on a FT4232H device
966 for i in xrange(4):
967 if i == 1:
968 # its an i2c interface ... see __init__ for details and TODO to make
969 # this configureable
970 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
971 else:
972 # its a gpio interface
973 servod_obj._interface_list[i].wr_rd(0)
974
975 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
976 allow_none=True)
977 server.register_introspection_functions()
978 server.register_multicall_functions()
979 server.register_instance(servod_obj)
980 logging.info("Listening on localhost port 9999")
981 server.serve_forever()
982
983if __name__ == "__main__":
984 test()
985
986 # simple client transaction would look like
987 """
988 remote_uri = 'http://localhost:9999'
989 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
990 send_str = "Hello_there"
991 print "Sent " + send_str + ", Recv " + client.echo(send_str)
992 """