Skip to content

3. Send IoT Data to the P2P Network

jollen chen edited this page Mar 30, 2018 · 1 revision

Introduction

To send the sensory data to the p2p network in WebSocket, use the URI ws://[ip_address:port]/object/[name]/send in which you must specify the IP address, port and user-defined object name. For example, there is one peer node running at the address 192.168.1.2:8001 within the p2p network.

ws://192.168.1.2:8001/object/frontdoor/send

Example

The following example periodically sends simulated temperature data to the p2p network. The node which received the sensory data will forward the data over the p2p network by using the Chord algorithm. The successor, the processing node of the data, will store the data in the blockchain.

var WebSocketClient = require('websocket').client;

var client = new WebSocketClient();

client.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
});

client.on('connect', function(connection) {
    console.log('WebSocket client connected');
    connection.on('error', function(error) {
        console.log("Connection Error: " + error.toString());
    });
    connection.on('close', function() {
        console.log('echo-protocol Connection Closed');
    });

    function sendNumber() {
        if (connection.connected) {
            var number = Math.round(Math.random() * 0xFFFFFF);
            var lucky = Math.round(Math.random() * 100 + 1);
            var obj = {temperature: lucky};

            console.log('[SEND]', JSON.stringify(obj));

            connection.sendUTF(JSON.stringify(obj));
            setTimeout(sendNumber, 1000);
        }
    }
    sendNumber();
});

client.connect('ws://192.168.1.2:8001/object/frontdoor/send', '');

Clone this wiki locally