blob: 46e6d694381e8392e1cef68f68a847f7084295ab [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,
Namyoon Woo341a8332019-03-07 12:01:31 -0800127 board='', model='', 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
Namyoon Woo341a8332019-03-07 12:01:31 -0800137 board: board name. e.g. octopus, coral, or scarlet.
138 model: model name of a given board. e.g. fleex, ampton, or apel.
Simran Basia23c1392013-08-06 14:59:10 -0700139 version: String. Servo board version. Examples: servo_v1, servo_v2,
140 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800141 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700142 sending keyboard commands to DUTs that do not have built in
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700143 keyboards. Used in FAFT tests. Use None for on board AVR MCU.
144 e.g. '/dev/ttyUSB0' or None.
Todd Brochdbb09982011-10-02 07:14:26 -0700145
146 Raises:
147 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700148 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700149 self._logger = logging.getLogger('Servod')
150 self._logger.debug('')
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800151 self._ifaces_available = threading.Event()
152 # Initially interfaces should be available.
153 self._ifaces_available.set()
Todd Broche505b8d2011-03-21 18:19:54 -0700154 self._vendor = vendor
155 self._product = product
Mary Ruthven13389642017-02-14 12:15:34 -0800156 self._devices = []
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700157 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700158 self._syscfg = config
159 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
160 # interfaces are mapped to
161 self._interface_list = []
162 # Dict of Dict to map control name, function name to to tuple (params, drv)
163 # Ex) _drv_dict[name]['get'] = (params, drv)
164 self._drv_dict = {}
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700165 self._base_board = ''
Namyoon Woo341a8332019-03-07 12:01:31 -0800166 self._board = board
167 if model:
168 self._board += '_' + model
169 self._model = model
Simran Basia23c1392013-08-06 14:59:10 -0700170 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800171 self._usbkm232 = usbkm232
Todd Brochdbb09982011-10-02 07:14:26 -0700172 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700173 try:
174 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
175 except KeyError:
176 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Dino Lic89d8c82018-01-11 09:56:47 +0800177 self._interfaces = interfaces
Todd Brochdbb09982011-10-02 07:14:26 -0700178
Kevin Chengdc3befd2016-07-15 12:34:00 -0700179 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700180 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800181
Mary Ruthven13389642017-02-14 12:15:34 -0800182 def reinitialize(self):
183 """Reinitialize all interfaces that support reinitialization"""
Mary Ruthven13389642017-02-14 12:15:34 -0800184 for i, interface in enumerate(self._interface_list):
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700185 if hasattr(interface, 'reinitialize'):
186 interface.reinitialize()
187 else:
188 self._logger.debug('interface %d has no reset functionality', i)
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800189 # Indicate interfaces are safe to use again.
190 self._ifaces_available.set()
Mary Ruthven13389642017-02-14 12:15:34 -0800191
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700192 def get_servo_interfaces(self, position, size):
193 """Get the list of servo interfaces.
194
195 Args:
196 position: The index the first interface to get.
197 size: The number of the interfaces.
198 """
199 return self._interface_list[position:(position + size)]
200
201 def set_servo_interfaces(self, position, interfaces):
202 """Set the list of servo interfaces.
203
204 Args:
205 position: The index the first interface to set.
206 interfaces: The list of interfaces to set.
207 """
208 size = len(interfaces)
209 self._interface_list[position:(position + size)] = interfaces
210
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800211 def _init_keyboard_handler(self, servo, board=''):
212 """Initialize the correct keyboard handler for board.
213
Kevin Chengdc3befd2016-07-15 12:34:00 -0700214 Args:
215 servo: servo object.
216 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800217
Kevin Chengdc3befd2016-07-15 12:34:00 -0700218 Returns:
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700219 keyboard handler object, or None if no keyboard supported.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800220 """
221 if board == 'parrot':
222 return keyboard_handlers.ParrotHandler(servo)
223 elif board == 'stout':
224 return keyboard_handlers.StoutHandler(servo)
Ravutappa29c58662019-03-21 09:56:35 -0700225 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'mistral',
226 'monroe', 'ninja', 'nyan_kitty', 'panther', 'rikku',
227 'sarien', 'stumpy', 'sumo', 'tidus', 'tricky',
228 'veyron_fievel', 'veyron_mickey', 'veyron_rialto',
229 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800230 if self._usbkm232 is None:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700231 logging.info('No device path specified for usbkm232 handler. Use '
232 'the servo atmega chip to handle.')
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700233
Danny Chan662b6022015-11-04 17:34:53 -0800234 # Use servo onboard keyboard emulator.
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700235 if not self._syscfg.is_control('atmega_rst'):
236 logging.warn('No atmega in servo board. So no keyboard support.')
237 return None
238
Nick Sanders78423782015-11-09 14:28:19 -0800239 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800240 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800241 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800242 self._usbkm232 = self.get('atmega_pty')
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700243
Kevin Cheng810fc782016-11-01 12:36:46 -0700244 # We don't need to set the atmega uart settings if we're a servo v4.
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700245 if 'servo_v4' not in self._version:
Kevin Cheng810fc782016-11-01 12:36:46 -0700246 self.set('atmega_baudrate', '9600')
247 self.set('atmega_bits', 'eight')
248 self.set('atmega_parity', 'none')
249 self.set('atmega_sbits', 'one')
250 self.set('usb_mux_sel4', 'on')
251 self.set('usb_mux_oe4', 'on')
252 # Allow atmega bootup time.
253 time.sleep(1.0)
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700254
Danny Chan662b6022015-11-04 17:34:53 -0800255 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800256 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
257 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800258 # The following boards don't use Chrome EC.
259 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
260 return keyboard_handlers.MatrixKeyboardHandler(servo)
261 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800262
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700263 def close(self):
264 """Servod turn down logic."""
265 for i, interface in enumerate(self._interface_list):
266 self._logger.info('Turning down interface %d' % i)
267 if hasattr(interface, 'close'):
268 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800269
Kevin Chengdc3befd2016-07-15 12:34:00 -0700270 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700271 """Dummy interface for ftdi devices.
272
273 This is a dummy function specifically for ftdi devices to not initialize
274 anything but to help pad the interface list.
275
276 Returns:
277 None.
278 """
279 return None
280
Kevin Chengdc3befd2016-07-15 12:34:00 -0700281 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700282 """Initialize gpio driver interface and open for use.
283
284 Args:
285 interface: interface number of FTDI device to use.
286
287 Returns:
288 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700289
290 Raises:
291 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700292 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700293 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700294 try:
295 fobj.open()
296 except ftdigpio.FgpioError as e:
297 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
298
Todd Broche505b8d2011-03-21 18:19:54 -0700299 return fobj
300
Kevin Chengdc3befd2016-07-15 12:34:00 -0700301 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800302 """Initialize stm32 uart interface and open for use
303
304 Note, the uart runs in a separate thread. Users wishing to
305 interact with it will query control for the pty's pathname and connect
306 with their favorite console program. For example:
307 cu -l /dev/pts/22
308
309 Args:
310 interface: dict of interface parameters.
311
312 Returns:
313 Instance object of interface
314
315 Raises:
316 ServodError: Raised on init failure.
317 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700318 self._logger.info('Suart: interface: %s' % interface)
319 sobj = stm32uart.Suart(vendor, product, interface['interface'], serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800320
321 try:
322 sobj.run()
323 except stm32uart.SuartError as e:
324 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
325
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700326 self._logger.info('%s' % sobj.get_pty())
Nick Sanders97bc4462016-01-04 15:37:31 -0800327 return sobj
328
Kevin Chengdc3befd2016-07-15 12:34:00 -0700329 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800330 """Initialize stm32 gpio interface.
331 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700332 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800333
334 Returns:
335 Instance object of interface
336
337 Raises:
338 SgpioError: Raised on init failure.
339 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700340 interface_number = interface
341 # Interface could be a dict.
342 if type(interface) is dict:
343 interface_number = interface['interface']
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700344 self._logger.info('Sgpio: interface: %s' % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700345 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800346
Kevin Chengdc3befd2016-07-15 12:34:00 -0700347 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800348 """Initialize stm32 USB to I2C bridge interface and open for use
349
350 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700351 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800352
353 Returns:
354 Instance object of interface.
355
356 Raises:
357 Si2cError: Raised on init failure.
358 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700359 self._logger.info('Si2cBus: interface: %s' % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800360 port = interface.get('port', 0)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700361 return stm32i2c.Si2cBus(vendor, product, interface['interface'], port=port,
362 serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800363
Kevin Chengdc3befd2016-07-15 12:34:00 -0700364 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800365 """Initalize beaglebone ADC interface."""
366 return bbadc.BBadc()
367
Kevin Chengdc3befd2016-07-15 12:34:00 -0700368 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700369 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700370 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700371
Kevin Chengdc3befd2016-07-15 12:34:00 -0700372 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700373 """Initialize i2c interface and open for use.
374
375 Args:
376 interface: interface number of FTDI device to use
377
378 Returns:
379 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700380
381 Raises:
382 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700383 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700384 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700385 try:
386 fobj.open()
387 except ftdii2c.Fi2cError as e:
388 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
389
Todd Broche505b8d2011-03-21 18:19:54 -0700390 # Set the frequency of operation of the i2c bus.
391 # TODO(tbroch) make configureable
392 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700393
Todd Broche505b8d2011-03-21 18:19:54 -0700394 return fobj
395
Simran Basie750a342013-03-12 13:45:26 -0700396 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
397 def _init_bb_i2c(self, interface):
398 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700399 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700400
Kevin Chengdc3befd2016-07-15 12:34:00 -0700401 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800402 """Initalize Linux i2c-dev interface."""
403 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
404
Kevin Chengdc3befd2016-07-15 12:34:00 -0700405 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700406 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700407
408 Note, the uart runs in a separate thread (pthreads). Users wishing to
409 interact with it will query control for the pty's pathname and connect
410 with there favorite console program. For example:
411 cu -l /dev/pts/22
412
413 Args:
414 interface: interface number of FTDI device to use
415
416 Returns:
417 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700418
419 Raises:
420 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700421 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700422 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700423 try:
424 fobj.run()
425 except ftdiuart.FuartError as e:
426 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
427
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700428 self._logger.info('%s' % fobj.get_pty())
Todd Broch47c43f42011-05-26 15:11:31 -0700429 return fobj
430
Simran Basie750a342013-03-12 13:45:26 -0700431 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700432 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700433 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700434 logging.debug('UART INTERFACE: %s', interface)
435 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700436
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700437 def _init_ftdi_gpiouart(self, vendor, product, serialname, interface):
Todd Broch888da782011-10-07 14:29:09 -0700438 """Initialize special gpio + uart interface and open for use
439
440 Note, the uart runs in a separate thread (pthreads). Users wishing to
441 interact with it will query control for the pty's pathname and connect
442 with there favorite console program. For example:
443 cu -l /dev/pts/22
444
445 Args:
446 interface: interface number of FTDI device to use
447
448 Returns:
449 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700450
451 Raises:
452 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700453 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700454 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700455 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700456 try:
457 fuart.run()
458 except ftdiuart.FuartError as e:
459 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
460
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700461 self._logger.info('uart pty: %s' % fuart.get_pty())
Todd Broch888da782011-10-07 14:29:09 -0700462 return fgpio, fuart
463
Kevin Chengdc3befd2016-07-15 12:34:00 -0700464 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800465 """Initialize EC-3PO console interpreter interface.
466
467 Args:
468 interface: A dictionary representing the interface.
469
470 Returns:
471 An EC3PO object representing the EC-3PO interface or None if there's no
472 interface for the USB PD UART.
473 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700474 raw_uart_name = interface['raw_pty']
Nick Sanders116ed9e2018-03-09 19:05:16 -0800475 raw_uart_source = interface['source']
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700476 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800477 raw_ec_uart = self.get(raw_uart_name)
Nick Sanders116ed9e2018-03-09 19:05:16 -0800478 return ec3po_interface.EC3PO(raw_ec_uart, raw_uart_source)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800479 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700480 # The overlay doesn't have the raw PTY defined, therefore we can skip
481 # initializing this interface since no control relies on it.
482 self._logger.debug(
483 'Skip initializing EC3PO for %s, no control specified.',
484 raw_uart_name)
485 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800486
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800487 def _camel_case(self, string):
488 output = ''
489 for s in string.split('_'):
490 if output:
491 output += s.capitalize()
492 else:
493 output = s
494 return output
495
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700496 def clear_cached_drv(self):
497 """Clear the cached drivers.
498
499 The drivers are cached in the Dict _drv_dict when a control is got or set.
500 When the servo interfaces are relocated, the cached values may become wrong.
501 Should call this method to clear the cached values.
502 """
503 self._drv_dict = {}
504
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800505 def _get_servo_specific_param(self, params, param_key, control_name):
506 """Get |param_key| from params by looking for servo specific params first.
507
508 Find the candidate servos. Using servo_v4 with a servo_micro connected as
509 example, the following shows the priority for selecting the interface.
510
511 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
512 2. servo_micro_interface
513 3. servo_v4_interface
514 4. Fallback to the default, interface.
515
516 Args:
517 params: params dictionary for a control
518 param_key: identifier in the params dictionary to look for
519 control_name: control name the params correspond to
520
521 Returns:
522 The best suited param value for param_key given the servo type or
523 None if even the default is not defined.
524 """
525 candidates = [self._version]
526 candidates.extend(reversed(self._version.split('_with_')))
527 candidates = ['%s_%s' % (c, param_key) for c in candidates]
528 candidates.append(param_key)
529 for c in candidates:
530 if c in params:
531 self._logger.debug('Using %s parameter.', c)
532 return params[c]
533 self._logger.error('Unable to determine %s for %s', param_key, control_name)
534 self._logger.error('params: %r', params)
535 return None
536
Todd Broche505b8d2011-03-21 18:19:54 -0700537 def _get_param_drv(self, control_name, is_get=True):
538 """Get access to driver for a given control.
539
540 Note, some controls have different parameter dictionaries for 'getting' the
541 control's value versus 'setting' it. Boolean is_get distinguishes which is
542 being requested.
543
544 Args:
545 control_name: string name of control
546 is_get: boolean to determine
547
548 Returns:
549 tuple (param, drv) where:
550 param: param dictionary for control
551 drv: instance object of driver for particular control
552
553 Raises:
554 ServodError: Error occurred while examining params dict
555 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700556 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700557 # if already setup just return tuple from driver dict
558 if control_name in self._drv_dict:
559 if is_get and ('get' in self._drv_dict[control_name]):
560 return self._drv_dict[control_name]['get']
561 if not is_get and ('set' in self._drv_dict[control_name]):
562 return self._drv_dict[control_name]['set']
563
564 params = self._syscfg.lookup_control_params(control_name, is_get)
Simran Basi668be0e2013-08-07 11:54:50 -0700565
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800566 # Get the most suitable drv given the servo instance.
567 drv_name = self._get_servo_specific_param(params, 'drv', control_name)
568 if drv_name == 'na':
569 # 'na' drv can be used to selectively turn controls into noops for
570 # a given servo hardware. Ensure that there is an interface.
571 params.setdefault('interface', 'servo')
572 self._logger.debug('Setting interface to default to %r for %r unless '
573 ' defined in params, as drv is %r.', 'servo',
574 control_name, 'na')
575 # Setting input_type to str allows all inputs through enabling a true noop
576 params.update({'input_type': 'str'})
577 interface_id = self._get_servo_specific_param(params, 'interface',
578 control_name)
579 if None in [drv_name, interface_id]:
580 raise ServodError('No drv/interface for control %r found' % control_name)
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700581
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800582 if interface_id == 'servo':
583 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700584 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700585 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800586 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700587
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800588 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800589 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700590 drv = drv_class(interface, params)
591 if control_name not in self._drv_dict:
592 self._drv_dict[control_name] = {}
593 if is_get:
594 self._drv_dict[control_name]['get'] = (params, drv)
595 else:
596 self._drv_dict[control_name]['set'] = (params, drv)
597 return (params, drv)
598
599 def doc_all(self):
600 """Return all documenation for controls.
601
602 Returns:
603 string of <doc> text in config file (xml) and the params dictionary for
604 all controls.
605
606 For example:
607 warm_reset :: Reset the device warmly
608 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
609 """
610 return self._syscfg.display_config()
611
612 def doc(self, name):
613 """Retreive doc string in system config file for given control name.
614
615 Args:
616 name: name string of control to get doc string
617
618 Returns:
619 doc string of name
620
621 Raises:
622 NameError: if fails to locate control
623 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700624 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700625 if self._syscfg.is_control(name):
626 return self._syscfg.get_control_docstring(name)
627 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700628 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700629
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800630 def safe_switch_usbkey_power(self, power_state, _=None):
Kevin Cheng5595b342016-09-29 15:51:01 -0700631 """Toggle the usb power safely.
632
Kevin Chengc49494e2016-07-25 12:13:38 -0700633 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700634 power_state: The setting to set for the usbkey power.
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800635 _: to conform to current API
Kevin Chengc49494e2016-07-25 12:13:38 -0700636
Kevin Cheng5595b342016-09-29 15:51:01 -0700637 Returns:
638 An empty string to appease the xmlrpc gods.
639 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800640 self.set('image_usbkey_pwr', power_state)
Kevin Cheng5595b342016-09-29 15:51:01 -0700641 return ''
642
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800643 def safe_switch_usbkey(self, mux_direction, _=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700644 """Toggle the usb direction safely.
645
Kevin Cheng5595b342016-09-29 15:51:01 -0700646 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800647 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800648 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700649
650 Returns:
651 An empty string to appease the xmlrpc gods.
652 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800653 self.set('image_usbkey_direction', mux_direction)
Kevin Cheng5595b342016-09-29 15:51:01 -0700654 return ''
655
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800656 def probe_host_usb_dev(self, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700657 """Probe the USB disk device plugged in the servo from the host side.
658
Kevin Cheng5595b342016-09-29 15:51:01 -0700659 Args:
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800660 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700661
Simran Basia9f41032012-05-11 14:21:58 -0700662 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700663 USB disk path if one and only one USB disk path is found, otherwise an
Simran Basia9f41032012-05-11 14:21:58 -0700664 """
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800665 return self.get('image_usbkey_dev')
Kevin Chengc49494e2016-07-25 12:13:38 -0700666
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800667 def download_image_to_usb(self, image_path, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700668 """Download image and save to the USB device found by probe_host_usb_dev.
669 If the image_path is a URL, it will download this url to the USB path;
670 otherwise it will simply copy the image_path's contents to the USB path.
671
672 Args:
673 image_path: path or url to the recovery image.
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800674 _: to conform to current API
Simran Basia9f41032012-05-11 14:21:58 -0700675
676 Returns:
677 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800678 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700679 """
Simran Basia9f41032012-05-11 14:21:58 -0700680 try:
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800681 self.set('download_image_to_usb_dev', image_path)
682 return True
683 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700684 return False
Simran Basia9f41032012-05-11 14:21:58 -0700685
686 def make_image_noninteractive(self):
687 """Makes the recovery image noninteractive.
688
689 A noninteractive image will reboot automatically after installation
690 instead of waiting for the USB device to be removed to initiate a system
691 reboot.
692
693 Mounts partition 1 of the image stored on usb_dev and creates a file
694 called "non_interactive" so that the image will become noninteractive.
695
696 Returns:
697 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800698 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700699 """
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800700 try:
701 usb_dev = self.get('image_usbkey_dev')
702 usb_dev_partition = '%s1' % usb_dev
703 self.set('make_usb_dev_image_noninteractive', usb_dev_partition)
704 return True
705 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700706 return False
Simran Basia9f41032012-05-11 14:21:58 -0700707
Todd Broch352b4b22013-03-22 09:48:40 -0700708 def set_get_all(self, cmds):
709 """Set &| get one or more control values.
710
711 Args:
712 cmds: list of control[:value] to get or set.
713
714 Returns:
715 rv: list of responses from calling get or set methods.
716 """
717 rv = []
718 for cmd in cmds:
719 if ':' in cmd:
720 (control, value) = cmd.split(':')
721 rv.append(self.set(control, value))
722 else:
723 rv.append(self.get(cmd))
724 return rv
725
Aseda Aboagye6921f602017-08-01 14:45:38 -0700726 def get_serial_number(self, name):
727 """Returns the desired serial number from the serialnames dict.
728
729 Args:
730 name: A string which is the key into the _serialnames dictionary.
731
732 Returns:
733 A string containing the serial number or "unknown".
734 """
735 if not name:
736 name = 'main'
737
738 try:
739 return self._serialnames[name]
740 except KeyError:
741 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700742 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700743
Todd Broche505b8d2011-03-21 18:19:54 -0700744 def get(self, name):
745 """Get control value.
746
747 Args:
748 name: name string of control
749
750 Returns:
751 Response from calling drv get method. Value is reformatted based on
752 control's dictionary parameters
753
754 Raises:
755 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800756 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700757 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800758 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
759 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700760 self._logger.debug('name(%s)' % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700761 # This route is to retrieve serialnames on servo v4, which
762 # connects to multiple servo-micros or CCD, like the controls,
763 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
764 # TODO(aaboagye): Refactor it.
765 if 'serialname' in name:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700766 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700767
Todd Broche505b8d2011-03-21 18:19:54 -0700768 (param, drv) = self._get_param_drv(name)
769 try:
770 val = drv.get()
771 rd_val = self._syscfg.reformat_val(param, val)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700772 self._logger.debug('%s = %s' % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700773 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700774 except AttributeError, error:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700775 self._logger.error('Getting %s: %s' % (name, error))
Todd Brochfbc499d2011-06-16 16:09:58 -0700776 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800777 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700778 self._logger.error('Getting %s' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700779 raise
Todd Brochd6061672012-05-11 15:52:47 -0700780
Todd Broche505b8d2011-03-21 18:19:54 -0700781 def get_all(self, verbose):
782 """Get all controls values.
783
784 Args:
785 verbose: Boolean on whether to return doc info as well
786
787 Returns:
788 string creating from trying to get all values of all controls. In case of
789 error attempting access to control, response is 'ERR'.
790 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800791 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700792 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700793 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700794 try:
795 value = self.get(name)
796 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700797 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -0700798 pass
799 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700800 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700801 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700802 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800803 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700804
805 def set(self, name, wr_val_str):
806 """Set control.
807
808 Args:
809 name: name string of control
810 wr_val_str: value string to write. Can be integer, float or a
811 alpha-numerical that is mapped to a integer or float.
812
813 Raises:
814 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800815 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700816 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800817 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
818 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700819 self._logger.debug('name(%s) wr_val(%s)' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700820 (params, drv) = self._get_param_drv(name, False)
821 wr_val = self._syscfg.resolve_val(params, wr_val_str)
822 try:
823 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800824 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700825 self._logger.error('Setting %s -> %s' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -0700826 raise
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +0800827 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
828 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -0700829 # marshall/unmarshall
830 return True
831
Todd Brochd6061672012-05-11 15:52:47 -0700832 def hwinit(self, verbose=False):
833 """Initialize all controls.
834
835 These values are part of the system config XML files of the form
836 init=<value>. This command should be used by clients wishing to return the
837 servo and DUT its connected to a known good/safe state.
838
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800839 Note that initialization errors are ignored (as in some cases they could
840 be caused by DUT firmware deficiencies). This might need to be fine tuned
841 later.
842
Todd Brochd6061672012-05-11 15:52:47 -0700843 Args:
844 verbose: boolean, if True prints info about control initialized.
845 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800846
847 Returns:
848 This function is called across RPC and as such is expected to return
849 something unless transferring 'none' across is allowed. Hence adding a
850 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700851 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800852 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800853 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700854 # Workaround for bug chrome-os-partner:42349. Without this check, the
855 # gpio will briefly pulse low if we set it from high to high.
856 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700857 self.set(control_name, value)
858 if verbose:
859 self._logger.info('Initialized %s to %s', control_name, value)
Matthew Bleckera5d979c2018-10-16 20:59:19 -0700860 except Exception:
861 self._logger.exception(
862 'Problem initializing %s -> %s', control_name, value)
Nick Sandersbc836282015-12-08 21:19:23 -0800863
864 # Init keyboard after all the intefaces are up.
865 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800866 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800867
Todd Broche505b8d2011-03-21 18:19:54 -0700868 def echo(self, echo):
869 """Dummy echo function for testing/examples.
870
871 Args:
872 echo: string to echo back to client
873 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700874 self._logger.debug('echo(%s)' % (echo))
875 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -0700876
J. Richard Barnettee2820552013-03-14 16:13:46 -0700877 def get_board(self):
878 """Return the board specified at startup, if any."""
879 return self._board
880
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700881 def get_base_board(self):
882 """Returns the board name of the base if present.
883
884 Returns:
885 A string of the board name, or '' if not present.
886 """
887 # The value is set in servo_postinit.
888 return self._base_board
889
Simran Basia23c1392013-08-06 14:59:10 -0700890 def get_version(self):
891 """Get servo board version."""
892 return self._version
893
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800894 def power_long_press(self):
895 """Simulate a long power button press."""
896 # After a long power press, the EC may ignore the next power
897 # button press (at least on Alex). To guarantee that this
898 # won't happen, we need to allow the EC one second to
899 # collect itself.
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800900 return self.set('power_key', 'long_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800901
902 def power_normal_press(self):
903 """Simulate a normal power button press."""
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800904 return self.set('power_key', 'press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800905
906 def power_short_press(self):
907 """Simulate a short power button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530908 return self.set('power_key', 'short_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800909
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530910 def power_key(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800911 """Simulate a power button press.
912
913 Args:
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530914 press_secs: Time in seconds to simulate the keypress.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800915 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530916 return self.set('power_key', 'press' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800917
918 def ctrl_d(self, press_secs=''):
919 """Simulate Ctrl-d simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530920 return self.set('ctrl_d', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800921
Victor Dodone539cea2016-03-29 18:50:17 -0700922 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800923 """Simulate Ctrl-u simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530924 return self.set('ctrl_u', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800925
926 def ctrl_enter(self, press_secs=''):
927 """Simulate Ctrl-enter simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530928 return self.set('ctrl_enter', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800929
930 def d_key(self, press_secs=''):
931 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530932 return self.set('d_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800933
934 def ctrl_key(self, press_secs=''):
935 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530936 return self.set('ctrl_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800937
938 def enter_key(self, press_secs=''):
939 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530940 return self.set('enter_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800941
942 def refresh_key(self, press_secs=''):
943 """Simulate Refresh key (F3) button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530944 return self.set('refresh_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800945
946 def ctrl_refresh_key(self, press_secs=''):
947 """Simulate Ctrl and Refresh (F3) simultaneous press.
948
949 This key combination is an alternative of Space key.
950 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530951 return self.set('ctrl_refresh_key', ('tab' if press_secs is '' else
952 press_secs))
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800953
954 def imaginary_key(self, press_secs=''):
955 """Simulate imaginary key button press.
956
957 Maps to a key that doesn't physically exist.
958 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530959 return self.set('imaginary_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800960
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200961 def sysrq_x(self, press_secs=''):
962 """Simulate Alt VolumeUp X simultaneous press.
963
964 This key combination is the kernel system request (sysrq) x.
965 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530966 return self.set('sysrq_x', 'tab' if press_secs is '' else press_secs)
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200967
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700968 def get_servo_serials(self):
969 """Return all the serials associated with this process."""
970 return self._serialnames
971
972
Todd Broche505b8d2011-03-21 18:19:54 -0700973def test():
974 """Integration testing.
975
976 TODO(tbroch) Enhance integration test and add unittest (see mox)
977 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700978 logging.basicConfig(
979 level=logging.DEBUG,
980 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -0700981 # configure server & listen
982 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700983 # 5 == number of interfaces on a FT4232H device
984 for i in xrange(1, 5):
985 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -0700986 # its an i2c interface ... see __init__ for details and TODO to make
987 # this configureable
988 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
989 else:
990 # its a gpio interface
991 servod_obj._interface_list[i].wr_rd(0)
992
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700993 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost', 9999),
Todd Broche505b8d2011-03-21 18:19:54 -0700994 allow_none=True)
995 server.register_introspection_functions()
996 server.register_multicall_functions()
997 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700998 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -0700999 server.serve_forever()
1000
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001001
1002if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -07001003 test()
1004
1005 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001006 """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)
1007
Todd Broche505b8d2011-03-21 18:19:54 -07001008 """