#Region Project Attributes
#AutoFlushLogs: True
#CheckArrayBounds: True
#StackBufferSize: 600
#End Region
Sub Process_Globals
Public Serial1 As Serial
Public WiFi As ESP8266WiFi
Private bc As ByteConverter
Private connection As Int
Private server(2) As WiFiServerSocket
Private astream(2) As AsyncStreams
Private timer1 As Timer
Private pinSensor, pinButton As Pin
Private pinLED As Pin
Private pin1 As D1Pins
End Sub
Private Sub AppStart
Log("AppStart")
Serial1.Initialize(115200)
Log("StartAP: ", WiFi.StartAccessPoint2("myWifi", "12345678"))
Log("My AP ip: ", WiFi.AccessPointIp)
IntiServer
End Sub
#Region "server-Subs"
Public Sub IntiServer
server(0).Initialize(51041, "Server_NewConnection")
server(0).Listen
server(1).Initialize(51042, "Server_NewConnection")
server(1).Listen
pinButton.Initialize(pin1.D3, pinButton.MODE_INPUT_PULLUP)
pinButton.AddListener("pinButton_StateChanged")
pinSensor.Initialize(pin1.D5, pinSensor.MODE_INPUT_PULLUP)
pinSensor.AddListener("pinSensor_StateChanged")
pinLED.Initialize(pin1.D1, pinLED.MODE_OUTPUT)
timer1.Initialize("timer1_Tick", 1000)
timer1.Enabled = True
End Sub
Sub Server_NewConnection (NewSocket As WiFiSocket)
Log("new connection")
astream(connection).Initialize(NewSocket.Stream, "astream_NewData", "astream_Error")
astream(connection).Write(bc.StringToBytes("OK"))
connection = connection + 1
timer1.Enabled = False
End Sub
Sub Timer1_Tick
'' astream.Write(bc.UIntsToBytes(Array As UInt(pin.AnalogRead)))
' If server.Socket.Connected Then
' pinLED.DigitalWrite(True)
' astream.Write("Time here is: ").Write(NumberFormat(Millis, 0, 0))
' Else
pinLED.DigitalWrite(Not(pinLED.DigitalRead))
' End If
End Sub
Sub astream_NewData (Buffer() As Byte)
Log("Received: ", Buffer)
If bc.StringFromBytes(Buffer) = 1 Then
pinLED.DigitalWrite(True)
Else
pinLED.DigitalWrite(False)
End If
End Sub
Sub astream_Error
Log("Error.")
For i = 0 To connection - 1
server(i).Listen
Next
timer1.Enabled = True
End Sub
#End Region
Sub pinButton_StateChanged (State As Boolean)
Log("pinButton: ", State)
'state will be False when the button is clicked because of the PULLUP mode.
If Not(State) Then
SendValue("a")
'astream.Write(bc.StringToBytes("0"))
Else
SendValue("b")
'astream.Write(bc.StringToBytes("-0"))
End If
End Sub
Sub pinSensor_StateChanged (State As Boolean)
Log("pinSensor: ", State)
'state will be False when the button is clicked because of the PULLUP mode.
If Not(State) Then
SendValue("c")
'astream.Write(bc.StringToBytes("+"))
Else
SendValue("d")
'astream.Write(bc.StringToBytes("-"))
End If
End Sub
Sub SendValue(str As String)
For i = 0 To connection - 1
astream(i).Write(bc.StringToBytes(str))
Next
End Sub