wifi_tools.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # Copyright 2018 Espressif Systems (Shanghai) PTE LTD
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. import time
  16. import dbus
  17. import dbus.mainloop.glib
  18. import netifaces
  19. def get_wiface_name():
  20. for iface in netifaces.interfaces():
  21. if iface.startswith('w'):
  22. return iface
  23. return None
  24. def get_wiface_IPv4(iface):
  25. try:
  26. [info] = netifaces.ifaddresses(iface)[netifaces.AF_INET]
  27. return info['addr']
  28. except KeyError:
  29. return None
  30. class wpa_cli:
  31. def __init__(self, iface, reset_on_exit=False):
  32. self.iface_name = iface
  33. self.iface_obj = None
  34. self.iface_ifc = None
  35. self.old_network = None
  36. self.new_network = None
  37. self.connected = False
  38. self.reset_on_exit = reset_on_exit
  39. try:
  40. dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  41. bus = dbus.SystemBus()
  42. service = dbus.Interface(bus.get_object('fi.w1.wpa_supplicant1', '/fi/w1/wpa_supplicant1'),
  43. 'fi.w1.wpa_supplicant1')
  44. iface_path = service.GetInterface(self.iface_name)
  45. self.iface_obj = bus.get_object('fi.w1.wpa_supplicant1', iface_path)
  46. self.iface_ifc = dbus.Interface(self.iface_obj, 'fi.w1.wpa_supplicant1.Interface')
  47. self.iface_props = dbus.Interface(self.iface_obj, 'org.freedesktop.DBus.Properties')
  48. if self.iface_ifc is None:
  49. raise RuntimeError('supplicant : Failed to fetch interface')
  50. self.old_network = self._get_iface_property('CurrentNetwork')
  51. print('Old network is %s' % self.old_network)
  52. if self.old_network == '/':
  53. self.old_network = None
  54. else:
  55. self.connected = True
  56. except Exception as err:
  57. raise Exception('Failure in wpa_cli init: {}'.format(err))
  58. def _get_iface_property(self, name):
  59. """ Read the property with 'name' from the wi-fi interface object
  60. Note: The result is a dbus wrapped type, so should usually convert it to the corresponding native
  61. Python type
  62. """
  63. return self.iface_props.Get('fi.w1.wpa_supplicant1.Interface', name)
  64. def connect(self, ssid, password):
  65. try:
  66. if self.connected is True:
  67. self.iface_ifc.Disconnect()
  68. self.connected = False
  69. if self.new_network is not None:
  70. self.iface_ifc.RemoveNetwork(self.new_network)
  71. print('Pre-connect state is %s, IP is %s' % (self._get_iface_property('State'), get_wiface_IPv4(self.iface_name)))
  72. self.new_network = self.iface_ifc.AddNetwork({'ssid': ssid, 'psk': password})
  73. self.iface_ifc.SelectNetwork(self.new_network)
  74. time.sleep(10)
  75. ip = None
  76. retry = 10
  77. while retry > 0:
  78. time.sleep(5)
  79. state = str(self._get_iface_property('State'))
  80. print('wpa iface state %s (scanning %s)' % (state, bool(self._get_iface_property('Scanning'))))
  81. if state in ['disconnected', 'inactive']:
  82. self.iface_ifc.Reconnect()
  83. ip = get_wiface_IPv4(self.iface_name)
  84. print('wpa iface %s IP %s' % (self.iface_name, ip))
  85. if ip is not None:
  86. self.connected = True
  87. return ip
  88. retry -= 1
  89. time.sleep(3)
  90. self.reset()
  91. print('wpa_cli : Connection failed')
  92. except Exception as err:
  93. raise Exception('Failure in wpa_cli init: {}'.format(err))
  94. def reset(self):
  95. if self.iface_ifc is not None:
  96. if self.connected is True:
  97. self.iface_ifc.Disconnect()
  98. self.connected = False
  99. if self.new_network is not None:
  100. self.iface_ifc.RemoveNetwork(self.new_network)
  101. self.new_network = None
  102. if self.old_network is not None:
  103. self.iface_ifc.SelectNetwork(self.old_network)
  104. self.old_network = None
  105. def __del__(self):
  106. if self.reset_on_exit is True:
  107. self.reset()