Sub Process_Globals
Public Serial1 As Serial
Private wifi As ESP8266WiFi
Private server As WiFiServerSocket
Private astream As AsyncStreams
Private ser As B4RSerializator
Public DHT11pin As Pin
Private dht11 As dht
Dim humidity,temperature As Double ' Humidity/Temperature DHT11 readings
Public timer As Timer
Public Const interval As ULong = 5000
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")
If wifi.Connect2("xxx", "yyy") Then
Log("Connected to wireless network.")
Log("My ip: ", wifi.LocalIp)
Else
Log("Failed to connect to network")
End If
timer.Initialize("timer_tick", interval)
DHT11pin.Initialize(2, DHT11pin.MODE_INPUT)
server.Initialize(51042, "server_NewConnection")
server.Listen
timer.Enabled = True
timer_tick
End Sub
Sub timer_tick
dht11.Read11(DHT11pin.PinNumber) ' Reading the DHT11 measure
temperature = dht11.GetTemperature ' Get temperature from readed measure
humidity = dht11.GetHumidity ' Get humidity from readed measure
Log("DHT11 ","Humidity = ", humidity, " %", " Temperature =", temperature, " ºC")
If server.Socket.Connected Then
astream.Write(ser.ConvertArrayToBytes(Array(humidity, temperature)))
End If
End Sub
Sub Server_NewConnection (NewSocket As WiFiSocket)
Log("Client connected")
astream.InitializePrefix(NewSocket.Stream, False, "astream_NewData", "astream_Error")
End Sub
Sub AStream_Error
Log("Error")
server.Listen
End Sub
Sub AStream_NewData (Buffer() As Byte)
Dim be(10) As Object
Dim data() As Object = ser.ConvertBytesToArray(Buffer, be)
Log("Received:")
For Each o As Object In data
Log(o)
Select o
Case "sleep"
wifi.Disconnect
DeepSleep(60000)
End Select
Next
End Sub
Private Sub DeepSleep(ms As ULong)
RunNative("deepSleep", ms * 1000)
End Sub
#if C
void deepSleep(B4R::Object* o) {
ESP.deepSleep(o->toULong());
}
#end if