I'm trying to comunicate with alarm system using socket library.
I would like to open socket connection, send command and get the response.
I would like to have open connection all the time my program runs.
My question is how to properly open socket connection, handle socket and AStream_Error (or AStream_Terminated) events and other situations that can close the connection like astream time out.
First of all here ale some code examples i use:
I run a timer that to check socket. every 5 seconds
I'm note sure if i shoud reInitialize client i connect sub and if i should run client.close in AStreams_Terminated and AStreams_Error
I would like to open socket connection, send command and get the response.
I would like to have open connection all the time my program runs.
My question is how to properly open socket connection, handle socket and AStream_Error (or AStream_Terminated) events and other situations that can close the connection like astream time out.
First of all here ale some code examples i use:
B4X:
Sub Class_Globals
Private AStreams As AsyncStreams
Private client As Socket
B4X:
Sub Connect
Main.AppLog("Satel:: Connecting..."&IP&":3000 ")
If client.Connected = False Then
client.Initialize("client")
Try
client.Connect(IP, Port, 3000)
Catch
Main.AppLog("Satel:: Connection problem: "&LastException.Message)
End Try
End If
End Sub
B4X:
Sub client_Connected (Successful As Boolean)
ReconnectTimer.Enabled = False
If AStreams.IsInitialized Then AStreams.Close
If Successful Then
Main.AppLog("Satel:: Connected")
Try
AStreams.Initialize(client.InputStream, client.OutputStream, "AStreams")
Main.AppLog("Satel:: AStreams_Initialized")
GetArmedZones
Catch
Main.AppLog("Satel:: AStreams_Initialize Problem: "&LastException.Message)
End Try
End If
End Sub
B4X:
Sub AStreams_Error
If Sender <> AStreams Then Return
Main.AppLog("Satel:: AStreams_Error "&LastException.Message)
client.Close
ReconnectTimer.Enabled = True
End Sub
B4X:
Sub AStreams_Terminated
If Sender <> AStreams Then Return
Main.AppLog("Satel:: AStreams_Terminated")
client.Close
ReconnectTimer.Enabled = True
End Sub
B4X:
Private Sub ReconnectTimer_Tick
Main.AppLog("Satel:: ReconnectTimer_Tick ")
If Not(client.Connected) Then
Main.AppLog("Satel:: Reconnecting by timer ")
Connect
End If
End Sub
B4X:
Private Sub ReconnectTimer_Tick
Main.AppLog("Satel:: ReconnectTimer_Tick ")
If Not(client.Connected) Then
Main.AppLog("Satel:: Reconnecting by timer ")
Connect
End If
End Sub
I'm note sure if i shoud reInitialize client i connect sub and if i should run client.close in AStreams_Terminated and AStreams_Error