blob: 5046405a94aba5056513724a22215ed97341d7f0 [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
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -080018import drv as servo_drv
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080019import interface as _interface
Mary Ruthvencb861852019-07-15 16:30:48 -070020import servo_dev
Simran Basie750a342013-03-12 13:45:26 -070021import servo_interfaces
Dana Goyette91cae862020-02-21 13:43:13 -080022import servo_logging
Kevin Cheng16304d12016-07-08 11:56:55 -070023import 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'
38 CCD_SERIAL = 'ccd'
Kevin Cheng4b4f0022016-09-09 02:37:07 -070039
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080040 # Timeout to wait for interfaces to become available again if reinitialization
Mary Ruthvenb7cc5542019-07-15 15:20:10 -070041 # is taking place. In seconds. This is supposed to recover from brief resets.
42 # If the interface disappears for more than 5 seconds, then someone probably
43 # intentionally disconnected the device. Servod shouldn't be responsible for
44 # waiting for the device during an intentional disconnect.
45 INTERFACE_AVAILABILITY_TIMEOUT = 5
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +080046
Dana Goyette4a61e902020-05-08 10:09:31 -070047 # Exceptions to count as known or ordinary. Any errors that aren't instances
48 # of these (or their subclasses) will be logged with "Please take a look."
49 KNOWN_EXCEPTIONS = (AttributeError, NameError, HwDriverError)
50
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070051 def init_servo_interfaces(self, vendor, product, serialname, interfaces):
Kevin Chengdc3befd2016-07-15 12:34:00 -070052 """Init the servo interfaces with the given interfaces.
53
54 We don't use the self._{vendor,product,serialname} attributes because we
55 want to allow other callers to initialize other interfaces that may not
56 be associated with the initialized attributes (e.g. a servo v4 servod object
57 that wants to also initialize a servo micro interface).
58
59 Args:
60 vendor: USB vendor id of FTDI device.
61 product: USB product id of FTDI device.
62 serialname: String of device serialname/number as defined in FTDI
63 eeprom.
64 interfaces: List of strings of interface types the server will
65 instantiate.
66
67 Raises:
68 ServodError if unable to locate init method for particular interface.
69 """
Mary Ruthven13389642017-02-14 12:15:34 -080070 # If it is a new device add it to the list
Wai-Hong Tam1f9e9a72017-05-02 14:14:46 -070071 device = (vendor, product, serialname)
Mary Ruthvencb861852019-07-15 16:30:48 -070072 self.add_device(device)
Mary Ruthven13389642017-02-14 12:15:34 -080073
Kevin Chengdc3befd2016-07-15 12:34:00 -070074 # Extend the interface list if we need to.
75 interfaces_len = len(interfaces)
76 interface_list_len = len(self._interface_list)
77 if interfaces_len > interface_list_len:
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080078 # Fill with dummies.
Sam Hurst2b487532020-08-05 11:00:23 -070079 self._interface_list += [_interface.empty.Empty()] * (interfaces_len -
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080080 interface_list_len)
Kevin Chengdc3befd2016-07-15 12:34:00 -070081
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080082 for i, interface_data in enumerate(interfaces):
83 if type(interface_data) is dict:
84 name = interface_data['name']
Kevin Chengdc3befd2016-07-15 12:34:00 -070085 # Store interface index for those that care about it.
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080086 interface_data['index'] = i
87 elif type(interface_data) is str:
Sam Hurst2b487532020-08-05 11:00:23 -070088 if interface_data in ['empty', 'ftdi_empty']:
89 # 'empty' reserves the interface for future use. Typically the
Ruben Rodriguez Buchillon78c23492019-06-18 13:55:21 -070090 # interface will be managed by external third-party tools like
91 # openOCD for JTAG or flashrom for SPI. In the case of servo V4,
92 # it serves as a placeholder for servo micro interfaces.
93 continue
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080094 name = interface_data
Kevin Chengdc3befd2016-07-15 12:34:00 -070095 else:
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -080096 raise ServodError('Illegal interface data type %s'
97 % type(interface_data))
Kevin Chengdc3befd2016-07-15 12:34:00 -070098
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -070099 self._logger.info('Initializing interface %d to %s', i, name)
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -0800100 result = _interface.Build(name=name, index=i, vid=vendor, pid=product,
101 sid=serialname, interface_data=interface_data,
102 servod=self)
Kevin Chengdc3befd2016-07-15 12:34:00 -0700103 if isinstance(result, tuple):
104 result_len = len(result)
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700105 self._interface_list[i:(i + result_len)] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700106 else:
Wai-Hong Tamd8a94d62017-04-28 10:11:51 -0700107 self._interface_list[i] = result
Kevin Chengdc3befd2016-07-15 12:34:00 -0700108
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700109 def __init__(self, config, vendor, product, serialname=None, interfaces=None,
Namyoon Woo341a8332019-03-07 12:01:31 -0800110 board='', model='', version=None, usbkm232=None):
Todd Broche505b8d2011-03-21 18:19:54 -0700111 """Servod constructor.
112
113 Args:
114 config: instance of SystemConfig containing all controls for
115 particular Servod invocation
116 vendor: usb vendor id of FTDI device
117 product: usb product id of FTDI device
Todd Brochad034442011-05-25 15:05:29 -0700118 serialname: string of device serialname/number as defined in FTDI eeprom.
Todd Brochdbb09982011-10-02 07:14:26 -0700119 interfaces: list of strings of interface types the server will instantiate
Namyoon Woo341a8332019-03-07 12:01:31 -0800120 board: board name. e.g. octopus, coral, or scarlet.
121 model: model name of a given board. e.g. fleex, ampton, or apel.
Simran Basia23c1392013-08-06 14:59:10 -0700122 version: String. Servo board version. Examples: servo_v1, servo_v2,
123 servo_v2_r0, servo_v3
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800124 usbkm232: String. Optional. Path to USB-KM232 device which allow for
Kevin Chengdc3befd2016-07-15 12:34:00 -0700125 sending keyboard commands to DUTs that do not have built in
Wai-Hong Tam7b9f2992017-10-24 16:07:14 -0700126 keyboards. Used in FAFT tests. Use None for on board AVR MCU.
127 e.g. '/dev/ttyUSB0' or None.
Todd Brochdbb09982011-10-02 07:14:26 -0700128
129 Raises:
130 ServodError: if unable to locate init method for particular interface
Todd Broche505b8d2011-03-21 18:19:54 -0700131 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700132 self._logger = logging.getLogger('Servod')
133 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700134 self._vendor = vendor
135 self._product = product
Mary Ruthvencb861852019-07-15 16:30:48 -0700136 self._devices = {}
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700137 self._serialnames = {self.MAIN_SERIAL: serialname}
Todd Broche505b8d2011-03-21 18:19:54 -0700138 self._syscfg = config
139 # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi
140 # interfaces are mapped to
141 self._interface_list = []
142 # Dict of Dict to map control name, function name to to tuple (params, drv)
143 # Ex) _drv_dict[name]['get'] = (params, drv)
144 self._drv_dict = {}
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700145 self._base_board = ''
Namyoon Woo341a8332019-03-07 12:01:31 -0800146 self._board = board
147 if model:
148 self._board += '_' + model
149 self._model = model
Simran Basia23c1392013-08-06 14:59:10 -0700150 self._version = version
Yusuf Mohsinally29e30d22014-01-14 15:29:17 -0800151 self._usbkm232 = usbkm232
Ruben Rodriguez Buchillon386a0102018-08-16 09:11:20 +0800152 self._keyboard = None
153 self._usb_keyboard = None
Todd Brochdbb09982011-10-02 07:14:26 -0700154 if not interfaces:
Todd Brochb21d8042014-05-15 12:54:54 -0700155 try:
156 interfaces = servo_interfaces.INTERFACE_BOARDS[board][vendor][product]
157 except KeyError:
158 interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product]
Dino Lic89d8c82018-01-11 09:56:47 +0800159 self._interfaces = interfaces
Todd Brochdbb09982011-10-02 07:14:26 -0700160
Kevin Chengdc3befd2016-07-15 12:34:00 -0700161 self.init_servo_interfaces(vendor, product, serialname, interfaces)
Kevin Cheng16304d12016-07-08 11:56:55 -0700162 servo_postinit.post_init(self)
Ruben Rodriguez Buchillon16e39eb2020-06-24 18:06:11 -0700163 self._syscfg.finalize()
Danny Chan662b6022015-11-04 17:34:53 -0800164
Mary Ruthven13389642017-02-14 12:15:34 -0800165 def reinitialize(self):
166 """Reinitialize all interfaces that support reinitialization"""
Mary Ruthven13389642017-02-14 12:15:34 -0800167 for i, interface in enumerate(self._interface_list):
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -0800168 interface.reinitialize()
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800169 # Indicate interfaces are safe to use again.
Mary Ruthvencb861852019-07-15 16:30:48 -0700170 for device in self._devices.values():
171 device.connect()
Mary Ruthven13389642017-02-14 12:15:34 -0800172
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700173 def get_servo_interfaces(self, position, size):
174 """Get the list of servo interfaces.
175
176 Args:
177 position: The index the first interface to get.
178 size: The number of the interfaces.
179 """
180 return self._interface_list[position:(position + size)]
181
182 def set_servo_interfaces(self, position, interfaces):
183 """Set the list of servo interfaces.
184
185 Args:
186 position: The index the first interface to set.
187 interfaces: The list of interfaces to set.
188 """
189 size = len(interfaces)
190 self._interface_list[position:(position + size)] = interfaces
191
Ruben Rodriguez Buchillona16374b2018-06-20 16:45:00 -0700192 def close(self):
193 """Servod turn down logic."""
194 for i, interface in enumerate(self._interface_list):
195 self._logger.info('Turning down interface %d' % i)
Ruben Rodriguez Buchillon1092ebf2020-02-28 15:12:19 -0800196 interface.close()
Todd Broch3ec8df02012-11-20 10:53:03 -0800197
Mary Ruthvencb861852019-07-15 16:30:48 -0700198 def get_devices(self):
199 return self._devices.values()
200
201 def add_device(self, device):
202 if device not in self._devices:
203 vid, pid, serial = device
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700204 servod_device = servo_dev.ServoDevice(vid, pid, serial)
Mary Ruthvencb861852019-07-15 16:30:48 -0700205 self._devices[device] = servod_device
206
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800207 def _camel_case(self, string):
208 output = ''
209 for s in string.split('_'):
210 if output:
211 output += s.capitalize()
212 else:
213 output = s
214 return output
215
Wai-Hong Tam4544c302017-05-24 19:44:53 -0700216 def clear_cached_drv(self):
217 """Clear the cached drivers.
218
219 The drivers are cached in the Dict _drv_dict when a control is got or set.
220 When the servo interfaces are relocated, the cached values may become wrong.
221 Should call this method to clear the cached values.
222 """
223 self._drv_dict = {}
224
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800225 def _get_servo_specific_param(self, params, param_key, control_name):
226 """Get |param_key| from params by looking for servo specific params first.
227
228 Find the candidate servos. Using servo_v4 with a servo_micro connected as
229 example, the following shows the priority for selecting the interface.
230
231 1. The full name. (e.g. - 'servo_v4_with_servo_micro_interface')
232 2. servo_micro_interface
233 3. servo_v4_interface
234 4. Fallback to the default, interface.
235
236 Args:
237 params: params dictionary for a control
238 param_key: identifier in the params dictionary to look for
239 control_name: control name the params correspond to
240
241 Returns:
242 The best suited param value for param_key given the servo type or
243 None if even the default is not defined.
244 """
245 candidates = [self._version]
Ruben Rodriguez Buchillond18c6eb2019-07-10 14:40:22 -0700246 if '_with_' in self._version:
247 v4, raw_dut_device = self._version.split('_with_')
248 dut_devices = raw_dut_device.split('_and_')
249 # NOTE(coconutruben): all of this nonsense is going away with the new
250 # servod and is to bridge the time until then. Please forgive the below
251 # until then.
252 if '.' in control_name:
253 # In the current implementation, the only case where a '.' (a prefix)
254 # is in the control name is when there is a dual instance with micro and
255 # ccd on a v4.
256 dut_device = dut_devices[1]
257 else:
258 # In the normal control name, we need to make sure the version used
259 # does not include the potential _and_ portion from a dual instance.
260 dut_device = dut_devices[0]
261 candidates.extend([dut_device, v4])
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800262 candidates = ['%s_%s' % (c, param_key) for c in candidates]
263 candidates.append(param_key)
264 for c in candidates:
265 if c in params:
266 self._logger.debug('Using %s parameter.', c)
267 return params[c]
268 self._logger.error('Unable to determine %s for %s', param_key, control_name)
269 self._logger.error('params: %r', params)
270 return None
271
Todd Broche505b8d2011-03-21 18:19:54 -0700272 def _get_param_drv(self, control_name, is_get=True):
273 """Get access to driver for a given control.
274
275 Note, some controls have different parameter dictionaries for 'getting' the
276 control's value versus 'setting' it. Boolean is_get distinguishes which is
277 being requested.
278
279 Args:
280 control_name: string name of control
281 is_get: boolean to determine
282
283 Returns:
Fei Shao8aec57b2019-12-11 17:08:40 +0800284 tuple (params, drv, device_info) where:
285 params: param dictionary for control
Todd Broche505b8d2011-03-21 18:19:54 -0700286 drv: instance object of driver for particular control
Fei Shao8aec57b2019-12-11 17:08:40 +0800287 device_info: servo device information
Todd Broche505b8d2011-03-21 18:19:54 -0700288
289 Raises:
290 ServodError: Error occurred while examining params dict
291 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700292 self._logger.debug('')
Todd Broche505b8d2011-03-21 18:19:54 -0700293 # if already setup just return tuple from driver dict
294 if control_name in self._drv_dict:
295 if is_get and ('get' in self._drv_dict[control_name]):
296 return self._drv_dict[control_name]['get']
297 if not is_get and ('set' in self._drv_dict[control_name]):
298 return self._drv_dict[control_name]['set']
299
300 params = self._syscfg.lookup_control_params(control_name, is_get)
Simran Basi668be0e2013-08-07 11:54:50 -0700301
Ruben Rodriguez Buchillon2c6589f2018-10-20 15:30:26 +0800302 # Get the most suitable drv given the servo instance.
303 drv_name = self._get_servo_specific_param(params, 'drv', control_name)
304 if drv_name == 'na':
305 # 'na' drv can be used to selectively turn controls into noops for
306 # a given servo hardware. Ensure that there is an interface.
307 params.setdefault('interface', 'servo')
308 self._logger.debug('Setting interface to default to %r for %r unless '
309 ' defined in params, as drv is %r.', 'servo',
310 control_name, 'na')
311 # Setting input_type to str allows all inputs through enabling a true noop
312 params.update({'input_type': 'str'})
313 interface_id = self._get_servo_specific_param(params, 'interface',
314 control_name)
315 if None in [drv_name, interface_id]:
316 raise ServodError('No drv/interface for control %r found' % control_name)
Aseda Aboagye1d8477b2017-05-10 17:24:31 -0700317
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800318 if interface_id == 'servo':
Matthew Blecker6b250ff2020-08-23 12:00:55 -0700319 interface = weakref.proxy(self)
Simran Basi668be0e2013-08-07 11:54:50 -0700320 else:
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700321 index = int(interface_id)
J. Richard Barnette275d9fd2014-02-11 14:38:54 -0800322 interface = self._interface_list[index]
Simran Basi668be0e2013-08-07 11:54:50 -0700323
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700324 device_info = None
325 if hasattr(interface, 'get_device_info'):
326 device_info = interface.get_device_info()
Wai-Hong Tam4c09eff2017-02-17 11:46:19 -0800327 drv_module = getattr(servo_drv, drv_name)
Tom Wai-Hong Tam28f0a5f2012-08-21 12:49:57 +0800328 drv_class = getattr(drv_module, self._camel_case(drv_name))
Todd Broche505b8d2011-03-21 18:19:54 -0700329 drv = drv_class(interface, params)
330 if control_name not in self._drv_dict:
331 self._drv_dict[control_name] = {}
332 if is_get:
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700333 self._drv_dict[control_name]['get'] = (params, drv, device_info)
Todd Broche505b8d2011-03-21 18:19:54 -0700334 else:
Mary Ruthven6b14d3f2019-07-15 12:52:53 -0700335 self._drv_dict[control_name]['set'] = (params, drv, device_info)
336 return (params, drv, device_info)
Todd Broche505b8d2011-03-21 18:19:54 -0700337
338 def doc_all(self):
339 """Return all documenation for controls.
340
341 Returns:
342 string of <doc> text in config file (xml) and the params dictionary for
343 all controls.
344
345 For example:
346 warm_reset :: Reset the device warmly
347 ------------------------> {'interface': '1', 'map': 'onoff_i', ... }
348 """
349 return self._syscfg.display_config()
350
351 def doc(self, name):
352 """Retreive doc string in system config file for given control name.
353
354 Args:
355 name: name string of control to get doc string
356
357 Returns:
358 doc string of name
359
360 Raises:
361 NameError: if fails to locate control
362 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700363 self._logger.debug('name(%s)' % (name))
Todd Broche505b8d2011-03-21 18:19:54 -0700364 if self._syscfg.is_control(name):
365 return self._syscfg.get_control_docstring(name)
366 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700367 raise NameError('No control %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700368
Todd Broch352b4b22013-03-22 09:48:40 -0700369 def set_get_all(self, cmds):
370 """Set &| get one or more control values.
371
372 Args:
373 cmds: list of control[:value] to get or set.
374
375 Returns:
376 rv: list of responses from calling get or set methods.
377 """
378 rv = []
379 for cmd in cmds:
380 if ':' in cmd:
Wai-Hong Tam269f1802019-05-16 12:37:17 -0700381 (control, value) = cmd.split(':', 1)
Todd Broch352b4b22013-03-22 09:48:40 -0700382 rv.append(self.set(control, value))
383 else:
384 rv.append(self.get(cmd))
385 return rv
386
Mary Ruthven493df512019-07-12 13:10:18 -0700387 def add_serial_number(self, name, serial_number):
388 """Adds the serial number to the _serialnames dictionary.
389
390 Args:
391 name: A string which is the key into the _serialnames dictionary.
392 serial_number: A string which is the key into the _serialnames dictionary.
393 """
394 self._serialnames[name] = serial_number
395 self._logger.debug('Added %s %s to serialnames %r', name, serial_number,
396 self._serialnames)
397
Aseda Aboagye6921f602017-08-01 14:45:38 -0700398 def get_serial_number(self, name):
399 """Returns the desired serial number from the serialnames dict.
400
401 Args:
402 name: A string which is the key into the _serialnames dictionary.
403
404 Returns:
405 A string containing the serial number or "unknown".
406 """
Mary Ruthvenf17fb172019-08-15 17:17:35 -0700407 # Remove the prefix from the serialname control. Serialnames are
408 # universal. It doesn't matter what the prefix is.
409 # The prefix is separated from the main control with '.'
410 name = name.split('.', 1)[-1]
411
Aseda Aboagye6921f602017-08-01 14:45:38 -0700412 if not name:
413 name = 'main'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700414 try:
415 return self._serialnames[name]
416 except KeyError:
417 self._logger.debug("'%s_serialname' not found!", name)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700418 return 'unknown'
Aseda Aboagye6921f602017-08-01 14:45:38 -0700419
Todd Broche505b8d2011-03-21 18:19:54 -0700420 def get(self, name):
421 """Get control value.
422
423 Args:
424 name: name string of control
425
426 Returns:
427 Response from calling drv get method. Value is reformatted based on
428 control's dictionary parameters
429
430 Raises:
431 HwDriverError: Error occurred while using drv
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800432 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700433 """
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700434 if 'serialname' in name:
Dana Goyette91cae862020-02-21 13:43:13 -0800435 # This route is to retrieve serialnames on servo v4, which
436 # connects to multiple servo-micros or CCD, like the controls,
437 # 'ccd_serialname', 'servo_micro_for_soraka_serialname', etc.
438 # TODO(aaboagye): Refactor it.
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700439 return self.get_serial_number(name.split('serialname')[0].strip('_'))
Wai-Hong Tambafeca72017-10-05 14:22:12 -0700440
Dana Goyette17b0d252020-03-09 10:32:50 -0700441 with servo_logging.WrapGetCall(
Dana Goyette4a61e902020-05-08 10:09:31 -0700442 name, known_exceptions=self.KNOWN_EXCEPTIONS) as wrapper:
Dana Goyette91cae862020-02-21 13:43:13 -0800443 (params, drv, device) = self._get_param_drv(name)
444 if device in self._devices:
445 self._devices[device].wait(self.INTERFACE_AVAILABILITY_TIMEOUT)
446
Todd Broche505b8d2011-03-21 18:19:54 -0700447 val = drv.get()
Fei Shao8aec57b2019-12-11 17:08:40 +0800448 rd_val = self._syscfg.reformat_val(params, val)
Dana Goyette91cae862020-02-21 13:43:13 -0800449 wrapper.got_result(rd_val)
Todd Broche505b8d2011-03-21 18:19:54 -0700450 return rd_val
Todd Brochd6061672012-05-11 15:52:47 -0700451
Todd Broche505b8d2011-03-21 18:19:54 -0700452 def get_all(self, verbose):
453 """Get all controls values.
454
455 Args:
456 verbose: Boolean on whether to return doc info as well
457
458 Returns:
459 string creating from trying to get all values of all controls. In case of
460 error attempting access to control, response is 'ERR'.
461 """
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800462 rsp = []
Todd Broche505b8d2011-03-21 18:19:54 -0700463 for name in self._syscfg.syscfg_dict['control']:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700464 self._logger.debug('name = %s' % name)
Todd Broche505b8d2011-03-21 18:19:54 -0700465 try:
466 value = self.get(name)
467 except Exception:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700468 value = 'ERR'
Todd Broche505b8d2011-03-21 18:19:54 -0700469 pass
470 if verbose:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700471 rsp.append('GET %s = %s :: %s' % (name, value, self.doc(name)))
Todd Broche505b8d2011-03-21 18:19:54 -0700472 else:
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700473 rsp.append('%s:%s' % (name, value))
Vadim Bendeburyb07944c2013-01-16 10:47:10 -0800474 return '\n'.join(sorted(rsp))
Todd Broche505b8d2011-03-21 18:19:54 -0700475
476 def set(self, name, wr_val_str):
477 """Set control.
478
479 Args:
480 name: name string of control
481 wr_val_str: value string to write. Can be integer, float or a
482 alpha-numerical that is mapped to a integer or float.
483
484 Raises:
485 HwDriverError: Error occurred while using driver
Ruben Rodriguez Buchillona5d8b922018-09-03 16:51:03 +0800486 ServodError: if interfaces are not available within timeout period
Todd Broche505b8d2011-03-21 18:19:54 -0700487 """
Dana Goyette17b0d252020-03-09 10:32:50 -0700488 with servo_logging.WrapSetCall(
Dana Goyette4a61e902020-05-08 10:09:31 -0700489 name, wr_val_str, known_exceptions=self.KNOWN_EXCEPTIONS):
Dana Goyette91cae862020-02-21 13:43:13 -0800490 (params, drv, device) = self._get_param_drv(name, False)
491 if device in self._devices:
492 self._devices[device].wait(self.INTERFACE_AVAILABILITY_TIMEOUT)
493 wr_val = self._syscfg.resolve_val(params, wr_val_str)
494
Todd Broche505b8d2011-03-21 18:19:54 -0700495 drv.set(wr_val)
Dana Goyette91cae862020-02-21 13:43:13 -0800496
Ruben Rodriguez Buchillonb5fe0f12018-05-09 10:19:56 +0800497 # TODO(crbug.com/841097) Figure out why despite allow_none=True for both
498 # xmlrpc server & client I still have to return something to appease the
Todd Broche505b8d2011-03-21 18:19:54 -0700499 # marshall/unmarshall
500 return True
501
Todd Brochd6061672012-05-11 15:52:47 -0700502 def hwinit(self, verbose=False):
503 """Initialize all controls.
504
505 These values are part of the system config XML files of the form
506 init=<value>. This command should be used by clients wishing to return the
507 servo and DUT its connected to a known good/safe state.
508
Vadim Bendeburybb51dd42013-01-31 13:47:46 -0800509 Note that initialization errors are ignored (as in some cases they could
510 be caused by DUT firmware deficiencies). This might need to be fine tuned
511 later.
512
Todd Brochd6061672012-05-11 15:52:47 -0700513 Args:
514 verbose: boolean, if True prints info about control initialized.
515 Otherwise prints nothing.
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800516
517 Returns:
518 This function is called across RPC and as such is expected to return
519 something unless transferring 'none' across is allowed. Hence adding a
Sam Hurst2b487532020-08-05 11:00:23 -0700520 mock return value to make things simpler.
Todd Brochd6061672012-05-11 15:52:47 -0700521 """
Todd Brochd9acf0a2012-12-05 13:43:06 -0800522 for control_name, value in self._syscfg.hwinit:
Todd Broch3ec8df02012-11-20 10:53:03 -0800523 try:
John Carey6fe2bbf2015-08-31 16:13:03 -0700524 # Workaround for bug chrome-os-partner:42349. Without this check, the
525 # gpio will briefly pulse low if we set it from high to high.
526 if self.get(control_name) != value:
Aseda Aboagyea849d462016-05-04 17:08:16 -0700527 self.set(control_name, value)
528 if verbose:
529 self._logger.info('Initialized %s to %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700530 except Exception as e:
531 self._logger.error(
Matthew Bleckera5d979c2018-10-16 20:59:19 -0700532 'Problem initializing %s -> %s', control_name, value)
Ruben Rodriguez Buchillon70eabcc2019-06-20 10:23:40 -0700533 self._logger.error(str(e))
534 self._logger.error('Please consider verifying the logs and if the '
535 'error is not just a setup issue, consider filing '
536 'a bug. Also checkout go/servo-ki.')
Nick Sandersbc836282015-12-08 21:19:23 -0800537
Namyoon Woo6ff36612019-10-16 16:41:12 -0700538 # If there is the control of 'active_v4_device', set active_v4_device to
539 # the default device as initialization.
Namyoon Wooad2a2bb2019-11-04 16:26:15 -0800540 try:
Mary Ruthvenf547c082020-05-07 11:32:28 -0700541 if self._syscfg.is_control('active_v4_device'):
542 self.set('active_v4_device', 'default')
Todd Brocha10cba12019-11-25 16:00:35 -0800543 except servo_drv.active_v4_device.activeV4DeviceError as e:
Mary Ruthvenf547c082020-05-07 11:32:28 -0700544 self._logger.debug('Could not set active device: %s', str(e))
Namyoon Woo6ff36612019-10-16 16:41:12 -0700545
Vadim Bendebury5934e4b2013-02-06 13:57:54 -0800546 return True
Todd Broch3ec8df02012-11-20 10:53:03 -0800547
Todd Broche505b8d2011-03-21 18:19:54 -0700548 def echo(self, echo):
Sam Hurst2b487532020-08-05 11:00:23 -0700549 """Mock echo function for testing/examples.
Todd Broche505b8d2011-03-21 18:19:54 -0700550
551 Args:
552 echo: string to echo back to client
553 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700554 self._logger.debug('echo(%s)' % (echo))
555 return 'ECH0ING: %s' % (echo)
Todd Broche505b8d2011-03-21 18:19:54 -0700556
J. Richard Barnettee2820552013-03-14 16:13:46 -0700557 def get_board(self):
558 """Return the board specified at startup, if any."""
559 return self._board
560
Wai-Hong Tam416cf612017-09-19 11:39:21 -0700561 def get_base_board(self):
562 """Returns the board name of the base if present.
563
564 Returns:
565 A string of the board name, or '' if not present.
566 """
567 # The value is set in servo_postinit.
568 return self._base_board
569
Simran Basia23c1392013-08-06 14:59:10 -0700570 def get_version(self):
571 """Get servo board version."""
572 return self._version
573
Kevin Cheng4b4f0022016-09-09 02:37:07 -0700574 def get_servo_serials(self):
575 """Return all the serials associated with this process."""
576 return self._serialnames
577
578
Todd Broche505b8d2011-03-21 18:19:54 -0700579def test():
580 """Integration testing.
581
582 TODO(tbroch) Enhance integration test and add unittest (see mox)
583 """
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700584 logging.basicConfig(
585 level=logging.DEBUG,
586 format='%(asctime)s - %(name)s - ' + '%(levelname)s - %(message)s')
Todd Broche505b8d2011-03-21 18:19:54 -0700587 # configure server & listen
588 servod_obj = Servod(1)
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700589 # 5 == number of interfaces on a FT4232H device
Ruben Rodriguez Buchillon50f35602020-03-20 18:41:19 -0700590 for i in range(1, 5):
Wai-Hong Tam564c1702017-04-24 09:23:38 -0700591 if i == 2:
Todd Broche505b8d2011-03-21 18:19:54 -0700592 # its an i2c interface ... see __init__ for details and TODO to make
593 # this configureable
594 servod_obj._interface_list[i].wr_rd(0x21, [0], 1)
595 else:
596 # its a gpio interface
597 servod_obj._interface_list[i].wr_rd(0)
598
Ruben Rodriguez Buchillon529b0de2020-03-20 18:33:36 -0700599 server = SimpleXMLRPCServer(('localhost', 9999), allow_none=True)
Todd Broche505b8d2011-03-21 18:19:54 -0700600 server.register_introspection_functions()
601 server.register_multicall_functions()
602 server.register_instance(servod_obj)
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700603 logging.info('Listening on localhost port 9999')
Todd Broche505b8d2011-03-21 18:19:54 -0700604 server.serve_forever()
605
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700606
607if __name__ == '__main__':
Todd Broche505b8d2011-03-21 18:19:54 -0700608 test()
609
610 # simple client transaction would look like
Puthikorn Voravootivat01ead152018-03-23 15:38:40 -0700611 """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)
612
Todd Broche505b8d2011-03-21 18:19:54 -0700613 """