Simran Basi | a9f4103 | 2012-05-11 14:21:58 -0700 | [diff] [blame] | 1 | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | """Servo Server.""" |
Simran Basi | a9f4103 | 2012-05-11 14:21:58 -0700 | [diff] [blame] | 5 | import fnmatch |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 6 | import imp |
| 7 | import logging |
Simran Basi | a9f4103 | 2012-05-11 14:21:58 -0700 | [diff] [blame] | 8 | import os |
| 9 | import shutil |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 10 | import SimpleXMLRPCServer |
Simran Basi | a9f4103 | 2012-05-11 14:21:58 -0700 | [diff] [blame] | 11 | import subprocess |
| 12 | import tempfile |
Todd Broch | 7a91c25 | 2012-02-03 12:37:45 -0800 | [diff] [blame] | 13 | import time |
Simran Basi | a9f4103 | 2012-05-11 14:21:58 -0700 | [diff] [blame] | 14 | import urllib |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 15 | |
| 16 | # TODO(tbroch) deprecate use of relative imports |
Vic Yang | be6cf26 | 2012-09-10 10:40:56 +0800 | [diff] [blame] | 17 | from drv.hw_driver import HwDriverError |
Simran Basi | a9ad25e | 2013-04-23 11:57:00 -0700 | [diff] [blame] | 18 | import bbi2c |
Simran Basi | 5492bde | 2013-05-16 17:08:47 -0700 | [diff] [blame] | 19 | import bbgpio |
Simran Basi | 949309b | 2013-05-31 15:12:15 -0700 | [diff] [blame^] | 20 | import bbuart |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 21 | import ftdigpio |
| 22 | import ftdii2c |
Todd Broch | dbb0998 | 2011-10-02 07:14:26 -0700 | [diff] [blame] | 23 | import ftdi_common |
Todd Broch | 47c43f4 | 2011-05-26 15:11:31 -0700 | [diff] [blame] | 24 | import ftdiuart |
Simran Basi | e750a34 | 2013-03-12 13:45:26 -0700 | [diff] [blame] | 25 | import servo_interfaces |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 26 | |
| 27 | MAX_I2C_CLOCK_HZ = 100000 |
| 28 | |
Todd Broch | dbb0998 | 2011-10-02 07:14:26 -0700 | [diff] [blame] | 29 | |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 30 | class ServodError(Exception): |
| 31 | """Exception class for servod.""" |
| 32 | |
| 33 | class Servod(object): |
| 34 | """Main class for Servo debug/controller Daemon.""" |
Simran Basi | a9f4103 | 2012-05-11 14:21:58 -0700 | [diff] [blame] | 35 | _USB_DETECTION_DELAY = 10 |
| 36 | _HTTP_PREFIX = "http://" |
| 37 | |
J. Richard Barnette | e282055 | 2013-03-14 16:13:46 -0700 | [diff] [blame] | 38 | def __init__(self, config, vendor, product, serialname=None, |
| 39 | interfaces=None, board=""): |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 40 | """Servod constructor. |
| 41 | |
| 42 | Args: |
| 43 | config: instance of SystemConfig containing all controls for |
| 44 | particular Servod invocation |
| 45 | vendor: usb vendor id of FTDI device |
| 46 | product: usb product id of FTDI device |
Todd Broch | ad03444 | 2011-05-25 15:05:29 -0700 | [diff] [blame] | 47 | serialname: string of device serialname/number as defined in FTDI eeprom. |
Todd Broch | dbb0998 | 2011-10-02 07:14:26 -0700 | [diff] [blame] | 48 | interfaces: list of strings of interface types the server will instantiate |
| 49 | |
| 50 | Raises: |
| 51 | ServodError: if unable to locate init method for particular interface |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 52 | """ |
| 53 | self._logger = logging.getLogger("Servod") |
| 54 | self._logger.debug("") |
| 55 | self._vendor = vendor |
| 56 | self._product = product |
Todd Broch | ad03444 | 2011-05-25 15:05:29 -0700 | [diff] [blame] | 57 | self._serialname = serialname |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 58 | self._syscfg = config |
| 59 | # list of objects (Fi2c, Fgpio) to physical interfaces (gpio, i2c) that ftdi |
| 60 | # interfaces are mapped to |
| 61 | self._interface_list = [] |
| 62 | # Dict of Dict to map control name, function name to to tuple (params, drv) |
| 63 | # Ex) _drv_dict[name]['get'] = (params, drv) |
| 64 | self._drv_dict = {} |
J. Richard Barnette | e282055 | 2013-03-14 16:13:46 -0700 | [diff] [blame] | 65 | self._board = board |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 66 | |
Todd Broch | dbb0998 | 2011-10-02 07:14:26 -0700 | [diff] [blame] | 67 | # Note, interface i is (i - 1) in list |
| 68 | if not interfaces: |
Simran Basi | e750a34 | 2013-03-12 13:45:26 -0700 | [diff] [blame] | 69 | interfaces = servo_interfaces.INTERFACE_DEFAULTS[vendor][product] |
Todd Broch | dbb0998 | 2011-10-02 07:14:26 -0700 | [diff] [blame] | 70 | |
Simran Basi | a9ad25e | 2013-04-23 11:57:00 -0700 | [diff] [blame] | 71 | for i, interface in enumerate(interfaces): |
| 72 | is_ftdi_interface = False |
| 73 | if type(interface) is dict: |
| 74 | name = interface['name'] |
| 75 | elif type(interface) is str: |
| 76 | # Its FTDI related interface |
| 77 | name = interface |
| 78 | interface = (i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) + 1 |
| 79 | is_ftdi_interface = True |
| 80 | else: |
| 81 | raise ServodError("Illegal interface type %s" % type(interface)) |
| 82 | |
Todd Broch | 8a77a99 | 2012-01-27 09:46:08 -0800 | [diff] [blame] | 83 | # servos with multiple FTDI are guaranteed to have contiguous USB PIDs |
Simran Basi | a9ad25e | 2013-04-23 11:57:00 -0700 | [diff] [blame] | 84 | if is_ftdi_interface and i and \ |
| 85 | ((i % ftdi_common.MAX_FTDI_INTERFACES_PER_DEVICE) == 0): |
Todd Broch | 8a77a99 | 2012-01-27 09:46:08 -0800 | [diff] [blame] | 86 | self._product += 1 |
| 87 | self._logger.info("Changing to next FTDI part @ pid = 0x%04x", |
| 88 | self._product) |
| 89 | |
Simran Basi | a9ad25e | 2013-04-23 11:57:00 -0700 | [diff] [blame] | 90 | self._logger.info("Initializing interface %d to %s", i + 1, name) |
Todd Broch | dbb0998 | 2011-10-02 07:14:26 -0700 | [diff] [blame] | 91 | try: |
| 92 | func = getattr(self, '_init_%s' % name) |
| 93 | except AttributeError: |
| 94 | raise ServodError("Unable to locate init for interface %s" % name) |
Simran Basi | a9ad25e | 2013-04-23 11:57:00 -0700 | [diff] [blame] | 95 | result = func(interface) |
Todd Broch | 888da78 | 2011-10-07 14:29:09 -0700 | [diff] [blame] | 96 | if isinstance(result, tuple): |
| 97 | self._interface_list.extend(result) |
| 98 | else: |
| 99 | self._interface_list.append(result) |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 100 | |
Todd Broch | 3ec8df0 | 2012-11-20 10:53:03 -0800 | [diff] [blame] | 101 | def __del__(self): |
| 102 | """Servod deconstructor.""" |
| 103 | for interface in self._interface_list: |
| 104 | del(interface) |
| 105 | |
Todd Broch | b304849 | 2012-01-15 21:52:41 -0800 | [diff] [blame] | 106 | def _init_dummy(self, interface): |
| 107 | """Initialize dummy interface. |
| 108 | |
| 109 | Dummy interface is just a mechanism to reserve that interface for non servod |
| 110 | interaction. Typically the interface will be managed by external |
| 111 | third-party tools like openOCD or urjtag for JTAG or flashrom for SPI |
| 112 | interfaces. |
| 113 | |
| 114 | TODO(tbroch): Investigate merits of incorporating these third-party |
| 115 | interfaces into servod or creating a communication channel between them |
| 116 | |
| 117 | Returns: None |
| 118 | """ |
| 119 | return None |
| 120 | |
Simran Basi | e750a34 | 2013-03-12 13:45:26 -0700 | [diff] [blame] | 121 | def _init_ftdi_gpio(self, interface): |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 122 | """Initialize gpio driver interface and open for use. |
| 123 | |
| 124 | Args: |
| 125 | interface: interface number of FTDI device to use. |
| 126 | |
| 127 | Returns: |
| 128 | Instance object of interface. |
Todd Broch | 6de9dc6 | 2012-04-09 15:23:53 -0700 | [diff] [blame] | 129 | |
| 130 | Raises: |
| 131 | ServodError: If init fails |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 132 | """ |
Todd Broch | ad03444 | 2011-05-25 15:05:29 -0700 | [diff] [blame] | 133 | fobj = ftdigpio.Fgpio(self._vendor, self._product, interface, |
| 134 | self._serialname) |
Todd Broch | 6de9dc6 | 2012-04-09 15:23:53 -0700 | [diff] [blame] | 135 | try: |
| 136 | fobj.open() |
| 137 | except ftdigpio.FgpioError as e: |
| 138 | raise ServodError('Opening gpio interface. %s ( %d )' % (e.msg, e.value)) |
| 139 | |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 140 | return fobj |
| 141 | |
Simran Basi | e750a34 | 2013-03-12 13:45:26 -0700 | [diff] [blame] | 142 | def _init_bb_gpio(self, interface): |
| 143 | """Initalize beaglebone gpio interface.""" |
Simran Basi | 5492bde | 2013-05-16 17:08:47 -0700 | [diff] [blame] | 144 | return bbgpio.BBgpio() |
Simran Basi | e750a34 | 2013-03-12 13:45:26 -0700 | [diff] [blame] | 145 | |
| 146 | def _init_ftdi_i2c(self, interface): |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 147 | """Initialize i2c interface and open for use. |
| 148 | |
| 149 | Args: |
| 150 | interface: interface number of FTDI device to use |
| 151 | |
| 152 | Returns: |
| 153 | Instance object of interface |
Todd Broch | 6de9dc6 | 2012-04-09 15:23:53 -0700 | [diff] [blame] | 154 | |
| 155 | Raises: |
| 156 | ServodError: If init fails |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 157 | """ |
Todd Broch | ad03444 | 2011-05-25 15:05:29 -0700 | [diff] [blame] | 158 | fobj = ftdii2c.Fi2c(self._vendor, self._product, interface, |
| 159 | self._serialname) |
Todd Broch | 6de9dc6 | 2012-04-09 15:23:53 -0700 | [diff] [blame] | 160 | try: |
| 161 | fobj.open() |
| 162 | except ftdii2c.Fi2cError as e: |
| 163 | raise ServodError('Opening i2c interface. %s ( %d )' % (e.msg, e.value)) |
| 164 | |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 165 | # Set the frequency of operation of the i2c bus. |
| 166 | # TODO(tbroch) make configureable |
| 167 | fobj.setclock(MAX_I2C_CLOCK_HZ) |
Todd Broch | 6de9dc6 | 2012-04-09 15:23:53 -0700 | [diff] [blame] | 168 | |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 169 | return fobj |
| 170 | |
Simran Basi | e750a34 | 2013-03-12 13:45:26 -0700 | [diff] [blame] | 171 | # TODO (sbasi) crbug.com/187489 - Implement bb_i2c. |
| 172 | def _init_bb_i2c(self, interface): |
| 173 | """Initalize beaglebone i2c interface.""" |
Simran Basi | a9ad25e | 2013-04-23 11:57:00 -0700 | [diff] [blame] | 174 | return bbi2c.BBi2c(interface) |
Simran Basi | e750a34 | 2013-03-12 13:45:26 -0700 | [diff] [blame] | 175 | |
| 176 | def _init_ftdi_uart(self, interface): |
| 177 | """Initialize ftdi uart inteface and open for use |
Todd Broch | 47c43f4 | 2011-05-26 15:11:31 -0700 | [diff] [blame] | 178 | |
| 179 | Note, the uart runs in a separate thread (pthreads). Users wishing to |
| 180 | interact with it will query control for the pty's pathname and connect |
| 181 | with there favorite console program. For example: |
| 182 | cu -l /dev/pts/22 |
| 183 | |
| 184 | Args: |
| 185 | interface: interface number of FTDI device to use |
| 186 | |
| 187 | Returns: |
| 188 | Instance object of interface |
Todd Broch | 6de9dc6 | 2012-04-09 15:23:53 -0700 | [diff] [blame] | 189 | |
| 190 | Raises: |
| 191 | ServodError: If init fails |
Todd Broch | 47c43f4 | 2011-05-26 15:11:31 -0700 | [diff] [blame] | 192 | """ |
Jeremy Thorpe | 9e11006 | 2012-10-25 10:40:00 -0700 | [diff] [blame] | 193 | fobj = ftdiuart.Fuart(self._vendor, self._product, interface, |
| 194 | self._serialname) |
Todd Broch | 6de9dc6 | 2012-04-09 15:23:53 -0700 | [diff] [blame] | 195 | try: |
| 196 | fobj.run() |
| 197 | except ftdiuart.FuartError as e: |
| 198 | raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value)) |
| 199 | |
Todd Broch | 47c43f4 | 2011-05-26 15:11:31 -0700 | [diff] [blame] | 200 | self._logger.info("%s" % fobj.get_pty()) |
| 201 | return fobj |
| 202 | |
Simran Basi | e750a34 | 2013-03-12 13:45:26 -0700 | [diff] [blame] | 203 | # TODO (sbasi) crbug.com/187492 - Implement bbuart. |
| 204 | def _init_bb_uart(self, interface): |
| 205 | """Initalize beaglebone uart interface.""" |
Simran Basi | 949309b | 2013-05-31 15:12:15 -0700 | [diff] [blame^] | 206 | logging.debug('UART INTERFACE: %s', interface) |
| 207 | return bbuart.BBuart(interface) |
Simran Basi | e750a34 | 2013-03-12 13:45:26 -0700 | [diff] [blame] | 208 | |
| 209 | def _init_ftdi_gpiouart(self, interface): |
Todd Broch | 888da78 | 2011-10-07 14:29:09 -0700 | [diff] [blame] | 210 | """Initialize special gpio + uart interface and open for use |
| 211 | |
| 212 | Note, the uart runs in a separate thread (pthreads). Users wishing to |
| 213 | interact with it will query control for the pty's pathname and connect |
| 214 | with there favorite console program. For example: |
| 215 | cu -l /dev/pts/22 |
| 216 | |
| 217 | Args: |
| 218 | interface: interface number of FTDI device to use |
| 219 | |
| 220 | Returns: |
| 221 | Instance objects of interface |
Todd Broch | 6de9dc6 | 2012-04-09 15:23:53 -0700 | [diff] [blame] | 222 | |
| 223 | Raises: |
| 224 | ServodError: If init fails |
Todd Broch | 888da78 | 2011-10-07 14:29:09 -0700 | [diff] [blame] | 225 | """ |
Simran Basi | e750a34 | 2013-03-12 13:45:26 -0700 | [diff] [blame] | 226 | fgpio = self._init_ftdi_gpio(interface) |
Jeremy Thorpe | 9e11006 | 2012-10-25 10:40:00 -0700 | [diff] [blame] | 227 | fuart = ftdiuart.Fuart(self._vendor, self._product, interface, |
| 228 | self._serialname, fgpio._fc) |
Todd Broch | 6de9dc6 | 2012-04-09 15:23:53 -0700 | [diff] [blame] | 229 | try: |
| 230 | fuart.run() |
| 231 | except ftdiuart.FuartError as e: |
| 232 | raise ServodError('Running uart interface. %s ( %d )' % (e.msg, e.value)) |
| 233 | |
Todd Broch | 888da78 | 2011-10-07 14:29:09 -0700 | [diff] [blame] | 234 | self._logger.info("uart pty: %s" % fuart.get_pty()) |
| 235 | return fgpio, fuart |
| 236 | |
Tom Wai-Hong Tam | 28f0a5f | 2012-08-21 12:49:57 +0800 | [diff] [blame] | 237 | def _camel_case(self, string): |
| 238 | output = '' |
| 239 | for s in string.split('_'): |
| 240 | if output: |
| 241 | output += s.capitalize() |
| 242 | else: |
| 243 | output = s |
| 244 | return output |
| 245 | |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 246 | def _get_param_drv(self, control_name, is_get=True): |
| 247 | """Get access to driver for a given control. |
| 248 | |
| 249 | Note, some controls have different parameter dictionaries for 'getting' the |
| 250 | control's value versus 'setting' it. Boolean is_get distinguishes which is |
| 251 | being requested. |
| 252 | |
| 253 | Args: |
| 254 | control_name: string name of control |
| 255 | is_get: boolean to determine |
| 256 | |
| 257 | Returns: |
| 258 | tuple (param, drv) where: |
| 259 | param: param dictionary for control |
| 260 | drv: instance object of driver for particular control |
| 261 | |
| 262 | Raises: |
| 263 | ServodError: Error occurred while examining params dict |
| 264 | """ |
| 265 | self._logger.debug("") |
| 266 | # if already setup just return tuple from driver dict |
| 267 | if control_name in self._drv_dict: |
| 268 | if is_get and ('get' in self._drv_dict[control_name]): |
| 269 | return self._drv_dict[control_name]['get'] |
| 270 | if not is_get and ('set' in self._drv_dict[control_name]): |
| 271 | return self._drv_dict[control_name]['set'] |
| 272 | |
| 273 | params = self._syscfg.lookup_control_params(control_name, is_get) |
| 274 | if 'drv' not in params: |
| 275 | self._logger.error("Unable to determine driver for %s" % control_name) |
| 276 | raise ServodError("'drv' key not found in params dict") |
| 277 | if 'interface' not in params: |
| 278 | self._logger.error("Unable to determine interface for %s" % |
| 279 | control_name) |
| 280 | |
| 281 | raise ServodError("'interface' key not found in params dict") |
| 282 | index = int(params['interface']) - 1 |
| 283 | interface = self._interface_list[index] |
| 284 | servo_pkg = imp.load_module('servo', *imp.find_module('servo')) |
| 285 | drv_pkg = imp.load_module('drv', |
| 286 | *imp.find_module('drv', servo_pkg.__path__)) |
| 287 | drv_name = params['drv'] |
| 288 | drv_module = getattr(drv_pkg, drv_name) |
Tom Wai-Hong Tam | 28f0a5f | 2012-08-21 12:49:57 +0800 | [diff] [blame] | 289 | drv_class = getattr(drv_module, self._camel_case(drv_name)) |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 290 | drv = drv_class(interface, params) |
| 291 | if control_name not in self._drv_dict: |
| 292 | self._drv_dict[control_name] = {} |
| 293 | if is_get: |
| 294 | self._drv_dict[control_name]['get'] = (params, drv) |
| 295 | else: |
| 296 | self._drv_dict[control_name]['set'] = (params, drv) |
| 297 | return (params, drv) |
| 298 | |
| 299 | def doc_all(self): |
| 300 | """Return all documenation for controls. |
| 301 | |
| 302 | Returns: |
| 303 | string of <doc> text in config file (xml) and the params dictionary for |
| 304 | all controls. |
| 305 | |
| 306 | For example: |
| 307 | warm_reset :: Reset the device warmly |
| 308 | ------------------------> {'interface': '1', 'map': 'onoff_i', ... } |
| 309 | """ |
| 310 | return self._syscfg.display_config() |
| 311 | |
| 312 | def doc(self, name): |
| 313 | """Retreive doc string in system config file for given control name. |
| 314 | |
| 315 | Args: |
| 316 | name: name string of control to get doc string |
| 317 | |
| 318 | Returns: |
| 319 | doc string of name |
| 320 | |
| 321 | Raises: |
| 322 | NameError: if fails to locate control |
| 323 | """ |
| 324 | self._logger.debug("name(%s)" % (name)) |
| 325 | if self._syscfg.is_control(name): |
| 326 | return self._syscfg.get_control_docstring(name) |
| 327 | else: |
| 328 | raise NameError("No control %s" %name) |
| 329 | |
Simran Basi | a9f4103 | 2012-05-11 14:21:58 -0700 | [diff] [blame] | 330 | def _get_usb_port_set(self): |
| 331 | """Gets a set of USB disks currently connected to the system |
| 332 | |
| 333 | Returns: |
| 334 | A set of USB disk paths. |
| 335 | """ |
| 336 | usb_set = fnmatch.filter(os.listdir("/dev/"), "sd[a-z]") |
| 337 | return set(["/dev/" + dev for dev in usb_set]) |
| 338 | |
| 339 | def _probe_host_usb_dev(self): |
| 340 | """Probe the USB disk device plugged in the servo from the host side. |
| 341 | |
| 342 | Method can fail by: |
| 343 | 1) Having multiple servos connected and returning incorrect /dev/sdX of |
| 344 | another servo. |
| 345 | 2) Finding multiple /dev/sdX and returning None. |
| 346 | |
| 347 | Returns: |
| 348 | USB disk path if one and only one USB disk path is found, otherwise None. |
| 349 | """ |
| 350 | original_value = self.get("usb_mux_sel1") |
| 351 | # Make the host unable to see the USB disk. |
| 352 | if original_value != "dut_sees_usbkey": |
| 353 | self.set("usb_mux_sel1", "dut_sees_usbkey") |
| 354 | time.sleep(self._USB_DETECTION_DELAY) |
| 355 | |
| 356 | no_usb_set = self._get_usb_port_set() |
| 357 | # Make the host able to see the USB disk. |
| 358 | self.set("usb_mux_sel1", "servo_sees_usbkey") |
| 359 | time.sleep(self._USB_DETECTION_DELAY) |
| 360 | |
| 361 | has_usb_set = self._get_usb_port_set() |
| 362 | # Back to its original value. |
| 363 | if original_value != "servo_sees_usbkey": |
| 364 | self.set("usb_mux_sel1", original_value) |
| 365 | time.sleep(self._USB_DETECTION_DELAY) |
| 366 | # Subtract the two sets to find the usb device. |
| 367 | diff_set = has_usb_set - no_usb_set |
| 368 | if len(diff_set) == 1: |
| 369 | return diff_set.pop() |
| 370 | else: |
| 371 | return None |
| 372 | |
| 373 | def download_image_to_usb(self, image_path): |
| 374 | """Download image and save to the USB device found by probe_host_usb_dev. |
| 375 | If the image_path is a URL, it will download this url to the USB path; |
| 376 | otherwise it will simply copy the image_path's contents to the USB path. |
| 377 | |
| 378 | Args: |
| 379 | image_path: path or url to the recovery image. |
| 380 | |
| 381 | Returns: |
| 382 | True|False: True if process completed successfully, False if error |
| 383 | occurred. |
| 384 | Can't return None because XMLRPC doesn't allow it. PTAL at tbroch's |
| 385 | comment at the end of set(). |
| 386 | """ |
| 387 | self._logger.debug("image_path(%s)" % image_path) |
| 388 | self._logger.debug("Detecting USB stick device...") |
| 389 | usb_dev = self._probe_host_usb_dev() |
| 390 | if not usb_dev: |
| 391 | self._logger.error("No usb device connected to servo") |
| 392 | return False |
| 393 | |
| 394 | try: |
| 395 | if image_path.startswith(self._HTTP_PREFIX): |
| 396 | self._logger.debug("Image path is a URL, downloading image") |
| 397 | urllib.urlretrieve(image_path, usb_dev) |
| 398 | else: |
| 399 | shutil.copyfile(image_path, usb_dev) |
| 400 | except IOError as e: |
| 401 | self._logger.error("Failed to transfer image to USB device: %s ( %d ) ", |
| 402 | e.strerror, e.errno) |
| 403 | return False |
| 404 | except urllib.ContentTooShortError: |
| 405 | self._logger.error("Failed to download URL: %s to USB device: %s", |
| 406 | image_path, usb_dev) |
| 407 | return False |
| 408 | except BaseException as e: |
| 409 | self._logger.error("Unexpected exception downloading %s to %s: %s", |
| 410 | image_path, usb_dev, str(e)) |
| 411 | return False |
J. Richard Barnette | e4125af | 2013-02-26 18:31:56 -0800 | [diff] [blame] | 412 | finally: |
| 413 | # We just plastered the partition table for a block device. |
| 414 | # Pass or fail, we mustn't go without telling the kernel about |
| 415 | # the change, or it will punish us with sporadic, hard-to-debug |
| 416 | # failures. |
| 417 | subprocess.call(["sync"]) |
| 418 | subprocess.call(["blockdev", "--rereadpt", usb_dev]) |
Simran Basi | a9f4103 | 2012-05-11 14:21:58 -0700 | [diff] [blame] | 419 | return True |
| 420 | |
| 421 | def make_image_noninteractive(self): |
| 422 | """Makes the recovery image noninteractive. |
| 423 | |
| 424 | A noninteractive image will reboot automatically after installation |
| 425 | instead of waiting for the USB device to be removed to initiate a system |
| 426 | reboot. |
| 427 | |
| 428 | Mounts partition 1 of the image stored on usb_dev and creates a file |
| 429 | called "non_interactive" so that the image will become noninteractive. |
| 430 | |
| 431 | Returns: |
| 432 | True|False: True if process completed successfully, False if error |
| 433 | occurred. |
| 434 | """ |
| 435 | result = True |
| 436 | usb_dev = self._probe_host_usb_dev() |
| 437 | if not usb_dev: |
| 438 | self._logger.error("No usb device connected to servo") |
| 439 | return False |
| 440 | # Create TempDirectory |
| 441 | tmpdir = tempfile.mkdtemp() |
| 442 | if tmpdir: |
| 443 | # Mount drive to tmpdir. |
| 444 | partition_1 = "%s1" % usb_dev |
| 445 | rc = subprocess.call(["mount", partition_1, tmpdir]) |
| 446 | if rc == 0: |
| 447 | # Create file 'non_interactive' |
| 448 | non_interactive_file = os.path.join(tmpdir, "non_interactive") |
| 449 | try: |
| 450 | open(non_interactive_file, "w").close() |
| 451 | except IOError as e: |
| 452 | self._logger.error("Failed to create file %s : %s ( %d )", |
| 453 | non_interactive_file, e.strerror, e.errno) |
| 454 | result = False |
| 455 | except BaseException as e: |
| 456 | self._logger.error("Unexpected Exception creating file %s : %s", |
| 457 | non_interactive_file, str(e)) |
| 458 | result = False |
| 459 | # Unmount drive regardless if file creation worked or not. |
| 460 | rc = subprocess.call(["umount", partition_1]) |
| 461 | if rc != 0: |
| 462 | self._logger.error("Failed to unmount USB Device") |
| 463 | result = False |
| 464 | else: |
| 465 | self._logger.error("Failed to mount USB Device") |
| 466 | result = False |
| 467 | |
| 468 | # Delete tmpdir. May throw exception if 'umount' failed. |
| 469 | try: |
| 470 | os.rmdir(tmpdir) |
| 471 | except OSError as e: |
| 472 | self._logger.error("Failed to remove temp directory %s : %s", |
| 473 | tmpdir, str(e)) |
| 474 | return False |
| 475 | except BaseException as e: |
| 476 | self._logger.error("Unexpected Exception removing tempdir %s : %s", |
| 477 | tmpdir, str(e)) |
| 478 | return False |
| 479 | else: |
| 480 | self._logger.error("Failed to create temp directory.") |
| 481 | return False |
| 482 | return result |
| 483 | |
Todd Broch | 352b4b2 | 2013-03-22 09:48:40 -0700 | [diff] [blame] | 484 | def set_get_all(self, cmds): |
| 485 | """Set &| get one or more control values. |
| 486 | |
| 487 | Args: |
| 488 | cmds: list of control[:value] to get or set. |
| 489 | |
| 490 | Returns: |
| 491 | rv: list of responses from calling get or set methods. |
| 492 | """ |
| 493 | rv = [] |
| 494 | for cmd in cmds: |
| 495 | if ':' in cmd: |
| 496 | (control, value) = cmd.split(':') |
| 497 | rv.append(self.set(control, value)) |
| 498 | else: |
| 499 | rv.append(self.get(cmd)) |
| 500 | return rv |
| 501 | |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 502 | def get(self, name): |
| 503 | """Get control value. |
| 504 | |
| 505 | Args: |
| 506 | name: name string of control |
| 507 | |
| 508 | Returns: |
| 509 | Response from calling drv get method. Value is reformatted based on |
| 510 | control's dictionary parameters |
| 511 | |
| 512 | Raises: |
| 513 | HwDriverError: Error occurred while using drv |
| 514 | """ |
| 515 | self._logger.debug("name(%s)" % (name)) |
| 516 | (param, drv) = self._get_param_drv(name) |
| 517 | try: |
| 518 | val = drv.get() |
| 519 | rd_val = self._syscfg.reformat_val(param, val) |
Todd Broch | b042e7a | 2011-12-14 17:41:36 -0800 | [diff] [blame] | 520 | self._logger.debug("%s = %s" % (name, rd_val)) |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 521 | return rd_val |
Todd Broch | fbc499d | 2011-06-16 16:09:58 -0700 | [diff] [blame] | 522 | except AttributeError, error: |
| 523 | self._logger.error("Getting %s: %s" % (name, error)) |
| 524 | raise |
Vic Yang | be6cf26 | 2012-09-10 10:40:56 +0800 | [diff] [blame] | 525 | except HwDriverError: |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 526 | self._logger.error("Getting %s" % (name)) |
| 527 | raise |
Todd Broch | d606167 | 2012-05-11 15:52:47 -0700 | [diff] [blame] | 528 | |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 529 | def get_all(self, verbose): |
| 530 | """Get all controls values. |
| 531 | |
| 532 | Args: |
| 533 | verbose: Boolean on whether to return doc info as well |
| 534 | |
| 535 | Returns: |
| 536 | string creating from trying to get all values of all controls. In case of |
| 537 | error attempting access to control, response is 'ERR'. |
| 538 | """ |
Vadim Bendebury | b07944c | 2013-01-16 10:47:10 -0800 | [diff] [blame] | 539 | rsp = [] |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 540 | for name in self._syscfg.syscfg_dict['control']: |
| 541 | self._logger.debug("name = %s" %name) |
| 542 | try: |
| 543 | value = self.get(name) |
| 544 | except Exception: |
| 545 | value = "ERR" |
| 546 | pass |
| 547 | if verbose: |
Vadim Bendebury | b07944c | 2013-01-16 10:47:10 -0800 | [diff] [blame] | 548 | rsp.append("GET %s = %s :: %s" % (name, value, self.doc(name))) |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 549 | else: |
Vadim Bendebury | b07944c | 2013-01-16 10:47:10 -0800 | [diff] [blame] | 550 | rsp.append("%s:%s" % (name, value)) |
| 551 | return '\n'.join(sorted(rsp)) |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 552 | |
| 553 | def set(self, name, wr_val_str): |
| 554 | """Set control. |
| 555 | |
| 556 | Args: |
| 557 | name: name string of control |
| 558 | wr_val_str: value string to write. Can be integer, float or a |
| 559 | alpha-numerical that is mapped to a integer or float. |
| 560 | |
| 561 | Raises: |
| 562 | HwDriverError: Error occurred while using driver |
| 563 | """ |
Todd Broch | 7a91c25 | 2012-02-03 12:37:45 -0800 | [diff] [blame] | 564 | if name == 'sleep': |
| 565 | time.sleep(float(wr_val_str)) |
| 566 | return True |
| 567 | |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 568 | self._logger.debug("name(%s) wr_val(%s)" % (name, wr_val_str)) |
| 569 | (params, drv) = self._get_param_drv(name, False) |
| 570 | wr_val = self._syscfg.resolve_val(params, wr_val_str) |
| 571 | try: |
| 572 | drv.set(wr_val) |
Vic Yang | be6cf26 | 2012-09-10 10:40:56 +0800 | [diff] [blame] | 573 | except HwDriverError: |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 574 | self._logger.error("Setting %s -> %s" % (name, wr_val_str)) |
| 575 | raise |
| 576 | # TODO(tbroch) Figure out why despite allow_none=True for both xmlrpc server |
| 577 | # & client I still have to return something to appease the |
| 578 | # marshall/unmarshall |
| 579 | return True |
| 580 | |
Todd Broch | d606167 | 2012-05-11 15:52:47 -0700 | [diff] [blame] | 581 | def hwinit(self, verbose=False): |
| 582 | """Initialize all controls. |
| 583 | |
| 584 | These values are part of the system config XML files of the form |
| 585 | init=<value>. This command should be used by clients wishing to return the |
| 586 | servo and DUT its connected to a known good/safe state. |
| 587 | |
Vadim Bendebury | bb51dd4 | 2013-01-31 13:47:46 -0800 | [diff] [blame] | 588 | Note that initialization errors are ignored (as in some cases they could |
| 589 | be caused by DUT firmware deficiencies). This might need to be fine tuned |
| 590 | later. |
| 591 | |
Todd Broch | d606167 | 2012-05-11 15:52:47 -0700 | [diff] [blame] | 592 | Args: |
| 593 | verbose: boolean, if True prints info about control initialized. |
| 594 | Otherwise prints nothing. |
Vadim Bendebury | 5934e4b | 2013-02-06 13:57:54 -0800 | [diff] [blame] | 595 | |
| 596 | Returns: |
| 597 | This function is called across RPC and as such is expected to return |
| 598 | something unless transferring 'none' across is allowed. Hence adding a |
| 599 | dummy return value to make things simpler. |
Todd Broch | d606167 | 2012-05-11 15:52:47 -0700 | [diff] [blame] | 600 | """ |
Todd Broch | d9acf0a | 2012-12-05 13:43:06 -0800 | [diff] [blame] | 601 | for control_name, value in self._syscfg.hwinit: |
Todd Broch | 3ec8df0 | 2012-11-20 10:53:03 -0800 | [diff] [blame] | 602 | try: |
| 603 | self.set(control_name, value) |
| 604 | except Exception as e: |
Todd Broch | 3ec8df0 | 2012-11-20 10:53:03 -0800 | [diff] [blame] | 605 | self._logger.error("Problem initializing %s -> %s :: %s", |
| 606 | control_name, value, str(e)) |
Todd Broch | d606167 | 2012-05-11 15:52:47 -0700 | [diff] [blame] | 607 | if verbose: |
| 608 | self._logger.info('Initialized %s to %s', control_name, value) |
Vadim Bendebury | 5934e4b | 2013-02-06 13:57:54 -0800 | [diff] [blame] | 609 | return True |
Todd Broch | 3ec8df0 | 2012-11-20 10:53:03 -0800 | [diff] [blame] | 610 | |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 611 | def echo(self, echo): |
| 612 | """Dummy echo function for testing/examples. |
| 613 | |
| 614 | Args: |
| 615 | echo: string to echo back to client |
| 616 | """ |
| 617 | self._logger.debug("echo(%s)" % (echo)) |
| 618 | return "ECH0ING: %s" % (echo) |
| 619 | |
J. Richard Barnette | e282055 | 2013-03-14 16:13:46 -0700 | [diff] [blame] | 620 | def get_board(self): |
| 621 | """Return the board specified at startup, if any.""" |
| 622 | return self._board |
| 623 | |
Todd Broch | dbb0998 | 2011-10-02 07:14:26 -0700 | [diff] [blame] | 624 | |
Todd Broch | e505b8d | 2011-03-21 18:19:54 -0700 | [diff] [blame] | 625 | def test(): |
| 626 | """Integration testing. |
| 627 | |
| 628 | TODO(tbroch) Enhance integration test and add unittest (see mox) |
| 629 | """ |
| 630 | logging.basicConfig(level=logging.DEBUG, |
| 631 | format="%(asctime)s - %(name)s - " + |
| 632 | "%(levelname)s - %(message)s") |
| 633 | # configure server & listen |
| 634 | servod_obj = Servod(1) |
| 635 | # 4 == number of interfaces on a FT4232H device |
| 636 | for i in xrange(4): |
| 637 | if i == 1: |
| 638 | # its an i2c interface ... see __init__ for details and TODO to make |
| 639 | # this configureable |
| 640 | servod_obj._interface_list[i].wr_rd(0x21, [0], 1) |
| 641 | else: |
| 642 | # its a gpio interface |
| 643 | servod_obj._interface_list[i].wr_rd(0) |
| 644 | |
| 645 | server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 9999), |
| 646 | allow_none=True) |
| 647 | server.register_introspection_functions() |
| 648 | server.register_multicall_functions() |
| 649 | server.register_instance(servod_obj) |
| 650 | logging.info("Listening on localhost port 9999") |
| 651 | server.serve_forever() |
| 652 | |
| 653 | if __name__ == "__main__": |
| 654 | test() |
| 655 | |
| 656 | # simple client transaction would look like |
| 657 | """ |
| 658 | remote_uri = 'http://localhost:9999' |
| 659 | client = xmlrpclib.ServerProxy(remote_uri, verbose=False) |
| 660 | send_str = "Hello_there" |
| 661 | print "Sent " + send_str + ", Recv " + client.echo(send_str) |
| 662 | """ |