Browse code

fix timeout issue

Louis authored on05/05/2025 18:36:16
Showing1 changed files
... ...
@@ -156,35 +156,39 @@ function authenticate(action_callback) {
156 156
         }
157 157
         var method = "GET";
158 158
         onload_function = function (xhr) {
159
-            response = JSON.parse(xhr.responseText);
160
-            if (response.success == true) {
161
-                sid = response.data.sid;
162
-                console.log('------Authentication succeeded');
163
-                if (sid != "") {
164
-                    message = "Authenticated";
165
-                    send_message_to_watch(message)
166
-                    home_mode_handler(action_callback);
159
+            console.log(JSON.stringify(xhr));
160
+            if (xhr.status == 0){
161
+                console.log('------Authentication failed because of request timed out');
162
+                message = "Time out";
163
+                send_message_to_watch(message)
164
+            } else {
165
+                response = JSON.parse(xhr.responseText);
166
+                if (response.success == true) {
167
+                    sid = response.data.sid;
168
+                    console.log('------Authentication succeeded');
169
+                    if (sid != "") {
170
+                        message = "Authenticated";
171
+                        send_message_to_watch(message)
172
+                        home_mode_handler(action_callback);
173
+                    } else {
174
+                        console.log('------Unexpected error : authentication is OK but no SID retrieved');
175
+                        message = "Auth error, no SID";
176
+                        send_message_to_watch(message)
177
+                    }
167 178
                 } else {
168
-                    console.log('------Unexpected error : authentication is OK but no SID retrieved');
169
-                    message = "Auth error, no SID";
179
+                    console.log('------Authentication failed : ' + JSON.stringify(response));
180
+                    if (response.error.code == 400) {
181
+                        console.log('------Authentication failed because of wrong creds');
182
+                        message = "Authentication failed, check your credentials";
183
+                    } else if (response.error.code == 404) {
184
+                        console.log('------Authentication failed because of wrong TOTP');
185
+                        message = "Authentication failed, check your TOTP seed";
186
+                    } else if (response.error.code == 407) {
187
+                        console.log('------Authentication failed because of IP Blocked');
188
+                        message = "Authentication failed, IP is blocked";
189
+                    }
170 190
                     send_message_to_watch(message)
171 191
                 }
172
-            } else {
173
-                console.log('------Authentication failed : ' + JSON.stringify(response));
174
-                if (response.error.code == 400) {
175
-                    console.log('------Authentication failed because of wrong creds');
176
-                    message = "Authentication failed, check your credentials";
177
-                } else if (response.error.code == 404) {
178
-                    console.log('------Authentication failed because of wrong TOTP');
179
-                    message = "Authentication failed, check your TOTP seed";
180
-                } else if (response.error.code == 407) {
181
-                    console.log('------Authentication failed because of IP Blocked');
182
-                    message = "Authentication failed, IP is blocked";
183
-                }else if (xhr.status == 0){
184
-                    console.log('------Authentication failed because of request timed out');
185
-                    message = "Time out";
186
-                }
187
-                send_message_to_watch(message)
188 192
             }
189 193
         };        
190 194
         send_message_to_watch("Authenticating....");
Browse code

manage timeout

Louis Jonget authored on02/05/2025 11:10:31
Showing1 changed files
... ...
@@ -106,8 +106,9 @@ function xhr_to_syno(method, url_path, onload_function, max_retry, timeout) {
106 106
                 } else if (xhr.status == 0) { //timeout
107 107
                     console.log('------xhr timed out');
108 108
                     //send back "timeout" to watch
109
-                    message = "Time out";
110
-                    send_message_to_watch(message)
109
+                    //message = "Time out";
110
+                    //send_message_to_watch(message)
111
+                    onload_function(xhr);
111 112
                 } else { // why would this happen?
112 113
                     console.log('------xhr request returned error code ' + xhr.status);
113 114
                     message = "Error (XHR" + xhr.status + ")";
... ...
@@ -179,6 +180,9 @@ function authenticate(action_callback) {
179 180
                 } else if (response.error.code == 407) {
180 181
                     console.log('------Authentication failed because of IP Blocked');
181 182
                     message = "Authentication failed, IP is blocked";
183
+                }else if (xhr.status == 0){
184
+                    console.log('------Authentication failed because of request timed out');
185
+                    message = "Time out";
182 186
                 }
183 187
                 send_message_to_watch(message)
184 188
             }
Browse code

new workflows adn refactoring

Louis authored on28/04/2025 18:37:32
Showing1 changed files
... ...
@@ -5,7 +5,7 @@ const jsSHA = require('./sha');
5 5
 
6 6
 var messageKeys = require('message_keys');
7 7
 
8
-var sid;
8
+var sid="";
9 9
 var status;
10 10
 var retry;
11 11
 retry = 0;
... ...
@@ -46,11 +46,12 @@ function leftpad(str, len, pad) {
46 46
 }
47 47
 
48 48
 function getOtp() {
49
+    send_message_to_watch("Authenticating..")
49 50
     key = base32tohex(JSON.parse(localStorage.getItem('clay-settings')).OTP_seed)
50 51
     //console.log('-- seed:' + JSON.parse(localStorage.getItem('clay-settings')).OTP_seed)
51 52
     //console.log('-- key:' + key)
52 53
     var epoch = Math.round(new Date().getTime() / 1000.0);
53
-    if ((30 - (epoch % 30)) < 10) {
54
+    if ((30 - (epoch % 30)) < 12) {
54 55
         console.log('------- waiting for new TOTP,' + epoch);
55 56
         return false;
56 57
     } else {
... ...
@@ -90,66 +91,27 @@ function xhr_to_syno(method, url_path, onload_function, max_retry, timeout) {
90 91
                     console.log('------xhr status 200 ');
91 92
                     onload_function(xhr);
92 93
                     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) ');
94
+                } else if (xhr.status == 407) { // IP blocked by syno (or by syno Firewall)
95
+                    console.log('------xhr status 407 IP blocked by syno (or by syno Firewall) ');
95 96
                     onload_function(xhr);
96 97
                     return false;
97
-                } else if (xhr.status >= 400) { //wrong credentials
98
-                    console.log('------xhr status 401 wrong credentials ');
98
+                } else if (xhr.status == 400) { //wrong credentials
99
+                    console.log('------xhr status wrong user or password ');
100
+                    onload_function(xhr);
101
+                    return false;
102
+                } else if (xhr.status == 404) { //wrong OTP
103
+                    console.log('------xhr status 404 wrong OTP ');
99 104
                     onload_function(xhr);
100 105
                     return false;
101 106
                 } else if (xhr.status == 0) { //timeout
102
-                    retry++;
103
-                    if (retry < max_retry) {
104
-                        console.log('------xhr timed out retrying another time ');
105
-                        //send back "timeout" to watch
106
-                        message = "Time out (" + retry + "), retrying...";
107
-
108
-                        // Build message
109
-                        var dict = {
110
-                            'status': message,
111
-                        };
112
-
113
-                        // Send the message
114
-                        Pebble.sendAppMessage(dict, function (e) {
115
-                            console.log('sent');
116
-                        }, function () {
117
-                            console.log('failed');
118
-                        });
119
-
120
-                        setTimeout(function () { xhr_to_syno(method, url_path, onload_function, max_retry, timeout) }, 60000 * retry);
121
-                    } else {
122
-                        console.log('------xhr timed out ' + retry + ' times');
123
-                        //send back "timeout" to watch
124
-                        message = "Time out " + retry + " times, verify settings and connectivity";
125
-
126
-                        // Build message
127
-                        var dict = {
128
-                            'status': message,
129
-                        };
130
-
131
-                        // Send the message
132
-                        Pebble.sendAppMessage(dict, function (e) {
133
-                            console.log('sent');
134
-                        }, function () {
135
-                            console.log('failed');
136
-                        });
137
-                        return false;
138
-                    }
139
-                } else { //timeout ?
107
+                    console.log('------xhr timed out');
108
+                    //send back "timeout" to watch
109
+                    message = "Time out";
110
+                    send_message_to_watch(message)
111
+                } else { // why would this happen?
140 112
                     console.log('------xhr request returned error code ' + xhr.status);
141 113
                     message = "Error (XHR" + xhr.status + ")";
142
-                    // Build message
143
-                    var dict = {
144
-                        'status': message,
145
-                    };
146
-
147
-                    // Send the message
148
-                    Pebble.sendAppMessage(dict, function (e) {
149
-                        console.log('sent');
150
-                    }, function () {
151
-                        console.log('failed');
152
-                    });
114
+                    send_message_to_watch(message)
153 115
                     return false;
154 116
                 }
155 117
             } else {
... ...
@@ -169,20 +131,23 @@ function xhr_to_syno(method, url_path, onload_function, max_retry, timeout) {
169 131
 
170 132
 }
171 133
 
172
-
173
-function authenticate() {
134
+function authenticate(action_callback) {    
135
+    send_message_to_watch("Authenticating.")
174 136
     var response;
175
-    sid = "";
137
+    sid = ""; //re-use sid from another session (7 days before expiry)
176 138
     console.log('---- authenticate');
177 139
     if (JSON.parse(localStorage.getItem('clay-settings')).username && JSON.parse(localStorage.getItem('clay-settings')).password) {
178 140
         var username = JSON.parse(localStorage.getItem('clay-settings')).username;
179 141
         var password = JSON.parse(localStorage.getItem('clay-settings')).password;
180
-        console.log('-- username:' + username);
181
-        console.log('-- password:' + password.substring(0, 1) + '...');
182 142
         var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=6&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
183 143
         if (JSON.parse(localStorage.getItem('clay-settings')).OTP_enabled) {
184 144
             var otp_code = getOtp()
185 145
             if (!otp_code) {
146
+                setTimeout( function () {
147
+                    send_message_to_watch("Authenticating...");
148
+                    home_mode_handler(action_callback);
149
+                    }
150
+                    ,4000);
186 151
                 return false
187 152
             }
188 153
             console.log('-- otp_code is :' + otp_code)
... ...
@@ -195,31 +160,13 @@ function authenticate() {
195 160
                 sid = response.data.sid;
196 161
                 console.log('------Authentication succeeded');
197 162
                 if (sid != "") {
198
-                    message = "Welcome to Syno Cam Switch ! ready & authenticated";
199
-                    // Build message
200
-                    var dict = {
201
-                        'auth': message,
202
-                    };
203
-                    // Send the message
204
-                    Pebble.sendAppMessage(dict, function (e) {
205
-                        console.log('sent');
206
-                    }, function () {
207
-                        console.log('failed');
208
-                    });
209
-                    timed_switch_home(15 * 60);
163
+                    message = "Authenticated";
164
+                    send_message_to_watch(message)
165
+                    home_mode_handler(action_callback);
210 166
                 } else {
211 167
                     console.log('------Unexpected error : authentication is OK but no SID retrieved');
212 168
                     message = "Auth error, no SID";
213
-                    // Build message
214
-                    var dict = {
215
-                        'auth': message,
216
-                    };
217
-                    // Send the message
218
-                    Pebble.sendAppMessage(dict, function (e) {
219
-                        console.log('sent');
220
-                    }, function () {
221
-                        console.log('failed');
222
-                    });
169
+                    send_message_to_watch(message)
223 170
                 }
224 171
             } else {
225 172
                 console.log('------Authentication failed : ' + JSON.stringify(response));
... ...
@@ -229,20 +176,15 @@ function authenticate() {
229 176
                 } else if (response.error.code == 404) {
230 177
                     console.log('------Authentication failed because of wrong TOTP');
231 178
                     message = "Authentication failed, check your TOTP seed";
179
+                } else if (response.error.code == 407) {
180
+                    console.log('------Authentication failed because of IP Blocked');
181
+                    message = "Authentication failed, IP is blocked";
232 182
                 }
233
-                // Build message
234
-                var dict = {
235
-                    'auth': message,
236
-                };
237
-                // Send the message
238
-                Pebble.sendAppMessage(dict, function (e) {
239
-                    console.log('sent');
240
-                }, function () {
241
-                    console.log('failed');
242
-                });
183
+                send_message_to_watch(message)
243 184
             }
244
-        };
245
-        max_retry = 1;
185
+        };        
186
+        send_message_to_watch("Authenticating....");
187
+        max_retry = 0;
246 188
         xhr_to_syno(method, url_path, onload_function, max_retry, 20000);
247 189
     } else {
248 190
         console.log("--- failed to get settings");
... ...
@@ -253,7 +195,6 @@ function authenticate() {
253 195
 
254 196
 }
255 197
 
256
-
257 198
 function get_status() {
258 199
     var response;
259 200
 
... ...
@@ -282,131 +223,93 @@ function get_status() {
282 223
             } else {
283 224
                 message = "something happened, try again ! (G200)";
284 225
             }
285
-            // Build message
286
-            var dict = {
287
-                'status': message,
288
-            };
289
-
290
-            // Send the message
291
-            Pebble.sendAppMessage(dict, function (e) {
292
-                console.log('sent');
293
-            }, function () {
294
-                console.log('failed');
295
-            });
226
+            send_message_to_watch(message)
296 227
         }
297 228
 
298 229
         max_retry = 10;
299 230
         xhr_to_syno(method, url_path, onload_function, max_retry, 10000);
300 231
 
301 232
     } else {
302
-        authenticate();        
303
-        get_status();
233
+        authenticate("get");
304 234
     }
305 235
 
306 236
 }
307 237
 
308
-
309
-function timed_switch_home(duration) {
238
+function home_mode_handler(action) {
310 239
     var response;
311
-    console.log('---- timed switch');
240
+    var duration = 15 * 60
312 241
     if (sid != "") {
242
+        console.log('---- switching home mode to ' + action);
313 243
         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
-            };
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
-
344
-
345
-    } else {
346
-        authenticate();
347
-        timed_switch_home(duration)
348
-    }
349
-
350
-}
351
-
352
-function switch_home(bool) {
353
-    var response;
354
-    if (sid != "") {
355
-        console.log('---- switching home mode to ' + bool);
356
-        var epoch = Math.round(new Date().getTime() / 1000.0);
357
-        var start_ts = epoch + 10
358
-        switch (bool) {
359
-            case true:
244
+        var start_ts = epoch + 10;
245
+        method = "GET";
246
+        max_retry = 0;
247
+        
248
+        switch (action) {
249
+            case "home_on":
250
+                send_message_to_watch("Setting Home Mode to ON")
360 251
                 url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=SaveOneTimeSwitch&onetime_enable_on=true&onetime_disable_on=false&onetime_enable_time=" + start_ts + "&_sid=" + sid;
361 252
                 break;
362
-            case false:
253
+            case "home_off":
254
+                send_message_to_watch("Setting Home Mode to OFF")
363 255
                 url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=SaveOneTimeSwitch&onetime_enable_on=false&onetime_disable_on=true&onetime_disable_time=" + start_ts + "&_sid=" + sid;
364 256
                 break;
257
+            case "timed":
258
+                send_message_to_watch("Temporary setting Home Mode to ON")
259
+                var end_ts = duration + start_ts
260
+                var d = new Date(end_ts * 1000)
261
+                var end_time = d.toLocaleTimeString("fr-FR",{timestyle:'short'});
262
+                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;    
263
+                break;
365 264
             default:
366 265
                 message = "something happened, try again ! (IMPOSSIBLE)";
367 266
         }
368
-
369
-        //url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on=" + bool + "&_sid=" + sid;
370
-        method = "GET"
267
+        
371 268
         onload_switch_function = function (xhr) {
372 269
             response = JSON.parse(xhr.responseText);
270
+            console.log(response.success);
373 271
             if (response.success == true) {
374
-                switch (bool) {
375
-                    case true:
272
+                switch (action) {
273
+                    case "home_on":
376 274
                         message = "Home mode is ON (camera is off)";
377 275
                         break;
378
-                    case false:
276
+                    case "home_off":
379 277
                         message = "Home mode is OFF (camera is on)";
380 278
                         break;
279
+                    case "timed":
280
+                        message = "Home mode is ON until " + end_time;
281
+                        break;
381 282
                     default:
382 283
                         message = "something happened, try again ! (IMPOSSIBLE)";
383 284
                 }
384 285
             } else {
385 286
                 message = "something happened, try again ! (S200)";
386 287
             }
387
-            // Build message
388
-            dict = {
389
-                'status': message,
390
-            };
391
-
392
-            // Send the message
393
-            Pebble.sendAppMessage(dict, function (e) {
394
-                console.log('sent');
395
-            }, function () {
396
-                console.log('failed');
397
-            });
288
+            send_message_to_watch(message)
398 289
         }
399
-        max_retry = 10;
290
+        max_retry = 0;
400 291
         xhr_to_syno(method, url_path, onload_switch_function, max_retry, 10000);
401 292
 
402 293
 
403 294
     } else {
404
-        authenticate();
405
-        switch_home(bool);
295
+        authenticate(action);
406 296
     }
407 297
 
408 298
 }
409 299
 
300
+function send_message_to_watch(message){
301
+    // Build message
302
+    var dict = {
303
+        'status': message,
304
+    };
305
+    console.log('DSCam Home-Switch: -- message to sent to watch:'+JSON.stringify(dict));
306
+    // Send the message
307
+    Pebble.sendAppMessage(dict, function (e) {
308
+        console.log('DSCam Home-Switch: -- message sent to watch');
309
+    }, function () {
310
+        console.log('DSCam Home-Switch: -- Failed to message sent to watch');
311
+    });
312
+}
410 313
 // Get JS readiness events
411 314
 Pebble.addEventListener('ready', function (e) {
412 315
     console.log("---- local storage:");
... ...
@@ -414,28 +317,25 @@ Pebble.addEventListener('ready', function (e) {
414 317
     console.log('PebbleKit JS is ready');
415 318
     // Update Watch on this
416 319
     Pebble.sendAppMessage({ 'JSReady': 1 });
320
+    send_message_to_watch("Welcome !")
417 321
 });
418 322
 
419 323
 // Get AppMessage events
420 324
 Pebble.addEventListener('appmessage', function (e) {
421 325
     // Get the dictionary from the message
422 326
     var dict = e.payload;
423
-    console.log(dict[0].toString());
424 327
     switch (dict[0]) {
425
-        case 'auth':
426
-            if (!authenticate()){
427
-                console.log("---- waited 1sec:");
428
-                setTimeout(authenticate(),1000);
429
-            }
430
-            break;
431 328
         case 'get':
432 329
             get_status();
433 330
             break;
331
+        case 'timed':
332
+            home_mode_handler("timed"); 
333
+            break;
434 334
         case 'home_on':
435
-            switch_home(true);
335
+            home_mode_handler("home_on");
436 336
             break;
437 337
         case 'home_off':
438
-            switch_home(false);
338
+            home_mode_handler("home_off");
439 339
             break;
440 340
         default:
441 341
             console.log('Sorry. I don\'t understand your request :' + dict[0]);
Browse code

better time management

Louis authored on27/04/2025 17:13:09
Showing1 changed files
... ...
@@ -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();
Browse code

now handling OTP expiration

Louis Jonget authored on28/02/2025 11:42:42
Showing1 changed files
... ...
@@ -50,18 +50,24 @@ function getOtp() {
50 50
         //console.log('-- seed:' + JSON.parse(localStorage.getItem('clay-settings')).OTP_seed)
51 51
         //console.log('-- key:' + key)
52 52
     var epoch = Math.round(new Date().getTime() / 1000.0);
53
-    var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0');
54
-    // updated for jsSHA v2.0.0 - http://caligatio.github.io/jsSHA/
55
-    var shaObj = new jsSHA("SHA-1", "HEX");
56
-    shaObj.setHMACKey(key, "HEX");
57
-    shaObj.update(time);
58
-    var hmac = shaObj.getHMAC("HEX");
59
-    //console.log('-- hmac:' + hmac)
60
-    var offset = hex2dec(hmac.substring(hmac.length - 1));
61
-    //console.log('--offset:' + offset)
62
-    var otp = (hex2dec(hmac.substring(offset * 2, offset * 2 + 8)) & hex2dec('7fffffff')) + '';
63
-    otp = (otp).substring(otp.length - 6, otp.length);
64
-    return otp
53
+    if ((30-(epoch % 30))<10){
54
+        console.log('------- waiting for new TOTP,'+ epoch);
55
+	return false;
56
+    }else{
57
+        var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0');
58
+        // updated for jsSHA v2.0.0 - http://caligatio.github.io/jsSHA/
59
+        var shaObj = new jsSHA("SHA-1", "HEX");
60
+        shaObj.setHMACKey(key, "HEX");
61
+        shaObj.update(time);
62
+        var hmac = shaObj.getHMAC("HEX");
63
+        //console.log('-- hmac:' + hmac)
64
+        var offset = hex2dec(hmac.substring(hmac.length - 1));
65
+        //console.log('--offset:' + offset)
66
+        var otp = (hex2dec(hmac.substring(offset * 2, offset * 2 + 8)) & hex2dec('7fffffff')) + '';
67
+        otp = (otp).substring(otp.length - 6, otp.length);
68
+        console.log('------- TOTP ' + otp + ' is expiring in ' + (30-(epoch % 30)));
69
+        return otp
70
+    }
65 71
 }
66 72
 
67 73
 function xhr_to_syno(method, url_path, onload_function, max_retry) {
... ...
@@ -146,7 +152,10 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
146 152
                     });
147 153
                     return false;
148 154
                 }
149
-            }
155
+            } else {
156
+                console.log('------xhr readyState ' + xhr.readyState );
157
+
158
+	    }
150 159
         };
151 160
 
152 161
         xhr.ontimeout = function(e) {
... ...
@@ -173,6 +182,10 @@ function authenticate() {
173 182
         var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=6&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
174 183
         if (JSON.parse(localStorage.getItem('clay-settings')).OTP_enabled) {
175 184
             var otp_code = getOtp()
185
+            if (!otp_code) {
186
+                setTimeout(function(){authenticate()},1000);
187
+		return true;
188
+	    }
176 189
             console.log('-- otp_code is :' + otp_code)
177 190
             url_path = url_path + "&otp_code=" + otp_code
178 191
         }
... ...
@@ -211,7 +224,13 @@ function authenticate() {
211 224
                 }
212 225
             } else {
213 226
                 console.log('------Authentication failed : ' + JSON.stringify(response));
214
-                message = "Authentication failed";
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
+		    }
215 234
                 // Build message
216 235
                 var dict = {
217 236
                     'auth': message,
... ...
@@ -224,7 +243,7 @@ function authenticate() {
224 243
                 });
225 244
             }
226 245
         };
227
-        max_retry = 10;
246
+        max_retry = 1;
228 247
         xhr_to_syno(method, url_path, onload_function, max_retry);
229 248
     } else {
230 249
         console.log("--- failed to get settings");
... ...
@@ -331,7 +350,6 @@ function timed_switch_home(duration) {
331 350
 
332 351
 function switch_home(bool) {
333 352
     var response;
334
-    console.log('---- authenticate');
335 353
     if (sid != "") {
336 354
         console.log('---- switching home mode to ' + bool);
337 355
         var epoch = Math.round(new Date().getTime() / 1000.0);
... ...
@@ -419,4 +437,4 @@ Pebble.addEventListener('appmessage', function(e) {
419 437
             console.log('Sorry. I don\'t understand your request :' + dict[0]);
420 438
     }
421 439
 
422
-});
423 440
\ No newline at end of file
441
+});
Browse code

increase timeout

Louis Jonget authored on14/02/2025 10:31:25
Showing1 changed files
... ...
@@ -71,7 +71,7 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
71 71
         var server = JSON.parse(localStorage.getItem('clay-settings')).server
72 72
         url = server + url_path;
73 73
         var xhr = new XMLHttpRequest();
74
-        xhr.timeout = 20000; // time in milliseconds
74
+        xhr.timeout = 120000; // time in milliseconds
75 75
 
76 76
         xhr.open(method, url, true);
77 77
         console.log('------xhr opened')
Browse code

fix schedule vs manual modes interactions

Louis Jonget authored on29/03/2024 10:58:42
Showing1 changed files
... ...
@@ -334,7 +334,20 @@ function switch_home(bool) {
334 334
     console.log('---- authenticate');
335 335
     if (sid != "") {
336 336
         console.log('---- switching home mode to ' + bool);
337
-        url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on=" + bool + "&_sid=" + sid;
337
+        var epoch = Math.round(new Date().getTime() / 1000.0);
338
+        var start_ts = epoch + 10
339
+        switch (bool) {
340
+            case true:
341
+                url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=SaveOneTimeSwitch&onetime_enable_on=true&onetime_disable_on=false&onetime_enable_time=" + start_ts + "&_sid=" + sid;
342
+                break;
343
+            case false:
344
+                url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=SaveOneTimeSwitch&onetime_enable_on=false&onetime_disable_on=true&onetime_disable_time=" + start_ts + "&_sid=" + sid;
345
+                break;
346
+            default:
347
+                message = "something happened, try again ! (IMPOSSIBLE)";
348
+        }
349
+        
350
+        //url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on=" + bool + "&_sid=" + sid;
338 351
         method = "GET"
339 352
         onload_switch_function = function(xhr) {
340 353
             response = JSON.parse(xhr.responseText);
Browse code

fix on timeout and XHR returned code

Louis Jonget authored on22/03/2024 14:30:49
Showing1 changed files
... ...
@@ -71,19 +71,66 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
71 71
         var server = JSON.parse(localStorage.getItem('clay-settings')).server
72 72
         url = server + url_path;
73 73
         var xhr = new XMLHttpRequest();
74
-        xhr.timeout = 60000; // time in milliseconds
74
+        xhr.timeout = 20000; // time in milliseconds
75 75
 
76 76
         xhr.open(method, url, true);
77 77
         console.log('------xhr opened')
78
-        xhr.onload = function() {
79
-            console.log('------xhr onload')
78
+        xhr.onreadystatechange = function() {
79
+            console.log('------xhr onreadystatechange')
80 80
             if (xhr.readyState === 4) {
81 81
                 retry = 0;
82
-                console.log('------xhr request returned');
82
+                console.log('------xhr readyState 4');
83 83
                 if (xhr.status == 200) {
84
-                    onload_function(xhr);
85
-                    return true;
86
-                } else {
84
+                  console.log('------xhr status 200 ');
85
+                  onload_function(xhr);
86
+                  return true;
87
+                } else if(xhr.status == 407){ //blocked by proxy (and syno Firewall too)
88
+                  console.log('------xhr status 407 blocked by proxy (and syno Firewall too) ');
89
+                  onload_function(xhr);
90
+                  return false;
91
+                } else if(xhr.status >= 400){ //wrong credentials
92
+                  console.log('------xhr status 401 wrong credentials ');
93
+                  onload_function(xhr);
94
+                  return false;
95
+                } else if(xhr.status == 0){ //timeout
96
+                  retry++;
97
+                    if (retry < max_retry) {
98
+                        console.log('------xhr timed out retrying another time ');
99
+                        //send back "timeout" to watch
100
+                        message = "Time out (" + retry + "), retrying...";
101
+
102
+                        // Build message
103
+                        var dict = {
104
+                            'status': message,
105
+                        };
106
+
107
+                        // Send the message
108
+                        Pebble.sendAppMessage(dict, function(e) {
109
+                            console.log('sent');
110
+                        }, function() {
111
+                            console.log('failed');
112
+                        });
113
+
114
+                        setTimeout(function() { xhr_to_syno(method, url_path, onload_function, max_retry) }, 60000 * retry);
115
+                    } else {
116
+                        console.log('------xhr timed out ' + retry + ' times');
117
+                        //send back "timeout" to watch
118
+                        message = "Time out " + retry + " times, verify settings and connectivity";
119
+
120
+                        // Build message
121
+                        var dict = {
122
+                            'status': message,
123
+                        };
124
+
125
+                        // Send the message
126
+                        Pebble.sendAppMessage(dict, function(e) {
127
+                            console.log('sent');
128
+                        }, function() {
129
+                            console.log('failed');
130
+                        });
131
+                        return false;
132
+                    }
133
+                } else { //timeout ?
87 134
                     console.log('------xhr request returned error code ' + xhr.status);
88 135
                     message = "Error (XHR" + xhr.status + ")";
89 136
                     // Build message
... ...
@@ -103,123 +150,87 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
103 150
         };
104 151
 
105 152
         xhr.ontimeout = function(e) {
106
-            retry++;
107
-            if (retry < max_retry) {
108
-                console.log('------xhr timed out retrying another time ');
109
-                //send back "timeout" to watch
110
-                message = "Time out (" + retry + "), retrying...";
153
+            
154
+        };
155
+        xhr.send(null);
111 156
 
112
-                // Build message
113
-                var dict = {
114
-                    'status': message,
115
-                };
157
+    } else {
158
+        Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
159
+    }
116 160
 
117
-                // Send the message
118
-                Pebble.sendAppMessage(dict, function(e) {
119
-                    console.log('sent');
120
-                }, function() {
121
-                    console.log('failed');
122
-                });
161
+}
123 162
 
124
-                setTimeout(function() { xhr_to_syno(method, url_path, onload_function, max_retry) }, 60000 * retry);
125
-            } else {
126
-                console.log('------xhr timed out ' + retry + ' times');
127
-                //send back "timeout" to watch
128
-                message = "Time out " + retry + " times, verify settings and connectivity";
129 163
 
164
+function authenticate() {
165
+    var response;
166
+    sid = "";
167
+    console.log('---- authenticate');
168
+    if (JSON.parse(localStorage.getItem('clay-settings')).username && JSON.parse(localStorage.getItem('clay-settings')).password) {
169
+        var username = JSON.parse(localStorage.getItem('clay-settings')).username;
170
+        var password = JSON.parse(localStorage.getItem('clay-settings')).password;
171
+        console.log('-- username:' + username);
172
+        console.log('-- password:' + password.substring(0, 1) + '...');
173
+        var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=6&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
174
+        if (JSON.parse(localStorage.getItem('clay-settings')).OTP_enabled) {
175
+            var otp_code = getOtp()
176
+            console.log('-- otp_code is :' + otp_code)
177
+            url_path = url_path + "&otp_code=" + otp_code
178
+        }
179
+        var method = "GET";
180
+        onload_function = function(xhr) {
181
+            response = JSON.parse(xhr.responseText);
182
+            if (response.success == true) {
183
+                sid = response.data.sid;
184
+                console.log('------Authentication succeeded');
185
+                if (sid != "") {
186
+                    message = "Welcome to Syno Cam Switch ! ready & authenticated";
187
+                    // Build message
188
+                    var dict = {
189
+                        'auth': message,
190
+                    };
191
+                    // Send the message
192
+                    Pebble.sendAppMessage(dict, function(e) {
193
+                        console.log('sent');
194
+                    }, function() {
195
+                        console.log('failed');
196
+                    });
197
+                    timed_switch_home(15*60);
198
+                } else {
199
+                    console.log('------Unexpected error : authentication is OK but no SID retrieved');
200
+                    message = "Auth error, no SID";
201
+                    // Build message
202
+                    var dict = {
203
+                        'auth': message,
204
+                    };
205
+                    // Send the message
206
+                    Pebble.sendAppMessage(dict, function(e) {
207
+                        console.log('sent');
208
+                    }, function() {
209
+                        console.log('failed');
210
+                    });
211
+                }
212
+            } else {
213
+                console.log('------Authentication failed : ' + JSON.stringify(response));
214
+                message = "Authentication failed";
130 215
                 // Build message
131 216
                 var dict = {
132
-                    'status': message,
217
+                    'auth': message,
133 218
                 };
134
-
135 219
                 // Send the message
136 220
                 Pebble.sendAppMessage(dict, function(e) {
137 221
                     console.log('sent');
138 222
                 }, function() {
139 223
                     console.log('failed');
140 224
                 });
141
-                return false;
142 225
             }
143 226
         };
144
-        xhr.send(null);
145
-
227
+        max_retry = 10;
228
+        xhr_to_syno(method, url_path, onload_function, max_retry);
146 229
     } else {
230
+        console.log("--- failed to get settings");
147 231
         Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
148 232
     }
149 233
 
150
-}
151
-
152
-
153
-function authenticate() {
154
-  var response;
155
-  sid = "";
156
-  console.log('---- authenticate');
157
-  if (JSON.parse(localStorage.getItem('clay-settings')).username && JSON.parse(localStorage.getItem('clay-settings')).password) {
158
-    var username = JSON.parse(localStorage.getItem('clay-settings')).username;
159
-    var password = JSON.parse(localStorage.getItem('clay-settings')).password;
160
-    console.log('-- username:' + username);
161
-    console.log('-- password:' + password.substring(0, 1) + '...');
162
-    var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=6&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
163
-    if (JSON.parse(localStorage.getItem('clay-settings')).OTP_enabled) {
164
-      var otp_code = getOtp()
165
-      console.log('-- otp_code is :' + otp_code)
166
-      url_path = url_path + "&otp_code=" + otp_code
167
-    }
168
-    var method = "GET";
169
-    onload_function = function (xhr) {
170
-      response = JSON.parse(xhr.responseText);
171
-      if (response.success == true) {
172
-        sid = response.data.sid;
173
-        console.log('------Authentication succeeded');
174
-        if (sid != "") {
175
-          message = "Welcome to Syno Cam Switch ! ready & authenticated";
176
-          // Build message
177
-          var dict = {
178
-            'auth': message,
179
-          };
180
-          // Send the message
181
-          Pebble.sendAppMessage(dict, function (e) {
182
-            console.log('sent');
183
-          }, function () {
184
-            console.log('failed');
185
-          });
186
-          timed_switch_home(15*60);
187
-        } else {
188
-          console.log('------Unexpected error : authentication is OK but no SID retrieved');
189
-          message = "Auth error, no SID";
190
-          // Build message
191
-          var dict = {
192
-            'auth': message,
193
-          };
194
-          // Send the message
195
-          Pebble.sendAppMessage(dict, function (e) {
196
-            console.log('sent');
197
-          }, function () {
198
-            console.log('failed');
199
-          });
200
-        }
201
-      } else {
202
-        console.log('------Authentication failed : ' + JSON.stringify(response));
203
-        message = "Authentication failed";
204
-        // Build message
205
-        var dict = {
206
-          'auth': message,
207
-        };
208
-        // Send the message
209
-        Pebble.sendAppMessage(dict, function (e) {
210
-          console.log('sent');
211
-        }, function () {
212
-          console.log('failed');
213
-        });
214
-      }
215
-    };
216
-    max_retry = 10;
217
-    xhr_to_syno(method, url_path, onload_function, max_retry);
218
-  } else {
219
-    console.log("--- failed to get settings");
220
-    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
221
-  }
222
-
223 234
 
224 235
 }
225 236
 
... ...
@@ -318,48 +329,6 @@ function timed_switch_home(duration) {
318 329
 
319 330
 }
320 331
 
321
-function timed_switch_home(duration) {
322
-  var response;
323
-  console.log('---- authenticate');
324
-  if (sid != "") {
325
-    var epoch = Math.round(new Date().getTime() / 1000.0);
326
-    var start_ts = epoch + 10
327
-    var end_ts = duration + start_ts
328
-    var d= new Date(end_ts*1000)
329
-    var end_time = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
330
-    console.log('---- switching home mode for ' + duration + 'seconds, until '+end_time);
331
-    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;
332
-    method = "GET"
333
-    onload_switch_function = function (xhr) {
334
-      response = JSON.parse(xhr.responseText);
335
-      if (response.success == true) {
336
-          message = "Home mode is ON until "+end_time;
337
-      }else{
338
-        message = "something happened, try again ! (S200)";
339
-      }
340
-      // Build message
341
-      dict = {
342
-        'status': message,
343
-      };
344
-
345
-      // Send the message Home mode is ON for 900 seconds
346
-      Pebble.sendAppMessage(dict, function (e) {
347
-        console.log('sent \"'+message+'\"');
348
-      }, function() {
349
-        console.log('failed');
350
-      });
351
-    }
352
-    max_retry = 10;
353
-    xhr_to_syno(method, url_path, onload_switch_function, max_retry);
354
-
355
-
356
-  } else {
357
-    authenticate();
358
-    switch_home(bool);
359
-  }
360
-
361
-}
362
-
363 332
 function switch_home(bool) {
364 333
     var response;
365 334
     console.log('---- authenticate');
... ...
@@ -416,26 +385,25 @@ Pebble.addEventListener('ready', function(e) {
416 385
 });
417 386
 
418 387
 // Get AppMessage events
419
-Pebble.addEventListener('appmessage', function (e) {
420
-  // Get the dictionary from the message
421
-  var dict = e.payload;
422
-  console.log(dict[0].toString());
423
-  switch (dict[0]) {
424
-    case 'auth':
425
-      authenticate();
426
-      break;
427
-    case 'get':
428
-      get_status();
429
-      break;
430
-    case 'home_on':
431
-      switch_home(true);
432
-      //timed_switch_home(15*60)
433
-      break;
434
-    case 'home_off':
435
-      switch_home(false);
436
-      break;
437
-    default:
438
-      console.log('Sorry. I don\'t understand your request :' + dict[0]);
439
-  }
388
+Pebble.addEventListener('appmessage', function(e) {
389
+    // Get the dictionary from the message
390
+    var dict = e.payload;
391
+    console.log(dict[0].toString());
392
+    switch (dict[0]) {
393
+        case 'auth':
394
+            authenticate();
395
+            break;
396
+        case 'get':
397
+            get_status();
398
+            break;
399
+        case 'home_on':
400
+            switch_home(true);
401
+            break;
402
+        case 'home_off':
403
+            switch_home(false);
404
+            break;
405
+        default:
406
+            console.log('Sorry. I don\'t understand your request :' + dict[0]);
407
+    }
440 408
 
441 409
 });
442 410
\ No newline at end of file
Browse code

Merge branch 'master' of ssh://jonget.fr:5522/volume1/web/gitlist.1.0.2/repos/synocam_home_switch/

Louis Jonget authored on11/03/2024 17:55:51
Showing0 changed files
Browse code

open app with timed_switch to reduce calls up button is back to hom mode on

Louis Jonget authored on11/03/2024 17:12:25
Showing1 changed files
... ...
@@ -182,7 +182,7 @@ function authenticate() {
182 182
           }, function () {
183 183
             console.log('failed');
184 184
           });
185
-          get_status();
185
+          timed_switch_home(15*60);
186 186
         } else {
187 187
           console.log('------Unexpected error : authentication is OK but no SID retrieved');
188 188
           message = "Auth error, no SID";
... ...
@@ -280,15 +280,17 @@ function timed_switch_home(duration) {
280 280
   console.log('---- authenticate');
281 281
   if (sid != "") {
282 282
     var epoch = Math.round(new Date().getTime() / 1000.0);
283
-    var start_ts = epoch //+ 10
283
+    var start_ts = epoch + 10
284 284
     var end_ts = duration + start_ts
285
-    console.log('---- switching home mode for ' + duration + 'seconds');
285
+    var d= new Date(end_ts*1000)
286
+    var end_time = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
287
+    console.log('---- switching home mode for ' + duration + 'seconds, until '+end_time);
286 288
     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;
287 289
     method = "GET"
288 290
     onload_switch_function = function (xhr) {
289 291
       response = JSON.parse(xhr.responseText);
290 292
       if (response.success == true) {
291
-          message = "Home mode is ON for "+duration+" seconds";
293
+          message = "Home mode is ON until "+end_time;
292 294
       }else{
293 295
         message = "something happened, try again ! (S200)";
294 296
       }
... ...
@@ -383,8 +385,8 @@ Pebble.addEventListener('appmessage', function (e) {
383 385
       get_status();
384 386
       break;
385 387
     case 'home_on':
386
-      //switch_home(true);
387
-      timed_switch_home(15*60)
388
+      switch_home(true);
389
+      //timed_switch_home(15*60)
388 390
       break;
389 391
     case 'home_off':
390 392
       switch_home(false);
Browse code

using timed switch instead of manual ON

Louis Jonget authored on22/12/2023 12:36:38
Showing1 changed files
... ...
@@ -275,6 +275,46 @@ function get_status() {
275 275
 }
276 276
 
277 277
 
278
+function timed_switch_home(duration) {
279
+  var response;
280
+  console.log('---- authenticate');
281
+  if (sid != "") {
282
+    var epoch = Math.round(new Date().getTime() / 1000.0);
283
+    var start_ts = epoch //+ 10
284
+    var end_ts = duration + start_ts
285
+    console.log('---- switching home mode for ' + duration + 'seconds');
286
+    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;
287
+    method = "GET"
288
+    onload_switch_function = function (xhr) {
289
+      response = JSON.parse(xhr.responseText);
290
+      if (response.success == true) {
291
+          message = "Home mode is ON for "+duration+" seconds";
292
+      }else{
293
+        message = "something happened, try again ! (S200)";
294
+      }
295
+      // Build message
296
+      dict = {
297
+        'status': message,
298
+      };
299
+
300
+      // Send the message Home mode is ON for 900 seconds
301
+      Pebble.sendAppMessage(dict, function (e) {
302
+        console.log('sent \"'+message+'\"');
303
+      }, function () {
304
+        console.log('failed');
305
+      });
306
+    }
307
+    max_retry = 10;
308
+    xhr_to_syno(method, url_path, onload_switch_function, max_retry);
309
+
310
+
311
+  } else {
312
+    authenticate();
313
+    switch_home(bool);
314
+  }
315
+
316
+}
317
+
278 318
 function switch_home(bool) {
279 319
   var response;
280 320
   console.log('---- authenticate');
... ...
@@ -343,7 +383,8 @@ Pebble.addEventListener('appmessage', function (e) {
343 383
       get_status();
344 384
       break;
345 385
     case 'home_on':
346
-      switch_home(true);
386
+      //switch_home(true);
387
+      timed_switch_home(15*60)
347 388
       break;
348 389
     case 'home_off':
349 390
       switch_home(false);
Browse code

- timeout and retry with incremental backoff - substr to substring

Louis authored on01/06/2023 21:50:13
Showing1 changed files
... ...
@@ -8,348 +8,349 @@ var messageKeys = require('message_keys');
8 8
 var sid;
9 9
 var status;
10 10
 var retry;
11
-retry = 1;
11
+retry = 0;
12 12
 
13 13
 
14 14
 function dec2hex(s) {
15
-  return (s < 15.5 ? '0' : '') + Math.round(s).toString(16);
15
+    return (s < 15.5 ? '0' : '') + Math.round(s).toString(16);
16 16
 }
17 17
 
18 18
 function hex2dec(s) {
19
-  return parseInt(s, 16);
19
+    return parseInt(s, 16);
20 20
 }
21 21
 
22 22
 function base32tohex(base32) {
23
-  var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
24
-  var bits = "";
25
-  var hex = "";
26
-
27
-  for (var i = 0; i < base32.length; i++) {
28
-    var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
29
-    bits += leftpad(val.toString(2), 5, '0');
30
-  }
31
-  //console.log('-- bits : ' + bits)
32
-
33
-  for (var i = 0; i + 4 <= bits.length; i += 4) {
34
-    var chunk = bits.substr(i, 4);
35
-    hex = hex + parseInt(chunk, 2).toString(16);
36
-  }
37
-  return hex;
23
+    var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
24
+    var bits = "";
25
+    var hex = "";
26
+
27
+    for (var i = 0; i < base32.length; i++) {
28
+        var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
29
+        bits += leftpad(val.toString(2), 5, '0');
30
+    }
31
+    //console.log('-- bits : ' + bits)
32
+
33
+    for (var i = 0; i + 4 <= bits.length; i += 4) {
34
+        var chunk = bits.substring(i, i + 4);
35
+        hex = hex + parseInt(chunk, 2).toString(16);
36
+    }
37
+    return hex;
38 38
 
39 39
 }
40 40
 
41 41
 function leftpad(str, len, pad) {
42
-  if (len + 1 >= str.length) {
43
-    str = Array(len + 1 - str.length).join(pad) + str;
44
-  }
45
-  return str;
42
+    if (len + 1 >= str.length) {
43
+        str = Array(len + 1 - str.length).join(pad) + str;
44
+    }
45
+    return str;
46 46
 }
47 47
 
48 48
 function getOtp() {
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)
52
-  var epoch = Math.round(new Date().getTime() / 1000.0);
53
-  var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0');
54
-  // updated for jsSHA v2.0.0 - http://caligatio.github.io/jsSHA/
55
-  var shaObj = new jsSHA("SHA-1", "HEX");
56
-  shaObj.setHMACKey(key, "HEX");
57
-  shaObj.update(time);
58
-  var hmac = shaObj.getHMAC("HEX");
59
-  //console.log('-- hmac:' + hmac)
60
-  var offset = hex2dec(hmac.substring(hmac.length - 1));
61
-  //console.log('--offset:' + offset)
62
-  var otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec('7fffffff')) + '';
63
-  otp = (otp).substr(otp.length - 6, 6);
64
-  return otp
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)
52
+    var epoch = Math.round(new Date().getTime() / 1000.0);
53
+    var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0');
54
+    // updated for jsSHA v2.0.0 - http://caligatio.github.io/jsSHA/
55
+    var shaObj = new jsSHA("SHA-1", "HEX");
56
+    shaObj.setHMACKey(key, "HEX");
57
+    shaObj.update(time);
58
+    var hmac = shaObj.getHMAC("HEX");
59
+    //console.log('-- hmac:' + hmac)
60
+    var offset = hex2dec(hmac.substring(hmac.length - 1));
61
+    //console.log('--offset:' + offset)
62
+    var otp = (hex2dec(hmac.substring(offset * 2, offset * 2 + 8)) & hex2dec('7fffffff')) + '';
63
+    otp = (otp).substring(otp.length - 6, otp.length);
64
+    return otp
65 65
 }
66 66
 
67 67
 function xhr_to_syno(method, url_path, onload_function, max_retry) {
68
-  console.log('------xhr start')
69
-  status = "";
70
-  if (JSON.parse(localStorage.getItem('clay-settings')).server) {
71
-    var server = JSON.parse(localStorage.getItem('clay-settings')).server
72
-    url = server + url_path;
73
-    var xhr = new XMLHttpRequest();
74
-    xhr.timeout = 6000; // time in milliseconds
75
-
76
-    xhr.open(method, url, true);
77
-    console.log('------xhr opened')
78
-    xhr.onload = function () {
79
-      console.log('------xhr onload')
80
-      if (xhr.readyState === 4) {
81
-        retry = 1;
82
-        console.log('------xhr request returned');
83
-        if (xhr.status == 200) {
84
-          onload_function(xhr);
85
-          return true;
86
-        } else {
87
-          console.log('------xhr request returned error code ' + xhr.status);
88
-          message = "Error (XHR"+xhr.status+")";
89
-          // Build message
90
-          var dict = {
91
-            'status': message,
92
-          };
93
-
94
-          // Send the message
95
-          Pebble.sendAppMessage(dict, function (e) {
96
-            console.log('sent');
97
-          }, function () {
98
-            console.log('failed');
99
-          });
100
-          return false;
101
-        }
102
-      }
103
-    };
104
-
105
-    xhr.ontimeout = function (e) {
106
-      retry++;
107
-      if (retry < max_retry) {
108
-        console.log('------xhr timed out retrying another time ');
109
-        //send back "timeout" to watch
110
-        message = "Time out, retrying...";
111
-
112
-        // Build message
113
-        var dict = {
114
-          'status': message,
68
+    console.log('------xhr start')
69
+    status = "";
70
+    if (JSON.parse(localStorage.getItem('clay-settings')).server) {
71
+        var server = JSON.parse(localStorage.getItem('clay-settings')).server
72
+        url = server + url_path;
73
+        var xhr = new XMLHttpRequest();
74
+        xhr.timeout = 60000; // time in milliseconds
75
+
76
+        xhr.open(method, url, true);
77
+        console.log('------xhr opened')
78
+        xhr.onload = function() {
79
+            console.log('------xhr onload')
80
+            if (xhr.readyState === 4) {
81
+                retry = 0;
82
+                console.log('------xhr request returned');
83
+                if (xhr.status == 200) {
84
+                    onload_function(xhr);
85
+                    return true;
86
+                } else {
87
+                    console.log('------xhr request returned error code ' + xhr.status);
88
+                    message = "Error (XHR" + xhr.status + ")";
89
+                    // Build message
90
+                    var dict = {
91
+                        'status': message,
92
+                    };
93
+
94
+                    // Send the message
95
+                    Pebble.sendAppMessage(dict, function(e) {
96
+                        console.log('sent');
97
+                    }, function() {
98
+                        console.log('failed');
99
+                    });
100
+                    return false;
101
+                }
102
+            }
115 103
         };
116 104
 
117
-        // Send the message
118
-        Pebble.sendAppMessage(dict, function (e) {
119
-          console.log('sent');
120
-        }, function () {
121
-          console.log('failed');
122
-        });
123
-        xhr_to_syno(method, url_path, onload_function, max_retry);
124
-      } else {
125
-        console.log('------xhr timed out ' + retry + ' times');
126
-        //send back "timeout" to watch
127
-        message = "Time out too many times, verify settings and connectivity";
128
-
129
-        // Build message
130
-        var dict = {
131
-          'status': message,
105
+        xhr.ontimeout = function(e) {
106
+            retry++;
107
+            if (retry < max_retry) {
108
+                console.log('------xhr timed out retrying another time ');
109
+                //send back "timeout" to watch
110
+                message = "Time out (" + retry + "), retrying...";
111
+
112
+                // Build message
113
+                var dict = {
114
+                    'status': message,
115
+                };
116
+
117
+                // Send the message
118
+                Pebble.sendAppMessage(dict, function(e) {
119
+                    console.log('sent');
120
+                }, function() {
121
+                    console.log('failed');
122
+                });
123
+
124
+                setTimeout(function() { xhr_to_syno(method, url_path, onload_function, max_retry) }, 60000 * retry);
125
+            } else {
126
+                console.log('------xhr timed out ' + retry + ' times');
127
+                //send back "timeout" to watch
128
+                message = "Time out " + retry + " times, verify settings and connectivity";
129
+
130
+                // Build message
131
+                var dict = {
132
+                    'status': message,
133
+                };
134
+
135
+                // Send the message
136
+                Pebble.sendAppMessage(dict, function(e) {
137
+                    console.log('sent');
138
+                }, function() {
139
+                    console.log('failed');
140
+                });
141
+                return false;
142
+            }
132 143
         };
144
+        xhr.send(null);
133 145
 
134
-        // Send the message
135
-        Pebble.sendAppMessage(dict, function (e) {
136
-          console.log('sent');
137
-        }, function () {
138
-          console.log('failed');
139
-        });
140
-        return false;
141
-      }
142
-    };
143
-    xhr.send(null);
144
-
145
-  } else {
146
-    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
147
-  }
146
+    } else {
147
+        Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
148
+    }
148 149
 
149 150
 }
150 151
 
151 152
 
152 153
 function authenticate() {
153
-  var response;
154
-  sid = "";
155
-  console.log('---- authenticate');
156
-  if (JSON.parse(localStorage.getItem('clay-settings')).username && JSON.parse(localStorage.getItem('clay-settings')).password) {
157
-    var username = JSON.parse(localStorage.getItem('clay-settings')).username;
158
-    var password = JSON.parse(localStorage.getItem('clay-settings')).password;
159
-    console.log('-- username:' + username);
160
-    console.log('-- password:' + password.substring(0, 1) + '...');
161
-    var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=6&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
162
-    if (JSON.parse(localStorage.getItem('clay-settings')).OTP_enabled) {
163
-      var otp_code = getOtp()
164
-      console.log('-- otp_code is :' + otp_code)
165
-      url_path = url_path + "&otp_code=" + otp_code
166
-    }
167
-    var method = "GET";
168
-    onload_function = function (xhr) {
169
-      response = JSON.parse(xhr.responseText);
170
-      if (response.success == true) {
171
-        sid = response.data.sid;
172
-        console.log('------Authentication succeeded');
173
-        if (sid != "") {
174
-          message = "Welcome to Syno Cam Switch ! ready & authenticated";
175
-          // Build message
176
-          var dict = {
177
-            'auth': message,
178
-          };
179
-          // Send the message
180
-          Pebble.sendAppMessage(dict, function (e) {
181
-            console.log('sent');
182
-          }, function () {
183
-            console.log('failed');
184
-          });
185
-          get_status();
186
-        } else {
187
-          console.log('------Unexpected error : authentication is OK but no SID retrieved');
188
-          message = "Auth error, no SID";
189
-          // Build message
190
-          var dict = {
191
-            'auth': message,
192
-          };
193
-          // Send the message
194
-          Pebble.sendAppMessage(dict, function (e) {
195
-            console.log('sent');
196
-          }, function () {
197
-            console.log('failed');
198
-          });
154
+    var response;
155
+    sid = "";
156
+    console.log('---- authenticate');
157
+    if (JSON.parse(localStorage.getItem('clay-settings')).username && JSON.parse(localStorage.getItem('clay-settings')).password) {
158
+        var username = JSON.parse(localStorage.getItem('clay-settings')).username;
159
+        var password = JSON.parse(localStorage.getItem('clay-settings')).password;
160
+        console.log('-- username:' + username);
161
+        console.log('-- password:' + password.substring(0, 1) + '...');
162
+        var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=6&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
163
+        if (JSON.parse(localStorage.getItem('clay-settings')).OTP_enabled) {
164
+            var otp_code = getOtp()
165
+            console.log('-- otp_code is :' + otp_code)
166
+            url_path = url_path + "&otp_code=" + otp_code
199 167
         }
200
-      } else {
201
-        console.log('------Authentication failed : ' + JSON.stringify(response));
202
-        message = "Authentication failed";
203
-        // Build message
204
-        var dict = {
205
-          'auth': message,
168
+        var method = "GET";
169
+        onload_function = function(xhr) {
170
+            response = JSON.parse(xhr.responseText);
171
+            if (response.success == true) {
172
+                sid = response.data.sid;
173
+                console.log('------Authentication succeeded');
174
+                if (sid != "") {
175
+                    message = "Welcome to Syno Cam Switch ! ready & authenticated";
176
+                    // Build message
177
+                    var dict = {
178
+                        'auth': message,
179
+                    };
180
+                    // Send the message
181
+                    Pebble.sendAppMessage(dict, function(e) {
182
+                        console.log('sent');
183
+                    }, function() {
184
+                        console.log('failed');
185
+                    });
186
+                    get_status();
187
+                } else {
188
+                    console.log('------Unexpected error : authentication is OK but no SID retrieved');
189
+                    message = "Auth error, no SID";
190
+                    // Build message
191
+                    var dict = {
192
+                        'auth': message,
193
+                    };
194
+                    // Send the message
195
+                    Pebble.sendAppMessage(dict, function(e) {
196
+                        console.log('sent');
197
+                    }, function() {
198
+                        console.log('failed');
199
+                    });
200
+                }
201
+            } else {
202
+                console.log('------Authentication failed : ' + JSON.stringify(response));
203
+                message = "Authentication failed";
204
+                // Build message
205
+                var dict = {
206
+                    'auth': message,
207
+                };
208
+                // Send the message
209
+                Pebble.sendAppMessage(dict, function(e) {
210
+                    console.log('sent');
211
+                }, function() {
212
+                    console.log('failed');
213
+                });
214
+            }
206 215
         };
207
-        // Send the message
208
-        Pebble.sendAppMessage(dict, function (e) {
209
-          console.log('sent');
210
-        }, function () {
211
-          console.log('failed');
212
-        });
213
-      }
214
-    };
215
-    max_retry = 10;
216
-    xhr_to_syno(method, url_path, onload_function, max_retry);
217
-  } else {
218
-    console.log("--- failed to get settings");
219
-    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
220
-  }
216
+        max_retry = 10;
217
+        xhr_to_syno(method, url_path, onload_function, max_retry);
218
+    } else {
219
+        console.log("--- failed to get settings");
220
+        Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
221
+    }
221 222
 
222 223
 
223 224
 }
224 225
 
225 226
 
226 227
 function get_status() {
227
-  var response;
228
-
229
-  if (sid != "") {
230
-    status = "";
231
-    console.log('---- get_status');
232
-
233
-    var url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid=" + sid;
234
-    var method = "GET";
235
-
236
-    onload_function = function (xhr) {
237
-      response = JSON.parse(xhr.responseText);
238
-      if (response.success == true) {
239
-        status = response.data.on;
240
-        var message;
241
-        switch (status) {
242
-          case true:
243
-            message = "Home mode is ON (camera is off)";
244
-            break;
245
-          case false:
246
-            message = "Home mode is OFF (camera is on)";
247
-            break;
248
-          default:
249
-            message = "something happened, try again ! (IMPOSSIBLE)";
228
+    var response;
229
+
230
+    if (sid != "") {
231
+        status = "";
232
+        console.log('---- get_status');
233
+
234
+        var url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid=" + sid;
235
+        var method = "GET";
236
+
237
+        onload_function = function(xhr) {
238
+            response = JSON.parse(xhr.responseText);
239
+            if (response.success == true) {
240
+                status = response.data.on;
241
+                var message;
242
+                switch (status) {
243
+                    case true:
244
+                        message = "Home mode is ON (camera is off)";
245
+                        break;
246
+                    case false:
247
+                        message = "Home mode is OFF (camera is on)";
248
+                        break;
249
+                    default:
250
+                        message = "something happened, try again ! (IMPOSSIBLE)";
251
+                }
252
+            } else {
253
+                message = "something happened, try again ! (G200)";
254
+            }
255
+            // Build message
256
+            var dict = {
257
+                'status': message,
258
+            };
259
+
260
+            // Send the message
261
+            Pebble.sendAppMessage(dict, function(e) {
262
+                console.log('sent');
263
+            }, function() {
264
+                console.log('failed');
265
+            });
250 266
         }
251
-      }else{
252
-        message = "something happened, try again ! (G200)";
253
-      }
254
-      // Build message
255
-      var dict = {
256
-        'status': message,
257
-      };
258
-
259
-      // Send the message
260
-      Pebble.sendAppMessage(dict, function (e) {
261
-        console.log('sent');
262
-      }, function () {
263
-        console.log('failed');
264
-      });
265
-    }
266 267
 
267
-    max_retry = 10;
268
-    xhr_to_syno(method, url_path, onload_function, max_retry);
268
+        max_retry = 10;
269
+        xhr_to_syno(method, url_path, onload_function, max_retry);
269 270
 
270
-  } else {
271
-    authenticate();
272
-    get_status();
273
-  }
271
+    } else {
272
+        authenticate();
273
+        get_status();
274
+    }
274 275
 
275 276
 }
276 277
 
277 278
 
278 279
 function switch_home(bool) {
279
-  var response;
280
-  console.log('---- authenticate');
281
-  if (sid != "") {
282
-    console.log('---- switching home mode to ' + bool);
283
-    url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on=" + bool + "&_sid=" + sid;
284
-    method = "GET"
285
-    onload_switch_function = function (xhr) {
286
-      response = JSON.parse(xhr.responseText);
287
-      if (response.success == true) {
288
-        switch (bool) {
289
-          case true:
290
-            message = "Home mode is ON (camera is off)";
291
-            break;
292
-          case false:
293
-            message = "Home mode is OFF (camera is on)";
294
-            break;
295
-          default:
296
-            message = "something happened, try again ! (IMPOSSIBLE)";
280
+    var response;
281
+    console.log('---- authenticate');
282
+    if (sid != "") {
283
+        console.log('---- switching home mode to ' + bool);
284
+        url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on=" + bool + "&_sid=" + sid;
285
+        method = "GET"
286
+        onload_switch_function = function(xhr) {
287
+            response = JSON.parse(xhr.responseText);
288
+            if (response.success == true) {
289
+                switch (bool) {
290
+                    case true:
291
+                        message = "Home mode is ON (camera is off)";
292
+                        break;
293
+                    case false:
294
+                        message = "Home mode is OFF (camera is on)";
295
+                        break;
296
+                    default:
297
+                        message = "something happened, try again ! (IMPOSSIBLE)";
298
+                }
299
+            } else {
300
+                message = "something happened, try again ! (S200)";
301
+            }
302
+            // Build message
303
+            dict = {
304
+                'status': message,
305
+            };
306
+
307
+            // Send the message
308
+            Pebble.sendAppMessage(dict, function(e) {
309
+                console.log('sent');
310
+            }, function() {
311
+                console.log('failed');
312
+            });
297 313
         }
298
-      }else{
299
-        message = "something happened, try again ! (S200)";
300
-      }
301
-      // Build message
302
-      dict = {
303
-        'status': message,
304
-      };
305
-
306
-      // Send the message
307
-      Pebble.sendAppMessage(dict, function (e) {
308
-        console.log('sent');
309
-      }, function () {
310
-        console.log('failed');
311
-      });
312
-    }
313
-    max_retry = 10;
314
-    xhr_to_syno(method, url_path, onload_switch_function, max_retry);
314
+        max_retry = 10;
315
+        xhr_to_syno(method, url_path, onload_switch_function, max_retry);
315 316
 
316 317
 
317
-  } else {
318
-    authenticate();
319
-    switch_home(bool);
320
-  }
318
+    } else {
319
+        authenticate();
320
+        switch_home(bool);
321
+    }
321 322
 
322 323
 }
323 324
 
324 325
 // Get JS readiness events
325
-Pebble.addEventListener('ready', function (e) {
326
-  console.log("---- local storage:");
327
-  console.log("user " + JSON.parse(localStorage.getItem('clay-settings')).username);
328
-  console.log('PebbleKit JS is ready');
329
-  // Update Watch on this
330
-  Pebble.sendAppMessage({ 'JSReady': 1 });
326
+Pebble.addEventListener('ready', function(e) {
327
+    console.log("---- local storage:");
328
+    console.log("user " + JSON.parse(localStorage.getItem('clay-settings')).username);
329
+    console.log('PebbleKit JS is ready');
330
+    // Update Watch on this
331
+    Pebble.sendAppMessage({ 'JSReady': 1 });
331 332
 });
332 333
 
333 334
 // Get AppMessage events
334
-Pebble.addEventListener('appmessage', function (e) {
335
-  // Get the dictionary from the message
336
-  var dict = e.payload;
337
-  console.log(dict[0].toString());
338
-  switch (dict[0]) {
339
-    case 'auth':
340
-      authenticate();
341
-      break;
342
-    case 'get':
343
-      get_status();
344
-      break;
345
-    case 'home_on':
346
-      switch_home(true);
347
-      break;
348
-    case 'home_off':
349
-      switch_home(false);
350
-      break;
351
-    default:
352
-      console.log('Sorry. I don\'t understand your request :' + dict[0]);
353
-  }
335
+Pebble.addEventListener('appmessage', function(e) {
336
+    // Get the dictionary from the message
337
+    var dict = e.payload;
338
+    console.log(dict[0].toString());
339
+    switch (dict[0]) {
340
+        case 'auth':
341
+            authenticate();
342
+            break;
343
+        case 'get':
344
+            get_status();
345
+            break;
346
+        case 'home_on':
347
+            switch_home(true);
348
+            break;
349
+        case 'home_off':
350
+            switch_home(false);
351
+            break;
352
+        default:
353
+            console.log('Sorry. I don\'t understand your request :' + dict[0]);
354
+    }
354 355
 
355 356
 });
356 357
\ No newline at end of file
Browse code

status now get at startup

louis.jonget authored on22/03/2023 15:58:29
Showing1 changed files
... ...
@@ -182,6 +182,7 @@ function authenticate() {
182 182
           }, function () {
183 183
             console.log('failed');
184 184
           });
185
+          get_status();
185 186
         } else {
186 187
           console.log('------Unexpected error : authentication is OK but no SID retrieved');
187 188
           message = "Auth error, no SID";
... ...
@@ -239,13 +240,13 @@ function get_status() {
239 240
         var message;
240 241
         switch (status) {
241 242
           case true:
242
-            message = "Your Home mode is ON";
243
+            message = "Home mode is ON (camera is off)";
243 244
             break;
244 245
           case false:
245
-            message = "Your Home mode is OFF";
246
+            message = "Home mode is OFF (camera is on)";
246 247
             break;
247 248
           default:
248
-            message = "home mode is unknown !";
249
+            message = "something happened, try again ! (IMPOSSIBLE)";
249 250
         }
250 251
       }else{
251 252
         message = "something happened, try again ! (G200)";
Browse code

V1.2: more error handling, forcing home mode, 10 retries everywhere

louis.jonget authored on20/03/2023 13:25:29
Showing1 changed files
... ...
@@ -85,6 +85,18 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
85 85
           return true;
86 86
         } else {
87 87
           console.log('------xhr request returned error code ' + xhr.status);
88
+          message = "Error (XHR"+xhr.status+")";
89
+          // Build message
90
+          var dict = {
91
+            'status': message,
92
+          };
93
+
94
+          // Send the message
95
+          Pebble.sendAppMessage(dict, function (e) {
96
+            console.log('sent');
97
+          }, function () {
98
+            console.log('failed');
99
+          });
88 100
           return false;
89 101
         }
90 102
       }
... ...
@@ -94,11 +106,25 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
94 106
       retry++;
95 107
       if (retry < max_retry) {
96 108
         console.log('------xhr timed out retrying another time ');
109
+        //send back "timeout" to watch
110
+        message = "Time out, retrying...";
111
+
112
+        // Build message
113
+        var dict = {
114
+          'status': message,
115
+        };
116
+
117
+        // Send the message
118
+        Pebble.sendAppMessage(dict, function (e) {
119
+          console.log('sent');
120
+        }, function () {
121
+          console.log('failed');
122
+        });
97 123
         xhr_to_syno(method, url_path, onload_function, max_retry);
98 124
       } else {
99
-        console.log('------xhr timed out ' + retry + ' time');
125
+        console.log('------xhr timed out ' + retry + ' times');
100 126
         //send back "timeout" to watch
101
-        message = "Call to server timed out, verify settings and connectivity";
127
+        message = "Time out too many times, verify settings and connectivity";
102 128
 
103 129
         // Build message
104 130
         var dict = {
... ...
@@ -158,12 +184,34 @@ function authenticate() {
158 184
           });
159 185
         } else {
160 186
           console.log('------Unexpected error : authentication is OK but no SID retrieved');
187
+          message = "Auth error, no SID";
188
+          // Build message
189
+          var dict = {
190
+            'auth': message,
191
+          };
192
+          // Send the message
193
+          Pebble.sendAppMessage(dict, function (e) {
194
+            console.log('sent');
195
+          }, function () {
196
+            console.log('failed');
197
+          });
161 198
         }
162 199
       } else {
163 200
         console.log('------Authentication failed : ' + JSON.stringify(response));
201
+        message = "Authentication failed";
202
+        // Build message
203
+        var dict = {
204
+          'auth': message,
205
+        };
206
+        // Send the message
207
+        Pebble.sendAppMessage(dict, function (e) {
208
+          console.log('sent');
209
+        }, function () {
210
+          console.log('failed');
211
+        });
164 212
       }
165 213
     };
166
-    max_retry = 1;
214
+    max_retry = 10;
167 215
     xhr_to_syno(method, url_path, onload_function, max_retry);
168 216
   } else {
169 217
     console.log("--- failed to get settings");
... ...
@@ -199,18 +247,20 @@ function get_status() {
199 247
           default:
200 248
             message = "home mode is unknown !";
201 249
         }
202
-        // Build message
203
-        var dict = {
204
-          'status': message,
205
-        };
206
-
207
-        // Send the message
208
-        Pebble.sendAppMessage(dict, function (e) {
209
-          console.log('sent');
210
-        }, function () {
211
-          console.log('failed');
212
-        });
250
+      }else{
251
+        message = "something happened, try again ! (G200)";
213 252
       }
253
+      // Build message
254
+      var dict = {
255
+        'status': message,
256
+      };
257
+
258
+      // Send the message
259
+      Pebble.sendAppMessage(dict, function (e) {
260
+        console.log('sent');
261
+      }, function () {
262
+        console.log('failed');
263
+      });
214 264
     }
215 265
 
216 266
     max_retry = 10;
... ...
@@ -228,82 +278,40 @@ function switch_home(bool) {
228 278
   var response;
229 279
   console.log('---- authenticate');
230 280
   if (sid != "") {
231
-    status = "";
232
-    console.log('---- get_status');
233
-    url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid=" + sid;
234
-    var method = "GET";
235
-
236
-    onload_status_function = function (xhr) {
281
+    console.log('---- switching home mode to ' + bool);
282
+    url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on=" + bool + "&_sid=" + sid;
283
+    method = "GET"
284
+    onload_switch_function = function (xhr) {
237 285
       response = JSON.parse(xhr.responseText);
238 286
       if (response.success == true) {
239
-        status = response.data.on;
240
-        console.log('------ status:' + status);
241
-        var message;
242
-        var dict;
243
-        if (status != bool) {
244
-          console.log('---- switching home mode to ' + bool);
245
-          url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on=" + bool + "&_sid=" + sid;
246
-          method = "GET"
247
-          onload_switch_function = function (xhr) {
248
-            response = JSON.parse(xhr.responseText);
249
-            if (response.success == true) {
250
-              status = bool;
251
-              switch (status) {
252
-                case true:
253
-                  message = "You just set Home mode ON";
254
-                  break;
255
-                case false:
256
-                  message = "You just set Home mode OFF";
257
-                  break;
258
-                default:
259
-                  message = "something happened, try again !";
260
-              }
261
-              // Build message
262
-              dict = {
263
-                'status': message,
264
-              };
265
-
266
-              // Send the message
267
-              Pebble.sendAppMessage(dict, function (e) {
268
-                console.log('sent');
269
-              }, function () {
270
-                console.log('failed');
271
-              });
272
-            }
273
-          }
274
-          max_retry = 10;
275
-          xhr_to_syno(method, url_path, onload_switch_function, max_retry);
276
-
277
-        } else {
278
-          console.log('---- nothing to do, status already ' + status);
279
-          switch (status) {
280
-            case true:
281
-              message = "Your Home Mode is already ON";
282
-              break;
283
-            case false:
284
-              message = "Your Home Mode is already OFF";
285
-              break;
286
-            default:
287
-              message = "something happened, try again !";
288
-          }
289
-          // Build message
290
-          dict = {
291
-            'status': message,
292
-          };
293
-
294
-          // Send the message
295
-          Pebble.sendAppMessage(dict, function (e) {
296
-            console.log('sent');
297
-          }, function () {
298
-            console.log('failed');
299
-          });
300
-
287
+        switch (bool) {
288
+          case true:
289
+            message = "Home mode is ON (camera is off)";
290
+            break;
291
+          case false:
292
+            message = "Home mode is OFF (camera is on)";
293
+            break;
294
+          default:
295
+            message = "something happened, try again ! (IMPOSSIBLE)";
301 296
         }
297
+      }else{
298
+        message = "something happened, try again ! (S200)";
302 299
       }
300
+      // Build message
301
+      dict = {
302
+        'status': message,
303
+      };
304
+
305
+      // Send the message
306
+      Pebble.sendAppMessage(dict, function (e) {
307
+        console.log('sent');
308
+      }, function () {
309
+        console.log('failed');
310
+      });
303 311
     }
304
-
305 312
     max_retry = 10;
306
-    xhr_to_syno(method, url_path, onload_status_function, max_retry);
313
+    xhr_to_syno(method, url_path, onload_switch_function, max_retry);
314
+
307 315
 
308 316
   } else {
309 317
     authenticate();
Browse code

fixed untracked files

louis.jonget authored on24/01/2023 10:30:34
Showing1 changed files
1 1
old mode 100755
2 2
new mode 100644
Browse code

timeout to 6 sec

louis.jonget authored on24/01/2023 10:24:34
Showing1 changed files
... ...
@@ -71,7 +71,7 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
71 71
     var server = JSON.parse(localStorage.getItem('clay-settings')).server
72 72
     url = server + url_path;
73 73
     var xhr = new XMLHttpRequest();
74
-    xhr.timeout = 4000; // time in milliseconds
74
+    xhr.timeout = 6000; // time in milliseconds
75 75
 
76 76
     xhr.open(method, url, true);
77 77
     console.log('------xhr opened')
Browse code

Merge branch 'retry_at_js_level' of ssh://jonget.fr:5522/volume1/web/gitlist.1.0.2/repos/synocam_home_switch/ into retry_at_js_level

louis.jonget authored on24/01/2023 10:19:56
Showing0 changed files
Browse code

2FA implementation

louis.jonget authored on18/01/2023 15:51:51
Showing1 changed files
... ...
@@ -1,6 +1,7 @@
1 1
 var Clay = require('pebble-clay');
2 2
 var clayConfig = require('./config');
3 3
 var clay = new Clay(clayConfig);
4
+const jsSHA = require('./sha');
4 5
 
5 6
 var messageKeys = require('message_keys');
6 7
 
... ...
@@ -9,6 +10,60 @@ var status;
9 10
 var retry;
10 11
 retry = 1;
11 12
 
13
+
14
+function dec2hex(s) {
15
+  return (s < 15.5 ? '0' : '') + Math.round(s).toString(16);
16
+}
17
+
18
+function hex2dec(s) {
19
+  return parseInt(s, 16);
20
+}
21
+
22
+function base32tohex(base32) {
23
+  var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
24
+  var bits = "";
25
+  var hex = "";
26
+
27
+  for (var i = 0; i < base32.length; i++) {
28
+    var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
29
+    bits += leftpad(val.toString(2), 5, '0');
30
+  }
31
+  //console.log('-- bits : ' + bits)
32
+
33
+  for (var i = 0; i + 4 <= bits.length; i += 4) {
34
+    var chunk = bits.substr(i, 4);
35
+    hex = hex + parseInt(chunk, 2).toString(16);
36
+  }
37
+  return hex;
38
+
39
+}
40
+
41
+function leftpad(str, len, pad) {
42
+  if (len + 1 >= str.length) {
43
+    str = Array(len + 1 - str.length).join(pad) + str;
44
+  }
45
+  return str;
46
+}
47
+
48
+function getOtp() {
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)
52
+  var epoch = Math.round(new Date().getTime() / 1000.0);
53
+  var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0');
54
+  // updated for jsSHA v2.0.0 - http://caligatio.github.io/jsSHA/
55
+  var shaObj = new jsSHA("SHA-1", "HEX");
56
+  shaObj.setHMACKey(key, "HEX");
57
+  shaObj.update(time);
58
+  var hmac = shaObj.getHMAC("HEX");
59
+  //console.log('-- hmac:' + hmac)
60
+  var offset = hex2dec(hmac.substring(hmac.length - 1));
61
+  //console.log('--offset:' + offset)
62
+  var otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec('7fffffff')) + '';
63
+  otp = (otp).substr(otp.length - 6, 6);
64
+  return otp
65
+}
66
+
12 67
 function xhr_to_syno(method, url_path, onload_function, max_retry) {
13 68
   console.log('------xhr start')
14 69
   status = "";
... ...
@@ -76,8 +131,13 @@ function authenticate() {
76 131
     var username = JSON.parse(localStorage.getItem('clay-settings')).username;
77 132
     var password = JSON.parse(localStorage.getItem('clay-settings')).password;
78 133
     console.log('-- username:' + username);
79
-    console.log('-- password:' + password);
80
-    var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
134
+    console.log('-- password:' + password.substring(0, 1) + '...');
135
+    var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=6&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
136
+    if (JSON.parse(localStorage.getItem('clay-settings')).OTP_enabled) {
137
+      var otp_code = getOtp()
138
+      console.log('-- otp_code is :' + otp_code)
139
+      url_path = url_path + "&otp_code=" + otp_code
140
+    }
81 141
     var method = "GET";
82 142
     onload_function = function (xhr) {
83 143
       response = JSON.parse(xhr.responseText);
... ...
@@ -100,7 +160,7 @@ function authenticate() {
100 160
           console.log('------Unexpected error : authentication is OK but no SID retrieved');
101 161
         }
102 162
       } else {
103
-        console.log('------Authentication failed : ' + response.toString());
163
+        console.log('------Authentication failed : ' + JSON.stringify(response));
104 164
       }
105 165
     };
106 166
     max_retry = 1;
Browse code

all calls to xhr function with retry feature

Louis authored on12/12/2022 20:09:06
Showing1 changed files
... ...
@@ -10,328 +10,275 @@ var retry;
10 10
 retry = 1;
11 11
 
12 12
 function xhr_to_syno(method, url_path, onload_function, max_retry) {
13
-  console.log('------xhr start')
14
-  status = "";
15
-  if (JSON.parse(localStorage.getItem('clay-settings')).server) {
16
-    var server = JSON.parse(localStorage.getItem('clay-settings')).server
17
-    url = server + url_path;
18
-    var xhr = new XMLHttpRequest();
19
-    xhr.timeout = 4000; // time in milliseconds
20
-
21
-    xhr.open(method, url, true);
22
-    console.log('------xhr opened')
23
-    xhr.onload = function () {
24
-      console.log('------xhr onload')
25
-      if (xhr.readyState === 4) {
26
-        retry = 1;
27
-        console.log('------xhr request returned');
28
-        if (xhr.status == 200) {
29
-          onload_function(xhr);
30
-          return true;
31
-        } else {
32
-          console.log('------xhr request returned error code ' + xhr.status);
33
-          return false;
34
-        }
35
-      }
36
-    };
37
-
38
-    xhr.ontimeout = function (e) {
39
-      retry++;
40
-      if (retry < max_retry) {
41
-        console.log('------xhr timed out retrying another time ');
42
-        xhr_to_syno(method, url_path, onload_function, max_retry);
43
-      } else {
44
-        console.log('------xhr timed out ' + retry + ' time');
45
-        //send back "timeout" to watch
46
-        message = "Call to server timed out, verify settings and connectivity";
47
-
48
-        // Build message
49
-        var dict = {
50
-          'status': message,
13
+    console.log('------xhr start')
14
+    status = "";
15
+    if (JSON.parse(localStorage.getItem('clay-settings')).server) {
16
+        var server = JSON.parse(localStorage.getItem('clay-settings')).server
17
+        url = server + url_path;
18
+        var xhr = new XMLHttpRequest();
19
+        xhr.timeout = 4000; // time in milliseconds
20
+
21
+        xhr.open(method, url, true);
22
+        console.log('------xhr opened on ' + url + ' # retry=' + retry)
23
+        xhr.onload = function() {
24
+            console.log('------xhr onload')
25
+            if (xhr.readyState === 4) {
26
+                retry = 1;
27
+                console.log('------xhr request returned');
28
+                if (xhr.status == 200) {
29
+                    onload_function(xhr);
30
+                    return true;
31
+                } else {
32
+                    console.log('------xhr request returned error code ' + xhr.status);
33
+                    return false;
34
+                }
35
+            }
51 36
         };
52 37
 
53
-        // Send the message
54
-        Pebble.sendAppMessage(dict, function (e) {
55
-          console.log('sent');
56
-        }, function () {
57
-          console.log('failed');
58
-        });
59
-        return false;
60
-      }
61
-    };
62
-    xhr.send(null);
63
-
64
-  } else {
65
-    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
66
-  }
67
-
68
-}
38
+        xhr.ontimeout = function(e) {
39
+            retry++;
40
+            if (retry < max_retry) {
41
+                console.log('------xhr timed out retrying another time ');
42
+                xhr_to_syno(method, url_path, onload_function, max_retry);
43
+            } else {
44
+                console.log('------xhr timed out ' + retry + ' time');
45
+                //send back "timeout" to watch
46
+                message = "Call to server timed out, verify settings and connectivity";
69 47
 
48
+                // Build message
49
+                var dict = {
50
+                    'status': message,
51
+                };
70 52
 
71
-function authenticate() {
72
-  var response;
73
-  sid = "";
74
-  console.log('---- authenticate');
75
-  if (JSON.parse(localStorage.getItem('clay-settings')).username && JSON.parse(localStorage.getItem('clay-settings')).password) {
76
-    var username = JSON.parse(localStorage.getItem('clay-settings')).username;
77
-    var password = JSON.parse(localStorage.getItem('clay-settings')).password;
78
-    console.log('-- username:' + username);
79
-    console.log('-- password:' + password);
80
-    var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
81
-    var method = "GET";
82
-    onload_function = function (xhr) {
83
-      response = JSON.parse(xhr.responseText);
84
-      if (response.success == true) {
85
-        sid = response.data.sid;
86
-        console.log('------Authentication succeeded');
87
-        if (sid != "") {
88
-          message = "Welcome to Syno Cam Switch ! ready & authenticated";
89
-          // Build message
90
-          var dict = {
91
-            'auth': message,
92
-          };
93
-          // Send the message
94
-          Pebble.sendAppMessage(dict, function (e) {
95
-            console.log('sent');
96
-          }, function () {
97
-            console.log('failed');
98
-          });
99
-        } else {
100
-          console.log('------Unexpected error : authentication is OK but no SID retrieved');
101
-        }
102
-      } else {
103
-        console.log('------Authentication failed : ' + response.toString());
104
-      }
105
-    };
106
-    max_retry = 1;
107
-    xhr_to_syno(method, url_path, onload_function, max_retry);
108
-  } else {
109
-    console.log("--- failed to get settings");
110
-    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
111
-  }
53
+                // Send the message
54
+                Pebble.sendAppMessage(dict, function(e) {
55
+                    console.log('sent');
56
+                }, function() {
57
+                    console.log('failed');
58
+                });
59
+                return false;
60
+            }
61
+        };
62
+        xhr.send(null);
112 63
 
64
+    } else {
65
+        Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
66
+    }
113 67
 
114 68
 }
115 69
 
116 70
 
117
-function get_status() {
118
-  var response;
119
-
120
-  if (sid != ""){
121
-    status = "";
122
-    console.log('---- get_status');
123
-
124
-    var url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid=" + sid;
125
-    var method = "GET";
126
-
127
-    onload_function = function (xhr) { }
128
-
129
-    max_retry = 1;
130
-    xhr_to_syno(method, url_path, onload_function, max_retry);
131
-
132
-    var xhr = new XMLHttpRequest();
133
-    xhr.timeout = 3000; // time in milliseconds
134
-
135
-    xhr.open("GET", url, true);
136
-
137
-    xhr.onload = function () {
138
-      if (xhr.readyState === 4) {
139
-        retry = 0;
140
-        console.log('------Get-status request returned');
141
-        if (xhr.status == 200) {
142
-          response = JSON.parse(xhr.responseText);
143
-          if (response.success == true) {
144
-            status = response.data.on;
145
-            var message;
146
-            switch (status) {
147
-              case true:
148
-                message = "Your Home mode is ON";
149
-                break;
150
-              case false:
151
-                message = "Your Home mode is OFF";
152
-                break;
153
-              default:
154
-                message = "home mode is unknown !";
71
+function authenticate() {
72
+    var response;
73
+    sid = "";
74
+    console.log('---- authenticate');
75
+    if (JSON.parse(localStorage.getItem('clay-settings')).username && JSON.parse(localStorage.getItem('clay-settings')).password) {
76
+        var username = JSON.parse(localStorage.getItem('clay-settings')).username;
77
+        var password = JSON.parse(localStorage.getItem('clay-settings')).password;
78
+        console.log('-- username:' + username);
79
+        console.log('-- password:' + password);
80
+        var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
81
+        var method = "GET";
82
+        onload_function = function(xhr) {
83
+            response = JSON.parse(xhr.responseText);
84
+            if (response.success == true) {
85
+                sid = response.data.sid;
86
+                console.log('------Authentication succeeded');
87
+                if (sid != "") {
88
+                    message = "Welcome to Syno Cam Switch ! ready & authenticated";
89
+                    // Build message
90
+                    var dict = {
91
+                        'auth': message,
92
+                    };
93
+                    // Send the message
94
+                    Pebble.sendAppMessage(dict, function(e) {
95
+                        console.log('sent');
96
+                    }, function() {
97
+                        console.log('failed');
98
+                    });
99
+                } else {
100
+                    console.log('------Unexpected error : authentication is OK but no SID retrieved');
101
+                }
102
+            } else {
103
+                console.log('------Authentication failed : ' + response.toString());
155 104
             }
156
-            // Build message
157
-            var dict = {
158
-              'status': message,
159
-            };
160
-
161
-            // Send the message
162
-            Pebble.sendAppMessage(dict, function (e) {
163
-              console.log('sent');
164
-            }, function () {
165
-              console.log('failed');
166
-            });
167
-          }
168
-        } else {
169
-          console.log('------Request returned error code ' + xhr.status);
170
-        }
171
-      }
172
-    }
173
-
174
-    xhr.ontimeout = function (e) {
175
-      retry++;
176
-      if (retry <= 1) {
177
-        console.log('------Get-Status timed out retrying another time ');
178
-        get_status();
179
-      } else {
180
-        console.log('------Get-Status timed out a second time');
181
-        //send back "timeout" to watch
182
-        message = "Get-Status timed out, verify settings and connectivity";
183
-
184
-        // Build message
185
-        var dict = {
186
-          'status': message,
187 105
         };
188
-
189
-        // Send the message
190
-        Pebble.sendAppMessage(dict, function (e) {
191
-          console.log('sent');
192
-        }, function () {
193
-          console.log('failed');
194
-        });
195
-      }
106
+        max_retry = 10;
107
+        xhr_to_syno(method, url_path, onload_function, max_retry);
108
+    } else {
109
+        console.log("--- failed to get settings");
110
+        Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
196 111
     }
197
-
198
-    xhr.send();
199
-
112
+}
200 113
 
201 114
 
202
-  } else {
203
-    authenticate();
204
-    get_status();
205
-  }
115
+function get_status() {
116
+    var response;
206 117
 
207
-}
118
+    if (sid != "") {
119
+        status = "";
120
+        console.log('---- get_status');
208 121
 
122
+        var url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid=" + sid;
123
+        var method = "GET";
209 124
 
210
-function switch_home(bool) {
211
-  var response;
212
-  console.log('---- authenticate');
213
-  if (sid != ""){
214
-    status = "";
215
-    console.log('---- get_status');
216
-    if (JSON.parse(localStorage.getItem('clay-settings')).server) {
217
-      var server = JSON.parse(localStorage.getItem('clay-settings')).server;
218
-      var xhr = new XMLHttpRequest();
219
-
220
-      url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
221
-
222
-      xhr.open("GET", url,false);
223
-      xhr.send();
224
-
225
-      if(xhr.status == 200) {
226
-        response = JSON.parse(xhr.responseText);
227
-        if (response.success == true){
228
-          status = response.data.on;
229
-          console.log('------ status:'+status);
230
-          var message;
231
-          var dict;
232
-          if ( status != bool){
233
-            console.log('---- switching home mode to '+ bool);
234
-            url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on="+bool+"&_sid="+sid;
235
-
236
-            xhr.open("GET", url,false);
237
-            xhr.send();
238
-
239
-            if(xhr.status == 200) {
240
-              response = JSON.parse(xhr.responseText);
241
-              if (response.success == true){
242
-                status=bool;
125
+        onload_function = function(xhr) {
126
+            response = JSON.parse(xhr.responseText);
127
+            if (response.success == true) {
128
+                status = response.data.on;
129
+                var message;
243 130
                 switch (status) {
244
-                  case true:
245
-                    message = "You just set Home mode ON";
246
-                    break;
247
-                  case false:
248
-                    message = "You just set Home mode OFF";
249
-                    break;
250
-                  default:
251
-                    message = "something happened, try again !";
131
+                    case true:
132
+                        message = "Your Home mode is ON";
133
+                        break;
134
+                    case false:
135
+                        message = "Your Home mode is OFF";
136
+                        break;
137
+                    default:
138
+                        message = "home mode is unknown !";
252 139
                 }
253 140
                 // Build message
254
-                dict = {
255
-                  'status': message,
141
+                var dict = {
142
+                    'status': message,
256 143
                 };
257 144
 
258 145
                 // Send the message
259 146
                 Pebble.sendAppMessage(dict, function(e) {
260
-                  console.log('sent');
147
+                    console.log('sent');
261 148
                 }, function() {
262
-                  console.log('failed');
149
+                    console.log('failed');
263 150
                 });
264
-              }
265
-            }else {
266
-              console.log('------Request returned error code ' + xhr.status.toString());
267 151
             }
268
-          }else{
269
-            console.log('---- nothing to do, status already '+status);
270
-            switch (status) {
271
-              case true:
272
-                message = "Your Home Mode is already ON";
273
-                break;
274
-              case false:
275
-                message = "Your Home Mode is already OFF";
276
-                break;
277
-              default:
278
-                message = "something happened, try again !";
152
+        }
153
+
154
+        max_retry = 10;
155
+        xhr_to_syno(method, url_path, onload_function, max_retry);
156
+
157
+    } else {
158
+        authenticate();
159
+        get_status();
160
+    }
161
+
162
+}
163
+
164
+
165
+function switch_home(bool) {
166
+    var response;
167
+    console.log('---- authenticate');
168
+    if (sid != "") {
169
+        status = "";
170
+        console.log('---- get_status');
171
+        url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid=" + sid;
172
+        var method = "GET";
173
+
174
+        onload_status_function = function(xhr) {
175
+            response = JSON.parse(xhr.responseText);
176
+            if (response.success == true) {
177
+                status = response.data.on;
178
+                console.log('------ status:' + status);
179
+                var message;
180
+                var dict;
181
+                if (status != bool) {
182
+                    console.log('---- switching home mode to ' + bool);
183
+                    url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on=" + bool + "&_sid=" + sid;
184
+                    method = "GET"
185
+                    onload_switch_function = function(xhr) {
186
+                        response = JSON.parse(xhr.responseText);
187
+                        if (response.success == true) {
188
+                            status = bool;
189
+                            switch (status) {
190
+                                case true:
191
+                                    message = "You just set Home mode ON";
192
+                                    break;
193
+                                case false:
194
+                                    message = "You just set Home mode OFF";
195
+                                    break;
196
+                                default:
197
+                                    message = "something happened, try again !";
198
+                            }
199
+                            // Build message
200
+                            dict = {
201
+                                'status': message,
202
+                            };
203
+
204
+                            // Send the message
205
+                            Pebble.sendAppMessage(dict, function(e) {
206
+                                console.log('sent');
207
+                            }, function() {
208
+                                console.log('failed');
209
+                            });
210
+                        }
211
+                    }
212
+                    max_retry = 10;
213
+                    xhr_to_syno(method, url_path, onload_switch_function, max_retry);
214
+
215
+                } else {
216
+                    console.log('---- nothing to do, status already ' + status);
217
+                    switch (status) {
218
+                        case true:
219
+                            message = "Your Home Mode is already ON";
220
+                            break;
221
+                        case false:
222
+                            message = "Your Home Mode is already OFF";
223
+                            break;
224
+                        default:
225
+                            message = "something happened, try again !";
226
+                    }
227
+                    // Build message
228
+                    dict = {
229
+                        'status': message,
230
+                    };
231
+
232
+                    // Send the message
233
+                    Pebble.sendAppMessage(dict, function(e) {
234
+                        console.log('sent');
235
+                    }, function() {
236
+                        console.log('failed');
237
+                    });
238
+
239
+                }
279 240
             }
280
-            // Build message
281
-            dict = {
282
-              'status': message,
283
-            };
284
-
285
-            // Send the message
286
-            Pebble.sendAppMessage(dict, function(e) {
287
-              console.log('sent');
288
-            }, function() {
289
-              console.log('failed');
290
-            });
291
-          }
292 241
         }
293
-      }else {
294
-        console.log('------Request returned error code ' + xhr.status.toString());
295
-      }
296
-    }else{
297
-      Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
242
+
243
+        max_retry = 10;
244
+        xhr_to_syno(method, url_path, onload_status_function, max_retry);
245
+
246
+    } else {
247
+        authenticate();
248
+        switch_home(bool);
298 249
     }
299
-  } else {
300
-    authenticate();
301
-    switch_home(bool);
302
-  }
303 250
 
304 251
 }
305 252
 
306 253
 // Get JS readiness events
307
-Pebble.addEventListener('ready',function(e){
308
-  console.log("---- local storage:");
309
-  console.log("user " + JSON.parse(localStorage.getItem('clay-settings')).username);
310
-  console.log('PebbleKit JS is ready');
311
-  // Update Watch on this
312
-  Pebble.sendAppMessage({'JSReady':1});
254
+Pebble.addEventListener('ready', function(e) {
255
+    console.log("---- local storage:");
256
+    console.log("user " + JSON.parse(localStorage.getItem('clay-settings')).username);
257
+    console.log('PebbleKit JS is ready');
258
+    // Update Watch on this
259
+    Pebble.sendAppMessage({ 'JSReady': 1 });
313 260
 });
314 261
 
315 262
 // Get AppMessage events
316 263
 Pebble.addEventListener('appmessage', function(e) {
317
-  // Get the dictionary from the message
318
-  var dict = e.payload;
319
-  console.log(dict[0].toString());
320
-  switch (dict[0]) {
321
-    case 'auth':
322
-      authenticate();
323
-      break;
324
-    case 'get':
325
-      get_status();
326
-      break;
327
-    case 'home_on':
328
-      switch_home(true);
329
-      break;
330
-    case 'home_off':
331
-      switch_home(false);
332
-      break;
333
-    default:
334
-      console.log('Sorry. I don\'t understand your request :'+ dict[0]);
335
-  }
264
+    // Get the dictionary from the message
265
+    var dict = e.payload;
266
+    console.log(dict[0].toString());
267
+    switch (dict[0]) {
268
+        case 'auth':
269
+            authenticate();
270
+            break;
271
+        case 'get':
272
+            get_status();
273
+            break;
274
+        case 'home_on':
275
+            switch_home(true);
276
+            break;
277
+        case 'home_off':
278
+            switch_home(false);
279
+            break;
280
+        default:
281
+            console.log('Sorry. I don\'t understand your request :' + dict[0]);
282
+    }
336 283
 
337
-});
284
+});
338 285
\ No newline at end of file
Browse code

clay config is now working, need more refactor on retry and xhr

louis.jonget authored on30/09/2022 12:19:50
Showing1 changed files
... ...
@@ -12,13 +12,11 @@ retry = 1;
12 12
 function xhr_to_syno(method, url_path, onload_function, max_retry) {
13 13
   console.log('------xhr start')
14 14
   status = "";
15
-  if (localStorage.getItem('username') && localStorage.getItem('password') && localStorage.getItem('server')) {
16
-    var username = localStorage.getItem('username');
17
-    var password = localStorage.getItem('password');
18
-    var server = localStorage.getItem('server');
15
+  if (JSON.parse(localStorage.getItem('clay-settings')).server) {
16
+    var server = JSON.parse(localStorage.getItem('clay-settings')).server
19 17
     url = server + url_path;
20 18
     var xhr = new XMLHttpRequest();
21
-    xhr.timeout = 3000; // time in milliseconds
19
+    xhr.timeout = 4000; // time in milliseconds
22 20
 
23 21
     xhr.open(method, url, true);
24 22
     console.log('------xhr opened')
... ...
@@ -74,9 +72,11 @@ function authenticate() {
74 72
   var response;
75 73
   sid = "";
76 74
   console.log('---- authenticate');
77
-  if (localStorage.getItem('username') && localStorage.getItem('password') && localStorage.getItem('server')) {
78
-    var username = localStorage.getItem('username');
79
-    var password = localStorage.getItem('password');
75
+  if (JSON.parse(localStorage.getItem('clay-settings')).username && JSON.parse(localStorage.getItem('clay-settings')).password) {
76
+    var username = JSON.parse(localStorage.getItem('clay-settings')).username;
77
+    var password = JSON.parse(localStorage.getItem('clay-settings')).password;
78
+    console.log('-- username:' + username);
79
+    console.log('-- password:' + password);
80 80
     var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
81 81
     var method = "GET";
82 82
     onload_function = function (xhr) {
... ...
@@ -106,6 +106,7 @@ function authenticate() {
106 106
     max_retry = 1;
107 107
     xhr_to_syno(method, url_path, onload_function, max_retry);
108 108
   } else {
109
+    console.log("--- failed to get settings");
109 110
     Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
110 111
   }
111 112
 
... ...
@@ -119,83 +120,88 @@ function get_status() {
119 120
   if (sid != ""){
120 121
     status = "";
121 122
     console.log('---- get_status');
122
-    if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
123
-      var username=localStorage.getItem('username');
124
-      var password=localStorage.getItem('password');
125
-      var server=localStorage.getItem('server');
126
-      url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
127
-      var xhr = new XMLHttpRequest();
128
-      xhr.timeout = 3000; // time in milliseconds
129
-
130
-      xhr.open("GET", url,true);
131
-
132
-      xhr.onload = function () {
133
-        if (xhr.readyState === 4) {
134
-          retry=0;
135
-          console.log('------Get-status request returned');
136
-          if(xhr.status == 200) {
137
-            response = JSON.parse(xhr.responseText);
138
-            if (response.success == true){
139
-              status = response.data.on;
140
-              var message;
141
-              switch (status) {
142
-                case true:
143
-                  message = "Your Home mode is ON";
144
-                  break;
145
-                case false:
146
-                  message = "Your Home mode is OFF";
147
-                  break;
148
-                default:
149
-                  message = "home mode is unknown !";
150
-              }
151
-              // Build message
152
-              var dict = {
153
-                'status': message,
154
-              };
155
-
156
-              // Send the message
157
-              Pebble.sendAppMessage(dict, function(e) {
158
-                console.log('sent');
159
-              }, function() {
160
-                console.log('failed');
161
-              });
123
+
124
+    var url_path = "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid=" + sid;
125
+    var method = "GET";
126
+
127
+    onload_function = function (xhr) { }
128
+
129
+    max_retry = 1;
130
+    xhr_to_syno(method, url_path, onload_function, max_retry);
131
+
132
+    var xhr = new XMLHttpRequest();
133
+    xhr.timeout = 3000; // time in milliseconds
134
+
135
+    xhr.open("GET", url, true);
136
+
137
+    xhr.onload = function () {
138
+      if (xhr.readyState === 4) {
139
+        retry = 0;
140
+        console.log('------Get-status request returned');
141
+        if (xhr.status == 200) {
142
+          response = JSON.parse(xhr.responseText);
143
+          if (response.success == true) {
144
+            status = response.data.on;
145
+            var message;
146
+            switch (status) {
147
+              case true:
148
+                message = "Your Home mode is ON";
149
+                break;
150
+              case false:
151
+                message = "Your Home mode is OFF";
152
+                break;
153
+              default:
154
+                message = "home mode is unknown !";
162 155
             }
163
-          }else {
164
-            console.log('------Request returned error code ' + xhr.status);
156
+            // Build message
157
+            var dict = {
158
+              'status': message,
159
+            };
160
+
161
+            // Send the message
162
+            Pebble.sendAppMessage(dict, function (e) {
163
+              console.log('sent');
164
+            }, function () {
165
+              console.log('failed');
166
+            });
165 167
           }
168
+        } else {
169
+          console.log('------Request returned error code ' + xhr.status);
166 170
         }
167 171
       }
172
+    }
168 173
 
169
-      xhr.ontimeout = function (e){
170
-        retry++;
171
-        if (retry<=1){
172
-          console.log('------Get-Status timed out retrying another time ');
173
-          get_status();
174
-        }else{
175
-          console.log('------Get-Status timed out a second time');
176
-          //send back "timeout" to watch
177
-          message ="Get-Status timed out, verify settings and connectivity";
174
+    xhr.ontimeout = function (e) {
175
+      retry++;
176
+      if (retry <= 1) {
177
+        console.log('------Get-Status timed out retrying another time ');
178
+        get_status();
179
+      } else {
180
+        console.log('------Get-Status timed out a second time');
181
+        //send back "timeout" to watch
182
+        message = "Get-Status timed out, verify settings and connectivity";
178 183
 
179
-          // Build message
180
-          var dict = {
181
-            'status': message,
182
-          };
184
+        // Build message
185
+        var dict = {
186
+          'status': message,
187
+        };
183 188
 
184
-          // Send the message
185
-          Pebble.sendAppMessage(dict, function(e) {
186
-            console.log('sent');
187
-          }, function() {
188
-            console.log('failed');
189
-          });
190
-        }
189
+        // Send the message
190
+        Pebble.sendAppMessage(dict, function (e) {
191
+          console.log('sent');
192
+        }, function () {
193
+          console.log('failed');
194
+        });
191 195
       }
196
+    }
192 197
 
193
-      xhr.send();
198
+    xhr.send();
194 199
 
195 200
 
196
-    }else{
197
-      Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
198
-    }
201
+
202
+  } else {
203
+    authenticate();
204
+    get_status();
199 205
   }
200 206
 
201 207
 }
... ...
@@ -207,10 +213,8 @@ function switch_home(bool) {
207 213
   if (sid != ""){
208 214
     status = "";
209 215
     console.log('---- get_status');
210
-    if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
211
-      var username=localStorage.getItem('username');
212
-      var password=localStorage.getItem('password');
213
-      var server=localStorage.getItem('server');
216
+    if (JSON.parse(localStorage.getItem('clay-settings')).server) {
217
+      var server = JSON.parse(localStorage.getItem('clay-settings')).server;
214 218
       var xhr = new XMLHttpRequest();
215 219
 
216 220
       url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
... ...
@@ -292,12 +296,17 @@ function switch_home(bool) {
292 296
     }else{
293 297
       Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
294 298
     }
295
-   }
299
+  } else {
300
+    authenticate();
301
+    switch_home(bool);
302
+  }
296 303
 
297 304
 }
298 305
 
299 306
 // Get JS readiness events
300 307
 Pebble.addEventListener('ready',function(e){
308
+  console.log("---- local storage:");
309
+  console.log("user " + JSON.parse(localStorage.getItem('clay-settings')).username);
301 310
   console.log('PebbleKit JS is ready');
302 311
   // Update Watch on this
303 312
   Pebble.sendAppMessage({'JSReady':1});
Browse code

sending xhr

louis.jonget authored on27/06/2022 11:56:24
Showing1 changed files
... ...
@@ -35,7 +35,7 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
35 35
           return false;
36 36
         }
37 37
       }
38
-    }
38
+    };
39 39
 
40 40
     xhr.ontimeout = function (e) {
41 41
       retry++;
... ...
@@ -60,7 +60,8 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
60 60
         });
61 61
         return false;
62 62
       }
63
-    }
63
+    };
64
+    xhr.send(null);
64 65
 
65 66
   } else {
66 67
     Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
Browse code

add some debug

louis.jonget authored on27/06/2022 11:53:33
Showing1 changed files
... ...
@@ -10,6 +10,7 @@ var retry;
10 10
 retry = 1;
11 11
 
12 12
 function xhr_to_syno(method, url_path, onload_function, max_retry) {
13
+  console.log('------xhr start')
13 14
   status = "";
14 15
   if (localStorage.getItem('username') && localStorage.getItem('password') && localStorage.getItem('server')) {
15 16
     var username = localStorage.getItem('username');
... ...
@@ -20,8 +21,9 @@ function xhr_to_syno(method, url_path, onload_function, max_retry) {
20 21
     xhr.timeout = 3000; // time in milliseconds
21 22
 
22 23
     xhr.open(method, url, true);
23
-
24
+    console.log('------xhr opened')
24 25
     xhr.onload = function () {
26
+      console.log('------xhr onload')
25 27
       if (xhr.readyState === 4) {
26 28
         retry = 1;
27 29
         console.log('------xhr request returned');
Browse code

correct onload function

louis.jonget authored on24/06/2022 15:40:54
Showing1 changed files
... ...
@@ -81,33 +81,27 @@ function authenticate() {
81 81
       if (response.success == true) {
82 82
         sid = response.data.sid;
83 83
         console.log('------Authentication succeeded');
84
+        if (sid != "") {
85
+          message = "Welcome to Syno Cam Switch ! ready & authenticated";
86
+          // Build message
87
+          var dict = {
88
+            'auth': message,
89
+          };
90
+          // Send the message
91
+          Pebble.sendAppMessage(dict, function (e) {
92
+            console.log('sent');
93
+          }, function () {
94
+            console.log('failed');
95
+          });
96
+        } else {
97
+          console.log('------Unexpected error : authentication is OK but no SID retrieved');
98
+        }
84 99
       } else {
85 100
         console.log('------Authentication failed : ' + response.toString());
86 101
       }
87 102
     };
88 103
     max_retry = 1;
89
-    if (xhr_to_syno(method, url_path, onload_function, max_retry) == true) {
90
-      if (sid != "") {
91
-        auth = "";
92
-        message = "Welcome to Syno Cam Switch ! ready & authenticated";
93
-
94
-        // Build message
95
-        var dict = {
96
-          'auth': message,
97
-        };
98
-
99
-        // Send the message
100
-        Pebble.sendAppMessage(dict, function (e) {
101
-          console.log('sent');
102
-        }, function () {
103
-          console.log('failed');
104
-        });
105
-      } else {
106
-        console.log('------Unexpected error : authentication is OK but no SID retrieved');
107
-      }
108
-    } else {
109
-      console.log('------Unexpected error : authentication is OK but no SID retrieved');
110
-    }
104
+    xhr_to_syno(method, url_path, onload_function, max_retry);
111 105
   } else {
112 106
     Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
113 107
   }
Browse code

refactoring xhr for authentication

louis.jonget authored on24/06/2022 15:26:04
Showing1 changed files
... ...
@@ -7,96 +7,118 @@ var messageKeys = require('message_keys');
7 7
 var sid;
8 8
 var status;
9 9
 var retry;
10
-retry=0;
10
+retry = 1;
11 11
 
12
-function authenticate() {
13
-  var response;
14
-  sid="";
15
-  console.log('---- authenticate');
16
-  console.log('-- '+localStorage.getItem('username'));
17
-  //console.log('-- '+localStorage.getItem('password'));
18
-  console.log('-- '+localStorage.getItem('server'));
19
-  if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
20
-    var username=localStorage.getItem('username');
21
-    var password=localStorage.getItem('password');
22
-    var server=localStorage.getItem('server');
23
-    var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
12
+function xhr_to_syno(method, url_path, onload_function, max_retry) {
13
+  status = "";
14
+  if (localStorage.getItem('username') && localStorage.getItem('password') && localStorage.getItem('server')) {
15
+    var username = localStorage.getItem('username');
16
+    var password = localStorage.getItem('password');
17
+    var server = localStorage.getItem('server');
18
+    url = server + url_path;
24 19
     var xhr = new XMLHttpRequest();
25 20
     xhr.timeout = 3000; // time in milliseconds
26 21
 
27
-    xhr.open("GET", url,true);
28
-    
22
+    xhr.open(method, url, true);
23
+
29 24
     xhr.onload = function () {
30 25
       if (xhr.readyState === 4) {
31
-        retry=0;
32
-        console.log('------authentication request returned');
33
-        if(xhr.status == 200) {
34
-          response = JSON.parse(xhr.responseText);
35
-          if (response.success == true){
36
-            sid = response.data.sid;
37
-          }else{
38
-  	    console.log('------Authentication failed : '+ response.toString());
39
-          }
40
-        }else {
41
-          console.log('------Request returned error code ' + xhr.status);
42
-        }
43
-    
44
-        if (sid != ""){
45
-          auth = "";
46
-          message = "Welcome to Syno Cam Switch ! ready & authenticated";
47
-               
48
-          // Build message
49
-          var dict = {
50
-            'auth': message,
51
-          };
52
-        
53
-          // Send the message
54
-          Pebble.sendAppMessage(dict, function(e) {
55
-            console.log('sent');
56
-          }, function() {
57
-            console.log('failed');
58
-          });
59
-         
60
-        }else{
61
-          console.log('------Unexpected error : authentication is OK but no SID retrieved');
26
+        retry = 1;
27
+        console.log('------xhr request returned');
28
+        if (xhr.status == 200) {
29
+          onload_function(xhr);
30
+          return true;
31
+        } else {
32
+          console.log('------xhr request returned error code ' + xhr.status);
33
+          return false;
62 34
         }
63 35
       }
64
-    };
36
+    }
65 37
 
66
-    xhr.ontimeout = function (e){
38
+    xhr.ontimeout = function (e) {
67 39
       retry++;
68
-      if (retry<=1){
69
-        console.log('------Authentication timed out retrying another time ');
70
-        authenticate();
71
-      }else{
72
-        console.log('------Authentication timed out a second time');
40
+      if (retry < max_retry) {
41
+        console.log('------xhr timed out retrying another time ');
42
+        xhr_to_syno(method, url_path, onload_function, max_retry);
43
+      } else {
44
+        console.log('------xhr timed out ' + retry + ' time');
73 45
         //send back "timeout" to watch
74
-        auth="";
75
-        message ="Authentication timed out, verify settings and connectivity";
46
+        message = "Call to server timed out, verify settings and connectivity";
76 47
 
77 48
         // Build message
78 49
         var dict = {
79
-          'auth': message,
50
+          'status': message,
80 51
         };
81 52
 
82 53
         // Send the message
83
-        Pebble.sendAppMessage(dict, function(e) {
54
+        Pebble.sendAppMessage(dict, function (e) {
84 55
           console.log('sent');
85
-        }, function() {
56
+        }, function () {
86 57
           console.log('failed');
87 58
         });
59
+        return false;
60
+      }
61
+    }
62
+
63
+  } else {
64
+    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
65
+  }
66
+
67
+}
68
+
69
+
70
+function authenticate() {
71
+  var response;
72
+  sid = "";
73
+  console.log('---- authenticate');
74
+  if (localStorage.getItem('username') && localStorage.getItem('password') && localStorage.getItem('server')) {
75
+    var username = localStorage.getItem('username');
76
+    var password = localStorage.getItem('password');
77
+    var url_path = "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
78
+    var method = "GET";
79
+    onload_function = function (xhr) {
80
+      response = JSON.parse(xhr.responseText);
81
+      if (response.success == true) {
82
+        sid = response.data.sid;
83
+        console.log('------Authentication succeeded');
84
+      } else {
85
+        console.log('------Authentication failed : ' + response.toString());
88 86
       }
89 87
     };
90
-      
91
-    xhr.send();
92
-  }else{
88
+    max_retry = 1;
89
+    if (xhr_to_syno(method, url_path, onload_function, max_retry) == true) {
90
+      if (sid != "") {
91
+        auth = "";
92
+        message = "Welcome to Syno Cam Switch ! ready & authenticated";
93
+
94
+        // Build message
95
+        var dict = {
96
+          'auth': message,
97
+        };
98
+
99
+        // Send the message
100
+        Pebble.sendAppMessage(dict, function (e) {
101
+          console.log('sent');
102
+        }, function () {
103
+          console.log('failed');
104
+        });
105
+      } else {
106
+        console.log('------Unexpected error : authentication is OK but no SID retrieved');
107
+      }
108
+    } else {
109
+      console.log('------Unexpected error : authentication is OK but no SID retrieved');
110
+    }
111
+  } else {
93 112
     Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
94 113
   }
114
+
115
+
95 116
 }
96 117
 
118
+
97 119
 function get_status() {
98 120
   var response;
99
-  
121
+
100 122
   if (sid != ""){
101 123
     status = "";
102 124
     console.log('---- get_status');
... ...
@@ -117,7 +139,7 @@ function get_status() {
117 139
           if(xhr.status == 200) {
118 140
             response = JSON.parse(xhr.responseText);
119 141
             if (response.success == true){
120
-              status=response.data.on;   
142
+              status = response.data.on;
121 143
               var message;
122 144
               switch (status) {
123 145
                 case true:
... ...
@@ -128,12 +150,12 @@ function get_status() {
128 150
                   break;
129 151
                 default:
130 152
                   message = "home mode is unknown !";
131
-              }      
153
+              }
132 154
               // Build message
133 155
               var dict = {
134 156
                 'status': message,
135 157
               };
136
-            
158
+
137 159
               // Send the message
138 160
               Pebble.sendAppMessage(dict, function(e) {
139 161
                 console.log('sent');
... ...
@@ -156,12 +178,12 @@ function get_status() {
156 178
           console.log('------Get-Status timed out a second time');
157 179
           //send back "timeout" to watch
158 180
           message ="Get-Status timed out, verify settings and connectivity";
159
-  
181
+
160 182
           // Build message
161 183
           var dict = {
162 184
             'status': message,
163 185
           };
164
-  
186
+
165 187
           // Send the message
166 188
           Pebble.sendAppMessage(dict, function(e) {
167 189
             console.log('sent');
... ...
@@ -173,12 +195,12 @@ function get_status() {
173 195
 
174 196
       xhr.send();
175 197
 
176
-      
198
+
177 199
     }else{
178 200
       Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
179 201
     }
180 202
   }
181
-      
203
+
182 204
 }
183 205
 
184 206
 
... ...
@@ -193,26 +215,26 @@ function switch_home(bool) {
193 215
       var password=localStorage.getItem('password');
194 216
       var server=localStorage.getItem('server');
195 217
       var xhr = new XMLHttpRequest();
196
-      
218
+
197 219
       url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
198
-      
220
+
199 221
       xhr.open("GET", url,false);
200 222
       xhr.send();
201
-  
223
+
202 224
       if(xhr.status == 200) {
203 225
         response = JSON.parse(xhr.responseText);
204 226
         if (response.success == true){
205
-          status=response.data.on;   
227
+          status = response.data.on;
206 228
           console.log('------ status:'+status);
207 229
           var message;
208 230
           var dict;
209 231
           if ( status != bool){
210 232
             console.log('---- switching home mode to '+ bool);
211 233
             url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on="+bool+"&_sid="+sid;
212
-            
234
+
213 235
             xhr.open("GET", url,false);
214 236
             xhr.send();
215
-        
237
+
216 238
             if(xhr.status == 200) {
217 239
               response = JSON.parse(xhr.responseText);
218 240
               if (response.success == true){
... ...
@@ -226,12 +248,12 @@ function switch_home(bool) {
226 248
                     break;
227 249
                   default:
228 250
                     message = "something happened, try again !";
229
-                }      
251
+                }
230 252
                 // Build message
231 253
                 dict = {
232 254
                   'status': message,
233 255
                 };
234
-              
256
+
235 257
                 // Send the message
236 258
                 Pebble.sendAppMessage(dict, function(e) {
237 259
                   console.log('sent');
... ...
@@ -253,18 +275,18 @@ function switch_home(bool) {
253 275
                 break;
254 276
               default:
255 277
                 message = "something happened, try again !";
256
-            }       
278
+            }
257 279
             // Build message
258 280
             dict = {
259 281
               'status': message,
260 282
             };
261
-  
283
+
262 284
             // Send the message
263 285
             Pebble.sendAppMessage(dict, function(e) {
264 286
               console.log('sent');
265 287
             }, function() {
266 288
               console.log('failed');
267
-            }); 
289
+            });
268 290
           }
269 291
         }
270 292
       }else {
... ...
@@ -305,6 +327,5 @@ Pebble.addEventListener('appmessage', function(e) {
305 327
     default:
306 328
       console.log('Sorry. I don\'t understand your request :'+ dict[0]);
307 329
   }
308
-  
309
-});
310 330
 
331
+});
Browse code

another xhr update with timeout

louis authored on23/06/2022 11:37:01
Showing1 changed files
... ...
@@ -28,6 +28,7 @@ function authenticate() {
28 28
     
29 29
     xhr.onload = function () {
30 30
       if (xhr.readyState === 4) {
31
+        retry=0;
31 32
         console.log('------authentication request returned');
32 33
         if(xhr.status == 200) {
33 34
           response = JSON.parse(xhr.responseText);
... ...
@@ -69,11 +70,11 @@ function authenticate() {
69 70
         authenticate();
70 71
       }else{
71 72
         console.log('------Authentication timed out a second time');
72
-	//send back "timeout" to watch
73
-	auth="";
74
-	message ="Authentication timed out, verify settings and connectivity";
73
+        //send back "timeout" to watch
74
+        auth="";
75
+        message ="Authentication timed out, verify settings and connectivity";
75 76
 
76
-	// Build message
77
+        // Build message
77 78
         var dict = {
78 79
           'auth': message,
79 80
         };
... ...
@@ -105,30 +106,62 @@ function get_status() {
105 106
       var server=localStorage.getItem('server');
106 107
       url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
107 108
       var xhr = new XMLHttpRequest();
109
+      xhr.timeout = 3000; // time in milliseconds
108 110
 
109
-      xhr.open("GET", url,false);
110
-      xhr.send();
111
+      xhr.open("GET", url,true);
111 112
 
112
-      if(xhr.status == 200) {
113
-        response = JSON.parse(xhr.responseText);
114
-        if (response.success == true){
115
-          status=response.data.on;   
116
-          var message;
117
-          switch (status) {
118
-            case true:
119
-              message = "Your Home mode is ON";
120
-              break;
121
-            case false:
122
-              message = "Your Home mode is OFF";
123
-              break;
124
-            default:
125
-              message = "home mode is unknown !";
126
-          }      
113
+      xhr.onload = function () {
114
+        if (xhr.readyState === 4) {
115
+          retry=0;
116
+          console.log('------Get-status request returned');
117
+          if(xhr.status == 200) {
118
+            response = JSON.parse(xhr.responseText);
119
+            if (response.success == true){
120
+              status=response.data.on;   
121
+              var message;
122
+              switch (status) {
123
+                case true:
124
+                  message = "Your Home mode is ON";
125
+                  break;
126
+                case false:
127
+                  message = "Your Home mode is OFF";
128
+                  break;
129
+                default:
130
+                  message = "home mode is unknown !";
131
+              }      
132
+              // Build message
133
+              var dict = {
134
+                'status': message,
135
+              };
136
+            
137
+              // Send the message
138
+              Pebble.sendAppMessage(dict, function(e) {
139
+                console.log('sent');
140
+              }, function() {
141
+                console.log('failed');
142
+              });
143
+            }
144
+          }else {
145
+            console.log('------Request returned error code ' + xhr.status);
146
+          }
147
+        }
148
+      }
149
+
150
+      xhr.ontimeout = function (e){
151
+        retry++;
152
+        if (retry<=1){
153
+          console.log('------Get-Status timed out retrying another time ');
154
+          get_status();
155
+        }else{
156
+          console.log('------Get-Status timed out a second time');
157
+          //send back "timeout" to watch
158
+          message ="Get-Status timed out, verify settings and connectivity";
159
+  
127 160
           // Build message
128 161
           var dict = {
129 162
             'status': message,
130 163
           };
131
-        
164
+  
132 165
           // Send the message
133 166
           Pebble.sendAppMessage(dict, function(e) {
134 167
             console.log('sent');
... ...
@@ -136,9 +169,11 @@ function get_status() {
136 169
             console.log('failed');
137 170
           });
138 171
         }
139
-      }else {
140
-        console.log('------Request returned error code ' + xhr.status.toString());
141 172
       }
173
+
174
+      xhr.send();
175
+
176
+      
142 177
     }else{
143 178
       Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
144 179
     }
... ...
@@ -272,3 +307,4 @@ Pebble.addEventListener('appmessage', function(e) {
272 307
   }
273 308
   
274 309
 });
310
+
Browse code

modified authenticate function to have timeout and second retry on failed xhr

louis authored on22/06/2022 17:06:52
Showing1 changed files
... ...
@@ -6,13 +6,15 @@ var messageKeys = require('message_keys');
6 6
 
7 7
 var sid;
8 8
 var status;
9
+var retry;
10
+retry=0;
9 11
 
10 12
 function authenticate() {
11 13
   var response;
12 14
   sid="";
13 15
   console.log('---- authenticate');
14 16
   console.log('-- '+localStorage.getItem('username'));
15
-  console.log('-- '+localStorage.getItem('password'));
17
+  //console.log('-- '+localStorage.getItem('password'));
16 18
   console.log('-- '+localStorage.getItem('server'));
17 19
   if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
18 20
     var username=localStorage.getItem('username');
... ...
@@ -20,37 +22,72 @@ function authenticate() {
20 22
     var server=localStorage.getItem('server');
21 23
     var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
22 24
     var xhr = new XMLHttpRequest();
23
-  
24
-    xhr.open("GET", url,false);
25
-    xhr.send();
25
+    xhr.timeout = 3000; // time in milliseconds
26 26
 
27
-    if(xhr.status == 200) {
28
-      response = JSON.parse(xhr.responseText);
29
-      if (response.success == true){
30
-        sid = response.data.sid;
31
-      }
32
-    }else {
33
-      console.log('------Request returned error code ' + xhr.status.toString());
34
-    }
35
-  
36
-    if (sid != ""){
37
-      auth = "";
38
-      message = "Welcome to Syno Cam Switch ! ready & authenticated";
39
-           
40
-      // Build message
41
-      var dict = {
42
-        'auth': message,
43
-      };
27
+    xhr.open("GET", url,true);
44 28
     
45
-      // Send the message
46
-      Pebble.sendAppMessage(dict, function(e) {
47
-        console.log('sent');
48
-      }, function() {
49
-        console.log('failed');
50
-      });
51
-       
52
-    }
29
+    xhr.onload = function () {
30
+      if (xhr.readyState === 4) {
31
+        console.log('------authentication request returned');
32
+        if(xhr.status == 200) {
33
+          response = JSON.parse(xhr.responseText);
34
+          if (response.success == true){
35
+            sid = response.data.sid;
36
+          }else{
37
+  	    console.log('------Authentication failed : '+ response.toString());
38
+          }
39
+        }else {
40
+          console.log('------Request returned error code ' + xhr.status);
41
+        }
42
+    
43
+        if (sid != ""){
44
+          auth = "";
45
+          message = "Welcome to Syno Cam Switch ! ready & authenticated";
46
+               
47
+          // Build message
48
+          var dict = {
49
+            'auth': message,
50
+          };
51
+        
52
+          // Send the message
53
+          Pebble.sendAppMessage(dict, function(e) {
54
+            console.log('sent');
55
+          }, function() {
56
+            console.log('failed');
57
+          });
58
+         
59
+        }else{
60
+          console.log('------Unexpected error : authentication is OK but no SID retrieved');
61
+        }
62
+      }
63
+    };
64
+
65
+    xhr.ontimeout = function (e){
66
+      retry++;
67
+      if (retry<=1){
68
+        console.log('------Authentication timed out retrying another time ');
69
+        authenticate();
70
+      }else{
71
+        console.log('------Authentication timed out a second time');
72
+	//send back "timeout" to watch
73
+	auth="";
74
+	message ="Authentication timed out, verify settings and connectivity";
75
+
76
+	// Build message
77
+        var dict = {
78
+          'auth': message,
79
+        };
80
+
81
+        // Send the message
82
+        Pebble.sendAppMessage(dict, function(e) {
83
+          console.log('sent');
84
+        }, function() {
85
+          console.log('failed');
86
+        });
87
+      }
88
+    };
53 89
       
90
+    xhr.send();
54 91
   }else{
55 92
     Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
56 93
   }
... ...
@@ -171,7 +208,7 @@ function switch_home(bool) {
171 208
               console.log('------Request returned error code ' + xhr.status.toString());
172 209
             }
173 210
           }else{
174
-            console.log('---- nothign to do, status already '+status);
211
+            console.log('---- nothing to do, status already '+status);
175 212
             switch (status) {
176 213
               case true:
177 214
                 message = "Your Home Mode is already ON";
... ...
@@ -212,38 +249,6 @@ Pebble.addEventListener('ready',function(e){
212 249
   Pebble.sendAppMessage({'JSReady':1});
213 250
 });
214 251
 
215
-/*
216
-Pebble.addEventListener('webviewclosed', function(e) {
217
-  if (e && !e.response) {
218
-    return;
219
-  }
220
-
221
-  // Get the keys and values from each config item
222
-  var dict = clay.getSettings(e.response);
223
-  //  console.log("server is "+dict[messageKeys.server]);
224
-
225
-  // Send settings values to watch side
226
-  Pebble.sendAppMessage({'server':dict[messageKeys.server]}, function(e) {
227
-    console.log('Sent server config to Pebble');
228
-  }, function(e) {
229
-    console.log('Failed to send server config!');
230
-    console.log(JSON.stringify(e));
231
-  });
232
-  Pebble.sendAppMessage({'username':dict[messageKeys.username]}, function(e) {
233
-    console.log('Sent username config to Pebble');
234
-  }, function(e) {
235
-    console.log('Failed to send username config!');
236
-    console.log(JSON.stringify(e));
237
-  });
238
-  Pebble.sendAppMessage({'password':dict[messageKeys.password]}, function(e) {
239
-    console.log('Sent password config to Pebble');
240
-  }, function(e) {
241
-    console.log('Failed to send password config!');
242
-    console.log(JSON.stringify(e));
243
-  });
244
-});
245
-*/
246
-
247 252
 // Get AppMessage events
248 253
 Pebble.addEventListener('appmessage', function(e) {
249 254
   // Get the dictionary from the message
Browse code

config try 1

Louis authored on27/10/2021 22:58:12
Showing1 changed files
... ...
@@ -212,7 +212,7 @@ Pebble.addEventListener('ready',function(e){
212 212
   Pebble.sendAppMessage({'JSReady':1});
213 213
 });
214 214
 
215
-
215
+/*
216 216
 Pebble.addEventListener('webviewclosed', function(e) {
217 217
   if (e && !e.response) {
218 218
     return;
... ...
@@ -242,6 +242,7 @@ Pebble.addEventListener('webviewclosed', function(e) {
242 242
     console.log(JSON.stringify(e));
243 243
   });
244 244
 });
245
+*/
245 246
 
246 247
 // Get AppMessage events
247 248
 Pebble.addEventListener('appmessage', function(e) {
Browse code

config try2

Louis authored on27/10/2021 22:52:52
Showing1 changed files
... ...
@@ -226,19 +226,19 @@ Pebble.addEventListener('webviewclosed', function(e) {
226 226
   Pebble.sendAppMessage({'server':dict[messageKeys.server]}, function(e) {
227 227
     console.log('Sent server config to Pebble');
228 228
   }, function(e) {
229
-    console.log('Failed to send config data!');
229
+    console.log('Failed to send server config!');
230 230
     console.log(JSON.stringify(e));
231 231
   });
232 232
   Pebble.sendAppMessage({'username':dict[messageKeys.username]}, function(e) {
233 233
     console.log('Sent username config to Pebble');
234 234
   }, function(e) {
235
-    console.log('Failed to send config data!');
235
+    console.log('Failed to send username config!');
236 236
     console.log(JSON.stringify(e));
237 237
   });
238 238
   Pebble.sendAppMessage({'password':dict[messageKeys.password]}, function(e) {
239 239
     console.log('Sent password config to Pebble');
240 240
   }, function(e) {
241
-    console.log('Failed to send config data!');
241
+    console.log('Failed to send password config!');
242 242
     console.log(JSON.stringify(e));
243 243
   });
244 244
 });
Browse code

config try1

Louis authored on27/10/2021 22:48:59
Showing1 changed files
... ...
@@ -223,19 +223,19 @@ Pebble.addEventListener('webviewclosed', function(e) {
223 223
   //  console.log("server is "+dict[messageKeys.server]);
224 224
 
225 225
   // Send settings values to watch side
226
-  Pebble.sendAppMessage({'server':dict[messageKeys.server], function(e) {
226
+  Pebble.sendAppMessage({'server':dict[messageKeys.server]}, function(e) {
227 227
     console.log('Sent server config to Pebble');
228 228
   }, function(e) {
229 229
     console.log('Failed to send config data!');
230 230
     console.log(JSON.stringify(e));
231 231
   });
232
-  Pebble.sendAppMessage({'username':dict[messageKeys.username], function(e) {
232
+  Pebble.sendAppMessage({'username':dict[messageKeys.username]}, function(e) {
233 233
     console.log('Sent username config to Pebble');
234 234
   }, function(e) {
235 235
     console.log('Failed to send config data!');
236 236
     console.log(JSON.stringify(e));
237 237
   });
238
-  Pebble.sendAppMessage({'password':dict[messageKeys.password], function(e) {
238
+  Pebble.sendAppMessage({'password':dict[messageKeys.password]}, function(e) {
239 239
     console.log('Sent password config to Pebble');
240 240
   }, function(e) {
241 241
     console.log('Failed to send config data!');
Browse code

config try1

Louis authored on27/10/2021 22:47:25
Showing1 changed files
... ...
@@ -220,11 +220,23 @@ Pebble.addEventListener('webviewclosed', function(e) {
220 220
 
221 221
   // Get the keys and values from each config item
222 222
   var dict = clay.getSettings(e.response);
223
-  console.log("server is "+dict[messageKeys.server]);
223
+  //  console.log("server is "+dict[messageKeys.server]);
224 224
 
225 225
   // Send settings values to watch side
226
-  Pebble.sendAppMessage(dict, function(e) {
227
-    console.log('Sent config data to Pebble');
226
+  Pebble.sendAppMessage({'server':dict[messageKeys.server], function(e) {
227
+    console.log('Sent server config to Pebble');
228
+  }, function(e) {
229
+    console.log('Failed to send config data!');
230
+    console.log(JSON.stringify(e));
231
+  });
232
+  Pebble.sendAppMessage({'username':dict[messageKeys.username], function(e) {
233
+    console.log('Sent username config to Pebble');
234
+  }, function(e) {
235
+    console.log('Failed to send config data!');
236
+    console.log(JSON.stringify(e));
237
+  });
238
+  Pebble.sendAppMessage({'password':dict[messageKeys.password], function(e) {
239
+    console.log('Sent password config to Pebble');
228 240
   }, function(e) {
229 241
     console.log('Failed to send config data!');
230 242
     console.log(JSON.stringify(e));
Browse code

debug2

Louis authored on27/10/2021 22:43:23
Showing1 changed files
... ...
@@ -220,7 +220,7 @@ Pebble.addEventListener('webviewclosed', function(e) {
220 220
 
221 221
   // Get the keys and values from each config item
222 222
   var dict = clay.getSettings(e.response);
223
-  console.log("server is "+dict[messageKeys.Server]);
223
+  console.log("server is "+dict[messageKeys.server]);
224 224
 
225 225
   // Send settings values to watch side
226 226
   Pebble.sendAppMessage(dict, function(e) {
Louis authored on27/10/2021 22:41:20
Showing1 changed files
... ...
@@ -2,6 +2,8 @@ var Clay = require('pebble-clay');
2 2
 var clayConfig = require('./config');
3 3
 var clay = new Clay(clayConfig);
4 4
 
5
+var messageKeys = require('message_keys');
6
+
5 7
 var sid;
6 8
 var status;
7 9
 
... ...
@@ -218,6 +220,7 @@ Pebble.addEventListener('webviewclosed', function(e) {
218 220
 
219 221
   // Get the keys and values from each config item
220 222
   var dict = clay.getSettings(e.response);
223
+  console.log("server is "+dict[messageKeys.Server]);
221 224
 
222 225
   // Send settings values to watch side
223 226
   Pebble.sendAppMessage(dict, function(e) {
Browse code

add handlerconfig

Louis authored on27/10/2021 21:00:13
Showing1 changed files
... ...
@@ -9,7 +9,7 @@ function authenticate() {
9 9
   var response;
10 10
   sid="";
11 11
   console.log('---- authenticate');
12
-  console.log('-- '+clay.getSettings('username'));
12
+  console.log('-- '+localStorage.getItem('username'));
13 13
   console.log('-- '+localStorage.getItem('password'));
14 14
   console.log('-- '+localStorage.getItem('server'));
15 15
   if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
... ...
@@ -210,6 +210,24 @@ Pebble.addEventListener('ready',function(e){
210 210
   Pebble.sendAppMessage({'JSReady':1});
211 211
 });
212 212
 
213
+
214
+Pebble.addEventListener('webviewclosed', function(e) {
215
+  if (e && !e.response) {
216
+    return;
217
+  }
218
+
219
+  // Get the keys and values from each config item
220
+  var dict = clay.getSettings(e.response);
221
+
222
+  // Send settings values to watch side
223
+  Pebble.sendAppMessage(dict, function(e) {
224
+    console.log('Sent config data to Pebble');
225
+  }, function(e) {
226
+    console.log('Failed to send config data!');
227
+    console.log(JSON.stringify(e));
228
+  });
229
+});
230
+
213 231
 // Get AppMessage events
214 232
 Pebble.addEventListener('appmessage', function(e) {
215 233
   // Get the dictionary from the message
Browse code

pebble-clay

Louis authored on26/10/2021 23:21:03
Showing1 changed files
... ...
@@ -9,7 +9,7 @@ function authenticate() {
9 9
   var response;
10 10
   sid="";
11 11
   console.log('---- authenticate');
12
-  console.log('-- '+localStorage.getItem('username'));
12
+  console.log('-- '+clay.getSettings('username'));
13 13
   console.log('-- '+localStorage.getItem('password'));
14 14
   console.log('-- '+localStorage.getItem('server'));
15 15
   if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
Browse code

more logs

Louis authored on26/10/2021 22:43:22
Showing1 changed files
... ...
@@ -9,6 +9,9 @@ function authenticate() {
9 9
   var response;
10 10
   sid="";
11 11
   console.log('---- authenticate');
12
+  console.log('-- '+localStorage.getItem('username'));
13
+  console.log('-- '+localStorage.getItem('password'));
14
+  console.log('-- '+localStorage.getItem('server'));
12 15
   if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
13 16
     var username=localStorage.getItem('username');
14 17
     var password=localStorage.getItem('password');
Browse code

authentication is now at start :)

Louis authored on14/03/2019 23:43:12
Showing1 changed files
... ...
@@ -63,7 +63,7 @@ function get_status() {
63 63
       var server=localStorage.getItem('server');
64 64
       url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
65 65
       var xhr = new XMLHttpRequest();
66
-      
66
+
67 67
       xhr.open("GET", url,false);
68 68
       xhr.send();
69 69
 
... ...
@@ -107,31 +107,16 @@ function get_status() {
107 107
 
108 108
 function switch_home(bool) {
109 109
   var response;
110
-  sid="";
111 110
   console.log('---- authenticate');
112
-  if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
113
-    var username=localStorage.getItem('username');
114
-    var password=localStorage.getItem('password');
115
-    var server=localStorage.getItem('server');
116
-    var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
117
-    var xhr = new XMLHttpRequest();
118
-  
119
-    xhr.open("GET", url,false);
120
-    xhr.send();
121
-  
122
-    if(xhr.status == 200) {
123
-      response = JSON.parse(xhr.responseText);
124
-      if (response.success == true){
125
-        sid = response.data.sid;
126
-        console.log('------ sid = '+sid);
127
-      }
128
-    }else {
129
-      console.log('------Request returned error code ' + xhr.status.toString());
130
-    }
131
-  
132
-    if (sid != ""){
133
-      status = "";
134
-      console.log('---- get_status');
111
+  if (sid != ""){
112
+    status = "";
113
+    console.log('---- get_status');
114
+    if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
115
+      var username=localStorage.getItem('username');
116
+      var password=localStorage.getItem('password');
117
+      var server=localStorage.getItem('server');
118
+      var xhr = new XMLHttpRequest();
119
+      
135 120
       url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
136 121
       
137 122
       xhr.open("GET", url,false);
... ...
@@ -208,10 +193,10 @@ function switch_home(bool) {
208 193
       }else {
209 194
         console.log('------Request returned error code ' + xhr.status.toString());
210 195
       }
196
+    }else{
197
+      Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
211 198
     }
212
-   }else{
213
-    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
214
-  }
199
+   }
215 200
 
216 201
 }
217 202
 
Browse code

adding logs

Louis authored on14/03/2019 23:38:24
Showing1 changed files
... ...
@@ -62,6 +62,7 @@ function get_status() {
62 62
       var password=localStorage.getItem('password');
63 63
       var server=localStorage.getItem('server');
64 64
       url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
65
+      var xhr = new XMLHttpRequest();
65 66
       
66 67
       xhr.open("GET", url,false);
67 68
       xhr.send();
Browse code

adding logs

Louis authored on14/03/2019 23:37:00
Showing1 changed files
... ...
@@ -57,40 +57,47 @@ function get_status() {
57 57
   if (sid != ""){
58 58
     status = "";
59 59
     console.log('---- get_status');
60
-    url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
61
-    
62
-    xhr.open("GET", url,false);
63
-    xhr.send();
64
-
65
-    if(xhr.status == 200) {
66
-      response = JSON.parse(xhr.responseText);
67
-      if (response.success == true){
68
-        status=response.data.on;   
69
-        var message;
70
-        switch (status) {
71
-          case true:
72
-            message = "Your Home mode is ON";
73
-            break;
74
-          case false:
75
-            message = "Your Home mode is OFF";
76
-            break;
77
-          default:
78
-            message = "home mode is unknown !";
79
-        }      
80
-        // Build message
81
-        var dict = {
82
-          'status': message,
83
-        };
60
+    if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
61
+      var username=localStorage.getItem('username');
62
+      var password=localStorage.getItem('password');
63
+      var server=localStorage.getItem('server');
64
+      url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
84 65
       
85
-        // Send the message
86
-        Pebble.sendAppMessage(dict, function(e) {
87
-          console.log('sent');
88
-        }, function() {
89
-          console.log('failed');
90
-        });
66
+      xhr.open("GET", url,false);
67
+      xhr.send();
68
+
69
+      if(xhr.status == 200) {
70
+        response = JSON.parse(xhr.responseText);
71
+        if (response.success == true){
72
+          status=response.data.on;   
73
+          var message;
74
+          switch (status) {
75
+            case true:
76
+              message = "Your Home mode is ON";
77
+              break;
78
+            case false:
79
+              message = "Your Home mode is OFF";
80
+              break;
81
+            default:
82
+              message = "home mode is unknown !";
83
+          }      
84
+          // Build message
85
+          var dict = {
86
+            'status': message,
87
+          };
88
+        
89
+          // Send the message
90
+          Pebble.sendAppMessage(dict, function(e) {
91
+            console.log('sent');
92
+          }, function() {
93
+            console.log('failed');
94
+          });
95
+        }
96
+      }else {
97
+        console.log('------Request returned error code ' + xhr.status.toString());
91 98
       }
92
-    }else {
93
-      console.log('------Request returned error code ' + xhr.status.toString());
99
+    }else{
100
+      Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
94 101
     }
95 102
   }
96 103
       
Browse code

adding logs

Louis authored on14/03/2019 23:26:40
Showing1 changed files
... ...
@@ -218,7 +218,7 @@ Pebble.addEventListener('ready',function(e){
218 218
 Pebble.addEventListener('appmessage', function(e) {
219 219
   // Get the dictionary from the message
220 220
   var dict = e.payload;
221
-  console.log(dict.toString());
221
+  console.log(dict[0].toString());
222 222
   switch (dict[0]) {
223 223
     case 'auth':
224 224
       authenticate();
... ...
@@ -233,7 +233,7 @@ Pebble.addEventListener('appmessage', function(e) {
233 233
       switch_home(false);
234 234
       break;
235 235
     default:
236
-      console.log('Sorry. I don\'t understand your request :'+ dict);
236
+      console.log('Sorry. I don\'t understand your request :'+ dict[0]);
237 237
   }
238 238
   
239 239
 });
Browse code

adding logs

Louis authored on14/03/2019 23:17:38
Showing1 changed files
... ...
@@ -218,7 +218,7 @@ Pebble.addEventListener('ready',function(e){
218 218
 Pebble.addEventListener('appmessage', function(e) {
219 219
   // Get the dictionary from the message
220 220
   var dict = e.payload;
221
-  
221
+  console.log(dict.toString());
222 222
   switch (dict[0]) {
223 223
     case 'auth':
224 224
       authenticate();
... ...
@@ -234,6 +234,6 @@ Pebble.addEventListener('appmessage', function(e) {
234 234
       break;
235 235
     default:
236 236
       console.log('Sorry. I don\'t understand your request :'+ dict);
237
-}
237
+  }
238 238
   
239 239
 });
Browse code

adding logs

Louis authored on14/03/2019 23:11:58
Showing1 changed files
... ...
@@ -233,7 +233,7 @@ Pebble.addEventListener('appmessage', function(e) {
233 233
       switch_home(false);
234 234
       break;
235 235
     default:
236
-      console.log('Sorry. I don\'t understand your request :'+ dict[0] );
236
+      console.log('Sorry. I don\'t understand your request :'+ dict);
237 237
 }
238 238
   
239 239
 });
Browse code

adding logs

Louis authored on14/03/2019 22:58:19
Showing1 changed files
... ...
@@ -233,7 +233,7 @@ Pebble.addEventListener('appmessage', function(e) {
233 233
       switch_home(false);
234 234
       break;
235 235
     default:
236
-      console.log('Sorry.');
236
+      console.log('Sorry. I don\'t understand your request :'+ dict[0] );
237 237
 }
238 238
   
239 239
 });
Browse code

removed authentication from get_status

Louis authored on14/03/2019 22:29:25
Showing1 changed files
... ...
@@ -53,70 +53,47 @@ function authenticate() {
53 53
 
54 54
 function get_status() {
55 55
   var response;
56
-  sid="";
57
-  console.log('---- authenticate');
58
-  if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
59
-    var username=localStorage.getItem('username');
60
-    var password=localStorage.getItem('password');
61
-    var server=localStorage.getItem('server');
62
-    var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
63
-    var xhr = new XMLHttpRequest();
64 56
   
57
+  if (sid != ""){
58
+    status = "";
59
+    console.log('---- get_status');
60
+    url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
61
+    
65 62
     xhr.open("GET", url,false);
66 63
     xhr.send();
67 64
 
68 65
     if(xhr.status == 200) {
69 66
       response = JSON.parse(xhr.responseText);
70 67
       if (response.success == true){
71
-        sid = response.data.sid;
68
+        status=response.data.on;   
69
+        var message;
70
+        switch (status) {
71
+          case true:
72
+            message = "Your Home mode is ON";
73
+            break;
74
+          case false:
75
+            message = "Your Home mode is OFF";
76
+            break;
77
+          default:
78
+            message = "home mode is unknown !";
79
+        }      
80
+        // Build message
81
+        var dict = {
82
+          'status': message,
83
+        };
84
+      
85
+        // Send the message
86
+        Pebble.sendAppMessage(dict, function(e) {
87
+          console.log('sent');
88
+        }, function() {
89
+          console.log('failed');
90
+        });
72 91
       }
73 92
     }else {
74 93
       console.log('------Request returned error code ' + xhr.status.toString());
75 94
     }
76
-  
77
-    if (sid != ""){
78
-      status = "";
79
-      console.log('---- get_status');
80
-      url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
81
-      
82
-      xhr.open("GET", url,false);
83
-      xhr.send();
84
-  
85
-      if(xhr.status == 200) {
86
-        response = JSON.parse(xhr.responseText);
87
-        if (response.success == true){
88
-          status=response.data.on;   
89
-          var message;
90
-          switch (status) {
91
-            case true:
92
-              message = "Your Home mode is ON";
93
-              break;
94
-            case false:
95
-              message = "Your Home mode is OFF";
96
-              break;
97
-            default:
98
-              message = "home mode is unknown !";
99
-          }      
100
-          // Build message
101
-          var dict = {
102
-            'status': message,
103
-          };
104
-        
105
-          // Send the message
106
-          Pebble.sendAppMessage(dict, function(e) {
107
-            console.log('sent');
108
-          }, function() {
109
-            console.log('failed');
110
-          });
111
-        }
112
-      }else {
113
-        console.log('------Request returned error code ' + xhr.status.toString());
114
-      }
115
-    }
116
-      
117
-  }else{
118
-    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
119 95
   }
96
+      
120 97
 }
121 98
 
122 99
 
Browse code

authenticate at app start

Louis authored on14/03/2019 22:27:39
Showing1 changed files
... ...
@@ -5,6 +5,52 @@ var clay = new Clay(clayConfig);
5 5
 var sid;
6 6
 var status;
7 7
 
8
+function authenticate() {
9
+  var response;
10
+  sid="";
11
+  console.log('---- authenticate');
12
+  if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
13
+    var username=localStorage.getItem('username');
14
+    var password=localStorage.getItem('password');
15
+    var server=localStorage.getItem('server');
16
+    var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
17
+    var xhr = new XMLHttpRequest();
18
+  
19
+    xhr.open("GET", url,false);
20
+    xhr.send();
21
+
22
+    if(xhr.status == 200) {
23
+      response = JSON.parse(xhr.responseText);
24
+      if (response.success == true){
25
+        sid = response.data.sid;
26
+      }
27
+    }else {
28
+      console.log('------Request returned error code ' + xhr.status.toString());
29
+    }
30
+  
31
+    if (sid != ""){
32
+      auth = "";
33
+      message = "Welcome to Syno Cam Switch ! ready & authenticated";
34
+           
35
+      // Build message
36
+      var dict = {
37
+        'auth': message,
38
+      };
39
+    
40
+      // Send the message
41
+      Pebble.sendAppMessage(dict, function(e) {
42
+        console.log('sent');
43
+      }, function() {
44
+        console.log('failed');
45
+      });
46
+       
47
+    }
48
+      
49
+  }else{
50
+    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
51
+  }
52
+}
53
+
8 54
 function get_status() {
9 55
   var response;
10 56
   sid="";
... ...
@@ -197,6 +243,9 @@ Pebble.addEventListener('appmessage', function(e) {
197 243
   var dict = e.payload;
198 244
   
199 245
   switch (dict[0]) {
246
+    case 'auth':
247
+      authenticate();
248
+      break;
200 249
     case 'get':
201 250
       get_status();
202 251
       break;
Browse code

better handling sent message ?

Louis authored on29/09/2018 01:27:02
Showing1 changed files
... ...
@@ -19,20 +19,6 @@ function get_status() {
19 19
     xhr.open("GET", url,false);
20 20
     xhr.send();
21 21
 
22
-    var message;
23
-    message = "sent...";
24
-    // Build message
25
-    var dict = {
26
-      'status': message,
27
-    };
28
-
29
-    // Send the message
30
-    Pebble.sendAppMessage(dict, function(e) {
31
-        console.log('sent');
32
-      }, function() {
33
-        console.log('failed');
34
-      });
35
-
36 22
     if(xhr.status == 200) {
37 23
       response = JSON.parse(xhr.responseText);
38 24
       if (response.success == true){
... ...
@@ -102,20 +88,6 @@ function switch_home(bool) {
102 88
     xhr.open("GET", url,false);
103 89
     xhr.send();
104 90
   
105
-    var message;
106
-    message = "sent...";
107
-    // Build message
108
-    var dict = {
109
-      'status': message,
110
-    };
111
-
112
-    // Send the message
113
-    Pebble.sendAppMessage(dict, function(e) {
114
-        console.log('sent');
115
-      }, function() {
116
-        console.log('failed');
117
-      });
118
-
119 91
     if(xhr.status == 200) {
120 92
       response = JSON.parse(xhr.responseText);
121 93
       if (response.success == true){
Browse code

sent message

Louis authored on22/09/2018 15:50:26
Showing1 changed files
... ...
@@ -18,7 +18,21 @@ function get_status() {
18 18
   
19 19
     xhr.open("GET", url,false);
20 20
     xhr.send();
21
-  
21
+
22
+    var message;
23
+    message = "sent...";
24
+    // Build message
25
+    var dict = {
26
+      'status': message,
27
+    };
28
+
29
+    // Send the message
30
+    Pebble.sendAppMessage(dict, function(e) {
31
+        console.log('sent');
32
+      }, function() {
33
+        console.log('failed');
34
+      });
35
+
22 36
     if(xhr.status == 200) {
23 37
       response = JSON.parse(xhr.responseText);
24 38
       if (response.success == true){
... ...
@@ -88,6 +102,20 @@ function switch_home(bool) {
88 102
     xhr.open("GET", url,false);
89 103
     xhr.send();
90 104
   
105
+    var message;
106
+    message = "sent...";
107
+    // Build message
108
+    var dict = {
109
+      'status': message,
110
+    };
111
+
112
+    // Send the message
113
+    Pebble.sendAppMessage(dict, function(e) {
114
+        console.log('sent');
115
+      }, function() {
116
+        console.log('failed');
117
+      });
118
+
91 119
     if(xhr.status == 200) {
92 120
       response = JSON.parse(xhr.responseText);
93 121
       if (response.success == true){
... ...
@@ -156,7 +184,7 @@ function switch_home(bool) {
156 184
                 message = "Your Home Mode is already ON";
157 185
                 break;
158 186
               case false:
159
-                message = "Your Home Mode is already off";
187
+                message = "Your Home Mode is already OFF";
160 188
                 break;
161 189
               default:
162 190
                 message = "something happened, try again !";
Browse code

JSReady enabled

Louis authored on18/09/2018 23:08:46
Showing1 changed files
... ...
@@ -184,6 +184,12 @@ function switch_home(bool) {
184 184
 
185 185
 }
186 186
 
187
+// Get JS readiness events
188
+Pebble.addEventListener('ready',function(e){
189
+  console.log('PebbleKit JS is ready');
190
+  // Update Watch on this
191
+  Pebble.sendAppMessage({'JSReady':1});
192
+});
187 193
 
188 194
 // Get AppMessage events
189 195
 Pebble.addEventListener('appmessage', function(e) {
Browse code

off -> OFF

Louis authored on25/08/2018 23:35:41
Showing1 changed files
... ...
@@ -129,7 +129,7 @@ function switch_home(bool) {
129 129
                     message = "You just set Home mode ON";
130 130
                     break;
131 131
                   case false:
132
-                    message = "You just set Home mode off";
132
+                    message = "You just set Home mode OFF";
133 133
                     break;
134 134
                   default:
135 135
                     message = "something happened, try again !";
... ...
@@ -204,4 +204,4 @@ Pebble.addEventListener('appmessage', function(e) {
204 204
       console.log('Sorry.');
205 205
 }
206 206
   
207
-});
208 207
\ No newline at end of file
208
+});
Browse code

error handling

Louis authored on12/07/2018 00:27:42
Showing1 changed files
... ...
@@ -9,170 +9,178 @@ function get_status() {
9 9
   var response;
10 10
   sid="";
11 11
   console.log('---- authenticate');
12
-  var username=localStorage.getItem('username');
13
-  var password=localStorage.getItem('password');
14
-  var server=localStorage.getItem('server');
15
-  var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
16
-  var xhr = new XMLHttpRequest();
17
-
18
-  xhr.open("GET", url,false);
19
-  xhr.send();
20
-
21
-  if(xhr.status == 200) {
22
-    response = JSON.parse(xhr.responseText);
23
-    if (response.success == true){
24
-      sid = response.data.sid;
25
-    }
26
-  }else {
27
-    console.log('------Request returned error code ' + xhr.status.toString());
28
-  }
29
-
30
-  if (sid != ""){
31
-    status = "";
32
-    console.log('---- get_status');
33
-    url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
34
-    
12
+  if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
13
+    var username=localStorage.getItem('username');
14
+    var password=localStorage.getItem('password');
15
+    var server=localStorage.getItem('server');
16
+    var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
17
+    var xhr = new XMLHttpRequest();
18
+  
35 19
     xhr.open("GET", url,false);
36 20
     xhr.send();
37
-
21
+  
38 22
     if(xhr.status == 200) {
39 23
       response = JSON.parse(xhr.responseText);
40 24
       if (response.success == true){
41
-        status=response.data.on;   
42
-        var message;
43
-        switch (status) {
44
-          case true:
45
-            message = "Your Home mode is ON";
46
-            break;
47
-          case false:
48
-            message = "Your Home mode is OFF";
49
-            break;
50
-          default:
51
-            message = "home mode is unknown !";
52
-        }      
53
-        // Build message
54
-        var dict = {
55
-          'status': message,
56
-        };
57
-      
58
-        // Send the message
59
-        Pebble.sendAppMessage(dict, function(e) {
60
-          console.log('sent');
61
-        }, function() {
62
-          console.log('failed');
63
-        });
25
+        sid = response.data.sid;
64 26
       }
65 27
     }else {
66 28
       console.log('------Request returned error code ' + xhr.status.toString());
67 29
     }
68
-  }
69
-}
70
-
71
-
72
-function switch_home(bool) {
73
-  var response;
74
-  sid="";
75
-  console.log('---- authenticate');
76
-  var username=localStorage.getItem('username');
77
-  var password=localStorage.getItem('password');
78
-  var server=localStorage.getItem('server');
79
-  var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
80
-  var xhr = new XMLHttpRequest();
81
-
82
-  xhr.open("GET", url,false);
83
-  xhr.send();
84
-
85
-  if(xhr.status == 200) {
86
-    response = JSON.parse(xhr.responseText);
87
-    if (response.success == true){
88
-      sid = response.data.sid;
89
-      console.log('------ sid = '+sid);
90
-    }
91
-  }else {
92
-    console.log('------Request returned error code ' + xhr.status.toString());
93
-  }
94
-
95
-  if (sid != ""){
96
-    status = "";
97
-    console.log('---- get_status');
98
-    url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
99
-    
100
-    xhr.open("GET", url,false);
101
-    xhr.send();
102
-
103
-    if(xhr.status == 200) {
104
-      response = JSON.parse(xhr.responseText);
105
-      if (response.success == true){
106
-        status=response.data.on;   
107
-        console.log('------ status:'+status);
108
-        var message;
109
-        var dict;
110
-        if ( status != bool){
111
-          console.log('---- switching home mode to '+ bool);
112
-          url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on="+bool+"&_sid="+sid;
113
-          
114
-          xhr.open("GET", url,false);
115
-          xhr.send();
30
+  
31
+    if (sid != ""){
32
+      status = "";
33
+      console.log('---- get_status');
34
+      url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
116 35
       
117
-          if(xhr.status == 200) {
118
-            response = JSON.parse(xhr.responseText);
119
-            if (response.success == true){
120
-              status=bool;
121
-              switch (status) {
122
-                case true:
123
-                  message = "You just set Home mode ON";
124
-                  break;
125
-                case false:
126
-                  message = "You just set Home mode off";
127
-                  break;
128
-                default:
129
-                  message = "something happened, try again !";
130
-              }      
131
-              // Build message
132
-              dict = {
133
-                'status': message,
134
-              };
135
-            
136
-              // Send the message
137
-              Pebble.sendAppMessage(dict, function(e) {
138
-                console.log('sent');
139
-              }, function() {
140
-                console.log('failed');
141
-              });
142
-            }
143
-          }else {
144
-            console.log('------Request returned error code ' + xhr.status.toString());
145
-          }
146
-        }else{
147
-          console.log('---- nothign to do, status already '+status);
36
+      xhr.open("GET", url,false);
37
+      xhr.send();
38
+  
39
+      if(xhr.status == 200) {
40
+        response = JSON.parse(xhr.responseText);
41
+        if (response.success == true){
42
+          status=response.data.on;   
43
+          var message;
148 44
           switch (status) {
149 45
             case true:
150
-              message = "Your Home Mode is already ON";
46
+              message = "Your Home mode is ON";
151 47
               break;
152 48
             case false:
153
-              message = "Your Home Mode is already off";
49
+              message = "Your Home mode is OFF";
154 50
               break;
155 51
             default:
156
-              message = "something happened, try again !";
157
-          }       
52
+              message = "home mode is unknown !";
53
+          }      
158 54
           // Build message
159
-          dict = {
55
+          var dict = {
160 56
             'status': message,
161 57
           };
162
-
58
+        
163 59
           // Send the message
164 60
           Pebble.sendAppMessage(dict, function(e) {
165 61
             console.log('sent');
166 62
           }, function() {
167 63
             console.log('failed');
168
-          }); 
64
+          });
169 65
         }
66
+      }else {
67
+        console.log('------Request returned error code ' + xhr.status.toString());
68
+      }
69
+    }
70
+      
71
+  }else{
72
+    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
73
+  }
74
+}
75
+
76
+
77
+function switch_home(bool) {
78
+  var response;
79
+  sid="";
80
+  console.log('---- authenticate');
81
+  if (localStorage.getItem('username')  && localStorage.getItem('password') && localStorage.getItem('server') ){
82
+    var username=localStorage.getItem('username');
83
+    var password=localStorage.getItem('password');
84
+    var server=localStorage.getItem('server');
85
+    var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
86
+    var xhr = new XMLHttpRequest();
87
+  
88
+    xhr.open("GET", url,false);
89
+    xhr.send();
90
+  
91
+    if(xhr.status == 200) {
92
+      response = JSON.parse(xhr.responseText);
93
+      if (response.success == true){
94
+        sid = response.data.sid;
95
+        console.log('------ sid = '+sid);
170 96
       }
171 97
     }else {
172 98
       console.log('------Request returned error code ' + xhr.status.toString());
173 99
     }
100
+  
101
+    if (sid != ""){
102
+      status = "";
103
+      console.log('---- get_status');
104
+      url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
105
+      
106
+      xhr.open("GET", url,false);
107
+      xhr.send();
108
+  
109
+      if(xhr.status == 200) {
110
+        response = JSON.parse(xhr.responseText);
111
+        if (response.success == true){
112
+          status=response.data.on;   
113
+          console.log('------ status:'+status);
114
+          var message;
115
+          var dict;
116
+          if ( status != bool){
117
+            console.log('---- switching home mode to '+ bool);
118
+            url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on="+bool+"&_sid="+sid;
119
+            
120
+            xhr.open("GET", url,false);
121
+            xhr.send();
122
+        
123
+            if(xhr.status == 200) {
124
+              response = JSON.parse(xhr.responseText);
125
+              if (response.success == true){
126
+                status=bool;
127
+                switch (status) {
128
+                  case true:
129
+                    message = "You just set Home mode ON";
130
+                    break;
131
+                  case false:
132
+                    message = "You just set Home mode off";
133
+                    break;
134
+                  default:
135
+                    message = "something happened, try again !";
136
+                }      
137
+                // Build message
138
+                dict = {
139
+                  'status': message,
140
+                };
141
+              
142
+                // Send the message
143
+                Pebble.sendAppMessage(dict, function(e) {
144
+                  console.log('sent');
145
+                }, function() {
146
+                  console.log('failed');
147
+                });
148
+              }
149
+            }else {
150
+              console.log('------Request returned error code ' + xhr.status.toString());
151
+            }
152
+          }else{
153
+            console.log('---- nothign to do, status already '+status);
154
+            switch (status) {
155
+              case true:
156
+                message = "Your Home Mode is already ON";
157
+                break;
158
+              case false:
159
+                message = "Your Home Mode is already off";
160
+                break;
161
+              default:
162
+                message = "something happened, try again !";
163
+            }       
164
+            // Build message
165
+            dict = {
166
+              'status': message,
167
+            };
168
+  
169
+            // Send the message
170
+            Pebble.sendAppMessage(dict, function(e) {
171
+              console.log('sent');
172
+            }, function() {
173
+              console.log('failed');
174
+            }); 
175
+          }
176
+        }
177
+      }else {
178
+        console.log('------Request returned error code ' + xhr.status.toString());
179
+      }
180
+    }
181
+   }else{
182
+    Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
174 183
   }
175
- 
176 184
 
177 185
 }
178 186
 
... ...
@@ -196,37 +204,4 @@ Pebble.addEventListener('appmessage', function(e) {
196 204
       console.log('Sorry.');
197 205
 }
198 206
   
199
-});
200
-/*
201
-// Get Configuration page 
202
-Pebble.addEventListener('showConfiguration', function() {
203
-  var username=localStorage.getItem('username');
204
-  var password=localStorage.getItem('password');
205
-  var server=localStorage.getItem('server');
206
-  var  url = 'https://jonget.fr/pebble/config_homeswitch.php?username='+username+'&password='+password+'&server='+server;
207
-  
208
-  Pebble.openURL(url);
209
-});
210
-
211
-Pebble.addEventListener('webviewclosed', function(e) {
212
-  // Decode the user's preferences
213
-  var configData = JSON.parse(decodeURIComponent(e.response));
214
-  localStorage.setItem('username',configData.username);
215
-  localStorage.setItem('password',configData.password);
216
-  localStorage.setItem('server',configData.server);
217
-  console.log('---- new username stored : '+localStorage.getItem('username'));
218
-  console.log('---- new password stored : '+localStorage.getItem('password'));
219
-  console.log('---- new server stored : '+localStorage.getItem('server'));
220
-  var dict = {
221
-    'username': configData.username,
222
-    'password': configData.password,
223
-    'server': configData.server
224
-  };
225
-            
226
-  // Send the message
227
-  Pebble.sendAppMessage(dict, function(e) {
228
-    console.log('sent');
229
-  }, function() {
230
-    console.log('failed');
231
-  }); 
232
-});*/
233 207
\ No newline at end of file
208
+});
234 209
\ No newline at end of file
Browse code

Clay with all files

Louis authored on10/07/2018 14:37:31
Showing1 changed files
... ...
@@ -1,7 +1,7 @@
1
+var Clay = require('pebble-clay');
2
+var clayConfig = require('./config');
3
+var clay = new Clay(clayConfig);
1 4
 
2
-var username;
3
-var password;
4
-var server;
5 5
 var sid;
6 6
 var status;
7 7
 
... ...
@@ -197,7 +197,7 @@ Pebble.addEventListener('appmessage', function(e) {
197 197
 }
198 198
   
199 199
 });
200
-
200
+/*
201 201
 // Get Configuration page 
202 202
 Pebble.addEventListener('showConfiguration', function() {
203 203
   var username=localStorage.getItem('username');
... ...
@@ -229,4 +229,4 @@ Pebble.addEventListener('webviewclosed', function(e) {
229 229
   }, function() {
230 230
     console.log('failed');
231 231
   }); 
232
-});
233 232
\ No newline at end of file
233
+});*/
234 234
\ No newline at end of file
Louis authored on10/07/2018 13:58:16
Showing1 changed files
1 1
new file mode 100755
... ...
@@ -0,0 +1,232 @@
1
+
2
+var username;
3
+var password;
4
+var server;
5
+var sid;
6
+var status;
7
+
8
+function get_status() {
9
+  var response;
10
+  sid="";
11
+  console.log('---- authenticate');
12
+  var username=localStorage.getItem('username');
13
+  var password=localStorage.getItem('password');
14
+  var server=localStorage.getItem('server');
15
+  var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
16
+  var xhr = new XMLHttpRequest();
17
+
18
+  xhr.open("GET", url,false);
19
+  xhr.send();
20
+
21
+  if(xhr.status == 200) {
22
+    response = JSON.parse(xhr.responseText);
23
+    if (response.success == true){
24
+      sid = response.data.sid;
25
+    }
26
+  }else {
27
+    console.log('------Request returned error code ' + xhr.status.toString());
28
+  }
29
+
30
+  if (sid != ""){
31
+    status = "";
32
+    console.log('---- get_status');
33
+    url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
34
+    
35
+    xhr.open("GET", url,false);
36
+    xhr.send();
37
+
38
+    if(xhr.status == 200) {
39
+      response = JSON.parse(xhr.responseText);
40
+      if (response.success == true){
41
+        status=response.data.on;   
42
+        var message;
43
+        switch (status) {
44
+          case true:
45
+            message = "Your Home mode is ON";
46
+            break;
47
+          case false:
48
+            message = "Your Home mode is OFF";
49
+            break;
50
+          default:
51
+            message = "home mode is unknown !";
52
+        }      
53
+        // Build message
54
+        var dict = {
55
+          'status': message,
56
+        };
57
+      
58
+        // Send the message
59
+        Pebble.sendAppMessage(dict, function(e) {
60
+          console.log('sent');
61
+        }, function() {
62
+          console.log('failed');
63
+        });
64
+      }
65
+    }else {
66
+      console.log('------Request returned error code ' + xhr.status.toString());
67
+    }
68
+  }
69
+}
70
+
71
+
72
+function switch_home(bool) {
73
+  var response;
74
+  sid="";
75
+  console.log('---- authenticate');
76
+  var username=localStorage.getItem('username');
77
+  var password=localStorage.getItem('password');
78
+  var server=localStorage.getItem('server');
79
+  var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account="+username+"&passwd="+password+"&session=SurveillanceStation&format=sid";
80
+  var xhr = new XMLHttpRequest();
81
+
82
+  xhr.open("GET", url,false);
83
+  xhr.send();
84
+
85
+  if(xhr.status == 200) {
86
+    response = JSON.parse(xhr.responseText);
87
+    if (response.success == true){
88
+      sid = response.data.sid;
89
+      console.log('------ sid = '+sid);
90
+    }
91
+  }else {
92
+    console.log('------Request returned error code ' + xhr.status.toString());
93
+  }
94
+
95
+  if (sid != ""){
96
+    status = "";
97
+    console.log('---- get_status');
98
+    url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid="+sid;
99
+    
100
+    xhr.open("GET", url,false);
101
+    xhr.send();
102
+
103
+    if(xhr.status == 200) {
104
+      response = JSON.parse(xhr.responseText);
105
+      if (response.success == true){
106
+        status=response.data.on;   
107
+        console.log('------ status:'+status);
108
+        var message;
109
+        var dict;
110
+        if ( status != bool){
111
+          console.log('---- switching home mode to '+ bool);
112
+          url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on="+bool+"&_sid="+sid;
113
+          
114
+          xhr.open("GET", url,false);
115
+          xhr.send();
116
+      
117
+          if(xhr.status == 200) {
118
+            response = JSON.parse(xhr.responseText);
119
+            if (response.success == true){
120
+              status=bool;
121
+              switch (status) {
122
+                case true:
123
+                  message = "You just set Home mode ON";
124
+                  break;
125
+                case false:
126
+                  message = "You just set Home mode off";
127
+                  break;
128
+                default:
129
+                  message = "something happened, try again !";
130
+              }      
131
+              // Build message
132
+              dict = {
133
+                'status': message,
134
+              };
135
+            
136
+              // Send the message
137
+              Pebble.sendAppMessage(dict, function(e) {
138
+                console.log('sent');
139
+              }, function() {
140
+                console.log('failed');
141
+              });
142
+            }
143
+          }else {
144
+            console.log('------Request returned error code ' + xhr.status.toString());
145
+          }
146
+        }else{
147
+          console.log('---- nothign to do, status already '+status);
148
+          switch (status) {
149
+            case true:
150
+              message = "Your Home Mode is already ON";
151
+              break;
152
+            case false:
153
+              message = "Your Home Mode is already off";
154
+              break;
155
+            default:
156
+              message = "something happened, try again !";
157
+          }       
158
+          // Build message
159
+          dict = {
160
+            'status': message,
161
+          };
162
+
163
+          // Send the message
164
+          Pebble.sendAppMessage(dict, function(e) {
165
+            console.log('sent');
166
+          }, function() {
167
+            console.log('failed');
168
+          }); 
169
+        }
170
+      }
171
+    }else {
172
+      console.log('------Request returned error code ' + xhr.status.toString());
173
+    }
174
+  }
175
+ 
176
+
177
+}
178
+
179
+
180
+// Get AppMessage events
181
+Pebble.addEventListener('appmessage', function(e) {
182
+  // Get the dictionary from the message
183
+  var dict = e.payload;
184
+  
185
+  switch (dict[0]) {
186
+    case 'get':
187
+      get_status();
188
+      break;
189
+    case 'home_on':
190
+      switch_home(true);
191
+      break;
192
+    case 'home_off':
193
+      switch_home(false);
194
+      break;
195
+    default:
196
+      console.log('Sorry.');
197
+}
198
+  
199
+});
200
+
201
+// Get Configuration page 
202
+Pebble.addEventListener('showConfiguration', function() {
203
+  var username=localStorage.getItem('username');
204
+  var password=localStorage.getItem('password');
205
+  var server=localStorage.getItem('server');
206
+  var  url = 'https://jonget.fr/pebble/config_homeswitch.php?username='+username+'&password='+password+'&server='+server;
207
+  
208
+  Pebble.openURL(url);
209
+});
210
+
211
+Pebble.addEventListener('webviewclosed', function(e) {
212
+  // Decode the user's preferences
213
+  var configData = JSON.parse(decodeURIComponent(e.response));
214
+  localStorage.setItem('username',configData.username);
215
+  localStorage.setItem('password',configData.password);
216
+  localStorage.setItem('server',configData.server);
217
+  console.log('---- new username stored : '+localStorage.getItem('username'));
218
+  console.log('---- new password stored : '+localStorage.getItem('password'));
219
+  console.log('---- new server stored : '+localStorage.getItem('server'));
220
+  var dict = {
221
+    'username': configData.username,
222
+    'password': configData.password,
223
+    'server': configData.server
224
+  };
225
+            
226
+  // Send the message
227
+  Pebble.sendAppMessage(dict, function(e) {
228
+    console.log('sent');
229
+  }, function() {
230
+    console.log('failed');
231
+  }); 
232
+});
0 233
\ No newline at end of file