blob: 8ed800eb42b274e2ff0c862e87cfeb75eb473b50 [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
Aseda Aboagye1d8477b2017-05-10 17:24:31 -070012import re
Simran Basia9f41032012-05-11 14:21:58 -070013import shutil
Todd Broche505b8d2011-03-21 18:19:54 -070014import SimpleXMLRPCServer
Simran Basia9f41032012-05-11 14:21:58 -070015import subprocess
16import tempfile
Todd Broch7a91c252012-02-03 12:37:45 -080017import time
Simran Basia9f41032012-05-11 14:21:58 -070018import urllib
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070019import usb
Todd Broche505b8d2011-03-21 18:19:54 -070020
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080021import drv as servo_drv
Aaron.Chuang88eff332014-07-31 08:32:00 +080022import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070023import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070024import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070025import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080026import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070027import ftdigpio
28import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070029import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070030import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080031import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080032import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070033import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070034import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080035import stm32gpio
36import stm32i2c
37import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070038
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080039HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080040
Todd Broche505b8d2011-03-21 18:19:54 -070041MAX_I2C_CLOCK_HZ = 100000
42
Kevin Cheng5595b342016-09-29 15:51:01 -070043# It takes about 16-17 seconds for the entire probe usb device method,
44# let's wait double plus some buffer.
45_MAX_USB_LOCK_WAIT = 40
Todd Brochdbb09982011-10-02 07:14:26 -070046
Todd Broche505b8d2011-03-21 18:19:54 -070047class ServodError(Exception):
48 """Exception class for servod."""
49
50class Servod(object):
51 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070052 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070053 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070054 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070055 _USB_J3 = "usb_mux_sel1"
56 _USB_J3_TO_SERVO = "servo_sees_usbkey"
57 _USB_J3_TO_DUT = "dut_sees_usbkey"
58 _USB_J3_PWR = "prtctl4_pwren"
59 _USB_J3_PWR_ON = "on"
60 _USB_J3_PWR_OFF = "off"
Kevin Chengc49494e2016-07-25 12:13:38 -070061 _USB_LOCK_FILE = "/var/lib/servod/lock_file"
Simran Basia9f41032012-05-11 14:21:58 -070062
Kevin Cheng4b4f0022016-09-09 02:37:07 -070063 # This is the key to get the main serial used in the _serialnames dict.
64 MAIN_SERIAL = "main"
Wai-Hong Tam4b235922016-10-07 12:26:22 -070065 MICRO_SERVO_SERIAL = "micro_servo"
Wai-Hong Tam85b4ced2016-10-07 14:15:38 -070066 CCD_SERIAL = "ccd"
Kevin Cheng4b4f0022016-09-09 02:37:07 -070067
Kevin Chengdc3befd2016-07-15 12:34:00 -070068 def init_servo_interfaces(self, vendor, product, serialname,
69 interfaces):
70 """Init the servo interfaces with the given interfaces.
71
72 We don't use the self._{vendor,product,serialname} attributes because we
73 want to allow other callers to initialize other interfaces that may not
74 be associated with the initialized attributes (e.g. a servo v4 servod object
75 that wants to also initialize a servo micro interface).
76
77 Args:
78 vendor: USB vendor id of FTDI device.
79 product: USB product id of FTDI device.
80 serialname: String of device serialname/number as defined in FTDI
81 eeprom.
82 interfaces: List of strings of interface types the server will
83 instantiate.
84
85 Raises:
86 ServodError if unable to locate init method for particular interface.
87 """
Mary Ruthven13389642017-02-14 12:15:34 -080088 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070089 device = (vendor, product, serialname)
Mary Ruthven13389642017-02-14 12:15:34 -080090 if device not in self._devices:
91 self._devices.append(device)
92
Kevin Chengdc3befd2016-07-15 12:34:00 -070093 # Extend the interface list if we need to.
94 interfaces_len = len(interfaces)
95 interface_list_len = len(self._interface_list)
96 if interfaces_len > interface_list_len:
97 self._interface_list += [None] * (interfaces_len - interface_list_len)
98
99 shifted = 0
100 for i, interface in enumerate(interfaces):
101 is_ftdi_interface = False
102 if type(interface) is dict:
103 name = interface['name']
104 # Store interface index for those that care about it.
105 interface['index'] = i
106 elif type(interface) is str and interface != 'dummy':
107 name = interface
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700108 # It's a FTDI related interface. #0 is reserved for no use.
109 interface = ((i - 1) % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
Kevin Chengdc3befd2016-07-15 12:34:00 -0700110 is_ftdi_interface = True
111 elif type(interface) is str and interface == 'dummy':
112 # 'dummy' reserves the interface for future use. Typically the
113 # interface will be managed by external third-party tools like
114 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
115 # it serves as a placeholder for servo micro interfaces.
116 continue
117 else:
118 raise ServodError("Illegal interface type %s" % type(interface))
119
120 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700121 product_increment = 0
122 if is_ftdi_interface:
123 product_increment = (i - 1) / ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE
124 if product_increment:
125 self._logger.info("Use the next FTDI part @ pid = 0x%04x",
126 product + product_increment)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700127
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700128 self._logger.info("Initializing interface %d to %s", i, name)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700129 try:
130 func = getattr(self, '_init_%s' % name)
131 except AttributeError:
132 raise ServodError("Unable to locate init for interface %s" % name)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700133 result = func(vendor, product + product_increment, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700134
135 if isinstance(result, tuple):
136 result_len = len(result)
Wai-Hong Tam9441b182016-11-01 11:05:09 -0700137 # More than one interface return. Extend the list.
138 self._interface_list += [None] * (result_len - 1)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700139 for result_index, r in enumerate(result):
Wai-Hong Tam9441b182016-11-01 11:05:09 -0700140 self._interface_list[i + shifted + result_index] = r
141 # Shift the remaining interfaces.
142 shifted += result_len - 1
Kevin Chengdc3befd2016-07-15 12:34:00 -0700143 else:
144 self._interface_list[i + shifted] = result
145
J. Richard Barnettee2820552013-03-14 16:13:46 -0700146 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800147 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700148 """Servod constructor.
149
150 Args:
151 config: instance of SystemConfig containing all controls for
152 particular Servod invocation
153 vendor: usb vendor id of FTDI device
154 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700155 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700156 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700157 version: String. Servo board version. Examples: servo_v1, servo_v2,
158 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800159 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700160 sending keyboard commands to DUTs that do not have built in
161 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
162 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -0700163
164 Raises:
165 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700166 """
167 self._logger = logging.getLogger("Servod")
168 self._logger.debug("")
169 self._vendor = vendor
170 self._product = product
Mary Ruthven13389642017-02-14 12:15:34 -0800171 self._devices = []
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700172 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700173 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700174 # Hold the last image path so we can reduce downloads to the usb device.
175 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700176 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
177 # interfaces are mapped to
178 self._interface_list = []
179 # Dict of Dict to map control name, function name to to tuple (params, drv)
180 # Ex) _drv_dict[name]['get'] = (params, drv)
181 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700182 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -0700183 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800184 self._usbkm232 = usbkm232
Kevin Chengc49494e2016-07-25 12:13:38 -0700185 # Seed the random generator with the serial to differentiate from other
186 # servod processes.
187 random.seed(serialname if serialname else time.time())
Todd Brochdbb09982011-10-02 07:14:26 -0700188 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700189 try:
190 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
191 except KeyError:
192 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -0700193
Kevin Chengdc3befd2016-07-15 12:34:00 -0700194 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700195 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800196
Mary Ruthven13389642017-02-14 12:15:34 -0800197 def reinitialize(self):
198 """Reinitialize all interfaces that support reinitialization"""
199
200 # If all of the devices that were originally connected are not connected
201 # now, wait up to max_tries * sleep_time for the devices to reconnect
202 max_tries = 10
203 sleep_time = 0.5
204 for i in range(max_tries):
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -0700205 for vid, pid, serialname in self._devices:
206 for current in usb.core.find(idVendor=vid, idProduct=pid,
207 find_all=True):
208 current_serial = usb.util.get_string(current, 256,
209 current.iSerialNumber)
210 if not serialname or serialname == current_serial:
211 # This device still available
212 break
213 else:
214 self._logger.warn('Servo USB device not found: %x:%x serial:%s',
215 vid, pid, serialname)
216 break
217 else:
218 # All the devices found. Reinitialize the interfaces...
Mary Ruthven13389642017-02-14 12:15:34 -0800219 break
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -0700220 time.sleep(sleep_time)
221 else:
222 raise ServodError('Servo USB device not found during reinitialize')
Mary Ruthven13389642017-02-14 12:15:34 -0800223
224 for i, interface in enumerate(self._interface_list):
225 if hasattr(interface, "reinitialize"):
226 interface.reinitialize()
227 else:
228 self._logger.debug("interface %d has no reset functionality", i)
229
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800230 def _init_keyboard_handler(self, servo, board=''):
231 """Initialize the correct keyboard handler for board.
232
Kevin Chengdc3befd2016-07-15 12:34:00 -0700233 Args:
234 servo: servo object.
235 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800236
Kevin Chengdc3befd2016-07-15 12:34:00 -0700237 Returns:
238 keyboard handler object.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800239 """
240 if board == 'parrot':
241 return keyboard_handlers.ParrotHandler(servo)
242 elif board == 'stout':
243 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800244 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800245 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
philipchenfc9eea12016-09-21 17:36:54 -0700246 'sumo', 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
247 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800248 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800249 logging.info("No device path specified for usbkm232 handler. Use "
250 "the servo atmega chip to handle.")
251 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800252 if self._usbkm232 == 'atmega':
253 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800254 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800255 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800256 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800257 self._usbkm232 = self.get('atmega_pty')
Kevin Cheng810fc782016-11-01 12:36:46 -0700258 # We don't need to set the atmega uart settings if we're a servo v4.
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700259 if 'servo_v4' not in self._version:
Kevin Cheng810fc782016-11-01 12:36:46 -0700260 self.set('atmega_baudrate', '9600')
261 self.set('atmega_bits', 'eight')
262 self.set('atmega_parity', 'none')
263 self.set('atmega_sbits', 'one')
264 self.set('usb_mux_sel4', 'on')
265 self.set('usb_mux_oe4', 'on')
266 # Allow atmega bootup time.
267 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800268 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800269 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
270 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800271 # The following boards don't use Chrome EC.
272 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
273 return keyboard_handlers.MatrixKeyboardHandler(servo)
274 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800275
Todd Broch3ec8df02012-11-20 10:53:03 -0800276 def __del__(self):
277 """Servod deconstructor."""
278 for interface in self._interface_list:
279 del(interface)
280
Kevin Chengdc3befd2016-07-15 12:34:00 -0700281 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700282 """Dummy interface for ftdi devices.
283
284 This is a dummy function specifically for ftdi devices to not initialize
285 anything but to help pad the interface list.
286
287 Returns:
288 None.
289 """
290 return None
291
Kevin Chengdc3befd2016-07-15 12:34:00 -0700292 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700293 """Initialize gpio driver interface and open for use.
294
295 Args:
296 interface: interface number of FTDI device to use.
297
298 Returns:
299 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700300
301 Raises:
302 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700303 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700304 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700305 try:
306 fobj.open()
307 except ftdigpio.FgpioError as e:
308 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
309
Todd Broche505b8d2011-03-21 18:19:54 -0700310 return fobj
311
Kevin Chengdc3befd2016-07-15 12:34:00 -0700312 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800313 """Initialize stm32 uart interface and open for use
314
315 Note, the uart runs in a separate thread. Users wishing to
316 interact with it will query control for the pty's pathname and connect
317 with their favorite console program. For example:
318 cu -l /dev/pts/22
319
320 Args:
321 interface: dict of interface parameters.
322
323 Returns:
324 Instance object of interface
325
326 Raises:
327 ServodError: Raised on init failure.
328 """
329 self._logger.info("Suart: interface: %s" % interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700330 sobj = stm32uart.Suart(vendor, product, interface['interface'],
331 serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800332
333 try:
334 sobj.run()
335 except stm32uart.SuartError as e:
336 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
337
338 self._logger.info("%s" % sobj.get_pty())
339 return sobj
340
Kevin Chengdc3befd2016-07-15 12:34:00 -0700341 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800342 """Initialize stm32 gpio interface.
343 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700344 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800345
346 Returns:
347 Instance object of interface
348
349 Raises:
350 SgpioError: Raised on init failure.
351 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700352 interface_number = interface
353 # Interface could be a dict.
354 if type(interface) is dict:
355 interface_number = interface['interface']
356 self._logger.info("Sgpio: interface: %s" % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700357 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800358
Kevin Chengdc3befd2016-07-15 12:34:00 -0700359 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800360 """Initialize stm32 USB to I2C bridge interface and open for use
361
362 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700363 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800364
365 Returns:
366 Instance object of interface.
367
368 Raises:
369 Si2cError: Raised on init failure.
370 """
371 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800372 port = interface.get('port', 0)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700373 return stm32i2c.Si2cBus(vendor, product, interface['interface'],
374 port=port, serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800375
Kevin Chengdc3befd2016-07-15 12:34:00 -0700376 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800377 """Initalize beaglebone ADC interface."""
378 return bbadc.BBadc()
379
Kevin Chengdc3befd2016-07-15 12:34:00 -0700380 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700381 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700382 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700383
Kevin Chengdc3befd2016-07-15 12:34:00 -0700384 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700385 """Initialize i2c interface and open for use.
386
387 Args:
388 interface: interface number of FTDI device to use
389
390 Returns:
391 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700392
393 Raises:
394 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700395 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700396 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700397 try:
398 fobj.open()
399 except ftdii2c.Fi2cError as e:
400 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
401
Todd Broche505b8d2011-03-21 18:19:54 -0700402 # Set the frequency of operation of the i2c bus.
403 # TODO(tbroch) make configureable
404 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700405
Todd Broche505b8d2011-03-21 18:19:54 -0700406 return fobj
407
Simran Basie750a342013-03-12 13:45:26 -0700408 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
409 def _init_bb_i2c(self, interface):
410 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700411 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700412
Kevin Chengdc3befd2016-07-15 12:34:00 -0700413 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800414 """Initalize Linux i2c-dev interface."""
415 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
416
Kevin Chengdc3befd2016-07-15 12:34:00 -0700417 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700418 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700419
420 Note, the uart runs in a separate thread (pthreads). Users wishing to
421 interact with it will query control for the pty's pathname and connect
422 with there favorite console program. For example:
423 cu -l /dev/pts/22
424
425 Args:
426 interface: interface number of FTDI device to use
427
428 Returns:
429 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700430
431 Raises:
432 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700433 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700434 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700435 try:
436 fobj.run()
437 except ftdiuart.FuartError as e:
438 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
439
Todd Broch47c43f42011-05-26 15:11:31 -0700440 self._logger.info("%s" % fobj.get_pty())
441 return fobj
442
Simran Basie750a342013-03-12 13:45:26 -0700443 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700444 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700445 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700446 logging.debug('UART INTERFACE: %s', interface)
447 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700448
Kevin Chengdc3befd2016-07-15 12:34:00 -0700449 def _init_ftdi_gpiouart(self, vendor, product, serialname,
450 interface):
Todd Broch888da782011-10-07 14:29:09 -0700451 """Initialize special gpio + uart interface and open for use
452
453 Note, the uart runs in a separate thread (pthreads). Users wishing to
454 interact with it will query control for the pty's pathname and connect
455 with there favorite console program. For example:
456 cu -l /dev/pts/22
457
458 Args:
459 interface: interface number of FTDI device to use
460
461 Returns:
462 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700463
464 Raises:
465 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700466 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700467 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700468 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700469 try:
470 fuart.run()
471 except ftdiuart.FuartError as e:
472 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
473
Todd Broch888da782011-10-07 14:29:09 -0700474 self._logger.info("uart pty: %s" % fuart.get_pty())
475 return fgpio, fuart
476
Kevin Chengdc3befd2016-07-15 12:34:00 -0700477 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800478 """Initialize EC-3PO console interpreter interface.
479
480 Args:
481 interface: A dictionary representing the interface.
482
483 Returns:
484 An EC3PO object representing the EC-3PO interface or None if there's no
485 interface for the USB PD UART.
486 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700487 raw_uart_name = interface['raw_pty']
488 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800489 raw_ec_uart = self.get(raw_uart_name)
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700490 return ec3po_interface.EC3PO(raw_ec_uart)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800491 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700492 # The overlay doesn't have the raw PTY defined, therefore we can skip
493 # initializing this interface since no control relies on it.
494 self._logger.debug(
495 'Skip initializing EC3PO for %s, no control specified.',
496 raw_uart_name)
497 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800498
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800499 def _camel_case(self, string):
500 output = ''
501 for s in string.split('_'):
502 if output:
503 output += s.capitalize()
504 else:
505 output = s
506 return output
507
Todd Broche505b8d2011-03-21 18:19:54 -0700508 def _get_param_drv(self, control_name, is_get=True):
509 """Get access to driver for a given control.
510
511 Note, some controls have different parameter dictionaries for 'getting' the
512 control's value versus 'setting' it. Boolean is_get distinguishes which is
513 being requested.
514
515 Args:
516 control_name: string name of control
517 is_get: boolean to determine
518
519 Returns:
520 tuple (param, drv) where:
521 param: param dictionary for control
522 drv: instance object of driver for particular control
523
524 Raises:
525 ServodError: Error occurred while examining params dict
526 """
527 self._logger.debug("")
528 # if already setup just return tuple from driver dict
529 if control_name in self._drv_dict:
530 if is_get and ('get' in self._drv_dict[control_name]):
531 return self._drv_dict[control_name]['get']
532 if not is_get and ('set' in self._drv_dict[control_name]):
533 return self._drv_dict[control_name]['set']
534
535 params = self._syscfg.lookup_control_params(control_name, is_get)
536 if 'drv' not in params:
537 self._logger.error("Unable to determine driver for %s" % control_name)
538 raise ServodError("'drv' key not found in params dict")
539 if 'interface' not in params:
540 self._logger.error("Unable to determine interface for %s" %
541 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700542 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700543
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700544 # Find the candidate servos. Using servo_v4 with a servo_micro connected as
545 # an example, the following shows the priority for selecting the interface.
546 #
547 # 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
548 # 2. servo_micro_interface
549 # 3. servo_v4_interface
550 # 4. Fallback to the default, interface.
551 candidates = [ self._version ]
552 candidates.extend(reversed(self._version.split('_with_')))
553
554 interface_id = 'unknown'
555 for c in candidates:
556 interface_name = '%s_interface' % c
557 if interface_name in params:
558 interface_id = params[interface_name]
559 self._logger.debug('Using %s parameter.' % interface_name)
560 break
561
562 # Use the default interface value if we couldn't find a more specific
563 # interface.
564 if interface_id == 'unknown':
565 interface_id = params['interface']
566 self._logger.debug('Using default interface parameter.')
567
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800568 if interface_id == 'servo':
569 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700570 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700571 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800572 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700573
Todd Broche505b8d2011-03-21 18:19:54 -0700574 drv_name = params['drv']
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800575 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800576 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700577 drv = drv_class(interface, params)
578 if control_name not in self._drv_dict:
579 self._drv_dict[control_name] = {}
580 if is_get:
581 self._drv_dict[control_name]['get'] = (params, drv)
582 else:
583 self._drv_dict[control_name]['set'] = (params, drv)
584 return (params, drv)
585
586 def doc_all(self):
587 """Return all documenation for controls.
588
589 Returns:
590 string of <doc> text in config file (xml) and the params dictionary for
591 all controls.
592
593 For example:
594 warm_reset :: Reset the device warmly
595 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
596 """
597 return self._syscfg.display_config()
598
599 def doc(self, name):
600 """Retreive doc string in system config file for given control name.
601
602 Args:
603 name: name string of control to get doc string
604
605 Returns:
606 doc string of name
607
608 Raises:
609 NameError: if fails to locate control
610 """
611 self._logger.debug("name(%s)" % (name))
612 if self._syscfg.is_control(name):
613 return self._syscfg.get_control_docstring(name)
614 else:
615 raise NameError("No control %s" %name)
616
Fang Deng90377712013-06-03 15:51:48 -0700617 def _switch_usbkey(self, mux_direction):
618 """Connect USB flash stick to either servo or DUT.
619
620 This function switches 'usb_mux_sel1' to provide electrical
621 connection between the USB port J3 and either servo or DUT side.
622
623 Switching the usb mux is accompanied by powercycling
624 of the USB stick, because it sometimes gets wedged if the mux
625 is switched while the stick power is on.
626
627 Args:
628 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
629 """
630 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
631 time.sleep(self._USB_POWEROFF_DELAY)
632 self.set(self._USB_J3, mux_direction)
633 time.sleep(self._USB_POWEROFF_DELAY)
634 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
635 if mux_direction == self._USB_J3_TO_SERVO:
636 time.sleep(self._USB_DETECTION_DELAY)
637
Simran Basia9f41032012-05-11 14:21:58 -0700638 def _get_usb_port_set(self):
639 """Gets a set of USB disks currently connected to the system
640
641 Returns:
642 A set of USB disk paths.
643 """
644 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
645 return set(["/dev/" + dev for dev in usb_set])
646
Kevin Cheng5595b342016-09-29 15:51:01 -0700647 @contextlib.contextmanager
648 def _block_other_servod(self, timeout=None):
Kevin Chengc49494e2016-07-25 12:13:38 -0700649 """Block other servod processes by locking a file.
650
651 To enable multiple servods processes to safely probe_host_usb_dev, we use
652 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700653 for a usb device. This will be a context manager that will return
654 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700655
656 If the lock file exists, we open it and try to lock it.
657 - If another servod processes has locked it already, we'll sleep a random
658 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700659 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700660
Kevin Cheng5595b342016-09-29 15:51:01 -0700661 - If we're able to lock the file, we'll yield that the block was successful
662 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700663
664 This blocking behavior is only enabled if the lock file exists, if it
665 doesn't, then we pretend the block was successful.
666
Kevin Cheng5595b342016-09-29 15:51:01 -0700667 Args:
668 timeout: Max waiting time for the block to succeed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700669 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700670 if not os.path.exists(self._USB_LOCK_FILE):
671 # No lock file so we'll pretend the block was a success.
672 yield True
673 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700674 start_time = datetime.datetime.now()
675 while True:
Kevin Cheng5595b342016-09-29 15:51:01 -0700676 with open(self._USB_LOCK_FILE) as lock_file:
677 try:
678 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
679 yield True
680 fcntl.flock(lock_file, fcntl.LOCK_UN)
681 break
682 except IOError:
683 current_time = datetime.datetime.now()
684 current_wait_time = (current_time - start_time).total_seconds()
685 if timeout and current_wait_time > timeout:
686 yield False
687 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700688 # Sleep random amount.
689 sleep_time = time.sleep(random.random())
Kevin Chengc49494e2016-07-25 12:13:38 -0700690
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700691 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700692 """Toggle the usb power safely.
693
694 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700695
696 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700697 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700698 timeout: Timeout to wait for blocking other servod processes, default is
699 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700700
Kevin Cheng5595b342016-09-29 15:51:01 -0700701 Returns:
702 An empty string to appease the xmlrpc gods.
703 """
704 with self._block_other_servod(timeout=timeout):
705 if power_state != self.get(self._USB_J3_PWR):
706 self.set(self._USB_J3_PWR, power_state)
707 return ''
708
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700709 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700710 """Toggle the usb direction safely.
711
712 We'll make sure we're the only servod process toggling the usbkey direction.
713
714 Args:
715 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700716 timeout: Timeout to wait for blocking other servod processes, default is
717 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700718
719 Returns:
720 An empty string to appease the xmlrpc gods.
721 """
722 with self._block_other_servod(timeout=timeout):
723 self._switch_usbkey(mux_direction)
724 return ''
725
726 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700727 """Probe the USB disk device plugged in the servo from the host side.
728
729 Method can fail by:
730 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700731 another servo unless _USB_LOCK_FILE exists on the servo host. If that
732 file exists, then it is safe to probe for usb devices among multiple
733 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700734 2) Finding multiple /dev/sdX and returning None.
735
Kevin Cheng5595b342016-09-29 15:51:01 -0700736 Args:
737 timeout: Timeout to wait for blocking other servod processes.
738
Simran Basia9f41032012-05-11 14:21:58 -0700739 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700740 USB disk path if one and only one USB disk path is found, otherwise an
741 empty string.
Simran Basia9f41032012-05-11 14:21:58 -0700742 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700743 with self._block_other_servod(timeout=timeout) as block_success:
744 if not block_success:
745 return ''
Kevin Chengc49494e2016-07-25 12:13:38 -0700746
Kevin Cheng5595b342016-09-29 15:51:01 -0700747 original_value = self.get(self._USB_J3)
748 original_usb_power = self.get(self._USB_J3_PWR)
749 # Make the host unable to see the USB disk.
750 if (original_usb_power == self._USB_J3_PWR_ON and
751 original_value != self._USB_J3_TO_DUT):
752 self._switch_usbkey(self._USB_J3_TO_DUT)
753 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700754
Kevin Cheng5595b342016-09-29 15:51:01 -0700755 # Make the host able to see the USB disk.
756 self._switch_usbkey(self._USB_J3_TO_SERVO)
757 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700758
Kevin Cheng5595b342016-09-29 15:51:01 -0700759 # Back to its original value.
760 if original_value != self._USB_J3_TO_SERVO:
761 self._switch_usbkey(original_value)
762 if original_usb_power != self._USB_J3_PWR_ON:
763 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
764 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700765
Kevin Cheng5595b342016-09-29 15:51:01 -0700766 # Subtract the two sets to find the usb device.
767 diff_set = has_usb_set - no_usb_set
768 if len(diff_set) == 1:
769 return diff_set.pop()
770 else:
771 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700772
Kevin Cheng85831332016-10-13 13:14:44 -0700773 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700774 """Download image and save to the USB device found by probe_host_usb_dev.
775 If the image_path is a URL, it will download this url to the USB path;
776 otherwise it will simply copy the image_path's contents to the USB path.
777
778 Args:
779 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700780 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700781
782 Returns:
783 True|False: True if process completed successfully, False if error
784 occurred.
785 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
786 comment at the end of set().
787 """
788 self._logger.debug("image_path(%s)" % image_path)
789 self._logger.debug("Detecting USB stick device...")
Kevin Cheng85831332016-10-13 13:14:44 -0700790 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700791 if not usb_dev:
792 self._logger.error("No usb device connected to servo")
793 return False
794
Kevin Cheng9071ed92016-06-21 14:37:54 -0700795 # Let's check if we downloaded this last time and if so assume the image is
796 # still on the usb device and return True.
797 if self._image_path == image_path:
798 self._logger.debug("Image already on USB device, skipping transfer")
799 return True
800
Simran Basia9f41032012-05-11 14:21:58 -0700801 try:
802 if image_path.startswith(self._HTTP_PREFIX):
803 self._logger.debug("Image path is a URL, downloading image")
804 urllib.urlretrieve(image_path, usb_dev)
805 else:
806 shutil.copyfile(image_path, usb_dev)
807 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700808 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700809 e.strerror, e.errno)
810 return False
811 except urllib.ContentTooShortError:
812 self._logger.error("Failed to download URL: %s to USB device: %s",
813 image_path, usb_dev)
814 return False
815 except BaseException as e:
816 self._logger.error("Unexpected exception downloading %s to %s: %s",
817 image_path, usb_dev, str(e))
818 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800819 finally:
820 # We just plastered the partition table for a block device.
821 # Pass or fail, we mustn't go without telling the kernel about
822 # the change, or it will punish us with sporadic, hard-to-debug
823 # failures.
824 subprocess.call(["sync"])
825 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700826 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700827 return True
828
829 def make_image_noninteractive(self):
830 """Makes the recovery image noninteractive.
831
832 A noninteractive image will reboot automatically after installation
833 instead of waiting for the USB device to be removed to initiate a system
834 reboot.
835
836 Mounts partition 1 of the image stored on usb_dev and creates a file
837 called "non_interactive" so that the image will become noninteractive.
838
839 Returns:
840 True|False: True if process completed successfully, False if error
841 occurred.
842 """
843 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700844 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700845 if not usb_dev:
846 self._logger.error("No usb device connected to servo")
847 return False
848 # Create TempDirectory
849 tmpdir = tempfile.mkdtemp()
850 if tmpdir:
851 # Mount drive to tmpdir.
852 partition_1 = "%s1" % usb_dev
853 rc = subprocess.call(["mount", partition_1, tmpdir])
854 if rc == 0:
855 # Create file 'non_interactive'
856 non_interactive_file = os.path.join(tmpdir, "non_interactive")
857 try:
858 open(non_interactive_file, "w").close()
859 except IOError as e:
860 self._logger.error("Failed to create file %s : %s ( %d )",
861 non_interactive_file, e.strerror, e.errno)
862 result = False
863 except BaseException as e:
864 self._logger.error("Unexpected Exception creating file %s : %s",
865 non_interactive_file, str(e))
866 result = False
867 # Unmount drive regardless if file creation worked or not.
868 rc = subprocess.call(["umount", partition_1])
869 if rc != 0:
870 self._logger.error("Failed to unmount USB Device")
871 result = False
872 else:
873 self._logger.error("Failed to mount USB Device")
874 result = False
875
876 # Delete tmpdir. May throw exception if 'umount' failed.
877 try:
878 os.rmdir(tmpdir)
879 except OSError as e:
880 self._logger.error("Failed to remove temp directory %s : %s",
881 tmpdir, str(e))
882 return False
883 except BaseException as e:
884 self._logger.error("Unexpected Exception removing tempdir %s : %s",
885 tmpdir, str(e))
886 return False
887 else:
888 self._logger.error("Failed to create temp directory.")
889 return False
890 return result
891
Todd Broch352b4b22013-03-22 09:48:40 -0700892 def set_get_all(self, cmds):
893 """Set &| get one or more control values.
894
895 Args:
896 cmds: list of control[:value] to get or set.
897
898 Returns:
899 rv: list of responses from calling get or set methods.
900 """
901 rv = []
902 for cmd in cmds:
903 if ':' in cmd:
904 (control, value) = cmd.split(':')
905 rv.append(self.set(control, value))
906 else:
907 rv.append(self.get(cmd))
908 return rv
909
Todd Broche505b8d2011-03-21 18:19:54 -0700910 def get(self, name):
911 """Get control value.
912
913 Args:
914 name: name string of control
915
916 Returns:
917 Response from calling drv get method. Value is reformatted based on
918 control's dictionary parameters
919
920 Raises:
921 HwDriverError: Error occurred while using drv
922 """
923 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700924 if name == 'serialname':
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700925 if self._serialnames[self.MAIN_SERIAL]:
926 return self._serialnames[self.MAIN_SERIAL]
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700927 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700928 (param, drv) = self._get_param_drv(name)
929 try:
930 val = drv.get()
931 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800932 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700933 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700934 except AttributeError, error:
935 self._logger.error("Getting %s: %s" % (name, error))
936 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800937 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700938 self._logger.error("Getting %s" % (name))
939 raise
Todd Brochd6061672012-05-11 15:52:47 -0700940
Todd Broche505b8d2011-03-21 18:19:54 -0700941 def get_all(self, verbose):
942 """Get all controls values.
943
944 Args:
945 verbose: Boolean on whether to return doc info as well
946
947 Returns:
948 string creating from trying to get all values of all controls. In case of
949 error attempting access to control, response is 'ERR'.
950 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800951 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700952 for name in self._syscfg.syscfg_dict['control']:
953 self._logger.debug("name = %s" %name)
954 try:
955 value = self.get(name)
956 except Exception:
957 value = "ERR"
958 pass
959 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800960 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700961 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800962 rsp.append("%s:%s" % (name, value))
963 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700964
965 def set(self, name, wr_val_str):
966 """Set control.
967
968 Args:
969 name: name string of control
970 wr_val_str: value string to write. Can be integer, float or a
971 alpha-numerical that is mapped to a integer or float.
972
973 Raises:
974 HwDriverError: Error occurred while using driver
975 """
976 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
977 (params, drv) = self._get_param_drv(name, False)
978 wr_val = self._syscfg.resolve_val(params, wr_val_str)
979 try:
980 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800981 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700982 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
983 raise
984 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
985 # & client I still have to return something to appease the
986 # marshall/unmarshall
987 return True
988
Todd Brochd6061672012-05-11 15:52:47 -0700989 def hwinit(self, verbose=False):
990 """Initialize all controls.
991
992 These values are part of the system config XML files of the form
993 init=<value>. This command should be used by clients wishing to return the
994 servo and DUT its connected to a known good/safe state.
995
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800996 Note that initialization errors are ignored (as in some cases they could
997 be caused by DUT firmware deficiencies). This might need to be fine tuned
998 later.
999
Todd Brochd6061672012-05-11 15:52:47 -07001000 Args:
1001 verbose: boolean, if True prints info about control initialized.
1002 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001003
1004 Returns:
1005 This function is called across RPC and as such is expected to return
1006 something unless transferring 'none' across is allowed. Hence adding a
1007 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -07001008 """
Todd Brochd9acf0a2012-12-05 13:43:06 -08001009 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -08001010 try:
John Carey6fe2bbf2015-08-31 16:13:03 -07001011 # Workaround for bug chrome-os-partner:42349. Without this check, the
1012 # gpio will briefly pulse low if we set it from high to high.
1013 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -07001014 self.set(control_name, value)
1015 if verbose:
1016 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -08001017 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -08001018 self._logger.error("Problem initializing %s -> %s :: %s",
1019 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -08001020
1021 # Init keyboard after all the intefaces are up.
1022 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001023 return True
Todd Broch3ec8df02012-11-20 10:53:03 -08001024
Todd Broche505b8d2011-03-21 18:19:54 -07001025 def echo(self, echo):
1026 """Dummy echo function for testing/examples.
1027
1028 Args:
1029 echo: string to echo back to client
1030 """
1031 self._logger.debug("echo(%s)" % (echo))
1032 return "ECH0ING: %s" % (echo)
1033
J. Richard Barnettee2820552013-03-14 16:13:46 -07001034 def get_board(self):
1035 """Return the board specified at startup, if any."""
1036 return self._board
1037
Simran Basia23c1392013-08-06 14:59:10 -07001038 def get_version(self):
1039 """Get servo board version."""
1040 return self._version
1041
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001042 def power_long_press(self):
1043 """Simulate a long power button press."""
1044 # After a long power press, the EC may ignore the next power
1045 # button press (at least on Alex). To guarantee that this
1046 # won't happen, we need to allow the EC one second to
1047 # collect itself.
1048 self._keyboard.power_long_press()
1049 return True
1050
1051 def power_normal_press(self):
1052 """Simulate a normal power button press."""
1053 self._keyboard.power_normal_press()
1054 return True
1055
1056 def power_short_press(self):
1057 """Simulate a short power button press."""
1058 self._keyboard.power_short_press()
1059 return True
1060
1061 def power_key(self, secs=''):
1062 """Simulate a power button press.
1063
1064 Args:
1065 secs: Time in seconds to simulate the keypress.
1066 """
1067 self._keyboard.power_key(secs)
1068 return True
1069
1070 def ctrl_d(self, press_secs=''):
1071 """Simulate Ctrl-d simultaneous button presses."""
1072 self._keyboard.ctrl_d(press_secs)
1073 return True
1074
Victor Dodone539cea2016-03-29 18:50:17 -07001075 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001076 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001077 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001078 return True
1079
1080 def ctrl_enter(self, press_secs=''):
1081 """Simulate Ctrl-enter simultaneous button presses."""
1082 self._keyboard.ctrl_enter(press_secs)
1083 return True
1084
1085 def d_key(self, press_secs=''):
1086 """Simulate Enter key button press."""
1087 self._keyboard.d_key(press_secs)
1088 return True
1089
1090 def ctrl_key(self, press_secs=''):
1091 """Simulate Enter key button press."""
1092 self._keyboard.ctrl_key(press_secs)
1093 return True
1094
1095 def enter_key(self, press_secs=''):
1096 """Simulate Enter key button press."""
1097 self._keyboard.enter_key(press_secs)
1098 return True
1099
1100 def refresh_key(self, press_secs=''):
1101 """Simulate Refresh key (F3) button press."""
1102 self._keyboard.refresh_key(press_secs)
1103 return True
1104
1105 def ctrl_refresh_key(self, press_secs=''):
1106 """Simulate Ctrl and Refresh (F3) simultaneous press.
1107
1108 This key combination is an alternative of Space key.
1109 """
1110 self._keyboard.ctrl_refresh_key(press_secs)
1111 return True
1112
1113 def imaginary_key(self, press_secs=''):
1114 """Simulate imaginary key button press.
1115
1116 Maps to a key that doesn't physically exist.
1117 """
1118 self._keyboard.imaginary_key(press_secs)
1119 return True
1120
Todd Brochdbb09982011-10-02 07:14:26 -07001121
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001122 def sysrq_x(self, press_secs=''):
1123 """Simulate Alt VolumeUp X simultaneous press.
1124
1125 This key combination is the kernel system request (sysrq) x.
1126 """
1127 self._keyboard.sysrq_x(press_secs)
1128 return True
1129
1130
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001131 def get_servo_serials(self):
1132 """Return all the serials associated with this process."""
1133 return self._serialnames
1134
1135
Todd Broche505b8d2011-03-21 18:19:54 -07001136def test():
1137 """Integration testing.
1138
1139 TODO(tbroch) Enhance integration test and add unittest (see mox)
1140 """
1141 logging.basicConfig(level=logging.DEBUG,
1142 format="%(asctime)s - %(name)s - " +
1143 "%(levelname)s - %(message)s")
1144 # configure server & listen
1145 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -07001146 # 5 == number of interfaces on a FT4232H device
1147 for i in xrange(1, 5):
1148 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -07001149 # its an i2c interface ... see __init__ for details and TODO to make
1150 # this configureable
1151 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1152 else:
1153 # its a gpio interface
1154 servod_obj._interface_list[i].wr_rd(0)
1155
1156 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1157 allow_none=True)
1158 server.register_introspection_functions()
1159 server.register_multicall_functions()
1160 server.register_instance(servod_obj)
1161 logging.info("Listening on localhost port 9999")
1162 server.serve_forever()
1163
1164if __name__ == "__main__":
1165 test()
1166
1167 # simple client transaction would look like
1168 """
1169 remote_uri = 'http://localhost:9999'
1170 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1171 send_str = "Hello_there"
1172 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1173 """