#!/usr/bin/python
# -*- coding: latin-1 -*-

import cherrypy
import platform
import os, sys
import datetime
import wget
from shutil import copyfile
import platform
import sqlite3 as lite
import pandas as pd
import numpy as np
import pickle
import matplotlib.pyplot as plt
import matplotlib
import time
from threading import Timer
from sqlite3 import dbapi2 as sqlite
from FreeSolRaspi_Helper import InitialisiereDB


if platform.system()!="Windows":
    import RPi.GPIO as GPIO

# Softwareversion    
Version= "0.95"
# 21.5.19 

print()
print("Analysestart. Alle Module erfolgreich importiert.")
print()

print("Datum, Uhrzeit: ")
print(datetime.datetime.now())
print()

print("Version Python: "+platform.python_version())
print()

print("Betriebssystem:")
print(platform.platform())
print(platform.system())
print(platform.release())
print(platform.version())
print()

print("Versionen wichtiger Pythonmodule")
print("pandas: "+str(pd.__version__))
print("matplotlib: "+str(matplotlib.__version__))
print("numpy: "+str(np.__version__))
print("cherrypy: "+str(cherrypy.__version__))
if platform.system()!="Windows":
    print("RPi: "+str(GPIO.VERSION))
print()


print("Versionen der FreeSol-Module")
Ergebnis={}
Software_Files = ['CherryPy-Zaehler.py', 'FreeSolRaspi_SolarZaehl.py', 'S0_Solar.py', 'S0_Solar_Test.py', 'Systemanalyse.py']
Startfilepfad=os.path.dirname(os.path.realpath(sys.argv[0]))

for File in Software_Files:
    Version=""
    with open(os.path.join(Startfilepfad,File), 'rb') as search:
        for line in search:
            if "Version=" in str(line):
                Version= str(line).split(" ")[1].replace("\\r\\n", "\\n").replace("\\n", "")[1:-2]
                break
    Ergebnis.update({File : Version})
Ergebnis.update({File : Version})    
for key in  Ergebnis:
    print(key +": "+Ergebnis[key])
print()

if platform.system()!="Windows":
    print("Pruefung wichtiger Systempfade")
    os.system('pwd')
    os.system('ls -l')
    print()
    os.system('ls -l "/" ')
    print()


if platform.system()!="Windows":    
    print("Test der S0-Schnittstelle")
    print(" ... der Test startet jetzt und dauert bis zu 1 Minute. Im Livemodus wird jeder empfangene Impuls wird angezeigt, ")
    print(" ... beim Abfangen des Outputs in in File wird zumindest die Gesamtzahl der Impulse gezeigt")
    
    def Interrupt1(channel):
        global Counter1
        input_value = GPIO.input(22)
        Counter1 = Counter1 + 1
        
    # S0-Interrupt einrichten
    # Kommando Pinout oder: https://raspberrypi.stackexchange.com/questions/12966/what-is-the-difference-between-board-and-bcm-for-gpio-pin-numbering
    GPIO.setmode(GPIO.BCM) #Hier Nummernsystem GPIO15, nicht die Nummern der reihe nach am Stecker (das wäre BOARD)
    GPIO.setup(22, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
        
    GPIO.add_event_detect(22, GPIO.FALLING, callback=Interrupt1, bouncetime = 200)
    
    Counter1 = 0
    
    #print("start")
    # Jede Minute den Counter abspeichern    
    z_alt = time.strftime("%M")
    while True:
        time.sleep(0.1) # Dieser Befehl erzeugt 100 ms keine CPU Last
        z = time.strftime("%M")
        if z != z_alt:
            S0 = Counter1
            Counter1 = 0
            date = time.strftime("%Y-%m-%d %H:%M:%S")
            print("Wert", date, S0)
            print("Zahl der empfangenen S0-Impulse", S0)
            z_alt = z
            break
    print()
    
print("Ende der Analyse")

