blob: 892df1d4d8be607713a63ee92b37d2e5c80ff06a [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
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070018import usb
Todd Broche505b8d2011-03-21 18:19:54 -070019
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080020import drv as servo_drv
Aaron.Chuang88eff332014-07-31 08:32:00 +080021import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070022import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070023import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070024import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080025import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070026import ftdigpio
27import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070028import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070029import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080030import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080031import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070032import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070033import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080034import stm32gpio
35import stm32i2c
36import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070037
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080038HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080039
Todd Broche505b8d2011-03-21 18:19:54 -070040MAX_I2C_CLOCK_HZ = 100000
41
Kevin Cheng5595b342016-09-29 15:51:01 -070042# It takes about 16-17 seconds for the entire probe usb device method,
43# let's wait double plus some buffer.
44_MAX_USB_LOCK_WAIT = 40
Todd Brochdbb09982011-10-02 07:14:26 -070045
Todd Broche505b8d2011-03-21 18:19:54 -070046class ServodError(Exception):
47 """Exception class for servod."""
48
49class Servod(object):
50 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070051 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070052 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070053 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070054 _USB_J3 = "usb_mux_sel1"
55 _USB_J3_TO_SERVO = "servo_sees_usbkey"
56 _USB_J3_TO_DUT = "dut_sees_usbkey"
57 _USB_J3_PWR = "prtctl4_pwren"
58 _USB_J3_PWR_ON = "on"
59 _USB_J3_PWR_OFF = "off"
Kevin Chengc49494e2016-07-25 12:13:38 -070060 _USB_LOCK_FILE = "/var/lib/servod/lock_file"
Simran Basia9f41032012-05-11 14:21:58 -070061
Kevin Cheng4b4f0022016-09-09 02:37:07 -070062 # This is the key to get the main serial used in the _serialnames dict.
63 MAIN_SERIAL = "main"
Wai-Hong Tam4b235922016-10-07 12:26:22 -070064 MICRO_SERVO_SERIAL = "micro_servo"
Wai-Hong Tam85b4ced2016-10-07 14:15:38 -070065 CCD_SERIAL = "ccd"
Kevin Cheng4b4f0022016-09-09 02:37:07 -070066
Kevin Chengdc3befd2016-07-15 12:34:00 -070067 def init_servo_interfaces(self, vendor, product, serialname,
68 interfaces):
69 """Init the servo interfaces with the given interfaces.
70
71 We don't use the self._{vendor,product,serialname} attributes because we
72 want to allow other callers to initialize other interfaces that may not
73 be associated with the initialized attributes (e.g. a servo v4 servod object
74 that wants to also initialize a servo micro interface).
75
76 Args:
77 vendor: USB vendor id of FTDI device.
78 product: USB product id of FTDI device.
79 serialname: String of device serialname/number as defined in FTDI
80 eeprom.
81 interfaces: List of strings of interface types the server will
82 instantiate.
83
84 Raises:
85 ServodError if unable to locate init method for particular interface.
86 """
Mary Ruthven13389642017-02-14 12:15:34 -080087 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070088 device = (vendor, product, serialname)
Mary Ruthven13389642017-02-14 12:15:34 -080089 if device not in self._devices:
90 self._devices.append(device)
91
Kevin Chengdc3befd2016-07-15 12:34:00 -070092 # Extend the interface list if we need to.
93 interfaces_len = len(interfaces)
94 interface_list_len = len(self._interface_list)
95 if interfaces_len > interface_list_len:
96 self._interface_list += [None] * (interfaces_len - interface_list_len)
97
98 shifted = 0
99 for i, interface in enumerate(interfaces):
100 is_ftdi_interface = False
101 if type(interface) is dict:
102 name = interface['name']
103 # Store interface index for those that care about it.
104 interface['index'] = i
105 elif type(interface) is str and interface != 'dummy':
106 name = interface
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700107 # It's a FTDI related interface. #0 is reserved for no use.
108 interface = ((i - 1) % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
Kevin Chengdc3befd2016-07-15 12:34:00 -0700109 is_ftdi_interface = True
110 elif type(interface) is str and interface == 'dummy':
111 # 'dummy' reserves the interface for future use. Typically the
112 # interface will be managed by external third-party tools like
113 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
114 # it serves as a placeholder for servo micro interfaces.
115 continue
116 else:
117 raise ServodError("Illegal interface type %s" % type(interface))
118
119 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700120 product_increment = 0
121 if is_ftdi_interface:
122 product_increment = (i - 1) / ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE
123 if product_increment:
124 self._logger.info("Use the next FTDI part @ pid = 0x%04x",
125 product + product_increment)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700126
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700127 self._logger.info("Initializing interface %d to %s", i, name)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700128 try:
129 func = getattr(self, '_init_%s' % name)
130 except AttributeError:
131 raise ServodError("Unable to locate init for interface %s" % name)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700132 result = func(vendor, product + product_increment, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700133
134 if isinstance(result, tuple):
135 result_len = len(result)
Wai-Hong Tam9441b182016-11-01 11:05:09 -0700136 # More than one interface return. Extend the list.
137 self._interface_list += [None] * (result_len - 1)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700138 for result_index, r in enumerate(result):
Wai-Hong Tam9441b182016-11-01 11:05:09 -0700139 self._interface_list[i + shifted + result_index] = r
140 # Shift the remaining interfaces.
141 shifted += result_len - 1
Kevin Chengdc3befd2016-07-15 12:34:00 -0700142 else:
143 self._interface_list[i + shifted] = result
144
J. Richard Barnettee2820552013-03-14 16:13:46 -0700145 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800146 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700147 """Servod constructor.
148
149 Args:
150 config: instance of SystemConfig containing all controls for
151 particular Servod invocation
152 vendor: usb vendor id of FTDI device
153 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700154 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700155 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700156 version: String. Servo board version. Examples: servo_v1, servo_v2,
157 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800158 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700159 sending keyboard commands to DUTs that do not have built in
160 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
161 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -0700162
163 Raises:
164 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700165 """
166 self._logger = logging.getLogger("Servod")
167 self._logger.debug("")
168 self._vendor = vendor
169 self._product = product
Mary Ruthven13389642017-02-14 12:15:34 -0800170 self._devices = []
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700171 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700172 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700173 # Hold the last image path so we can reduce downloads to the usb device.
174 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700175 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
176 # interfaces are mapped to
177 self._interface_list = []
178 # Dict of Dict to map control name, function name to to tuple (params, drv)
179 # Ex) _drv_dict[name]['get'] = (params, drv)
180 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700181 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -0700182 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800183 self._usbkm232 = usbkm232
Kevin Chengc49494e2016-07-25 12:13:38 -0700184 # Seed the random generator with the serial to differentiate from other
185 # servod processes.
186 random.seed(serialname if serialname else time.time())
Todd Brochdbb09982011-10-02 07:14:26 -0700187 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700188 try:
189 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
190 except KeyError:
191 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -0700192
Kevin Chengdc3befd2016-07-15 12:34:00 -0700193 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700194 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800195
Mary Ruthven13389642017-02-14 12:15:34 -0800196 def reinitialize(self):
197 """Reinitialize all interfaces that support reinitialization"""
198
199 # If all of the devices that were originally connected are not connected
200 # now, wait up to max_tries * sleep_time for the devices to reconnect
201 max_tries = 10
202 sleep_time = 0.5
203 for i in range(max_tries):
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -0700204 for vid, pid, serialname in self._devices:
205 for current in usb.core.find(idVendor=vid, idProduct=pid,
206 find_all=True):
207 current_serial = usb.util.get_string(current, 256,
208 current.iSerialNumber)
209 if not serialname or serialname == current_serial:
210 # This device still available
211 break
212 else:
213 self._logger.warn('Servo USB device not found: %x:%x serial:%s',
214 vid, pid, serialname)
215 break
216 else:
217 # All the devices found. Reinitialize the interfaces...
Mary Ruthven13389642017-02-14 12:15:34 -0800218 break
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -0700219 time.sleep(sleep_time)
220 else:
221 raise ServodError('Servo USB device not found during reinitialize')
Mary Ruthven13389642017-02-14 12:15:34 -0800222
223 for i, interface in enumerate(self._interface_list):
224 if hasattr(interface, "reinitialize"):
225 interface.reinitialize()
226 else:
227 self._logger.debug("interface %d has no reset functionality", i)
228
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800229 def _init_keyboard_handler(self, servo, board=''):
230 """Initialize the correct keyboard handler for board.
231
Kevin Chengdc3befd2016-07-15 12:34:00 -0700232 Args:
233 servo: servo object.
234 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800235
Kevin Chengdc3befd2016-07-15 12:34:00 -0700236 Returns:
237 keyboard handler object.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800238 """
239 if board == 'parrot':
240 return keyboard_handlers.ParrotHandler(servo)
241 elif board == 'stout':
242 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800243 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800244 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
philipchenfc9eea12016-09-21 17:36:54 -0700245 'sumo', 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
246 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800247 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800248 logging.info("No device path specified for usbkm232 handler. Use "
249 "the servo atmega chip to handle.")
250 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800251 if self._usbkm232 == 'atmega':
252 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800253 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800254 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800255 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800256 self._usbkm232 = self.get('atmega_pty')
Kevin Cheng810fc782016-11-01 12:36:46 -0700257 # We don't need to set the atmega uart settings if we're a servo v4.
258 if self._version != 'servo_v4':
259 self.set('atmega_baudrate', '9600')
260 self.set('atmega_bits', 'eight')
261 self.set('atmega_parity', 'none')
262 self.set('atmega_sbits', 'one')
263 self.set('usb_mux_sel4', 'on')
264 self.set('usb_mux_oe4', 'on')
265 # Allow atmega bootup time.
266 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800267 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800268 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
269 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800270 # The following boards don't use Chrome EC.
271 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
272 return keyboard_handlers.MatrixKeyboardHandler(servo)
273 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800274
Todd Broch3ec8df02012-11-20 10:53:03 -0800275 def __del__(self):
276 """Servod deconstructor."""
277 for interface in self._interface_list:
278 del(interface)
279
Kevin Chengdc3befd2016-07-15 12:34:00 -0700280 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700281 """Dummy interface for ftdi devices.
282
283 This is a dummy function specifically for ftdi devices to not initialize
284 anything but to help pad the interface list.
285
286 Returns:
287 None.
288 """
289 return None
290
Kevin Chengdc3befd2016-07-15 12:34:00 -0700291 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700292 """Initialize gpio driver interface and open for use.
293
294 Args:
295 interface: interface number of FTDI device to use.
296
297 Returns:
298 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700299
300 Raises:
301 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700302 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700303 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700304 try:
305 fobj.open()
306 except ftdigpio.FgpioError as e:
307 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
308
Todd Broche505b8d2011-03-21 18:19:54 -0700309 return fobj
310
Kevin Chengdc3befd2016-07-15 12:34:00 -0700311 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800312 """Initialize stm32 uart interface and open for use
313
314 Note, the uart runs in a separate thread. Users wishing to
315 interact with it will query control for the pty's pathname and connect
316 with their favorite console program. For example:
317 cu -l /dev/pts/22
318
319 Args:
320 interface: dict of interface parameters.
321
322 Returns:
323 Instance object of interface
324
325 Raises:
326 ServodError: Raised on init failure.
327 """
328 self._logger.info("Suart: interface: %s" % interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700329 sobj = stm32uart.Suart(vendor, product, interface['interface'],
330 serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800331
332 try:
333 sobj.run()
334 except stm32uart.SuartError as e:
335 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
336
337 self._logger.info("%s" % sobj.get_pty())
338 return sobj
339
Kevin Chengdc3befd2016-07-15 12:34:00 -0700340 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800341 """Initialize stm32 gpio interface.
342 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700343 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800344
345 Returns:
346 Instance object of interface
347
348 Raises:
349 SgpioError: Raised on init failure.
350 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700351 interface_number = interface
352 # Interface could be a dict.
353 if type(interface) is dict:
354 interface_number = interface['interface']
355 self._logger.info("Sgpio: interface: %s" % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700356 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800357
Kevin Chengdc3befd2016-07-15 12:34:00 -0700358 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800359 """Initialize stm32 USB to I2C bridge interface and open for use
360
361 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700362 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800363
364 Returns:
365 Instance object of interface.
366
367 Raises:
368 Si2cError: Raised on init failure.
369 """
370 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800371 port = interface.get('port', 0)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700372 return stm32i2c.Si2cBus(vendor, product, interface['interface'],
373 port=port, serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800374
Kevin Chengdc3befd2016-07-15 12:34:00 -0700375 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800376 """Initalize beaglebone ADC interface."""
377 return bbadc.BBadc()
378
Kevin Chengdc3befd2016-07-15 12:34:00 -0700379 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700380 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700381 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700382
Kevin Chengdc3befd2016-07-15 12:34:00 -0700383 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700384 """Initialize i2c interface and open for use.
385
386 Args:
387 interface: interface number of FTDI device to use
388
389 Returns:
390 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700391
392 Raises:
393 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700394 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700395 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700396 try:
397 fobj.open()
398 except ftdii2c.Fi2cError as e:
399 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
400
Todd Broche505b8d2011-03-21 18:19:54 -0700401 # Set the frequency of operation of the i2c bus.
402 # TODO(tbroch) make configureable
403 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700404
Todd Broche505b8d2011-03-21 18:19:54 -0700405 return fobj
406
Simran Basie750a342013-03-12 13:45:26 -0700407 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
408 def _init_bb_i2c(self, interface):
409 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700410 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700411
Kevin Chengdc3befd2016-07-15 12:34:00 -0700412 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800413 """Initalize Linux i2c-dev interface."""
414 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
415
Kevin Chengdc3befd2016-07-15 12:34:00 -0700416 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700417 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700418
419 Note, the uart runs in a separate thread (pthreads). Users wishing to
420 interact with it will query control for the pty's pathname and connect
421 with there favorite console program. For example:
422 cu -l /dev/pts/22
423
424 Args:
425 interface: interface number of FTDI device to use
426
427 Returns:
428 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700429
430 Raises:
431 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700432 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700433 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700434 try:
435 fobj.run()
436 except ftdiuart.FuartError as e:
437 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
438
Todd Broch47c43f42011-05-26 15:11:31 -0700439 self._logger.info("%s" % fobj.get_pty())
440 return fobj
441
Simran Basie750a342013-03-12 13:45:26 -0700442 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700443 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700444 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700445 logging.debug('UART INTERFACE: %s', interface)
446 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700447
Kevin Chengdc3befd2016-07-15 12:34:00 -0700448 def _init_ftdi_gpiouart(self, vendor, product, serialname,
449 interface):
Todd Broch888da782011-10-07 14:29:09 -0700450 """Initialize special gpio + uart interface and open for use
451
452 Note, the uart runs in a separate thread (pthreads). Users wishing to
453 interact with it will query control for the pty's pathname and connect
454 with there favorite console program. For example:
455 cu -l /dev/pts/22
456
457 Args:
458 interface: interface number of FTDI device to use
459
460 Returns:
461 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700462
463 Raises:
464 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700465 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700466 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700467 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700468 try:
469 fuart.run()
470 except ftdiuart.FuartError as e:
471 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
472
Todd Broch888da782011-10-07 14:29:09 -0700473 self._logger.info("uart pty: %s" % fuart.get_pty())
474 return fgpio, fuart
475
Kevin Chengdc3befd2016-07-15 12:34:00 -0700476 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800477 """Initialize EC-3PO console interpreter interface.
478
479 Args:
480 interface: A dictionary representing the interface.
481
482 Returns:
483 An EC3PO object representing the EC-3PO interface or None if there's no
484 interface for the USB PD UART.
485 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700486 raw_uart_name = interface['raw_pty']
487 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800488 raw_ec_uart = self.get(raw_uart_name)
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700489 return ec3po_interface.EC3PO(raw_ec_uart)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800490 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700491 # The overlay doesn't have the raw PTY defined, therefore we can skip
492 # initializing this interface since no control relies on it.
493 self._logger.debug(
494 'Skip initializing EC3PO for %s, no control specified.',
495 raw_uart_name)
496 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800497
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800498 def _camel_case(self, string):
499 output = ''
500 for s in string.split('_'):
501 if output:
502 output += s.capitalize()
503 else:
504 output = s
505 return output
506
Todd Broche505b8d2011-03-21 18:19:54 -0700507 def _get_param_drv(self, control_name, is_get=True):
508 """Get access to driver for a given control.
509
510 Note, some controls have different parameter dictionaries for 'getting' the
511 control's value versus 'setting' it. Boolean is_get distinguishes which is
512 being requested.
513
514 Args:
515 control_name: string name of control
516 is_get: boolean to determine
517
518 Returns:
519 tuple (param, drv) where:
520 param: param dictionary for control
521 drv: instance object of driver for particular control
522
523 Raises:
524 ServodError: Error occurred while examining params dict
525 """
526 self._logger.debug("")
527 # if already setup just return tuple from driver dict
528 if control_name in self._drv_dict:
529 if is_get and ('get' in self._drv_dict[control_name]):
530 return self._drv_dict[control_name]['get']
531 if not is_get and ('set' in self._drv_dict[control_name]):
532 return self._drv_dict[control_name]['set']
533
534 params = self._syscfg.lookup_control_params(control_name, is_get)
535 if 'drv' not in params:
536 self._logger.error("Unable to determine driver for %s" % control_name)
537 raise ServodError("'drv' key not found in params dict")
538 if 'interface' not in params:
539 self._logger.error("Unable to determine interface for %s" %
540 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700541 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700542
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800543 interface_id = params.get(
544 '%s_interface' % self._version, params['interface'])
545 if interface_id == 'servo':
546 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700547 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700548 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800549 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700550
Todd Broche505b8d2011-03-21 18:19:54 -0700551 drv_name = params['drv']
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800552 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800553 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700554 drv = drv_class(interface, params)
555 if control_name not in self._drv_dict:
556 self._drv_dict[control_name] = {}
557 if is_get:
558 self._drv_dict[control_name]['get'] = (params, drv)
559 else:
560 self._drv_dict[control_name]['set'] = (params, drv)
561 return (params, drv)
562
563 def doc_all(self):
564 """Return all documenation for controls.
565
566 Returns:
567 string of <doc> text in config file (xml) and the params dictionary for
568 all controls.
569
570 For example:
571 warm_reset :: Reset the device warmly
572 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
573 """
574 return self._syscfg.display_config()
575
576 def doc(self, name):
577 """Retreive doc string in system config file for given control name.
578
579 Args:
580 name: name string of control to get doc string
581
582 Returns:
583 doc string of name
584
585 Raises:
586 NameError: if fails to locate control
587 """
588 self._logger.debug("name(%s)" % (name))
589 if self._syscfg.is_control(name):
590 return self._syscfg.get_control_docstring(name)
591 else:
592 raise NameError("No control %s" %name)
593
Fang Deng90377712013-06-03 15:51:48 -0700594 def _switch_usbkey(self, mux_direction):
595 """Connect USB flash stick to either servo or DUT.
596
597 This function switches 'usb_mux_sel1' to provide electrical
598 connection between the USB port J3 and either servo or DUT side.
599
600 Switching the usb mux is accompanied by powercycling
601 of the USB stick, because it sometimes gets wedged if the mux
602 is switched while the stick power is on.
603
604 Args:
605 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
606 """
607 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
608 time.sleep(self._USB_POWEROFF_DELAY)
609 self.set(self._USB_J3, mux_direction)
610 time.sleep(self._USB_POWEROFF_DELAY)
611 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
612 if mux_direction == self._USB_J3_TO_SERVO:
613 time.sleep(self._USB_DETECTION_DELAY)
614
Simran Basia9f41032012-05-11 14:21:58 -0700615 def _get_usb_port_set(self):
616 """Gets a set of USB disks currently connected to the system
617
618 Returns:
619 A set of USB disk paths.
620 """
621 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
622 return set(["/dev/" + dev for dev in usb_set])
623
Kevin Cheng5595b342016-09-29 15:51:01 -0700624 @contextlib.contextmanager
625 def _block_other_servod(self, timeout=None):
Kevin Chengc49494e2016-07-25 12:13:38 -0700626 """Block other servod processes by locking a file.
627
628 To enable multiple servods processes to safely probe_host_usb_dev, we use
629 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700630 for a usb device. This will be a context manager that will return
631 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700632
633 If the lock file exists, we open it and try to lock it.
634 - If another servod processes has locked it already, we'll sleep a random
635 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700636 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700637
Kevin Cheng5595b342016-09-29 15:51:01 -0700638 - If we're able to lock the file, we'll yield that the block was successful
639 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700640
641 This blocking behavior is only enabled if the lock file exists, if it
642 doesn't, then we pretend the block was successful.
643
Kevin Cheng5595b342016-09-29 15:51:01 -0700644 Args:
645 timeout: Max waiting time for the block to succeed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700646 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700647 if not os.path.exists(self._USB_LOCK_FILE):
648 # No lock file so we'll pretend the block was a success.
649 yield True
650 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700651 start_time = datetime.datetime.now()
652 while True:
Kevin Cheng5595b342016-09-29 15:51:01 -0700653 with open(self._USB_LOCK_FILE) as lock_file:
654 try:
655 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
656 yield True
657 fcntl.flock(lock_file, fcntl.LOCK_UN)
658 break
659 except IOError:
660 current_time = datetime.datetime.now()
661 current_wait_time = (current_time - start_time).total_seconds()
662 if timeout and current_wait_time > timeout:
663 yield False
664 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700665 # Sleep random amount.
666 sleep_time = time.sleep(random.random())
Kevin Chengc49494e2016-07-25 12:13:38 -0700667
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700668 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700669 """Toggle the usb power safely.
670
671 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700672
673 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700674 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700675 timeout: Timeout to wait for blocking other servod processes, default is
676 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700677
Kevin Cheng5595b342016-09-29 15:51:01 -0700678 Returns:
679 An empty string to appease the xmlrpc gods.
680 """
681 with self._block_other_servod(timeout=timeout):
682 if power_state != self.get(self._USB_J3_PWR):
683 self.set(self._USB_J3_PWR, power_state)
684 return ''
685
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700686 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700687 """Toggle the usb direction safely.
688
689 We'll make sure we're the only servod process toggling the usbkey direction.
690
691 Args:
692 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700693 timeout: Timeout to wait for blocking other servod processes, default is
694 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700695
696 Returns:
697 An empty string to appease the xmlrpc gods.
698 """
699 with self._block_other_servod(timeout=timeout):
700 self._switch_usbkey(mux_direction)
701 return ''
702
703 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700704 """Probe the USB disk device plugged in the servo from the host side.
705
706 Method can fail by:
707 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700708 another servo unless _USB_LOCK_FILE exists on the servo host. If that
709 file exists, then it is safe to probe for usb devices among multiple
710 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700711 2) Finding multiple /dev/sdX and returning None.
712
Kevin Cheng5595b342016-09-29 15:51:01 -0700713 Args:
714 timeout: Timeout to wait for blocking other servod processes.
715
Simran Basia9f41032012-05-11 14:21:58 -0700716 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700717 USB disk path if one and only one USB disk path is found, otherwise an
718 empty string.
Simran Basia9f41032012-05-11 14:21:58 -0700719 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700720 with self._block_other_servod(timeout=timeout) as block_success:
721 if not block_success:
722 return ''
Kevin Chengc49494e2016-07-25 12:13:38 -0700723
Kevin Cheng5595b342016-09-29 15:51:01 -0700724 original_value = self.get(self._USB_J3)
725 original_usb_power = self.get(self._USB_J3_PWR)
726 # Make the host unable to see the USB disk.
727 if (original_usb_power == self._USB_J3_PWR_ON and
728 original_value != self._USB_J3_TO_DUT):
729 self._switch_usbkey(self._USB_J3_TO_DUT)
730 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700731
Kevin Cheng5595b342016-09-29 15:51:01 -0700732 # Make the host able to see the USB disk.
733 self._switch_usbkey(self._USB_J3_TO_SERVO)
734 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700735
Kevin Cheng5595b342016-09-29 15:51:01 -0700736 # Back to its original value.
737 if original_value != self._USB_J3_TO_SERVO:
738 self._switch_usbkey(original_value)
739 if original_usb_power != self._USB_J3_PWR_ON:
740 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
741 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700742
Kevin Cheng5595b342016-09-29 15:51:01 -0700743 # Subtract the two sets to find the usb device.
744 diff_set = has_usb_set - no_usb_set
745 if len(diff_set) == 1:
746 return diff_set.pop()
747 else:
748 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700749
Kevin Cheng85831332016-10-13 13:14:44 -0700750 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700751 """Download image and save to the USB device found by probe_host_usb_dev.
752 If the image_path is a URL, it will download this url to the USB path;
753 otherwise it will simply copy the image_path's contents to the USB path.
754
755 Args:
756 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700757 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700758
759 Returns:
760 True|False: True if process completed successfully, False if error
761 occurred.
762 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
763 comment at the end of set().
764 """
765 self._logger.debug("image_path(%s)" % image_path)
766 self._logger.debug("Detecting USB stick device...")
Kevin Cheng85831332016-10-13 13:14:44 -0700767 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700768 if not usb_dev:
769 self._logger.error("No usb device connected to servo")
770 return False
771
Kevin Cheng9071ed92016-06-21 14:37:54 -0700772 # Let's check if we downloaded this last time and if so assume the image is
773 # still on the usb device and return True.
774 if self._image_path == image_path:
775 self._logger.debug("Image already on USB device, skipping transfer")
776 return True
777
Simran Basia9f41032012-05-11 14:21:58 -0700778 try:
779 if image_path.startswith(self._HTTP_PREFIX):
780 self._logger.debug("Image path is a URL, downloading image")
781 urllib.urlretrieve(image_path, usb_dev)
782 else:
783 shutil.copyfile(image_path, usb_dev)
784 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700785 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700786 e.strerror, e.errno)
787 return False
788 except urllib.ContentTooShortError:
789 self._logger.error("Failed to download URL: %s to USB device: %s",
790 image_path, usb_dev)
791 return False
792 except BaseException as e:
793 self._logger.error("Unexpected exception downloading %s to %s: %s",
794 image_path, usb_dev, str(e))
795 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800796 finally:
797 # We just plastered the partition table for a block device.
798 # Pass or fail, we mustn't go without telling the kernel about
799 # the change, or it will punish us with sporadic, hard-to-debug
800 # failures.
801 subprocess.call(["sync"])
802 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700803 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700804 return True
805
806 def make_image_noninteractive(self):
807 """Makes the recovery image noninteractive.
808
809 A noninteractive image will reboot automatically after installation
810 instead of waiting for the USB device to be removed to initiate a system
811 reboot.
812
813 Mounts partition 1 of the image stored on usb_dev and creates a file
814 called "non_interactive" so that the image will become noninteractive.
815
816 Returns:
817 True|False: True if process completed successfully, False if error
818 occurred.
819 """
820 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700821 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700822 if not usb_dev:
823 self._logger.error("No usb device connected to servo")
824 return False
825 # Create TempDirectory
826 tmpdir = tempfile.mkdtemp()
827 if tmpdir:
828 # Mount drive to tmpdir.
829 partition_1 = "%s1" % usb_dev
830 rc = subprocess.call(["mount", partition_1, tmpdir])
831 if rc == 0:
832 # Create file 'non_interactive'
833 non_interactive_file = os.path.join(tmpdir, "non_interactive")
834 try:
835 open(non_interactive_file, "w").close()
836 except IOError as e:
837 self._logger.error("Failed to create file %s : %s ( %d )",
838 non_interactive_file, e.strerror, e.errno)
839 result = False
840 except BaseException as e:
841 self._logger.error("Unexpected Exception creating file %s : %s",
842 non_interactive_file, str(e))
843 result = False
844 # Unmount drive regardless if file creation worked or not.
845 rc = subprocess.call(["umount", partition_1])
846 if rc != 0:
847 self._logger.error("Failed to unmount USB Device")
848 result = False
849 else:
850 self._logger.error("Failed to mount USB Device")
851 result = False
852
853 # Delete tmpdir. May throw exception if 'umount' failed.
854 try:
855 os.rmdir(tmpdir)
856 except OSError as e:
857 self._logger.error("Failed to remove temp directory %s : %s",
858 tmpdir, str(e))
859 return False
860 except BaseException as e:
861 self._logger.error("Unexpected Exception removing tempdir %s : %s",
862 tmpdir, str(e))
863 return False
864 else:
865 self._logger.error("Failed to create temp directory.")
866 return False
867 return result
868
Todd Broch352b4b22013-03-22 09:48:40 -0700869 def set_get_all(self, cmds):
870 """Set &| get one or more control values.
871
872 Args:
873 cmds: list of control[:value] to get or set.
874
875 Returns:
876 rv: list of responses from calling get or set methods.
877 """
878 rv = []
879 for cmd in cmds:
880 if ':' in cmd:
881 (control, value) = cmd.split(':')
882 rv.append(self.set(control, value))
883 else:
884 rv.append(self.get(cmd))
885 return rv
886
Todd Broche505b8d2011-03-21 18:19:54 -0700887 def get(self, name):
888 """Get control value.
889
890 Args:
891 name: name string of control
892
893 Returns:
894 Response from calling drv get method. Value is reformatted based on
895 control's dictionary parameters
896
897 Raises:
898 HwDriverError: Error occurred while using drv
899 """
900 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700901 if name == 'serialname':
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700902 if self._serialnames[self.MAIN_SERIAL]:
903 return self._serialnames[self.MAIN_SERIAL]
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700904 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700905 (param, drv) = self._get_param_drv(name)
906 try:
907 val = drv.get()
908 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800909 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700910 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700911 except AttributeError, error:
912 self._logger.error("Getting %s: %s" % (name, error))
913 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800914 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700915 self._logger.error("Getting %s" % (name))
916 raise
Todd Brochd6061672012-05-11 15:52:47 -0700917
Todd Broche505b8d2011-03-21 18:19:54 -0700918 def get_all(self, verbose):
919 """Get all controls values.
920
921 Args:
922 verbose: Boolean on whether to return doc info as well
923
924 Returns:
925 string creating from trying to get all values of all controls. In case of
926 error attempting access to control, response is 'ERR'.
927 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800928 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700929 for name in self._syscfg.syscfg_dict['control']:
930 self._logger.debug("name = %s" %name)
931 try:
932 value = self.get(name)
933 except Exception:
934 value = "ERR"
935 pass
936 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800937 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700938 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800939 rsp.append("%s:%s" % (name, value))
940 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700941
942 def set(self, name, wr_val_str):
943 """Set control.
944
945 Args:
946 name: name string of control
947 wr_val_str: value string to write. Can be integer, float or a
948 alpha-numerical that is mapped to a integer or float.
949
950 Raises:
951 HwDriverError: Error occurred while using driver
952 """
953 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
954 (params, drv) = self._get_param_drv(name, False)
955 wr_val = self._syscfg.resolve_val(params, wr_val_str)
956 try:
957 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800958 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700959 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
960 raise
961 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
962 # & client I still have to return something to appease the
963 # marshall/unmarshall
964 return True
965
Todd Brochd6061672012-05-11 15:52:47 -0700966 def hwinit(self, verbose=False):
967 """Initialize all controls.
968
969 These values are part of the system config XML files of the form
970 init=<value>. This command should be used by clients wishing to return the
971 servo and DUT its connected to a known good/safe state.
972
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800973 Note that initialization errors are ignored (as in some cases they could
974 be caused by DUT firmware deficiencies). This might need to be fine tuned
975 later.
976
Todd Brochd6061672012-05-11 15:52:47 -0700977 Args:
978 verbose: boolean, if True prints info about control initialized.
979 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800980
981 Returns:
982 This function is called across RPC and as such is expected to return
983 something unless transferring 'none' across is allowed. Hence adding a
984 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700985 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800986 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800987 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700988 # Workaround for bug chrome-os-partner:42349. Without this check, the
989 # gpio will briefly pulse low if we set it from high to high.
990 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700991 self.set(control_name, value)
992 if verbose:
993 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800994 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800995 self._logger.error("Problem initializing %s -> %s :: %s",
996 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -0800997
998 # Init keyboard after all the intefaces are up.
999 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001000 return True
Todd Broch3ec8df02012-11-20 10:53:03 -08001001
Todd Broche505b8d2011-03-21 18:19:54 -07001002 def echo(self, echo):
1003 """Dummy echo function for testing/examples.
1004
1005 Args:
1006 echo: string to echo back to client
1007 """
1008 self._logger.debug("echo(%s)" % (echo))
1009 return "ECH0ING: %s" % (echo)
1010
J. Richard Barnettee2820552013-03-14 16:13:46 -07001011 def get_board(self):
1012 """Return the board specified at startup, if any."""
1013 return self._board
1014
Simran Basia23c1392013-08-06 14:59:10 -07001015 def get_version(self):
1016 """Get servo board version."""
1017 return self._version
1018
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001019 def power_long_press(self):
1020 """Simulate a long power button press."""
1021 # After a long power press, the EC may ignore the next power
1022 # button press (at least on Alex). To guarantee that this
1023 # won't happen, we need to allow the EC one second to
1024 # collect itself.
1025 self._keyboard.power_long_press()
1026 return True
1027
1028 def power_normal_press(self):
1029 """Simulate a normal power button press."""
1030 self._keyboard.power_normal_press()
1031 return True
1032
1033 def power_short_press(self):
1034 """Simulate a short power button press."""
1035 self._keyboard.power_short_press()
1036 return True
1037
1038 def power_key(self, secs=''):
1039 """Simulate a power button press.
1040
1041 Args:
1042 secs: Time in seconds to simulate the keypress.
1043 """
1044 self._keyboard.power_key(secs)
1045 return True
1046
1047 def ctrl_d(self, press_secs=''):
1048 """Simulate Ctrl-d simultaneous button presses."""
1049 self._keyboard.ctrl_d(press_secs)
1050 return True
1051
Victor Dodone539cea2016-03-29 18:50:17 -07001052 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001053 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001054 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001055 return True
1056
1057 def ctrl_enter(self, press_secs=''):
1058 """Simulate Ctrl-enter simultaneous button presses."""
1059 self._keyboard.ctrl_enter(press_secs)
1060 return True
1061
1062 def d_key(self, press_secs=''):
1063 """Simulate Enter key button press."""
1064 self._keyboard.d_key(press_secs)
1065 return True
1066
1067 def ctrl_key(self, press_secs=''):
1068 """Simulate Enter key button press."""
1069 self._keyboard.ctrl_key(press_secs)
1070 return True
1071
1072 def enter_key(self, press_secs=''):
1073 """Simulate Enter key button press."""
1074 self._keyboard.enter_key(press_secs)
1075 return True
1076
1077 def refresh_key(self, press_secs=''):
1078 """Simulate Refresh key (F3) button press."""
1079 self._keyboard.refresh_key(press_secs)
1080 return True
1081
1082 def ctrl_refresh_key(self, press_secs=''):
1083 """Simulate Ctrl and Refresh (F3) simultaneous press.
1084
1085 This key combination is an alternative of Space key.
1086 """
1087 self._keyboard.ctrl_refresh_key(press_secs)
1088 return True
1089
1090 def imaginary_key(self, press_secs=''):
1091 """Simulate imaginary key button press.
1092
1093 Maps to a key that doesn't physically exist.
1094 """
1095 self._keyboard.imaginary_key(press_secs)
1096 return True
1097
Todd Brochdbb09982011-10-02 07:14:26 -07001098
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001099 def sysrq_x(self, press_secs=''):
1100 """Simulate Alt VolumeUp X simultaneous press.
1101
1102 This key combination is the kernel system request (sysrq) x.
1103 """
1104 self._keyboard.sysrq_x(press_secs)
1105 return True
1106
1107
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001108 def get_servo_serials(self):
1109 """Return all the serials associated with this process."""
1110 return self._serialnames
1111
1112
Todd Broche505b8d2011-03-21 18:19:54 -07001113def test():
1114 """Integration testing.
1115
1116 TODO(tbroch) Enhance integration test and add unittest (see mox)
1117 """
1118 logging.basicConfig(level=logging.DEBUG,
1119 format="%(asctime)s - %(name)s - " +
1120 "%(levelname)s - %(message)s")
1121 # configure server & listen
1122 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -07001123 # 5 == number of interfaces on a FT4232H device
1124 for i in xrange(1, 5):
1125 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -07001126 # its an i2c interface ... see __init__ for details and TODO to make
1127 # this configureable
1128 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1129 else:
1130 # its a gpio interface
1131 servod_obj._interface_list[i].wr_rd(0)
1132
1133 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1134 allow_none=True)
1135 server.register_introspection_functions()
1136 server.register_multicall_functions()
1137 server.register_instance(servod_obj)
1138 logging.info("Listening on localhost port 9999")
1139 server.serve_forever()
1140
1141if __name__ == "__main__":
1142 test()
1143
1144 # simple client transaction would look like
1145 """
1146 remote_uri = 'http://localhost:9999'
1147 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1148 send_str = "Hello_there"
1149 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1150 """