blob: 9c7f326ec3b8e40897a1f6b5195afe03d4b3cf7e [file] [log] [blame]
Simran Basia9f41032012-05-11 14:21:58 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Todd Broche505b8d2011-03-21 18:19:54 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""Servo Server."""
Kevin Cheng5595b342016-09-29 15:51:01 -07005import contextlib
Kevin Chengc49494e2016-07-25 12:13:38 -07006import datetime
7import fcntl
Simran Basia9f41032012-05-11 14:21:58 -07008import fnmatch
Todd Broche505b8d2011-03-21 18:19:54 -07009import logging
Simran Basia9f41032012-05-11 14:21:58 -070010import os
Kevin Chengc49494e2016-07-25 12:13:38 -070011import random
Simran Basia9f41032012-05-11 14:21:58 -070012import shutil
Todd Broche505b8d2011-03-21 18:19:54 -070013import SimpleXMLRPCServer
Simran Basia9f41032012-05-11 14:21:58 -070014import subprocess
15import tempfile
Todd Broch7a91c252012-02-03 12:37:45 -080016import time
Simran Basia9f41032012-05-11 14:21:58 -070017import urllib
Todd Broche505b8d2011-03-21 18:19:54 -070018
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080019import drv as servo_drv
Aaron.Chuang88eff332014-07-31 08:32:00 +080020import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070021import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070022import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070023import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080024import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070025import ftdigpio
26import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070027import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070028import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080029import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080030import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070031import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070032import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080033import stm32gpio
34import stm32i2c
35import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070036
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080037HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080038
Todd Broche505b8d2011-03-21 18:19:54 -070039MAX_I2C_CLOCK_HZ = 100000
40
Kevin Cheng5595b342016-09-29 15:51:01 -070041# It takes about 16-17 seconds for the entire probe usb device method,
42# let's wait double plus some buffer.
43_MAX_USB_LOCK_WAIT = 40
Todd Brochdbb09982011-10-02 07:14:26 -070044
Todd Broche505b8d2011-03-21 18:19:54 -070045class ServodError(Exception):
46 """Exception class for servod."""
47
48class Servod(object):
49 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070050 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070051 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070052 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070053 _USB_J3 = "usb_mux_sel1"
54 _USB_J3_TO_SERVO = "servo_sees_usbkey"
55 _USB_J3_TO_DUT = "dut_sees_usbkey"
56 _USB_J3_PWR = "prtctl4_pwren"
57 _USB_J3_PWR_ON = "on"
58 _USB_J3_PWR_OFF = "off"
Kevin Chengc49494e2016-07-25 12:13:38 -070059 _USB_LOCK_FILE = "/var/lib/servod/lock_file"
Simran Basia9f41032012-05-11 14:21:58 -070060
Kevin Cheng4b4f0022016-09-09 02:37:07 -070061 # This is the key to get the main serial used in the _serialnames dict.
62 MAIN_SERIAL = "main"
Wai-Hong Tam4b235922016-10-07 12:26:22 -070063 MICRO_SERVO_SERIAL = "micro_servo"
Wai-Hong Tam85b4ced2016-10-07 14:15:38 -070064 CCD_SERIAL = "ccd"
Kevin Cheng4b4f0022016-09-09 02:37:07 -070065
Kevin Chengdc3befd2016-07-15 12:34:00 -070066 def init_servo_interfaces(self, vendor, product, serialname,
67 interfaces):
68 """Init the servo interfaces with the given interfaces.
69
70 We don't use the self._{vendor,product,serialname} attributes because we
71 want to allow other callers to initialize other interfaces that may not
72 be associated with the initialized attributes (e.g. a servo v4 servod object
73 that wants to also initialize a servo micro interface).
74
75 Args:
76 vendor: USB vendor id of FTDI device.
77 product: USB product id of FTDI device.
78 serialname: String of device serialname/number as defined in FTDI
79 eeprom.
80 interfaces: List of strings of interface types the server will
81 instantiate.
82
83 Raises:
84 ServodError if unable to locate init method for particular interface.
85 """
Mary Ruthven13389642017-02-14 12:15:34 -080086 # If it is a new device add it to the list
87 device = "%x:%x" % (vendor, product)
88 if device not in self._devices:
89 self._devices.append(device)
90
Kevin Chengdc3befd2016-07-15 12:34:00 -070091 # Extend the interface list if we need to.
92 interfaces_len = len(interfaces)
93 interface_list_len = len(self._interface_list)
94 if interfaces_len > interface_list_len:
95 self._interface_list += [None] * (interfaces_len - interface_list_len)
96
97 shifted = 0
98 for i, interface in enumerate(interfaces):
99 is_ftdi_interface = False
100 if type(interface) is dict:
101 name = interface['name']
102 # Store interface index for those that care about it.
103 interface['index'] = i
104 elif type(interface) is str and interface != 'dummy':
105 name = interface
106 # It's a FTDI related interface.
107 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
108 is_ftdi_interface = True
109 elif type(interface) is str and interface == 'dummy':
110 # 'dummy' reserves the interface for future use. Typically the
111 # interface will be managed by external third-party tools like
112 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
113 # it serves as a placeholder for servo micro interfaces.
114 continue
115 else:
116 raise ServodError("Illegal interface type %s" % type(interface))
117
118 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
119 if is_ftdi_interface and i and \
120 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
121 product += 1
122 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
123 product)
124
125 self._logger.info("Initializing interface %d to %s", i + 1, name)
126 try:
127 func = getattr(self, '_init_%s' % name)
128 except AttributeError:
129 raise ServodError("Unable to locate init for interface %s" % name)
130 result = func(vendor, product, serialname, interface)
131
132 if isinstance(result, tuple):
133 result_len = len(result)
Wai-Hong Tam9441b182016-11-01 11:05:09 -0700134 # More than one interface return. Extend the list.
135 self._interface_list += [None] * (result_len - 1)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700136 for result_index, r in enumerate(result):
Wai-Hong Tam9441b182016-11-01 11:05:09 -0700137 self._interface_list[i + shifted + result_index] = r
138 # Shift the remaining interfaces.
139 shifted += result_len - 1
Kevin Chengdc3befd2016-07-15 12:34:00 -0700140 else:
141 self._interface_list[i + shifted] = result
142
J. Richard Barnettee2820552013-03-14 16:13:46 -0700143 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800144 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700145 """Servod constructor.
146
147 Args:
148 config: instance of SystemConfig containing all controls for
149 particular Servod invocation
150 vendor: usb vendor id of FTDI device
151 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700152 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700153 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700154 version: String. Servo board version. Examples: servo_v1, servo_v2,
155 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800156 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700157 sending keyboard commands to DUTs that do not have built in
158 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
159 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -0700160
161 Raises:
162 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700163 """
164 self._logger = logging.getLogger("Servod")
165 self._logger.debug("")
166 self._vendor = vendor
167 self._product = product
Mary Ruthven13389642017-02-14 12:15:34 -0800168 self._devices = []
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700169 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700170 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700171 # Hold the last image path so we can reduce downloads to the usb device.
172 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700173 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
174 # interfaces are mapped to
175 self._interface_list = []
176 # Dict of Dict to map control name, function name to to tuple (params, drv)
177 # Ex) _drv_dict[name]['get'] = (params, drv)
178 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700179 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -0700180 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800181 self._usbkm232 = usbkm232
Kevin Chengc49494e2016-07-25 12:13:38 -0700182 # Seed the random generator with the serial to differentiate from other
183 # servod processes.
184 random.seed(serialname if serialname else time.time())
Todd Brochdbb09982011-10-02 07:14:26 -0700185 # Note, interface i is (i - 1) in list
186 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700187 try:
188 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
189 except KeyError:
190 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -0700191
Kevin Chengdc3befd2016-07-15 12:34:00 -0700192 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700193 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800194
Mary Ruthven13389642017-02-14 12:15:34 -0800195 def reinitialize(self):
196 """Reinitialize all interfaces that support reinitialization"""
197
198 # If all of the devices that were originally connected are not connected
199 # now, wait up to max_tries * sleep_time for the devices to reconnect
200 max_tries = 10
201 sleep_time = 0.5
202 for i in range(max_tries):
203 try:
204 for device in self._devices:
205 # This will raise an error if the device is not found
206 subprocess.check_output(["lsusb", "-vd", device])
207 break
208 except:
209 time.sleep(sleep_time)
210
211 for i, interface in enumerate(self._interface_list):
212 if hasattr(interface, "reinitialize"):
213 interface.reinitialize()
214 else:
215 self._logger.debug("interface %d has no reset functionality", i)
216
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800217 def _init_keyboard_handler(self, servo, board=''):
218 """Initialize the correct keyboard handler for board.
219
Kevin Chengdc3befd2016-07-15 12:34:00 -0700220 Args:
221 servo: servo object.
222 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800223
Kevin Chengdc3befd2016-07-15 12:34:00 -0700224 Returns:
225 keyboard handler object.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800226 """
227 if board == 'parrot':
228 return keyboard_handlers.ParrotHandler(servo)
229 elif board == 'stout':
230 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800231 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800232 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
philipchenfc9eea12016-09-21 17:36:54 -0700233 'sumo', 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
234 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800235 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800236 logging.info("No device path specified for usbkm232 handler. Use "
237 "the servo atmega chip to handle.")
238 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800239 if self._usbkm232 == 'atmega':
240 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800241 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800242 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800243 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800244 self._usbkm232 = self.get('atmega_pty')
Kevin Cheng810fc782016-11-01 12:36:46 -0700245 # We don't need to set the atmega uart settings if we're a servo v4.
246 if self._version != 'servo_v4':
247 self.set('atmega_baudrate', '9600')
248 self.set('atmega_bits', 'eight')
249 self.set('atmega_parity', 'none')
250 self.set('atmega_sbits', 'one')
251 self.set('usb_mux_sel4', 'on')
252 self.set('usb_mux_oe4', 'on')
253 # Allow atmega bootup time.
254 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800255 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800256 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
257 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800258 # The following boards don't use Chrome EC.
259 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
260 return keyboard_handlers.MatrixKeyboardHandler(servo)
261 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800262
Todd Broch3ec8df02012-11-20 10:53:03 -0800263 def __del__(self):
264 """Servod deconstructor."""
265 for interface in self._interface_list:
266 del(interface)
267
Kevin Chengdc3befd2016-07-15 12:34:00 -0700268 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700269 """Dummy interface for ftdi devices.
270
271 This is a dummy function specifically for ftdi devices to not initialize
272 anything but to help pad the interface list.
273
274 Returns:
275 None.
276 """
277 return None
278
Kevin Chengdc3befd2016-07-15 12:34:00 -0700279 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700280 """Initialize gpio driver interface and open for use.
281
282 Args:
283 interface: interface number of FTDI device to use.
284
285 Returns:
286 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700287
288 Raises:
289 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700290 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700291 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700292 try:
293 fobj.open()
294 except ftdigpio.FgpioError as e:
295 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
296
Todd Broche505b8d2011-03-21 18:19:54 -0700297 return fobj
298
Kevin Chengdc3befd2016-07-15 12:34:00 -0700299 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800300 """Initialize stm32 uart interface and open for use
301
302 Note, the uart runs in a separate thread. Users wishing to
303 interact with it will query control for the pty's pathname and connect
304 with their favorite console program. For example:
305 cu -l /dev/pts/22
306
307 Args:
308 interface: dict of interface parameters.
309
310 Returns:
311 Instance object of interface
312
313 Raises:
314 ServodError: Raised on init failure.
315 """
316 self._logger.info("Suart: interface: %s" % interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700317 sobj = stm32uart.Suart(vendor, product, interface['interface'],
318 serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800319
320 try:
321 sobj.run()
322 except stm32uart.SuartError as e:
323 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
324
325 self._logger.info("%s" % sobj.get_pty())
326 return sobj
327
Kevin Chengdc3befd2016-07-15 12:34:00 -0700328 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800329 """Initialize stm32 gpio interface.
330 Args:
331 interface: interface number of stm32 device to use.
332
333 Returns:
334 Instance object of interface
335
336 Raises:
337 SgpioError: Raised on init failure.
338 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700339 interface_number = interface
340 # Interface could be a dict.
341 if type(interface) is dict:
342 interface_number = interface['interface']
343 self._logger.info("Sgpio: interface: %s" % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700344 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800345
Kevin Chengdc3befd2016-07-15 12:34:00 -0700346 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800347 """Initialize stm32 USB to I2C bridge interface and open for use
348
349 Args:
350 interface: USB interface number of stm32 device to use
351
352 Returns:
353 Instance object of interface.
354
355 Raises:
356 Si2cError: Raised on init failure.
357 """
358 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800359 port = interface.get('port', 0)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700360 return stm32i2c.Si2cBus(vendor, product, interface['interface'],
361 port=port, serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800362
Kevin Chengdc3befd2016-07-15 12:34:00 -0700363 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800364 """Initalize beaglebone ADC interface."""
365 return bbadc.BBadc()
366
Kevin Chengdc3befd2016-07-15 12:34:00 -0700367 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700368 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700369 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700370
Kevin Chengdc3befd2016-07-15 12:34:00 -0700371 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700372 """Initialize i2c interface and open for use.
373
374 Args:
375 interface: interface number of FTDI device to use
376
377 Returns:
378 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700379
380 Raises:
381 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700382 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700383 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700384 try:
385 fobj.open()
386 except ftdii2c.Fi2cError as e:
387 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
388
Todd Broche505b8d2011-03-21 18:19:54 -0700389 # Set the frequency of operation of the i2c bus.
390 # TODO(tbroch) make configureable
391 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700392
Todd Broche505b8d2011-03-21 18:19:54 -0700393 return fobj
394
Simran Basie750a342013-03-12 13:45:26 -0700395 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
396 def _init_bb_i2c(self, interface):
397 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700398 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700399
Kevin Chengdc3befd2016-07-15 12:34:00 -0700400 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800401 """Initalize Linux i2c-dev interface."""
402 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
403
Kevin Chengdc3befd2016-07-15 12:34:00 -0700404 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700405 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700406
407 Note, the uart runs in a separate thread (pthreads). Users wishing to
408 interact with it will query control for the pty's pathname and connect
409 with there favorite console program. For example:
410 cu -l /dev/pts/22
411
412 Args:
413 interface: interface number of FTDI device to use
414
415 Returns:
416 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700417
418 Raises:
419 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700420 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700421 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700422 try:
423 fobj.run()
424 except ftdiuart.FuartError as e:
425 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
426
Todd Broch47c43f42011-05-26 15:11:31 -0700427 self._logger.info("%s" % fobj.get_pty())
428 return fobj
429
Simran Basie750a342013-03-12 13:45:26 -0700430 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700431 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700432 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700433 logging.debug('UART INTERFACE: %s', interface)
434 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700435
Kevin Chengdc3befd2016-07-15 12:34:00 -0700436 def _init_ftdi_gpiouart(self, vendor, product, serialname,
437 interface):
Todd Broch888da782011-10-07 14:29:09 -0700438 """Initialize special gpio + uart interface and open for use
439
440 Note, the uart runs in a separate thread (pthreads). Users wishing to
441 interact with it will query control for the pty's pathname and connect
442 with there favorite console program. For example:
443 cu -l /dev/pts/22
444
445 Args:
446 interface: interface number of FTDI device to use
447
448 Returns:
449 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700450
451 Raises:
452 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700453 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700454 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700455 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700456 try:
457 fuart.run()
458 except ftdiuart.FuartError as e:
459 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
460
Todd Broch888da782011-10-07 14:29:09 -0700461 self._logger.info("uart pty: %s" % fuart.get_pty())
462 return fgpio, fuart
463
Kevin Chengdc3befd2016-07-15 12:34:00 -0700464 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800465 """Initialize EC-3PO console interpreter interface.
466
467 Args:
468 interface: A dictionary representing the interface.
469
470 Returns:
471 An EC3PO object representing the EC-3PO interface or None if there's no
472 interface for the USB PD UART.
473 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700474 vid = vendor
475 pid = product
Aseda Aboagyea4922212015-11-20 15:19:08 -0800476 # The current PID might be incremented if there are multiple FTDI.
477 # Therefore, try rewinding the PID back one if we don't find the base PID in
478 # the SERVO_ID_DEFAULTS
479 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
480 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
481 pid -= 1
482 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
483
Nick Sanders97bc4462016-01-04 15:37:31 -0800484 if 'raw_pty' in interface:
485 # We have specified an explicit target for this ec3po.
486 raw_uart_name = interface['raw_pty']
487 raw_ec_uart = self.get(raw_uart_name)
488
Aseda Aboagyea4922212015-11-20 15:19:08 -0800489 # Servo V2 / V3 should have the interface indicies in the same spot.
Nick Sanders97bc4462016-01-04 15:37:31 -0800490 elif ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
Aseda Aboagyea4922212015-11-20 15:19:08 -0800491 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
492 # Determine if it's a PD interface or just main EC console.
493 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
494 try:
495 # Obtain the raw EC UART PTY and create the EC-3PO interface.
496 raw_ec_uart = self.get('raw_usbpd_uart_pty')
497 except NameError:
498 # This overlay doesn't have a USB PD MCU, so skip init.
499 self._logger.info('No PD MCU UART.')
500 return None
501 except AttributeError:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700502 # This overlay has no get method for the interface so skip init. For
503 # servo v2, it's common for interfaces to be overridden such as
504 # reusing JTAG pins for the PD MCU UART instead. Therefore, print an
505 # error message indicating that the interface might be set
506 # incorrectly.
507 if (vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS:
508 self._logger.warn('No interface for PD MCU UART.')
509 self._logger.warn('Usually, this happens because the interface is '
510 'set incorrectly. If you\'re overriding an '
511 'existing interface, be sure to update the '
512 'interface lists for your board at the end of '
513 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800514 return None
515
516 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
517 raw_ec_uart = self.get('raw_ec_uart_pty')
518
519 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
520 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
521 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
522 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
523 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
524 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
525 raw_ec_uart = self.get('raw_ec_uart_pty')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800526 else:
527 raise ServodError(('Unexpected EC-3PO interface!'
528 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
529
530 return ec3po_interface.EC3PO(raw_ec_uart)
531
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800532 def _camel_case(self, string):
533 output = ''
534 for s in string.split('_'):
535 if output:
536 output += s.capitalize()
537 else:
538 output = s
539 return output
540
Todd Broche505b8d2011-03-21 18:19:54 -0700541 def _get_param_drv(self, control_name, is_get=True):
542 """Get access to driver for a given control.
543
544 Note, some controls have different parameter dictionaries for 'getting' the
545 control's value versus 'setting' it. Boolean is_get distinguishes which is
546 being requested.
547
548 Args:
549 control_name: string name of control
550 is_get: boolean to determine
551
552 Returns:
553 tuple (param, drv) where:
554 param: param dictionary for control
555 drv: instance object of driver for particular control
556
557 Raises:
558 ServodError: Error occurred while examining params dict
559 """
560 self._logger.debug("")
561 # if already setup just return tuple from driver dict
562 if control_name in self._drv_dict:
563 if is_get and ('get' in self._drv_dict[control_name]):
564 return self._drv_dict[control_name]['get']
565 if not is_get and ('set' in self._drv_dict[control_name]):
566 return self._drv_dict[control_name]['set']
567
568 params = self._syscfg.lookup_control_params(control_name, is_get)
569 if 'drv' not in params:
570 self._logger.error("Unable to determine driver for %s" % control_name)
571 raise ServodError("'drv' key not found in params dict")
572 if 'interface' not in params:
573 self._logger.error("Unable to determine interface for %s" %
574 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700575 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700576
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800577 interface_id = params.get(
578 '%s_interface' % self._version, params['interface'])
579 if interface_id == 'servo':
580 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700581 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800582 index = int(interface_id) - 1
583 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700584
Todd Broche505b8d2011-03-21 18:19:54 -0700585 drv_name = params['drv']
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800586 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800587 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700588 drv = drv_class(interface, params)
589 if control_name not in self._drv_dict:
590 self._drv_dict[control_name] = {}
591 if is_get:
592 self._drv_dict[control_name]['get'] = (params, drv)
593 else:
594 self._drv_dict[control_name]['set'] = (params, drv)
595 return (params, drv)
596
597 def doc_all(self):
598 """Return all documenation for controls.
599
600 Returns:
601 string of <doc> text in config file (xml) and the params dictionary for
602 all controls.
603
604 For example:
605 warm_reset :: Reset the device warmly
606 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
607 """
608 return self._syscfg.display_config()
609
610 def doc(self, name):
611 """Retreive doc string in system config file for given control name.
612
613 Args:
614 name: name string of control to get doc string
615
616 Returns:
617 doc string of name
618
619 Raises:
620 NameError: if fails to locate control
621 """
622 self._logger.debug("name(%s)" % (name))
623 if self._syscfg.is_control(name):
624 return self._syscfg.get_control_docstring(name)
625 else:
626 raise NameError("No control %s" %name)
627
Fang Deng90377712013-06-03 15:51:48 -0700628 def _switch_usbkey(self, mux_direction):
629 """Connect USB flash stick to either servo or DUT.
630
631 This function switches 'usb_mux_sel1' to provide electrical
632 connection between the USB port J3 and either servo or DUT side.
633
634 Switching the usb mux is accompanied by powercycling
635 of the USB stick, because it sometimes gets wedged if the mux
636 is switched while the stick power is on.
637
638 Args:
639 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
640 """
641 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
642 time.sleep(self._USB_POWEROFF_DELAY)
643 self.set(self._USB_J3, mux_direction)
644 time.sleep(self._USB_POWEROFF_DELAY)
645 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
646 if mux_direction == self._USB_J3_TO_SERVO:
647 time.sleep(self._USB_DETECTION_DELAY)
648
Simran Basia9f41032012-05-11 14:21:58 -0700649 def _get_usb_port_set(self):
650 """Gets a set of USB disks currently connected to the system
651
652 Returns:
653 A set of USB disk paths.
654 """
655 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
656 return set(["/dev/" + dev for dev in usb_set])
657
Kevin Cheng5595b342016-09-29 15:51:01 -0700658 @contextlib.contextmanager
659 def _block_other_servod(self, timeout=None):
Kevin Chengc49494e2016-07-25 12:13:38 -0700660 """Block other servod processes by locking a file.
661
662 To enable multiple servods processes to safely probe_host_usb_dev, we use
663 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700664 for a usb device. This will be a context manager that will return
665 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700666
667 If the lock file exists, we open it and try to lock it.
668 - If another servod processes has locked it already, we'll sleep a random
669 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700670 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700671
Kevin Cheng5595b342016-09-29 15:51:01 -0700672 - If we're able to lock the file, we'll yield that the block was successful
673 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700674
675 This blocking behavior is only enabled if the lock file exists, if it
676 doesn't, then we pretend the block was successful.
677
Kevin Cheng5595b342016-09-29 15:51:01 -0700678 Args:
679 timeout: Max waiting time for the block to succeed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700680 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700681 if not os.path.exists(self._USB_LOCK_FILE):
682 # No lock file so we'll pretend the block was a success.
683 yield True
684 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700685 start_time = datetime.datetime.now()
686 while True:
Kevin Cheng5595b342016-09-29 15:51:01 -0700687 with open(self._USB_LOCK_FILE) as lock_file:
688 try:
689 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
690 yield True
691 fcntl.flock(lock_file, fcntl.LOCK_UN)
692 break
693 except IOError:
694 current_time = datetime.datetime.now()
695 current_wait_time = (current_time - start_time).total_seconds()
696 if timeout and current_wait_time > timeout:
697 yield False
698 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700699 # Sleep random amount.
700 sleep_time = time.sleep(random.random())
Kevin Chengc49494e2016-07-25 12:13:38 -0700701
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700702 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700703 """Toggle the usb power safely.
704
705 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700706
707 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700708 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700709 timeout: Timeout to wait for blocking other servod processes, default is
710 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700711
Kevin Cheng5595b342016-09-29 15:51:01 -0700712 Returns:
713 An empty string to appease the xmlrpc gods.
714 """
715 with self._block_other_servod(timeout=timeout):
716 if power_state != self.get(self._USB_J3_PWR):
717 self.set(self._USB_J3_PWR, power_state)
718 return ''
719
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700720 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700721 """Toggle the usb direction safely.
722
723 We'll make sure we're the only servod process toggling the usbkey direction.
724
725 Args:
726 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700727 timeout: Timeout to wait for blocking other servod processes, default is
728 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700729
730 Returns:
731 An empty string to appease the xmlrpc gods.
732 """
733 with self._block_other_servod(timeout=timeout):
734 self._switch_usbkey(mux_direction)
735 return ''
736
737 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700738 """Probe the USB disk device plugged in the servo from the host side.
739
740 Method can fail by:
741 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700742 another servo unless _USB_LOCK_FILE exists on the servo host. If that
743 file exists, then it is safe to probe for usb devices among multiple
744 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700745 2) Finding multiple /dev/sdX and returning None.
746
Kevin Cheng5595b342016-09-29 15:51:01 -0700747 Args:
748 timeout: Timeout to wait for blocking other servod processes.
749
Simran Basia9f41032012-05-11 14:21:58 -0700750 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700751 USB disk path if one and only one USB disk path is found, otherwise an
752 empty string.
Simran Basia9f41032012-05-11 14:21:58 -0700753 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700754 with self._block_other_servod(timeout=timeout) as block_success:
755 if not block_success:
756 return ''
Kevin Chengc49494e2016-07-25 12:13:38 -0700757
Kevin Cheng5595b342016-09-29 15:51:01 -0700758 original_value = self.get(self._USB_J3)
759 original_usb_power = self.get(self._USB_J3_PWR)
760 # Make the host unable to see the USB disk.
761 if (original_usb_power == self._USB_J3_PWR_ON and
762 original_value != self._USB_J3_TO_DUT):
763 self._switch_usbkey(self._USB_J3_TO_DUT)
764 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700765
Kevin Cheng5595b342016-09-29 15:51:01 -0700766 # Make the host able to see the USB disk.
767 self._switch_usbkey(self._USB_J3_TO_SERVO)
768 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700769
Kevin Cheng5595b342016-09-29 15:51:01 -0700770 # Back to its original value.
771 if original_value != self._USB_J3_TO_SERVO:
772 self._switch_usbkey(original_value)
773 if original_usb_power != self._USB_J3_PWR_ON:
774 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
775 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700776
Kevin Cheng5595b342016-09-29 15:51:01 -0700777 # Subtract the two sets to find the usb device.
778 diff_set = has_usb_set - no_usb_set
779 if len(diff_set) == 1:
780 return diff_set.pop()
781 else:
782 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700783
Kevin Cheng85831332016-10-13 13:14:44 -0700784 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700785 """Download image and save to the USB device found by probe_host_usb_dev.
786 If the image_path is a URL, it will download this url to the USB path;
787 otherwise it will simply copy the image_path's contents to the USB path.
788
789 Args:
790 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700791 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700792
793 Returns:
794 True|False: True if process completed successfully, False if error
795 occurred.
796 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
797 comment at the end of set().
798 """
799 self._logger.debug("image_path(%s)" % image_path)
800 self._logger.debug("Detecting USB stick device...")
Kevin Cheng85831332016-10-13 13:14:44 -0700801 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700802 if not usb_dev:
803 self._logger.error("No usb device connected to servo")
804 return False
805
Kevin Cheng9071ed92016-06-21 14:37:54 -0700806 # Let's check if we downloaded this last time and if so assume the image is
807 # still on the usb device and return True.
808 if self._image_path == image_path:
809 self._logger.debug("Image already on USB device, skipping transfer")
810 return True
811
Simran Basia9f41032012-05-11 14:21:58 -0700812 try:
813 if image_path.startswith(self._HTTP_PREFIX):
814 self._logger.debug("Image path is a URL, downloading image")
815 urllib.urlretrieve(image_path, usb_dev)
816 else:
817 shutil.copyfile(image_path, usb_dev)
818 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700819 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700820 e.strerror, e.errno)
821 return False
822 except urllib.ContentTooShortError:
823 self._logger.error("Failed to download URL: %s to USB device: %s",
824 image_path, usb_dev)
825 return False
826 except BaseException as e:
827 self._logger.error("Unexpected exception downloading %s to %s: %s",
828 image_path, usb_dev, str(e))
829 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800830 finally:
831 # We just plastered the partition table for a block device.
832 # Pass or fail, we mustn't go without telling the kernel about
833 # the change, or it will punish us with sporadic, hard-to-debug
834 # failures.
835 subprocess.call(["sync"])
836 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700837 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700838 return True
839
840 def make_image_noninteractive(self):
841 """Makes the recovery image noninteractive.
842
843 A noninteractive image will reboot automatically after installation
844 instead of waiting for the USB device to be removed to initiate a system
845 reboot.
846
847 Mounts partition 1 of the image stored on usb_dev and creates a file
848 called "non_interactive" so that the image will become noninteractive.
849
850 Returns:
851 True|False: True if process completed successfully, False if error
852 occurred.
853 """
854 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700855 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700856 if not usb_dev:
857 self._logger.error("No usb device connected to servo")
858 return False
859 # Create TempDirectory
860 tmpdir = tempfile.mkdtemp()
861 if tmpdir:
862 # Mount drive to tmpdir.
863 partition_1 = "%s1" % usb_dev
864 rc = subprocess.call(["mount", partition_1, tmpdir])
865 if rc == 0:
866 # Create file 'non_interactive'
867 non_interactive_file = os.path.join(tmpdir, "non_interactive")
868 try:
869 open(non_interactive_file, "w").close()
870 except IOError as e:
871 self._logger.error("Failed to create file %s : %s ( %d )",
872 non_interactive_file, e.strerror, e.errno)
873 result = False
874 except BaseException as e:
875 self._logger.error("Unexpected Exception creating file %s : %s",
876 non_interactive_file, str(e))
877 result = False
878 # Unmount drive regardless if file creation worked or not.
879 rc = subprocess.call(["umount", partition_1])
880 if rc != 0:
881 self._logger.error("Failed to unmount USB Device")
882 result = False
883 else:
884 self._logger.error("Failed to mount USB Device")
885 result = False
886
887 # Delete tmpdir. May throw exception if 'umount' failed.
888 try:
889 os.rmdir(tmpdir)
890 except OSError as e:
891 self._logger.error("Failed to remove temp directory %s : %s",
892 tmpdir, str(e))
893 return False
894 except BaseException as e:
895 self._logger.error("Unexpected Exception removing tempdir %s : %s",
896 tmpdir, str(e))
897 return False
898 else:
899 self._logger.error("Failed to create temp directory.")
900 return False
901 return result
902
Todd Broch352b4b22013-03-22 09:48:40 -0700903 def set_get_all(self, cmds):
904 """Set &| get one or more control values.
905
906 Args:
907 cmds: list of control[:value] to get or set.
908
909 Returns:
910 rv: list of responses from calling get or set methods.
911 """
912 rv = []
913 for cmd in cmds:
914 if ':' in cmd:
915 (control, value) = cmd.split(':')
916 rv.append(self.set(control, value))
917 else:
918 rv.append(self.get(cmd))
919 return rv
920
Todd Broche505b8d2011-03-21 18:19:54 -0700921 def get(self, name):
922 """Get control value.
923
924 Args:
925 name: name string of control
926
927 Returns:
928 Response from calling drv get method. Value is reformatted based on
929 control's dictionary parameters
930
931 Raises:
932 HwDriverError: Error occurred while using drv
933 """
934 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700935 if name == 'serialname':
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700936 if self._serialnames[self.MAIN_SERIAL]:
937 return self._serialnames[self.MAIN_SERIAL]
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700938 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700939 (param, drv) = self._get_param_drv(name)
940 try:
941 val = drv.get()
942 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800943 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700944 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700945 except AttributeError, error:
946 self._logger.error("Getting %s: %s" % (name, error))
947 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800948 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700949 self._logger.error("Getting %s" % (name))
950 raise
Todd Brochd6061672012-05-11 15:52:47 -0700951
Todd Broche505b8d2011-03-21 18:19:54 -0700952 def get_all(self, verbose):
953 """Get all controls values.
954
955 Args:
956 verbose: Boolean on whether to return doc info as well
957
958 Returns:
959 string creating from trying to get all values of all controls. In case of
960 error attempting access to control, response is 'ERR'.
961 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800962 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700963 for name in self._syscfg.syscfg_dict['control']:
964 self._logger.debug("name = %s" %name)
965 try:
966 value = self.get(name)
967 except Exception:
968 value = "ERR"
969 pass
970 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800971 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700972 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800973 rsp.append("%s:%s" % (name, value))
974 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700975
976 def set(self, name, wr_val_str):
977 """Set control.
978
979 Args:
980 name: name string of control
981 wr_val_str: value string to write. Can be integer, float or a
982 alpha-numerical that is mapped to a integer or float.
983
984 Raises:
985 HwDriverError: Error occurred while using driver
986 """
987 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
988 (params, drv) = self._get_param_drv(name, False)
989 wr_val = self._syscfg.resolve_val(params, wr_val_str)
990 try:
991 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800992 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700993 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
994 raise
995 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
996 # & client I still have to return something to appease the
997 # marshall/unmarshall
998 return True
999
Todd Brochd6061672012-05-11 15:52:47 -07001000 def hwinit(self, verbose=False):
1001 """Initialize all controls.
1002
1003 These values are part of the system config XML files of the form
1004 init=<value>. This command should be used by clients wishing to return the
1005 servo and DUT its connected to a known good/safe state.
1006
Vadim Bendeburybb51dd42013-01-31 13:47:46 -08001007 Note that initialization errors are ignored (as in some cases they could
1008 be caused by DUT firmware deficiencies). This might need to be fine tuned
1009 later.
1010
Todd Brochd6061672012-05-11 15:52:47 -07001011 Args:
1012 verbose: boolean, if True prints info about control initialized.
1013 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001014
1015 Returns:
1016 This function is called across RPC and as such is expected to return
1017 something unless transferring 'none' across is allowed. Hence adding a
1018 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -07001019 """
Todd Brochd9acf0a2012-12-05 13:43:06 -08001020 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -08001021 try:
John Carey6fe2bbf2015-08-31 16:13:03 -07001022 # Workaround for bug chrome-os-partner:42349. Without this check, the
1023 # gpio will briefly pulse low if we set it from high to high.
1024 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -07001025 self.set(control_name, value)
1026 if verbose:
1027 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -08001028 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -08001029 self._logger.error("Problem initializing %s -> %s :: %s",
1030 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -08001031
1032 # Init keyboard after all the intefaces are up.
1033 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001034 return True
Todd Broch3ec8df02012-11-20 10:53:03 -08001035
Todd Broche505b8d2011-03-21 18:19:54 -07001036 def echo(self, echo):
1037 """Dummy echo function for testing/examples.
1038
1039 Args:
1040 echo: string to echo back to client
1041 """
1042 self._logger.debug("echo(%s)" % (echo))
1043 return "ECH0ING: %s" % (echo)
1044
J. Richard Barnettee2820552013-03-14 16:13:46 -07001045 def get_board(self):
1046 """Return the board specified at startup, if any."""
1047 return self._board
1048
Simran Basia23c1392013-08-06 14:59:10 -07001049 def get_version(self):
1050 """Get servo board version."""
1051 return self._version
1052
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001053 def power_long_press(self):
1054 """Simulate a long power button press."""
1055 # After a long power press, the EC may ignore the next power
1056 # button press (at least on Alex). To guarantee that this
1057 # won't happen, we need to allow the EC one second to
1058 # collect itself.
1059 self._keyboard.power_long_press()
1060 return True
1061
1062 def power_normal_press(self):
1063 """Simulate a normal power button press."""
1064 self._keyboard.power_normal_press()
1065 return True
1066
1067 def power_short_press(self):
1068 """Simulate a short power button press."""
1069 self._keyboard.power_short_press()
1070 return True
1071
1072 def power_key(self, secs=''):
1073 """Simulate a power button press.
1074
1075 Args:
1076 secs: Time in seconds to simulate the keypress.
1077 """
1078 self._keyboard.power_key(secs)
1079 return True
1080
1081 def ctrl_d(self, press_secs=''):
1082 """Simulate Ctrl-d simultaneous button presses."""
1083 self._keyboard.ctrl_d(press_secs)
1084 return True
1085
Victor Dodone539cea2016-03-29 18:50:17 -07001086 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001087 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001088 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001089 return True
1090
1091 def ctrl_enter(self, press_secs=''):
1092 """Simulate Ctrl-enter simultaneous button presses."""
1093 self._keyboard.ctrl_enter(press_secs)
1094 return True
1095
1096 def d_key(self, press_secs=''):
1097 """Simulate Enter key button press."""
1098 self._keyboard.d_key(press_secs)
1099 return True
1100
1101 def ctrl_key(self, press_secs=''):
1102 """Simulate Enter key button press."""
1103 self._keyboard.ctrl_key(press_secs)
1104 return True
1105
1106 def enter_key(self, press_secs=''):
1107 """Simulate Enter key button press."""
1108 self._keyboard.enter_key(press_secs)
1109 return True
1110
1111 def refresh_key(self, press_secs=''):
1112 """Simulate Refresh key (F3) button press."""
1113 self._keyboard.refresh_key(press_secs)
1114 return True
1115
1116 def ctrl_refresh_key(self, press_secs=''):
1117 """Simulate Ctrl and Refresh (F3) simultaneous press.
1118
1119 This key combination is an alternative of Space key.
1120 """
1121 self._keyboard.ctrl_refresh_key(press_secs)
1122 return True
1123
1124 def imaginary_key(self, press_secs=''):
1125 """Simulate imaginary key button press.
1126
1127 Maps to a key that doesn't physically exist.
1128 """
1129 self._keyboard.imaginary_key(press_secs)
1130 return True
1131
Todd Brochdbb09982011-10-02 07:14:26 -07001132
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001133 def sysrq_x(self, press_secs=''):
1134 """Simulate Alt VolumeUp X simultaneous press.
1135
1136 This key combination is the kernel system request (sysrq) x.
1137 """
1138 self._keyboard.sysrq_x(press_secs)
1139 return True
1140
1141
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001142 def get_servo_serials(self):
1143 """Return all the serials associated with this process."""
1144 return self._serialnames
1145
1146
Todd Broche505b8d2011-03-21 18:19:54 -07001147def test():
1148 """Integration testing.
1149
1150 TODO(tbroch) Enhance integration test and add unittest (see mox)
1151 """
1152 logging.basicConfig(level=logging.DEBUG,
1153 format="%(asctime)s - %(name)s - " +
1154 "%(levelname)s - %(message)s")
1155 # configure server & listen
1156 servod_obj = Servod(1)
1157 # 4 == number of interfaces on a FT4232H device
1158 for i in xrange(4):
1159 if i == 1:
1160 # its an i2c interface ... see __init__ for details and TODO to make
1161 # this configureable
1162 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1163 else:
1164 # its a gpio interface
1165 servod_obj._interface_list[i].wr_rd(0)
1166
1167 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1168 allow_none=True)
1169 server.register_introspection_functions()
1170 server.register_multicall_functions()
1171 server.register_instance(servod_obj)
1172 logging.info("Listening on localhost port 9999")
1173 server.serve_forever()
1174
1175if __name__ == "__main__":
1176 test()
1177
1178 # simple client transaction would look like
1179 """
1180 remote_uri = 'http://localhost:9999'
1181 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1182 send_str = "Hello_there"
1183 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1184 """