akellyirl

Heating Lambda

Jan 15th, 2017
458
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Alexa Skill basic template
  3.  *
  4.  * Additional Notes
  5.  * https://developer.amazon.com/appsandservices/solutions/alexa/alexa-skills-kit/getting-started-guide
  6.  */
  7.  
  8. // Route the incoming request based on type (LaunchRequest, IntentRequest,
  9. // etc.) The JSON body of the request is provided in the event parameter.
  10. exports.handler = function (event, context) {
  11.     try {
  12.         console.log("event.session.application.applicationId=" + event.session.application.applicationId);
  13.  
  14.         /**
  15.          * Uncomment this if statement and populate with your skill's application ID to
  16.          * prevent someone else from configuring a skill that sends requests to this function.
  17.          */
  18.        
  19.         if (event.session.application.applicationId !== "amzn1.ask.skill.29489395-1295-406c-a96f-7e3a019278a2") {
  20.              context.fail("Invalid Application ID");
  21.          }
  22.        
  23.  
  24.         if (event.session.new) {
  25.             onSessionStarted({requestId: event.request.requestId}, event.session);
  26.         }
  27.  
  28.         if (event.request.type === "LaunchRequest") {
  29.             onLaunch(event.request,
  30.                      event.session,
  31.                      function callback(sessionAttributes, speechletResponse) {
  32.                         context.succeed(buildResponse(sessionAttributes, speechletResponse));
  33.                      });
  34.         }  else if (event.request.type === "IntentRequest") {
  35.             onIntent(event.request,
  36.                      event.session,
  37.                      function callback(sessionAttributes, speechletResponse) {
  38.                          context.succeed(buildResponse(sessionAttributes, speechletResponse));
  39.                      });
  40.         } else if (event.request.type === "SessionEndedRequest") {
  41.             onSessionEnded(event.request, event.session);
  42.             context.succeed();
  43.         }
  44.     } catch (e) {
  45.         context.fail("Exception: " + e);
  46.     }
  47. };
  48.  
  49. /**
  50.  * Called when the session starts.
  51.  */
  52. function onSessionStarted(sessionStartedRequest, session) {
  53.     console.log("onSessionStarted requestId=" + sessionStartedRequest.requestId
  54.                 + ", sessionId=" + session.sessionId);
  55. }
  56.  
  57. /**
  58.  * Called when the user launches the skill without specifying what they want.
  59.  */
  60. function onLaunch(launchRequest, session, callback) {
  61.     console.log("onLaunch requestId=" + launchRequest.requestId
  62.                 + ", sessionId=" + session.sessionId);
  63.  
  64.     // Dispatch to your skill's launch.
  65.     getWelcomeResponse(callback);
  66. }
  67.  
  68. /**
  69.  * Called when the user specifies an intent for this skill.
  70.  */
  71. function onIntent(intentRequest, session, callback) {
  72.     console.log("onIntent requestId=" + intentRequest.requestId
  73.                 + ", sessionId=" + session.sessionId);
  74.  
  75.     var intent = intentRequest.intent,
  76.         intentName = intentRequest.intent.name;
  77.  
  78.     // Dispatch to your skill's intent handlers
  79.     if ("GetDownTempIntent" === intentName) {
  80.         GetDownTemp(intent, session, callback);
  81.     }
  82.     else if ("TurnOnIntent" === intentName) {
  83.         TurnOn(intent, session, callback);
  84.     }
  85.     else if ("SetDownTempFRACIntent" === intentName) {
  86.         SetDownTempFRAC(intent, session, callback);
  87.     }else{
  88.         throw "Invalid intent";
  89.     }
  90. }
  91.  
  92.  
  93. /**
  94.  * Called when the user ends the session.
  95.  * Is not called when the skill returns shouldEndSession=true.
  96.  */
  97. function onSessionEnded(sessionEndedRequest, session) {
  98.     console.log("onSessionEnded requestId=" + sessionEndedRequest.requestId
  99.                 + ", sessionId=" + session.sessionId);
  100.     // Add cleanup logic here
  101. }
  102.  
  103. // --------------- Functions that control the skill's behavior -----------------------
  104.  
  105. function getWelcomeResponse(callback) {
  106.     // If we wanted to initialize the session to have some attributes we could add those here.
  107.    
  108.     var sessionAttributes = {};
  109.     var cardTitle = "Welcome";
  110.        
  111.     var speechOutput = "Hello, welcome to the Heating Controller.\
  112.    You can ask me things to do with the home heating controller.\
  113.    Try: what's the temperature downstairs? or What is the water temperature?";
  114.  
  115.     // If the user either does not reply to the welcome message or says something that is not
  116.     // understood, they will be prompted again with this text.
  117.     var repromptText = "Hello? are you there?";
  118.     var shouldEndSession = false;
  119.  
  120.     callback(sessionAttributes,
  121.              buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
  122. }
  123.  
  124. function GetDownTemp(intent,session,callback){
  125.     var sessionAttributes = {};
  126.     var cardTitle = "GetDownTemp";
  127.     var repromptText=null;
  128.    
  129.     GET("tempDOWN",function(response) {    
  130.     var speechOutput = "The down stairs temperature is "+response/10+" degrees";
  131.    
  132.     var shouldEndSession = true;
  133.    
  134.     callback(sessionAttributes,
  135.              buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
  136.     });
  137. }
  138.  
  139.  
  140. function TurnOn(intent,session,callback){
  141.     var sessionAttributes = {};
  142.     var cardTitle = "TurnOn";
  143.     var repromptText=null;
  144.    
  145.     POST("STATE:1",function(response) {    
  146.         if (response==1) {
  147.             var speechOutput = "I've turned the heating on.";
  148.         } else {
  149.             var speechOutput = "I'm sorry. The heating has returned an error. I can't turn it on.";
  150.         }
  151.    
  152.     var shouldEndSession = true;
  153.    
  154.     callback(sessionAttributes,
  155.              buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
  156.     });
  157. }
  158.  
  159.  
  160. function SetDownTempFRAC(intent,session,callback){
  161.     var sessionAttributes = {};
  162.     var cardTitle = "SetDownTemp";
  163.     var repromptText=null;
  164.    
  165.     POST("SETDOWN:"+intent.slots.DownSetInt.value+"."+intent.slots.DownSetFrac.value, function(response) {  
  166.         if (response==1) {
  167.             var speechOutput = "I've set the downstairs temperature to \
  168. "+intent.slots.DownSetInt.value+" point "+intent.slots.DownSetFrac.value+" degrees";
  169.         } else {
  170.             var speechOutput = "I'm sorry. The heating has returned an error.";
  171.         }
  172.    
  173.     var shouldEndSession = true;
  174.    
  175.     callback(sessionAttributes,
  176.              buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
  177.     });
  178. }
  179.  
  180.  
  181. function GET(cmd,response) {
  182.     var https = require('https');
  183.    
  184.     var url = 'https://api.particle.io/v1/devices/1234fffe/\
  185. '+cmd+'\
  186. ?access_token=dada1234';
  187.    
  188.     https.get(url, function(res) {
  189.       var body = '';
  190.       res.on('data', function(chunk) {
  191.         body += chunk;
  192.       });
  193.       res.on('end', function() {
  194.         var jsData = JSON.parse(body);
  195.         response(jsData.result);
  196.       });
  197.     }).on('error', function(e) {
  198.       console.log("Got error: " + e.message);
  199.     });
  200. }
  201.  
  202. function POST(cmd,response) {
  203.     var http = require("https");
  204.  
  205.     var options = {
  206.       "method": "POST",
  207.       "hostname": "api.spark.io",
  208.       "port": null,
  209.       "path": "/v1/devices/1234fffe/SetVal?access_token=dada1234",
  210.       "headers": {
  211.         "content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
  212.         "cache-control": "no-cache",
  213.       }
  214.     };
  215.    
  216.     var req = http.request(options, function (res) {
  217.       var chunks = [];
  218.    
  219.       res.on("data", function (chunk) {
  220.         chunks.push(chunk);
  221.       });
  222.    
  223.       res.on("end", function () {
  224.         var body = Buffer.concat(chunks);
  225.         var jsData = JSON.parse(body);
  226.         response(jsData.return_value);
  227.       });
  228.     });
  229.    
  230.     req.write("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data;\
  231. name=\"params\"\r\n\r\n"+cmd+"\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");
  232.     req.end();
  233. }
  234.  
  235. // --------------- Helpers that build all of the responses -----------------------
  236.  
  237. function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
  238.     return {
  239.         outputSpeech: {
  240.             type: "PlainText",
  241.             text: output
  242.         },
  243.         card: {
  244.             type: "Simple",
  245.            // title: "SessionSpeechlet - " + title,
  246.            // content: "SessionSpeechlet - " + output
  247.             title:  title,
  248.             content: output
  249.         },
  250.         reprompt: {
  251.             outputSpeech: {
  252.                 type: "PlainText",
  253.                 text: repromptText
  254.             }
  255.         },
  256.         shouldEndSession: shouldEndSession
  257.     }
  258. }
  259.  
  260. function buildResponse(sessionAttributes, speechletResponse) {
  261.     return {
  262.         version: "1.0",
  263.         sessionAttributes: sessionAttributes,
  264.         response: speechletResponse
  265.     }
  266. }
Add Comment
Please, Sign In to add comment