blob: 2757f627461bc97f2bbcb4f27fe2560b8ef44a28 [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
Matthew Blecker6b250ff2020-08-23 12:00:55 -070016import weakref
Todd Broche505b8d2011-03-21 18:19:54 -070017
Ruben Rodriguez Buchillon4386b622020-11-18 14:00:13 -080018from . import drv as servo_drv
19from . import interface as _interface
20from . import servo_dev
21from . import servo_interfaces
22from . import servo_logging
23from . import servo_postinit
Todd Broche505b8d2011-03-21 18:19:54 -070024
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080025HwDriverError = servo_drv.hw_driver.HwDriverError
Aseda Aboagyea4922212015-11-20 15:19:08 -080026
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070027
Todd Broche505b8d2011-03-21 18:19:54 -070028class ServodError(Exception):
29 """Exception class for servod."""
30
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070031
Todd Broche505b8d2011-03-21 18:19:54 -070032class Servod(object):
33 """Main class for Servo debug/controller Daemon."""
Simran Basia9f41032012-05-11 14:21:58 -070034
Kevin Cheng4b4f0022016-09-09 02:37:07 -070035 # This is the key to get the main serial used in the _serialnames dict.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070036 MAIN_SERIAL = 'main'
37 SERVO_MICRO_SERIAL = 'servo_micro'
Matthew Blecker8ce0ddc2020-11-02 17:19:25 -080038 C2D2_SERIAL = 'c2d2'
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070039 CCD_SERIAL = 'ccd'
Kevin Cheng4b4f0022016-09-09 02:37:07 -070040
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080041 # Timeout to wait for interfaces to become available again if reinitialization
Mary Ruthvenb7cc5542019-07-15 15:20:10 -070042 # is taking place. In seconds. This is supposed to recover from brief resets.
43 # If the interface disappears for more than 5 seconds, then someone probably
44 # intentionally disconnected the device. Servod shouldn't be responsible for
45 # waiting for the device during an intentional disconnect.
46 INTERFACE_AVAILABILITY_TIMEOUT = 5
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080047
Dana Goyette4a61e902020-05-08 10:09:31 -070048 # Exceptions to count as known or ordinary. Any errors that aren't instances
49 # of these (or their subclasses) will be logged with "Please take a look."
50 KNOWN_EXCEPTIONS = (AttributeError, NameError, HwDriverError)
51
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070052 def init_servo_interfaces(self, vendor, product, serialname, interfaces):
Kevin Chengdc3befd2016-07-15 12:34:00 -070053 """Init the servo interfaces with the given interfaces.
54
55 We don't use the self._{vendor,product,serialname} attributes because we
56 want to allow other callers to initialize other interfaces that may not
57 be associated with the initialized attributes (e.g. a servo v4 servod object
58 that wants to also initialize a servo micro interface).
59
60 Args:
61 vendor: USB vendor id of FTDI device.
62 product: USB product id of FTDI device.
63 serialname: String of device serialname/number as defined in FTDI
64 eeprom.
65 interfaces: List of strings of interface types the server will
66 instantiate.
67
68 Raises:
69 ServodError if unable to locate init method for particular interface.
70 """
Mary Ruthven13389642017-02-14 12:15:34 -080071 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070072 device = (vendor, product, serialname)
Mary Ruthvencb861852019-07-15 16:30:48 -070073 self.add_device(device)
Mary Ruthven13389642017-02-14 12:15:34 -080074
Kevin Chengdc3befd2016-07-15 12:34:00 -070075 # Extend the interface list if we need to.
76 interfaces_len = len(interfaces)
77 interface_list_len = len(self._interface_list)
78 if interfaces_len > interface_list_len:
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080079 # Fill with dummies.
Sam Hurst2b487532020-08-05 11:00:23 -070080 self._interface_list += [_interface.empty.Empty()] * (interfaces_len -
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080081 interface_list_len)
Kevin Chengdc3befd2016-07-15 12:34:00 -070082
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080083 for i, interface_data in enumerate(interfaces):
84 if type(interface_data) is dict:
85 name = interface_data['name']
Kevin Chengdc3befd2016-07-15 12:34:00 -070086 # Store interface index for those that care about it.
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080087 interface_data['index'] = i
88 elif type(interface_data) is str:
Sam Hurst2b487532020-08-05 11:00:23 -070089 if interface_data in ['empty', 'ftdi_empty']:
90 # 'empty' reserves the interface for future use. Typically the
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -070091 # interface will be managed by external third-party tools like
92 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
93 # it serves as a placeholder for servo micro interfaces.
94 continue
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080095 name = interface_data
Kevin Chengdc3befd2016-07-15 12:34:00 -070096 else:
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080097 raise ServodError('Illegal interface data type %s'
98 % type(interface_data))
Kevin Chengdc3befd2016-07-15 12:34:00 -070099
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700100 self._logger.info('Initializing interface %d to %s', i, name)
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -0800101 result = _interface.Build(name=name, index=i, vid=vendor, pid=product,
102 sid=serialname, interface_data=interface_data,
103 servod=self)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700104 if isinstance(result, tuple):
105 result_len = len(result)
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700106 self._interface_list[i:(i + result_len)] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700107 else:
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700108 self._interface_list[i] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700109
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700110 def __init__(self, config, vendor, product, serialname=None, interfaces=None,
Namyoon Woo341a8332019-03-07 12:01:31 -0800111 board='', model='', version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700112 """Servod constructor.
113
114 Args:
115 config: instance of SystemConfig containing all controls for
116 particular Servod invocation
117 vendor: usb vendor id of FTDI device
118 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700119 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700120 interfaces: list of strings of interface types the server will instantiate
Namyoon Woo341a8332019-03-07 12:01:31 -0800121 board: board name. e.g. octopus, coral, or scarlet.
122 model: model name of a given board. e.g. fleex, ampton, or apel.
Simran Basia23c1392013-08-06 14:59:10 -0700123 version: String. Servo board version. Examples: servo_v1, servo_v2,
124 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800125 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700126 sending keyboard commands to DUTs that do not have built in
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700127 keyboards. Used in FAFT tests. Use None for on board AVR MCU.
128 e.g. '/dev/ttyUSB0' or None.
Todd Brochdbb09982011-10-02 07:14:26 -0700129
130 Raises:
131 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700132 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700133 self._logger = logging.getLogger('Servod')
134 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700135 self._vendor = vendor
136 self._product = product
Mary Ruthvencb861852019-07-15 16:30:48 -0700137 self._devices = {}
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700138 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700139 self._syscfg = config
140 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
141 # interfaces are mapped to
142 self._interface_list = []
143 # Dict of Dict to map control name, function name to to tuple (params, drv)
144 # Ex) _drv_dict[name]['get'] = (params, drv)
145 self._drv_dict = {}
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700146 self._base_board = ''
Namyoon Woo341a8332019-03-07 12:01:31 -0800147 self._board = board
148 if model:
149 self._board += '_' + model
150 self._model = model
Simran Basia23c1392013-08-06 14:59:10 -0700151 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800152 self._usbkm232 = usbkm232
Ruben Rodriguez Buchillon386a0102018-08-16 09:11:20 +0800153 self._keyboard = None
154 self._usb_keyboard = None
Todd Brochdbb09982011-10-02 07:14:26 -0700155 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700156 try:
157 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
158 except KeyError:
159 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Dino Lic89d8c82018-01-11 09:56:47 +0800160 self._interfaces = interfaces
Todd Brochdbb09982011-10-02 07:14:26 -0700161
Kevin Chengdc3befd2016-07-15 12:34:00 -0700162 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700163 servo_postinit.post_init(self)
Ruben Rodriguez Buchillon16e39eb2020-06-24 18:06:11 -0700164 self._syscfg.finalize()
Danny Chan662b6022015-11-04 17:34:53 -0800165
Mary Ruthven13389642017-02-14 12:15:34 -0800166 def reinitialize(self):
167 """Reinitialize all interfaces that support reinitialization"""
Mary Ruthven13389642017-02-14 12:15:34 -0800168 for i, interface in enumerate(self._interface_list):
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -0800169 interface.reinitialize()
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800170 # Indicate interfaces are safe to use again.
Mary Ruthvencb861852019-07-15 16:30:48 -0700171 for device in self._devices.values():
172 device.connect()
Mary Ruthven13389642017-02-14 12:15:34 -0800173
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700174 def get_servo_interfaces(self, position, size):
175 """Get the list of servo interfaces.
176
177 Args:
178 position: The index the first interface to get.
179 size: The number of the interfaces.
180 """
181 return self._interface_list[position:(position + size)]
182
183 def set_servo_interfaces(self, position, interfaces):
184 """Set the list of servo interfaces.
185
186 Args:
187 position: The index the first interface to set.
188 interfaces: The list of interfaces to set.
189 """
190 size = len(interfaces)
191 self._interface_list[position:(position + size)] = interfaces
192
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700193 def close(self):
194 """Servod turn down logic."""
195 for i, interface in enumerate(self._interface_list):
Ruben Rodriguez Buchillon18aafeb2020-11-13 21:20:26 -0800196 if not isinstance(interface, _interface.empty.Empty):
197 # Only print this on real interfaces and not place holders.
198 self._logger.info('Turning down interface %d', i)
199 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800200
Mary Ruthvencb861852019-07-15 16:30:48 -0700201 def get_devices(self):
202 return self._devices.values()
203
204 def add_device(self, device):
205 if device not in self._devices:
206 vid, pid, serial = device
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700207 servod_device = servo_dev.ServoDevice(vid, pid, serial)
Mary Ruthvencb861852019-07-15 16:30:48 -0700208 self._devices[device] = servod_device
209
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800210 def _camel_case(self, string):
211 output = ''
212 for s in string.split('_'):
213 if output:
214 output += s.capitalize()
215 else:
216 output = s
217 return output
218
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700219 def clear_cached_drv(self):
220 """Clear the cached drivers.
221
222 The drivers are cached in the Dict _drv_dict when a control is got or set.
223 When the servo interfaces are relocated, the cached values may become wrong.
224 Should call this method to clear the cached values.
225 """
226 self._drv_dict = {}
227
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800228 def _get_servo_specific_param(self, params, param_key, control_name):
229 """Get |param_key| from params by looking for servo specific params first.
230
231 Find the candidate servos. Using servo_v4 with a servo_micro connected as
232 example, the following shows the priority for selecting the interface.
233
234 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
235 2. servo_micro_interface
236 3. servo_v4_interface
237 4. Fallback to the default, interface.
238
239 Args:
240 params: params dictionary for a control
241 param_key: identifier in the params dictionary to look for
242 control_name: control name the params correspond to
243
244 Returns:
245 The best suited param value for param_key given the servo type or
246 None if even the default is not defined.
247 """
248 candidates = [self._version]
Ruben Rodriguez Buchillond18c6eb2019-07-10 14:40:22 -0700249 if '_with_' in self._version:
250 v4, raw_dut_device = self._version.split('_with_')
251 dut_devices = raw_dut_device.split('_and_')
252 # NOTE(coconutruben): all of this nonsense is going away with the new
253 # servod and is to bridge the time until then. Please forgive the below
254 # until then.
255 if '.' in control_name:
256 # In the current implementation, the only case where a '.' (a prefix)
257 # is in the control name is when there is a dual instance with micro and
258 # ccd on a v4.
259 dut_device = dut_devices[1]
260 else:
261 # In the normal control name, we need to make sure the version used
262 # does not include the potential _and_ portion from a dual instance.
263 dut_device = dut_devices[0]
264 candidates.extend([dut_device, v4])
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800265 candidates = ['%s_%s' % (c, param_key) for c in candidates]
266 candidates.append(param_key)
267 for c in candidates:
268 if c in params:
269 self._logger.debug('Using %s parameter.', c)
270 return params[c]
271 self._logger.error('Unable to determine %s for %s', param_key, control_name)
272 self._logger.error('params: %r', params)
273 return None
274
Todd Broche505b8d2011-03-21 18:19:54 -0700275 def _get_param_drv(self, control_name, is_get=True):
276 """Get access to driver for a given control.
277
278 Note, some controls have different parameter dictionaries for 'getting' the
279 control's value versus 'setting' it. Boolean is_get distinguishes which is
280 being requested.
281
282 Args:
283 control_name: string name of control
284 is_get: boolean to determine
285
286 Returns:
Fei Shao8aec57b2019-12-11 17:08:40 +0800287 tuple (params, drv, device_info) where:
288 params: param dictionary for control
Todd Broche505b8d2011-03-21 18:19:54 -0700289 drv: instance object of driver for particular control
Fei Shao8aec57b2019-12-11 17:08:40 +0800290 device_info: servo device information
Todd Broche505b8d2011-03-21 18:19:54 -0700291
292 Raises:
293 ServodError: Error occurred while examining params dict
294 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700295 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700296 # if already setup just return tuple from driver dict
297 if control_name in self._drv_dict:
298 if is_get and ('get' in self._drv_dict[control_name]):
299 return self._drv_dict[control_name]['get']
300 if not is_get and ('set' in self._drv_dict[control_name]):
301 return self._drv_dict[control_name]['set']
302
303 params = self._syscfg.lookup_control_params(control_name, is_get)
Simran Basi668be0e2013-08-07 11:54:50 -0700304
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800305 # Get the most suitable drv given the servo instance.
306 drv_name = self._get_servo_specific_param(params, 'drv', control_name)
307 if drv_name == 'na':
308 # 'na' drv can be used to selectively turn controls into noops for
309 # a given servo hardware. Ensure that there is an interface.
310 params.setdefault('interface', 'servo')
311 self._logger.debug('Setting interface to default to %r for %r unless '
312 ' defined in params, as drv is %r.', 'servo',
313 control_name, 'na')
314 # Setting input_type to str allows all inputs through enabling a true noop
315 params.update({'input_type': 'str'})
316 interface_id = self._get_servo_specific_param(params, 'interface',
317 control_name)
318 if None in [drv_name, interface_id]:
319 raise ServodError('No drv/interface for control %r found' % control_name)
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700320
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800321 if interface_id == 'servo':
Matthew Blecker6b250ff2020-08-23 12:00:55 -0700322 interface = weakref.proxy(self)
Simran Basi668be0e2013-08-07 11:54:50 -0700323 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700324 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800325 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700326
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700327 device_info = None
328 if hasattr(interface, 'get_device_info'):
329 device_info = interface.get_device_info()
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800330 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800331 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700332 drv = drv_class(interface, params)
333 if control_name not in self._drv_dict:
334 self._drv_dict[control_name] = {}
335 if is_get:
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700336 self._drv_dict[control_name]['get'] = (params, drv, device_info)
Todd Broche505b8d2011-03-21 18:19:54 -0700337 else:
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700338 self._drv_dict[control_name]['set'] = (params, drv, device_info)
339 return (params, drv, device_info)
Todd Broche505b8d2011-03-21 18:19:54 -0700340
Ruben Rodriguez Buchillon2ffef242020-11-13 20:51:02 -0800341 def _has_control(self, control):
342 """Returns True if control is available in servod."""
343 return self._syscfg.is_control(control)
344
Todd Broche505b8d2011-03-21 18:19:54 -0700345 def doc_all(self):
346 """Return all documenation for controls.
347
348 Returns:
349 string of <doc> text in config file (xml) and the params dictionary for
350 all controls.
351
352 For example:
353 warm_reset :: Reset the device warmly
354 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
355 """
356 return self._syscfg.display_config()
357
358 def doc(self, name):
359 """Retreive doc string in system config file for given control name.
360
361 Args:
362 name: name string of control to get doc string
363
364 Returns:
365 doc string of name
366
367 Raises:
368 NameError: if fails to locate control
369 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700370 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700371 if self._syscfg.is_control(name):
372 return self._syscfg.get_control_docstring(name)
373 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700374 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700375
Todd Broch352b4b22013-03-22 09:48:40 -0700376 def set_get_all(self, cmds):
377 """Set &| get one or more control values.
378
379 Args:
380 cmds: list of control[:value] to get or set.
381
382 Returns:
383 rv: list of responses from calling get or set methods.
384 """
385 rv = []
386 for cmd in cmds:
387 if ':' in cmd:
Wai-Hong Tam269f1802019-05-16 12:37:17 -0700388 (control, value) = cmd.split(':', 1)
Todd Broch352b4b22013-03-22 09:48:40 -0700389 rv.append(self.set(control, value))
390 else:
391 rv.append(self.get(cmd))
392 return rv
393
Mary Ruthven493df512019-07-12 13:10:18 -0700394 def add_serial_number(self, name, serial_number):
395 """Adds the serial number to the _serialnames dictionary.
396
397 Args:
398 name: A string which is the key into the _serialnames dictionary.
399 serial_number: A string which is the key into the _serialnames dictionary.
400 """
401 self._serialnames[name] = serial_number
402 self._logger.debug('Added %s %s to serialnames %r', name, serial_number,
403 self._serialnames)
404
Aseda Aboagye6921f602017-08-01 14:45:38 -0700405 def get_serial_number(self, name):
406 """Returns the desired serial number from the serialnames dict.
407
408 Args:
409 name: A string which is the key into the _serialnames dictionary.
410
411 Returns:
412 A string containing the serial number or "unknown".
413 """
Mary Ruthvenf17fb172019-08-15 17:17:35 -0700414 # Remove the prefix from the serialname control. Serialnames are
415 # universal. It doesn't matter what the prefix is.
416 # The prefix is separated from the main control with '.'
417 name = name.split('.', 1)[-1]
418
Aseda Aboagye6921f602017-08-01 14:45:38 -0700419 if not name:
420 name = 'main'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700421 try:
422 return self._serialnames[name]
423 except KeyError:
424 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700425 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700426
Todd Broche505b8d2011-03-21 18:19:54 -0700427 def get(self, name):
428 """Get control value.
429
430 Args:
431 name: name string of control
432
433 Returns:
434 Response from calling drv get method. Value is reformatted based on
435 control's dictionary parameters
436
437 Raises:
438 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800439 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700440 """
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700441 if 'serialname' in name:
Dana Goyette91cae862020-02-21 13:43:13 -0800442 # This route is to retrieve serialnames on servo v4, which
443 # connects to multiple servo-micros or CCD, like the controls,
444 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
445 # TODO(aaboagye): Refactor it.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700446 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700447
Dana Goyette17b0d252020-03-09 10:32:50 -0700448 with servo_logging.WrapGetCall(
Dana Goyette4a61e902020-05-08 10:09:31 -0700449 name, known_exceptions=self.KNOWN_EXCEPTIONS) as wrapper:
Dana Goyette91cae862020-02-21 13:43:13 -0800450 (params, drv, device) = self._get_param_drv(name)
451 if device in self._devices:
452 self._devices[device].wait(self.INTERFACE_AVAILABILITY_TIMEOUT)
453
Todd Broche505b8d2011-03-21 18:19:54 -0700454 val = drv.get()
Fei Shao8aec57b2019-12-11 17:08:40 +0800455 rd_val = self._syscfg.reformat_val(params, val)
Dana Goyette91cae862020-02-21 13:43:13 -0800456 wrapper.got_result(rd_val)
Todd Broche505b8d2011-03-21 18:19:54 -0700457 return rd_val
Todd Brochd6061672012-05-11 15:52:47 -0700458
Todd Broche505b8d2011-03-21 18:19:54 -0700459 def get_all(self, verbose):
460 """Get all controls values.
461
462 Args:
463 verbose: Boolean on whether to return doc info as well
464
465 Returns:
466 string creating from trying to get all values of all controls. In case of
467 error attempting access to control, response is 'ERR'.
468 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800469 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700470 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700471 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700472 try:
473 value = self.get(name)
474 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700475 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -0700476 pass
477 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700478 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700479 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700480 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800481 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700482
483 def set(self, name, wr_val_str):
484 """Set control.
485
486 Args:
487 name: name string of control
488 wr_val_str: value string to write. Can be integer, float or a
489 alpha-numerical that is mapped to a integer or float.
490
491 Raises:
492 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800493 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700494 """
Dana Goyette17b0d252020-03-09 10:32:50 -0700495 with servo_logging.WrapSetCall(
Dana Goyette4a61e902020-05-08 10:09:31 -0700496 name, wr_val_str, known_exceptions=self.KNOWN_EXCEPTIONS):
Dana Goyette91cae862020-02-21 13:43:13 -0800497 (params, drv, device) = self._get_param_drv(name, False)
498 if device in self._devices:
499 self._devices[device].wait(self.INTERFACE_AVAILABILITY_TIMEOUT)
500 wr_val = self._syscfg.resolve_val(params, wr_val_str)
501
Todd Broche505b8d2011-03-21 18:19:54 -0700502 drv.set(wr_val)
Dana Goyette91cae862020-02-21 13:43:13 -0800503
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +0800504 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
505 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -0700506 # marshall/unmarshall
507 return True
508
Todd Brochd6061672012-05-11 15:52:47 -0700509 def hwinit(self, verbose=False):
510 """Initialize all controls.
511
512 These values are part of the system config XML files of the form
513 init=<value>. This command should be used by clients wishing to return the
514 servo and DUT its connected to a known good/safe state.
515
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800516 Note that initialization errors are ignored (as in some cases they could
517 be caused by DUT firmware deficiencies). This might need to be fine tuned
518 later.
519
Todd Brochd6061672012-05-11 15:52:47 -0700520 Args:
521 verbose: boolean, if True prints info about control initialized.
522 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800523
524 Returns:
525 This function is called across RPC and as such is expected to return
526 something unless transferring 'none' across is allowed. Hence adding a
Sam Hurst2b487532020-08-05 11:00:23 -0700527 mock return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700528 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800529 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800530 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700531 # Workaround for bug chrome-os-partner:42349. Without this check, the
532 # gpio will briefly pulse low if we set it from high to high.
533 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700534 self.set(control_name, value)
535 if verbose:
536 self._logger.info('Initialized %s to %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700537 except Exception as e:
538 self._logger.error(
Matthew Bleckera5d979c2018-10-16 20:59:19 -0700539 'Problem initializing %s -> %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700540 self._logger.error(str(e))
541 self._logger.error('Please consider verifying the logs and if the '
542 'error is not just a setup issue, consider filing '
543 'a bug. Also checkout go/servo-ki.')
Nick Sandersbc836282015-12-08 21:19:23 -0800544
Namyoon Woo6ff36612019-10-16 16:41:12 -0700545 # If there is the control of 'active_v4_device', set active_v4_device to
546 # the default device as initialization.
Namyoon Wooad2a2bb2019-11-04 16:26:15 -0800547 try:
Mary Ruthvenf547c082020-05-07 11:32:28 -0700548 if self._syscfg.is_control('active_v4_device'):
549 self.set('active_v4_device', 'default')
Todd Brocha10cba12019-11-25 16:00:35 -0800550 except servo_drv.active_v4_device.activeV4DeviceError as e:
Mary Ruthvenf547c082020-05-07 11:32:28 -0700551 self._logger.debug('Could not set active device: %s', str(e))
Namyoon Woo6ff36612019-10-16 16:41:12 -0700552
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800553 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800554
Todd Broche505b8d2011-03-21 18:19:54 -0700555 def echo(self, echo):
Sam Hurst2b487532020-08-05 11:00:23 -0700556 """Mock echo function for testing/examples.
Todd Broche505b8d2011-03-21 18:19:54 -0700557
558 Args:
559 echo: string to echo back to client
560 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700561 self._logger.debug('echo(%s)' % (echo))
562 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -0700563
J. Richard Barnettee2820552013-03-14 16:13:46 -0700564 def get_board(self):
565 """Return the board specified at startup, if any."""
566 return self._board
567
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700568 def get_base_board(self):
569 """Returns the board name of the base if present.
570
571 Returns:
572 A string of the board name, or '' if not present.
573 """
574 # The value is set in servo_postinit.
575 return self._base_board
576
Simran Basia23c1392013-08-06 14:59:10 -0700577 def get_version(self):
578 """Get servo board version."""
579 return self._version
580
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700581 def get_servo_serials(self):
582 """Return all the serials associated with this process."""
583 return self._serialnames
584
585
Todd Broche505b8d2011-03-21 18:19:54 -0700586def test():
587 """Integration testing.
588
589 TODO(tbroch) Enhance integration test and add unittest (see mox)
590 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700591 logging.basicConfig(
592 level=logging.DEBUG,
593 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -0700594 # configure server & listen
595 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700596 # 5 == number of interfaces on a FT4232H device
Ruben Rodriguez Buchillon50f35602020-03-20 18:41:19 -0700597 for i in range(1, 5):
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700598 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -0700599 # its an i2c interface ... see __init__ for details and TODO to make
600 # this configureable
601 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
602 else:
603 # its a gpio interface
604 servod_obj._interface_list[i].wr_rd(0)
605
Ruben Rodriguez Buchillon529b0de2020-03-20 18:33:36 -0700606 server = SimpleXMLRPCServer(('localhost', 9999), allow_none=True)
Todd Broche505b8d2011-03-21 18:19:54 -0700607 server.register_introspection_functions()
608 server.register_multicall_functions()
609 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700610 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -0700611 server.serve_forever()
612
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700613
614if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -0700615 test()
616
617 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700618 """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)
619
Todd Broche505b8d2011-03-21 18:19:54 -0700620 """