blob: e3b199d84ec12afa7a5c9ca0b61651531f79fd27 [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
Simran Basia9f41032012-05-11 14:21:58 -070012import shutil
Todd Broche505b8d2011-03-21 18:19:54 -070013import SimpleXMLRPCServer
Simran Basia9f41032012-05-11 14:21:58 -070014import subprocess
15import tempfile
Todd Broch7a91c252012-02-03 12:37:45 -080016import time
Simran Basia9f41032012-05-11 14:21:58 -070017import urllib
Todd Broche505b8d2011-03-21 18:19:54 -070018
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080019import drv as servo_drv
Aaron.Chuang88eff332014-07-31 08:32:00 +080020import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070021import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070022import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070023import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080024import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070025import ftdigpio
26import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070027import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070028import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080029import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080030import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070031import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070032import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080033import stm32gpio
34import stm32i2c
35import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070036
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080037HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080038
Todd Broche505b8d2011-03-21 18:19:54 -070039MAX_I2C_CLOCK_HZ = 100000
40
Kevin Cheng5595b342016-09-29 15:51:01 -070041# It takes about 16-17 seconds for the entire probe usb device method,
42# let's wait double plus some buffer.
43_MAX_USB_LOCK_WAIT = 40
Todd Brochdbb09982011-10-02 07:14:26 -070044
Todd Broche505b8d2011-03-21 18:19:54 -070045class ServodError(Exception):
46 """Exception class for servod."""
47
48class Servod(object):
49 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070050 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070051 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070052 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070053 _USB_J3 = "usb_mux_sel1"
54 _USB_J3_TO_SERVO = "servo_sees_usbkey"
55 _USB_J3_TO_DUT = "dut_sees_usbkey"
56 _USB_J3_PWR = "prtctl4_pwren"
57 _USB_J3_PWR_ON = "on"
58 _USB_J3_PWR_OFF = "off"
Kevin Chengc49494e2016-07-25 12:13:38 -070059 _USB_LOCK_FILE = "/var/lib/servod/lock_file"
Simran Basia9f41032012-05-11 14:21:58 -070060
Kevin Cheng4b4f0022016-09-09 02:37:07 -070061 # This is the key to get the main serial used in the _serialnames dict.
62 MAIN_SERIAL = "main"
Wai-Hong Tam4b235922016-10-07 12:26:22 -070063 MICRO_SERVO_SERIAL = "micro_servo"
Wai-Hong Tam85b4ced2016-10-07 14:15:38 -070064 CCD_SERIAL = "ccd"
Kevin Cheng4b4f0022016-09-09 02:37:07 -070065
Kevin Chengdc3befd2016-07-15 12:34:00 -070066 def init_servo_interfaces(self, vendor, product, serialname,
67 interfaces):
68 """Init the servo interfaces with the given interfaces.
69
70 We don't use the self._{vendor,product,serialname} attributes because we
71 want to allow other callers to initialize other interfaces that may not
72 be associated with the initialized attributes (e.g. a servo v4 servod object
73 that wants to also initialize a servo micro interface).
74
75 Args:
76 vendor: USB vendor id of FTDI device.
77 product: USB product id of FTDI device.
78 serialname: String of device serialname/number as defined in FTDI
79 eeprom.
80 interfaces: List of strings of interface types the server will
81 instantiate.
82
83 Raises:
84 ServodError if unable to locate init method for particular interface.
85 """
86 # Extend the interface list if we need to.
87 interfaces_len = len(interfaces)
88 interface_list_len = len(self._interface_list)
89 if interfaces_len > interface_list_len:
90 self._interface_list += [None] * (interfaces_len - interface_list_len)
91
92 shifted = 0
93 for i, interface in enumerate(interfaces):
94 is_ftdi_interface = False
95 if type(interface) is dict:
96 name = interface['name']
97 # Store interface index for those that care about it.
98 interface['index'] = i
99 elif type(interface) is str and interface != 'dummy':
100 name = interface
101 # It's a FTDI related interface.
102 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
103 is_ftdi_interface = True
104 elif type(interface) is str and interface == 'dummy':
105 # 'dummy' reserves the interface for future use. Typically the
106 # interface will be managed by external third-party tools like
107 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
108 # it serves as a placeholder for servo micro interfaces.
109 continue
110 else:
111 raise ServodError("Illegal interface type %s" % type(interface))
112
113 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
114 if is_ftdi_interface and i and \
115 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
116 product += 1
117 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
118 product)
119
120 self._logger.info("Initializing interface %d to %s", i + 1, name)
121 try:
122 func = getattr(self, '_init_%s' % name)
123 except AttributeError:
124 raise ServodError("Unable to locate init for interface %s" % name)
125 result = func(vendor, product, serialname, interface)
126
127 if isinstance(result, tuple):
128 result_len = len(result)
Wai-Hong Tam9441b182016-11-01 11:05:09 -0700129 # More than one interface return. Extend the list.
130 self._interface_list += [None] * (result_len - 1)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700131 for result_index, r in enumerate(result):
Wai-Hong Tam9441b182016-11-01 11:05:09 -0700132 self._interface_list[i + shifted + result_index] = r
133 # Shift the remaining interfaces.
134 shifted += result_len - 1
Kevin Chengdc3befd2016-07-15 12:34:00 -0700135 else:
136 self._interface_list[i + shifted] = result
137
J. Richard Barnettee2820552013-03-14 16:13:46 -0700138 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800139 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700140 """Servod constructor.
141
142 Args:
143 config: instance of SystemConfig containing all controls for
144 particular Servod invocation
145 vendor: usb vendor id of FTDI device
146 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700147 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700148 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700149 version: String. Servo board version. Examples: servo_v1, servo_v2,
150 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800151 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700152 sending keyboard commands to DUTs that do not have built in
153 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
154 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -0700155
156 Raises:
157 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700158 """
159 self._logger = logging.getLogger("Servod")
160 self._logger.debug("")
161 self._vendor = vendor
162 self._product = product
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700163 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700164 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700165 # Hold the last image path so we can reduce downloads to the usb device.
166 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700167 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
168 # interfaces are mapped to
169 self._interface_list = []
170 # Dict of Dict to map control name, function name to to tuple (params, drv)
171 # Ex) _drv_dict[name]['get'] = (params, drv)
172 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700173 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -0700174 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800175 self._usbkm232 = usbkm232
Kevin Chengc49494e2016-07-25 12:13:38 -0700176 # Seed the random generator with the serial to differentiate from other
177 # servod processes.
178 random.seed(serialname if serialname else time.time())
Todd Brochdbb09982011-10-02 07:14:26 -0700179 # Note, interface i is (i - 1) in list
180 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700181 try:
182 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
183 except KeyError:
184 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -0700185
Kevin Chengdc3befd2016-07-15 12:34:00 -0700186 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700187 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800188
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800189 def _init_keyboard_handler(self, servo, board=''):
190 """Initialize the correct keyboard handler for board.
191
Kevin Chengdc3befd2016-07-15 12:34:00 -0700192 Args:
193 servo: servo object.
194 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800195
Kevin Chengdc3befd2016-07-15 12:34:00 -0700196 Returns:
197 keyboard handler object.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800198 """
199 if board == 'parrot':
200 return keyboard_handlers.ParrotHandler(servo)
201 elif board == 'stout':
202 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800203 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800204 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
philipchenfc9eea12016-09-21 17:36:54 -0700205 'sumo', 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
206 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800207 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800208 logging.info("No device path specified for usbkm232 handler. Use "
209 "the servo atmega chip to handle.")
210 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800211 if self._usbkm232 == 'atmega':
212 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800213 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800214 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800215 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800216 self._usbkm232 = self.get('atmega_pty')
Kevin Cheng810fc782016-11-01 12:36:46 -0700217 # We don't need to set the atmega uart settings if we're a servo v4.
218 if self._version != 'servo_v4':
219 self.set('atmega_baudrate', '9600')
220 self.set('atmega_bits', 'eight')
221 self.set('atmega_parity', 'none')
222 self.set('atmega_sbits', 'one')
223 self.set('usb_mux_sel4', 'on')
224 self.set('usb_mux_oe4', 'on')
225 # Allow atmega bootup time.
226 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800227 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800228 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
229 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800230 # The following boards don't use Chrome EC.
231 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
232 return keyboard_handlers.MatrixKeyboardHandler(servo)
233 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800234
Todd Broch3ec8df02012-11-20 10:53:03 -0800235 def __del__(self):
236 """Servod deconstructor."""
237 for interface in self._interface_list:
238 del(interface)
239
Kevin Chengdc3befd2016-07-15 12:34:00 -0700240 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700241 """Dummy interface for ftdi devices.
242
243 This is a dummy function specifically for ftdi devices to not initialize
244 anything but to help pad the interface list.
245
246 Returns:
247 None.
248 """
249 return None
250
Kevin Chengdc3befd2016-07-15 12:34:00 -0700251 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700252 """Initialize gpio driver interface and open for use.
253
254 Args:
255 interface: interface number of FTDI device to use.
256
257 Returns:
258 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700259
260 Raises:
261 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700262 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700263 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700264 try:
265 fobj.open()
266 except ftdigpio.FgpioError as e:
267 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
268
Todd Broche505b8d2011-03-21 18:19:54 -0700269 return fobj
270
Kevin Chengdc3befd2016-07-15 12:34:00 -0700271 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800272 """Initialize stm32 uart interface and open for use
273
274 Note, the uart runs in a separate thread. Users wishing to
275 interact with it will query control for the pty's pathname and connect
276 with their favorite console program. For example:
277 cu -l /dev/pts/22
278
279 Args:
280 interface: dict of interface parameters.
281
282 Returns:
283 Instance object of interface
284
285 Raises:
286 ServodError: Raised on init failure.
287 """
288 self._logger.info("Suart: interface: %s" % interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700289 sobj = stm32uart.Suart(vendor, product, interface['interface'],
290 serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800291
292 try:
293 sobj.run()
294 except stm32uart.SuartError as e:
295 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
296
297 self._logger.info("%s" % sobj.get_pty())
298 return sobj
299
Kevin Chengdc3befd2016-07-15 12:34:00 -0700300 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800301 """Initialize stm32 gpio interface.
302 Args:
303 interface: interface number of stm32 device to use.
304
305 Returns:
306 Instance object of interface
307
308 Raises:
309 SgpioError: Raised on init failure.
310 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700311 interface_number = interface
312 # Interface could be a dict.
313 if type(interface) is dict:
314 interface_number = interface['interface']
315 self._logger.info("Sgpio: interface: %s" % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700316 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800317
Kevin Chengdc3befd2016-07-15 12:34:00 -0700318 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800319 """Initialize stm32 USB to I2C bridge interface and open for use
320
321 Args:
322 interface: USB interface number of stm32 device to use
323
324 Returns:
325 Instance object of interface.
326
327 Raises:
328 Si2cError: Raised on init failure.
329 """
330 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800331 port = interface.get('port', 0)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700332 return stm32i2c.Si2cBus(vendor, product, interface['interface'],
333 port=port, serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800334
Kevin Chengdc3befd2016-07-15 12:34:00 -0700335 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800336 """Initalize beaglebone ADC interface."""
337 return bbadc.BBadc()
338
Kevin Chengdc3befd2016-07-15 12:34:00 -0700339 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700340 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700341 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700342
Kevin Chengdc3befd2016-07-15 12:34:00 -0700343 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700344 """Initialize i2c interface and open for use.
345
346 Args:
347 interface: interface number of FTDI device to use
348
349 Returns:
350 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700351
352 Raises:
353 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700354 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700355 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700356 try:
357 fobj.open()
358 except ftdii2c.Fi2cError as e:
359 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
360
Todd Broche505b8d2011-03-21 18:19:54 -0700361 # Set the frequency of operation of the i2c bus.
362 # TODO(tbroch) make configureable
363 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700364
Todd Broche505b8d2011-03-21 18:19:54 -0700365 return fobj
366
Simran Basie750a342013-03-12 13:45:26 -0700367 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
368 def _init_bb_i2c(self, interface):
369 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700370 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700371
Kevin Chengdc3befd2016-07-15 12:34:00 -0700372 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800373 """Initalize Linux i2c-dev interface."""
374 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
375
Kevin Chengdc3befd2016-07-15 12:34:00 -0700376 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700377 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700378
379 Note, the uart runs in a separate thread (pthreads). Users wishing to
380 interact with it will query control for the pty's pathname and connect
381 with there favorite console program. For example:
382 cu -l /dev/pts/22
383
384 Args:
385 interface: interface number of FTDI device to use
386
387 Returns:
388 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700389
390 Raises:
391 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700392 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700393 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700394 try:
395 fobj.run()
396 except ftdiuart.FuartError as e:
397 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
398
Todd Broch47c43f42011-05-26 15:11:31 -0700399 self._logger.info("%s" % fobj.get_pty())
400 return fobj
401
Simran Basie750a342013-03-12 13:45:26 -0700402 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700403 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700404 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700405 logging.debug('UART INTERFACE: %s', interface)
406 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700407
Kevin Chengdc3befd2016-07-15 12:34:00 -0700408 def _init_ftdi_gpiouart(self, vendor, product, serialname,
409 interface):
Todd Broch888da782011-10-07 14:29:09 -0700410 """Initialize special gpio + uart interface and open for use
411
412 Note, the uart runs in a separate thread (pthreads). Users wishing to
413 interact with it will query control for the pty's pathname and connect
414 with there favorite console program. For example:
415 cu -l /dev/pts/22
416
417 Args:
418 interface: interface number of FTDI device to use
419
420 Returns:
421 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700422
423 Raises:
424 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700425 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700426 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700427 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700428 try:
429 fuart.run()
430 except ftdiuart.FuartError as e:
431 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
432
Todd Broch888da782011-10-07 14:29:09 -0700433 self._logger.info("uart pty: %s" % fuart.get_pty())
434 return fgpio, fuart
435
Kevin Chengdc3befd2016-07-15 12:34:00 -0700436 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800437 """Initialize EC-3PO console interpreter interface.
438
439 Args:
440 interface: A dictionary representing the interface.
441
442 Returns:
443 An EC3PO object representing the EC-3PO interface or None if there's no
444 interface for the USB PD UART.
445 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700446 vid = vendor
447 pid = product
Aseda Aboagyea4922212015-11-20 15:19:08 -0800448 # The current PID might be incremented if there are multiple FTDI.
449 # Therefore, try rewinding the PID back one if we don't find the base PID in
450 # the SERVO_ID_DEFAULTS
451 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
452 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
453 pid -= 1
454 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
455
Nick Sanders97bc4462016-01-04 15:37:31 -0800456 if 'raw_pty' in interface:
457 # We have specified an explicit target for this ec3po.
458 raw_uart_name = interface['raw_pty']
459 raw_ec_uart = self.get(raw_uart_name)
460
Aseda Aboagyea4922212015-11-20 15:19:08 -0800461 # Servo V2 / V3 should have the interface indicies in the same spot.
Nick Sanders97bc4462016-01-04 15:37:31 -0800462 elif ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
Aseda Aboagyea4922212015-11-20 15:19:08 -0800463 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
464 # Determine if it's a PD interface or just main EC console.
465 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
466 try:
467 # Obtain the raw EC UART PTY and create the EC-3PO interface.
468 raw_ec_uart = self.get('raw_usbpd_uart_pty')
469 except NameError:
470 # This overlay doesn't have a USB PD MCU, so skip init.
471 self._logger.info('No PD MCU UART.')
472 return None
473 except AttributeError:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700474 # This overlay has no get method for the interface so skip init. For
475 # servo v2, it's common for interfaces to be overridden such as
476 # reusing JTAG pins for the PD MCU UART instead. Therefore, print an
477 # error message indicating that the interface might be set
478 # incorrectly.
479 if (vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS:
480 self._logger.warn('No interface for PD MCU UART.')
481 self._logger.warn('Usually, this happens because the interface is '
482 'set incorrectly. If you\'re overriding an '
483 'existing interface, be sure to update the '
484 'interface lists for your board at the end of '
485 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800486 return None
487
488 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
489 raw_ec_uart = self.get('raw_ec_uart_pty')
490
491 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
492 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
493 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
494 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
495 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
496 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
497 raw_ec_uart = self.get('raw_ec_uart_pty')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800498 else:
499 raise ServodError(('Unexpected EC-3PO interface!'
500 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
501
502 return ec3po_interface.EC3PO(raw_ec_uart)
503
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800504 def _camel_case(self, string):
505 output = ''
506 for s in string.split('_'):
507 if output:
508 output += s.capitalize()
509 else:
510 output = s
511 return output
512
Todd Broche505b8d2011-03-21 18:19:54 -0700513 def _get_param_drv(self, control_name, is_get=True):
514 """Get access to driver for a given control.
515
516 Note, some controls have different parameter dictionaries for 'getting' the
517 control's value versus 'setting' it. Boolean is_get distinguishes which is
518 being requested.
519
520 Args:
521 control_name: string name of control
522 is_get: boolean to determine
523
524 Returns:
525 tuple (param, drv) where:
526 param: param dictionary for control
527 drv: instance object of driver for particular control
528
529 Raises:
530 ServodError: Error occurred while examining params dict
531 """
532 self._logger.debug("")
533 # if already setup just return tuple from driver dict
534 if control_name in self._drv_dict:
535 if is_get and ('get' in self._drv_dict[control_name]):
536 return self._drv_dict[control_name]['get']
537 if not is_get and ('set' in self._drv_dict[control_name]):
538 return self._drv_dict[control_name]['set']
539
540 params = self._syscfg.lookup_control_params(control_name, is_get)
541 if 'drv' not in params:
542 self._logger.error("Unable to determine driver for %s" % control_name)
543 raise ServodError("'drv' key not found in params dict")
544 if 'interface' not in params:
545 self._logger.error("Unable to determine interface for %s" %
546 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700547 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700548
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800549 interface_id = params.get(
550 '%s_interface' % self._version, params['interface'])
551 if interface_id == 'servo':
552 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700553 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800554 index = int(interface_id) - 1
555 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700556
Todd Broche505b8d2011-03-21 18:19:54 -0700557 drv_name = params['drv']
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800558 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800559 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700560 drv = drv_class(interface, params)
561 if control_name not in self._drv_dict:
562 self._drv_dict[control_name] = {}
563 if is_get:
564 self._drv_dict[control_name]['get'] = (params, drv)
565 else:
566 self._drv_dict[control_name]['set'] = (params, drv)
567 return (params, drv)
568
569 def doc_all(self):
570 """Return all documenation for controls.
571
572 Returns:
573 string of <doc> text in config file (xml) and the params dictionary for
574 all controls.
575
576 For example:
577 warm_reset :: Reset the device warmly
578 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
579 """
580 return self._syscfg.display_config()
581
582 def doc(self, name):
583 """Retreive doc string in system config file for given control name.
584
585 Args:
586 name: name string of control to get doc string
587
588 Returns:
589 doc string of name
590
591 Raises:
592 NameError: if fails to locate control
593 """
594 self._logger.debug("name(%s)" % (name))
595 if self._syscfg.is_control(name):
596 return self._syscfg.get_control_docstring(name)
597 else:
598 raise NameError("No control %s" %name)
599
Fang Deng90377712013-06-03 15:51:48 -0700600 def _switch_usbkey(self, mux_direction):
601 """Connect USB flash stick to either servo or DUT.
602
603 This function switches 'usb_mux_sel1' to provide electrical
604 connection between the USB port J3 and either servo or DUT side.
605
606 Switching the usb mux is accompanied by powercycling
607 of the USB stick, because it sometimes gets wedged if the mux
608 is switched while the stick power is on.
609
610 Args:
611 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
612 """
613 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
614 time.sleep(self._USB_POWEROFF_DELAY)
615 self.set(self._USB_J3, mux_direction)
616 time.sleep(self._USB_POWEROFF_DELAY)
617 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
618 if mux_direction == self._USB_J3_TO_SERVO:
619 time.sleep(self._USB_DETECTION_DELAY)
620
Simran Basia9f41032012-05-11 14:21:58 -0700621 def _get_usb_port_set(self):
622 """Gets a set of USB disks currently connected to the system
623
624 Returns:
625 A set of USB disk paths.
626 """
627 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
628 return set(["/dev/" + dev for dev in usb_set])
629
Kevin Cheng5595b342016-09-29 15:51:01 -0700630 @contextlib.contextmanager
631 def _block_other_servod(self, timeout=None):
Kevin Chengc49494e2016-07-25 12:13:38 -0700632 """Block other servod processes by locking a file.
633
634 To enable multiple servods processes to safely probe_host_usb_dev, we use
635 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700636 for a usb device. This will be a context manager that will return
637 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700638
639 If the lock file exists, we open it and try to lock it.
640 - If another servod processes has locked it already, we'll sleep a random
641 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700642 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700643
Kevin Cheng5595b342016-09-29 15:51:01 -0700644 - If we're able to lock the file, we'll yield that the block was successful
645 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700646
647 This blocking behavior is only enabled if the lock file exists, if it
648 doesn't, then we pretend the block was successful.
649
Kevin Cheng5595b342016-09-29 15:51:01 -0700650 Args:
651 timeout: Max waiting time for the block to succeed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700652 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700653 if not os.path.exists(self._USB_LOCK_FILE):
654 # No lock file so we'll pretend the block was a success.
655 yield True
656 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700657 start_time = datetime.datetime.now()
658 while True:
Kevin Cheng5595b342016-09-29 15:51:01 -0700659 with open(self._USB_LOCK_FILE) as lock_file:
660 try:
661 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
662 yield True
663 fcntl.flock(lock_file, fcntl.LOCK_UN)
664 break
665 except IOError:
666 current_time = datetime.datetime.now()
667 current_wait_time = (current_time - start_time).total_seconds()
668 if timeout and current_wait_time > timeout:
669 yield False
670 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700671 # Sleep random amount.
672 sleep_time = time.sleep(random.random())
Kevin Chengc49494e2016-07-25 12:13:38 -0700673
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700674 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700675 """Toggle the usb power safely.
676
677 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700678
679 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700680 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700681 timeout: Timeout to wait for blocking other servod processes, default is
682 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700683
Kevin Cheng5595b342016-09-29 15:51:01 -0700684 Returns:
685 An empty string to appease the xmlrpc gods.
686 """
687 with self._block_other_servod(timeout=timeout):
688 if power_state != self.get(self._USB_J3_PWR):
689 self.set(self._USB_J3_PWR, power_state)
690 return ''
691
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700692 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700693 """Toggle the usb direction safely.
694
695 We'll make sure we're the only servod process toggling the usbkey direction.
696
697 Args:
698 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700699 timeout: Timeout to wait for blocking other servod processes, default is
700 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700701
702 Returns:
703 An empty string to appease the xmlrpc gods.
704 """
705 with self._block_other_servod(timeout=timeout):
706 self._switch_usbkey(mux_direction)
707 return ''
708
709 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700710 """Probe the USB disk device plugged in the servo from the host side.
711
712 Method can fail by:
713 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700714 another servo unless _USB_LOCK_FILE exists on the servo host. If that
715 file exists, then it is safe to probe for usb devices among multiple
716 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700717 2) Finding multiple /dev/sdX and returning None.
718
Kevin Cheng5595b342016-09-29 15:51:01 -0700719 Args:
720 timeout: Timeout to wait for blocking other servod processes.
721
Simran Basia9f41032012-05-11 14:21:58 -0700722 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700723 USB disk path if one and only one USB disk path is found, otherwise an
724 empty string.
Simran Basia9f41032012-05-11 14:21:58 -0700725 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700726 with self._block_other_servod(timeout=timeout) as block_success:
727 if not block_success:
728 return ''
Kevin Chengc49494e2016-07-25 12:13:38 -0700729
Kevin Cheng5595b342016-09-29 15:51:01 -0700730 original_value = self.get(self._USB_J3)
731 original_usb_power = self.get(self._USB_J3_PWR)
732 # Make the host unable to see the USB disk.
733 if (original_usb_power == self._USB_J3_PWR_ON and
734 original_value != self._USB_J3_TO_DUT):
735 self._switch_usbkey(self._USB_J3_TO_DUT)
736 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700737
Kevin Cheng5595b342016-09-29 15:51:01 -0700738 # Make the host able to see the USB disk.
739 self._switch_usbkey(self._USB_J3_TO_SERVO)
740 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700741
Kevin Cheng5595b342016-09-29 15:51:01 -0700742 # Back to its original value.
743 if original_value != self._USB_J3_TO_SERVO:
744 self._switch_usbkey(original_value)
745 if original_usb_power != self._USB_J3_PWR_ON:
746 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
747 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700748
Kevin Cheng5595b342016-09-29 15:51:01 -0700749 # Subtract the two sets to find the usb device.
750 diff_set = has_usb_set - no_usb_set
751 if len(diff_set) == 1:
752 return diff_set.pop()
753 else:
754 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700755
Kevin Cheng85831332016-10-13 13:14:44 -0700756 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700757 """Download image and save to the USB device found by probe_host_usb_dev.
758 If the image_path is a URL, it will download this url to the USB path;
759 otherwise it will simply copy the image_path's contents to the USB path.
760
761 Args:
762 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700763 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700764
765 Returns:
766 True|False: True if process completed successfully, False if error
767 occurred.
768 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
769 comment at the end of set().
770 """
771 self._logger.debug("image_path(%s)" % image_path)
772 self._logger.debug("Detecting USB stick device...")
Kevin Cheng85831332016-10-13 13:14:44 -0700773 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700774 if not usb_dev:
775 self._logger.error("No usb device connected to servo")
776 return False
777
Kevin Cheng9071ed92016-06-21 14:37:54 -0700778 # Let's check if we downloaded this last time and if so assume the image is
779 # still on the usb device and return True.
780 if self._image_path == image_path:
781 self._logger.debug("Image already on USB device, skipping transfer")
782 return True
783
Simran Basia9f41032012-05-11 14:21:58 -0700784 try:
785 if image_path.startswith(self._HTTP_PREFIX):
786 self._logger.debug("Image path is a URL, downloading image")
787 urllib.urlretrieve(image_path, usb_dev)
788 else:
789 shutil.copyfile(image_path, usb_dev)
790 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700791 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700792 e.strerror, e.errno)
793 return False
794 except urllib.ContentTooShortError:
795 self._logger.error("Failed to download URL: %s to USB device: %s",
796 image_path, usb_dev)
797 return False
798 except BaseException as e:
799 self._logger.error("Unexpected exception downloading %s to %s: %s",
800 image_path, usb_dev, str(e))
801 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800802 finally:
803 # We just plastered the partition table for a block device.
804 # Pass or fail, we mustn't go without telling the kernel about
805 # the change, or it will punish us with sporadic, hard-to-debug
806 # failures.
807 subprocess.call(["sync"])
808 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700809 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700810 return True
811
812 def make_image_noninteractive(self):
813 """Makes the recovery image noninteractive.
814
815 A noninteractive image will reboot automatically after installation
816 instead of waiting for the USB device to be removed to initiate a system
817 reboot.
818
819 Mounts partition 1 of the image stored on usb_dev and creates a file
820 called "non_interactive" so that the image will become noninteractive.
821
822 Returns:
823 True|False: True if process completed successfully, False if error
824 occurred.
825 """
826 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700827 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700828 if not usb_dev:
829 self._logger.error("No usb device connected to servo")
830 return False
831 # Create TempDirectory
832 tmpdir = tempfile.mkdtemp()
833 if tmpdir:
834 # Mount drive to tmpdir.
835 partition_1 = "%s1" % usb_dev
836 rc = subprocess.call(["mount", partition_1, tmpdir])
837 if rc == 0:
838 # Create file 'non_interactive'
839 non_interactive_file = os.path.join(tmpdir, "non_interactive")
840 try:
841 open(non_interactive_file, "w").close()
842 except IOError as e:
843 self._logger.error("Failed to create file %s : %s ( %d )",
844 non_interactive_file, e.strerror, e.errno)
845 result = False
846 except BaseException as e:
847 self._logger.error("Unexpected Exception creating file %s : %s",
848 non_interactive_file, str(e))
849 result = False
850 # Unmount drive regardless if file creation worked or not.
851 rc = subprocess.call(["umount", partition_1])
852 if rc != 0:
853 self._logger.error("Failed to unmount USB Device")
854 result = False
855 else:
856 self._logger.error("Failed to mount USB Device")
857 result = False
858
859 # Delete tmpdir. May throw exception if 'umount' failed.
860 try:
861 os.rmdir(tmpdir)
862 except OSError as e:
863 self._logger.error("Failed to remove temp directory %s : %s",
864 tmpdir, str(e))
865 return False
866 except BaseException as e:
867 self._logger.error("Unexpected Exception removing tempdir %s : %s",
868 tmpdir, str(e))
869 return False
870 else:
871 self._logger.error("Failed to create temp directory.")
872 return False
873 return result
874
Todd Broch352b4b22013-03-22 09:48:40 -0700875 def set_get_all(self, cmds):
876 """Set &| get one or more control values.
877
878 Args:
879 cmds: list of control[:value] to get or set.
880
881 Returns:
882 rv: list of responses from calling get or set methods.
883 """
884 rv = []
885 for cmd in cmds:
886 if ':' in cmd:
887 (control, value) = cmd.split(':')
888 rv.append(self.set(control, value))
889 else:
890 rv.append(self.get(cmd))
891 return rv
892
Todd Broche505b8d2011-03-21 18:19:54 -0700893 def get(self, name):
894 """Get control value.
895
896 Args:
897 name: name string of control
898
899 Returns:
900 Response from calling drv get method. Value is reformatted based on
901 control's dictionary parameters
902
903 Raises:
904 HwDriverError: Error occurred while using drv
905 """
906 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700907 if name == 'serialname':
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700908 if self._serialnames[self.MAIN_SERIAL]:
909 return self._serialnames[self.MAIN_SERIAL]
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700910 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700911 (param, drv) = self._get_param_drv(name)
912 try:
913 val = drv.get()
914 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800915 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700916 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700917 except AttributeError, error:
918 self._logger.error("Getting %s: %s" % (name, error))
919 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800920 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700921 self._logger.error("Getting %s" % (name))
922 raise
Todd Brochd6061672012-05-11 15:52:47 -0700923
Todd Broche505b8d2011-03-21 18:19:54 -0700924 def get_all(self, verbose):
925 """Get all controls values.
926
927 Args:
928 verbose: Boolean on whether to return doc info as well
929
930 Returns:
931 string creating from trying to get all values of all controls. In case of
932 error attempting access to control, response is 'ERR'.
933 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800934 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700935 for name in self._syscfg.syscfg_dict['control']:
936 self._logger.debug("name = %s" %name)
937 try:
938 value = self.get(name)
939 except Exception:
940 value = "ERR"
941 pass
942 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800943 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700944 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800945 rsp.append("%s:%s" % (name, value))
946 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700947
948 def set(self, name, wr_val_str):
949 """Set control.
950
951 Args:
952 name: name string of control
953 wr_val_str: value string to write. Can be integer, float or a
954 alpha-numerical that is mapped to a integer or float.
955
956 Raises:
957 HwDriverError: Error occurred while using driver
958 """
959 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
960 (params, drv) = self._get_param_drv(name, False)
961 wr_val = self._syscfg.resolve_val(params, wr_val_str)
962 try:
963 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800964 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700965 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
966 raise
967 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
968 # & client I still have to return something to appease the
969 # marshall/unmarshall
970 return True
971
Todd Brochd6061672012-05-11 15:52:47 -0700972 def hwinit(self, verbose=False):
973 """Initialize all controls.
974
975 These values are part of the system config XML files of the form
976 init=<value>. This command should be used by clients wishing to return the
977 servo and DUT its connected to a known good/safe state.
978
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800979 Note that initialization errors are ignored (as in some cases they could
980 be caused by DUT firmware deficiencies). This might need to be fine tuned
981 later.
982
Todd Brochd6061672012-05-11 15:52:47 -0700983 Args:
984 verbose: boolean, if True prints info about control initialized.
985 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800986
987 Returns:
988 This function is called across RPC and as such is expected to return
989 something unless transferring 'none' across is allowed. Hence adding a
990 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700991 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800992 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800993 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700994 # Workaround for bug chrome-os-partner:42349. Without this check, the
995 # gpio will briefly pulse low if we set it from high to high.
996 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700997 self.set(control_name, value)
998 if verbose:
999 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -08001000 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -08001001 self._logger.error("Problem initializing %s -> %s :: %s",
1002 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -08001003
1004 # Init keyboard after all the intefaces are up.
1005 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001006 return True
Todd Broch3ec8df02012-11-20 10:53:03 -08001007
Todd Broche505b8d2011-03-21 18:19:54 -07001008 def echo(self, echo):
1009 """Dummy echo function for testing/examples.
1010
1011 Args:
1012 echo: string to echo back to client
1013 """
1014 self._logger.debug("echo(%s)" % (echo))
1015 return "ECH0ING: %s" % (echo)
1016
J. Richard Barnettee2820552013-03-14 16:13:46 -07001017 def get_board(self):
1018 """Return the board specified at startup, if any."""
1019 return self._board
1020
Simran Basia23c1392013-08-06 14:59:10 -07001021 def get_version(self):
1022 """Get servo board version."""
1023 return self._version
1024
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001025 def power_long_press(self):
1026 """Simulate a long power button press."""
1027 # After a long power press, the EC may ignore the next power
1028 # button press (at least on Alex). To guarantee that this
1029 # won't happen, we need to allow the EC one second to
1030 # collect itself.
1031 self._keyboard.power_long_press()
1032 return True
1033
1034 def power_normal_press(self):
1035 """Simulate a normal power button press."""
1036 self._keyboard.power_normal_press()
1037 return True
1038
1039 def power_short_press(self):
1040 """Simulate a short power button press."""
1041 self._keyboard.power_short_press()
1042 return True
1043
1044 def power_key(self, secs=''):
1045 """Simulate a power button press.
1046
1047 Args:
1048 secs: Time in seconds to simulate the keypress.
1049 """
1050 self._keyboard.power_key(secs)
1051 return True
1052
1053 def ctrl_d(self, press_secs=''):
1054 """Simulate Ctrl-d simultaneous button presses."""
1055 self._keyboard.ctrl_d(press_secs)
1056 return True
1057
Victor Dodone539cea2016-03-29 18:50:17 -07001058 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001059 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001060 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001061 return True
1062
1063 def ctrl_enter(self, press_secs=''):
1064 """Simulate Ctrl-enter simultaneous button presses."""
1065 self._keyboard.ctrl_enter(press_secs)
1066 return True
1067
1068 def d_key(self, press_secs=''):
1069 """Simulate Enter key button press."""
1070 self._keyboard.d_key(press_secs)
1071 return True
1072
1073 def ctrl_key(self, press_secs=''):
1074 """Simulate Enter key button press."""
1075 self._keyboard.ctrl_key(press_secs)
1076 return True
1077
1078 def enter_key(self, press_secs=''):
1079 """Simulate Enter key button press."""
1080 self._keyboard.enter_key(press_secs)
1081 return True
1082
1083 def refresh_key(self, press_secs=''):
1084 """Simulate Refresh key (F3) button press."""
1085 self._keyboard.refresh_key(press_secs)
1086 return True
1087
1088 def ctrl_refresh_key(self, press_secs=''):
1089 """Simulate Ctrl and Refresh (F3) simultaneous press.
1090
1091 This key combination is an alternative of Space key.
1092 """
1093 self._keyboard.ctrl_refresh_key(press_secs)
1094 return True
1095
1096 def imaginary_key(self, press_secs=''):
1097 """Simulate imaginary key button press.
1098
1099 Maps to a key that doesn't physically exist.
1100 """
1101 self._keyboard.imaginary_key(press_secs)
1102 return True
1103
Todd Brochdbb09982011-10-02 07:14:26 -07001104
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001105 def sysrq_x(self, press_secs=''):
1106 """Simulate Alt VolumeUp X simultaneous press.
1107
1108 This key combination is the kernel system request (sysrq) x.
1109 """
1110 self._keyboard.sysrq_x(press_secs)
1111 return True
1112
1113
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001114 def get_servo_serials(self):
1115 """Return all the serials associated with this process."""
1116 return self._serialnames
1117
1118
Todd Broche505b8d2011-03-21 18:19:54 -07001119def test():
1120 """Integration testing.
1121
1122 TODO(tbroch) Enhance integration test and add unittest (see mox)
1123 """
1124 logging.basicConfig(level=logging.DEBUG,
1125 format="%(asctime)s - %(name)s - " +
1126 "%(levelname)s - %(message)s")
1127 # configure server & listen
1128 servod_obj = Servod(1)
1129 # 4 == number of interfaces on a FT4232H device
1130 for i in xrange(4):
1131 if i == 1:
1132 # its an i2c interface ... see __init__ for details and TODO to make
1133 # this configureable
1134 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1135 else:
1136 # its a gpio interface
1137 servod_obj._interface_list[i].wr_rd(0)
1138
1139 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1140 allow_none=True)
1141 server.register_introspection_functions()
1142 server.register_multicall_functions()
1143 server.register_instance(servod_obj)
1144 logging.info("Listening on localhost port 9999")
1145 server.serve_forever()
1146
1147if __name__ == "__main__":
1148 test()
1149
1150 # simple client transaction would look like
1151 """
1152 remote_uri = 'http://localhost:9999'
1153 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1154 send_str = "Hello_there"
1155 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1156 """