wifi_tools.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. #
  4. import time
  5. import dbus
  6. import dbus.mainloop.glib
  7. import netifaces
  8. def get_wiface_name():
  9. for iface in netifaces.interfaces():
  10. if iface.startswith('w'):
  11. return iface
  12. return None
  13. def get_wiface_IPv4(iface):
  14. try:
  15. [info] = netifaces.ifaddresses(iface)[netifaces.AF_INET]
  16. return info['addr']
  17. except KeyError:
  18. return None
  19. class wpa_cli:
  20. def __init__(self, iface, reset_on_exit=False):
  21. self.iface_name = iface
  22. self.iface_obj = None
  23. self.iface_ifc = None
  24. self.old_network = None
  25. self.new_network = None
  26. self.connected = False
  27. self.reset_on_exit = reset_on_exit
  28. try:
  29. dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  30. bus = dbus.SystemBus()
  31. service = dbus.Interface(bus.get_object('fi.w1.wpa_supplicant1', '/fi/w1/wpa_supplicant1'),
  32. 'fi.w1.wpa_supplicant1')
  33. iface_path = service.GetInterface(self.iface_name)
  34. self.iface_obj = bus.get_object('fi.w1.wpa_supplicant1', iface_path)
  35. self.iface_ifc = dbus.Interface(self.iface_obj, 'fi.w1.wpa_supplicant1.Interface')
  36. self.iface_props = dbus.Interface(self.iface_obj, 'org.freedesktop.DBus.Properties')
  37. if self.iface_ifc is None:
  38. raise RuntimeError('supplicant : Failed to fetch interface')
  39. self.old_network = self._get_iface_property('CurrentNetwork')
  40. print('Old network is %s' % self.old_network)
  41. if self.old_network == '/':
  42. self.old_network = None
  43. else:
  44. self.connected = True
  45. except Exception as err:
  46. raise Exception('Failure in wpa_cli init: {}'.format(err))
  47. def _get_iface_property(self, name):
  48. """ Read the property with 'name' from the wi-fi interface object
  49. Note: The result is a dbus wrapped type, so should usually convert it to the corresponding native
  50. Python type
  51. """
  52. return self.iface_props.Get('fi.w1.wpa_supplicant1.Interface', name)
  53. def connect(self, ssid, password):
  54. try:
  55. if self.connected is True:
  56. self.iface_ifc.Disconnect()
  57. self.connected = False
  58. if self.new_network is not None:
  59. self.iface_ifc.RemoveNetwork(self.new_network)
  60. print('Pre-connect state is %s, IP is %s' % (self._get_iface_property('State'), get_wiface_IPv4(self.iface_name)))
  61. self.new_network = self.iface_ifc.AddNetwork({'ssid': ssid, 'psk': password})
  62. self.iface_ifc.SelectNetwork(self.new_network)
  63. time.sleep(10)
  64. ip = None
  65. retry = 10
  66. while retry > 0:
  67. time.sleep(5)
  68. state = str(self._get_iface_property('State'))
  69. print('wpa iface state %s (scanning %s)' % (state, bool(self._get_iface_property('Scanning'))))
  70. if state in ['disconnected', 'inactive']:
  71. self.iface_ifc.Reconnect()
  72. ip = get_wiface_IPv4(self.iface_name)
  73. print('wpa iface %s IP %s' % (self.iface_name, ip))
  74. if ip is not None:
  75. self.connected = True
  76. return ip
  77. retry -= 1
  78. time.sleep(3)
  79. self.reset()
  80. print('wpa_cli : Connection failed')
  81. except Exception as err:
  82. raise Exception('Failure in wpa_cli init: {}'.format(err))
  83. def reset(self):
  84. if self.iface_ifc is not None:
  85. if self.connected is True:
  86. self.iface_ifc.Disconnect()
  87. self.connected = False
  88. if self.new_network is not None:
  89. self.iface_ifc.RemoveNetwork(self.new_network)
  90. self.new_network = None
  91. if self.old_network is not None:
  92. self.iface_ifc.SelectNetwork(self.old_network)
  93. self.old_network = None
  94. def __del__(self):
  95. if self.reset_on_exit is True:
  96. self.reset()