Commit aaee335d authored by Giacomo Lavermicocca's avatar Giacomo Lavermicocca
Browse files

Aggiunto nuove funzionalità

parent 14cd5fd1
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -3,6 +3,7 @@

# Node.js
node_modules/*
example/node_modules/*
npm-debug.log

.idea

example/.cycles.js.swp

0 → 100644
+12 KiB

File added.

No diff preview for this file type.

+45 −5
Original line number Diff line number Diff line
@@ -65,7 +65,7 @@ passport.use(new GoogleStrategy({
    //then edit your /etc/hosts local file to point on your private IP. 
    //Also both sign-in button + callbackURL has to be share the same url, otherwise two cookies will be created and lead to lost your session
    //if you use it.
    callbackURL: "http://acasapiccardi.ddns.net:3000/auth/google/callback",
    callbackURL: "http://vwoqi7ziagyiik9t.myfritz.net:3000/auth/google/callback",
    passReqToCallback   : true,
    access_type: 'offline'
  },
@@ -129,7 +129,7 @@ app.get('/webcam2', ensureAuthenticated, function (req, res) {
});

app.get('/webcam', ensureAuthenticated, function (req, res) {
    exec('v4l2-ctl --set-fmt-video=width=2592,height=1944,pixelformat=3 & v4l2-ctl --set-ctrl=rotate=180 --stream-mmap=3 --stream-count=1 --stream-to=public/camera2.jpg', function (err, stdout, stderr) {
    exec('' + __dirname + '/camera.sh', function (err, stdout, stderr) {
        if (err) {
            // node couldn't execute the command
            console.log('stdout: ${stdout}'); // node
@@ -160,6 +160,39 @@ app.get('/account', ensureAuthenticated, function(req, res){
app.get('/dashboard', ensureAuthenticated, function (req, res) {
    res.render('dashboard', { user: req.user });
});
//--------------------------- TEMPE -------------------------------------
var sensore = require('./sensore.js')
app.get('/sensore', ensureAuthenticated, function (req, res) {

    sensore.read((resp)=>{
        res.send(resp);
    })
});
//--------------------------- PLAY --------------------------------------
var playcicala = require('./cicala.js')
app.get('/cicalastart', ensureAuthenticated, function(req, res){
    playcicala.start()
    res.send("ok")
});
app.get('/cicalastop', ensureAuthenticated, function (req, res) {
    playcicala.stop()
    res.send("ok")
});

//--------------------------- RELES -------------------------------------
var servo = require('./servo.js')
app.get('/sinistra', ensureAuthenticated, function(req, res){
    servo.sinistra();
    res.send("ok");
});
app.get('/destra', ensureAuthenticated, function (req, res) {
    servo.destra();
    res.send("ok");
});
app.get('/centro', ensureAuthenticated, function (req, res) {
    servo.centro();
    res.send("ok");
});
//--------------------------- RELES -------------------------------------
app.get('/releStatus.js', ensureAuthenticated, function (req, res) {
    res.send(rele.fileRead());
@@ -176,6 +209,14 @@ app.get('/releToggleOff.js', ensureAuthenticated, function (req, res) {

    res.send(rele.fileRead());
});
//--------------------------- LEDS ---------------------------------------
var leds = require('./leds.js')
app.get('/ledsWhite', ensureAuthenticated, function (req, res) {

    leds.ledsWhite()

    res.send("ok")
});
//--------------------------- CYCLES -------------------------------------
app.get('/cyclesStatus.js', ensureAuthenticated, function (req, res) {
    res.send(cycles.statusFileRead());
@@ -261,9 +302,8 @@ function intervalFunc() {

            if (startMidnight >= cycle.cycle1[0] && startMidnight <= cycle.cycle1[1]) {
                rele.releOn();
            } 
	    else if (startMidnight >= cycle.cycle2[0] && startMidnight <= cycle.cycle2[1]) {
                rele.releOn();
            } else if (startMidnight >= cycle.cycle2[0] && startMidnight <= cycle.cycle2[1]) {
                rele.releOff();
            }
            else {
                rele.releOff(); //out of times

example/app.js.bak

0 → 100755
+287 −0
Original line number Diff line number Diff line
var express          = require( 'express' )
  , app              = express()
  , server           = require( 'http' ).createServer( app ) 
  , passport         = require( 'passport' )
  , util             = require( 'util' )
  , bodyParser       = require( 'body-parser' )
  , cookieParser     = require( 'cookie-parser' )
  , session          = require( 'express-session' )
  , RedisStore       = require( 'connect-redis' )( session )
  , GoogleStrategy   = require( 'passport-google-oauth2' ).Strategy
  , rele = require('./rele')
  , cycles = require('./cycles');

app.use('/public', express.static(__dirname + '/public'));

var exec = require('child_process').exec;

var io = require('socket.io')(server);

io.on('connection', function (socket) {
    console.log('user connected');

    socket.on('toggle manual', function (msg) {
        socket.broadcast.emit('toggle manual', msg);
    });
    socket.on('toggle automatic', function (msg) {
        socket.broadcast.emit('toggle automatic', msg);
    });
    socket.on('sliders change', function (msg) {
        socket.broadcast.emit('sliders change', msg);
    });
});

// API Access link for creating client ID and secret:
// https://code.google.com/apis/console/
//var GOOGLE_CLIENT_ID      = "529751334929-2m6vn4eath13724bb1ouark2g1boagne.apps.googleusercontent.com"
//  , GOOGLE_CLIENT_SECRET  = "EnGmoYufAVRgVMpL12kD4YaY";

// Passport session setup.
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing.  However, since this example does not
//   have a database of user records, the complete Google profile is
//   serialized and deserialized.
passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});


// Use the GoogleStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Google
//   profile), and invoke a callback with a user object.
passport.use(new GoogleStrategy({
    clientID:     '769415575905-v2bt6mmg0g03hs8v5pbgobfbfheoon97.apps.googleusercontent.com',
    clientSecret: 'NW4vmWJ3fvJMAjr30aU4_yJa',
    //NOTE :
    //Carefull ! and avoid usage of Private IP, otherwise you will get the device_id device_name issue for Private IP during authentication
    //The workaround is to set up thru the google cloud console a fully qualified domain name such as http://mydomain:3000/ 
    //then edit your /etc/hosts local file to point on your private IP. 
    //Also both sign-in button + callbackURL has to be share the same url, otherwise two cookies will be created and lead to lost your session
    //if you use it.
    callbackURL: "http://acasapiccardi.ddns.net:3000/auth/google/callback",
    passReqToCallback   : true,
    access_type: 'offline'
  },
  function(request, accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {
      
      // To keep the example simple, the user's Google profile is returned to
      // represent the logged-in user.  In a typical application, you would want
      // to associate the Google account with a user record in your database,
      // and return that user instead.
      return done(null, profile);
    });
  }
));

// configure Express
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
//app.use( express.static(__dirname + '/public'));


// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());

//----------------------------- GET POST CALLS ----------------------------

//app.use('/static', express.static('public'));
app.use('/static', ensureAuthenticated)
app.use('/static', express.static(__dirname + '/private'));


//app.use('/public', function ensureAuthenticated(req, res, next) {
//    return next();
//})
//app.use('/public', express.static(__dirname + '/public'));


app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/webcam2', ensureAuthenticated, function (req, res) {
	exec('python ' + __dirname + '/camera.py', function (err, stdout, stderr) {
	if (err) {
    	     // node couldn't execute the command
             console.log(`stdout: ${stdout}`); // node
             return;
	 }
         res.sendFile(__dirname + "/public/camera.jpg");
     });
});

app.get('/webcam', ensureAuthenticated, function (req, res) {
    exec('' + __dirname + '/camera.sh', function (err, stdout, stderr) {
        if (err) {
            // node couldn't execute the command
            console.log('stdout: ${stdout}'); // node
              return;
          }
          res.sendFile(__dirname + "/public/camera2.jpg");
    });
});

app.get('/temp', ensureAuthenticated, function (req, res) {
    exec(__dirname + '/temp.sh', (err, stdout, stderr) => {
        if (err) {
            // node couldn't execute the command
            //res.redirect("/public/camera.jpg");
            // the *entire* stdout and stderr (buffered)
            console.log(`stdout: ${stdout}`);
            console.log(`stderr: ${stderr}`);
            return;
        }
        res.send(stdout);
    });
});

app.get('/account', ensureAuthenticated, function(req, res){
  res.render('account', { user: req.user });
});

app.get('/dashboard', ensureAuthenticated, function (req, res) {
    res.render('dashboard', { user: req.user });
});
//--------------------------- RELES -------------------------------------
app.get('/releStatus.js', ensureAuthenticated, function (req, res) {
    res.send(rele.fileRead());
});
app.get('/releToggleOn.js', ensureAuthenticated, function(req, res){

    rele.releToggleOn();

    res.send(rele.fileRead());
});
app.get('/releToggleOff.js', ensureAuthenticated, function (req, res) {

    rele.releToggleOff();

    res.send(rele.fileRead());
});
//--------------------------- CYCLES -------------------------------------
app.get('/cyclesStatus.js', ensureAuthenticated, function (req, res) {
    res.send(cycles.statusFileRead());
});
app.get('/cyclesToggleOn.js', ensureAuthenticated, function (req, res) {

    cycles.cyclesToggleOn();

    res.send(cycles.statusFileRead());
});
app.get('/cyclesToggleOff.js', ensureAuthenticated, function (req, res) {

    cycles.cyclesToggleOff();

    res.send(cycles.statusFileRead());
});

app.get('/cyclesRead.js', ensureAuthenticated, function (req, res) {
    res.send(cycles.cyclesFileRead());
});
app.post('/cycleSend.js', ensureAuthenticated, function (req, res) {

    cycles.cyclesFileSave(req.body);

    res.send(cycles.cyclesFileRead());
});
//--------------------------- OTHERS --------------------------------------
app.get('/login', function(req, res){
  res.render('login', { user: req.user });
});

// GET /auth/google
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in Google authentication will involve
//   redirecting the user to google.com.  After authorization, Google
//   will redirect the user back to this application at /auth/google/callback
app.get('/auth/google', passport.authenticate('google', { scope: [
        'https://www.googleapis.com/auth/plus.login',
	'https://www.googleapis.com/auth/plus.profile.emails.read'] 
}));

// GET /auth/google/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get( '/auth/google/callback', 
    	passport.authenticate( 'google', {
    		successRedirect: '/static/index.html',
    		failureRedirect: '/login'
}));

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

app.use('*',function(req, res){
  res.send('Error 404: Not Found!');
});

server.listen(3000, function (error){
    if (error)
    {
        console.log(error);
    }
    else
    {
        setInterval(intervalFunc, 60000);
    }
});

function intervalFunc() {

    if (rele.fileRead().status == false) {
        if (cycles.statusFileRead().status == true) {

            var cycle = cycles.cyclesFileRead();

            var curretTime = new Date();

            var startMidnight = (curretTime.getHours() * 60) + curretTime.getMinutes();

            if (startMidnight >= cycle.cycle1[0] && startMidnight <= cycle.cycle1[1]) {
                rele.releOn();
            } else if (startMidnight >= cycle.cycle2[0] && startMidnight <= cycle.cycle2[1]) {
                rele.releOff();
            }
            else {
                rele.releOff(); //out of times
            }
        }
        else {
            rele.releOff();
        }
    }
}

// Simple route middleware to ensure user is authenticated.
//   Use this route middleware on any resource that needs to be protected.  If
//   the request is authenticated (typically via a persistent login session),
//   the request will proceed.  Otherwise, the user will be redirected to the
//   login page.
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
	return next();
  }
  res.redirect('/login');
}

example/cam2.jpg

0 → 100644
+276 KiB
Loading image diff...
Loading