Taiyuk
Published © GPL3+

Anger Management

IoT button to know our buddy, Anger, using AWS IoT to track how often we get angry, if certain threshold reach, let us calm.

IntermediateFull instructions provided1,435

Things used in this project

Story

Read more

Schematics

Schematics

Raw materials

Raspberry Pi, Button

Raw materials

Raspberry Pi, Button

Code

Lambda function

JavaScript
var AWS = require('aws-sdk');
var url = require('url');
var dynamodb = new AWS.DynamoDB();

exports.handler = function(event, context) {
    var tableName = "angar";
    var datetime = new Date().getTime().toString();
    var date = new Date();
    var tmp = date.getFullYear()+""+date.getMonth()+1+""+date.getDate()+"-"+date.getHours() + date.getMinutes() + date.getSeconds();
    
    dynamodb.putItem({
            "TableName": tableName,
            "Item": {
                "date": {
                    "S": tmp
                }, 
                "timedate": {
                    "N": datetime
                }
            }
        }, function(err, data) {
            if (err) {
                context.fail('ERROR: Dynamo failed: ' + err);
            } else {
                console.log('Dynamo Success: ' + JSON.stringify(data, null, '  '));
                context.succeed('SUCCESS');
            }
        });

    tmp = "" + date.getFullYear()+""+date.getMonth()+1+""+date.getDate();
    var params = {
        "TableName": "angar",
        "ScanFilter": {
            "date": {
                "AttributeValueList": [{"S": tmp }],
                "ComparisonOperator": "BEGINS_WITH"
            },
        },
        "Limit": "10"
    };
    dynamodb.scan(params, function(err, result) {
        if (err) {
            console.log(err); 
        } else {
            if (result.Count>9){
                var client = new AWS.IotData({endpoint: 'xxxxx.iot.xxxxx.amazonaws.com'});
                client.publish({
                payload: JSON.stringify(result),
                    topic: 'topic/play'
                }, function(err, data){
                if(err) {
                    context.fail(err);
                } else {
                    context.succeed({published:true});
                }
                });
            }
        }
    });
}

NodeJS client

JavaScript
var awsIot = require('aws-iot-device-sdk');
var Gpio = require('onoff').Gpio;
var sleep = require('sleep');
var Sound = require('node-aplay');

var thingShadows = awsIot.thingShadow({
   keyPath: 'private.pem.key',
  certPath: 'certificate.pem.crt',
    caPath: 'root-CA.crt',
  clientId: 'raspberrypi',
    region: 'ap-northeast-1'
});

function exit() {
  high.unexport();
  button.unexport();
  process.exit();
}

var State = {"state":{"reported":{"connected":"yes"}}};

var clientTokenUpdate;

thingShadows.on('connect', function() {
    thingShadows.register( 'raspberrypi' , { ignoreDeltas: true, persistentSubscribe: true } );
    thingShadows.subscribe('topic/play');
    setTimeout( function() {
       clientTokenUpdate = thingShadows.update('raspberrypi', State  );
       }, 2000 );
    });

thingShadows.on('status',
    function(thingName, stat, clientToken, stateObject) {
       console.log('received '+stat+' on '+thingName+': '+
                   JSON.stringify(stateObject));
    });

thingShadows.on('message', function(topic, payload) {
    if(topic.indexOf('play') > -1) {
	    new Sound('~/song.wav').play();
	  }
  });

high = new Gpio(23, 'out');
high.writeSync(1);
button = new Gpio(24, 'in', 'rising');

button.watch(
    function(err, value) {
       delete State['version'];
       delete State['connected'];
       State["state"]["reported"]["button"] = 1;
       buttonStateResponse = thingShadows.update('raspberrypi', State);
       thingShadows.publish('topic/pressed', value.toString());
    });
process.on('SIGINT', exit);

Credits

Taiyuk

Taiyuk

3 projects • 7 followers

Comments