Browse Source

first commit

tsi 6 years ago
commit
6a41f3bc14
7 changed files with 202 additions and 0 deletions
  1. 8 0
      config/fb.conf
  2. 28 0
      config/ssmtp.conf
  3. 26 0
      scripts/check_vpn.sh
  4. 57 0
      scripts/rpi_serial.py
  5. 55 0
      scripts/send_email.py
  6. 16 0
      service/rpi_serial.service
  7. 12 0
      service/vpnc@.service

+ 8 - 0
config/fb.conf

@@ -0,0 +1,8 @@
+IPSec gateway 178.202.86.170
+IPSec ID rpi_vpn
+IPSec secret 1fUnV3vLS5vAbPFS
+IKE Authmode psk
+Xauth username rpi_vpn
+Xauth password Dac0s0.
+local port 0
+DPD idle timeout (our side) 0

+ 28 - 0
config/ssmtp.conf

@@ -0,0 +1,28 @@
+#
+# Config file for sSMTP sendmail
+#
+# The person who gets all mail for userids < 1000
+# Make this empty to disable rewriting.
+root=postmaster
+
+# The place where the mail goes. The actual machine name is required no 
+# MX records are consulted. Commonly mailhosts are named mail.domain.com
+mailhub=mail
+
+# Where will the mail seem to come from?
+#rewriteDomain=
+
+# The full hostname
+hostname=raspberrypi
+
+# Are users allowed to set their own From: address?
+# YES - Allow the user to specify their own From: address
+# NO - Use the system generated From: address
+#FromLineOverride=YE
+#
+UseSTARTTLS=YES
+FromLineOverride=YES
+root=admin@example.com
+mailhub=smtp.outlook.com:587
+AuthUser=net_flix_11@outlook.de
+AuthPass=kathrein47

+ 26 - 0
scripts/check_vpn.sh

@@ -0,0 +1,26 @@
+#!/bin/sh
+
+LOG_FILE=/var/log/vpn_check.log
+now=$(date)
+
+
+echo "${now} - Running Check" | tee -a ${LOG_FILE}
+
+curl -sI https://tbsgl.xyz/vpn | grep "HTTP/2 200" | grep -v grep > /dev/null
+# Check if VPN-On Flag is set
+if [ $? = 0 ]
+	then
+	ping -c 1 192.168.178.1 | grep "64 bytes from" | grep -v grep > /dev/null
+	# Check if VPN is already connected
+	if [ $? != 0 ]
+		then
+		# If not, then Restart VPN
+		systemctl restart vpnc@fb > /dev/null
+		echo "Ping not successful - Restarting VPN\n" | tee -a ${LOG_FILE}
+	else
+		echo "Ping reached router, doing nothing\n" | tee -a ${LOG_FILE}
+	fi
+else
+	systemctl stop vpnc@fb
+	echo "VPN Flag seems to be disabled or no Internet, stopping service\n" | tee -a ${LOG_FILE}
+fi

+ 57 - 0
scripts/rpi_serial.py

@@ -0,0 +1,57 @@
+#!/usr/bin/python3.7
+
+import re, serial, logging, datetime
+from influxdb import InfluxDBClient
+
+# Logging 
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+handler = logging.FileHandler('rpi_serial.log')
+handler.setLevel(logging.INFO)
+formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+handler.setFormatter(formatter)
+logger.addHandler(handler)
+
+# InfluxDB
+client = InfluxDBClient(host="localhost", port=8086)
+client.switch_database("solar")
+
+# Regex Prep
+regex = r"(\d{2}\.\d{2}\.\d{4})\s*(\d{2}:\d{2}:\d{2})\s*(\d{1,2})\s*(\d+\.\d{1})\s*(\d+\.\d{2})\s*(\d+)\s*(\d+\.\d{1})\s*(\d+\.\d{2})\s*(\d+)\s*(\d+)"
+pattern = re.compile(regex)
+
+# Setup
+serial_port = '/dev/ttyUSB0'
+
+def field_janitor(value_list):
+    fields = {'mode': value_list[0][2],
+              'generatorspannung': float(value_list[0][3]),
+              'generatorstrom': float(value_list[0][4]),
+              'generatorleistung': float(value_list[0][5]),
+              'netzspannung': float(value_list[0][6]),
+              'netzstrom': float(value_list[0][7]),
+              'eingespeiste_leistung': float(value_list[0][8]),
+              'temperatur': float(value_list[0][9]) }
+    return fields
+
+try:
+    ser = serial.Serial(serial_port)
+    logger.info("Connected to Serial Port, start polling")
+except:
+    logger.error("Couldn't connect to serial port {}".format(serial_port))
+    raise
+
+while True:
+    line = ser.readline().decode('utf-8')
+    print(line)
+    value_list = pattern.findall(line)
+    print(len(value_list))
+    if value_list and len(value_list[0]) == 10:
+        measure = {}
+        measure['measurement'] = "Tannenstrasse"
+        date = datetime.datetime.strptime(value_list[0][0] + "-" + value_list[0][1], "%d.%m.%Y-%X").strftime('%s')
+        measure['time'] = int(date) - 3600
+        measure['fields'] = field_janitor(value_list)
+        client.write_points([measure], time_precision="s")
+    else:
+        logger.warning("received invalid line: {}".format(line))

+ 55 - 0
scripts/send_email.py

@@ -0,0 +1,55 @@
+import urllib.request, tempfile, smtplib, email, time
+from datetime import datetime
+tmpdir = tempfile.TemporaryDirectory() 
+urllib.request.urlretrieve("http://192.168.178.201:3000/render/d-solo/-wCxs6mgk/solaranlage?orgId=1&refresh=10s&panelId=2&from=" + str((1000*int(time.time()))-(24*3600000)) + "&to=" + str(1000*int(time.time())) + "&width=600&height=300&tz=Europe%2FBerlin", tmpdir.name + "/leistung.png")
+
+# Send an HTML email with an embedded image and a plain text message for
+# email clients that don't want to display the HTML.
+
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+from email.mime.image import MIMEImage
+
+# Define these once; use them twice!
+strFrom = 'net_flix_11@outlook.de'
+strTo = ["tobias.siegel@outlook.com", "t.siegel91@gmail.com","wsiegel@web.de"]
+
+# Create the root message and fill in the from, to, and subject headers
+msgRoot = MIMEMultipart('related')
+msgRoot['Subject'] = datetime.today().strftime('%Y-%m-%d') + ' Solaranlage'
+msgRoot['From'] = strFrom
+msgRoot['To'] = ",".join(strTo)
+msgRoot.preamble = 'This is a multi-part message in MIME format.'
+
+# Encapsulate the plain and HTML versions of the message body in an
+# 'alternative' part, so message agents can decide which they want to display.
+msgAlternative = MIMEMultipart('alternative')
+msgRoot.attach(msgAlternative)
+
+msgText = MIMEText('This is the alternative plain text message.')
+msgAlternative.attach(msgText)
+
+# We reference the image in the IMG SRC attribute by the ID we give it below
+msgText = MIMEText('<img src="cid:image1">', 'html')
+msgAlternative.attach(msgText)
+
+# This example assumes the image is in the current directory
+fp = open(tmpdir.name + '/leistung.png', 'rb')
+msgImage = MIMEImage(fp.read())
+fp.close()
+
+# Define the image's ID as referenced above
+msgImage.add_header('Content-ID', '<image1>')
+msgRoot.attach(msgImage)
+
+# Send the email (this example assumes SMTP authentication is required)
+import smtplib, ssl
+context = ssl.create_default_context()
+with smtplib.SMTP('smtp.outlook.com', 587) as server:
+    server.ehlo()  # Can be omitted
+    server.starttls(context=context)
+    server.ehlo()  # Can be omitted
+    server.login(strFrom, 'kathrein47')
+    server.sendmail(strFrom, strTo, msgRoot.as_string())
+
+tmpdir.cleanup()

+ 16 - 0
service/rpi_serial.service

@@ -0,0 +1,16 @@
+[Unit]
+Description=Serial-Connector logger for Solar
+After=syslog.target
+StartLimitBurst=5
+
+[Service]
+Type=simple
+ExecStart=/home/pi/rpi_serial.py
+SyslogIdentifier=rpi_serial
+StandardOutput=syslog
+StandardError=syslog
+Restart=always
+RestartSec=30
+
+[Install]
+WantedBy=multi-user.target

+ 12 - 0
service/vpnc@.service

@@ -0,0 +1,12 @@
+[Unit]                                                                                                                                                                  
+Description=VPNC connection to %i
+Wants=network-online.target
+After=network.target network-online.target
+
+[Service]
+Type=forking
+ExecStart=/usr/sbin/vpnc --pid-file=/run/vpnc@%i.pid /etc/vpnc/%i.conf
+PIDFile=/run/vpnc@%i.pid
+
+[Install]
+WantedBy=multi-user.target