blob: d88ae01486712d40d892fd573777e115655350fb [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
Mary Ruthvenb7cc5542019-07-15 15:20:10 -070052 # is taking place. In seconds. This is supposed to recover from brief resets.
53 # If the interface disappears for more than 5 seconds, then someone probably
54 # intentionally disconnected the device. Servod shouldn't be responsible for
55 # waiting for the device during an intentional disconnect.
56 INTERFACE_AVAILABILITY_TIMEOUT = 5
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080057
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070058 def init_servo_interfaces(self, vendor, product, serialname, interfaces):
Kevin Chengdc3befd2016-07-15 12:34:00 -070059 """Init the servo interfaces with the given interfaces.
60
61 We don't use the self._{vendor,product,serialname} attributes because we
62 want to allow other callers to initialize other interfaces that may not
63 be associated with the initialized attributes (e.g. a servo v4 servod object
64 that wants to also initialize a servo micro interface).
65
66 Args:
67 vendor: USB vendor id of FTDI device.
68 product: USB product id of FTDI device.
69 serialname: String of device serialname/number as defined in FTDI
70 eeprom.
71 interfaces: List of strings of interface types the server will
72 instantiate.
73
74 Raises:
75 ServodError if unable to locate init method for particular interface.
76 """
Mary Ruthven13389642017-02-14 12:15:34 -080077 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070078 device = (vendor, product, serialname)
Mary Ruthven13389642017-02-14 12:15:34 -080079 if device not in self._devices:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070080 self._devices.append(device)
Mary Ruthven13389642017-02-14 12:15:34 -080081
Kevin Chengdc3befd2016-07-15 12:34:00 -070082 # Extend the interface list if we need to.
83 interfaces_len = len(interfaces)
84 interface_list_len = len(self._interface_list)
85 if interfaces_len > interface_list_len:
86 self._interface_list += [None] * (interfaces_len - interface_list_len)
87
Kevin Chengdc3befd2016-07-15 12:34:00 -070088 for i, interface in enumerate(interfaces):
89 is_ftdi_interface = False
90 if type(interface) is dict:
91 name = interface['name']
92 # Store interface index for those that care about it.
93 interface['index'] = i
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -070094 elif type(interface) is str:
95 if interface == 'dummy':
96 # 'dummy' reserves the interface for future use. Typically the
97 # interface will be managed by external third-party tools like
98 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
99 # it serves as a placeholder for servo micro interfaces.
100 continue
Kevin Chengdc3befd2016-07-15 12:34:00 -0700101 name = interface
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -0700102 is_ftdi_interface = interface.startswith('ftdi')
Kevin Chengdc3befd2016-07-15 12:34:00 -0700103 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700104 raise ServodError('Illegal interface type %s' % type(interface))
Kevin Chengdc3befd2016-07-15 12:34:00 -0700105
106 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700107 product_increment = 0
108 if is_ftdi_interface:
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -0700109 # The interface argument in ftdi initialization is the interface number.
110 interface = ((i - 1) % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700111 product_increment = (i - 1) / ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE
112 if product_increment:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700113 self._logger.info('Use the next FTDI part @ pid = 0x%04x',
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700114 product + product_increment)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700115
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700116 self._logger.info('Initializing interface %d to %s', i, name)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700117 try:
118 func = getattr(self, '_init_%s' % name)
119 except AttributeError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700120 raise ServodError('Unable to locate init for interface %s' % name)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700121 result = func(vendor, product + product_increment, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700122
123 if isinstance(result, tuple):
124 result_len = len(result)
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700125 self._interface_list[i:(i + result_len)] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700126 else:
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700127 self._interface_list[i] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700128
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700129 def __init__(self, config, vendor, product, serialname=None, interfaces=None,
Namyoon Woo341a8332019-03-07 12:01:31 -0800130 board='', model='', version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700131 """Servod constructor.
132
133 Args:
134 config: instance of SystemConfig containing all controls for
135 particular Servod invocation
136 vendor: usb vendor id of FTDI device
137 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700138 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700139 interfaces: list of strings of interface types the server will instantiate
Namyoon Woo341a8332019-03-07 12:01:31 -0800140 board: board name. e.g. octopus, coral, or scarlet.
141 model: model name of a given board. e.g. fleex, ampton, or apel.
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
162 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
163 # interfaces are mapped to
164 self._interface_list = []
165 # Dict of Dict to map control name, function name to to tuple (params, drv)
166 # Ex) _drv_dict[name]['get'] = (params, drv)
167 self._drv_dict = {}
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700168 self._base_board = ''
Namyoon Woo341a8332019-03-07 12:01:31 -0800169 self._board = board
170 if model:
171 self._board += '_' + model
172 self._model = model
Simran Basia23c1392013-08-06 14:59:10 -0700173 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800174 self._usbkm232 = usbkm232
Ruben Rodriguez Buchillon386a0102018-08-16 09:11:20 +0800175 self._keyboard = None
176 self._usb_keyboard = None
Todd Brochdbb09982011-10-02 07:14:26 -0700177 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700178 try:
179 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
180 except KeyError:
181 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Dino Lic89d8c82018-01-11 09:56:47 +0800182 self._interfaces = interfaces
Todd Brochdbb09982011-10-02 07:14:26 -0700183
Kevin Chengdc3befd2016-07-15 12:34:00 -0700184 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700185 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800186
Mary Ruthven13389642017-02-14 12:15:34 -0800187 def reinitialize(self):
188 """Reinitialize all interfaces that support reinitialization"""
Mary Ruthven13389642017-02-14 12:15:34 -0800189 for i, interface in enumerate(self._interface_list):
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700190 if hasattr(interface, 'reinitialize'):
191 interface.reinitialize()
192 else:
193 self._logger.debug('interface %d has no reset functionality', i)
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800194 # Indicate interfaces are safe to use again.
195 self._ifaces_available.set()
Mary Ruthven13389642017-02-14 12:15:34 -0800196
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700197 def get_servo_interfaces(self, position, size):
198 """Get the list of servo interfaces.
199
200 Args:
201 position: The index the first interface to get.
202 size: The number of the interfaces.
203 """
204 return self._interface_list[position:(position + size)]
205
206 def set_servo_interfaces(self, position, interfaces):
207 """Set the list of servo interfaces.
208
209 Args:
210 position: The index the first interface to set.
211 interfaces: The list of interfaces to set.
212 """
213 size = len(interfaces)
214 self._interface_list[position:(position + size)] = interfaces
215
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700216 def close(self):
217 """Servod turn down logic."""
218 for i, interface in enumerate(self._interface_list):
219 self._logger.info('Turning down interface %d' % i)
220 if hasattr(interface, 'close'):
221 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800222
Kevin Chengdc3befd2016-07-15 12:34:00 -0700223 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700224 """Dummy interface for ftdi devices.
225
226 This is a dummy function specifically for ftdi devices to not initialize
227 anything but to help pad the interface list.
228
229 Returns:
230 None.
231 """
232 return None
233
Kevin Chengdc3befd2016-07-15 12:34:00 -0700234 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700235 """Initialize gpio driver interface and open for use.
236
237 Args:
238 interface: interface number of FTDI device to use.
239
240 Returns:
241 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700242
243 Raises:
244 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700245 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700246 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700247 try:
248 fobj.open()
249 except ftdigpio.FgpioError as e:
250 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
251
Todd Broche505b8d2011-03-21 18:19:54 -0700252 return fobj
253
Kevin Chengdc3befd2016-07-15 12:34:00 -0700254 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800255 """Initialize stm32 uart interface and open for use
256
257 Note, the uart runs in a separate thread. Users wishing to
258 interact with it will query control for the pty's pathname and connect
259 with their favorite console program. For example:
260 cu -l /dev/pts/22
261
262 Args:
263 interface: dict of interface parameters.
264
265 Returns:
266 Instance object of interface
267
268 Raises:
269 ServodError: Raised on init failure.
270 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700271 self._logger.info('Suart: interface: %s' % interface)
272 sobj = stm32uart.Suart(vendor, product, interface['interface'], serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800273
274 try:
275 sobj.run()
276 except stm32uart.SuartError as e:
277 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
278
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700279 self._logger.info('%s' % sobj.get_pty())
Nick Sanders97bc4462016-01-04 15:37:31 -0800280 return sobj
281
Kevin Chengdc3befd2016-07-15 12:34:00 -0700282 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800283 """Initialize stm32 gpio interface.
284 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700285 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800286
287 Returns:
288 Instance object of interface
289
290 Raises:
291 SgpioError: Raised on init failure.
292 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700293 interface_number = interface
294 # Interface could be a dict.
295 if type(interface) is dict:
296 interface_number = interface['interface']
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700297 self._logger.info('Sgpio: interface: %s' % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700298 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800299
Kevin Chengdc3befd2016-07-15 12:34:00 -0700300 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800301 """Initialize stm32 USB to I2C bridge interface and open for use
302
303 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700304 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800305
306 Returns:
307 Instance object of interface.
308
309 Raises:
310 Si2cError: Raised on init failure.
311 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700312 self._logger.info('Si2cBus: interface: %s' % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800313 port = interface.get('port', 0)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700314 return stm32i2c.Si2cBus(vendor, product, interface['interface'], port=port,
315 serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800316
Kevin Chengdc3befd2016-07-15 12:34:00 -0700317 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800318 """Initalize beaglebone ADC interface."""
319 return bbadc.BBadc()
320
Kevin Chengdc3befd2016-07-15 12:34:00 -0700321 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700322 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700323 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700324
Kevin Chengdc3befd2016-07-15 12:34:00 -0700325 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700326 """Initialize i2c interface and open for use.
327
328 Args:
329 interface: interface number of FTDI device to use
330
331 Returns:
332 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700333
334 Raises:
335 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700336 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700337 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700338 try:
339 fobj.open()
340 except ftdii2c.Fi2cError as e:
341 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
342
Todd Broche505b8d2011-03-21 18:19:54 -0700343 # Set the frequency of operation of the i2c bus.
344 # TODO(tbroch) make configureable
345 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700346
Todd Broche505b8d2011-03-21 18:19:54 -0700347 return fobj
348
Simran Basie750a342013-03-12 13:45:26 -0700349 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
350 def _init_bb_i2c(self, interface):
351 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700352 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700353
Kevin Chengdc3befd2016-07-15 12:34:00 -0700354 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800355 """Initalize Linux i2c-dev interface."""
356 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
357
Kevin Chengdc3befd2016-07-15 12:34:00 -0700358 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700359 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700360
361 Note, the uart runs in a separate thread (pthreads). Users wishing to
362 interact with it will query control for the pty's pathname and connect
363 with there favorite console program. For example:
364 cu -l /dev/pts/22
365
366 Args:
367 interface: interface number of FTDI device to use
368
369 Returns:
370 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700371
372 Raises:
373 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700374 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700375 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700376 try:
377 fobj.run()
378 except ftdiuart.FuartError as e:
379 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
380
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700381 self._logger.info('%s' % fobj.get_pty())
Todd Broch47c43f42011-05-26 15:11:31 -0700382 return fobj
383
Simran Basie750a342013-03-12 13:45:26 -0700384 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700385 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700386 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700387 logging.debug('UART INTERFACE: %s', interface)
388 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700389
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700390 def _init_ftdi_gpiouart(self, vendor, product, serialname, interface):
Todd Broch888da782011-10-07 14:29:09 -0700391 """Initialize special gpio + uart interface and open for use
392
393 Note, the uart runs in a separate thread (pthreads). Users wishing to
394 interact with it will query control for the pty's pathname and connect
395 with there favorite console program. For example:
396 cu -l /dev/pts/22
397
398 Args:
399 interface: interface number of FTDI device to use
400
401 Returns:
402 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700403
404 Raises:
405 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700406 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700407 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700408 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700409 try:
410 fuart.run()
411 except ftdiuart.FuartError as e:
412 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
413
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700414 self._logger.info('uart pty: %s' % fuart.get_pty())
Todd Broch888da782011-10-07 14:29:09 -0700415 return fgpio, fuart
416
Kevin Chengdc3befd2016-07-15 12:34:00 -0700417 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800418 """Initialize EC-3PO console interpreter interface.
419
420 Args:
421 interface: A dictionary representing the interface.
422
423 Returns:
424 An EC3PO object representing the EC-3PO interface or None if there's no
425 interface for the USB PD UART.
426 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700427 raw_uart_name = interface['raw_pty']
Nick Sanders116ed9e2018-03-09 19:05:16 -0800428 raw_uart_source = interface['source']
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700429 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800430 raw_ec_uart = self.get(raw_uart_name)
Nick Sanders116ed9e2018-03-09 19:05:16 -0800431 return ec3po_interface.EC3PO(raw_ec_uart, raw_uart_source)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800432 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700433 # The overlay doesn't have the raw PTY defined, therefore we can skip
434 # initializing this interface since no control relies on it.
435 self._logger.debug(
436 'Skip initializing EC3PO for %s, no control specified.',
437 raw_uart_name)
438 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800439
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800440 def _camel_case(self, string):
441 output = ''
442 for s in string.split('_'):
443 if output:
444 output += s.capitalize()
445 else:
446 output = s
447 return output
448
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700449 def clear_cached_drv(self):
450 """Clear the cached drivers.
451
452 The drivers are cached in the Dict _drv_dict when a control is got or set.
453 When the servo interfaces are relocated, the cached values may become wrong.
454 Should call this method to clear the cached values.
455 """
456 self._drv_dict = {}
457
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800458 def _get_servo_specific_param(self, params, param_key, control_name):
459 """Get |param_key| from params by looking for servo specific params first.
460
461 Find the candidate servos. Using servo_v4 with a servo_micro connected as
462 example, the following shows the priority for selecting the interface.
463
464 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
465 2. servo_micro_interface
466 3. servo_v4_interface
467 4. Fallback to the default, interface.
468
469 Args:
470 params: params dictionary for a control
471 param_key: identifier in the params dictionary to look for
472 control_name: control name the params correspond to
473
474 Returns:
475 The best suited param value for param_key given the servo type or
476 None if even the default is not defined.
477 """
478 candidates = [self._version]
479 candidates.extend(reversed(self._version.split('_with_')))
480 candidates = ['%s_%s' % (c, param_key) for c in candidates]
481 candidates.append(param_key)
482 for c in candidates:
483 if c in params:
484 self._logger.debug('Using %s parameter.', c)
485 return params[c]
486 self._logger.error('Unable to determine %s for %s', param_key, control_name)
487 self._logger.error('params: %r', params)
488 return None
489
Todd Broche505b8d2011-03-21 18:19:54 -0700490 def _get_param_drv(self, control_name, is_get=True):
491 """Get access to driver for a given control.
492
493 Note, some controls have different parameter dictionaries for 'getting' the
494 control's value versus 'setting' it. Boolean is_get distinguishes which is
495 being requested.
496
497 Args:
498 control_name: string name of control
499 is_get: boolean to determine
500
501 Returns:
502 tuple (param, drv) where:
503 param: param dictionary for control
504 drv: instance object of driver for particular control
505
506 Raises:
507 ServodError: Error occurred while examining params dict
508 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700509 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700510 # if already setup just return tuple from driver dict
511 if control_name in self._drv_dict:
512 if is_get and ('get' in self._drv_dict[control_name]):
513 return self._drv_dict[control_name]['get']
514 if not is_get and ('set' in self._drv_dict[control_name]):
515 return self._drv_dict[control_name]['set']
516
517 params = self._syscfg.lookup_control_params(control_name, is_get)
Simran Basi668be0e2013-08-07 11:54:50 -0700518
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800519 # Get the most suitable drv given the servo instance.
520 drv_name = self._get_servo_specific_param(params, 'drv', control_name)
521 if drv_name == 'na':
522 # 'na' drv can be used to selectively turn controls into noops for
523 # a given servo hardware. Ensure that there is an interface.
524 params.setdefault('interface', 'servo')
525 self._logger.debug('Setting interface to default to %r for %r unless '
526 ' defined in params, as drv is %r.', 'servo',
527 control_name, 'na')
528 # Setting input_type to str allows all inputs through enabling a true noop
529 params.update({'input_type': 'str'})
530 interface_id = self._get_servo_specific_param(params, 'interface',
531 control_name)
532 if None in [drv_name, interface_id]:
533 raise ServodError('No drv/interface for control %r found' % control_name)
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700534
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800535 if interface_id == 'servo':
536 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700537 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700538 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800539 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700540
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800541 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800542 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700543 drv = drv_class(interface, params)
544 if control_name not in self._drv_dict:
545 self._drv_dict[control_name] = {}
546 if is_get:
547 self._drv_dict[control_name]['get'] = (params, drv)
548 else:
549 self._drv_dict[control_name]['set'] = (params, drv)
550 return (params, drv)
551
552 def doc_all(self):
553 """Return all documenation for controls.
554
555 Returns:
556 string of <doc> text in config file (xml) and the params dictionary for
557 all controls.
558
559 For example:
560 warm_reset :: Reset the device warmly
561 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
562 """
563 return self._syscfg.display_config()
564
565 def doc(self, name):
566 """Retreive doc string in system config file for given control name.
567
568 Args:
569 name: name string of control to get doc string
570
571 Returns:
572 doc string of name
573
574 Raises:
575 NameError: if fails to locate control
576 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700577 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700578 if self._syscfg.is_control(name):
579 return self._syscfg.get_control_docstring(name)
580 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700581 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700582
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800583 def safe_switch_usbkey_power(self, power_state, _=None):
Kevin Cheng5595b342016-09-29 15:51:01 -0700584 """Toggle the usb power safely.
585
Kevin Chengc49494e2016-07-25 12:13:38 -0700586 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700587 power_state: The setting to set for the usbkey power.
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800588 _: to conform to current API
Kevin Chengc49494e2016-07-25 12:13:38 -0700589
Kevin Cheng5595b342016-09-29 15:51:01 -0700590 Returns:
591 An empty string to appease the xmlrpc gods.
592 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800593 self.set('image_usbkey_pwr', power_state)
Kevin Cheng5595b342016-09-29 15:51:01 -0700594 return ''
595
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800596 def safe_switch_usbkey(self, mux_direction, _=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700597 """Toggle the usb direction safely.
598
Kevin Cheng5595b342016-09-29 15:51:01 -0700599 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800600 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800601 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700602
603 Returns:
604 An empty string to appease the xmlrpc gods.
605 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800606 self.set('image_usbkey_direction', mux_direction)
Kevin Cheng5595b342016-09-29 15:51:01 -0700607 return ''
608
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800609 def probe_host_usb_dev(self, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700610 """Probe the USB disk device plugged in the servo from the host side.
611
Kevin Cheng5595b342016-09-29 15:51:01 -0700612 Args:
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800613 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700614
Simran Basia9f41032012-05-11 14:21:58 -0700615 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700616 USB disk path if one and only one USB disk path is found, otherwise an
Simran Basia9f41032012-05-11 14:21:58 -0700617 """
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800618 return self.get('image_usbkey_dev')
Kevin Chengc49494e2016-07-25 12:13:38 -0700619
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800620 def download_image_to_usb(self, image_path, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700621 """Download image and save to the USB device found by probe_host_usb_dev.
622 If the image_path is a URL, it will download this url to the USB path;
623 otherwise it will simply copy the image_path's contents to the USB path.
624
625 Args:
626 image_path: path or url to the recovery image.
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800627 _: to conform to current API
Simran Basia9f41032012-05-11 14:21:58 -0700628
629 Returns:
630 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800631 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700632 """
Simran Basia9f41032012-05-11 14:21:58 -0700633 try:
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800634 self.set('download_image_to_usb_dev', image_path)
635 return True
636 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700637 return False
Simran Basia9f41032012-05-11 14:21:58 -0700638
639 def make_image_noninteractive(self):
640 """Makes the recovery image noninteractive.
641
642 A noninteractive image will reboot automatically after installation
643 instead of waiting for the USB device to be removed to initiate a system
644 reboot.
645
646 Mounts partition 1 of the image stored on usb_dev and creates a file
647 called "non_interactive" so that the image will become noninteractive.
648
649 Returns:
650 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800651 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700652 """
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800653 try:
654 usb_dev = self.get('image_usbkey_dev')
655 usb_dev_partition = '%s1' % usb_dev
656 self.set('make_usb_dev_image_noninteractive', usb_dev_partition)
657 return True
658 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700659 return False
Simran Basia9f41032012-05-11 14:21:58 -0700660
Todd Broch352b4b22013-03-22 09:48:40 -0700661 def set_get_all(self, cmds):
662 """Set &| get one or more control values.
663
664 Args:
665 cmds: list of control[:value] to get or set.
666
667 Returns:
668 rv: list of responses from calling get or set methods.
669 """
670 rv = []
671 for cmd in cmds:
672 if ':' in cmd:
Wai-Hong Tam269f1802019-05-16 12:37:17 -0700673 (control, value) = cmd.split(':', 1)
Todd Broch352b4b22013-03-22 09:48:40 -0700674 rv.append(self.set(control, value))
675 else:
676 rv.append(self.get(cmd))
677 return rv
678
Mary Ruthven493df512019-07-12 13:10:18 -0700679 def add_serial_number(self, name, serial_number):
680 """Adds the serial number to the _serialnames dictionary.
681
682 Args:
683 name: A string which is the key into the _serialnames dictionary.
684 serial_number: A string which is the key into the _serialnames dictionary.
685 """
686 self._serialnames[name] = serial_number
687 self._logger.debug('Added %s %s to serialnames %r', name, serial_number,
688 self._serialnames)
689
Aseda Aboagye6921f602017-08-01 14:45:38 -0700690 def get_serial_number(self, name):
691 """Returns the desired serial number from the serialnames dict.
692
693 Args:
694 name: A string which is the key into the _serialnames dictionary.
695
696 Returns:
697 A string containing the serial number or "unknown".
698 """
699 if not name:
700 name = 'main'
701
702 try:
703 return self._serialnames[name]
704 except KeyError:
705 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700706 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700707
Todd Broche505b8d2011-03-21 18:19:54 -0700708 def get(self, name):
709 """Get control value.
710
711 Args:
712 name: name string of control
713
714 Returns:
715 Response from calling drv get method. Value is reformatted based on
716 control's dictionary parameters
717
718 Raises:
719 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800720 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700721 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800722 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
723 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700724 self._logger.debug('name(%s)' % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700725 # This route is to retrieve serialnames on servo v4, which
726 # connects to multiple servo-micros or CCD, like the controls,
727 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
728 # TODO(aaboagye): Refactor it.
729 if 'serialname' in name:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700730 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700731
Todd Broche505b8d2011-03-21 18:19:54 -0700732 (param, drv) = self._get_param_drv(name)
733 try:
734 val = drv.get()
735 rd_val = self._syscfg.reformat_val(param, val)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700736 self._logger.debug('%s = %s' % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700737 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700738 except AttributeError, error:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700739 self._logger.error('Getting %s: %s' % (name, error))
Todd Brochfbc499d2011-06-16 16:09:58 -0700740 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800741 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700742 self._logger.error('Getting %s' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700743 raise
Todd Brochd6061672012-05-11 15:52:47 -0700744
Todd Broche505b8d2011-03-21 18:19:54 -0700745 def get_all(self, verbose):
746 """Get all controls values.
747
748 Args:
749 verbose: Boolean on whether to return doc info as well
750
751 Returns:
752 string creating from trying to get all values of all controls. In case of
753 error attempting access to control, response is 'ERR'.
754 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800755 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700756 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700757 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700758 try:
759 value = self.get(name)
760 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700761 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -0700762 pass
763 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700764 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700765 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700766 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800767 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700768
769 def set(self, name, wr_val_str):
770 """Set control.
771
772 Args:
773 name: name string of control
774 wr_val_str: value string to write. Can be integer, float or a
775 alpha-numerical that is mapped to a integer or float.
776
777 Raises:
778 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800779 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700780 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800781 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
782 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700783 self._logger.debug('name(%s) wr_val(%s)' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700784 (params, drv) = self._get_param_drv(name, False)
785 wr_val = self._syscfg.resolve_val(params, wr_val_str)
786 try:
787 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800788 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700789 self._logger.error('Setting %s -> %s' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700790 raise
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +0800791 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
792 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -0700793 # marshall/unmarshall
794 return True
795
Todd Brochd6061672012-05-11 15:52:47 -0700796 def hwinit(self, verbose=False):
797 """Initialize all controls.
798
799 These values are part of the system config XML files of the form
800 init=<value>. This command should be used by clients wishing to return the
801 servo and DUT its connected to a known good/safe state.
802
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800803 Note that initialization errors are ignored (as in some cases they could
804 be caused by DUT firmware deficiencies). This might need to be fine tuned
805 later.
806
Todd Brochd6061672012-05-11 15:52:47 -0700807 Args:
808 verbose: boolean, if True prints info about control initialized.
809 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800810
811 Returns:
812 This function is called across RPC and as such is expected to return
813 something unless transferring 'none' across is allowed. Hence adding a
814 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700815 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800816 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800817 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700818 # Workaround for bug chrome-os-partner:42349. Without this check, the
819 # gpio will briefly pulse low if we set it from high to high.
820 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700821 self.set(control_name, value)
822 if verbose:
823 self._logger.info('Initialized %s to %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700824 except Exception as e:
825 self._logger.error(
Matthew Bleckera5d979c2018-10-16 20:59:19 -0700826 'Problem initializing %s -> %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700827 self._logger.error(str(e))
828 self._logger.error('Please consider verifying the logs and if the '
829 'error is not just a setup issue, consider filing '
830 'a bug. Also checkout go/servo-ki.')
Nick Sandersbc836282015-12-08 21:19:23 -0800831
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800832 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800833
Todd Broche505b8d2011-03-21 18:19:54 -0700834 def echo(self, echo):
835 """Dummy echo function for testing/examples.
836
837 Args:
838 echo: string to echo back to client
839 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700840 self._logger.debug('echo(%s)' % (echo))
841 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -0700842
J. Richard Barnettee2820552013-03-14 16:13:46 -0700843 def get_board(self):
844 """Return the board specified at startup, if any."""
845 return self._board
846
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700847 def get_base_board(self):
848 """Returns the board name of the base if present.
849
850 Returns:
851 A string of the board name, or '' if not present.
852 """
853 # The value is set in servo_postinit.
854 return self._base_board
855
Simran Basia23c1392013-08-06 14:59:10 -0700856 def get_version(self):
857 """Get servo board version."""
858 return self._version
859
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800860 def power_long_press(self):
861 """Simulate a long power button press."""
862 # After a long power press, the EC may ignore the next power
863 # button press (at least on Alex). To guarantee that this
864 # won't happen, we need to allow the EC one second to
865 # collect itself.
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800866 return self.set('power_key', 'long_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800867
868 def power_normal_press(self):
869 """Simulate a normal power button press."""
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800870 return self.set('power_key', 'press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800871
872 def power_short_press(self):
873 """Simulate a short power button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530874 return self.set('power_key', 'short_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800875
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530876 def power_key(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800877 """Simulate a power button press.
878
879 Args:
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530880 press_secs: Time in seconds to simulate the keypress.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800881 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530882 return self.set('power_key', 'press' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800883
884 def ctrl_d(self, press_secs=''):
885 """Simulate Ctrl-d simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530886 return self.set('ctrl_d', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800887
Victor Dodone539cea2016-03-29 18:50:17 -0700888 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800889 """Simulate Ctrl-u simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530890 return self.set('ctrl_u', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800891
892 def ctrl_enter(self, press_secs=''):
893 """Simulate Ctrl-enter simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530894 return self.set('ctrl_enter', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800895
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800896 def ctrl_key(self, press_secs=''):
897 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530898 return self.set('ctrl_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800899
900 def enter_key(self, press_secs=''):
901 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530902 return self.set('enter_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800903
904 def refresh_key(self, press_secs=''):
905 """Simulate Refresh key (F3) button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530906 return self.set('refresh_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800907
908 def ctrl_refresh_key(self, press_secs=''):
909 """Simulate Ctrl and Refresh (F3) simultaneous press.
910
911 This key combination is an alternative of Space key.
912 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530913 return self.set('ctrl_refresh_key', ('tab' if press_secs is '' else
914 press_secs))
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800915
916 def imaginary_key(self, press_secs=''):
917 """Simulate imaginary key button press.
918
919 Maps to a key that doesn't physically exist.
920 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530921 return self.set('imaginary_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800922
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200923 def sysrq_x(self, press_secs=''):
924 """Simulate Alt VolumeUp X simultaneous press.
925
926 This key combination is the kernel system request (sysrq) x.
927 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530928 return self.set('sysrq_x', 'tab' if press_secs is '' else press_secs)
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200929
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700930 def get_servo_serials(self):
931 """Return all the serials associated with this process."""
932 return self._serialnames
933
934
Todd Broche505b8d2011-03-21 18:19:54 -0700935def test():
936 """Integration testing.
937
938 TODO(tbroch) Enhance integration test and add unittest (see mox)
939 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700940 logging.basicConfig(
941 level=logging.DEBUG,
942 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -0700943 # configure server & listen
944 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700945 # 5 == number of interfaces on a FT4232H device
946 for i in xrange(1, 5):
947 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -0700948 # its an i2c interface ... see __init__ for details and TODO to make
949 # this configureable
950 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
951 else:
952 # its a gpio interface
953 servod_obj._interface_list[i].wr_rd(0)
954
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700955 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost', 9999),
Todd Broche505b8d2011-03-21 18:19:54 -0700956 allow_none=True)
957 server.register_introspection_functions()
958 server.register_multicall_functions()
959 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700960 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -0700961 server.serve_forever()
962
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700963
964if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -0700965 test()
966
967 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700968 """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)
969
Todd Broche505b8d2011-03-21 18:19:54 -0700970 """