#!/usr/bin/env python

import time
import urllib
import subprocess
import smtplib

#--- Variablen deklarieren ------------------------------------------------------------------------

Fehler = 0

#--- Logbuch anlegen ------------------------------------------------------------------------------

File = open("/volume1/web/robi.log", "a")
File.write("*** "+time.strftime("%Y-%m-%d %H:%M:%S")+" ***\n")

#--- Checksumme pruefen ---------------------------------------------------------------------------

def AddToCRC(b, crc):
    b2 = b
    if (b < 0):
        b2 = b + 256
    for i in xrange(8):
        odd = ((b2^crc) & 1) == 1
        crc >>= 1
        b2 >>= 1
        if (odd):
            crc ^= 0x8C
    return crc

def CalcCheckSum(WebAnswer):
	hex = ""
	i = 1
	while i < (len(WebAnswer.split('-'))-2):
		hex = hex + WebAnswer.split('-')[i]
		i = i + 1
	byte = bytearray(hex.decode("hex"))
	checksum = 0
	for i in byte:
		checksum = AddToCRC(i, checksum)
	return checksum

#--- Syntax-Pruefung ------------------------------------------------------------------------------

def CheckSyntax(WebAnswer, Fehler):
	if (WebAnswer.split('-')[0] == "02"):
		print "Erstes Byte....passt"
	else:
		print "Fehler: Erstes Byte falsch: %s" % WebAnswer.split('-')[0]
		Fehler = Fehler + 1

	if WebAnswer.split('-')[len(WebAnswer.split('-'))-2] == hex(CalcCheckSum(WebAnswer))[2:].rjust(2, "0"):
		print "Checksumme.....passt"
	else:
		print "Fehler Checksumme falsch: " + (WebAnswer.split('-')[len(WebAnswer.split('-'))-2]) + " <> " + (hex(CalcCheckSum(WebAnswer))[2:].rjust(2, "0"))
		Fehler = Fehler + 1
		
	if WebAnswer.split('-')[len(WebAnswer.split('-'))-1] == "03":
		print "Letztes Byte...passt"
	else:
		print "Fehler: Letztes Byte falsch: %s" % WebAnswer.split('-')[len(WebAnswer.split('-'))-1]
		Fehler = Fehler + 1

	return Fehler

#--- WebAnswer analysieren ------------------------------------------------------------------------

def AnalyseBytes(WebAnswer, StartByte, Bytes):
	hex = ""
	i = 0
	while i < Bytes:
		hex = hex + WebAnswer.split('-')[StartByte+Bytes-i-1]
		i = i + 1
	val = int(hex, 16);
	if Bytes > 1:
		if (val & (1 << ((Bytes * 8) - 1))) != 0:
			val = val - (1 << (Bytes * 8))
	return val

#--- Verbindung pruefen ---------------------------------------------------------------------------

try:
	f = urllib.urlopen("http://192.168.x.y/")
	Connection = True
except:
	print "\nFehler beim Verbindungsaufbau!"
	File.write("Fehler beim Verbindungsaufbau!\n")
	Connection = False
	
#--- Status abfragen ------------------------------------------------------------------------------

if Connection:
	print "\nStatus:"

	f = urllib.urlopen("http://192.168.x.y/send?cmd=02-12-01-01-9F-03")
	WebAnswer = f.read()
	print WebAnswer
	File.write("Status.............."+WebAnswer+"\n")
	Fehler = CheckSyntax(WebAnswer, Fehler)

	Status = AnalyseBytes(WebAnswer,  4, 1)
		
	print "Status = %d" % Status

#--- Batterie-Status abfragen ----------------------------------------------------------------------

if Connection:
	print "\nBatterie-Status:"

	f = urllib.urlopen("http://192.168.x.y/send?cmd=02-14-01-01-4E-03")
	WebAnswer = f.read()
	print WebAnswer
	File.write("Batterie-Status....."+WebAnswer+"\n")
	Fehler = CheckSyntax(WebAnswer, Fehler)

	U = str(round((AnalyseBytes(WebAnswer,  4, 2)/1000.0), 3))
	Q = str(round((AnalyseBytes(WebAnswer,  6, 2)), 0))
	I = str(round((AnalyseBytes(WebAnswer,  8, 2)), 0))
	T = str(round((AnalyseBytes(WebAnswer, 10, 1)/10.0 + AnalyseBytes(WebAnswer, 11, 1)*25.5) , 3))
	
	print "U = %sV"    % U
	print "Q = %smAh"  % Q
	print "I = %smA"   % I
	print "T = %sgrdC" % T

#--- Radmotor-Status abfragen ----------------------------------------------------------------------

if Connection:
	print "\nRadmotor-Status:"

	f = urllib.urlopen("http://192.168.x.y/send?cmd=02-14-01-02-AC-03")
	WebAnswer = f.read()
	print WebAnswer
	File.write("Radmotor-Status....."+WebAnswer+"\n")
	Fehler = CheckSyntax(WebAnswer, Fehler)

	P_links =  str(round((AnalyseBytes(WebAnswer,  4, 2)), 0))
	n_links =  str(round((AnalyseBytes(WebAnswer,  6, 2)), 0))
	I_links =  str(round((AnalyseBytes(WebAnswer,  8, 2)), 0))
	P_rechts = str(round((AnalyseBytes(WebAnswer, 10, 2)), 0))
	n_rechts = str(round((AnalyseBytes(WebAnswer, 12, 2)), 0))
	I_rechts = str(round((AnalyseBytes(WebAnswer, 14, 2)), 0))

	print "P_links  = %s%%"    % P_links
	print "n_links  = %sU/min" % n_links
	print "I_links  = %smA"    % I_links
	print "P_rechts = %s%%"    % P_rechts
	print "n_rechts = %sU/min" % n_rechts
	print "I_rechts = %smA"    % I_rechts

#--- Maehmotor-Status abfragen --------------------------------------------------------------------

if Connection:
	print "\nMaehmotor-Status:"

	f = urllib.urlopen("http://192.168.x.y/send?cmd=02-14-01-03-F2-03")
	WebAnswer = f.read()
	File.write("Maehmotor-Status...."+WebAnswer+"\n")
	print WebAnswer
	Fehler = CheckSyntax(WebAnswer, Fehler)

	n_Motor = str(round((AnalyseBytes(WebAnswer, 4, 2)), 0))
	I_Motor = str(round((AnalyseBytes(WebAnswer, 6, 2)), 0))

	print "n_Motor = %sU/min" % n_Motor
	print "I_Motor = %smA"    % I_Motor

#--- Sensor-Status abfragen -----------------------------------------------------------------------

if Connection:
	print "\nSensor-Status:"

	f = urllib.urlopen("http://192.168.x.y/send?cmd=02-14-01-04-71-03")
	WebAnswer = f.read()
	print WebAnswer
	File.write("Sensor-Status......."+WebAnswer+"\n")
	Fehler = CheckSyntax(WebAnswer, Fehler)

	X = str(round((AnalyseBytes(WebAnswer,  6, 2) / 10.0), 1))
	Y = str(round((AnalyseBytes(WebAnswer,  8, 2) / 10.0), 1))
	Z = str(round((AnalyseBytes(WebAnswer, 10, 2) / 10.0), 1))

	print "X = %s" % X
	print "Y = %s" % Y
	print "Z = %s" % Z

#--- Fehler gefunden? -----------------------------------------------------------------------------

if Connection:
	if Fehler == 0:
		print "\nKeine Uebertragungsfehler"
		File.write("Keine Uebertragungsfehler\n")
	else:
		print "\n%i Uebertragungsfehler" % Fehler
		File.write(str(Fehler)+" Uebertragungsfehler\n")

#--- Letzten Status in Tabelle "Robi" ermitteln ---------------------------------------------------

cmd = "/bin/mysql -hlocalhost -P3306 -uuser -ppassword -e \"USE Robi; SELECT MAX(ID) FROM Robi;\""
print cmd + "\n"
result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)

Irgendwas = result.stdout.readline()
MAX_ID = int(result.stdout.readline())

cmd = "/bin/mysql -hlocalhost -P3306 -uuser -ppassword -e \"USE Robi; SELECT Status FROM Robi WHERE ID = " + str(MAX_ID) + ";\""
print cmd + "\n"
result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)

Irgendwas = result.stdout.readline()
LetzterStatus = int(result.stdout.readline())

#--- Daten in Tabelle "Robi" schreiben ------------------------------------------------------------

print ""
if Connection:
	cmd = "/bin/mysql -hlocalhost -P3306 -uuser -ppassword -e \"USE Robi; INSERT INTO Robi (Fehler, Status, U, Q, I, T, P_links, n_links, I_links, P_rechts, n_rechts, I_rechts, n_Motor, I_Motor, X, Y, Z, DatumImport, UhrzeitImport) VALUES ("+str(Fehler)+", "+str(Status)+", "+U+", "+Q+", "+I+", "+T+", "+P_links+", "+n_links+", "+I_links+", "+P_rechts+", "+n_rechts+", "+I_rechts+", "+n_Motor+", "+I_Motor+", "+X+", "+Y+", "+Z+", NOW(), NOW());\""
	print cmd + "\n"
	result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
else:
	if LetzterStatus == -1:
		print "letzter Status = %i, kein weiterer leerer Eintrag" % LetzterStatus
	else:
		cmd = "/bin/mysql -hlocalhost -P3306 -uuser -ppassword -e \"USE Robi; INSERT INTO Robi (Fehler, Status, U, Q, I, T, P_links, n_links, I_links, P_rechts, n_rechts, I_rechts, n_Motor, I_Motor, X, Y, Z, DatumImport, UhrzeitImport) VALUES (0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NOW(), NOW());\""
		print cmd + "\n"
		result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)

#--- Bei Fehler Mail schreiben --------------------------------------------------------------------

if Connection:
	if LetzterStatus != Status and Status == 7:								# 7 = Fehler
		server = smtplib.SMTP('smtp.web.de:587')
		server.ehlo()
		server.starttls()
		server.login('mymail@web.de','password')
		subject = "Nachricht aus Programm robi.py"
		message = 'Status geaendert von %d nach %d (7 = Fehler)' % (LetzterStatus,Status)
		mailbody = 'From: %s\nTo: %s\nSubject: %s\n\n%s' % ('mymail@web.de','mymail@gmx.de',subject,message) # ...mit Eintrag "To:"
		server.sendmail('mymail@web.de','mymail@gmx.de',mailbody)
		server.quit()
	if LetzterStatus != Status and LetzterStatus == 7 and Status == 4:		# 7 = Fehler, 4 = Laden
		server = smtplib.SMTP('smtp.web.de:587')
		server.ehlo()
		server.starttls()
		server.login('mymail@web.de','password')
		subject = "Nachricht aus Programm robi.py"
		message = 'Status geaendert von %d (Fehler) nach %d (Laden)' % (LetzterStatus,Status)
		mailbody = 'From: %s\nTo: %s\nSubject: %s\n\n%s' % ('mymail@web.de','mymail@gmx.de',subject,message) # ...mit Eintrag "To:"
		server.sendmail('mymail@web.de','mymail@gmx.de',mailbody)
		server.quit()

#--- Logbuch schliessen ---------------------------------------------------------------------------

File.close()

#--- Ende -----------------------------------------------------------------------------------------