From 50662e24f2ec31d128d864cc93292d5394001584 Mon Sep 17 00:00:00 2001 From: test2 Date: Sun, 24 Nov 2019 18:37:51 +0200 Subject: [PATCH] pi2server --- IoT/SensorNode2Server.adoc | 520 ++++++++++++++++++++++++++++++++++++- 1 file changed, 518 insertions(+), 2 deletions(-) diff --git a/IoT/SensorNode2Server.adoc b/IoT/SensorNode2Server.adoc index efcf116..c32cb4d 100644 --- a/IoT/SensorNode2Server.adoc +++ b/IoT/SensorNode2Server.adoc @@ -207,9 +207,9 @@ This provides some configuration for the Arduino serial connection: sudo stty -F /dev/ttyACM0 cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts ---- -==== Reading in the arduino +==== Reading in arduino -.handle the reading in the arduino +.C code in the arduino [source,bash] ---- void loop() { @@ -352,6 +352,522 @@ init(() => { ---- + +=== Send data2server + + +==== NodeJS + +.NodeJS code in Raspberry Pi - send +[source,c] +---- + +... +var serverIOT=IP_SERVER + const socket = require('socket.io-client')('https://'+serverIOT+':9080'); + socket.on('connect', function () { + socket.emit('subscribe', log); + var obj = new Object(); + obj.room = log; + obj.message = data; + var text = JSON.stringify(obj); + var text1 = Buffer.from(text); + var text5 = text1.toString('base64'); + socket.emit('log', text5, log ) + //console.log(util.inspect(text5, false, null, true /* enable colors */)) + + res.json({ + 'message':"ok" + }); + }); + +... + +---- + +==== PHP + +.PHP code in Raspberry Pi - send +[source,php] +---- +require "vendor/autoload.php"; + +$client = new \GuzzleHttp\Client(["base_uri" => "http://SERVER"]); + +$options = [ + + 'form_params' => [ + + "fruit" => "apple" + + ] + + ]; + +$response = $client->post("/post", $options); + +echo $response->getBody(); +---- + + +[NOTE] +==== +composer require guzzlehttp/guzzle +==== + + + +== IoT Server + +=== NodeJS + +==== Gateway + +.NodeJS code in Raspberry Pi - Server Gateway +[source,c] +---- +// Setup basic express server +var express = require('express'); +var app = express(); +var path = require('path'); +var server = require('http').createServer(app); +var io = require('../..')(server); +//const util = require('util') +var bodyParser = require('body-parser') +var serverIoT=SERVER +app.use(bodyParser.json()) + +const { check, validationResult } = require('express-validator'); +app.post('/log', [ + check('serverdebug').isFQDN({ require_tld: true, allow_underscores: false, allow_trailing_dot: false }), + check('log').isBase64(), + check('data').isBase64() +], (req, res) => { + const errors = validationResult(req) + if (!errors.isEmpty()) { + return res.status(422).json({ errors: errors.array() }) + } + //console.log(util.inspect(req, false, null, true /* enable colors */)) + //console.log(util.inspect(req.body, false, null, true /* enable colors */)) + var log = req.body.log + var data = req.body.data + var serverdebug = req.body.serverdebug + data = Buffer.from(data, 'base64').toString('utf-8') + const socket = require('socket.io-client')('https://'+serverIoT+':9080'); + socket.on('connect', function () { + socket.emit('subscribe', log); + var obj = new Object(); + obj.room = log; + obj.message = data; + var text = JSON.stringify(obj); + var text1 = Buffer.from(text); + var text5 = text1.toString('base64'); + socket.emit('log', text5, log ) + //console.log(util.inspect(text5, false, null, true /* enable colors */)) + + res.json({ + 'message':"ok" + }); + }); +}); +app.get('/test', (req, res) => { + var text5 = "ok"; + res.json({ + 'message':text5 + }); +}); + +// Change the 404 message modifing the middleware +app.use(function(req, res, next) { + res.status(404).send("Sorry, that route doesn't exist. Have a nice day :)"); +}); + +// start the server in the port 3000 ! +app.listen(9089, function () { + console.log('Example app listening on port 9089.'); +}); + +---- + +==== Broadcast + +.NodeJS code in Raspberry Pi - Server broadcast +[source,c] +---- +// Setup basic express server +var express = require('express'); +var app = express(); +var path = require('path'); +var server = require('http').createServer(app); +var io = require('../..')(server); +var port = process.env.PORT || 9080; +const util = require('util') + + + +server.listen(port, () => { + console.log('Server listening at port %d', port); +}); + +// Routing +app.use(express.static(path.join(__dirname, 'public'))); + +var numUsers = 0; + +io.on('connection', (socket) => { + + socket.on('subscribe', function(room) { + console.log('joining room', room); + socket.join(room); + }) + + socket.on('unsubscribe', function(room) { + console.log('leaving room', room); + socket.leave(room); + }) + + // when the client emits 'new message', this listens and executes + socket.on('log', (data, room) => { + console.log(util.inspect(data, false, null, true /* enable colors */)) + socket.broadcast.to(room).emit('message', data) + console.log('broadcast', room); + + }); + + +}); + + +---- + +==== Client Connection Raspberry + +.NodeJS code in Raspberry Pi - Client +[source,c] +---- +// Setup basic express server +var express = require('express'); +var app = express(); +var path = require('path'); +var server = require('http').createServer(app); +var io = require('../..')(server); +var port = process.env.PORT || 9000; + +server.listen(port, () => { + console.log('Server listening at port %d', port); +}); + +// Routing +app.use(express.static(path.join(__dirname, 'public'))); + + +var numUsers = 0; + +io.on('connection', (socket) => { + var addedUser = false; + + // when the client emits 'new message', this listens and executes + socket.on('new message', (data, room) => { + console.log('Server listening at port %d', data); + }); + +}); + +---- + +==== Client Connection - Web Server + +.Javascript code +[source,c] +---- +$(function() { + var FADE_TIME = 150; // ms + var TYPING_TIMER_LENGTH = 400; // ms + var COLORS = [ + '#e21400', '#91580f', '#f8a700', '#f78b00', + '#58dc00', '#287b00', '#a8f07a', '#4ae8c4', + '#3b88eb', '#3824aa', '#a700ff', '#d300e7' + ]; + + // Initialize variables + var $window = $(window); + var $usernameInput = $('.usernameInput'); // Input for username + var $messages = $('.messages'); // Messages area + var $inputMessage = $('.inputMessage'); // Input message input box + + var $loginPage = $('.login.page'); // The login page + var $chatPage = $('.chat.page'); // The room page + + // Prompt for setting a username + var username; + var connected = false; + var typing = false; + var lastTypingTime; + var $currentInput = $usernameInput.focus(); + + var socket = io(); + + const addParticipantsMessage = (data) => { + var message = ''; + if (data.numUsers === 1) { + message += "there's 1 participant"; + } else { + message += "there are " + data.numUsers + " participants"; + } + log(message); + } + + // Sets the client's username + const setUsername = () => { + username = cleanInput($usernameInput.val().trim()); + + // If the username is valid + if (username) { + $loginPage.fadeOut(); + $chatPage.show(); + $loginPage.off('click'); + $currentInput = $inputMessage.focus(); + + // Tell the server your username + socket.emit('add user', username); + } + } + + // Sends a message + const sendMessage = () => { + var message = $inputMessage.val(); + // Prevent markup from being injected into the message + message = cleanInput(message); + // if there is a non-empty message and a socket connection + if (message && connected) { + $inputMessage.val(''); + addChatMessage({ + username: username, + message: message + }); + // tell server to execute 'new message' and send along one parameter + socket.emit('new message', message); + } + } + + // Log a message + const log = (message, options) => { + var $el = $('
  • ').addClass('log').text(message); + addMessageElement($el, options); + } + + // Adds the visual message to the message list + const addChatMessage = (data, options) => { + // Don't fade the message in if there is an 'X was typing' + var $typingMessages = getTypingMessages(data); + options = options || {}; + if ($typingMessages.length !== 0) { + options.fade = false; + $typingMessages.remove(); + } + + var $usernameDiv = $('') + .text(data.username) + .css('color', getUsernameColor(data.username)); + var $messageBodyDiv = $('') + .text(data.message); + + var typingClass = data.typing ? 'typing' : ''; + var $messageDiv = $('
  • ') + .data('username', data.username) + .addClass(typingClass) + .append($usernameDiv, $messageBodyDiv); + + addMessageElement($messageDiv, options); + } + + // Adds the visual typing message + const addChatTyping = (data) => { + data.typing = true; + data.message = 'is typing'; + addChatMessage(data); + } + + // Removes the visual typing message + const removeChatTyping = (data) => { + getTypingMessages(data).fadeOut(function () { + $(this).remove(); + }); + } + + // Adds a message element to the messages and scrolls to the bottom + // el - The element to add as a message + // options.fade - If the element should fade-in (default = true) + // options.prepend - If the element should prepend + // all other messages (default = false) + const addMessageElement = (el, options) => { + var $el = $(el); + + // Setup default options + if (!options) { + options = {}; + } + if (typeof options.fade === 'undefined') { + options.fade = true; + } + if (typeof options.prepend === 'undefined') { + options.prepend = false; + } + + // Apply options + if (options.fade) { + $el.hide().fadeIn(FADE_TIME); + } + if (options.prepend) { + $messages.prepend($el); + } else { + $messages.append($el); + } + $messages[0].scrollTop = $messages[0].scrollHeight; + } + + // Prevents input from having injected markup + const cleanInput = (input) => { + return $('
    ').text(input).html(); + } + + // Updates the typing event + const updateTyping = () => { + if (connected) { + if (!typing) { + typing = true; + socket.emit('typing'); + } + lastTypingTime = (new Date()).getTime(); + + setTimeout(() => { + var typingTimer = (new Date()).getTime(); + var timeDiff = typingTimer - lastTypingTime; + if (timeDiff >= TYPING_TIMER_LENGTH && typing) { + socket.emit('stop typing'); + typing = false; + } + }, TYPING_TIMER_LENGTH); + } + } + + // Gets the 'X is typing' messages of a user + const getTypingMessages = (data) => { + return $('.typing.message').filter(function (i) { + return $(this).data('username') === data.username; + }); + } + + // Gets the color of a username through our hash function + const getUsernameColor = (username) => { + // Compute hash code + var hash = 7; + for (var i = 0; i < username.length; i++) { + hash = username.charCodeAt(i) + (hash << 5) - hash; + } + // Calculate color + var index = Math.abs(hash % COLORS.length); + return COLORS[index]; + } + + // Keyboard events + + $window.keydown(event => { + // Auto-focus the current input when a key is typed + if (!(event.ctrlKey || event.metaKey || event.altKey)) { + $currentInput.focus(); + } + // When the client hits ENTER on their keyboard + if (event.which === 13) { + if (username) { + sendMessage(); + socket.emit('stop typing'); + typing = false; + } else { + setUsername(); + } + } + }); + + $inputMessage.on('input', () => { + updateTyping(); + }); + + // Click events + + // Focus input when clicking anywhere on login page + $loginPage.click(() => { + $currentInput.focus(); + }); + + // Focus input when clicking on the message input's border + $inputMessage.click(() => { + $inputMessage.focus(); + }); + + // Socket events + + // Whenever the server emits 'login', log the login message + socket.on('login', (data) => { + connected = true; + // Display the welcome message + var message = "Welcome to Swarmlab Chat – "; + log(message, { + prepend: true + }); + addParticipantsMessage(data); + }); + + // Whenever the server emits 'new message', update the body + socket.on('new message', (data) => { + addChatMessage(data); + }); + + // Whenever the server emits 'user joined', log it in the body + socket.on('user joined', (data) => { + log(data.username + ' joined'); + addParticipantsMessage(data); + }); + + // Whenever the server emits 'user left', log it in the body + socket.on('user left', (data) => { + log(data.username + ' left'); + addParticipantsMessage(data); + removeChatTyping(data); + }); + + // Whenever the server emits 'typing', show the typing message + socket.on('typing', (data) => { + addChatTyping(data); + }); + + // Whenever the server emits 'stop typing', kill the typing message + socket.on('stop typing', (data) => { + removeChatTyping(data); + }); + + socket.on('disconnect', () => { + log('you have been disconnected'); + }); + + socket.on('reconnect', () => { + log('you have been reconnected'); + if (username) { + socket.emit('add user', username); + } + }); + + socket.on('reconnect_error', () => { + log('attempt to reconnect has failed'); + }); + +}); + +---- + + + + [appendix] == Config