Muhammad Afzal
Published © Apache-2.0

Alexa Smart Power Strip with Temperature

Smart Power Strip is controlled by Alexa Smart Home skills with an extra temperature feature. It can be used generally everywhere at home.

IntermediateFull instructions provided5 hours4,337
Alexa Smart Power Strip with Temperature

Things used in this project

Hardware components

Arduino MKR1000
Arduino MKR1000
×1
Temperature Sensor
Temperature Sensor
×1
Generice 4 Channel Relay Module
×1
Echo Dot
Amazon Alexa Echo Dot
×1
Plastic Sheet 3MM Thick
×1

Software apps and online services

Arduino IDE
Arduino IDE
Alexa Skills Kit
Amazon Alexa Alexa Skills Kit
AWS Lambda
Amazon Web Services AWS Lambda
Cayenne
myDevices Cayenne

Hand tools and fabrication machines

Laser cutter (generic)
Laser cutter (generic)

Story

Read more

Schematics

Fritzing circult diagram.

Code

MKR1000 Smart power Strip Arduino Code

Arduino
// This example shows how to connect to Cayenne using an Arduino/Genuino MKR1000 and send/receive sample data.

//#define CAYENNE_DEBUG
#define CAYENNE_PRINT Serial
#include <CayenneMQTTMKR1000.h>

// WiFi network info.
char ssid[] = "----SSID----";
char wifiPassword[] = "----SSID Password----";

// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "----UserName-------";
char password[] = "----Password-------";
char clientID[] = "----Client ID-------";

unsigned long lastMillis = 0;

void setup() {
     Serial.begin(9600);
     pinMode(1,OUTPUT);
     pinMode(2,OUTPUT);
     pinMode(3,OUTPUT);
     pinMode(4,OUTPUT);
     pinMode(A1,INPUT);
 
	   Cayenne.begin(username, password, clientID, ssid, wifiPassword);
}

void loop() {
	  Cayenne.loop();

  	if (millis() - lastMillis > 100000) {
      float temperature=(((analogRead(A1)*3.22)-500)/10);
      Serial.print("Temperature=");
      Serial.println(temperature);
  		Cayenne.celsiusWrite(5, temperature);
  	}
}

CAYENNE_IN_DEFAULT()
{
  	CAYENNE_LOG("CAYENNE_IN_DEFAULT(%u) - %s, %s", request.channel, getValue.getId(), getValue.asString());
  	//Process message here. If there is an error set an error message using getValue.setError(), e.g getValue.setError("Error message");
    digitalWrite(request.channel,getValue.asInt());
}

AWS Lambda Code

JavaScript
This Lambda Code will bridge the Alexa Smart Home Skills API with Ceyenne Mydevices Cloud
exports.handler = function (request, context) {
	
	//Cayenne MyDevices DeviceID & SensorID 
	var Cayenne_DeviceID="-------Cayenne Device ID--------";
	var Cayenne_Temperature_SensorID="-------Cayenne Sensor ID--------";
	var Cayenne_UserName="---------Cayenne Account username-----------";
	var Cayenne_Password="---------Cayenne Account password-----------";
	
    if (request.directive.header.namespace === 'Alexa.Discovery' && request.directive.header.name === 'Discover') {
        log("DEBUG:", "Discover request",  JSON.stringify(request));
        handleDiscovery(request, context, "");
    }
    else if (request.directive.header.namespace === 'Alexa.PowerController') {
        if (request.directive.header.name === 'TurnOn' || request.directive.header.name === 'TurnOff') {
            log("DEBUG:", "TurnOn or TurnOff Request", JSON.stringify(request));
            handlePowerControl(request, context);
        }
    }else if(request.directive.endpoint.endpointId==="Appliance-001-05"){
		log("DEBUG:", "Temperature",  JSON.stringify(request));
		CayenneTemperatureControl(request,context);
	}
    function handleDiscovery(request, context) {
        var payload = {
            "endpoints":
            [
                {
                    "endpointId": "Appliance-001-01",
                    "manufacturerName": "Smart Device Company",
                    "friendlyName": "Socket One",
                    "description": "Smart Device Switch",
                    "displayCategories": ["SWITCH"],
                    "cookie": {
                    },
                    "capabilities":
                    [
                        {
                          "type": "AlexaInterface",
                          "interface": "Alexa",
                          "version": "3"
                        },
                        {
                            "interface": "Alexa.PowerController",
                            "version": "3",
                            "type": "AlexaInterface",
                            "properties": {
                                "supported": [{
                                    "name": "powerState"
                                }],
                                 "retrievable": true
                            }
                        }
                    ]
                },{
                    "endpointId": "Appliance-001-02",
                    "manufacturerName": "Smart Device Company",
                    "friendlyName": "Socket Two",
                    "description": "Smart Device Switch",
                    "displayCategories": ["SWITCH"],
                    "cookie": {

                    },
                    "capabilities":
                    [
                        {
                          "type": "AlexaInterface",
                          "interface": "Alexa",
                          "version": "3"
                        },
                        {
                            "interface": "Alexa.PowerController",
                            "version": "3",
                            "type": "AlexaInterface",
                            "properties": {
                                "supported": [{
                                    "name": "powerState"
                                }],
                                 "retrievable": true
                            }
                        }
                    ]
                },{
                    "endpointId": "Appliance-001-03",
                    "manufacturerName": "Smart Device Company",
                    "friendlyName": "Socket Three",
                    "description": "Smart Device Switch",
                    "displayCategories": ["SWITCH"],
                    "cookie": {
                    },
                    "capabilities":
                    [
                        {
                          "type": "AlexaInterface",
                          "interface": "Alexa",
                          "version": "3"
                        },
                        {
                            "interface": "Alexa.PowerController",
                            "version": "3",
                            "type": "AlexaInterface",
                            "properties": {
                                "supported": [{
                                    "name": "powerState"
                                }],
                                 "retrievable": true
                            }
                        }
                    ]
                },{
                    "endpointId": "Appliance-001-04",
                    "manufacturerName": "Smart Device Company",
                    "friendlyName": "Socket Four",
                    "description": "Smart Device Switch",
                    "displayCategories": ["SWITCH"],
                    "cookie": {
                    },
                    "capabilities":
                    [
                        {
                          "type": "AlexaInterface",
                          "interface": "Alexa",
                          "version": "3"
                        },
                        {
                            "interface": "Alexa.PowerController",
                            "version": "3",
                            "type": "AlexaInterface",
                            "properties": {
                                "supported": [{
                                    "name": "powerState"
                                }],
                                 "retrievable": true
                            }
                        }
                    ]
                },
				{
                    "endpointId": "Appliance-001-05",
                    "manufacturerName": "Smart Device Company",
                    "friendlyName": "Room Temperature",
                    "description": "Smart Room Temperature",
                    "displayCategories": ["THERMOSTAT"],
                    "cookie": {
                    },
                    "capabilities":
                    [
                        {
							"type": "AlexaInterface",
                            "interface": "Alexa.TemperatureSensor",
                            "version": "3",
                            "properties": {
                                "supported": [{
                                    "name": "temperature"
                                }],
                                 "retrievable": true
                            }
                        }
                    ]
                }
			]
        };
        var header = request.directive.header;
        header.name = "Discover.Response";
        log("DEBUG", "Discovery Response: ", JSON.stringify({ header: header, payload: payload }));
        context.succeed({ event: { header: header, payload: payload } });
    }

    function log(message, message1, message2) {
        console.log(message + message1 + message2);
    }

    function handlePowerControl(request, context) {
        // get device ID passed in during discovery
        var requestMethod = request.directive.header.name;
        // get user token pass in request
        //var requestToken = request.directive.payload.scope.token;
        var powerResult;
		var CayenneDeviceChannel=request.directive.endpoint.endpointId.substr(request.directive.endpoint.endpointId.length-1,1);
        if (requestMethod === "TurnOn") {

            // Make the call to your device cloud for control 
            // powerResult = stubControlFunctionToYourCloud(endpointId, token, request);
            powerResult = "ON";
            CayennePowerControl(1,context,CayenneDeviceChannel);
        }
       else if (requestMethod === "TurnOff") {
            // Make the call to your device cloud for control and check for success 
            // powerResult = stubControlFunctionToYourCloud(endpointId, token, request);
            powerResult = "OFF";
			CayennePowerControl(0,context,CayenneDeviceChannel);
        }
		
    } 
  
	function TemperatureContext(request,context,value,Time_Stamp){
		var a = {
                         "context": {
                             "properties": [ {
                                "namespace": "Alexa.TemperatureSensor",
                                 "name": "temperature",
                                 "value": {
									"value": value,
									"scale": "CELSIUS"
								  },
                                 "timeOfSample": Time_Stamp,
                                 "uncertaintyInMilliseconds": 1000
                             }
                            ]
                         },
                        "event": {
                            "header": {
                                "namespace": "Alexa",
                                "name": "StateReport",
                                "payloadVersion": request.directive.header.payloadVersion,
                                "messageId": request.directive.header.messageId,
                                "correlationToken": request.directive.header.correlationToken
                            },
                            "endpoint": {
                                 "scope": {
                                 "type": "BearerToken",
                                 "token" :request.directive.endpoint.scope.token
                                 },
                                "endpointId": request.directive.endpoint.endpointId
                            },
                            "payload": {
                                "code":"LightIsOff",
                                "description":"Light is off.",
                                "message":"Light is off"
                            }
                        }
                    };
					log("DEBUG:", "StateReport",  JSON.stringify(a));
					context.succeed(a);
	}
	function PowerContext(context){
		var a = {
                         "context": {
                             "properties": [ {
                                "namespace": "Alexa.PowerController",
                                 "name": "powerState",
                                 "value": "ON",
                                 "timeOfSample": "2017-02-03T16:20:50.52Z",
                                 "uncertaintyInMilliseconds": 5000
                             },{
                                "namespace": "Alexa.EndpointHealth",
                                "name": "connectivity",
                                "value": {
                                    "value": "OK Good"
                                },
                                "timeOfSample": "2017-09-27T18:30:30.45Z",
                                "uncertaintyInMilliseconds": 200
                                }
                            ]
                         },
                        "event": {
                            "header": {
                                "namespace": "Alexa",
                                "name": "Response",
                                "payloadVersion": request.directive.header.payloadVersion,
                                "messageId": request.directive.header.messageId,
                                "correlationToken": request.directive.header.correlationToken
                            },
                            "endpoint": {
                                 "scope": {
                                 "type": "BearerToken",
                                 "token" :request.directive.endpoint.scope.token
                                 },
                                "endpointId": request.directive.endpoint.endpointId
                            },
                            "payload": {
                                "code":"LightIsOff",
                                "description":"Light is off.",
                                "message":"Light is off"
                            }
                        }
                    };
					
					context.succeed(a);
	}
    function CayennePowerControl(turn,context,CayenneDeviceChannel){
        var http = require('https');
		var AccessToken="";
		var body = JSON.stringify({
			"grant_type": "password",
			"email":Cayenne_UserName,
			"password":Cayenne_Password
		});

		var options={
			hostname: "auth.mydevices.com",
			path: "/oauth/token",
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				"Content-Length": Buffer.byteLength(body)
			}
		};
		var req=http.request(options,function(res){
			var responseString = "";

			res.on("data", function (data) {
				responseString += data;
				// save all the data from response
			});
			res.on("end", function () {
				var jsonRes=JSON.parse(responseString);
				AccessToken=jsonRes['access_token'];
				console.log("DEBUG:"+AccessToken);
				
				
				//Write the Values
				if(AccessToken!=""){
					var cmdValue = JSON.stringify({
						"value":turn,
						"channel": CayenneDeviceChannel
					});
					var options1={
					hostname: "platform.mydevices.com",
					path: "/v1.1/things/"+Cayenne_DeviceID+"/cmd",
					method: "POST",
						headers: {
							"Authorization": "Bearer "+AccessToken,
							"Content-Type": "application/json; charset=UTF-8",
							"Content-Length": Buffer.byteLength(cmdValue)
						}
					};
					var req1=http.request(options1,function(res1){
						var Result = "";

						res1.on("data", function (data) {
							Result += data;
							
							// save all the data from response
						});
						res1.on("end", function () {
							console.log("DEBUG:"+Result);
							PowerContext(context);
						});
					}).write(cmdValue);
				}
				
				
			});
		}).write(body);

         
    }

	 function CayenneTemperatureControl(request,context){
        var http = require('https');
		var AccessToken="";
		var body = JSON.stringify({
			"grant_type": "password",
			"email":Cayenne_UserName,
			"password":Cayenne_Password
		});

		var options={
			hostname: "auth.mydevices.com",
			path: "/oauth/token",
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				"Content-Length": Buffer.byteLength(body)
			}
		};
		var req=http.request(options,function(res){
			var responseString = "";

			res.on("data", function (data) {
				responseString += data;
				// save all the data from response
			});
			res.on("end", function () {
				var jsonRes=JSON.parse(responseString);
				AccessToken=jsonRes['access_token'];
				console.log("DEBUG:"+AccessToken);
				
				
				//Write the Values
				if(AccessToken!=""){
					var options1={
						hostname: "platform.mydevices.com",
						path: "/v1.1/telemetry/"+Cayenne_DeviceID+"/sensors/"+Cayenne_Temperature_SensorID+"/summaries?type=latest",
						method: "GET",
							headers: {
								"Authorization": "Bearer "+AccessToken,
							}
						};
						var req1=http.request(options1,function(res1){
							var Result = "";

							res1.on("data", function (data) {
								Result += data;
								// save all the data from response
							});
							res1.on("end", function () {
								console.log(Result);
								Result=JSON.parse(Result);
								var Temperature_Value=Result[0].v;
								var Time_Stamp=Result[0].ts;
								TemperatureContext(request,context,Temperature_Value,Time_Stamp);
							});
						}).end();
				}
				
				
			});
		}).write(body);

         
    }
	
};

Credits

Muhammad Afzal

Muhammad Afzal

25 projects • 117 followers
I am Software Eng having 13+ Years of experience. Hackster.io & Cayenne Mydevices Ambassador in Pakistan.

Comments