Skip to content

Relay / Gateway

You can create a relay to forward data from one protocol to another.

For example, if you have a BLE only device and you want to forward packets from your Wi-Fi.

Create your relay

import { SocketProtocol } from '@iotize/device-com-socket.node';
import { ComProtocol } from '@iotize/device-client.js/protocol/api';
import { ComRelay } from '@iotize/device-client.js/relay/impl';

let relay = new ComRelay();

// Configure source and target protocol
let sourceProtocol: ComProtocol; // ... Your target protocol object instance (could be any of the supported protocols: BLE, socket, websocket, NFC...)
let targetProtocol: ComProtocol; // ... Your target protocol object instance (could be any of the supported protocols: BLE, socket, websocket, NFC...)

relay.setTargetProtocol(targetProtocol);
relay.setSourceProtocol(sourceProtocol);

// Start your relay
await relay.start({
  timeout: 5000, // a timeout exception occurs if it does not start within 5 seconds
});

console.log('Relay is now started');

Socket/Websocket server

If your source protocol is sockets or websockets, you need a socket/websocket server to send and listen to requests. This very basic server broadcasts any messages to clients.

import { RelayServer } from '@iotize/device-client.js/relay/impl';

// For websocket server
import { WebSocketAdapter } from '@iotize/device-com-websocket.js/relay';
// For socket server
import { SocketAdapter } from '@iotize/device-com-socket.node/relay';

// Create a web socket server
let webSocketServer: RelayServer = new RelayServer(
  new WebSocketAdapter.Server(),
  {
    port: 2000,
  }
);
webSocketServer.start();

// Or socket server
let socketServer: RelayServer = new RelayServer(new SocketAdapter.Server(), {
  port: 2001,
});
socketServer.start();

Info

You can also use your own adapter if it has a ServerAdapter interface.

Architecture of relay with sockets

Socket relay architecture