blob: 7542f369349eb6bc6607dd8588ecdcab9cab99a4 [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."""
Todd Broche505b8d2011-03-21 18:19:54 -07005import logging
Ruben Rodriguez Buchillon529b0de2020-03-20 18:33:36 -07006import os
7import re
8try:
9 from SimpleXMLRPCServer import SimpleXMLRPCServer
10except ImportError:
11 from xmlrpc.server import SimpleXMLRPCServer
12 # TODO(crbug.com/999878): This is for python3 compatibility.
13 # Remove once fully moved to python3.
14import time
15import usb
Todd Broche505b8d2011-03-21 18:19:54 -070016
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080017import drv as servo_drv
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080018import interface as _interface
Mary Ruthvencb861852019-07-15 16:30:48 -070019import servo_dev
Simran Basie750a342013-03-12 13:45:26 -070020import servo_interfaces
Dana Goyette91cae862020-02-21 13:43:13 -080021import servo_logging
Kevin Cheng16304d12016-07-08 11:56:55 -070022import servo_postinit
Todd Broche505b8d2011-03-21 18:19:54 -070023
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080024HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080025
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070026
Todd Broche505b8d2011-03-21 18:19:54 -070027class ServodError(Exception):
28 """Exception class for servod."""
29
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070030
Todd Broche505b8d2011-03-21 18:19:54 -070031class Servod(object):
32 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070033
Kevin Cheng4b4f0022016-09-09 02:37:07 -070034 # This is the key to get the main serial used in the _serialnames dict.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070035 MAIN_SERIAL = 'main'
36 SERVO_MICRO_SERIAL = 'servo_micro'
37 CCD_SERIAL = 'ccd'
Kevin Cheng4b4f0022016-09-09 02:37:07 -070038
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080039 # Timeout to wait for interfaces to become available again if reinitialization
Mary Ruthvenb7cc5542019-07-15 15:20:10 -070040 # is taking place. In seconds. This is supposed to recover from brief resets.
41 # If the interface disappears for more than 5 seconds, then someone probably
42 # intentionally disconnected the device. Servod shouldn't be responsible for
43 # waiting for the device during an intentional disconnect.
44 INTERFACE_AVAILABILITY_TIMEOUT = 5
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080045
Dana Goyette4a61e902020-05-08 10:09:31 -070046 # Exceptions to count as known or ordinary. Any errors that aren't instances
47 # of these (or their subclasses) will be logged with "Please take a look."
48 KNOWN_EXCEPTIONS = (AttributeError, NameError, HwDriverError)
49
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070050 def init_servo_interfaces(self, vendor, product, serialname, interfaces):
Kevin Chengdc3befd2016-07-15 12:34:00 -070051 """Init the servo interfaces with the given interfaces.
52
53 We don't use the self._{vendor,product,serialname} attributes because we
54 want to allow other callers to initialize other interfaces that may not
55 be associated with the initialized attributes (e.g. a servo v4 servod object
56 that wants to also initialize a servo micro interface).
57
58 Args:
59 vendor: USB vendor id of FTDI device.
60 product: USB product id of FTDI device.
61 serialname: String of device serialname/number as defined in FTDI
62 eeprom.
63 interfaces: List of strings of interface types the server will
64 instantiate.
65
66 Raises:
67 ServodError if unable to locate init method for particular interface.
68 """
Mary Ruthven13389642017-02-14 12:15:34 -080069 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070070 device = (vendor, product, serialname)
Mary Ruthvencb861852019-07-15 16:30:48 -070071 self.add_device(device)
Mary Ruthven13389642017-02-14 12:15:34 -080072
Kevin Chengdc3befd2016-07-15 12:34:00 -070073 # Extend the interface list if we need to.
74 interfaces_len = len(interfaces)
75 interface_list_len = len(self._interface_list)
76 if interfaces_len > interface_list_len:
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080077 # Fill with dummies.
78 self._interface_list += [_interface.dummy.Dummy()] * (interfaces_len -
79 interface_list_len)
Kevin Chengdc3befd2016-07-15 12:34:00 -070080
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080081 for i, interface_data in enumerate(interfaces):
82 if type(interface_data) is dict:
83 name = interface_data['name']
Kevin Chengdc3befd2016-07-15 12:34:00 -070084 # Store interface index for those that care about it.
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080085 interface_data['index'] = i
86 elif type(interface_data) is str:
87 if interface_data in ['dummy', 'ftdi_dummy']:
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -070088 # 'dummy' reserves the interface for future use. Typically the
89 # interface will be managed by external third-party tools like
90 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
91 # it serves as a placeholder for servo micro interfaces.
92 continue
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080093 name = interface_data
Kevin Chengdc3befd2016-07-15 12:34:00 -070094 else:
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080095 raise ServodError('Illegal interface data type %s'
96 % type(interface_data))
Kevin Chengdc3befd2016-07-15 12:34:00 -070097
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070098 self._logger.info('Initializing interface %d to %s', i, name)
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080099 result = _interface.Build(name=name, index=i, vid=vendor, pid=product,
100 sid=serialname, interface_data=interface_data,
101 servod=self)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700102 if isinstance(result, tuple):
103 result_len = len(result)
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700104 self._interface_list[i:(i + result_len)] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700105 else:
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700106 self._interface_list[i] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700107
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700108 def __init__(self, config, vendor, product, serialname=None, interfaces=None,
Namyoon Woo341a8332019-03-07 12:01:31 -0800109 board='', model='', version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700110 """Servod constructor.
111
112 Args:
113 config: instance of SystemConfig containing all controls for
114 particular Servod invocation
115 vendor: usb vendor id of FTDI device
116 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700117 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700118 interfaces: list of strings of interface types the server will instantiate
Namyoon Woo341a8332019-03-07 12:01:31 -0800119 board: board name. e.g. octopus, coral, or scarlet.
120 model: model name of a given board. e.g. fleex, ampton, or apel.
Simran Basia23c1392013-08-06 14:59:10 -0700121 version: String. Servo board version. Examples: servo_v1, servo_v2,
122 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800123 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700124 sending keyboard commands to DUTs that do not have built in
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700125 keyboards. Used in FAFT tests. Use None for on board AVR MCU.
126 e.g. '/dev/ttyUSB0' or None.
Todd Brochdbb09982011-10-02 07:14:26 -0700127
128 Raises:
129 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700130 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700131 self._logger = logging.getLogger('Servod')
132 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700133 self._vendor = vendor
134 self._product = product
Mary Ruthvencb861852019-07-15 16:30:48 -0700135 self._devices = {}
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700136 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700137 self._syscfg = config
138 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
139 # interfaces are mapped to
140 self._interface_list = []
141 # Dict of Dict to map control name, function name to to tuple (params, drv)
142 # Ex) _drv_dict[name]['get'] = (params, drv)
143 self._drv_dict = {}
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700144 self._base_board = ''
Namyoon Woo341a8332019-03-07 12:01:31 -0800145 self._board = board
146 if model:
147 self._board += '_' + model
148 self._model = model
Simran Basia23c1392013-08-06 14:59:10 -0700149 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800150 self._usbkm232 = usbkm232
Ruben Rodriguez Buchillon386a0102018-08-16 09:11:20 +0800151 self._keyboard = None
152 self._usb_keyboard = None
Todd Brochdbb09982011-10-02 07:14:26 -0700153 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700154 try:
155 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
156 except KeyError:
157 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Dino Lic89d8c82018-01-11 09:56:47 +0800158 self._interfaces = interfaces
Todd Brochdbb09982011-10-02 07:14:26 -0700159
Kevin Chengdc3befd2016-07-15 12:34:00 -0700160 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700161 servo_postinit.post_init(self)
Danny Chan662b6022015-11-04 17:34:53 -0800162
Mary Ruthven13389642017-02-14 12:15:34 -0800163 def reinitialize(self):
164 """Reinitialize all interfaces that support reinitialization"""
Mary Ruthven13389642017-02-14 12:15:34 -0800165 for i, interface in enumerate(self._interface_list):
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -0800166 interface.reinitialize()
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800167 # Indicate interfaces are safe to use again.
Mary Ruthvencb861852019-07-15 16:30:48 -0700168 for device in self._devices.values():
169 device.connect()
Mary Ruthven13389642017-02-14 12:15:34 -0800170
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700171 def get_servo_interfaces(self, position, size):
172 """Get the list of servo interfaces.
173
174 Args:
175 position: The index the first interface to get.
176 size: The number of the interfaces.
177 """
178 return self._interface_list[position:(position + size)]
179
180 def set_servo_interfaces(self, position, interfaces):
181 """Set the list of servo interfaces.
182
183 Args:
184 position: The index the first interface to set.
185 interfaces: The list of interfaces to set.
186 """
187 size = len(interfaces)
188 self._interface_list[position:(position + size)] = interfaces
189
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700190 def close(self):
191 """Servod turn down logic."""
192 for i, interface in enumerate(self._interface_list):
193 self._logger.info('Turning down interface %d' % i)
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -0800194 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800195
Mary Ruthvencb861852019-07-15 16:30:48 -0700196 def get_devices(self):
197 return self._devices.values()
198
199 def add_device(self, device):
200 if device not in self._devices:
201 vid, pid, serial = device
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700202 servod_device = servo_dev.ServoDevice(vid, pid, serial)
Mary Ruthvencb861852019-07-15 16:30:48 -0700203 self._devices[device] = servod_device
204
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800205 def _camel_case(self, string):
206 output = ''
207 for s in string.split('_'):
208 if output:
209 output += s.capitalize()
210 else:
211 output = s
212 return output
213
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700214 def clear_cached_drv(self):
215 """Clear the cached drivers.
216
217 The drivers are cached in the Dict _drv_dict when a control is got or set.
218 When the servo interfaces are relocated, the cached values may become wrong.
219 Should call this method to clear the cached values.
220 """
221 self._drv_dict = {}
222
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800223 def _get_servo_specific_param(self, params, param_key, control_name):
224 """Get |param_key| from params by looking for servo specific params first.
225
226 Find the candidate servos. Using servo_v4 with a servo_micro connected as
227 example, the following shows the priority for selecting the interface.
228
229 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
230 2. servo_micro_interface
231 3. servo_v4_interface
232 4. Fallback to the default, interface.
233
234 Args:
235 params: params dictionary for a control
236 param_key: identifier in the params dictionary to look for
237 control_name: control name the params correspond to
238
239 Returns:
240 The best suited param value for param_key given the servo type or
241 None if even the default is not defined.
242 """
243 candidates = [self._version]
Ruben Rodriguez Buchillond18c6eb2019-07-10 14:40:22 -0700244 if '_with_' in self._version:
245 v4, raw_dut_device = self._version.split('_with_')
246 dut_devices = raw_dut_device.split('_and_')
247 # NOTE(coconutruben): all of this nonsense is going away with the new
248 # servod and is to bridge the time until then. Please forgive the below
249 # until then.
250 if '.' in control_name:
251 # In the current implementation, the only case where a '.' (a prefix)
252 # is in the control name is when there is a dual instance with micro and
253 # ccd on a v4.
254 dut_device = dut_devices[1]
255 else:
256 # In the normal control name, we need to make sure the version used
257 # does not include the potential _and_ portion from a dual instance.
258 dut_device = dut_devices[0]
259 candidates.extend([dut_device, v4])
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800260 candidates = ['%s_%s' % (c, param_key) for c in candidates]
261 candidates.append(param_key)
262 for c in candidates:
263 if c in params:
264 self._logger.debug('Using %s parameter.', c)
265 return params[c]
266 self._logger.error('Unable to determine %s for %s', param_key, control_name)
267 self._logger.error('params: %r', params)
268 return None
269
Todd Broche505b8d2011-03-21 18:19:54 -0700270 def _get_param_drv(self, control_name, is_get=True):
271 """Get access to driver for a given control.
272
273 Note, some controls have different parameter dictionaries for 'getting' the
274 control's value versus 'setting' it. Boolean is_get distinguishes which is
275 being requested.
276
277 Args:
278 control_name: string name of control
279 is_get: boolean to determine
280
281 Returns:
Fei Shao8aec57b2019-12-11 17:08:40 +0800282 tuple (params, drv, device_info) where:
283 params: param dictionary for control
Todd Broche505b8d2011-03-21 18:19:54 -0700284 drv: instance object of driver for particular control
Fei Shao8aec57b2019-12-11 17:08:40 +0800285 device_info: servo device information
Todd Broche505b8d2011-03-21 18:19:54 -0700286
287 Raises:
288 ServodError: Error occurred while examining params dict
289 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700290 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700291 # if already setup just return tuple from driver dict
292 if control_name in self._drv_dict:
293 if is_get and ('get' in self._drv_dict[control_name]):
294 return self._drv_dict[control_name]['get']
295 if not is_get and ('set' in self._drv_dict[control_name]):
296 return self._drv_dict[control_name]['set']
297
298 params = self._syscfg.lookup_control_params(control_name, is_get)
Simran Basi668be0e2013-08-07 11:54:50 -0700299
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800300 # Get the most suitable drv given the servo instance.
301 drv_name = self._get_servo_specific_param(params, 'drv', control_name)
302 if drv_name == 'na':
303 # 'na' drv can be used to selectively turn controls into noops for
304 # a given servo hardware. Ensure that there is an interface.
305 params.setdefault('interface', 'servo')
306 self._logger.debug('Setting interface to default to %r for %r unless '
307 ' defined in params, as drv is %r.', 'servo',
308 control_name, 'na')
309 # Setting input_type to str allows all inputs through enabling a true noop
310 params.update({'input_type': 'str'})
311 interface_id = self._get_servo_specific_param(params, 'interface',
312 control_name)
313 if None in [drv_name, interface_id]:
314 raise ServodError('No drv/interface for control %r found' % control_name)
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700315
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800316 if interface_id == 'servo':
317 interface = self
Simran Basi668be0e2013-08-07 11:54:50 -0700318 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700319 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800320 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700321
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700322 device_info = None
323 if hasattr(interface, 'get_device_info'):
324 device_info = interface.get_device_info()
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800325 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800326 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700327 drv = drv_class(interface, params)
328 if control_name not in self._drv_dict:
329 self._drv_dict[control_name] = {}
330 if is_get:
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700331 self._drv_dict[control_name]['get'] = (params, drv, device_info)
Todd Broche505b8d2011-03-21 18:19:54 -0700332 else:
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700333 self._drv_dict[control_name]['set'] = (params, drv, device_info)
334 return (params, drv, device_info)
Todd Broche505b8d2011-03-21 18:19:54 -0700335
336 def doc_all(self):
337 """Return all documenation for controls.
338
339 Returns:
340 string of <doc> text in config file (xml) and the params dictionary for
341 all controls.
342
343 For example:
344 warm_reset :: Reset the device warmly
345 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
346 """
347 return self._syscfg.display_config()
348
349 def doc(self, name):
350 """Retreive doc string in system config file for given control name.
351
352 Args:
353 name: name string of control to get doc string
354
355 Returns:
356 doc string of name
357
358 Raises:
359 NameError: if fails to locate control
360 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700361 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700362 if self._syscfg.is_control(name):
363 return self._syscfg.get_control_docstring(name)
364 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700365 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700366
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800367 def safe_switch_usbkey_power(self, power_state, _=None):
Kevin Cheng5595b342016-09-29 15:51:01 -0700368 """Toggle the usb power safely.
369
Kevin Chengc49494e2016-07-25 12:13:38 -0700370 Args:
Kevin Cheng5595b342016-09-29 15:51:01 -0700371 power_state: The setting to set for the usbkey power.
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800372 _: to conform to current API
Kevin Chengc49494e2016-07-25 12:13:38 -0700373
Kevin Cheng5595b342016-09-29 15:51:01 -0700374 Returns:
375 An empty string to appease the xmlrpc gods.
376 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800377 self.set('image_usbkey_pwr', power_state)
Kevin Cheng5595b342016-09-29 15:51:01 -0700378 return ''
379
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800380 def safe_switch_usbkey(self, mux_direction, _=0):
Kevin Cheng5595b342016-09-29 15:51:01 -0700381 """Toggle the usb direction safely.
382
Kevin Cheng5595b342016-09-29 15:51:01 -0700383 Args:
Wai-Hong Tamf93f9a22018-02-06 14:24:46 -0800384 mux_direction: "servo_sees_usbkey" or "dut_sees_usbkey".
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800385 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700386
387 Returns:
388 An empty string to appease the xmlrpc gods.
389 """
Ruben Rodriguez Buchillon247d88f2018-08-03 18:07:01 +0800390 self.set('image_usbkey_direction', mux_direction)
Kevin Cheng5595b342016-09-29 15:51:01 -0700391 return ''
392
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800393 def probe_host_usb_dev(self, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700394 """Probe the USB disk device plugged in the servo from the host side.
395
Kevin Cheng5595b342016-09-29 15:51:01 -0700396 Args:
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800397 _: to conform to current API
Kevin Cheng5595b342016-09-29 15:51:01 -0700398
Simran Basia9f41032012-05-11 14:21:58 -0700399 Returns:
Kevin Chengc49494e2016-07-25 12:13:38 -0700400 USB disk path if one and only one USB disk path is found, otherwise an
Simran Basia9f41032012-05-11 14:21:58 -0700401 """
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800402 return self.get('image_usbkey_dev')
Kevin Chengc49494e2016-07-25 12:13:38 -0700403
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800404 def download_image_to_usb(self, image_path, _=0):
Simran Basia9f41032012-05-11 14:21:58 -0700405 """Download image and save to the USB device found by probe_host_usb_dev.
406 If the image_path is a URL, it will download this url to the USB path;
407 otherwise it will simply copy the image_path's contents to the USB path.
408
409 Args:
410 image_path: path or url to the recovery image.
Ruben Rodriguez Buchillon68958f82018-08-03 18:24:28 +0800411 _: to conform to current API
Simran Basia9f41032012-05-11 14:21:58 -0700412
413 Returns:
414 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800415 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700416 """
Simran Basia9f41032012-05-11 14:21:58 -0700417 try:
Ruben Rodriguez Buchillon4e00f0e2018-08-28 15:21:47 +0800418 self.set('download_image_to_usb_dev', image_path)
419 return True
420 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700421 return False
Simran Basia9f41032012-05-11 14:21:58 -0700422
423 def make_image_noninteractive(self):
424 """Makes the recovery image noninteractive.
425
426 A noninteractive image will reboot automatically after installation
427 instead of waiting for the USB device to be removed to initiate a system
428 reboot.
429
430 Mounts partition 1 of the image stored on usb_dev and creates a file
431 called "non_interactive" so that the image will become noninteractive.
432
433 Returns:
434 True|False: True if process completed successfully, False if error
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800435 occurred.
Simran Basia9f41032012-05-11 14:21:58 -0700436 """
Ruben Rodriguez Buchillon1a3a7ec2018-08-03 18:44:55 +0800437 try:
438 usb_dev = self.get('image_usbkey_dev')
439 usb_dev_partition = '%s1' % usb_dev
440 self.set('make_usb_dev_image_noninteractive', usb_dev_partition)
441 return True
442 except Exception:
Simran Basia9f41032012-05-11 14:21:58 -0700443 return False
Simran Basia9f41032012-05-11 14:21:58 -0700444
Todd Broch352b4b22013-03-22 09:48:40 -0700445 def set_get_all(self, cmds):
446 """Set &| get one or more control values.
447
448 Args:
449 cmds: list of control[:value] to get or set.
450
451 Returns:
452 rv: list of responses from calling get or set methods.
453 """
454 rv = []
455 for cmd in cmds:
456 if ':' in cmd:
Wai-Hong Tam269f1802019-05-16 12:37:17 -0700457 (control, value) = cmd.split(':', 1)
Todd Broch352b4b22013-03-22 09:48:40 -0700458 rv.append(self.set(control, value))
459 else:
460 rv.append(self.get(cmd))
461 return rv
462
Mary Ruthven493df512019-07-12 13:10:18 -0700463 def add_serial_number(self, name, serial_number):
464 """Adds the serial number to the _serialnames dictionary.
465
466 Args:
467 name: A string which is the key into the _serialnames dictionary.
468 serial_number: A string which is the key into the _serialnames dictionary.
469 """
470 self._serialnames[name] = serial_number
471 self._logger.debug('Added %s %s to serialnames %r', name, serial_number,
472 self._serialnames)
473
Aseda Aboagye6921f602017-08-01 14:45:38 -0700474 def get_serial_number(self, name):
475 """Returns the desired serial number from the serialnames dict.
476
477 Args:
478 name: A string which is the key into the _serialnames dictionary.
479
480 Returns:
481 A string containing the serial number or "unknown".
482 """
Mary Ruthvenf17fb172019-08-15 17:17:35 -0700483 # Remove the prefix from the serialname control. Serialnames are
484 # universal. It doesn't matter what the prefix is.
485 # The prefix is separated from the main control with '.'
486 name = name.split('.', 1)[-1]
487
Aseda Aboagye6921f602017-08-01 14:45:38 -0700488 if not name:
489 name = 'main'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700490 try:
491 return self._serialnames[name]
492 except KeyError:
493 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700494 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700495
Todd Broche505b8d2011-03-21 18:19:54 -0700496 def get(self, name):
497 """Get control value.
498
499 Args:
500 name: name string of control
501
502 Returns:
503 Response from calling drv get method. Value is reformatted based on
504 control's dictionary parameters
505
506 Raises:
507 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800508 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700509 """
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700510 if 'serialname' in name:
Dana Goyette91cae862020-02-21 13:43:13 -0800511 # This route is to retrieve serialnames on servo v4, which
512 # connects to multiple servo-micros or CCD, like the controls,
513 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
514 # TODO(aaboagye): Refactor it.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700515 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700516
Dana Goyette17b0d252020-03-09 10:32:50 -0700517 with servo_logging.WrapGetCall(
Dana Goyette4a61e902020-05-08 10:09:31 -0700518 name, known_exceptions=self.KNOWN_EXCEPTIONS) as wrapper:
Dana Goyette91cae862020-02-21 13:43:13 -0800519 (params, drv, device) = self._get_param_drv(name)
520 if device in self._devices:
521 self._devices[device].wait(self.INTERFACE_AVAILABILITY_TIMEOUT)
522
Todd Broche505b8d2011-03-21 18:19:54 -0700523 val = drv.get()
Fei Shao8aec57b2019-12-11 17:08:40 +0800524 rd_val = self._syscfg.reformat_val(params, val)
Dana Goyette91cae862020-02-21 13:43:13 -0800525 wrapper.got_result(rd_val)
Todd Broche505b8d2011-03-21 18:19:54 -0700526 return rd_val
Todd Brochd6061672012-05-11 15:52:47 -0700527
Todd Broche505b8d2011-03-21 18:19:54 -0700528 def get_all(self, verbose):
529 """Get all controls values.
530
531 Args:
532 verbose: Boolean on whether to return doc info as well
533
534 Returns:
535 string creating from trying to get all values of all controls. In case of
536 error attempting access to control, response is 'ERR'.
537 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800538 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700539 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700540 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700541 try:
542 value = self.get(name)
543 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700544 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -0700545 pass
546 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700547 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700548 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700549 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800550 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700551
552 def set(self, name, wr_val_str):
553 """Set control.
554
555 Args:
556 name: name string of control
557 wr_val_str: value string to write. Can be integer, float or a
558 alpha-numerical that is mapped to a integer or float.
559
560 Raises:
561 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800562 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700563 """
Dana Goyette17b0d252020-03-09 10:32:50 -0700564 with servo_logging.WrapSetCall(
Dana Goyette4a61e902020-05-08 10:09:31 -0700565 name, wr_val_str, known_exceptions=self.KNOWN_EXCEPTIONS):
Dana Goyette91cae862020-02-21 13:43:13 -0800566 (params, drv, device) = self._get_param_drv(name, False)
567 if device in self._devices:
568 self._devices[device].wait(self.INTERFACE_AVAILABILITY_TIMEOUT)
569 wr_val = self._syscfg.resolve_val(params, wr_val_str)
570
Todd Broche505b8d2011-03-21 18:19:54 -0700571 drv.set(wr_val)
Dana Goyette91cae862020-02-21 13:43:13 -0800572
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +0800573 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
574 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -0700575 # marshall/unmarshall
576 return True
577
Todd Brochd6061672012-05-11 15:52:47 -0700578 def hwinit(self, verbose=False):
579 """Initialize all controls.
580
581 These values are part of the system config XML files of the form
582 init=<value>. This command should be used by clients wishing to return the
583 servo and DUT its connected to a known good/safe state.
584
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800585 Note that initialization errors are ignored (as in some cases they could
586 be caused by DUT firmware deficiencies). This might need to be fine tuned
587 later.
588
Todd Brochd6061672012-05-11 15:52:47 -0700589 Args:
590 verbose: boolean, if True prints info about control initialized.
591 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800592
593 Returns:
594 This function is called across RPC and as such is expected to return
595 something unless transferring 'none' across is allowed. Hence adding a
596 dummy return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700597 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800598 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800599 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700600 # Workaround for bug chrome-os-partner:42349. Without this check, the
601 # gpio will briefly pulse low if we set it from high to high.
602 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700603 self.set(control_name, value)
604 if verbose:
605 self._logger.info('Initialized %s to %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700606 except Exception as e:
607 self._logger.error(
Matthew Bleckera5d979c2018-10-16 20:59:19 -0700608 'Problem initializing %s -> %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700609 self._logger.error(str(e))
610 self._logger.error('Please consider verifying the logs and if the '
611 'error is not just a setup issue, consider filing '
612 'a bug. Also checkout go/servo-ki.')
Nick Sandersbc836282015-12-08 21:19:23 -0800613
Namyoon Woo6ff36612019-10-16 16:41:12 -0700614 # If there is the control of 'active_v4_device', set active_v4_device to
615 # the default device as initialization.
Namyoon Wooad2a2bb2019-11-04 16:26:15 -0800616 try:
Mary Ruthvenf547c082020-05-07 11:32:28 -0700617 if self._syscfg.is_control('active_v4_device'):
618 self.set('active_v4_device', 'default')
Todd Brocha10cba12019-11-25 16:00:35 -0800619 except servo_drv.active_v4_device.activeV4DeviceError as e:
Mary Ruthvenf547c082020-05-07 11:32:28 -0700620 self._logger.debug('Could not set active device: %s', str(e))
Namyoon Woo6ff36612019-10-16 16:41:12 -0700621
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800622 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800623
Todd Broche505b8d2011-03-21 18:19:54 -0700624 def echo(self, echo):
625 """Dummy echo function for testing/examples.
626
627 Args:
628 echo: string to echo back to client
629 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700630 self._logger.debug('echo(%s)' % (echo))
631 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -0700632
J. Richard Barnettee2820552013-03-14 16:13:46 -0700633 def get_board(self):
634 """Return the board specified at startup, if any."""
635 return self._board
636
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700637 def get_base_board(self):
638 """Returns the board name of the base if present.
639
640 Returns:
641 A string of the board name, or '' if not present.
642 """
643 # The value is set in servo_postinit.
644 return self._base_board
645
Simran Basia23c1392013-08-06 14:59:10 -0700646 def get_version(self):
647 """Get servo board version."""
648 return self._version
649
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800650 def power_long_press(self):
651 """Simulate a long power button press."""
652 # After a long power press, the EC may ignore the next power
653 # button press (at least on Alex). To guarantee that this
654 # won't happen, we need to allow the EC one second to
655 # collect itself.
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800656 return self.set('power_key', 'long_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800657
658 def power_normal_press(self):
659 """Simulate a normal power button press."""
Ruben Rodriguez Buchillon0f467942018-07-27 18:02:32 +0800660 return self.set('power_key', 'press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800661
662 def power_short_press(self):
663 """Simulate a short power button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530664 return self.set('power_key', 'short_press')
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800665
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530666 def power_key(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800667 """Simulate a power button press.
668
669 Args:
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530670 press_secs: Time in seconds to simulate the keypress.
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800671 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530672 return self.set('power_key', 'press' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800673
674 def ctrl_d(self, press_secs=''):
675 """Simulate Ctrl-d simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530676 return self.set('ctrl_d', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800677
Victor Dodone539cea2016-03-29 18:50:17 -0700678 def ctrl_u(self, press_secs=''):
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800679 """Simulate Ctrl-u simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530680 return self.set('ctrl_u', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800681
682 def ctrl_enter(self, press_secs=''):
683 """Simulate Ctrl-enter simultaneous button presses."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530684 return self.set('ctrl_enter', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800685
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800686 def ctrl_key(self, press_secs=''):
687 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530688 return self.set('ctrl_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800689
690 def enter_key(self, press_secs=''):
691 """Simulate Enter key button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530692 return self.set('enter_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800693
694 def refresh_key(self, press_secs=''):
695 """Simulate Refresh key (F3) button press."""
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530696 return self.set('refresh_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800697
698 def ctrl_refresh_key(self, press_secs=''):
699 """Simulate Ctrl and Refresh (F3) simultaneous press.
700
701 This key combination is an alternative of Space key.
702 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530703 return self.set('ctrl_refresh_key', ('tab' if press_secs is '' else
704 press_secs))
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800705
706 def imaginary_key(self, press_secs=''):
707 """Simulate imaginary key button press.
708
709 Maps to a key that doesn't physically exist.
710 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530711 return self.set('imaginary_key', 'tab' if press_secs is '' else press_secs)
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800712
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200713 def sysrq_x(self, press_secs=''):
714 """Simulate Alt VolumeUp X simultaneous press.
715
716 This key combination is the kernel system request (sysrq) x.
717 """
Lenine Ajagappane400d7d22018-09-05 02:29:21 +0530718 return self.set('sysrq_x', 'tab' if press_secs is '' else press_secs)
Vincent Palatin3acbbe52016-07-19 17:40:12 +0200719
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700720 def get_servo_serials(self):
721 """Return all the serials associated with this process."""
722 return self._serialnames
723
724
Todd Broche505b8d2011-03-21 18:19:54 -0700725def test():
726 """Integration testing.
727
728 TODO(tbroch) Enhance integration test and add unittest (see mox)
729 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700730 logging.basicConfig(
731 level=logging.DEBUG,
732 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -0700733 # configure server & listen
734 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700735 # 5 == number of interfaces on a FT4232H device
Ruben Rodriguez Buchillon50f35602020-03-20 18:41:19 -0700736 for i in range(1, 5):
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700737 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -0700738 # its an i2c interface ... see __init__ for details and TODO to make
739 # this configureable
740 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
741 else:
742 # its a gpio interface
743 servod_obj._interface_list[i].wr_rd(0)
744
Ruben Rodriguez Buchillon529b0de2020-03-20 18:33:36 -0700745 server = SimpleXMLRPCServer(('localhost', 9999), allow_none=True)
Todd Broche505b8d2011-03-21 18:19:54 -0700746 server.register_introspection_functions()
747 server.register_multicall_functions()
748 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700749 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -0700750 server.serve_forever()
751
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700752
753if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -0700754 test()
755
756 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700757 """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)
758
Todd Broche505b8d2011-03-21 18:19:54 -0700759 """