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