|
1 | | -#!/usr/bin/python3 |
2 | | - |
3 | | -import sys |
4 | | - |
5 | | -if (sys.platform == "linux") or (sys.platform == "linux2"): |
6 | | - pass |
7 | | -else: |
8 | | - # Replace libraries by fake ones |
9 | | - import fake_rpi |
10 | | - |
11 | | - sys.modules['RPi'] = fake_rpi.RPi # Fake RPi |
12 | | - sys.modules['RPi.GPIO'] = fake_rpi.RPi.GPIO # Fake GPIO |
13 | | - sys.modules['smbus'] = fake_rpi.smbus # Fake smbus (I2C) |
14 | | - |
15 | | -from pimodules import configuration |
16 | | -from pimodules.alerts import sendEmail |
17 | | -from pimodules.daemon import Daemon |
18 | | -import RPi.GPIO as GPIO |
19 | | -import socket |
20 | | -import xmltodict |
21 | | -import argparse |
22 | | -import logging.handlers |
23 | | -import logging |
24 | | -import time |
25 | | -import atexit |
26 | | -import signal |
27 | | -import os |
28 | | -""" |
29 | | -
|
30 | | -PiModules(R) UPS PIco file-safe shutdown daemon. |
31 | | -
|
32 | | -""" |
33 | | - |
34 | | - |
35 | | -CLOCK_PIN = 27 |
36 | | -PULSE_PIN = 22 |
37 | | -BOUNCE_TIME = 30 |
38 | | - |
39 | | - |
40 | | -class fssd(Daemon): |
41 | | - def __init__(self, pidfile, xmlconfig, loglevel=logging.NOTSET): |
42 | | - Daemon.__init__(self, pidfile) |
43 | | - self.loglevel = loglevel |
44 | | - self.log = logging.getLogger(__name__) |
45 | | - self.log.setLevel(self.loglevel) |
46 | | - self.log.setLevel(logging.DEBUG) |
47 | | - if (sys.platform == "linux") or (sys.platform == "linux2"): |
48 | | - handler = logging.handlers.SysLogHandler(address='/dev/log') |
49 | | - else: |
50 | | - handler = logging.StreamHandler(sys.stdout) |
51 | | - formatter = logging.Formatter('%(module)s[%(process)s]: <%(levelname)s>: %(message)s') |
52 | | - handler.setFormatter(formatter) |
53 | | - self.log.addHandler(handler) |
54 | | - |
55 | | - try: |
56 | | - self.xmlconfig = xmlconfig |
57 | | - with open(self.xmlconfig, 'rb') as fi: |
58 | | - self.config = xmltodict.parse(fi) |
59 | | - except IOError as e: |
60 | | - self.log.warning( |
61 | | - "Failed to load XML config file, loading defaults. Alerts will be disabled") |
62 | | - self.config = xmltodict.parse(configuration.DEFAULT_FSSD_XML_CONFIG) |
63 | | - |
64 | | - self.config = self.config['root']['fssd:config']['fssd:alerts']['fssd:email'] |
65 | | - self.config['fssd:enabled'] = (self.config['fssd:enabled'] == 'True') |
66 | | - |
67 | | - signal.signal(signal.SIGTERM, self.sigcatch) |
68 | | - |
69 | | - self.counter = 0 |
70 | | - self.mail_sent = False |
71 | | - |
72 | | - # first interrupt on isr pin will start pulse high |
73 | | - self.sqwave = True |
74 | | - |
75 | | - def setup(self): |
76 | | - """ |
77 | | - GPIO initialisation |
78 | | -
|
79 | | - Note: This cannot go in the __init__ method because the unix double-fork in the generic daemon code |
80 | | - mucks up the initialisation of the GPIO system. |
81 | | -
|
82 | | - So it is called in the over-ridden run method. |
83 | | - """ |
84 | | - |
85 | | - GPIO.setmode(GPIO.BCM) |
86 | | - GPIO.setwarnings(False) |
87 | | - GPIO.setup(CLOCK_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) |
88 | | - GPIO.setup(PULSE_PIN, GPIO.OUT, initial=self.sqwave) |
89 | | - GPIO.add_event_detect(CLOCK_PIN, GPIO.FALLING, callback=self.isr, bouncetime=BOUNCE_TIME) |
90 | | - |
91 | | - def isr(self, channel): |
92 | | - """ |
93 | | - GPIO interrupt service routine |
94 | | - """ |
95 | | - # This test is here because the user *might* have another HAT plugged in or another circuit that produces a |
96 | | - # falling-edge signal on another GPIO pin. |
97 | | - if channel != CLOCK_PIN: |
98 | | - return |
99 | | - |
100 | | - # we can get the state of a pin with GPIO.input even when it is currently configured as an output |
101 | | - self.sqwave = not GPIO.input(PULSE_PIN) |
102 | | - |
103 | | - # set pulse pin low before changing it to input to look for shutdown signal |
104 | | - GPIO.output(PULSE_PIN, False) |
105 | | - GPIO.setup(PULSE_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) |
106 | | - if not GPIO.input(PULSE_PIN): |
107 | | - # disable irq to prevent multiple mails |
108 | | - GPIO.remove_event_detect(CLOCK_PIN) |
109 | | - # pin is low, this is shutdown signal from pico |
110 | | - self.counter += 1 |
111 | | - self.log.warning("Lost power supply, Pi will shutdown") |
112 | | - if self.mail_sent == False: |
113 | | - self.mail_sent = True |
114 | | - self.alert_email() |
115 | | - time.sleep(2) |
116 | | - os.system('/sbin/shutdown -h now') |
117 | | - else: |
118 | | - self.counter = 0 |
119 | | - |
120 | | - # change pulse pin back to output with flipped state |
121 | | - GPIO.setup(PULSE_PIN, GPIO.OUT, initial=self.sqwave) |
122 | | - |
123 | | - def sigcatch(self, signum, frame): |
124 | | - """ |
125 | | - Signal handler |
126 | | - """ |
127 | | - |
128 | | - if signum == signal.SIGTERM: |
129 | | - sys.exit(0) |
130 | | - |
131 | | - def cleanup(self): |
132 | | - """ |
133 | | - GPIO cleanup |
134 | | - """ |
135 | | - |
136 | | - self.log.debug("Cleanup") |
137 | | - self.log.info("Stopped") |
138 | | - GPIO.cleanup() |
139 | | - |
140 | | - def alert_email(self): |
141 | | - # emailserver, username, port, security, fromAddr, toAddr, b64Password, msgSubjectTemplate, msgBodyTemplate |
142 | | - try: |
143 | | - if not self.config['fssd:enabled']: |
144 | | - self.log.debug("Email alert is disabled") |
145 | | - return True |
146 | | - |
147 | | - sendEmail(self.config['fssd:server'], self.config['fssd:username'], self.config['fssd:port'], self.config['fssd:security'], |
148 | | - self.config['fssd:sender-email-address'], self.config['fssd:recipient-email-address'], |
149 | | - self.config['fssd:sender-password'], self.config['fssd:subject-template'], |
150 | | - self.config['fssd:body-template']) |
151 | | - except socket.error as e: |
152 | | - self.log.error(format("Exception in alert_email: %d, %s" % (e.errno, e.strerror))) |
153 | | - except: |
154 | | - self.log.error("Unexpected error in alert_email:", sys.exc_info()[0]) |
155 | | - |
156 | | - def run(self): |
157 | | - """ |
158 | | - Super-class overloaded run method. |
159 | | - """ |
160 | | - self.log.info("Started") |
161 | | - self.log.debug(self.config['fssd:enabled']) |
162 | | - self.log.debug(self.config['fssd:server']) |
163 | | - self.log.debug(self.config['fssd:username']) |
164 | | - self.log.debug(self.config['fssd:sender-email-address']) |
165 | | - self.log.debug(self.config['fssd:recipient-email-address']) |
166 | | - |
167 | | - # register function to cleanup at exit |
168 | | - atexit.register(self.cleanup) |
169 | | - |
170 | | - self.setup() |
171 | | - |
172 | | - while True: |
173 | | - time.sleep(5) |
174 | | - |
175 | | - |
176 | | -# parse the command-line |
177 | | -parser = argparse.ArgumentParser() |
178 | | -parser.add_argument('-l', '--log-level', help="Log level, 'info' or 'debug'", |
179 | | - default='info', choices=['info', 'debug']) |
180 | | -parser.add_argument("-x", "--xml-config", help="XML config file", |
181 | | - default='picofssd.xml', required=True) |
182 | | -group = parser.add_mutually_exclusive_group(required=True) |
183 | | -group.add_argument("-d", "--debug", help="Keep in the foreground, do not daemonize", |
184 | | - action="store_true", default=False) |
185 | | -group.add_argument("-p", "--pid-file", help="PID file") |
186 | | -args = parser.parse_args() |
187 | | - |
188 | | -sd = fssd(args.pid_file, args.xml_config, { |
189 | | - 'info': logging.INFO, 'debug': logging.DEBUG}[args.log_level]) |
190 | | - |
191 | | -# the argument to the start method is opposite of debug |
192 | | -sd.start(not args.debug) |
| 1 | +#!/usr/bin/python3 |
| 2 | + |
| 3 | +import sys |
| 4 | + |
| 5 | +if (sys.platform == "linux") or (sys.platform == "linux2"): |
| 6 | + pass |
| 7 | +else: |
| 8 | + # Replace libraries by fake ones |
| 9 | + import fake_rpi |
| 10 | + |
| 11 | + sys.modules['RPi'] = fake_rpi.RPi # Fake RPi |
| 12 | + sys.modules['RPi.GPIO'] = fake_rpi.RPi.GPIO # Fake GPIO |
| 13 | + sys.modules['smbus'] = fake_rpi.smbus # Fake smbus (I2C) |
| 14 | + |
| 15 | +from pimodules import configuration |
| 16 | +from pimodules.alerts import sendEmail |
| 17 | +from pimodules.daemon import Daemon |
| 18 | +import RPi.GPIO as GPIO |
| 19 | +import socket |
| 20 | +import xmltodict |
| 21 | +import argparse |
| 22 | +import logging.handlers |
| 23 | +import logging |
| 24 | +import time |
| 25 | +import atexit |
| 26 | +import signal |
| 27 | +import os |
| 28 | +""" |
| 29 | +
|
| 30 | +PiModules(R) UPS PIco file-safe shutdown daemon. |
| 31 | +
|
| 32 | +""" |
| 33 | + |
| 34 | + |
| 35 | +CLOCK_PIN = 27 |
| 36 | +PULSE_PIN = 22 |
| 37 | +BOUNCE_TIME = 30 |
| 38 | + |
| 39 | + |
| 40 | +class fssd(Daemon): |
| 41 | + def __init__(self, pidfile, xmlconfig, loglevel=logging.NOTSET): |
| 42 | + Daemon.__init__(self, pidfile) |
| 43 | + self.loglevel = loglevel |
| 44 | + self.log = logging.getLogger(__name__) |
| 45 | + self.log.setLevel(self.loglevel) |
| 46 | + self.log.setLevel(logging.DEBUG) |
| 47 | + if (sys.platform == "linux") or (sys.platform == "linux2"): |
| 48 | + handler = logging.handlers.SysLogHandler(address='/dev/log') |
| 49 | + else: |
| 50 | + handler = logging.StreamHandler(sys.stdout) |
| 51 | + formatter = logging.Formatter('%(module)s[%(process)s]: <%(levelname)s>: %(message)s') |
| 52 | + handler.setFormatter(formatter) |
| 53 | + self.log.addHandler(handler) |
| 54 | + |
| 55 | + try: |
| 56 | + self.xmlconfig = xmlconfig |
| 57 | + with open(self.xmlconfig, 'rb') as fi: |
| 58 | + self.config = xmltodict.parse(fi) |
| 59 | + except IOError as e: |
| 60 | + self.log.warning( |
| 61 | + "Failed to load XML config file, loading defaults. Alerts will be disabled") |
| 62 | + self.config = xmltodict.parse(configuration.DEFAULT_FSSD_XML_CONFIG) |
| 63 | + |
| 64 | + self.config = self.config['root']['fssd:config']['fssd:alerts']['fssd:email'] |
| 65 | + self.config['fssd:enabled'] = (self.config['fssd:enabled'] == 'True') |
| 66 | + |
| 67 | + signal.signal(signal.SIGTERM, self.sigcatch) |
| 68 | + |
| 69 | + self.counter = 0 |
| 70 | + self.mail_sent = False |
| 71 | + |
| 72 | + # first interrupt on isr pin will start pulse high |
| 73 | + self.sqwave = True |
| 74 | + |
| 75 | + def setup(self): |
| 76 | + """ |
| 77 | + GPIO initialisation |
| 78 | +
|
| 79 | + Note: This cannot go in the __init__ method because the unix double-fork in the generic daemon code |
| 80 | + mucks up the initialisation of the GPIO system. |
| 81 | +
|
| 82 | + So it is called in the over-ridden run method. |
| 83 | + """ |
| 84 | + |
| 85 | + GPIO.setmode(GPIO.BCM) |
| 86 | + GPIO.setwarnings(False) |
| 87 | + GPIO.setup(CLOCK_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) |
| 88 | + GPIO.setup(PULSE_PIN, GPIO.OUT, initial=self.sqwave) |
| 89 | + GPIO.add_event_detect(CLOCK_PIN, GPIO.FALLING, callback=self.isr, bouncetime=BOUNCE_TIME) |
| 90 | + |
| 91 | + def isr(self, channel): |
| 92 | + """ |
| 93 | + GPIO interrupt service routine |
| 94 | + """ |
| 95 | + # This test is here because the user *might* have another HAT plugged in or another circuit that produces a |
| 96 | + # falling-edge signal on another GPIO pin. |
| 97 | + if channel != CLOCK_PIN: |
| 98 | + return |
| 99 | + |
| 100 | + # we can get the state of a pin with GPIO.input even when it is currently configured as an output |
| 101 | + self.sqwave = not GPIO.input(PULSE_PIN) |
| 102 | + |
| 103 | + # set pulse pin low before changing it to input to look for shutdown signal |
| 104 | + GPIO.output(PULSE_PIN, False) |
| 105 | + GPIO.setup(PULSE_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) |
| 106 | + if not GPIO.input(PULSE_PIN): |
| 107 | + # disable irq to prevent multiple mails |
| 108 | + GPIO.remove_event_detect(CLOCK_PIN) |
| 109 | + # pin is low, this is shutdown signal from pico |
| 110 | + self.counter += 1 |
| 111 | + self.log.warning("Lost power supply, Pi will shutdown") |
| 112 | + if self.mail_sent == False: |
| 113 | + self.mail_sent = True |
| 114 | + self.alert_email() |
| 115 | + time.sleep(2) |
| 116 | + os.system('/sbin/shutdown -h now') |
| 117 | + else: |
| 118 | + self.counter = 0 |
| 119 | + |
| 120 | + # change pulse pin back to output with flipped state |
| 121 | + GPIO.setup(PULSE_PIN, GPIO.OUT, initial=self.sqwave) |
| 122 | + |
| 123 | + def sigcatch(self, signum, frame): |
| 124 | + """ |
| 125 | + Signal handler |
| 126 | + """ |
| 127 | + |
| 128 | + if signum == signal.SIGTERM: |
| 129 | + sys.exit(0) |
| 130 | + |
| 131 | + def cleanup(self): |
| 132 | + """ |
| 133 | + GPIO cleanup |
| 134 | + """ |
| 135 | + |
| 136 | + self.log.debug("Cleanup") |
| 137 | + self.log.info("Stopped") |
| 138 | + GPIO.cleanup() |
| 139 | + |
| 140 | + def alert_email(self): |
| 141 | + # emailserver, username, port, security, fromAddr, toAddr, b64Password, msgSubjectTemplate, msgBodyTemplate |
| 142 | + try: |
| 143 | + if not self.config['fssd:enabled']: |
| 144 | + self.log.debug("Email alert is disabled") |
| 145 | + return True |
| 146 | + |
| 147 | + sendEmail(self.config['fssd:server'], self.config['fssd:username'], self.config['fssd:port'], self.config['fssd:security'], |
| 148 | + self.config['fssd:sender-email-address'], self.config['fssd:recipient-email-address'], |
| 149 | + self.config['fssd:sender-password'], self.config['fssd:subject-template'], |
| 150 | + self.config['fssd:body-template']) |
| 151 | + except socket.error as e: |
| 152 | + self.log.error(format("Exception in alert_email: %d, %s" % (e.errno, e.strerror))) |
| 153 | + except: |
| 154 | + self.log.error("Unexpected error in alert_email:", sys.exc_info()[0]) |
| 155 | + |
| 156 | + def run(self): |
| 157 | + """ |
| 158 | + Super-class overloaded run method. |
| 159 | + """ |
| 160 | + self.log.info("Started") |
| 161 | + self.log.debug(self.config['fssd:enabled']) |
| 162 | + self.log.debug(self.config['fssd:server']) |
| 163 | + self.log.debug(self.config['fssd:username']) |
| 164 | + self.log.debug(self.config['fssd:sender-email-address']) |
| 165 | + self.log.debug(self.config['fssd:recipient-email-address']) |
| 166 | + |
| 167 | + # register function to cleanup at exit |
| 168 | + atexit.register(self.cleanup) |
| 169 | + |
| 170 | + self.setup() |
| 171 | + |
| 172 | + while True: |
| 173 | + time.sleep(5) |
| 174 | + |
| 175 | +if __name__ == "__main__": |
| 176 | + # parse the command-line |
| 177 | + parser = argparse.ArgumentParser() |
| 178 | + parser.add_argument('-l', '--log-level', help="Log level, 'info' or 'debug'", |
| 179 | + default='info', choices=['info', 'debug']) |
| 180 | + parser.add_argument("-x", "--xml-config", help="XML config file", |
| 181 | + default='picofssd.xml', required=True) |
| 182 | + group = parser.add_mutually_exclusive_group(required=True) |
| 183 | + group.add_argument("-d", "--debug", help="Keep in the foreground, do not daemonize", |
| 184 | + action="store_true", default=False) |
| 185 | + group.add_argument("-p", "--pid-file", help="PID file") |
| 186 | + args = parser.parse_args() |
| 187 | + |
| 188 | + sd = fssd(args.pid_file, args.xml_config, { |
| 189 | + 'info': logging.INFO, 'debug': logging.DEBUG}[args.log_level]) |
| 190 | + |
| 191 | + # the argument to the start method is opposite of debug |
| 192 | + sd.start(not args.debug) |
0 commit comments