Repository navigation
Expand file tree
/
Copy pathhandler.js
More file actions
68 lines (59 loc) · 2.29 KB
/
Copy pathhandler.js
File metadata and controls
68 lines (59 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'use strict'
/**
* This is a sample Lambda function that sends an Email on click of a
* button. It creates a SNS topic, subscribes an endpoint (EMAIL)
* to the topic and publishes to the topic.
*
* Follow these steps to complete the configuration of your function:
*
* 1. Update the email environment variable with your email address.
* 2. Enter a name for your execution role in the "Role name" field.
* Your function's execution role needs specific permissions for SNS operations
* to send an email. We have pre-selected the "AWS IoT Button permissions"
* policy template that will automatically add these permissions.
*/
const AWS = require('aws-sdk')
const SNS = new AWS.SNS({apiVersion: '2010-03-31'})
const dynamoDbHelper = require('./common/dynamodb-helper')
const snsHelper = require('./common/sns-helper')
const TABLE = process.env.DYNAMODB_TABLE_BUTTON
/**
* The following JSON template shows what is sent as the payload:
{
"serialNumber": "GXXXXXXXXXXXXXXXXX",
"batteryVoltage": "xxmV",
"clickType": "SINGLE" | "DOUBLE" | "LONG"
}
*
* A "LONG" clickType is sent if the first press lasts longer than 1.5 seconds.
* "SINGLE" and "DOUBLE" clickType payloads are sent for short clicks.
*
* For more documentation, follow the link below.
* http://docs.aws.amazon.com/iot/latest/developerguide/iot-lambda-rule.html
*/
exports.pubSNS = (event, context, callback) => {
console.log('Received event:', event)
// create/get topic
snsHelper.createTopic('aws-iot-button-sns-topic', (err, topicArn) => {
if (err) {
return callback(err)
}
console.log(`Publishing to topic ${topicArn}`)
// publish message
const params = {
Message: `${event.serialNumber} -- processed by Lambda\nBattery voltage: ${event.batteryVoltage}`,
Subject: `Hello from your IoT Button ${event.serialNumber}: ${event.clickType}`,
TopicArn: topicArn
}
console.log(JSON.stringify(params))
const data = {
serialNumber: event.serialNumber,
batteryVoltage: event.batteryVoltage,
clickType: event.clickType,
timestamp: Date.now(),
date: new Date().toJSON()
}
dynamoDbHelper.putItem(TABLE, data).then(() => SNS.publish(params, callback))
.catch(error => callback(null, {statusCode: 400, body: JSON.stringify(error)}))
})
}