blob: e4ed9bd42bbc2dc1b4dbffb6cad64820a3db76dc [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
Todd Broche505b8d2011-03-21 18:19:54 -070011import SimpleXMLRPCServer
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080012import threading
Todd Broch7a91c252012-02-03 12:37:45 -080013import time
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070014import usb
Todd Broche505b8d2011-03-21 18:19:54 -070015
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080016import drv as servo_drv
Aaron.Chuang88eff332014-07-31 08:32:00 +080017import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070018import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070019import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070020import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080021import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070022import ftdigpio
23import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070024import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070025import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080026import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080027import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070028import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070029import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080030import stm32gpio
31import stm32i2c
32import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070033
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080034HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080035
Todd Broche505b8d2011-03-21 18:19:54 -070036MAX_I2C_CLOCK_HZ = 100000
37
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070038
Todd Broche505b8d2011-03-21 18:19:54 -070039class ServodError(Exception):
40 """Exception class for servod."""
41
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070042
Todd Broche505b8d2011-03-21 18:19:54 -070043class Servod(object):
44 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070045
Kevin Cheng4b4f0022016-09-09 02:37:07 -070046 # This is the key to get the main serial used in the _serialnames dict.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070047 MAIN_SERIAL = 'main'
48 SERVO_MICRO_SERIAL = 'servo_micro'
49 CCD_SERIAL = 'ccd'
Kevin Cheng4b4f0022016-09-09 02:37:07 -070050
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080051 # Timeout to wait for interfaces to become available again if reinitialization
52 # is taking place. In seconds.
53 INTERFACE_AVAILABILITY_TIMEOUT = 60
54
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070055 def init_servo_interfaces(self, vendor, product, serialname, interfaces):
Kevin Chengdc3befd2016-07-15 12:34:00 -070056 """Init the servo interfaces with the given interfaces.
57
58 We don't use the self._{vendor,product,serialname} attributes because we
59 want to allow other callers to initialize other interfaces that may not
60 be associated with the initialized attributes (e.g. a servo v4 servod object
61 that wants to also initialize a servo micro interface).
62
63 Args:
64 vendor: USB vendor id of FTDI device.
65 product: USB product id of FTDI device.
66 serialname: String of device serialname/number as defined in FTDI
67 eeprom.
68 interfaces: List of strings of interface types the server will
69 instantiate.
70
71 Raises:
72 ServodError if unable to locate init method for particular interface.
73 """
Mary Ruthven13389642017-02-14 12:15:34 -080074 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070075 device = (vendor, product, serialname)
Mary Ruthven13389642017-02-14 12:15:34 -080076 if device not in self._devices:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070077 self._devices.append(device)
Mary Ruthven13389642017-02-14 12:15:34 -080078
Kevin Chengdc3befd2016-07-15 12:34:00 -070079 # Extend the interface list if we need to.
80 interfaces_len = len(interfaces)
81 interface_list_len = len(self._interface_list)
82 if interfaces_len > interface_list_len:
83 self._interface_list += [None] * (interfaces_len - interface_list_len)
84
Kevin Chengdc3befd2016-07-15 12:34:00 -070085 for i, interface in enumerate(interfaces):
86 is_ftdi_interface = False
87 if type(interface) is dict:
88 name = interface['name']
89 # Store interface index for those that care about it.
90 interface['index'] = i
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -070091 elif type(interface) is str:
92 if interface == 'dummy':
93 # 'dummy' reserves the interface for future use. Typically the
94 # interface will be managed by external third-party tools like
95 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
96 # it serves as a placeholder for servo micro interfaces.
97 continue
Kevin Chengdc3befd2016-07-15 12:34:00 -070098 name = interface
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -070099 is_ftdi_interface = interface.startswith('ftdi')
Kevin Chengdc3befd2016-07-15 12:34:00 -0700100 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700101 raise ServodError('Illegal interface type %s' % type(interface))
Kevin Chengdc3befd2016-07-15 12:34:00 -0700102
103 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700104 product_increment = 0
105 if is_ftdi_interface:
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -0700106 # The interface argument in ftdi initialization is the interface number.
107 interface = ((i - 1) % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700108 product_increment = (i - 1) / ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE
109 if product_increment:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700110 self._logger.info('Use the next FTDI part @ pid = 0x%04x',
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700111 product + product_increment)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700112
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700113 self._logger.info('Initializing interface %d to %s', i, name)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700114 try:
115 func = getattr(self, '_init_%s' % name)
116 except AttributeError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700117 raise ServodError('Unable to locate init for interface %s' % name)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700118 result = func(vendor, product + product_increment, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700119
120 if isinstance(result, tuple):
121 result_len = len(result)
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700122 self._interface_list[i:(i + result_len)] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700123 else:
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700124 self._interface_list[i] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700125
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700126 def __init__(self, config, vendor, product, serialname=None, interfaces=None,
Namyoon Woo341a8332019-03-07 12:01:31 -0800127 board='', model='', version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700128 """Servod constructor.
129
130 Args:
131 config: instance of SystemConfig containing all controls for
132 particular Servod invocation
133 vendor: usb vendor id of FTDI device
134 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700135 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700136 interfaces: list of strings of interface types the server will instantiate
Namyoon Woo341a8332019-03-07 12:01:31 -0800137 board: board name. e.g. octopus, coral, or scarlet.
138 model: model name of a given board. e.g. fleex, ampton, or apel.
Simran Basia23c1392013-08-06 14:59:10 -0700139 version: String. Servo board version. Examples: servo_v1, servo_v2,
140 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800141 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700142 sending keyboard commands to DUTs that do not have built in
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700143 keyboards. Used in FAFT tests. Use None for on board AVR MCU.
144 e.g. '/dev/ttyUSB0' or None.
Todd Brochdbb09982011-10-02 07:14:26 -0700145
146 Raises:
147 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700148 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700149 self._logger = logging.getLogger('Servod')
150 self._logger.debug('')
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800151 self._ifaces_available = threading.Event()
152 # Initially interfaces should be available.
153 self._ifaces_available.set()
Todd Broche505b8d2011-03-21 18:19:54 -0700154 self._vendor = vendor
155 self._product = product
Mary Ruthven13389642017-02-14 12:15:34 -0800156 self._devices = []
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700157 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700158 self._syscfg = config
159 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
160 # interfaces are mapped to
161 self._interface_list = []
162 # Dict of Dict to map control name, function name to to tuple (params, drv)
163 # Ex) _drv_dict[name]['get'] = (params, drv)
164 self._drv_dict = {}
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700165 self._base_board = ''
Namyoon Woo341a8332019-03-07 12:01:31 -0800166 self._board = board
167 if model:
168 self._board += '_' + model
169 self._model = model
Simran Basia23c1392013-08-06 14:59:10 -0700170 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800171 self._usbkm232 = usbkm232
Ruben Rodriguez Buchillon386a0102018-08-16 09:11:20 +0800172 self._keyboard = None
173 self._usb_keyboard = None
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
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700213 def close(self):
214 """Servod turn down logic."""
215 for i, interface in enumerate(self._interface_list):
216 self._logger.info('Turning down interface %d' % i)
217 if hasattr(interface, 'close'):
218 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800219
Kevin Chengdc3befd2016-07-15 12:34:00 -0700220 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700221 """Dummy interface for ftdi devices.
222
223 This is a dummy function specifically for ftdi devices to not initialize
224 anything but to help pad the interface list.
225
226 Returns:
227 None.
228 """
229 return None
230
Kevin Chengdc3befd2016-07-15 12:34:00 -0700231 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700232 """Initialize gpio driver interface and open for use.
233
234 Args:
235 interface: interface number of FTDI device to use.
236
237 Returns:
238 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700239
240 Raises:
241 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700242 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700243 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700244 try:
245 fobj.open()
246 except ftdigpio.FgpioError as e:
247 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
248
Todd Broche505b8d2011-03-21 18:19:54 -0700249 return fobj
250
Kevin Chengdc3befd2016-07-15 12:34:00 -0700251 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800252 """Initialize stm32 uart interface and open for use
253
254 Note, the uart runs in a separate thread. Users wishing to
255 interact with it will query control for the pty's pathname and connect
256 with their favorite console program. For example:
257 cu -l /dev/pts/22
258
259 Args:
260 interface: dict of interface parameters.
261
262 Returns:
263 Instance object of interface
264
265 Raises:
266 ServodError: Raised on init failure.
267 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700268 self._logger.info('Suart: interface: %s' % interface)
269 sobj = stm32uart.Suart(vendor, product, interface['interface'], serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800270
271 try:
272 sobj.run()
273 except stm32uart.SuartError as e:
274 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
275
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700276 self._logger.info('%s' % sobj.get_pty())
Nick Sanders97bc4462016-01-04 15:37:31 -0800277 return sobj
278
Kevin Chengdc3befd2016-07-15 12:34:00 -0700279 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800280 """Initialize stm32 gpio interface.
281 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700282 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800283
284 Returns:
285 Instance object of interface
286
287 Raises:
288 SgpioError: Raised on init failure.
289 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700290 interface_number = interface
291 # Interface could be a dict.
292 if type(interface) is dict:
293 interface_number = interface['interface']
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700294 self._logger.info('Sgpio: interface: %s' % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700295 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800296
Kevin Chengdc3befd2016-07-15 12:34:00 -0700297 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800298 """Initialize stm32 USB to I2C bridge interface and open for use
299
300 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700301 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800302
303 Returns:
304 Instance object of interface.
305
306 Raises:
307 Si2cError: Raised on init failure.
308 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700309 self._logger.info('Si2cBus: interface: %s' % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800310 port = interface.get('port', 0)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700311 return stm32i2c.Si2cBus(vendor, product, interface['interface'], port=port,
312 serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800313
Kevin Chengdc3befd2016-07-15 12:34:00 -0700314 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800315 """Initalize beaglebone ADC interface."""
316 return bbadc.BBadc()
317
Kevin Chengdc3befd2016-07-15 12:34:00 -0700318 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700319 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700320 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700321
Kevin Chengdc3befd2016-07-15 12:34:00 -0700322 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700323 """Initialize i2c interface and open for use.
324
325 Args:
326 interface: interface number of FTDI device to use
327
328 Returns:
329 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700330
331 Raises:
332 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700333 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700334 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700335 try:
336 fobj.open()
337 except ftdii2c.Fi2cError as e:
338 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
339
Todd Broche505b8d2011-03-21 18:19:54 -0700340 # Set the frequency of operation of the i2c bus.
341 # TODO(tbroch) make configureable
342 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700343
Todd Broche505b8d2011-03-21 18:19:54 -0700344 return fobj
345
Simran Basie750a342013-03-12 13:45:26 -0700346 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
347 def _init_bb_i2c(self, interface):
348 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700349 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700350
Kevin Chengdc3befd2016-07-15 12:34:00 -0700351 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800352 """Initalize Linux i2c-dev interface."""
353 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
354
Kevin Chengdc3befd2016-07-15 12:34:00 -0700355 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700356 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700357
358 Note, the uart runs in a separate thread (pthreads). Users wishing to
359 interact with it will query control for the pty's pathname and connect
360 with there favorite console program. For example:
361 cu -l /dev/pts/22
362
363 Args:
364 interface: interface number of FTDI device to use
365
366 Returns:
367 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700368
369 Raises:
370 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700371 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700372 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700373 try:
374 fobj.run()
375 except ftdiuart.FuartError as e:
376 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
377
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700378 self._logger.info('%s' % fobj.get_pty())
Todd Broch47c43f42011-05-26 15:11:31 -0700379 return fobj
380
Simran Basie750a342013-03-12 13:45:26 -0700381 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700382 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700383 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700384 logging.debug('UART INTERFACE: %s', interface)
385 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700386
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700387 def _init_ftdi_gpiouart(self, vendor, product, serialname, interface):
Todd Broch888da782011-10-07 14:29:09 -0700388 """Initialize special gpio + uart interface and open for use
389
390 Note, the uart runs in a separate thread (pthreads). Users wishing to
391 interact with it will query control for the pty's pathname and connect
392 with there favorite console program. For example:
393 cu -l /dev/pts/22
394
395 Args:
396 interface: interface number of FTDI device to use
397
398 Returns:
399 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700400
401 Raises:
402 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700403 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700404 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700405 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700406 try:
407 fuart.run()
408 except ftdiuart.FuartError as e:
409 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
410
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700411 self._logger.info('uart pty: %s' % fuart.get_pty())
Todd Broch888da782011-10-07 14:29:09 -0700412 return fgpio, fuart
413
Kevin Chengdc3befd2016-07-15 12:34:00 -0700414 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800415 """Initialize EC-3PO console interpreter interface.
416
417 Args:
418 interface: A dictionary representing the interface.
419
420 Returns:
421 An EC3PO object representing the EC-3PO interface or None if there's no
422 interface for the USB PD UART.
423 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700424 raw_uart_name = interface['raw_pty']
Nick Sanders116ed9e2018-03-09 19:05:16 -0800425 raw_uart_source = interface['source']
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700426 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800427 raw_ec_uart = self.get(raw_uart_name)
Nick Sanders116ed9e2018-03-09 19:05:16 -0800428 return ec3po_interface.EC3PO(raw_ec_uart, raw_uart_source)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800429 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700430 # The overlay doesn't have the raw PTY defined, therefore we can skip
431 # initializing this interface since no control relies on it.
432 self._logger.debug(
433 'Skip initializing EC3PO for %s, no control specified.',
434 raw_uart_name)
435 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800436
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800437 def _camel_case(self, string):
438 output = ''
439 for s in string.split('_'):
440 if output:
441 output += s.capitalize()
442 else:
443 output = s
444 return output
445
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700446 def clear_cached_drv(self):
447 """Clear the cached drivers.
448
449 The drivers are cached in the Dict _drv_dict when a control is got or set.
450 When the servo interfaces are relocated, the cached values may become wrong.
451 Should call this method to clear the cached values.
452 """
453 self._drv_dict = {}
454
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800455 def _get_servo_specific_param(self, params, param_key, control_name):
456 """Get |param_key| from params by looking for servo specific params first.
457
458 Find the candidate servos. Using servo_v4 with a servo_micro connected as
459 example, the following shows the priority for selecting the interface.
460
461 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
462 2. servo_micro_interface
463 3. servo_v4_interface
464 4. Fallback to the default, interface.
465
466 Args:
467 params: params dictionary for a control
468 param_key: identifier in the params dictionary to look for
469 control_name: control name the params correspond to
470
471 Returns:
472 The best suited param value for param_key given the servo type or
473 None if even the default is not defined.
474 """
475 candidates = [self._version]
476 candidates.extend(reversed(self._version.split('_with_')))
477 candidates = ['%s_%s' % (c, param_key) for c in candidates]
478 candidates.append(param_key)
479 for c in candidates:
480 if c in params:
481 self._logger.debug('Using %s parameter.', c)
482 return params[c]
483 self._logger.error('Unable to determine %s for %s', param_key, control_name)
484 self._logger.error('params: %r', params)
485 return None
486
Todd Broche505b8d2011-03-21 18:19:54 -0700487 def _get_param_drv(self, control_name, is_get=True):
488 """Get access to driver for a given control.
489
490 Note, some controls have different parameter dictionaries for 'getting' the
491 control's value versus 'setting' it. Boolean is_get distinguishes which is
492 being requested.
493
494 Args:
495 control_name: string name of control
496 is_get: boolean to determine
497
498 Returns:
499 tuple (param, drv) where:
500 param: param dictionary for control
501 drv: instance object of driver for particular control
502
503 Raises:
504 ServodError: Error occurred while examining params dict
505 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700506 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700507 # if already setup just return tuple from driver dict
508 if control_name in self._drv_dict:
509 if is_get and ('get' in self._drv_dict[control_name]):
510 return self._drv_dict[control_name]['get']
511 if not is_get and ('set' in self._drv_dict[control_name]):
512 return self._drv_dict[control_name]['set']
513
514 params = self._syscfg.lookup_control_params(control_name, is_get)
Simran Basi668be0e2013-08-07 11:54:50 -0700515
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800516 # Get the most suitable drv given the servo instance.
517 drv_name = self._get_servo_specific_param(params, 'drv', control_name)
518 if drv_name == 'na':
519 # 'na' drv can be used to selectively turn controls into noops for
520 # a given servo hardware. Ensure that there is an interface.
521 params.setdefault('interface', 'servo')
522 self._logger.debug('Setting interface to default to %r for %r unless '
523 ' defined in params, as drv is %r.', 'servo',
524 control_name, 'na')
525 # Setting input_type to str allows all inputs through enabling a true noop
526 params.update({'input_type': 'str'})
527 interface_id = self._get_servo_specific_param(params, 'interface',
528 control_name)
529 if None in [drv_name, interface_id]:
530 raise ServodError('No drv/interface for control %r found' % control_name)
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700531
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800532 if interface_id == 'servo':
533 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700534 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700535 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800536 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700537
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800538 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800539 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700540 drv = drv_class(interface, params)
541 if control_name not in self._drv_dict:
542 self._drv_dict[control_name] = {}
543 if is_get:
544 self._drv_dict[control_name]['get'] = (params, drv)
545 else:
546 self._drv_dict[control_name]['set'] = (params, drv)
547 return (params, drv)
548
549 def doc_all(self):
550 """Return all documenation for controls.
551
552 Returns:
553 string of <doc> text in config file (xml) and the params dictionary for
554 all controls.
555
556 For example:
557 warm_reset :: Reset the device warmly
558 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
559 """
560 return self._syscfg.display_config()
561
562 def doc(self, name):
563 """Retreive doc string in system config file for given control name.
564
565 Args:
566 name: name string of control to get doc string
567
568 Returns:
569 doc string of name
570
571 Raises:
572 NameError: if fails to locate control
573 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700574 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700575 if self._syscfg.is_control(name):
576 return self._syscfg.get_control_docstring(name)
577 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700578 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700579
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800580 def safe_switch_usbkey_power(self, power_state, _=None):
Kevin Cheng5595b342016-09-29 15:51:01 -0700581 """Toggle the usb power safely.
582
Kevin Chengc49494e2016-07-25 12:13:38 -0700583 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700584 power_state: The setting to set for the usbkey power.
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800585 _: to conform to current API
Kevin Chengc49494e2016-07-25 12:13:38 -0700586
Kevin Cheng5595b342016-09-29 15:51:01 -0700587 Returns:
588 An empty string to appease the xmlrpc gods.
589 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800590 self.set('image_usbkey_pwr', power_state)
Kevin Cheng5595b342016-09-29 15:51:01 -0700591 return ''
592
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800593 def safe_switch_usbkey(self, mux_direction, _=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700594 """Toggle the usb direction safely.
595
Kevin Cheng5595b342016-09-29 15:51:01 -0700596 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800597 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800598 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700599
600 Returns:
601 An empty string to appease the xmlrpc gods.
602 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800603 self.set('image_usbkey_direction', mux_direction)
Kevin Cheng5595b342016-09-29 15:51:01 -0700604 return ''
605
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800606 def probe_host_usb_dev(self, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700607 """Probe the USB disk device plugged in the servo from the host side.
608
Kevin Cheng5595b342016-09-29 15:51:01 -0700609 Args:
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800610 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700611
Simran Basia9f41032012-05-11 14:21:58 -0700612 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700613 USB disk path if one and only one USB disk path is found, otherwise an
Simran Basia9f41032012-05-11 14:21:58 -0700614 """
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800615 return self.get('image_usbkey_dev')
Kevin Chengc49494e2016-07-25 12:13:38 -0700616
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800617 def download_image_to_usb(self, image_path, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700618 """Download image and save to the USB device found by probe_host_usb_dev.
619 If the image_path is a URL, it will download this url to the USB path;
620 otherwise it will simply copy the image_path's contents to the USB path.
621
622 Args:
623 image_path: path or url to the recovery image.
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800624 _: to conform to current API
Simran Basia9f41032012-05-11 14:21:58 -0700625
626 Returns:
627 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800628 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700629 """
Simran Basia9f41032012-05-11 14:21:58 -0700630 try:
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800631 self.set('download_image_to_usb_dev', image_path)
632 return True
633 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700634 return False
Simran Basia9f41032012-05-11 14:21:58 -0700635
636 def make_image_noninteractive(self):
637 """Makes the recovery image noninteractive.
638
639 A noninteractive image will reboot automatically after installation
640 instead of waiting for the USB device to be removed to initiate a system
641 reboot.
642
643 Mounts partition 1 of the image stored on usb_dev and creates a file
644 called "non_interactive" so that the image will become noninteractive.
645
646 Returns:
647 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800648 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700649 """
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800650 try:
651 usb_dev = self.get('image_usbkey_dev')
652 usb_dev_partition = '%s1' % usb_dev
653 self.set('make_usb_dev_image_noninteractive', usb_dev_partition)
654 return True
655 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700656 return False
Simran Basia9f41032012-05-11 14:21:58 -0700657
Todd Broch352b4b22013-03-22 09:48:40 -0700658 def set_get_all(self, cmds):
659 """Set &| get one or more control values.
660
661 Args:
662 cmds: list of control[:value] to get or set.
663
664 Returns:
665 rv: list of responses from calling get or set methods.
666 """
667 rv = []
668 for cmd in cmds:
669 if ':' in cmd:
Wai-Hong Tam269f1802019-05-16 12:37:17 -0700670 (control, value) = cmd.split(':', 1)
Todd Broch352b4b22013-03-22 09:48:40 -0700671 rv.append(self.set(control, value))
672 else:
673 rv.append(self.get(cmd))
674 return rv
675
Mary Ruthven493df512019-07-12 13:10:18 -0700676 def add_serial_number(self, name, serial_number):
677 """Adds the serial number to the _serialnames dictionary.
678
679 Args:
680 name: A string which is the key into the _serialnames dictionary.
681 serial_number: A string which is the key into the _serialnames dictionary.
682 """
683 self._serialnames[name] = serial_number
684 self._logger.debug('Added %s %s to serialnames %r', name, serial_number,
685 self._serialnames)
686
Aseda Aboagye6921f602017-08-01 14:45:38 -0700687 def get_serial_number(self, name):
688 """Returns the desired serial number from the serialnames dict.
689
690 Args:
691 name: A string which is the key into the _serialnames dictionary.
692
693 Returns:
694 A string containing the serial number or "unknown".
695 """
696 if not name:
697 name = 'main'
698
699 try:
700 return self._serialnames[name]
701 except KeyError:
702 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700703 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700704
Todd Broche505b8d2011-03-21 18:19:54 -0700705 def get(self, name):
706 """Get control value.
707
708 Args:
709 name: name string of control
710
711 Returns:
712 Response from calling drv get method. Value is reformatted based on
713 control's dictionary parameters
714
715 Raises:
716 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800717 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700718 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800719 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
720 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700721 self._logger.debug('name(%s)' % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700722 # This route is to retrieve serialnames on servo v4, which
723 # connects to multiple servo-micros or CCD, like the controls,
724 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
725 # TODO(aaboagye): Refactor it.
726 if 'serialname' in name:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700727 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700728
Todd Broche505b8d2011-03-21 18:19:54 -0700729 (param, drv) = self._get_param_drv(name)
730 try:
731 val = drv.get()
732 rd_val = self._syscfg.reformat_val(param, val)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700733 self._logger.debug('%s = %s' % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700734 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700735 except AttributeError, error:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700736 self._logger.error('Getting %s: %s' % (name, error))
Todd Brochfbc499d2011-06-16 16:09:58 -0700737 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800738 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700739 self._logger.error('Getting %s' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700740 raise
Todd Brochd6061672012-05-11 15:52:47 -0700741
Todd Broche505b8d2011-03-21 18:19:54 -0700742 def get_all(self, verbose):
743 """Get all controls values.
744
745 Args:
746 verbose: Boolean on whether to return doc info as well
747
748 Returns:
749 string creating from trying to get all values of all controls. In case of
750 error attempting access to control, response is 'ERR'.
751 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800752 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700753 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700754 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700755 try:
756 value = self.get(name)
757 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700758 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -0700759 pass
760 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700761 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700762 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700763 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800764 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700765
766 def set(self, name, wr_val_str):
767 """Set control.
768
769 Args:
770 name: name string of control
771 wr_val_str: value string to write. Can be integer, float or a
772 alpha-numerical that is mapped to a integer or float.
773
774 Raises:
775 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800776 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700777 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800778 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
779 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700780 self._logger.debug('name(%s) wr_val(%s)' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700781 (params, drv) = self._get_param_drv(name, False)
782 wr_val = self._syscfg.resolve_val(params, wr_val_str)
783 try:
784 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800785 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700786 self._logger.error('Setting %s -> %s' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700787 raise
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +0800788 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
789 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -0700790 # marshall/unmarshall
791 return True
792
Todd Brochd6061672012-05-11 15:52:47 -0700793 def hwinit(self, verbose=False):
794 """Initialize all controls.
795
796 These values are part of the system config XML files of the form
797 init=<value>. This command should be used by clients wishing to return the
798 servo and DUT its connected to a known good/safe state.
799
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800800 Note that initialization errors are ignored (as in some cases they could
801 be caused by DUT firmware deficiencies). This might need to be fine tuned
802 later.
803
Todd Brochd6061672012-05-11 15:52:47 -0700804 Args:
805 verbose: boolean, if True prints info about control initialized.
806 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800807
808 Returns:
809 This function is called across RPC and as such is expected to return
810 something unless transferring 'none' across is allowed. Hence adding a
811 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700812 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800813 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800814 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700815 # Workaround for bug chrome-os-partner:42349. Without this check, the
816 # gpio will briefly pulse low if we set it from high to high.
817 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700818 self.set(control_name, value)
819 if verbose:
820 self._logger.info('Initialized %s to %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700821 except Exception as e:
822 self._logger.error(
Matthew Bleckera5d979c2018-10-16 20:59:19 -0700823 'Problem initializing %s -> %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700824 self._logger.error(str(e))
825 self._logger.error('Please consider verifying the logs and if the '
826 'error is not just a setup issue, consider filing '
827 'a bug. Also checkout go/servo-ki.')
Nick Sandersbc836282015-12-08 21:19:23 -0800828
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800829 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800830
Todd Broche505b8d2011-03-21 18:19:54 -0700831 def echo(self, echo):
832 """Dummy echo function for testing/examples.
833
834 Args:
835 echo: string to echo back to client
836 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700837 self._logger.debug('echo(%s)' % (echo))
838 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -0700839
J. Richard Barnettee2820552013-03-14 16:13:46 -0700840 def get_board(self):
841 """Return the board specified at startup, if any."""
842 return self._board
843
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700844 def get_base_board(self):
845 """Returns the board name of the base if present.
846
847 Returns:
848 A string of the board name, or '' if not present.
849 """
850 # The value is set in servo_postinit.
851 return self._base_board
852
Simran Basia23c1392013-08-06 14:59:10 -0700853 def get_version(self):
854 """Get servo board version."""
855 return self._version
856
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800857 def power_long_press(self):
858 """Simulate a long power button press."""
859 # After a long power press, the EC may ignore the next power
860 # button press (at least on Alex). To guarantee that this
861 # won't happen, we need to allow the EC one second to
862 # collect itself.
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800863 return self.set('power_key', 'long_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800864
865 def power_normal_press(self):
866 """Simulate a normal power button press."""
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800867 return self.set('power_key', 'press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800868
869 def power_short_press(self):
870 """Simulate a short power button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530871 return self.set('power_key', 'short_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800872
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530873 def power_key(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800874 """Simulate a power button press.
875
876 Args:
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530877 press_secs: Time in seconds to simulate the keypress.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800878 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530879 return self.set('power_key', 'press' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800880
881 def ctrl_d(self, press_secs=''):
882 """Simulate Ctrl-d simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530883 return self.set('ctrl_d', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800884
Victor Dodone539cea2016-03-29 18:50:17 -0700885 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800886 """Simulate Ctrl-u simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530887 return self.set('ctrl_u', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800888
889 def ctrl_enter(self, press_secs=''):
890 """Simulate Ctrl-enter simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530891 return self.set('ctrl_enter', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800892
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800893 def ctrl_key(self, press_secs=''):
894 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530895 return self.set('ctrl_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800896
897 def enter_key(self, press_secs=''):
898 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530899 return self.set('enter_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800900
901 def refresh_key(self, press_secs=''):
902 """Simulate Refresh key (F3) button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530903 return self.set('refresh_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800904
905 def ctrl_refresh_key(self, press_secs=''):
906 """Simulate Ctrl and Refresh (F3) simultaneous press.
907
908 This key combination is an alternative of Space key.
909 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530910 return self.set('ctrl_refresh_key', ('tab' if press_secs is '' else
911 press_secs))
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800912
913 def imaginary_key(self, press_secs=''):
914 """Simulate imaginary key button press.
915
916 Maps to a key that doesn't physically exist.
917 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530918 return self.set('imaginary_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800919
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200920 def sysrq_x(self, press_secs=''):
921 """Simulate Alt VolumeUp X simultaneous press.
922
923 This key combination is the kernel system request (sysrq) x.
924 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530925 return self.set('sysrq_x', 'tab' if press_secs is '' else press_secs)
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200926
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700927 def get_servo_serials(self):
928 """Return all the serials associated with this process."""
929 return self._serialnames
930
931
Todd Broche505b8d2011-03-21 18:19:54 -0700932def test():
933 """Integration testing.
934
935 TODO(tbroch) Enhance integration test and add unittest (see mox)
936 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700937 logging.basicConfig(
938 level=logging.DEBUG,
939 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -0700940 # configure server & listen
941 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700942 # 5 == number of interfaces on a FT4232H device
943 for i in xrange(1, 5):
944 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -0700945 # its an i2c interface ... see __init__ for details and TODO to make
946 # this configureable
947 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
948 else:
949 # its a gpio interface
950 servod_obj._interface_list[i].wr_rd(0)
951
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700952 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost', 9999),
Todd Broche505b8d2011-03-21 18:19:54 -0700953 allow_none=True)
954 server.register_introspection_functions()
955 server.register_multicall_functions()
956 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700957 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -0700958 server.serve_forever()
959
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700960
961if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -0700962 test()
963
964 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700965 """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)
966
Todd Broche505b8d2011-03-21 18:19:54 -0700967 """