blob: 18c37ecaca21ea7e3bf82574a2d88569dfaf166a [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"
Wai-Hong Tam4b235922016-10-07 12:26:22 -070064 MICRO_SERVO_SERIAL = "micro_servo"
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)
129 shifted += result_len - 1
130 self._interface_list += [None] * result_len
131 for result_index, r in enumerate(result):
132 self._interface_list[i + result_index] = r
133 else:
134 self._interface_list[i + shifted] = result
135
J. Richard Barnettee2820552013-03-14 16:13:46 -0700136 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800137 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700138 """Servod constructor.
139
140 Args:
141 config: instance of SystemConfig containing all controls for
142 particular Servod invocation
143 vendor: usb vendor id of FTDI device
144 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700145 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700146 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700147 version: String. Servo board version. Examples: servo_v1, servo_v2,
148 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800149 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700150 sending keyboard commands to DUTs that do not have built in
151 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
152 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -0700153
154 Raises:
155 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700156 """
157 self._logger = logging.getLogger("Servod")
158 self._logger.debug("")
159 self._vendor = vendor
160 self._product = product
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700161 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700162 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700163 # Hold the last image path so we can reduce downloads to the usb device.
164 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700165 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
166 # interfaces are mapped to
167 self._interface_list = []
168 # Dict of Dict to map control name, function name to to tuple (params, drv)
169 # Ex) _drv_dict[name]['get'] = (params, drv)
170 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700171 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -0700172 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800173 self._usbkm232 = usbkm232
Kevin Chengc49494e2016-07-25 12:13:38 -0700174 # Seed the random generator with the serial to differentiate from other
175 # servod processes.
176 random.seed(serialname if serialname else time.time())
Todd Brochdbb09982011-10-02 07:14:26 -0700177 # Note, interface i is (i - 1) in list
178 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700179 try:
180 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
181 except KeyError:
182 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -0700183
Kevin Chengdc3befd2016-07-15 12:34:00 -0700184 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700185 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800186
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800187 def _init_keyboard_handler(self, servo, board=''):
188 """Initialize the correct keyboard handler for board.
189
Kevin Chengdc3befd2016-07-15 12:34:00 -0700190 Args:
191 servo: servo object.
192 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800193
Kevin Chengdc3befd2016-07-15 12:34:00 -0700194 Returns:
195 keyboard handler object.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800196 """
197 if board == 'parrot':
198 return keyboard_handlers.ParrotHandler(servo)
199 elif board == 'stout':
200 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800201 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800202 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
philipchenfc9eea12016-09-21 17:36:54 -0700203 'sumo', 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
204 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800205 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800206 logging.info("No device path specified for usbkm232 handler. Use "
207 "the servo atmega chip to handle.")
208 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800209 if self._usbkm232 == 'atmega':
210 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800211 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800212 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800213 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800214 self._usbkm232 = self.get('atmega_pty')
Kevin Cheng810fc782016-11-01 12:36:46 -0700215 # We don't need to set the atmega uart settings if we're a servo v4.
216 if self._version != 'servo_v4':
217 self.set('atmega_baudrate', '9600')
218 self.set('atmega_bits', 'eight')
219 self.set('atmega_parity', 'none')
220 self.set('atmega_sbits', 'one')
221 self.set('usb_mux_sel4', 'on')
222 self.set('usb_mux_oe4', 'on')
223 # Allow atmega bootup time.
224 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800225 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800226 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
227 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800228 # The following boards don't use Chrome EC.
229 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
230 return keyboard_handlers.MatrixKeyboardHandler(servo)
231 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800232
Todd Broch3ec8df02012-11-20 10:53:03 -0800233 def __del__(self):
234 """Servod deconstructor."""
235 for interface in self._interface_list:
236 del(interface)
237
Kevin Chengdc3befd2016-07-15 12:34:00 -0700238 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700239 """Dummy interface for ftdi devices.
240
241 This is a dummy function specifically for ftdi devices to not initialize
242 anything but to help pad the interface list.
243
244 Returns:
245 None.
246 """
247 return None
248
Kevin Chengdc3befd2016-07-15 12:34:00 -0700249 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700250 """Initialize gpio driver interface and open for use.
251
252 Args:
253 interface: interface number of FTDI device to use.
254
255 Returns:
256 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700257
258 Raises:
259 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700260 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700261 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700262 try:
263 fobj.open()
264 except ftdigpio.FgpioError as e:
265 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
266
Todd Broche505b8d2011-03-21 18:19:54 -0700267 return fobj
268
Kevin Chengdc3befd2016-07-15 12:34:00 -0700269 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800270 """Initialize stm32 uart interface and open for use
271
272 Note, the uart runs in a separate thread. Users wishing to
273 interact with it will query control for the pty's pathname and connect
274 with their favorite console program. For example:
275 cu -l /dev/pts/22
276
277 Args:
278 interface: dict of interface parameters.
279
280 Returns:
281 Instance object of interface
282
283 Raises:
284 ServodError: Raised on init failure.
285 """
286 self._logger.info("Suart: interface: %s" % interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700287 sobj = stm32uart.Suart(vendor, product, interface['interface'],
288 serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800289
290 try:
291 sobj.run()
292 except stm32uart.SuartError as e:
293 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
294
295 self._logger.info("%s" % sobj.get_pty())
296 return sobj
297
Kevin Chengdc3befd2016-07-15 12:34:00 -0700298 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800299 """Initialize stm32 gpio interface.
300 Args:
301 interface: interface number of stm32 device to use.
302
303 Returns:
304 Instance object of interface
305
306 Raises:
307 SgpioError: Raised on init failure.
308 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700309 interface_number = interface
310 # Interface could be a dict.
311 if type(interface) is dict:
312 interface_number = interface['interface']
313 self._logger.info("Sgpio: interface: %s" % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700314 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800315
Kevin Chengdc3befd2016-07-15 12:34:00 -0700316 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800317 """Initialize stm32 USB to I2C bridge interface and open for use
318
319 Args:
320 interface: USB interface number of stm32 device to use
321
322 Returns:
323 Instance object of interface.
324
325 Raises:
326 Si2cError: Raised on init failure.
327 """
328 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800329 port = interface.get('port', 0)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700330 return stm32i2c.Si2cBus(vendor, product, interface['interface'],
331 port=port, serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800332
Kevin Chengdc3befd2016-07-15 12:34:00 -0700333 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800334 """Initalize beaglebone ADC interface."""
335 return bbadc.BBadc()
336
Kevin Chengdc3befd2016-07-15 12:34:00 -0700337 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700338 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700339 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700340
Kevin Chengdc3befd2016-07-15 12:34:00 -0700341 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700342 """Initialize i2c interface and open for use.
343
344 Args:
345 interface: interface number of FTDI device to use
346
347 Returns:
348 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700349
350 Raises:
351 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700352 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700353 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700354 try:
355 fobj.open()
356 except ftdii2c.Fi2cError as e:
357 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
358
Todd Broche505b8d2011-03-21 18:19:54 -0700359 # Set the frequency of operation of the i2c bus.
360 # TODO(tbroch) make configureable
361 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700362
Todd Broche505b8d2011-03-21 18:19:54 -0700363 return fobj
364
Simran Basie750a342013-03-12 13:45:26 -0700365 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
366 def _init_bb_i2c(self, interface):
367 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700368 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700369
Kevin Chengdc3befd2016-07-15 12:34:00 -0700370 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800371 """Initalize Linux i2c-dev interface."""
372 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
373
Kevin Chengdc3befd2016-07-15 12:34:00 -0700374 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700375 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700376
377 Note, the uart runs in a separate thread (pthreads). Users wishing to
378 interact with it will query control for the pty's pathname and connect
379 with there favorite console program. For example:
380 cu -l /dev/pts/22
381
382 Args:
383 interface: interface number of FTDI device to use
384
385 Returns:
386 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700387
388 Raises:
389 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700390 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700391 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700392 try:
393 fobj.run()
394 except ftdiuart.FuartError as e:
395 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
396
Todd Broch47c43f42011-05-26 15:11:31 -0700397 self._logger.info("%s" % fobj.get_pty())
398 return fobj
399
Simran Basie750a342013-03-12 13:45:26 -0700400 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700401 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700402 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700403 logging.debug('UART INTERFACE: %s', interface)
404 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700405
Kevin Chengdc3befd2016-07-15 12:34:00 -0700406 def _init_ftdi_gpiouart(self, vendor, product, serialname,
407 interface):
Todd Broch888da782011-10-07 14:29:09 -0700408 """Initialize special gpio + uart interface and open for use
409
410 Note, the uart runs in a separate thread (pthreads). Users wishing to
411 interact with it will query control for the pty's pathname and connect
412 with there favorite console program. For example:
413 cu -l /dev/pts/22
414
415 Args:
416 interface: interface number of FTDI device to use
417
418 Returns:
419 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700420
421 Raises:
422 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700423 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700424 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700425 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700426 try:
427 fuart.run()
428 except ftdiuart.FuartError as e:
429 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
430
Todd Broch888da782011-10-07 14:29:09 -0700431 self._logger.info("uart pty: %s" % fuart.get_pty())
432 return fgpio, fuart
433
Kevin Chengdc3befd2016-07-15 12:34:00 -0700434 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800435 """Initialize EC-3PO console interpreter interface.
436
437 Args:
438 interface: A dictionary representing the interface.
439
440 Returns:
441 An EC3PO object representing the EC-3PO interface or None if there's no
442 interface for the USB PD UART.
443 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700444 vid = vendor
445 pid = product
Aseda Aboagyea4922212015-11-20 15:19:08 -0800446 # The current PID might be incremented if there are multiple FTDI.
447 # Therefore, try rewinding the PID back one if we don't find the base PID in
448 # the SERVO_ID_DEFAULTS
449 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
450 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
451 pid -= 1
452 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
453
Nick Sanders97bc4462016-01-04 15:37:31 -0800454 if 'raw_pty' in interface:
455 # We have specified an explicit target for this ec3po.
456 raw_uart_name = interface['raw_pty']
457 raw_ec_uart = self.get(raw_uart_name)
458
Aseda Aboagyea4922212015-11-20 15:19:08 -0800459 # Servo V2 / V3 should have the interface indicies in the same spot.
Nick Sanders97bc4462016-01-04 15:37:31 -0800460 elif ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
Aseda Aboagyea4922212015-11-20 15:19:08 -0800461 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
462 # Determine if it's a PD interface or just main EC console.
463 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
464 try:
465 # Obtain the raw EC UART PTY and create the EC-3PO interface.
466 raw_ec_uart = self.get('raw_usbpd_uart_pty')
467 except NameError:
468 # This overlay doesn't have a USB PD MCU, so skip init.
469 self._logger.info('No PD MCU UART.')
470 return None
471 except AttributeError:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700472 # This overlay has no get method for the interface so skip init. For
473 # servo v2, it's common for interfaces to be overridden such as
474 # reusing JTAG pins for the PD MCU UART instead. Therefore, print an
475 # error message indicating that the interface might be set
476 # incorrectly.
477 if (vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS:
478 self._logger.warn('No interface for PD MCU UART.')
479 self._logger.warn('Usually, this happens because the interface is '
480 'set incorrectly. If you\'re overriding an '
481 'existing interface, be sure to update the '
482 'interface lists for your board at the end of '
483 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800484 return None
485
486 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
487 raw_ec_uart = self.get('raw_ec_uart_pty')
488
489 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
490 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
491 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
492 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
493 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
494 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
495 raw_ec_uart = self.get('raw_ec_uart_pty')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800496 else:
497 raise ServodError(('Unexpected EC-3PO interface!'
498 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
499
500 return ec3po_interface.EC3PO(raw_ec_uart)
501
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800502 def _camel_case(self, string):
503 output = ''
504 for s in string.split('_'):
505 if output:
506 output += s.capitalize()
507 else:
508 output = s
509 return output
510
Todd Broche505b8d2011-03-21 18:19:54 -0700511 def _get_param_drv(self, control_name, is_get=True):
512 """Get access to driver for a given control.
513
514 Note, some controls have different parameter dictionaries for 'getting' the
515 control's value versus 'setting' it. Boolean is_get distinguishes which is
516 being requested.
517
518 Args:
519 control_name: string name of control
520 is_get: boolean to determine
521
522 Returns:
523 tuple (param, drv) where:
524 param: param dictionary for control
525 drv: instance object of driver for particular control
526
527 Raises:
528 ServodError: Error occurred while examining params dict
529 """
530 self._logger.debug("")
531 # if already setup just return tuple from driver dict
532 if control_name in self._drv_dict:
533 if is_get and ('get' in self._drv_dict[control_name]):
534 return self._drv_dict[control_name]['get']
535 if not is_get and ('set' in self._drv_dict[control_name]):
536 return self._drv_dict[control_name]['set']
537
538 params = self._syscfg.lookup_control_params(control_name, is_get)
539 if 'drv' not in params:
540 self._logger.error("Unable to determine driver for %s" % control_name)
541 raise ServodError("'drv' key not found in params dict")
542 if 'interface' not in params:
543 self._logger.error("Unable to determine interface for %s" %
544 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700545 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700546
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800547 interface_id = params.get(
548 '%s_interface' % self._version, params['interface'])
549 if interface_id == 'servo':
550 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700551 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800552 index = int(interface_id) - 1
553 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700554
Todd Broche505b8d2011-03-21 18:19:54 -0700555 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
556 drv_pkg = imp.load_module('drv',
557 *imp.find_module('drv', servo_pkg.__path__))
558 drv_name = params['drv']
559 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800560 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700561 drv = drv_class(interface, params)
562 if control_name not in self._drv_dict:
563 self._drv_dict[control_name] = {}
564 if is_get:
565 self._drv_dict[control_name]['get'] = (params, drv)
566 else:
567 self._drv_dict[control_name]['set'] = (params, drv)
568 return (params, drv)
569
570 def doc_all(self):
571 """Return all documenation for controls.
572
573 Returns:
574 string of <doc> text in config file (xml) and the params dictionary for
575 all controls.
576
577 For example:
578 warm_reset :: Reset the device warmly
579 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
580 """
581 return self._syscfg.display_config()
582
583 def doc(self, name):
584 """Retreive doc string in system config file for given control name.
585
586 Args:
587 name: name string of control to get doc string
588
589 Returns:
590 doc string of name
591
592 Raises:
593 NameError: if fails to locate control
594 """
595 self._logger.debug("name(%s)" % (name))
596 if self._syscfg.is_control(name):
597 return self._syscfg.get_control_docstring(name)
598 else:
599 raise NameError("No control %s" %name)
600
Fang Deng90377712013-06-03 15:51:48 -0700601 def _switch_usbkey(self, mux_direction):
602 """Connect USB flash stick to either servo or DUT.
603
604 This function switches 'usb_mux_sel1' to provide electrical
605 connection between the USB port J3 and either servo or DUT side.
606
607 Switching the usb mux is accompanied by powercycling
608 of the USB stick, because it sometimes gets wedged if the mux
609 is switched while the stick power is on.
610
611 Args:
612 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
613 """
614 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
615 time.sleep(self._USB_POWEROFF_DELAY)
616 self.set(self._USB_J3, mux_direction)
617 time.sleep(self._USB_POWEROFF_DELAY)
618 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
619 if mux_direction == self._USB_J3_TO_SERVO:
620 time.sleep(self._USB_DETECTION_DELAY)
621
Simran Basia9f41032012-05-11 14:21:58 -0700622 def _get_usb_port_set(self):
623 """Gets a set of USB disks currently connected to the system
624
625 Returns:
626 A set of USB disk paths.
627 """
628 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
629 return set(["/dev/" + dev for dev in usb_set])
630
Kevin Cheng5595b342016-09-29 15:51:01 -0700631 @contextlib.contextmanager
632 def _block_other_servod(self, timeout=None):
Kevin Chengc49494e2016-07-25 12:13:38 -0700633 """Block other servod processes by locking a file.
634
635 To enable multiple servods processes to safely probe_host_usb_dev, we use
636 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700637 for a usb device. This will be a context manager that will return
638 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700639
640 If the lock file exists, we open it and try to lock it.
641 - If another servod processes has locked it already, we'll sleep a random
642 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700643 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700644
Kevin Cheng5595b342016-09-29 15:51:01 -0700645 - If we're able to lock the file, we'll yield that the block was successful
646 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700647
648 This blocking behavior is only enabled if the lock file exists, if it
649 doesn't, then we pretend the block was successful.
650
Kevin Cheng5595b342016-09-29 15:51:01 -0700651 Args:
652 timeout: Max waiting time for the block to succeed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700653 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700654 if not os.path.exists(self._USB_LOCK_FILE):
655 # No lock file so we'll pretend the block was a success.
656 yield True
657 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700658 start_time = datetime.datetime.now()
659 while True:
Kevin Cheng5595b342016-09-29 15:51:01 -0700660 with open(self._USB_LOCK_FILE) as lock_file:
661 try:
662 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
663 yield True
664 fcntl.flock(lock_file, fcntl.LOCK_UN)
665 break
666 except IOError:
667 current_time = datetime.datetime.now()
668 current_wait_time = (current_time - start_time).total_seconds()
669 if timeout and current_wait_time > timeout:
670 yield False
671 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700672 # Sleep random amount.
673 sleep_time = time.sleep(random.random())
Kevin Chengc49494e2016-07-25 12:13:38 -0700674
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700675 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700676 """Toggle the usb power safely.
677
678 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700679
680 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700681 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700682 timeout: Timeout to wait for blocking other servod processes, default is
683 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700684
Kevin Cheng5595b342016-09-29 15:51:01 -0700685 Returns:
686 An empty string to appease the xmlrpc gods.
687 """
688 with self._block_other_servod(timeout=timeout):
689 if power_state != self.get(self._USB_J3_PWR):
690 self.set(self._USB_J3_PWR, power_state)
691 return ''
692
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700693 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700694 """Toggle the usb direction safely.
695
696 We'll make sure we're the only servod process toggling the usbkey direction.
697
698 Args:
699 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700700 timeout: Timeout to wait for blocking other servod processes, default is
701 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700702
703 Returns:
704 An empty string to appease the xmlrpc gods.
705 """
706 with self._block_other_servod(timeout=timeout):
707 self._switch_usbkey(mux_direction)
708 return ''
709
710 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700711 """Probe the USB disk device plugged in the servo from the host side.
712
713 Method can fail by:
714 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700715 another servo unless _USB_LOCK_FILE exists on the servo host. If that
716 file exists, then it is safe to probe for usb devices among multiple
717 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700718 2) Finding multiple /dev/sdX and returning None.
719
Kevin Cheng5595b342016-09-29 15:51:01 -0700720 Args:
721 timeout: Timeout to wait for blocking other servod processes.
722
Simran Basia9f41032012-05-11 14:21:58 -0700723 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700724 USB disk path if one and only one USB disk path is found, otherwise an
725 empty string.
Simran Basia9f41032012-05-11 14:21:58 -0700726 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700727 with self._block_other_servod(timeout=timeout) as block_success:
728 if not block_success:
729 return ''
Kevin Chengc49494e2016-07-25 12:13:38 -0700730
Kevin Cheng5595b342016-09-29 15:51:01 -0700731 original_value = self.get(self._USB_J3)
732 original_usb_power = self.get(self._USB_J3_PWR)
733 # Make the host unable to see the USB disk.
734 if (original_usb_power == self._USB_J3_PWR_ON and
735 original_value != self._USB_J3_TO_DUT):
736 self._switch_usbkey(self._USB_J3_TO_DUT)
737 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700738
Kevin Cheng5595b342016-09-29 15:51:01 -0700739 # Make the host able to see the USB disk.
740 self._switch_usbkey(self._USB_J3_TO_SERVO)
741 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700742
Kevin Cheng5595b342016-09-29 15:51:01 -0700743 # Back to its original value.
744 if original_value != self._USB_J3_TO_SERVO:
745 self._switch_usbkey(original_value)
746 if original_usb_power != self._USB_J3_PWR_ON:
747 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
748 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700749
Kevin Cheng5595b342016-09-29 15:51:01 -0700750 # Subtract the two sets to find the usb device.
751 diff_set = has_usb_set - no_usb_set
752 if len(diff_set) == 1:
753 return diff_set.pop()
754 else:
755 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700756
Kevin Cheng85831332016-10-13 13:14:44 -0700757 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700758 """Download image and save to the USB device found by probe_host_usb_dev.
759 If the image_path is a URL, it will download this url to the USB path;
760 otherwise it will simply copy the image_path's contents to the USB path.
761
762 Args:
763 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700764 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700765
766 Returns:
767 True|False: True if process completed successfully, False if error
768 occurred.
769 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
770 comment at the end of set().
771 """
772 self._logger.debug("image_path(%s)" % image_path)
773 self._logger.debug("Detecting USB stick device...")
Kevin Cheng85831332016-10-13 13:14:44 -0700774 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700775 if not usb_dev:
776 self._logger.error("No usb device connected to servo")
777 return False
778
Kevin Cheng9071ed92016-06-21 14:37:54 -0700779 # Let's check if we downloaded this last time and if so assume the image is
780 # still on the usb device and return True.
781 if self._image_path == image_path:
782 self._logger.debug("Image already on USB device, skipping transfer")
783 return True
784
Simran Basia9f41032012-05-11 14:21:58 -0700785 try:
786 if image_path.startswith(self._HTTP_PREFIX):
787 self._logger.debug("Image path is a URL, downloading image")
788 urllib.urlretrieve(image_path, usb_dev)
789 else:
790 shutil.copyfile(image_path, usb_dev)
791 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700792 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700793 e.strerror, e.errno)
794 return False
795 except urllib.ContentTooShortError:
796 self._logger.error("Failed to download URL: %s to USB device: %s",
797 image_path, usb_dev)
798 return False
799 except BaseException as e:
800 self._logger.error("Unexpected exception downloading %s to %s: %s",
801 image_path, usb_dev, str(e))
802 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800803 finally:
804 # We just plastered the partition table for a block device.
805 # Pass or fail, we mustn't go without telling the kernel about
806 # the change, or it will punish us with sporadic, hard-to-debug
807 # failures.
808 subprocess.call(["sync"])
809 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700810 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700811 return True
812
813 def make_image_noninteractive(self):
814 """Makes the recovery image noninteractive.
815
816 A noninteractive image will reboot automatically after installation
817 instead of waiting for the USB device to be removed to initiate a system
818 reboot.
819
820 Mounts partition 1 of the image stored on usb_dev and creates a file
821 called "non_interactive" so that the image will become noninteractive.
822
823 Returns:
824 True|False: True if process completed successfully, False if error
825 occurred.
826 """
827 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700828 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700829 if not usb_dev:
830 self._logger.error("No usb device connected to servo")
831 return False
832 # Create TempDirectory
833 tmpdir = tempfile.mkdtemp()
834 if tmpdir:
835 # Mount drive to tmpdir.
836 partition_1 = "%s1" % usb_dev
837 rc = subprocess.call(["mount", partition_1, tmpdir])
838 if rc == 0:
839 # Create file 'non_interactive'
840 non_interactive_file = os.path.join(tmpdir, "non_interactive")
841 try:
842 open(non_interactive_file, "w").close()
843 except IOError as e:
844 self._logger.error("Failed to create file %s : %s ( %d )",
845 non_interactive_file, e.strerror, e.errno)
846 result = False
847 except BaseException as e:
848 self._logger.error("Unexpected Exception creating file %s : %s",
849 non_interactive_file, str(e))
850 result = False
851 # Unmount drive regardless if file creation worked or not.
852 rc = subprocess.call(["umount", partition_1])
853 if rc != 0:
854 self._logger.error("Failed to unmount USB Device")
855 result = False
856 else:
857 self._logger.error("Failed to mount USB Device")
858 result = False
859
860 # Delete tmpdir. May throw exception if 'umount' failed.
861 try:
862 os.rmdir(tmpdir)
863 except OSError as e:
864 self._logger.error("Failed to remove temp directory %s : %s",
865 tmpdir, str(e))
866 return False
867 except BaseException as e:
868 self._logger.error("Unexpected Exception removing tempdir %s : %s",
869 tmpdir, str(e))
870 return False
871 else:
872 self._logger.error("Failed to create temp directory.")
873 return False
874 return result
875
Todd Broch352b4b22013-03-22 09:48:40 -0700876 def set_get_all(self, cmds):
877 """Set &| get one or more control values.
878
879 Args:
880 cmds: list of control[:value] to get or set.
881
882 Returns:
883 rv: list of responses from calling get or set methods.
884 """
885 rv = []
886 for cmd in cmds:
887 if ':' in cmd:
888 (control, value) = cmd.split(':')
889 rv.append(self.set(control, value))
890 else:
891 rv.append(self.get(cmd))
892 return rv
893
Todd Broche505b8d2011-03-21 18:19:54 -0700894 def get(self, name):
895 """Get control value.
896
897 Args:
898 name: name string of control
899
900 Returns:
901 Response from calling drv get method. Value is reformatted based on
902 control's dictionary parameters
903
904 Raises:
905 HwDriverError: Error occurred while using drv
906 """
907 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700908 if name == 'serialname':
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700909 if self._serialnames[self.MAIN_SERIAL]:
910 return self._serialnames[self.MAIN_SERIAL]
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700911 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700912 (param, drv) = self._get_param_drv(name)
913 try:
914 val = drv.get()
915 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800916 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700917 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700918 except AttributeError, error:
919 self._logger.error("Getting %s: %s" % (name, error))
920 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800921 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700922 self._logger.error("Getting %s" % (name))
923 raise
Todd Brochd6061672012-05-11 15:52:47 -0700924
Todd Broche505b8d2011-03-21 18:19:54 -0700925 def get_all(self, verbose):
926 """Get all controls values.
927
928 Args:
929 verbose: Boolean on whether to return doc info as well
930
931 Returns:
932 string creating from trying to get all values of all controls. In case of
933 error attempting access to control, response is 'ERR'.
934 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800935 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700936 for name in self._syscfg.syscfg_dict['control']:
937 self._logger.debug("name = %s" %name)
938 try:
939 value = self.get(name)
940 except Exception:
941 value = "ERR"
942 pass
943 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800944 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700945 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800946 rsp.append("%s:%s" % (name, value))
947 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700948
949 def set(self, name, wr_val_str):
950 """Set control.
951
952 Args:
953 name: name string of control
954 wr_val_str: value string to write. Can be integer, float or a
955 alpha-numerical that is mapped to a integer or float.
956
957 Raises:
958 HwDriverError: Error occurred while using driver
959 """
960 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
961 (params, drv) = self._get_param_drv(name, False)
962 wr_val = self._syscfg.resolve_val(params, wr_val_str)
963 try:
964 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800965 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700966 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
967 raise
968 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
969 # & client I still have to return something to appease the
970 # marshall/unmarshall
971 return True
972
Todd Brochd6061672012-05-11 15:52:47 -0700973 def hwinit(self, verbose=False):
974 """Initialize all controls.
975
976 These values are part of the system config XML files of the form
977 init=<value>. This command should be used by clients wishing to return the
978 servo and DUT its connected to a known good/safe state.
979
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800980 Note that initialization errors are ignored (as in some cases they could
981 be caused by DUT firmware deficiencies). This might need to be fine tuned
982 later.
983
Todd Brochd6061672012-05-11 15:52:47 -0700984 Args:
985 verbose: boolean, if True prints info about control initialized.
986 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800987
988 Returns:
989 This function is called across RPC and as such is expected to return
990 something unless transferring 'none' across is allowed. Hence adding a
991 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700992 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800993 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800994 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700995 # Workaround for bug chrome-os-partner:42349. Without this check, the
996 # gpio will briefly pulse low if we set it from high to high.
997 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700998 self.set(control_name, value)
999 if verbose:
1000 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -08001001 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -08001002 self._logger.error("Problem initializing %s -> %s :: %s",
1003 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -08001004
1005 # Init keyboard after all the intefaces are up.
1006 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001007 return True
Todd Broch3ec8df02012-11-20 10:53:03 -08001008
Todd Broche505b8d2011-03-21 18:19:54 -07001009 def echo(self, echo):
1010 """Dummy echo function for testing/examples.
1011
1012 Args:
1013 echo: string to echo back to client
1014 """
1015 self._logger.debug("echo(%s)" % (echo))
1016 return "ECH0ING: %s" % (echo)
1017
J. Richard Barnettee2820552013-03-14 16:13:46 -07001018 def get_board(self):
1019 """Return the board specified at startup, if any."""
1020 return self._board
1021
Simran Basia23c1392013-08-06 14:59:10 -07001022 def get_version(self):
1023 """Get servo board version."""
1024 return self._version
1025
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001026 def power_long_press(self):
1027 """Simulate a long power button press."""
1028 # After a long power press, the EC may ignore the next power
1029 # button press (at least on Alex). To guarantee that this
1030 # won't happen, we need to allow the EC one second to
1031 # collect itself.
1032 self._keyboard.power_long_press()
1033 return True
1034
1035 def power_normal_press(self):
1036 """Simulate a normal power button press."""
1037 self._keyboard.power_normal_press()
1038 return True
1039
1040 def power_short_press(self):
1041 """Simulate a short power button press."""
1042 self._keyboard.power_short_press()
1043 return True
1044
1045 def power_key(self, secs=''):
1046 """Simulate a power button press.
1047
1048 Args:
1049 secs: Time in seconds to simulate the keypress.
1050 """
1051 self._keyboard.power_key(secs)
1052 return True
1053
1054 def ctrl_d(self, press_secs=''):
1055 """Simulate Ctrl-d simultaneous button presses."""
1056 self._keyboard.ctrl_d(press_secs)
1057 return True
1058
Victor Dodone539cea2016-03-29 18:50:17 -07001059 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001060 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001061 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001062 return True
1063
1064 def ctrl_enter(self, press_secs=''):
1065 """Simulate Ctrl-enter simultaneous button presses."""
1066 self._keyboard.ctrl_enter(press_secs)
1067 return True
1068
1069 def d_key(self, press_secs=''):
1070 """Simulate Enter key button press."""
1071 self._keyboard.d_key(press_secs)
1072 return True
1073
1074 def ctrl_key(self, press_secs=''):
1075 """Simulate Enter key button press."""
1076 self._keyboard.ctrl_key(press_secs)
1077 return True
1078
1079 def enter_key(self, press_secs=''):
1080 """Simulate Enter key button press."""
1081 self._keyboard.enter_key(press_secs)
1082 return True
1083
1084 def refresh_key(self, press_secs=''):
1085 """Simulate Refresh key (F3) button press."""
1086 self._keyboard.refresh_key(press_secs)
1087 return True
1088
1089 def ctrl_refresh_key(self, press_secs=''):
1090 """Simulate Ctrl and Refresh (F3) simultaneous press.
1091
1092 This key combination is an alternative of Space key.
1093 """
1094 self._keyboard.ctrl_refresh_key(press_secs)
1095 return True
1096
1097 def imaginary_key(self, press_secs=''):
1098 """Simulate imaginary key button press.
1099
1100 Maps to a key that doesn't physically exist.
1101 """
1102 self._keyboard.imaginary_key(press_secs)
1103 return True
1104
Todd Brochdbb09982011-10-02 07:14:26 -07001105
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001106 def sysrq_x(self, press_secs=''):
1107 """Simulate Alt VolumeUp X simultaneous press.
1108
1109 This key combination is the kernel system request (sysrq) x.
1110 """
1111 self._keyboard.sysrq_x(press_secs)
1112 return True
1113
1114
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001115 def get_servo_serials(self):
1116 """Return all the serials associated with this process."""
1117 return self._serialnames
1118
1119
Todd Broche505b8d2011-03-21 18:19:54 -07001120def test():
1121 """Integration testing.
1122
1123 TODO(tbroch) Enhance integration test and add unittest (see mox)
1124 """
1125 logging.basicConfig(level=logging.DEBUG,
1126 format="%(asctime)s - %(name)s - " +
1127 "%(levelname)s - %(message)s")
1128 # configure server & listen
1129 servod_obj = Servod(1)
1130 # 4 == number of interfaces on a FT4232H device
1131 for i in xrange(4):
1132 if i == 1:
1133 # its an i2c interface ... see __init__ for details and TODO to make
1134 # this configureable
1135 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1136 else:
1137 # its a gpio interface
1138 servod_obj._interface_list[i].wr_rd(0)
1139
1140 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1141 allow_none=True)
1142 server.register_introspection_functions()
1143 server.register_multicall_functions()
1144 server.register_instance(servod_obj)
1145 logging.info("Listening on localhost port 9999")
1146 server.serve_forever()
1147
1148if __name__ == "__main__":
1149 test()
1150
1151 # simple client transaction would look like
1152 """
1153 remote_uri = 'http://localhost:9999'
1154 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1155 send_str = "Hello_there"
1156 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1157 """