Sending Data on TCP library (mjs)

  1. My goal is: To create a TCP server on ESP32 and send data to and from ESP using mjs and this library. I want to send some data from esp32 when i press the button gpio.
  2. My actions are: I am able to create a tcp server on esp32 and establish a connection with tcp client on my computer.
    Below is my code:

load(‘api_net.js’);

load(‘api_gpio.js’);

load(‘api_config.js’);

let data = ‘123’;

let btn = Cfg.get(‘board.btn1.pin’);

let btnPull, btnEdge;

if (Cfg.get(‘board.btn1.pull_up’) ? GPIO.PULL_UP : GPIO.PULL_DOWN) {

btnPull = GPIO.PULL_UP;

btnEdge = GPIO.INT_EDGE_NEG;

} else {

btnPull = GPIO.PULL_DOWN;

btnEdge = GPIO.INT_EDGE_POS;

}

Net.serve({

addr: ‘tcp://1980’,

onconnect: function(conn) {

print('**Connected to device');

print('**Received device from:', Net.ctos(conn, false, true, true));

},

ondata: function(conn, data) {

print('**Received data from:', Net.ctos(conn, false, true, true), ':', data);

}

});

GPIO.set_button_handler(btn, btnPull, btnEdge, 20, function() {

Net.send(conn, data);

}, null);

  1. The result I see is: I am able to send data from esp server to the client thru the ‘Net.send(conn, data)’ of the ‘Net.serve’ function scope. But outside the scope, I am not able to call ‘Net.send’ function. It shows ‘conn’ not defined.
  2. My expectation & question is: I want to know how to avoid the error and how to increase the scope of var pointer ‘conn’ outside the ‘Net.serve’ function.

conn is not visible from the set_button_handler handler.

Try something like this:

let conn = Net.serve({
  addr: "tcp://1980",
  onconnect: function (conn) {
    print('**Connected to device');
    print('**Received device from:', Net.ctos(conn, false, true, true));
  },
  ondata: function (conn, data) {
    print('**Received data from:', Net.ctos(conn, false, true, true), ':', data);
  }
});

GPIO.set_button_handler(btn, btnPull, btnEdge, 20, function () {
  print('Button handler');
  Net.send(conn, data);
}, null);

Refs:
serve
_bind
mgos_bind

1 Like