blob: 76007ec48b3dfa9762aba203c06d5010461a6596 [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
Nick Sanders97bc4462016-01-04 15:37:31 -080030import stm32gpio
31import stm32i2c
32import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070033
Aseda Aboagyea4922212015-11-20 15:19:08 -080034
Todd Broche505b8d2011-03-21 18:19:54 -070035MAX_I2C_CLOCK_HZ = 100000
36
Todd Brochdbb09982011-10-02 07:14:26 -070037
Todd Broche505b8d2011-03-21 18:19:54 -070038class ServodError(Exception):
39 """Exception class for servod."""
40
41class Servod(object):
42 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070043 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070044 _USB_POWEROFF_DELAY = 2
Simran Basia9f41032012-05-11 14:21:58 -070045 _HTTP_PREFIX = "http://"
Fang Deng90377712013-06-03 15:51:48 -070046 _USB_J3 = "usb_mux_sel1"
47 _USB_J3_TO_SERVO = "servo_sees_usbkey"
48 _USB_J3_TO_DUT = "dut_sees_usbkey"
49 _USB_J3_PWR = "prtctl4_pwren"
50 _USB_J3_PWR_ON = "on"
51 _USB_J3_PWR_OFF = "off"
Simran Basia9f41032012-05-11 14:21:58 -070052
J. Richard Barnettee2820552013-03-14 16:13:46 -070053 def __init__(self, config, vendor, product, serialname=None,
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080054 interfaces=None, board="", version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -070055 """Servod constructor.
56
57 Args:
58 config: instance of SystemConfig containing all controls for
59 particular Servod invocation
60 vendor: usb vendor id of FTDI device
61 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -070062 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -070063 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -070064 version: String. Servo board version. Examples: servo_v1, servo_v2,
65 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080066 usbkm232: String. Optional. Path to USB-KM232 device which allow for
67 sending keyboard commands to DUTs that do not have built in
Danny Chan662b6022015-11-04 17:34:53 -080068 keyboards. Used in FAFT tests. Use 'atmega' for on board AVR MCU.
69 e.g. '/dev/ttyUSB0' or 'atmega'
Todd Brochdbb09982011-10-02 07:14:26 -070070
71 Raises:
72 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -070073 """
74 self._logger = logging.getLogger("Servod")
75 self._logger.debug("")
76 self._vendor = vendor
77 self._product = product
Todd Brochad034442011-05-25 15:05:29 -070078 self._serialname = serialname
Todd Broche505b8d2011-03-21 18:19:54 -070079 self._syscfg = config
80 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
81 # interfaces are mapped to
82 self._interface_list = []
83 # Dict of Dict to map control name, function name to to tuple (params, drv)
84 # Ex) _drv_dict[name]['get'] = (params, drv)
85 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -070086 self._board = board
Simran Basia23c1392013-08-06 14:59:10 -070087 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080088 self._usbkm232 = usbkm232
Todd Brochdbb09982011-10-02 07:14:26 -070089 # Note, interface i is (i - 1) in list
90 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -070091 try:
92 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
93 except KeyError:
94 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Todd Brochdbb09982011-10-02 07:14:26 -070095
Simran Basia9ad25e2013-04-23 11:57:00 -070096 for i, interface in enumerate(interfaces):
97 is_ftdi_interface = False
98 if type(interface) is dict:
99 name = interface['name']
Aseda Aboagyea4922212015-11-20 15:19:08 -0800100 # Store interface index for those that care about it.
101 interface['index'] = i
Simran Basia9ad25e2013-04-23 11:57:00 -0700102 elif type(interface) is str:
Simran Basia9ad25e2013-04-23 11:57:00 -0700103 name = interface
Aseda Aboagyea4922212015-11-20 15:19:08 -0800104 # It's a FTDI related interface.
Simran Basia9ad25e2013-04-23 11:57:00 -0700105 interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
106 is_ftdi_interface = True
107 else:
108 raise ServodError("Illegal interface type %s" % type(interface))
109
Todd Broch8a77a992012-01-27 09:46:08 -0800110 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Simran Basia9ad25e2013-04-23 11:57:00 -0700111 if is_ftdi_interface and i and \
112 ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0):
Todd Broch8a77a992012-01-27 09:46:08 -0800113 self._product += 1
114 self._logger.info("Changing to next FTDI part @ pid = 0x%04x",
115 self._product)
116
Simran Basia9ad25e2013-04-23 11:57:00 -0700117 self._logger.info("Initializing interface %d to %s", i + 1, name)
Todd Brochdbb09982011-10-02 07:14:26 -0700118 try:
119 func = getattr(self, '_init_%s' % name)
120 except AttributeError:
121 raise ServodError("Unable to locate init for interface %s" % name)
Simran Basia9ad25e2013-04-23 11:57:00 -0700122 result = func(interface)
Todd Broch888da782011-10-07 14:29:09 -0700123 if isinstance(result, tuple):
124 self._interface_list.extend(result)
125 else:
126 self._interface_list.append(result)
Todd Broche505b8d2011-03-21 18:19:54 -0700127
Danny Chan662b6022015-11-04 17:34:53 -0800128
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800129 def _init_keyboard_handler(self, servo, board=''):
130 """Initialize the correct keyboard handler for board.
131
132 @param servo: servo object.
133 @param board: string, board name.
134
135 """
136 if board == 'parrot':
137 return keyboard_handlers.ParrotHandler(servo)
138 elif board == 'stout':
139 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800140 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800141 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy',
Jason Simmonse5cccd12015-08-25 16:05:25 -0700142 'sumo', 'tidus', 'tricky', 'veyron_mickey', 'veyron_rialto',
143 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800144 if self._usbkm232 is None:
Tom Wai-Hong Tam4c7d6472016-03-08 06:55:50 +0800145 logging.info("No device path specified for usbkm232 handler. Use "
146 "the servo atmega chip to handle.")
147 self._usbkm232 = 'atmega'
Danny Chan662b6022015-11-04 17:34:53 -0800148 if self._usbkm232 == 'atmega':
149 # Use servo onboard keyboard emulator.
Nick Sanders78423782015-11-09 14:28:19 -0800150 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800151 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800152 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800153 self._usbkm232 = self.get('atmega_pty')
154 self.set('atmega_baudrate', '9600')
155 self.set('atmega_bits', 'eight')
156 self.set('atmega_parity', 'none')
157 self.set('atmega_sbits', 'one')
158 self.set('usb_mux_sel4', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800159 self.set('usb_mux_oe4', 'on')
Nick Sanders78423782015-11-09 14:28:19 -0800160 # Allow atmega bootup time.
161 time.sleep(1.0)
Danny Chan662b6022015-11-04 17:34:53 -0800162 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800163 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
164 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800165 # The following boards don't use Chrome EC.
166 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
167 return keyboard_handlers.MatrixKeyboardHandler(servo)
168 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800169
Todd Broch3ec8df02012-11-20 10:53:03 -0800170 def __del__(self):
171 """Servod deconstructor."""
172 for interface in self._interface_list:
173 del(interface)
174
Todd Brochb3048492012-01-15 21:52:41 -0800175 def _init_dummy(self, interface):
176 """Initialize dummy interface.
177
178 Dummy interface is just a mechanism to reserve that interface for non servod
179 interaction. Typically the interface will be managed by external
180 third-party tools like openOCD or urjtag for JTAG or flashrom for SPI
181 interfaces.
182
183 TODO(tbroch): Investigate merits of incorporating these third-party
184 interfaces into servod or creating a communication channel between them
185
186 Returns: None
187 """
188 return None
189
Simran Basie750a342013-03-12 13:45:26 -0700190 def _init_ftdi_gpio(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700191 """Initialize gpio driver interface and open for use.
192
193 Args:
194 interface: interface number of FTDI device to use.
195
196 Returns:
197 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700198
199 Raises:
200 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700201 """
Todd Brochad034442011-05-25 15:05:29 -0700202 fobj = ftdigpio.Fgpio(self._vendor, self._product, interface,
203 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700204 try:
205 fobj.open()
206 except ftdigpio.FgpioError as e:
207 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
208
Todd Broche505b8d2011-03-21 18:19:54 -0700209 return fobj
210
Nick Sanders97bc4462016-01-04 15:37:31 -0800211 def _init_stm32_uart(self, interface):
212 """Initialize stm32 uart interface and open for use
213
214 Note, the uart runs in a separate thread. Users wishing to
215 interact with it will query control for the pty's pathname and connect
216 with their favorite console program. For example:
217 cu -l /dev/pts/22
218
219 Args:
220 interface: dict of interface parameters.
221
222 Returns:
223 Instance object of interface
224
225 Raises:
226 ServodError: Raised on init failure.
227 """
228 self._logger.info("Suart: interface: %s" % interface)
229 sobj = stm32uart.Suart(self._vendor, self._product, interface['interface'])
230
231 try:
232 sobj.run()
233 except stm32uart.SuartError as e:
234 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
235
236 self._logger.info("%s" % sobj.get_pty())
237 return sobj
238
239 def _init_stm32_gpio(self, interface):
240 """Initialize stm32 gpio interface.
241 Args:
242 interface: interface number of stm32 device to use.
243
244 Returns:
245 Instance object of interface
246
247 Raises:
248 SgpioError: Raised on init failure.
249 """
250 self._logger.info("Sgpio: interface: %s" % interface)
251 return stm32gpio.Sgpio(self._vendor, self._product)
252
253 def _init_stm32_i2c(self, interface):
254 """Initialize stm32 USB to I2C bridge interface and open for use
255
256 Args:
257 interface: USB interface number of stm32 device to use
258
259 Returns:
260 Instance object of interface.
261
262 Raises:
263 Si2cError: Raised on init failure.
264 """
265 self._logger.info("Si2cBus: interface: %s" % interface)
266 return stm32i2c.Si2cBus(self._vendor, self._product, interface['interface'])
267
Aaron.Chuang88eff332014-07-31 08:32:00 +0800268 def _init_bb_adc(self, interface):
269 """Initalize beaglebone ADC interface."""
270 return bbadc.BBadc()
271
Simran Basie750a342013-03-12 13:45:26 -0700272 def _init_bb_gpio(self, interface):
273 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700274 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700275
276 def _init_ftdi_i2c(self, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700277 """Initialize i2c interface and open for use.
278
279 Args:
280 interface: interface number of FTDI device to use
281
282 Returns:
283 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700284
285 Raises:
286 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700287 """
Todd Brochad034442011-05-25 15:05:29 -0700288 fobj = ftdii2c.Fi2c(self._vendor, self._product, interface,
289 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700290 try:
291 fobj.open()
292 except ftdii2c.Fi2cError as e:
293 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
294
Todd Broche505b8d2011-03-21 18:19:54 -0700295 # Set the frequency of operation of the i2c bus.
296 # TODO(tbroch) make configureable
297 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700298
Todd Broche505b8d2011-03-21 18:19:54 -0700299 return fobj
300
Simran Basie750a342013-03-12 13:45:26 -0700301 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
302 def _init_bb_i2c(self, interface):
303 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700304 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700305
Rong Changc6c8c022014-08-11 14:07:11 +0800306 def _init_dev_i2c(self, interface):
307 """Initalize Linux i2c-dev interface."""
308 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
309
Simran Basie750a342013-03-12 13:45:26 -0700310 def _init_ftdi_uart(self, interface):
311 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700312
313 Note, the uart runs in a separate thread (pthreads). Users wishing to
314 interact with it will query control for the pty's pathname and connect
315 with there favorite console program. For example:
316 cu -l /dev/pts/22
317
318 Args:
319 interface: interface number of FTDI device to use
320
321 Returns:
322 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700323
324 Raises:
325 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700326 """
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700327 fobj = ftdiuart.Fuart(self._vendor, self._product, interface,
328 self._serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700329 try:
330 fobj.run()
331 except ftdiuart.FuartError as e:
332 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
333
Todd Broch47c43f42011-05-26 15:11:31 -0700334 self._logger.info("%s" % fobj.get_pty())
335 return fobj
336
Simran Basie750a342013-03-12 13:45:26 -0700337 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
338 def _init_bb_uart(self, interface):
339 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700340 logging.debug('UART INTERFACE: %s', interface)
341 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700342
343 def _init_ftdi_gpiouart(self, interface):
Todd Broch888da782011-10-07 14:29:09 -0700344 """Initialize special gpio + uart interface and open for use
345
346 Note, the uart runs in a separate thread (pthreads). Users wishing to
347 interact with it will query control for the pty's pathname and connect
348 with there favorite console program. For example:
349 cu -l /dev/pts/22
350
351 Args:
352 interface: interface number of FTDI device to use
353
354 Returns:
355 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700356
357 Raises:
358 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700359 """
Simran Basie750a342013-03-12 13:45:26 -0700360 fgpio = self._init_ftdi_gpio(interface)
Jeremy Thorpe9e110062012-10-25 10:40:00 -0700361 fuart = ftdiuart.Fuart(self._vendor, self._product, interface,
362 self._serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700363 try:
364 fuart.run()
365 except ftdiuart.FuartError as e:
366 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
367
Todd Broch888da782011-10-07 14:29:09 -0700368 self._logger.info("uart pty: %s" % fuart.get_pty())
369 return fgpio, fuart
370
Aseda Aboagyea4922212015-11-20 15:19:08 -0800371 def _init_ec3po_uart(self, interface):
372 """Initialize EC-3PO console interpreter interface.
373
374 Args:
375 interface: A dictionary representing the interface.
376
377 Returns:
378 An EC3PO object representing the EC-3PO interface or None if there's no
379 interface for the USB PD UART.
380 """
381 vid = self._vendor
382 pid = self._product
383 # The current PID might be incremented if there are multiple FTDI.
384 # Therefore, try rewinding the PID back one if we don't find the base PID in
385 # the SERVO_ID_DEFAULTS
386 if (vid, pid) not in servo_interfaces.SERVO_ID_DEFAULTS:
387 self._logger.debug('VID:PID pair not found. Rewinding PID back one...')
388 pid -= 1
389 self._logger.debug('vid:0x%04x, pid:0x%04x', vid, pid)
390
Nick Sanders97bc4462016-01-04 15:37:31 -0800391 if 'raw_pty' in interface:
392 # We have specified an explicit target for this ec3po.
393 raw_uart_name = interface['raw_pty']
394 raw_ec_uart = self.get(raw_uart_name)
395
Aseda Aboagyea4922212015-11-20 15:19:08 -0800396 # Servo V2 / V3 should have the interface indicies in the same spot.
Nick Sanders97bc4462016-01-04 15:37:31 -0800397 elif ((vid, pid) in servo_interfaces.SERVO_V2_DEFAULTS or
Aseda Aboagyea4922212015-11-20 15:19:08 -0800398 (vid, pid) in servo_interfaces.SERVO_V3_DEFAULTS):
399 # Determine if it's a PD interface or just main EC console.
400 if interface['index'] == servo_interfaces.EC3PO_USBPD_INTERFACE_NUM:
401 try:
402 # Obtain the raw EC UART PTY and create the EC-3PO interface.
403 raw_ec_uart = self.get('raw_usbpd_uart_pty')
404 except NameError:
405 # This overlay doesn't have a USB PD MCU, so skip init.
406 self._logger.info('No PD MCU UART.')
407 return None
408 except AttributeError:
409 # This overlay has no get method for the interface so skip init.
410 self._logger.warn('No interface for PD MCU UART.')
Aseda Aboagyec24a3882016-03-15 12:37:56 -0700411 self._logger.warn('Usually, this happens because the interface is set'
412 ' incorrectly. If you\'re overriding an existing'
413 ' interface, be sure to update the interface lists'
414 ' for your board at the end of '
415 'servo/servo_interfaces.py')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800416 return None
417
418 elif interface['index'] == servo_interfaces.EC3PO_EC_INTERFACE_NUM:
419 raw_ec_uart = self.get('raw_ec_uart_pty')
420
421 # Servo V3, miniservo, Toad, Reston, Fruitpie, or Plankton
422 elif ((vid, pid) in servo_interfaces.MINISERVO_ID_DEFAULTS or
423 (vid, pid) in servo_interfaces.TOAD_ID_DEFAULTS or
424 (vid, pid) in servo_interfaces.RESTON_ID_DEFAULTS or
425 (vid, pid) in servo_interfaces.FRUITPIE_ID_DEFAULTS or
426 (vid, pid) in servo_interfaces.PLANKTON_ID_DEFAULTS):
427 raw_ec_uart = self.get('raw_ec_uart_pty')
Aseda Aboagyea4922212015-11-20 15:19:08 -0800428 else:
429 raise ServodError(('Unexpected EC-3PO interface!'
430 ' (0x%04x:0x%04x) %r') % (vid, pid, interface))
431
432 return ec3po_interface.EC3PO(raw_ec_uart)
433
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800434 def _camel_case(self, string):
435 output = ''
436 for s in string.split('_'):
437 if output:
438 output += s.capitalize()
439 else:
440 output = s
441 return output
442
Todd Broche505b8d2011-03-21 18:19:54 -0700443 def _get_param_drv(self, control_name, is_get=True):
444 """Get access to driver for a given control.
445
446 Note, some controls have different parameter dictionaries for 'getting' the
447 control's value versus 'setting' it. Boolean is_get distinguishes which is
448 being requested.
449
450 Args:
451 control_name: string name of control
452 is_get: boolean to determine
453
454 Returns:
455 tuple (param, drv) where:
456 param: param dictionary for control
457 drv: instance object of driver for particular control
458
459 Raises:
460 ServodError: Error occurred while examining params dict
461 """
462 self._logger.debug("")
463 # if already setup just return tuple from driver dict
464 if control_name in self._drv_dict:
465 if is_get and ('get' in self._drv_dict[control_name]):
466 return self._drv_dict[control_name]['get']
467 if not is_get and ('set' in self._drv_dict[control_name]):
468 return self._drv_dict[control_name]['set']
469
470 params = self._syscfg.lookup_control_params(control_name, is_get)
471 if 'drv' not in params:
472 self._logger.error("Unable to determine driver for %s" % control_name)
473 raise ServodError("'drv' key not found in params dict")
474 if 'interface' not in params:
475 self._logger.error("Unable to determine interface for %s" %
476 control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700477 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700478
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800479 interface_id = params.get(
480 '%s_interface' % self._version, params['interface'])
481 if interface_id == 'servo':
482 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700483 else:
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800484 index = int(interface_id) - 1
485 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700486
Todd Broche505b8d2011-03-21 18:19:54 -0700487 servo_pkg = imp.load_module('servo', *imp.find_module('servo'))
488 drv_pkg = imp.load_module('drv',
489 *imp.find_module('drv', servo_pkg.__path__))
490 drv_name = params['drv']
491 drv_module = getattr(drv_pkg, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800492 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700493 drv = drv_class(interface, params)
494 if control_name not in self._drv_dict:
495 self._drv_dict[control_name] = {}
496 if is_get:
497 self._drv_dict[control_name]['get'] = (params, drv)
498 else:
499 self._drv_dict[control_name]['set'] = (params, drv)
500 return (params, drv)
501
502 def doc_all(self):
503 """Return all documenation for controls.
504
505 Returns:
506 string of <doc> text in config file (xml) and the params dictionary for
507 all controls.
508
509 For example:
510 warm_reset :: Reset the device warmly
511 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
512 """
513 return self._syscfg.display_config()
514
515 def doc(self, name):
516 """Retreive doc string in system config file for given control name.
517
518 Args:
519 name: name string of control to get doc string
520
521 Returns:
522 doc string of name
523
524 Raises:
525 NameError: if fails to locate control
526 """
527 self._logger.debug("name(%s)" % (name))
528 if self._syscfg.is_control(name):
529 return self._syscfg.get_control_docstring(name)
530 else:
531 raise NameError("No control %s" %name)
532
Fang Deng90377712013-06-03 15:51:48 -0700533 def _switch_usbkey(self, mux_direction):
534 """Connect USB flash stick to either servo or DUT.
535
536 This function switches 'usb_mux_sel1' to provide electrical
537 connection between the USB port J3 and either servo or DUT side.
538
539 Switching the usb mux is accompanied by powercycling
540 of the USB stick, because it sometimes gets wedged if the mux
541 is switched while the stick power is on.
542
543 Args:
544 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
545 """
546 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
547 time.sleep(self._USB_POWEROFF_DELAY)
548 self.set(self._USB_J3, mux_direction)
549 time.sleep(self._USB_POWEROFF_DELAY)
550 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
551 if mux_direction == self._USB_J3_TO_SERVO:
552 time.sleep(self._USB_DETECTION_DELAY)
553
Simran Basia9f41032012-05-11 14:21:58 -0700554 def _get_usb_port_set(self):
555 """Gets a set of USB disks currently connected to the system
556
557 Returns:
558 A set of USB disk paths.
559 """
560 usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]")
561 return set(["/dev/" + dev for dev in usb_set])
562
563 def _probe_host_usb_dev(self):
564 """Probe the USB disk device plugged in the servo from the host side.
565
566 Method can fail by:
567 1) Having multiple servos connected and returning incorrect /dev/sdX of
568 another servo.
569 2) Finding multiple /dev/sdX and returning None.
570
571 Returns:
572 USB disk path if one and only one USB disk path is found, otherwise None.
573 """
Fang Deng90377712013-06-03 15:51:48 -0700574 original_value = self.get(self._USB_J3)
575 original_usb_power = self.get(self._USB_J3_PWR)
Simran Basia9f41032012-05-11 14:21:58 -0700576 # Make the host unable to see the USB disk.
Fang Deng90377712013-06-03 15:51:48 -0700577 if (original_usb_power == self._USB_J3_PWR_ON and
578 original_value != self._USB_J3_TO_DUT):
579 self._switch_usbkey(self._USB_J3_TO_DUT)
Simran Basia9f41032012-05-11 14:21:58 -0700580 no_usb_set = self._get_usb_port_set()
Simran Basia9f41032012-05-11 14:21:58 -0700581
Fang Deng90377712013-06-03 15:51:48 -0700582 # Make the host able to see the USB disk.
583 self._switch_usbkey(self._USB_J3_TO_SERVO)
Simran Basia9f41032012-05-11 14:21:58 -0700584 has_usb_set = self._get_usb_port_set()
Fang Deng90377712013-06-03 15:51:48 -0700585
Simran Basia9f41032012-05-11 14:21:58 -0700586 # Back to its original value.
Fang Deng90377712013-06-03 15:51:48 -0700587 if original_value != self._USB_J3_TO_SERVO:
588 self._switch_usbkey(original_value)
589 if original_usb_power != self._USB_J3_PWR_ON:
590 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
591 time.sleep(self._USB_POWEROFF_DELAY)
592
Simran Basia9f41032012-05-11 14:21:58 -0700593 # Subtract the two sets to find the usb device.
594 diff_set = has_usb_set - no_usb_set
595 if len(diff_set) == 1:
596 return diff_set.pop()
597 else:
598 return None
599
600 def download_image_to_usb(self, image_path):
601 """Download image and save to the USB device found by probe_host_usb_dev.
602 If the image_path is a URL, it will download this url to the USB path;
603 otherwise it will simply copy the image_path's contents to the USB path.
604
605 Args:
606 image_path: path or url to the recovery image.
607
608 Returns:
609 True|False: True if process completed successfully, False if error
610 occurred.
611 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
612 comment at the end of set().
613 """
614 self._logger.debug("image_path(%s)" % image_path)
615 self._logger.debug("Detecting USB stick device...")
616 usb_dev = self._probe_host_usb_dev()
617 if not usb_dev:
618 self._logger.error("No usb device connected to servo")
619 return False
620
621 try:
622 if image_path.startswith(self._HTTP_PREFIX):
623 self._logger.debug("Image path is a URL, downloading image")
624 urllib.urlretrieve(image_path, usb_dev)
625 else:
626 shutil.copyfile(image_path, usb_dev)
627 except IOError as e:
628 self._logger.error("Failed to transfer image to USB device: %s ( %d ) ",
629 e.strerror, e.errno)
630 return False
631 except urllib.ContentTooShortError:
632 self._logger.error("Failed to download URL: %s to USB device: %s",
633 image_path, usb_dev)
634 return False
635 except BaseException as e:
636 self._logger.error("Unexpected exception downloading %s to %s: %s",
637 image_path, usb_dev, str(e))
638 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800639 finally:
640 # We just plastered the partition table for a block device.
641 # Pass or fail, we mustn't go without telling the kernel about
642 # the change, or it will punish us with sporadic, hard-to-debug
643 # failures.
644 subprocess.call(["sync"])
645 subprocess.call(["blockdev", "--rereadpt", usb_dev])
Simran Basia9f41032012-05-11 14:21:58 -0700646 return True
647
648 def make_image_noninteractive(self):
649 """Makes the recovery image noninteractive.
650
651 A noninteractive image will reboot automatically after installation
652 instead of waiting for the USB device to be removed to initiate a system
653 reboot.
654
655 Mounts partition 1 of the image stored on usb_dev and creates a file
656 called "non_interactive" so that the image will become noninteractive.
657
658 Returns:
659 True|False: True if process completed successfully, False if error
660 occurred.
661 """
662 result = True
663 usb_dev = self._probe_host_usb_dev()
664 if not usb_dev:
665 self._logger.error("No usb device connected to servo")
666 return False
667 # Create TempDirectory
668 tmpdir = tempfile.mkdtemp()
669 if tmpdir:
670 # Mount drive to tmpdir.
671 partition_1 = "%s1" % usb_dev
672 rc = subprocess.call(["mount", partition_1, tmpdir])
673 if rc == 0:
674 # Create file 'non_interactive'
675 non_interactive_file = os.path.join(tmpdir, "non_interactive")
676 try:
677 open(non_interactive_file, "w").close()
678 except IOError as e:
679 self._logger.error("Failed to create file %s : %s ( %d )",
680 non_interactive_file, e.strerror, e.errno)
681 result = False
682 except BaseException as e:
683 self._logger.error("Unexpected Exception creating file %s : %s",
684 non_interactive_file, str(e))
685 result = False
686 # Unmount drive regardless if file creation worked or not.
687 rc = subprocess.call(["umount", partition_1])
688 if rc != 0:
689 self._logger.error("Failed to unmount USB Device")
690 result = False
691 else:
692 self._logger.error("Failed to mount USB Device")
693 result = False
694
695 # Delete tmpdir. May throw exception if 'umount' failed.
696 try:
697 os.rmdir(tmpdir)
698 except OSError as e:
699 self._logger.error("Failed to remove temp directory %s : %s",
700 tmpdir, str(e))
701 return False
702 except BaseException as e:
703 self._logger.error("Unexpected Exception removing tempdir %s : %s",
704 tmpdir, str(e))
705 return False
706 else:
707 self._logger.error("Failed to create temp directory.")
708 return False
709 return result
710
Todd Broch352b4b22013-03-22 09:48:40 -0700711 def set_get_all(self, cmds):
712 """Set &| get one or more control values.
713
714 Args:
715 cmds: list of control[:value] to get or set.
716
717 Returns:
718 rv: list of responses from calling get or set methods.
719 """
720 rv = []
721 for cmd in cmds:
722 if ':' in cmd:
723 (control, value) = cmd.split(':')
724 rv.append(self.set(control, value))
725 else:
726 rv.append(self.get(cmd))
727 return rv
728
Todd Broche505b8d2011-03-21 18:19:54 -0700729 def get(self, name):
730 """Get control value.
731
732 Args:
733 name: name string of control
734
735 Returns:
736 Response from calling drv get method. Value is reformatted based on
737 control's dictionary parameters
738
739 Raises:
740 HwDriverError: Error occurred while using drv
741 """
742 self._logger.debug("name(%s)" % (name))
Vadim Bendeburyc3a83cf2015-03-24 13:07:00 -0700743 if name == 'serialname':
744 if self._serialname:
745 return self._serialname
746 return 'unknown'
Todd Broche505b8d2011-03-21 18:19:54 -0700747 (param, drv) = self._get_param_drv(name)
748 try:
749 val = drv.get()
750 rd_val = self._syscfg.reformat_val(param, val)
Todd Brochb042e7a2011-12-14 17:41:36 -0800751 self._logger.debug("%s = %s" % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700752 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700753 except AttributeError, error:
754 self._logger.error("Getting %s: %s" % (name, error))
755 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800756 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700757 self._logger.error("Getting %s" % (name))
758 raise
Todd Brochd6061672012-05-11 15:52:47 -0700759
Todd Broche505b8d2011-03-21 18:19:54 -0700760 def get_all(self, verbose):
761 """Get all controls values.
762
763 Args:
764 verbose: Boolean on whether to return doc info as well
765
766 Returns:
767 string creating from trying to get all values of all controls. In case of
768 error attempting access to control, response is 'ERR'.
769 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800770 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700771 for name in self._syscfg.syscfg_dict['control']:
772 self._logger.debug("name = %s" %name)
773 try:
774 value = self.get(name)
775 except Exception:
776 value = "ERR"
777 pass
778 if verbose:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800779 rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700780 else:
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800781 rsp.append("%s:%s" % (name, value))
782 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700783
784 def set(self, name, wr_val_str):
785 """Set control.
786
787 Args:
788 name: name string of control
789 wr_val_str: value string to write. Can be integer, float or a
790 alpha-numerical that is mapped to a integer or float.
791
792 Raises:
793 HwDriverError: Error occurred while using driver
794 """
795 self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str))
796 (params, drv) = self._get_param_drv(name, False)
797 wr_val = self._syscfg.resolve_val(params, wr_val_str)
798 try:
799 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +0800800 except HwDriverError:
Todd Broche505b8d2011-03-21 18:19:54 -0700801 self._logger.error("Setting %s -> %s" % (name, wr_val_str))
802 raise
803 # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server
804 # & client I still have to return something to appease the
805 # marshall/unmarshall
806 return True
807
Todd Brochd6061672012-05-11 15:52:47 -0700808 def hwinit(self, verbose=False):
809 """Initialize all controls.
810
811 These values are part of the system config XML files of the form
812 init=<value>. This command should be used by clients wishing to return the
813 servo and DUT its connected to a known good/safe state.
814
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800815 Note that initialization errors are ignored (as in some cases they could
816 be caused by DUT firmware deficiencies). This might need to be fine tuned
817 later.
818
Todd Brochd6061672012-05-11 15:52:47 -0700819 Args:
820 verbose: boolean, if True prints info about control initialized.
821 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800822
823 Returns:
824 This function is called across RPC and as such is expected to return
825 something unless transferring 'none' across is allowed. Hence adding a
826 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700827 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800828 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800829 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700830 # Workaround for bug chrome-os-partner:42349. Without this check, the
831 # gpio will briefly pulse low if we set it from high to high.
832 if self.get(control_name) != value:
833 self.set(control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -0800834 except Exception as e:
Todd Broch3ec8df02012-11-20 10:53:03 -0800835 self._logger.error("Problem initializing %s -> %s :: %s",
836 control_name, value, str(e))
Todd Brochd6061672012-05-11 15:52:47 -0700837 if verbose:
838 self._logger.info('Initialized %s to %s', control_name, value)
Nick Sandersbc836282015-12-08 21:19:23 -0800839
840 # Init keyboard after all the intefaces are up.
841 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800842 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800843
Todd Broche505b8d2011-03-21 18:19:54 -0700844 def echo(self, echo):
845 """Dummy echo function for testing/examples.
846
847 Args:
848 echo: string to echo back to client
849 """
850 self._logger.debug("echo(%s)" % (echo))
851 return "ECH0ING: %s" % (echo)
852
J. Richard Barnettee2820552013-03-14 16:13:46 -0700853 def get_board(self):
854 """Return the board specified at startup, if any."""
855 return self._board
856
Simran Basia23c1392013-08-06 14:59:10 -0700857 def get_version(self):
858 """Get servo board version."""
859 return self._version
860
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800861 def power_long_press(self):
862 """Simulate a long power button press."""
863 # After a long power press, the EC may ignore the next power
864 # button press (at least on Alex). To guarantee that this
865 # won't happen, we need to allow the EC one second to
866 # collect itself.
867 self._keyboard.power_long_press()
868 return True
869
870 def power_normal_press(self):
871 """Simulate a normal power button press."""
872 self._keyboard.power_normal_press()
873 return True
874
875 def power_short_press(self):
876 """Simulate a short power button press."""
877 self._keyboard.power_short_press()
878 return True
879
880 def power_key(self, secs=''):
881 """Simulate a power button press.
882
883 Args:
884 secs: Time in seconds to simulate the keypress.
885 """
886 self._keyboard.power_key(secs)
887 return True
888
889 def ctrl_d(self, press_secs=''):
890 """Simulate Ctrl-d simultaneous button presses."""
891 self._keyboard.ctrl_d(press_secs)
892 return True
893
894 def ctrl_u(self):
895 """Simulate Ctrl-u simultaneous button presses."""
896 self._keyboard.ctrl_u()
897 return True
898
899 def ctrl_enter(self, press_secs=''):
900 """Simulate Ctrl-enter simultaneous button presses."""
901 self._keyboard.ctrl_enter(press_secs)
902 return True
903
904 def d_key(self, press_secs=''):
905 """Simulate Enter key button press."""
906 self._keyboard.d_key(press_secs)
907 return True
908
909 def ctrl_key(self, press_secs=''):
910 """Simulate Enter key button press."""
911 self._keyboard.ctrl_key(press_secs)
912 return True
913
914 def enter_key(self, press_secs=''):
915 """Simulate Enter key button press."""
916 self._keyboard.enter_key(press_secs)
917 return True
918
919 def refresh_key(self, press_secs=''):
920 """Simulate Refresh key (F3) button press."""
921 self._keyboard.refresh_key(press_secs)
922 return True
923
924 def ctrl_refresh_key(self, press_secs=''):
925 """Simulate Ctrl and Refresh (F3) simultaneous press.
926
927 This key combination is an alternative of Space key.
928 """
929 self._keyboard.ctrl_refresh_key(press_secs)
930 return True
931
932 def imaginary_key(self, press_secs=''):
933 """Simulate imaginary key button press.
934
935 Maps to a key that doesn't physically exist.
936 """
937 self._keyboard.imaginary_key(press_secs)
938 return True
939
Todd Brochdbb09982011-10-02 07:14:26 -0700940
Todd Broche505b8d2011-03-21 18:19:54 -0700941def test():
942 """Integration testing.
943
944 TODO(tbroch) Enhance integration test and add unittest (see mox)
945 """
946 logging.basicConfig(level=logging.DEBUG,
947 format="%(asctime)s - %(name)s - " +
948 "%(levelname)s - %(message)s")
949 # configure server & listen
950 servod_obj = Servod(1)
951 # 4 == number of interfaces on a FT4232H device
952 for i in xrange(4):
953 if i == 1:
954 # its an i2c interface ... see __init__ for details and TODO to make
955 # this configureable
956 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
957 else:
958 # its a gpio interface
959 servod_obj._interface_list[i].wr_rd(0)
960
961 server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999),
962 allow_none=True)
963 server.register_introspection_functions()
964 server.register_multicall_functions()
965 server.register_instance(servod_obj)
966 logging.info("Listening on localhost port 9999")
967 server.serve_forever()
968
969if __name__ == "__main__":
970 test()
971
972 # simple client transaction would look like
973 """
974 remote_uri = 'http://localhost:9999'
975 client = xmlrpclib.ServerProxy(remote_uri, verbose=False)
976 send_str = "Hello_there"
977 print "Sent " + send_str + ", Recv " + client.echo(send_str)
978 """