-
Notifications
You must be signed in to change notification settings - Fork 59
/
push-pushed.js
65 lines (60 loc) · 1.79 KB
/
push-pushed.js
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
/**
* Push notifications using Pushed service, pushed.co
* You can pair this script with another that emits events, for example
* readouts from a BLE sensor and push a notification to your phone
*/
let CONFIG = {
PUSHED_URL: 'https://api.pushed.co/1/push',
PUSHED_APP_KEY: null,
PUSHED_APP_SECRET: null,
PUSHED_TARGET_TYPE: "app",
};
function getPushedDataObject(msg) {
if (CONFIG.PUSHED_APP_KEY === null) return null;
if (CONFIG.PUSHED_APP_SECRET === null) return null;
if (typeof msg === "undefined" || msg === null) return null;
//object with keys as expected by Pushed
let result = {
app_key: CONFIG.PUSHED_APP_KEY,
app_secret: CONFIG.PUSHED_APP_SECRET,
target_type: CONFIG.PUSHED_TARGET_TYPE,
content: msg,
};
return result;
}
//JS object to x-www-form-urlencoded
function prepareFormData(pushed_obj) {
let post_body_arr = [];
for (let i in pushed_obj) {
post_body_arr.push(i + "=" + pushed_obj[i]);
}
let result = "";
for (let a_i in post_body_arr) {
if (result.length > 0) result += "&";
result += post_body_arr[a_i];
}
return result;
}
let notificationInFlight = false;
function sendNotification(msg) {
//bail out if we are sending at the moment, prevent spam
if (notificationInFlight) return false;
let pushed_data = getPushedDataObject(msg);
if(pushed_data === null) return;
let pushed_form_data = prepareFormData(pushed_data);
Shelly.call(
"HTTP.POST",
{
url: CONFIG.PUSHED_URL,
content_type: "application/x-www-form-urlencoded",
ssl_ca: "*",
timeout: 10,
body: pushed_form_data,
},
function (result, err_code, err_message) {
if (err_code !== 0) print(err_message);
console.log("Pushed result", JSON.stringify(result));
}
);
}
sendNotification("A message from Shelly");