blob: c4a06f955023f3528518cae6c21bb04aa13b195d [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 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700474 raw_uart_name = interface['raw_pty']
475 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800476 raw_ec_uart = self.get(raw_uart_name)
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700477 return ec3po_interface.EC3PO(raw_ec_uart)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800478 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700479 # The overlay doesn't have the raw PTY defined, therefore we can skip
480 # initializing this interface since no control relies on it.
481 self._logger.debug(
482 'Skip initializing EC3PO for %s, no control specified.',
483 raw_uart_name)
484 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800485
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800486 def _camel_case(self, string):
487 output = ''
488 for s in string.split('_'):
489 if output:
490 output += s.capitalize()
491 else:
492 output = s
493 return output
494
Todd Broche505b8d2011-03-21 18:19:54 -0700495 def _get_param_drv(self, control_name, is_get=True):
496 """Get access to driver for a given control.
497
498 Note, some controls have different parameter dictionaries for 'getting' the
499 control's value versus 'setting' it. Boolean is_get distinguishes which is
500 being requested.
501
502 Args:
503 control_name: string name of control
504 is_get: boolean to determine
505
506 Returns:
507 tuple (param, drv) where:
508 param: param dictionary for control
509 drv: instance object of driver for particular control
510
511 Raises:
512 ServodError: Error occurred while examining params dict
513 """
514 self._logger.debug("")
515 # if already setup just return tuple from driver dict
516 if control_name in self._drv_dict:
517 if is_get and ('get' in self._drv_dict[control_name]):
518 return self._drv_dict[control_name]['get']
519 if not is_get and ('set' in self._drv_dict[control_name]):
520 return self._drv_dict[control_name]['set']
521
522 params = self._syscfg.lookup_control_params(control_name, is_get)
523 if 'drv' not in params:
524 self._logger.error("Unable to determine driver for %s" % control_name)
525 raise ServodError("'drv' key not found in params dict")
526 if 'interface' not in params:
527 self._logger.error("Unable to determine interface for %s" %
528 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700529 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700530
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800531 interface_id = params.get(
532 '%s_interface' % self._version, params['interface'])
533 if interface_id == 'servo':
534 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700535 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800536 index = int(interface_id) - 1
537 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700538
Todd Broche505b8d2011-03-21 18:19:54 -0700539 drv_name = params['drv']
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800540 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800541 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700542 drv = drv_class(interface, params)
543 if control_name not in self._drv_dict:
544 self._drv_dict[control_name] = {}
545 if is_get:
546 self._drv_dict[control_name]['get'] = (params, drv)
547 else:
548 self._drv_dict[control_name]['set'] = (params, drv)
549 return (params, drv)
550
551 def doc_all(self):
552 """Return all documenation for controls.
553
554 Returns:
555 string of <doc> text in config file (xml) and the params dictionary for
556 all controls.
557
558 For example:
559 warm_reset :: Reset the device warmly
560 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
561 """
562 return self._syscfg.display_config()
563
564 def doc(self, name):
565 """Retreive doc string in system config file for given control name.
566
567 Args:
568 name: name string of control to get doc string
569
570 Returns:
571 doc string of name
572
573 Raises:
574 NameError: if fails to locate control
575 """
576 self._logger.debug("name(%s)" % (name))
577 if self._syscfg.is_control(name):
578 return self._syscfg.get_control_docstring(name)
579 else:
580 raise NameError("No control %s" %name)
581
Fang Deng90377712013-06-03 15:51:48 -0700582 def _switch_usbkey(self, mux_direction):
583 """Connect USB flash stick to either servo or DUT.
584
585 This function switches 'usb_mux_sel1' to provide electrical
586 connection between the USB port J3 and either servo or DUT side.
587
588 Switching the usb mux is accompanied by powercycling
589 of the USB stick, because it sometimes gets wedged if the mux
590 is switched while the stick power is on.
591
592 Args:
593 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
594 """
595 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
596 time.sleep(self._USB_POWEROFF_DELAY)
597 self.set(self._USB_J3, mux_direction)
598 time.sleep(self._USB_POWEROFF_DELAY)
599 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
600 if mux_direction == self._USB_J3_TO_SERVO:
601 time.sleep(self._USB_DETECTION_DELAY)
602
Simran Basia9f41032012-05-11 14:21:58 -0700603 def _get_usb_port_set(self):
604 """Gets a set of USB disks currently connected to the system
605
606 Returns:
607 A set of USB disk paths.
608 """
609 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
610 return set(["/dev/" + dev for dev in usb_set])
611
Kevin Cheng5595b342016-09-29 15:51:01 -0700612 @contextlib.contextmanager
613 def _block_other_servod(self, timeout=None):
Kevin Chengc49494e2016-07-25 12:13:38 -0700614 """Block other servod processes by locking a file.
615
616 To enable multiple servods processes to safely probe_host_usb_dev, we use
617 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700618 for a usb device. This will be a context manager that will return
619 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700620
621 If the lock file exists, we open it and try to lock it.
622 - If another servod processes has locked it already, we'll sleep a random
623 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700624 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700625
Kevin Cheng5595b342016-09-29 15:51:01 -0700626 - If we're able to lock the file, we'll yield that the block was successful
627 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700628
629 This blocking behavior is only enabled if the lock file exists, if it
630 doesn't, then we pretend the block was successful.
631
Kevin Cheng5595b342016-09-29 15:51:01 -0700632 Args:
633 timeout: Max waiting time for the block to succeed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700634 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700635 if not os.path.exists(self._USB_LOCK_FILE):
636 # No lock file so we'll pretend the block was a success.
637 yield True
638 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700639 start_time = datetime.datetime.now()
640 while True:
Kevin Cheng5595b342016-09-29 15:51:01 -0700641 with open(self._USB_LOCK_FILE) as lock_file:
642 try:
643 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
644 yield True
645 fcntl.flock(lock_file, fcntl.LOCK_UN)
646 break
647 except IOError:
648 current_time = datetime.datetime.now()
649 current_wait_time = (current_time - start_time).total_seconds()
650 if timeout and current_wait_time > timeout:
651 yield False
652 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700653 # Sleep random amount.
654 sleep_time = time.sleep(random.random())
Kevin Chengc49494e2016-07-25 12:13:38 -0700655
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700656 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700657 """Toggle the usb power safely.
658
659 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700660
661 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700662 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700663 timeout: Timeout to wait for blocking other servod processes, default is
664 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700665
Kevin Cheng5595b342016-09-29 15:51:01 -0700666 Returns:
667 An empty string to appease the xmlrpc gods.
668 """
669 with self._block_other_servod(timeout=timeout):
670 if power_state != self.get(self._USB_J3_PWR):
671 self.set(self._USB_J3_PWR, power_state)
672 return ''
673
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700674 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700675 """Toggle the usb direction safely.
676
677 We'll make sure we're the only servod process toggling the usbkey direction.
678
679 Args:
680 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700681 timeout: Timeout to wait for blocking other servod processes, default is
682 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700683
684 Returns:
685 An empty string to appease the xmlrpc gods.
686 """
687 with self._block_other_servod(timeout=timeout):
688 self._switch_usbkey(mux_direction)
689 return ''
690
691 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700692 """Probe the USB disk device plugged in the servo from the host side.
693
694 Method can fail by:
695 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700696 another servo unless _USB_LOCK_FILE exists on the servo host. If that
697 file exists, then it is safe to probe for usb devices among multiple
698 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700699 2) Finding multiple /dev/sdX and returning None.
700
Kevin Cheng5595b342016-09-29 15:51:01 -0700701 Args:
702 timeout: Timeout to wait for blocking other servod processes.
703
Simran Basia9f41032012-05-11 14:21:58 -0700704 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700705 USB disk path if one and only one USB disk path is found, otherwise an
706 empty string.
Simran Basia9f41032012-05-11 14:21:58 -0700707 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700708 with self._block_other_servod(timeout=timeout) as block_success:
709 if not block_success:
710 return ''
Kevin Chengc49494e2016-07-25 12:13:38 -0700711
Kevin Cheng5595b342016-09-29 15:51:01 -0700712 original_value = self.get(self._USB_J3)
713 original_usb_power = self.get(self._USB_J3_PWR)
714 # Make the host unable to see the USB disk.
715 if (original_usb_power == self._USB_J3_PWR_ON and
716 original_value != self._USB_J3_TO_DUT):
717 self._switch_usbkey(self._USB_J3_TO_DUT)
718 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700719
Kevin Cheng5595b342016-09-29 15:51:01 -0700720 # Make the host able to see the USB disk.
721 self._switch_usbkey(self._USB_J3_TO_SERVO)
722 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700723
Kevin Cheng5595b342016-09-29 15:51:01 -0700724 # Back to its original value.
725 if original_value != self._USB_J3_TO_SERVO:
726 self._switch_usbkey(original_value)
727 if original_usb_power != self._USB_J3_PWR_ON:
728 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
729 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700730
Kevin Cheng5595b342016-09-29 15:51:01 -0700731 # Subtract the two sets to find the usb device.
732 diff_set = has_usb_set - no_usb_set
733 if len(diff_set) == 1:
734 return diff_set.pop()
735 else:
736 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700737
Kevin Cheng85831332016-10-13 13:14:44 -0700738 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700739 """Download image and save to the USB device found by probe_host_usb_dev.
740 If the image_path is a URL, it will download this url to the USB path;
741 otherwise it will simply copy the image_path's contents to the USB path.
742
743 Args:
744 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700745 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700746
747 Returns:
748 True|False: True if process completed successfully, False if error
749 occurred.
750 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
751 comment at the end of set().
752 """
753 self._logger.debug("image_path(%s)" % image_path)
754 self._logger.debug("Detecting USB stick device...")
Kevin Cheng85831332016-10-13 13:14:44 -0700755 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700756 if not usb_dev:
757 self._logger.error("No usb device connected to servo")
758 return False
759
Kevin Cheng9071ed92016-06-21 14:37:54 -0700760 # Let's check if we downloaded this last time and if so assume the image is
761 # still on the usb device and return True.
762 if self._image_path == image_path:
763 self._logger.debug("Image already on USB device, skipping transfer")
764 return True
765
Simran Basia9f41032012-05-11 14:21:58 -0700766 try:
767 if image_path.startswith(self._HTTP_PREFIX):
768 self._logger.debug("Image path is a URL, downloading image")
769 urllib.urlretrieve(image_path, usb_dev)
770 else:
771 shutil.copyfile(image_path, usb_dev)
772 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700773 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700774 e.strerror, e.errno)
775 return False
776 except urllib.ContentTooShortError:
777 self._logger.error("Failed to download URL: %s to USB device: %s",
778 image_path, usb_dev)
779 return False
780 except BaseException as e:
781 self._logger.error("Unexpected exception downloading %s to %s: %s",
782 image_path, usb_dev, str(e))
783 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800784 finally:
785 # We just plastered the partition table for a block device.
786 # Pass or fail, we mustn't go without telling the kernel about
787 # the change, or it will punish us with sporadic, hard-to-debug
788 # failures.
789 subprocess.call(["sync"])
790 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700791 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700792 return True
793
794 def make_image_noninteractive(self):
795 """Makes the recovery image noninteractive.
796
797 A noninteractive image will reboot automatically after installation
798 instead of waiting for the USB device to be removed to initiate a system
799 reboot.
800
801 Mounts partition 1 of the image stored on usb_dev and creates a file
802 called "non_interactive" so that the image will become noninteractive.
803
804 Returns:
805 True|False: True if process completed successfully, False if error
806 occurred.
807 """
808 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700809 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700810 if not usb_dev:
811 self._logger.error("No usb device connected to servo")
812 return False
813 # Create TempDirectory
814 tmpdir = tempfile.mkdtemp()
815 if tmpdir:
816 # Mount drive to tmpdir.
817 partition_1 = "%s1" % usb_dev
818 rc = subprocess.call(["mount", partition_1, tmpdir])
819 if rc == 0:
820 # Create file 'non_interactive'
821 non_interactive_file = os.path.join(tmpdir, "non_interactive")
822 try:
823 open(non_interactive_file, "w").close()
824 except IOError as e:
825 self._logger.error("Failed to create file %s : %s ( %d )",
826 non_interactive_file, e.strerror, e.errno)
827 result = False
828 except BaseException as e:
829 self._logger.error("Unexpected Exception creating file %s : %s",
830 non_interactive_file, str(e))
831 result = False
832 # Unmount drive regardless if file creation worked or not.
833 rc = subprocess.call(["umount", partition_1])
834 if rc != 0:
835 self._logger.error("Failed to unmount USB Device")
836 result = False
837 else:
838 self._logger.error("Failed to mount USB Device")
839 result = False
840
841 # Delete tmpdir. May throw exception if 'umount' failed.
842 try:
843 os.rmdir(tmpdir)
844 except OSError as e:
845 self._logger.error("Failed to remove temp directory %s : %s",
846 tmpdir, str(e))
847 return False
848 except BaseException as e:
849 self._logger.error("Unexpected Exception removing tempdir %s : %s",
850 tmpdir, str(e))
851 return False
852 else:
853 self._logger.error("Failed to create temp directory.")
854 return False
855 return result
856
Todd Broch352b4b22013-03-22 09:48:40 -0700857 def set_get_all(self, cmds):
858 """Set &| get one or more control values.
859
860 Args:
861 cmds: list of control[:value] to get or set.
862
863 Returns:
864 rv: list of responses from calling get or set methods.
865 """
866 rv = []
867 for cmd in cmds:
868 if ':' in cmd:
869 (control, value) = cmd.split(':')
870 rv.append(self.set(control, value))
871 else:
872 rv.append(self.get(cmd))
873 return rv
874
Todd Broche505b8d2011-03-21 18:19:54 -0700875 def get(self, name):
876 """Get control value.
877
878 Args:
879 name: name string of control
880
881 Returns:
882 Response from calling drv get method. Value is reformatted based on
883 control's dictionary parameters
884
885 Raises:
886 HwDriverError: Error occurred while using drv
887 """
888 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700889 if name == 'serialname':
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700890 if self._serialnames[self.MAIN_SERIAL]:
891 return self._serialnames[self.MAIN_SERIAL]
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700892 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700893 (param, drv) = self._get_param_drv(name)
894 try:
895 val = drv.get()
896 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800897 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700898 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700899 except AttributeError, error:
900 self._logger.error("Getting %s: %s" % (name, error))
901 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800902 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700903 self._logger.error("Getting %s" % (name))
904 raise
Todd Brochd6061672012-05-11 15:52:47 -0700905
Todd Broche505b8d2011-03-21 18:19:54 -0700906 def get_all(self, verbose):
907 """Get all controls values.
908
909 Args:
910 verbose: Boolean on whether to return doc info as well
911
912 Returns:
913 string creating from trying to get all values of all controls. In case of
914 error attempting access to control, response is 'ERR'.
915 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800916 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700917 for name in self._syscfg.syscfg_dict['control']:
918 self._logger.debug("name = %s" %name)
919 try:
920 value = self.get(name)
921 except Exception:
922 value = "ERR"
923 pass
924 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800925 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700926 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800927 rsp.append("%s:%s" % (name, value))
928 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700929
930 def set(self, name, wr_val_str):
931 """Set control.
932
933 Args:
934 name: name string of control
935 wr_val_str: value string to write. Can be integer, float or a
936 alpha-numerical that is mapped to a integer or float.
937
938 Raises:
939 HwDriverError: Error occurred while using driver
940 """
941 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
942 (params, drv) = self._get_param_drv(name, False)
943 wr_val = self._syscfg.resolve_val(params, wr_val_str)
944 try:
945 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800946 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700947 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
948 raise
949 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
950 # & client I still have to return something to appease the
951 # marshall/unmarshall
952 return True
953
Todd Brochd6061672012-05-11 15:52:47 -0700954 def hwinit(self, verbose=False):
955 """Initialize all controls.
956
957 These values are part of the system config XML files of the form
958 init=<value>. This command should be used by clients wishing to return the
959 servo and DUT its connected to a known good/safe state.
960
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800961 Note that initialization errors are ignored (as in some cases they could
962 be caused by DUT firmware deficiencies). This might need to be fine tuned
963 later.
964
Todd Brochd6061672012-05-11 15:52:47 -0700965 Args:
966 verbose: boolean, if True prints info about control initialized.
967 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800968
969 Returns:
970 This function is called across RPC and as such is expected to return
971 something unless transferring 'none' across is allowed. Hence adding a
972 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700973 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800974 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800975 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700976 # Workaround for bug chrome-os-partner:42349. Without this check, the
977 # gpio will briefly pulse low if we set it from high to high.
978 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700979 self.set(control_name, value)
980 if verbose:
981 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800982 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800983 self._logger.error("Problem initializing %s -> %s :: %s",
984 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -0800985
986 # Init keyboard after all the intefaces are up.
987 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800988 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800989
Todd Broche505b8d2011-03-21 18:19:54 -0700990 def echo(self, echo):
991 """Dummy echo function for testing/examples.
992
993 Args:
994 echo: string to echo back to client
995 """
996 self._logger.debug("echo(%s)" % (echo))
997 return "ECH0ING: %s" % (echo)
998
J. Richard Barnettee2820552013-03-14 16:13:46 -0700999 def get_board(self):
1000 """Return the board specified at startup, if any."""
1001 return self._board
1002
Simran Basia23c1392013-08-06 14:59:10 -07001003 def get_version(self):
1004 """Get servo board version."""
1005 return self._version
1006
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001007 def power_long_press(self):
1008 """Simulate a long power button press."""
1009 # After a long power press, the EC may ignore the next power
1010 # button press (at least on Alex). To guarantee that this
1011 # won't happen, we need to allow the EC one second to
1012 # collect itself.
1013 self._keyboard.power_long_press()
1014 return True
1015
1016 def power_normal_press(self):
1017 """Simulate a normal power button press."""
1018 self._keyboard.power_normal_press()
1019 return True
1020
1021 def power_short_press(self):
1022 """Simulate a short power button press."""
1023 self._keyboard.power_short_press()
1024 return True
1025
1026 def power_key(self, secs=''):
1027 """Simulate a power button press.
1028
1029 Args:
1030 secs: Time in seconds to simulate the keypress.
1031 """
1032 self._keyboard.power_key(secs)
1033 return True
1034
1035 def ctrl_d(self, press_secs=''):
1036 """Simulate Ctrl-d simultaneous button presses."""
1037 self._keyboard.ctrl_d(press_secs)
1038 return True
1039
Victor Dodone539cea2016-03-29 18:50:17 -07001040 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001041 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001042 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001043 return True
1044
1045 def ctrl_enter(self, press_secs=''):
1046 """Simulate Ctrl-enter simultaneous button presses."""
1047 self._keyboard.ctrl_enter(press_secs)
1048 return True
1049
1050 def d_key(self, press_secs=''):
1051 """Simulate Enter key button press."""
1052 self._keyboard.d_key(press_secs)
1053 return True
1054
1055 def ctrl_key(self, press_secs=''):
1056 """Simulate Enter key button press."""
1057 self._keyboard.ctrl_key(press_secs)
1058 return True
1059
1060 def enter_key(self, press_secs=''):
1061 """Simulate Enter key button press."""
1062 self._keyboard.enter_key(press_secs)
1063 return True
1064
1065 def refresh_key(self, press_secs=''):
1066 """Simulate Refresh key (F3) button press."""
1067 self._keyboard.refresh_key(press_secs)
1068 return True
1069
1070 def ctrl_refresh_key(self, press_secs=''):
1071 """Simulate Ctrl and Refresh (F3) simultaneous press.
1072
1073 This key combination is an alternative of Space key.
1074 """
1075 self._keyboard.ctrl_refresh_key(press_secs)
1076 return True
1077
1078 def imaginary_key(self, press_secs=''):
1079 """Simulate imaginary key button press.
1080
1081 Maps to a key that doesn't physically exist.
1082 """
1083 self._keyboard.imaginary_key(press_secs)
1084 return True
1085
Todd Brochdbb09982011-10-02 07:14:26 -07001086
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001087 def sysrq_x(self, press_secs=''):
1088 """Simulate Alt VolumeUp X simultaneous press.
1089
1090 This key combination is the kernel system request (sysrq) x.
1091 """
1092 self._keyboard.sysrq_x(press_secs)
1093 return True
1094
1095
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001096 def get_servo_serials(self):
1097 """Return all the serials associated with this process."""
1098 return self._serialnames
1099
1100
Todd Broche505b8d2011-03-21 18:19:54 -07001101def test():
1102 """Integration testing.
1103
1104 TODO(tbroch) Enhance integration test and add unittest (see mox)
1105 """
1106 logging.basicConfig(level=logging.DEBUG,
1107 format="%(asctime)s - %(name)s - " +
1108 "%(levelname)s - %(message)s")
1109 # configure server & listen
1110 servod_obj = Servod(1)
1111 # 4 == number of interfaces on a FT4232H device
1112 for i in xrange(4):
1113 if i == 1:
1114 # its an i2c interface ... see __init__ for details and TODO to make
1115 # this configureable
1116 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1117 else:
1118 # its a gpio interface
1119 servod_obj._interface_list[i].wr_rd(0)
1120
1121 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1122 allow_none=True)
1123 server.register_introspection_functions()
1124 server.register_multicall_functions()
1125 server.register_instance(servod_obj)
1126 logging.info("Listening on localhost port 9999")
1127 server.serve_forever()
1128
1129if __name__ == "__main__":
1130 test()
1131
1132 # simple client transaction would look like
1133 """
1134 remote_uri = 'http://localhost:9999'
1135 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1136 send_str = "Hello_there"
1137 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1138 """