blob: a757cb2f6ed752f2f69b76f37be5c40e6988d8bc [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]
Ruben Rodriguez Buchillond18c6eb2019-07-10 14:40:22 -0700486 if '_with_' in self._version:
487 v4, raw_dut_device = self._version.split('_with_')
488 dut_devices = raw_dut_device.split('_and_')
489 # NOTE(coconutruben): all of this nonsense is going away with the new
490 # servod and is to bridge the time until then. Please forgive the below
491 # until then.
492 if '.' in control_name:
493 # In the current implementation, the only case where a '.' (a prefix)
494 # is in the control name is when there is a dual instance with micro and
495 # ccd on a v4.
496 dut_device = dut_devices[1]
497 else:
498 # In the normal control name, we need to make sure the version used
499 # does not include the potential _and_ portion from a dual instance.
500 dut_device = dut_devices[0]
501 candidates.extend([dut_device, v4])
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800502 candidates = ['%s_%s' % (c, param_key) for c in candidates]
503 candidates.append(param_key)
504 for c in candidates:
505 if c in params:
506 self._logger.debug('Using %s parameter.', c)
507 return params[c]
508 self._logger.error('Unable to determine %s for %s', param_key, control_name)
509 self._logger.error('params: %r', params)
510 return None
511
Todd Broche505b8d2011-03-21 18:19:54 -0700512 def _get_param_drv(self, control_name, is_get=True):
513 """Get access to driver for a given control.
514
515 Note, some controls have different parameter dictionaries for 'getting' the
516 control's value versus 'setting' it. Boolean is_get distinguishes which is
517 being requested.
518
519 Args:
520 control_name: string name of control
521 is_get: boolean to determine
522
523 Returns:
524 tuple (param, drv) where:
525 param: param dictionary for control
526 drv: instance object of driver for particular control
527
528 Raises:
529 ServodError: Error occurred while examining params dict
530 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700531 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700532 # if already setup just return tuple from driver dict
533 if control_name in self._drv_dict:
534 if is_get and ('get' in self._drv_dict[control_name]):
535 return self._drv_dict[control_name]['get']
536 if not is_get and ('set' in self._drv_dict[control_name]):
537 return self._drv_dict[control_name]['set']
538
539 params = self._syscfg.lookup_control_params(control_name, is_get)
Simran Basi668be0e2013-08-07 11:54:50 -0700540
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800541 # Get the most suitable drv given the servo instance.
542 drv_name = self._get_servo_specific_param(params, 'drv', control_name)
543 if drv_name == 'na':
544 # 'na' drv can be used to selectively turn controls into noops for
545 # a given servo hardware. Ensure that there is an interface.
546 params.setdefault('interface', 'servo')
547 self._logger.debug('Setting interface to default to %r for %r unless '
548 ' defined in params, as drv is %r.', 'servo',
549 control_name, 'na')
550 # Setting input_type to str allows all inputs through enabling a true noop
551 params.update({'input_type': 'str'})
552 interface_id = self._get_servo_specific_param(params, 'interface',
553 control_name)
554 if None in [drv_name, interface_id]:
555 raise ServodError('No drv/interface for control %r found' % control_name)
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700556
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800557 if interface_id == 'servo':
558 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700559 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700560 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800561 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700562
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700563 device_info = None
564 if hasattr(interface, 'get_device_info'):
565 device_info = interface.get_device_info()
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800566 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800567 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700568 drv = drv_class(interface, params)
569 if control_name not in self._drv_dict:
570 self._drv_dict[control_name] = {}
571 if is_get:
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700572 self._drv_dict[control_name]['get'] = (params, drv, device_info)
Todd Broche505b8d2011-03-21 18:19:54 -0700573 else:
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700574 self._drv_dict[control_name]['set'] = (params, drv, device_info)
575 return (params, drv, device_info)
Todd Broche505b8d2011-03-21 18:19:54 -0700576
577 def doc_all(self):
578 """Return all documenation for controls.
579
580 Returns:
581 string of <doc> text in config file (xml) and the params dictionary for
582 all controls.
583
584 For example:
585 warm_reset :: Reset the device warmly
586 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
587 """
588 return self._syscfg.display_config()
589
590 def doc(self, name):
591 """Retreive doc string in system config file for given control name.
592
593 Args:
594 name: name string of control to get doc string
595
596 Returns:
597 doc string of name
598
599 Raises:
600 NameError: if fails to locate control
601 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700602 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700603 if self._syscfg.is_control(name):
604 return self._syscfg.get_control_docstring(name)
605 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700606 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700607
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800608 def safe_switch_usbkey_power(self, power_state, _=None):
Kevin Cheng5595b342016-09-29 15:51:01 -0700609 """Toggle the usb power safely.
610
Kevin Chengc49494e2016-07-25 12:13:38 -0700611 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700612 power_state: The setting to set for the usbkey power.
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800613 _: to conform to current API
Kevin Chengc49494e2016-07-25 12:13:38 -0700614
Kevin Cheng5595b342016-09-29 15:51:01 -0700615 Returns:
616 An empty string to appease the xmlrpc gods.
617 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800618 self.set('image_usbkey_pwr', power_state)
Kevin Cheng5595b342016-09-29 15:51:01 -0700619 return ''
620
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800621 def safe_switch_usbkey(self, mux_direction, _=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700622 """Toggle the usb direction safely.
623
Kevin Cheng5595b342016-09-29 15:51:01 -0700624 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800625 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800626 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700627
628 Returns:
629 An empty string to appease the xmlrpc gods.
630 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800631 self.set('image_usbkey_direction', mux_direction)
Kevin Cheng5595b342016-09-29 15:51:01 -0700632 return ''
633
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800634 def probe_host_usb_dev(self, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700635 """Probe the USB disk device plugged in the servo from the host side.
636
Kevin Cheng5595b342016-09-29 15:51:01 -0700637 Args:
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800638 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700639
Simran Basia9f41032012-05-11 14:21:58 -0700640 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700641 USB disk path if one and only one USB disk path is found, otherwise an
Simran Basia9f41032012-05-11 14:21:58 -0700642 """
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800643 return self.get('image_usbkey_dev')
Kevin Chengc49494e2016-07-25 12:13:38 -0700644
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800645 def download_image_to_usb(self, image_path, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700646 """Download image and save to the USB device found by probe_host_usb_dev.
647 If the image_path is a URL, it will download this url to the USB path;
648 otherwise it will simply copy the image_path's contents to the USB path.
649
650 Args:
651 image_path: path or url to the recovery image.
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800652 _: to conform to current API
Simran Basia9f41032012-05-11 14:21:58 -0700653
654 Returns:
655 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800656 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700657 """
Simran Basia9f41032012-05-11 14:21:58 -0700658 try:
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800659 self.set('download_image_to_usb_dev', image_path)
660 return True
661 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700662 return False
Simran Basia9f41032012-05-11 14:21:58 -0700663
664 def make_image_noninteractive(self):
665 """Makes the recovery image noninteractive.
666
667 A noninteractive image will reboot automatically after installation
668 instead of waiting for the USB device to be removed to initiate a system
669 reboot.
670
671 Mounts partition 1 of the image stored on usb_dev and creates a file
672 called "non_interactive" so that the image will become noninteractive.
673
674 Returns:
675 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800676 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700677 """
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800678 try:
679 usb_dev = self.get('image_usbkey_dev')
680 usb_dev_partition = '%s1' % usb_dev
681 self.set('make_usb_dev_image_noninteractive', usb_dev_partition)
682 return True
683 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700684 return False
Simran Basia9f41032012-05-11 14:21:58 -0700685
Todd Broch352b4b22013-03-22 09:48:40 -0700686 def set_get_all(self, cmds):
687 """Set &| get one or more control values.
688
689 Args:
690 cmds: list of control[:value] to get or set.
691
692 Returns:
693 rv: list of responses from calling get or set methods.
694 """
695 rv = []
696 for cmd in cmds:
697 if ':' in cmd:
Wai-Hong Tam269f1802019-05-16 12:37:17 -0700698 (control, value) = cmd.split(':', 1)
Todd Broch352b4b22013-03-22 09:48:40 -0700699 rv.append(self.set(control, value))
700 else:
701 rv.append(self.get(cmd))
702 return rv
703
Mary Ruthven493df512019-07-12 13:10:18 -0700704 def add_serial_number(self, name, serial_number):
705 """Adds the serial number to the _serialnames dictionary.
706
707 Args:
708 name: A string which is the key into the _serialnames dictionary.
709 serial_number: A string which is the key into the _serialnames dictionary.
710 """
711 self._serialnames[name] = serial_number
712 self._logger.debug('Added %s %s to serialnames %r', name, serial_number,
713 self._serialnames)
714
Aseda Aboagye6921f602017-08-01 14:45:38 -0700715 def get_serial_number(self, name):
716 """Returns the desired serial number from the serialnames dict.
717
718 Args:
719 name: A string which is the key into the _serialnames dictionary.
720
721 Returns:
722 A string containing the serial number or "unknown".
723 """
Mary Ruthvenf17fb172019-08-15 17:17:35 -0700724 # Remove the prefix from the serialname control. Serialnames are
725 # universal. It doesn't matter what the prefix is.
726 # The prefix is separated from the main control with '.'
727 name = name.split('.', 1)[-1]
728
Aseda Aboagye6921f602017-08-01 14:45:38 -0700729 if not name:
730 name = 'main'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700731 try:
732 return self._serialnames[name]
733 except KeyError:
734 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700735 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700736
Todd Broche505b8d2011-03-21 18:19:54 -0700737 def get(self, name):
738 """Get control value.
739
740 Args:
741 name: name string of control
742
743 Returns:
744 Response from calling drv get method. Value is reformatted based on
745 control's dictionary parameters
746
747 Raises:
748 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800749 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700750 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700751 self._logger.debug('name(%s)' % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700752 # This route is to retrieve serialnames on servo v4, which
753 # connects to multiple servo-micros or CCD, like the controls,
754 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
755 # TODO(aaboagye): Refactor it.
756 if 'serialname' in name:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700757 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700758
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700759 (param, drv, device) = self._get_param_drv(name)
760 if device in self._devices:
761 self._devices[device].wait(self.INTERFACE_AVAILABILITY_TIMEOUT)
Todd Broche505b8d2011-03-21 18:19:54 -0700762 try:
763 val = drv.get()
764 rd_val = self._syscfg.reformat_val(param, val)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700765 self._logger.debug('%s = %s' % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700766 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700767 except AttributeError, error:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700768 self._logger.error('Getting %s: %s' % (name, error))
Todd Brochfbc499d2011-06-16 16:09:58 -0700769 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800770 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700771 self._logger.error('Getting %s' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700772 raise
Ruben Rodriguez Buchillon73cc5a82018-09-24 16:23:11 +0800773 # pylint: disable=broad-except
774 # This acts as a safety to inform the user of errors that should not
775 # be happening/require more investigation.
776 except Exception:
777 self._logger.error('Unknown issue getting %s. Please take a look.', name)
778 raise
Todd Brochd6061672012-05-11 15:52:47 -0700779
Todd Broche505b8d2011-03-21 18:19:54 -0700780 def get_all(self, verbose):
781 """Get all controls values.
782
783 Args:
784 verbose: Boolean on whether to return doc info as well
785
786 Returns:
787 string creating from trying to get all values of all controls. In case of
788 error attempting access to control, response is 'ERR'.
789 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800790 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700791 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700792 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700793 try:
794 value = self.get(name)
795 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700796 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -0700797 pass
798 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700799 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700800 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700801 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800802 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700803
804 def set(self, name, wr_val_str):
805 """Set control.
806
807 Args:
808 name: name string of control
809 wr_val_str: value string to write. Can be integer, float or a
810 alpha-numerical that is mapped to a integer or float.
811
812 Raises:
813 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800814 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700815 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700816 self._logger.debug('name(%s) wr_val(%s)' % (name, wr_val_str))
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700817 (params, drv, device) = self._get_param_drv(name, False)
818 if device in self._devices:
819 self._devices[device].wait(self.INTERFACE_AVAILABILITY_TIMEOUT)
Todd Broche505b8d2011-03-21 18:19:54 -0700820 wr_val = self._syscfg.resolve_val(params, wr_val_str)
821 try:
822 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800823 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700824 self._logger.error('Setting %s -> %s' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700825 raise
Ruben Rodriguez Buchillon73cc5a82018-09-24 16:23:11 +0800826 # pylint: disable=broad-except
827 # This acts as a safety to inform the user of errors that should not
828 # be happening/require more investigation.
829 except Exception:
830 self._logger.error('Unknown issue setting %s -> %s. Please take a look.',
831 name, wr_val_str)
832 raise
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +0800833 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
834 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -0700835 # marshall/unmarshall
836 return True
837
Todd Brochd6061672012-05-11 15:52:47 -0700838 def hwinit(self, verbose=False):
839 """Initialize all controls.
840
841 These values are part of the system config XML files of the form
842 init=<value>. This command should be used by clients wishing to return the
843 servo and DUT its connected to a known good/safe state.
844
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800845 Note that initialization errors are ignored (as in some cases they could
846 be caused by DUT firmware deficiencies). This might need to be fine tuned
847 later.
848
Todd Brochd6061672012-05-11 15:52:47 -0700849 Args:
850 verbose: boolean, if True prints info about control initialized.
851 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800852
853 Returns:
854 This function is called across RPC and as such is expected to return
855 something unless transferring 'none' across is allowed. Hence adding a
856 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700857 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800858 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800859 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700860 # Workaround for bug chrome-os-partner:42349. Without this check, the
861 # gpio will briefly pulse low if we set it from high to high.
862 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700863 self.set(control_name, value)
864 if verbose:
865 self._logger.info('Initialized %s to %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700866 except Exception as e:
867 self._logger.error(
Matthew Bleckera5d979c2018-10-16 20:59:19 -0700868 'Problem initializing %s -> %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700869 self._logger.error(str(e))
870 self._logger.error('Please consider verifying the logs and if the '
871 'error is not just a setup issue, consider filing '
872 'a bug. Also checkout go/servo-ki.')
Nick Sandersbc836282015-12-08 21:19:23 -0800873
Namyoon Woo6ff36612019-10-16 16:41:12 -0700874 # If there is the control of 'active_v4_device', set active_v4_device to
875 # the default device as initialization.
Namyoon Wooad2a2bb2019-11-04 16:26:15 -0800876 try:
Namyoon Woo6ff36612019-10-16 16:41:12 -0700877 self.set('active_v4_device', 'default')
Namyoon Wooad2a2bb2019-11-04 16:26:15 -0800878 except NameError as e:
879 # If the control does not exist, just pass it.
880 pass
881 except activeV4DeviceError as e:
882 self._logger.error(str(e))
Namyoon Woo6ff36612019-10-16 16:41:12 -0700883
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800884 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800885
Todd Broche505b8d2011-03-21 18:19:54 -0700886 def echo(self, echo):
887 """Dummy echo function for testing/examples.
888
889 Args:
890 echo: string to echo back to client
891 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700892 self._logger.debug('echo(%s)' % (echo))
893 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -0700894
J. Richard Barnettee2820552013-03-14 16:13:46 -0700895 def get_board(self):
896 """Return the board specified at startup, if any."""
897 return self._board
898
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700899 def get_base_board(self):
900 """Returns the board name of the base if present.
901
902 Returns:
903 A string of the board name, or '' if not present.
904 """
905 # The value is set in servo_postinit.
906 return self._base_board
907
Simran Basia23c1392013-08-06 14:59:10 -0700908 def get_version(self):
909 """Get servo board version."""
910 return self._version
911
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800912 def power_long_press(self):
913 """Simulate a long power button press."""
914 # After a long power press, the EC may ignore the next power
915 # button press (at least on Alex). To guarantee that this
916 # won't happen, we need to allow the EC one second to
917 # collect itself.
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800918 return self.set('power_key', 'long_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800919
920 def power_normal_press(self):
921 """Simulate a normal power button press."""
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800922 return self.set('power_key', 'press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800923
924 def power_short_press(self):
925 """Simulate a short power button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530926 return self.set('power_key', 'short_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800927
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530928 def power_key(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800929 """Simulate a power button press.
930
931 Args:
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530932 press_secs: Time in seconds to simulate the keypress.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800933 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530934 return self.set('power_key', 'press' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800935
936 def ctrl_d(self, press_secs=''):
937 """Simulate Ctrl-d simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530938 return self.set('ctrl_d', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800939
Victor Dodone539cea2016-03-29 18:50:17 -0700940 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800941 """Simulate Ctrl-u simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530942 return self.set('ctrl_u', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800943
944 def ctrl_enter(self, press_secs=''):
945 """Simulate Ctrl-enter simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530946 return self.set('ctrl_enter', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800947
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800948 def ctrl_key(self, press_secs=''):
949 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530950 return self.set('ctrl_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800951
952 def enter_key(self, press_secs=''):
953 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530954 return self.set('enter_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800955
956 def refresh_key(self, press_secs=''):
957 """Simulate Refresh key (F3) button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530958 return self.set('refresh_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800959
960 def ctrl_refresh_key(self, press_secs=''):
961 """Simulate Ctrl and Refresh (F3) simultaneous press.
962
963 This key combination is an alternative of Space key.
964 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530965 return self.set('ctrl_refresh_key', ('tab' if press_secs is '' else
966 press_secs))
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800967
968 def imaginary_key(self, press_secs=''):
969 """Simulate imaginary key button press.
970
971 Maps to a key that doesn't physically exist.
972 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530973 return self.set('imaginary_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800974
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200975 def sysrq_x(self, press_secs=''):
976 """Simulate Alt VolumeUp X simultaneous press.
977
978 This key combination is the kernel system request (sysrq) x.
979 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530980 return self.set('sysrq_x', 'tab' if press_secs is '' else press_secs)
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200981
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700982 def get_servo_serials(self):
983 """Return all the serials associated with this process."""
984 return self._serialnames
985
986
Todd Broche505b8d2011-03-21 18:19:54 -0700987def test():
988 """Integration testing.
989
990 TODO(tbroch) Enhance integration test and add unittest (see mox)
991 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700992 logging.basicConfig(
993 level=logging.DEBUG,
994 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -0700995 # configure server & listen
996 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700997 # 5 == number of interfaces on a FT4232H device
998 for i in xrange(1, 5):
999 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -07001000 # its an i2c interface ... see __init__ for details and TODO to make
1001 # this configureable
1002 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1003 else:
1004 # its a gpio interface
1005 servod_obj._interface_list[i].wr_rd(0)
1006
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001007 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost', 9999),
Todd Broche505b8d2011-03-21 18:19:54 -07001008 allow_none=True)
1009 server.register_introspection_functions()
1010 server.register_multicall_functions()
1011 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001012 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -07001013 server.serve_forever()
1014
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001015
1016if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -07001017 test()
1018
1019 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001020 """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)
1021
Todd Broche505b8d2011-03-21 18:19:54 -07001022 """