#Region Project Attributes
#AutoFlushLogs: True
#CheckArrayBounds: True
#StackBufferSize: 600
#End Region
Sub Process_Globals
Public Serial1 As Serial
Public WiFi As ESP8266WiFi
Public esp As ESP8266
Private eeprom As EEPROM
Private const MAGIC_EEPROM As Byte = 123
Private bc As ByteConverter
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")
WiFiServer.Start
ConnectToNetwork
End Sub
Public Sub SaveNetworkDetails(SSID As String, Password As String)
Log("Saving network data: ", SSID, ", ", Password)
SSID = bc.StringFromBytes(WiFiServer.ReplaceString(SSID, "%20", " "))
eeprom.WriteBytes(Array As Byte(MAGIC_EEPROM, SSID.Length + 1 + Password.Length), 0)
Dim pos As Int = 2
eeprom.WriteBytes(SSID, pos)
pos = pos + SSID.Length
eeprom.WriteBytes(Array As Byte(0), pos)
pos = pos + 1
eeprom.WriteBytes(Password, pos)
End Sub
Public Sub ConnectToNetwork
WiFi.Disconnect
'read settings from EEPROM
Dim header() As Byte = eeprom.ReadBytes(0, 2)
If header(0) = MAGIC_EEPROM Then
Dim data() As Byte = eeprom.ReadBytes(2, header(1))
Dim i As Int = bc.IndexOf(data, Array As Byte(0))
If i = -1 Then
Log("Error parsing network data.")
Return
End If
Dim SSID As String = bc.StringFromBytes(bc.SubString2(data, 0, i))
Dim Password As String = bc.StringFromBytes(bc.SubString(data, i + 1))
Log("Trying to connect to: ", SSID, " password: ", Password)
If WiFi.Connect2(SSID, Password) Then
Log("Connected successfully to: ", SSID)
Log(WiFi.LocalIp)
Else
Log("Failed to connect.")
End If
Else
Log("Network data not found.")
End If
End Sub