"""Connect the Henry Pump to Meshify."""

import threading
import time
from device_base import deviceBase
from Channel import Channel

data_source = "PLC"
plc_ip = '192.168.1.10'

channels = [
    Channel(plc_ip, "faultcode", "sts_FaultCode", "INT", 1.0, 3600),
    Channel(plc_ip, "voltagedrop", "val_CableVoltageDrop", "REAL", 1.0, 3600),
    Channel(plc_ip, "strokelength", "val_CalculatedStrokeLength", "REAL", 1.0, 3600),
    Channel(plc_ip, "flowrate", "val_FlowRate", "REAL", 1.0, 3600),
    Channel(plc_ip, "motorcurrent", "val_MotorCurrent", "REAL", 1.0, 3600),
    Channel(plc_ip, "strokeslifetime", "val_StrokeCountLifetime", "DINT", 100.0, 3600),
    Channel(plc_ip, "strokestoday", "val_StrokeCountToday", "DINT", 100.0, 3600),
    Channel(plc_ip, "strokesperminute", "val_StrokesPerMinute", "REAL", 0.5, 3600),
    Channel(plc_ip, "surfacepressure", "val_SurfacePressure", "REAL", 1.0, 3600),
]


class start(threading.Thread, deviceBase):
    """Start the class for the driver."""

    def __init__(self, name=None, number=None, mac=None, Q=None, mcu=None, companyId=None, offset=None, mqtt=None, Nodes=None):
        """Initialize the class."""
        threading.Thread.__init__(self)
        deviceBase.__init__(self, name=name, number=number, mac=mac, Q=Q, mcu=mcu, companyId=companyId, offset=offset, mqtt=mqtt, Nodes=Nodes)
        self.forceSend = True
        self.daemon = True
        self.version = "2"
        self.finished = threading.Event()
        threading.Thread.start(self)

    # this is a required function for all drivers, its goal is to upload some piece of data
    # about your device so it can be seen on the web
    def register(self):
        """Register the device."""
        self.sendtodb("log", "registered", 0)

    def run(self):
        """Run the main loop."""
        while True:
            if self.forceSend:
                print "FORCE SEND: TRUE"
            for c in channels:
                if c.read(self.forceSend):
                    self.sendtodb(c.mesh_name, c.value, 0)
            if self.forceSend:
                self.forceSend = False
            time.sleep(5)
            print("thehenrypump driver still alive... check back in 5 sec.")

    def thehenrypump_sync(self, name, value):
        """Sync all data from the driver."""
        self.forceSend = True
        self.sendtodb("log", "synced", 0)
        return True
