blob: 70579310aae377cdce223b32cd3d42b64a657904 [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
Todd Broch7a91c252012-02-03 12:37:45 -080012import time
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070013import usb
Todd Broche505b8d2011-03-21 18:19:54 -070014
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080015import drv as servo_drv
Aaron.Chuang88eff332014-07-31 08:32:00 +080016import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070017import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070018import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070019import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080020import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070021import ftdigpio
22import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070023import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070024import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080025import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080026import keyboard_handlers
Mary Ruthvencb861852019-07-15 16:30:48 -070027import servo_dev
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 Ruthvencb861852019-07-15 16:30:48 -070079 self.add_device(device)
Mary Ruthven13389642017-02-14 12:15:34 -080080
Kevin Chengdc3befd2016-07-15 12:34:00 -070081 # Extend the interface list if we need to.
82 interfaces_len = len(interfaces)
83 interface_list_len = len(self._interface_list)
84 if interfaces_len > interface_list_len:
85 self._interface_list += [None] * (interfaces_len - interface_list_len)
86
Kevin Chengdc3befd2016-07-15 12:34:00 -070087 for i, interface in enumerate(interfaces):
88 is_ftdi_interface = False
89 if type(interface) is dict:
90 name = interface['name']
91 # Store interface index for those that care about it.
92 interface['index'] = i
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -070093 elif type(interface) is str:
94 if interface == 'dummy':
95 # 'dummy' reserves the interface for future use. Typically the
96 # interface will be managed by external third-party tools like
97 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
98 # it serves as a placeholder for servo micro interfaces.
99 continue
Kevin Chengdc3befd2016-07-15 12:34:00 -0700100 name = interface
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -0700101 is_ftdi_interface = interface.startswith('ftdi')
Kevin Chengdc3befd2016-07-15 12:34:00 -0700102 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700103 raise ServodError('Illegal interface type %s' % type(interface))
Kevin Chengdc3befd2016-07-15 12:34:00 -0700104
105 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700106 product_increment = 0
107 if is_ftdi_interface:
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -0700108 # The interface argument in ftdi initialization is the interface number.
109 interface = ((i - 1) % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700110 product_increment = (i - 1) / ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE
111 if product_increment:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700112 self._logger.info('Use the next FTDI part @ pid = 0x%04x',
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700113 product + product_increment)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700114
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700115 self._logger.info('Initializing interface %d to %s', i, name)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700116 try:
117 func = getattr(self, '_init_%s' % name)
118 except AttributeError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700119 raise ServodError('Unable to locate init for interface %s' % name)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700120 result = func(vendor, product + product_increment, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700121
122 if isinstance(result, tuple):
123 result_len = len(result)
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700124 self._interface_list[i:(i + result_len)] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700125 else:
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700126 self._interface_list[i] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700127
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700128 def __init__(self, config, vendor, product, serialname=None, interfaces=None,
Namyoon Woo341a8332019-03-07 12:01:31 -0800129 board='', model='', version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700130 """Servod constructor.
131
132 Args:
133 config: instance of SystemConfig containing all controls for
134 particular Servod invocation
135 vendor: usb vendor id of FTDI device
136 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700137 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700138 interfaces: list of strings of interface types the server will instantiate
Namyoon Woo341a8332019-03-07 12:01:31 -0800139 board: board name. e.g. octopus, coral, or scarlet.
140 model: model name of a given board. e.g. fleex, ampton, or apel.
Simran Basia23c1392013-08-06 14:59:10 -0700141 version: String. Servo board version. Examples: servo_v1, servo_v2,
142 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800143 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700144 sending keyboard commands to DUTs that do not have built in
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700145 keyboards. Used in FAFT tests. Use None for on board AVR MCU.
146 e.g. '/dev/ttyUSB0' or None.
Todd Brochdbb09982011-10-02 07:14:26 -0700147
148 Raises:
149 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700150 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700151 self._logger = logging.getLogger('Servod')
152 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700153 self._vendor = vendor
154 self._product = product
Mary Ruthvencb861852019-07-15 16:30:48 -0700155 self._devices = {}
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700156 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700157 self._syscfg = config
158 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
159 # interfaces are mapped to
160 self._interface_list = []
161 # Dict of Dict to map control name, function name to to tuple (params, drv)
162 # Ex) _drv_dict[name]['get'] = (params, drv)
163 self._drv_dict = {}
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700164 self._base_board = ''
Namyoon Woo341a8332019-03-07 12:01:31 -0800165 self._board = board
166 if model:
167 self._board += '_' + model
168 self._model = model
Simran Basia23c1392013-08-06 14:59:10 -0700169 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800170 self._usbkm232 = usbkm232
Ruben Rodriguez Buchillon386a0102018-08-16 09:11:20 +0800171 self._keyboard = None
172 self._usb_keyboard = None
Todd Brochdbb09982011-10-02 07:14:26 -0700173 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700174 try:
175 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
176 except KeyError:
177 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Dino Lic89d8c82018-01-11 09:56:47 +0800178 self._interfaces = interfaces
Todd Brochdbb09982011-10-02 07:14:26 -0700179
Kevin Chengdc3befd2016-07-15 12:34:00 -0700180 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700181 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800182
Mary Ruthven13389642017-02-14 12:15:34 -0800183 def reinitialize(self):
184 """Reinitialize all interfaces that support reinitialization"""
Mary Ruthven13389642017-02-14 12:15:34 -0800185 for i, interface in enumerate(self._interface_list):
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700186 if hasattr(interface, 'reinitialize'):
187 interface.reinitialize()
188 else:
189 self._logger.debug('interface %d has no reset functionality', i)
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800190 # Indicate interfaces are safe to use again.
Mary Ruthvencb861852019-07-15 16:30:48 -0700191 for device in self._devices.values():
192 device.connect()
Mary Ruthven13389642017-02-14 12:15:34 -0800193
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700194 def get_servo_interfaces(self, position, size):
195 """Get the list of servo interfaces.
196
197 Args:
198 position: The index the first interface to get.
199 size: The number of the interfaces.
200 """
201 return self._interface_list[position:(position + size)]
202
203 def set_servo_interfaces(self, position, interfaces):
204 """Set the list of servo interfaces.
205
206 Args:
207 position: The index the first interface to set.
208 interfaces: The list of interfaces to set.
209 """
210 size = len(interfaces)
211 self._interface_list[position:(position + size)] = interfaces
212
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700213 def close(self):
214 """Servod turn down logic."""
215 for i, interface in enumerate(self._interface_list):
216 self._logger.info('Turning down interface %d' % i)
217 if hasattr(interface, 'close'):
218 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800219
Mary Ruthvencb861852019-07-15 16:30:48 -0700220 def get_devices(self):
221 return self._devices.values()
222
223 def add_device(self, device):
224 if device not in self._devices:
225 vid, pid, serial = device
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700226 servod_device = servo_dev.ServoDevice(vid, pid, serial)
Mary Ruthvencb861852019-07-15 16:30:48 -0700227 self._devices[device] = servod_device
228
Kevin Chengdc3befd2016-07-15 12:34:00 -0700229 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700230 """Dummy interface for ftdi devices.
231
232 This is a dummy function specifically for ftdi devices to not initialize
233 anything but to help pad the interface list.
234
235 Returns:
236 None.
237 """
238 return None
239
Kevin Chengdc3befd2016-07-15 12:34:00 -0700240 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700241 """Initialize gpio driver interface and open for use.
242
243 Args:
244 interface: interface number of FTDI device to use.
245
246 Returns:
247 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700248
249 Raises:
250 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700251 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700252 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700253 try:
254 fobj.open()
255 except ftdigpio.FgpioError as e:
256 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
257
Todd Broche505b8d2011-03-21 18:19:54 -0700258 return fobj
259
Kevin Chengdc3befd2016-07-15 12:34:00 -0700260 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800261 """Initialize stm32 uart interface and open for use
262
263 Note, the uart runs in a separate thread. Users wishing to
264 interact with it will query control for the pty's pathname and connect
265 with their favorite console program. For example:
266 cu -l /dev/pts/22
267
268 Args:
269 interface: dict of interface parameters.
270
271 Returns:
272 Instance object of interface
273
274 Raises:
275 ServodError: Raised on init failure.
276 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700277 self._logger.info('Suart: interface: %s' % interface)
278 sobj = stm32uart.Suart(vendor, product, interface['interface'], serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800279
280 try:
281 sobj.run()
282 except stm32uart.SuartError as e:
283 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
284
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700285 self._logger.info('%s' % sobj.get_pty())
Nick Sanders97bc4462016-01-04 15:37:31 -0800286 return sobj
287
Kevin Chengdc3befd2016-07-15 12:34:00 -0700288 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800289 """Initialize stm32 gpio interface.
290 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700291 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800292
293 Returns:
294 Instance object of interface
295
296 Raises:
297 SgpioError: Raised on init failure.
298 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700299 interface_number = interface
300 # Interface could be a dict.
301 if type(interface) is dict:
302 interface_number = interface['interface']
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700303 self._logger.info('Sgpio: interface: %s' % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700304 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800305
Kevin Chengdc3befd2016-07-15 12:34:00 -0700306 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800307 """Initialize stm32 USB to I2C bridge interface and open for use
308
309 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700310 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800311
312 Returns:
313 Instance object of interface.
314
315 Raises:
316 Si2cError: Raised on init failure.
317 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700318 self._logger.info('Si2cBus: interface: %s' % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800319 port = interface.get('port', 0)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700320 return stm32i2c.Si2cBus(vendor, product, interface['interface'], port=port,
321 serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800322
Kevin Chengdc3befd2016-07-15 12:34:00 -0700323 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800324 """Initalize beaglebone ADC interface."""
325 return bbadc.BBadc()
326
Kevin Chengdc3befd2016-07-15 12:34:00 -0700327 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700328 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700329 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700330
Kevin Chengdc3befd2016-07-15 12:34:00 -0700331 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700332 """Initialize i2c interface and open for use.
333
334 Args:
335 interface: interface number of FTDI device to use
336
337 Returns:
338 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700339
340 Raises:
341 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700342 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700343 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700344 try:
345 fobj.open()
346 except ftdii2c.Fi2cError as e:
347 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
348
Todd Broche505b8d2011-03-21 18:19:54 -0700349 # Set the frequency of operation of the i2c bus.
350 # TODO(tbroch) make configureable
351 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700352
Todd Broche505b8d2011-03-21 18:19:54 -0700353 return fobj
354
Simran Basie750a342013-03-12 13:45:26 -0700355 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
356 def _init_bb_i2c(self, interface):
357 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700358 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700359
Kevin Chengdc3befd2016-07-15 12:34:00 -0700360 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800361 """Initalize Linux i2c-dev interface."""
362 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
363
Kevin Chengdc3befd2016-07-15 12:34:00 -0700364 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700365 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700366
367 Note, the uart runs in a separate thread (pthreads). Users wishing to
368 interact with it will query control for the pty's pathname and connect
369 with there favorite console program. For example:
370 cu -l /dev/pts/22
371
372 Args:
373 interface: interface number of FTDI device to use
374
375 Returns:
376 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700377
378 Raises:
379 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700380 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700381 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700382 try:
383 fobj.run()
384 except ftdiuart.FuartError as e:
385 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
386
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700387 self._logger.info('%s' % fobj.get_pty())
Todd Broch47c43f42011-05-26 15:11:31 -0700388 return fobj
389
Simran Basie750a342013-03-12 13:45:26 -0700390 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700391 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700392 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700393 logging.debug('UART INTERFACE: %s', interface)
394 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700395
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700396 def _init_ftdi_gpiouart(self, vendor, product, serialname, interface):
Todd Broch888da782011-10-07 14:29:09 -0700397 """Initialize special gpio + uart interface and open for use
398
399 Note, the uart runs in a separate thread (pthreads). Users wishing to
400 interact with it will query control for the pty's pathname and connect
401 with there favorite console program. For example:
402 cu -l /dev/pts/22
403
404 Args:
405 interface: interface number of FTDI device to use
406
407 Returns:
408 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700409
410 Raises:
411 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700412 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700413 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700414 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700415 try:
416 fuart.run()
417 except ftdiuart.FuartError as e:
418 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
419
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700420 self._logger.info('uart pty: %s' % fuart.get_pty())
Todd Broch888da782011-10-07 14:29:09 -0700421 return fgpio, fuart
422
Kevin Chengdc3befd2016-07-15 12:34:00 -0700423 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800424 """Initialize EC-3PO console interpreter interface.
425
426 Args:
427 interface: A dictionary representing the interface.
428
429 Returns:
430 An EC3PO object representing the EC-3PO interface or None if there's no
431 interface for the USB PD UART.
432 """
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700433 device = (vendor, product, serialname)
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700434 raw_uart_name = interface['raw_pty']
Nick Sanders116ed9e2018-03-09 19:05:16 -0800435 raw_uart_source = interface['source']
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700436 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800437 raw_ec_uart = self.get(raw_uart_name)
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700438 return ec3po_interface.EC3PO(raw_ec_uart, raw_uart_source, device)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800439 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700440 # The overlay doesn't have the raw PTY defined, therefore we can skip
441 # initializing this interface since no control relies on it.
442 self._logger.debug(
443 'Skip initializing EC3PO for %s, no control specified.',
444 raw_uart_name)
445 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800446
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800447 def _camel_case(self, string):
448 output = ''
449 for s in string.split('_'):
450 if output:
451 output += s.capitalize()
452 else:
453 output = s
454 return output
455
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700456 def clear_cached_drv(self):
457 """Clear the cached drivers.
458
459 The drivers are cached in the Dict _drv_dict when a control is got or set.
460 When the servo interfaces are relocated, the cached values may become wrong.
461 Should call this method to clear the cached values.
462 """
463 self._drv_dict = {}
464
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800465 def _get_servo_specific_param(self, params, param_key, control_name):
466 """Get |param_key| from params by looking for servo specific params first.
467
468 Find the candidate servos. Using servo_v4 with a servo_micro connected as
469 example, the following shows the priority for selecting the interface.
470
471 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
472 2. servo_micro_interface
473 3. servo_v4_interface
474 4. Fallback to the default, interface.
475
476 Args:
477 params: params dictionary for a control
478 param_key: identifier in the params dictionary to look for
479 control_name: control name the params correspond to
480
481 Returns:
482 The best suited param value for param_key given the servo type or
483 None if even the default is not defined.
484 """
485 candidates = [self._version]
Matthew Blecker992d3242019-08-04 22:34:45 +0000486 candidates.extend(reversed(self._version.split('_with_')))
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800487 candidates = ['%s_%s' % (c, param_key) for c in candidates]
488 candidates.append(param_key)
489 for c in candidates:
490 if c in params:
491 self._logger.debug('Using %s parameter.', c)
492 return params[c]
493 self._logger.error('Unable to determine %s for %s', param_key, control_name)
494 self._logger.error('params: %r', params)
495 return None
496
Todd Broche505b8d2011-03-21 18:19:54 -0700497 def _get_param_drv(self, control_name, is_get=True):
498 """Get access to driver for a given control.
499
500 Note, some controls have different parameter dictionaries for 'getting' the
501 control's value versus 'setting' it. Boolean is_get distinguishes which is
502 being requested.
503
504 Args:
505 control_name: string name of control
506 is_get: boolean to determine
507
508 Returns:
509 tuple (param, drv) where:
510 param: param dictionary for control
511 drv: instance object of driver for particular control
512
513 Raises:
514 ServodError: Error occurred while examining params dict
515 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700516 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700517 # if already setup just return tuple from driver dict
518 if control_name in self._drv_dict:
519 if is_get and ('get' in self._drv_dict[control_name]):
520 return self._drv_dict[control_name]['get']
521 if not is_get and ('set' in self._drv_dict[control_name]):
522 return self._drv_dict[control_name]['set']
523
524 params = self._syscfg.lookup_control_params(control_name, is_get)
Simran Basi668be0e2013-08-07 11:54:50 -0700525
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800526 # Get the most suitable drv given the servo instance.
527 drv_name = self._get_servo_specific_param(params, 'drv', control_name)
528 if drv_name == 'na':
529 # 'na' drv can be used to selectively turn controls into noops for
530 # a given servo hardware. Ensure that there is an interface.
531 params.setdefault('interface', 'servo')
532 self._logger.debug('Setting interface to default to %r for %r unless '
533 ' defined in params, as drv is %r.', 'servo',
534 control_name, 'na')
535 # Setting input_type to str allows all inputs through enabling a true noop
536 params.update({'input_type': 'str'})
537 interface_id = self._get_servo_specific_param(params, 'interface',
538 control_name)
539 if None in [drv_name, interface_id]:
540 raise ServodError('No drv/interface for control %r found' % control_name)
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700541
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800542 if interface_id == 'servo':
543 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700544 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700545 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800546 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700547
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700548 device_info = None
549 if hasattr(interface, 'get_device_info'):
550 device_info = interface.get_device_info()
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800551 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800552 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700553 drv = drv_class(interface, params)
554 if control_name not in self._drv_dict:
555 self._drv_dict[control_name] = {}
556 if is_get:
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700557 self._drv_dict[control_name]['get'] = (params, drv, device_info)
Todd Broche505b8d2011-03-21 18:19:54 -0700558 else:
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700559 self._drv_dict[control_name]['set'] = (params, drv, device_info)
560 return (params, drv, device_info)
Todd Broche505b8d2011-03-21 18:19:54 -0700561
562 def doc_all(self):
563 """Return all documenation for controls.
564
565 Returns:
566 string of <doc> text in config file (xml) and the params dictionary for
567 all controls.
568
569 For example:
570 warm_reset :: Reset the device warmly
571 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
572 """
573 return self._syscfg.display_config()
574
575 def doc(self, name):
576 """Retreive doc string in system config file for given control name.
577
578 Args:
579 name: name string of control to get doc string
580
581 Returns:
582 doc string of name
583
584 Raises:
585 NameError: if fails to locate control
586 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700587 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700588 if self._syscfg.is_control(name):
589 return self._syscfg.get_control_docstring(name)
590 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700591 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700592
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800593 def safe_switch_usbkey_power(self, power_state, _=None):
Kevin Cheng5595b342016-09-29 15:51:01 -0700594 """Toggle the usb power safely.
595
Kevin Chengc49494e2016-07-25 12:13:38 -0700596 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700597 power_state: The setting to set for the usbkey power.
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800598 _: to conform to current API
Kevin Chengc49494e2016-07-25 12:13:38 -0700599
Kevin Cheng5595b342016-09-29 15:51:01 -0700600 Returns:
601 An empty string to appease the xmlrpc gods.
602 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800603 self.set('image_usbkey_pwr', power_state)
Kevin Cheng5595b342016-09-29 15:51:01 -0700604 return ''
605
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800606 def safe_switch_usbkey(self, mux_direction, _=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700607 """Toggle the usb direction safely.
608
Kevin Cheng5595b342016-09-29 15:51:01 -0700609 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800610 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800611 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700612
613 Returns:
614 An empty string to appease the xmlrpc gods.
615 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800616 self.set('image_usbkey_direction', mux_direction)
Kevin Cheng5595b342016-09-29 15:51:01 -0700617 return ''
618
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800619 def probe_host_usb_dev(self, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700620 """Probe the USB disk device plugged in the servo from the host side.
621
Kevin Cheng5595b342016-09-29 15:51:01 -0700622 Args:
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800623 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700624
Simran Basia9f41032012-05-11 14:21:58 -0700625 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700626 USB disk path if one and only one USB disk path is found, otherwise an
Simran Basia9f41032012-05-11 14:21:58 -0700627 """
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800628 return self.get('image_usbkey_dev')
Kevin Chengc49494e2016-07-25 12:13:38 -0700629
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800630 def download_image_to_usb(self, image_path, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700631 """Download image and save to the USB device found by probe_host_usb_dev.
632 If the image_path is a URL, it will download this url to the USB path;
633 otherwise it will simply copy the image_path's contents to the USB path.
634
635 Args:
636 image_path: path or url to the recovery image.
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800637 _: to conform to current API
Simran Basia9f41032012-05-11 14:21:58 -0700638
639 Returns:
640 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800641 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700642 """
Simran Basia9f41032012-05-11 14:21:58 -0700643 try:
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800644 self.set('download_image_to_usb_dev', image_path)
645 return True
646 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700647 return False
Simran Basia9f41032012-05-11 14:21:58 -0700648
649 def make_image_noninteractive(self):
650 """Makes the recovery image noninteractive.
651
652 A noninteractive image will reboot automatically after installation
653 instead of waiting for the USB device to be removed to initiate a system
654 reboot.
655
656 Mounts partition 1 of the image stored on usb_dev and creates a file
657 called "non_interactive" so that the image will become noninteractive.
658
659 Returns:
660 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800661 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700662 """
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800663 try:
664 usb_dev = self.get('image_usbkey_dev')
665 usb_dev_partition = '%s1' % usb_dev
666 self.set('make_usb_dev_image_noninteractive', usb_dev_partition)
667 return True
668 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700669 return False
Simran Basia9f41032012-05-11 14:21:58 -0700670
Todd Broch352b4b22013-03-22 09:48:40 -0700671 def set_get_all(self, cmds):
672 """Set &| get one or more control values.
673
674 Args:
675 cmds: list of control[:value] to get or set.
676
677 Returns:
678 rv: list of responses from calling get or set methods.
679 """
680 rv = []
681 for cmd in cmds:
682 if ':' in cmd:
Wai-Hong Tam269f1802019-05-16 12:37:17 -0700683 (control, value) = cmd.split(':', 1)
Todd Broch352b4b22013-03-22 09:48:40 -0700684 rv.append(self.set(control, value))
685 else:
686 rv.append(self.get(cmd))
687 return rv
688
Mary Ruthven493df512019-07-12 13:10:18 -0700689 def add_serial_number(self, name, serial_number):
690 """Adds the serial number to the _serialnames dictionary.
691
692 Args:
693 name: A string which is the key into the _serialnames dictionary.
694 serial_number: A string which is the key into the _serialnames dictionary.
695 """
696 self._serialnames[name] = serial_number
697 self._logger.debug('Added %s %s to serialnames %r', name, serial_number,
698 self._serialnames)
699
Aseda Aboagye6921f602017-08-01 14:45:38 -0700700 def get_serial_number(self, name):
701 """Returns the desired serial number from the serialnames dict.
702
703 Args:
704 name: A string which is the key into the _serialnames dictionary.
705
706 Returns:
707 A string containing the serial number or "unknown".
708 """
709 if not name:
710 name = 'main'
711
712 try:
713 return self._serialnames[name]
714 except KeyError:
715 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700716 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700717
Todd Broche505b8d2011-03-21 18:19:54 -0700718 def get(self, name):
719 """Get control value.
720
721 Args:
722 name: name string of control
723
724 Returns:
725 Response from calling drv get method. Value is reformatted based on
726 control's dictionary parameters
727
728 Raises:
729 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800730 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700731 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700732 self._logger.debug('name(%s)' % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700733 # This route is to retrieve serialnames on servo v4, which
734 # connects to multiple servo-micros or CCD, like the controls,
735 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
736 # TODO(aaboagye): Refactor it.
737 if 'serialname' in name:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700738 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700739
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700740 (param, drv, device) = self._get_param_drv(name)
741 if device in self._devices:
742 self._devices[device].wait(self.INTERFACE_AVAILABILITY_TIMEOUT)
Todd Broche505b8d2011-03-21 18:19:54 -0700743 try:
744 val = drv.get()
745 rd_val = self._syscfg.reformat_val(param, val)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700746 self._logger.debug('%s = %s' % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700747 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700748 except AttributeError, error:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700749 self._logger.error('Getting %s: %s' % (name, error))
Todd Brochfbc499d2011-06-16 16:09:58 -0700750 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800751 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700752 self._logger.error('Getting %s' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700753 raise
Todd Brochd6061672012-05-11 15:52:47 -0700754
Todd Broche505b8d2011-03-21 18:19:54 -0700755 def get_all(self, verbose):
756 """Get all controls values.
757
758 Args:
759 verbose: Boolean on whether to return doc info as well
760
761 Returns:
762 string creating from trying to get all values of all controls. In case of
763 error attempting access to control, response is 'ERR'.
764 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800765 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700766 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700767 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700768 try:
769 value = self.get(name)
770 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700771 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -0700772 pass
773 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700774 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700775 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700776 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800777 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700778
779 def set(self, name, wr_val_str):
780 """Set control.
781
782 Args:
783 name: name string of control
784 wr_val_str: value string to write. Can be integer, float or a
785 alpha-numerical that is mapped to a integer or float.
786
787 Raises:
788 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800789 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700790 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700791 self._logger.debug('name(%s) wr_val(%s)' % (name, wr_val_str))
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700792 (params, drv, device) = self._get_param_drv(name, False)
793 if device in self._devices:
794 self._devices[device].wait(self.INTERFACE_AVAILABILITY_TIMEOUT)
Todd Broche505b8d2011-03-21 18:19:54 -0700795 wr_val = self._syscfg.resolve_val(params, wr_val_str)
796 try:
797 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800798 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700799 self._logger.error('Setting %s -> %s' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700800 raise
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +0800801 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
802 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -0700803 # marshall/unmarshall
804 return True
805
Todd Brochd6061672012-05-11 15:52:47 -0700806 def hwinit(self, verbose=False):
807 """Initialize all controls.
808
809 These values are part of the system config XML files of the form
810 init=<value>. This command should be used by clients wishing to return the
811 servo and DUT its connected to a known good/safe state.
812
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800813 Note that initialization errors are ignored (as in some cases they could
814 be caused by DUT firmware deficiencies). This might need to be fine tuned
815 later.
816
Todd Brochd6061672012-05-11 15:52:47 -0700817 Args:
818 verbose: boolean, if True prints info about control initialized.
819 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800820
821 Returns:
822 This function is called across RPC and as such is expected to return
823 something unless transferring 'none' across is allowed. Hence adding a
824 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700825 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800826 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800827 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700828 # Workaround for bug chrome-os-partner:42349. Without this check, the
829 # gpio will briefly pulse low if we set it from high to high.
830 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700831 self.set(control_name, value)
832 if verbose:
833 self._logger.info('Initialized %s to %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700834 except Exception as e:
835 self._logger.error(
Matthew Bleckera5d979c2018-10-16 20:59:19 -0700836 'Problem initializing %s -> %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700837 self._logger.error(str(e))
838 self._logger.error('Please consider verifying the logs and if the '
839 'error is not just a setup issue, consider filing '
840 'a bug. Also checkout go/servo-ki.')
Nick Sandersbc836282015-12-08 21:19:23 -0800841
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800842 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800843
Todd Broche505b8d2011-03-21 18:19:54 -0700844 def echo(self, echo):
845 """Dummy echo function for testing/examples.
846
847 Args:
848 echo: string to echo back to client
849 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700850 self._logger.debug('echo(%s)' % (echo))
851 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -0700852
J. Richard Barnettee2820552013-03-14 16:13:46 -0700853 def get_board(self):
854 """Return the board specified at startup, if any."""
855 return self._board
856
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700857 def get_base_board(self):
858 """Returns the board name of the base if present.
859
860 Returns:
861 A string of the board name, or '' if not present.
862 """
863 # The value is set in servo_postinit.
864 return self._base_board
865
Simran Basia23c1392013-08-06 14:59:10 -0700866 def get_version(self):
867 """Get servo board version."""
868 return self._version
869
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800870 def power_long_press(self):
871 """Simulate a long power button press."""
872 # After a long power press, the EC may ignore the next power
873 # button press (at least on Alex). To guarantee that this
874 # won't happen, we need to allow the EC one second to
875 # collect itself.
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800876 return self.set('power_key', 'long_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800877
878 def power_normal_press(self):
879 """Simulate a normal power button press."""
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800880 return self.set('power_key', 'press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800881
882 def power_short_press(self):
883 """Simulate a short power button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530884 return self.set('power_key', 'short_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800885
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530886 def power_key(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800887 """Simulate a power button press.
888
889 Args:
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530890 press_secs: Time in seconds to simulate the keypress.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800891 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530892 return self.set('power_key', 'press' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800893
894 def ctrl_d(self, press_secs=''):
895 """Simulate Ctrl-d simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530896 return self.set('ctrl_d', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800897
Victor Dodone539cea2016-03-29 18:50:17 -0700898 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800899 """Simulate Ctrl-u simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530900 return self.set('ctrl_u', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800901
902 def ctrl_enter(self, press_secs=''):
903 """Simulate Ctrl-enter simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530904 return self.set('ctrl_enter', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800905
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800906 def ctrl_key(self, press_secs=''):
907 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530908 return self.set('ctrl_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800909
910 def enter_key(self, press_secs=''):
911 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530912 return self.set('enter_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800913
914 def refresh_key(self, press_secs=''):
915 """Simulate Refresh key (F3) button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530916 return self.set('refresh_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800917
918 def ctrl_refresh_key(self, press_secs=''):
919 """Simulate Ctrl and Refresh (F3) simultaneous press.
920
921 This key combination is an alternative of Space key.
922 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530923 return self.set('ctrl_refresh_key', ('tab' if press_secs is '' else
924 press_secs))
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800925
926 def imaginary_key(self, press_secs=''):
927 """Simulate imaginary key button press.
928
929 Maps to a key that doesn't physically exist.
930 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530931 return self.set('imaginary_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800932
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200933 def sysrq_x(self, press_secs=''):
934 """Simulate Alt VolumeUp X simultaneous press.
935
936 This key combination is the kernel system request (sysrq) x.
937 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530938 return self.set('sysrq_x', 'tab' if press_secs is '' else press_secs)
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200939
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700940 def get_servo_serials(self):
941 """Return all the serials associated with this process."""
942 return self._serialnames
943
944
Todd Broche505b8d2011-03-21 18:19:54 -0700945def test():
946 """Integration testing.
947
948 TODO(tbroch) Enhance integration test and add unittest (see mox)
949 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700950 logging.basicConfig(
951 level=logging.DEBUG,
952 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -0700953 # configure server & listen
954 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700955 # 5 == number of interfaces on a FT4232H device
956 for i in xrange(1, 5):
957 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -0700958 # its an i2c interface ... see __init__ for details and TODO to make
959 # this configureable
960 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
961 else:
962 # its a gpio interface
963 servod_obj._interface_list[i].wr_rd(0)
964
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700965 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost', 9999),
Todd Broche505b8d2011-03-21 18:19:54 -0700966 allow_none=True)
967 server.register_introspection_functions()
968 server.register_multicall_functions()
969 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700970 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -0700971 server.serve_forever()
972
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700973
974if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -0700975 test()
976
977 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700978 """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)
979
Todd Broche505b8d2011-03-21 18:19:54 -0700980 """