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