-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathfbxosctrl.py
More file actions
executable file
·1373 lines (1149 loc) · 47.7 KB
/
fbxosctrl.py
File metadata and controls
executable file
·1373 lines (1149 loc) · 47.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
########################################################################
# Nothing expected to be modified below this line... unless bugs fix ;-)
########################################################################
import argparse
import os
import sys
import json
import requests
import hmac
from zeroconf import Zeroconf
from datetime import datetime, timedelta
FBXOSCTRL_VERSION = "2.4.5"
__author__ = "Christophe Lherieau (aka skimpax)"
__copyright__ = "Copyright 2019, Christophe Lherieau"
__credits__ = []
__license__ = "GPL"
__version__ = FBXOSCTRL_VERSION
__maintainer__ = "skimpax"
__email__ = "skimpax@gmail.com"
__status__ = "Production"
# Return code definitions
RC_OK = 0
RC_WIFI_OFF = 0
RC_WIFI_ON = 1
# Descriptor of this app presented to FreeboxOS server to be granted
g_app_desc = {
"app_id": "fr.freebox.fbxosctrl",
"app_name": "Skimpax FbxOSCtrl",
"app_version": "2.0.0",
"device_name": "FbxOS Client"
}
g_log_enabled = False
def log(what):
"""Logger function"""
global g_log_enabled
if g_log_enabled:
print(what)
def enable_log(is_enabled):
"""Update log state"""
global g_log_enabled
g_log_enabled = is_enabled
class FbxException(Exception):
""" Exception for FreeboxOS domain """
def __init__(self, reason):
self.reason = reason
def __str__(self):
return self.reason
class FbxConfiguration:
"""Configuration/registration management"""
def __init__(self, app_desc):
"""Constructor"""
self._app_desc = app_desc
self._addr_file = 'fbxosctrl_addressing.txt'
self._reg_file = 'fbxosctrl_registration.txt'
self._addr_params = None
self._reg_params = None
self._resp_as_json = False
self._conf_path = '.'
@property
def freebox_address(self):
url = '{}://{}:{}'.format(
self._addr_params['protocol'],
self._addr_params['api_domain'],
self._addr_params['port'])
return url
@property
def app_desc(self):
return self._app_desc
@property
def reg_file(self):
return self._reg_file
@reg_file.setter
def reg_file(self, reg_file):
self._reg_file = reg_file
@property
def reg_params(self):
return self._reg_params
@reg_params.setter
def reg_params(self, reg_params):
self._reg_params = reg_params
self._save_registration_params()
@property
def resp_as_json(self):
return self._resp_as_json
@resp_as_json.setter
def resp_as_json(self, resp_as_json):
self._resp_as_json = resp_as_json
@property
def conf_path(self):
return self._conf_path
@conf_path.setter
def conf_path(self, conf_path):
log('>>> conf_path: {}'.format(conf_path))
if conf_path.endswith('/'):
conf_path = conf_path[:-1]
self._conf_path = conf_path
self._addr_file = self._conf_path + '/' + self._addr_file
self._reg_file = self._conf_path + '/' + self._reg_file
def load(self, want_regapp):
"""Load configuration params"""
log('>>> load')
self._load_addressing_params()
self._load_registration_params()
if self._reg_params is None:
if not want_regapp:
print('No registration params found in directory: {}'.format(self._conf_path))
print("You should launch 'fbxosctrl --regapp' once to register to the Freebox Server first.")
sys.exit(0)
else:
# use wants to register: this is normal not having reg params yet
pass
else:
url = self.freebox_address
if not self.resp_as_json:
# print only if not in JSON format
print('Freebox Server is accessible via: {}'.format(url))
def has_registration_params(self):
""" Indicate whether registration params look initialized """
log('>>> has_registration_params')
if (self._reg_params and
self._reg_params.get('track_id') != None and
self._reg_params.get('app_token') != ''):
return True
else:
return False
def api_address(self, api_url=None):
"""Build the full API URL based on the mDNS info"""
url = '{freebox_addr}{api_base_url}v{major_api_version}'.format(
freebox_addr=self.freebox_address,
api_base_url=self._addr_params['api_base_url'],
major_api_version=self._addr_params['api_version'][:1])
if api_url:
if api_url[0] != '/':
url += '/'
url += '{}'.format(api_url)
return url
def _fetch_fbx_mdns_info_via_mdns(self):
print('Querying mDNS about Freebox Server information...')
info = {}
try:
r = Zeroconf()
serv_info = r.get_service_info('_fbx-api._tcp.local.', 'Freebox Server._fbx-api._tcp.local.')
info['api_domain'] = serv_info.properties[b'api_domain'].decode()
info['https_available'] = True if serv_info.properties[b'https_available'] == b'1' else False
info['https_port'] = int(serv_info.properties[b'https_port'])
info['api_base_url'] = serv_info.properties[b'api_base_url'].decode()
info['api_version'] = serv_info.properties[b'api_version'].decode()
r.close()
except Exception:
print('Unable to retrieve configuration, assuming bridged mode')
d = requests.get("http://mafreebox.freebox.fr/api_version")
data = d.json()
info['api_domain'] = data['api_domain']
info['https_available'] = data['https_available']
info['https_port'] = data['https_port']
info['api_base_url'] = data['api_base_url']
info['api_version'] = data['api_version']
return info
def _save_registration_params(self):
""" Save registration parameters (app_id/token) to a local file """
log('>>> save_registration_params')
with open(self._reg_file, 'w') as of:
json.dump(self._reg_params, of, indent=True, sort_keys=True)
def _load_addressing_params(self):
"""Load existing addressing params or get them via mDNS"""
if os.path.exists(self._addr_file):
with open(self._addr_file) as infile:
self._addr_params = json.load(infile)
elif self._addr_params is None:
mdns_info = self._fetch_fbx_mdns_info_via_mdns()
log('Freebox mDNS info: {}'.format(mdns_info))
self._addr_params = {}
self._addr_params['protocol'] = 'https' if mdns_info['https_available'] else 'http'
self._addr_params['api_domain'] = mdns_info['api_domain']
self._addr_params['port'] = mdns_info['https_port']
self._addr_params['api_base_url'] = mdns_info['api_base_url']
self._addr_params['api_version'] = mdns_info['api_version']
with open(self._addr_file, 'w') as of:
json.dump(self._addr_params, of, indent=True, sort_keys=True)
def _load_registration_params(self):
log('>>> load_registration_params: file: {}'.format(self._reg_file))
if os.path.exists(self._reg_file):
with open(self._reg_file) as infile:
self._reg_params = json.load(infile)
class FbxResponse:
""""Response from Freebox"""
@staticmethod
def build(jsonresp):
"""Constructor"""
return FbxResponse(jsonresp)
def __init__(self, jsonresp):
"""Constructor"""
# convert to obj
self._resp = json.loads(jsonresp)
# expected content checks
if self._resp.get('success') is None:
raise FbxException('Mandatory field missing: success')
elif self._resp.get('success') != True and self._resp['success'] != False:
raise FbxException('Field success must be either true or false')
if self._resp['success'] is False:
if self._resp.get('msg') is None:
raise FbxException('Mandatory error field missing: msg')
if self._resp.get('error_code') is None:
raise FbxException('Mandatory error field missing: error_code')
@property
def whole_content(self):
"""Return operation whole response"""
return self._resp
@property
def success(self):
"""Return operation success status"""
return self._resp.get('success')
@property
def result(self):
"""Return operation success result"""
return self._resp.get('result')
@property
def error_msg(self):
"""Return operation error message"""
return self._resp.get('msg')
@property
def error_code(self):
"""Return operation error code"""
return self._resp.get('error_code')
class FbxHttp():
""""HTTP transporter"""
def __init__(self, conf):
"""Constructor"""
self._conf = conf
self._http_timeout = 30
self._is_logged_in = False
self._challenge = None
self._session_token = None
self._certificates_file = 'fbxosctrl_certificates.txt'
self._make_certificate_chain()
def __del__(self):
"""Logout on deletion"""
if self._is_logged_in:
try:
self._logout()
except Exception:
pass
@property
def headers(self):
"""Build headers"""
h = {'Content-type': 'application/json', 'Accept': 'application/json'}
if self._session_token != None:
h['X-Fbx-App-Auth'] = self._session_token
return h
def get(self, uri, timeout=None, no_login=False):
"""GET request"""
log(">>> get")
if not no_login:
self._login()
url = self._conf.api_address(uri)
log('GET url: {}'.format(url))
r = requests.get(
url,
verify=self._certificates_file,
headers=self.headers,
timeout=timeout if timeout != None else self._http_timeout)
log('GET response: {}'.format(r.text))
# ensure status_code is 200, else raise exception
if requests.codes.ok != r.status_code:
raise FbxException('GET error - http_status: {} {}'.format(r.status_code, r.text))
return FbxResponse.build(r.text)
def put(self, uri, data, timeout=None, no_login=False):
"""PUT request"""
log(">>> put")
if not no_login:
self._login()
url = self._conf.api_address(uri)
jdata = json.dumps(data)
log('PUT url: {} data: {}'.format(url, jdata))
r = requests.put(
url,
verify=self._certificates_file,
data=jdata,
headers=self.headers,
timeout=timeout if timeout != None else self._http_timeout)
log('PUT response: {}'.format(r.text))
# ensure status_code is 200, else raise exception
if requests.codes.ok != r.status_code:
raise FbxException('PUT error - http_status: {} {}'.format(r.status_code, r.text))
return FbxResponse.build(r.text)
def post(self, uri, data={}, timeout=None, no_login=False):
"""POST request"""
log(">>> post")
if not no_login:
self._login()
url = self._conf.api_address(uri)
jdata = json.dumps(data)
log('POST url: {} data: {}'.format(url, jdata))
r = requests.post(
url,
verify=self._certificates_file,
data=jdata,
headers=self.headers,
timeout=timeout if timeout != None else self._http_timeout)
log('POST response: {}'.format(r.text))
# ensure status_code is 200, else raise exception
if requests.codes.ok != r.status_code:
raise FbxException('POST error - http_status: {} {}'.format(r.status_code, r.text))
return FbxResponse.build(r.text)
def _login(self):
""" Login to FreeboxOS using API credentials """
log(">>> _login")
if not self._is_logged_in:
self._session_token = None
# 1st stage: get challenge
resp = self.get('/login', no_login=True)
if resp.success:
if not resp.result.get('logged_in'):
self._challenge = resp.result.get('challenge')
else:
raise FbxException('Challenge failure: {}'.format(resp))
# 2nd stage: open a session
app_token = self._conf.reg_params.get('app_token')
log('challenge: {}, apptoken: {}'.format(self._challenge, app_token))
# Hashing token with key
password = hmac.new(app_token.encode(), self._challenge.encode(), 'sha1').hexdigest()
uri = '/login/session/'
payload = {'app_id': self._conf.app_desc.get('app_id'), 'password': password}
# post it
resp = self.post(uri, payload, no_login=True)
if resp.success:
self._session_token = resp.result.get('session_token')
permissions = resp.result.get('permissions')
log('Permissions: {}'.format(permissions))
if not permissions.get('settings'):
print(
"Warning: permission 'settings' has not been allowed yet" +
' in FreeboxOS server. This script may fail!')
else:
raise FbxException('Session failure: {}'.format(resp))
# set headers for next dialogs
self._is_logged_in = True
def _logout(self):
""" logout from FreeboxOS """
log(">>> _logout")
if self._is_logged_in:
url = self._conf.api_address('/login/logout/')
resp = self._http.post(url, headers=self.headers)
# reset headers as no more dialogs expected
self._http_headers = None
if not resp.success:
raise FbxException('Logout failure: {}'.format(resp))
self._session_token = None
self._is_logged_in = False
def _make_certificate_chain(self):
"""Store the certificate chain required for HTTPS"""
with open(self._certificates_file, 'w') as of:
of.write(
# see https://dev.freebox.fr/sdk/os/# for content below
"""-----BEGIN CERTIFICATE-----
MIICWTCCAd+gAwIBAgIJAMaRcLnIgyukMAoGCCqGSM49BAMCMGExCzAJBgNVBAYT
AkZSMQ8wDQYDVQQIDAZGcmFuY2UxDjAMBgNVBAcMBVBhcmlzMRMwEQYDVQQKDApG
cmVlYm94IFNBMRwwGgYDVQQDDBNGcmVlYm94IEVDQyBSb290IENBMB4XDTE1MDkw
MTE4MDIwN1oXDTM1MDgyNzE4MDIwN1owYTELMAkGA1UEBhMCRlIx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lyHXXODUfV3arLCwFoNB+IIrde1E/JoOry9oKvF8DZTo/Qm6o2KsdZ
dxs/YcIUsCvKX8WCKtH6la/kFCUcXIb8f1u+Y4pjj3PBmKI/1+Rs9GqB0kt1otyx
Q6bqxqBSgsrkuhCfRxwjbfBgmXjIZ/a4muY5uMI0gbl9zbMFEJHDojhH6TUB5qd0
JJlI61gldaT5Ci1aLbvVcJtdeGhElf7pOE9JrXINpP3NOJJaUSueAvxyj/WWoo0v
4KO7njox8F6jCHALNDLdTsX0FTGmUZ/s/QfJry3VNwyjCyWDy1ra4KWoqt6U7SzM
d5jENIZChM8TnDXJzqc+mu00cI3icn9bV9flYCXLTIsprB21wVSMh0XeBGylKxeB
S27oDfFq04XSox7JM9HdTt2hLK96x1T7FpFrBTnALzb7vHv9MhXqAT90fPR/8A==
-----END CERTIFICATE-----
""")
class FbxService:
""""Service base class"""
def __init__(self, http, conf):
"""Constructor"""
self._http = http
self._conf = conf
def get_service_data(self, uri):
"""Get service data"""
resp = self._http.get(uri)
if not resp.success:
raise FbxException('Request failure: {}'.format(resp))
return resp
class FbxServiceAuth(FbxService):
""""Authentication domain"""
def __init__(self, http, conf):
"""Constructor"""
super().__init__(http, conf)
self._registered = False
def is_registered(self):
""" Check that the app is currently registered (granted) """
log(">>> is_registered")
if self._registered:
return True
self._registered = (self.get_registration_status() == 'granted')
return self._registered
def get_registration_status(self):
""" Get the current registration status thanks to the track_id """
log(">>> get_registration_status")
if self._conf.has_registration_params():
uri = '/login/authorize/{}'.format(self._conf.reg_params.get('track_id'))
resp = self._http.get(uri, no_login=True)
return resp.result.get('status')
else:
return "Not registered yet!"
def get_registration_status_diagnostic(self):
""" Get the current registration status and display diagnosic """
log(">>> get_registration_status_diagnostic")
status = self.get_registration_status()
track_id = self._conf.reg_params.get('track_id')
if 'granted' == status:
print(
'This app is already granted on Freebox Server' +
' (track_id={}).'.format(track_id) + ' You can now dialog with it.')
elif 'pending' == status:
print(
'This app grant is still pending: user should grant it' +
' on Freebox Server lcd/touchpad (track_id = {}).'
.format(track_id))
elif 'unknown' == status:
print(
'This track_id ({}) is unknown by Freebox Server: '.format(track_id) +
'you have to register again to Freebox Server to get a new app_id.')
elif 'denied' == status:
print(
'This app has been denied by user on Freebox Server (track_id = {}).'
.format(self._conf.reg_params.get('track_id')))
elif 'timeout' == status:
print(
'Timeout occured for this app_id: you have to register again' +
' to Freebox Server to get a new app_id (current track_id = {}).'
.format(track_id))
else:
print('Unexpected response: {}'.format(status))
return status
def register_app(self):
""" Register this app to FreeboxOS to that user grants this apps via Freebox Server
LCD screen. This command shall be executed only once. """
log(">>> register_app")
register = True
if self._conf.has_registration_params():
status = self.get_registration_status_diagnostic()
if 'granted' == status:
register = False
if register:
self._conf._load_addressing_params()
uri = '/login/authorize/'
data = self._conf.app_desc
# post it
resp = self._http.post(uri, data=data, no_login=True)
# save registration params
if resp.success:
params = {
'app_token': resp.result.get('app_token'),
'track_id': resp.result.get('track_id')}
self._conf.reg_params = params
print(
'Now you have to accept this app on your Freebox server:' +
' take a look on its LCD screen.')
print(input('Press Enter key once you have accepted on LCD screen: '))
# check new status (it seems to be mandatory to reach in 'granted' state)
status = self.get_registration_status_diagnostic()
print('{}'.format('OK' if 'granted' == status else 'NOK'))
else:
print('NOK')
class FbxServiceSystem(FbxService):
"""System domain"""
def reboot(self):
""" Reboot the freebox server now! """
log(">>> reboot")
uri = '/system/reboot/'
self._http.post(uri, timeout=3)
return True
def get_system_info(self):
"""Retrieve the system info"""
uri = '/system'
resp = self._http.get(uri)
if self._conf.resp_as_json:
return resp.whole_content
print('Server info:')
print(' - Model: {}'.format(resp.result['model_info']['pretty_name']))
print(' - MAC: {}'.format(resp.result['mac']))
print(' - Firmware: {}'.format(resp.result['firmware_version']))
print(' - Uptime: {}'.format(resp.result['uptime']))
print(' - Sensors:')
for sensor in resp.result['sensors']:
unit = '°C' if sensor['id'].startswith('temp_') else ''
print(' - {:20} {}{}'.format(sensor['name'] + ':', sensor['value'], unit))
return True
class FbxServiceConnection(FbxService):
"""Connection domain"""
@staticmethod
def rate_to_human_readable(bps):
"""Convert bits per seconds to human readable format"""
if bps > 1000000:
return '{:.2f} Mb/s ({:.1f} MB/s)'.format(bps/1000000, bps/1000000/8)
elif bps > 1000:
return '{:.1f} Kb/s ({:.1f} KB/s)'.format(bps/1000, bps/1000/8)
elif bps:
return '{} b/s ({} B/s)'.format(bps, bps/8)
def get_line_ethernet_info(self):
uri = '/connection'
resp = self._http.get(uri)
if self._conf.resp_as_json:
return resp.whole_content
print('Ethernet info:')
print(' - Info:')
print(' - IPv4: {}'.format(resp.result['ipv4']))
print(' - IPv6: {}'.format(resp.result['ipv6']))
print(' - Media: {}'.format(resp.result['media']))
print(' - State: {}'.format(resp.result['state']))
print(' - Down:')
print(
' - Bandwidth: {}'
.format(FbxServiceConnection.rate_to_human_readable(resp.result['bandwidth_down'])))
print(
' - Current rate: {}'
.format(FbxServiceConnection.rate_to_human_readable(resp.result['rate_down'])))
print(' - Up:')
print(
' - Bandwidth: {}'
.format(FbxServiceConnection.rate_to_human_readable(resp.result['bandwidth_up'])))
print(
' - Current rate: {}'
.format(FbxServiceConnection.rate_to_human_readable(resp.result['rate_up'])))
return True
def get_line_media_info(self):
"""Retieve xDSL or FTTH info"""
uri = '/connection'
resp = self._http.get(uri)
if resp.result['media'] == 'ftth':
return self._get_ftth_info()
else:
return self._get_xdsl_info()
def _get_xdsl_info(self):
"""Retrieve the xDSL info"""
uri = '/connection/xdsl'
resp = self._http.get(uri)
if self._conf.resp_as_json:
return resp.whole_content
print('xDSL info:')
print(' - Status:')
for k, v in resp.result['status'].items():
print(' - {:13} {}'.format(k+':', v))
down = resp.result['down']
print(' - Down:')
print(
' - Max Rate: {}'
.format(FbxServiceConnection.rate_to_human_readable(down['rate']*1000)))
print(' - Attenuation: {} dB'.format(down['attn_10']/10))
print(' - Noise magin: {} dB'.format(down['snr_10']/10))
up = resp.result['up']
print(' - Up:')
print(
' - Max Rate: {}'
.format(FbxServiceConnection.rate_to_human_readable(up['rate']*1000)))
print(' - Attenuation: {} dB'.format(up['attn_10']/10))
print(' - Noise magin: {} dB'.format(up['snr_10']/10))
return True
def _get_ftth_info(self):
"""Retrieve the FTTH info"""
uri = '/connection/ftth'
resp = self._http.get(uri)
if self._conf.resp_as_json:
return resp.whole_content
if resp.result['has_sfp'] != True and resp.result['sfp_present'] != True:
print('No SFP module detected')
return False
print('FTTH info:')
print(' - SPF Module:')
print(' - Model: {}'.format(resp.result['sfp_model']))
print(' - Vendor {}'.format(resp.result['sfp_vendor']))
print(' - Serial: {}'.format(resp.result['sfp_serial']))
print(' - Status:')
print(' - Signal: {}'.format(resp.result['sfp_has_signal']))
print(' - Alim: {}'.format(resp.result['sfp_alim_ok']))
# print(' - Powered: {}'.format(resp.result['sfp_has_power_report']))
if resp.result['link'] != True:
print(' - Link: {}'.format(resp.result['link']))
else:
print(' - Link:')
print(' - Tx: {} dB'.format(resp.result['sfp_pwr_tx']/100))
print(' - Rx: {} dB'.format(resp.result['sfp_pwr_rx']/100))
return True
class FbxServiceStorage(FbxService):
"""Storage domain"""
def get_connected_drives(self):
"""Retrieve the spining state for drives"""
uri = '/storage/disk/'
resp = self._http.get(uri)
if self._conf.resp_as_json:
return resp.whole_content
print('Drives connected :')
for drive in resp.result:
model = drive['model']
serial = drive['serial']
if model == '':
model = '_no_brand_'
if serial == '':
serial = '_no_serial_'
temp = drive['temp']
spinning = drive['spinning']
print(' - {} ({}) | temp: {} | spining: {}'.format(model, serial, temp, spinning))
return True
def get_storage_status(self):
"""Retrieve the storage partitions and spaces"""
uri = '/storage/disk/'
resp = self._http.get(uri)
if self._conf.resp_as_json:
return resp.whole_content
print('Storage info:')
for drive in resp.result:
model = drive['model']
if model == '':
model = '_no_brand_'
print(' - {}'.format(model))
for part in drive['partitions']:
if part['total_bytes'] > pow(1024, 3):
total = part['total_bytes'] / pow(1024, 3)
avail = part['free_bytes'] / pow(1024, 3)
used = part['used_bytes'] / pow(1024, 3)
unit = 'Go'
else:
total = part['total_bytes'] / pow(1024, 2)
avail = part['free_bytes'] / pow(1024, 2)
used = part['used_bytes'] / pow(1024, 2)
unit = 'Mo'
free_percent = avail * 100 / total
print(
' #{:15s} :\t'.format(part['label']) +
'total: {value:4.0f}{unit} |'.format(value=total, unit=unit) +
' used: {value:4.0f}{unit} |'.format(value=used, unit=unit) +
' free: {value:4.0f}{unit}'.format(value=avail, unit=unit) +
' ({value:.1f}{unit} free)'.format(value=free_percent, unit='%'))
return True
class FbxServiceWifi(FbxService):
"""Wifi domain"""
def get_wifi_config(self):
"""Get the current wifi config"""
uri = '/wifi/config/'
resp = self._http.get(uri)
return resp
def get_wifi_radio_state(self):
""" Get the current status of wifi radio: 1 means ON, 0 means OFF """
log('>>> get_wifi_radio_state')
uri = '/wifi/config/'
resp = self._http.get(uri)
if self._conf.resp_as_json:
return resp.whole_content
is_on = resp.success and resp.result.get('enabled')
print('Wifi is {}'.format('ON' if is_on else 'OFF'))
return is_on
def set_wifi_radio_on(self):
self._set_wifi_radio_state(True)
def set_wifi_radio_off(self):
self._set_wifi_radio_state(False)
def _set_wifi_radio_state(self, set_on):
""" Utility to activate or deactivate wifi radio module """
log('>>> set_wifi_radio_state {}'.format('ON' if set_on else 'OFF'))
# PUT wifi status
uri = '/wifi/config/'
data = {'enabled': True} if set_on else {'enabled': False}
timeout = 3 if not set_on else None
# PUT
try:
resp = self._http.put(uri, data=data, timeout=timeout)
except requests.exceptions.Timeout as exc:
if not set_on:
# If we are connected using wifi, disabling wifi will close connection
# thus PUT response will never be received: a timeout is expected
print('Wifi radio is now OFF')
return 0
else:
# Forward timeout exception as should not occur
raise exc
if not resp.success:
raise FbxException('Request failure: {}'.format(resp))
if self._conf.resp_as_json:
return resp.whole_content
is_on = resp.result.get('enabled')
print('Wifi radio is now {}'.format('ON' if is_on else 'OFF'))
return is_on
def get_wifi_planning(self):
""" Get the current status of wifi: 1 means planning enabled, 0 means no planning """
log('>>> get_wifi_planning')
uri = '/wifi/planning/'
resp = self._http.get(uri)
if self._conf.resp_as_json:
return resp.whole_content
is_on = resp.success and resp.result.get('use_planning')
print('Wifi planning is {}'.format('ON' if is_on else 'OFF'))
return is_on
def set_wifi_planning_on(self):
self._set_wifi_planning(True)
def set_wifi_planning_off(self):
self._set_wifi_planning(False)
def _set_wifi_planning(self, set_on):
""" Utility to activate or deactivate wifi planning mode """
log('>>> set_wifi_planning {}'.format('ON' if set_on else 'OFF'))
# PUT wifi planning
url = '/wifi/planning/'
data = {'use_planning': True} if set_on else {'use_planning': False}
resp = self._http.put(url, data=data)
if not resp.success:
raise FbxException('Request failure: {}'.format(resp))
if self._conf.resp_as_json:
return resp.whole_content
is_on = resp.result.get('use_planning')
print('Wifi planning is now {}'.format('ON' if is_on else 'OFF'))
return is_on
class FbxServiceDhcp(FbxService):
"""DHCP domain"""
def get_config(self):
"""Get the current DHCP config"""
uri = '/dhcp/config/'
resp = self._http.get(uri)
return resp
def get_dhcp_leases(self):
""" List the DHCP leases on going"""
log(">>> get_dhcp_leases")
# GET wifi status
uri = '/dhcp/dynamic_lease/'
resp = self._http.get(uri)
if not resp.success:
raise FbxException('Request failure: {}'.format(resp))
# json response format
if self._conf.resp_as_json:
return resp.whole_content
# human response format
leases = resp.result
if leases is None:
print('No DHCP leases')
return 0
def display_lease_entry(count, lease):
print(
' #{}: mac: {}, ip: {}, hostname: {}, static: {}'
.format(
count, lease.get('mac'), lease.get('ip'),
lease.get('hostname'), lease.get('is_static')))
count = 1
print('List of reachable leases:')
for lease in leases:
if 'host' in lease and lease.get('host').get('reachable'):
display_lease_entry(count, lease)
count += 1
count = 1
print('List of unreachable leases:')
for lease in leases:
if 'host' in lease and not lease.get('host').get('reachable'):
display_lease_entry(count, lease)
count += 1
count = 1
print('List of other leases:')
for lease in leases:
if 'host' not in lease:
display_lease_entry(count, lease)
count += 1
return 0
class FbxServicePortForwarding(FbxService):
"""Port Forwarding"""
def get_port_forwardings(self):
""" List the port forwarding on going"""
uri = '/fw/redir/'
resp = self._http.get(uri)
if not resp.success:
raise FbxException('Request failure: {}'.format(resp))
# json response format
if self._conf.resp_as_json:
return resp.whole_content
# human response format
pforwardings = resp.result
if pforwardings is None:
print('No port forwarding')
return 0
def display_port_forwarding_entry(count, pforwarding):
data = ' #{}: id: {}, enabled: {}, hostname: {}, comment: {},\n'
data += ' lan_port: {}, wan_port_start: {}, wan_port_end: {}\n'
data += ' src_ip: {}, lan_ip: {}, ip_proto: {}'
print(data.format(
count, pforwarding.get('id'), pforwarding.get('enabled'),
pforwarding.get('hostname'), pforwarding.get('comment'), pforwarding.get('lan_port'),
pforwarding.get('wan_port_start'), pforwarding.get('wan_port_end'),
pforwarding.get('src_ip'), pforwarding.get('lan_ip'), pforwarding.get('ip_proto')))
count = 1
print('List of reachable leases:')
for pforwarding in pforwardings:
display_port_forwarding_entry(count, pforwarding)
count += 1
return 0
class FbxServiceCall(FbxService):
"""Call domain"""
def get_new_calls_list(self):