Function for checking wifi connection


#1

I’ve written this code to check wifi connectivity every 5 seconds with Photon, and of course can easily be converted for cc3000 (just comment/uncommment the proper line and mod the code relating the onboard led?).
This function:
-check for wifi connection status
-if there isn’t a connection it scans for available wireless network
-connect to wifi with the given ssid and password assuming that the wifi protection is wpa2.
-can be run as a thread to be sure that in case of disconnection from the wireless AP the board will restore the connection
-uses the Photon onboard RGB led in this way: blue (no connection, trying to connect) green (connected), red (error in the code).

Any improvement or suggestion for the code would be very appreciated

import streams
streams.serial()
############################################
from wireless import wifi

uncomment the following line to use the CC3000 driver (Particle Core or CC3000 Wifi shields)

from cc3000 import cc3000 as wifi_driver

uncomment the following line to use the BCM43362 driver (Particle Photon)

from bcm43362 import bcm43362 as wifi_driver
wifi_driver.auto_init()
############################################

def smartWifiLink(ap_ssid, ap_password):
ap_connection_status = 1
while True:
sleep(5000)
print(“Checking Wi-Fi connection status”)
if wifi.is_linked() != True:
ap_connection_status = 1
digitalWrite(D13,HIGH)# turn OFF green photon rgb led
digitalWrite(D14,LOW)# turn ON red photon rgb led
else:
ap_connection_status = 0
digitalWrite(D14,HIGH)# turn OFF blue photon rgb led
digitalWrite(D13,LOW) #turn ON green photon rgb led
if ap_connection_status == 1:
print(“Wi-Fi is not connected, restabilishing connection…”)
while ap_connection_status == 1:
list_available_wifi_ap = wifi.scan(500)
for wifi_ap in list_available_wifi_ap:
if wifi_ap[0] == ap_ssid:
wifi.link(ap_ssid,wifi.WIFI_WPA2,ap_password)
ap_connection_status = 0
print(“Wi-Fi connection reestablished”)
else:
print(“Wi-Fi connection: OK”)

try:

thread(smartWifiLink('SSID', 'password'))

except Exception as e:

print (e)

digitalWrite(D12,LOW)# turn ON red photon rgb led
digitalWrite(D13,HIGH)# turn OFF green photon rgb led
digitalWrite(D14,HIGH)# turn OFF blue photon rgb led<br>
<br>