blob: 3c896d3817770871478e015148527ea76c7fd305 [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"
Wai-Hong Tam85b4ced2016-10-07 14:15:38 -070065 CCD_SERIAL = "ccd"
Kevin Cheng4b4f0022016-09-09 02:37:07 -070066
Kevin Chengdc3befd2016-07-15 12:34:00 -070067 def init_servo_interfaces(self, vendor, product, serialname,
68 interfaces):
69 """Init the servo interfaces with the given interfaces.
70
71 We don't use the self._{vendor,product,serialname} attributes because we
72 want to allow other callers to initialize other interfaces that may not
73 be associated with the initialized attributes (e.g. a servo v4 servod object
74 that wants to also initialize a servo micro interface).
75
76 Args:
77 vendor: USB vendor id of FTDI device.
78 product: USB product id of FTDI device.
79 serialname: String of device serialname/number as defined in FTDI
80 eeprom.
81 interfaces: List of strings of interface types the server will
82 instantiate.
83
84 Raises:
85 ServodError if unable to locate init method for particular interface.
86 """
87 # Extend the interface list if we need to.
88 interfaces_len = len(interfaces)
89 interface_list_len = len(self._interface_list)
90 if interfaces_len > interface_list_len:
91 self._interface_list += [None] * (interfaces_len - interface_list_len)
92
93 shifted = 0
94 for i, interface in enumerate(interfaces):
95 is_ftdi_interface = False
96 if type(interface) is dict:
97 name = interface['name']
98 # Store interface index for those that care about it.
99 interface['index'] = i
100 elif type(interface) is str and interface != 'dummy':
101 name = interface
102 # It's a FTDI related interface.
103 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
104 is_ftdi_interface = True
105 elif type(interface) is str and interface == 'dummy':
106 # 'dummy' reserves the interface for future use. Typically the
107 # interface will be managed by external third-party tools like
108 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
109 # it serves as a placeholder for servo micro interfaces.
110 continue
111 else:
112 raise ServodError("Illegal interface type %s" % type(interface))
113
114 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
115 if is_ftdi_interface and i and \
116 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
117 product += 1
118 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
119 product)
120
121 self._logger.info("Initializing interface %d to %s", i + 1, name)
122 try:
123 func = getattr(self, '_init_%s' % name)
124 except AttributeError:
125 raise ServodError("Unable to locate init for interface %s" % name)
126 result = func(vendor, product, serialname, interface)
127
128 if isinstance(result, tuple):
129 result_len = len(result)
130 shifted += result_len - 1
131 self._interface_list += [None] * result_len
132 for result_index, r in enumerate(result):
133 self._interface_list[i + result_index] = r
134 else:
135 self._interface_list[i + shifted] = result
136
J. Richard Barnettee2820552013-03-14 16:13:46 -0700137 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800138 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700139 """Servod constructor.
140
141 Args:
142 config: instance of SystemConfig containing all controls for
143 particular Servod invocation
144 vendor: usb vendor id of FTDI device
145 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700146 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700147 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700148 version: String. Servo board version. Examples: servo_v1, servo_v2,
149 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800150 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700151 sending keyboard commands to DUTs that do not have built in
152 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
153 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -0700154
155 Raises:
156 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700157 """
158 self._logger = logging.getLogger("Servod")
159 self._logger.debug("")
160 self._vendor = vendor
161 self._product = product
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700162 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700163 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700164 # Hold the last image path so we can reduce downloads to the usb device.
165 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700166 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
167 # interfaces are mapped to
168 self._interface_list = []
169 # Dict of Dict to map control name, function name to to tuple (params, drv)
170 # Ex) _drv_dict[name]['get'] = (params, drv)
171 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700172 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -0700173 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800174 self._usbkm232 = usbkm232
Kevin Chengc49494e2016-07-25 12:13:38 -0700175 # Seed the random generator with the serial to differentiate from other
176 # servod processes.
177 random.seed(serialname if serialname else time.time())
Todd Brochdbb09982011-10-02 07:14:26 -0700178 # Note, interface i is (i - 1) in list
179 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700180 try:
181 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
182 except KeyError:
183 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -0700184
Kevin Chengdc3befd2016-07-15 12:34:00 -0700185 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700186 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800187
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800188 def _init_keyboard_handler(self, servo, board=''):
189 """Initialize the correct keyboard handler for board.
190
Kevin Chengdc3befd2016-07-15 12:34:00 -0700191 Args:
192 servo: servo object.
193 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800194
Kevin Chengdc3befd2016-07-15 12:34:00 -0700195 Returns:
196 keyboard handler object.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800197 """
198 if board == 'parrot':
199 return keyboard_handlers.ParrotHandler(servo)
200 elif board == 'stout':
201 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800202 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800203 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
philipchenfc9eea12016-09-21 17:36:54 -0700204 'sumo', 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
205 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800206 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800207 logging.info("No device path specified for usbkm232 handler. Use "
208 "the servo atmega chip to handle.")
209 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800210 if self._usbkm232 == 'atmega':
211 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800212 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800213 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800214 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800215 self._usbkm232 = self.get('atmega_pty')
Kevin Cheng810fc782016-11-01 12:36:46 -0700216 # We don't need to set the atmega uart settings if we're a servo v4.
217 if self._version != 'servo_v4':
218 self.set('atmega_baudrate', '9600')
219 self.set('atmega_bits', 'eight')
220 self.set('atmega_parity', 'none')
221 self.set('atmega_sbits', 'one')
222 self.set('usb_mux_sel4', 'on')
223 self.set('usb_mux_oe4', 'on')
224 # Allow atmega bootup time.
225 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800226 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800227 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
228 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800229 # The following boards don't use Chrome EC.
230 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
231 return keyboard_handlers.MatrixKeyboardHandler(servo)
232 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800233
Todd Broch3ec8df02012-11-20 10:53:03 -0800234 def __del__(self):
235 """Servod deconstructor."""
236 for interface in self._interface_list:
237 del(interface)
238
Kevin Chengdc3befd2016-07-15 12:34:00 -0700239 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700240 """Dummy interface for ftdi devices.
241
242 This is a dummy function specifically for ftdi devices to not initialize
243 anything but to help pad the interface list.
244
245 Returns:
246 None.
247 """
248 return None
249
Kevin Chengdc3befd2016-07-15 12:34:00 -0700250 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700251 """Initialize gpio driver interface and open for use.
252
253 Args:
254 interface: interface number of FTDI device to use.
255
256 Returns:
257 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700258
259 Raises:
260 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700261 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700262 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700263 try:
264 fobj.open()
265 except ftdigpio.FgpioError as e:
266 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
267
Todd Broche505b8d2011-03-21 18:19:54 -0700268 return fobj
269
Kevin Chengdc3befd2016-07-15 12:34:00 -0700270 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800271 """Initialize stm32 uart interface and open for use
272
273 Note, the uart runs in a separate thread. Users wishing to
274 interact with it will query control for the pty's pathname and connect
275 with their favorite console program. For example:
276 cu -l /dev/pts/22
277
278 Args:
279 interface: dict of interface parameters.
280
281 Returns:
282 Instance object of interface
283
284 Raises:
285 ServodError: Raised on init failure.
286 """
287 self._logger.info("Suart: interface: %s" % interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700288 sobj = stm32uart.Suart(vendor, product, interface['interface'],
289 serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800290
291 try:
292 sobj.run()
293 except stm32uart.SuartError as e:
294 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
295
296 self._logger.info("%s" % sobj.get_pty())
297 return sobj
298
Kevin Chengdc3befd2016-07-15 12:34:00 -0700299 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800300 """Initialize stm32 gpio interface.
301 Args:
302 interface: interface number of stm32 device to use.
303
304 Returns:
305 Instance object of interface
306
307 Raises:
308 SgpioError: Raised on init failure.
309 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700310 interface_number = interface
311 # Interface could be a dict.
312 if type(interface) is dict:
313 interface_number = interface['interface']
314 self._logger.info("Sgpio: interface: %s" % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700315 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800316
Kevin Chengdc3befd2016-07-15 12:34:00 -0700317 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800318 """Initialize stm32 USB to I2C bridge interface and open for use
319
320 Args:
321 interface: USB interface number of stm32 device to use
322
323 Returns:
324 Instance object of interface.
325
326 Raises:
327 Si2cError: Raised on init failure.
328 """
329 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800330 port = interface.get('port', 0)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700331 return stm32i2c.Si2cBus(vendor, product, interface['interface'],
332 port=port, serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800333
Kevin Chengdc3befd2016-07-15 12:34:00 -0700334 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800335 """Initalize beaglebone ADC interface."""
336 return bbadc.BBadc()
337
Kevin Chengdc3befd2016-07-15 12:34:00 -0700338 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700339 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700340 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700341
Kevin Chengdc3befd2016-07-15 12:34:00 -0700342 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700343 """Initialize i2c interface and open for use.
344
345 Args:
346 interface: interface number of FTDI device to use
347
348 Returns:
349 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700350
351 Raises:
352 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700353 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700354 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700355 try:
356 fobj.open()
357 except ftdii2c.Fi2cError as e:
358 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
359
Todd Broche505b8d2011-03-21 18:19:54 -0700360 # Set the frequency of operation of the i2c bus.
361 # TODO(tbroch) make configureable
362 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700363
Todd Broche505b8d2011-03-21 18:19:54 -0700364 return fobj
365
Simran Basie750a342013-03-12 13:45:26 -0700366 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
367 def _init_bb_i2c(self, interface):
368 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700369 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700370
Kevin Chengdc3befd2016-07-15 12:34:00 -0700371 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800372 """Initalize Linux i2c-dev interface."""
373 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
374
Kevin Chengdc3befd2016-07-15 12:34:00 -0700375 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700376 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700377
378 Note, the uart runs in a separate thread (pthreads). Users wishing to
379 interact with it will query control for the pty's pathname and connect
380 with there favorite console program. For example:
381 cu -l /dev/pts/22
382
383 Args:
384 interface: interface number of FTDI device to use
385
386 Returns:
387 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700388
389 Raises:
390 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700391 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700392 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700393 try:
394 fobj.run()
395 except ftdiuart.FuartError as e:
396 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
397
Todd Broch47c43f42011-05-26 15:11:31 -0700398 self._logger.info("%s" % fobj.get_pty())
399 return fobj
400
Simran Basie750a342013-03-12 13:45:26 -0700401 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700402 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700403 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700404 logging.debug('UART INTERFACE: %s', interface)
405 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700406
Kevin Chengdc3befd2016-07-15 12:34:00 -0700407 def _init_ftdi_gpiouart(self, vendor, product, serialname,
408 interface):
Todd Broch888da782011-10-07 14:29:09 -0700409 """Initialize special gpio + uart interface and open for use
410
411 Note, the uart runs in a separate thread (pthreads). Users wishing to
412 interact with it will query control for the pty's pathname and connect
413 with there favorite console program. For example:
414 cu -l /dev/pts/22
415
416 Args:
417 interface: interface number of FTDI device to use
418
419 Returns:
420 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700421
422 Raises:
423 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700424 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700425 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700426 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700427 try:
428 fuart.run()
429 except ftdiuart.FuartError as e:
430 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
431
Todd Broch888da782011-10-07 14:29:09 -0700432 self._logger.info("uart pty: %s" % fuart.get_pty())
433 return fgpio, fuart
434
Kevin Chengdc3befd2016-07-15 12:34:00 -0700435 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800436 """Initialize EC-3PO console interpreter interface.
437
438 Args:
439 interface: A dictionary representing the interface.
440
441 Returns:
442 An EC3PO object representing the EC-3PO interface or None if there's no
443 interface for the USB PD UART.
444 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700445 vid = vendor
446 pid = product
Aseda Aboagyea4922212015-11-20 15:19:08 -0800447 # The current PID might be incremented if there are multiple FTDI.
448 # Therefore, try rewinding the PID back one if we don't find the base PID in
449 # the SERVO_ID_DEFAULTS
450 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
451 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
452 pid -= 1
453 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
454
Nick Sanders97bc4462016-01-04 15:37:31 -0800455 if 'raw_pty' in interface:
456 # We have specified an explicit target for this ec3po.
457 raw_uart_name = interface['raw_pty']
458 raw_ec_uart = self.get(raw_uart_name)
459
Aseda Aboagyea4922212015-11-20 15:19:08 -0800460 # Servo V2 / V3 should have the interface indicies in the same spot.
Nick Sanders97bc4462016-01-04 15:37:31 -0800461 elif ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
Aseda Aboagyea4922212015-11-20 15:19:08 -0800462 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
463 # Determine if it's a PD interface or just main EC console.
464 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
465 try:
466 # Obtain the raw EC UART PTY and create the EC-3PO interface.
467 raw_ec_uart = self.get('raw_usbpd_uart_pty')
468 except NameError:
469 # This overlay doesn't have a USB PD MCU, so skip init.
470 self._logger.info('No PD MCU UART.')
471 return None
472 except AttributeError:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700473 # This overlay has no get method for the interface so skip init. For
474 # servo v2, it's common for interfaces to be overridden such as
475 # reusing JTAG pins for the PD MCU UART instead. Therefore, print an
476 # error message indicating that the interface might be set
477 # incorrectly.
478 if (vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS:
479 self._logger.warn('No interface for PD MCU UART.')
480 self._logger.warn('Usually, this happens because the interface is '
481 'set incorrectly. If you\'re overriding an '
482 'existing interface, be sure to update the '
483 'interface lists for your board at the end of '
484 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800485 return None
486
487 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
488 raw_ec_uart = self.get('raw_ec_uart_pty')
489
490 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
491 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
492 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
493 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
494 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
495 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
496 raw_ec_uart = self.get('raw_ec_uart_pty')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800497 else:
498 raise ServodError(('Unexpected EC-3PO interface!'
499 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
500
501 return ec3po_interface.EC3PO(raw_ec_uart)
502
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800503 def _camel_case(self, string):
504 output = ''
505 for s in string.split('_'):
506 if output:
507 output += s.capitalize()
508 else:
509 output = s
510 return output
511
Todd Broche505b8d2011-03-21 18:19:54 -0700512 def _get_param_drv(self, control_name, is_get=True):
513 """Get access to driver for a given control.
514
515 Note, some controls have different parameter dictionaries for 'getting' the
516 control's value versus 'setting' it. Boolean is_get distinguishes which is
517 being requested.
518
519 Args:
520 control_name: string name of control
521 is_get: boolean to determine
522
523 Returns:
524 tuple (param, drv) where:
525 param: param dictionary for control
526 drv: instance object of driver for particular control
527
528 Raises:
529 ServodError: Error occurred while examining params dict
530 """
531 self._logger.debug("")
532 # if already setup just return tuple from driver dict
533 if control_name in self._drv_dict:
534 if is_get and ('get' in self._drv_dict[control_name]):
535 return self._drv_dict[control_name]['get']
536 if not is_get and ('set' in self._drv_dict[control_name]):
537 return self._drv_dict[control_name]['set']
538
539 params = self._syscfg.lookup_control_params(control_name, is_get)
540 if 'drv' not in params:
541 self._logger.error("Unable to determine driver for %s" % control_name)
542 raise ServodError("'drv' key not found in params dict")
543 if 'interface' not in params:
544 self._logger.error("Unable to determine interface for %s" %
545 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700546 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700547
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800548 interface_id = params.get(
549 '%s_interface' % self._version, params['interface'])
550 if interface_id == 'servo':
551 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700552 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800553 index = int(interface_id) - 1
554 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700555
Todd Broche505b8d2011-03-21 18:19:54 -0700556 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
557 drv_pkg = imp.load_module('drv',
558 *imp.find_module('drv', servo_pkg.__path__))
559 drv_name = params['drv']
560 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800561 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700562 drv = drv_class(interface, params)
563 if control_name not in self._drv_dict:
564 self._drv_dict[control_name] = {}
565 if is_get:
566 self._drv_dict[control_name]['get'] = (params, drv)
567 else:
568 self._drv_dict[control_name]['set'] = (params, drv)
569 return (params, drv)
570
571 def doc_all(self):
572 """Return all documenation for controls.
573
574 Returns:
575 string of <doc> text in config file (xml) and the params dictionary for
576 all controls.
577
578 For example:
579 warm_reset :: Reset the device warmly
580 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
581 """
582 return self._syscfg.display_config()
583
584 def doc(self, name):
585 """Retreive doc string in system config file for given control name.
586
587 Args:
588 name: name string of control to get doc string
589
590 Returns:
591 doc string of name
592
593 Raises:
594 NameError: if fails to locate control
595 """
596 self._logger.debug("name(%s)" % (name))
597 if self._syscfg.is_control(name):
598 return self._syscfg.get_control_docstring(name)
599 else:
600 raise NameError("No control %s" %name)
601
Fang Deng90377712013-06-03 15:51:48 -0700602 def _switch_usbkey(self, mux_direction):
603 """Connect USB flash stick to either servo or DUT.
604
605 This function switches 'usb_mux_sel1' to provide electrical
606 connection between the USB port J3 and either servo or DUT side.
607
608 Switching the usb mux is accompanied by powercycling
609 of the USB stick, because it sometimes gets wedged if the mux
610 is switched while the stick power is on.
611
612 Args:
613 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
614 """
615 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
616 time.sleep(self._USB_POWEROFF_DELAY)
617 self.set(self._USB_J3, mux_direction)
618 time.sleep(self._USB_POWEROFF_DELAY)
619 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
620 if mux_direction == self._USB_J3_TO_SERVO:
621 time.sleep(self._USB_DETECTION_DELAY)
622
Simran Basia9f41032012-05-11 14:21:58 -0700623 def _get_usb_port_set(self):
624 """Gets a set of USB disks currently connected to the system
625
626 Returns:
627 A set of USB disk paths.
628 """
629 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
630 return set(["/dev/" + dev for dev in usb_set])
631
Kevin Cheng5595b342016-09-29 15:51:01 -0700632 @contextlib.contextmanager
633 def _block_other_servod(self, timeout=None):
Kevin Chengc49494e2016-07-25 12:13:38 -0700634 """Block other servod processes by locking a file.
635
636 To enable multiple servods processes to safely probe_host_usb_dev, we use
637 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700638 for a usb device. This will be a context manager that will return
639 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700640
641 If the lock file exists, we open it and try to lock it.
642 - If another servod processes has locked it already, we'll sleep a random
643 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700644 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700645
Kevin Cheng5595b342016-09-29 15:51:01 -0700646 - If we're able to lock the file, we'll yield that the block was successful
647 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700648
649 This blocking behavior is only enabled if the lock file exists, if it
650 doesn't, then we pretend the block was successful.
651
Kevin Cheng5595b342016-09-29 15:51:01 -0700652 Args:
653 timeout: Max waiting time for the block to succeed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700654 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700655 if not os.path.exists(self._USB_LOCK_FILE):
656 # No lock file so we'll pretend the block was a success.
657 yield True
658 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700659 start_time = datetime.datetime.now()
660 while True:
Kevin Cheng5595b342016-09-29 15:51:01 -0700661 with open(self._USB_LOCK_FILE) as lock_file:
662 try:
663 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
664 yield True
665 fcntl.flock(lock_file, fcntl.LOCK_UN)
666 break
667 except IOError:
668 current_time = datetime.datetime.now()
669 current_wait_time = (current_time - start_time).total_seconds()
670 if timeout and current_wait_time > timeout:
671 yield False
672 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700673 # Sleep random amount.
674 sleep_time = time.sleep(random.random())
Kevin Chengc49494e2016-07-25 12:13:38 -0700675
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700676 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700677 """Toggle the usb power safely.
678
679 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700680
681 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700682 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700683 timeout: Timeout to wait for blocking other servod processes, default is
684 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700685
Kevin Cheng5595b342016-09-29 15:51:01 -0700686 Returns:
687 An empty string to appease the xmlrpc gods.
688 """
689 with self._block_other_servod(timeout=timeout):
690 if power_state != self.get(self._USB_J3_PWR):
691 self.set(self._USB_J3_PWR, power_state)
692 return ''
693
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700694 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700695 """Toggle the usb direction safely.
696
697 We'll make sure we're the only servod process toggling the usbkey direction.
698
699 Args:
700 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700701 timeout: Timeout to wait for blocking other servod processes, default is
702 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700703
704 Returns:
705 An empty string to appease the xmlrpc gods.
706 """
707 with self._block_other_servod(timeout=timeout):
708 self._switch_usbkey(mux_direction)
709 return ''
710
711 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700712 """Probe the USB disk device plugged in the servo from the host side.
713
714 Method can fail by:
715 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700716 another servo unless _USB_LOCK_FILE exists on the servo host. If that
717 file exists, then it is safe to probe for usb devices among multiple
718 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700719 2) Finding multiple /dev/sdX and returning None.
720
Kevin Cheng5595b342016-09-29 15:51:01 -0700721 Args:
722 timeout: Timeout to wait for blocking other servod processes.
723
Simran Basia9f41032012-05-11 14:21:58 -0700724 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700725 USB disk path if one and only one USB disk path is found, otherwise an
726 empty string.
Simran Basia9f41032012-05-11 14:21:58 -0700727 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700728 with self._block_other_servod(timeout=timeout) as block_success:
729 if not block_success:
730 return ''
Kevin Chengc49494e2016-07-25 12:13:38 -0700731
Kevin Cheng5595b342016-09-29 15:51:01 -0700732 original_value = self.get(self._USB_J3)
733 original_usb_power = self.get(self._USB_J3_PWR)
734 # Make the host unable to see the USB disk.
735 if (original_usb_power == self._USB_J3_PWR_ON and
736 original_value != self._USB_J3_TO_DUT):
737 self._switch_usbkey(self._USB_J3_TO_DUT)
738 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700739
Kevin Cheng5595b342016-09-29 15:51:01 -0700740 # Make the host able to see the USB disk.
741 self._switch_usbkey(self._USB_J3_TO_SERVO)
742 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700743
Kevin Cheng5595b342016-09-29 15:51:01 -0700744 # Back to its original value.
745 if original_value != self._USB_J3_TO_SERVO:
746 self._switch_usbkey(original_value)
747 if original_usb_power != self._USB_J3_PWR_ON:
748 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
749 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700750
Kevin Cheng5595b342016-09-29 15:51:01 -0700751 # Subtract the two sets to find the usb device.
752 diff_set = has_usb_set - no_usb_set
753 if len(diff_set) == 1:
754 return diff_set.pop()
755 else:
756 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700757
Kevin Cheng85831332016-10-13 13:14:44 -0700758 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700759 """Download image and save to the USB device found by probe_host_usb_dev.
760 If the image_path is a URL, it will download this url to the USB path;
761 otherwise it will simply copy the image_path's contents to the USB path.
762
763 Args:
764 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700765 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700766
767 Returns:
768 True|False: True if process completed successfully, False if error
769 occurred.
770 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
771 comment at the end of set().
772 """
773 self._logger.debug("image_path(%s)" % image_path)
774 self._logger.debug("Detecting USB stick device...")
Kevin Cheng85831332016-10-13 13:14:44 -0700775 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700776 if not usb_dev:
777 self._logger.error("No usb device connected to servo")
778 return False
779
Kevin Cheng9071ed92016-06-21 14:37:54 -0700780 # Let's check if we downloaded this last time and if so assume the image is
781 # still on the usb device and return True.
782 if self._image_path == image_path:
783 self._logger.debug("Image already on USB device, skipping transfer")
784 return True
785
Simran Basia9f41032012-05-11 14:21:58 -0700786 try:
787 if image_path.startswith(self._HTTP_PREFIX):
788 self._logger.debug("Image path is a URL, downloading image")
789 urllib.urlretrieve(image_path, usb_dev)
790 else:
791 shutil.copyfile(image_path, usb_dev)
792 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700793 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700794 e.strerror, e.errno)
795 return False
796 except urllib.ContentTooShortError:
797 self._logger.error("Failed to download URL: %s to USB device: %s",
798 image_path, usb_dev)
799 return False
800 except BaseException as e:
801 self._logger.error("Unexpected exception downloading %s to %s: %s",
802 image_path, usb_dev, str(e))
803 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800804 finally:
805 # We just plastered the partition table for a block device.
806 # Pass or fail, we mustn't go without telling the kernel about
807 # the change, or it will punish us with sporadic, hard-to-debug
808 # failures.
809 subprocess.call(["sync"])
810 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700811 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700812 return True
813
814 def make_image_noninteractive(self):
815 """Makes the recovery image noninteractive.
816
817 A noninteractive image will reboot automatically after installation
818 instead of waiting for the USB device to be removed to initiate a system
819 reboot.
820
821 Mounts partition 1 of the image stored on usb_dev and creates a file
822 called "non_interactive" so that the image will become noninteractive.
823
824 Returns:
825 True|False: True if process completed successfully, False if error
826 occurred.
827 """
828 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700829 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700830 if not usb_dev:
831 self._logger.error("No usb device connected to servo")
832 return False
833 # Create TempDirectory
834 tmpdir = tempfile.mkdtemp()
835 if tmpdir:
836 # Mount drive to tmpdir.
837 partition_1 = "%s1" % usb_dev
838 rc = subprocess.call(["mount", partition_1, tmpdir])
839 if rc == 0:
840 # Create file 'non_interactive'
841 non_interactive_file = os.path.join(tmpdir, "non_interactive")
842 try:
843 open(non_interactive_file, "w").close()
844 except IOError as e:
845 self._logger.error("Failed to create file %s : %s ( %d )",
846 non_interactive_file, e.strerror, e.errno)
847 result = False
848 except BaseException as e:
849 self._logger.error("Unexpected Exception creating file %s : %s",
850 non_interactive_file, str(e))
851 result = False
852 # Unmount drive regardless if file creation worked or not.
853 rc = subprocess.call(["umount", partition_1])
854 if rc != 0:
855 self._logger.error("Failed to unmount USB Device")
856 result = False
857 else:
858 self._logger.error("Failed to mount USB Device")
859 result = False
860
861 # Delete tmpdir. May throw exception if 'umount' failed.
862 try:
863 os.rmdir(tmpdir)
864 except OSError as e:
865 self._logger.error("Failed to remove temp directory %s : %s",
866 tmpdir, str(e))
867 return False
868 except BaseException as e:
869 self._logger.error("Unexpected Exception removing tempdir %s : %s",
870 tmpdir, str(e))
871 return False
872 else:
873 self._logger.error("Failed to create temp directory.")
874 return False
875 return result
876
Todd Broch352b4b22013-03-22 09:48:40 -0700877 def set_get_all(self, cmds):
878 """Set &| get one or more control values.
879
880 Args:
881 cmds: list of control[:value] to get or set.
882
883 Returns:
884 rv: list of responses from calling get or set methods.
885 """
886 rv = []
887 for cmd in cmds:
888 if ':' in cmd:
889 (control, value) = cmd.split(':')
890 rv.append(self.set(control, value))
891 else:
892 rv.append(self.get(cmd))
893 return rv
894
Todd Broche505b8d2011-03-21 18:19:54 -0700895 def get(self, name):
896 """Get control value.
897
898 Args:
899 name: name string of control
900
901 Returns:
902 Response from calling drv get method. Value is reformatted based on
903 control's dictionary parameters
904
905 Raises:
906 HwDriverError: Error occurred while using drv
907 """
908 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700909 if name == 'serialname':
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700910 if self._serialnames[self.MAIN_SERIAL]:
911 return self._serialnames[self.MAIN_SERIAL]
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700912 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700913 (param, drv) = self._get_param_drv(name)
914 try:
915 val = drv.get()
916 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800917 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700918 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700919 except AttributeError, error:
920 self._logger.error("Getting %s: %s" % (name, error))
921 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800922 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700923 self._logger.error("Getting %s" % (name))
924 raise
Todd Brochd6061672012-05-11 15:52:47 -0700925
Todd Broche505b8d2011-03-21 18:19:54 -0700926 def get_all(self, verbose):
927 """Get all controls values.
928
929 Args:
930 verbose: Boolean on whether to return doc info as well
931
932 Returns:
933 string creating from trying to get all values of all controls. In case of
934 error attempting access to control, response is 'ERR'.
935 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800936 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700937 for name in self._syscfg.syscfg_dict['control']:
938 self._logger.debug("name = %s" %name)
939 try:
940 value = self.get(name)
941 except Exception:
942 value = "ERR"
943 pass
944 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800945 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700946 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800947 rsp.append("%s:%s" % (name, value))
948 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700949
950 def set(self, name, wr_val_str):
951 """Set control.
952
953 Args:
954 name: name string of control
955 wr_val_str: value string to write. Can be integer, float or a
956 alpha-numerical that is mapped to a integer or float.
957
958 Raises:
959 HwDriverError: Error occurred while using driver
960 """
961 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
962 (params, drv) = self._get_param_drv(name, False)
963 wr_val = self._syscfg.resolve_val(params, wr_val_str)
964 try:
965 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800966 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700967 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
968 raise
969 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
970 # & client I still have to return something to appease the
971 # marshall/unmarshall
972 return True
973
Todd Brochd6061672012-05-11 15:52:47 -0700974 def hwinit(self, verbose=False):
975 """Initialize all controls.
976
977 These values are part of the system config XML files of the form
978 init=<value>. This command should be used by clients wishing to return the
979 servo and DUT its connected to a known good/safe state.
980
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800981 Note that initialization errors are ignored (as in some cases they could
982 be caused by DUT firmware deficiencies). This might need to be fine tuned
983 later.
984
Todd Brochd6061672012-05-11 15:52:47 -0700985 Args:
986 verbose: boolean, if True prints info about control initialized.
987 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800988
989 Returns:
990 This function is called across RPC and as such is expected to return
991 something unless transferring 'none' across is allowed. Hence adding a
992 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700993 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800994 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800995 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700996 # Workaround for bug chrome-os-partner:42349. Without this check, the
997 # gpio will briefly pulse low if we set it from high to high.
998 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700999 self.set(control_name, value)
1000 if verbose:
1001 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -08001002 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -08001003 self._logger.error("Problem initializing %s -> %s :: %s",
1004 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -08001005
1006 # Init keyboard after all the intefaces are up.
1007 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001008 return True
Todd Broch3ec8df02012-11-20 10:53:03 -08001009
Todd Broche505b8d2011-03-21 18:19:54 -07001010 def echo(self, echo):
1011 """Dummy echo function for testing/examples.
1012
1013 Args:
1014 echo: string to echo back to client
1015 """
1016 self._logger.debug("echo(%s)" % (echo))
1017 return "ECH0ING: %s" % (echo)
1018
J. Richard Barnettee2820552013-03-14 16:13:46 -07001019 def get_board(self):
1020 """Return the board specified at startup, if any."""
1021 return self._board
1022
Simran Basia23c1392013-08-06 14:59:10 -07001023 def get_version(self):
1024 """Get servo board version."""
1025 return self._version
1026
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001027 def power_long_press(self):
1028 """Simulate a long power button press."""
1029 # After a long power press, the EC may ignore the next power
1030 # button press (at least on Alex). To guarantee that this
1031 # won't happen, we need to allow the EC one second to
1032 # collect itself.
1033 self._keyboard.power_long_press()
1034 return True
1035
1036 def power_normal_press(self):
1037 """Simulate a normal power button press."""
1038 self._keyboard.power_normal_press()
1039 return True
1040
1041 def power_short_press(self):
1042 """Simulate a short power button press."""
1043 self._keyboard.power_short_press()
1044 return True
1045
1046 def power_key(self, secs=''):
1047 """Simulate a power button press.
1048
1049 Args:
1050 secs: Time in seconds to simulate the keypress.
1051 """
1052 self._keyboard.power_key(secs)
1053 return True
1054
1055 def ctrl_d(self, press_secs=''):
1056 """Simulate Ctrl-d simultaneous button presses."""
1057 self._keyboard.ctrl_d(press_secs)
1058 return True
1059
Victor Dodone539cea2016-03-29 18:50:17 -07001060 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001061 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001062 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001063 return True
1064
1065 def ctrl_enter(self, press_secs=''):
1066 """Simulate Ctrl-enter simultaneous button presses."""
1067 self._keyboard.ctrl_enter(press_secs)
1068 return True
1069
1070 def d_key(self, press_secs=''):
1071 """Simulate Enter key button press."""
1072 self._keyboard.d_key(press_secs)
1073 return True
1074
1075 def ctrl_key(self, press_secs=''):
1076 """Simulate Enter key button press."""
1077 self._keyboard.ctrl_key(press_secs)
1078 return True
1079
1080 def enter_key(self, press_secs=''):
1081 """Simulate Enter key button press."""
1082 self._keyboard.enter_key(press_secs)
1083 return True
1084
1085 def refresh_key(self, press_secs=''):
1086 """Simulate Refresh key (F3) button press."""
1087 self._keyboard.refresh_key(press_secs)
1088 return True
1089
1090 def ctrl_refresh_key(self, press_secs=''):
1091 """Simulate Ctrl and Refresh (F3) simultaneous press.
1092
1093 This key combination is an alternative of Space key.
1094 """
1095 self._keyboard.ctrl_refresh_key(press_secs)
1096 return True
1097
1098 def imaginary_key(self, press_secs=''):
1099 """Simulate imaginary key button press.
1100
1101 Maps to a key that doesn't physically exist.
1102 """
1103 self._keyboard.imaginary_key(press_secs)
1104 return True
1105
Todd Brochdbb09982011-10-02 07:14:26 -07001106
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001107 def sysrq_x(self, press_secs=''):
1108 """Simulate Alt VolumeUp X simultaneous press.
1109
1110 This key combination is the kernel system request (sysrq) x.
1111 """
1112 self._keyboard.sysrq_x(press_secs)
1113 return True
1114
1115
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001116 def get_servo_serials(self):
1117 """Return all the serials associated with this process."""
1118 return self._serialnames
1119
1120
Todd Broche505b8d2011-03-21 18:19:54 -07001121def test():
1122 """Integration testing.
1123
1124 TODO(tbroch) Enhance integration test and add unittest (see mox)
1125 """
1126 logging.basicConfig(level=logging.DEBUG,
1127 format="%(asctime)s - %(name)s - " +
1128 "%(levelname)s - %(message)s")
1129 # configure server & listen
1130 servod_obj = Servod(1)
1131 # 4 == number of interfaces on a FT4232H device
1132 for i in xrange(4):
1133 if i == 1:
1134 # its an i2c interface ... see __init__ for details and TODO to make
1135 # this configureable
1136 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1137 else:
1138 # its a gpio interface
1139 servod_obj._interface_list[i].wr_rd(0)
1140
1141 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1142 allow_none=True)
1143 server.register_introspection_functions()
1144 server.register_multicall_functions()
1145 server.register_instance(servod_obj)
1146 logging.info("Listening on localhost port 9999")
1147 server.serve_forever()
1148
1149if __name__ == "__main__":
1150 test()
1151
1152 # simple client transaction would look like
1153 """
1154 remote_uri = 'http://localhost:9999'
1155 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1156 send_str = "Hello_there"
1157 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1158 """