Node.js Application
- Express and socket.io are used to support the web interface functionality
- The code for LED manipulation, web interface connectivity, and the HTTP server providing web client files is in the server.js file
- Web client files are served from the /public folder
Configuration and Installation
git clone https://github.com/tibbotech/tps-gpio-tutorials
cd tps-gpio-tutorials
npm install .
cd one-led
node server
server.js
Comments in the code explain how it works
const express = require("express");
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const gpio = require("@tibbo-tps/gpio");
app.use("/", express.static('public'));
const led = gpio.init("S15A");
if(led.getDirection() === "input"){
led.setDirection('output');
led.setValue(1);
}
var clients = io.on('connection', function(socket){
console.log('USER CONNECTED');
var value = led.getValue();
clients.emit('tps:state:changed', value);
socket.on('web:state:changed', function(value){
led.setValue(value);
clients.emit('tps:state:changed', value);
});
socket.on('disconnect', function(){
console.log('USER DISCONNECTED');
});
});
http.listen(3000,function(){
console.log("LISTENING");
});
Web client
index.html
Comments in the code explain how it works:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<script type="text/javascript" src="client.js"></script>
<link href="main.css" rel="stylesheet" type="text/css"/>
</head>
<body ng-app="leds">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="110px" height="110px" xml:space="preserve"
ng-controller="ledsController"
ng-hide="locked">
<g transform="translate(5,5)" class="led-icon">
<rect width="100" height="100" class="frame"></rect>
<rect x="10" y="10" width="80" height="80"
class="led"
ng-class="(state ? 'on' : 'off')"
ng-click="switch()">
</rect>
</g>
</svg>
</body>
</html>
client.js
Comments in the code explain how it works:
angular.module('leds', [])
.controller('ledsController', function($scope) {
var socket = io();
$scope.locked = true;
socket.on('connect', function () {
$scope.locked = false;
$scope.$apply();
});
socket.on('disconnect', function () {
$scope.locked = true;
$scope.$apply();
});
socket.on('tps:state:changed', function (value) {
$scope.state = value == 0;
$scope.$apply();
});
$scope.switch = function() {
console.log($scope.state ? 1 : 0);
socket.emit('web:state:changed', $scope.state ? 1 : 0);
}
});