iwd.py (53990B)
1 #!/usr/bin/python3 2 from gi.repository import GLib 3 4 import dbus 5 import dbus.service 6 import dbus.mainloop.glib 7 import sys 8 import os 9 import threading 10 import time 11 import collections.abc 12 import datetime 13 import weakref 14 15 from collections.abc import Mapping 16 from abc import ABCMeta, abstractmethod 17 from enum import Enum 18 19 from config import ctx 20 21 IWD_STORAGE_DIR = '/tmp/iwd' 22 IWD_CONFIG_DIR = '/tmp' 23 24 DBUS_OBJECT_MANAGER = 'org.freedesktop.DBus.ObjectManager' 25 DBUS_PROPERTIES = 'org.freedesktop.DBus.Properties' 26 27 IWD_SERVICE = 'net.connman.iwd' 28 IWD_WIPHY_INTERFACE = 'net.connman.iwd.Adapter' 29 IWD_AGENT_INTERFACE = 'net.connman.iwd.Agent' 30 IWD_AGENT_MANAGER_INTERFACE = 'net.connman.iwd.AgentManager' 31 IWD_DEVICE_INTERFACE = 'net.connman.iwd.Device' 32 IWD_KNOWN_NETWORK_INTERFACE = 'net.connman.iwd.KnownNetwork' 33 IWD_NETWORK_INTERFACE = 'net.connman.iwd.Network' 34 IWD_WSC_INTERFACE = 'net.connman.iwd.SimpleConfiguration' 35 IWD_SIGNAL_AGENT_INTERFACE = 'net.connman.iwd.SignalLevelAgent' 36 IWD_AP_INTERFACE = 'net.connman.iwd.AccessPoint' 37 IWD_ADHOC_INTERFACE = 'net.connman.iwd.AdHoc' 38 IWD_STATION_INTERFACE = 'net.connman.iwd.Station' 39 IWD_P2P_INTERFACE = 'net.connman.iwd.p2p.Device' 40 IWD_P2P_PEER_INTERFACE = 'net.connman.iwd.p2p.Peer' 41 IWD_P2P_SERVICE_MANAGER_INTERFACE = 'net.connman.iwd.p2p.ServiceManager' 42 IWD_P2P_WFD_INTERFACE = 'net.connman.iwd.p2p.Display' 43 IWD_STATION_DEBUG_INTERFACE = 'net.connman.iwd.StationDebug' 44 IWD_DPP_INTERFACE = 'net.connman.iwd.DeviceProvisioning' 45 IWD_DPP_PKEX_INTERFACE = 'net.connman.iwd.SharedCodeDeviceProvisioning' 46 IWD_SHARED_CODE_AGENT_INTERFACE = 'net.connman.iwd.SharedCodeAgent' 47 48 IWD_AGENT_MANAGER_PATH = '/net/connman/iwd' 49 IWD_TOP_LEVEL_PATH = '/' 50 51 class UnknownDBusEx(Exception): pass 52 class InProgressEx(dbus.DBusException): pass 53 class FailedEx(dbus.DBusException): pass 54 class AbortedEx(dbus.DBusException): pass 55 class NotAvailableEx(dbus.DBusException): pass 56 class InvalidArgumentsEx(dbus.DBusException): pass 57 class InvalidFormatEx(dbus.DBusException): pass 58 class AlreadyExistsEx(dbus.DBusException): pass 59 class NotFoundEx(dbus.DBusException): pass 60 class NotSupportedEx(dbus.DBusException): pass 61 class NoAgentEx(dbus.DBusException): pass 62 class NotConnectedEx(dbus.DBusException): pass 63 class NotConfiguredEx(dbus.DBusException): pass 64 class NotImplementedEx(dbus.DBusException): pass 65 class ServiceSetOverlapEx(dbus.DBusException): pass 66 class AlreadyProvisionedEx(dbus.DBusException): pass 67 class NotHiddenEx(dbus.DBusException): pass 68 class CanceledEx(dbus.DBusException): 69 _dbus_error_name = 'net.connman.iwd.Error.Canceled' 70 71 72 _dbus_ex_to_py = { 73 'Canceled' : CanceledEx, 74 'InProgress' : InProgressEx, 75 'Failed' : FailedEx, 76 'Aborted' : AbortedEx, 77 'NotAvailable' : NotAvailableEx, 78 'InvalidArguments' : InvalidArgumentsEx, 79 'InvalidFormat' : InvalidFormatEx, 80 'AlreadyExists' : AlreadyExistsEx, 81 'NotFound' : NotFoundEx, 82 'NotSupported' : NotSupportedEx, 83 'NoAgent' : NoAgentEx, 84 'NotConnected' : NotConnectedEx, 85 'NotConfigured' : NotConfiguredEx, 86 'NotImplemented' : NotImplementedEx, 87 'ServiceSetOverlap' : ServiceSetOverlapEx, 88 'AlreadyProvisioned' : AlreadyProvisionedEx, 89 'NotHidden' : NotHiddenEx, 90 } 91 92 93 def _convert_dbus_ex(dbus_ex): 94 ex_name = dbus_ex.get_dbus_name() 95 ex_short_name = ex_name[ex_name.rfind(".") + 1:] 96 if ex_short_name in _dbus_ex_to_py: 97 return _dbus_ex_to_py[ex_short_name](dbus_ex) 98 else: 99 return UnknownDBusEx(ex_name + ': ' + dbus_ex.get_dbus_message()) 100 101 102 class AsyncOpAbstract(object): 103 __metaclass__ = ABCMeta 104 105 _is_completed = False 106 _exception = None 107 108 def _success(self): 109 self._is_completed = True 110 111 def _failure(self, ex): 112 self._is_completed = True 113 self._exception = _convert_dbus_ex(ex) 114 115 def _wait_for_async_op(self, timeout=50): 116 ctx.non_block_wait(lambda s: s._is_completed, timeout, self, exception=None) 117 118 self._is_completed = False 119 if self._exception is not None: 120 tmp = self._exception 121 self._exception = None 122 raise tmp 123 124 125 class IWDDBusAbstract(AsyncOpAbstract): 126 __metaclass__ = ABCMeta 127 128 def __init__(self, object_path = None, properties = None, service=IWD_SERVICE, namespace=ctx): 129 self._bus = namespace.get_bus() 130 self._namespace = namespace 131 132 self._object_path = object_path 133 proxy = self._bus.get_object(service, self._object_path) 134 self._iface = dbus.Interface(proxy, self._iface_name) 135 self._prop_proxy = dbus.Interface(proxy, DBUS_PROPERTIES) 136 137 if properties is None: 138 self._properties = self._prop_proxy.GetAll(self._iface_name) 139 else: 140 self._properties = properties 141 142 self._prop_proxy.connect_to_signal("PropertiesChanged", 143 self._property_changed_handler, 144 DBUS_PROPERTIES, 145 path_keyword="path") 146 147 def _property_changed_handler(self, interface, changed, invalidated, path): 148 if interface == self._iface_name and path == self._object_path: 149 for name, value in changed.items(): 150 self._properties[name] = value 151 152 @abstractmethod 153 def __str__(self): 154 pass 155 156 157 class DeviceState(Enum): 158 '''Conection state of a device''' 159 connected = 'connected' 160 disconnected = 'disconnected' 161 connecting = 'connecting' 162 disconnecting = 'disconnecting' 163 roaming = 'roaming' 164 165 def __str__(self): 166 return self.value 167 168 @classmethod 169 def from_str(cls, string): 170 return getattr(cls, string, None) 171 172 173 class NetworkType(Enum): 174 '''Network security type''' 175 open = 'open' 176 psk = 'psk' 177 eap = '8021x' 178 hotspot = 'hotspot' 179 180 def __str__(self): 181 return str(self.value) 182 183 @classmethod 184 def from_string(cls, string): 185 type = None 186 for attr in dir(cls): 187 if (str(getattr(cls, attr)) == string): 188 type = getattr(cls, attr) 189 break 190 return type 191 192 193 class SignalAgent(dbus.service.Object): 194 def __init__(self, passphrase = None): 195 self._path = '/test/agent/' + str(int(round(time.time() * 1000))) 196 197 dbus.service.Object.__init__(self, ctx.get_bus(), self._path) 198 199 @property 200 def path(self): 201 return self._path 202 203 @dbus.service.method(IWD_SIGNAL_AGENT_INTERFACE, 204 in_signature='o', out_signature='') 205 def Release(self, path): 206 print("SignalAgent released %s" % path) 207 208 @dbus.service.method(IWD_SIGNAL_AGENT_INTERFACE, 209 in_signature='oy', out_signature='') 210 def Changed(self, path, level): 211 self.handle_new_level(str(path), int(level)) 212 213 @abstractmethod 214 def handle_new_level(self, path, level): 215 pass 216 217 class SharedCodeAgent(dbus.service.Object): 218 def __init__(self, codes = {}): 219 self._path = '/test/agent/' + str(int(round(time.time() * 1000))) 220 self._codes = codes 221 222 dbus.service.Object.__init__(self, ctx.get_bus(), self._path) 223 224 @property 225 def path(self): 226 return self._path 227 228 @dbus.service.method(IWD_SHARED_CODE_AGENT_INTERFACE, 229 in_signature='', out_signature='') 230 def Release(self): 231 print("SharedCodeAgent released") 232 233 @dbus.service.method(IWD_SHARED_CODE_AGENT_INTERFACE, 234 in_signature='s', out_signature='') 235 def Cancel(self, reason): 236 print("SharedCodeAgent canceled (%s)" % reason) 237 238 @dbus.service.method(IWD_SHARED_CODE_AGENT_INTERFACE, 239 in_signature='s', out_signature='s') 240 def RequestSharedCode(self, identifier): 241 print("SharedCodeAgent request for %s" % identifier) 242 243 code = self._codes.get(identifier, None) 244 if not code: 245 return NotFoundEx("No code found for %s" % identifier) 246 247 return code 248 249 class AdHocDevice(IWDDBusAbstract): 250 ''' 251 Class represents an AdHoc device object: net.connman.iwd.AdHoc 252 ''' 253 _iface_name = IWD_ADHOC_INTERFACE 254 255 @property 256 def started(self): 257 return self._properties['Started'] 258 259 @property 260 def connected_peers(self): 261 return self._properties['ConnectedPeers'] 262 263 class StationDebug(IWDDBusAbstract): 264 ''' 265 Class represents net.connman.iwd.StationDebug 266 ''' 267 _iface_name = IWD_STATION_DEBUG_INTERFACE 268 269 def __init__(self, *args, **kwargs): 270 self._events = [] 271 272 IWDDBusAbstract.__init__(self, *args, **kwargs) 273 274 self._iface.connect_to_signal("Event", self._event_handler) 275 276 def _event_handler(self, event, data): 277 self._events.insert(0, (event, data)) 278 279 @property 280 def autoconnect(self): 281 return self._properties['AutoConnect'] 282 283 def connect_bssid(self, address, wait=True): 284 self._iface.ConnectBssid( 285 dbus.ByteArray.fromhex(address.replace(':', '')), 286 reply_handler=self._success, 287 error_handler=self._failure 288 ) 289 290 if wait: 291 self._wait_for_async_op() 292 293 def roam(self, address): 294 self._iface.Roam(dbus.ByteArray.fromhex(address.replace(':', ''))) 295 296 def scan(self, frequencies): 297 frequencies = dbus.Array([dbus.UInt16(f) for f in frequencies]) 298 self._iface.Scan(frequencies) 299 300 def _poll_event(self, event): 301 for idx, e in enumerate(self._events): 302 if event == e[0]: 303 # Consume any older events 304 self._events = self._events[:idx] 305 return True 306 307 return False 308 309 def clear_events(self): 310 self._events = [] 311 312 def wait_for_event(self, event, timeout=10): 313 return ctx.non_block_wait(self._poll_event, timeout, event, 314 exception=TimeoutError("waiting for event")) 315 316 def event_ocurred(self, event): 317 return self._poll_event(event) 318 319 class DeviceProvisioning(IWDDBusAbstract): 320 ''' 321 Class represents net.connman.iwd.DeviceProvisioning 322 ''' 323 _iface_name = IWD_DPP_INTERFACE 324 325 def start_enrollee(self): 326 return self._iface.StartEnrollee() 327 328 def start_configurator(self, uri=None): 329 if uri: 330 return self._iface.ConfigureEnrollee(uri) 331 else: 332 return self._iface.StartConfigurator() 333 334 def stop(self): 335 self._iface.Stop() 336 337 @property 338 def uri(self): 339 return self._properties['URI'] 340 341 @property 342 def started(self): 343 return self._properties['Started'] 344 345 @property 346 def role(self): 347 return self._properties['Role'] 348 349 class SharedCodeDeviceProvisioning(IWDDBusAbstract): 350 _iface_name = IWD_DPP_PKEX_INTERFACE 351 352 def start_enrollee(self, code, identifier=None): 353 args = { 354 "Code": code 355 } 356 357 if identifier: 358 args["Identifier"] = identifier 359 360 self._iface.StartEnrollee(args) 361 362 def start_configurator(self, path): 363 self._iface.StartConfigurator(dbus.ObjectPath(path)) 364 365 def configure_enrollee(self, code, identifier=None): 366 args = { 367 "Code": code 368 } 369 370 if identifier: 371 args["Identifier"] = identifier 372 373 self._iface.ConfigureEnrollee(args) 374 375 def stop(self): 376 self._iface.Stop() 377 378 @property 379 def started(self): 380 return self._properties['Started'] 381 382 @property 383 def role(self): 384 return self._properties['Role'] 385 386 class AccessPointDevice(IWDDBusAbstract): 387 ''' 388 Class represents net.connman.iwd.AccessPoint 389 ''' 390 _iface_name = IWD_AP_INTERFACE 391 392 def start(self, ssid, psk): 393 self._iface.Start(ssid, psk, reply_handler=self._success, 394 error_handler=self._failure) 395 self._wait_for_async_op() 396 397 IWD._wait_for_object_condition(self, 'obj.started == True') 398 399 def start_profile(self, ssid): 400 self._iface.StartProfile(ssid, reply_handler=self._success, 401 error_handler=self._failure) 402 self._wait_for_async_op() 403 404 IWD._wait_for_object_condition(self, 'obj.started == True') 405 406 def stop(self): 407 self._iface.Stop(reply_handler=self._success, 408 error_handler=self._failure) 409 self._wait_for_async_op() 410 411 IWD._wait_for_object_condition(self, 'obj.started == False') 412 413 def scan(self): 414 self._iface.Scan(reply_handler=self._success, 415 error_handler=self._failure) 416 self._wait_for_async_op() 417 418 IWD._wait_for_object_condition(self, 'obj.scanning == True') 419 IWD._wait_for_object_condition(self, 'obj.scanning == False') 420 421 def get_ordered_networks(self): 422 return self._iface.GetOrderedNetworks() 423 424 @property 425 def started(self): 426 return self._properties['Started'] 427 428 @property 429 def name(self): 430 return self._properties['Name'] 431 432 @property 433 def scanning(self): 434 return self._properties['Scanning'] 435 436 @property 437 def frequency(self): 438 return self._properties['Frequency'] 439 440 @property 441 def pairwise_ciphers(self): 442 return self._properties['PairwiseCiphers'] 443 444 @property 445 def group_cipher(self): 446 return self._properties['GroupCipher'] 447 448 449 class Device(IWDDBusAbstract): 450 ''' 451 Class represents a network device object: net.connman.iwd.Device 452 with its properties and methods 453 ''' 454 _iface_name = IWD_DEVICE_INTERFACE 455 456 def __init__(self, *args, **kwargs): 457 self._wps_manager_if = None 458 self._station_if = None 459 self._station_props = None 460 self._dpp_obj = None 461 self._sc_dpp_obj = None 462 self._ap_obj = None 463 464 IWDDBusAbstract.__init__(self, *args, **kwargs) 465 466 self._station_debug_obj = StationDebug(object_path=self._object_path, 467 namespace=self._namespace) 468 469 @property 470 def _wps_manager(self): 471 if self._wps_manager_if is None: 472 _wps_manager_if =\ 473 dbus.Interface(self._bus.get_object(IWD_SERVICE, 474 self.device_path), 475 IWD_WSC_INTERFACE) 476 return _wps_manager_if 477 478 @property 479 def _station(self): 480 if self._station_if is None: 481 self._station_if = dbus.Interface(self._bus.get_object(IWD_SERVICE, 482 self.device_path), 483 IWD_STATION_INTERFACE) 484 return self._station_if 485 486 @property 487 def _device_provisioning(self): 488 if self._properties['Mode'] != 'station': 489 self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'station') 490 491 if self._dpp_obj is None: 492 self._dpp_obj = DeviceProvisioning(object_path=self._object_path, 493 namespace=self._namespace) 494 495 return self._dpp_obj 496 497 @property 498 def _sc_device_provisioning(self): 499 if self._properties['Mode'] != 'station': 500 self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'station') 501 502 if self._sc_dpp_obj is None: 503 self._sc_dpp_obj = SharedCodeDeviceProvisioning( 504 object_path=self._object_path, 505 namespace=self._namespace) 506 return self._sc_dpp_obj 507 508 @property 509 def _station_debug(self): 510 if self._properties['Mode'] != 'station': 511 self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'station') 512 513 if self._station_debug_obj is None: 514 self._station_debug_obj = StationDebug(object_path=self._object_path, 515 namespace=self._namespace) 516 517 return self._station_debug_obj 518 519 @property 520 def _ap(self): 521 if self._properties['Mode'] != 'ap': 522 self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'ap') 523 524 if self._ap_obj is None: 525 self._ap_obj = AccessPointDevice(object_path=self._object_path, 526 namespace=self._namespace) 527 528 return self._ap_obj 529 530 def _station_properties(self): 531 if self._station_props is not None: 532 return self._station_props 533 534 if self._properties['Mode'] != 'station': 535 self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'station') 536 537 self._station_prop_if = \ 538 dbus.Interface(self._bus.get_object(IWD_SERVICE, 539 self.device_path), 540 DBUS_PROPERTIES) 541 542 self._station_props = self._station_prop_if.GetAll(IWD_STATION_INTERFACE) 543 544 self._station_prop_if.connect_to_signal("PropertiesChanged", 545 self.__station_property_changed_handler, 546 DBUS_PROPERTIES, path_keyword="path") 547 548 return self._station_props 549 550 def __station_property_changed_handler(self, interface, changed, 551 invalidated, path): 552 if interface == IWD_STATION_INTERFACE and path == self._object_path: 553 for name, value in changed.items(): 554 self._station_props[name] = value 555 556 if name == 'Mode' and value != 'station': 557 self._station_debug_obj = None 558 559 @property 560 def device_path(self): 561 ''' 562 Device's dbus path. 563 564 @rtype: string 565 ''' 566 return self._object_path 567 568 @property 569 def name(self): 570 ''' 571 Device's interface name. 572 573 @rtype: string 574 ''' 575 return self._properties['Name'] 576 577 @property 578 def address(self): 579 ''' 580 Interface's hardware address in the XX:XX:XX:XX:XX:XX format. 581 582 @rtype: string 583 ''' 584 return self._properties['Address'] 585 586 @property 587 def state(self): 588 ''' 589 Reflects the general network connection state. 590 591 @rtype: object (State) 592 ''' 593 props = self._station_properties() 594 return DeviceState.from_str(props['State']) 595 596 @property 597 def connected_network(self): 598 ''' 599 net.connman.iwd.Network object representing the 600 network the device is currently connected to or to 601 which a connection is in progress. 602 603 @rtype: object (Network) 604 ''' 605 props = self._station_properties() 606 return props.get('ConnectedNetwork') 607 608 @property 609 def connected_bss(self): 610 props = self._station_properties() 611 return props.get('ConnectedAccessPoint') 612 613 @property 614 def powered(self): 615 ''' 616 True if the interface is UP. If false, the device's radio is 617 powered down and no other actions can be performed on the device. 618 619 @rtype: boolean 620 ''' 621 return bool(self._properties['Powered']) 622 623 @property 624 def scanning(self): 625 ''' 626 Reflects whether the device is currently scanning 627 for networks. For station devices net.connman.iwd.Network 628 objects are updated when this property goes from true to false 629 630 @rtype: boolean 631 ''' 632 if self._properties['Mode'] == 'station': 633 props = self._station_properties() 634 return bool(props['Scanning']) 635 else: 636 return bool(self._ap.scanning) 637 638 @property 639 def autoconnect(self): 640 return self._station_debug.autoconnect 641 642 @autoconnect.setter 643 def autoconnect(self, value): 644 self._station_debug._prop_proxy.Set(IWD_STATION_DEBUG_INTERFACE, 645 'AutoConnect', value) 646 647 @property 648 def affinities(self): 649 return self._station_properties()['Affinities'] 650 651 @affinities.setter 652 def affinities(self, values): 653 self._station_properties() 654 self._station_prop_if.Set( 655 IWD_STATION_INTERFACE, 'Affinities', 656 dbus.Array([dbus.ObjectPath(v) for v in values], signature="o"), 657 reply_handler=self._success, error_handler=self._failure) 658 self._wait_for_async_op() 659 660 def scan(self, wait=True): 661 '''Schedule a network scan. 662 663 Possible exception: BusyEx 664 FailedEx 665 ''' 666 if self._properties['Mode'] == 'station': 667 self._iface.Scan(dbus_interface=IWD_STATION_INTERFACE, 668 reply_handler=self._success, 669 error_handler=self._failure) 670 if wait: 671 self._wait_for_async_op() 672 else: 673 self._ap.scan() 674 675 def disconnect(self): 676 '''Disconnect from the network 677 678 Possible exception: BusyEx 679 FailedEx 680 NotConnectedEx 681 ''' 682 self._iface.Disconnect(dbus_interface=IWD_STATION_INTERFACE, 683 reply_handler=self._success, 684 error_handler=self._failure) 685 686 self._wait_for_async_op() 687 688 def get_ordered_networks(self, scan_if_needed = True, full_scan = False, list = []): 689 '''Return the list of networks found in the most recent 690 scan, sorted by their user interface importance 691 score as calculated by iwd. If the device is 692 currently connected to a network, that network is 693 always first on the list, followed by any known 694 networks that have been used at least once before, 695 followed by any other known networks and any other 696 detected networks as the last group. Within these 697 groups the maximum relative signal-strength is the 698 main sorting factor. 699 ''' 700 if self._properties['Mode'] == 'ap': 701 return self._ap.get_ordered_networks() 702 703 ordered_networks = [] 704 if not full_scan: 705 for bus_obj in self._station.GetOrderedNetworks(): 706 ordered_network = OrderedNetwork(bus_obj, self._bus, self._namespace) 707 ordered_networks.append(ordered_network) 708 709 names = [x.name for x in ordered_networks] 710 711 # all() will always return true if 'list' is empty 712 if all(x in names for x in list) and len(names) > 0: 713 return ordered_networks 714 elif not scan_if_needed: 715 return None 716 717 condition = 'not obj.scanning' 718 IWD._wait_for_object_condition(self, condition) 719 720 try: 721 # Do a full scan if instructed or if hostapd isn't being used 722 if full_scan or not ctx.hostapd: 723 self.scan() 724 else: 725 self.debug_scan(ctx.get_frequencies()) 726 except InProgressEx: 727 pass 728 729 condition = 'obj.scanning' 730 IWD._wait_for_object_condition(self, condition) 731 condition = 'not obj.scanning' 732 IWD._wait_for_object_condition(self, condition) 733 734 for bus_obj in self._station.GetOrderedNetworks(): 735 ordered_network = OrderedNetwork(bus_obj, self._bus, self._namespace) 736 ordered_networks.append(ordered_network) 737 738 if len(ordered_networks) > 0: 739 return ordered_networks 740 741 return None 742 743 def get_ordered_network(self, network, scan_if_needed = True, full_scan = False): 744 '''Returns a single network from ordered network call, or None if the 745 network wasn't found. If the network is not found an exception is 746 raised, this removes the need to extra asserts in autotests. 747 ''' 748 def wait_for_network(self, network, scan_if_needed, full_scan): 749 networks = self.get_ordered_networks(scan_if_needed, full_scan, list=[network]) 750 751 if not networks: 752 # No point in continuing if we aren't going to re-scan 753 if not scan_if_needed: 754 raise Exception("Network %s not found" % network) 755 756 return False 757 758 for n in networks: 759 if n.name == network: 760 return n 761 762 return False 763 764 return ctx.non_block_wait(wait_for_network, 30, self, network, scan_if_needed, full_scan, 765 exception=Exception("Network %s not found" % network)) 766 767 def wps_push_button(self): 768 self._wps_manager.PushButton(dbus_interface=IWD_WSC_INTERFACE, 769 reply_handler=self._success, 770 error_handler=self._failure) 771 self._wait_for_async_op() 772 773 def wps_generate_pin(self): 774 return self._wps_manager.GeneratePin() 775 776 def wps_start_pin(self, pin): 777 self._wps_manager.StartPin(pin, reply_handler=self._success, 778 error_handler=self._failure) 779 780 def wps_cancel(self): 781 self._wps_manager.Cancel(dbus_interface=IWD_WSC_INTERFACE, 782 reply_handler=self._success, 783 error_handler=self._failure) 784 self._wait_for_async_op() 785 786 def register_signal_agent(self, signal_agent, levels): 787 self._station.RegisterSignalLevelAgent(signal_agent.path, 788 dbus.Array(levels, 'n'), 789 dbus_interface=IWD_STATION_INTERFACE, 790 reply_handler=self._success, 791 error_handler=self._failure) 792 self._wait_for_async_op() 793 794 def unregister_signal_agent(self, signal_agent): 795 self._station.UnregisterSignalLevelAgent(signal_agent.path, 796 dbus_interface=IWD_STATION_INTERFACE, 797 reply_handler=self._success, 798 error_handler=self._failure) 799 self._wait_for_async_op() 800 801 def start_ap(self, ssid, psk=None): 802 try: 803 self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'ap') 804 except Exception as e: 805 raise _convert_dbus_ex(e) 806 807 if psk: 808 self._ap.start(ssid, psk) 809 else: 810 self._ap.start_profile(ssid) 811 812 def stop_ap(self): 813 self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'station') 814 815 IWD._wait_for_object_condition(self, "obj._properties['Mode'] == 'station'") 816 817 @property 818 def group_cipher(self): 819 if self._properties['Mode'] != 'ap': 820 raise Exception('group_cipher only supported in AP mode') 821 822 return self._ap.group_cipher 823 824 @property 825 def pairwise_ciphers(self): 826 if self._properties['Mode'] != 'ap': 827 raise Exception('pairwise_cipher only supported in AP mode') 828 829 return self._ap.pairwise_ciphers 830 831 def connect_hidden_network(self, name): 832 '''Connect to a hidden network 833 Possible exception: BusyEx 834 FailedEx 835 InvalidArgumentsEx 836 NotConfiguredEx 837 NotConnectedEx 838 NotFoundEx 839 ServiceSetOverlapEx 840 ''' 841 self._iface.ConnectHiddenNetwork(name, 842 dbus_interface=IWD_STATION_INTERFACE, 843 reply_handler=self._success, 844 error_handler=self._failure) 845 self._wait_for_async_op() 846 847 def connect_hidden_network_async(self, name, reply_handler, error_handler): 848 '''Connect to a hidden network 849 Possible exception: BusyEx 850 FailedEx 851 InvalidArgumentsEx 852 NotConfiguredEx 853 NotConnectedEx 854 NotFoundEx 855 ServiceSetOverlapEx 856 ''' 857 self._iface.ConnectHiddenNetwork(name, 858 dbus_interface=IWD_STATION_INTERFACE, 859 reply_handler=reply_handler, 860 error_handler=error_handler) 861 862 def start_adhoc(self, ssid, psk=None): 863 self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'ad-hoc') 864 self._adhoc_iface = dbus.Interface(self._bus.get_object(IWD_SERVICE, 865 self.device_path), 866 IWD_ADHOC_INTERFACE) 867 if not psk: 868 self._adhoc_iface.StartOpen(ssid, reply_handler=self._success, 869 error_handler=self._failure) 870 else: 871 self._adhoc_iface.Start(ssid, psk, reply_handler=self._success, 872 error_handler=self._failure) 873 self._wait_for_async_op() 874 875 return AdHocDevice(self.device_path) 876 877 def stop_adhoc(self): 878 self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'station') 879 880 def connect_bssid(self, address, wait=True): 881 self._station_debug.connect_bssid(address, wait=wait) 882 883 def roam(self, address): 884 self._station_debug.roam(address) 885 886 def debug_scan(self, frequencies): 887 self._station_debug.scan(frequencies) 888 889 def wait_for_event(self, event, timeout=10): 890 self._station_debug.wait_for_event(event, timeout) 891 892 def clear_events(self): 893 self._station_debug.clear_events() 894 895 def event_ocurred(self, event): 896 return self._station_debug.event_ocurred(event) 897 898 def dpp_start_enrollee(self): 899 ret = self._device_provisioning.start_enrollee() 900 901 condition = 'obj.started == True' 902 IWD._wait_for_object_condition(self._device_provisioning, condition) 903 condition = 'obj.role == "enrollee"' 904 IWD._wait_for_object_condition(self._device_provisioning, condition) 905 906 return ret 907 908 def dpp_start_configurator(self, uri=None): 909 ret = self._device_provisioning.start_configurator(uri) 910 911 condition = 'obj.started == True' 912 IWD._wait_for_object_condition(self._device_provisioning, condition) 913 condition = 'obj.role == "configurator"' 914 IWD._wait_for_object_condition(self._device_provisioning, condition) 915 916 return ret 917 918 def dpp_pkex_enroll(self, *args, **kwargs): 919 ret = self._sc_device_provisioning.start_enrollee(*args, **kwargs) 920 921 condition = 'obj.started == True' 922 IWD._wait_for_object_condition(self._sc_device_provisioning, condition) 923 condition = 'obj.role == "enrollee"' 924 IWD._wait_for_object_condition(self._sc_device_provisioning, condition) 925 926 return ret 927 928 def dpp_pkex_start_configurator(self, *args, **kwargs): 929 ret = self._sc_device_provisioning.start_configurator(*args, **kwargs) 930 931 condition = 'obj.started == True' 932 IWD._wait_for_object_condition(self._sc_device_provisioning, condition) 933 condition = 'obj.role == "configurator"' 934 IWD._wait_for_object_condition(self._sc_device_provisioning, condition) 935 936 return ret 937 938 def dpp_pkex_configure_enrollee(self, *args, **kwargs): 939 ret = self._sc_device_provisioning.configure_enrollee(*args, **kwargs) 940 941 condition = 'obj.started == True' 942 IWD._wait_for_object_condition(self._sc_device_provisioning, condition) 943 condition = 'obj.role == "configurator"' 944 IWD._wait_for_object_condition(self._sc_device_provisioning, condition) 945 946 return ret 947 948 def dpp_pkex_stop(self): 949 ret = self._sc_device_provisioning.stop() 950 951 condition = 'obj.started == False' 952 IWD._wait_for_object_condition(self._sc_device_provisioning, condition) 953 954 return ret 955 956 def dpp_pkex_register_agent(self, path): 957 self._sc_device_provisioning.register_agent(path) 958 959 def dpp_pkex_unregister_agent(self): 960 self._sc_device_provisioning.unregister_agent() 961 962 def dpp_stop(self): 963 ret = self._device_provisioning.stop() 964 965 condition = 'obj.started == False' 966 IWD._wait_for_object_condition(self._device_provisioning, condition) 967 968 return ret 969 970 def __str__(self, prefix = ''): 971 s = prefix + 'Device: ' + self.device_path + '\n'\ 972 + prefix + '\tName:\t\t' + self.name + '\n'\ 973 + prefix + '\tAddress:\t' + self.address + '\n' \ 974 + prefix + '\tPowered:\t' + str(self.powered) + '\n'\ 975 + prefix + '\tMode:\t\t' + self._properties['Mode'] + '\n' 976 977 if self._properties['Mode'] == 'station': 978 s += prefix + '\tState:\t\t' + str(self.state) + '\n'\ 979 + prefix + '\tConnected net:\t' + str(self.connected_network) + '\n' 980 981 return s 982 983 class Network(IWDDBusAbstract): 984 '''Class represents a network object: net.connman.iwd.Network''' 985 _iface_name = IWD_NETWORK_INTERFACE 986 987 @property 988 def name(self): 989 ''' 990 Network SSID. 991 992 @rtype: string 993 ''' 994 return self._properties['Name'] 995 996 @property 997 def connected(self): 998 ''' 999 Reflects whether the device is connected to this network. 1000 1001 @rtype: boolean 1002 ''' 1003 return bool(self._properties['Connected']) 1004 1005 @property 1006 def extended_service_set(self): 1007 return self._properties['ExtendedServiceSet'] 1008 1009 def connect(self, wait=True, timeout=50, reply_handler=None, error_handler=None): 1010 ''' 1011 Connect to the network. Request the device implied by the object 1012 path to connect to specified network. 1013 1014 Possible exception: AbortedEx 1015 BusyEx 1016 FailedEx 1017 NoAgentEx 1018 NotSupportedEx 1019 TimeoutEx 1020 1021 @rtype: void 1022 ''' 1023 1024 if not reply_handler: 1025 reply_handler = self._success 1026 1027 if not error_handler: 1028 error_handler = self._failure 1029 1030 self._iface.Connect(dbus_interface=self._iface_name, 1031 reply_handler=reply_handler, 1032 error_handler=error_handler, 1033 timeout=timeout) 1034 1035 if wait: 1036 self._wait_for_async_op(timeout=timeout) 1037 1038 def __str__(self, prefix = ''): 1039 return prefix + 'Network:\n' \ 1040 + prefix + '\tName:\t' + self.name + '\n' \ 1041 + prefix + '\tConnected:\t' + str(self.connected) 1042 1043 1044 class KnownNetwork(IWDDBusAbstract): 1045 '''Class represents a known network object: net.connman.iwd.KnownNetwork''' 1046 _iface_name = IWD_KNOWN_NETWORK_INTERFACE 1047 1048 def forget(self): 1049 ''' 1050 Removes information saved by IWD about this network 1051 causing it to be treated as if IWD had never connected 1052 to it before. 1053 ''' 1054 self._iface.Forget(dbus_interface=self._iface_name, 1055 reply_handler=self._success, 1056 error_handler=self._failure) 1057 self._wait_for_async_op() 1058 1059 @property 1060 def name(self): 1061 '''Contains the Name (SSID) of the network.''' 1062 return str(self._properties['Name']) 1063 1064 @property 1065 def type(self): 1066 '''Contains the type of the network.''' 1067 return NetworkType(self._properties['Type']) 1068 1069 @property 1070 def last_connected_time(self): 1071 ''' 1072 Contains the last time this network has been connected to. 1073 If the network is known, but has never been successfully 1074 connected to, this attribute is set to None. 1075 1076 @rtype: datetime 1077 ''' 1078 if 'LastConnectedTime' not in self._properties: 1079 return None 1080 1081 val = self._properties['LastConnectedTime'] 1082 return datetime.datetime.strptime(val, "%Y-%m-%dT%H:%M:%SZ") 1083 1084 def __str__(self, prefix = ''): 1085 return prefix + 'Known Network:\n' \ 1086 + prefix + '\tName:\t' + self.name + '\n' \ 1087 + prefix + '\tType:\t' + str(self.type) + '\n' \ 1088 + prefix + '\tLast connected:\t' + str(self.last_connected_time) 1089 1090 class OrderedNetwork(object): 1091 '''Represents a network found in the scan''' 1092 1093 def __init__(self, o_n_tuple, bus, namespace=ctx): 1094 self._bus = bus 1095 self._network_object = Network(o_n_tuple[0], namespace=namespace) 1096 self._network_proxy = dbus.Interface(self._bus.get_object(IWD_SERVICE, 1097 o_n_tuple[0]), 1098 DBUS_PROPERTIES) 1099 self._properties = self._network_proxy.GetAll(IWD_NETWORK_INTERFACE) 1100 1101 self._name = self._properties['Name'] 1102 self._signal_strength = o_n_tuple[1] 1103 self._type = NetworkType.from_string(str(self._properties['Type'])) 1104 1105 @property 1106 def network_object(self): 1107 ''' 1108 net.connman.iwd.Network object representing the network. 1109 1110 @rtype: Network 1111 ''' 1112 return self._network_object 1113 1114 @property 1115 def name(self): 1116 ''' 1117 Device's interface name. 1118 1119 @rtype: string 1120 ''' 1121 return self._name 1122 1123 @property 1124 def signal_strength(self): 1125 ''' 1126 Network's maximum signal strength expressed in 100 * dBm. 1127 The value is the range of 0 (strongest signal) to 1128 -10000 (weakest signal) 1129 1130 @rtype: number 1131 ''' 1132 return self._signal_strength 1133 1134 @property 1135 def type(self): 1136 ''' 1137 Contains the type of the network. 1138 1139 @rtype: NetworkType 1140 ''' 1141 return self._type 1142 1143 def __str__(self): 1144 return 'Ordered Network:\n'\ 1145 '\tName:\t\t' + self._name + '\n'\ 1146 '\tNetwork Type:\t' + str(self._type) + '\n'\ 1147 '\tSignal Strength:'\ 1148 + ('None' if self.signal_strength is None else\ 1149 str(self.signal_strength)) + '\n'\ 1150 '\tObject: \n' + self.network_object.__str__('\t\t') 1151 1152 agent_count = 0 1153 1154 class PSKAgent(dbus.service.Object): 1155 1156 def __init__(self, passphrases=[], users=[], namespace=ctx): 1157 global agent_count 1158 1159 if type(passphrases) != list: 1160 passphrases = [passphrases] 1161 self.passphrases = passphrases 1162 if type(users) != list: 1163 users = [users] 1164 self.users = users 1165 self._path = '/test/agent/%s' % agent_count 1166 self._bus = dbus.bus.BusConnection(address_or_type=namespace.dbus_address) 1167 1168 agent_count += 1 1169 1170 dbus.service.Object.__init__(self, self._bus, self._path) 1171 1172 @property 1173 def path(self): 1174 return self._path 1175 1176 @dbus.service.method(IWD_AGENT_INTERFACE, in_signature='', out_signature='') 1177 def Release(self): 1178 print("Agent released") 1179 1180 @dbus.service.method(IWD_AGENT_INTERFACE, in_signature='s', 1181 out_signature='') 1182 def Cancel(self, reason): 1183 print("Cancel: " + reason) 1184 1185 1186 @dbus.service.method(IWD_AGENT_INTERFACE, in_signature='o', 1187 out_signature='s') 1188 def RequestPassphrase(self, path): 1189 print('Requested PSK for ' + path) 1190 1191 if not self.passphrases: 1192 raise CanceledEx("canceled") 1193 1194 return self.passphrases.pop(0) 1195 1196 @dbus.service.method(IWD_AGENT_INTERFACE, in_signature='o', 1197 out_signature='s') 1198 def RequestPrivateKeyPassphrase(self, path): 1199 print('Requested private-key passphrase for ' + path) 1200 1201 if not self.passphrases: 1202 raise CanceledEx("canceled") 1203 1204 return self.passphrases.pop(0) 1205 1206 @dbus.service.method(IWD_AGENT_INTERFACE, in_signature='o', 1207 out_signature='ss') 1208 def RequestUserNameAndPassword(self, path): 1209 print('Requested the user name and password for ' + path) 1210 1211 if not self.users: 1212 raise CanceledEx("canceled") 1213 1214 return self.users.pop(0) 1215 1216 @dbus.service.method(IWD_AGENT_INTERFACE, in_signature='os', 1217 out_signature='s') 1218 def RequestUserPassword(self, path, req_user): 1219 print('Requested the password for ' + path + ' for user ' + req_user) 1220 1221 if not self.users: 1222 raise CanceledEx("canceled") 1223 1224 user, passwd = self.users.pop(0) 1225 if user != req_user: 1226 raise CanceledEx("canceled") 1227 1228 return passwd 1229 1230 1231 class P2PDevice(IWDDBusAbstract): 1232 _iface_name = IWD_P2P_INTERFACE 1233 1234 def __init__(self, *args, **kwargs): 1235 self._discovery_request = False 1236 self._peer_dict = {} 1237 IWDDBusAbstract.__init__(self, *args, **kwargs) 1238 1239 @property 1240 def name(self): 1241 return str(self._properties['Name']) 1242 1243 @name.setter 1244 def name(self, name): 1245 self._prop_proxy.Set(self._iface_name, 'Name', name) 1246 1247 @property 1248 def enabled(self): 1249 return bool(self._properties['Enabled']) 1250 1251 @enabled.setter 1252 def enabled(self, enabled): 1253 self._prop_proxy.Set(self._iface_name, 'Enabled', enabled) 1254 1255 @property 1256 def discovery_request(self): 1257 return self._discovery_request 1258 1259 @discovery_request.setter 1260 def discovery_request(self, req): 1261 if self._discovery_request == bool(req): 1262 return 1263 1264 if bool(req): 1265 self._iface.RequestDiscovery() 1266 else: 1267 self._iface.ReleaseDiscovery() 1268 1269 self._discovery_request = bool(req) 1270 1271 def get_peers(self): 1272 old_dict = self._peer_dict 1273 self._peer_dict = {} 1274 1275 for path, rssi in self._iface.GetPeers(): 1276 self._peer_dict[path] = old_dict[path] if path in old_dict else P2PPeer(path, namespace=self._namespace) 1277 self._peer_dict[path].rssi = rssi 1278 1279 return self._peer_dict 1280 1281 1282 class P2PPeer(IWDDBusAbstract): 1283 _iface_name = IWD_P2P_PEER_INTERFACE 1284 1285 @property 1286 def name(self): 1287 return str(self._properties['Name']) 1288 1289 @property 1290 def category(self): 1291 return str(self._properties['DeviceCategory']) 1292 1293 @property 1294 def subcategory(self): 1295 return str(self._properties['DeviceSubcategory']) 1296 1297 @property 1298 def connected(self): 1299 return bool(self._properties['Connected']) 1300 1301 @property 1302 def connected_interface(self): 1303 return str(self._properties['ConnectedInterface']) 1304 1305 @property 1306 def connected_ip(self): 1307 return str(self._properties['ConnectedIP']) 1308 1309 def connect(self, wait=True, pin=None): 1310 if pin is None: 1311 self._iface.PushButton(dbus_interface=IWD_WSC_INTERFACE, 1312 reply_handler=self._success, 1313 error_handler=self._failure) 1314 else: 1315 self._iface.StartPin(pin, 1316 dbus_interface=IWD_WSC_INTERFACE, 1317 reply_handler=self._success, 1318 error_handler=self._failure) 1319 1320 if wait: 1321 self._wait_for_async_op() 1322 return (self.connected_interface, self.connected_ip) 1323 1324 def disconnect(self): 1325 self._iface.Disconnect() 1326 1327 1328 class DeviceList(Mapping): 1329 def __init__(self, iwd): 1330 self._dict = {} 1331 self._p2p_dict = {} 1332 self._namespace = iwd.namespace 1333 1334 iwd._object_manager.connect_to_signal("InterfacesAdded", 1335 self._interfaces_added_handler) 1336 iwd._object_manager.connect_to_signal("InterfacesRemoved", 1337 self._interfaces_removed_handler) 1338 1339 objects = iwd._object_manager.GetManagedObjects() 1340 1341 for path in objects: 1342 for interface in objects[path]: 1343 if interface == IWD_DEVICE_INTERFACE: 1344 self._dict[path] = Device(path, objects[path][interface], 1345 namespace=self._namespace) 1346 elif interface == IWD_P2P_INTERFACE: 1347 self._p2p_dict[path] = P2PDevice(path, objects[path][interface], 1348 namespace=self._namespace) 1349 1350 def __getitem__(self, key): 1351 return self._dict.__getitem__(key) 1352 1353 def __iter__(self): 1354 return self._dict.__iter__() 1355 1356 def __len__(self): 1357 return self._dict.__len__() 1358 1359 def __delitem__(self, key): 1360 self._dict.pop(key).remove() 1361 1362 def _interfaces_added_handler(self, path, interfaces): 1363 if IWD_DEVICE_INTERFACE in interfaces: 1364 self._dict[path] = Device(path, interfaces[IWD_DEVICE_INTERFACE], 1365 namespace=self._namespace) 1366 elif IWD_P2P_INTERFACE in interfaces: 1367 self._p2p_dict[path] = P2PDevice(path, interfaces[IWD_P2P_INTERFACE], 1368 namespace=self._namespace) 1369 1370 def _interfaces_removed_handler(self, path, interfaces): 1371 if IWD_DEVICE_INTERFACE in interfaces: 1372 del self._dict[path] 1373 elif IWD_P2P_INTERFACE in interfaces: 1374 del self._p2p_dict[path] 1375 1376 @property 1377 def p2p_dict(self): 1378 return self._p2p_dict 1379 1380 1381 class IWD(AsyncOpAbstract): 1382 ''' 1383 Start an IWD instance. By default IWD should already be running, but 1384 some tests do require starting IWD using this constructor (by passing 1385 start_iwd_daemon=True) 1386 ''' 1387 _default_instance = None 1388 1389 def __init__(self, start_iwd_daemon = False, iwd_config_dir = '/tmp', 1390 iwd_storage_dir = IWD_STORAGE_DIR, namespace=ctx, 1391 developer_mode = True): 1392 self.namespace = namespace 1393 self._bus = namespace.get_bus() 1394 self._object_manager_if = None 1395 self._iwd_proc = None 1396 1397 if start_iwd_daemon: 1398 if self.namespace.is_process_running('iwd'): 1399 raise Exception("IWD requested to start but is already running") 1400 1401 self._iwd_proc = self.namespace.start_iwd(iwd_config_dir, 1402 iwd_storage_dir, 1403 developer_mode) 1404 1405 self._devices = DeviceList(self) 1406 1407 # Weak to make sure the test's reference to @self is the only counted 1408 # reference so that __del__ gets called when it's released. This is only 1409 # done for the root namespace in order to allow testutil to function 1410 # correctly in non-namespace tests. 1411 if self.namespace.name is None: 1412 IWD._default_instance = weakref.ref(self) 1413 1414 self.psk_agents = [] 1415 1416 def stop(self): 1417 if self.namespace.is_process_running('iwd'): 1418 self._iwd_proc.kill() 1419 1420 def __del__(self): 1421 for agent in self.psk_agents: 1422 self.unregister_psk_agent(agent) 1423 1424 self.psk_agents = [] 1425 1426 self._object_manager_if = None 1427 self._known_networks = None 1428 self._devices = None 1429 1430 if self._iwd_proc is not None: 1431 self.namespace.stop_process(self._iwd_proc) 1432 self._iwd_proc = None 1433 1434 self.namespace = None 1435 1436 @property 1437 def _object_manager(self): 1438 if self._object_manager_if is None: 1439 self._object_manager_if = \ 1440 dbus.Interface(self._bus.get_object(IWD_SERVICE, 1441 IWD_TOP_LEVEL_PATH), 1442 DBUS_OBJECT_MANAGER) 1443 return self._object_manager_if 1444 1445 @staticmethod 1446 def _wait_for_object_condition(obj, condition_str, max_wait = 50): 1447 def _eval_wrap(obj, condition_str): 1448 return eval(condition_str) 1449 1450 ctx.non_block_wait(_eval_wrap, max_wait, obj, condition_str, 1451 exception=TimeoutError('[' + condition_str + ']'\ 1452 ' condition was not met in '\ 1453 + str(max_wait) + ' sec')) 1454 1455 def wait_for_object_condition(self, *args, **kwargs): 1456 self._wait_for_object_condition(*args, **kwargs) 1457 1458 def wait_for_object_change(self, obj, from_str, to_str, max_wait = 50): 1459 ''' 1460 Wait for 'from_str' to evaluate true then waits for 'to_str'. If 1461 at any point during the wait 'from_str' evaluates false, an exception is 1462 raised. 1463 1464 This allows an object to be checked for a state transition without any 1465 intermediate state changes. 1466 ''' 1467 def _eval_from_to(obj, from_str, to_str): 1468 # If neither the initial or expected condition evaluate the 1469 # object must be in another unexpected state. 1470 if not eval(from_str) and not eval(to_str): 1471 raise Exception('unexpected condition between [%s] and [%s]' % 1472 (from_str, to_str)) 1473 1474 # Initial condition does not evaluate but expected does, pass 1475 if not eval(from_str) and eval(to_str): 1476 return True 1477 1478 return False 1479 1480 # wait for initial condition 1481 self._wait_for_object_condition(obj, from_str) 1482 1483 ctx.non_block_wait(_eval_from_to, max_wait, obj, from_str, to_str, 1484 exception=TimeoutError('[' + to_str + ']'\ 1485 ' condition was not met in '\ 1486 + str(max_wait) + ' sec')) 1487 1488 @staticmethod 1489 def wait(time): 1490 ctx.non_block_wait(lambda : False, time, exception=False) 1491 1492 @staticmethod 1493 def clear_storage(storage_dir=IWD_STORAGE_DIR): 1494 os.system('rm -rf ' + storage_dir + '/*') 1495 os.system('rm -rf ' + storage_dir + '/hotspot/*') 1496 os.system('rm -rf ' + storage_dir + '/ap/*') 1497 1498 @staticmethod 1499 def create_in_storage(file_name, file_content, storage_dir=IWD_STORAGE_DIR): 1500 f = open(storage_dir + '/' + file_name, 'w') 1501 1502 f.write(file_content) 1503 f.close() 1504 1505 @staticmethod 1506 def _ensure_storage_dir_exists(storage_dir): 1507 if not os.path.exists(storage_dir): 1508 os.mkdir(storage_dir) 1509 1510 @staticmethod 1511 def copy_to_storage(source, storage_dir=IWD_STORAGE_DIR, name=None): 1512 import shutil 1513 1514 assert not os.path.isabs(source) 1515 1516 target = storage_dir 1517 if name: 1518 target += '/%s' % name 1519 1520 IWD._ensure_storage_dir_exists(storage_dir) 1521 shutil.copy(source, target) 1522 1523 @staticmethod 1524 def copy_to_hotspot(source, storage_dir=IWD_STORAGE_DIR): 1525 IWD._ensure_storage_dir_exists(storage_dir) 1526 1527 if not os.path.exists(storage_dir + "/hotspot"): 1528 os.mkdir(storage_dir + "/hotspot") 1529 1530 IWD.copy_to_storage(source, storage_dir + "/hotspot") 1531 1532 @staticmethod 1533 def copy_to_ap(source, storage_dir=IWD_STORAGE_DIR): 1534 if not os.path.exists(storage_dir + "/ap"): 1535 os.mkdir(storage_dir + "/ap") 1536 1537 IWD.copy_to_storage(source, storage_dir + '/ap/') 1538 1539 @staticmethod 1540 def remove_from_storage(file_name, storage_dir=IWD_STORAGE_DIR): 1541 os.system('rm -rf ' + storage_dir + '/\'' + file_name + '\'') 1542 1543 def list_devices(self, wait_to_appear = 0, max_wait = 50, p2p = False): 1544 if not wait_to_appear: 1545 return list(self._devices.values() if not p2p else self._devices.p2p_dict.values()) 1546 1547 ctx.non_block_wait(lambda s, n: len(s._devices) >= n, max_wait, self, wait_to_appear, 1548 exception=TimeoutError('IWD has no associated devices')) 1549 1550 return list(self._devices.values() if not p2p else self._devices.p2p_dict.values())[:wait_to_appear] 1551 1552 def list_p2p_devices(self, *args, **kwargs): 1553 return self.list_devices(*args, **kwargs, p2p=True) 1554 1555 def list_known_networks(self): 1556 '''Returns the list of KnownNetwork objects.''' 1557 objects = self._object_manager.GetManagedObjects() 1558 known_network_list = [] 1559 1560 for path in objects: 1561 for interface in objects[path]: 1562 if interface == IWD_KNOWN_NETWORK_INTERFACE: 1563 known_network_list.append( 1564 KnownNetwork(path, objects[path][interface])) 1565 1566 return known_network_list 1567 1568 def register_psk_agent(self, psk_agent): 1569 iface = dbus.Interface(psk_agent._bus.get_object(IWD_SERVICE, 1570 IWD_AGENT_MANAGER_PATH), 1571 IWD_AGENT_MANAGER_INTERFACE) 1572 iface.RegisterAgent(psk_agent.path, 1573 dbus_interface=IWD_AGENT_MANAGER_INTERFACE, 1574 reply_handler=self._success, 1575 error_handler=self._failure) 1576 1577 self._wait_for_async_op() 1578 self.psk_agents.append(psk_agent) 1579 1580 def unregister_psk_agent(self, psk_agent): 1581 iface = dbus.Interface(psk_agent._bus.get_object(IWD_SERVICE, 1582 IWD_AGENT_MANAGER_PATH), 1583 IWD_AGENT_MANAGER_INTERFACE) 1584 iface.UnregisterAgent(psk_agent.path, 1585 dbus_interface=IWD_AGENT_MANAGER_INTERFACE, 1586 reply_handler=self._success, 1587 error_handler=self._failure) 1588 self._wait_for_async_op() 1589 self.psk_agents.remove(psk_agent) 1590 1591 @staticmethod 1592 def get_instance(): 1593 return IWD._default_instance()