Browse code

better time management

Louis authored on27/04/2025 17:13:09
Showing4 changed files
1 1
Binary files a/build/synocam_home_switch.pbw and b/build/synocam_home_switch.pbw differ
2 2
new file mode 100644
... ...
@@ -0,0 +1,12 @@
1
+{
2
+  "name": "dscam-h-s",
3
+  "version": "1.2.0",
4
+  "lockfileVersion": 2,
5
+  "requires": true,
6
+  "packages": {
7
+    "node_modules/pebble-clay": {
8
+      "version": "1.0.4",
9
+      "license": "MIT"
10
+    }
11
+  }
12
+}
0 13
new file mode 100644
... ...
@@ -0,0 +1,24 @@
1
+{
2
+  "name": "dscam-h-s",
3
+  "version": "1.2.0",
4
+  "lockfileVersion": 2,
5
+  "requires": true,
6
+  "packages": {
7
+    "": {
8
+      "name": "dscam-h-s",
9
+      "version": "1.2.0",
10
+      "dependencies": {
11
+        "pebble-clay": "^1.0.4"
12
+      }
13
+    },
14
+    "node_modules/pebble-clay": {
15
+      "version": "1.0.4",
16
+      "license": "MIT"
17
+    }
18
+  },
19
+  "dependencies": {
20
+    "pebble-clay": {
21
+      "version": "1.0.4"
22
+    }
23
+  }
24
+}
... ...
@@ -47,13 +47,13 @@ function leftpad(str, len, pad) {
47 47
 
48 48
 function getOtp() {
49 49
     key = base32tohex(JSON.parse(localStorage.getItem('clay-settings')).OTP_seed)
50
-        //console.log('-- seed:' + JSON.parse(localStorage.getItem('clay-settings')).OTP_seed)
51
-        //console.log('-- key:' + key)
50
+    //console.log('-- seed:' + JSON.parse(localStorage.getItem('clay-settings')).OTP_seed)
51
+    //console.log('-- key:' + key)
52 52
     var epoch = Math.round(new Date().getTime() / 1000.0);
53
-    if ((30-(epoch % 30))<10){
54
-        console.log('------- waiting for new TOTP,'+ epoch);
55
-	return false;
56
-    }else{
53
+    if ((30 - (epoch % 30)) < 10) {
54
+        console.log('------- waiting for new TOTP,' + epoch);
55
+        return false;
56
+    } else {
57 57
         var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0');
58 58
         // updated for jsSHA v2.0.0 - http://caligatio.github.io/jsSHA/
59 59
         var shaObj = new jsSHA("SHA-1", "HEX");
... ...
@@ -65,41 +65,41 @@ function getOtp() {
65 65
         //console.log('--offset:' + offset)
66 66
         var otp = (hex2dec(hmac.substring(offset * 2, offset * 2 + 8)) & hex2dec('7fffffff')) + '';
67 67
         otp = (otp).substring(otp.length - 6, otp.length);
68
-        console.log('------- TOTP ' + otp + ' is expiring in ' + (30-(epoch % 30)));
68
+        console.log('------- TOTP ' + otp + ' is expiring in ' + (30 - (epoch % 30)));
69 69
         return otp
70 70
     }
71 71
 }
72 72
 
73
-function xhr_to_syno(method, url_path, onload_function, max_retry) {
73
+function xhr_to_syno(method, url_path, onload_function, max_retry, timeout) {
74 74
     console.log('------xhr start')
75 75
     status = "";
76 76
     if (JSON.parse(localStorage.getItem('clay-settings')).server) {
77 77
         var server = JSON.parse(localStorage.getItem('clay-settings')).server
78 78
         url = server + url_path;
79 79
         var xhr = new XMLHttpRequest();
80
-        xhr.timeout = 120000; // time in milliseconds
80
+        xhr.timeout = timeout; // time in milliseconds
81 81
 
82 82
         xhr.open(method, url, true);
83 83
         console.log('------xhr opened')
84
-        xhr.onreadystatechange = function() {
84
+        xhr.onreadystatechange = function () {
85 85
             console.log('------xhr onreadystatechange')
86 86
             if (xhr.readyState === 4) {
87 87
                 retry = 0;
88 88
                 console.log('------xhr readyState 4');
89 89
                 if (xhr.status == 200) {
90
-                  console.log('------xhr status 200 ');
91
-                  onload_function(xhr);
92
-                  return true;
93
-                } else if(xhr.status == 407){ //blocked by proxy (and syno Firewall too)
94
-                  console.log('------xhr status 407 blocked by proxy (and syno Firewall too) ');
95
-                  onload_function(xhr);
96
-                  return false;
97
-                } else if(xhr.status >= 400){ //wrong credentials
98
-                  console.log('------xhr status 401 wrong credentials ');
99
-                  onload_function(xhr);
100
-                  return false;
101
-                } else if(xhr.status == 0){ //timeout
102
-                  retry++;
90
+                    console.log('------xhr status 200 ');
91
+                    onload_function(xhr);
92
+                    return true;
93
+                } else if (xhr.status == 407) { //blocked by proxy (and syno Firewall too)
94
+                    console.log('------xhr status 407 blocked by proxy (and syno Firewall too) ');
95
+                    onload_function(xhr);
96
+                    return false;
97
+                } else if (xhr.status >= 400) { //wrong credentials
98
+                    console.log('------xhr status 401 wrong credentials ');
99
+                    onload_function(xhr);
100
+                    return false;
101
+                } else if (xhr.status == 0) { //timeout
102
+                    retry++;
103 103
                     if (retry < max_retry) {
104 104
                         console.log('------xhr timed out retrying another time ');
105 105
                         //send back "timeout" to watch
... ...
@@ -111,13 +111,13 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
111 111
                         };
112 112
 
113 113
                         // Send the message
114
-                        Pebble.sendAppMessage(dict, function(e) {
114
+                        Pebble.sendAppMessage(dict, function (e) {
115 115
                             console.log('sent');
116
-                        }, function() {
116
+                        }, function () {
117 117
                             console.log('failed');
118 118
                         });
119 119
 
120
-                        setTimeout(function() { xhr_to_syno(method, url_path, onload_function, max_retry) }, 60000 * retry);
120
+                        setTimeout(function () { xhr_to_syno(method, url_path, onload_function, max_retry, timeout) }, 60000 * retry);
121 121
                     } else {
122 122
                         console.log('------xhr timed out ' + retry + ' times');
123 123
                         //send back "timeout" to watch
... ...
@@ -129,9 +129,9 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
129 129
                         };
130 130
 
131 131
                         // Send the message
132
-                        Pebble.sendAppMessage(dict, function(e) {
132
+                        Pebble.sendAppMessage(dict, function (e) {
133 133
                             console.log('sent');
134
-                        }, function() {
134
+                        }, function () {
135 135
                             console.log('failed');
136 136
                         });
137 137
                         return false;
... ...
@@ -145,21 +145,21 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
145 145
                     };
146 146
 
147 147
                     // Send the message
148
-                    Pebble.sendAppMessage(dict, function(e) {
148
+                    Pebble.sendAppMessage(dict, function (e) {
149 149
                         console.log('sent');
150
-                    }, function() {
150
+                    }, function () {
151 151
                         console.log('failed');
152 152
                     });
153 153
                     return false;
154 154
                 }
155 155
             } else {
156
-                console.log('------xhr readyState ' + xhr.readyState );
156
+                console.log('------xhr readyState ' + xhr.readyState);
157 157
 
158
-	    }
158
+            }
159 159
         };
160 160
 
161
-        xhr.ontimeout = function(e) {
162
-            
161
+        xhr.ontimeout = function (e) {
162
+
163 163
         };
164 164
         xhr.send(null);
165 165
 
... ...
@@ -183,14 +183,13 @@ function authenticate() {
183 183
         if (JSON.parse(localStorage.getItem('clay-settings')).OTP_enabled) {
184 184
             var otp_code = getOtp()
185 185
             if (!otp_code) {
186
-                setTimeout(function(){authenticate()},1000);
187
-		return true;
188
-	    }
186
+                return false
187
+            }
189 188
             console.log('-- otp_code is :' + otp_code)
190 189
             url_path = url_path + "&otp_code=" + otp_code
191 190
         }
192 191
         var method = "GET";
193
-        onload_function = function(xhr) {
192
+        onload_function = function (xhr) {
194 193
             response = JSON.parse(xhr.responseText);
195 194
             if (response.success == true) {
196 195
                 sid = response.data.sid;
... ...
@@ -202,12 +201,12 @@ function authenticate() {
202 201
                         'auth': message,
203 202
                     };
204 203
                     // Send the message
205
-                    Pebble.sendAppMessage(dict, function(e) {
204
+                    Pebble.sendAppMessage(dict, function (e) {
206 205
                         console.log('sent');
207
-                    }, function() {
206
+                    }, function () {
208 207
                         console.log('failed');
209 208
                     });
210
-                    timed_switch_home(15*60);
209
+                    timed_switch_home(15 * 60);
211 210
                 } else {
212 211
                     console.log('------Unexpected error : authentication is OK but no SID retrieved');
213 212
                     message = "Auth error, no SID";
... ...
@@ -216,39 +215,40 @@ function authenticate() {
216 215
                         'auth': message,
217 216
                     };
218 217
                     // Send the message
219
-                    Pebble.sendAppMessage(dict, function(e) {
218
+                    Pebble.sendAppMessage(dict, function (e) {
220 219
                         console.log('sent');
221
-                    }, function() {
220
+                    }, function () {
222 221
                         console.log('failed');
223 222
                     });
224 223
                 }
225 224
             } else {
226 225
                 console.log('------Authentication failed : ' + JSON.stringify(response));
227
-		    if (response.error.code==400){
228
-		        console.log('------Authentication failed because of wrong creds');
229
-                        message = "Authentication failed, check your credentials";
230
-		    }else if(response.error.code==404){
231
-			console.log('------Authentication failed because of wrong TOTP');
232
-                        message = "Authentication failed, check your TOTP seed";
233
-		    }
226
+                if (response.error.code == 400) {
227
+                    console.log('------Authentication failed because of wrong creds');
228
+                    message = "Authentication failed, check your credentials";
229
+                } else if (response.error.code == 404) {
230
+                    console.log('------Authentication failed because of wrong TOTP');
231
+                    message = "Authentication failed, check your TOTP seed";
232
+                }
234 233
                 // Build message
235 234
                 var dict = {
236 235
                     'auth': message,
237 236
                 };
238 237
                 // Send the message
239
-                Pebble.sendAppMessage(dict, function(e) {
238
+                Pebble.sendAppMessage(dict, function (e) {
240 239
                     console.log('sent');
241
-                }, function() {
240
+                }, function () {
242 241
                     console.log('failed');
243 242
                 });
244 243
             }
245 244
         };
246 245
         max_retry = 1;
247
-        xhr_to_syno(method, url_path, onload_function, max_retry);
246
+        xhr_to_syno(method, url_path, onload_function, max_retry, 20000);
248 247
     } else {
249 248
         console.log("--- failed to get settings");
250 249
         Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
251 250
     }
251
+    return true
252 252
 
253 253
 
254 254
 }
... ...
@@ -264,7 +264,7 @@ function get_status() {
264 264
         var url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid=" + sid;
265 265
         var method = "GET";
266 266
 
267
-        onload_function = function(xhr) {
267
+        onload_function = function (xhr) {
268 268
             response = JSON.parse(xhr.responseText);
269 269
             if (response.success == true) {
270 270
                 status = response.data.on;
... ...
@@ -288,18 +288,18 @@ function get_status() {
288 288
             };
289 289
 
290 290
             // Send the message
291
-            Pebble.sendAppMessage(dict, function(e) {
291
+            Pebble.sendAppMessage(dict, function (e) {
292 292
                 console.log('sent');
293
-            }, function() {
293
+            }, function () {
294 294
                 console.log('failed');
295 295
             });
296 296
         }
297 297
 
298 298
         max_retry = 10;
299
-        xhr_to_syno(method, url_path, onload_function, max_retry);
299
+        xhr_to_syno(method, url_path, onload_function, max_retry, 10000);
300 300
 
301 301
     } else {
302
-        authenticate();
302
+        authenticate();        
303 303
         get_status();
304 304
     }
305 305
 
... ...
@@ -307,44 +307,45 @@ function get_status() {
307 307
 
308 308
 
309 309
 function timed_switch_home(duration) {
310
-  var response;
311
-  console.log('---- authenticate');
312
-  if (sid != "") {
313
-    var epoch = Math.round(new Date().getTime() / 1000.0);
314
-    var start_ts = epoch + 10
315
-    var end_ts = duration + start_ts
316
-    var d= new Date(end_ts*1000)
317
-    var end_time = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
318
-    console.log('---- switching home mode for ' + duration + 'seconds, until '+end_time);
319
-    url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=SaveOneTimeSwitch&onetime_enable_on=true&onetime_disable_on=true&onetime_enable_time=" + start_ts + "&onetime_disable_time=" + end_ts + "&_sid=" + sid;
320
-    method = "GET"
321
-    onload_switch_function = function (xhr) {
322
-      response = JSON.parse(xhr.responseText);
323
-      if (response.success == true) {
324
-          message = "Home mode is ON until "+end_time;
325
-      }else{
326
-        message = "something happened, try again ! (S200)";
327
-      }
328
-      // Build message
329
-      dict = {
330
-        'status': message,
331
-      };
332
-
333
-      // Send the message Home mode is ON for 900 seconds
334
-      Pebble.sendAppMessage(dict, function (e) {
335
-        console.log('sent \"'+message+'\"');
336
-      }, function () {
337
-        console.log('failed');
338
-      });
339
-    }
340
-    max_retry = 10;
341
-    xhr_to_syno(method, url_path, onload_switch_function, max_retry);
310
+    var response;
311
+    console.log('---- timed switch');
312
+    if (sid != "") {
313
+        var epoch = Math.round(new Date().getTime() / 1000.0);
314
+        var start_ts = epoch + 10
315
+        var end_ts = duration + start_ts
316
+        var d = new Date(end_ts * 1000)
317
+        var end_time = d.toLocaleTimeString("fr-FR",{timestyle:'short'});
318
+        console.log('---- switching home mode for ' + duration + 'seconds, until ' + end_time);
319
+        url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=SaveOneTimeSwitch&onetime_enable_on=true&onetime_disable_on=true&onetime_enable_time=" + start_ts + "&onetime_disable_time=" + end_ts + "&_sid=" + sid;
320
+        method = "GET"
321
+        onload_switch_function = function (xhr) {
322
+            response = JSON.parse(xhr.responseText);
323
+            if (response.success == true) {
324
+                message = "Home mode is ON until " + end_time;
325
+            } else {
326
+                message = "something happened, try again ! (S200)";
327
+                console.log('---- ' + message + ' ' + xhr.responseText)
328
+            }
329
+            // Build message
330
+            dict = {
331
+                'status': message,
332
+            };
342 333
 
334
+            // Send the message Home mode is ON for 900 seconds
335
+            Pebble.sendAppMessage(dict, function (e) {
336
+                console.log('sent \"' + message + '\"');
337
+            }, function () {
338
+                console.log('failed');
339
+            });
340
+        }
341
+        max_retry = 10;
342
+        xhr_to_syno(method, url_path, onload_switch_function, max_retry, 10000);
343 343
 
344
-  } else {
345
-    authenticate();
346
-    switch_home(bool);
347
-  }
344
+
345
+    } else {
346
+        authenticate();
347
+        timed_switch_home(duration)
348
+    }
348 349
 
349 350
 }
350 351
 
... ...
@@ -364,10 +365,10 @@ function switch_home(bool) {
364 365
             default:
365 366
                 message = "something happened, try again ! (IMPOSSIBLE)";
366 367
         }
367
-        
368
+
368 369
         //url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on=" + bool + "&_sid=" + sid;
369 370
         method = "GET"
370
-        onload_switch_function = function(xhr) {
371
+        onload_switch_function = function (xhr) {
371 372
             response = JSON.parse(xhr.responseText);
372 373
             if (response.success == true) {
373 374
                 switch (bool) {
... ...
@@ -389,14 +390,14 @@ function switch_home(bool) {
389 390
             };
390 391
 
391 392
             // Send the message
392
-            Pebble.sendAppMessage(dict, function(e) {
393
+            Pebble.sendAppMessage(dict, function (e) {
393 394
                 console.log('sent');
394
-            }, function() {
395
+            }, function () {
395 396
                 console.log('failed');
396 397
             });
397 398
         }
398 399
         max_retry = 10;
399
-        xhr_to_syno(method, url_path, onload_switch_function, max_retry);
400
+        xhr_to_syno(method, url_path, onload_switch_function, max_retry, 10000);
400 401
 
401 402
 
402 403
     } else {
... ...
@@ -407,7 +408,7 @@ function switch_home(bool) {
407 408
 }
408 409
 
409 410
 // Get JS readiness events
410
-Pebble.addEventListener('ready', function(e) {
411
+Pebble.addEventListener('ready', function (e) {
411 412
     console.log("---- local storage:");
412 413
     console.log("user " + JSON.parse(localStorage.getItem('clay-settings')).username);
413 414
     console.log('PebbleKit JS is ready');
... ...
@@ -416,13 +417,16 @@ Pebble.addEventListener('ready', function(e) {
416 417
 });
417 418
 
418 419
 // Get AppMessage events
419
-Pebble.addEventListener('appmessage', function(e) {
420
+Pebble.addEventListener('appmessage', function (e) {
420 421
     // Get the dictionary from the message
421 422
     var dict = e.payload;
422 423
     console.log(dict[0].toString());
423 424
     switch (dict[0]) {
424 425
         case 'auth':
425
-            authenticate();
426
+            if (!authenticate()){
427
+                console.log("---- waited 1sec:");
428
+                setTimeout(authenticate(),1000);
429
+            }
426 430
             break;
427 431
         case 'get':
428 432
             get_status();