blob: 2dac7f9a1709481b571a8297abe5c4a40e31bfba [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
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700155 keyboards. Used in FAFT tests. Use None for on board AVR MCU.
156 e.g. '/dev/ttyUSB0' or None.
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]
Dino Lic89d8c82018-01-11 09:56:47 +0800188 self._interfaces = interfaces
Todd Brochdbb09982011-10-02 07:14:26 -0700189
Kevin Chengdc3befd2016-07-15 12:34:00 -0700190 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700191 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800192
Mary Ruthven13389642017-02-14 12:15:34 -0800193 def reinitialize(self):
194 """Reinitialize all interfaces that support reinitialization"""
195
196 # If all of the devices that were originally connected are not connected
197 # now, wait up to max_tries * sleep_time for the devices to reconnect
198 max_tries = 10
199 sleep_time = 0.5
200 for i in range(max_tries):
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -0700201 for vid, pid, serialname in self._devices:
202 for current in usb.core.find(idVendor=vid, idProduct=pid,
203 find_all=True):
204 current_serial = usb.util.get_string(current, 256,
205 current.iSerialNumber)
206 if not serialname or serialname == current_serial:
207 # This device still available
208 break
209 else:
210 self._logger.warn('Servo USB device not found: %x:%x serial:%s',
211 vid, pid, serialname)
212 break
213 else:
214 # All the devices found. Reinitialize the interfaces...
Mary Ruthven13389642017-02-14 12:15:34 -0800215 break
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -0700216 time.sleep(sleep_time)
217 else:
218 raise ServodError('Servo USB device not found during reinitialize')
Mary Ruthven13389642017-02-14 12:15:34 -0800219
220 for i, interface in enumerate(self._interface_list):
221 if hasattr(interface, "reinitialize"):
222 interface.reinitialize()
223 else:
224 self._logger.debug("interface %d has no reset functionality", i)
225
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700226 def get_servo_interfaces(self, position, size):
227 """Get the list of servo interfaces.
228
229 Args:
230 position: The index the first interface to get.
231 size: The number of the interfaces.
232 """
233 return self._interface_list[position:(position + size)]
234
235 def set_servo_interfaces(self, position, interfaces):
236 """Set the list of servo interfaces.
237
238 Args:
239 position: The index the first interface to set.
240 interfaces: The list of interfaces to set.
241 """
242 size = len(interfaces)
243 self._interface_list[position:(position + size)] = interfaces
244
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800245 def _init_keyboard_handler(self, servo, board=''):
246 """Initialize the correct keyboard handler for board.
247
Kevin Chengdc3befd2016-07-15 12:34:00 -0700248 Args:
249 servo: servo object.
250 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800251
Kevin Chengdc3befd2016-07-15 12:34:00 -0700252 Returns:
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700253 keyboard handler object, or None if no keyboard supported.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800254 """
255 if board == 'parrot':
256 return keyboard_handlers.ParrotHandler(servo)
257 elif board == 'stout':
258 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800259 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800260 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
philipchenfc9eea12016-09-21 17:36:54 -0700261 'sumo', 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
Shelley Chen94cd2352017-07-26 11:36:45 -0700262 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800263 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800264 logging.info("No device path specified for usbkm232 handler. Use "
265 "the servo atmega chip to handle.")
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700266
Danny Chan662b6022015-11-04 17:34:53 -0800267 # Use servo onboard keyboard emulator.
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700268 if not self._syscfg.is_control('atmega_rst'):
269 logging.warn('No atmega in servo board. So no keyboard support.')
270 return None
271
Nick Sanders78423782015-11-09 14:28:19 -0800272 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800273 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800274 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800275 self._usbkm232 = self.get('atmega_pty')
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700276
Kevin Cheng810fc782016-11-01 12:36:46 -0700277 # We don't need to set the atmega uart settings if we're a servo v4.
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700278 if 'servo_v4' not in self._version:
Kevin Cheng810fc782016-11-01 12:36:46 -0700279 self.set('atmega_baudrate', '9600')
280 self.set('atmega_bits', 'eight')
281 self.set('atmega_parity', 'none')
282 self.set('atmega_sbits', 'one')
283 self.set('usb_mux_sel4', 'on')
284 self.set('usb_mux_oe4', 'on')
285 # Allow atmega bootup time.
286 time.sleep(1.0)
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700287
Danny Chan662b6022015-11-04 17:34:53 -0800288 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800289 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
290 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800291 # The following boards don't use Chrome EC.
292 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
293 return keyboard_handlers.MatrixKeyboardHandler(servo)
294 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800295
Todd Broch3ec8df02012-11-20 10:53:03 -0800296 def __del__(self):
297 """Servod deconstructor."""
298 for interface in self._interface_list:
299 del(interface)
300
Kevin Chengdc3befd2016-07-15 12:34:00 -0700301 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700302 """Dummy interface for ftdi devices.
303
304 This is a dummy function specifically for ftdi devices to not initialize
305 anything but to help pad the interface list.
306
307 Returns:
308 None.
309 """
310 return None
311
Kevin Chengdc3befd2016-07-15 12:34:00 -0700312 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700313 """Initialize gpio driver interface and open for use.
314
315 Args:
316 interface: interface number of FTDI device to use.
317
318 Returns:
319 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700320
321 Raises:
322 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700323 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700324 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700325 try:
326 fobj.open()
327 except ftdigpio.FgpioError as e:
328 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
329
Todd Broche505b8d2011-03-21 18:19:54 -0700330 return fobj
331
Kevin Chengdc3befd2016-07-15 12:34:00 -0700332 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800333 """Initialize stm32 uart interface and open for use
334
335 Note, the uart runs in a separate thread. Users wishing to
336 interact with it will query control for the pty's pathname and connect
337 with their favorite console program. For example:
338 cu -l /dev/pts/22
339
340 Args:
341 interface: dict of interface parameters.
342
343 Returns:
344 Instance object of interface
345
346 Raises:
347 ServodError: Raised on init failure.
348 """
349 self._logger.info("Suart: interface: %s" % interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700350 sobj = stm32uart.Suart(vendor, product, interface['interface'],
351 serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800352
353 try:
354 sobj.run()
355 except stm32uart.SuartError as e:
356 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
357
358 self._logger.info("%s" % sobj.get_pty())
359 return sobj
360
Kevin Chengdc3befd2016-07-15 12:34:00 -0700361 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800362 """Initialize stm32 gpio interface.
363 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700364 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800365
366 Returns:
367 Instance object of interface
368
369 Raises:
370 SgpioError: Raised on init failure.
371 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700372 interface_number = interface
373 # Interface could be a dict.
374 if type(interface) is dict:
375 interface_number = interface['interface']
376 self._logger.info("Sgpio: interface: %s" % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700377 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800378
Kevin Chengdc3befd2016-07-15 12:34:00 -0700379 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800380 """Initialize stm32 USB to I2C bridge interface and open for use
381
382 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700383 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800384
385 Returns:
386 Instance object of interface.
387
388 Raises:
389 Si2cError: Raised on init failure.
390 """
391 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800392 port = interface.get('port', 0)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700393 return stm32i2c.Si2cBus(vendor, product, interface['interface'],
394 port=port, serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800395
Kevin Chengdc3befd2016-07-15 12:34:00 -0700396 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800397 """Initalize beaglebone ADC interface."""
398 return bbadc.BBadc()
399
Kevin Chengdc3befd2016-07-15 12:34:00 -0700400 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700401 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700402 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700403
Kevin Chengdc3befd2016-07-15 12:34:00 -0700404 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700405 """Initialize i2c interface and open for use.
406
407 Args:
408 interface: interface number of FTDI device to use
409
410 Returns:
411 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700412
413 Raises:
414 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700415 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700416 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700417 try:
418 fobj.open()
419 except ftdii2c.Fi2cError as e:
420 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
421
Todd Broche505b8d2011-03-21 18:19:54 -0700422 # Set the frequency of operation of the i2c bus.
423 # TODO(tbroch) make configureable
424 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700425
Todd Broche505b8d2011-03-21 18:19:54 -0700426 return fobj
427
Simran Basie750a342013-03-12 13:45:26 -0700428 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
429 def _init_bb_i2c(self, interface):
430 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700431 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700432
Kevin Chengdc3befd2016-07-15 12:34:00 -0700433 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800434 """Initalize Linux i2c-dev interface."""
435 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
436
Kevin Chengdc3befd2016-07-15 12:34:00 -0700437 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700438 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700439
440 Note, the uart runs in a separate thread (pthreads). Users wishing to
441 interact with it will query control for the pty's pathname and connect
442 with there favorite console program. For example:
443 cu -l /dev/pts/22
444
445 Args:
446 interface: interface number of FTDI device to use
447
448 Returns:
449 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700450
451 Raises:
452 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700453 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700454 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700455 try:
456 fobj.run()
457 except ftdiuart.FuartError as e:
458 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
459
Todd Broch47c43f42011-05-26 15:11:31 -0700460 self._logger.info("%s" % fobj.get_pty())
461 return fobj
462
Simran Basie750a342013-03-12 13:45:26 -0700463 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700464 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700465 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700466 logging.debug('UART INTERFACE: %s', interface)
467 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700468
Kevin Chengdc3befd2016-07-15 12:34:00 -0700469 def _init_ftdi_gpiouart(self, vendor, product, serialname,
470 interface):
Todd Broch888da782011-10-07 14:29:09 -0700471 """Initialize special gpio + uart interface and open for use
472
473 Note, the uart runs in a separate thread (pthreads). Users wishing to
474 interact with it will query control for the pty's pathname and connect
475 with there favorite console program. For example:
476 cu -l /dev/pts/22
477
478 Args:
479 interface: interface number of FTDI device to use
480
481 Returns:
482 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700483
484 Raises:
485 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700486 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700487 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700488 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700489 try:
490 fuart.run()
491 except ftdiuart.FuartError as e:
492 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
493
Todd Broch888da782011-10-07 14:29:09 -0700494 self._logger.info("uart pty: %s" % fuart.get_pty())
495 return fgpio, fuart
496
Kevin Chengdc3befd2016-07-15 12:34:00 -0700497 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800498 """Initialize EC-3PO console interpreter interface.
499
500 Args:
501 interface: A dictionary representing the interface.
502
503 Returns:
504 An EC3PO object representing the EC-3PO interface or None if there's no
505 interface for the USB PD UART.
506 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700507 raw_uart_name = interface['raw_pty']
508 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800509 raw_ec_uart = self.get(raw_uart_name)
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700510 return ec3po_interface.EC3PO(raw_ec_uart)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800511 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700512 # The overlay doesn't have the raw PTY defined, therefore we can skip
513 # initializing this interface since no control relies on it.
514 self._logger.debug(
515 'Skip initializing EC3PO for %s, no control specified.',
516 raw_uart_name)
517 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800518
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800519 def _camel_case(self, string):
520 output = ''
521 for s in string.split('_'):
522 if output:
523 output += s.capitalize()
524 else:
525 output = s
526 return output
527
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700528 def clear_cached_drv(self):
529 """Clear the cached drivers.
530
531 The drivers are cached in the Dict _drv_dict when a control is got or set.
532 When the servo interfaces are relocated, the cached values may become wrong.
533 Should call this method to clear the cached values.
534 """
535 self._drv_dict = {}
536
Todd Broche505b8d2011-03-21 18:19:54 -0700537 def _get_param_drv(self, control_name, is_get=True):
538 """Get access to driver for a given control.
539
540 Note, some controls have different parameter dictionaries for 'getting' the
541 control's value versus 'setting' it. Boolean is_get distinguishes which is
542 being requested.
543
544 Args:
545 control_name: string name of control
546 is_get: boolean to determine
547
548 Returns:
549 tuple (param, drv) where:
550 param: param dictionary for control
551 drv: instance object of driver for particular control
552
553 Raises:
554 ServodError: Error occurred while examining params dict
555 """
556 self._logger.debug("")
557 # if already setup just return tuple from driver dict
558 if control_name in self._drv_dict:
559 if is_get and ('get' in self._drv_dict[control_name]):
560 return self._drv_dict[control_name]['get']
561 if not is_get and ('set' in self._drv_dict[control_name]):
562 return self._drv_dict[control_name]['set']
563
564 params = self._syscfg.lookup_control_params(control_name, is_get)
565 if 'drv' not in params:
566 self._logger.error("Unable to determine driver for %s" % control_name)
567 raise ServodError("'drv' key not found in params dict")
568 if 'interface' not in params:
569 self._logger.error("Unable to determine interface for %s" %
570 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700571 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700572
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700573 # Find the candidate servos. Using servo_v4 with a servo_micro connected as
574 # an example, the following shows the priority for selecting the interface.
575 #
576 # 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
577 # 2. servo_micro_interface
578 # 3. servo_v4_interface
579 # 4. Fallback to the default, interface.
580 candidates = [ self._version ]
581 candidates.extend(reversed(self._version.split('_with_')))
582
583 interface_id = 'unknown'
584 for c in candidates:
585 interface_name = '%s_interface' % c
586 if interface_name in params:
587 interface_id = params[interface_name]
588 self._logger.debug('Using %s parameter.' % interface_name)
589 break
590
591 # Use the default interface value if we couldn't find a more specific
592 # interface.
593 if interface_id == 'unknown':
594 interface_id = params['interface']
595 self._logger.debug('Using default interface parameter.')
596
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800597 if interface_id == 'servo':
598 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700599 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700600 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800601 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700602
Todd Broche505b8d2011-03-21 18:19:54 -0700603 drv_name = params['drv']
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800604 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800605 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700606 drv = drv_class(interface, params)
607 if control_name not in self._drv_dict:
608 self._drv_dict[control_name] = {}
609 if is_get:
610 self._drv_dict[control_name]['get'] = (params, drv)
611 else:
612 self._drv_dict[control_name]['set'] = (params, drv)
613 return (params, drv)
614
615 def doc_all(self):
616 """Return all documenation for controls.
617
618 Returns:
619 string of <doc> text in config file (xml) and the params dictionary for
620 all controls.
621
622 For example:
623 warm_reset :: Reset the device warmly
624 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
625 """
626 return self._syscfg.display_config()
627
628 def doc(self, name):
629 """Retreive doc string in system config file for given control name.
630
631 Args:
632 name: name string of control to get doc string
633
634 Returns:
635 doc string of name
636
637 Raises:
638 NameError: if fails to locate control
639 """
640 self._logger.debug("name(%s)" % (name))
641 if self._syscfg.is_control(name):
642 return self._syscfg.get_control_docstring(name)
643 else:
644 raise NameError("No control %s" %name)
645
Fang Deng90377712013-06-03 15:51:48 -0700646 def _switch_usbkey(self, mux_direction):
647 """Connect USB flash stick to either servo or DUT.
648
649 This function switches 'usb_mux_sel1' to provide electrical
650 connection between the USB port J3 and either servo or DUT side.
651
652 Switching the usb mux is accompanied by powercycling
653 of the USB stick, because it sometimes gets wedged if the mux
654 is switched while the stick power is on.
655
656 Args:
657 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
658 """
659 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
660 time.sleep(self._USB_POWEROFF_DELAY)
661 self.set(self._USB_J3, mux_direction)
662 time.sleep(self._USB_POWEROFF_DELAY)
663 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
664 if mux_direction == self._USB_J3_TO_SERVO:
665 time.sleep(self._USB_DETECTION_DELAY)
666
Simran Basia9f41032012-05-11 14:21:58 -0700667 def _get_usb_port_set(self):
668 """Gets a set of USB disks currently connected to the system
669
670 Returns:
671 A set of USB disk paths.
672 """
673 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
674 return set(["/dev/" + dev for dev in usb_set])
675
Kevin Cheng5595b342016-09-29 15:51:01 -0700676 @contextlib.contextmanager
677 def _block_other_servod(self, timeout=None):
Kevin Chengc49494e2016-07-25 12:13:38 -0700678 """Block other servod processes by locking a file.
679
680 To enable multiple servods processes to safely probe_host_usb_dev, we use
681 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700682 for a usb device. This will be a context manager that will return
683 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700684
685 If the lock file exists, we open it and try to lock it.
686 - If another servod processes has locked it already, we'll sleep a random
687 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700688 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700689
Kevin Cheng5595b342016-09-29 15:51:01 -0700690 - If we're able to lock the file, we'll yield that the block was successful
691 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700692
693 This blocking behavior is only enabled if the lock file exists, if it
694 doesn't, then we pretend the block was successful.
695
Kevin Cheng5595b342016-09-29 15:51:01 -0700696 Args:
697 timeout: Max waiting time for the block to succeed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700698 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700699 if not os.path.exists(self._USB_LOCK_FILE):
700 # No lock file so we'll pretend the block was a success.
701 yield True
702 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700703 start_time = datetime.datetime.now()
704 while True:
Kevin Cheng5595b342016-09-29 15:51:01 -0700705 with open(self._USB_LOCK_FILE) as lock_file:
706 try:
707 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
708 yield True
709 fcntl.flock(lock_file, fcntl.LOCK_UN)
710 break
711 except IOError:
712 current_time = datetime.datetime.now()
713 current_wait_time = (current_time - start_time).total_seconds()
714 if timeout and current_wait_time > timeout:
715 yield False
716 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700717 # Sleep random amount.
718 sleep_time = time.sleep(random.random())
Kevin Chengc49494e2016-07-25 12:13:38 -0700719
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700720 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700721 """Toggle the usb power safely.
722
723 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700724
725 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700726 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700727 timeout: Timeout to wait for blocking other servod processes, default is
728 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700729
Kevin Cheng5595b342016-09-29 15:51:01 -0700730 Returns:
731 An empty string to appease the xmlrpc gods.
732 """
733 with self._block_other_servod(timeout=timeout):
734 if power_state != self.get(self._USB_J3_PWR):
735 self.set(self._USB_J3_PWR, power_state)
736 return ''
737
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700738 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700739 """Toggle the usb direction safely.
740
741 We'll make sure we're the only servod process toggling the usbkey direction.
742
743 Args:
744 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700745 timeout: Timeout to wait for blocking other servod processes, default is
746 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700747
748 Returns:
749 An empty string to appease the xmlrpc gods.
750 """
751 with self._block_other_servod(timeout=timeout):
752 self._switch_usbkey(mux_direction)
753 return ''
754
755 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700756 """Probe the USB disk device plugged in the servo from the host side.
757
758 Method can fail by:
759 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700760 another servo unless _USB_LOCK_FILE exists on the servo host. If that
761 file exists, then it is safe to probe for usb devices among multiple
762 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700763 2) Finding multiple /dev/sdX and returning None.
764
Kevin Cheng5595b342016-09-29 15:51:01 -0700765 Args:
766 timeout: Timeout to wait for blocking other servod processes.
767
Simran Basia9f41032012-05-11 14:21:58 -0700768 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700769 USB disk path if one and only one USB disk path is found, otherwise an
770 empty string.
Simran Basia9f41032012-05-11 14:21:58 -0700771 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700772 with self._block_other_servod(timeout=timeout) as block_success:
773 if not block_success:
774 return ''
Kevin Chengc49494e2016-07-25 12:13:38 -0700775
Kevin Cheng5595b342016-09-29 15:51:01 -0700776 original_value = self.get(self._USB_J3)
777 original_usb_power = self.get(self._USB_J3_PWR)
778 # Make the host unable to see the USB disk.
779 if (original_usb_power == self._USB_J3_PWR_ON and
780 original_value != self._USB_J3_TO_DUT):
781 self._switch_usbkey(self._USB_J3_TO_DUT)
782 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700783
Kevin Cheng5595b342016-09-29 15:51:01 -0700784 # Make the host able to see the USB disk.
785 self._switch_usbkey(self._USB_J3_TO_SERVO)
786 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700787
Kevin Cheng5595b342016-09-29 15:51:01 -0700788 # Back to its original value.
789 if original_value != self._USB_J3_TO_SERVO:
790 self._switch_usbkey(original_value)
791 if original_usb_power != self._USB_J3_PWR_ON:
792 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
793 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700794
Kevin Cheng5595b342016-09-29 15:51:01 -0700795 # Subtract the two sets to find the usb device.
796 diff_set = has_usb_set - no_usb_set
797 if len(diff_set) == 1:
798 return diff_set.pop()
799 else:
800 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700801
Kevin Cheng85831332016-10-13 13:14:44 -0700802 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700803 """Download image and save to the USB device found by probe_host_usb_dev.
804 If the image_path is a URL, it will download this url to the USB path;
805 otherwise it will simply copy the image_path's contents to the USB path.
806
807 Args:
808 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700809 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700810
811 Returns:
812 True|False: True if process completed successfully, False if error
813 occurred.
814 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
815 comment at the end of set().
816 """
817 self._logger.debug("image_path(%s)" % image_path)
818 self._logger.debug("Detecting USB stick device...")
Kevin Cheng85831332016-10-13 13:14:44 -0700819 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700820 if not usb_dev:
821 self._logger.error("No usb device connected to servo")
822 return False
823
Kevin Cheng9071ed92016-06-21 14:37:54 -0700824 # Let's check if we downloaded this last time and if so assume the image is
825 # still on the usb device and return True.
826 if self._image_path == image_path:
827 self._logger.debug("Image already on USB device, skipping transfer")
828 return True
829
Simran Basia9f41032012-05-11 14:21:58 -0700830 try:
831 if image_path.startswith(self._HTTP_PREFIX):
832 self._logger.debug("Image path is a URL, downloading image")
833 urllib.urlretrieve(image_path, usb_dev)
834 else:
835 shutil.copyfile(image_path, usb_dev)
836 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700837 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700838 e.strerror, e.errno)
839 return False
840 except urllib.ContentTooShortError:
841 self._logger.error("Failed to download URL: %s to USB device: %s",
842 image_path, usb_dev)
843 return False
844 except BaseException as e:
845 self._logger.error("Unexpected exception downloading %s to %s: %s",
846 image_path, usb_dev, str(e))
847 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800848 finally:
849 # We just plastered the partition table for a block device.
850 # Pass or fail, we mustn't go without telling the kernel about
851 # the change, or it will punish us with sporadic, hard-to-debug
852 # failures.
853 subprocess.call(["sync"])
854 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700855 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700856 return True
857
858 def make_image_noninteractive(self):
859 """Makes the recovery image noninteractive.
860
861 A noninteractive image will reboot automatically after installation
862 instead of waiting for the USB device to be removed to initiate a system
863 reboot.
864
865 Mounts partition 1 of the image stored on usb_dev and creates a file
866 called "non_interactive" so that the image will become noninteractive.
867
868 Returns:
869 True|False: True if process completed successfully, False if error
870 occurred.
871 """
872 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700873 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700874 if not usb_dev:
875 self._logger.error("No usb device connected to servo")
876 return False
877 # Create TempDirectory
878 tmpdir = tempfile.mkdtemp()
879 if tmpdir:
880 # Mount drive to tmpdir.
881 partition_1 = "%s1" % usb_dev
882 rc = subprocess.call(["mount", partition_1, tmpdir])
883 if rc == 0:
884 # Create file 'non_interactive'
885 non_interactive_file = os.path.join(tmpdir, "non_interactive")
886 try:
887 open(non_interactive_file, "w").close()
888 except IOError as e:
889 self._logger.error("Failed to create file %s : %s ( %d )",
890 non_interactive_file, e.strerror, e.errno)
891 result = False
892 except BaseException as e:
893 self._logger.error("Unexpected Exception creating file %s : %s",
894 non_interactive_file, str(e))
895 result = False
896 # Unmount drive regardless if file creation worked or not.
897 rc = subprocess.call(["umount", partition_1])
898 if rc != 0:
899 self._logger.error("Failed to unmount USB Device")
900 result = False
901 else:
902 self._logger.error("Failed to mount USB Device")
903 result = False
904
905 # Delete tmpdir. May throw exception if 'umount' failed.
906 try:
907 os.rmdir(tmpdir)
908 except OSError as e:
909 self._logger.error("Failed to remove temp directory %s : %s",
910 tmpdir, str(e))
911 return False
912 except BaseException as e:
913 self._logger.error("Unexpected Exception removing tempdir %s : %s",
914 tmpdir, str(e))
915 return False
916 else:
917 self._logger.error("Failed to create temp directory.")
918 return False
919 return result
920
Todd Broch352b4b22013-03-22 09:48:40 -0700921 def set_get_all(self, cmds):
922 """Set &| get one or more control values.
923
924 Args:
925 cmds: list of control[:value] to get or set.
926
927 Returns:
928 rv: list of responses from calling get or set methods.
929 """
930 rv = []
931 for cmd in cmds:
932 if ':' in cmd:
933 (control, value) = cmd.split(':')
934 rv.append(self.set(control, value))
935 else:
936 rv.append(self.get(cmd))
937 return rv
938
Aseda Aboagye6921f602017-08-01 14:45:38 -0700939 def get_serial_number(self, name):
940 """Returns the desired serial number from the serialnames dict.
941
942 Args:
943 name: A string which is the key into the _serialnames dictionary.
944
945 Returns:
946 A string containing the serial number or "unknown".
947 """
948 if not name:
949 name = 'main'
950
951 try:
952 return self._serialnames[name]
953 except KeyError:
954 self._logger.debug("'%s_serialname' not found!", name)
955 return "unknown"
956
Todd Broche505b8d2011-03-21 18:19:54 -0700957 def get(self, name):
958 """Get control value.
959
960 Args:
961 name: name string of control
962
963 Returns:
964 Response from calling drv get method. Value is reformatted based on
965 control's dictionary parameters
966
967 Raises:
968 HwDriverError: Error occurred while using drv
969 """
970 self._logger.debug("name(%s)" % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700971 # This route is to retrieve serialnames on servo v4, which
972 # connects to multiple servo-micros or CCD, like the controls,
973 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
974 # TODO(aaboagye): Refactor it.
975 if 'serialname' in name:
976 return self.get_serial_number(name.split('serialname')[0].strip('_'))
977
Todd Broche505b8d2011-03-21 18:19:54 -0700978 (param, drv) = self._get_param_drv(name)
979 try:
980 val = drv.get()
981 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800982 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700983 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700984 except AttributeError, error:
985 self._logger.error("Getting %s: %s" % (name, error))
986 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800987 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700988 self._logger.error("Getting %s" % (name))
989 raise
Todd Brochd6061672012-05-11 15:52:47 -0700990
Todd Broche505b8d2011-03-21 18:19:54 -0700991 def get_all(self, verbose):
992 """Get all controls values.
993
994 Args:
995 verbose: Boolean on whether to return doc info as well
996
997 Returns:
998 string creating from trying to get all values of all controls. In case of
999 error attempting access to control, response is 'ERR'.
1000 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -08001001 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -07001002 for name in self._syscfg.syscfg_dict['control']:
1003 self._logger.debug("name = %s" %name)
1004 try:
1005 value = self.get(name)
1006 except Exception:
1007 value = "ERR"
1008 pass
1009 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -08001010 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -07001011 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -08001012 rsp.append("%s:%s" % (name, value))
1013 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -07001014
1015 def set(self, name, wr_val_str):
1016 """Set control.
1017
1018 Args:
1019 name: name string of control
1020 wr_val_str: value string to write. Can be integer, float or a
1021 alpha-numerical that is mapped to a integer or float.
1022
1023 Raises:
1024 HwDriverError: Error occurred while using driver
1025 """
1026 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
1027 (params, drv) = self._get_param_drv(name, False)
1028 wr_val = self._syscfg.resolve_val(params, wr_val_str)
1029 try:
1030 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +08001031 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -07001032 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
1033 raise
1034 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
1035 # & client I still have to return something to appease the
1036 # marshall/unmarshall
1037 return True
1038
Todd Brochd6061672012-05-11 15:52:47 -07001039 def hwinit(self, verbose=False):
1040 """Initialize all controls.
1041
1042 These values are part of the system config XML files of the form
1043 init=<value>. This command should be used by clients wishing to return the
1044 servo and DUT its connected to a known good/safe state.
1045
Vadim Bendeburybb51dd42013-01-31 13:47:46 -08001046 Note that initialization errors are ignored (as in some cases they could
1047 be caused by DUT firmware deficiencies). This might need to be fine tuned
1048 later.
1049
Todd Brochd6061672012-05-11 15:52:47 -07001050 Args:
1051 verbose: boolean, if True prints info about control initialized.
1052 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001053
1054 Returns:
1055 This function is called across RPC and as such is expected to return
1056 something unless transferring 'none' across is allowed. Hence adding a
1057 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -07001058 """
Todd Brochd9acf0a2012-12-05 13:43:06 -08001059 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -08001060 try:
John Carey6fe2bbf2015-08-31 16:13:03 -07001061 # Workaround for bug chrome-os-partner:42349. Without this check, the
1062 # gpio will briefly pulse low if we set it from high to high.
1063 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -07001064 self.set(control_name, value)
1065 if verbose:
1066 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -08001067 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -08001068 self._logger.error("Problem initializing %s -> %s :: %s",
1069 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -08001070
1071 # Init keyboard after all the intefaces are up.
1072 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001073 return True
Todd Broch3ec8df02012-11-20 10:53:03 -08001074
Dino Lic89d8c82018-01-11 09:56:47 +08001075 def ftdii2c(self, args):
1076 """Calling a method of Fi2c."""
1077 index = self._interfaces.index('ftdi_i2c')
1078 if index:
1079 obj = self._interface_list[index]
1080 func = getattr(obj, '%s' % args[0])
1081 func()
1082 return True
1083
1084 return False
1085
Todd Broche505b8d2011-03-21 18:19:54 -07001086 def echo(self, echo):
1087 """Dummy echo function for testing/examples.
1088
1089 Args:
1090 echo: string to echo back to client
1091 """
1092 self._logger.debug("echo(%s)" % (echo))
1093 return "ECH0ING: %s" % (echo)
1094
J. Richard Barnettee2820552013-03-14 16:13:46 -07001095 def get_board(self):
1096 """Return the board specified at startup, if any."""
1097 return self._board
1098
Wai-Hong Tam416cf612017-09-19 11:39:21 -07001099 def get_base_board(self):
1100 """Returns the board name of the base if present.
1101
1102 Returns:
1103 A string of the board name, or '' if not present.
1104 """
1105 # The value is set in servo_postinit.
1106 return self._base_board
1107
Simran Basia23c1392013-08-06 14:59:10 -07001108 def get_version(self):
1109 """Get servo board version."""
1110 return self._version
1111
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001112 def power_long_press(self):
1113 """Simulate a long power button press."""
1114 # After a long power press, the EC may ignore the next power
1115 # button press (at least on Alex). To guarantee that this
1116 # won't happen, we need to allow the EC one second to
1117 # collect itself.
1118 self._keyboard.power_long_press()
1119 return True
1120
1121 def power_normal_press(self):
1122 """Simulate a normal power button press."""
1123 self._keyboard.power_normal_press()
1124 return True
1125
1126 def power_short_press(self):
1127 """Simulate a short power button press."""
1128 self._keyboard.power_short_press()
1129 return True
1130
1131 def power_key(self, secs=''):
1132 """Simulate a power button press.
1133
1134 Args:
1135 secs: Time in seconds to simulate the keypress.
1136 """
1137 self._keyboard.power_key(secs)
1138 return True
1139
1140 def ctrl_d(self, press_secs=''):
1141 """Simulate Ctrl-d simultaneous button presses."""
1142 self._keyboard.ctrl_d(press_secs)
1143 return True
1144
Victor Dodone539cea2016-03-29 18:50:17 -07001145 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001146 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001147 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001148 return True
1149
1150 def ctrl_enter(self, press_secs=''):
1151 """Simulate Ctrl-enter simultaneous button presses."""
1152 self._keyboard.ctrl_enter(press_secs)
1153 return True
1154
1155 def d_key(self, press_secs=''):
1156 """Simulate Enter key button press."""
1157 self._keyboard.d_key(press_secs)
1158 return True
1159
1160 def ctrl_key(self, press_secs=''):
1161 """Simulate Enter key button press."""
1162 self._keyboard.ctrl_key(press_secs)
1163 return True
1164
1165 def enter_key(self, press_secs=''):
1166 """Simulate Enter key button press."""
1167 self._keyboard.enter_key(press_secs)
1168 return True
1169
1170 def refresh_key(self, press_secs=''):
1171 """Simulate Refresh key (F3) button press."""
1172 self._keyboard.refresh_key(press_secs)
1173 return True
1174
1175 def ctrl_refresh_key(self, press_secs=''):
1176 """Simulate Ctrl and Refresh (F3) simultaneous press.
1177
1178 This key combination is an alternative of Space key.
1179 """
1180 self._keyboard.ctrl_refresh_key(press_secs)
1181 return True
1182
1183 def imaginary_key(self, press_secs=''):
1184 """Simulate imaginary key button press.
1185
1186 Maps to a key that doesn't physically exist.
1187 """
1188 self._keyboard.imaginary_key(press_secs)
1189 return True
1190
Todd Brochdbb09982011-10-02 07:14:26 -07001191
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001192 def sysrq_x(self, press_secs=''):
1193 """Simulate Alt VolumeUp X simultaneous press.
1194
1195 This key combination is the kernel system request (sysrq) x.
1196 """
1197 self._keyboard.sysrq_x(press_secs)
1198 return True
1199
1200
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001201 def get_servo_serials(self):
1202 """Return all the serials associated with this process."""
1203 return self._serialnames
1204
1205
Todd Broche505b8d2011-03-21 18:19:54 -07001206def test():
1207 """Integration testing.
1208
1209 TODO(tbroch) Enhance integration test and add unittest (see mox)
1210 """
1211 logging.basicConfig(level=logging.DEBUG,
1212 format="%(asctime)s - %(name)s - " +
1213 "%(levelname)s - %(message)s")
1214 # configure server & listen
1215 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -07001216 # 5 == number of interfaces on a FT4232H device
1217 for i in xrange(1, 5):
1218 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -07001219 # its an i2c interface ... see __init__ for details and TODO to make
1220 # this configureable
1221 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1222 else:
1223 # its a gpio interface
1224 servod_obj._interface_list[i].wr_rd(0)
1225
1226 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1227 allow_none=True)
1228 server.register_introspection_functions()
1229 server.register_multicall_functions()
1230 server.register_instance(servod_obj)
1231 logging.info("Listening on localhost port 9999")
1232 server.serve_forever()
1233
1234if __name__ == "__main__":
1235 test()
1236
1237 # simple client transaction would look like
1238 """
1239 remote_uri = 'http://localhost:9999'
1240 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1241 send_str = "Hello_there"
1242 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1243 """