wifi_tools.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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 dbus
  16. import dbus.mainloop.glib
  17. import netifaces
  18. import time
  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. dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  40. bus = dbus.SystemBus()
  41. service = dbus.Interface(bus.get_object("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
  42. "fi.w1.wpa_supplicant1")
  43. iface_path = service.GetInterface(self.iface_name)
  44. self.iface_obj = bus.get_object("fi.w1.wpa_supplicant1", iface_path)
  45. self.iface_ifc = dbus.Interface(self.iface_obj, "fi.w1.wpa_supplicant1.Interface")
  46. self.iface_props = dbus.Interface(self.iface_obj, 'org.freedesktop.DBus.Properties')
  47. if self.iface_ifc is None:
  48. raise RuntimeError('supplicant : Failed to fetch interface')
  49. self.old_network = self._get_iface_property("CurrentNetwork")
  50. print("Old network is %s" % self.old_network)
  51. if self.old_network == '/':
  52. self.old_network = None
  53. else:
  54. self.connected = True
  55. def _get_iface_property(self, name):
  56. """ Read the property with 'name' from the wi-fi interface object
  57. Note: The result is a dbus wrapped type, so should usually convert it to the corresponding native
  58. Python type
  59. """
  60. return self.iface_props.Get("fi.w1.wpa_supplicant1.Interface", name)
  61. def connect(self, ssid, password):
  62. if self.connected is True:
  63. self.iface_ifc.Disconnect()
  64. self.connected = False
  65. if self.new_network is not None:
  66. self.iface_ifc.RemoveNetwork(self.new_network)
  67. print("Pre-connect state is %s, IP is %s" % (self._get_iface_property("State"), get_wiface_IPv4(self.iface_name)))
  68. self.new_network = self.iface_ifc.AddNetwork({"ssid": ssid, "psk": password})
  69. self.iface_ifc.SelectNetwork(self.new_network)
  70. ip = None
  71. retry = 10
  72. while retry > 0:
  73. time.sleep(5)
  74. state = str(self._get_iface_property("State"))
  75. print("wpa iface state %s (scanning %s)" % (state, bool(self._get_iface_property("Scanning"))))
  76. if state in ["disconnected", "inactive"]:
  77. self.iface_ifc.Reconnect()
  78. ip = get_wiface_IPv4(self.iface_name)
  79. print("wpa iface %s IP %s" % (self.iface_name, ip))
  80. if ip is not None:
  81. self.connected = True
  82. return ip
  83. retry -= 1
  84. self.reset()
  85. raise RuntimeError('wpa_cli : Connection failed')
  86. def reset(self):
  87. if self.iface_ifc is not None:
  88. if self.connected is True:
  89. self.iface_ifc.Disconnect()
  90. self.connected = False
  91. if self.new_network is not None:
  92. self.iface_ifc.RemoveNetwork(self.new_network)
  93. self.new_network = None
  94. if self.old_network is not None:
  95. self.iface_ifc.SelectNetwork(self.old_network)
  96. self.old_network = None
  97. def __del__(self):
  98. if self.reset_on_exit is True:
  99. self.reset()