blob: 90ef7f0a68fe230a3f246d81e8defd1a68e42ea4 [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"
Aseda Aboagyea9fee382017-08-01 15:11:03 -070065 SERVO_MICRO_SERIAL = "servo_micro"
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
Kevin Chengdc3befd2016-07-15 12:34:00 -070099 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 Tamd8a94d62017-04-28 10:11:51 -0700136 self._interface_list[i:(i + result_len)] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700137 else:
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700138 self._interface_list[i] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700139
J. Richard Barnettee2820552013-03-14 16:13:46 -0700140 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800141 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700142 """Servod constructor.
143
144 Args:
145 config: instance of SystemConfig containing all controls for
146 particular Servod invocation
147 vendor: usb vendor id of FTDI device
148 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700149 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700150 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700151 version: String. Servo board version. Examples: servo_v1, servo_v2,
152 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800153 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700154 sending keyboard commands to DUTs that do not have built in
155 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
156 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -0700157
158 Raises:
159 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700160 """
161 self._logger = logging.getLogger("Servod")
162 self._logger.debug("")
163 self._vendor = vendor
164 self._product = product
Mary Ruthven13389642017-02-14 12:15:34 -0800165 self._devices = []
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700166 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700167 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700168 # Hold the last image path so we can reduce downloads to the usb device.
169 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700170 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
171 # interfaces are mapped to
172 self._interface_list = []
173 # Dict of Dict to map control name, function name to to tuple (params, drv)
174 # Ex) _drv_dict[name]['get'] = (params, drv)
175 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700176 self._board = board
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700177 self._base_board = ''
Simran Basia23c1392013-08-06 14:59:10 -0700178 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800179 self._usbkm232 = usbkm232
Kevin Chengc49494e2016-07-25 12:13:38 -0700180 # Seed the random generator with the serial to differentiate from other
181 # servod processes.
182 random.seed(serialname if serialname else time.time())
Todd Brochdbb09982011-10-02 07:14:26 -0700183 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700184 try:
185 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
186 except KeyError:
187 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -0700188
Kevin Chengdc3befd2016-07-15 12:34:00 -0700189 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700190 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800191
Mary Ruthven13389642017-02-14 12:15:34 -0800192 def reinitialize(self):
193 """Reinitialize all interfaces that support reinitialization"""
194
195 # If all of the devices that were originally connected are not connected
196 # now, wait up to max_tries * sleep_time for the devices to reconnect
197 max_tries = 10
198 sleep_time = 0.5
199 for i in range(max_tries):
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -0700200 for vid, pid, serialname in self._devices:
201 for current in usb.core.find(idVendor=vid, idProduct=pid,
202 find_all=True):
203 current_serial = usb.util.get_string(current, 256,
204 current.iSerialNumber)
205 if not serialname or serialname == current_serial:
206 # This device still available
207 break
208 else:
209 self._logger.warn('Servo USB device not found: %x:%x serial:%s',
210 vid, pid, serialname)
211 break
212 else:
213 # All the devices found. Reinitialize the interfaces...
Mary Ruthven13389642017-02-14 12:15:34 -0800214 break
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -0700215 time.sleep(sleep_time)
216 else:
217 raise ServodError('Servo USB device not found during reinitialize')
Mary Ruthven13389642017-02-14 12:15:34 -0800218
219 for i, interface in enumerate(self._interface_list):
220 if hasattr(interface, "reinitialize"):
221 interface.reinitialize()
222 else:
223 self._logger.debug("interface %d has no reset functionality", i)
224
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700225 def get_servo_interfaces(self, position, size):
226 """Get the list of servo interfaces.
227
228 Args:
229 position: The index the first interface to get.
230 size: The number of the interfaces.
231 """
232 return self._interface_list[position:(position + size)]
233
234 def set_servo_interfaces(self, position, interfaces):
235 """Set the list of servo interfaces.
236
237 Args:
238 position: The index the first interface to set.
239 interfaces: The list of interfaces to set.
240 """
241 size = len(interfaces)
242 self._interface_list[position:(position + size)] = interfaces
243
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800244 def _init_keyboard_handler(self, servo, board=''):
245 """Initialize the correct keyboard handler for board.
246
Kevin Chengdc3befd2016-07-15 12:34:00 -0700247 Args:
248 servo: servo object.
249 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800250
Kevin Chengdc3befd2016-07-15 12:34:00 -0700251 Returns:
252 keyboard handler object.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800253 """
254 if board == 'parrot':
255 return keyboard_handlers.ParrotHandler(servo)
256 elif board == 'stout':
257 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800258 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800259 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
philipchenfc9eea12016-09-21 17:36:54 -0700260 'sumo', 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
Shelley Chen94cd2352017-07-26 11:36:45 -0700261 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800262 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800263 logging.info("No device path specified for usbkm232 handler. Use "
264 "the servo atmega chip to handle.")
265 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800266 if self._usbkm232 == 'atmega':
267 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800268 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800269 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800270 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800271 self._usbkm232 = self.get('atmega_pty')
Kevin Cheng810fc782016-11-01 12:36:46 -0700272 # We don't need to set the atmega uart settings if we're a servo v4.
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700273 if 'servo_v4' not in self._version:
Kevin Cheng810fc782016-11-01 12:36:46 -0700274 self.set('atmega_baudrate', '9600')
275 self.set('atmega_bits', 'eight')
276 self.set('atmega_parity', 'none')
277 self.set('atmega_sbits', 'one')
278 self.set('usb_mux_sel4', 'on')
279 self.set('usb_mux_oe4', 'on')
280 # Allow atmega bootup time.
281 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800282 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800283 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
284 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800285 # The following boards don't use Chrome EC.
286 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
287 return keyboard_handlers.MatrixKeyboardHandler(servo)
288 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800289
Todd Broch3ec8df02012-11-20 10:53:03 -0800290 def __del__(self):
291 """Servod deconstructor."""
292 for interface in self._interface_list:
293 del(interface)
294
Kevin Chengdc3befd2016-07-15 12:34:00 -0700295 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700296 """Dummy interface for ftdi devices.
297
298 This is a dummy function specifically for ftdi devices to not initialize
299 anything but to help pad the interface list.
300
301 Returns:
302 None.
303 """
304 return None
305
Kevin Chengdc3befd2016-07-15 12:34:00 -0700306 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700307 """Initialize gpio driver interface and open for use.
308
309 Args:
310 interface: interface number of FTDI device to use.
311
312 Returns:
313 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700314
315 Raises:
316 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700317 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700318 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700319 try:
320 fobj.open()
321 except ftdigpio.FgpioError as e:
322 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
323
Todd Broche505b8d2011-03-21 18:19:54 -0700324 return fobj
325
Kevin Chengdc3befd2016-07-15 12:34:00 -0700326 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800327 """Initialize stm32 uart interface and open for use
328
329 Note, the uart runs in a separate thread. Users wishing to
330 interact with it will query control for the pty's pathname and connect
331 with their favorite console program. For example:
332 cu -l /dev/pts/22
333
334 Args:
335 interface: dict of interface parameters.
336
337 Returns:
338 Instance object of interface
339
340 Raises:
341 ServodError: Raised on init failure.
342 """
343 self._logger.info("Suart: interface: %s" % interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700344 sobj = stm32uart.Suart(vendor, product, interface['interface'],
345 serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800346
347 try:
348 sobj.run()
349 except stm32uart.SuartError as e:
350 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
351
352 self._logger.info("%s" % sobj.get_pty())
353 return sobj
354
Kevin Chengdc3befd2016-07-15 12:34:00 -0700355 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800356 """Initialize stm32 gpio interface.
357 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700358 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800359
360 Returns:
361 Instance object of interface
362
363 Raises:
364 SgpioError: Raised on init failure.
365 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700366 interface_number = interface
367 # Interface could be a dict.
368 if type(interface) is dict:
369 interface_number = interface['interface']
370 self._logger.info("Sgpio: interface: %s" % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700371 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800372
Kevin Chengdc3befd2016-07-15 12:34:00 -0700373 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800374 """Initialize stm32 USB to I2C bridge interface and open for use
375
376 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700377 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800378
379 Returns:
380 Instance object of interface.
381
382 Raises:
383 Si2cError: Raised on init failure.
384 """
385 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800386 port = interface.get('port', 0)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700387 return stm32i2c.Si2cBus(vendor, product, interface['interface'],
388 port=port, serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800389
Kevin Chengdc3befd2016-07-15 12:34:00 -0700390 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800391 """Initalize beaglebone ADC interface."""
392 return bbadc.BBadc()
393
Kevin Chengdc3befd2016-07-15 12:34:00 -0700394 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700395 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700396 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700397
Kevin Chengdc3befd2016-07-15 12:34:00 -0700398 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700399 """Initialize i2c interface and open for use.
400
401 Args:
402 interface: interface number of FTDI device to use
403
404 Returns:
405 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700406
407 Raises:
408 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700409 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700410 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700411 try:
412 fobj.open()
413 except ftdii2c.Fi2cError as e:
414 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
415
Todd Broche505b8d2011-03-21 18:19:54 -0700416 # Set the frequency of operation of the i2c bus.
417 # TODO(tbroch) make configureable
418 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700419
Todd Broche505b8d2011-03-21 18:19:54 -0700420 return fobj
421
Simran Basie750a342013-03-12 13:45:26 -0700422 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
423 def _init_bb_i2c(self, interface):
424 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700425 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700426
Kevin Chengdc3befd2016-07-15 12:34:00 -0700427 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800428 """Initalize Linux i2c-dev interface."""
429 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
430
Kevin Chengdc3befd2016-07-15 12:34:00 -0700431 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700432 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700433
434 Note, the uart runs in a separate thread (pthreads). Users wishing to
435 interact with it will query control for the pty's pathname and connect
436 with there favorite console program. For example:
437 cu -l /dev/pts/22
438
439 Args:
440 interface: interface number of FTDI device to use
441
442 Returns:
443 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700444
445 Raises:
446 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700447 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700448 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700449 try:
450 fobj.run()
451 except ftdiuart.FuartError as e:
452 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
453
Todd Broch47c43f42011-05-26 15:11:31 -0700454 self._logger.info("%s" % fobj.get_pty())
455 return fobj
456
Simran Basie750a342013-03-12 13:45:26 -0700457 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700458 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700459 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700460 logging.debug('UART INTERFACE: %s', interface)
461 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700462
Kevin Chengdc3befd2016-07-15 12:34:00 -0700463 def _init_ftdi_gpiouart(self, vendor, product, serialname,
464 interface):
Todd Broch888da782011-10-07 14:29:09 -0700465 """Initialize special gpio + uart interface and open for use
466
467 Note, the uart runs in a separate thread (pthreads). Users wishing to
468 interact with it will query control for the pty's pathname and connect
469 with there favorite console program. For example:
470 cu -l /dev/pts/22
471
472 Args:
473 interface: interface number of FTDI device to use
474
475 Returns:
476 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700477
478 Raises:
479 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700480 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700481 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700482 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700483 try:
484 fuart.run()
485 except ftdiuart.FuartError as e:
486 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
487
Todd Broch888da782011-10-07 14:29:09 -0700488 self._logger.info("uart pty: %s" % fuart.get_pty())
489 return fgpio, fuart
490
Kevin Chengdc3befd2016-07-15 12:34:00 -0700491 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800492 """Initialize EC-3PO console interpreter interface.
493
494 Args:
495 interface: A dictionary representing the interface.
496
497 Returns:
498 An EC3PO object representing the EC-3PO interface or None if there's no
499 interface for the USB PD UART.
500 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700501 raw_uart_name = interface['raw_pty']
502 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800503 raw_ec_uart = self.get(raw_uart_name)
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700504 return ec3po_interface.EC3PO(raw_ec_uart)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800505 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700506 # The overlay doesn't have the raw PTY defined, therefore we can skip
507 # initializing this interface since no control relies on it.
508 self._logger.debug(
509 'Skip initializing EC3PO for %s, no control specified.',
510 raw_uart_name)
511 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800512
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800513 def _camel_case(self, string):
514 output = ''
515 for s in string.split('_'):
516 if output:
517 output += s.capitalize()
518 else:
519 output = s
520 return output
521
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700522 def clear_cached_drv(self):
523 """Clear the cached drivers.
524
525 The drivers are cached in the Dict _drv_dict when a control is got or set.
526 When the servo interfaces are relocated, the cached values may become wrong.
527 Should call this method to clear the cached values.
528 """
529 self._drv_dict = {}
530
Todd Broche505b8d2011-03-21 18:19:54 -0700531 def _get_param_drv(self, control_name, is_get=True):
532 """Get access to driver for a given control.
533
534 Note, some controls have different parameter dictionaries for 'getting' the
535 control's value versus 'setting' it. Boolean is_get distinguishes which is
536 being requested.
537
538 Args:
539 control_name: string name of control
540 is_get: boolean to determine
541
542 Returns:
543 tuple (param, drv) where:
544 param: param dictionary for control
545 drv: instance object of driver for particular control
546
547 Raises:
548 ServodError: Error occurred while examining params dict
549 """
550 self._logger.debug("")
551 # if already setup just return tuple from driver dict
552 if control_name in self._drv_dict:
553 if is_get and ('get' in self._drv_dict[control_name]):
554 return self._drv_dict[control_name]['get']
555 if not is_get and ('set' in self._drv_dict[control_name]):
556 return self._drv_dict[control_name]['set']
557
558 params = self._syscfg.lookup_control_params(control_name, is_get)
559 if 'drv' not in params:
560 self._logger.error("Unable to determine driver for %s" % control_name)
561 raise ServodError("'drv' key not found in params dict")
562 if 'interface' not in params:
563 self._logger.error("Unable to determine interface for %s" %
564 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700565 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700566
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700567 # Find the candidate servos. Using servo_v4 with a servo_micro connected as
568 # an example, the following shows the priority for selecting the interface.
569 #
570 # 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
571 # 2. servo_micro_interface
572 # 3. servo_v4_interface
573 # 4. Fallback to the default, interface.
574 candidates = [ self._version ]
575 candidates.extend(reversed(self._version.split('_with_')))
576
577 interface_id = 'unknown'
578 for c in candidates:
579 interface_name = '%s_interface' % c
580 if interface_name in params:
581 interface_id = params[interface_name]
582 self._logger.debug('Using %s parameter.' % interface_name)
583 break
584
585 # Use the default interface value if we couldn't find a more specific
586 # interface.
587 if interface_id == 'unknown':
588 interface_id = params['interface']
589 self._logger.debug('Using default interface parameter.')
590
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800591 if interface_id == 'servo':
592 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700593 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700594 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800595 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700596
Todd Broche505b8d2011-03-21 18:19:54 -0700597 drv_name = params['drv']
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800598 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800599 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700600 drv = drv_class(interface, params)
601 if control_name not in self._drv_dict:
602 self._drv_dict[control_name] = {}
603 if is_get:
604 self._drv_dict[control_name]['get'] = (params, drv)
605 else:
606 self._drv_dict[control_name]['set'] = (params, drv)
607 return (params, drv)
608
609 def doc_all(self):
610 """Return all documenation for controls.
611
612 Returns:
613 string of <doc> text in config file (xml) and the params dictionary for
614 all controls.
615
616 For example:
617 warm_reset :: Reset the device warmly
618 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
619 """
620 return self._syscfg.display_config()
621
622 def doc(self, name):
623 """Retreive doc string in system config file for given control name.
624
625 Args:
626 name: name string of control to get doc string
627
628 Returns:
629 doc string of name
630
631 Raises:
632 NameError: if fails to locate control
633 """
634 self._logger.debug("name(%s)" % (name))
635 if self._syscfg.is_control(name):
636 return self._syscfg.get_control_docstring(name)
637 else:
638 raise NameError("No control %s" %name)
639
Fang Deng90377712013-06-03 15:51:48 -0700640 def _switch_usbkey(self, mux_direction):
641 """Connect USB flash stick to either servo or DUT.
642
643 This function switches 'usb_mux_sel1' to provide electrical
644 connection between the USB port J3 and either servo or DUT side.
645
646 Switching the usb mux is accompanied by powercycling
647 of the USB stick, because it sometimes gets wedged if the mux
648 is switched while the stick power is on.
649
650 Args:
651 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
652 """
653 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
654 time.sleep(self._USB_POWEROFF_DELAY)
655 self.set(self._USB_J3, mux_direction)
656 time.sleep(self._USB_POWEROFF_DELAY)
657 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
658 if mux_direction == self._USB_J3_TO_SERVO:
659 time.sleep(self._USB_DETECTION_DELAY)
660
Simran Basia9f41032012-05-11 14:21:58 -0700661 def _get_usb_port_set(self):
662 """Gets a set of USB disks currently connected to the system
663
664 Returns:
665 A set of USB disk paths.
666 """
667 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
668 return set(["/dev/" + dev for dev in usb_set])
669
Kevin Cheng5595b342016-09-29 15:51:01 -0700670 @contextlib.contextmanager
671 def _block_other_servod(self, timeout=None):
Kevin Chengc49494e2016-07-25 12:13:38 -0700672 """Block other servod processes by locking a file.
673
674 To enable multiple servods processes to safely probe_host_usb_dev, we use
675 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700676 for a usb device. This will be a context manager that will return
677 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700678
679 If the lock file exists, we open it and try to lock it.
680 - If another servod processes has locked it already, we'll sleep a random
681 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700682 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700683
Kevin Cheng5595b342016-09-29 15:51:01 -0700684 - If we're able to lock the file, we'll yield that the block was successful
685 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700686
687 This blocking behavior is only enabled if the lock file exists, if it
688 doesn't, then we pretend the block was successful.
689
Kevin Cheng5595b342016-09-29 15:51:01 -0700690 Args:
691 timeout: Max waiting time for the block to succeed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700692 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700693 if not os.path.exists(self._USB_LOCK_FILE):
694 # No lock file so we'll pretend the block was a success.
695 yield True
696 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700697 start_time = datetime.datetime.now()
698 while True:
Kevin Cheng5595b342016-09-29 15:51:01 -0700699 with open(self._USB_LOCK_FILE) as lock_file:
700 try:
701 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
702 yield True
703 fcntl.flock(lock_file, fcntl.LOCK_UN)
704 break
705 except IOError:
706 current_time = datetime.datetime.now()
707 current_wait_time = (current_time - start_time).total_seconds()
708 if timeout and current_wait_time > timeout:
709 yield False
710 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700711 # Sleep random amount.
712 sleep_time = time.sleep(random.random())
Kevin Chengc49494e2016-07-25 12:13:38 -0700713
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700714 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700715 """Toggle the usb power safely.
716
717 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700718
719 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700720 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700721 timeout: Timeout to wait for blocking other servod processes, default is
722 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700723
Kevin Cheng5595b342016-09-29 15:51:01 -0700724 Returns:
725 An empty string to appease the xmlrpc gods.
726 """
727 with self._block_other_servod(timeout=timeout):
728 if power_state != self.get(self._USB_J3_PWR):
729 self.set(self._USB_J3_PWR, power_state)
730 return ''
731
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700732 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700733 """Toggle the usb direction safely.
734
735 We'll make sure we're the only servod process toggling the usbkey direction.
736
737 Args:
738 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700739 timeout: Timeout to wait for blocking other servod processes, default is
740 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700741
742 Returns:
743 An empty string to appease the xmlrpc gods.
744 """
745 with self._block_other_servod(timeout=timeout):
746 self._switch_usbkey(mux_direction)
747 return ''
748
749 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700750 """Probe the USB disk device plugged in the servo from the host side.
751
752 Method can fail by:
753 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700754 another servo unless _USB_LOCK_FILE exists on the servo host. If that
755 file exists, then it is safe to probe for usb devices among multiple
756 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700757 2) Finding multiple /dev/sdX and returning None.
758
Kevin Cheng5595b342016-09-29 15:51:01 -0700759 Args:
760 timeout: Timeout to wait for blocking other servod processes.
761
Simran Basia9f41032012-05-11 14:21:58 -0700762 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700763 USB disk path if one and only one USB disk path is found, otherwise an
764 empty string.
Simran Basia9f41032012-05-11 14:21:58 -0700765 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700766 with self._block_other_servod(timeout=timeout) as block_success:
767 if not block_success:
768 return ''
Kevin Chengc49494e2016-07-25 12:13:38 -0700769
Kevin Cheng5595b342016-09-29 15:51:01 -0700770 original_value = self.get(self._USB_J3)
771 original_usb_power = self.get(self._USB_J3_PWR)
772 # Make the host unable to see the USB disk.
773 if (original_usb_power == self._USB_J3_PWR_ON and
774 original_value != self._USB_J3_TO_DUT):
775 self._switch_usbkey(self._USB_J3_TO_DUT)
776 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700777
Kevin Cheng5595b342016-09-29 15:51:01 -0700778 # Make the host able to see the USB disk.
779 self._switch_usbkey(self._USB_J3_TO_SERVO)
780 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700781
Kevin Cheng5595b342016-09-29 15:51:01 -0700782 # Back to its original value.
783 if original_value != self._USB_J3_TO_SERVO:
784 self._switch_usbkey(original_value)
785 if original_usb_power != self._USB_J3_PWR_ON:
786 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
787 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700788
Kevin Cheng5595b342016-09-29 15:51:01 -0700789 # Subtract the two sets to find the usb device.
790 diff_set = has_usb_set - no_usb_set
791 if len(diff_set) == 1:
792 return diff_set.pop()
793 else:
794 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700795
Kevin Cheng85831332016-10-13 13:14:44 -0700796 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700797 """Download image and save to the USB device found by probe_host_usb_dev.
798 If the image_path is a URL, it will download this url to the USB path;
799 otherwise it will simply copy the image_path's contents to the USB path.
800
801 Args:
802 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700803 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700804
805 Returns:
806 True|False: True if process completed successfully, False if error
807 occurred.
808 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
809 comment at the end of set().
810 """
811 self._logger.debug("image_path(%s)" % image_path)
812 self._logger.debug("Detecting USB stick device...")
Kevin Cheng85831332016-10-13 13:14:44 -0700813 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700814 if not usb_dev:
815 self._logger.error("No usb device connected to servo")
816 return False
817
Kevin Cheng9071ed92016-06-21 14:37:54 -0700818 # Let's check if we downloaded this last time and if so assume the image is
819 # still on the usb device and return True.
820 if self._image_path == image_path:
821 self._logger.debug("Image already on USB device, skipping transfer")
822 return True
823
Simran Basia9f41032012-05-11 14:21:58 -0700824 try:
825 if image_path.startswith(self._HTTP_PREFIX):
826 self._logger.debug("Image path is a URL, downloading image")
827 urllib.urlretrieve(image_path, usb_dev)
828 else:
829 shutil.copyfile(image_path, usb_dev)
830 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700831 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700832 e.strerror, e.errno)
833 return False
834 except urllib.ContentTooShortError:
835 self._logger.error("Failed to download URL: %s to USB device: %s",
836 image_path, usb_dev)
837 return False
838 except BaseException as e:
839 self._logger.error("Unexpected exception downloading %s to %s: %s",
840 image_path, usb_dev, str(e))
841 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800842 finally:
843 # We just plastered the partition table for a block device.
844 # Pass or fail, we mustn't go without telling the kernel about
845 # the change, or it will punish us with sporadic, hard-to-debug
846 # failures.
847 subprocess.call(["sync"])
848 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700849 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700850 return True
851
852 def make_image_noninteractive(self):
853 """Makes the recovery image noninteractive.
854
855 A noninteractive image will reboot automatically after installation
856 instead of waiting for the USB device to be removed to initiate a system
857 reboot.
858
859 Mounts partition 1 of the image stored on usb_dev and creates a file
860 called "non_interactive" so that the image will become noninteractive.
861
862 Returns:
863 True|False: True if process completed successfully, False if error
864 occurred.
865 """
866 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700867 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700868 if not usb_dev:
869 self._logger.error("No usb device connected to servo")
870 return False
871 # Create TempDirectory
872 tmpdir = tempfile.mkdtemp()
873 if tmpdir:
874 # Mount drive to tmpdir.
875 partition_1 = "%s1" % usb_dev
876 rc = subprocess.call(["mount", partition_1, tmpdir])
877 if rc == 0:
878 # Create file 'non_interactive'
879 non_interactive_file = os.path.join(tmpdir, "non_interactive")
880 try:
881 open(non_interactive_file, "w").close()
882 except IOError as e:
883 self._logger.error("Failed to create file %s : %s ( %d )",
884 non_interactive_file, e.strerror, e.errno)
885 result = False
886 except BaseException as e:
887 self._logger.error("Unexpected Exception creating file %s : %s",
888 non_interactive_file, str(e))
889 result = False
890 # Unmount drive regardless if file creation worked or not.
891 rc = subprocess.call(["umount", partition_1])
892 if rc != 0:
893 self._logger.error("Failed to unmount USB Device")
894 result = False
895 else:
896 self._logger.error("Failed to mount USB Device")
897 result = False
898
899 # Delete tmpdir. May throw exception if 'umount' failed.
900 try:
901 os.rmdir(tmpdir)
902 except OSError as e:
903 self._logger.error("Failed to remove temp directory %s : %s",
904 tmpdir, str(e))
905 return False
906 except BaseException as e:
907 self._logger.error("Unexpected Exception removing tempdir %s : %s",
908 tmpdir, str(e))
909 return False
910 else:
911 self._logger.error("Failed to create temp directory.")
912 return False
913 return result
914
Todd Broch352b4b22013-03-22 09:48:40 -0700915 def set_get_all(self, cmds):
916 """Set &| get one or more control values.
917
918 Args:
919 cmds: list of control[:value] to get or set.
920
921 Returns:
922 rv: list of responses from calling get or set methods.
923 """
924 rv = []
925 for cmd in cmds:
926 if ':' in cmd:
927 (control, value) = cmd.split(':')
928 rv.append(self.set(control, value))
929 else:
930 rv.append(self.get(cmd))
931 return rv
932
Aseda Aboagye6921f602017-08-01 14:45:38 -0700933 def get_serial_number(self, name):
934 """Returns the desired serial number from the serialnames dict.
935
936 Args:
937 name: A string which is the key into the _serialnames dictionary.
938
939 Returns:
940 A string containing the serial number or "unknown".
941 """
942 if not name:
943 name = 'main'
944
945 try:
946 return self._serialnames[name]
947 except KeyError:
948 self._logger.debug("'%s_serialname' not found!", name)
949 return "unknown"
950
Todd Broche505b8d2011-03-21 18:19:54 -0700951 def get(self, name):
952 """Get control value.
953
954 Args:
955 name: name string of control
956
957 Returns:
958 Response from calling drv get method. Value is reformatted based on
959 control's dictionary parameters
960
961 Raises:
962 HwDriverError: Error occurred while using drv
963 """
964 self._logger.debug("name(%s)" % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700965 # This route is to retrieve serialnames on servo v4, which
966 # connects to multiple servo-micros or CCD, like the controls,
967 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
968 # TODO(aaboagye): Refactor it.
969 if 'serialname' in name:
970 return self.get_serial_number(name.split('serialname')[0].strip('_'))
971
Todd Broche505b8d2011-03-21 18:19:54 -0700972 (param, drv) = self._get_param_drv(name)
973 try:
974 val = drv.get()
975 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800976 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700977 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700978 except AttributeError, error:
979 self._logger.error("Getting %s: %s" % (name, error))
980 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800981 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700982 self._logger.error("Getting %s" % (name))
983 raise
Todd Brochd6061672012-05-11 15:52:47 -0700984
Todd Broche505b8d2011-03-21 18:19:54 -0700985 def get_all(self, verbose):
986 """Get all controls values.
987
988 Args:
989 verbose: Boolean on whether to return doc info as well
990
991 Returns:
992 string creating from trying to get all values of all controls. In case of
993 error attempting access to control, response is 'ERR'.
994 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800995 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700996 for name in self._syscfg.syscfg_dict['control']:
997 self._logger.debug("name = %s" %name)
998 try:
999 value = self.get(name)
1000 except Exception:
1001 value = "ERR"
1002 pass
1003 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -08001004 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -07001005 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -08001006 rsp.append("%s:%s" % (name, value))
1007 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -07001008
1009 def set(self, name, wr_val_str):
1010 """Set control.
1011
1012 Args:
1013 name: name string of control
1014 wr_val_str: value string to write. Can be integer, float or a
1015 alpha-numerical that is mapped to a integer or float.
1016
1017 Raises:
1018 HwDriverError: Error occurred while using driver
1019 """
1020 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
1021 (params, drv) = self._get_param_drv(name, False)
1022 wr_val = self._syscfg.resolve_val(params, wr_val_str)
1023 try:
1024 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +08001025 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -07001026 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
1027 raise
1028 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
1029 # & client I still have to return something to appease the
1030 # marshall/unmarshall
1031 return True
1032
Todd Brochd6061672012-05-11 15:52:47 -07001033 def hwinit(self, verbose=False):
1034 """Initialize all controls.
1035
1036 These values are part of the system config XML files of the form
1037 init=<value>. This command should be used by clients wishing to return the
1038 servo and DUT its connected to a known good/safe state.
1039
Vadim Bendeburybb51dd42013-01-31 13:47:46 -08001040 Note that initialization errors are ignored (as in some cases they could
1041 be caused by DUT firmware deficiencies). This might need to be fine tuned
1042 later.
1043
Todd Brochd6061672012-05-11 15:52:47 -07001044 Args:
1045 verbose: boolean, if True prints info about control initialized.
1046 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001047
1048 Returns:
1049 This function is called across RPC and as such is expected to return
1050 something unless transferring 'none' across is allowed. Hence adding a
1051 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -07001052 """
Todd Brochd9acf0a2012-12-05 13:43:06 -08001053 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -08001054 try:
John Carey6fe2bbf2015-08-31 16:13:03 -07001055 # Workaround for bug chrome-os-partner:42349. Without this check, the
1056 # gpio will briefly pulse low if we set it from high to high.
1057 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -07001058 self.set(control_name, value)
1059 if verbose:
1060 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -08001061 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -08001062 self._logger.error("Problem initializing %s -> %s :: %s",
1063 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -08001064
1065 # Init keyboard after all the intefaces are up.
1066 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001067 return True
Todd Broch3ec8df02012-11-20 10:53:03 -08001068
Todd Broche505b8d2011-03-21 18:19:54 -07001069 def echo(self, echo):
1070 """Dummy echo function for testing/examples.
1071
1072 Args:
1073 echo: string to echo back to client
1074 """
1075 self._logger.debug("echo(%s)" % (echo))
1076 return "ECH0ING: %s" % (echo)
1077
J. Richard Barnettee2820552013-03-14 16:13:46 -07001078 def get_board(self):
1079 """Return the board specified at startup, if any."""
1080 return self._board
1081
Wai-Hong Tam416cf612017-09-19 11:39:21 -07001082 def get_base_board(self):
1083 """Returns the board name of the base if present.
1084
1085 Returns:
1086 A string of the board name, or '' if not present.
1087 """
1088 # The value is set in servo_postinit.
1089 return self._base_board
1090
Simran Basia23c1392013-08-06 14:59:10 -07001091 def get_version(self):
1092 """Get servo board version."""
1093 return self._version
1094
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001095 def power_long_press(self):
1096 """Simulate a long power button press."""
1097 # After a long power press, the EC may ignore the next power
1098 # button press (at least on Alex). To guarantee that this
1099 # won't happen, we need to allow the EC one second to
1100 # collect itself.
1101 self._keyboard.power_long_press()
1102 return True
1103
1104 def power_normal_press(self):
1105 """Simulate a normal power button press."""
1106 self._keyboard.power_normal_press()
1107 return True
1108
1109 def power_short_press(self):
1110 """Simulate a short power button press."""
1111 self._keyboard.power_short_press()
1112 return True
1113
1114 def power_key(self, secs=''):
1115 """Simulate a power button press.
1116
1117 Args:
1118 secs: Time in seconds to simulate the keypress.
1119 """
1120 self._keyboard.power_key(secs)
1121 return True
1122
1123 def ctrl_d(self, press_secs=''):
1124 """Simulate Ctrl-d simultaneous button presses."""
1125 self._keyboard.ctrl_d(press_secs)
1126 return True
1127
Victor Dodone539cea2016-03-29 18:50:17 -07001128 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001129 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001130 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001131 return True
1132
1133 def ctrl_enter(self, press_secs=''):
1134 """Simulate Ctrl-enter simultaneous button presses."""
1135 self._keyboard.ctrl_enter(press_secs)
1136 return True
1137
1138 def d_key(self, press_secs=''):
1139 """Simulate Enter key button press."""
1140 self._keyboard.d_key(press_secs)
1141 return True
1142
1143 def ctrl_key(self, press_secs=''):
1144 """Simulate Enter key button press."""
1145 self._keyboard.ctrl_key(press_secs)
1146 return True
1147
1148 def enter_key(self, press_secs=''):
1149 """Simulate Enter key button press."""
1150 self._keyboard.enter_key(press_secs)
1151 return True
1152
1153 def refresh_key(self, press_secs=''):
1154 """Simulate Refresh key (F3) button press."""
1155 self._keyboard.refresh_key(press_secs)
1156 return True
1157
1158 def ctrl_refresh_key(self, press_secs=''):
1159 """Simulate Ctrl and Refresh (F3) simultaneous press.
1160
1161 This key combination is an alternative of Space key.
1162 """
1163 self._keyboard.ctrl_refresh_key(press_secs)
1164 return True
1165
1166 def imaginary_key(self, press_secs=''):
1167 """Simulate imaginary key button press.
1168
1169 Maps to a key that doesn't physically exist.
1170 """
1171 self._keyboard.imaginary_key(press_secs)
1172 return True
1173
Todd Brochdbb09982011-10-02 07:14:26 -07001174
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001175 def sysrq_x(self, press_secs=''):
1176 """Simulate Alt VolumeUp X simultaneous press.
1177
1178 This key combination is the kernel system request (sysrq) x.
1179 """
1180 self._keyboard.sysrq_x(press_secs)
1181 return True
1182
1183
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001184 def get_servo_serials(self):
1185 """Return all the serials associated with this process."""
1186 return self._serialnames
1187
1188
Todd Broche505b8d2011-03-21 18:19:54 -07001189def test():
1190 """Integration testing.
1191
1192 TODO(tbroch) Enhance integration test and add unittest (see mox)
1193 """
1194 logging.basicConfig(level=logging.DEBUG,
1195 format="%(asctime)s - %(name)s - " +
1196 "%(levelname)s - %(message)s")
1197 # configure server & listen
1198 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -07001199 # 5 == number of interfaces on a FT4232H device
1200 for i in xrange(1, 5):
1201 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -07001202 # its an i2c interface ... see __init__ for details and TODO to make
1203 # this configureable
1204 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1205 else:
1206 # its a gpio interface
1207 servod_obj._interface_list[i].wr_rd(0)
1208
1209 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1210 allow_none=True)
1211 server.register_introspection_functions()
1212 server.register_multicall_functions()
1213 server.register_instance(servod_obj)
1214 logging.info("Listening on localhost port 9999")
1215 server.serve_forever()
1216
1217if __name__ == "__main__":
1218 test()
1219
1220 # simple client transaction would look like
1221 """
1222 remote_uri = 'http://localhost:9999'
1223 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1224 send_str = "Hello_there"
1225 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1226 """