Good day, dear habrovchane. It is no secret that single-board Linux computers based on SoC today are widespread among both amateurs and more or less professional users. More and more tasks can be solved with the help of microcomputers, and even those tasks that were previously solved solely with the help of microcontrollers. It would seem that the use of a full-fledged, albeit small, computer for solving simple tasks is one more overkill, but let's see, is this so bad? This article is the answer to our small dispute with devzona habrovchanin about this.

#!/bin/bash LOG="/var/log/rtc-sync.log" DATE=`date` sleep 30 echo "*** $DATE" >>$LOG until ping -nq -c3 8.8.8.8; do echo "No network, updating system clock from RTC." >>$LOG rtc-pi 2>&1 exit done echo "Network detected. Updating RTC." >>$LOG date +%Y%m%d%H%M%S |xargs ./rtc-pi 2>&1 #!/bin/sh # /etc/init.d/rtc ### BEGIN INIT INFO # Provides: RTC controll # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Simple script to start RTC sync # Description: A simple script from prostosergik <serge.liskovsky@gmail.com> which will run script that synchronizes RTC module clock with system clock at startup. ### END INIT INFO case "$1" in start) echo "RTC sync..." /usr/local/bin/update_rtc& 2>&1 ;; stop) echo "Stopping RTC Sync..." # kill application you want to stop killall update_rtc ;; *) echo "Usage: /etc/init.d/rtc {start|stop}" exit 1 ;; esac exit 0 sudo update-rc.d rtc defaults #!/usr/bin/python # -*- coding: utf-8 -*- import cgi, re, json from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import collections from config import * class MainRequestHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path == '/': lessons = readSchedule() schedule = '' for lesson in lessons: schedule += u"<b> "+lesson+"</b>: "+lessons[lesson].get('start', '--:--') + " - " + lessons[lesson].get('end', '--:--') + "<br />" data = { 'schedule': schedule.encode('utf-8') } TemplateOut(self, 'index.html', data) return elif self.path == '/form.html': lessons = readSchedule() form = '' for lesson in lessons: form += u"<div class='form_block'><label> "+lesson+"</label> <input type='text' name='lesson_"+lesson+"_start' value='"+lessons[lesson].get('start', '--:--') + "'> - <input type='text' name='lesson_"+lesson+"_end' value='"+lessons[lesson].get('end', '--:--') + "'> </div> """ data = { 'form': form.encode('utf-8') } TemplateOut(self, 'form.html', data) return elif self.path == '/remote.html': lessons = readScheduleRemote() form = '' for lesson in lessons: form += u"<div class='form_block'><label> "+lesson+"</label> <input type='text' name='lesson_"+lesson+"_start' value='"+lessons[lesson].get('start', '--:--') + "'> - <input type='text' name='lesson_"+lesson+"_end' value='"+lessons[lesson].get('end', '--:--') + "'> </div> """ data = { 'form': form.encode('utf-8') } TemplateOut(self, 'form.html', data) return else: try: TemplateOut(self, self.path) except IOError: self.send_error(404, 'File Not Found: %s' % self.path) def do_POST(self): # Parse the form data posted form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], } ) lessons = {} if self.path.endswith('save'): # Echo back information about what was posted in the form for field in form.keys(): field_item = form[field] if type(field_item) == type([]): pass # no arrays processing now else: if field_item.filename: pass #no files now. else: if re.match('lesson_([\d]+)_(start|end)', field): (lesson, state) = re.findall('lesson_([\d]+)_(start|end)', field)[0] try: lessons[lesson] except Exception: lessons[lesson] = {} lessons[lesson][state] = field_item.value # printlessons json_s = json.dumps(lessons) if json_s: try: f = open(JSON_FILE, 'w+') f.write(json_s) f.close() HTMLOut(self, 'Saved OK.' + JS_REDIRECT) except IOError, e: # raise e HTMLOut(self, 'Error saving. IO error. '+e.message) else: HTMLOut(self, 'Json Error.') else: self.send_error(404, 'Wrong POST url: %s' % self.path) return def Redirect(request, location): request.send_response(301) request.send_header('Location', location) request.end_headers() return def Headers200(request): request.send_response(200) request.send_header('Content-type', 'text/html') request.end_headers() return def TemplateOut(request, out_file, data = {}): f = open(SCRIPT_DIR + out_file) out = f.read() f.close() #tiny template engine for key, var in data.items(): out = out.replace("{{"+key+"}}", var) HTMLOut(request, out) def HTMLOut(request, html): Headers200(request) f = open(SCRIPT_DIR + 'base.html') out = f.read() f.close() out = out.replace("{{content}}", html) request.wfile.write(out) def readSchedule(): try: f = open(JSON_FILE, 'r') json_s = f.read() f.close() except IOError: return [] try: lessons = json.loads(json_s) except Exception: return [] lessons = collections.OrderedDict(sorted(lessons.items())) return lessons def readScheduleRemote(): import urllib2 try: response = urllib2.urlopen(REMOTE_URL) json_s = response.read() except Exception: return [] try: lessons = json.loads(json_s) except Exception: return [] lessons = collections.OrderedDict(sorted(lessons.items())) return lessons def main(): try: server = HTTPServer(('', 8088), MainRequestHandler) print 'Started httpserver...' server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down server.' server.socket.close() if __name__ == '__main__': main() #!/usr/bin/python # -*- coding: utf-8 -*- import time import threading import json import RPi.GPIO as GPIO from config import * GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(25, GPIO.OUT) GPIO.output(25, False) def read_schedule(): schedule = [] try: f = open(JSON_FILE, 'r') json_s = f.read() f.close() try: json_data = json.loads(json_s) except Exception, e: json_data = [] for lesson in json_data.values(): start = lesson.get('start', False) end = lesson.get('end', False) if start is not False: # print start.split(":") (s_h, s_m) = start.split(":") schedule.append({'h': int(s_h), 'm':int(s_m)}) del s_h del s_m if end is not False: (e_h, e_m) = end.split(":") schedule.append({'h': int(e_h), 'm':int(e_m)}) del e_h del e_m return schedule # schedule except IOError, e: return [] except Exception, e: return [] class Alarm(threading.Thread): def __init__(self): super(Alarm, self).__init__() self.schedule = read_schedule() self.keep_running = True def run(self): try: while self.keep_running: now = time.localtime() for schedule_item in self.schedule: if now.tm_hour == schedule_item['h'] and now.tm_min == schedule_item['m']: print "Ring start..." GPIO.output(25, True) time.sleep(5) print "Ring end..." GPIO.output(25, False) self.schedule = read_schedule() #reload schedule if it was changed time.sleep(55) # more than 1 minute #print "Check at "+str(now.tm_hour)+':'+str(now.tm_min)+':'+str(now.tm_sec) time.sleep(1) except Exception, e: raise e # return def die(self): self.keep_running = False alarm = Alarm() def main(): try: alarm.start() print 'Started daemon...' while True: continue except KeyboardInterrupt: print '^C received, shutting down daemon.' alarm.die() if __name__ == '__main__': main() #!/bin/sh ### BEGIN INIT INFO # Provides: schedule_daemon # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # description: School Ring Schedule daemon # processname: School Ring Schedule daemon ### END INIT INFO export SCHEDULE_ROOT=/home/pi/ring_app export PATH=$PATH:$SCHEDULE_ROOT SERVICE_PID=`ps -ef | grep daemon.py | grep -v grep | awk 'END{print $2}'` usage() { echo "service schedule_daemon {start|stop|status}" exit 0 } case $1 in start) if [ $SERVICE_PID ];then echo "Service is already running. PID: $SERVICE_PID" else $SCHEDULE_ROOT/daemon.py& 2>&1 fi ;; stop) if [ $SERVICE_PID ];then kill -9 $SERVICE_PID else echo "Service is not running" fi ;; status) if [ $SERVICE_PID ];then echo "Running. PID: $SERVICE_PID" else echo "Not running" fi ;; *) usage ;; esac #!/bin/sh ### BEGIN INIT INFO # Provides: schedule_webserver # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # description: School Ring Schedule web-server # processname: School Ring Schedule web-server ### END INIT INFO export SCHEDULE_ROOT=/home/pi/ring_app export PATH=$PATH:$SCHEDULE_ROOT SERVICE_PID=`ps -ef | grep webserver.py | grep -v grep | awk 'END{print $2}'` usage() { echo "service schedule_webserver {start|stop|status}" exit 0 } case $1 in start) if [ $SERVICE_PID ];then echo "Service is already running. PID: $SERVICE_PID" else $SCHEDULE_ROOT/webserver.py& 2>&1 fi ;; stop) if [ $SERVICE_PID ];then kill -9 $SERVICE_PID else echo "Service is not running" fi ;; status) if [ $SERVICE_PID ];then echo "Running. PID: $SERVICE_PID" else echo "Not running" fi ;; *) usage ;; esac #!/bin/sh ### BEGIN INIT INFO # Provides: schedule_daemon_wd # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # description: School Ring Schedule daemon watchdog # processname: School Ring Schedule daemon watchdog ### END INIT INFO export SCHEDULE_ROOT=/home/pi/ring_app export PATH=$PATH:$SCHEDULE_ROOT SERVICE_PID=`ps -ef | grep daemon.py | grep -v grep | awk '{print $2}'` check_service() { if [ -z $SERVICE_PID ];then service schedule_daemon start fi } check_service usage() { echo "schedule_daemon_wd {start|stop|status}" exit 0 } case $1 in start ) if [ $SERVICE_PID ];then echo "schedule_daemon is already running. PID: $SERVICE_PID" else service schedule_daemon start fi ;; stop ) if [ $SERVICE_PID ];then service schedule_daemon stop else echo "schedule_daemon is already stopped" fi ;; status) if [ $SERVICE_PID ];then echo "schedule_daemon is running. PID: $SERVICE_PID" else echo "schedule_daemon is not running" fi ;; *) usage ;; esac #!/bin/sh ### BEGIN INIT INFO # Provides: schedule_webserver_wd # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # description: School Ring Schedule web-server watchdog # processname: School Ring Schedule web-server watchdog ### END INIT INFO export SCHEDULE_ROOT=/home/pi/ring_app export PATH=$PATH:$SCHEDULE_ROOT SERVICE_PID=`ps -ef | grep webserver.py | grep -v grep | awk '{print $2}'` check_service() { if [ -z $SERVICE_PID ];then service schedule_webserver start fi } check_service usage() { echo "schedule_webserver_wd {start|stop|status}" exit 0 } case $1 in start ) if [ $SERVICE_PID ];then echo "schedule_webserver is already running. PID: $SERVICE_PID" else service schedule_webserver start fi ;; stop ) if [ $SERVICE_PID ];then service schedule_webserver stop else echo "schedule_webserver is already stopped" fi ;; status) if [ $SERVICE_PID ];then echo "schedule_webserver is running. PID: $SERVICE_PID" else echo "schedule_webserver is not running" fi ;; *) usage ;; esac sudo update-rc.d schedule_daemon_wd defaults sudo update-rc.d schedule_webserver_wd defaults #Watchdog tasks * * * * * /etc/init.d/schedule_daemon_wd * * * * * /etc/init.d/schedule_webserver_wd 
Source: https://habr.com/ru/post/207138/
All Articles