blob: 4a15eadcb74747d34a6cd055f106226508b59db4 [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 imp
9import logging
Simran Basia9f41032012-05-11 14:21:58 -070010import os
Kevin Chengc49494e2016-07-25 12:13:38 -070011import random
Simran Basia9f41032012-05-11 14:21:58 -070012import shutil
Todd Broche505b8d2011-03-21 18:19:54 -070013import SimpleXMLRPCServer
Simran Basia9f41032012-05-11 14:21:58 -070014import subprocess
15import tempfile
Todd Broch7a91c252012-02-03 12:37:45 -080016import time
Simran Basia9f41032012-05-11 14:21:58 -070017import urllib
Todd Broche505b8d2011-03-21 18:19:54 -070018
19# TODO(tbroch) deprecate use of relative imports
Vic Yangbe6cf262012-09-10 10:40:56 +080020from drv.hw_driver import HwDriverError
Aaron.Chuang88eff332014-07-31 08:32:00 +080021import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070022import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070023import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070024import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080025import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070026import ftdigpio
27import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070028import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070029import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080030import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080031import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070032import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070033import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080034import stm32gpio
35import stm32i2c
36import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070037
Aseda Aboagyea4922212015-11-20 15:19:08 -080038
Todd Broche505b8d2011-03-21 18:19:54 -070039MAX_I2C_CLOCK_HZ = 100000
40
Todd Brochdbb09982011-10-02 07:14:26 -070041
Todd Broche505b8d2011-03-21 18:19:54 -070042class ServodError(Exception):
43 """Exception class for servod."""
44
45class Servod(object):
46 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070047 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070048 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070049 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070050 _USB_J3 = "usb_mux_sel1"
51 _USB_J3_TO_SERVO = "servo_sees_usbkey"
52 _USB_J3_TO_DUT = "dut_sees_usbkey"
53 _USB_J3_PWR = "prtctl4_pwren"
54 _USB_J3_PWR_ON = "on"
55 _USB_J3_PWR_OFF = "off"
Kevin Chengc49494e2016-07-25 12:13:38 -070056 _USB_LOCK_FILE = "/var/lib/servod/lock_file"
57 # It takes about 16-17 seconds for the entire probe usb device method,
58 # let's wait double plus some buffer.
59 _MAX_USB_LOCK_WAIT = 40
Simran Basia9f41032012-05-11 14:21:58 -070060
Kevin Chengdc3befd2016-07-15 12:34:00 -070061 def init_servo_interfaces(self, vendor, product, serialname,
62 interfaces):
63 """Init the servo interfaces with the given interfaces.
64
65 We don't use the self._{vendor,product,serialname} attributes because we
66 want to allow other callers to initialize other interfaces that may not
67 be associated with the initialized attributes (e.g. a servo v4 servod object
68 that wants to also initialize a servo micro interface).
69
70 Args:
71 vendor: USB vendor id of FTDI device.
72 product: USB product id of FTDI device.
73 serialname: String of device serialname/number as defined in FTDI
74 eeprom.
75 interfaces: List of strings of interface types the server will
76 instantiate.
77
78 Raises:
79 ServodError if unable to locate init method for particular interface.
80 """
81 # Extend the interface list if we need to.
82 interfaces_len = len(interfaces)
83 interface_list_len = len(self._interface_list)
84 if interfaces_len > interface_list_len:
85 self._interface_list += [None] * (interfaces_len - interface_list_len)
86
87 shifted = 0
88 for i, interface in enumerate(interfaces):
89 is_ftdi_interface = False
90 if type(interface) is dict:
91 name = interface['name']
92 # Store interface index for those that care about it.
93 interface['index'] = i
94 elif type(interface) is str and interface != 'dummy':
95 name = interface
96 # It's a FTDI related interface.
97 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
98 is_ftdi_interface = True
99 elif type(interface) is str and interface == 'dummy':
100 # 'dummy' reserves the interface for future use. Typically the
101 # interface will be managed by external third-party tools like
102 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
103 # it serves as a placeholder for servo micro interfaces.
104 continue
105 else:
106 raise ServodError("Illegal interface type %s" % type(interface))
107
108 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
109 if is_ftdi_interface and i and \
110 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
111 product += 1
112 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
113 product)
114
115 self._logger.info("Initializing interface %d to %s", i + 1, name)
116 try:
117 func = getattr(self, '_init_%s' % name)
118 except AttributeError:
119 raise ServodError("Unable to locate init for interface %s" % name)
120 result = func(vendor, product, serialname, interface)
121
122 if isinstance(result, tuple):
123 result_len = len(result)
124 shifted += result_len - 1
125 self._interface_list += [None] * result_len
126 for result_index, r in enumerate(result):
127 self._interface_list[i + result_index] = r
128 else:
129 self._interface_list[i + shifted] = result
130
J. Richard Barnettee2820552013-03-14 16:13:46 -0700131 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800132 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700133 """Servod constructor.
134
135 Args:
136 config: instance of SystemConfig containing all controls for
137 particular Servod invocation
138 vendor: usb vendor id of FTDI device
139 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700140 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700141 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700142 version: String. Servo board version. Examples: servo_v1, servo_v2,
143 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800144 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700145 sending keyboard commands to DUTs that do not have built in
146 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
147 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -0700148
149 Raises:
150 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700151 """
152 self._logger = logging.getLogger("Servod")
153 self._logger.debug("")
154 self._vendor = vendor
155 self._product = product
Todd Brochad034442011-05-25 15:05:29 -0700156 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -0700157 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700158 # Hold the last image path so we can reduce downloads to the usb device.
159 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700160 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
161 # interfaces are mapped to
162 self._interface_list = []
163 # Dict of Dict to map control name, function name to to tuple (params, drv)
164 # Ex) _drv_dict[name]['get'] = (params, drv)
165 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700166 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -0700167 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800168 self._usbkm232 = usbkm232
Kevin Chengc49494e2016-07-25 12:13:38 -0700169 # Seed the random generator with the serial to differentiate from other
170 # servod processes.
171 random.seed(serialname if serialname else time.time())
Todd Brochdbb09982011-10-02 07:14:26 -0700172 # Note, interface i is (i - 1) in list
173 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700174 try:
175 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
176 except KeyError:
177 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
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
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800182 def _init_keyboard_handler(self, servo, board=''):
183 """Initialize the correct keyboard handler for board.
184
Kevin Chengdc3befd2016-07-15 12:34:00 -0700185 Args:
186 servo: servo object.
187 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800188
Kevin Chengdc3befd2016-07-15 12:34:00 -0700189 Returns:
190 keyboard handler object.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800191 """
192 if board == 'parrot':
193 return keyboard_handlers.ParrotHandler(servo)
194 elif board == 'stout':
195 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800196 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800197 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
Jason Simmonse5cccd12015-08-25 16:05:25 -0700198 'sumo', 'tidus', 'tricky', 'veyron_mickey', 'veyron_rialto',
ren kuobf62ddd2016-06-24 11:55:43 +0800199 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800200 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800201 logging.info("No device path specified for usbkm232 handler. Use "
202 "the servo atmega chip to handle.")
203 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800204 if self._usbkm232 == 'atmega':
205 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800206 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800207 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800208 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800209 self._usbkm232 = self.get('atmega_pty')
210 self.set('atmega_baudrate', '9600')
211 self.set('atmega_bits', 'eight')
212 self.set('atmega_parity', 'none')
213 self.set('atmega_sbits', 'one')
214 self.set('usb_mux_sel4', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800215 self.set('usb_mux_oe4', 'on')
Nick Sanders78423782015-11-09 14:28:19 -0800216 # Allow atmega bootup time.
217 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800218 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800219 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
220 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800221 # The following boards don't use Chrome EC.
222 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
223 return keyboard_handlers.MatrixKeyboardHandler(servo)
224 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800225
Todd Broch3ec8df02012-11-20 10:53:03 -0800226 def __del__(self):
227 """Servod deconstructor."""
228 for interface in self._interface_list:
229 del(interface)
230
Kevin Chengdc3befd2016-07-15 12:34:00 -0700231 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700232 """Dummy interface for ftdi devices.
233
234 This is a dummy function specifically for ftdi devices to not initialize
235 anything but to help pad the interface list.
236
237 Returns:
238 None.
239 """
240 return None
241
Kevin Chengdc3befd2016-07-15 12:34:00 -0700242 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700243 """Initialize gpio driver interface and open for use.
244
245 Args:
246 interface: interface number of FTDI device to use.
247
248 Returns:
249 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700250
251 Raises:
252 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700253 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700254 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700255 try:
256 fobj.open()
257 except ftdigpio.FgpioError as e:
258 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
259
Todd Broche505b8d2011-03-21 18:19:54 -0700260 return fobj
261
Kevin Chengdc3befd2016-07-15 12:34:00 -0700262 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800263 """Initialize stm32 uart interface and open for use
264
265 Note, the uart runs in a separate thread. Users wishing to
266 interact with it will query control for the pty's pathname and connect
267 with their favorite console program. For example:
268 cu -l /dev/pts/22
269
270 Args:
271 interface: dict of interface parameters.
272
273 Returns:
274 Instance object of interface
275
276 Raises:
277 ServodError: Raised on init failure.
278 """
279 self._logger.info("Suart: interface: %s" % interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700280 sobj = stm32uart.Suart(vendor, product, interface['interface'],
281 serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800282
283 try:
284 sobj.run()
285 except stm32uart.SuartError as e:
286 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
287
288 self._logger.info("%s" % sobj.get_pty())
289 return sobj
290
Kevin Chengdc3befd2016-07-15 12:34:00 -0700291 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800292 """Initialize stm32 gpio interface.
293 Args:
294 interface: interface number of stm32 device to use.
295
296 Returns:
297 Instance object of interface
298
299 Raises:
300 SgpioError: Raised on init failure.
301 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700302 interface_number = interface
303 # Interface could be a dict.
304 if type(interface) is dict:
305 interface_number = interface['interface']
306 self._logger.info("Sgpio: interface: %s" % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700307 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800308
Kevin Chengdc3befd2016-07-15 12:34:00 -0700309 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800310 """Initialize stm32 USB to I2C bridge interface and open for use
311
312 Args:
313 interface: USB interface number of stm32 device to use
314
315 Returns:
316 Instance object of interface.
317
318 Raises:
319 Si2cError: Raised on init failure.
320 """
321 self._logger.info("Si2cBus: interface: %s" % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800322 port = interface.get('port', 0)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700323 return stm32i2c.Si2cBus(vendor, product, interface['interface'],
324 port=port, serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800325
Kevin Chengdc3befd2016-07-15 12:34:00 -0700326 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800327 """Initalize beaglebone ADC interface."""
328 return bbadc.BBadc()
329
Kevin Chengdc3befd2016-07-15 12:34:00 -0700330 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700331 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700332 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700333
Kevin Chengdc3befd2016-07-15 12:34:00 -0700334 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700335 """Initialize i2c interface and open for use.
336
337 Args:
338 interface: interface number of FTDI device to use
339
340 Returns:
341 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700342
343 Raises:
344 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700345 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700346 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700347 try:
348 fobj.open()
349 except ftdii2c.Fi2cError as e:
350 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
351
Todd Broche505b8d2011-03-21 18:19:54 -0700352 # Set the frequency of operation of the i2c bus.
353 # TODO(tbroch) make configureable
354 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700355
Todd Broche505b8d2011-03-21 18:19:54 -0700356 return fobj
357
Simran Basie750a342013-03-12 13:45:26 -0700358 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
359 def _init_bb_i2c(self, interface):
360 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700361 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700362
Kevin Chengdc3befd2016-07-15 12:34:00 -0700363 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800364 """Initalize Linux i2c-dev interface."""
365 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
366
Kevin Chengdc3befd2016-07-15 12:34:00 -0700367 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700368 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700369
370 Note, the uart runs in a separate thread (pthreads). Users wishing to
371 interact with it will query control for the pty's pathname and connect
372 with there favorite console program. For example:
373 cu -l /dev/pts/22
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 Broch47c43f42011-05-26 15:11:31 -0700383 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700384 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700385 try:
386 fobj.run()
387 except ftdiuart.FuartError as e:
388 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
389
Todd Broch47c43f42011-05-26 15:11:31 -0700390 self._logger.info("%s" % fobj.get_pty())
391 return fobj
392
Simran Basie750a342013-03-12 13:45:26 -0700393 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700394 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700395 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700396 logging.debug('UART INTERFACE: %s', interface)
397 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700398
Kevin Chengdc3befd2016-07-15 12:34:00 -0700399 def _init_ftdi_gpiouart(self, vendor, product, serialname,
400 interface):
Todd Broch888da782011-10-07 14:29:09 -0700401 """Initialize special gpio + uart interface and open for use
402
403 Note, the uart runs in a separate thread (pthreads). Users wishing to
404 interact with it will query control for the pty's pathname and connect
405 with there favorite console program. For example:
406 cu -l /dev/pts/22
407
408 Args:
409 interface: interface number of FTDI device to use
410
411 Returns:
412 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700413
414 Raises:
415 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700416 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700417 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700418 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700419 try:
420 fuart.run()
421 except ftdiuart.FuartError as e:
422 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
423
Todd Broch888da782011-10-07 14:29:09 -0700424 self._logger.info("uart pty: %s" % fuart.get_pty())
425 return fgpio, fuart
426
Kevin Chengdc3befd2016-07-15 12:34:00 -0700427 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800428 """Initialize EC-3PO console interpreter interface.
429
430 Args:
431 interface: A dictionary representing the interface.
432
433 Returns:
434 An EC3PO object representing the EC-3PO interface or None if there's no
435 interface for the USB PD UART.
436 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700437 vid = vendor
438 pid = product
Aseda Aboagyea4922212015-11-20 15:19:08 -0800439 # The current PID might be incremented if there are multiple FTDI.
440 # Therefore, try rewinding the PID back one if we don't find the base PID in
441 # the SERVO_ID_DEFAULTS
442 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
443 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
444 pid -= 1
445 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
446
Nick Sanders97bc4462016-01-04 15:37:31 -0800447 if 'raw_pty' in interface:
448 # We have specified an explicit target for this ec3po.
449 raw_uart_name = interface['raw_pty']
450 raw_ec_uart = self.get(raw_uart_name)
451
Aseda Aboagyea4922212015-11-20 15:19:08 -0800452 # Servo V2 / V3 should have the interface indicies in the same spot.
Nick Sanders97bc4462016-01-04 15:37:31 -0800453 elif ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
Aseda Aboagyea4922212015-11-20 15:19:08 -0800454 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
455 # Determine if it's a PD interface or just main EC console.
456 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
457 try:
458 # Obtain the raw EC UART PTY and create the EC-3PO interface.
459 raw_ec_uart = self.get('raw_usbpd_uart_pty')
460 except NameError:
461 # This overlay doesn't have a USB PD MCU, so skip init.
462 self._logger.info('No PD MCU UART.')
463 return None
464 except AttributeError:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700465 # This overlay has no get method for the interface so skip init. For
466 # servo v2, it's common for interfaces to be overridden such as
467 # reusing JTAG pins for the PD MCU UART instead. Therefore, print an
468 # error message indicating that the interface might be set
469 # incorrectly.
470 if (vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS:
471 self._logger.warn('No interface for PD MCU UART.')
472 self._logger.warn('Usually, this happens because the interface is '
473 'set incorrectly. If you\'re overriding an '
474 'existing interface, be sure to update the '
475 'interface lists for your board at the end of '
476 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800477 return None
478
479 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
480 raw_ec_uart = self.get('raw_ec_uart_pty')
481
482 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
483 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
484 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
485 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
486 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
487 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
488 raw_ec_uart = self.get('raw_ec_uart_pty')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800489 else:
490 raise ServodError(('Unexpected EC-3PO interface!'
491 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
492
493 return ec3po_interface.EC3PO(raw_ec_uart)
494
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800495 def _camel_case(self, string):
496 output = ''
497 for s in string.split('_'):
498 if output:
499 output += s.capitalize()
500 else:
501 output = s
502 return output
503
Todd Broche505b8d2011-03-21 18:19:54 -0700504 def _get_param_drv(self, control_name, is_get=True):
505 """Get access to driver for a given control.
506
507 Note, some controls have different parameter dictionaries for 'getting' the
508 control's value versus 'setting' it. Boolean is_get distinguishes which is
509 being requested.
510
511 Args:
512 control_name: string name of control
513 is_get: boolean to determine
514
515 Returns:
516 tuple (param, drv) where:
517 param: param dictionary for control
518 drv: instance object of driver for particular control
519
520 Raises:
521 ServodError: Error occurred while examining params dict
522 """
523 self._logger.debug("")
524 # if already setup just return tuple from driver dict
525 if control_name in self._drv_dict:
526 if is_get and ('get' in self._drv_dict[control_name]):
527 return self._drv_dict[control_name]['get']
528 if not is_get and ('set' in self._drv_dict[control_name]):
529 return self._drv_dict[control_name]['set']
530
531 params = self._syscfg.lookup_control_params(control_name, is_get)
532 if 'drv' not in params:
533 self._logger.error("Unable to determine driver for %s" % control_name)
534 raise ServodError("'drv' key not found in params dict")
535 if 'interface' not in params:
536 self._logger.error("Unable to determine interface for %s" %
537 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700538 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700539
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800540 interface_id = params.get(
541 '%s_interface' % self._version, params['interface'])
542 if interface_id == 'servo':
543 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700544 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800545 index = int(interface_id) - 1
546 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700547
Todd Broche505b8d2011-03-21 18:19:54 -0700548 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
549 drv_pkg = imp.load_module('drv',
550 *imp.find_module('drv', servo_pkg.__path__))
551 drv_name = params['drv']
552 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800553 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700554 drv = drv_class(interface, params)
555 if control_name not in self._drv_dict:
556 self._drv_dict[control_name] = {}
557 if is_get:
558 self._drv_dict[control_name]['get'] = (params, drv)
559 else:
560 self._drv_dict[control_name]['set'] = (params, drv)
561 return (params, drv)
562
563 def doc_all(self):
564 """Return all documenation for controls.
565
566 Returns:
567 string of <doc> text in config file (xml) and the params dictionary for
568 all controls.
569
570 For example:
571 warm_reset :: Reset the device warmly
572 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
573 """
574 return self._syscfg.display_config()
575
576 def doc(self, name):
577 """Retreive doc string in system config file for given control name.
578
579 Args:
580 name: name string of control to get doc string
581
582 Returns:
583 doc string of name
584
585 Raises:
586 NameError: if fails to locate control
587 """
588 self._logger.debug("name(%s)" % (name))
589 if self._syscfg.is_control(name):
590 return self._syscfg.get_control_docstring(name)
591 else:
592 raise NameError("No control %s" %name)
593
Fang Deng90377712013-06-03 15:51:48 -0700594 def _switch_usbkey(self, mux_direction):
595 """Connect USB flash stick to either servo or DUT.
596
597 This function switches 'usb_mux_sel1' to provide electrical
598 connection between the USB port J3 and either servo or DUT side.
599
600 Switching the usb mux is accompanied by powercycling
601 of the USB stick, because it sometimes gets wedged if the mux
602 is switched while the stick power is on.
603
604 Args:
605 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
606 """
607 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
608 time.sleep(self._USB_POWEROFF_DELAY)
609 self.set(self._USB_J3, mux_direction)
610 time.sleep(self._USB_POWEROFF_DELAY)
611 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
612 if mux_direction == self._USB_J3_TO_SERVO:
613 time.sleep(self._USB_DETECTION_DELAY)
614
Simran Basia9f41032012-05-11 14:21:58 -0700615 def _get_usb_port_set(self):
616 """Gets a set of USB disks currently connected to the system
617
618 Returns:
619 A set of USB disk paths.
620 """
621 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
622 return set(["/dev/" + dev for dev in usb_set])
623
Kevin Chengc49494e2016-07-25 12:13:38 -0700624 def _block_other_servod_usb_probe(self):
625 """Block other servod processes by locking a file.
626
627 To enable multiple servods processes to safely probe_host_usb_dev, we use
628 a given lock file to signal other servod processes that we're probing
629 for a usb device.
630
631 If the lock file exists, we open it and try to lock it.
632 - If another servod processes has locked it already, we'll sleep a random
633 amount of time and try again, we'll keep doing that until
634 _MAX_USB_LOCK_WAIT amount of time has passed.
635
636 - If we're able to lock the file, we'll return the file descriptor for the
637 _unblock_other_servod_usb_probe() method to unlock and close the file
638 descriptor.
639
640 This blocking behavior is only enabled if the lock file exists, if it
641 doesn't, then we pretend the block was successful.
642
643 Returns:
644 A tuple of (lock_file_descriptor, lock_succeeded).
645 - lock_file_descriptor is the file descriptor of the open lock file.
646 We'll keep it open until we're done probing for the usb device.
647 - lock_succeeded is a boolean to enable us to proceed probing for a
648 device if the lock file does not exist. We need to be able to tell
649 the difference between failing to lock a file and no lock file existing.
650 """
651 if os.path.exists(self._USB_LOCK_FILE):
652 start_time = datetime.datetime.now()
653 while True:
654 try:
655 lock_file = open(self._USB_LOCK_FILE)
656 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
657 return lock_file, True
658 except IOError:
659 lock_file.close()
660 current_time = datetime.datetime.now()
661 current_wait_time = (current_time - start_time).total_seconds()
662 if current_wait_time > self._MAX_USB_LOCK_WAIT:
663 return None, False
664 # Sleep random amount.
665 sleep_time = time.sleep(random.random())
666 return None, True
667
668 def _unblock_other_servod_usb_probe(self, lock_file):
669 """Unblock other servod processes from probing usb devices.
670
671 Args:
672 lock_file: File descriptor of lock file to unlock and close.
673 """
674 if lock_file:
675 fcntl.flock(lock_file, fcntl.LOCK_UN)
676 lock_file.close()
677
678 def probe_host_usb_dev(self):
Simran Basia9f41032012-05-11 14:21:58 -0700679 """Probe the USB disk device plugged in the servo from the host side.
680
681 Method can fail by:
682 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700683 another servo unless _USB_LOCK_FILE exists on the servo host. If that
684 file exists, then it is safe to probe for usb devices among multiple
685 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700686 2) Finding multiple /dev/sdX and returning None.
687
688 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700689 USB disk path if one and only one USB disk path is found, otherwise an
690 empty string.
Simran Basia9f41032012-05-11 14:21:58 -0700691 """
Kevin Chengc49494e2016-07-25 12:13:38 -0700692 lock_file, block_success = self._block_other_servod_usb_probe()
693 if not block_success:
694 return ''
695
Fang Deng90377712013-06-03 15:51:48 -0700696 original_value = self.get(self._USB_J3)
697 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700698 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700699 if (original_usb_power == self._USB_J3_PWR_ON and
700 original_value != self._USB_J3_TO_DUT):
701 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700702 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700703
Fang Deng90377712013-06-03 15:51:48 -0700704 # Make the host able to see the USB disk.
705 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700706 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700707
Simran Basia9f41032012-05-11 14:21:58 -0700708 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700709 if original_value != self._USB_J3_TO_SERVO:
710 self._switch_usbkey(original_value)
711 if original_usb_power != self._USB_J3_PWR_ON:
712 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
713 time.sleep(self._USB_POWEROFF_DELAY)
714
Kevin Chengc49494e2016-07-25 12:13:38 -0700715 self._unblock_other_servod_usb_probe(lock_file)
716
Simran Basia9f41032012-05-11 14:21:58 -0700717 # Subtract the two sets to find the usb device.
718 diff_set = has_usb_set - no_usb_set
719 if len(diff_set) == 1:
720 return diff_set.pop()
721 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700722 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700723
724 def download_image_to_usb(self, image_path):
725 """Download image and save to the USB device found by probe_host_usb_dev.
726 If the image_path is a URL, it will download this url to the USB path;
727 otherwise it will simply copy the image_path's contents to the USB path.
728
729 Args:
730 image_path: path or url to the recovery image.
731
732 Returns:
733 True|False: True if process completed successfully, False if error
734 occurred.
735 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
736 comment at the end of set().
737 """
738 self._logger.debug("image_path(%s)" % image_path)
739 self._logger.debug("Detecting USB stick device...")
Kevin Chengc49494e2016-07-25 12:13:38 -0700740 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700741 if not usb_dev:
742 self._logger.error("No usb device connected to servo")
743 return False
744
Kevin Cheng9071ed92016-06-21 14:37:54 -0700745 # Let's check if we downloaded this last time and if so assume the image is
746 # still on the usb device and return True.
747 if self._image_path == image_path:
748 self._logger.debug("Image already on USB device, skipping transfer")
749 return True
750
Simran Basia9f41032012-05-11 14:21:58 -0700751 try:
752 if image_path.startswith(self._HTTP_PREFIX):
753 self._logger.debug("Image path is a URL, downloading image")
754 urllib.urlretrieve(image_path, usb_dev)
755 else:
756 shutil.copyfile(image_path, usb_dev)
757 except IOError as e:
Victor Dodonb7cddb82016-04-28 17:00:24 -0700758 self._logger.error("Failed to transfer image to USB device: %s ( %s ) ",
Simran Basia9f41032012-05-11 14:21:58 -0700759 e.strerror, e.errno)
760 return False
761 except urllib.ContentTooShortError:
762 self._logger.error("Failed to download URL: %s to USB device: %s",
763 image_path, usb_dev)
764 return False
765 except BaseException as e:
766 self._logger.error("Unexpected exception downloading %s to %s: %s",
767 image_path, usb_dev, str(e))
768 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800769 finally:
770 # We just plastered the partition table for a block device.
771 # Pass or fail, we mustn't go without telling the kernel about
772 # the change, or it will punish us with sporadic, hard-to-debug
773 # failures.
774 subprocess.call(["sync"])
775 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700776 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700777 return True
778
779 def make_image_noninteractive(self):
780 """Makes the recovery image noninteractive.
781
782 A noninteractive image will reboot automatically after installation
783 instead of waiting for the USB device to be removed to initiate a system
784 reboot.
785
786 Mounts partition 1 of the image stored on usb_dev and creates a file
787 called "non_interactive" so that the image will become noninteractive.
788
789 Returns:
790 True|False: True if process completed successfully, False if error
791 occurred.
792 """
793 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700794 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700795 if not usb_dev:
796 self._logger.error("No usb device connected to servo")
797 return False
798 # Create TempDirectory
799 tmpdir = tempfile.mkdtemp()
800 if tmpdir:
801 # Mount drive to tmpdir.
802 partition_1 = "%s1" % usb_dev
803 rc = subprocess.call(["mount", partition_1, tmpdir])
804 if rc == 0:
805 # Create file 'non_interactive'
806 non_interactive_file = os.path.join(tmpdir, "non_interactive")
807 try:
808 open(non_interactive_file, "w").close()
809 except IOError as e:
810 self._logger.error("Failed to create file %s : %s ( %d )",
811 non_interactive_file, e.strerror, e.errno)
812 result = False
813 except BaseException as e:
814 self._logger.error("Unexpected Exception creating file %s : %s",
815 non_interactive_file, str(e))
816 result = False
817 # Unmount drive regardless if file creation worked or not.
818 rc = subprocess.call(["umount", partition_1])
819 if rc != 0:
820 self._logger.error("Failed to unmount USB Device")
821 result = False
822 else:
823 self._logger.error("Failed to mount USB Device")
824 result = False
825
826 # Delete tmpdir. May throw exception if 'umount' failed.
827 try:
828 os.rmdir(tmpdir)
829 except OSError as e:
830 self._logger.error("Failed to remove temp directory %s : %s",
831 tmpdir, str(e))
832 return False
833 except BaseException as e:
834 self._logger.error("Unexpected Exception removing tempdir %s : %s",
835 tmpdir, str(e))
836 return False
837 else:
838 self._logger.error("Failed to create temp directory.")
839 return False
840 return result
841
Todd Broch352b4b22013-03-22 09:48:40 -0700842 def set_get_all(self, cmds):
843 """Set &| get one or more control values.
844
845 Args:
846 cmds: list of control[:value] to get or set.
847
848 Returns:
849 rv: list of responses from calling get or set methods.
850 """
851 rv = []
852 for cmd in cmds:
853 if ':' in cmd:
854 (control, value) = cmd.split(':')
855 rv.append(self.set(control, value))
856 else:
857 rv.append(self.get(cmd))
858 return rv
859
Todd Broche505b8d2011-03-21 18:19:54 -0700860 def get(self, name):
861 """Get control value.
862
863 Args:
864 name: name string of control
865
866 Returns:
867 Response from calling drv get method. Value is reformatted based on
868 control's dictionary parameters
869
870 Raises:
871 HwDriverError: Error occurred while using drv
872 """
873 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700874 if name == 'serialname':
875 if self._serialname:
876 return self._serialname
877 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700878 (param, drv) = self._get_param_drv(name)
879 try:
880 val = drv.get()
881 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800882 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700883 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700884 except AttributeError, error:
885 self._logger.error("Getting %s: %s" % (name, error))
886 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800887 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700888 self._logger.error("Getting %s" % (name))
889 raise
Todd Brochd6061672012-05-11 15:52:47 -0700890
Todd Broche505b8d2011-03-21 18:19:54 -0700891 def get_all(self, verbose):
892 """Get all controls values.
893
894 Args:
895 verbose: Boolean on whether to return doc info as well
896
897 Returns:
898 string creating from trying to get all values of all controls. In case of
899 error attempting access to control, response is 'ERR'.
900 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800901 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700902 for name in self._syscfg.syscfg_dict['control']:
903 self._logger.debug("name = %s" %name)
904 try:
905 value = self.get(name)
906 except Exception:
907 value = "ERR"
908 pass
909 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800910 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700911 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800912 rsp.append("%s:%s" % (name, value))
913 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700914
915 def set(self, name, wr_val_str):
916 """Set control.
917
918 Args:
919 name: name string of control
920 wr_val_str: value string to write. Can be integer, float or a
921 alpha-numerical that is mapped to a integer or float.
922
923 Raises:
924 HwDriverError: Error occurred while using driver
925 """
926 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
927 (params, drv) = self._get_param_drv(name, False)
928 wr_val = self._syscfg.resolve_val(params, wr_val_str)
929 try:
930 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800931 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700932 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
933 raise
934 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
935 # & client I still have to return something to appease the
936 # marshall/unmarshall
937 return True
938
Todd Brochd6061672012-05-11 15:52:47 -0700939 def hwinit(self, verbose=False):
940 """Initialize all controls.
941
942 These values are part of the system config XML files of the form
943 init=<value>. This command should be used by clients wishing to return the
944 servo and DUT its connected to a known good/safe state.
945
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800946 Note that initialization errors are ignored (as in some cases they could
947 be caused by DUT firmware deficiencies). This might need to be fine tuned
948 later.
949
Todd Brochd6061672012-05-11 15:52:47 -0700950 Args:
951 verbose: boolean, if True prints info about control initialized.
952 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800953
954 Returns:
955 This function is called across RPC and as such is expected to return
956 something unless transferring 'none' across is allowed. Hence adding a
957 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700958 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800959 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800960 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700961 # Workaround for bug chrome-os-partner:42349. Without this check, the
962 # gpio will briefly pulse low if we set it from high to high.
963 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700964 self.set(control_name, value)
965 if verbose:
966 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800967 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800968 self._logger.error("Problem initializing %s -> %s :: %s",
969 control_name, value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -0800970
971 # Init keyboard after all the intefaces are up.
972 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800973 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800974
Todd Broche505b8d2011-03-21 18:19:54 -0700975 def echo(self, echo):
976 """Dummy echo function for testing/examples.
977
978 Args:
979 echo: string to echo back to client
980 """
981 self._logger.debug("echo(%s)" % (echo))
982 return "ECH0ING: %s" % (echo)
983
J. Richard Barnettee2820552013-03-14 16:13:46 -0700984 def get_board(self):
985 """Return the board specified at startup, if any."""
986 return self._board
987
Simran Basia23c1392013-08-06 14:59:10 -0700988 def get_version(self):
989 """Get servo board version."""
990 return self._version
991
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800992 def power_long_press(self):
993 """Simulate a long power button press."""
994 # After a long power press, the EC may ignore the next power
995 # button press (at least on Alex). To guarantee that this
996 # won't happen, we need to allow the EC one second to
997 # collect itself.
998 self._keyboard.power_long_press()
999 return True
1000
1001 def power_normal_press(self):
1002 """Simulate a normal power button press."""
1003 self._keyboard.power_normal_press()
1004 return True
1005
1006 def power_short_press(self):
1007 """Simulate a short power button press."""
1008 self._keyboard.power_short_press()
1009 return True
1010
1011 def power_key(self, secs=''):
1012 """Simulate a power button press.
1013
1014 Args:
1015 secs: Time in seconds to simulate the keypress.
1016 """
1017 self._keyboard.power_key(secs)
1018 return True
1019
1020 def ctrl_d(self, press_secs=''):
1021 """Simulate Ctrl-d simultaneous button presses."""
1022 self._keyboard.ctrl_d(press_secs)
1023 return True
1024
Victor Dodone539cea2016-03-29 18:50:17 -07001025 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001026 """Simulate Ctrl-u simultaneous button presses."""
Victor Dodone539cea2016-03-29 18:50:17 -07001027 self._keyboard.ctrl_u(press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001028 return True
1029
1030 def ctrl_enter(self, press_secs=''):
1031 """Simulate Ctrl-enter simultaneous button presses."""
1032 self._keyboard.ctrl_enter(press_secs)
1033 return True
1034
1035 def d_key(self, press_secs=''):
1036 """Simulate Enter key button press."""
1037 self._keyboard.d_key(press_secs)
1038 return True
1039
1040 def ctrl_key(self, press_secs=''):
1041 """Simulate Enter key button press."""
1042 self._keyboard.ctrl_key(press_secs)
1043 return True
1044
1045 def enter_key(self, press_secs=''):
1046 """Simulate Enter key button press."""
1047 self._keyboard.enter_key(press_secs)
1048 return True
1049
1050 def refresh_key(self, press_secs=''):
1051 """Simulate Refresh key (F3) button press."""
1052 self._keyboard.refresh_key(press_secs)
1053 return True
1054
1055 def ctrl_refresh_key(self, press_secs=''):
1056 """Simulate Ctrl and Refresh (F3) simultaneous press.
1057
1058 This key combination is an alternative of Space key.
1059 """
1060 self._keyboard.ctrl_refresh_key(press_secs)
1061 return True
1062
1063 def imaginary_key(self, press_secs=''):
1064 """Simulate imaginary key button press.
1065
1066 Maps to a key that doesn't physically exist.
1067 """
1068 self._keyboard.imaginary_key(press_secs)
1069 return True
1070
Todd Brochdbb09982011-10-02 07:14:26 -07001071
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001072 def sysrq_x(self, press_secs=''):
1073 """Simulate Alt VolumeUp X simultaneous press.
1074
1075 This key combination is the kernel system request (sysrq) x.
1076 """
1077 self._keyboard.sysrq_x(press_secs)
1078 return True
1079
1080
Todd Broche505b8d2011-03-21 18:19:54 -07001081def test():
1082 """Integration testing.
1083
1084 TODO(tbroch) Enhance integration test and add unittest (see mox)
1085 """
1086 logging.basicConfig(level=logging.DEBUG,
1087 format="%(asctime)s - %(name)s - " +
1088 "%(levelname)s - %(message)s")
1089 # configure server & listen
1090 servod_obj = Servod(1)
1091 # 4 == number of interfaces on a FT4232H device
1092 for i in xrange(4):
1093 if i == 1:
1094 # its an i2c interface ... see __init__ for details and TODO to make
1095 # this configureable
1096 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1097 else:
1098 # its a gpio interface
1099 servod_obj._interface_list[i].wr_rd(0)
1100
1101 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
1102 allow_none=True)
1103 server.register_introspection_functions()
1104 server.register_multicall_functions()
1105 server.register_instance(servod_obj)
1106 logging.info("Listening on localhost port 9999")
1107 server.serve_forever()
1108
1109if __name__ == "__main__":
1110 test()
1111
1112 # simple client transaction would look like
1113 """
1114 remote_uri = 'http://localhost:9999'
1115 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
1116 send_str = "Hello_there"
1117 print "Sent " + send_str + ", Recv " + client.echo(send_str)
1118 """