Farn-Yu KhongOfra Or
Published

Read Write Map aka Smart Map

A smart city needs a smarter map. Where citizen can post emergencies, events, breaking news, etc, and anybody see it in real time.

IntermediateShowcase (no instructions)919
Read Write Map aka Smart Map

Things used in this project

Hardware components

Amazon Tap
Amazon Alexa Amazon Tap
×1

Software apps and online services

Watson
IBM Watson
Alexa Skills Kit
Amazon Alexa Alexa Skills Kit

Story

Read more

Schematics

Node Red Schematic

This node red analyze sentiment of a map entry. We use this to determine if the map entry is in distress

Code

Node-Red service for sentiment analysis

snippets
This code is exported from Node-Red console. It takes a url parameter, and output sentiment number. We use this sentiment number to analyze map entry posting to see if it is distress. And messages with distress will be group together for authority to response to promptly
[{"id":"ae81db64.071f4","type":"http in","z":"c6484ac.1f53638","name":"testWord","url":"/abc","method":"get","swaggerDoc":"","x":179,"y":153,"wires":[["cd22eeff.b5443","b1db7228.5cf82"]]},{"id":"cd22eeff.b5443","type":"debug","z":"c6484ac.1f53638","name":"","active":true,"console":"false","complete":"payload","x":365,"y":97,"wires":[]},{"id":"b1db7228.5cf82","type":"function","z":"c6484ac.1f53638","name":"","func":"\nmsg.payload = msg.payload.string;\nreturn msg;","outputs":1,"noerr":0,"x":344.5,"y":229,"wires":[["4026a18c.9892d8"]]},{"id":"db3157a3.7cbfe","type":"http response","z":"c6484ac.1f53638","name":"","x":753.5,"y":270,"wires":[]},{"id":"4026a18c.9892d8","type":"sentiment","z":"c6484ac.1f53638","name":"","x":465.5,"y":313,"wires":[["138b6867.032488"]]},{"id":"138b6867.032488","type":"function","z":"c6484ac.1f53638","name":"","func":"msg.res.set(\"Access-Control-Allow-Origin\", \"*\");\n\nmsg.payload = msg.sentiment.score;\n\nreturn msg;","outputs":1,"noerr":0,"x":617.5,"y":378,"wires":[["db3157a3.7cbfe"]]},{"id":"ac631764.67ceb","type":"function","z":"c6484ac.1f53638","name":"","func":"msg.res.set(\"Access-Control-Allow-Origin\", \"*\");\nreturn msg;","outputs":1,"noerr":0,"x":656.5,"y":468,"wires":[[]]}]

Alexa gives briefing in the morning about what events in my area

snippets
When you wake up in the morning, and we can ask Alexa to give me a briefing of what events in my are.
/* eslint-disable  func-names */
/* eslint quote-props: ["error", "consistent"]*/
/**
 * This sample demonstrates a simple skill built with the Amazon Alexa Skills
 * nodejs skill development kit.
 * This sample supports multiple lauguages. (en-US, en-GB, de-DE).
 * The Intent Schema, Custom Slots and Sample Utterances for this skill, as well
 * as testing instructions are located at https://github.com/alexa/skill-sample-nodejs-fact
 **/

'use strict';
var https = require('http');

const Alexa = require('alexa-sdk');

const APP_ID = undefined;  // TODO replace with your app ID (OPTIONAL).

const languageStrings = {
    'en-GB': {
        translation: {
            FACTS: [
                'A year on Mercury is just 88 days long.',
                'Despite being farther from the Sun, Venus experiences higher temperatures than Mercury.',
                'Venus rotates anti-clockwise, possibly because of a collision in the past with an asteroid.',
                'On Mars, the Sun appears about half the size as it does on Earth.',
                'Earth is the only planet not named after a god.',
                'Jupiter has the shortest day of all the planets.',
                'The Milky Way galaxy will collide with the Andromeda Galaxy in about 5 billion years.',
                'The Sun contains 99.86% of the mass in the Solar System.',
                'The Sun is an almost perfect sphere.',
                'A total solar eclipse can happen once every 1 to 2 years. This makes them a rare event.',
                'Saturn radiates two and a half times more energy into space than it receives from the sun.',
                'The temperature inside the Sun can reach 15 million degrees Celsius.',
                'The Moon is moving approximately 3.8 cm away from our planet every year.',
            ],
            SKILL_NAME: 'British Space Facts',
            GET_FACT_MESSAGE: "Here's your fact: ",
            HELP_MESSAGE: 'You can say tell me a space fact, or, you can say exit... What can I help you with?',
            HELP_REPROMPT: 'What can I help you with?',
            STOP_MESSAGE: 'Goodbye!',
        },
    },
    'en-US': {
        translation: {
            FACTS: [
                'A year on Mercury is just 88 days long.',
                'Despite being farther from the Sun, Venus experiences higher temperatures than Mercury.',
                'Venus rotates counter-clockwise, possibly because of a collision in the past with an asteroid.',
                'On Mars, the Sun appears about half the size as it does on Earth.',
                'Earth is the only planet not named after a god.',
                'Jupiter has the shortest day of all the planets.',
                'The Milky Way galaxy will collide with the Andromeda Galaxy in about 5 billion years.',
                'The Sun contains 99.86% of the mass in the Solar System.',
                'The Sun is an almost perfect sphere.',
                'A total solar eclipse can happen once every 1 to 2 years. This makes them a rare event.',
                'Saturn radiates two and a half times more energy into space than it receives from the sun.',
                'The temperature inside the Sun can reach 15 million degrees Celsius.',
                'The Moon is moving approximately 3.8 cm away from our planet every year.',
            ],
            SKILL_NAME: 'American Space Facts',
            GET_FACT_MESSAGE: "Here's your fact: ",
            HELP_MESSAGE: 'You can say tell me a space fact, or, you can say exit... What can I help you with?',
            HELP_REPROMPT: 'What can I help you with?',
            STOP_MESSAGE: 'Goodbye!',
        },
    },
    'de-DE': {
        translation: {
            FACTS: [
                'Ein Jahr dauert auf dem Merkur nur 88 Tage.',
                'Die Venus ist zwar weiter von der Sonne entfernt, hat aber hhere Temperaturen als Merkur.',
                'Venus dreht sich entgegen dem Uhrzeigersinn, mglicherweise aufgrund eines frheren Zusammenstoes mit einem Asteroiden.',
                'Auf dem Mars erscheint die Sonne nur halb so gro wie auf der Erde.',
                'Die Erde ist der einzige Planet, der nicht nach einem Gott benannt ist.',
                'Jupiter hat den krzesten Tag aller Planeten.',
                'Die Milchstraengalaxis wird in etwa 5 Milliarden Jahren mit der Andromeda-Galaxis zusammenstoen.',
                'Die Sonne macht rund 99,86 % der Masse im Sonnensystem aus.',
                'Die Sonne ist eine fast perfekte Kugel.',
                'Eine Sonnenfinsternis kann alle ein bis zwei Jahre eintreten. Sie ist daher ein seltenes Ereignis.',
                'Der Saturn strahlt zweieinhalb mal mehr Energie in den Weltraum aus als er von der Sonne erhlt.',
                'Die Temperatur in der Sonne kann 15 Millionen Grad Celsius erreichen.',
                'Der Mond entfernt sich von unserem Planeten etwa 3,8 cm pro Jahr.',
            ],
            SKILL_NAME: 'Weltraumwissen auf Deutsch',
            GET_FACT_MESSAGE: 'Hier sind deine Fakten: ',
            HELP_MESSAGE: 'Du kannst sagen, Nenne mir einen Fakt ber den Weltraum, oder du kannst Beenden sagen... Wie kann ich dir helfen?',
            HELP_REPROMPT: 'Wie kann ich dir helfen?',
            STOP_MESSAGE: 'Auf Wiedersehen!',
        },
    },
};

const handlers = {
    'LaunchRequest': function () {
        this.emit('ReadNews');
    },
    'GetNewFactIntent': function () {
        this.emit('GetFact');
    },
    
     //==================================

    'GetFact': function () {
        // Get a random space fact from the space facts list
        // Use this.t() to get corresponding language data
        const factArr = this.t('FACTS');
        const factIndex = Math.floor(Math.random() * factArr.length);
        const randomFact = factArr[factIndex];

        // Create speech output
        const speechOutput = this.t('GET_FACT_MESSAGE') + randomFact;
        this.emit(':tellWithCard', speechOutput, this.t('SKILL_NAME'), randomFact);
    },
    
    
    //==================================
    
    //==================================

    'ReadNews': function () {
        //maintain context
        var parentOfthis=this;
        
        // http get
        console.log("in read news event");
        
        readNews(function(speechOutput){
            console.log("in callback from read news function");
        // Create speech output
        //var speechOutput = "Read my news";
        parentOfthis.emit(':tell', speechOutput);
        })


    },
    
    
    //==================================
    'AMAZON.HelpIntent': function () {
        const speechOutput = this.t('HELP_MESSAGE');
        const reprompt = this.t('HELP_MESSAGE');
        this.emit(':ask', speechOutput, reprompt);
    },
    'AMAZON.CancelIntent': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
    'AMAZON.StopIntent': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
    'SessionEndedRequest': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
};

function readNews(callback) {
    console.log("in read news function");

        // GET is a web service request that is fully defined by a URL string
        // Try GET in your browser:
        // https://rmwum5l4zc.execute-api.us-east-1.amazonaws.com/prod/stateresource?usstate=Virginia

        var result = 0;
//TODO change host and path
        var options = {
            host: 'www.tech.chat',
            port: 80,
            path: '/v1/gme?r=event',
            method: 'GET'
        };

        var req = https.request(options, res => {
                res.setEncoding('utf8');
            var returnData = "";

            res.on('data', chunk => {
                console.log("got data");
                returnData = returnData + chunk;
            });

            res.on('end',  () => {
                console.log("call complete");
                // we have now received the raw return data in the returnData variable.
                // e.g. {"usstate":"Florida","attributes":[{"population":20300000},{"rank":3}]}
                // We can see it in the log output via:
                // console.log(JSON.stringify(returnData))
                // we may need to parse through it to extract the needed data

//TODO parse the result

                //var myStrSpeechFromJson = JSON.parse(returnData).entries[0].msg;
                var myStrSpeechFromJson = JSON.parse(returnData).entries;
                var myStrSpeechNoJson = returnData;
                var speechOutput = '';
                for(var i in myStrSpeechFromJson) {
                    console.log(i, myStrSpeechFromJson[i].msg);
                    speechOutput += "  ," + myStrSpeechFromJson[i].msg;
                }
                
                console.log("about to call back");
                callback(speechOutput);

            });

        });
        req.end();

    }

exports.handler = (event, context) => {
    const alexa = Alexa.handler(event, context);
    alexa.APP_ID = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    alexa.resources = languageStrings;
    alexa.registerHandlers(handlers);
    alexa.execute();
};

Credits

Farn-Yu Khong

Farn-Yu Khong

1 project • 1 follower
Ofra Or

Ofra Or

1 project • 1 follower
Thanks to Alexa and Watson sponsors.

Comments