B4R Library WebSocketClient

rWebSocketClient library is a WebSocket client implementation. It is based on this open source project: https://github.com/brandenhall/Arduino-Websocket

The library is similar to B4X WebSocketHandler class: https://www.b4x.com/android/forum/threads/websocket-client-library.40221/#content
This means that it is intended to be used with B4J WebSocket servers.

Using it is simple:
1. Create a client object such as EthernetSocket.
2. Call Connect to connect to the server:
B4X:
websocket.ConnectIp(ethClient.Stream, serverIp, serverPort, path)

3. Send events to the server with SendEventToServer:
B4X:
websocket.SendEventToServer("Btn_StateChanged", Array As String("btn", 0, "state", Not(State)))

This will cause the Btn_StateChanged sub on the server to be raised:
B4X:
'b4j
Sub Btn_StateChanged (Params As Map)
   Dim id As String = "arduino_btn" & Params.Get("btn")
   Dim state As Boolean = Params.Get("state")
   For Each br As Browser In Main.ConnectedBrowsers.Keys
     CallSubDelayed3(br, "UpdateButton", id, state)
   Next
End Sub

4. The server can send events to the client:
B4X:
'Must be an array of strings and the parameters cannot include quotes.
ws.RunFunction("Led", Array As String(LedId.SubString("arduino_led".Length), State))
ws.Flush

This will cause the WebSocket_NewMessage event to be raised on the Arduino:
B4X:
Sub WebSocket_NewMessage (FunctionName As String, Params() As String)
   Select FunctionName
     Case "ServerTime"
       Log("Server time: ", Params(0))
     Case "Led"
       leds(Params(0)).DigitalWrite(Params(1) = "true")
   End Select
End Sub

So now it is easy to control the Arduino from the browser!

SS-2016-04-25_09.13.15.png


The connections diagram for this example:

SS-2016-04-25_09.25.40.png


The projects and library are attached. The B4R project requires B4R v1.00 beta 8+.
 

Attachments

  • B4R_WebSocketExample.zip
    1.3 KB · Views: 1,156
  • B4J_WebSocketExample.zip
    6.7 KB · Views: 981
  • rWebSocketClient.zip
    9.2 KB · Views: 1,027

Beja

Expert
Licensed User
Longtime User
I must give this a big Like.. thanks Erel
My experience with websockets is limited in devices on the same network, therefore I wish there is a tutorial on how to
control an Arduino over the WWW without having a personal web server.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User

MathiasM

Active Member
Licensed User
This might be a stupid question, but is rWebsocketClient able to connect to a Secure Websocket?
Thanks
 
Top