blob: 79c77d241a5b2fa8e623b285fad6297633fd9fba [file] [log] [blame]
Simran Basia9f41032012-05-11 14:21:58 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Todd Broche505b8d2011-03-21 18:19:54 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""Servo Server."""
Kevin Chengc49494e2016-07-25 12:13:38 -07005import datetime
6import fcntl
Simran Basia9f41032012-05-11 14:21:58 -07007import fnmatch
Todd Broche505b8d2011-03-21 18:19:54 -07008import logging
Simran Basia9f41032012-05-11 14:21:58 -07009import os
Aseda Aboagye1d8477b2017-05-10 17:24:31 -070010import re
Todd Broche505b8d2011-03-21 18:19:54 -070011import SimpleXMLRPCServer
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080012import threading
Todd Broch7a91c252012-02-03 12:37:45 -080013import time
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070014import usb
Todd Broche505b8d2011-03-21 18:19:54 -070015
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080016import drv as servo_drv
Aaron.Chuang88eff332014-07-31 08:32:00 +080017import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070018import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070019import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070020import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080021import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070022import ftdigpio
23import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070024import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070025import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080026import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080027import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070028import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070029import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080030import stm32gpio
31import stm32i2c
32import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070033
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080034HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080035
Todd Broche505b8d2011-03-21 18:19:54 -070036MAX_I2C_CLOCK_HZ = 100000
37
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070038
Todd Broche505b8d2011-03-21 18:19:54 -070039class ServodError(Exception):
40 """Exception class for servod."""
41
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070042
Todd Broche505b8d2011-03-21 18:19:54 -070043class Servod(object):
44 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070045
Kevin Cheng4b4f0022016-09-09 02:37:07 -070046 # This is the key to get the main serial used in the _serialnames dict.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070047 MAIN_SERIAL = 'main'
48 SERVO_MICRO_SERIAL = 'servo_micro'
49 CCD_SERIAL = 'ccd'
Kevin Cheng4b4f0022016-09-09 02:37:07 -070050
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080051 # Timeout to wait for interfaces to become available again if reinitialization
52 # is taking place. In seconds.
53 INTERFACE_AVAILABILITY_TIMEOUT = 60
54
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070055 def init_servo_interfaces(self, vendor, product, serialname, interfaces):
Kevin Chengdc3befd2016-07-15 12:34:00 -070056 """Init the servo interfaces with the given interfaces.
57
58 We don't use the self._{vendor,product,serialname} attributes because we
59 want to allow other callers to initialize other interfaces that may not
60 be associated with the initialized attributes (e.g. a servo v4 servod object
61 that wants to also initialize a servo micro interface).
62
63 Args:
64 vendor: USB vendor id of FTDI device.
65 product: USB product id of FTDI device.
66 serialname: String of device serialname/number as defined in FTDI
67 eeprom.
68 interfaces: List of strings of interface types the server will
69 instantiate.
70
71 Raises:
72 ServodError if unable to locate init method for particular interface.
73 """
Mary Ruthven13389642017-02-14 12:15:34 -080074 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070075 device = (vendor, product, serialname)
Mary Ruthven13389642017-02-14 12:15:34 -080076 if device not in self._devices:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070077 self._devices.append(device)
Mary Ruthven13389642017-02-14 12:15:34 -080078
Kevin Chengdc3befd2016-07-15 12:34:00 -070079 # Extend the interface list if we need to.
80 interfaces_len = len(interfaces)
81 interface_list_len = len(self._interface_list)
82 if interfaces_len > interface_list_len:
83 self._interface_list += [None] * (interfaces_len - interface_list_len)
84
Kevin Chengdc3befd2016-07-15 12:34:00 -070085 for i, interface in enumerate(interfaces):
86 is_ftdi_interface = False
87 if type(interface) is dict:
88 name = interface['name']
89 # Store interface index for those that care about it.
90 interface['index'] = i
91 elif type(interface) is str and interface != 'dummy':
92 name = interface
Wai-Hong Tam564c1702017-04-24 09:23:38 -070093 # It's a FTDI related interface. #0 is reserved for no use.
94 interface = ((i - 1) % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
Kevin Chengdc3befd2016-07-15 12:34:00 -070095 is_ftdi_interface = True
96 elif type(interface) is str and interface == 'dummy':
97 # 'dummy' reserves the interface for future use. Typically the
98 # interface will be managed by external third-party tools like
99 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
100 # it serves as a placeholder for servo micro interfaces.
101 continue
102 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:
108 product_increment = (i - 1) / ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE
109 if product_increment:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700110 self._logger.info('Use the next FTDI part @ pid = 0x%04x',
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700111 product + product_increment)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700112
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700113 self._logger.info('Initializing interface %d to %s', i, name)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700114 try:
115 func = getattr(self, '_init_%s' % name)
116 except AttributeError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700117 raise ServodError('Unable to locate init for interface %s' % name)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700118 result = func(vendor, product + product_increment, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700119
120 if isinstance(result, tuple):
121 result_len = len(result)
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700122 self._interface_list[i:(i + result_len)] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700123 else:
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700124 self._interface_list[i] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700125
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700126 def __init__(self, config, vendor, product, serialname=None, interfaces=None,
127 board='', version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700128 """Servod constructor.
129
130 Args:
131 config: instance of SystemConfig containing all controls for
132 particular Servod invocation
133 vendor: usb vendor id of FTDI device
134 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700135 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700136 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700137 version: String. Servo board version. Examples: servo_v1, servo_v2,
138 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800139 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700140 sending keyboard commands to DUTs that do not have built in
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700141 keyboards. Used in FAFT tests. Use None for on board AVR MCU.
142 e.g. '/dev/ttyUSB0' or None.
Todd Brochdbb09982011-10-02 07:14:26 -0700143
144 Raises:
145 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700146 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700147 self._logger = logging.getLogger('Servod')
148 self._logger.debug('')
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800149 self._ifaces_available = threading.Event()
150 # Initially interfaces should be available.
151 self._ifaces_available.set()
Todd Broche505b8d2011-03-21 18:19:54 -0700152 self._vendor = vendor
153 self._product = product
Mary Ruthven13389642017-02-14 12:15:34 -0800154 self._devices = []
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700155 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700156 self._syscfg = config
157 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
158 # interfaces are mapped to
159 self._interface_list = []
160 # Dict of Dict to map control name, function name to to tuple (params, drv)
161 # Ex) _drv_dict[name]['get'] = (params, drv)
162 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700163 self._board = board
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700164 self._base_board = ''
Simran Basia23c1392013-08-06 14:59:10 -0700165 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800166 self._usbkm232 = usbkm232
Todd Brochdbb09982011-10-02 07:14:26 -0700167 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700168 try:
169 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
170 except KeyError:
171 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Dino Lic89d8c82018-01-11 09:56:47 +0800172 self._interfaces = interfaces
Todd Brochdbb09982011-10-02 07:14:26 -0700173
Kevin Chengdc3befd2016-07-15 12:34:00 -0700174 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700175 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800176
Mary Ruthven13389642017-02-14 12:15:34 -0800177 def reinitialize(self):
178 """Reinitialize all interfaces that support reinitialization"""
Mary Ruthven13389642017-02-14 12:15:34 -0800179 for i, interface in enumerate(self._interface_list):
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700180 if hasattr(interface, 'reinitialize'):
181 interface.reinitialize()
182 else:
183 self._logger.debug('interface %d has no reset functionality', i)
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800184 # Indicate interfaces are safe to use again.
185 self._ifaces_available.set()
Mary Ruthven13389642017-02-14 12:15:34 -0800186
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700187 def get_servo_interfaces(self, position, size):
188 """Get the list of servo interfaces.
189
190 Args:
191 position: The index the first interface to get.
192 size: The number of the interfaces.
193 """
194 return self._interface_list[position:(position + size)]
195
196 def set_servo_interfaces(self, position, interfaces):
197 """Set the list of servo interfaces.
198
199 Args:
200 position: The index the first interface to set.
201 interfaces: The list of interfaces to set.
202 """
203 size = len(interfaces)
204 self._interface_list[position:(position + size)] = interfaces
205
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800206 def _init_keyboard_handler(self, servo, board=''):
207 """Initialize the correct keyboard handler for board.
208
Kevin Chengdc3befd2016-07-15 12:34:00 -0700209 Args:
210 servo: servo object.
211 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800212
Kevin Chengdc3befd2016-07-15 12:34:00 -0700213 Returns:
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700214 keyboard handler object, or None if no keyboard supported.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800215 """
216 if board == 'parrot':
217 return keyboard_handlers.ParrotHandler(servo)
218 elif board == 'stout':
219 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800220 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700221 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy', 'sumo',
222 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
Shelley Chen94cd2352017-07-26 11:36:45 -0700223 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800224 if self._usbkm232 is None:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700225 logging.info('No device path specified for usbkm232 handler. Use '
226 'the servo atmega chip to handle.')
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700227
Danny Chan662b6022015-11-04 17:34:53 -0800228 # Use servo onboard keyboard emulator.
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700229 if not self._syscfg.is_control('atmega_rst'):
230 logging.warn('No atmega in servo board. So no keyboard support.')
231 return None
232
Nick Sanders78423782015-11-09 14:28:19 -0800233 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800234 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800235 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800236 self._usbkm232 = self.get('atmega_pty')
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700237
Kevin Cheng810fc782016-11-01 12:36:46 -0700238 # We don't need to set the atmega uart settings if we're a servo v4.
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700239 if 'servo_v4' not in self._version:
Kevin Cheng810fc782016-11-01 12:36:46 -0700240 self.set('atmega_baudrate', '9600')
241 self.set('atmega_bits', 'eight')
242 self.set('atmega_parity', 'none')
243 self.set('atmega_sbits', 'one')
244 self.set('usb_mux_sel4', 'on')
245 self.set('usb_mux_oe4', 'on')
246 # Allow atmega bootup time.
247 time.sleep(1.0)
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700248
Danny Chan662b6022015-11-04 17:34:53 -0800249 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800250 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
251 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800252 # The following boards don't use Chrome EC.
253 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
254 return keyboard_handlers.MatrixKeyboardHandler(servo)
255 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800256
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700257 def close(self):
258 """Servod turn down logic."""
259 for i, interface in enumerate(self._interface_list):
260 self._logger.info('Turning down interface %d' % i)
261 if hasattr(interface, 'close'):
262 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800263
Kevin Chengdc3befd2016-07-15 12:34:00 -0700264 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700265 """Dummy interface for ftdi devices.
266
267 This is a dummy function specifically for ftdi devices to not initialize
268 anything but to help pad the interface list.
269
270 Returns:
271 None.
272 """
273 return None
274
Kevin Chengdc3befd2016-07-15 12:34:00 -0700275 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700276 """Initialize gpio driver interface and open for use.
277
278 Args:
279 interface: interface number of FTDI device to use.
280
281 Returns:
282 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700283
284 Raises:
285 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700286 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700287 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700288 try:
289 fobj.open()
290 except ftdigpio.FgpioError as e:
291 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
292
Todd Broche505b8d2011-03-21 18:19:54 -0700293 return fobj
294
Kevin Chengdc3befd2016-07-15 12:34:00 -0700295 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800296 """Initialize stm32 uart interface and open for use
297
298 Note, the uart runs in a separate thread. Users wishing to
299 interact with it will query control for the pty's pathname and connect
300 with their favorite console program. For example:
301 cu -l /dev/pts/22
302
303 Args:
304 interface: dict of interface parameters.
305
306 Returns:
307 Instance object of interface
308
309 Raises:
310 ServodError: Raised on init failure.
311 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700312 self._logger.info('Suart: interface: %s' % interface)
313 sobj = stm32uart.Suart(vendor, product, interface['interface'], serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800314
315 try:
316 sobj.run()
317 except stm32uart.SuartError as e:
318 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
319
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700320 self._logger.info('%s' % sobj.get_pty())
Nick Sanders97bc4462016-01-04 15:37:31 -0800321 return sobj
322
Kevin Chengdc3befd2016-07-15 12:34:00 -0700323 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800324 """Initialize stm32 gpio interface.
325 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700326 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800327
328 Returns:
329 Instance object of interface
330
331 Raises:
332 SgpioError: Raised on init failure.
333 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700334 interface_number = interface
335 # Interface could be a dict.
336 if type(interface) is dict:
337 interface_number = interface['interface']
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700338 self._logger.info('Sgpio: interface: %s' % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700339 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800340
Kevin Chengdc3befd2016-07-15 12:34:00 -0700341 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800342 """Initialize stm32 USB to I2C bridge interface and open for use
343
344 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700345 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800346
347 Returns:
348 Instance object of interface.
349
350 Raises:
351 Si2cError: Raised on init failure.
352 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700353 self._logger.info('Si2cBus: interface: %s' % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800354 port = interface.get('port', 0)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700355 return stm32i2c.Si2cBus(vendor, product, interface['interface'], port=port,
356 serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800357
Kevin Chengdc3befd2016-07-15 12:34:00 -0700358 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800359 """Initalize beaglebone ADC interface."""
360 return bbadc.BBadc()
361
Kevin Chengdc3befd2016-07-15 12:34:00 -0700362 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700363 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700364 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700365
Kevin Chengdc3befd2016-07-15 12:34:00 -0700366 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700367 """Initialize i2c interface and open for use.
368
369 Args:
370 interface: interface number of FTDI device to use
371
372 Returns:
373 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700374
375 Raises:
376 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700377 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700378 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700379 try:
380 fobj.open()
381 except ftdii2c.Fi2cError as e:
382 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
383
Todd Broche505b8d2011-03-21 18:19:54 -0700384 # Set the frequency of operation of the i2c bus.
385 # TODO(tbroch) make configureable
386 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700387
Todd Broche505b8d2011-03-21 18:19:54 -0700388 return fobj
389
Simran Basie750a342013-03-12 13:45:26 -0700390 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
391 def _init_bb_i2c(self, interface):
392 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700393 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700394
Kevin Chengdc3befd2016-07-15 12:34:00 -0700395 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800396 """Initalize Linux i2c-dev interface."""
397 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
398
Kevin Chengdc3befd2016-07-15 12:34:00 -0700399 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700400 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700401
402 Note, the uart runs in a separate thread (pthreads). Users wishing to
403 interact with it will query control for the pty's pathname and connect
404 with there favorite console program. For example:
405 cu -l /dev/pts/22
406
407 Args:
408 interface: interface number of FTDI device to use
409
410 Returns:
411 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700412
413 Raises:
414 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700415 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700416 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700417 try:
418 fobj.run()
419 except ftdiuart.FuartError as e:
420 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
421
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700422 self._logger.info('%s' % fobj.get_pty())
Todd Broch47c43f42011-05-26 15:11:31 -0700423 return fobj
424
Simran Basie750a342013-03-12 13:45:26 -0700425 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700426 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700427 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700428 logging.debug('UART INTERFACE: %s', interface)
429 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700430
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700431 def _init_ftdi_gpiouart(self, vendor, product, serialname, interface):
Todd Broch888da782011-10-07 14:29:09 -0700432 """Initialize special gpio + uart interface and open for use
433
434 Note, the uart runs in a separate thread (pthreads). Users wishing to
435 interact with it will query control for the pty's pathname and connect
436 with there favorite console program. For example:
437 cu -l /dev/pts/22
438
439 Args:
440 interface: interface number of FTDI device to use
441
442 Returns:
443 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700444
445 Raises:
446 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700447 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700448 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700449 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700450 try:
451 fuart.run()
452 except ftdiuart.FuartError as e:
453 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
454
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700455 self._logger.info('uart pty: %s' % fuart.get_pty())
Todd Broch888da782011-10-07 14:29:09 -0700456 return fgpio, fuart
457
Kevin Chengdc3befd2016-07-15 12:34:00 -0700458 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800459 """Initialize EC-3PO console interpreter interface.
460
461 Args:
462 interface: A dictionary representing the interface.
463
464 Returns:
465 An EC3PO object representing the EC-3PO interface or None if there's no
466 interface for the USB PD UART.
467 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700468 raw_uart_name = interface['raw_pty']
Nick Sanders116ed9e2018-03-09 19:05:16 -0800469 raw_uart_source = interface['source']
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700470 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800471 raw_ec_uart = self.get(raw_uart_name)
Nick Sanders116ed9e2018-03-09 19:05:16 -0800472 return ec3po_interface.EC3PO(raw_ec_uart, raw_uart_source)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800473 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700474 # The overlay doesn't have the raw PTY defined, therefore we can skip
475 # initializing this interface since no control relies on it.
476 self._logger.debug(
477 'Skip initializing EC3PO for %s, no control specified.',
478 raw_uart_name)
479 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800480
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800481 def _camel_case(self, string):
482 output = ''
483 for s in string.split('_'):
484 if output:
485 output += s.capitalize()
486 else:
487 output = s
488 return output
489
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700490 def clear_cached_drv(self):
491 """Clear the cached drivers.
492
493 The drivers are cached in the Dict _drv_dict when a control is got or set.
494 When the servo interfaces are relocated, the cached values may become wrong.
495 Should call this method to clear the cached values.
496 """
497 self._drv_dict = {}
498
Todd Broche505b8d2011-03-21 18:19:54 -0700499 def _get_param_drv(self, control_name, is_get=True):
500 """Get access to driver for a given control.
501
502 Note, some controls have different parameter dictionaries for 'getting' the
503 control's value versus 'setting' it. Boolean is_get distinguishes which is
504 being requested.
505
506 Args:
507 control_name: string name of control
508 is_get: boolean to determine
509
510 Returns:
511 tuple (param, drv) where:
512 param: param dictionary for control
513 drv: instance object of driver for particular control
514
515 Raises:
516 ServodError: Error occurred while examining params dict
517 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700518 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700519 # if already setup just return tuple from driver dict
520 if control_name in self._drv_dict:
521 if is_get and ('get' in self._drv_dict[control_name]):
522 return self._drv_dict[control_name]['get']
523 if not is_get and ('set' in self._drv_dict[control_name]):
524 return self._drv_dict[control_name]['set']
525
526 params = self._syscfg.lookup_control_params(control_name, is_get)
527 if 'drv' not in params:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700528 self._logger.error('Unable to determine driver for %s' % control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700529 raise ServodError("'drv' key not found in params dict")
530 if 'interface' not in params:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700531 self._logger.error('Unable to determine interface for %s' % control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700532 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700533
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700534 # Find the candidate servos. Using servo_v4 with a servo_micro connected as
535 # an example, the following shows the priority for selecting the interface.
536 #
537 # 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
538 # 2. servo_micro_interface
539 # 3. servo_v4_interface
540 # 4. Fallback to the default, interface.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700541 candidates = [self._version]
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700542 candidates.extend(reversed(self._version.split('_with_')))
543
544 interface_id = 'unknown'
545 for c in candidates:
546 interface_name = '%s_interface' % c
547 if interface_name in params:
548 interface_id = params[interface_name]
549 self._logger.debug('Using %s parameter.' % interface_name)
550 break
551
552 # Use the default interface value if we couldn't find a more specific
553 # interface.
554 if interface_id == 'unknown':
555 interface_id = params['interface']
556 self._logger.debug('Using default interface parameter.')
557
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800558 if interface_id == 'servo':
559 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700560 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700561 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800562 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700563
Todd Broche505b8d2011-03-21 18:19:54 -0700564 drv_name = params['drv']
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800565 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800566 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700567 drv = drv_class(interface, params)
568 if control_name not in self._drv_dict:
569 self._drv_dict[control_name] = {}
570 if is_get:
571 self._drv_dict[control_name]['get'] = (params, drv)
572 else:
573 self._drv_dict[control_name]['set'] = (params, drv)
574 return (params, drv)
575
576 def doc_all(self):
577 """Return all documenation for controls.
578
579 Returns:
580 string of <doc> text in config file (xml) and the params dictionary for
581 all controls.
582
583 For example:
584 warm_reset :: Reset the device warmly
585 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
586 """
587 return self._syscfg.display_config()
588
589 def doc(self, name):
590 """Retreive doc string in system config file for given control name.
591
592 Args:
593 name: name string of control to get doc string
594
595 Returns:
596 doc string of name
597
598 Raises:
599 NameError: if fails to locate control
600 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700601 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700602 if self._syscfg.is_control(name):
603 return self._syscfg.get_control_docstring(name)
604 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700605 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700606
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800607 def safe_switch_usbkey_power(self, power_state, _=None):
Kevin Cheng5595b342016-09-29 15:51:01 -0700608 """Toggle the usb power safely.
609
Kevin Chengc49494e2016-07-25 12:13:38 -0700610 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700611 power_state: The setting to set for the usbkey power.
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800612 _: to conform to current API
Kevin Chengc49494e2016-07-25 12:13:38 -0700613
Kevin Cheng5595b342016-09-29 15:51:01 -0700614 Returns:
615 An empty string to appease the xmlrpc gods.
616 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800617 self.set('image_usbkey_pwr', power_state)
Kevin Cheng5595b342016-09-29 15:51:01 -0700618 return ''
619
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800620 def safe_switch_usbkey(self, mux_direction, _=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700621 """Toggle the usb direction safely.
622
Kevin Cheng5595b342016-09-29 15:51:01 -0700623 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800624 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800625 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700626
627 Returns:
628 An empty string to appease the xmlrpc gods.
629 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800630 self.set('image_usbkey_direction', mux_direction)
Kevin Cheng5595b342016-09-29 15:51:01 -0700631 return ''
632
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800633 def probe_host_usb_dev(self, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700634 """Probe the USB disk device plugged in the servo from the host side.
635
Kevin Cheng5595b342016-09-29 15:51:01 -0700636 Args:
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800637 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700638
Simran Basia9f41032012-05-11 14:21:58 -0700639 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700640 USB disk path if one and only one USB disk path is found, otherwise an
Simran Basia9f41032012-05-11 14:21:58 -0700641 """
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800642 return self.get('image_usbkey_dev')
Kevin Chengc49494e2016-07-25 12:13:38 -0700643
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800644 def download_image_to_usb(self, image_path, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700645 """Download image and save to the USB device found by probe_host_usb_dev.
646 If the image_path is a URL, it will download this url to the USB path;
647 otherwise it will simply copy the image_path's contents to the USB path.
648
649 Args:
650 image_path: path or url to the recovery image.
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800651 _: to conform to current API
Simran Basia9f41032012-05-11 14:21:58 -0700652
653 Returns:
654 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800655 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700656 """
Simran Basia9f41032012-05-11 14:21:58 -0700657 try:
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800658 self.set('download_image_to_usb_dev', image_path)
659 return True
660 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700661 return False
Simran Basia9f41032012-05-11 14:21:58 -0700662
663 def make_image_noninteractive(self):
664 """Makes the recovery image noninteractive.
665
666 A noninteractive image will reboot automatically after installation
667 instead of waiting for the USB device to be removed to initiate a system
668 reboot.
669
670 Mounts partition 1 of the image stored on usb_dev and creates a file
671 called "non_interactive" so that the image will become noninteractive.
672
673 Returns:
674 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800675 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700676 """
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800677 try:
678 usb_dev = self.get('image_usbkey_dev')
679 usb_dev_partition = '%s1' % usb_dev
680 self.set('make_usb_dev_image_noninteractive', usb_dev_partition)
681 return True
682 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700683 return False
Simran Basia9f41032012-05-11 14:21:58 -0700684
Todd Broch352b4b22013-03-22 09:48:40 -0700685 def set_get_all(self, cmds):
686 """Set &| get one or more control values.
687
688 Args:
689 cmds: list of control[:value] to get or set.
690
691 Returns:
692 rv: list of responses from calling get or set methods.
693 """
694 rv = []
695 for cmd in cmds:
696 if ':' in cmd:
697 (control, value) = cmd.split(':')
698 rv.append(self.set(control, value))
699 else:
700 rv.append(self.get(cmd))
701 return rv
702
Aseda Aboagye6921f602017-08-01 14:45:38 -0700703 def get_serial_number(self, name):
704 """Returns the desired serial number from the serialnames dict.
705
706 Args:
707 name: A string which is the key into the _serialnames dictionary.
708
709 Returns:
710 A string containing the serial number or "unknown".
711 """
712 if not name:
713 name = 'main'
714
715 try:
716 return self._serialnames[name]
717 except KeyError:
718 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700719 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700720
Todd Broche505b8d2011-03-21 18:19:54 -0700721 def get(self, name):
722 """Get control value.
723
724 Args:
725 name: name string of control
726
727 Returns:
728 Response from calling drv get method. Value is reformatted based on
729 control's dictionary parameters
730
731 Raises:
732 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800733 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700734 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800735 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
736 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700737 self._logger.debug('name(%s)' % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700738 # This route is to retrieve serialnames on servo v4, which
739 # connects to multiple servo-micros or CCD, like the controls,
740 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
741 # TODO(aaboagye): Refactor it.
742 if 'serialname' in name:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700743 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700744
Todd Broche505b8d2011-03-21 18:19:54 -0700745 (param, drv) = self._get_param_drv(name)
746 try:
747 val = drv.get()
748 rd_val = self._syscfg.reformat_val(param, val)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700749 self._logger.debug('%s = %s' % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700750 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700751 except AttributeError, error:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700752 self._logger.error('Getting %s: %s' % (name, error))
Todd Brochfbc499d2011-06-16 16:09:58 -0700753 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800754 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700755 self._logger.error('Getting %s' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700756 raise
Todd Brochd6061672012-05-11 15:52:47 -0700757
Todd Broche505b8d2011-03-21 18:19:54 -0700758 def get_all(self, verbose):
759 """Get all controls values.
760
761 Args:
762 verbose: Boolean on whether to return doc info as well
763
764 Returns:
765 string creating from trying to get all values of all controls. In case of
766 error attempting access to control, response is 'ERR'.
767 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800768 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700769 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700770 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700771 try:
772 value = self.get(name)
773 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700774 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -0700775 pass
776 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700777 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700778 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700779 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800780 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700781
782 def set(self, name, wr_val_str):
783 """Set control.
784
785 Args:
786 name: name string of control
787 wr_val_str: value string to write. Can be integer, float or a
788 alpha-numerical that is mapped to a integer or float.
789
790 Raises:
791 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800792 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700793 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800794 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
795 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700796 self._logger.debug('name(%s) wr_val(%s)' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700797 (params, drv) = self._get_param_drv(name, False)
798 wr_val = self._syscfg.resolve_val(params, wr_val_str)
799 try:
800 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800801 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700802 self._logger.error('Setting %s -> %s' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700803 raise
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +0800804 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
805 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -0700806 # marshall/unmarshall
807 return True
808
Todd Brochd6061672012-05-11 15:52:47 -0700809 def hwinit(self, verbose=False):
810 """Initialize all controls.
811
812 These values are part of the system config XML files of the form
813 init=<value>. This command should be used by clients wishing to return the
814 servo and DUT its connected to a known good/safe state.
815
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800816 Note that initialization errors are ignored (as in some cases they could
817 be caused by DUT firmware deficiencies). This might need to be fine tuned
818 later.
819
Todd Brochd6061672012-05-11 15:52:47 -0700820 Args:
821 verbose: boolean, if True prints info about control initialized.
822 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800823
824 Returns:
825 This function is called across RPC and as such is expected to return
826 something unless transferring 'none' across is allowed. Hence adding a
827 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700828 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800829 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800830 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700831 # Workaround for bug chrome-os-partner:42349. Without this check, the
832 # gpio will briefly pulse low if we set it from high to high.
833 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700834 self.set(control_name, value)
835 if verbose:
836 self._logger.info('Initialized %s to %s', control_name, value)
Matthew Bleckera5d979c2018-10-16 20:59:19 -0700837 except Exception:
838 self._logger.exception(
839 'Problem initializing %s -> %s', control_name, value)
Nick Sandersbc836282015-12-08 21:19:23 -0800840
841 # Init keyboard after all the intefaces are up.
842 self._keyboard = self._init_keyboard_handler(self, self._board)
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
907 def d_key(self, press_secs=''):
908 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530909 return self.set('d_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800910
911 def ctrl_key(self, press_secs=''):
912 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530913 return self.set('ctrl_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800914
915 def enter_key(self, press_secs=''):
916 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530917 return self.set('enter_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800918
919 def refresh_key(self, press_secs=''):
920 """Simulate Refresh key (F3) button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530921 return self.set('refresh_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800922
923 def ctrl_refresh_key(self, press_secs=''):
924 """Simulate Ctrl and Refresh (F3) simultaneous press.
925
926 This key combination is an alternative of Space key.
927 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530928 return self.set('ctrl_refresh_key', ('tab' if press_secs is '' else
929 press_secs))
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800930
931 def imaginary_key(self, press_secs=''):
932 """Simulate imaginary key button press.
933
934 Maps to a key that doesn't physically exist.
935 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530936 return self.set('imaginary_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800937
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200938 def sysrq_x(self, press_secs=''):
939 """Simulate Alt VolumeUp X simultaneous press.
940
941 This key combination is the kernel system request (sysrq) x.
942 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530943 return self.set('sysrq_x', 'tab' if press_secs is '' else press_secs)
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200944
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700945 def get_servo_serials(self):
946 """Return all the serials associated with this process."""
947 return self._serialnames
948
949
Todd Broche505b8d2011-03-21 18:19:54 -0700950def test():
951 """Integration testing.
952
953 TODO(tbroch) Enhance integration test and add unittest (see mox)
954 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700955 logging.basicConfig(
956 level=logging.DEBUG,
957 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -0700958 # configure server & listen
959 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700960 # 5 == number of interfaces on a FT4232H device
961 for i in xrange(1, 5):
962 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -0700963 # its an i2c interface ... see __init__ for details and TODO to make
964 # this configureable
965 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
966 else:
967 # its a gpio interface
968 servod_obj._interface_list[i].wr_rd(0)
969
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700970 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost', 9999),
Todd Broche505b8d2011-03-21 18:19:54 -0700971 allow_none=True)
972 server.register_introspection_functions()
973 server.register_multicall_functions()
974 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700975 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -0700976 server.serve_forever()
977
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700978
979if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -0700980 test()
981
982 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700983 """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)
984
Todd Broche505b8d2011-03-21 18:19:54 -0700985 """