-
Notifications
You must be signed in to change notification settings - Fork 0
/
nas_script.py
4079 lines (3537 loc) · 140 KB
/
nas_script.py
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
#-------------- Base NAS Script v1.0 beta --------------#
# #
# Created by: Marus Alexander (Romania/Europe) #
# Contact and bug report: marus.gradinaru@gmail.com #
# Website link: https://marus-gradinaru.42web.io #
# Donation link: https://revolut.me/marusgradinaru #
# #
#-------------------------------------------------------#
# Note:
# Currently, the power button has been disabled. After I built the first prototype, I discovered that the power button
# was not working properly, because of a design flaw. So, I redesigned it, as you can see in the schematics, and now
# I'm in the process of testing the second version. Please check the website later for the fully functional code.
# ======================== USER INPUT PARAMETERS ===============================
# ----- GPIO pin definitions ----------
RPiChip = '/dev/gpiochip0'
SDReadyPin = 13 # Output Shutdown ready pin number, high = safe to shutdown
SDReqPin = 26 # Input Pull-UP Rising Bounce=10ms Shutdown request pin number, low to high = shutdown requested
RpmPin = 24 # Input Pull-UP Falling Fan RPM pin
UAlertPin = 17 # Input Pull-DOWN Rising UPS I2C alert pin
NAlertPin = 4 # Input Pull-UP NAS I2C alert pin
# ----- NAS settings -------------------
NasName = 'NAS' # The name of the shared Samba NasRoot
NasRoot = '/NAS' # NAS Root folder where to mount all block devices
NasPerms = 0o2770 # NAS Root folder and mounted drives content permisions (2: setgid bit - all created files inherit NAS group)
NasGroup = 'rpinas' # NAS permission group name
# ----- Other settings -----------------
SDCountdown = 300 # Low battery shutdown countdown timer (seconds)
# ========================== BASIC SETUP ===================================
import sys, os, time, importlib, subprocess
from datetime import datetime
# --- Color codes -------
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
EXCEPT = '\033[38;5;147m' # light purple
RESET = '\033[0m'
EventColor = ['', GREEN, YELLOW, RED]
AppLogFile = '/tmp/rpinas_log.txt'
def LogD(level, msg):
try:
with open(AppLogFile, 'a') as appLog:
DT = datetime.now()
TimeStamp = '{:02d}:{:02d}:{:02d}, {:02d}-{:02d}-{:04d}'.format(DT.hour, DT.minute, DT.second, DT.day, DT.month, DT.year)
appLog.write(f'{TimeStamp} [ Level: {level} ] - {msg}\n')
except: pass
LogD(0, 'App started'+'-'*40)
ParamList = sys.argv[1:]
Debug = not any(param == '-sys' for param in ParamList)
InstDeps = Debug and any(param.startswith('-install') for param in ParamList) and not any(param == '-nodeps' for param in ParamList)
if os.geteuid() != 0:
if Debug: print("This script must be run as root. Please try again with 'sudo'.")
sys.exit(1)
# ======================= INSTALL DEPENDENCIES ===============================
def MinVersion(item_ver, min_ver):
if (min_ver == None) or (min_ver == ''): return True
item_parts = list(map(int, item_ver.split('.')))
min_parts = list(map(int, min_ver.split('.')))
for i in range(max(len(item_parts), len(min_parts))):
item_part = item_parts[i] if i < len(item_parts) else 0
min_part = min_parts[i] if i < len(min_parts) else 0
if item_part > min_part: return True
elif item_part < min_part: return False
return True
def CheckInstImp(item):
if isinstance(item, list):
item_name = item[0]
min_ver = item[1]
cmd_purge = ['apt', 'purge', '-y'] + item[2:]
else:
item_name = item
min_ver = ''
cmd_purge = []
if item_name.startswith('python3-'): item_name = item_name[8:]
try: item_obj = importlib.import_module(item_name)
except: return False
if min_ver != '':
item_ver = item_obj.__version__
if not MinVersion(item_ver, min_ver):
if len(cmd_purge) > 3:
print(f' - Removing old version of: {item_name} (v{item_ver}) ... ', end='', flush=True)
try:
result = subprocess.run(cmd_purge, capture_output=True, text=True)
except:
print(RED+'Failed !'+RESET)
raise
if result.returncode == 0:
print(GREEN+'Done.'+RESET)
time.sleep(0.6)
return False
else:
print(RED+'Failed !'+RESET)
print(YELLOW+f' {result.stderr}'+RESET)
sys.exit(1)
else:
print(YELLOW+f'Internal error: Invalid uninstall command.'+RESET)
sys.exit(1)
return True
def CheckInstDpkg(item):
if isinstance(item, list):
item_name = item[0]
min_ver = item[1]
else:
item_name = item
min_ver = ''
result = subprocess.run(['dpkg', '-l', item_name], capture_output=True, text=True)
if result.returncode == 0:
Lines = result.stdout.splitlines()
for line in Lines:
words = line.split(maxsplit=2)[:2]
if (len(words) == 2) and (words[0] == 'ii') and (words[1] == item_name): return True
return False
if InstDeps:
try:
SysDeps = [
[ CheckInstDpkg, ['apt', 'install', '-y'], ['python3-pip', 'samba', 'samba-common-bin', 'smbclient', 'hdparm', 'smartmontools'] ],
[ CheckInstImp, ['apt', 'install', '-y'], ['python3-psutil', 'python3-netifaces', 'python3-pyudev', 'python3-dbus'] ],
[ CheckInstImp, ['pip3', 'install', '--break-system-packages'], [
['gpiod', '2', 'gpiod', 'libgpiod2', 'python3-libgpiod'] ] ]
] # to install, min.ver, to remove...
print('Checking dependencies...')
for dlist in SysDeps:
CheckInstalled = dlist[0];
for item in dlist[2]:
item_name = item[0] if isinstance(item, list) else item
command = dlist[1] + [item_name]
if not CheckInstalled(item):
print(f' - Installing required dependence: {item_name} ... ', end='', flush=True)
try:
result = subprocess.run(command, capture_output=True, text=True)
except:
print(RED+'Failed !'+RESET)
raise
if result.returncode == 0:
print(GREEN+'Done.'+RESET)
time.sleep(0.6)
else:
print(RED+'Failed !'+RESET)
print(YELLOW+f' {result.stderr}'+RESET)
sys.exit(1)
print('All dependencies are installed.\n')
# Restart the script in normal mode (bypassing the depenenciess installation)
os.execv('/usr/bin/sudo', ['sudo', sys.executable] + sys.argv + ['-nodeps'])
except Exception as E:
print(YELLOW+f'Exception: {E}'+RESET)
sys.exit(1)
LogD(1, 'Passed dependencies install')
# ========================== IMPORT MODULES ==================================
# --- Internal Modules ----------
import os.path, socket, signal, threading, configparser, select, asyncio
import fcntl, struct, re, mmap, grp, pwd, traceback, shutil, pty, requests
from datetime import timedelta
# --- External Modules ----------
import gpiod, psutil, netifaces, pyudev
from smbus2 import SMBus
from gpiod.line import Edge, Bias, Direction
LogD(2, 'Modules imported')
# ========================== SYSTEM DEFINITIONS ==============================
# ----- Install Config ------------------
SambaCfgFile = '/etc/samba/smb.conf'
ServiceCfgFile = '/etc/systemd/system/nas_script.service'
RebootCfgFile = '/etc/systemd/system/systemd-reboot.service.d/99-nas-script-reboot.conf'
PwrOffCfgFile = '/etc/systemd/system/systemd-poweroff.service.d/99-nas-script-poweroff.conf'
FirmwareFile = '/boot/firmware/config.txt'
SambaNasCfg = [f'path = {NasRoot}', 'writeable = yes', 'inherit permissions = yes', 'public = no']
RebootCfg = ['ExecStartPre=python3 %RunPath%/nas_script.py -sys -reboot']
PwrOffCfg = ['ExecStartPre=python3 %RunPath%/nas_script.py -sys -shutdown']
FirmwarePwmCfg = ['dtoverlay=pwm,pin=18,func=2']
FirmwareLedCfg = ['dtoverlay=act-led,gpio=19']
FirmwareCfg = [FirmwarePwmCfg[0], FirmwareLedCfg[0]]
ServiceCfg = [
['Unit', 'Description=NAS Script', 'After=network.target'],
['Service', 'ExecStart=/usr/bin/python3 %RunPath%/nas_script.py -sys', 'WorkingDirectory=%RunPath%', 'StandardOutput=null',
'StandardError=null', 'Restart=no', 'User=root'],
['Install', 'WantedBy=multi-user.target']
]
FirmwareDel = ['dtoverlay=pwm', 'dtoverlay=act-led']
RebootSec = 'Service'
PwrOffSec = 'Service'
FirmwareSec = 'all'
# ----- I2C Section -----------------------
PicoAddr = 0x41
IntAddr = 0x48
HddAddr = 0x49
ExtAddr = 0x4F
cmdPowerOff = b'\xB1\x83\x6A\x4D'
cmdRstReady = b'\x83\xB1\xC7\xA6'
cmdShdReady = b'\xB1\x83\x6A\xC7'
cmdReadBat = b'\xA6\x3D\x81\xF7'
cmdReadTerm = b'\x52\xE9\x4B\x83'
regCMD = 0xBD # write: 4-byte commands / read: nothing
regRTC = 0x1C # write: 9-byte packed datetime / read: nothing
regAlert = 0x7A # write: nothing / read: 12 bytes (3 x 4-byte registers)
regMain = 0xE4 # write: nothing / read: 13 bytes
regFanCfg = 0x58 # write: 11 bytes / read nothing
regSilentCfg = 0x9B # write: 11 bytes / read nothing
regBatCfg = 0xD2 # write: 14 bytes / read nothing
regBatLow = 0xD3 # write: 2 bytes / read nothing
regShdState = 0xA6 # write: 1 bytes / read nothing
sigContinue = 0xCC
sigRetry = 0x33
sigStop = 0x69
stNone = b'\x01\x01\x01\x01'
stShdNow = b'\x57\xDF\x48\x9B'
stShdLow = b'\x84\x75\xB9\xFD'
stPowerON = b'\x72\xC4\x9A\x31'
stPowerOFF = b'\xA9\x27\x13\x4C'
stBatON = b'\x6E\x24\xA5\xD3'
stBatOFF = b'\x5A\xE6\x3D\x42'
stBatOver = b'\x41\xF8\xA5\x27'
# ----- TCP Server commands ---------------
COMP_CMDID = 0x24
ANDRO_CMDID = 0x25
RASPI_CMDID = 0x42
CMD_NONE = b'\x00\x00\x00\x00'
CMD_RPIREADY = b'\xDB\x00\x01\x10'
CMD_MESSAGE = b'\xDB\x00\x01\x11'
CMD_DEVICES = b'\xDB\x00\x01\x15'
CMD_DINFO = b'\xDB\x00\x01\x16'
CMD_RTINFO = b'\xDB\x00\x01\x17'
CMD_SMART = b'\xDB\x00\x01\x18'
CMD_UNMOUNT = b'\xDB\x00\x01\x19'
CMD_MOUNT = b'\xDB\x00\x01\x1A'
CMD_RTISTART = b'\xDB\x00\x01\x1B'
CMD_RTISTOP = b'\xDB\x00\x01\x1C'
CMD_NASRST = b'\xDB\x00\x01\x1D'
CMD_UPSSHD = b'\xDB\x00\x01\x1E'
CMD_NASSHD = b'\xDB\x00\x01\x1F'
CMD_ALLSHD = b'\xDB\x00\x01\x20'
CMD_SLEEP = b'\xDB\x00\x01\x21'
CMD_SRVRST = b'\xDB\x00\x01\x22'
CMD_GETBATVI = b'\xDB\x00\x01\x23'
CMD_UNLOCK = b'\xDB\x00\x01\x24'
CMD_READPF = b'\xDB\x00\x01\x25'
CMD_SETLABEL = b'\xDB\x00\x01\x26'
CMD_SYSLGET = b'\xDB\x00\x01\x27'
CMD_SYSLCLR = b'\xDB\x00\x01\x28'
CMD_GETUPSTERM = b'\xDB\x00\x01\x29'
CMD_GETNASTERM = b'\xDB\x00\x01\x2A'
CMD_CNTDOWN = b'\xDB\x00\x01\x2B'
CMD_THEEND = b'\xDB\x00\x01\x2C'
CMD_UPSRST = b'\xDB\x00\x01\x2D'
CMD_INSTCHECK = b'\xDB\x00\x01\x2E'
CMD_GETAPM = b'\xDB\x00\x01\x2F'
CMD_FAILED = b'\xDB\x00\x02\x01'
CMD_SUCCESS = b'\xDB\x00\x02\x02'
CMD_TESTMSG = b'\xDB\x00\x02\x03'
CMD_SETNETCFG = b'\xDB\x00\x02\x04'
CMD_SETNOTCFG = b'\xDB\x00\x02\x05'
CMD_SETSTBCFG = b'\xDB\x00\x02\x07'
CMD_SETNFANCFG = b'\xDB\x00\x02\x08'
CMD_SETUFANCFG = b'\xDB\x00\x02\x09'
CMD_SETSILCFG = b'\xDB\x00\x02\x0A'
CMD_SETBATCFG = b'\xDB\x00\x02\x0B'
CMD_SETBATLOW = b'\xDB\x00\x02\x0C'
CMD_SETAPMCFG = b'\xDB\x00\x02\x0D'
CMD_GETSMBPATH = b'\xDB\x00\x02\x0E'
CMD_STDOUTBUFF = b'\xDB\x00\x03\x01'
CMD_STDINBUFF = b'\xDB\x00\x03\x02'
CMD_TERMABORT = b'\xDB\x00\x03\x03'
CMD_UPGRADE = b'\xDB\x00\x03\x10'
CMD_REPAIRFS = b'\xDB\x00\x03\x11'
CMD_CHECKSTB = b'\xDB\x00\x03\x12'
CMD_SMBSTOP = b'\xDB\x00\x03\x13'
CMD_SMBSTART = b'\xDB\x00\x03\x14'
CMD_SMBRESTART = b'\xDB\x00\x03\x15'
CMD_SMBSTATUS = b'\xDB\x00\x03\x16'
CMD_DEBUG1 = b'\xDB\x00\x10\x01'
CMD_SETTOKEN = b'\xDB\x00\x20\x01'
CMD_SETLINK = b'\xDB\x00\x20\x02'
CMD_GETAMPOOL = b'\xDB\x00\x20\x03'
# ----- Main Exit -------------------------
exNone = 0
exRestartNAS = 1
exShutdownNAS = 2
exRestartUPS = 3
exShutdownUPS = 4
exShutdownALL = 5
ExitStr = ['exNone', 'exRestartNAS', 'exShutdownNAS', 'exRestartUPS', 'exShutdownUPS', 'exShutdownALL']
# ----- Other constants -------------------
# ----- Notifications ----------------------
OnlineMsg = 0
RebootMsg = 1
ShutdownMsg = 2
AppTermMsg = 3
HddPark1Msg = 4
HddPark0Msg = 5
MainLostMsg = 6
MainAvailMsg = 7
BatLowMsg = 8
BatSafeMsg = 9
BatLostMsg = 10
BatAvailMsg = 11
BatOvr1Msg = 12
BatOvr0Msg = 13
BrdMsg = [
'Raspberry Pi is back online: Main is {}, Batt is {}',
'Raspberry Pi is rebooting...',
'Raspberry Pi has been shut down !',
'Raspberry App has been terminated ({}).',
'All hard drives were successfully powered off: {}',
'Error while powering off device {}:\n{}',
'Warning: Main power is lost !',
'Main power is now available.',
'Warning: Battery voltage is low !',
'Battery voltage is now at a safe level.',
'Warning: Battery has been disconnected !',
'The battery has been reconnected.',
'Warning: Battery overvoltage detected !',
'Battery voltage is now at a safe level.']
SrvResetStr = 'The Raspberry server was restarted.'
PowerFailureMsg = 'Warning: power failure detected !'
# ----- Default Settings -------------------
DefaultSettings = """
[General]
FirstSysRun = true
[Network]
CompIP = none
CompPort = 0
RaspiIP = none
RaspiPort = 60303
[Firebase]
AppToken = none
FCMLink = none
[Notifications]
Online.comp = yes
Online.push = no
Online.log = no
Reboot.comp = yes
Reboot.push = no
Reboot.log = no
Shutdown.comp = yes
Shutdown.push = yes
Shutdown.log = no
AppTerm.comp = yes
AppTerm.push = yes
AppTerm.log = no
HddPark.comp = yes
HddPark.push = no
HddPark.log = no
MainLost.comp = yes
MainLost.push = yes
MainLost.log = yes
MainAvail.comp = yes
MainAvail.push = yes
MainAvail.log = yes
BatLow.comp = yes
BatLow.push = yes
BatLow.log = no
BatSafe.comp = yes
BatSafe.push = yes
BatSafe.log = no
BatLost.comp = yes
BatLost.push = yes
BatLost.log = yes
BatAvail.comp = yes
BatAvail.push = yes
BatAvail.log = yes
BatOvr1.comp = yes
BatOvr1.push = yes
BatOvr1.log = yes
BatOvr0.comp = yes
BatOvr0.push = yes
BatOvr0.log = yes
UseIdle = yes
IdleVal = 10
[Standby]
Enabled = yes
CheckPeriod = 60
Default = 5/30
[StandbyCustom]
[APM]
Enabled = yes
Default = 254
[ApmCustom]
[ApmAvail]
[Cooling]
NasFAuto = yes
NasLowTemp = 3800
NasHighTemp = 4100
NasLowDuty = 20
NasHighDuty = 100
NasFixDuty = 50
UpsFAuto = yes
UpsLowTemp = 3300
UpsHighTemp = 3600
UpsLowDuty = 20
UpsHighDuty = 100
UpsFixDuty = 50
[Silent]
Enabled = yes
StartHour = 22
StartMin = 30
StopHour = 8
StopMin = 0
MaxFDuty = 35
[Samba]
User = none
Pass = none
"""
NotifName = ['Online', 'Reboot', 'Shutdown', 'AppTerm', 'HddPark', 'MainLost', 'MainAvail', 'BatLow', 'BatSafe', 'BatLost', 'BatAvail', 'BatOvr1', 'BatOvr0']
NotifExt = ['.comp', '.push', '.log']
# ----- CRC 8 table -----------------------
crc8_tab = (
0, 105, 210, 187, 205, 164, 31, 118, 243, 154, 33, 72, 62, 87, 236, 133,
143, 230, 93, 52, 66, 43, 144, 249, 124, 21, 174, 199, 177, 216, 99, 10,
119, 30, 165, 204, 186, 211, 104, 1, 132, 237, 86, 63, 73, 32, 155, 242,
248, 145, 42, 67, 53, 92, 231, 142, 11, 98, 217, 176, 198, 175, 20, 125,
238, 135, 60, 85, 35, 74, 241, 152, 29, 116, 207, 166, 208, 185, 2, 107,
97, 8, 179, 218, 172, 197, 126, 23, 146, 251, 64, 41, 95, 54, 141, 228,
153, 240, 75, 34, 84, 61, 134, 239, 106, 3, 184, 209, 167, 206, 117, 28,
22, 127, 196, 173, 219, 178, 9, 96, 229, 140, 55, 94, 40, 65, 250, 147,
181, 220, 103, 14, 120, 17, 170, 195, 70, 47, 148, 253, 139, 226, 89, 48,
58, 83, 232, 129, 247, 158, 37, 76, 201, 160, 27, 114, 4, 109, 214, 191,
194, 171, 16, 121, 15, 102, 221, 180, 49, 88, 227, 138, 252, 149, 46, 71,
77, 36, 159, 246, 128, 233, 82, 59, 190, 215, 108, 5, 115, 26, 161, 200,
91, 50, 137, 224, 150, 255, 68, 45, 168, 193, 122, 19, 101, 12, 183, 222,
212, 189, 6, 111, 25, 112, 203, 162, 39, 78, 245, 156, 234, 131, 56, 81,
44, 69, 254, 151, 225, 136, 51, 90, 223, 182, 13, 100, 18, 123, 192, 169,
163, 202, 113, 24, 110, 7, 188, 213, 80, 57, 130, 235, 157, 244, 79, 38)
# ----- Devices Database -------------------
DevList = [] # DevList = array of Disk
# Disk
# [0] - Device name (String)
# [1] - Device path (String)
# [2] - Device serial (String)
# [3] - Size (UInt64)
# [4] - Rotational (Byte) 0 = unknown, 1 = SSD, 2 = HDD
# [5] - Drive Status (-obj-)
# [6] - Partitions (-obj-)
# [7] - APM Available (Byte) 0 = unknown, 1 = no, 2 = yes
# Drive Status
# [0] - IO count (UInt64)
# [1] - keep alive count (UInt32) [CheckPeriod multiple]
# [2] - idle count (UInt32) [CheckPeriod multiple]
# [3] - State code (Byte) 0 = unknown, 1 = active, 2 = standby
# [4] - State name (String)
# [5] - KAS level
# [6] - SBT level
# Disk Partition
# [0] - Device name (String)
# [1] - Device path (String)
# [2] - Label (String)
# [3] - UUID (String)
# [4] - File system type (String)
# [5] - Size (UInt64)
# [6] - Mount Point (-obj-)
# Mount Point
# [0] - Folder name (String)
# [1] - Mount path (String)
# [2] - Partition type (String)
# [3] - Mount options (String)
LogD(3, 'All definitions loaded')
# ========================= C L A S S E S ==================================
#------ AverageInt Class ----------------------
class AverageInt:
def __init__(self, Count):
if Count < 2: Count = 2
self.Size = Count
self.Items = [0] * Count
self.IntX = 0
self.FirstAdd = True
def reset(self, NewSize=0):
if NewSize < 2: NewSize = self.Size
self.Size = NewSize
self.Items = [0.0] * NewSize
self.IntX = 0
self.FirstAdd = True
def add_data(self, value):
if self.FirstAdd:
self.Items = [value] * self.Size
self.FirstAdd = False
else:
self.Items[self.IntX] = value
if self.IntX == len(self.Items) - 1: self.IntX = 0
else: self.IntX += 1
def get_avg(self):
return sum(self.Items) // self.Size
#------ TMP275 Sensor Class --------------------
class TMP275:
temp_reg = 0x00
conf_reg = 0x01
tlow_reg = 0x02
thig_reg = 0x03
def __init__(self, TheI2C, Address, ResBits):
self.I2C = TheI2C
self.Addr = Address
self.Config(ResBits)
def Config(self, NewResBits):
self.ResBits = NewResBits
self.Resolution = 128 / (2 ** (self.ResBits-1))
self.B2_bits = self.ResBits - 8
self.B2_shift = 8 - self.B2_bits
self.B2_mask = (2 ** self.B2_bits) - 1
CONF = ( 0b00010000 | ((self.ResBits - 9) << 5) ) & 0xFF
with i2cLock: self.I2C.write_byte_data(self.Addr, self.conf_reg, CONF)
def Temperature(self):
with i2cLock: raw = self.I2C.read_i2c_block_data(self.Addr, self.temp_reg, 2)
LSB = ((raw[1] >> self.B2_shift) & self.B2_mask) * self.Resolution
return int((raw[0]+LSB)*100)
def GetTempAlert(self, Reg):
with i2cLock: raw = self.I2C.read_i2c_block_data(self.Addr, Reg, 2)
LSB = ((raw[1] >> 4) & 0x0F) * self.Resolution
return round(raw[0]+LSB, 2)
def SetTempAlert(self, Reg, Value):
if Value > 127.9375: Value = 127.9375
Value = int(Value / 0.0625)
B1 = (Value >> 4) & 0xFF
B2 = (Value << 4) & 0xF0
with i2cLock: self.I2C.write_i2c_block_data(self.Addr, Reg, [B1, B2])
#------ Fast Timer Class --------------------
class FastTimer(threading.Thread):
def __init__(self, interval, callback, args=None, kwargs=None, shots=1, name=None):
super().__init__(name=name)
self.daemon = True
self.interval = interval
self.callback = callback
self.args = args if args is not None else []
self.kwargs = kwargs if kwargs is not None else {}
self.last_shot = shots
self.trigger = threading.Event()
self.done = threading.Event()
self.terminated = threading.Event()
self.start()
def Terminate(self):
if self.is_alive():
self.terminated.set()
self.done.set()
self.trigger.set()
self.join()
def Gooo(self):
if self.is_alive():
self.trigger.set()
def Abort(self):
if self.is_alive():
self.done.set()
self.trigger.clear()
def Reset(self):
if self.is_alive():
self.done.set()
def Mark(self):
if self.is_alive():
if self.trigger.is_set(): self.done.set()
else: self.trigger.set()
def run(self):
while not self.terminated.is_set():
if not self.trigger.is_set():
shot = 0; self.done.clear()
self.trigger.wait()
Reseted = self.done.wait(self.interval)
self.done.clear()
if self.terminated.is_set(): break
if not Reseted:
if self.last_shot > 0:
shot += 1
if shot == self.last_shot:
self.trigger.clear()
self.callback(*self.args, **self.kwargs)
#------ GPIO Pin Monitor Class -------------------
class GpioMonitor(threading.Thread):
def __init__(self, label, config, callbacks):
super().__init__(name='GPIO Monitor')
self.daemon = False
self.Label = label
self.LConfig = config
self.LCallbacks = callbacks
self.done_fd = os.eventfd(0)
self.start()
def Terminate(self):
if self.is_alive():
os.eventfd_write(self.done_fd, 1)
self.join()
def run(self):
with gpiod.request_lines(RPiChip, consumer=self.Label, config=self.LConfig) as request:
poll = select.poll()
poll.register(request.fd, select.POLLIN)
poll.register(self.done_fd, select.POLLIN)
while True:
for fd, event in poll.poll():
if fd == self.done_fd: return
for event in request.read_edge_events():
if event.line_offset in self.LCallbacks:
try: self.LCallbacks[event.line_offset](event)
except: pass
#------ BlockDev Monitor Class --------------------
class BlockDevMonitor(threading.Thread):
def __init__(self, callback, args=None, kwargs=None):
import time
super().__init__(name='Block Devices Monitor')
self.loop = None
self.timer = FastTimer(1, callback, args, kwargs, name='Block Devices FastTimer')
self.start()
time.sleep(0.3)
def Terminate(self):
if self.is_alive():
if self.loop != None: self.loop.quit()
self.join()
self.timer.Terminate()
def run(self):
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
def sigUnitChg(*args):
if (len(args) >= 1) and ( args[0].startswith('blockdev@') or ('-block-' in args[0]) or (r'-by\x2dlabel-' in args[0]) ): self.timer.Mark()
if Debug: print('DevMonitor thread started.')
DBusGMainLoop(set_as_default=True)
self.loop = GLib.MainLoop()
bus = dbus.SystemBus()
bus.add_signal_receiver(sigUnitChg, dbus_interface='org.freedesktop.systemd1.Manager', signal_name='UnitNew', path='/org/freedesktop/systemd1')
bus.add_signal_receiver(sigUnitChg, dbus_interface='org.freedesktop.systemd1.Manager', signal_name='UnitRemoved', path='/org/freedesktop/systemd1')
self.loop.run()
if Debug: print('DevMonitor thread ended.')
#------ Permission Manager Class --------------------
class PermissionManager:
def __init__(self):
self.TaskList = []
self.Access = threading.RLock()
self.Done = threading.Event()
self.Done.set()
def AddTask(self, tg_dev, tg_mpoint):
with self.Access:
for i in range(len(self.TaskList)):
if self.TaskList[i][2] == tg_dev:
SendMessageToComp(CMD_MESSAGE, f'Please wait ! Already working on permissions on {tg_dev}...', 2)
return
end_flag = threading.Event()
WT = threading.Thread(target=self.WorkThread, args=(tg_mpoint, end_flag), name='Permission Manager')
self.TaskList.append([WT, end_flag, tg_dev, tg_mpoint])
self.Done.clear()
WT.start()
def Terminate(self):
with self.Access:
for i in range(len(self.TaskList)): self.TaskList[i][1].set()
self.Done.wait()
def WorkThread(self, mpoint, terminated):
Commands = [
[['sudo', 'find', mpoint, '-type', 'd', '-exec', 'chmod', oct(NasPerms)[2:], '--', '{}', '+'], 'dir chmod'],
[['sudo', 'find', mpoint, '-type', 'f', '-exec', 'chmod', 'ug+rw,g-s', '--', '{}', '+'], 'file chmod'],
[['sudo', 'chown', '-R', ':'+NasGroup, mpoint], 'chown']]
SendMessageToComp(CMD_MESSAGE, f'Start setting file permissions for {mpoint}...', 1)
try:
for i in range(len(Commands)):
process = subprocess.Popen(Commands[i][0], stderr=subprocess.PIPE)
tr_sent = False
while process.poll() is None:
if not tr_sent and terminated.is_set():
process.terminate()
tr_sent = True
time.sleep(0.5)
if process.returncode != 0:
if terminated.is_set(): SendMessageToComp(CMD_MESSAGE, f'Setting permissions for {mpoint} aborted at: {Commands[i][1]} !', 2)
else: SendMessageToComp(CMD_MESSAGE, f'Failed setting permisions for {mpoint}: {process.stderr.read().decode("utf-8")}', 3)
return
SendMessageToComp(CMD_MESSAGE, f'Setting permissions for {mpoint} completed successfully.', 1)
except Exception as E:
SendMessageToComp(CMD_MESSAGE, f'Failed setting permissions for {mpoint}: {E}', 3)
finally:
with self.Access:
CT = threading.current_thread()
for i in range(len(self.TaskList)):
if self.TaskList[i][0] == CT:
del self.TaskList[i]; break
if len(self.TaskList) == 0: self.Done.set()
#------ Hardware PWM Class --------------------
# pwm0 is GPIO pin 18 is physical pin 32 (dtoverlay can be deployed to use GPIO 12 instead)
# pwm1 is GPIO pin 19 is physical pin 33 (dtoverlay can be deployed to use GPIO 13 instead)
class HardwarePWMException(Exception): pass
class HardwarePWM:
ChipPath: str = '/sys/class/pwm/pwmchip0'
DC: float
Freq: float
def __init__(self, channel: int, freq: float):
if channel not in {0, 1}:
raise HardwarePWMException('Only channel 0 and 1 are available on the Rpi.')
self.pwm_dir = f'{self.ChipPath}/pwm{channel}'; self.DC = 0
if not os.path.isdir(self.ChipPath):
raise HardwarePWMException('PWM overlay is not enabled.')
if not os.access(self.ChipPath+'/export', os.W_OK):
raise HardwarePWMException(f'Need write access to files in "{self.ChipPath}"')
if not os.path.isdir(self.pwm_dir):
self.echo(channel, f'{self.ChipPath}/export')
self.SetFreq(freq)
def echo(self, message: int, filename: str):
with open(filename, 'w') as file: file.write(f'{message}\n')
def Start(self, duty_cycle: float):
self.SetDuty(duty_cycle)
self.echo(1, f'{self.pwm_dir}/enable')
def Stop(self):
self.SetDuty(0)
self.echo(0, f'{self.pwm_dir}/enable')
def SetDuty(self, duty_cycle: float):
if not (0 <= duty_cycle <= 100):
raise HardwarePWMException('Duty cycle must be between 0 and 100 (inclusive).')
self.DC = duty_cycle
per = 1000000000 / float(self.Freq) # in nanoseconds
pdc = int(per * duty_cycle / 100) # in nanoseconds
self.echo(pdc, f'{self.pwm_dir}/duty_cycle')
def SetFreq(self, freq: float):
if freq < 0.1: raise HardwarePWMException('Frequency cannot be lower than 0.1 on the Rpi.')
self.Freq = freq
# we first have to change duty cycle, since https://stackoverflow.com/a/23050835/1895939
BackDC = self.DC
if self.DC > 0: self.SetDuty(0)
per = 1000000000 / float(freq) # in nanoseconds
self.echo(int(per), f'{self.pwm_dir}/period')
self.SetDuty(BackDC)
# ========================= F U N C T I O N S ================================
#----- System functions -------------------------
def AlreadyRunning():
current_pid = os.getpid()
script_name = os.path.basename(__file__)
# print(f'CPID: {current_pid} Name: {script_name}')
for process in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
if 'python' in process.info['name']:
# print(f'PID: {process.info["pid"]} Name: {process.info["name"]} CmdLine: {" ".join(process.info["cmdline"])}')
if (process.info['pid'] != current_pid) and (script_name in ' '.join(process.info['cmdline'])): return True
except (psutil.NoSuchProcess, psutil.AccessDenied): continue
return False
def MainExit(cmd, rsecs = 10):
global ExitCmd, ExitRSecs, AsyncTerminated
if not AsyncTerminated:
ExitCmd = cmd
ExitRSecs = rsecs
AsyncTerminated = True
with upsLock: UPSEvent.set()
def NASMarkSD():
with open('/tmp/sdtype', 'w') as SDFile:
SDFile.write('SD-NAS')
def UPSMarkSD():
with open('/tmp/sdtype', 'w') as SDFile:
SDFile.write('SD-UPS')
def UPSMarkRS(secs):
with open('/tmp/sdtype', 'w') as SDFile:
SDFile.write(f'RS-UPS:{secs}')
def ALLMarkSD():
with open('/tmp/sdtype', 'w') as SDFile:
SDFile.write('SD-ALL')
def ShutdownType():
try:
with open('/tmp/sdtype', 'r') as SDFile:
SDT = SDFile.read().strip().split(':')
if SDT[0] == 'SD-NAS': return 'SD-NAS', None
elif SDT[0] == 'RS-UPS': return 'RS-UPS', int(SDT[1])
elif SDT[0] == 'SD-UPS': return 'SD-UPS', None
elif SDT[0] == 'SD-ALL': return 'SD-ALL', None
else: return 'RS-UPS', 10
except: return 'RS-UPS', 10
def SignalToCutThePower():
try:
SDType, RSecs = ShutdownType()
I2CBus = SMBus(1)
try:
if SDType == 'SD-NAS':
I2CBus.write_i2c_block_data(PicoAddr, regShdState, [1])
time.sleep(0.5)
elif SDType == 'SD-ALL':
I2CBus.write_i2c_block_data(PicoAddr, regCMD, list(cmdPowerOff))
time.sleep(5)
elif SDType == 'SD-UPS':
I2CBus.write_i2c_block_data(PicoAddr, regCMD, list(cmdShdReady))
time.sleep(5)
elif SDType == 'RS-UPS':
I2CBus.write_i2c_block_data(PicoAddr, regCMD, list(cmdRstReady + struct.pack('<H', RSecs)))
time.sleep(5)
finally: I2CBus.close()
except: pass
SDReadyCfg = { SDReadyPin: gpiod.LineSettings(direction=Direction.OUTPUT) }
with gpiod.request_lines(RPiChip, consumer="NAS-CutPower", config=SDReadyCfg) as request:
request.set_value(SDReadyPin, gpiod.line.Value.ACTIVE)
time.sleep(1)
def PowerOffHDDs():
disks = []
for dev in UDEV.list_devices(subsystem='block', DEVTYPE='disk'):
if re.match(r'sd[a-z]$', dev.sys_name) and RotationalDisk(dev.sys_name):
disks.append([dev.sys_name, dev.device_node])
if len(disks) == 0: return
disks.sort(key=lambda x: x[0])
devices = ', '.join([disk[0] for disk in disks]); AllOK = True
for disk in disks: KeepAlive(disk[1])
time.sleep(5)
for disk in disks:
cmd = ['sudo', '/usr/sbin/hdparm', '-y', disk[1]]
result = subprocess.run(cmd, capture_output=True, text=True)
if AllOK and result.returncode != 0:
AllOK = False; ErrMsg1 = disk[1]; ErrMsg2 = result.stderr
if AllOK: BroadcastMsg(HddPark1Msg, 1, [devices])
else: BroadcastMsg(HddPark0Msg, 3, [ErrMsg1, ErrMsg2])
time.sleep(8)
def SetSafeShd():
open(SafeShdFile, 'a').close()
def ClearSafeShd():
try: os.remove(SafeShdFile)
except: pass
def WasSafeShd():
with cfgLock:
try: FirstRun = Config['General'].getboolean('FirstSysRun')
except: FirstRun = True
return FirstRun or os.path.exists(SafeShdFile)
def PowerFailureMsgHandler():
global Sshd_Ack
with pflLock:
if not Debug and not Sshd_Ack:
idle = SendMessageToComp(CMD_MESSAGE, PowerFailureMsg, 3)
if idle >= 0: Sshd_Ack = True
#----- Simple functions -------------------------
def MsgFormat(Msg, Params):
if Msg.count('{}') == len(Params):
return Msg.format(*Params)
else: return None
def rPad(the_str, length):
the_str = str(the_str)
if len(the_str) >= length: return the_str
else: return the_str + ' ' * (length - len(the_str))
def PackSStr(TheStr):
PS = TheStr.encode('utf-8')
Size = struct.pack('<B', len(PS))
return Size + PS
def PackWStr(TheStr):
PS = TheStr.encode('utf-8')
Size = struct.pack('<H', len(PS))
return Size + PS
def PackStr(TheStr):
PS = TheStr.encode('utf-8')
Size = struct.pack('<I', len(PS))
return Size + PS
def UnpackSStr(Buff, Idx):
Size = struct.unpack('<B', Buff[Idx:Idx+1])[0]
return Buff[Idx+1:Idx+1+Size].decode('utf-8'), Size+1
def UnpackWStr(Buff, Idx):
Size = struct.unpack('<H', Buff[Idx:Idx+2])[0]
return Buff[Idx+2:Idx+2+Size].decode('utf-8'), Size+2