blob: 46ac716a54c2b7a8233774b0e2ce40dd4a3ce70b [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."""
Simran Basia9f41032012-05-11 14:21:58 -07005import fnmatch
Todd Broche505b8d2011-03-21 18:19:54 -07006import imp
7import logging
Simran Basia9f41032012-05-11 14:21:58 -07008import os
9import shutil
Todd Broche505b8d2011-03-21 18:19:54 -070010import SimpleXMLRPCServer
Simran Basia9f41032012-05-11 14:21:58 -070011import subprocess
12import tempfile
Todd Broch7a91c252012-02-03 12:37:45 -080013import time
Simran Basia9f41032012-05-11 14:21:58 -070014import urllib
Todd Broche505b8d2011-03-21 18:19:54 -070015
16# TODO(tbroch) deprecate use of relative imports
Vic Yangbe6cf262012-09-10 10:40:56 +080017from drv.hw_driver import HwDriverError
Aaron.Chuang88eff332014-07-31 08:32:00 +080018import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070019import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070020import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070021import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080022import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070023import ftdigpio
24import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070025import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070026import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080027import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080028import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070029import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070030import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080031import stm32gpio
32import stm32i2c
33import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070034
Aseda Aboagyea4922212015-11-20 15:19:08 -080035
Todd Broche505b8d2011-03-21 18:19:54 -070036MAX_I2C_CLOCK_HZ = 100000
37
Todd Brochdbb09982011-10-02 07:14:26 -070038
Todd Broche505b8d2011-03-21 18:19:54 -070039class ServodError(Exception):
40 """Exception class for servod."""
41
42class Servod(object):
43 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070044 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070045 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070046 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070047 _USB_J3 = "usb_mux_sel1"
48 _USB_J3_TO_SERVO = "servo_sees_usbkey"
49 _USB_J3_TO_DUT = "dut_sees_usbkey"
50 _USB_J3_PWR = "prtctl4_pwren"
51 _USB_J3_PWR_ON = "on"
52 _USB_J3_PWR_OFF = "off"
Simran Basia9f41032012-05-11 14:21:58 -070053
Kevin Chengdc3befd2016-07-15 12:34:00 -070054 def init_servo_interfaces(self, vendor, product, serialname,
55 interfaces):
56 """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 """
74 # Extend the interface list if we need to.
75 interfaces_len = len(interfaces)
76 interface_list_len = len(self._interface_list)
77 if interfaces_len > interface_list_len:
78 self._interface_list += [None] * (interfaces_len - interface_list_len)
79
80 shifted = 0
81 for i, interface in enumerate(interfaces):
82 is_ftdi_interface = False
83 if type(interface) is dict:
84 name = interface['name']
85 # Store interface index for those that care about it.
86 interface['index'] = i
87 elif type(interface) is str and interface != 'dummy':
88 name = interface
89 # It's a FTDI related interface.
90 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
91 is_ftdi_interface = True
92 elif type(interface) is str and interface == 'dummy':
93 # 'dummy' reserves the interface for future use. Typically the
94 # interface will be managed by external third-party tools like
95 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
96 # it serves as a placeholder for servo micro interfaces.
97 continue
98 else:
99 raise ServodError("Illegal interface type %s" % type(interface))
100
101 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
102 if is_ftdi_interface and i and \
103 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
104 product += 1
105 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
106 product)
107
108 self._logger.info("Initializing interface %d to %s", i + 1, name)
109 try:
110 func = getattr(self, '_init_%s' % name)
111 except AttributeError:
112 raise ServodError("Unable to locate init for interface %s" % name)
113 result = func(vendor, product, serialname, interface)
114
115 if isinstance(result, tuple):
116 result_len = len(result)
117 shifted += result_len - 1
118 self._interface_list += [None] * result_len
119 for result_index, r in enumerate(result):
120 self._interface_list[i + result_index] = r
121 else:
122 self._interface_list[i + shifted] = result
123
J. Richard Barnettee2820552013-03-14 16:13:46 -0700124 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800125 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700126 """Servod constructor.
127
128 Args:
129 config: instance of SystemConfig containing all controls for
130 particular Servod invocation
131 vendor: usb vendor id of FTDI device
132 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700133 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700134 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700135 version: String. Servo board version. Examples: servo_v1, servo_v2,
136 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800137 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700138 sending keyboard commands to DUTs that do not have built in
139 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
140 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -0700141
142 Raises:
143 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700144 """
145 self._logger = logging.getLogger("Servod")
146 self._logger.debug("")
147 self._vendor = vendor
148 self._product = product
Todd Brochad034442011-05-25 15:05:29 -0700149 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -0700150 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700151 # Hold the last image path so we can reduce downloads to the usb device.
152 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700153 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
154 # interfaces are mapped to
155 self._interface_list = []
156 # Dict of Dict to map control name, function name to to tuple (params, drv)
157 # Ex) _drv_dict[name]['get'] = (params, drv)
158 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700159 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -0700160 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800161 self._usbkm232 = usbkm232
Todd Brochdbb09982011-10-02 07:14:26 -0700162 # Note, interface i is (i - 1) in list
163 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700164 try:
165 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
166 except KeyError:
167 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -0700168
Kevin Chengdc3befd2016-07-15 12:34:00 -0700169 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700170 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800171
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800172 def _init_keyboard_handler(self, servo, board=''):
173 """Initialize the correct keyboard handler for board.
174
Kevin Chengdc3befd2016-07-15 12:34:00 -0700175 Args:
176 servo: servo object.
177 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800178
Kevin Chengdc3befd2016-07-15 12:34:00 -0700179 Returns:
180 keyboard handler object.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800181 """
182 if board == 'parrot':
183 return keyboard_handlers.ParrotHandler(servo)
184 elif board == 'stout':
185 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800186 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800187 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
Jason Simmonse5cccd12015-08-25 16:05:25 -0700188 'sumo', 'tidus', 'tricky', 'veyron_mickey', 'veyron_rialto',
ren kuobf62ddd2016-06-24 11:55:43 +0800189 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800190 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800191 logging.info("No device path specified for usbkm232 handler. Use "
192 "the servo atmega chip to handle.")
193 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800194 if self._usbkm232 == 'atmega':
195 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800196 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800197 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800198 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800199 self._usbkm232 = self.get('atmega_pty')
200 self.set('atmega_baudrate', '9600')
201 self.set('atmega_bits', 'eight')
202 self.set('atmega_parity', 'none')
203 self.set('atmega_sbits', 'one')
204 self.set('usb_mux_sel4', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800205 self.set('usb_mux_oe4', 'on')
Nick Sanders78423782015-11-09 14:28:19 -0800206 # Allow atmega bootup time.
207 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800208 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800209 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
210 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800211 # The following boards don't use Chrome EC.
212 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
213 return keyboard_handlers.MatrixKeyboardHandler(servo)
214 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800215
Todd Broch3ec8df02012-11-20 10:53:03 -0800216 def __del__(self):
217 """Servod deconstructor."""
218 for interface in self._interface_list:
219 del(interface)
220
Kevin Chengdc3befd2016-07-15 12:34:00 -0700221 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700222 """Dummy interface for ftdi devices.
223
224 This is a dummy function specifically for ftdi devices to not initialize
225 anything but to help pad the interface list.
226
227 Returns:
228 None.
229 """
230 return None
231
Kevin Chengdc3befd2016-07-15 12:34:00 -0700232 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700233 """Initialize gpio driver interface and open for use.
234
235 Args:
236 interface: interface number of FTDI device to use.
237
238 Returns:
239 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700240
241 Raises:
242 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700243 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700244 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700245 try:
246 fobj.open()
247 except ftdigpio.FgpioError as e:
248 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
249
Todd Broche505b8d2011-03-21 18:19:54 -0700250 return fobj
251
Kevin Chengdc3befd2016-07-15 12:34:00 -0700252 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800253 """Initialize stm32 uart interface and open for use
254
255 Note, the uart runs in a separate thread. Users wishing to
256 interact with it will query control for the pty's pathname and connect
257 with their favorite console program. For example:
258 cu -l /dev/pts/22
259
260 Args:
261 interface: dict of interface parameters.
262
263 Returns:
264 Instance object of interface
265
266 Raises:
267 ServodError: Raised on init failure.
268 """
269 self._logger.info("Suart: interface: %s" % interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700270 sobj = stm32uart.Suart(vendor, product, interface['interface'],
271 serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800272
273 try:
274 sobj.run()
275 except stm32uart.SuartError as e:
276 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
277
278 self._logger.info("%s" % sobj.get_pty())
279 return sobj
280
Kevin Chengdc3befd2016-07-15 12:34:00 -0700281 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800282 """Initialize stm32 gpio interface.
283 Args:
284 interface: interface number of stm32 device to use.
285
286 Returns:
287 Instance object of interface
288
289 Raises:
290 SgpioError: Raised on init failure.
291 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700292 interface_number = interface
293 # Interface could be a dict.
294 if type(interface) is dict:
295 interface_number = interface['interface']
296 self._logger.info("Sgpio: interface: %s" % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700297 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800298
Kevin Chengdc3befd2016-07-15 12:34:00 -0700299 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800300 """Initialize stm32 USB to I2C bridge interface and open for use
301
302 Args:
303 interface: USB interface number of stm32 device to use
304
305 Returns:
306 Instance object of interface.
307
308 Raises:
309 Si2cError: Raised on init failure.
310 """
311 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800312 port = interface.get('port', 0)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700313 return stm32i2c.Si2cBus(vendor, product, interface['interface'],
314 port=port, serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800315
Kevin Chengdc3befd2016-07-15 12:34:00 -0700316 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800317 """Initalize beaglebone ADC interface."""
318 return bbadc.BBadc()
319
Kevin Chengdc3befd2016-07-15 12:34:00 -0700320 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700321 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700322 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700323
Kevin Chengdc3befd2016-07-15 12:34:00 -0700324 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700325 """Initialize i2c interface and open for use.
326
327 Args:
328 interface: interface number of FTDI device to use
329
330 Returns:
331 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700332
333 Raises:
334 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700335 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700336 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700337 try:
338 fobj.open()
339 except ftdii2c.Fi2cError as e:
340 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
341
Todd Broche505b8d2011-03-21 18:19:54 -0700342 # Set the frequency of operation of the i2c bus.
343 # TODO(tbroch) make configureable
344 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700345
Todd Broche505b8d2011-03-21 18:19:54 -0700346 return fobj
347
Simran Basie750a342013-03-12 13:45:26 -0700348 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
349 def _init_bb_i2c(self, interface):
350 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700351 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700352
Kevin Chengdc3befd2016-07-15 12:34:00 -0700353 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800354 """Initalize Linux i2c-dev interface."""
355 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
356
Kevin Chengdc3befd2016-07-15 12:34:00 -0700357 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700358 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700359
360 Note, the uart runs in a separate thread (pthreads). Users wishing to
361 interact with it will query control for the pty's pathname and connect
362 with there favorite console program. For example:
363 cu -l /dev/pts/22
364
365 Args:
366 interface: interface number of FTDI device to use
367
368 Returns:
369 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700370
371 Raises:
372 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700373 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700374 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700375 try:
376 fobj.run()
377 except ftdiuart.FuartError as e:
378 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
379
Todd Broch47c43f42011-05-26 15:11:31 -0700380 self._logger.info("%s" % fobj.get_pty())
381 return fobj
382
Simran Basie750a342013-03-12 13:45:26 -0700383 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700384 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700385 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700386 logging.debug('UART INTERFACE: %s', interface)
387 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700388
Kevin Chengdc3befd2016-07-15 12:34:00 -0700389 def _init_ftdi_gpiouart(self, vendor, product, serialname,
390 interface):
Todd Broch888da782011-10-07 14:29:09 -0700391 """Initialize special gpio + uart interface and open for use
392
393 Note, the uart runs in a separate thread (pthreads). Users wishing to
394 interact with it will query control for the pty's pathname and connect
395 with there favorite console program. For example:
396 cu -l /dev/pts/22
397
398 Args:
399 interface: interface number of FTDI device to use
400
401 Returns:
402 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700403
404 Raises:
405 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700406 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700407 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700408 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700409 try:
410 fuart.run()
411 except ftdiuart.FuartError as e:
412 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
413
Todd Broch888da782011-10-07 14:29:09 -0700414 self._logger.info("uart pty: %s" % fuart.get_pty())
415 return fgpio, fuart
416
Kevin Chengdc3befd2016-07-15 12:34:00 -0700417 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800418 """Initialize EC-3PO console interpreter interface.
419
420 Args:
421 interface: A dictionary representing the interface.
422
423 Returns:
424 An EC3PO object representing the EC-3PO interface or None if there's no
425 interface for the USB PD UART.
426 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700427 vid = vendor
428 pid = product
Aseda Aboagyea4922212015-11-20 15:19:08 -0800429 # The current PID might be incremented if there are multiple FTDI.
430 # Therefore, try rewinding the PID back one if we don't find the base PID in
431 # the SERVO_ID_DEFAULTS
432 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
433 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
434 pid -= 1
435 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
436
Nick Sanders97bc4462016-01-04 15:37:31 -0800437 if 'raw_pty' in interface:
438 # We have specified an explicit target for this ec3po.
439 raw_uart_name = interface['raw_pty']
440 raw_ec_uart = self.get(raw_uart_name)
441
Aseda Aboagyea4922212015-11-20 15:19:08 -0800442 # Servo V2 / V3 should have the interface indicies in the same spot.
Nick Sanders97bc4462016-01-04 15:37:31 -0800443 elif ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
Aseda Aboagyea4922212015-11-20 15:19:08 -0800444 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
445 # Determine if it's a PD interface or just main EC console.
446 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
447 try:
448 # Obtain the raw EC UART PTY and create the EC-3PO interface.
449 raw_ec_uart = self.get('raw_usbpd_uart_pty')
450 except NameError:
451 # This overlay doesn't have a USB PD MCU, so skip init.
452 self._logger.info('No PD MCU UART.')
453 return None
454 except AttributeError:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700455 # This overlay has no get method for the interface so skip init. For
456 # servo v2, it's common for interfaces to be overridden such as
457 # reusing JTAG pins for the PD MCU UART instead. Therefore, print an
458 # error message indicating that the interface might be set
459 # incorrectly.
460 if (vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS:
461 self._logger.warn('No interface for PD MCU UART.')
462 self._logger.warn('Usually, this happens because the interface is '
463 'set incorrectly. If you\'re overriding an '
464 'existing interface, be sure to update the '
465 'interface lists for your board at the end of '
466 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800467 return None
468
469 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
470 raw_ec_uart = self.get('raw_ec_uart_pty')
471
472 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
473 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
474 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
475 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
476 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
477 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
478 raw_ec_uart = self.get('raw_ec_uart_pty')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800479 else:
480 raise ServodError(('Unexpected EC-3PO interface!'
481 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
482
483 return ec3po_interface.EC3PO(raw_ec_uart)
484
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800485 def _camel_case(self, string):
486 output = ''
487 for s in string.split('_'):
488 if output:
489 output += s.capitalize()
490 else:
491 output = s
492 return output
493
Todd Broche505b8d2011-03-21 18:19:54 -0700494 def _get_param_drv(self, control_name, is_get=True):
495 """Get access to driver for a given control.
496
497 Note, some controls have different parameter dictionaries for 'getting' the
498 control's value versus 'setting' it. Boolean is_get distinguishes which is
499 being requested.
500
501 Args:
502 control_name: string name of control
503 is_get: boolean to determine
504
505 Returns:
506 tuple (param, drv) where:
507 param: param dictionary for control
508 drv: instance object of driver for particular control
509
510 Raises:
511 ServodError: Error occurred while examining params dict
512 """
513 self._logger.debug("")
514 # if already setup just return tuple from driver dict
515 if control_name in self._drv_dict:
516 if is_get and ('get' in self._drv_dict[control_name]):
517 return self._drv_dict[control_name]['get']
518 if not is_get and ('set' in self._drv_dict[control_name]):
519 return self._drv_dict[control_name]['set']
520
521 params = self._syscfg.lookup_control_params(control_name, is_get)
522 if 'drv' not in params:
523 self._logger.error("Unable to determine driver for %s" % control_name)
524 raise ServodError("'drv' key not found in params dict")
525 if 'interface' not in params:
526 self._logger.error("Unable to determine interface for %s" %
527 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700528 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700529
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800530 interface_id = params.get(
531 '%s_interface' % self._version, params['interface'])
532 if interface_id == 'servo':
533 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700534 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800535 index = int(interface_id) - 1
536 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700537
Todd Broche505b8d2011-03-21 18:19:54 -0700538 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
539 drv_pkg = imp.load_module('drv',
540 *imp.find_module('drv', servo_pkg.__path__))
541 drv_name = params['drv']
542 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800543 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700544 drv = drv_class(interface, params)
545 if control_name not in self._drv_dict:
546 self._drv_dict[control_name] = {}
547 if is_get:
548 self._drv_dict[control_name]['get'] = (params, drv)
549 else:
550 self._drv_dict[control_name]['set'] = (params, drv)
551 return (params, drv)
552
553 def doc_all(self):
554 """Return all documenation for controls.
555
556 Returns:
557 string of <doc> text in config file (xml) and the params dictionary for
558 all controls.
559
560 For example:
561 warm_reset :: Reset the device warmly
562 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
563 """
564 return self._syscfg.display_config()
565
566 def doc(self, name):
567 """Retreive doc string in system config file for given control name.
568
569 Args:
570 name: name string of control to get doc string
571
572 Returns:
573 doc string of name
574
575 Raises:
576 NameError: if fails to locate control
577 """
578 self._logger.debug("name(%s)" % (name))
579 if self._syscfg.is_control(name):
580 return self._syscfg.get_control_docstring(name)
581 else:
582 raise NameError("No control %s" %name)
583
Fang Deng90377712013-06-03 15:51:48 -0700584 def _switch_usbkey(self, mux_direction):
585 """Connect USB flash stick to either servo or DUT.
586
587 This function switches 'usb_mux_sel1' to provide electrical
588 connection between the USB port J3 and either servo or DUT side.
589
590 Switching the usb mux is accompanied by powercycling
591 of the USB stick, because it sometimes gets wedged if the mux
592 is switched while the stick power is on.
593
594 Args:
595 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
596 """
597 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
598 time.sleep(self._USB_POWEROFF_DELAY)
599 self.set(self._USB_J3, mux_direction)
600 time.sleep(self._USB_POWEROFF_DELAY)
601 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
602 if mux_direction == self._USB_J3_TO_SERVO:
603 time.sleep(self._USB_DETECTION_DELAY)
604
Simran Basia9f41032012-05-11 14:21:58 -0700605 def _get_usb_port_set(self):
606 """Gets a set of USB disks currently connected to the system
607
608 Returns:
609 A set of USB disk paths.
610 """
611 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
612 return set(["/dev/" + dev for dev in usb_set])
613
614 def _probe_host_usb_dev(self):
615 """Probe the USB disk device plugged in the servo from the host side.
616
617 Method can fail by:
618 1) Having multiple servos connected and returning incorrect /dev/sdX of
619 another servo.
620 2) Finding multiple /dev/sdX and returning None.
621
622 Returns:
623 USB disk path if one and only one USB disk path is found, otherwise None.
624 """
Fang Deng90377712013-06-03 15:51:48 -0700625 original_value = self.get(self._USB_J3)
626 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700627 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700628 if (original_usb_power == self._USB_J3_PWR_ON and
629 original_value != self._USB_J3_TO_DUT):
630 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700631 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700632
Fang Deng90377712013-06-03 15:51:48 -0700633 # Make the host able to see the USB disk.
634 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700635 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700636
Simran Basia9f41032012-05-11 14:21:58 -0700637 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700638 if original_value != self._USB_J3_TO_SERVO:
639 self._switch_usbkey(original_value)
640 if original_usb_power != self._USB_J3_PWR_ON:
641 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
642 time.sleep(self._USB_POWEROFF_DELAY)
643
Simran Basia9f41032012-05-11 14:21:58 -0700644 # Subtract the two sets to find the usb device.
645 diff_set = has_usb_set - no_usb_set
646 if len(diff_set) == 1:
647 return diff_set.pop()
648 else:
649 return None
650
651 def download_image_to_usb(self, image_path):
652 """Download image and save to the USB device found by probe_host_usb_dev.
653 If the image_path is a URL, it will download this url to the USB path;
654 otherwise it will simply copy the image_path's contents to the USB path.
655
656 Args:
657 image_path: path or url to the recovery image.
658
659 Returns:
660 True|False: True if process completed successfully, False if error
661 occurred.
662 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
663 comment at the end of set().
664 """
665 self._logger.debug("image_path(%s)" % image_path)
666 self._logger.debug("Detecting USB stick device...")
667 usb_dev = self._probe_host_usb_dev()
668 if not usb_dev:
669 self._logger.error("No usb device connected to servo")
670 return False
671
Kevin Cheng9071ed92016-06-21 14:37:54 -0700672 # Let's check if we downloaded this last time and if so assume the image is
673 # still on the usb device and return True.
674 if self._image_path == image_path:
675 self._logger.debug("Image already on USB device, skipping transfer")
676 return True
677
Simran Basia9f41032012-05-11 14:21:58 -0700678 try:
679 if image_path.startswith(self._HTTP_PREFIX):
680 self._logger.debug("Image path is a URL, downloading image")
681 urllib.urlretrieve(image_path, usb_dev)
682 else:
683 shutil.copyfile(image_path, usb_dev)
684 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700685 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700686 e.strerror, e.errno)
687 return False
688 except urllib.ContentTooShortError:
689 self._logger.error("Failed to download URL: %s to USB device: %s",
690 image_path, usb_dev)
691 return False
692 except BaseException as e:
693 self._logger.error("Unexpected exception downloading %s to %s: %s",
694 image_path, usb_dev, str(e))
695 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800696 finally:
697 # We just plastered the partition table for a block device.
698 # Pass or fail, we mustn't go without telling the kernel about
699 # the change, or it will punish us with sporadic, hard-to-debug
700 # failures.
701 subprocess.call(["sync"])
702 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700703 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700704 return True
705
706 def make_image_noninteractive(self):
707 """Makes the recovery image noninteractive.
708
709 A noninteractive image will reboot automatically after installation
710 instead of waiting for the USB device to be removed to initiate a system
711 reboot.
712
713 Mounts partition 1 of the image stored on usb_dev and creates a file
714 called "non_interactive" so that the image will become noninteractive.
715
716 Returns:
717 True|False: True if process completed successfully, False if error
718 occurred.
719 """
720 result = True
721 usb_dev = self._probe_host_usb_dev()
722 if not usb_dev:
723 self._logger.error("No usb device connected to servo")
724 return False
725 # Create TempDirectory
726 tmpdir = tempfile.mkdtemp()
727 if tmpdir:
728 # Mount drive to tmpdir.
729 partition_1 = "%s1" % usb_dev
730 rc = subprocess.call(["mount", partition_1, tmpdir])
731 if rc == 0:
732 # Create file 'non_interactive'
733 non_interactive_file = os.path.join(tmpdir, "non_interactive")
734 try:
735 open(non_interactive_file, "w").close()
736 except IOError as e:
737 self._logger.error("Failed to create file %s : %s ( %d )",
738 non_interactive_file, e.strerror, e.errno)
739 result = False
740 except BaseException as e:
741 self._logger.error("Unexpected Exception creating file %s : %s",
742 non_interactive_file, str(e))
743 result = False
744 # Unmount drive regardless if file creation worked or not.
745 rc = subprocess.call(["umount", partition_1])
746 if rc != 0:
747 self._logger.error("Failed to unmount USB Device")
748 result = False
749 else:
750 self._logger.error("Failed to mount USB Device")
751 result = False
752
753 # Delete tmpdir. May throw exception if 'umount' failed.
754 try:
755 os.rmdir(tmpdir)
756 except OSError as e:
757 self._logger.error("Failed to remove temp directory %s : %s",
758 tmpdir, str(e))
759 return False
760 except BaseException as e:
761 self._logger.error("Unexpected Exception removing tempdir %s : %s",
762 tmpdir, str(e))
763 return False
764 else:
765 self._logger.error("Failed to create temp directory.")
766 return False
767 return result
768
Todd Broch352b4b22013-03-22 09:48:40 -0700769 def set_get_all(self, cmds):
770 """Set &| get one or more control values.
771
772 Args:
773 cmds: list of control[:value] to get or set.
774
775 Returns:
776 rv: list of responses from calling get or set methods.
777 """
778 rv = []
779 for cmd in cmds:
780 if ':' in cmd:
781 (control, value) = cmd.split(':')
782 rv.append(self.set(control, value))
783 else:
784 rv.append(self.get(cmd))
785 return rv
786
Todd Broche505b8d2011-03-21 18:19:54 -0700787 def get(self, name):
788 """Get control value.
789
790 Args:
791 name: name string of control
792
793 Returns:
794 Response from calling drv get method. Value is reformatted based on
795 control's dictionary parameters
796
797 Raises:
798 HwDriverError: Error occurred while using drv
799 """
800 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700801 if name == 'serialname':
802 if self._serialname:
803 return self._serialname
804 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700805 (param, drv) = self._get_param_drv(name)
806 try:
807 val = drv.get()
808 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800809 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700810 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700811 except AttributeError, error:
812 self._logger.error("Getting %s: %s" % (name, error))
813 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800814 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700815 self._logger.error("Getting %s" % (name))
816 raise
Todd Brochd6061672012-05-11 15:52:47 -0700817
Todd Broche505b8d2011-03-21 18:19:54 -0700818 def get_all(self, verbose):
819 """Get all controls values.
820
821 Args:
822 verbose: Boolean on whether to return doc info as well
823
824 Returns:
825 string creating from trying to get all values of all controls. In case of
826 error attempting access to control, response is 'ERR'.
827 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800828 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700829 for name in self._syscfg.syscfg_dict['control']:
830 self._logger.debug("name = %s" %name)
831 try:
832 value = self.get(name)
833 except Exception:
834 value = "ERR"
835 pass
836 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800837 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700838 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800839 rsp.append("%s:%s" % (name, value))
840 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700841
842 def set(self, name, wr_val_str):
843 """Set control.
844
845 Args:
846 name: name string of control
847 wr_val_str: value string to write. Can be integer, float or a
848 alpha-numerical that is mapped to a integer or float.
849
850 Raises:
851 HwDriverError: Error occurred while using driver
852 """
853 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
854 (params, drv) = self._get_param_drv(name, False)
855 wr_val = self._syscfg.resolve_val(params, wr_val_str)
856 try:
857 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800858 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700859 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
860 raise
861 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
862 # & client I still have to return something to appease the
863 # marshall/unmarshall
864 return True
865
Todd Brochd6061672012-05-11 15:52:47 -0700866 def hwinit(self, verbose=False):
867 """Initialize all controls.
868
869 These values are part of the system config XML files of the form
870 init=<value>. This command should be used by clients wishing to return the
871 servo and DUT its connected to a known good/safe state.
872
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800873 Note that initialization errors are ignored (as in some cases they could
874 be caused by DUT firmware deficiencies). This might need to be fine tuned
875 later.
876
Todd Brochd6061672012-05-11 15:52:47 -0700877 Args:
878 verbose: boolean, if True prints info about control initialized.
879 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800880
881 Returns:
882 This function is called across RPC and as such is expected to return
883 something unless transferring 'none' across is allowed. Hence adding a
884 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700885 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800886 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800887 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700888 # Workaround for bug chrome-os-partner:42349. Without this check, the
889 # gpio will briefly pulse low if we set it from high to high.
890 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700891 self.set(control_name, value)
892 if verbose:
893 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800894 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800895 self._logger.error("Problem initializing %s -> %s :: %s",
896 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -0800897
898 # Init keyboard after all the intefaces are up.
899 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800900 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800901
Todd Broche505b8d2011-03-21 18:19:54 -0700902 def echo(self, echo):
903 """Dummy echo function for testing/examples.
904
905 Args:
906 echo: string to echo back to client
907 """
908 self._logger.debug("echo(%s)" % (echo))
909 return "ECH0ING: %s" % (echo)
910
J. Richard Barnettee2820552013-03-14 16:13:46 -0700911 def get_board(self):
912 """Return the board specified at startup, if any."""
913 return self._board
914
Simran Basia23c1392013-08-06 14:59:10 -0700915 def get_version(self):
916 """Get servo board version."""
917 return self._version
918
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800919 def power_long_press(self):
920 """Simulate a long power button press."""
921 # After a long power press, the EC may ignore the next power
922 # button press (at least on Alex). To guarantee that this
923 # won't happen, we need to allow the EC one second to
924 # collect itself.
925 self._keyboard.power_long_press()
926 return True
927
928 def power_normal_press(self):
929 """Simulate a normal power button press."""
930 self._keyboard.power_normal_press()
931 return True
932
933 def power_short_press(self):
934 """Simulate a short power button press."""
935 self._keyboard.power_short_press()
936 return True
937
938 def power_key(self, secs=''):
939 """Simulate a power button press.
940
941 Args:
942 secs: Time in seconds to simulate the keypress.
943 """
944 self._keyboard.power_key(secs)
945 return True
946
947 def ctrl_d(self, press_secs=''):
948 """Simulate Ctrl-d simultaneous button presses."""
949 self._keyboard.ctrl_d(press_secs)
950 return True
951
Victor Dodone539cea2016-03-29 18:50:17 -0700952 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800953 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -0700954 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800955 return True
956
957 def ctrl_enter(self, press_secs=''):
958 """Simulate Ctrl-enter simultaneous button presses."""
959 self._keyboard.ctrl_enter(press_secs)
960 return True
961
962 def d_key(self, press_secs=''):
963 """Simulate Enter key button press."""
964 self._keyboard.d_key(press_secs)
965 return True
966
967 def ctrl_key(self, press_secs=''):
968 """Simulate Enter key button press."""
969 self._keyboard.ctrl_key(press_secs)
970 return True
971
972 def enter_key(self, press_secs=''):
973 """Simulate Enter key button press."""
974 self._keyboard.enter_key(press_secs)
975 return True
976
977 def refresh_key(self, press_secs=''):
978 """Simulate Refresh key (F3) button press."""
979 self._keyboard.refresh_key(press_secs)
980 return True
981
982 def ctrl_refresh_key(self, press_secs=''):
983 """Simulate Ctrl and Refresh (F3) simultaneous press.
984
985 This key combination is an alternative of Space key.
986 """
987 self._keyboard.ctrl_refresh_key(press_secs)
988 return True
989
990 def imaginary_key(self, press_secs=''):
991 """Simulate imaginary key button press.
992
993 Maps to a key that doesn't physically exist.
994 """
995 self._keyboard.imaginary_key(press_secs)
996 return True
997
Todd Brochdbb09982011-10-02 07:14:26 -0700998
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200999 def sysrq_x(self, press_secs=''):
1000 """Simulate Alt VolumeUp X simultaneous press.
1001
1002 This key combination is the kernel system request (sysrq) x.
1003 """
1004 self._keyboard.sysrq_x(press_secs)
1005 return True
1006
1007
Todd Broche505b8d2011-03-21 18:19:54 -07001008def test():
1009 """Integration testing.
1010
1011 TODO(tbroch) Enhance integration test and add unittest (see mox)
1012 """
1013 logging.basicConfig(level=logging.DEBUG,
1014 format="%(asctime)s - %(name)s - " +
1015 "%(levelname)s - %(message)s")
1016 # configure server & listen
1017 servod_obj = Servod(1)
1018 # 4 == number of interfaces on a FT4232H device
1019 for i in xrange(4):
1020 if i == 1:
1021 # its an i2c interface ... see __init__ for details and TODO to make
1022 # this configureable
1023 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1024 else:
1025 # its a gpio interface
1026 servod_obj._interface_list[i].wr_rd(0)
1027
1028 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1029 allow_none=True)
1030 server.register_introspection_functions()
1031 server.register_multicall_functions()
1032 server.register_instance(servod_obj)
1033 logging.info("Listening on localhost port 9999")
1034 server.serve_forever()
1035
1036if __name__ == "__main__":
1037 test()
1038
1039 # simple client transaction would look like
1040 """
1041 remote_uri = 'http://localhost:9999'
1042 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1043 send_str = "Hello_there"
1044 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1045 """