#!/usr/bin/python
# -* coding: utf-8 *-

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Developed 2009-2010 by Bernd Wurst <bernd@schokokeks.org> 
# for own use.
# Released to the public in 2012.


import time, sys, os
from solarmax import SolarMax

#from sqlite3 import dbapi2 as sqlite
#DB_FILE=sys.argv[1]

inverters = { '192.168.1.191': [1,],
            }


smlist = []
for host in inverters.keys():
  sm = SolarMax(host, 12345)
  sm.use_inverters(inverters[host])
  smlist.append(sm)


allinverters = []
for host in inverters.keys():
  allinverters.extend(inverters[host])

while True:
  pac_gesamt = 0.0
  daysum_gesamt = 0.0

  count = 0
  for sm in smlist:
    for (no, ivdata) in sm.inverters().items():
      try:
        (inverter, current) = sm.query(no, ['PAC', 'KDY', 'KT0', 'IDC', 'UDC', 'IL1', 'UL1', 'FDAT', 'SYS'])
        count += 1
      except:
        # Kommunikationsfehler, evtl. Wechselrichter aus
        print ('Kommunikationsfehler, WR %i') % no
        continue
    
      ivmax = ivdata['installed']
      ivname = ivdata['desc']
      PAC = current['IL1'] * current['UL1']
      percent = int((PAC/ivmax) * 100)
      PDC = current['IDC'] * current['UDC']
      (status, errors) = sm.status(no)
      if errors:
        print ('WR %i: %s (%s)') % (no, status, errors)
      

      print ('''
      WR %i (%s)
        Status: %s
        Aktuell: %9.1f Watt / errechnet: %8.1f W (%i %% von %i Watt)
        P_DC:    %9.1f Watt (Wirkungsgrad: %i %%)
        Gesamt heute:   %8.1f   kWh
        Gesamt bisher:  %8.1f   kWh (seit %s)
      ''') % (inverter, ivname, status, current['PAC'], PAC, percent, ivmax, PDC, int((float(PAC)/PDC) * 100), current['KDY'], current['KT0'], current['FDAT'].date())

  time.sleep(10)