blob: e8295253cc296000b735b6cbd125f1935ca33ed7 [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 Chengc49494e2016-07-25 12:13:38 -07005import datetime
6import fcntl
Simran Basia9f41032012-05-11 14:21:58 -07007import fnmatch
Todd Broche505b8d2011-03-21 18:19:54 -07008import logging
Simran Basia9f41032012-05-11 14:21:58 -07009import os
Aseda Aboagye1d8477b2017-05-10 17:24:31 -070010import re
Simran Basia9f41032012-05-11 14:21:58 -070011import shutil
Todd Broche505b8d2011-03-21 18:19:54 -070012import SimpleXMLRPCServer
Simran Basia9f41032012-05-11 14:21:58 -070013import subprocess
14import tempfile
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080015import threading
Todd Broch7a91c252012-02-03 12:37:45 -080016import time
Simran Basia9f41032012-05-11 14:21:58 -070017import urllib
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070018import usb
Todd Broche505b8d2011-03-21 18:19:54 -070019
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080020import drv as servo_drv
Aaron.Chuang88eff332014-07-31 08:32:00 +080021import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070022import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070023import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070024import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080025import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070026import ftdigpio
27import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070028import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070029import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080030import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080031import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070032import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070033import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080034import stm32gpio
35import stm32i2c
36import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070037
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080038HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080039
Todd Broche505b8d2011-03-21 18:19:54 -070040MAX_I2C_CLOCK_HZ = 100000
41
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070042
Todd Broche505b8d2011-03-21 18:19:54 -070043class ServodError(Exception):
44 """Exception class for servod."""
45
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070046
Todd Broche505b8d2011-03-21 18:19:54 -070047class Servod(object):
48 """Main class for Servo debug/controller Daemon."""
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070049 _HTTP_PREFIX = 'http://'
Simran Basia9f41032012-05-11 14:21:58 -070050
Kevin Cheng4b4f0022016-09-09 02:37:07 -070051 # This is the key to get the main serial used in the _serialnames dict.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070052 MAIN_SERIAL = 'main'
53 SERVO_MICRO_SERIAL = 'servo_micro'
54 CCD_SERIAL = 'ccd'
Kevin Cheng4b4f0022016-09-09 02:37:07 -070055
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080056 # Timeout to wait for interfaces to become available again if reinitialization
57 # is taking place. In seconds.
58 INTERFACE_AVAILABILITY_TIMEOUT = 60
59
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070060 def init_servo_interfaces(self, vendor, product, serialname, interfaces):
Kevin Chengdc3befd2016-07-15 12:34:00 -070061 """Init the servo interfaces with the given interfaces.
62
63 We don't use the self._{vendor,product,serialname} attributes because we
64 want to allow other callers to initialize other interfaces that may not
65 be associated with the initialized attributes (e.g. a servo v4 servod object
66 that wants to also initialize a servo micro interface).
67
68 Args:
69 vendor: USB vendor id of FTDI device.
70 product: USB product id of FTDI device.
71 serialname: String of device serialname/number as defined in FTDI
72 eeprom.
73 interfaces: List of strings of interface types the server will
74 instantiate.
75
76 Raises:
77 ServodError if unable to locate init method for particular interface.
78 """
Mary Ruthven13389642017-02-14 12:15:34 -080079 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070080 device = (vendor, product, serialname)
Mary Ruthven13389642017-02-14 12:15:34 -080081 if device not in self._devices:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070082 self._devices.append(device)
Mary Ruthven13389642017-02-14 12:15:34 -080083
Kevin Chengdc3befd2016-07-15 12:34:00 -070084 # Extend the interface list if we need to.
85 interfaces_len = len(interfaces)
86 interface_list_len = len(self._interface_list)
87 if interfaces_len > interface_list_len:
88 self._interface_list += [None] * (interfaces_len - interface_list_len)
89
Kevin Chengdc3befd2016-07-15 12:34:00 -070090 for i, interface in enumerate(interfaces):
91 is_ftdi_interface = False
92 if type(interface) is dict:
93 name = interface['name']
94 # Store interface index for those that care about it.
95 interface['index'] = i
96 elif type(interface) is str and interface != 'dummy':
97 name = interface
Wai-Hong Tam564c1702017-04-24 09:23:38 -070098 # It's a FTDI related interface. #0 is reserved for no use.
99 interface = ((i - 1) % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
Kevin Chengdc3befd2016-07-15 12:34:00 -0700100 is_ftdi_interface = True
101 elif type(interface) is str and interface == 'dummy':
102 # 'dummy' reserves the interface for future use. Typically the
103 # interface will be managed by external third-party tools like
104 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
105 # it serves as a placeholder for servo micro interfaces.
106 continue
107 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700108 raise ServodError('Illegal interface type %s' % type(interface))
Kevin Chengdc3befd2016-07-15 12:34:00 -0700109
110 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700111 product_increment = 0
112 if is_ftdi_interface:
113 product_increment = (i - 1) / ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE
114 if product_increment:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700115 self._logger.info('Use the next FTDI part @ pid = 0x%04x',
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700116 product + product_increment)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700117
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700118 self._logger.info('Initializing interface %d to %s', i, name)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700119 try:
120 func = getattr(self, '_init_%s' % name)
121 except AttributeError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700122 raise ServodError('Unable to locate init for interface %s' % name)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700123 result = func(vendor, product + product_increment, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700124
125 if isinstance(result, tuple):
126 result_len = len(result)
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700127 self._interface_list[i:(i + result_len)] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700128 else:
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700129 self._interface_list[i] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700130
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700131 def __init__(self, config, vendor, product, serialname=None, interfaces=None,
132 board='', version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700133 """Servod constructor.
134
135 Args:
136 config: instance of SystemConfig containing all controls for
137 particular Servod invocation
138 vendor: usb vendor id of FTDI device
139 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700140 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700141 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700142 version: String. Servo board version. Examples: servo_v1, servo_v2,
143 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800144 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700145 sending keyboard commands to DUTs that do not have built in
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700146 keyboards. Used in FAFT tests. Use None for on board AVR MCU.
147 e.g. '/dev/ttyUSB0' or None.
Todd Brochdbb09982011-10-02 07:14:26 -0700148
149 Raises:
150 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700151 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700152 self._logger = logging.getLogger('Servod')
153 self._logger.debug('')
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800154 self._ifaces_available = threading.Event()
155 # Initially interfaces should be available.
156 self._ifaces_available.set()
Todd Broche505b8d2011-03-21 18:19:54 -0700157 self._vendor = vendor
158 self._product = product
Mary Ruthven13389642017-02-14 12:15:34 -0800159 self._devices = []
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700160 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700161 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700162 # Hold the last image path so we can reduce downloads to the usb device.
163 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700164 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
165 # interfaces are mapped to
166 self._interface_list = []
167 # Dict of Dict to map control name, function name to to tuple (params, drv)
168 # Ex) _drv_dict[name]['get'] = (params, drv)
169 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700170 self._board = board
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700171 self._base_board = ''
Simran Basia23c1392013-08-06 14:59:10 -0700172 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800173 self._usbkm232 = usbkm232
Todd Brochdbb09982011-10-02 07:14:26 -0700174 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700175 try:
176 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
177 except KeyError:
178 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Dino Lic89d8c82018-01-11 09:56:47 +0800179 self._interfaces = interfaces
Todd Brochdbb09982011-10-02 07:14:26 -0700180
Kevin Chengdc3befd2016-07-15 12:34:00 -0700181 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700182 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800183
Mary Ruthven13389642017-02-14 12:15:34 -0800184 def reinitialize(self):
185 """Reinitialize all interfaces that support reinitialization"""
Mary Ruthven13389642017-02-14 12:15:34 -0800186 for i, interface in enumerate(self._interface_list):
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700187 if hasattr(interface, 'reinitialize'):
188 interface.reinitialize()
189 else:
190 self._logger.debug('interface %d has no reset functionality', i)
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800191 # Indicate interfaces are safe to use again.
192 self._ifaces_available.set()
Mary Ruthven13389642017-02-14 12:15:34 -0800193
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700194 def get_servo_interfaces(self, position, size):
195 """Get the list of servo interfaces.
196
197 Args:
198 position: The index the first interface to get.
199 size: The number of the interfaces.
200 """
201 return self._interface_list[position:(position + size)]
202
203 def set_servo_interfaces(self, position, interfaces):
204 """Set the list of servo interfaces.
205
206 Args:
207 position: The index the first interface to set.
208 interfaces: The list of interfaces to set.
209 """
210 size = len(interfaces)
211 self._interface_list[position:(position + size)] = interfaces
212
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800213 def _init_keyboard_handler(self, servo, board=''):
214 """Initialize the correct keyboard handler for board.
215
Kevin Chengdc3befd2016-07-15 12:34:00 -0700216 Args:
217 servo: servo object.
218 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800219
Kevin Chengdc3befd2016-07-15 12:34:00 -0700220 Returns:
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700221 keyboard handler object, or None if no keyboard supported.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800222 """
223 if board == 'parrot':
224 return keyboard_handlers.ParrotHandler(servo)
225 elif board == 'stout':
226 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800227 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700228 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy', 'sumo',
229 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
Shelley Chen94cd2352017-07-26 11:36:45 -0700230 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800231 if self._usbkm232 is None:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700232 logging.info('No device path specified for usbkm232 handler. Use '
233 'the servo atmega chip to handle.')
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700234
Danny Chan662b6022015-11-04 17:34:53 -0800235 # Use servo onboard keyboard emulator.
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700236 if not self._syscfg.is_control('atmega_rst'):
237 logging.warn('No atmega in servo board. So no keyboard support.')
238 return None
239
Nick Sanders78423782015-11-09 14:28:19 -0800240 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800241 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800242 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800243 self._usbkm232 = self.get('atmega_pty')
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700244
Kevin Cheng810fc782016-11-01 12:36:46 -0700245 # We don't need to set the atmega uart settings if we're a servo v4.
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700246 if 'servo_v4' not in self._version:
Kevin Cheng810fc782016-11-01 12:36:46 -0700247 self.set('atmega_baudrate', '9600')
248 self.set('atmega_bits', 'eight')
249 self.set('atmega_parity', 'none')
250 self.set('atmega_sbits', 'one')
251 self.set('usb_mux_sel4', 'on')
252 self.set('usb_mux_oe4', 'on')
253 # Allow atmega bootup time.
254 time.sleep(1.0)
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700255
Danny Chan662b6022015-11-04 17:34:53 -0800256 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800257 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
258 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800259 # The following boards don't use Chrome EC.
260 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
261 return keyboard_handlers.MatrixKeyboardHandler(servo)
262 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800263
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700264 def close(self):
265 """Servod turn down logic."""
266 for i, interface in enumerate(self._interface_list):
267 self._logger.info('Turning down interface %d' % i)
268 if hasattr(interface, 'close'):
269 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800270
Kevin Chengdc3befd2016-07-15 12:34:00 -0700271 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700272 """Dummy interface for ftdi devices.
273
274 This is a dummy function specifically for ftdi devices to not initialize
275 anything but to help pad the interface list.
276
277 Returns:
278 None.
279 """
280 return None
281
Kevin Chengdc3befd2016-07-15 12:34:00 -0700282 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700283 """Initialize gpio driver interface and open for use.
284
285 Args:
286 interface: interface number of FTDI device to use.
287
288 Returns:
289 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700290
291 Raises:
292 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700293 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700294 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700295 try:
296 fobj.open()
297 except ftdigpio.FgpioError as e:
298 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
299
Todd Broche505b8d2011-03-21 18:19:54 -0700300 return fobj
301
Kevin Chengdc3befd2016-07-15 12:34:00 -0700302 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800303 """Initialize stm32 uart interface and open for use
304
305 Note, the uart runs in a separate thread. Users wishing to
306 interact with it will query control for the pty's pathname and connect
307 with their favorite console program. For example:
308 cu -l /dev/pts/22
309
310 Args:
311 interface: dict of interface parameters.
312
313 Returns:
314 Instance object of interface
315
316 Raises:
317 ServodError: Raised on init failure.
318 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700319 self._logger.info('Suart: interface: %s' % interface)
320 sobj = stm32uart.Suart(vendor, product, interface['interface'], serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800321
322 try:
323 sobj.run()
324 except stm32uart.SuartError as e:
325 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
326
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700327 self._logger.info('%s' % sobj.get_pty())
Nick Sanders97bc4462016-01-04 15:37:31 -0800328 return sobj
329
Kevin Chengdc3befd2016-07-15 12:34:00 -0700330 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800331 """Initialize stm32 gpio interface.
332 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700333 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800334
335 Returns:
336 Instance object of interface
337
338 Raises:
339 SgpioError: Raised on init failure.
340 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700341 interface_number = interface
342 # Interface could be a dict.
343 if type(interface) is dict:
344 interface_number = interface['interface']
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700345 self._logger.info('Sgpio: interface: %s' % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700346 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800347
Kevin Chengdc3befd2016-07-15 12:34:00 -0700348 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800349 """Initialize stm32 USB to I2C bridge interface and open for use
350
351 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700352 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800353
354 Returns:
355 Instance object of interface.
356
357 Raises:
358 Si2cError: Raised on init failure.
359 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700360 self._logger.info('Si2cBus: interface: %s' % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800361 port = interface.get('port', 0)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700362 return stm32i2c.Si2cBus(vendor, product, interface['interface'], port=port,
363 serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800364
Kevin Chengdc3befd2016-07-15 12:34:00 -0700365 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800366 """Initalize beaglebone ADC interface."""
367 return bbadc.BBadc()
368
Kevin Chengdc3befd2016-07-15 12:34:00 -0700369 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700370 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700371 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700372
Kevin Chengdc3befd2016-07-15 12:34:00 -0700373 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700374 """Initialize i2c interface and open for use.
375
376 Args:
377 interface: interface number of FTDI device to use
378
379 Returns:
380 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700381
382 Raises:
383 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700384 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700385 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700386 try:
387 fobj.open()
388 except ftdii2c.Fi2cError as e:
389 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
390
Todd Broche505b8d2011-03-21 18:19:54 -0700391 # Set the frequency of operation of the i2c bus.
392 # TODO(tbroch) make configureable
393 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700394
Todd Broche505b8d2011-03-21 18:19:54 -0700395 return fobj
396
Simran Basie750a342013-03-12 13:45:26 -0700397 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
398 def _init_bb_i2c(self, interface):
399 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700400 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700401
Kevin Chengdc3befd2016-07-15 12:34:00 -0700402 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800403 """Initalize Linux i2c-dev interface."""
404 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
405
Kevin Chengdc3befd2016-07-15 12:34:00 -0700406 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700407 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700408
409 Note, the uart runs in a separate thread (pthreads). Users wishing to
410 interact with it will query control for the pty's pathname and connect
411 with there favorite console program. For example:
412 cu -l /dev/pts/22
413
414 Args:
415 interface: interface number of FTDI device to use
416
417 Returns:
418 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700419
420 Raises:
421 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700422 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700423 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700424 try:
425 fobj.run()
426 except ftdiuart.FuartError as e:
427 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
428
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700429 self._logger.info('%s' % fobj.get_pty())
Todd Broch47c43f42011-05-26 15:11:31 -0700430 return fobj
431
Simran Basie750a342013-03-12 13:45:26 -0700432 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700433 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700434 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700435 logging.debug('UART INTERFACE: %s', interface)
436 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700437
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700438 def _init_ftdi_gpiouart(self, vendor, product, serialname, interface):
Todd Broch888da782011-10-07 14:29:09 -0700439 """Initialize special gpio + uart interface and open for use
440
441 Note, the uart runs in a separate thread (pthreads). Users wishing to
442 interact with it will query control for the pty's pathname and connect
443 with there favorite console program. For example:
444 cu -l /dev/pts/22
445
446 Args:
447 interface: interface number of FTDI device to use
448
449 Returns:
450 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700451
452 Raises:
453 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700454 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700455 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700456 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700457 try:
458 fuart.run()
459 except ftdiuart.FuartError as e:
460 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
461
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700462 self._logger.info('uart pty: %s' % fuart.get_pty())
Todd Broch888da782011-10-07 14:29:09 -0700463 return fgpio, fuart
464
Kevin Chengdc3befd2016-07-15 12:34:00 -0700465 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800466 """Initialize EC-3PO console interpreter interface.
467
468 Args:
469 interface: A dictionary representing the interface.
470
471 Returns:
472 An EC3PO object representing the EC-3PO interface or None if there's no
473 interface for the USB PD UART.
474 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700475 raw_uart_name = interface['raw_pty']
Nick Sanders116ed9e2018-03-09 19:05:16 -0800476 raw_uart_source = interface['source']
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700477 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800478 raw_ec_uart = self.get(raw_uart_name)
Nick Sanders116ed9e2018-03-09 19:05:16 -0800479 return ec3po_interface.EC3PO(raw_ec_uart, raw_uart_source)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800480 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700481 # The overlay doesn't have the raw PTY defined, therefore we can skip
482 # initializing this interface since no control relies on it.
483 self._logger.debug(
484 'Skip initializing EC3PO for %s, no control specified.',
485 raw_uart_name)
486 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800487
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800488 def _camel_case(self, string):
489 output = ''
490 for s in string.split('_'):
491 if output:
492 output += s.capitalize()
493 else:
494 output = s
495 return output
496
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700497 def clear_cached_drv(self):
498 """Clear the cached drivers.
499
500 The drivers are cached in the Dict _drv_dict when a control is got or set.
501 When the servo interfaces are relocated, the cached values may become wrong.
502 Should call this method to clear the cached values.
503 """
504 self._drv_dict = {}
505
Todd Broche505b8d2011-03-21 18:19:54 -0700506 def _get_param_drv(self, control_name, is_get=True):
507 """Get access to driver for a given control.
508
509 Note, some controls have different parameter dictionaries for 'getting' the
510 control's value versus 'setting' it. Boolean is_get distinguishes which is
511 being requested.
512
513 Args:
514 control_name: string name of control
515 is_get: boolean to determine
516
517 Returns:
518 tuple (param, drv) where:
519 param: param dictionary for control
520 drv: instance object of driver for particular control
521
522 Raises:
523 ServodError: Error occurred while examining params dict
524 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700525 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700526 # if already setup just return tuple from driver dict
527 if control_name in self._drv_dict:
528 if is_get and ('get' in self._drv_dict[control_name]):
529 return self._drv_dict[control_name]['get']
530 if not is_get and ('set' in self._drv_dict[control_name]):
531 return self._drv_dict[control_name]['set']
532
533 params = self._syscfg.lookup_control_params(control_name, is_get)
534 if 'drv' not in params:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700535 self._logger.error('Unable to determine driver for %s' % control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700536 raise ServodError("'drv' key not found in params dict")
537 if 'interface' not in params:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700538 self._logger.error('Unable to determine interface for %s' % control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700539 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700540
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700541 # Find the candidate servos. Using servo_v4 with a servo_micro connected as
542 # an example, the following shows the priority for selecting the interface.
543 #
544 # 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
545 # 2. servo_micro_interface
546 # 3. servo_v4_interface
547 # 4. Fallback to the default, interface.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700548 candidates = [self._version]
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700549 candidates.extend(reversed(self._version.split('_with_')))
550
551 interface_id = 'unknown'
552 for c in candidates:
553 interface_name = '%s_interface' % c
554 if interface_name in params:
555 interface_id = params[interface_name]
556 self._logger.debug('Using %s parameter.' % interface_name)
557 break
558
559 # Use the default interface value if we couldn't find a more specific
560 # interface.
561 if interface_id == 'unknown':
562 interface_id = params['interface']
563 self._logger.debug('Using default interface parameter.')
564
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800565 if interface_id == 'servo':
566 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700567 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700568 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800569 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700570
Todd Broche505b8d2011-03-21 18:19:54 -0700571 drv_name = params['drv']
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800572 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800573 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700574 drv = drv_class(interface, params)
575 if control_name not in self._drv_dict:
576 self._drv_dict[control_name] = {}
577 if is_get:
578 self._drv_dict[control_name]['get'] = (params, drv)
579 else:
580 self._drv_dict[control_name]['set'] = (params, drv)
581 return (params, drv)
582
583 def doc_all(self):
584 """Return all documenation for controls.
585
586 Returns:
587 string of <doc> text in config file (xml) and the params dictionary for
588 all controls.
589
590 For example:
591 warm_reset :: Reset the device warmly
592 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
593 """
594 return self._syscfg.display_config()
595
596 def doc(self, name):
597 """Retreive doc string in system config file for given control name.
598
599 Args:
600 name: name string of control to get doc string
601
602 Returns:
603 doc string of name
604
605 Raises:
606 NameError: if fails to locate control
607 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700608 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700609 if self._syscfg.is_control(name):
610 return self._syscfg.get_control_docstring(name)
611 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700612 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700613
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800614 def safe_switch_usbkey_power(self, power_state, _=None):
Kevin Cheng5595b342016-09-29 15:51:01 -0700615 """Toggle the usb power safely.
616
Kevin Chengc49494e2016-07-25 12:13:38 -0700617 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700618 power_state: The setting to set for the usbkey power.
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800619 _: to conform to current API
Kevin Chengc49494e2016-07-25 12:13:38 -0700620
Kevin Cheng5595b342016-09-29 15:51:01 -0700621 Returns:
622 An empty string to appease the xmlrpc gods.
623 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800624 self.set('image_usbkey_pwr', power_state)
Kevin Cheng5595b342016-09-29 15:51:01 -0700625 return ''
626
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800627 def safe_switch_usbkey(self, mux_direction, _=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700628 """Toggle the usb direction safely.
629
Kevin Cheng5595b342016-09-29 15:51:01 -0700630 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800631 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800632 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700633
634 Returns:
635 An empty string to appease the xmlrpc gods.
636 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800637 self.set('image_usbkey_direction', mux_direction)
Kevin Cheng5595b342016-09-29 15:51:01 -0700638 return ''
639
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800640 def probe_host_usb_dev(self, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700641 """Probe the USB disk device plugged in the servo from the host side.
642
Kevin Cheng5595b342016-09-29 15:51:01 -0700643 Args:
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800644 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700645
Simran Basia9f41032012-05-11 14:21:58 -0700646 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700647 USB disk path if one and only one USB disk path is found, otherwise an
Simran Basia9f41032012-05-11 14:21:58 -0700648 """
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800649 return self.get('image_usbkey_dev')
Kevin Chengc49494e2016-07-25 12:13:38 -0700650
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800651 def download_image_to_usb(self, image_path, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700652 """Download image and save to the USB device found by probe_host_usb_dev.
653 If the image_path is a URL, it will download this url to the USB path;
654 otherwise it will simply copy the image_path's contents to the USB path.
655
656 Args:
657 image_path: path or url to the recovery image.
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800658 _: to conform to current API
Simran Basia9f41032012-05-11 14:21:58 -0700659
660 Returns:
661 True|False: True if process completed successfully, False if error
662 occurred.
663 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
664 comment at the end of set().
665 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700666 self._logger.debug('image_path(%s)' % image_path)
667 self._logger.debug('Detecting USB stick device...')
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800668 usb_dev = self.get('image_usbkey_dev')
Simran Basia9f41032012-05-11 14:21:58 -0700669 if not usb_dev:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700670 self._logger.error('No usb device connected to servo')
Simran Basia9f41032012-05-11 14:21:58 -0700671 return False
672
Kevin Cheng9071ed92016-06-21 14:37:54 -0700673 # Let's check if we downloaded this last time and if so assume the image is
674 # still on the usb device and return True.
675 if self._image_path == image_path:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700676 self._logger.debug('Image already on USB device, skipping transfer')
Kevin Cheng9071ed92016-06-21 14:37:54 -0700677 return True
678
Simran Basia9f41032012-05-11 14:21:58 -0700679 try:
680 if image_path.startswith(self._HTTP_PREFIX):
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700681 self._logger.debug('Image path is a URL, downloading image')
Simran Basia9f41032012-05-11 14:21:58 -0700682 urllib.urlretrieve(image_path, usb_dev)
683 else:
684 shutil.copyfile(image_path, usb_dev)
685 except IOError as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700686 self._logger.error('Failed to transfer image to USB device: %s ( %s ) ',
Simran Basia9f41032012-05-11 14:21:58 -0700687 e.strerror, e.errno)
688 return False
689 except urllib.ContentTooShortError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700690 self._logger.error('Failed to download URL: %s to USB device: %s',
Simran Basia9f41032012-05-11 14:21:58 -0700691 image_path, usb_dev)
692 return False
693 except BaseException as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700694 self._logger.error('Unexpected exception downloading %s to %s: %s',
Simran Basia9f41032012-05-11 14:21:58 -0700695 image_path, usb_dev, str(e))
696 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800697 finally:
698 # We just plastered the partition table for a block device.
699 # Pass or fail, we mustn't go without telling the kernel about
700 # the change, or it will punish us with sporadic, hard-to-debug
701 # failures.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700702 subprocess.call(['sync'])
703 subprocess.call(['blockdev', '--rereadpt', usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700704 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700705 return True
706
707 def make_image_noninteractive(self):
708 """Makes the recovery image noninteractive.
709
710 A noninteractive image will reboot automatically after installation
711 instead of waiting for the USB device to be removed to initiate a system
712 reboot.
713
714 Mounts partition 1 of the image stored on usb_dev and creates a file
715 called "non_interactive" so that the image will become noninteractive.
716
717 Returns:
718 True|False: True if process completed successfully, False if error
719 occurred.
720 """
721 result = True
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800722 usb_dev = self.get('image_usbkey_dev')
Simran Basia9f41032012-05-11 14:21:58 -0700723 if not usb_dev:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700724 self._logger.error('No usb device connected to servo')
Simran Basia9f41032012-05-11 14:21:58 -0700725 return False
726 # Create TempDirectory
727 tmpdir = tempfile.mkdtemp()
728 if tmpdir:
729 # Mount drive to tmpdir.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700730 partition_1 = '%s1' % usb_dev
731 rc = subprocess.call(['mount', partition_1, tmpdir])
Simran Basia9f41032012-05-11 14:21:58 -0700732 if rc == 0:
733 # Create file 'non_interactive'
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700734 non_interactive_file = os.path.join(tmpdir, 'non_interactive')
Simran Basia9f41032012-05-11 14:21:58 -0700735 try:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700736 open(non_interactive_file, 'w').close()
Simran Basia9f41032012-05-11 14:21:58 -0700737 except IOError as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700738 self._logger.error('Failed to create file %s : %s ( %d )',
Simran Basia9f41032012-05-11 14:21:58 -0700739 non_interactive_file, e.strerror, e.errno)
740 result = False
741 except BaseException as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700742 self._logger.error('Unexpected Exception creating file %s : %s',
Simran Basia9f41032012-05-11 14:21:58 -0700743 non_interactive_file, str(e))
744 result = False
745 # Unmount drive regardless if file creation worked or not.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700746 rc = subprocess.call(['umount', partition_1])
Simran Basia9f41032012-05-11 14:21:58 -0700747 if rc != 0:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700748 self._logger.error('Failed to unmount USB Device')
Simran Basia9f41032012-05-11 14:21:58 -0700749 result = False
750 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700751 self._logger.error('Failed to mount USB Device')
Simran Basia9f41032012-05-11 14:21:58 -0700752 result = False
753
754 # Delete tmpdir. May throw exception if 'umount' failed.
755 try:
756 os.rmdir(tmpdir)
757 except OSError as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700758 self._logger.error('Failed to remove temp directory %s : %s', tmpdir,
759 str(e))
Simran Basia9f41032012-05-11 14:21:58 -0700760 return False
761 except BaseException as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700762 self._logger.error('Unexpected Exception removing tempdir %s : %s',
Simran Basia9f41032012-05-11 14:21:58 -0700763 tmpdir, str(e))
764 return False
765 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700766 self._logger.error('Failed to create temp directory.')
Simran Basia9f41032012-05-11 14:21:58 -0700767 return False
768 return result
769
Todd Broch352b4b22013-03-22 09:48:40 -0700770 def set_get_all(self, cmds):
771 """Set &| get one or more control values.
772
773 Args:
774 cmds: list of control[:value] to get or set.
775
776 Returns:
777 rv: list of responses from calling get or set methods.
778 """
779 rv = []
780 for cmd in cmds:
781 if ':' in cmd:
782 (control, value) = cmd.split(':')
783 rv.append(self.set(control, value))
784 else:
785 rv.append(self.get(cmd))
786 return rv
787
Aseda Aboagye6921f602017-08-01 14:45:38 -0700788 def get_serial_number(self, name):
789 """Returns the desired serial number from the serialnames dict.
790
791 Args:
792 name: A string which is the key into the _serialnames dictionary.
793
794 Returns:
795 A string containing the serial number or "unknown".
796 """
797 if not name:
798 name = 'main'
799
800 try:
801 return self._serialnames[name]
802 except KeyError:
803 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700804 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700805
Todd Broche505b8d2011-03-21 18:19:54 -0700806 def get(self, name):
807 """Get control value.
808
809 Args:
810 name: name string of control
811
812 Returns:
813 Response from calling drv get method. Value is reformatted based on
814 control's dictionary parameters
815
816 Raises:
817 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800818 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700819 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800820 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
821 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700822 self._logger.debug('name(%s)' % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700823 # This route is to retrieve serialnames on servo v4, which
824 # connects to multiple servo-micros or CCD, like the controls,
825 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
826 # TODO(aaboagye): Refactor it.
827 if 'serialname' in name:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700828 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700829
Todd Broche505b8d2011-03-21 18:19:54 -0700830 (param, drv) = self._get_param_drv(name)
831 try:
832 val = drv.get()
833 rd_val = self._syscfg.reformat_val(param, val)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700834 self._logger.debug('%s = %s' % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700835 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700836 except AttributeError, error:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700837 self._logger.error('Getting %s: %s' % (name, error))
Todd Brochfbc499d2011-06-16 16:09:58 -0700838 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800839 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700840 self._logger.error('Getting %s' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700841 raise
Todd Brochd6061672012-05-11 15:52:47 -0700842
Todd Broche505b8d2011-03-21 18:19:54 -0700843 def get_all(self, verbose):
844 """Get all controls values.
845
846 Args:
847 verbose: Boolean on whether to return doc info as well
848
849 Returns:
850 string creating from trying to get all values of all controls. In case of
851 error attempting access to control, response is 'ERR'.
852 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800853 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700854 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700855 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700856 try:
857 value = self.get(name)
858 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700859 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -0700860 pass
861 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700862 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700863 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700864 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800865 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700866
867 def set(self, name, wr_val_str):
868 """Set control.
869
870 Args:
871 name: name string of control
872 wr_val_str: value string to write. Can be integer, float or a
873 alpha-numerical that is mapped to a integer or float.
874
875 Raises:
876 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800877 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700878 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800879 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
880 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700881 self._logger.debug('name(%s) wr_val(%s)' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700882 (params, drv) = self._get_param_drv(name, False)
883 wr_val = self._syscfg.resolve_val(params, wr_val_str)
884 try:
885 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800886 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700887 self._logger.error('Setting %s -> %s' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700888 raise
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +0800889 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
890 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -0700891 # marshall/unmarshall
892 return True
893
Todd Brochd6061672012-05-11 15:52:47 -0700894 def hwinit(self, verbose=False):
895 """Initialize all controls.
896
897 These values are part of the system config XML files of the form
898 init=<value>. This command should be used by clients wishing to return the
899 servo and DUT its connected to a known good/safe state.
900
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800901 Note that initialization errors are ignored (as in some cases they could
902 be caused by DUT firmware deficiencies). This might need to be fine tuned
903 later.
904
Todd Brochd6061672012-05-11 15:52:47 -0700905 Args:
906 verbose: boolean, if True prints info about control initialized.
907 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800908
909 Returns:
910 This function is called across RPC and as such is expected to return
911 something unless transferring 'none' across is allowed. Hence adding a
912 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700913 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800914 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800915 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700916 # Workaround for bug chrome-os-partner:42349. Without this check, the
917 # gpio will briefly pulse low if we set it from high to high.
918 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700919 self.set(control_name, value)
920 if verbose:
921 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800922 except Exception as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700923 self._logger.error('Problem initializing %s -> %s :: %s', control_name,
924 value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -0800925
926 # Init keyboard after all the intefaces are up.
927 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800928 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800929
Todd Broche505b8d2011-03-21 18:19:54 -0700930 def echo(self, echo):
931 """Dummy echo function for testing/examples.
932
933 Args:
934 echo: string to echo back to client
935 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700936 self._logger.debug('echo(%s)' % (echo))
937 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -0700938
J. Richard Barnettee2820552013-03-14 16:13:46 -0700939 def get_board(self):
940 """Return the board specified at startup, if any."""
941 return self._board
942
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700943 def get_base_board(self):
944 """Returns the board name of the base if present.
945
946 Returns:
947 A string of the board name, or '' if not present.
948 """
949 # The value is set in servo_postinit.
950 return self._base_board
951
Simran Basia23c1392013-08-06 14:59:10 -0700952 def get_version(self):
953 """Get servo board version."""
954 return self._version
955
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800956 def power_long_press(self):
957 """Simulate a long power button press."""
958 # After a long power press, the EC may ignore the next power
959 # button press (at least on Alex). To guarantee that this
960 # won't happen, we need to allow the EC one second to
961 # collect itself.
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800962 return self.set('power_key', 'long_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800963
964 def power_normal_press(self):
965 """Simulate a normal power button press."""
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800966 return self.set('power_key', 'press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800967
968 def power_short_press(self):
969 """Simulate a short power button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530970 return self.set('power_key', 'short_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800971
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530972 def power_key(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800973 """Simulate a power button press.
974
975 Args:
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530976 press_secs: Time in seconds to simulate the keypress.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800977 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530978 return self.set('power_key', 'press' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800979
980 def ctrl_d(self, press_secs=''):
981 """Simulate Ctrl-d simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530982 return self.set('ctrl_d', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800983
Victor Dodone539cea2016-03-29 18:50:17 -0700984 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800985 """Simulate Ctrl-u simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530986 return self.set('ctrl_u', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800987
988 def ctrl_enter(self, press_secs=''):
989 """Simulate Ctrl-enter simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530990 return self.set('ctrl_enter', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800991
992 def d_key(self, press_secs=''):
993 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530994 return self.set('d_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800995
996 def ctrl_key(self, press_secs=''):
997 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530998 return self.set('ctrl_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800999
1000 def enter_key(self, press_secs=''):
1001 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301002 return self.set('enter_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001003
1004 def refresh_key(self, press_secs=''):
1005 """Simulate Refresh key (F3) button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301006 return self.set('refresh_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001007
1008 def ctrl_refresh_key(self, press_secs=''):
1009 """Simulate Ctrl and Refresh (F3) simultaneous press.
1010
1011 This key combination is an alternative of Space key.
1012 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301013 return self.set('ctrl_refresh_key', ('tab' if press_secs is '' else
1014 press_secs))
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001015
1016 def imaginary_key(self, press_secs=''):
1017 """Simulate imaginary key button press.
1018
1019 Maps to a key that doesn't physically exist.
1020 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301021 return self.set('imaginary_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001022
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001023 def sysrq_x(self, press_secs=''):
1024 """Simulate Alt VolumeUp X simultaneous press.
1025
1026 This key combination is the kernel system request (sysrq) x.
1027 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301028 return self.set('sysrq_x', 'tab' if press_secs is '' else press_secs)
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001029
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001030 def get_servo_serials(self):
1031 """Return all the serials associated with this process."""
1032 return self._serialnames
1033
1034
Todd Broche505b8d2011-03-21 18:19:54 -07001035def test():
1036 """Integration testing.
1037
1038 TODO(tbroch) Enhance integration test and add unittest (see mox)
1039 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001040 logging.basicConfig(
1041 level=logging.DEBUG,
1042 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -07001043 # configure server & listen
1044 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -07001045 # 5 == number of interfaces on a FT4232H device
1046 for i in xrange(1, 5):
1047 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -07001048 # its an i2c interface ... see __init__ for details and TODO to make
1049 # this configureable
1050 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1051 else:
1052 # its a gpio interface
1053 servod_obj._interface_list[i].wr_rd(0)
1054
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001055 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost', 9999),
Todd Broche505b8d2011-03-21 18:19:54 -07001056 allow_none=True)
1057 server.register_introspection_functions()
1058 server.register_multicall_functions()
1059 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001060 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -07001061 server.serve_forever()
1062
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001063
1064if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -07001065 test()
1066
1067 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001068 """remote_uri = 'http://localhost:9999' client = xmlrpclib.ServerProxy(remote_uri, verbose=False) send_str = "Hello_there" print "Sent " + send_str + ", Recv " + client.echo(send_str)
1069
Todd Broche505b8d2011-03-21 18:19:54 -07001070 """