diff --git a/REAME.md b/REAME.md index 925a0ab..7bcaa58 100644 --- a/REAME.md +++ b/REAME.md @@ -1,19 +1,19 @@ -## RASPBERRY PI ALS ZENTRALRECHNER FUER BIENENSTOCKUEBERWACHUNG +# RASPBERRY PI ALS ZENTRALRECHNER FUER BIENENSTOCKUEBERWACHUNG -# Hardware Variante A +## Hardware Variante A - Raspberry Pi Zero W - 3G Stick Huawei E3531 - -# Hardware Variante B (Kurt Jakob) +## Hardware Variante B (Kurt Jakob) - Raspberry Pi 3 Model B - Itead Raspberry Pi GSM/GPRS Board (SIM800) - ModMyPi Itead GSM Board Gehäuse - ## INSTALLATION -Image: 2017-09-07-raspbian-stretch-lite.zip +### Grundinstallation +``` +Image: 2017-09-07-raspbian-stretch-lite.zip von https://www.raspberrypi.org/downloads/raspbian/ Installation auf SD: # unzip -p 2017-09-07-raspbian-stretch-lite.zip |dd of=/dev/sdXXX bs=4M conv=fsync @@ -27,6 +27,26 @@ Installation auf SD: - Change Wifi Country: CH - Keyboard: Generic 105-key (Intl), German (Switzerland) +# apt-get update +# apt-get upgrade + +Software installieren: +# apt-get install gammu python-gammu +# apt-get install python-serial +# apt-get install python-yaml +# apt-get install minicom +# apt-get install ppp +# apt-get install python-pexpect +# apt-get install hostapd +# apt-get install ntpdate +# apt-get install dnsmasq + +Firmware-Update: +# rpi-update +``` + +### Zugang ermöglichen per WLAN +``` # cat /etc/wpa_supplicant/wpa_supplicant.conf country=CH ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev @@ -36,22 +56,11 @@ network={ ssid="haerdoepfu27" psk="XXXXXXXXXXXX" } - -# apt-get update -# apt-get upgrade - -Software installieren: -# apt-get install gammu gammu-smsd python-gammu -# apt-get install python-serial -# apt-get install python-yaml -# apt-get install minicom -# apt-get install ppp -# apt-get install python-pexpect - +``` ### Variante A +``` Einrichten GSM: - /etc/usb_modeswitch.d/12d1:1f01: # Huawei E353 (3.se) @@ -87,61 +96,15 @@ connection = at Quick Tutorial Gammu: https://wammu.eu/docs/manual/quick/index.html -Test SMS-Versand: -gammu sendsms TEXT 0765006123 -text "Halooo von beielipi" - - +``` ### Variante B - -Wie Raspberry Zero, jedoch folgende Besonderheiten: - +``` # systemctl disable hciuart.service -root@beielipi:/etc/cron.d# more gsm_poweron -@reboot root /usr/local/bin/gsm_poweron.py +# cp install/files/etc/cron.d/gsm_poweron /etc/cron.d - -root@beielipi:~# cat /usr/local/bin/gsm_poweron.py -#!/usr/bin/python -# -# GSM-Modul anschalten, falls ein keine Antwort gibt... -# -import time -import RPi.GPIO as GPIO -import serial - -def PowerOn(): - # RPi.GPIO Layout verwenden (wie Pin-Nummern) - GPIO.setmode(GPIO.BOARD) - - # Pin 11 (GPIO 17) auf Output setzen - GPIO.setup(11, GPIO.OUT) - - # Druecken simulieren - GPIO.output(11, GPIO.HIGH) - - # Pause, mindestens eine Sekunde gemaess https://www.itead.cc/wiki/RPI_SIM800_GSM/GPRS_ADD-ON_V2.0 - time.sleep(1.5) - - # Weg vom Taster... - GPIO.output(11, GPIO.LOW) - - # Cleanup - GPIO.cleanup() - -with serial.Serial('/dev/ttyAMA0', 115200, timeout=2) as ser: - ser.write(b'AT\n') - line = ser.readline() - line = ser.readline() - print "Feedback: %s" % (line) - if line.strip() != "OK": - print "Modem reagiert nicht, evtl. abgeschaltet... wir schalten es ein..." - PowerOn() -ser.close() # close port -=== - -root@beielipi:~# cat /boot/config.txt +# cat /boot/config.txt ... # Wegen GSM Modul dtoverlay=pi3-miniuart-bt @@ -149,63 +112,19 @@ dtoverlay=pi3-miniuart-bt enable_uart=1 === -root@beielipi:~# cat /boot/cmdline.txt +# cat /boot/cmdline.txt dwc_otg.lpm_enable=0 root=PARTUUID=61612258-02 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait === +``` + +### Test SMS-Versand: +``` +gammu sendsms TEXT 0765006123 -text "Halooo von beielipi" +``` -root@beielipi:~# cat /root/.gammurc -; Diese Konfigurationsdatei wurde von gammu-detect erstellt. -; Bitte lesen Sie das Gammu-Benutzerhandbuch für weitere Informationen. - -[gammu] -device = /dev/ttyAMA0 -name = Telefon an serielle USB-Schnittstelle Silicon_Labs CP2102_USB_to_UART_Bri -dge_Controller angeschlossen -connection = at -pin = 8296 - -=== - - -SMS senden: - -$ gammu-smsd-inject TEXT 0765006123 -text "Hallo Velo" - - - -root@beielipi:/tmp# cat /etc/gammu-smsdrc -# Configuration file for Gammu SMS Daemon - -# Gammu library configuration, see gammurc(5) -[gammu] -# Please configure this! -port = /dev/ttyAMA0 -connection = at -# Debugging -#logformat = textall -logformat = errorsdate -pin = 8296 - -# SMSD configuration, see gammu-smsdrc(5) -[smsd] -service = files -#logfile = syslog -# Increase for debugging information -debuglevel = 0 -PIN = 8296 -RunOnReceive = /usr/local/bin/run_on_receive.sh - -# Paths where messages are stored -inboxpath = /var/spool/gammu/inbox/ -outboxpath = /var/spool/gammu/outbox/ -sentsmspath = /var/spool/gammu/sent/ -errorsmspath = /var/spool/gammu/error/ -=== - - -## Blabla - +### Installation Applikation +``` User/Gruppe erstellen: # groupadd -g 2000 beieli # useradd -m -g beieli beieli -s /bin/bash @@ -215,48 +134,21 @@ User/Gruppe erstellen: Passwoerter anpassen: # passwd pi => meielis-... +# Aus Git uebernehmen: +(auf anderem Rechner): +$ git clone https://git.nbit.ch/joerg/beielipi.git +$ cd beielipi +$ tar cvf /var/tmp/beielipi-git-files.tar . + +# cd /home/beieli && tar xvf /var/tmp/beielipi-git-files.tar +# su - beieli +beieli@beielipi:~ $ mkdir config_backups data send_sms_queue tmp web-csv +beieli@beielipi:~ $ exit +# cd /home/beieli/install_files +# for i in $(find . -type f); do echo cp $i /$i ; done + +Reboot: +# init 6 - -root@beielipi:~# rpi-update - *** Raspberry Pi firmware updater by Hexxeh, enhanced by AndrewS and Dom - *** Performing self-update - % Total % Received % Xferd Average Speed Time Time Time Current - Dload Upload Total Spent Left Speed -100 13403 100 13403 0 0 25182 0 --:--:-- --:--:-- --:--:-- 25193 - *** Relaunching after update - *** Raspberry Pi firmware updater by Hexxeh, enhanced by AndrewS and Dom - *** We're running for the first time - *** Backing up files (this will take a few minutes) - *** Backing up firmware - *** Backing up modules 4.9.41+ -############################################################# -This update bumps to rpi-4.9.y linux tree -Be aware there could be compatibility issues with some drivers -Discussion here: -https://www.raspberrypi.org/forums/viewtopic.php?f=29&t=167934 -############################################################## - *** Downloading specific firmware revision (this will take a few minutes) - % Total % Received % Xferd Average Speed Time Time Time Current - Dload Upload Total Spent Left Speed -100 168 0 168 0 0 25 0 --:--:-- 0:00:06 --:--:-- 35 -100 54.1M 100 54.1M 0 0 989k 0 0:00:56 0:00:56 --:--:-- 1153k - *** Updating firmware - *** Updating kernel modules - *** depmod 4.9.50-v7+ - *** depmod 4.9.50+ - *** Updating VideoCore libraries - *** Using HardFP libraries - *** Updating SDK - *** Running ldconfig - *** Storing current firmware revision - *** Deleting downloaded files - *** Syncing changes to disk - *** If no errors appeared, your firmware was successfully updated to a31db890da1e5135fe666909d562bdc6113c14d6 - *** A reboot is needed to activate the new firmware -root@beielipi:~# -root@beielipi:~# init 6 -Connection to 192.168.0.34 closed by remote host. -Connection to 192.168.0.34 closed. - - +``` diff --git a/bin/beielimon.py b/bin/beielimon.py index c11f664..b098d2c 100755 --- a/bin/beielimon.py +++ b/bin/beielimon.py @@ -10,13 +10,13 @@ """Beehive Monitoring""" from __future__ import print_function -import gammu.smsd import os import sys import serial import time import yaml import random +import string # Root Path APP_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) @@ -25,16 +25,12 @@ APP_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) with open("%s/bin/beielimon-config.yaml" % (APP_ROOT), 'r') as stream: try: config_data = yaml.load(stream) - #print(config_data) except yaml.YAMLError as exc: print(exc) # Constants INVALID_VALUE = -999 -# Interface to gammu-smsd -smsd = gammu.smsd.SMSD('/etc/gammu-smsdrc') - class Scale(object): def __init__(self, scale_config): self.last_values = [] @@ -54,7 +50,6 @@ class Scale(object): else: prefix = 'weight' datafilename = "%s/data/%s-%s-%s%s%s.log" % (APP_ROOT,prefix,self.scale_config['scale_uuid'],year,month,day) - #print('Log to File %s' % (datafilename)) with open(datafilename, 'a') as file: file.write('%s,%d\n' % (timestamp,weigh_in_gram)) @@ -62,8 +57,6 @@ class Scale(object): self.last_values.append(weigh_in_gram) if len(self.last_values) > config_data['number_of_samples']: self.last_values = self.last_values[1:] - #print('DEBUG WEIGHT: %d' % (weigh_in_gram)) - #print(self.last_values) # Wir loggen den Wert noch self.LogValue(weigh_in_gram,False) @@ -85,7 +78,6 @@ class Scale(object): def GetWeighLoss(self): last_value = self.GetLastValue() max_value = max(self.last_values or [0]) - #print('BBB: ',max_value,last_value) return (max_value - last_value) def GetScaleConfig(self): @@ -106,51 +98,19 @@ class ScaleUSB_PCE(Scale): try: res = int(weight_string[2:11]) except: - print('DEBUG WEIGHT STRING IS NOT AN INTEGER: %s' % (weight_string[2:11])) + print('Problem with Read Scale: weight string is not an integer: %s' % (weight_string[2:11])) else: - print('DEBUG WEIGHT STRING SHOULD BE IN GRAMS: but is [%s]' % (weight_string[12:13])) + print('Problem with Read Scale: weigth should be in grams, but is [%s]' % (weight_string[12:13])) else: - print('DEBUG WEIGHT STRING SHOULD BE 16 DIGITS: but is %d' % (len(weight_string))) + print('Problem with Read Scale: value should be 16 digits: but is %d' % (len(weight_string))) if res != INVALID_VALUE: self.AppendReading(res) -class ScaleBT_KDPSB(Scale): - def __init__(self,serial_int, scale_config): - Scale.__init__(self, scale_config) - self.ser = serial_int - - def Read(self): - res = INVALID_VALUE - try: - self.ser.write('\x02G\x03') - except: - print('DEBUG FEHLER BEIM SCHREIBEN') - time.sleep(1) - try: - weight_string = self.ser.read(12) - except: - print('DEBUG FEHLER BEIM LESEN') - weight_string='' - #print('DEBUG READ STRING HEX: %s' % (':'.join(x.encode('hex') for x in weight_string))) - #print('DEBUG READ STRING: %s' % (weight_string)) - if len(weight_string) == 12: - #print('DEBUG READ STRING BBB: %s' % (weight_string[1:8])) - res = int(float(weight_string[1:8])*1000) - #print('DEBUG GEWICHT IN GRAM: %s' % (weight_string)) - if res != INVALID_VALUE: - self.AppendReading(res) - - def CalibrateToZero(self): - try: - self.ser.write('\x02T\x03') - except: - print('DEBUG FEHLER BEIM KALIBRIEREN') - time.sleep(1) - class ScaleDummy(Scale): def __init__(self,scale_config): Scale.__init__(self, scale_config) + self.AppendReading(random.randint(500,1000)) def Read(self): # Gewichts- Zu/Abnahme ist Random, manchmal gibt es einen @@ -168,32 +128,19 @@ class ScaleDummy(Scale): def send_sms(phonenumbers , text): - for phonenumber in phonenumbers: - message = { - 'Text': text, - 'SMSC': {'Location': 1}, - 'Number': phonenumber - } - - #GELD SPAREN smsd.InjectSMS([message]) - smsd.InjectSMS([message]) - print("Send SMS to %s, Text: %s" % (phonenumber, text)) + data = {} + data['phonenumbers'] = phonenumbers + data['text'] = text + # wird von smsmon verarbeitet... + print("Send SMS to %s, Text: %s" % (phonenumbers, text)) + randomstr = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7)) + with open("%s/send_sms_queue/%s.yml" % (APP_ROOT,randomstr), "w") as outfile: + yaml.dump(data, outfile, default_flow_style=False) def main(): scales = [] for scale_config in config_data['scales']: - if scale_config['interface_type'] == 'bt_kdpsb': - #print('DEBUG: sudo /usr/bin/rfcomm bind ' + scale_config['interface_name'] + ' ' + scale_config['address'] + ' ' + scale_config['interface_channel']) - os.system('sudo /usr/bin/rfcomm bind ' + scale_config['interface_name'] + ' ' + scale_config['address'] + ' ' + scale_config['interface_channel']) - ser = serial.Serial(port='/dev/' + scale_config['interface_name'], - baudrate=9600, - bytesize=serial.EIGHTBITS, - parity=serial.PARITY_EVEN, - timeout=20) - scale=ScaleBT_KDPSB(ser, scale_config) - #scale.CalibrateToZero() - scales.append(scale) - elif scale_config['interface_type'] == 'usb_pce': + if scale_config['interface_type'] == 'usb_pce': ser = serial.Serial(port='/dev/' + scale_config['interface_name'], baudrate=9600, bytesize=serial.EIGHTBITS, diff --git a/bin/process_sms_request.py b/bin/process_sms_request.py deleted file mode 100755 index d90f12a..0000000 --- a/bin/process_sms_request.py +++ /dev/null @@ -1,283 +0,0 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# vim: expandtab sw=4 ts=4 sts=4: -# -# Beehive-Monitoring, process SMS Requests -# -# Author: Joerg Lehmann, nbit Informatik GmbH -# -"""Beehive Monitoring - SMS Processing""" - -from __future__ import print_function -import gammu.smsd -import os -import sys -import time -import yaml -import smtplib -import re -import glob -import shutil -from os.path import basename -from email.mime.application import MIMEApplication -from email.mime.multipart import MIMEMultipart -from email.mime.text import MIMEText -from email.utils import COMMASPACE, formatdate - -# Interface to gammu-smsd -smsd = gammu.smsd.SMSD('/etc/gammu-smsdrc') - -# Root Path -APP_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) - -# Read Configuration from YAML-File -with open("%s/bin/beielimon-config.yaml" % APP_ROOT, 'r') as stream: - try: - config_data = yaml.load(stream) - except yaml.YAMLError as exc: - print(exc) - -def send_sms(phonenumbers , text): - for phonenumber in phonenumbers: - message = { - 'Text': text, - 'SMSC': {'Location': 1}, - 'Number': phonenumber - } - - #GELD SPAREN smsd.InjectSMS([message]) - smsd.InjectSMS([message]) - print("Send SMS to %s, Text: %s" % (phonenumber, text)) - -def send_mail(send_from, send_to, subject, text, files=None): - os.system('/usr/bin/sudo %s/root-bin/connect_to_internet' % (APP_ROOT)) - msg = MIMEMultipart() - msg['From'] = send_from - msg['To'] = send_to - msg['Date'] = formatdate(localtime=True) - msg['Subject'] = subject - - msg.attach(MIMEText(text)) - - for f in files or []: - with open(f, "rb") as fil: - part = MIMEApplication( - fil.read(), - Name=basename(f) - ) - # After the file is closed - part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) - msg.attach(part) - - smtp = smtplib.SMTP(config_data['mailserver'],config_data['mailserver_port'],timeout=60) - smtp.set_debuglevel(1) - smtp.ehlo() - smtp.starttls() - smtp.login(config_data['mailuser'], config_data['mailpwd']) - smtp.sendmail(send_from, send_to, msg.as_string()) - smtp.close() - os.system('/usr/bin/sudo %s/root-bin/disconnect_from_internet' % (APP_ROOT)) - -def send_help(phonenumber,command): - # SMS Maximale Groesse: 140 Zeichen - if command == '': - sms_message = """Moegliche Befehle: - -help, info, balance, reboot, shutdown, hotspot - -Naehere Hilfe: help , z.B. help info""" - - elif command == 'info': - sms_message = """info - letzte Messwerte (SMS) -info 2017 - Messwerte 2017 (EMail) -info 201711 - Messwerte Nov. 2017 -info 20171102 - Messwerte 2. Nov. 2017""" - - elif command == 'help': - sms_message = "Zeigt die moeglichen Befehle an" - - elif command == 'balance': - sms_message = "Anforderung Info zum Prepaid-Guthaben" - - elif command == 'reboot': - sms_message = "Neustart des Raspberry Pi's" - - elif command == 'shutdown': - sms_message = """Herunterfahren des Raspberry Pi's - -ACHTUNG: ZUM STARTEN MUSS STROM AUS- UND WIEDER EINGESTECKT WERDEN! -""" - - elif command == 'hotspot': - sms_message = """hotspot on - Hotspot Funktion einschalten -hotspot off - Hotspot ausschalten - -Hotspot erlaubt ein Auslesen per Smartphone/Table (WLAN)""" - - send_sms([phonenumber],sms_message) - - -def GetLastValues(scale_uuid): - files = glob.glob("%s/data/weight-%s-????????.log" % (APP_ROOT,scale_uuid)) - if len(files) > 0: - with open(sorted(files)[-1], "r") as f: - for line in f: pass - result = line - - - # Beispiel: 2017-11-07 08:23,0 - m = re.match("(\d{4})-(\d{2})-(\d{2}) (\d\d:\d\d),(\d+)", result) - if m: - return "%sg (%s.%s.%s %s)" % (m.group(5),m.group(3),m.group(2),m.group(1),m.group(4)) - else: - return "Fehler beim Parsen: %s" % (result) - - else: - return "keine Messwerte" - -def CreateAttachements(infotime): - mypid = os.getpid() - mycsvdir = "%s/tmp/%s/csv" % (APP_ROOT,mypid) - if not os.path.exists(mycsvdir): - os.makedirs(mycsvdir) - myzipdir = "%s/tmp/%s/zip" % (APP_ROOT,mypid) - if not os.path.exists(myzipdir): - os.makedirs(myzipdir) - res = [] - my_pattern = '%s%s' % (infotime,'?' * (8 - len(infotime))) - files = glob.glob("%s/data/weight-*-%s.log" % (APP_ROOT,my_pattern)) - for s in config_data['scales']: - filename = "%s/%s-%s.csv" % (mycsvdir,s['alias'].replace(' ','_'),infotime) - with_data = False - with open(filename, 'a') as file: - for ifile in sorted(files): - if (s['scale_uuid'] in ifile) and (infotime in ifile): - with_data = True - with open(ifile, 'r') as ifile: - for line in ifile: - m = re.match("(\d{4})-(\d{2})-(\d{2}) (\d\d:\d\d),(\d+)", line) - if m: - file.write("%s.%s.%s %s,%s\n" % (m.group(3),m.group(2),m.group(1),m.group(4),m.group(5))) - else: - file.write("Fehler beim Parsen: %s" % (line)) - if with_data: - res.append(filename) - - zipfile = "%s/%s" % (myzipdir,infotime) - shutil.make_archive(zipfile, 'zip', mycsvdir) - return [ "%s.zip" % (zipfile) ] - -def send_report(infotime): - # Send EMail Report - my_text = my_text = "Letzte Messwerte:\n" - for s in config_data['scales']: - my_text += "%s: %s\n" % (s['alias'],GetLastValues(s['scale_uuid'])) - my_text += "\n\nIm ZIP-File sind die Messwerte der gewuenschten Periode enthalten. Die Daten sind im CSV-Format abgespeichert und koennen z.B. mit Excel analysiert werden.\n" - attachements = CreateAttachements(infotime) - - #send_mail(config_data['mailfrom'],config_data['mailto'],'Messwerte BeieliPi',my_text,attachements) - -def send_info_sms(phonenumber): - my_text = "Letzte Messwerte:\n" - for s in config_data['scales']: - my_text += "%s: %s\n" % (s['alias'],GetLastValues(s['scale_uuid'])) - - send_sms([phonenumber],my_text) - -def send_info(phonenumber, message_uc): - print("AAA: send_info %s" % message_uc) - m = re.match(".*(INFO)\s+(\d{8})", message_uc) - if m: - send_report(m.group(2)) - print("BBB: send_info %s" % message_uc) - else: - m = re.match(".*(INFO)\s+(\d{6})", message_uc) - if m: - send_report(m.group(2)) - print("CCC: send_info %s %s" % (message_uc,m.group(2))) - else: - m = re.match(".*(INFO)\s+(\d{4})", message_uc) - if m: - send_report(m.group(2)) - print("DDD: send_info %s" % message_uc) - else: - send_info_sms(phonenumber) - print("EEE: send_info %s" % message_uc) - -def balance(): - send_sms([config_data['balance_number']],config_data['balance_command']) - -def reboot(): - os.system('/usr/bin/sudo /sbin/init 6') - -def shutdown(): - os.system('/usr/bin/sudo /sbin/init 0') - -def hotspot_on(): - os.system('/usr/bin/sudo %s/root-bin/hotspot_on' % (APP_ROOT)) - -def hotspot_off(): - os.system('/usr/bin/sudo %s/root-bin/hotspot_off' % (APP_ROOT)) - -def command_not_understood(phonenumber, message): - send_sms([phonenumber],'Befehl nicht verstanden: %s\n\nMoegliche Befehle: help, info, balance, reboot, shutdown, hotspot' % (message[:50])) - -def main(): - print('%s was called at %s with these arguments: %s\n' % (sys.argv[0],formatdate(localtime=True),str(sys.argv))) - if len(sys.argv) != 3: - print("Da kann etwas nicht stimmen, ungueltige Anzahl Argumente") - sys.exit(1) - - phonenumber = sys.argv[1] - message = sys.argv[2] - - # Falls es von forward_sms_from_this_number kommt, machen wir ein Foward an - # die Master Nummer - if phonenumber == config_data['forward_sms_from_this_number']: - send_sms([config_data['master_sms_number']],message) - - else: - # message in Grossbuchstaben (damit Gross-/Kleinschreibung keine Rolle spielt) - message_uc = message.upper() - - # Bestimmung, ob es eine gueltige Telefonnummer ist - valid_number = False - for s in config_data['scales']: - if phonenumber in s['sms_alert_phonenumbers']: - valid_number = True - - if not valid_number: - print("Da versucht ein unberechtigter, etwas abzufragen... (Nummer: %s)" % (phonenumber)) - sys.exit(2) - - if 'HELP INFO' in message_uc: - send_help(phonenumber,'info') - elif 'HELP HELP' in message_uc: - send_help(phonenumber,'help') - elif 'HELP BALANCE' in message_uc: - send_help(phonenumber,'balance') - elif 'HELP REBOOT' in message_uc: - send_help(phonenumber,'reboot') - elif 'HELP SHUTDOWN' in message_uc: - send_help(phonenumber,'shutdown') - elif 'HELP HOTSPOT' in message_uc: - send_help(phonenumber,'hotspot') - elif 'HELP' in message_uc: - send_help(phonenumber,'') - elif 'INFO' in message_uc: - send_info(phonenumber, message_uc) - elif 'BALANCE' in message_uc: - balance() - elif 'REBOOT' in message_uc: - reboot() - elif 'SHUTDOWN' in message_uc: - shutdown() - elif 'HOTSPOT OFF' in message_uc: - hotspot_off() - elif 'HOTSPOT ON' in message_uc: - hotspot_on() - else: - command_not_understood(phonenumber, message) - -if __name__ == "__main__": - main() diff --git a/bin/smsmon.py b/bin/smsmon.py index f0ee840..17cd637 100755 --- a/bin/smsmon.py +++ b/bin/smsmon.py @@ -32,7 +32,6 @@ APP_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) # Set Default Encoding to UTF-8 reload(sys) # Reload does the trick! sys.setdefaultencoding('UTF8') -print(sys.getdefaultencoding()) # State Machine fuer Gammu sm = gammu.StateMachine() @@ -52,7 +51,7 @@ def send_sms(phonenumbers , text): 'Number': phonenumber } - #GELD SPAREN smsd.InjectSMS([message]) + #GELD SPAREN sm.SendSMS(message) sm.SendSMS(message) print("Send SMS to %s, Text: %s" % (phonenumber, text)) @@ -65,7 +64,7 @@ def send_mail(send_from, send_to, subject, text, files=None): msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject - msg.attach(MIMEText(text)) + msg.attach(MIMEText(text,"plain","utf-8")) for f in files or []: with open(f, "rb") as fil: @@ -77,7 +76,7 @@ def send_mail(send_from, send_to, subject, text, files=None): part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) msg.attach(part) - smtp = smtplib.SMTP(config_data['mailserver'],config_data['mailserver_port'],timeout=60) + smtp = smtplib.SMTP(config_data['mailserver'],config_data['mailserver_port'],timeout=120) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() @@ -144,6 +143,17 @@ def GetLastValues(scale_uuid): else: return "keine Messwerte" + +def ProcessSend_SMS_Queue(): + files = glob.glob("%s/send_sms_queue/*yml" % (APP_ROOT)) + for f in files: + with open("%s" % f, 'r') as stream: + try: + sms_data = yaml.load(stream) + except yaml.YAMLError as exc: + print(exc) + os.remove(f) + send_sms(sms_data['phonenumbers'],sms_data['text']) def CreateAttachements(infotime): mypid = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7)) @@ -173,16 +183,36 @@ def CreateAttachements(infotime): if with_data: res.append(filename) + files = glob.glob("%s/data/swarmalarm-*-%s.log" % (APP_ROOT,my_pattern)) + for s in config_data['scales']: + filename = "%s/Schwarmalarm-%s-%s.csv" % (mycsvdir,s['alias'].replace(' ','_'),infotime) + with_data = False + with open(filename, 'a') as file: + for ifile in sorted(files): + if (s['scale_uuid'] in ifile) and (infotime in ifile): + with_data = True + with open(ifile, 'r') as ifile: + for line in ifile: + m = re.match("(\d{4})-(\d{2})-(\d{2}) (\d\d:\d\d),(\d+)", line) + if m: + file.write("%s.%s.%s %s\n" % (m.group(3),m.group(2),m.group(1),m.group(4))) + else: + file.write("Fehler beim Parsen: %s" % (line)) + if with_data: + res.append(filename) + + zipfile = "%s/%s" % (myzipdir,infotime) zipfile = "%s/%s" % (myzipdir,infotime) shutil.make_archive(zipfile, 'zip', mycsvdir) return [ "%s.zip" % (zipfile) ] def send_report(infotime): # Send EMail Report - my_text = my_text = "Letzte Messwerte:\n" + my_text = my_text = "Diese Meldung ist die Antwort auf die SMS-Anfrage \"info %s\"\n\n" % (infotime) + my_text += "Letzte Messwerte:\n" for s in config_data['scales']: my_text += "%s: %s\n" % (s['alias'],GetLastValues(s['scale_uuid'])) - my_text += "\n\nIm ZIP-File sind die Messwerte der gewuenschten Periode enthalten. Die Daten sind im CSV-Format abgespeichert und koennen z.B. mit Excel analysiert werden.\n" + my_text += "\n\nIm ZIP-File sind die Messwerte der angefragten Periode enthalten. Die Messdaten sind im CSV-Format abgespeichert und können z.B. mit Excel analysiert werden.\n\n" attachements = CreateAttachements(infotime) send_mail(config_data['mailfrom'],config_data['mailto'],'Messwerte BeieliPi',my_text,attachements) @@ -195,24 +225,19 @@ def send_info_sms(phonenumber): send_sms([phonenumber],my_text) def send_info(phonenumber, message_uc): - print("AAA: send_info %s" % message_uc) m = re.match(".*(INFO)\s+(\d{8})", message_uc) if m: send_report(m.group(2)) - print("BBB: send_info %s" % message_uc) else: m = re.match(".*(INFO)\s+(\d{6})", message_uc) if m: send_report(m.group(2)) - print("CCC: send_info %s %s" % (message_uc,m.group(2))) else: m = re.match(".*(INFO)\s+(\d{4})", message_uc) if m: send_report(m.group(2)) - print("DDD: send_info %s" % message_uc) else: send_info_sms(phonenumber) - print("EEE: send_info %s" % message_uc) def balance(): send_sms([config_data['balance_number']],config_data['balance_command']) @@ -298,26 +323,25 @@ def main(): sm.Init() counter = 0 status = sm.GetSMSStatus() - print(status) + #print(status) remain = status['SIMUsed'] + status['PhoneUsed'] + status['TemplatesUsed'] - print("remain: %d\n" % (remain)) - if remain: firstsms = sm.GetNextSMS(Start = True, Folder = 0) - print("FIRSTSMS: %s" % (firstsms)) + #print("FIRSTSMS: %s" % (firstsms)) for x in range(len(firstsms)): sm.DeleteSMS(firstsms[x]['Folder'], firstsms[x]['Location']) - print("sm.DeleteSMS: %s %s" % (firstsms[x]['Folder'], firstsms[x]['Location'])) + #print("sm.DeleteSMS: %s %s" % (firstsms[x]['Folder'], firstsms[x]['Location'])) number = firstsms[x]['Number'] message = firstsms[x]['Text'] - print(number,message) + #print(number,message) print("process_received_sms %s %s" % (number,message)) process_received_sms(number,message) remain = remain - len(firstsms) sys.stdout.flush() - time.sleep(10) + ProcessSend_SMS_Queue() + time.sleep(15) diff --git a/install-files/etc/default/gammu-smsd b/install-files/etc/default/gammu-smsd deleted file mode 100644 index 6249e73..0000000 --- a/install-files/etc/default/gammu-smsd +++ /dev/null @@ -1,15 +0,0 @@ -# Defaults for gammu-smsd initscript -# sourced by /etc/init.d/gammu-smsd -# installed at /etc/default/gammu-smsd by the maintainer scripts - -# -# This is a POSIX shell fragment -# - -# Additional options that are passed to the Daemon. -DAEMON_OPTS="" - -# user to use (gammu is default) -#USER=gammu -USER=beieli - diff --git a/install-files/etc/gammurc b/install-files/etc/gammurc new file mode 100644 index 0000000..f962880 --- /dev/null +++ b/install-files/etc/gammurc @@ -0,0 +1,8 @@ +[gammu] +# Please configure this! +port = /dev/ttyAMA0 +connection = at +# Debugging +#logformat = textall +logformat = errorsdate +#pin = 8296 diff --git a/install-files/etc/sudoers.d/beieli b/install-files/etc/sudoers.d/beieli index 9826477..cc1422b 100644 --- a/install-files/etc/sudoers.d/beieli +++ b/install-files/etc/sudoers.d/beieli @@ -1 +1 @@ -beieli ALL=(ALL) NOPASSWD: /sbin/init,/home/beieli/root-bin/connect_to_internet,/home/beieli/root-bin/disconnect_from_internet,/home/beieli/root-bin/hotspot_on,/home/beieli/root-bin/hotspot_off +beieli ALL=(ALL) NOPASSWD: /sbin/init,/home/beieli/root-bin/connect_to_internet,/home/beieli/root-bin/disconnect_from_internet,/home/beieli/root-bin/hotspot_on,/home/beieli/root-bin/hotspot_off,/home/beieli/root-bin/sync_time_with_internet diff --git a/install-files/etc/systemd/system/gammu-smsd.service b/install-files/etc/systemd/system/gammu-smsd.service deleted file mode 100644 index 6523392..0000000 --- a/install-files/etc/systemd/system/gammu-smsd.service +++ /dev/null @@ -1,18 +0,0 @@ -[Unit] -Description=SMS daemon for Gammu -Documentation=man:gammu-smsd(1) -After=mysql.service postgresql.service - -[Service] -EnvironmentFile=-/etc/sysconfig/gammu-smsd -# Run daemon as root user -#ExecStart=/usr/bin/gammu-smsd --pid=/var/run/gammu-smsd.pid --daemon -# Run daemon as non-root user (set user/group in /etc/sysconfig/gammu-smsd) -ExecStart=/usr/bin/gammu-smsd --user=beieli --group=gammu --pid=/var/run/gammu-smsd.pid --daemon -ExecReload=/bin/kill -HUP $MAINPID -ExecStopPost=/bin/rm -f /var/run/gammu-smsd.pid -Type=forking -PIDFile=/var/run/gammu-smsd.pid - -[Install] -WantedBy=multi-user.target diff --git a/install-files/etc/systemd/system/smsmon.service b/install-files/etc/systemd/system/smsmon.service new file mode 100644 index 0000000..8ca224d --- /dev/null +++ b/install-files/etc/systemd/system/smsmon.service @@ -0,0 +1,15 @@ +[Unit] +Description=smsmon service +After=syslog.target +After=network.target + +[Service] +Type=simple +User=beieli +Group=beieli +WorkingDirectory=/home/beieli/bin +ExecStart=/home/beieli/bin/smsmon.py +Restart=always + +[Install] +WantedBy=multi-user.target diff --git a/root-bin/connect_to_internet b/root-bin/connect_to_internet index 10e6547..1cd5007 100755 --- a/root-bin/connect_to_internet +++ b/root-bin/connect_to_internet @@ -1,18 +1,18 @@ #!/bin/bash echo "$(date): Connect to Internet..." -#systemctl stop gammu-smsd pon rnet -sleep 20 +sleep 5 +x=0 # Wait until connection is established -if ping -c 1 8.8.8.8 &>/dev/null ; then - echo "Already Connected - $(date)" -else - echo "Not Connected - $( date )" - echo "connecting wait ..." - sleep 20 -fi - -# Wir wollen sicher sein, dass die Verbindung steht... -ping -c 1 -w 30 8.8.8.8 >/dev/null -sleep 3 +while ! ping -c 1 8.8.8.8 &>/dev/null ; do + echo "$(date): wait for internet connection to come up" + sleep 5 + if [ $x -gt 10 ]; then + # Time out here + echo "$(date): Could not connect to internet (timeout)..." + exit 1 + fi + x=$((x+1)) +done +echo "$(date): Connected to Internet..." diff --git a/root-bin/disconnect_from_internet b/root-bin/disconnect_from_internet index e571123..9f028de 100755 --- a/root-bin/disconnect_from_internet +++ b/root-bin/disconnect_from_internet @@ -1,6 +1,5 @@ #!/bin/bash echo "$(date): Disconnect from Internet..." poff rnet -sleep 10 -#systemctl start gammu-smsd +sleep 5 pkill pppd diff --git a/root-bin/my_web_server.py b/root-bin/my_web_server.py index 6f3ddbf..577ddf1 100755 --- a/root-bin/my_web_server.py +++ b/root-bin/my_web_server.py @@ -18,7 +18,6 @@ APP_ROOT = "/home/beieli" with open("%s/bin/beielimon-config.yaml" % (APP_ROOT), 'r') as stream: try: config_data = yaml.load(stream) - #print(config_data) except yaml.YAMLError as exc: print(exc) @@ -98,6 +97,8 @@ def GetInfoText(): commands_output = "" for comm_arr in [ ['uptime','--pretty'], + ['date'], + ['uname', '-a'], ['df','-h','/boot','/root'], ['free','-m'], ['ip','a'] ]: @@ -200,8 +201,6 @@ def download(infotime): os.makedirs(myzipdir) my_pattern = '%s%s' % (infotime,'?' * (8 - len(infotime))) files = glob.glob("%s/data/weight-*-%s.log" % (APP_ROOT,my_pattern)) - for f in files: - print("%s" % (f)) for s in config_data['scales']: filename = "%s/%s-%s.csv" % (mycsvdir,s['alias'].replace(' ','_'),infotime) with open(filename, 'a') as file: diff --git a/root-bin/run_on_receive.sh b/root-bin/run_on_receive.sh deleted file mode 100755 index fba6569..0000000 --- a/root-bin/run_on_receive.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -PROGRAM=/home/beieli/bin/process_sms_request.py -echo "Received $SMS_MESSAGES physical messages and $DECODED_PARTS of decoded message parts" >> /tmp/process_sms_request.log 2>&1 -for i in `seq $SMS_MESSAGES` ; do - eval "/usr/bin/sudo -u beieli $PROGRAM \"\${SMS_${i}_NUMBER}\" \"\${SMS_${i}_TEXT}\" >> /tmp/process_sms_request.log 2>&1" -done -exit 0