-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
102 lines (95 loc) · 2.71 KB
/
background.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const API_URL = "https://api.spark.io/v1/devices/48ff6a065067555031111087/";
const INTERVAL = 5000;
const MOTION = 1000; // Threshold for IR sensor
const BRIGHTNESS = 1000; // Threshold for CDS sensor
function consoleError(devise, json) {
console.error("connection error : " + devise);
console.log(json);
if(JSON.parse(json.responseText).error == "invalid_grant") {
chrome.browserAction.setBadgeText({ text: "Token" });
} else {
chrome.browserAction.setBadgeText({ text: "Error" });
}
}
function clearError() {
chrome.browserAction.setBadgeText({ text: "" });
}
(function() {
var checkIndex = 0;
var valueMotion = 0;
var valueBrightness = 0;
setInterval(function() {
var sensorType = (checkIndex == 0) ? "A0" : "A1";
$.ajax({
type: 'POST',
url: API_URL + "analogread",
data: {
"access_token": localStorage["accessToken"],
"params" : sensorType
},
success: function(json) {
clearError()
var value = json.return_value;
// IR sensor
if(sensorType == "A0") {
valueMotion = value;
//chrome.browserAction.setBadgeText({ text: String(value) });
// CDS sensor
} else {
valueBrightness = value;
var usage = (valueMotion > MOTION) ? "use" : "vacant";
var light = (valueBrightness > BRIGHTNESS) ? "light" : "dark";
image = usage + "_" + light + ".png";
chrome.browserAction.setIcon({ path: image });
}
},
error: function(json) {
consoleError(sensorType, json);
}
});
checkIndex = (checkIndex + 1) % 2;
}, INTERVAL);
}).call(this);
chrome.browserAction.onClicked.addListener(
function knock() {
console.log("knock");
// on
$.ajax({
type: 'POST',
url: API_URL + "analogwrite",
data: {
"access_token": localStorage["accessToken"],
"params" : "D0,20"
},
success: function(json) {
var sleep = function(time) {
return (function() {
var dfd = $.Deferred()
setTimeout(function() { dfd.resolve(); }, time);
return dfd.promise()
})
}
sleep(1000);
// off
$.ajax({
type: 'POST',
url: API_URL + "analogwrite",
data: {
"access_token": localStorage["accessToken"],
"params" : "D0,0"
},
success: function(json) {
clearError()
var value = json.return_value;
},
error: function(json) {
consoleError("buzzer", json);
}
});
},
error: function(json) {
consoleError("buzzer", json);
}
});
}
);