blob: 25e7a2e5fd85e8d5319b52fa943137bc39e9f04a [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 Cheng5595b342016-09-29 15:51:01 -07005import contextlib
Kevin Chengc49494e2016-07-25 12:13:38 -07006import datetime
7import fcntl
Simran Basia9f41032012-05-11 14:21:58 -07008import fnmatch
Todd Broche505b8d2011-03-21 18:19:54 -07009import logging
Simran Basia9f41032012-05-11 14:21:58 -070010import os
Kevin Chengc49494e2016-07-25 12:13:38 -070011import random
Aseda Aboagye1d8477b2017-05-10 17:24:31 -070012import re
Simran Basia9f41032012-05-11 14:21:58 -070013import shutil
Todd Broche505b8d2011-03-21 18:19:54 -070014import SimpleXMLRPCServer
Simran Basia9f41032012-05-11 14:21:58 -070015import subprocess
16import tempfile
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080017import threading
Todd Broch7a91c252012-02-03 12:37:45 -080018import time
Simran Basia9f41032012-05-11 14:21:58 -070019import urllib
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070020import usb
Todd Broche505b8d2011-03-21 18:19:54 -070021
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080022import drv as servo_drv
Aaron.Chuang88eff332014-07-31 08:32:00 +080023import bbadc
Simran Basia9ad25e2013-04-23 11:57:00 -070024import bbi2c
Simran Basi5492bde2013-05-16 17:08:47 -070025import bbgpio
Simran Basi949309b2013-05-31 15:12:15 -070026import bbuart
Aseda Aboagyea4922212015-11-20 15:19:08 -080027import ec3po_interface
Todd Broche505b8d2011-03-21 18:19:54 -070028import ftdigpio
29import ftdii2c
Todd Brochdbb09982011-10-02 07:14:26 -070030import ftdi_common
Todd Broch47c43f42011-05-26 15:11:31 -070031import ftdiuart
Rong Changc6c8c022014-08-11 14:07:11 +080032import i2cbus
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -080033import keyboard_handlers
Simran Basie750a342013-03-12 13:45:26 -070034import servo_interfaces
Kevin Cheng16304d12016-07-08 11:56:55 -070035import servo_postinit
Nick Sanders97bc4462016-01-04 15:37:31 -080036import stm32gpio
37import stm32i2c
38import stm32uart
Todd Broche505b8d2011-03-21 18:19:54 -070039
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080040HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080041
Todd Broche505b8d2011-03-21 18:19:54 -070042MAX_I2C_CLOCK_HZ = 100000
43
Kevin Cheng5595b342016-09-29 15:51:01 -070044# It takes about 16-17 seconds for the entire probe usb device method,
45# let's wait double plus some buffer.
46_MAX_USB_LOCK_WAIT = 40
Todd Brochdbb09982011-10-02 07:14:26 -070047
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070048
Todd Broche505b8d2011-03-21 18:19:54 -070049class ServodError(Exception):
50 """Exception class for servod."""
51
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070052
Todd Broche505b8d2011-03-21 18:19:54 -070053class Servod(object):
54 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070055 _USB_DETECTION_DELAY = 10
Fang Deng90377712013-06-03 15:51:48 -070056 _USB_POWEROFF_DELAY = 2
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070057 _HTTP_PREFIX = 'http://'
58 _USB_J3 = 'usb_mux_sel1'
59 _USB_J3_TO_SERVO = 'servo_sees_usbkey'
60 _USB_J3_TO_DUT = 'dut_sees_usbkey'
61 _USB_J3_PWR = 'prtctl4_pwren'
62 _USB_J3_PWR_ON = 'on'
63 _USB_J3_PWR_OFF = 'off'
64 _USB_LOCK_FILE = '/var/lib/servod/lock_file'
Simran Basia9f41032012-05-11 14:21:58 -070065
Kevin Cheng4b4f0022016-09-09 02:37:07 -070066 # This is the key to get the main serial used in the _serialnames dict.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070067 MAIN_SERIAL = 'main'
68 SERVO_MICRO_SERIAL = 'servo_micro'
69 CCD_SERIAL = 'ccd'
Kevin Cheng4b4f0022016-09-09 02:37:07 -070070
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080071 # Timeout to wait for interfaces to become available again if reinitialization
72 # is taking place. In seconds.
73 INTERFACE_AVAILABILITY_TIMEOUT = 60
74
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070075 def init_servo_interfaces(self, vendor, product, serialname, interfaces):
Kevin Chengdc3befd2016-07-15 12:34:00 -070076 """Init the servo interfaces with the given interfaces.
77
78 We don't use the self._{vendor,product,serialname} attributes because we
79 want to allow other callers to initialize other interfaces that may not
80 be associated with the initialized attributes (e.g. a servo v4 servod object
81 that wants to also initialize a servo micro interface).
82
83 Args:
84 vendor: USB vendor id of FTDI device.
85 product: USB product id of FTDI device.
86 serialname: String of device serialname/number as defined in FTDI
87 eeprom.
88 interfaces: List of strings of interface types the server will
89 instantiate.
90
91 Raises:
92 ServodError if unable to locate init method for particular interface.
93 """
Mary Ruthven13389642017-02-14 12:15:34 -080094 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070095 device = (vendor, product, serialname)
Mary Ruthven13389642017-02-14 12:15:34 -080096 if device not in self._devices:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070097 self._devices.append(device)
Mary Ruthven13389642017-02-14 12:15:34 -080098
Kevin Chengdc3befd2016-07-15 12:34:00 -070099 # Extend the interface list if we need to.
100 interfaces_len = len(interfaces)
101 interface_list_len = len(self._interface_list)
102 if interfaces_len > interface_list_len:
103 self._interface_list += [None] * (interfaces_len - interface_list_len)
104
Kevin Chengdc3befd2016-07-15 12:34:00 -0700105 for i, interface in enumerate(interfaces):
106 is_ftdi_interface = False
107 if type(interface) is dict:
108 name = interface['name']
109 # Store interface index for those that care about it.
110 interface['index'] = i
111 elif type(interface) is str and interface != 'dummy':
112 name = interface
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700113 # It's a FTDI related interface. #0 is reserved for no use.
114 interface = ((i - 1) % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1
Kevin Chengdc3befd2016-07-15 12:34:00 -0700115 is_ftdi_interface = True
116 elif type(interface) is str and interface == 'dummy':
117 # 'dummy' reserves the interface for future use. Typically the
118 # interface will be managed by external third-party tools like
119 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
120 # it serves as a placeholder for servo micro interfaces.
121 continue
122 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700123 raise ServodError('Illegal interface type %s' % type(interface))
Kevin Chengdc3befd2016-07-15 12:34:00 -0700124
125 # servos with multiple FTDI are guaranteed to have contiguous USB PIDs
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700126 product_increment = 0
127 if is_ftdi_interface:
128 product_increment = (i - 1) / ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE
129 if product_increment:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700130 self._logger.info('Use the next FTDI part @ pid = 0x%04x',
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700131 product + product_increment)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700132
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700133 self._logger.info('Initializing interface %d to %s', i, name)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700134 try:
135 func = getattr(self, '_init_%s' % name)
136 except AttributeError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700137 raise ServodError('Unable to locate init for interface %s' % name)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700138 result = func(vendor, product + product_increment, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700139
140 if isinstance(result, tuple):
141 result_len = len(result)
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700142 self._interface_list[i:(i + result_len)] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700143 else:
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700144 self._interface_list[i] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700145
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700146 def __init__(self, config, vendor, product, serialname=None, interfaces=None,
147 board='', version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700148 """Servod constructor.
149
150 Args:
151 config: instance of SystemConfig containing all controls for
152 particular Servod invocation
153 vendor: usb vendor id of FTDI device
154 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700155 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700156 interfaces: list of strings of interface types the server will instantiate
Simran Basia23c1392013-08-06 14:59:10 -0700157 version: String. Servo board version. Examples: servo_v1, servo_v2,
158 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800159 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700160 sending keyboard commands to DUTs that do not have built in
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700161 keyboards. Used in FAFT tests. Use None for on board AVR MCU.
162 e.g. '/dev/ttyUSB0' or None.
Todd Brochdbb09982011-10-02 07:14:26 -0700163
164 Raises:
165 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700166 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700167 self._logger = logging.getLogger('Servod')
168 self._logger.debug('')
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800169 self._ifaces_available = threading.Event()
170 # Initially interfaces should be available.
171 self._ifaces_available.set()
Todd Broche505b8d2011-03-21 18:19:54 -0700172 self._vendor = vendor
173 self._product = product
Mary Ruthven13389642017-02-14 12:15:34 -0800174 self._devices = []
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700175 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700176 self._syscfg = config
Kevin Cheng9071ed92016-06-21 14:37:54 -0700177 # Hold the last image path so we can reduce downloads to the usb device.
178 self._image_path = None
Todd Broche505b8d2011-03-21 18:19:54 -0700179 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
180 # interfaces are mapped to
181 self._interface_list = []
182 # Dict of Dict to map control name, function name to to tuple (params, drv)
183 # Ex) _drv_dict[name]['get'] = (params, drv)
184 self._drv_dict = {}
J. Richard Barnettee2820552013-03-14 16:13:46 -0700185 self._board = board
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700186 self._base_board = ''
Simran Basia23c1392013-08-06 14:59:10 -0700187 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800188 self._usbkm232 = usbkm232
Kevin Chengc49494e2016-07-25 12:13:38 -0700189 # Seed the random generator with the serial to differentiate from other
190 # servod processes.
191 random.seed(serialname if serialname else time.time())
Todd Brochdbb09982011-10-02 07:14:26 -0700192 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700193 try:
194 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
195 except KeyError:
196 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Dino Lic89d8c82018-01-11 09:56:47 +0800197 self._interfaces = interfaces
Todd Brochdbb09982011-10-02 07:14:26 -0700198
Kevin Chengdc3befd2016-07-15 12:34:00 -0700199 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700200 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800201
Mary Ruthven13389642017-02-14 12:15:34 -0800202 def reinitialize(self):
203 """Reinitialize all interfaces that support reinitialization"""
Mary Ruthven13389642017-02-14 12:15:34 -0800204 for i, interface in enumerate(self._interface_list):
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700205 if hasattr(interface, 'reinitialize'):
206 interface.reinitialize()
207 else:
208 self._logger.debug('interface %d has no reset functionality', i)
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800209 # Indicate interfaces are safe to use again.
210 self._ifaces_available.set()
Mary Ruthven13389642017-02-14 12:15:34 -0800211
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700212 def get_servo_interfaces(self, position, size):
213 """Get the list of servo interfaces.
214
215 Args:
216 position: The index the first interface to get.
217 size: The number of the interfaces.
218 """
219 return self._interface_list[position:(position + size)]
220
221 def set_servo_interfaces(self, position, interfaces):
222 """Set the list of servo interfaces.
223
224 Args:
225 position: The index the first interface to set.
226 interfaces: The list of interfaces to set.
227 """
228 size = len(interfaces)
229 self._interface_list[position:(position + size)] = interfaces
230
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800231 def _init_keyboard_handler(self, servo, board=''):
232 """Initialize the correct keyboard handler for board.
233
Kevin Chengdc3befd2016-07-15 12:34:00 -0700234 Args:
235 servo: servo object.
236 board: string, board name.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800237
Kevin Chengdc3befd2016-07-15 12:34:00 -0700238 Returns:
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700239 keyboard handler object, or None if no keyboard supported.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800240 """
241 if board == 'parrot':
242 return keyboard_handlers.ParrotHandler(servo)
243 elif board == 'stout':
244 return keyboard_handlers.StoutHandler(servo)
PeggyChuang4f07d872015-08-07 12:11:38 +0800245 elif board in ('buddy', 'cranky', 'guado', 'jecht', 'mccloud', 'monroe',
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700246 'ninja', 'nyan_kitty', 'panther', 'rikku', 'stumpy', 'sumo',
247 'tidus', 'tricky', 'veyron_fievel', 'veyron_mickey',
Shelley Chen94cd2352017-07-26 11:36:45 -0700248 'veyron_rialto', 'veyron_tiger', 'zako'):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800249 if self._usbkm232 is None:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700250 logging.info('No device path specified for usbkm232 handler. Use '
251 'the servo atmega chip to handle.')
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700252
Danny Chan662b6022015-11-04 17:34:53 -0800253 # Use servo onboard keyboard emulator.
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700254 if not self._syscfg.is_control('atmega_rst'):
255 logging.warn('No atmega in servo board. So no keyboard support.')
256 return None
257
Nick Sanders78423782015-11-09 14:28:19 -0800258 self.set('atmega_rst', 'on')
Nick Sandersbc836282015-12-08 21:19:23 -0800259 self.set('at_hwb', 'off')
Nick Sanders78423782015-11-09 14:28:19 -0800260 self.set('atmega_rst', 'off')
Danny Chan662b6022015-11-04 17:34:53 -0800261 self._usbkm232 = self.get('atmega_pty')
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700262
Kevin Cheng810fc782016-11-01 12:36:46 -0700263 # We don't need to set the atmega uart settings if we're a servo v4.
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700264 if 'servo_v4' not in self._version:
Kevin Cheng810fc782016-11-01 12:36:46 -0700265 self.set('atmega_baudrate', '9600')
266 self.set('atmega_bits', 'eight')
267 self.set('atmega_parity', 'none')
268 self.set('atmega_sbits', 'one')
269 self.set('usb_mux_sel4', 'on')
270 self.set('usb_mux_oe4', 'on')
271 # Allow atmega bootup time.
272 time.sleep(1.0)
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700273
Danny Chan662b6022015-11-04 17:34:53 -0800274 self._logger.info('USBKM232: %s', self._usbkm232)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800275 return keyboard_handlers.USBkm232Handler(servo, self._usbkm232)
276 else:
Tom Wai-Hong Tamd64164c2015-04-29 07:59:45 +0800277 # The following boards don't use Chrome EC.
278 if board in ('alex', 'butterfly', 'lumpy', 'zgb'):
279 return keyboard_handlers.MatrixKeyboardHandler(servo)
280 return keyboard_handlers.ChromeECHandler(servo)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800281
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700282 def close(self):
283 """Servod turn down logic."""
284 for i, interface in enumerate(self._interface_list):
285 self._logger.info('Turning down interface %d' % i)
286 if hasattr(interface, 'close'):
287 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800288
Kevin Chengdc3befd2016-07-15 12:34:00 -0700289 def _init_ftdi_dummy(self, vendor, product, serialname, interface):
Kevin Cheng042f4932016-07-19 10:46:00 -0700290 """Dummy interface for ftdi devices.
291
292 This is a dummy function specifically for ftdi devices to not initialize
293 anything but to help pad the interface list.
294
295 Returns:
296 None.
297 """
298 return None
299
Kevin Chengdc3befd2016-07-15 12:34:00 -0700300 def _init_ftdi_gpio(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700301 """Initialize gpio driver interface and open for use.
302
303 Args:
304 interface: interface number of FTDI device to use.
305
306 Returns:
307 Instance object of interface.
Todd Broch6de9dc62012-04-09 15:23:53 -0700308
309 Raises:
310 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700311 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700312 fobj = ftdigpio.Fgpio(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700313 try:
314 fobj.open()
315 except ftdigpio.FgpioError as e:
316 raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value))
317
Todd Broche505b8d2011-03-21 18:19:54 -0700318 return fobj
319
Kevin Chengdc3befd2016-07-15 12:34:00 -0700320 def _init_stm32_uart(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800321 """Initialize stm32 uart interface and open for use
322
323 Note, the uart runs in a separate thread. Users wishing to
324 interact with it will query control for the pty's pathname and connect
325 with their favorite console program. For example:
326 cu -l /dev/pts/22
327
328 Args:
329 interface: dict of interface parameters.
330
331 Returns:
332 Instance object of interface
333
334 Raises:
335 ServodError: Raised on init failure.
336 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700337 self._logger.info('Suart: interface: %s' % interface)
338 sobj = stm32uart.Suart(vendor, product, interface['interface'], serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800339
340 try:
341 sobj.run()
342 except stm32uart.SuartError as e:
343 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
344
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700345 self._logger.info('%s' % sobj.get_pty())
Nick Sanders97bc4462016-01-04 15:37:31 -0800346 return sobj
347
Kevin Chengdc3befd2016-07-15 12:34:00 -0700348 def _init_stm32_gpio(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800349 """Initialize stm32 gpio interface.
350 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700351 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800352
353 Returns:
354 Instance object of interface
355
356 Raises:
357 SgpioError: Raised on init failure.
358 """
Kevin Cheng71a046f2016-06-13 16:37:58 -0700359 interface_number = interface
360 # Interface could be a dict.
361 if type(interface) is dict:
362 interface_number = interface['interface']
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700363 self._logger.info('Sgpio: interface: %s' % interface_number)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700364 return stm32gpio.Sgpio(vendor, product, interface_number, serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800365
Kevin Chengdc3befd2016-07-15 12:34:00 -0700366 def _init_stm32_i2c(self, vendor, product, serialname, interface):
Nick Sanders97bc4462016-01-04 15:37:31 -0800367 """Initialize stm32 USB to I2C bridge interface and open for use
368
369 Args:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700370 interface: dict of interface parameters.
Nick Sanders97bc4462016-01-04 15:37:31 -0800371
372 Returns:
373 Instance object of interface.
374
375 Raises:
376 Si2cError: Raised on init failure.
377 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700378 self._logger.info('Si2cBus: interface: %s' % interface)
Nick Sandersa3649712016-03-01 16:53:52 -0800379 port = interface.get('port', 0)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700380 return stm32i2c.Si2cBus(vendor, product, interface['interface'], port=port,
381 serialname=serialname)
Nick Sanders97bc4462016-01-04 15:37:31 -0800382
Kevin Chengdc3befd2016-07-15 12:34:00 -0700383 def _init_bb_adc(self, vendor, product, serialname, interface):
Aaron.Chuang88eff332014-07-31 08:32:00 +0800384 """Initalize beaglebone ADC interface."""
385 return bbadc.BBadc()
386
Kevin Chengdc3befd2016-07-15 12:34:00 -0700387 def _init_bb_gpio(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700388 """Initalize beaglebone gpio interface."""
Simran Basi5492bde2013-05-16 17:08:47 -0700389 return bbgpio.BBgpio()
Simran Basie750a342013-03-12 13:45:26 -0700390
Kevin Chengdc3befd2016-07-15 12:34:00 -0700391 def _init_ftdi_i2c(self, vendor, product, serialname, interface):
Todd Broche505b8d2011-03-21 18:19:54 -0700392 """Initialize i2c interface and open for use.
393
394 Args:
395 interface: interface number of FTDI device to use
396
397 Returns:
398 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700399
400 Raises:
401 ServodError: If init fails
Todd Broche505b8d2011-03-21 18:19:54 -0700402 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700403 fobj = ftdii2c.Fi2c(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700404 try:
405 fobj.open()
406 except ftdii2c.Fi2cError as e:
407 raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value))
408
Todd Broche505b8d2011-03-21 18:19:54 -0700409 # Set the frequency of operation of the i2c bus.
410 # TODO(tbroch) make configureable
411 fobj.setclock(MAX_I2C_CLOCK_HZ)
Todd Broch6de9dc62012-04-09 15:23:53 -0700412
Todd Broche505b8d2011-03-21 18:19:54 -0700413 return fobj
414
Simran Basie750a342013-03-12 13:45:26 -0700415 # TODO (sbasi) crbug.com/187489 - Implement bb_i2c.
416 def _init_bb_i2c(self, interface):
417 """Initalize beaglebone i2c interface."""
Simran Basia9ad25e2013-04-23 11:57:00 -0700418 return bbi2c.BBi2c(interface)
Simran Basie750a342013-03-12 13:45:26 -0700419
Kevin Chengdc3befd2016-07-15 12:34:00 -0700420 def _init_dev_i2c(self, vendor, product, serialname, interface):
Rong Changc6c8c022014-08-11 14:07:11 +0800421 """Initalize Linux i2c-dev interface."""
422 return i2cbus.I2CBus('/dev/i2c-%d' % interface['bus_num'])
423
Kevin Chengdc3befd2016-07-15 12:34:00 -0700424 def _init_ftdi_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700425 """Initialize ftdi uart inteface and open for use
Todd Broch47c43f42011-05-26 15:11:31 -0700426
427 Note, the uart runs in a separate thread (pthreads). Users wishing to
428 interact with it will query control for the pty's pathname and connect
429 with there favorite console program. For example:
430 cu -l /dev/pts/22
431
432 Args:
433 interface: interface number of FTDI device to use
434
435 Returns:
436 Instance object of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700437
438 Raises:
439 ServodError: If init fails
Todd Broch47c43f42011-05-26 15:11:31 -0700440 """
Kevin Chengdc3befd2016-07-15 12:34:00 -0700441 fobj = ftdiuart.Fuart(vendor, product, interface, serialname)
Todd Broch6de9dc62012-04-09 15:23:53 -0700442 try:
443 fobj.run()
444 except ftdiuart.FuartError as e:
445 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
446
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700447 self._logger.info('%s' % fobj.get_pty())
Todd Broch47c43f42011-05-26 15:11:31 -0700448 return fobj
449
Simran Basie750a342013-03-12 13:45:26 -0700450 # TODO (sbasi) crbug.com/187492 - Implement bbuart.
Kevin Chengdc3befd2016-07-15 12:34:00 -0700451 def _init_bb_uart(self, vendor, product, serialname, interface):
Simran Basie750a342013-03-12 13:45:26 -0700452 """Initalize beaglebone uart interface."""
Simran Basi949309b2013-05-31 15:12:15 -0700453 logging.debug('UART INTERFACE: %s', interface)
454 return bbuart.BBuart(interface)
Simran Basie750a342013-03-12 13:45:26 -0700455
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700456 def _init_ftdi_gpiouart(self, vendor, product, serialname, interface):
Todd Broch888da782011-10-07 14:29:09 -0700457 """Initialize special gpio + uart interface and open for use
458
459 Note, the uart runs in a separate thread (pthreads). Users wishing to
460 interact with it will query control for the pty's pathname and connect
461 with there favorite console program. For example:
462 cu -l /dev/pts/22
463
464 Args:
465 interface: interface number of FTDI device to use
466
467 Returns:
468 Instance objects of interface
Todd Broch6de9dc62012-04-09 15:23:53 -0700469
470 Raises:
471 ServodError: If init fails
Todd Broch888da782011-10-07 14:29:09 -0700472 """
Kevin Chengce7dafd2016-08-02 11:11:38 -0700473 fgpio = self._init_ftdi_gpio(vendor, product, serialname, interface)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700474 fuart = ftdiuart.Fuart(vendor, product, interface, serialname, fgpio._fc)
Todd Broch6de9dc62012-04-09 15:23:53 -0700475 try:
476 fuart.run()
477 except ftdiuart.FuartError as e:
478 raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value))
479
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700480 self._logger.info('uart pty: %s' % fuart.get_pty())
Todd Broch888da782011-10-07 14:29:09 -0700481 return fgpio, fuart
482
Kevin Chengdc3befd2016-07-15 12:34:00 -0700483 def _init_ec3po_uart(self, vendor, product, serialname, interface):
Aseda Aboagyea4922212015-11-20 15:19:08 -0800484 """Initialize EC-3PO console interpreter interface.
485
486 Args:
487 interface: A dictionary representing the interface.
488
489 Returns:
490 An EC3PO object representing the EC-3PO interface or None if there's no
491 interface for the USB PD UART.
492 """
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700493 raw_uart_name = interface['raw_pty']
Nick Sanders116ed9e2018-03-09 19:05:16 -0800494 raw_uart_source = interface['source']
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700495 if self._syscfg.is_control(raw_uart_name):
Nick Sanders97bc4462016-01-04 15:37:31 -0800496 raw_ec_uart = self.get(raw_uart_name)
Nick Sanders116ed9e2018-03-09 19:05:16 -0800497 return ec3po_interface.EC3PO(raw_ec_uart, raw_uart_source)
Aseda Aboagyea4922212015-11-20 15:19:08 -0800498 else:
Wai-Hong Tam6c0fa592017-04-21 12:41:33 -0700499 # The overlay doesn't have the raw PTY defined, therefore we can skip
500 # initializing this interface since no control relies on it.
501 self._logger.debug(
502 'Skip initializing EC3PO for %s, no control specified.',
503 raw_uart_name)
504 return None
Aseda Aboagyea4922212015-11-20 15:19:08 -0800505
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800506 def _camel_case(self, string):
507 output = ''
508 for s in string.split('_'):
509 if output:
510 output += s.capitalize()
511 else:
512 output = s
513 return output
514
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700515 def clear_cached_drv(self):
516 """Clear the cached drivers.
517
518 The drivers are cached in the Dict _drv_dict when a control is got or set.
519 When the servo interfaces are relocated, the cached values may become wrong.
520 Should call this method to clear the cached values.
521 """
522 self._drv_dict = {}
523
Todd Broche505b8d2011-03-21 18:19:54 -0700524 def _get_param_drv(self, control_name, is_get=True):
525 """Get access to driver for a given control.
526
527 Note, some controls have different parameter dictionaries for 'getting' the
528 control's value versus 'setting' it. Boolean is_get distinguishes which is
529 being requested.
530
531 Args:
532 control_name: string name of control
533 is_get: boolean to determine
534
535 Returns:
536 tuple (param, drv) where:
537 param: param dictionary for control
538 drv: instance object of driver for particular control
539
540 Raises:
541 ServodError: Error occurred while examining params dict
542 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700543 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700544 # if already setup just return tuple from driver dict
545 if control_name in self._drv_dict:
546 if is_get and ('get' in self._drv_dict[control_name]):
547 return self._drv_dict[control_name]['get']
548 if not is_get and ('set' in self._drv_dict[control_name]):
549 return self._drv_dict[control_name]['set']
550
551 params = self._syscfg.lookup_control_params(control_name, is_get)
552 if 'drv' not in params:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700553 self._logger.error('Unable to determine driver for %s' % control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700554 raise ServodError("'drv' key not found in params dict")
555 if 'interface' not in params:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700556 self._logger.error('Unable to determine interface for %s' % control_name)
Todd Broche505b8d2011-03-21 18:19:54 -0700557 raise ServodError("'interface' key not found in params dict")
Simran Basi668be0e2013-08-07 11:54:50 -0700558
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700559 # Find the candidate servos. Using servo_v4 with a servo_micro connected as
560 # an example, the following shows the priority for selecting the interface.
561 #
562 # 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
563 # 2. servo_micro_interface
564 # 3. servo_v4_interface
565 # 4. Fallback to the default, interface.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700566 candidates = [self._version]
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700567 candidates.extend(reversed(self._version.split('_with_')))
568
569 interface_id = 'unknown'
570 for c in candidates:
571 interface_name = '%s_interface' % c
572 if interface_name in params:
573 interface_id = params[interface_name]
574 self._logger.debug('Using %s parameter.' % interface_name)
575 break
576
577 # Use the default interface value if we couldn't find a more specific
578 # interface.
579 if interface_id == 'unknown':
580 interface_id = params['interface']
581 self._logger.debug('Using default interface parameter.')
582
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800583 if interface_id == 'servo':
584 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700585 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700586 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800587 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700588
Todd Broche505b8d2011-03-21 18:19:54 -0700589 drv_name = params['drv']
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800590 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800591 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700592 drv = drv_class(interface, params)
593 if control_name not in self._drv_dict:
594 self._drv_dict[control_name] = {}
595 if is_get:
596 self._drv_dict[control_name]['get'] = (params, drv)
597 else:
598 self._drv_dict[control_name]['set'] = (params, drv)
599 return (params, drv)
600
601 def doc_all(self):
602 """Return all documenation for controls.
603
604 Returns:
605 string of <doc> text in config file (xml) and the params dictionary for
606 all controls.
607
608 For example:
609 warm_reset :: Reset the device warmly
610 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
611 """
612 return self._syscfg.display_config()
613
614 def doc(self, name):
615 """Retreive doc string in system config file for given control name.
616
617 Args:
618 name: name string of control to get doc string
619
620 Returns:
621 doc string of name
622
623 Raises:
624 NameError: if fails to locate control
625 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700626 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700627 if self._syscfg.is_control(name):
628 return self._syscfg.get_control_docstring(name)
629 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700630 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700631
Fang Deng90377712013-06-03 15:51:48 -0700632 def _switch_usbkey(self, mux_direction):
633 """Connect USB flash stick to either servo or DUT.
634
635 This function switches 'usb_mux_sel1' to provide electrical
636 connection between the USB port J3 and either servo or DUT side.
637
638 Switching the usb mux is accompanied by powercycling
639 of the USB stick, because it sometimes gets wedged if the mux
640 is switched while the stick power is on.
641
642 Args:
643 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
644 """
645 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
646 time.sleep(self._USB_POWEROFF_DELAY)
647 self.set(self._USB_J3, mux_direction)
648 time.sleep(self._USB_POWEROFF_DELAY)
649 self.set(self._USB_J3_PWR, self._USB_J3_PWR_ON)
650 if mux_direction == self._USB_J3_TO_SERVO:
651 time.sleep(self._USB_DETECTION_DELAY)
652
Simran Basia9f41032012-05-11 14:21:58 -0700653 def _get_usb_port_set(self):
654 """Gets a set of USB disks currently connected to the system
655
656 Returns:
657 A set of USB disk paths.
658 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700659 usb_set = fnmatch.filter(os.listdir('/dev/'), 'sd[a-z]')
660 return set(['/dev/' + dev for dev in usb_set])
Simran Basia9f41032012-05-11 14:21:58 -0700661
Kevin Cheng5595b342016-09-29 15:51:01 -0700662 @contextlib.contextmanager
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800663 def _block_other_servod(self, timeout):
Kevin Chengc49494e2016-07-25 12:13:38 -0700664 """Block other servod processes by locking a file.
665
666 To enable multiple servods processes to safely probe_host_usb_dev, we use
667 a given lock file to signal other servod processes that we're probing
Kevin Cheng5595b342016-09-29 15:51:01 -0700668 for a usb device. This will be a context manager that will return
669 if the block was successful or not.
Kevin Chengc49494e2016-07-25 12:13:38 -0700670
671 If the lock file exists, we open it and try to lock it.
672 - If another servod processes has locked it already, we'll sleep a random
673 amount of time and try again, we'll keep doing that until
Kevin Cheng5595b342016-09-29 15:51:01 -0700674 timeout amount of time has passed.
Kevin Chengc49494e2016-07-25 12:13:38 -0700675
Kevin Cheng5595b342016-09-29 15:51:01 -0700676 - If we're able to lock the file, we'll yield that the block was successful
677 and upon return, unlock the file and exit out.
Kevin Chengc49494e2016-07-25 12:13:38 -0700678
679 This blocking behavior is only enabled if the lock file exists, if it
680 doesn't, then we pretend the block was successful.
681
Kevin Cheng5595b342016-09-29 15:51:01 -0700682 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800683 timeout: Max waiting time for the block to succeed; 0 to wait forever.
Kevin Chengc49494e2016-07-25 12:13:38 -0700684 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700685 if not os.path.exists(self._USB_LOCK_FILE):
686 # No lock file so we'll pretend the block was a success.
687 yield True
688 else:
Kevin Chengc49494e2016-07-25 12:13:38 -0700689 start_time = datetime.datetime.now()
690 while True:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800691 with open(self._USB_LOCK_FILE, 'w') as lock_file:
Kevin Cheng5595b342016-09-29 15:51:01 -0700692 try:
693 fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
694 yield True
695 fcntl.flock(lock_file, fcntl.LOCK_UN)
696 break
697 except IOError:
698 current_time = datetime.datetime.now()
699 current_wait_time = (current_time - start_time).total_seconds()
700 if timeout and current_wait_time > timeout:
701 yield False
702 break
Kevin Chengc49494e2016-07-25 12:13:38 -0700703 # Sleep random amount.
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800704 sleep_time = random.random()
705 logging.debug('sleep %.04fs and try obtaining a lock...', sleep_time)
706 time.sleep(sleep_time)
Kevin Chengc49494e2016-07-25 12:13:38 -0700707
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700708 def safe_switch_usbkey_power(self, power_state, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700709 """Toggle the usb power safely.
710
711 We'll make sure we're the only servod process toggling the usbkey power.
Kevin Chengc49494e2016-07-25 12:13:38 -0700712
713 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700714 power_state: The setting to set for the usbkey power.
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700715 timeout: Timeout to wait for blocking other servod processes, default is
716 no timeout.
Kevin Chengc49494e2016-07-25 12:13:38 -0700717
Kevin Cheng5595b342016-09-29 15:51:01 -0700718 Returns:
719 An empty string to appease the xmlrpc gods.
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800720
721 Raises:
722 ServodError if failed to obtain a lock.
Kevin Cheng5595b342016-09-29 15:51:01 -0700723 """
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800724 with self._block_other_servod(timeout=timeout) as block_success:
725 if not block_success:
726 raise ServodError('Timed out obtaining a lock to block other servod')
727
Kevin Cheng5595b342016-09-29 15:51:01 -0700728 if power_state != self.get(self._USB_J3_PWR):
729 self.set(self._USB_J3_PWR, power_state)
730 return ''
731
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700732 def safe_switch_usbkey(self, mux_direction, timeout=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700733 """Toggle the usb direction safely.
734
735 We'll make sure we're the only servod process toggling the usbkey direction.
736
737 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800738 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
Kevin Cheng8fcf06c2016-10-12 08:02:44 -0700739 timeout: Timeout to wait for blocking other servod processes, default is
740 no timeout.
Kevin Cheng5595b342016-09-29 15:51:01 -0700741
742 Returns:
743 An empty string to appease the xmlrpc gods.
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800744
745 Raises:
746 ServodError if failed to obtain a lock.
Kevin Cheng5595b342016-09-29 15:51:01 -0700747 """
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800748 with self._block_other_servod(timeout=timeout) as block_success:
749 if not block_success:
750 raise ServodError('Timed out obtaining a lock to block other servod')
751
Kevin Cheng5595b342016-09-29 15:51:01 -0700752 self._switch_usbkey(mux_direction)
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800753
Kevin Cheng5595b342016-09-29 15:51:01 -0700754 return ''
755
756 def probe_host_usb_dev(self, timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700757 """Probe the USB disk device plugged in the servo from the host side.
758
759 Method can fail by:
760 1) Having multiple servos connected and returning incorrect /dev/sdX of
Kevin Chengc49494e2016-07-25 12:13:38 -0700761 another servo unless _USB_LOCK_FILE exists on the servo host. If that
762 file exists, then it is safe to probe for usb devices among multiple
763 servod instances.
Simran Basia9f41032012-05-11 14:21:58 -0700764 2) Finding multiple /dev/sdX and returning None.
765
Kevin Cheng5595b342016-09-29 15:51:01 -0700766 Args:
767 timeout: Timeout to wait for blocking other servod processes.
768
Simran Basia9f41032012-05-11 14:21:58 -0700769 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700770 USB disk path if one and only one USB disk path is found, otherwise an
771 empty string.
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800772
773 Raises:
774 ServodError if failed to obtain a lock.
Simran Basia9f41032012-05-11 14:21:58 -0700775 """
Kevin Cheng5595b342016-09-29 15:51:01 -0700776 with self._block_other_servod(timeout=timeout) as block_success:
777 if not block_success:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800778 raise ServodError('Timed out obtaining a lock to block other servod')
Kevin Chengc49494e2016-07-25 12:13:38 -0700779
Kevin Cheng5595b342016-09-29 15:51:01 -0700780 original_value = self.get(self._USB_J3)
781 original_usb_power = self.get(self._USB_J3_PWR)
782 # Make the host unable to see the USB disk.
783 if (original_usb_power == self._USB_J3_PWR_ON and
784 original_value != self._USB_J3_TO_DUT):
785 self._switch_usbkey(self._USB_J3_TO_DUT)
786 no_usb_set = self._get_usb_port_set()
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800787 logging.debug('Device set when USB disk unplugged: %r', no_usb_set)
Simran Basia9f41032012-05-11 14:21:58 -0700788
Kevin Cheng5595b342016-09-29 15:51:01 -0700789 # Make the host able to see the USB disk.
790 self._switch_usbkey(self._USB_J3_TO_SERVO)
791 has_usb_set = self._get_usb_port_set()
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800792 logging.debug('Device set when USB disk plugged: %r', has_usb_set)
Fang Deng90377712013-06-03 15:51:48 -0700793
Kevin Cheng5595b342016-09-29 15:51:01 -0700794 # Back to its original value.
795 if original_value != self._USB_J3_TO_SERVO:
796 self._switch_usbkey(original_value)
797 if original_usb_power != self._USB_J3_PWR_ON:
798 self.set(self._USB_J3_PWR, self._USB_J3_PWR_OFF)
799 time.sleep(self._USB_POWEROFF_DELAY)
Fang Deng90377712013-06-03 15:51:48 -0700800
Kevin Cheng5595b342016-09-29 15:51:01 -0700801 # Subtract the two sets to find the usb device.
802 diff_set = has_usb_set - no_usb_set
803 if len(diff_set) == 1:
804 return diff_set.pop()
805 else:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800806 logging.warn("Can't find the USB device. Diff: %r", diff_set)
Kevin Cheng5595b342016-09-29 15:51:01 -0700807 return ''
Simran Basia9f41032012-05-11 14:21:58 -0700808
Kevin Cheng85831332016-10-13 13:14:44 -0700809 def download_image_to_usb(self, image_path, probe_timeout=_MAX_USB_LOCK_WAIT):
Simran Basia9f41032012-05-11 14:21:58 -0700810 """Download image and save to the USB device found by probe_host_usb_dev.
811 If the image_path is a URL, it will download this url to the USB path;
812 otherwise it will simply copy the image_path's contents to the USB path.
813
814 Args:
815 image_path: path or url to the recovery image.
Kevin Cheng85831332016-10-13 13:14:44 -0700816 probe_timeout: timeout for the probe to take.
Simran Basia9f41032012-05-11 14:21:58 -0700817
818 Returns:
819 True|False: True if process completed successfully, False if error
820 occurred.
821 Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's
822 comment at the end of set().
823 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700824 self._logger.debug('image_path(%s)' % image_path)
825 self._logger.debug('Detecting USB stick device...')
Kevin Cheng85831332016-10-13 13:14:44 -0700826 usb_dev = self.probe_host_usb_dev(timeout=probe_timeout)
Simran Basia9f41032012-05-11 14:21:58 -0700827 if not usb_dev:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700828 self._logger.error('No usb device connected to servo')
Simran Basia9f41032012-05-11 14:21:58 -0700829 return False
830
Kevin Cheng9071ed92016-06-21 14:37:54 -0700831 # Let's check if we downloaded this last time and if so assume the image is
832 # still on the usb device and return True.
833 if self._image_path == image_path:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700834 self._logger.debug('Image already on USB device, skipping transfer')
Kevin Cheng9071ed92016-06-21 14:37:54 -0700835 return True
836
Simran Basia9f41032012-05-11 14:21:58 -0700837 try:
838 if image_path.startswith(self._HTTP_PREFIX):
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700839 self._logger.debug('Image path is a URL, downloading image')
Simran Basia9f41032012-05-11 14:21:58 -0700840 urllib.urlretrieve(image_path, usb_dev)
841 else:
842 shutil.copyfile(image_path, usb_dev)
843 except IOError as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700844 self._logger.error('Failed to transfer image to USB device: %s ( %s ) ',
Simran Basia9f41032012-05-11 14:21:58 -0700845 e.strerror, e.errno)
846 return False
847 except urllib.ContentTooShortError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700848 self._logger.error('Failed to download URL: %s to USB device: %s',
Simran Basia9f41032012-05-11 14:21:58 -0700849 image_path, usb_dev)
850 return False
851 except BaseException as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700852 self._logger.error('Unexpected exception downloading %s to %s: %s',
Simran Basia9f41032012-05-11 14:21:58 -0700853 image_path, usb_dev, str(e))
854 return False
J. Richard Barnettee4125af2013-02-26 18:31:56 -0800855 finally:
856 # We just plastered the partition table for a block device.
857 # Pass or fail, we mustn't go without telling the kernel about
858 # the change, or it will punish us with sporadic, hard-to-debug
859 # failures.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700860 subprocess.call(['sync'])
861 subprocess.call(['blockdev', '--rereadpt', usb_dev])
Kevin Cheng9071ed92016-06-21 14:37:54 -0700862 self._image_path = image_path
Simran Basia9f41032012-05-11 14:21:58 -0700863 return True
864
865 def make_image_noninteractive(self):
866 """Makes the recovery image noninteractive.
867
868 A noninteractive image will reboot automatically after installation
869 instead of waiting for the USB device to be removed to initiate a system
870 reboot.
871
872 Mounts partition 1 of the image stored on usb_dev and creates a file
873 called "non_interactive" so that the image will become noninteractive.
874
875 Returns:
876 True|False: True if process completed successfully, False if error
877 occurred.
878 """
879 result = True
Kevin Chengc49494e2016-07-25 12:13:38 -0700880 usb_dev = self.probe_host_usb_dev()
Simran Basia9f41032012-05-11 14:21:58 -0700881 if not usb_dev:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700882 self._logger.error('No usb device connected to servo')
Simran Basia9f41032012-05-11 14:21:58 -0700883 return False
884 # Create TempDirectory
885 tmpdir = tempfile.mkdtemp()
886 if tmpdir:
887 # Mount drive to tmpdir.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700888 partition_1 = '%s1' % usb_dev
889 rc = subprocess.call(['mount', partition_1, tmpdir])
Simran Basia9f41032012-05-11 14:21:58 -0700890 if rc == 0:
891 # Create file 'non_interactive'
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700892 non_interactive_file = os.path.join(tmpdir, 'non_interactive')
Simran Basia9f41032012-05-11 14:21:58 -0700893 try:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700894 open(non_interactive_file, 'w').close()
Simran Basia9f41032012-05-11 14:21:58 -0700895 except IOError as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700896 self._logger.error('Failed to create file %s : %s ( %d )',
Simran Basia9f41032012-05-11 14:21:58 -0700897 non_interactive_file, e.strerror, e.errno)
898 result = False
899 except BaseException as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700900 self._logger.error('Unexpected Exception creating file %s : %s',
Simran Basia9f41032012-05-11 14:21:58 -0700901 non_interactive_file, str(e))
902 result = False
903 # Unmount drive regardless if file creation worked or not.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700904 rc = subprocess.call(['umount', partition_1])
Simran Basia9f41032012-05-11 14:21:58 -0700905 if rc != 0:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700906 self._logger.error('Failed to unmount USB Device')
Simran Basia9f41032012-05-11 14:21:58 -0700907 result = False
908 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700909 self._logger.error('Failed to mount USB Device')
Simran Basia9f41032012-05-11 14:21:58 -0700910 result = False
911
912 # Delete tmpdir. May throw exception if 'umount' failed.
913 try:
914 os.rmdir(tmpdir)
915 except OSError as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700916 self._logger.error('Failed to remove temp directory %s : %s', tmpdir,
917 str(e))
Simran Basia9f41032012-05-11 14:21:58 -0700918 return False
919 except BaseException as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700920 self._logger.error('Unexpected Exception removing tempdir %s : %s',
Simran Basia9f41032012-05-11 14:21:58 -0700921 tmpdir, str(e))
922 return False
923 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700924 self._logger.error('Failed to create temp directory.')
Simran Basia9f41032012-05-11 14:21:58 -0700925 return False
926 return result
927
Todd Broch352b4b22013-03-22 09:48:40 -0700928 def set_get_all(self, cmds):
929 """Set &| get one or more control values.
930
931 Args:
932 cmds: list of control[:value] to get or set.
933
934 Returns:
935 rv: list of responses from calling get or set methods.
936 """
937 rv = []
938 for cmd in cmds:
939 if ':' in cmd:
940 (control, value) = cmd.split(':')
941 rv.append(self.set(control, value))
942 else:
943 rv.append(self.get(cmd))
944 return rv
945
Aseda Aboagye6921f602017-08-01 14:45:38 -0700946 def get_serial_number(self, name):
947 """Returns the desired serial number from the serialnames dict.
948
949 Args:
950 name: A string which is the key into the _serialnames dictionary.
951
952 Returns:
953 A string containing the serial number or "unknown".
954 """
955 if not name:
956 name = 'main'
957
958 try:
959 return self._serialnames[name]
960 except KeyError:
961 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700962 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700963
Todd Broche505b8d2011-03-21 18:19:54 -0700964 def get(self, name):
965 """Get control value.
966
967 Args:
968 name: name string of control
969
970 Returns:
971 Response from calling drv get method. Value is reformatted based on
972 control's dictionary parameters
973
974 Raises:
975 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800976 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700977 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800978 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
979 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700980 self._logger.debug('name(%s)' % (name))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700981 # This route is to retrieve serialnames on servo v4, which
982 # connects to multiple servo-micros or CCD, like the controls,
983 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
984 # TODO(aaboagye): Refactor it.
985 if 'serialname' in name:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700986 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700987
Todd Broche505b8d2011-03-21 18:19:54 -0700988 (param, drv) = self._get_param_drv(name)
989 try:
990 val = drv.get()
991 rd_val = self._syscfg.reformat_val(param, val)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700992 self._logger.debug('%s = %s' % (name, rd_val))
Todd Broche505b8d2011-03-21 18:19:54 -0700993 return rd_val
Todd Brochfbc499d2011-06-16 16:09:58 -0700994 except AttributeError, error:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700995 self._logger.error('Getting %s: %s' % (name, error))
Todd Brochfbc499d2011-06-16 16:09:58 -0700996 raise
Vic Yangbe6cf262012-09-10 10:40:56 +0800997 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700998 self._logger.error('Getting %s' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700999 raise
Todd Brochd6061672012-05-11 15:52:47 -07001000
Todd Broche505b8d2011-03-21 18:19:54 -07001001 def get_all(self, verbose):
1002 """Get all controls values.
1003
1004 Args:
1005 verbose: Boolean on whether to return doc info as well
1006
1007 Returns:
1008 string creating from trying to get all values of all controls. In case of
1009 error attempting access to control, response is 'ERR'.
1010 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -08001011 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -07001012 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001013 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -07001014 try:
1015 value = self.get(name)
1016 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001017 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -07001018 pass
1019 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001020 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -07001021 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001022 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -08001023 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -07001024
1025 def set(self, name, wr_val_str):
1026 """Set control.
1027
1028 Args:
1029 name: name string of control
1030 wr_val_str: value string to write. Can be integer, float or a
1031 alpha-numerical that is mapped to a integer or float.
1032
1033 Raises:
1034 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +08001035 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -07001036 """
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +08001037 if not self._ifaces_available.wait(self.INTERFACE_AVAILABILITY_TIMEOUT):
1038 raise ServodError('Timed out waiting for interfaces to become available.')
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001039 self._logger.debug('name(%s) wr_val(%s)' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -07001040 (params, drv) = self._get_param_drv(name, False)
1041 wr_val = self._syscfg.resolve_val(params, wr_val_str)
1042 try:
1043 drv.set(wr_val)
Vic Yangbe6cf262012-09-10 10:40:56 +08001044 except HwDriverError:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001045 self._logger.error('Setting %s -> %s' % (name, wr_val_str))
Todd Broche505b8d2011-03-21 18:19:54 -07001046 raise
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +08001047 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
1048 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -07001049 # marshall/unmarshall
1050 return True
1051
Todd Brochd6061672012-05-11 15:52:47 -07001052 def hwinit(self, verbose=False):
1053 """Initialize all controls.
1054
1055 These values are part of the system config XML files of the form
1056 init=<value>. This command should be used by clients wishing to return the
1057 servo and DUT its connected to a known good/safe state.
1058
Vadim Bendeburybb51dd42013-01-31 13:47:46 -08001059 Note that initialization errors are ignored (as in some cases they could
1060 be caused by DUT firmware deficiencies). This might need to be fine tuned
1061 later.
1062
Todd Brochd6061672012-05-11 15:52:47 -07001063 Args:
1064 verbose: boolean, if True prints info about control initialized.
1065 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001066
1067 Returns:
1068 This function is called across RPC and as such is expected to return
1069 something unless transferring 'none' across is allowed. Hence adding a
1070 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -07001071 """
Todd Brochd9acf0a2012-12-05 13:43:06 -08001072 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -08001073 try:
John Carey6fe2bbf2015-08-31 16:13:03 -07001074 # Workaround for bug chrome-os-partner:42349. Without this check, the
1075 # gpio will briefly pulse low if we set it from high to high.
1076 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -07001077 self.set(control_name, value)
1078 if verbose:
1079 self._logger.info('Initialized %s to %s', control_name, value)
Todd Broch3ec8df02012-11-20 10:53:03 -08001080 except Exception as e:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001081 self._logger.error('Problem initializing %s -> %s :: %s', control_name,
1082 value, str(e))
Nick Sandersbc836282015-12-08 21:19:23 -08001083
1084 # Init keyboard after all the intefaces are up.
1085 self._keyboard = self._init_keyboard_handler(self, self._board)
Vadim Bendebury5934e4b2013-02-06 13:57:54 -08001086 return True
Todd Broch3ec8df02012-11-20 10:53:03 -08001087
Todd Broche505b8d2011-03-21 18:19:54 -07001088 def echo(self, echo):
1089 """Dummy echo function for testing/examples.
1090
1091 Args:
1092 echo: string to echo back to client
1093 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001094 self._logger.debug('echo(%s)' % (echo))
1095 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -07001096
J. Richard Barnettee2820552013-03-14 16:13:46 -07001097 def get_board(self):
1098 """Return the board specified at startup, if any."""
1099 return self._board
1100
Wai-Hong Tam416cf612017-09-19 11:39:21 -07001101 def get_base_board(self):
1102 """Returns the board name of the base if present.
1103
1104 Returns:
1105 A string of the board name, or '' if not present.
1106 """
1107 # The value is set in servo_postinit.
1108 return self._base_board
1109
Simran Basia23c1392013-08-06 14:59:10 -07001110 def get_version(self):
1111 """Get servo board version."""
1112 return self._version
1113
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001114 def power_long_press(self):
1115 """Simulate a long power button press."""
1116 # After a long power press, the EC may ignore the next power
1117 # button press (at least on Alex). To guarantee that this
1118 # won't happen, we need to allow the EC one second to
1119 # collect itself.
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +08001120 return self.set('power_key', 'long_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001121
1122 def power_normal_press(self):
1123 """Simulate a normal power button press."""
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +08001124 return self.set('power_key', 'press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001125
1126 def power_short_press(self):
1127 """Simulate a short power button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301128 return self.set('power_key', 'short_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001129
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301130 def power_key(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001131 """Simulate a power button press.
1132
1133 Args:
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301134 press_secs: Time in seconds to simulate the keypress.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001135 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301136 return self.set('power_key', 'press' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001137
1138 def ctrl_d(self, press_secs=''):
1139 """Simulate Ctrl-d simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301140 return self.set('ctrl_d', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001141
Victor Dodone539cea2016-03-29 18:50:17 -07001142 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001143 """Simulate Ctrl-u simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301144 return self.set('ctrl_u', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001145
1146 def ctrl_enter(self, press_secs=''):
1147 """Simulate Ctrl-enter simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301148 return self.set('ctrl_enter', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001149
1150 def d_key(self, press_secs=''):
1151 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301152 return self.set('d_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001153
1154 def ctrl_key(self, press_secs=''):
1155 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301156 return self.set('ctrl_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001157
1158 def enter_key(self, press_secs=''):
1159 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301160 return self.set('enter_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001161
1162 def refresh_key(self, press_secs=''):
1163 """Simulate Refresh key (F3) button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301164 return self.set('refresh_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001165
1166 def ctrl_refresh_key(self, press_secs=''):
1167 """Simulate Ctrl and Refresh (F3) simultaneous press.
1168
1169 This key combination is an alternative of Space key.
1170 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301171 return self.set('ctrl_refresh_key', ('tab' if press_secs is '' else
1172 press_secs))
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001173
1174 def imaginary_key(self, press_secs=''):
1175 """Simulate imaginary key button press.
1176
1177 Maps to a key that doesn't physically exist.
1178 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301179 return self.set('imaginary_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -08001180
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001181 def sysrq_x(self, press_secs=''):
1182 """Simulate Alt VolumeUp X simultaneous press.
1183
1184 This key combination is the kernel system request (sysrq) x.
1185 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +05301186 return self.set('sysrq_x', 'tab' if press_secs is '' else press_secs)
Vincent Palatin3acbbe52016-07-19 17:40:12 +02001187
Kevin Cheng4b4f0022016-09-09 02:37:07 -07001188 def get_servo_serials(self):
1189 """Return all the serials associated with this process."""
1190 return self._serialnames
1191
1192
Todd Broche505b8d2011-03-21 18:19:54 -07001193def test():
1194 """Integration testing.
1195
1196 TODO(tbroch) Enhance integration test and add unittest (see mox)
1197 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001198 logging.basicConfig(
1199 level=logging.DEBUG,
1200 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -07001201 # configure server & listen
1202 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -07001203 # 5 == number of interfaces on a FT4232H device
1204 for i in xrange(1, 5):
1205 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -07001206 # its an i2c interface ... see __init__ for details and TODO to make
1207 # this configureable
1208 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
1209 else:
1210 # its a gpio interface
1211 servod_obj._interface_list[i].wr_rd(0)
1212
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001213 server = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost', 9999),
Todd Broche505b8d2011-03-21 18:19:54 -07001214 allow_none=True)
1215 server.register_introspection_functions()
1216 server.register_multicall_functions()
1217 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001218 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -07001219 server.serve_forever()
1220
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001221
1222if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -07001223 test()
1224
1225 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -07001226 """remote_uri = 'http://localhost:9999' client = xmlrpclib.ServerProxy(remote_uri, verbose=False) send_str = "Hello_there" print "Sent " + send_str + ", Recv " + client.echo(send_str)
1227
Todd Broche505b8d2011-03-21 18:19:54 -07001228 """