#Region Project Attributes
#AutoFlushLogs: True
#CheckArrayBounds: True
#StackBufferSize: 600
#End Region
Sub Process_Globals
Public Serial1 As Serial
Private wifi As ESP8266WiFi
Private bc As ByteConverter
Private Astream As AsyncStreams
Private server As WiFiServerSocket
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Delay(3000)
Log("AppStart")
Start
End Sub
Public Sub Start
Log("StartAP: ", wifi.StartAccessPoint2("AP_name", ""))
Log("My AP ip: ", wifi.AccessPointIp)
server.Initialize(80, "server_NewConnection")
server.Listen
End Sub
Private Sub Server_NewConnection (NewSocket As WiFiSocket)
Astream.Initialize(NewSocket.Stream, "astream_NewData", "astream_Error")
End Sub
Private Sub Astream_NewData (Buffer() As Byte)
Log(Buffer)
If bc.IndexOf(Buffer, "GET") <> -1 Then
If bc.IndexOf(Buffer, "/set") <> -1 Then
Dim ssid = "", password = "" As String
Dim i1 As Int = 0
Dim i2 As Int = 0
For Each b1() As Byte In bc.Split(Buffer, " ")
If i1 = 1 Then
For Each b2() As Byte In bc.Split(b1, "/")
Select i2
Case 2
ssid = bc.StringFromBytes(b2)
Log("New ssid = ", ssid)
Case 3
password = bc.StringFromBytes(b2)
Log("New pass = ", password)
End Select
i2 = i2 + 1
Next
End If
i1 = i1 + 1
Next
Log("StackBufferUsage2 = ", StackBufferUsage)
Astream.Write("HTTP/1.1 200").Write(CRLF)
Astream.Write("Content-Type: text/html").Write(CRLF).Write(CRLF)
If ssid.Length > 14 Or password.Length > 14 Then
Astream.Write("WiFi SSID or password is too long, change shorter")
Else
Astream.Write("<script>setTimeout(function(){location.href=""http://192.168.4.1""} , 5000);</script>")
Astream.Write("WiFi has been set to: ").Write(ssid).Write(", password: ").Write(password) '.Write("<br/>Please wait...")
Log("AP: ssid and password are received")
GlobalStore.Put(0, ssid)
GlobalStore.Put(1, password)
CallSubPlus("ConnectWifi", 500, 0)
End If
Else If bc.IndexOf(Buffer, " / ") <> -1 Then
Astream.Write("HTTP/1.1 200").Write(CRLF).Write(CRLF)
If wifi.IsConnected Then
Astream.Write("Connected to network.").Write(CRLF)
Astream.Write("Device IP address: ").Write(wifi.LocalIp)
'others.restart(0)
Else
Astream.Write("Not connected!")
End If
Else
Astream.Write("HTTP/1.1 404").Write(CRLF)
End If
CallSubPlus("CloseConnection", 200, 0)
End If
End Sub
Private Sub ConnectWifi(u As Byte)
'example of connecting to a local network
If wifi.Connect2(bc.StringFromBytes(GlobalStore.Slot0), bc.StringFromBytes(GlobalStore.Slot1)) Then
Log("Connected to network")
Else
Log("Failed to connect to network")
End If
End Sub
Private Sub CloseConnection(u As Byte)
Log("Close AP connection")
If server.Socket.Connected Then
server.Socket.Stream.Flush
server.Socket.Close
End If
End Sub
Private Sub AStream_Error
Log("AP AStream_Error: disconnected")
server.Listen
End Sub