from inputs.snap7_server import SiemensServer
from inputs.snap7_connect import SiemensCPU
from inputs.balluff_html import Balluff
from inputs.allen_bradley_connect import AllenBradleyCPU
from database import *
import logging
import time

logging.basicConfig(level=logging.WARNING)

logging.info("starting")

sources = [
  SiemensCPU("192.168.0.10"),
  SiemensServer(),
  #Balluff(),
  #AllenBradleyCPU("192.168.10.5"),
]

sinks = [
  InfluxDB("http://localhost:8086"),
  CSVStorage("logs"),
]

for source in sources:
  source.start()

logging.info("started sources")

startTime = 0

def printStats(values):
  global startTime
  counts = {}
  dt = time.monotonic() - startTime
  startTime = time.monotonic()
  text = ""
  for meas in values:
    id = "{} {}".format(meas.series, meas.source)
    if id in counts:
      counts[id] += 1
    else:
      counts[id] = 1
  if counts:
    ids = list(counts.keys())
    ids.sort()
    for id in ids:
      text += "{}: {:4d} in {:.03f}s, {:.1f}/s    ".format(id, counts[id], dt, counts[id] / dt)
  else:
    text = "0 Messungen in {:.03f}s               ".format(dt)

  print(text, end='\r')

while True:
  values = []
  for source in sources:
    values.extend(source.read())

  for sink in sinks:
    sink.write(values)

  printStats(values)
  time.sleep(1.9)
