blob: 5203c36843cfb6e7d17ed0ece3409e2a54611e66 [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 imp
10import logging
Simran Basia9f41032012-05-11 14:21:58 -070011import os
Kevin Chengc49494e2016-07-25 12:13:38 -070012import random
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
Todd Broche505b8d2011-03-21 18:19:54 -070019
20# TODO(tbroch) deprecate use of relative imports
Vic Yangbe6cf262012-09-10 10:40:56 +080021from drv.hw_driver import HwDriverError
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
Aseda Aboagyea4922212015-11-20 15:19:08 -080039
Todd Broche505b8d2011-03-21 18:19:54 -070040MAX_I2C_CLOCK_HZ = 100000
41
Kevin Cheng5595b342016-09-29 15:51:01 -070042# It takes about 16-17 seconds for the entire probe usb device method,
43# let's wait double plus some buffer.
44_MAX_USB_LOCK_WAIT = 40
Todd Brochdbb09982011-10-02 07:14:26 -070045
Todd Broche505b8d2011-03-21 18:19:54 -070046class ServodError(Exception):
47 """Exception class for servod."""
48
49class Servod(object):
50 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070051 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070052 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070053 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070054 _USB_J3 = "usb_mux_sel1"
55 _USB_J3_TO_SERVO = "servo_sees_usbkey"
56 _USB_J3_TO_DUT = "dut_sees_usbkey"
57 _USB_J3_PWR = "prtctl4_pwren"
58 _USB_J3_PWR_ON = "on"
59 _USB_J3_PWR_OFF = "off"
Kevin Chengc49494e2016-07-25 12:13:38 -070060 _USB_LOCK_FILE = "/var/lib/servod/lock_file"
Simran Basia9f41032012-05-11 14:21:58 -070061
Kevin Cheng4b4f0022016-09-09 02:37:07 -070062 # This is the key to get the main serial used in the _serialnames dict.
63 MAIN_SERIAL = "main"
64
Kevin Chengdc3befd2016-07-15 12:34:00 -070065 def init_servo_interfaces(self, vendor, product, serialname,
66 interfaces):
67 """Init the servo interfaces with the given interfaces.
68
69 We don't use the self._{vendor,product,serialname} attributes because we
70 want to allow other callers to initialize other interfaces that may not
71 be associated with the initialized attributes (e.g. a servo v4 servod object
72 that wants to also initialize a servo micro interface).
73
74 Args:
75 vendor: USB vendor id of FTDI device.
76 product: USB product id of FTDI device.
77 serialname: String of device serialname/number as defined in FTDI
78 eeprom.
79 interfaces: List of strings of interface types the server will
80 instantiate.
81
82 Raises:
83 ServodError if unable to locate init method for particular interface.
84 """
85 # Extend the interface list if we need to.
86 interfaces_len = len(interfaces)
87 interface_list_len = len(self._interface_list)
88 if interfaces_len > interface_list_len:
89 self._interface_list += [None] * (interfaces_len - interface_list_len)
90
91 shifted = 0
92 for i, interface in enumerate(interfaces):
93 is_ftdi_interface = False
94 if type(interface) is dict:
95 name = interface['name']
96 # Store interface index for those that care about it.
97 interface['index'] = i
98 elif type(interface) is str and interface != 'dummy':
99 name = interface
100 # It's a FTDI related interface.
101 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
102 is_ftdi_interface = True
103 elif type(interface) is str and interface == 'dummy':
104 # 'dummy' reserves the interface for future use. Typically the
105 # interface will be managed by external third-party tools like
106 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
107 # it serves as a placeholder for servo micro interfaces.
108 continue
109 else:
110 raise ServodError("Illegal interface type %s" % type(interface))
111
112 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
113 if is_ftdi_interface and i and \
114 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
115 product += 1
116 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
117 product)
118
119 self._logger.info("Initializing interface %d to %s", i + 1, name)
120 try:
121 func = getattr(self, '_init_%s' % name)
122 except AttributeError:
123 raise ServodError("Unable to locate init for interface %s" % name)
124 result = func(vendor, product, serialname, interface)
125
126 if isinstance(result, tuple):
127 result_len = len(result)
128 shifted += result_len - 1
129 self._interface_list += [None] * result_len
130 for result_index, r in enumerate(result):
131 self._interface_list[i + result_index] = r
132 else:
133 self._interface_list[i + shifted] = result
134
J. Richard Barnettee2820552013-03-14 16:13:46 -0700135 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800136 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700137 """Servod constructor.
138
139 Args:
140 config: instance of SystemConfig containing all controls for
141 particular Servod invocation
142 vendor: usb vendor id of FTDI device
143 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700144 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700145 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700146 version: String. Servo board version. Examples: servo_v1, servo_v2,
147 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800148 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700149 sending keyboard commands to DUTs that do not have built in
150 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
151 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -0700152
153 Raises:
154 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700155 """
156 self._logger = logging.getLogger("Servod")
157 self._logger.debug("")
158 self._vendor = vendor
159 self._product = product
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700160 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700161 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700162 # Hold the last image path so we can reduce downloads to the usb device.
163 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700164 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
165 # interfaces are mapped to
166 self._interface_list = []
167 # Dict of Dict to map control name, function name to to tuple (params, drv)
168 # Ex) _drv_dict[name]['get'] = (params, drv)
169 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700170 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -0700171 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800172 self._usbkm232 = usbkm232
Kevin Chengc49494e2016-07-25 12:13:38 -0700173 # Seed the random generator with the serial to differentiate from other
174 # servod processes.
175 random.seed(serialname if serialname else time.time())
Todd Brochdbb09982011-10-02 07:14:26 -0700176 # Note, interface i is (i - 1) in list
177 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700178 try:
179 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
180 except KeyError:
181 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -0700182
Kevin Chengdc3befd2016-07-15 12:34:00 -0700183 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700184 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800185
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800186 def _init_keyboard_handler(self, servo, board=''):
187 """Initialize the correct keyboard handler for board.
188
Kevin Chengdc3befd2016-07-15 12:34:00 -0700189 Args:
190 servo: servo object.
191 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800192
Kevin Chengdc3befd2016-07-15 12:34:00 -0700193 Returns:
194 keyboard handler object.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800195 """
196 if board == 'parrot':
197 return keyboard_handlers.ParrotHandler(servo)
198 elif board == 'stout':
199 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800200 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800201 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
philipchenfc9eea12016-09-21 17:36:54 -0700202 'sumo', 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
203 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800204 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800205 logging.info("No device path specified for usbkm232 handler. Use "
206 "the servo atmega chip to handle.")
207 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800208 if self._usbkm232 == 'atmega':
209 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800210 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800211 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800212 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800213 self._usbkm232 = self.get('atmega_pty')
214 self.set('atmega_baudrate', '9600')
215 self.set('atmega_bits', 'eight')
216 self.set('atmega_parity', 'none')
217 self.set('atmega_sbits', 'one')
218 self.set('usb_mux_sel4', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800219 self.set('usb_mux_oe4', 'on')
Nick Sanders78423782015-11-09 14:28:19 -0800220 # Allow atmega bootup time.
221 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800222 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800223 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
224 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800225 # The following boards don't use Chrome EC.
226 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
227 return keyboard_handlers.MatrixKeyboardHandler(servo)
228 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800229
Todd Broch3ec8df02012-11-20 10:53:03 -0800230 def __del__(self):
231 """Servod deconstructor."""
232 for interface in self._interface_list:
233 del(interface)
234
Kevin Chengdc3befd2016-07-15 12:34:00 -0700235 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700236 """Dummy interface for ftdi devices.
237
238 This is a dummy function specifically for ftdi devices to not initialize
239 anything but to help pad the interface list.
240
241 Returns:
242 None.
243 """
244 return None
245
Kevin Chengdc3befd2016-07-15 12:34:00 -0700246 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700247 """Initialize gpio driver interface and open for use.
248
249 Args:
250 interface: interface number of FTDI device to use.
251
252 Returns:
253 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700254
255 Raises:
256 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700257 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700258 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700259 try:
260 fobj.open()
261 except ftdigpio.FgpioError as e:
262 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
263
Todd Broche505b8d2011-03-21 18:19:54 -0700264 return fobj
265
Kevin Chengdc3befd2016-07-15 12:34:00 -0700266 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800267 """Initialize stm32 uart interface and open for use
268
269 Note, the uart runs in a separate thread. Users wishing to
270 interact with it will query control for the pty's pathname and connect
271 with their favorite console program. For example:
272 cu -l /dev/pts/22
273
274 Args:
275 interface: dict of interface parameters.
276
277 Returns:
278 Instance object of interface
279
280 Raises:
281 ServodError: Raised on init failure.
282 """
283 self._logger.info("Suart: interface: %s" % interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700284 sobj = stm32uart.Suart(vendor, product, interface['interface'],
285 serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800286
287 try:
288 sobj.run()
289 except stm32uart.SuartError as e:
290 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
291
292 self._logger.info("%s" % sobj.get_pty())
293 return sobj
294
Kevin Chengdc3befd2016-07-15 12:34:00 -0700295 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800296 """Initialize stm32 gpio interface.
297 Args:
298 interface: interface number of stm32 device to use.
299
300 Returns:
301 Instance object of interface
302
303 Raises:
304 SgpioError: Raised on init failure.
305 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700306 interface_number = interface
307 # Interface could be a dict.
308 if type(interface) is dict:
309 interface_number = interface['interface']
310 self._logger.info("Sgpio: interface: %s" % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700311 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800312
Kevin Chengdc3befd2016-07-15 12:34:00 -0700313 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800314 """Initialize stm32 USB to I2C bridge interface and open for use
315
316 Args:
317 interface: USB interface number of stm32 device to use
318
319 Returns:
320 Instance object of interface.
321
322 Raises:
323 Si2cError: Raised on init failure.
324 """
325 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800326 port = interface.get('port', 0)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700327 return stm32i2c.Si2cBus(vendor, product, interface['interface'],
328 port=port, serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800329
Kevin Chengdc3befd2016-07-15 12:34:00 -0700330 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800331 """Initalize beaglebone ADC interface."""
332 return bbadc.BBadc()
333
Kevin Chengdc3befd2016-07-15 12:34:00 -0700334 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700335 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700336 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700337
Kevin Chengdc3befd2016-07-15 12:34:00 -0700338 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700339 """Initialize i2c interface and open for use.
340
341 Args:
342 interface: interface number of FTDI device to use
343
344 Returns:
345 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700346
347 Raises:
348 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700349 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700350 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700351 try:
352 fobj.open()
353 except ftdii2c.Fi2cError as e:
354 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
355
Todd Broche505b8d2011-03-21 18:19:54 -0700356 # Set the frequency of operation of the i2c bus.
357 # TODO(tbroch) make configureable
358 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700359
Todd Broche505b8d2011-03-21 18:19:54 -0700360 return fobj
361
Simran Basie750a342013-03-12 13:45:26 -0700362 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
363 def _init_bb_i2c(self, interface):
364 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700365 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700366
Kevin Chengdc3befd2016-07-15 12:34:00 -0700367 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800368 """Initalize Linux i2c-dev interface."""
369 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
370
Kevin Chengdc3befd2016-07-15 12:34:00 -0700371 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700372 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700373
374 Note, the uart runs in a separate thread (pthreads). Users wishing to
375 interact with it will query control for the pty's pathname and connect
376 with there favorite console program. For example:
377 cu -l /dev/pts/22
378
379 Args:
380 interface: interface number of FTDI device to use
381
382 Returns:
383 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700384
385 Raises:
386 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700387 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700388 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700389 try:
390 fobj.run()
391 except ftdiuart.FuartError as e:
392 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
393
Todd Broch47c43f42011-05-26 15:11:31 -0700394 self._logger.info("%s" % fobj.get_pty())
395 return fobj
396
Simran Basie750a342013-03-12 13:45:26 -0700397 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700398 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700399 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700400 logging.debug('UART INTERFACE: %s', interface)
401 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700402
Kevin Chengdc3befd2016-07-15 12:34:00 -0700403 def _init_ftdi_gpiouart(self, vendor, product, serialname,
404 interface):
Todd Broch888da782011-10-07 14:29:09 -0700405 """Initialize special gpio + uart interface and open for use
406
407 Note, the uart runs in a separate thread (pthreads). Users wishing to
408 interact with it will query control for the pty's pathname and connect
409 with there favorite console program. For example:
410 cu -l /dev/pts/22
411
412 Args:
413 interface: interface number of FTDI device to use
414
415 Returns:
416 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700417
418 Raises:
419 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700420 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700421 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700422 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700423 try:
424 fuart.run()
425 except ftdiuart.FuartError as e:
426 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
427
Todd Broch888da782011-10-07 14:29:09 -0700428 self._logger.info("uart pty: %s" % fuart.get_pty())
429 return fgpio, fuart
430
Kevin Chengdc3befd2016-07-15 12:34:00 -0700431 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800432 """Initialize EC-3PO console interpreter interface.
433
434 Args:
435 interface: A dictionary representing the interface.
436
437 Returns:
438 An EC3PO object representing the EC-3PO interface or None if there's no
439 interface for the USB PD UART.
440 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700441 vid = vendor
442 pid = product
Aseda Aboagyea4922212015-11-20 15:19:08 -0800443 # The current PID might be incremented if there are multiple FTDI.
444 # Therefore, try rewinding the PID back one if we don't find the base PID in
445 # the SERVO_ID_DEFAULTS
446 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
447 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
448 pid -= 1
449 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
450
Nick Sanders97bc4462016-01-04 15:37:31 -0800451 if 'raw_pty' in interface:
452 # We have specified an explicit target for this ec3po.
453 raw_uart_name = interface['raw_pty']
454 raw_ec_uart = self.get(raw_uart_name)
455
Aseda Aboagyea4922212015-11-20 15:19:08 -0800456 # Servo V2 / V3 should have the interface indicies in the same spot.
Nick Sanders97bc4462016-01-04 15:37:31 -0800457 elif ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
Aseda Aboagyea4922212015-11-20 15:19:08 -0800458 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
459 # Determine if it's a PD interface or just main EC console.
460 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
461 try:
462 # Obtain the raw EC UART PTY and create the EC-3PO interface.
463 raw_ec_uart = self.get('raw_usbpd_uart_pty')
464 except NameError:
465 # This overlay doesn't have a USB PD MCU, so skip init.
466 self._logger.info('No PD MCU UART.')
467 return None
468 except AttributeError:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700469 # This overlay has no get method for the interface so skip init. For
470 # servo v2, it's common for interfaces to be overridden such as
471 # reusing JTAG pins for the PD MCU UART instead. Therefore, print an
472 # error message indicating that the interface might be set
473 # incorrectly.
474 if (vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS:
475 self._logger.warn('No interface for PD MCU UART.')
476 self._logger.warn('Usually, this happens because the interface is '
477 'set incorrectly. If you\'re overriding an '
478 'existing interface, be sure to update the '
479 'interface lists for your board at the end of '
480 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800481 return None
482
483 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
484 raw_ec_uart = self.get('raw_ec_uart_pty')
485
486 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
487 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
488 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
489 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
490 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
491 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
492 raw_ec_uart = self.get('raw_ec_uart_pty')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800493 else:
494 raise ServodError(('Unexpected EC-3PO interface!'
495 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
496
497 return ec3po_interface.EC3PO(raw_ec_uart)
498
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800499 def _camel_case(self, string):
500 output = ''
501 for s in string.split('_'):
502 if output:
503 output += s.capitalize()
504 else:
505 output = s
506 return output
507
Todd Broche505b8d2011-03-21 18:19:54 -0700508 def _get_param_drv(self, control_name, is_get=True):
509 """Get access to driver for a given control.
510
511 Note, some controls have different parameter dictionaries for 'getting' the
512 control's value versus 'setting' it. Boolean is_get distinguishes which is
513 being requested.
514
515 Args:
516 control_name: string name of control
517 is_get: boolean to determine
518
519 Returns:
520 tuple (param, drv) where:
521 param: param dictionary for control
522 drv: instance object of driver for particular control
523
524 Raises:
525 ServodError: Error occurred while examining params dict
526 """
527 self._logger.debug("")
528 # if already setup just return tuple from driver dict
529 if control_name in self._drv_dict:
530 if is_get and ('get' in self._drv_dict[control_name]):
531 return self._drv_dict[control_name]['get']
532 if not is_get and ('set' in self._drv_dict[control_name]):
533 return self._drv_dict[control_name]['set']
534
535 params = self._syscfg.lookup_control_params(control_name, is_get)
536 if 'drv' not in params:
537 self._logger.error("Unable to determine driver for %s" % control_name)
538 raise ServodError("'drv' key not found in params dict")
539 if 'interface' not in params:
540 self._logger.error("Unable to determine interface for %s" %
541 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700542 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700543
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800544 interface_id = params.get(
545 '%s_interface' % self._version, params['interface'])
546 if interface_id == 'servo':
547 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700548 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800549 index = int(interface_id) - 1
550 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700551
Todd Broche505b8d2011-03-21 18:19:54 -0700552 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
553 drv_pkg = imp.load_module('drv',
554 *imp.find_module('drv', servo_pkg.__path__))
555 drv_name = params['drv']
556 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800557 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700558 drv = drv_class(interface, params)
559 if control_name not in self._drv_dict:
560 self._drv_dict[control_name] = {}
561 if is_get:
562 self._drv_dict[control_name]['get'] = (params, drv)
563 else:
564 self._drv_dict[control_name]['set'] = (params, drv)
565 return (params, drv)
566
567 def doc_all(self):
568 """Return all documenation for controls.
569
570 Returns:
571 string of <doc> text in config file (xml) and the params dictionary for
572 all controls.
573
574 For example:
575 warm_reset :: Reset the device warmly
576 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
577 """
578 return self._syscfg.display_config()
579
580 def doc(self, name):
581 """Retreive doc string in system config file for given control name.
582
583 Args:
584 name: name string of control to get doc string
585
586 Returns:
587 doc string of name
588
589 Raises:
590 NameError: if fails to locate control
591 """
592 self._logger.debug("name(%s)" % (name))
593 if self._syscfg.is_control(name):
594 return self._syscfg.get_control_docstring(name)
595 else:
596 raise NameError("No control %s" %name)
597
Fang Deng90377712013-06-03 15:51:48 -0700598 def _switch_usbkey(self, mux_direction):
599 """Connect USB flash stick to either servo or DUT.
600
601 This function switches 'usb_mux_sel1' to provide electrical
602 connection between the USB port J3 and either servo or DUT side.
603
604 Switching the usb mux is accompanied by powercycling
605 of the USB stick, because it sometimes gets wedged if the mux
606 is switched while the stick power is on.
607
608 Args:
609 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
610 """
611 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
612 time.sleep(self._USB_POWEROFF_DELAY)
613 self.set(self._USB_J3, mux_direction)
614 time.sleep(self._USB_POWEROFF_DELAY)
615 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
616 if mux_direction == self._USB_J3_TO_SERVO:
617 time.sleep(self._USB_DETECTION_DELAY)
618
Simran Basia9f41032012-05-11 14:21:58 -0700619 def _get_usb_port_set(self):
620 """Gets a set of USB disks currently connected to the system
621
622 Returns:
623 A set of USB disk paths.
624 """
625 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
626 return set(["/dev/" + dev for dev in usb_set])
627
Kevin Cheng5595b342016-09-29 15:51:01 -0700628 @contextlib.contextmanager
629 def _block_other_servod(self, timeout=None):
Kevin Chengc49494e2016-07-25 12:13:38 -0700630 """Block other servod processes by locking a file.
631
632 To enable multiple servods processes to safely probe_host_usb_dev, we use
633 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700634 for a usb device. This will be a context manager that will return
635 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700636
637 If the lock file exists, we open it and try to lock it.
638 - If another servod processes has locked it already, we'll sleep a random
639 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700640 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700641
Kevin Cheng5595b342016-09-29 15:51:01 -0700642 - If we're able to lock the file, we'll yield that the block was successful
643 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700644
645 This blocking behavior is only enabled if the lock file exists, if it
646 doesn't, then we pretend the block was successful.
647
Kevin Cheng5595b342016-09-29 15:51:01 -0700648 Args:
649 timeout: Max waiting time for the block to succeed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700650 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700651 if not os.path.exists(self._USB_LOCK_FILE):
652 # No lock file so we'll pretend the block was a success.
653 yield True
654 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700655 start_time = datetime.datetime.now()
656 while True:
Kevin Cheng5595b342016-09-29 15:51:01 -0700657 with open(self._USB_LOCK_FILE) as lock_file:
658 try:
659 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
660 yield True
661 fcntl.flock(lock_file, fcntl.LOCK_UN)
662 break
663 except IOError:
664 current_time = datetime.datetime.now()
665 current_wait_time = (current_time - start_time).total_seconds()
666 if timeout and current_wait_time > timeout:
667 yield False
668 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700669 # Sleep random amount.
670 sleep_time = time.sleep(random.random())
Kevin Chengc49494e2016-07-25 12:13:38 -0700671
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700672 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700673 """Toggle the usb power safely.
674
675 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700676
677 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700678 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700679 timeout: Timeout to wait for blocking other servod processes, default is
680 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700681
Kevin Cheng5595b342016-09-29 15:51:01 -0700682 Returns:
683 An empty string to appease the xmlrpc gods.
684 """
685 with self._block_other_servod(timeout=timeout):
686 if power_state != self.get(self._USB_J3_PWR):
687 self.set(self._USB_J3_PWR, power_state)
688 return ''
689
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700690 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700691 """Toggle the usb direction safely.
692
693 We'll make sure we're the only servod process toggling the usbkey direction.
694
695 Args:
696 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700697 timeout: Timeout to wait for blocking other servod processes, default is
698 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700699
700 Returns:
701 An empty string to appease the xmlrpc gods.
702 """
703 with self._block_other_servod(timeout=timeout):
704 self._switch_usbkey(mux_direction)
705 return ''
706
707 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700708 """Probe the USB disk device plugged in the servo from the host side.
709
710 Method can fail by:
711 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700712 another servo unless _USB_LOCK_FILE exists on the servo host. If that
713 file exists, then it is safe to probe for usb devices among multiple
714 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700715 2) Finding multiple /dev/sdX and returning None.
716
Kevin Cheng5595b342016-09-29 15:51:01 -0700717 Args:
718 timeout: Timeout to wait for blocking other servod processes.
719
Simran Basia9f41032012-05-11 14:21:58 -0700720 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700721 USB disk path if one and only one USB disk path is found, otherwise an
722 empty string.
Simran Basia9f41032012-05-11 14:21:58 -0700723 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700724 with self._block_other_servod(timeout=timeout) as block_success:
725 if not block_success:
726 return ''
Kevin Chengc49494e2016-07-25 12:13:38 -0700727
Kevin Cheng5595b342016-09-29 15:51:01 -0700728 original_value = self.get(self._USB_J3)
729 original_usb_power = self.get(self._USB_J3_PWR)
730 # Make the host unable to see the USB disk.
731 if (original_usb_power == self._USB_J3_PWR_ON and
732 original_value != self._USB_J3_TO_DUT):
733 self._switch_usbkey(self._USB_J3_TO_DUT)
734 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700735
Kevin Cheng5595b342016-09-29 15:51:01 -0700736 # Make the host able to see the USB disk.
737 self._switch_usbkey(self._USB_J3_TO_SERVO)
738 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700739
Kevin Cheng5595b342016-09-29 15:51:01 -0700740 # Back to its original value.
741 if original_value != self._USB_J3_TO_SERVO:
742 self._switch_usbkey(original_value)
743 if original_usb_power != self._USB_J3_PWR_ON:
744 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
745 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700746
Kevin Cheng5595b342016-09-29 15:51:01 -0700747 # Subtract the two sets to find the usb device.
748 diff_set = has_usb_set - no_usb_set
749 if len(diff_set) == 1:
750 return diff_set.pop()
751 else:
752 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700753
Kevin Cheng85831332016-10-13 13:14:44 -0700754 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700755 """Download image and save to the USB device found by probe_host_usb_dev.
756 If the image_path is a URL, it will download this url to the USB path;
757 otherwise it will simply copy the image_path's contents to the USB path.
758
759 Args:
760 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700761 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700762
763 Returns:
764 True|False: True if process completed successfully, False if error
765 occurred.
766 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
767 comment at the end of set().
768 """
769 self._logger.debug("image_path(%s)" % image_path)
770 self._logger.debug("Detecting USB stick device...")
Kevin Cheng85831332016-10-13 13:14:44 -0700771 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700772 if not usb_dev:
773 self._logger.error("No usb device connected to servo")
774 return False
775
Kevin Cheng9071ed92016-06-21 14:37:54 -0700776 # Let's check if we downloaded this last time and if so assume the image is
777 # still on the usb device and return True.
778 if self._image_path == image_path:
779 self._logger.debug("Image already on USB device, skipping transfer")
780 return True
781
Simran Basia9f41032012-05-11 14:21:58 -0700782 try:
783 if image_path.startswith(self._HTTP_PREFIX):
784 self._logger.debug("Image path is a URL, downloading image")
785 urllib.urlretrieve(image_path, usb_dev)
786 else:
787 shutil.copyfile(image_path, usb_dev)
788 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700789 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700790 e.strerror, e.errno)
791 return False
792 except urllib.ContentTooShortError:
793 self._logger.error("Failed to download URL: %s to USB device: %s",
794 image_path, usb_dev)
795 return False
796 except BaseException as e:
797 self._logger.error("Unexpected exception downloading %s to %s: %s",
798 image_path, usb_dev, str(e))
799 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800800 finally:
801 # We just plastered the partition table for a block device.
802 # Pass or fail, we mustn't go without telling the kernel about
803 # the change, or it will punish us with sporadic, hard-to-debug
804 # failures.
805 subprocess.call(["sync"])
806 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700807 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700808 return True
809
810 def make_image_noninteractive(self):
811 """Makes the recovery image noninteractive.
812
813 A noninteractive image will reboot automatically after installation
814 instead of waiting for the USB device to be removed to initiate a system
815 reboot.
816
817 Mounts partition 1 of the image stored on usb_dev and creates a file
818 called "non_interactive" so that the image will become noninteractive.
819
820 Returns:
821 True|False: True if process completed successfully, False if error
822 occurred.
823 """
824 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700825 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700826 if not usb_dev:
827 self._logger.error("No usb device connected to servo")
828 return False
829 # Create TempDirectory
830 tmpdir = tempfile.mkdtemp()
831 if tmpdir:
832 # Mount drive to tmpdir.
833 partition_1 = "%s1" % usb_dev
834 rc = subprocess.call(["mount", partition_1, tmpdir])
835 if rc == 0:
836 # Create file 'non_interactive'
837 non_interactive_file = os.path.join(tmpdir, "non_interactive")
838 try:
839 open(non_interactive_file, "w").close()
840 except IOError as e:
841 self._logger.error("Failed to create file %s : %s ( %d )",
842 non_interactive_file, e.strerror, e.errno)
843 result = False
844 except BaseException as e:
845 self._logger.error("Unexpected Exception creating file %s : %s",
846 non_interactive_file, str(e))
847 result = False
848 # Unmount drive regardless if file creation worked or not.
849 rc = subprocess.call(["umount", partition_1])
850 if rc != 0:
851 self._logger.error("Failed to unmount USB Device")
852 result = False
853 else:
854 self._logger.error("Failed to mount USB Device")
855 result = False
856
857 # Delete tmpdir. May throw exception if 'umount' failed.
858 try:
859 os.rmdir(tmpdir)
860 except OSError as e:
861 self._logger.error("Failed to remove temp directory %s : %s",
862 tmpdir, str(e))
863 return False
864 except BaseException as e:
865 self._logger.error("Unexpected Exception removing tempdir %s : %s",
866 tmpdir, str(e))
867 return False
868 else:
869 self._logger.error("Failed to create temp directory.")
870 return False
871 return result
872
Todd Broch352b4b22013-03-22 09:48:40 -0700873 def set_get_all(self, cmds):
874 """Set &| get one or more control values.
875
876 Args:
877 cmds: list of control[:value] to get or set.
878
879 Returns:
880 rv: list of responses from calling get or set methods.
881 """
882 rv = []
883 for cmd in cmds:
884 if ':' in cmd:
885 (control, value) = cmd.split(':')
886 rv.append(self.set(control, value))
887 else:
888 rv.append(self.get(cmd))
889 return rv
890
Todd Broche505b8d2011-03-21 18:19:54 -0700891 def get(self, name):
892 """Get control value.
893
894 Args:
895 name: name string of control
896
897 Returns:
898 Response from calling drv get method. Value is reformatted based on
899 control's dictionary parameters
900
901 Raises:
902 HwDriverError: Error occurred while using drv
903 """
904 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700905 if name == 'serialname':
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700906 if self._serialnames[self.MAIN_SERIAL]:
907 return self._serialnames[self.MAIN_SERIAL]
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700908 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700909 (param, drv) = self._get_param_drv(name)
910 try:
911 val = drv.get()
912 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800913 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700914 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700915 except AttributeError, error:
916 self._logger.error("Getting %s: %s" % (name, error))
917 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800918 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700919 self._logger.error("Getting %s" % (name))
920 raise
Todd Brochd6061672012-05-11 15:52:47 -0700921
Todd Broche505b8d2011-03-21 18:19:54 -0700922 def get_all(self, verbose):
923 """Get all controls values.
924
925 Args:
926 verbose: Boolean on whether to return doc info as well
927
928 Returns:
929 string creating from trying to get all values of all controls. In case of
930 error attempting access to control, response is 'ERR'.
931 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800932 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700933 for name in self._syscfg.syscfg_dict['control']:
934 self._logger.debug("name = %s" %name)
935 try:
936 value = self.get(name)
937 except Exception:
938 value = "ERR"
939 pass
940 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800941 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700942 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800943 rsp.append("%s:%s" % (name, value))
944 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700945
946 def set(self, name, wr_val_str):
947 """Set control.
948
949 Args:
950 name: name string of control
951 wr_val_str: value string to write. Can be integer, float or a
952 alpha-numerical that is mapped to a integer or float.
953
954 Raises:
955 HwDriverError: Error occurred while using driver
956 """
957 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
958 (params, drv) = self._get_param_drv(name, False)
959 wr_val = self._syscfg.resolve_val(params, wr_val_str)
960 try:
961 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800962 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700963 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
964 raise
965 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
966 # & client I still have to return something to appease the
967 # marshall/unmarshall
968 return True
969
Todd Brochd6061672012-05-11 15:52:47 -0700970 def hwinit(self, verbose=False):
971 """Initialize all controls.
972
973 These values are part of the system config XML files of the form
974 init=<value>. This command should be used by clients wishing to return the
975 servo and DUT its connected to a known good/safe state.
976
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800977 Note that initialization errors are ignored (as in some cases they could
978 be caused by DUT firmware deficiencies). This might need to be fine tuned
979 later.
980
Todd Brochd6061672012-05-11 15:52:47 -0700981 Args:
982 verbose: boolean, if True prints info about control initialized.
983 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800984
985 Returns:
986 This function is called across RPC and as such is expected to return
987 something unless transferring 'none' across is allowed. Hence adding a
988 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700989 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800990 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800991 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700992 # Workaround for bug chrome-os-partner:42349. Without this check, the
993 # gpio will briefly pulse low if we set it from high to high.
994 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700995 self.set(control_name, value)
996 if verbose:
997 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800998 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800999 self._logger.error("Problem initializing %s -> %s :: %s",
1000 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -08001001
1002 # Init keyboard after all the intefaces are up.
1003 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001004 return True
Todd Broch3ec8df02012-11-20 10:53:03 -08001005
Todd Broche505b8d2011-03-21 18:19:54 -07001006 def echo(self, echo):
1007 """Dummy echo function for testing/examples.
1008
1009 Args:
1010 echo: string to echo back to client
1011 """
1012 self._logger.debug("echo(%s)" % (echo))
1013 return "ECH0ING: %s" % (echo)
1014
J. Richard Barnettee2820552013-03-14 16:13:46 -07001015 def get_board(self):
1016 """Return the board specified at startup, if any."""
1017 return self._board
1018
Simran Basia23c1392013-08-06 14:59:10 -07001019 def get_version(self):
1020 """Get servo board version."""
1021 return self._version
1022
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001023 def power_long_press(self):
1024 """Simulate a long power button press."""
1025 # After a long power press, the EC may ignore the next power
1026 # button press (at least on Alex). To guarantee that this
1027 # won't happen, we need to allow the EC one second to
1028 # collect itself.
1029 self._keyboard.power_long_press()
1030 return True
1031
1032 def power_normal_press(self):
1033 """Simulate a normal power button press."""
1034 self._keyboard.power_normal_press()
1035 return True
1036
1037 def power_short_press(self):
1038 """Simulate a short power button press."""
1039 self._keyboard.power_short_press()
1040 return True
1041
1042 def power_key(self, secs=''):
1043 """Simulate a power button press.
1044
1045 Args:
1046 secs: Time in seconds to simulate the keypress.
1047 """
1048 self._keyboard.power_key(secs)
1049 return True
1050
1051 def ctrl_d(self, press_secs=''):
1052 """Simulate Ctrl-d simultaneous button presses."""
1053 self._keyboard.ctrl_d(press_secs)
1054 return True
1055
Victor Dodone539cea2016-03-29 18:50:17 -07001056 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001057 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001058 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001059 return True
1060
1061 def ctrl_enter(self, press_secs=''):
1062 """Simulate Ctrl-enter simultaneous button presses."""
1063 self._keyboard.ctrl_enter(press_secs)
1064 return True
1065
1066 def d_key(self, press_secs=''):
1067 """Simulate Enter key button press."""
1068 self._keyboard.d_key(press_secs)
1069 return True
1070
1071 def ctrl_key(self, press_secs=''):
1072 """Simulate Enter key button press."""
1073 self._keyboard.ctrl_key(press_secs)
1074 return True
1075
1076 def enter_key(self, press_secs=''):
1077 """Simulate Enter key button press."""
1078 self._keyboard.enter_key(press_secs)
1079 return True
1080
1081 def refresh_key(self, press_secs=''):
1082 """Simulate Refresh key (F3) button press."""
1083 self._keyboard.refresh_key(press_secs)
1084 return True
1085
1086 def ctrl_refresh_key(self, press_secs=''):
1087 """Simulate Ctrl and Refresh (F3) simultaneous press.
1088
1089 This key combination is an alternative of Space key.
1090 """
1091 self._keyboard.ctrl_refresh_key(press_secs)
1092 return True
1093
1094 def imaginary_key(self, press_secs=''):
1095 """Simulate imaginary key button press.
1096
1097 Maps to a key that doesn't physically exist.
1098 """
1099 self._keyboard.imaginary_key(press_secs)
1100 return True
1101
Todd Brochdbb09982011-10-02 07:14:26 -07001102
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001103 def sysrq_x(self, press_secs=''):
1104 """Simulate Alt VolumeUp X simultaneous press.
1105
1106 This key combination is the kernel system request (sysrq) x.
1107 """
1108 self._keyboard.sysrq_x(press_secs)
1109 return True
1110
1111
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001112 def get_servo_serials(self):
1113 """Return all the serials associated with this process."""
1114 return self._serialnames
1115
1116
Todd Broche505b8d2011-03-21 18:19:54 -07001117def test():
1118 """Integration testing.
1119
1120 TODO(tbroch) Enhance integration test and add unittest (see mox)
1121 """
1122 logging.basicConfig(level=logging.DEBUG,
1123 format="%(asctime)s - %(name)s - " +
1124 "%(levelname)s - %(message)s")
1125 # configure server & listen
1126 servod_obj = Servod(1)
1127 # 4 == number of interfaces on a FT4232H device
1128 for i in xrange(4):
1129 if i == 1:
1130 # its an i2c interface ... see __init__ for details and TODO to make
1131 # this configureable
1132 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1133 else:
1134 # its a gpio interface
1135 servod_obj._interface_list[i].wr_rd(0)
1136
1137 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1138 allow_none=True)
1139 server.register_introspection_functions()
1140 server.register_multicall_functions()
1141 server.register_instance(servod_obj)
1142 logging.info("Listening on localhost port 9999")
1143 server.serve_forever()
1144
1145if __name__ == "__main__":
1146 test()
1147
1148 # simple client transaction would look like
1149 """
1150 remote_uri = 'http://localhost:9999'
1151 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1152 send_str = "Hello_there"
1153 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1154 """