Copyright © https://mongoose-os.com

Mongoose OS Forum

frame

How to call RPC handler from HTML WebSocket client?

bravokeylbravokeyl Seoul, South Korea (Nomadist)

I added an RPC Handler (BAD.Led) using the following code for NodeMCU - ESP8266 12E:

load('api_rpc.js');
load('api_gpio.js');

// Configure LED
let led = ffi('int get_led_gpio_pin()')();  // Get built-in LED GPIO pin
GPIO.set_mode(led, GPIO.MODE_OUTPUT);

RPC.addHandler('BAD.Led',function(a){
  GPIO.write(led,a.state);
  return true;
});

I know that we can easily call this handler on terminal using

mos --port ws://IP/rpc call BAD.Led '{"state": 0}'

I have a HTML page where I created websocket and connect to the IP address of board.

<!DOCTYPE html>

<head>
    <meta charset="utf-8" />
    <title>WebSocket</title>
</head>

<body>
    <script language="javascript" type="text/javascript">
        var wsUri = "ws://192.168.2.128/rpc/";
        var output;

        function init() {
            mgos_socket();
        }

        function mgos_socket() {
            websocket = new WebSocket(wsUri);
            websocket.onopen = function(evt) {
                console.log("WebSocket Open",evt);
                websocket.send(JSON.stringify({
                    "state": 0
                }));
            };

            websocket.onclose = function(evt) {
              console.log("WebSocket Closed",evt);
            };
        }

        function onClose(evt) {
          websocket.close();
        }

        window.addEventListener("load", init, false);
    </script>
</body>
</html>

Where 192.168.2.128 is the IP address of the board. I'm getting invalid frame error like this.

mgos_http_ev         0x3fff124c HTTP connection from 192.168.2.88:36822
mg_rpc_ev_handler    0x3ffefe8c INVALID FRAME (11): '{"state":0}'
mg_rpc_ws_handler    0x3ffefe8c CLOSED

Am I missing anything here, how to call RPC handler?

Comments

Sign In or Register to comment.