blob: 277ac6979ca96dc17044a3ae48afe71377196037 [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
Mary Ruthvencb861852019-07-15 16:30:48 -070028import servo_dev
Simran Basie750a342013-03-12 13:45:26 -070029import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070030import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080031import stm32gpio
32import stm32i2c
33import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070034
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080035HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080036
Todd Broche505b8d2011-03-21 18:19:54 -070037MAX_I2C_CLOCK_HZ = 100000
38
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070039
Todd Broche505b8d2011-03-21 18:19:54 -070040class ServodError(Exception):
41 """Exception class for servod."""
42
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070043
Todd Broche505b8d2011-03-21 18:19:54 -070044class Servod(object):
45 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070046
Kevin Cheng4b4f0022016-09-09 02:37:07 -070047 # This is the key to get the main serial used in the _serialnames dict.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070048 MAIN_SERIAL = 'main'
49 SERVO_MICRO_SERIAL = 'servo_micro'
50 CCD_SERIAL = 'ccd'
Kevin Cheng4b4f0022016-09-09 02:37:07 -070051
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080052 # Timeout to wait for interfaces to become available again if reinitialization
Mary Ruthvenb7cc5542019-07-15 15:20:10 -070053 # is taking place. In seconds. This is supposed to recover from brief resets.
54 # If the interface disappears for more than 5 seconds, then someone probably
55 # intentionally disconnected the device. Servod shouldn't be responsible for
56 # waiting for the device during an intentional disconnect.
57 INTERFACE_AVAILABILITY_TIMEOUT = 5
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080058
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070059 def init_servo_interfaces(self, vendor, product, serialname, interfaces):
Kevin Chengdc3befd2016-07-15 12:34:00 -070060 """Init the servo interfaces with the given interfaces.
61
62 We don't use the self._{vendor,product,serialname} attributes because we
63 want to allow other callers to initialize other interfaces that may not
64 be associated with the initialized attributes (e.g. a servo v4 servod object
65 that wants to also initialize a servo micro interface).
66
67 Args:
68 vendor: USB vendor id of FTDI device.
69 product: USB product id of FTDI device.
70 serialname: String of device serialname/number as defined in FTDI
71 eeprom.
72 interfaces: List of strings of interface types the server will
73 instantiate.
74
75 Raises:
76 ServodError if unable to locate init method for particular interface.
77 """
Mary Ruthven13389642017-02-14 12:15:34 -080078 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070079 device = (vendor, product, serialname)
Mary Ruthvencb861852019-07-15 16:30:48 -070080 self.add_device(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 Ruthvencb861852019-07-15 16:30:48 -0700159 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.
Mary Ruthvencb861852019-07-15 16:30:48 -0700195 for device in self._devices.values():
196 device.connect()
Mary Ruthven13389642017-02-14 12:15:34 -0800197
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700198 def get_servo_interfaces(self, position, size):
199 """Get the list of servo interfaces.
200
201 Args:
202 position: The index the first interface to get.
203 size: The number of the interfaces.
204 """
205 return self._interface_list[position:(position + size)]
206
207 def set_servo_interfaces(self, position, interfaces):
208 """Set the list of servo interfaces.
209
210 Args:
211 position: The index the first interface to set.
212 interfaces: The list of interfaces to set.
213 """
214 size = len(interfaces)
215 self._interface_list[position:(position + size)] = interfaces
216
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700217 def close(self):
218 """Servod turn down logic."""
219 for i, interface in enumerate(self._interface_list):
220 self._logger.info('Turning down interface %d' % i)
221 if hasattr(interface, 'close'):
222 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800223
Mary Ruthvencb861852019-07-15 16:30:48 -0700224 def get_devices(self):
225 return self._devices.values()
226
227 def add_device(self, device):
228 if device not in self._devices:
229 vid, pid, serial = device
230 servod_device = servo_dev.ServoDevice(vid, pid, serial,
231 self._ifaces_available)
232 self._devices[device] = servod_device
233
Kevin Chengdc3befd2016-07-15 12:34:00 -0700234 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700235 """Dummy interface for ftdi devices.
236
237 This is a dummy function specifically for ftdi devices to not initialize
238 anything but to help pad the interface list.
239
240 Returns:
241 None.
242 """
243 return None
244
Kevin Chengdc3befd2016-07-15 12:34:00 -0700245 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700246 """Initialize gpio driver interface and open for use.
247
248 Args:
249 interface: interface number of FTDI device to use.
250
251 Returns:
252 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700253
254 Raises:
255 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700256 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700257 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700258 try:
259 fobj.open()
260 except ftdigpio.FgpioError as e:
261 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
262
Todd Broche505b8d2011-03-21 18:19:54 -0700263 return fobj
264
Kevin Chengdc3befd2016-07-15 12:34:00 -0700265 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800266 """Initialize stm32 uart interface and open for use
267
268 Note, the uart runs in a separate thread. Users wishing to
269 interact with it will query control for the pty's pathname and connect
270 with their favorite console program. For example:
271 cu -l /dev/pts/22
272
273 Args:
274 interface: dict of interface parameters.
275
276 Returns:
277 Instance object of interface
278
279 Raises:
280 ServodError: Raised on init failure.
281 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700282 self._logger.info('Suart: interface: %s' % interface)
283 sobj = stm32uart.Suart(vendor, product, interface['interface'], serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800284
285 try:
286 sobj.run()
287 except stm32uart.SuartError as e:
288 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
289
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700290 self._logger.info('%s' % sobj.get_pty())
Nick Sanders97bc4462016-01-04 15:37:31 -0800291 return sobj
292
Kevin Chengdc3befd2016-07-15 12:34:00 -0700293 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800294 """Initialize stm32 gpio interface.
295 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700296 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800297
298 Returns:
299 Instance object of interface
300
301 Raises:
302 SgpioError: Raised on init failure.
303 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700304 interface_number = interface
305 # Interface could be a dict.
306 if type(interface) is dict:
307 interface_number = interface['interface']
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700308 self._logger.info('Sgpio: interface: %s' % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700309 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800310
Kevin Chengdc3befd2016-07-15 12:34:00 -0700311 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800312 """Initialize stm32 USB to I2C bridge interface and open for use
313
314 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700315 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800316
317 Returns:
318 Instance object of interface.
319
320 Raises:
321 Si2cError: Raised on init failure.
322 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700323 self._logger.info('Si2cBus: interface: %s' % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800324 port = interface.get('port', 0)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700325 return stm32i2c.Si2cBus(vendor, product, interface['interface'], port=port,
326 serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800327
Kevin Chengdc3befd2016-07-15 12:34:00 -0700328 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800329 """Initalize beaglebone ADC interface."""
330 return bbadc.BBadc()
331
Kevin Chengdc3befd2016-07-15 12:34:00 -0700332 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700333 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700334 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700335
Kevin Chengdc3befd2016-07-15 12:34:00 -0700336 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700337 """Initialize i2c interface and open for use.
338
339 Args:
340 interface: interface number of FTDI device to use
341
342 Returns:
343 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700344
345 Raises:
346 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700347 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700348 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700349 try:
350 fobj.open()
351 except ftdii2c.Fi2cError as e:
352 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
353
Todd Broche505b8d2011-03-21 18:19:54 -0700354 # Set the frequency of operation of the i2c bus.
355 # TODO(tbroch) make configureable
356 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700357
Todd Broche505b8d2011-03-21 18:19:54 -0700358 return fobj
359
Simran Basie750a342013-03-12 13:45:26 -0700360 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
361 def _init_bb_i2c(self, interface):
362 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700363 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700364
Kevin Chengdc3befd2016-07-15 12:34:00 -0700365 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800366 """Initalize Linux i2c-dev interface."""
367 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
368
Kevin Chengdc3befd2016-07-15 12:34:00 -0700369 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700370 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700371
372 Note, the uart runs in a separate thread (pthreads). Users wishing to
373 interact with it will query control for the pty's pathname and connect
374 with there favorite console program. For example:
375 cu -l /dev/pts/22
376
377 Args:
378 interface: interface number of FTDI device to use
379
380 Returns:
381 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700382
383 Raises:
384 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700385 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700386 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700387 try:
388 fobj.run()
389 except ftdiuart.FuartError as e:
390 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
391
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700392 self._logger.info('%s' % fobj.get_pty())
Todd Broch47c43f42011-05-26 15:11:31 -0700393 return fobj
394
Simran Basie750a342013-03-12 13:45:26 -0700395 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700396 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700397 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700398 logging.debug('UART INTERFACE: %s', interface)
399 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700400
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700401 def _init_ftdi_gpiouart(self, vendor, product, serialname, interface):
Todd Broch888da782011-10-07 14:29:09 -0700402 """Initialize special gpio + uart interface and open for use
403
404 Note, the uart runs in a separate thread (pthreads). Users wishing to
405 interact with it will query control for the pty's pathname and connect
406 with there favorite console program. For example:
407 cu -l /dev/pts/22
408
409 Args:
410 interface: interface number of FTDI device to use
411
412 Returns:
413 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700414
415 Raises:
416 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700417 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700418 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700419 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700420 try:
421 fuart.run()
422 except ftdiuart.FuartError as e:
423 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
424
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700425 self._logger.info('uart pty: %s' % fuart.get_pty())
Todd Broch888da782011-10-07 14:29:09 -0700426 return fgpio, fuart
427
Kevin Chengdc3befd2016-07-15 12:34:00 -0700428 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800429 """Initialize EC-3PO console interpreter interface.
430
431 Args:
432 interface: A dictionary representing the interface.
433
434 Returns:
435 An EC3PO object representing the EC-3PO interface or None if there's no
436 interface for the USB PD UART.
437 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700438 raw_uart_name = interface['raw_pty']
Nick Sanders116ed9e2018-03-09 19:05:16 -0800439 raw_uart_source = interface['source']
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700440 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800441 raw_ec_uart = self.get(raw_uart_name)
Nick Sanders116ed9e2018-03-09 19:05:16 -0800442 return ec3po_interface.EC3PO(raw_ec_uart, raw_uart_source)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800443 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700444 # The overlay doesn't have the raw PTY defined, therefore we can skip
445 # initializing this interface since no control relies on it.
446 self._logger.debug(
447 'Skip initializing EC3PO for %s, no control specified.',
448 raw_uart_name)
449 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800450
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800451 def _camel_case(self, string):
452 output = ''
453 for s in string.split('_'):
454 if output:
455 output += s.capitalize()
456 else:
457 output = s
458 return output
459
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700460 def clear_cached_drv(self):
461 """Clear the cached drivers.
462
463 The drivers are cached in the Dict _drv_dict when a control is got or set.
464 When the servo interfaces are relocated, the cached values may become wrong.
465 Should call this method to clear the cached values.
466 """
467 self._drv_dict = {}
468
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800469 def _get_servo_specific_param(self, params, param_key, control_name):
470 """Get |param_key| from params by looking for servo specific params first.
471
472 Find the candidate servos. Using servo_v4 with a servo_micro connected as
473 example, the following shows the priority for selecting the interface.
474
475 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
476 2. servo_micro_interface
477 3. servo_v4_interface
478 4. Fallback to the default, interface.
479
480 Args:
481 params: params dictionary for a control
482 param_key: identifier in the params dictionary to look for
483 control_name: control name the params correspond to
484
485 Returns:
486 The best suited param value for param_key given the servo type or
487 None if even the default is not defined.
488 """
489 candidates = [self._version]
490 candidates.extend(reversed(self._version.split('_with_')))
491 candidates = ['%s_%s' % (c, param_key) for c in candidates]
492 candidates.append(param_key)
493 for c in candidates:
494 if c in params:
495 self._logger.debug('Using %s parameter.', c)
496 return params[c]
497 self._logger.error('Unable to determine %s for %s', param_key, control_name)
498 self._logger.error('params: %r', params)
499 return None
500
Todd Broche505b8d2011-03-21 18:19:54 -0700501 def _get_param_drv(self, control_name, is_get=True):
502 """Get access to driver for a given control.
503
504 Note, some controls have different parameter dictionaries for 'getting' the
505 control's value versus 'setting' it. Boolean is_get distinguishes which is
506 being requested.
507
508 Args:
509 control_name: string name of control
510 is_get: boolean to determine
511
512 Returns:
513 tuple (param, drv) where:
514 param: param dictionary for control
515 drv: instance object of driver for particular control
516
517 Raises:
518 ServodError: Error occurred while examining params dict
519 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700520 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700521 # if already setup just return tuple from driver dict
522 if control_name in self._drv_dict:
523 if is_get and ('get' in self._drv_dict[control_name]):
524 return self._drv_dict[control_name]['get']
525 if not is_get and ('set' in self._drv_dict[control_name]):
526 return self._drv_dict[control_name]['set']
527
528 params = self._syscfg.lookup_control_params(control_name, is_get)
Simran Basi668be0e2013-08-07 11:54:50 -0700529
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800530 # Get the most suitable drv given the servo instance.
531 drv_name = self._get_servo_specific_param(params, 'drv', control_name)
532 if drv_name == 'na':
533 # 'na' drv can be used to selectively turn controls into noops for
534 # a given servo hardware. Ensure that there is an interface.
535 params.setdefault('interface', 'servo')
536 self._logger.debug('Setting interface to default to %r for %r unless '
537 ' defined in params, as drv is %r.', 'servo',
538 control_name, 'na')
539 # Setting input_type to str allows all inputs through enabling a true noop
540 params.update({'input_type': 'str'})
541 interface_id = self._get_servo_specific_param(params, 'interface',
542 control_name)
543 if None in [drv_name, interface_id]:
544 raise ServodError('No drv/interface for control %r found' % control_name)
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700545
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800546 if interface_id == 'servo':
547 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700548 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700549 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800550 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700551
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800552 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800553 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700554 drv = drv_class(interface, params)
555 if control_name not in self._drv_dict:
556 self._drv_dict[control_name] = {}
557 if is_get:
558 self._drv_dict[control_name]['get'] = (params, drv)
559 else:
560 self._drv_dict[control_name]['set'] = (params, drv)
561 return (params, drv)
562
563 def doc_all(self):
564 """Return all documenation for controls.
565
566 Returns:
567 string of <doc> text in config file (xml) and the params dictionary for
568 all controls.
569
570 For example:
571 warm_reset :: Reset the device warmly
572 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
573 """
574 return self._syscfg.display_config()
575
576 def doc(self, name):
577 """Retreive doc string in system config file for given control name.
578
579 Args:
580 name: name string of control to get doc string
581
582 Returns:
583 doc string of name
584
585 Raises:
586 NameError: if fails to locate control
587 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700588 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700589 if self._syscfg.is_control(name):
590 return self._syscfg.get_control_docstring(name)
591 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700592 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700593
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800594 def safe_switch_usbkey_power(self, power_state, _=None):
Kevin Cheng5595b342016-09-29 15:51:01 -0700595 """Toggle the usb power safely.
596
Kevin Chengc49494e2016-07-25 12:13:38 -0700597 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700598 power_state: The setting to set for the usbkey power.
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800599 _: to conform to current API
Kevin Chengc49494e2016-07-25 12:13:38 -0700600
Kevin Cheng5595b342016-09-29 15:51:01 -0700601 Returns:
602 An empty string to appease the xmlrpc gods.
603 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800604 self.set('image_usbkey_pwr', power_state)
Kevin Cheng5595b342016-09-29 15:51:01 -0700605 return ''
606
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800607 def safe_switch_usbkey(self, mux_direction, _=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700608 """Toggle the usb direction safely.
609
Kevin Cheng5595b342016-09-29 15:51:01 -0700610 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800611 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800612 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700613
614 Returns:
615 An empty string to appease the xmlrpc gods.
616 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800617 self.set('image_usbkey_direction', mux_direction)
Kevin Cheng5595b342016-09-29 15:51:01 -0700618 return ''
619
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800620 def probe_host_usb_dev(self, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700621 """Probe the USB disk device plugged in the servo from the host side.
622
Kevin Cheng5595b342016-09-29 15:51:01 -0700623 Args:
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800624 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700625
Simran Basia9f41032012-05-11 14:21:58 -0700626 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700627 USB disk path if one and only one USB disk path is found, otherwise an
Simran Basia9f41032012-05-11 14:21:58 -0700628 """
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800629 return self.get('image_usbkey_dev')
Kevin Chengc49494e2016-07-25 12:13:38 -0700630
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800631 def download_image_to_usb(self, image_path, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700632 """Download image and save to the USB device found by probe_host_usb_dev.
633 If the image_path is a URL, it will download this url to the USB path;
634 otherwise it will simply copy the image_path's contents to the USB path.
635
636 Args:
637 image_path: path or url to the recovery image.
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800638 _: to conform to current API
Simran Basia9f41032012-05-11 14:21:58 -0700639
640 Returns:
641 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800642 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700643 """
Simran Basia9f41032012-05-11 14:21:58 -0700644 try:
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800645 self.set('download_image_to_usb_dev', image_path)
646 return True
647 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700648 return False
Simran Basia9f41032012-05-11 14:21:58 -0700649
650 def make_image_noninteractive(self):
651 """Makes the recovery image noninteractive.
652
653 A noninteractive image will reboot automatically after installation
654 instead of waiting for the USB device to be removed to initiate a system
655 reboot.
656
657 Mounts partition 1 of the image stored on usb_dev and creates a file
658 called "non_interactive" so that the image will become noninteractive.
659
660 Returns:
661 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800662 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700663 """
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800664 try:
665 usb_dev = self.get('image_usbkey_dev')
666 usb_dev_partition = '%s1' % usb_dev
667 self.set('make_usb_dev_image_noninteractive', usb_dev_partition)
668 return True
669 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700670 return False
Simran Basia9f41032012-05-11 14:21:58 -0700671
Todd Broch352b4b22013-03-22 09:48:40 -0700672 def set_get_all(self, cmds):
673 """Set &| get one or more control values.
674
675 Args:
676 cmds: list of control[:value] to get or set.
677
678 Returns:
679 rv: list of responses from calling get or set methods.
680 """
681 rv = []
682 for cmd in cmds:
683 if ':' in cmd:
Wai-Hong Tam269f1802019-05-16 12:37:17 -0700684 (control, value) = cmd.split(':', 1)
Todd Broch352b4b22013-03-22 09:48:40 -0700685 rv.append(self.set(control, value))
686 else:
687 rv.append(self.get(cmd))
688 return rv
689
Mary Ruthven493df512019-07-12 13:10:18 -0700690 def add_serial_number(self, name, serial_number):
691 """Adds the serial number to the _serialnames dictionary.
692
693 Args:
694 name: A string which is the key into the _serialnames dictionary.
695 serial_number: A string which is the key into the _serialnames dictionary.
696 """
697 self._serialnames[name] = serial_number
698 self._logger.debug('Added %s %s to serialnames %r', name, serial_number,
699 self._serialnames)
700
Aseda Aboagye6921f602017-08-01 14:45:38 -0700701 def get_serial_number(self, name):
702 """Returns the desired serial number from the serialnames dict.
703
704 Args:
705 name: A string which is the key into the _serialnames dictionary.
706
707 Returns:
708 A string containing the serial number or "unknown".
709 """
710 if not name:
711 name = 'main'
712
713 try:
714 return self._serialnames[name]
715 except KeyError:
716 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700717 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700718
Todd Broche505b8d2011-03-21 18:19:54 -0700719 def get(self, name):
720 """Get control value.
721
722 Args:
723 name: name string of control
724
725 Returns:
726 Response from calling drv get method. Value is reformatted based on
727 control's dictionary parameters
728
729 Raises:
730 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800731 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700732 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800733 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
734 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700735 self._logger.debug('name(%s)' % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700736 # This route is to retrieve serialnames on servo v4, which
737 # connects to multiple servo-micros or CCD, like the controls,
738 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
739 # TODO(aaboagye): Refactor it.
740 if 'serialname' in name:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700741 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700742
Todd Broche505b8d2011-03-21 18:19:54 -0700743 (param, drv) = self._get_param_drv(name)
744 try:
745 val = drv.get()
746 rd_val = self._syscfg.reformat_val(param, val)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700747 self._logger.debug('%s = %s' % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700748 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700749 except AttributeError, error:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700750 self._logger.error('Getting %s: %s' % (name, error))
Todd Brochfbc499d2011-06-16 16:09:58 -0700751 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800752 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700753 self._logger.error('Getting %s' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700754 raise
Todd Brochd6061672012-05-11 15:52:47 -0700755
Todd Broche505b8d2011-03-21 18:19:54 -0700756 def get_all(self, verbose):
757 """Get all controls values.
758
759 Args:
760 verbose: Boolean on whether to return doc info as well
761
762 Returns:
763 string creating from trying to get all values of all controls. In case of
764 error attempting access to control, response is 'ERR'.
765 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800766 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700767 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700768 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700769 try:
770 value = self.get(name)
771 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700772 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -0700773 pass
774 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700775 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700776 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700777 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800778 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700779
780 def set(self, name, wr_val_str):
781 """Set control.
782
783 Args:
784 name: name string of control
785 wr_val_str: value string to write. Can be integer, float or a
786 alpha-numerical that is mapped to a integer or float.
787
788 Raises:
789 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800790 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700791 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800792 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
793 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700794 self._logger.debug('name(%s) wr_val(%s)' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700795 (params, drv) = self._get_param_drv(name, False)
796 wr_val = self._syscfg.resolve_val(params, wr_val_str)
797 try:
798 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800799 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700800 self._logger.error('Setting %s -> %s' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700801 raise
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +0800802 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
803 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -0700804 # marshall/unmarshall
805 return True
806
Todd Brochd6061672012-05-11 15:52:47 -0700807 def hwinit(self, verbose=False):
808 """Initialize all controls.
809
810 These values are part of the system config XML files of the form
811 init=<value>. This command should be used by clients wishing to return the
812 servo and DUT its connected to a known good/safe state.
813
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800814 Note that initialization errors are ignored (as in some cases they could
815 be caused by DUT firmware deficiencies). This might need to be fine tuned
816 later.
817
Todd Brochd6061672012-05-11 15:52:47 -0700818 Args:
819 verbose: boolean, if True prints info about control initialized.
820 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800821
822 Returns:
823 This function is called across RPC and as such is expected to return
824 something unless transferring 'none' across is allowed. Hence adding a
825 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700826 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800827 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800828 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700829 # Workaround for bug chrome-os-partner:42349. Without this check, the
830 # gpio will briefly pulse low if we set it from high to high.
831 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700832 self.set(control_name, value)
833 if verbose:
834 self._logger.info('Initialized %s to %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700835 except Exception as e:
836 self._logger.error(
Matthew Bleckera5d979c2018-10-16 20:59:19 -0700837 'Problem initializing %s -> %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700838 self._logger.error(str(e))
839 self._logger.error('Please consider verifying the logs and if the '
840 'error is not just a setup issue, consider filing '
841 'a bug. Also checkout go/servo-ki.')
Nick Sandersbc836282015-12-08 21:19:23 -0800842
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800843 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800844
Todd Broche505b8d2011-03-21 18:19:54 -0700845 def echo(self, echo):
846 """Dummy echo function for testing/examples.
847
848 Args:
849 echo: string to echo back to client
850 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700851 self._logger.debug('echo(%s)' % (echo))
852 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -0700853
J. Richard Barnettee2820552013-03-14 16:13:46 -0700854 def get_board(self):
855 """Return the board specified at startup, if any."""
856 return self._board
857
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700858 def get_base_board(self):
859 """Returns the board name of the base if present.
860
861 Returns:
862 A string of the board name, or '' if not present.
863 """
864 # The value is set in servo_postinit.
865 return self._base_board
866
Simran Basia23c1392013-08-06 14:59:10 -0700867 def get_version(self):
868 """Get servo board version."""
869 return self._version
870
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800871 def power_long_press(self):
872 """Simulate a long power button press."""
873 # After a long power press, the EC may ignore the next power
874 # button press (at least on Alex). To guarantee that this
875 # won't happen, we need to allow the EC one second to
876 # collect itself.
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800877 return self.set('power_key', 'long_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800878
879 def power_normal_press(self):
880 """Simulate a normal power button press."""
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800881 return self.set('power_key', 'press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800882
883 def power_short_press(self):
884 """Simulate a short power button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530885 return self.set('power_key', 'short_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800886
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530887 def power_key(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800888 """Simulate a power button press.
889
890 Args:
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530891 press_secs: Time in seconds to simulate the keypress.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800892 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530893 return self.set('power_key', 'press' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800894
895 def ctrl_d(self, press_secs=''):
896 """Simulate Ctrl-d simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530897 return self.set('ctrl_d', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800898
Victor Dodone539cea2016-03-29 18:50:17 -0700899 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800900 """Simulate Ctrl-u simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530901 return self.set('ctrl_u', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800902
903 def ctrl_enter(self, press_secs=''):
904 """Simulate Ctrl-enter simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530905 return self.set('ctrl_enter', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800906
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800907 def ctrl_key(self, press_secs=''):
908 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530909 return self.set('ctrl_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800910
911 def enter_key(self, press_secs=''):
912 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530913 return self.set('enter_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800914
915 def refresh_key(self, press_secs=''):
916 """Simulate Refresh key (F3) button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530917 return self.set('refresh_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800918
919 def ctrl_refresh_key(self, press_secs=''):
920 """Simulate Ctrl and Refresh (F3) simultaneous press.
921
922 This key combination is an alternative of Space key.
923 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530924 return self.set('ctrl_refresh_key', ('tab' if press_secs is '' else
925 press_secs))
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800926
927 def imaginary_key(self, press_secs=''):
928 """Simulate imaginary key button press.
929
930 Maps to a key that doesn't physically exist.
931 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530932 return self.set('imaginary_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800933
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200934 def sysrq_x(self, press_secs=''):
935 """Simulate Alt VolumeUp X simultaneous press.
936
937 This key combination is the kernel system request (sysrq) x.
938 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530939 return self.set('sysrq_x', 'tab' if press_secs is '' else press_secs)
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200940
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700941 def get_servo_serials(self):
942 """Return all the serials associated with this process."""
943 return self._serialnames
944
945
Todd Broche505b8d2011-03-21 18:19:54 -0700946def test():
947 """Integration testing.
948
949 TODO(tbroch) Enhance integration test and add unittest (see mox)
950 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700951 logging.basicConfig(
952 level=logging.DEBUG,
953 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -0700954 # configure server & listen
955 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700956 # 5 == number of interfaces on a FT4232H device
957 for i in xrange(1, 5):
958 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -0700959 # its an i2c interface ... see __init__ for details and TODO to make
960 # this configureable
961 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
962 else:
963 # its a gpio interface
964 servod_obj._interface_list[i].wr_rd(0)
965
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700966 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost', 9999),
Todd Broche505b8d2011-03-21 18:19:54 -0700967 allow_none=True)
968 server.register_introspection_functions()
969 server.register_multicall_functions()
970 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700971 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -0700972 server.serve_forever()
973
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700974
975if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -0700976 test()
977
978 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700979 """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)
980
Todd Broche505b8d2011-03-21 18:19:54 -0700981 """