blob: 4dd94b9e9aae576054cea4cb5d410572b83ede04 [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."""
Kevin Cheng5595b342016-09-29 15:51:01 -07005import contextlib
Kevin Chengc49494e2016-07-25 12:13:38 -07006import datetime
7import fcntl
Simran Basia9f41032012-05-11 14:21:58 -07008import fnmatch
Todd Broche505b8d2011-03-21 18:19:54 -07009import logging
Simran Basia9f41032012-05-11 14:21:58 -070010import os
Kevin Chengc49494e2016-07-25 12:13:38 -070011import random
Aseda Aboagye1d8477b2017-05-10 17:24:31 -070012import re
Simran Basia9f41032012-05-11 14:21:58 -070013import shutil
Todd Broche505b8d2011-03-21 18:19:54 -070014import SimpleXMLRPCServer
Simran Basia9f41032012-05-11 14:21:58 -070015import subprocess
16import tempfile
Todd Broch7a91c252012-02-03 12:37:45 -080017import time
Simran Basia9f41032012-05-11 14:21:58 -070018import urllib
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070019import usb
Todd Broche505b8d2011-03-21 18:19:54 -070020
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080021import drv as servo_drv
Aaron.Chuang88eff332014-07-31 08:32:00 +080022import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070023import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070024import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070025import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080026import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070027import ftdigpio
28import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070029import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070030import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080031import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080032import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070033import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070034import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080035import stm32gpio
36import stm32i2c
37import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070038
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080039HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080040
Todd Broche505b8d2011-03-21 18:19:54 -070041MAX_I2C_CLOCK_HZ = 100000
42
Kevin Cheng5595b342016-09-29 15:51:01 -070043# It takes about 16-17 seconds for the entire probe usb device method,
44# let's wait double plus some buffer.
45_MAX_USB_LOCK_WAIT = 40
Todd Brochdbb09982011-10-02 07:14:26 -070046
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070047
Todd Broche505b8d2011-03-21 18:19:54 -070048class ServodError(Exception):
49 """Exception class for servod."""
50
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070051
Todd Broche505b8d2011-03-21 18:19:54 -070052class Servod(object):
53 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070054 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070055 _USB_POWEROFF_DELAY = 2
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070056 _HTTP_PREFIX = 'http://'
57 _USB_J3 = 'usb_mux_sel1'
58 _USB_J3_TO_SERVO = 'servo_sees_usbkey'
59 _USB_J3_TO_DUT = 'dut_sees_usbkey'
60 _USB_J3_PWR = 'prtctl4_pwren'
61 _USB_J3_PWR_ON = 'on'
62 _USB_J3_PWR_OFF = 'off'
63 _USB_LOCK_FILE = '/var/lib/servod/lock_file'
Simran Basia9f41032012-05-11 14:21:58 -070064
Kevin Cheng4b4f0022016-09-09 02:37:07 -070065 # This is the key to get the main serial used in the _serialnames dict.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070066 MAIN_SERIAL = 'main'
67 SERVO_MICRO_SERIAL = 'servo_micro'
68 CCD_SERIAL = 'ccd'
Kevin Cheng4b4f0022016-09-09 02:37:07 -070069
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070070 def init_servo_interfaces(self, vendor, product, serialname, interfaces):
Kevin Chengdc3befd2016-07-15 12:34:00 -070071 """Init the servo interfaces with the given interfaces.
72
73 We don't use the self._{vendor,product,serialname} attributes because we
74 want to allow other callers to initialize other interfaces that may not
75 be associated with the initialized attributes (e.g. a servo v4 servod object
76 that wants to also initialize a servo micro interface).
77
78 Args:
79 vendor: USB vendor id of FTDI device.
80 product: USB product id of FTDI device.
81 serialname: String of device serialname/number as defined in FTDI
82 eeprom.
83 interfaces: List of strings of interface types the server will
84 instantiate.
85
86 Raises:
87 ServodError if unable to locate init method for particular interface.
88 """
Mary Ruthven13389642017-02-14 12:15:34 -080089 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070090 device = (vendor, product, serialname)
Mary Ruthven13389642017-02-14 12:15:34 -080091 if device not in self._devices:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070092 self._devices.append(device)
Mary Ruthven13389642017-02-14 12:15:34 -080093
Kevin Chengdc3befd2016-07-15 12:34:00 -070094 # Extend the interface list if we need to.
95 interfaces_len = len(interfaces)
96 interface_list_len = len(self._interface_list)
97 if interfaces_len > interface_list_len:
98 self._interface_list += [None] * (interfaces_len - interface_list_len)
99
Kevin Chengdc3befd2016-07-15 12:34:00 -0700100 for i, interface in enumerate(interfaces):
101 is_ftdi_interface = False
102 if type(interface) is dict:
103 name = interface['name']
104 # Store interface index for those that care about it.
105 interface['index'] = i
106 elif type(interface) is str and interface != 'dummy':
107 name = interface
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700108 # It's a FTDI related interface. #0 is reserved for no use.
109 interface = ((i - 1) % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
Kevin Chengdc3befd2016-07-15 12:34:00 -0700110 is_ftdi_interface = True
111 elif type(interface) is str and interface == 'dummy':
112 # 'dummy' reserves the interface for future use. Typically the
113 # interface will be managed by external third-party tools like
114 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
115 # it serves as a placeholder for servo micro interfaces.
116 continue
117 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700118 raise ServodError('Illegal interface type %s' % type(interface))
Kevin Chengdc3befd2016-07-15 12:34:00 -0700119
120 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700121 product_increment = 0
122 if is_ftdi_interface:
123 product_increment = (i - 1) / ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE
124 if product_increment:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700125 self._logger.info('Use the next FTDI part @ pid = 0x%04x',
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700126 product + product_increment)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700127
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700128 self._logger.info('Initializing interface %d to %s', i, name)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700129 try:
130 func = getattr(self, '_init_%s' % name)
131 except AttributeError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700132 raise ServodError('Unable to locate init for interface %s' % name)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700133 result = func(vendor, product + product_increment, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700134
135 if isinstance(result, tuple):
136 result_len = len(result)
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700137 self._interface_list[i:(i + result_len)] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700138 else:
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700139 self._interface_list[i] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700140
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700141 def __init__(self, config, vendor, product, serialname=None, interfaces=None,
142 board='', version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700143 """Servod constructor.
144
145 Args:
146 config: instance of SystemConfig containing all controls for
147 particular Servod invocation
148 vendor: usb vendor id of FTDI device
149 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700150 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700151 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700152 version: String. Servo board version. Examples: servo_v1, servo_v2,
153 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800154 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700155 sending keyboard commands to DUTs that do not have built in
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700156 keyboards. Used in FAFT tests. Use None for on board AVR MCU.
157 e.g. '/dev/ttyUSB0' or None.
Todd Brochdbb09982011-10-02 07:14:26 -0700158
159 Raises:
160 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700161 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700162 self._logger = logging.getLogger('Servod')
163 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700164 self._vendor = vendor
165 self._product = product
Mary Ruthven13389642017-02-14 12:15:34 -0800166 self._devices = []
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700167 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700168 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700169 # Hold the last image path so we can reduce downloads to the usb device.
170 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700171 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
172 # interfaces are mapped to
173 self._interface_list = []
174 # Dict of Dict to map control name, function name to to tuple (params, drv)
175 # Ex) _drv_dict[name]['get'] = (params, drv)
176 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700177 self._board = board
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700178 self._base_board = ''
Simran Basia23c1392013-08-06 14:59:10 -0700179 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800180 self._usbkm232 = usbkm232
Kevin Chengc49494e2016-07-25 12:13:38 -0700181 # Seed the random generator with the serial to differentiate from other
182 # servod processes.
183 random.seed(serialname if serialname else time.time())
Todd Brochdbb09982011-10-02 07:14:26 -0700184 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700185 try:
186 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
187 except KeyError:
188 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Dino Lic89d8c82018-01-11 09:56:47 +0800189 self._interfaces = interfaces
Todd Brochdbb09982011-10-02 07:14:26 -0700190
Kevin Chengdc3befd2016-07-15 12:34:00 -0700191 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700192 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800193
Mary Ruthven13389642017-02-14 12:15:34 -0800194 def reinitialize(self):
195 """Reinitialize all interfaces that support reinitialization"""
196
197 # If all of the devices that were originally connected are not connected
198 # now, wait up to max_tries * sleep_time for the devices to reconnect
199 max_tries = 10
200 sleep_time = 0.5
201 for i in range(max_tries):
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700202 for vid, pid, serialname in self._devices:
203 for current in usb.core.find(idVendor=vid, idProduct=pid,
204 find_all=True):
Mary Ruthvena8dcf912018-07-25 16:48:27 -0700205 current_serial = usb.util.get_string(current, 256,
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700206 current.iSerialNumber)
207 if not serialname or serialname == current_serial:
208 # This device still available
Mary Ruthven13389642017-02-14 12:15:34 -0800209 break
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700210 else:
211 self._logger.warn('Servo USB device not found: %x:%x serial:%s', vid,
212 pid, serialname)
213 break
214 else:
215 # All the devices found. Reinitialize the interfaces...
216 break
217 time.sleep(sleep_time)
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -0700218 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700219 raise ServodError('Servo USB device not found during reinitialize')
Mary Ruthven13389642017-02-14 12:15:34 -0800220
221 for i, interface in enumerate(self._interface_list):
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700222 if hasattr(interface, 'reinitialize'):
223 interface.reinitialize()
224 else:
225 self._logger.debug('interface %d has no reset functionality', i)
Mary Ruthven13389642017-02-14 12:15:34 -0800226
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700227 def get_servo_interfaces(self, position, size):
228 """Get the list of servo interfaces.
229
230 Args:
231 position: The index the first interface to get.
232 size: The number of the interfaces.
233 """
234 return self._interface_list[position:(position + size)]
235
236 def set_servo_interfaces(self, position, interfaces):
237 """Set the list of servo interfaces.
238
239 Args:
240 position: The index the first interface to set.
241 interfaces: The list of interfaces to set.
242 """
243 size = len(interfaces)
244 self._interface_list[position:(position + size)] = interfaces
245
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800246 def _init_keyboard_handler(self, servo, board=''):
247 """Initialize the correct keyboard handler for board.
248
Kevin Chengdc3befd2016-07-15 12:34:00 -0700249 Args:
250 servo: servo object.
251 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800252
Kevin Chengdc3befd2016-07-15 12:34:00 -0700253 Returns:
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700254 keyboard handler object, or None if no keyboard supported.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800255 """
256 if board == 'parrot':
257 return keyboard_handlers.ParrotHandler(servo)
258 elif board == 'stout':
259 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800260 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700261 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy', 'sumo',
262 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
Shelley Chen94cd2352017-07-26 11:36:45 -0700263 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800264 if self._usbkm232 is None:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700265 logging.info('No device path specified for usbkm232 handler. Use '
266 'the servo atmega chip to handle.')
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700267
Danny Chan662b6022015-11-04 17:34:53 -0800268 # Use servo onboard keyboard emulator.
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700269 if not self._syscfg.is_control('atmega_rst'):
270 logging.warn('No atmega in servo board. So no keyboard support.')
271 return None
272
Nick Sanders78423782015-11-09 14:28:19 -0800273 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800274 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800275 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800276 self._usbkm232 = self.get('atmega_pty')
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700277
Kevin Cheng810fc782016-11-01 12:36:46 -0700278 # We don't need to set the atmega uart settings if we're a servo v4.
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700279 if 'servo_v4' not in self._version:
Kevin Cheng810fc782016-11-01 12:36:46 -0700280 self.set('atmega_baudrate', '9600')
281 self.set('atmega_bits', 'eight')
282 self.set('atmega_parity', 'none')
283 self.set('atmega_sbits', 'one')
284 self.set('usb_mux_sel4', 'on')
285 self.set('usb_mux_oe4', 'on')
286 # Allow atmega bootup time.
287 time.sleep(1.0)
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700288
Danny Chan662b6022015-11-04 17:34:53 -0800289 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800290 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
291 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800292 # The following boards don't use Chrome EC.
293 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
294 return keyboard_handlers.MatrixKeyboardHandler(servo)
295 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800296
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700297 def close(self):
298 """Servod turn down logic."""
299 for i, interface in enumerate(self._interface_list):
300 self._logger.info('Turning down interface %d' % i)
301 if hasattr(interface, 'close'):
302 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800303
Kevin Chengdc3befd2016-07-15 12:34:00 -0700304 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700305 """Dummy interface for ftdi devices.
306
307 This is a dummy function specifically for ftdi devices to not initialize
308 anything but to help pad the interface list.
309
310 Returns:
311 None.
312 """
313 return None
314
Kevin Chengdc3befd2016-07-15 12:34:00 -0700315 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700316 """Initialize gpio driver interface and open for use.
317
318 Args:
319 interface: interface number of FTDI device to use.
320
321 Returns:
322 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700323
324 Raises:
325 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700326 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700327 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700328 try:
329 fobj.open()
330 except ftdigpio.FgpioError as e:
331 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
332
Todd Broche505b8d2011-03-21 18:19:54 -0700333 return fobj
334
Kevin Chengdc3befd2016-07-15 12:34:00 -0700335 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800336 """Initialize stm32 uart interface and open for use
337
338 Note, the uart runs in a separate thread. Users wishing to
339 interact with it will query control for the pty's pathname and connect
340 with their favorite console program. For example:
341 cu -l /dev/pts/22
342
343 Args:
344 interface: dict of interface parameters.
345
346 Returns:
347 Instance object of interface
348
349 Raises:
350 ServodError: Raised on init failure.
351 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700352 self._logger.info('Suart: interface: %s' % interface)
353 sobj = stm32uart.Suart(vendor, product, interface['interface'], serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800354
355 try:
356 sobj.run()
357 except stm32uart.SuartError as e:
358 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
359
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700360 self._logger.info('%s' % sobj.get_pty())
Nick Sanders97bc4462016-01-04 15:37:31 -0800361 return sobj
362
Kevin Chengdc3befd2016-07-15 12:34:00 -0700363 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800364 """Initialize stm32 gpio interface.
365 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700366 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800367
368 Returns:
369 Instance object of interface
370
371 Raises:
372 SgpioError: Raised on init failure.
373 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700374 interface_number = interface
375 # Interface could be a dict.
376 if type(interface) is dict:
377 interface_number = interface['interface']
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700378 self._logger.info('Sgpio: interface: %s' % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700379 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800380
Kevin Chengdc3befd2016-07-15 12:34:00 -0700381 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800382 """Initialize stm32 USB to I2C bridge interface and open for use
383
384 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700385 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800386
387 Returns:
388 Instance object of interface.
389
390 Raises:
391 Si2cError: Raised on init failure.
392 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700393 self._logger.info('Si2cBus: interface: %s' % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800394 port = interface.get('port', 0)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700395 return stm32i2c.Si2cBus(vendor, product, interface['interface'], port=port,
396 serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800397
Kevin Chengdc3befd2016-07-15 12:34:00 -0700398 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800399 """Initalize beaglebone ADC interface."""
400 return bbadc.BBadc()
401
Kevin Chengdc3befd2016-07-15 12:34:00 -0700402 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700403 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700404 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700405
Kevin Chengdc3befd2016-07-15 12:34:00 -0700406 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700407 """Initialize i2c interface and open for use.
408
409 Args:
410 interface: interface number of FTDI device to use
411
412 Returns:
413 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700414
415 Raises:
416 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700417 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700418 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700419 try:
420 fobj.open()
421 except ftdii2c.Fi2cError as e:
422 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
423
Todd Broche505b8d2011-03-21 18:19:54 -0700424 # Set the frequency of operation of the i2c bus.
425 # TODO(tbroch) make configureable
426 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700427
Todd Broche505b8d2011-03-21 18:19:54 -0700428 return fobj
429
Simran Basie750a342013-03-12 13:45:26 -0700430 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
431 def _init_bb_i2c(self, interface):
432 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700433 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700434
Kevin Chengdc3befd2016-07-15 12:34:00 -0700435 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800436 """Initalize Linux i2c-dev interface."""
437 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
438
Kevin Chengdc3befd2016-07-15 12:34:00 -0700439 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700440 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700441
442 Note, the uart runs in a separate thread (pthreads). Users wishing to
443 interact with it will query control for the pty's pathname and connect
444 with there favorite console program. For example:
445 cu -l /dev/pts/22
446
447 Args:
448 interface: interface number of FTDI device to use
449
450 Returns:
451 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700452
453 Raises:
454 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700455 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700456 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700457 try:
458 fobj.run()
459 except ftdiuart.FuartError as e:
460 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
461
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700462 self._logger.info('%s' % fobj.get_pty())
Todd Broch47c43f42011-05-26 15:11:31 -0700463 return fobj
464
Simran Basie750a342013-03-12 13:45:26 -0700465 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700466 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700467 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700468 logging.debug('UART INTERFACE: %s', interface)
469 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700470
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700471 def _init_ftdi_gpiouart(self, vendor, product, serialname, interface):
Todd Broch888da782011-10-07 14:29:09 -0700472 """Initialize special gpio + uart interface and open for use
473
474 Note, the uart runs in a separate thread (pthreads). Users wishing to
475 interact with it will query control for the pty's pathname and connect
476 with there favorite console program. For example:
477 cu -l /dev/pts/22
478
479 Args:
480 interface: interface number of FTDI device to use
481
482 Returns:
483 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700484
485 Raises:
486 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700487 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700488 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700489 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700490 try:
491 fuart.run()
492 except ftdiuart.FuartError as e:
493 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
494
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700495 self._logger.info('uart pty: %s' % fuart.get_pty())
Todd Broch888da782011-10-07 14:29:09 -0700496 return fgpio, fuart
497
Kevin Chengdc3befd2016-07-15 12:34:00 -0700498 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800499 """Initialize EC-3PO console interpreter interface.
500
501 Args:
502 interface: A dictionary representing the interface.
503
504 Returns:
505 An EC3PO object representing the EC-3PO interface or None if there's no
506 interface for the USB PD UART.
507 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700508 raw_uart_name = interface['raw_pty']
Nick Sanders116ed9e2018-03-09 19:05:16 -0800509 raw_uart_source = interface['source']
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700510 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800511 raw_ec_uart = self.get(raw_uart_name)
Nick Sanders116ed9e2018-03-09 19:05:16 -0800512 return ec3po_interface.EC3PO(raw_ec_uart, raw_uart_source)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800513 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700514 # The overlay doesn't have the raw PTY defined, therefore we can skip
515 # initializing this interface since no control relies on it.
516 self._logger.debug(
517 'Skip initializing EC3PO for %s, no control specified.',
518 raw_uart_name)
519 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800520
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800521 def _camel_case(self, string):
522 output = ''
523 for s in string.split('_'):
524 if output:
525 output += s.capitalize()
526 else:
527 output = s
528 return output
529
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700530 def clear_cached_drv(self):
531 """Clear the cached drivers.
532
533 The drivers are cached in the Dict _drv_dict when a control is got or set.
534 When the servo interfaces are relocated, the cached values may become wrong.
535 Should call this method to clear the cached values.
536 """
537 self._drv_dict = {}
538
Todd Broche505b8d2011-03-21 18:19:54 -0700539 def _get_param_drv(self, control_name, is_get=True):
540 """Get access to driver for a given control.
541
542 Note, some controls have different parameter dictionaries for 'getting' the
543 control's value versus 'setting' it. Boolean is_get distinguishes which is
544 being requested.
545
546 Args:
547 control_name: string name of control
548 is_get: boolean to determine
549
550 Returns:
551 tuple (param, drv) where:
552 param: param dictionary for control
553 drv: instance object of driver for particular control
554
555 Raises:
556 ServodError: Error occurred while examining params dict
557 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700558 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700559 # if already setup just return tuple from driver dict
560 if control_name in self._drv_dict:
561 if is_get and ('get' in self._drv_dict[control_name]):
562 return self._drv_dict[control_name]['get']
563 if not is_get and ('set' in self._drv_dict[control_name]):
564 return self._drv_dict[control_name]['set']
565
566 params = self._syscfg.lookup_control_params(control_name, is_get)
567 if 'drv' not in params:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700568 self._logger.error('Unable to determine driver for %s' % control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700569 raise ServodError("'drv' key not found in params dict")
570 if 'interface' not in params:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700571 self._logger.error('Unable to determine interface for %s' % control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700572 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700573
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700574 # Find the candidate servos. Using servo_v4 with a servo_micro connected as
575 # an example, the following shows the priority for selecting the interface.
576 #
577 # 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
578 # 2. servo_micro_interface
579 # 3. servo_v4_interface
580 # 4. Fallback to the default, interface.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700581 candidates = [self._version]
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700582 candidates.extend(reversed(self._version.split('_with_')))
583
584 interface_id = 'unknown'
585 for c in candidates:
586 interface_name = '%s_interface' % c
587 if interface_name in params:
588 interface_id = params[interface_name]
589 self._logger.debug('Using %s parameter.' % interface_name)
590 break
591
592 # Use the default interface value if we couldn't find a more specific
593 # interface.
594 if interface_id == 'unknown':
595 interface_id = params['interface']
596 self._logger.debug('Using default interface parameter.')
597
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800598 if interface_id == 'servo':
599 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700600 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700601 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800602 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700603
Todd Broche505b8d2011-03-21 18:19:54 -0700604 drv_name = params['drv']
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800605 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800606 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700607 drv = drv_class(interface, params)
608 if control_name not in self._drv_dict:
609 self._drv_dict[control_name] = {}
610 if is_get:
611 self._drv_dict[control_name]['get'] = (params, drv)
612 else:
613 self._drv_dict[control_name]['set'] = (params, drv)
614 return (params, drv)
615
616 def doc_all(self):
617 """Return all documenation for controls.
618
619 Returns:
620 string of <doc> text in config file (xml) and the params dictionary for
621 all controls.
622
623 For example:
624 warm_reset :: Reset the device warmly
625 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
626 """
627 return self._syscfg.display_config()
628
629 def doc(self, name):
630 """Retreive doc string in system config file for given control name.
631
632 Args:
633 name: name string of control to get doc string
634
635 Returns:
636 doc string of name
637
638 Raises:
639 NameError: if fails to locate control
640 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700641 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700642 if self._syscfg.is_control(name):
643 return self._syscfg.get_control_docstring(name)
644 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700645 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700646
Fang Deng90377712013-06-03 15:51:48 -0700647 def _switch_usbkey(self, mux_direction):
648 """Connect USB flash stick to either servo or DUT.
649
650 This function switches 'usb_mux_sel1' to provide electrical
651 connection between the USB port J3 and either servo or DUT side.
652
653 Switching the usb mux is accompanied by powercycling
654 of the USB stick, because it sometimes gets wedged if the mux
655 is switched while the stick power is on.
656
657 Args:
658 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
659 """
660 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
661 time.sleep(self._USB_POWEROFF_DELAY)
662 self.set(self._USB_J3, mux_direction)
663 time.sleep(self._USB_POWEROFF_DELAY)
664 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
665 if mux_direction == self._USB_J3_TO_SERVO:
666 time.sleep(self._USB_DETECTION_DELAY)
667
Simran Basia9f41032012-05-11 14:21:58 -0700668 def _get_usb_port_set(self):
669 """Gets a set of USB disks currently connected to the system
670
671 Returns:
672 A set of USB disk paths.
673 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700674 usb_set = fnmatch.filter(os.listdir('/dev/'), 'sd[a-z]')
675 return set(['/dev/' + dev for dev in usb_set])
Simran Basia9f41032012-05-11 14:21:58 -0700676
Kevin Cheng5595b342016-09-29 15:51:01 -0700677 @contextlib.contextmanager
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800678 def _block_other_servod(self, timeout):
Kevin Chengc49494e2016-07-25 12:13:38 -0700679 """Block other servod processes by locking a file.
680
681 To enable multiple servods processes to safely probe_host_usb_dev, we use
682 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700683 for a usb device. This will be a context manager that will return
684 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700685
686 If the lock file exists, we open it and try to lock it.
687 - If another servod processes has locked it already, we'll sleep a random
688 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700689 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700690
Kevin Cheng5595b342016-09-29 15:51:01 -0700691 - If we're able to lock the file, we'll yield that the block was successful
692 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700693
694 This blocking behavior is only enabled if the lock file exists, if it
695 doesn't, then we pretend the block was successful.
696
Kevin Cheng5595b342016-09-29 15:51:01 -0700697 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800698 timeout: Max waiting time for the block to succeed; 0 to wait forever.
Kevin Chengc49494e2016-07-25 12:13:38 -0700699 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700700 if not os.path.exists(self._USB_LOCK_FILE):
701 # No lock file so we'll pretend the block was a success.
702 yield True
703 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700704 start_time = datetime.datetime.now()
705 while True:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800706 with open(self._USB_LOCK_FILE, 'w') as lock_file:
Kevin Cheng5595b342016-09-29 15:51:01 -0700707 try:
708 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
709 yield True
710 fcntl.flock(lock_file, fcntl.LOCK_UN)
711 break
712 except IOError:
713 current_time = datetime.datetime.now()
714 current_wait_time = (current_time - start_time).total_seconds()
715 if timeout and current_wait_time > timeout:
716 yield False
717 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700718 # Sleep random amount.
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800719 sleep_time = random.random()
720 logging.debug('sleep %.04fs and try obtaining a lock...', sleep_time)
721 time.sleep(sleep_time)
Kevin Chengc49494e2016-07-25 12:13:38 -0700722
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700723 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700724 """Toggle the usb power safely.
725
726 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700727
728 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700729 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700730 timeout: Timeout to wait for blocking other servod processes, default is
731 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700732
Kevin Cheng5595b342016-09-29 15:51:01 -0700733 Returns:
734 An empty string to appease the xmlrpc gods.
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800735
736 Raises:
737 ServodError if failed to obtain a lock.
Kevin Cheng5595b342016-09-29 15:51:01 -0700738 """
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800739 with self._block_other_servod(timeout=timeout) as block_success:
740 if not block_success:
741 raise ServodError('Timed out obtaining a lock to block other servod')
742
Kevin Cheng5595b342016-09-29 15:51:01 -0700743 if power_state != self.get(self._USB_J3_PWR):
744 self.set(self._USB_J3_PWR, power_state)
745 return ''
746
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700747 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700748 """Toggle the usb direction safely.
749
750 We'll make sure we're the only servod process toggling the usbkey direction.
751
752 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800753 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700754 timeout: Timeout to wait for blocking other servod processes, default is
755 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700756
757 Returns:
758 An empty string to appease the xmlrpc gods.
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800759
760 Raises:
761 ServodError if failed to obtain a lock.
Kevin Cheng5595b342016-09-29 15:51:01 -0700762 """
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800763 with self._block_other_servod(timeout=timeout) as block_success:
764 if not block_success:
765 raise ServodError('Timed out obtaining a lock to block other servod')
766
Kevin Cheng5595b342016-09-29 15:51:01 -0700767 self._switch_usbkey(mux_direction)
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800768
Kevin Cheng5595b342016-09-29 15:51:01 -0700769 return ''
770
771 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700772 """Probe the USB disk device plugged in the servo from the host side.
773
774 Method can fail by:
775 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700776 another servo unless _USB_LOCK_FILE exists on the servo host. If that
777 file exists, then it is safe to probe for usb devices among multiple
778 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700779 2) Finding multiple /dev/sdX and returning None.
780
Kevin Cheng5595b342016-09-29 15:51:01 -0700781 Args:
782 timeout: Timeout to wait for blocking other servod processes.
783
Simran Basia9f41032012-05-11 14:21:58 -0700784 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700785 USB disk path if one and only one USB disk path is found, otherwise an
786 empty string.
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800787
788 Raises:
789 ServodError if failed to obtain a lock.
Simran Basia9f41032012-05-11 14:21:58 -0700790 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700791 with self._block_other_servod(timeout=timeout) as block_success:
792 if not block_success:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800793 raise ServodError('Timed out obtaining a lock to block other servod')
Kevin Chengc49494e2016-07-25 12:13:38 -0700794
Kevin Cheng5595b342016-09-29 15:51:01 -0700795 original_value = self.get(self._USB_J3)
796 original_usb_power = self.get(self._USB_J3_PWR)
797 # Make the host unable to see the USB disk.
798 if (original_usb_power == self._USB_J3_PWR_ON and
799 original_value != self._USB_J3_TO_DUT):
800 self._switch_usbkey(self._USB_J3_TO_DUT)
801 no_usb_set = self._get_usb_port_set()
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800802 logging.debug('Device set when USB disk unplugged: %r', no_usb_set)
Simran Basia9f41032012-05-11 14:21:58 -0700803
Kevin Cheng5595b342016-09-29 15:51:01 -0700804 # Make the host able to see the USB disk.
805 self._switch_usbkey(self._USB_J3_TO_SERVO)
806 has_usb_set = self._get_usb_port_set()
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800807 logging.debug('Device set when USB disk plugged: %r', has_usb_set)
Fang Deng90377712013-06-03 15:51:48 -0700808
Kevin Cheng5595b342016-09-29 15:51:01 -0700809 # Back to its original value.
810 if original_value != self._USB_J3_TO_SERVO:
811 self._switch_usbkey(original_value)
812 if original_usb_power != self._USB_J3_PWR_ON:
813 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
814 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700815
Kevin Cheng5595b342016-09-29 15:51:01 -0700816 # Subtract the two sets to find the usb device.
817 diff_set = has_usb_set - no_usb_set
818 if len(diff_set) == 1:
819 return diff_set.pop()
820 else:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800821 logging.warn("Can't find the USB device. Diff: %r", diff_set)
Kevin Cheng5595b342016-09-29 15:51:01 -0700822 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700823
Kevin Cheng85831332016-10-13 13:14:44 -0700824 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700825 """Download image and save to the USB device found by probe_host_usb_dev.
826 If the image_path is a URL, it will download this url to the USB path;
827 otherwise it will simply copy the image_path's contents to the USB path.
828
829 Args:
830 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700831 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700832
833 Returns:
834 True|False: True if process completed successfully, False if error
835 occurred.
836 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
837 comment at the end of set().
838 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700839 self._logger.debug('image_path(%s)' % image_path)
840 self._logger.debug('Detecting USB stick device...')
Kevin Cheng85831332016-10-13 13:14:44 -0700841 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700842 if not usb_dev:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700843 self._logger.error('No usb device connected to servo')
Simran Basia9f41032012-05-11 14:21:58 -0700844 return False
845
Kevin Cheng9071ed92016-06-21 14:37:54 -0700846 # Let's check if we downloaded this last time and if so assume the image is
847 # still on the usb device and return True.
848 if self._image_path == image_path:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700849 self._logger.debug('Image already on USB device, skipping transfer')
Kevin Cheng9071ed92016-06-21 14:37:54 -0700850 return True
851
Simran Basia9f41032012-05-11 14:21:58 -0700852 try:
853 if image_path.startswith(self._HTTP_PREFIX):
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700854 self._logger.debug('Image path is a URL, downloading image')
Simran Basia9f41032012-05-11 14:21:58 -0700855 urllib.urlretrieve(image_path, usb_dev)
856 else:
857 shutil.copyfile(image_path, usb_dev)
858 except IOError as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700859 self._logger.error('Failed to transfer image to USB device: %s ( %s ) ',
Simran Basia9f41032012-05-11 14:21:58 -0700860 e.strerror, e.errno)
861 return False
862 except urllib.ContentTooShortError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700863 self._logger.error('Failed to download URL: %s to USB device: %s',
Simran Basia9f41032012-05-11 14:21:58 -0700864 image_path, usb_dev)
865 return False
866 except BaseException as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700867 self._logger.error('Unexpected exception downloading %s to %s: %s',
Simran Basia9f41032012-05-11 14:21:58 -0700868 image_path, usb_dev, str(e))
869 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800870 finally:
871 # We just plastered the partition table for a block device.
872 # Pass or fail, we mustn't go without telling the kernel about
873 # the change, or it will punish us with sporadic, hard-to-debug
874 # failures.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700875 subprocess.call(['sync'])
876 subprocess.call(['blockdev', '--rereadpt', usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700877 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700878 return True
879
880 def make_image_noninteractive(self):
881 """Makes the recovery image noninteractive.
882
883 A noninteractive image will reboot automatically after installation
884 instead of waiting for the USB device to be removed to initiate a system
885 reboot.
886
887 Mounts partition 1 of the image stored on usb_dev and creates a file
888 called "non_interactive" so that the image will become noninteractive.
889
890 Returns:
891 True|False: True if process completed successfully, False if error
892 occurred.
893 """
894 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700895 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700896 if not usb_dev:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700897 self._logger.error('No usb device connected to servo')
Simran Basia9f41032012-05-11 14:21:58 -0700898 return False
899 # Create TempDirectory
900 tmpdir = tempfile.mkdtemp()
901 if tmpdir:
902 # Mount drive to tmpdir.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700903 partition_1 = '%s1' % usb_dev
904 rc = subprocess.call(['mount', partition_1, tmpdir])
Simran Basia9f41032012-05-11 14:21:58 -0700905 if rc == 0:
906 # Create file 'non_interactive'
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700907 non_interactive_file = os.path.join(tmpdir, 'non_interactive')
Simran Basia9f41032012-05-11 14:21:58 -0700908 try:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700909 open(non_interactive_file, 'w').close()
Simran Basia9f41032012-05-11 14:21:58 -0700910 except IOError as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700911 self._logger.error('Failed to create file %s : %s ( %d )',
Simran Basia9f41032012-05-11 14:21:58 -0700912 non_interactive_file, e.strerror, e.errno)
913 result = False
914 except BaseException as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700915 self._logger.error('Unexpected Exception creating file %s : %s',
Simran Basia9f41032012-05-11 14:21:58 -0700916 non_interactive_file, str(e))
917 result = False
918 # Unmount drive regardless if file creation worked or not.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700919 rc = subprocess.call(['umount', partition_1])
Simran Basia9f41032012-05-11 14:21:58 -0700920 if rc != 0:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700921 self._logger.error('Failed to unmount USB Device')
Simran Basia9f41032012-05-11 14:21:58 -0700922 result = False
923 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700924 self._logger.error('Failed to mount USB Device')
Simran Basia9f41032012-05-11 14:21:58 -0700925 result = False
926
927 # Delete tmpdir. May throw exception if 'umount' failed.
928 try:
929 os.rmdir(tmpdir)
930 except OSError as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700931 self._logger.error('Failed to remove temp directory %s : %s', tmpdir,
932 str(e))
Simran Basia9f41032012-05-11 14:21:58 -0700933 return False
934 except BaseException as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700935 self._logger.error('Unexpected Exception removing tempdir %s : %s',
Simran Basia9f41032012-05-11 14:21:58 -0700936 tmpdir, str(e))
937 return False
938 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700939 self._logger.error('Failed to create temp directory.')
Simran Basia9f41032012-05-11 14:21:58 -0700940 return False
941 return result
942
Todd Broch352b4b22013-03-22 09:48:40 -0700943 def set_get_all(self, cmds):
944 """Set &| get one or more control values.
945
946 Args:
947 cmds: list of control[:value] to get or set.
948
949 Returns:
950 rv: list of responses from calling get or set methods.
951 """
952 rv = []
953 for cmd in cmds:
954 if ':' in cmd:
955 (control, value) = cmd.split(':')
956 rv.append(self.set(control, value))
957 else:
958 rv.append(self.get(cmd))
959 return rv
960
Aseda Aboagye6921f602017-08-01 14:45:38 -0700961 def get_serial_number(self, name):
962 """Returns the desired serial number from the serialnames dict.
963
964 Args:
965 name: A string which is the key into the _serialnames dictionary.
966
967 Returns:
968 A string containing the serial number or "unknown".
969 """
970 if not name:
971 name = 'main'
972
973 try:
974 return self._serialnames[name]
975 except KeyError:
976 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700977 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700978
Todd Broche505b8d2011-03-21 18:19:54 -0700979 def get(self, name):
980 """Get control value.
981
982 Args:
983 name: name string of control
984
985 Returns:
986 Response from calling drv get method. Value is reformatted based on
987 control's dictionary parameters
988
989 Raises:
990 HwDriverError: Error occurred while using drv
991 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700992 self._logger.debug('name(%s)' % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700993 # This route is to retrieve serialnames on servo v4, which
994 # connects to multiple servo-micros or CCD, like the controls,
995 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
996 # TODO(aaboagye): Refactor it.
997 if 'serialname' in name:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700998 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700999
Todd Broche505b8d2011-03-21 18:19:54 -07001000 (param, drv) = self._get_param_drv(name)
1001 try:
1002 val = drv.get()
1003 rd_val = self._syscfg.reformat_val(param, val)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001004 self._logger.debug('%s = %s' % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -07001005 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -07001006 except AttributeError, error:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001007 self._logger.error('Getting %s: %s' % (name, error))
Todd Brochfbc499d2011-06-16 16:09:58 -07001008 raise
Vic Yangbe6cf262012-09-10 10:40:56 +08001009 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001010 self._logger.error('Getting %s' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -07001011 raise
Todd Brochd6061672012-05-11 15:52:47 -07001012
Todd Broche505b8d2011-03-21 18:19:54 -07001013 def get_all(self, verbose):
1014 """Get all controls values.
1015
1016 Args:
1017 verbose: Boolean on whether to return doc info as well
1018
1019 Returns:
1020 string creating from trying to get all values of all controls. In case of
1021 error attempting access to control, response is 'ERR'.
1022 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -08001023 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -07001024 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001025 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -07001026 try:
1027 value = self.get(name)
1028 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001029 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -07001030 pass
1031 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001032 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -07001033 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001034 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -08001035 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -07001036
1037 def set(self, name, wr_val_str):
1038 """Set control.
1039
1040 Args:
1041 name: name string of control
1042 wr_val_str: value string to write. Can be integer, float or a
1043 alpha-numerical that is mapped to a integer or float.
1044
1045 Raises:
1046 HwDriverError: Error occurred while using driver
1047 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001048 self._logger.debug('name(%s) wr_val(%s)' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -07001049 (params, drv) = self._get_param_drv(name, False)
1050 wr_val = self._syscfg.resolve_val(params, wr_val_str)
1051 try:
1052 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +08001053 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001054 self._logger.error('Setting %s -> %s' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -07001055 raise
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +08001056 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
1057 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -07001058 # marshall/unmarshall
1059 return True
1060
Todd Brochd6061672012-05-11 15:52:47 -07001061 def hwinit(self, verbose=False):
1062 """Initialize all controls.
1063
1064 These values are part of the system config XML files of the form
1065 init=<value>. This command should be used by clients wishing to return the
1066 servo and DUT its connected to a known good/safe state.
1067
Vadim Bendeburybb51dd42013-01-31 13:47:46 -08001068 Note that initialization errors are ignored (as in some cases they could
1069 be caused by DUT firmware deficiencies). This might need to be fine tuned
1070 later.
1071
Todd Brochd6061672012-05-11 15:52:47 -07001072 Args:
1073 verbose: boolean, if True prints info about control initialized.
1074 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001075
1076 Returns:
1077 This function is called across RPC and as such is expected to return
1078 something unless transferring 'none' across is allowed. Hence adding a
1079 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -07001080 """
Todd Brochd9acf0a2012-12-05 13:43:06 -08001081 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -08001082 try:
John Carey6fe2bbf2015-08-31 16:13:03 -07001083 # Workaround for bug chrome-os-partner:42349. Without this check, the
1084 # gpio will briefly pulse low if we set it from high to high.
1085 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -07001086 self.set(control_name, value)
1087 if verbose:
1088 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -08001089 except Exception as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001090 self._logger.error('Problem initializing %s -> %s :: %s', control_name,
1091 value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -08001092
1093 # Init keyboard after all the intefaces are up.
1094 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001095 return True
Todd Broch3ec8df02012-11-20 10:53:03 -08001096
Dino Lic89d8c82018-01-11 09:56:47 +08001097 def ftdii2c(self, args):
1098 """Calling a method of Fi2c."""
1099 index = self._interfaces.index('ftdi_i2c')
1100 if index:
1101 obj = self._interface_list[index]
1102 func = getattr(obj, '%s' % args[0])
1103 func()
1104 return True
1105
1106 return False
1107
Todd Broche505b8d2011-03-21 18:19:54 -07001108 def echo(self, echo):
1109 """Dummy echo function for testing/examples.
1110
1111 Args:
1112 echo: string to echo back to client
1113 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001114 self._logger.debug('echo(%s)' % (echo))
1115 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -07001116
J. Richard Barnettee2820552013-03-14 16:13:46 -07001117 def get_board(self):
1118 """Return the board specified at startup, if any."""
1119 return self._board
1120
Wai-Hong Tam416cf612017-09-19 11:39:21 -07001121 def get_base_board(self):
1122 """Returns the board name of the base if present.
1123
1124 Returns:
1125 A string of the board name, or '' if not present.
1126 """
1127 # The value is set in servo_postinit.
1128 return self._base_board
1129
Simran Basia23c1392013-08-06 14:59:10 -07001130 def get_version(self):
1131 """Get servo board version."""
1132 return self._version
1133
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001134 def power_long_press(self):
1135 """Simulate a long power button press."""
1136 # After a long power press, the EC may ignore the next power
1137 # button press (at least on Alex). To guarantee that this
1138 # won't happen, we need to allow the EC one second to
1139 # collect itself.
1140 self._keyboard.power_long_press()
1141 return True
1142
1143 def power_normal_press(self):
1144 """Simulate a normal power button press."""
1145 self._keyboard.power_normal_press()
1146 return True
1147
1148 def power_short_press(self):
1149 """Simulate a short power button press."""
1150 self._keyboard.power_short_press()
1151 return True
1152
1153 def power_key(self, secs=''):
1154 """Simulate a power button press.
1155
1156 Args:
1157 secs: Time in seconds to simulate the keypress.
1158 """
1159 self._keyboard.power_key(secs)
1160 return True
1161
1162 def ctrl_d(self, press_secs=''):
1163 """Simulate Ctrl-d simultaneous button presses."""
1164 self._keyboard.ctrl_d(press_secs)
1165 return True
1166
Victor Dodone539cea2016-03-29 18:50:17 -07001167 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001168 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001169 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001170 return True
1171
1172 def ctrl_enter(self, press_secs=''):
1173 """Simulate Ctrl-enter simultaneous button presses."""
1174 self._keyboard.ctrl_enter(press_secs)
1175 return True
1176
1177 def d_key(self, press_secs=''):
1178 """Simulate Enter key button press."""
1179 self._keyboard.d_key(press_secs)
1180 return True
1181
1182 def ctrl_key(self, press_secs=''):
1183 """Simulate Enter key button press."""
1184 self._keyboard.ctrl_key(press_secs)
1185 return True
1186
1187 def enter_key(self, press_secs=''):
1188 """Simulate Enter key button press."""
1189 self._keyboard.enter_key(press_secs)
1190 return True
1191
1192 def refresh_key(self, press_secs=''):
1193 """Simulate Refresh key (F3) button press."""
1194 self._keyboard.refresh_key(press_secs)
1195 return True
1196
1197 def ctrl_refresh_key(self, press_secs=''):
1198 """Simulate Ctrl and Refresh (F3) simultaneous press.
1199
1200 This key combination is an alternative of Space key.
1201 """
1202 self._keyboard.ctrl_refresh_key(press_secs)
1203 return True
1204
1205 def imaginary_key(self, press_secs=''):
1206 """Simulate imaginary key button press.
1207
1208 Maps to a key that doesn't physically exist.
1209 """
1210 self._keyboard.imaginary_key(press_secs)
1211 return True
1212
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001213 def sysrq_x(self, press_secs=''):
1214 """Simulate Alt VolumeUp X simultaneous press.
1215
1216 This key combination is the kernel system request (sysrq) x.
1217 """
1218 self._keyboard.sysrq_x(press_secs)
1219 return True
1220
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001221 def get_servo_serials(self):
1222 """Return all the serials associated with this process."""
1223 return self._serialnames
1224
1225
Todd Broche505b8d2011-03-21 18:19:54 -07001226def test():
1227 """Integration testing.
1228
1229 TODO(tbroch) Enhance integration test and add unittest (see mox)
1230 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001231 logging.basicConfig(
1232 level=logging.DEBUG,
1233 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -07001234 # configure server & listen
1235 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -07001236 # 5 == number of interfaces on a FT4232H device
1237 for i in xrange(1, 5):
1238 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -07001239 # its an i2c interface ... see __init__ for details and TODO to make
1240 # this configureable
1241 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1242 else:
1243 # its a gpio interface
1244 servod_obj._interface_list[i].wr_rd(0)
1245
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001246 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost', 9999),
Todd Broche505b8d2011-03-21 18:19:54 -07001247 allow_none=True)
1248 server.register_introspection_functions()
1249 server.register_multicall_functions()
1250 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001251 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -07001252 server.serve_forever()
1253
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001254
1255if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -07001256 test()
1257
1258 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001259 """remote_uri = 'http://localhost:9999' client = xmlrpclib.ServerProxy(remote_uri, verbose=False) send_str = "Hello_there" print "Sent " + send_str + ", Recv " + client.echo(send_str)
1260
Todd Broche505b8d2011-03-21 18:19:54 -07001261 """