#!/usr/bin/python

import threading
import time
from device_base import deviceBase
import micro800 as u800

addr = '10.20.4.5'
channels = {}


e300_current = {
    0: 'None',
    1: 'Overload',
    2: 'Phase Loss',
    4: 'Ground Fault',
    8: 'Stall',
    16: 'Jam',
    32: 'Underload',
    64: 'Current Imbalance',
    128: 'L1 Undercurrent',
    256: 'L2 Undercurrent',
    512: 'L3 Undercurrent',
    1024: 'L1 Overcurrent',
    2048: 'L2 Overcurrent',
    4096: 'L3 Overcurrent',
    8192: 'L1 Line Loss',
    16384: 'L2 Line Loss',
    32768: 'L3 Line Loss'
}

e300_voltage = {
    0: 'None',
    1: 'Undervoltage',
    2: 'Overvoltage',
    4: 'Voltage Unbalance',
    8: 'Phase Rotation',
    16: 'Overfrequency'
}

e300_control = {
    0: 'None',
    1: 'Test Trip',
    2: 'DLX Trip',
    4: 'PTC Trip',
    8: 'Operator Station Trip',
    16: 'Remote Trip',
    32: 'Blocked Start Trip',
    64: 'Hardware Fault Trip',
    128: 'Config Trip',
    256: 'Option Match Trip',
    512: 'DLX FB Timeout Trip',
    1024: 'Expansion Bus Trip',
    2048: 'Reserved',
    4096: 'Reserved',
    8192: 'NVS Trip',
    16384: 'Test Mode Trip'
}

e300_power = {
    0: 'None',
    1: 'Under kW',
    2: 'Over kW',
    4: 'Under kVAR Consumed',
    8: 'Over kVAR Consumed',
    16: 'Under kVAR Generated',
    32: 'Over kVAR Generated',
    64: 'Under kVA',
    128: 'Over kVA',
    256: 'Under PF Lag',
    512: 'Over PF Lag',
    1024: 'Under PF Lead',
    2048: 'Over PF Lead'
}


class Channel():
    def read(self):
        valData = u800.readMicroTag(self.device_addr, self.tag)
        if valData:
            nowVal = valData[0]
            if self.map_obj:
                nowVal = self.map_obj[nowVal]
            self.data_type = valData[1]
            if (self.data_type == "BOOL") or (type(nowVal) is str) or (type(nowVal) is str):
                if self.last_value == "":
                    self.sendFn(self.name, nowVal, 0)
                    self.last_time_uploaded = time.time()
                    self.last_value = nowVal
                elif (not (self.last_value == nowVal)) or ((time.time() - self.last_time_uploaded) > self.max_time_between_uploads):
                    self.sendFn(self.name, nowVal, 0)
                    self.last_time_uploaded = time.time()
                    self.last_value = nowVal
            elif (self.data_type == "REAL") or (self.data_type[-3:] == "INT"):
                if self.last_value == "":
                    self.sendFn(self.name, nowVal, 0)
                    self.last_time_uploaded = time.time()
                    self.last_value = nowVal
                elif (abs(self.last_value - nowVal) > self.change_threshold) or ((time.time() - self.last_time_uploaded) > self.max_time_between_uploads):
                    self.sendFn(self.name, nowVal, 0)
                    self.last_time_uploaded = time.time()
                    self.last_value = nowVal
            return True
        return False

    def __init__(self, name, tag, max_time_between_uploads, sendFn, change_threshold=0.0, e300_param=False, writeable=False, map_obj=None):
        global addr
        self.name = name
        self.tag = tag
        self.data_type = ''
        self.last_value = ''
        self.last_time_uploaded = 0
        self.change_threshold = change_threshold
        self.max_time_between_uploads = int(max_time_between_uploads)
        self.sendFn = sendFn
        self.device_addr = addr
        self.writeable = bool(writeable)
        self.map_obj = map_obj
        self.e300_param = e300_param
        self.read()

    def write(self, val, handshake=None, handshake_val=None):
        if self.writeable:
            if not self.e300_param:
                if handshake is None:
                    if u800.writeMicroTag(self.device_addr, self.tag, val):
                        self.sendFn(self.name, val, time.time())
                        self.last_value = val
                        return True
                    else:
                        return False
                else:
                    return u800.writeMicroTag(self.device_addr, self.tag, val, handshake=handshake, handshake_val=handshake_val)
            else:
                if u800.writeMicroTag(self.device_addr, self.tag, val):
                    if u800.writeMicroTag(self.device_addr, "write_E300", 1):
                        self.sendFn(self.name, val, time.time())
                        self.last_value = val
                        return True
                return False

        else:
            print("NOT ALLOWED TO WRITE TO {}".format(self.name))
            return False


class start(threading.Thread, deviceBase):
    def writeTag_WriteE300(self, addr, tag, val):
        write_tag = u800.writeMicroTag(addr, tag, val)
        write_e300 = u800.writeMicroTag(addr, "write_E300", 1)
        return write_tag and write_e300

    def updateGPS(self):
        gps = self.mcu.gps
        print("GPS found me at {0}".format(gps))
        self.sendtodb("gps", gps, 0)

    def setupChannels(self):
        global channels
        channels = {
            'automode': Channel('automode', 'Auto_Mode', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'cfgcflasetting': Channel('cfgcflasetting', 'cfg_C_FLASetting', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgcleartripcountafter': Channel('cfgcleartripcountafter', 'cfg_ClearTripCountAfter', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'cfggfgroundfaultinhibittime': Channel('cfggfgroundfaultinhibittime', 'cfg_GF_GroundFaultInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfggfgroundfaulttripdelay': Channel('cfggfgroundfaulttripdelay', 'cfg_GF_GroundFaultTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfggfgroundfaulttriplevel': Channel('cfggfgroundfaulttriplevel', 'cfg_GF_GroundFaultTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfggfgroundfaultwarningdelay': Channel('cfggfgroundfaultwarningdelay', 'cfg_GF_GroundFaultWarningDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfggfgroundfaultwarninglevel': Channel('cfggfgroundfaultwarninglevel', 'cfg_GF_GroundFaultWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgictprimary': Channel('cfgictprimary', 'cfg_I_CTPrimary', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgictsecondary': Channel('cfgictsecondary', 'cfg_I_CTSecondary', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgicurrentimbalanceinhibittim': Channel('cfgicurrentimbalanceinhibittim', 'cfg_I_CurrentImbalanceInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgicurrentimbalancetripdelay': Channel('cfgicurrentimbalancetripdelay', 'cfg_I_CurrentImbalanceTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgicurrentimbalancetriplevel': Channel('cfgicurrentimbalancetriplevel', 'cfg_I_CurrentImbalanceTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgicurrentimbalancewarninglev': Channel('cfgicurrentimbalancewarninglev', 'cfg_I_CurrentImbalanceWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgijaminhibittime': Channel('cfgijaminhibittime', 'cfg_I_JamInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgijamtripdelay': Channel('cfgijamtripdelay', 'cfg_I_JamTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgijamtriplevel': Channel('cfgijamtriplevel', 'cfg_I_JamTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgijamwarninglevel': Channel('cfgijamwarninglevel', 'cfg_I_JamWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgilinelossinhibittime': Channel('cfgilinelossinhibittime', 'cfg_I_LineLossInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgilinelosstripdelay': Channel('cfgilinelosstripdelay', 'cfg_I_LineLossTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiovercurrentinhibittime': Channel('cfgiovercurrentinhibittime', 'cfg_I_OvercurrentInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiovercurrenttripdelay': Channel('cfgiovercurrenttripdelay', 'cfg_I_OvercurrentTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiovercurrenttriplevel': Channel('cfgiovercurrenttriplevel', 'cfg_I_OvercurrentTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiovercurrentwarninglevel': Channel('cfgiovercurrentwarninglevel', 'cfg_I_OvercurrentWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgistallenabledtime': Channel('cfgistallenabledtime', 'cfg_I_StallEnabledTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgistalltriplevel': Channel('cfgistalltriplevel', 'cfg_I_StallTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiundercurrentinhibittime': Channel('cfgiundercurrentinhibittime', 'cfg_I_UndercurrentInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiundercurrenttripdelay': Channel('cfgiundercurrenttripdelay', 'cfg_I_UndercurrentTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiundercurrenttriplevel': Channel('cfgiundercurrenttriplevel', 'cfg_I_UndercurrentTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiundercurrentwarninglevel': Channel('cfgiundercurrentwarninglevel', 'cfg_I_UndercurrentWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiunderloadinhibittime': Channel('cfgiunderloadinhibittime', 'cfg_I_UnderloadInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiunderloadtripdelay': Channel('cfgiunderloadtripdelay', 'cfg_I_UnderloadTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiunderloadtriplevel': Channel('cfgiunderloadtriplevel', 'cfg_I_UnderloadTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgiunderloadwarninglevel': Channel('cfgiunderloadwarninglevel', 'cfg_I_UnderloadWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgoverloadtripcountlimit': Channel('cfgoverloadtripcountlimit', 'cfg_OverloadTripCountLimit', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'cfgplphaselossinhibittime': Channel('cfgplphaselossinhibittime', 'cfg_PL_PhaseLossInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgplphaselosstripdelay': Channel('cfgplphaselosstripdelay', 'cfg_PL_PhaseLossTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgread': Channel('cfgread', 'cfg_READ', 86400, self.sendtodbJSON, writeable=True, e300_param=False),
            'cfgspecificgravity': Channel('cfgspecificgravity', 'cfg_SpecificGravity', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'cfgtcuolresetlevel': Channel('cfgtcuolresetlevel', 'cfg_TCU_OLResetLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgtcuolwarninglevel': Channel('cfgtcuolwarninglevel', 'cfg_TCU_OLWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgtcutripclass': Channel('cfgtcutripclass', 'cfg_TCU_TripClass', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgtimermodeenabled': Channel('cfgtimermodeenabled', 'cfg_TimerModeEnabled', 86400, self.sendtodbJSON, writeable=True, e300_param=False),
            'cfgtimerruntime': Channel('cfgtimerruntime', 'cfg_TimerRunTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'cfgtimerwaittime': Channel('cfgtimerwaittime', 'cfg_TimerWaitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'cfgtripcountlimit': Channel('cfgtripcountlimit', 'cfg_TripCountLimit', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'cfgvoverfrequencyinhibittime': Channel('cfgvoverfrequencyinhibittime', 'cfg_V_OverfrequencyInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvoverfrequencytripdelay': Channel('cfgvoverfrequencytripdelay', 'cfg_V_OverfrequencyTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvoverfrequencytriplevel': Channel('cfgvoverfrequencytriplevel', 'cfg_V_OverfrequencyTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvoverfrequencywarninglevel': Channel('cfgvoverfrequencywarninglevel', 'cfg_V_OverfrequencyWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvovervoltageinhibittime': Channel('cfgvovervoltageinhibittime', 'cfg_V_OvervoltageInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvovervoltagetripdelay': Channel('cfgvovervoltagetripdelay', 'cfg_V_OvervoltageTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvovervoltagetriplevel': Channel('cfgvovervoltagetriplevel', 'cfg_V_OvervoltageTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvovervoltagewarninglevel': Channel('cfgvovervoltagewarninglevel', 'cfg_V_OvervoltageWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvphaserotationinhibittime': Channel('cfgvphaserotationinhibittime', 'cfg_V_PhaseRotationInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvphaserotationtriptype': Channel('cfgvphaserotationtriptype', 'cfg_V_PhaseRotationTripType', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvptprimary': Channel('cfgvptprimary', 'cfg_V_PTPrimary', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvptsecondary': Channel('cfgvptsecondary', 'cfg_V_PTSecondary', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvunderfrequencyinhibittime': Channel('cfgvunderfrequencyinhibittime', 'cfg_V_UnderfrequencyInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvunderfrequencytripdelay': Channel('cfgvunderfrequencytripdelay', 'cfg_V_UnderfrequencyTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvunderfrequencytriplevel': Channel('cfgvunderfrequencytriplevel', 'cfg_V_UnderfrequencyTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvunderfrequencywarninglevel': Channel('cfgvunderfrequencywarninglevel', 'cfg_V_UnderfrequencyWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvundervoltageinhibittime': Channel('cfgvundervoltageinhibittime', 'cfg_V_UndervoltageInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvundervoltagetripdelay': Channel('cfgvundervoltagetripdelay', 'cfg_V_UndervoltageTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvundervoltagetriplevel': Channel('cfgvundervoltagetriplevel', 'cfg_V_UndervoltageTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvundervoltagewarninglevel': Channel('cfgvundervoltagewarninglevel', 'cfg_V_UndervoltageWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvvoltageimbalanceinhibittim': Channel('cfgvvoltageimbalanceinhibittim', 'cfg_V_VoltageImbalanceInhibitTime', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvvoltageimbalancetripdelay': Channel('cfgvvoltageimbalancetripdelay', 'cfg_V_VoltageImbalanceTripDelay', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvvoltageimbalancetriplevel': Channel('cfgvvoltageimbalancetriplevel', 'cfg_V_VoltageImbalanceTripLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvvoltageimbalancewarninglev': Channel('cfgvvoltageimbalancewarninglev', 'cfg_V_VoltageImbalanceWarningLevel', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgvvoltagemode': Channel('cfgvvoltagemode', 'cfg_V_VoltageMode', 86400, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=True),
            'cfgwrite': Channel('cfgwrite', 'cfg_WRITE', 86400, self.sendtodbJSON, writeable=True, e300_param=False),
            'contactorstatus': Channel('contactorstatus', 'Contactor_Status', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'dhdownholestatusint': Channel('dhdownholestatusint', 'DH_DownholeStatus_INT', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'dhfluidlevel': Channel('dhfluidlevel', 'DH_Fluid_Level', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'dhintakepressure': Channel('dhintakepressure', 'DH_IntakePressure', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'dhintaketemperature': Channel('dhintaketemperature', 'DH_IntakeTemperature', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'dhmaxintakepressureforever': Channel('dhmaxintakepressureforever', 'DH_MaxIntakePressure_Forever', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'dhmaxintakepressurestartup': Channel('dhmaxintakepressurestartup', 'DH_MaxIntakePressure_Startup', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'dhmaxintaketemperatureforever': Channel('dhmaxintaketemperatureforever', 'DH_MaxIntakeTemperature_Forever', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'dhmaxintaketemperaturestartup': Channel('dhmaxintaketemperaturestartup', 'DH_MaxIntakeTemperature_Startup', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'dhnumchannels': Channel('dhnumchannels', 'DH_NumChannels', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'dhpsirating': Channel('dhpsirating', 'DH_PSIRating', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'dhtooltype': Channel('dhtooltype', 'DH_ToolType', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'dhtoolvoltage': Channel('dhtoolvoltage', 'DH_ToolVoltage', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'downholetoolenabled': Channel('downholetoolenabled', 'Downhole_Tool_Enabled', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'downtimetimeparameter': Channel('downtimetimeparameter', 'Downtime_Time_Parameter', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'downtimetimeparameterol': Channel('downtimetimeparameterol', 'Downtime_Time_Parameter_OL', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'e300averagecurrent': Channel('e300averagecurrent', 'E300_AverageCurrent', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300averagellvoltage': Channel('e300averagellvoltage', 'E300_AverageLLVoltage', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300averagelnvoltage': Channel('e300averagelnvoltage', 'E300_AverageLNVoltage', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300kwh': Channel('e300kwh', 'E300_kWh', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300kwhregen': Channel('e300kwhregen', 'E300_kWh_Regen', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l1apparentpower': Channel('e300l1apparentpower', 'E300_L1ApparentPower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l1current': Channel('e300l1current', 'E300_L1Current', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l1l2voltage': Channel('e300l1l2voltage', 'E300_L1L2Voltage', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l1nvoltage': Channel('e300l1nvoltage', 'E300_L1NVoltage', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l1reactivepower': Channel('e300l1reactivepower', 'E300_L1ReactivePower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l1realpower': Channel('e300l1realpower', 'E300_L1RealPower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l1truepowerfactor': Channel('e300l1truepowerfactor', 'E300_L1TruePowerFactor', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l2apparentpower': Channel('e300l2apparentpower', 'E300_L2ApparentPower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l2current': Channel('e300l2current', 'E300_L2Current', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l2l3voltage': Channel('e300l2l3voltage', 'E300_L2L3Voltage', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l2nvoltage': Channel('e300l2nvoltage', 'E300_L2NVoltage', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l2reactivepower': Channel('e300l2reactivepower', 'E300_L2ReactivePower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l2realpower': Channel('e300l2realpower', 'E300_L2RealPower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l2truepowerfactor': Channel('e300l2truepowerfactor', 'E300_L2TruePowerFactor', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l3apparentpower': Channel('e300l3apparentpower', 'E300_L3ApparentPower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l3current': Channel('e300l3current', 'E300_L3Current', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l3l1voltage': Channel('e300l3l1voltage', 'E300_L3L1Voltage', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l3nvoltage': Channel('e300l3nvoltage', 'E300_L3NVoltage', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l3reactivepower': Channel('e300l3reactivepower', 'E300_L3ReactivePower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l3realpower': Channel('e300l3realpower', 'E300_L3RealPower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300l3truepowerfactor': Channel('e300l3truepowerfactor', 'E300_L3TruePowerFactor', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300linefrequency': Channel('e300linefrequency', 'E300_LineFrequency', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300percentcurrentunbalance': Channel('e300percentcurrentunbalance', 'E300_PercentCurrentUnbalance', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300percentvoltageunbalance': Channel('e300percentvoltageunbalance', 'E300_PercentVoltageUnbalance', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300threephasetruepowerfactor': Channel('e300threephasetruepowerfactor', 'E300_ThreePhaseTruePowerFactor', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300totalapparentpower': Channel('e300totalapparentpower', 'E300_TotalApparentPower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300totalreactivepower': Channel('e300totalreactivepower', 'E300_TotalReactivePower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'e300totalrealpower': Channel('e300totalrealpower', 'E300_TotalRealPower', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'flowrate': Channel('flowrate', 'Flowrate', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'handmode': Channel('handmode', 'Hand_Mode', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'overloadtrip': Channel('overloadtrip', 'OverloadTrip', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'pressurealarmdelay': Channel('pressurealarmdelay', 'Pressure_Alarm_Delay', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'pressurealarmstartupdelay': Channel('pressurealarmstartupdelay', 'Pressure_Alarm_Startup_Delay', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'pressureeumax': Channel('pressureeumax', 'Pressure_EU_Max', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'pressureeumin': Channel('pressureeumin', 'Pressure_EU_Min', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'pressurehi': Channel('pressurehi', 'Pressure_Hi', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'pressurehisp': Channel('pressurehisp', 'Pressure_Hi_SP', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'pressurein': Channel('pressurein', 'Pressure_In', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'pressurelo': Channel('pressurelo', 'Pressure_Lo', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'pressurelosp': Channel('pressurelosp', 'Pressure_Lo_SP', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'pressureok': Channel('pressureok', 'Pressure_OK', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'pressureshutdown': Channel('pressureshutdown', 'Pressure_Shutdown', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'pressureshutdownenabled': Channel('pressureshutdownenabled', 'Pressure_Shutdown_Enabled', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'pressurestartup': Channel('pressurestartup', 'Pressure_Startup', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'pressurestartupenabled': Channel('pressurestartupenabled', 'Pressure_Startup_Enabled', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'pressureswitchenabled': Channel('pressureswitchenabled', 'Pressure_Switch_Enabled', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'pressuretransducerenabled': Channel('pressuretransducerenabled', 'Pressure_Transducer_Enabled', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'rpmode': Channel('rpmode', 'RP_Mode', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'rppressure': Channel('rppressure', 'RP_Pressure', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'rptemperature': Channel('rptemperature', 'RP_Temperature', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'rptrip': Channel('rptrip', 'RP_Trip', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'rptubingpressure': Channel('rptubingpressure', 'RP_TubingPressure', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'runpermissive': Channel('runpermissive', 'Run_Permissive', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'spmode': Channel('spmode', 'SP_Mode', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'sppressure': Channel('sppressure', 'SP_Pressure', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'sptemperature': Channel('sptemperature', 'SP_Temperature', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'sptrip': Channel('sptrip', 'SP_Trip', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'spvoltage': Channel('spvoltage', 'SP_Voltage', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'startbutton': Channel('startbutton', 'Start_Button', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'startcommand': Channel('startcommand', 'Start_Command', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'startpermissive': Channel('startpermissive', 'Start_Permissive', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'stopcommand': Channel('stopcommand', 'Stop_Command', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tempshutdown': Channel('tempshutdown', 'Temp_Shutdown', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'tempshutdownenabled': Channel('tempshutdownenabled', 'Temp_Shutdown_Enabled', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tempstartup': Channel('tempstartup', 'Temp_Startup', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False),
            'tempstartupenabled': Channel('tempstartupenabled', 'Temp_Startup_Enabled', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'testmode': Channel('testmode', 'Test_Mode', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'tripenabledicurrentimbalance': Channel('tripenabledicurrentimbalance', 'TripEnabled_I_CurrentImbalance', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenabledigroundfault': Channel('tripenabledigroundfault', 'TripEnabled_I_GroundFault', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenabledijam': Channel('tripenabledijam', 'TripEnabled_I_Jam', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenabledilineloss': Channel('tripenabledilineloss', 'TripEnabled_I_LineLoss', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenablediovercurrent': Channel('tripenablediovercurrent', 'TripEnabled_I_Overcurrent', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenabledioverload': Channel('tripenabledioverload', 'TripEnabled_I_Overload', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenablediphaseloss': Channel('tripenablediphaseloss', 'TripEnabled_I_PhaseLoss', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenabledistall': Channel('tripenabledistall', 'TripEnabled_I_Stall', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenablediundercurrent': Channel('tripenablediundercurrent', 'TripEnabled_I_Undercurrent', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenablediunderload': Channel('tripenablediunderload', 'TripEnabled_I_Underload', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenablevoverfrequency': Channel('tripenablevoverfrequency', 'TripEnable_V_Overfrequency', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenablevovervoltage': Channel('tripenablevovervoltage', 'TripEnable_V_Overvoltage', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenablevphaserotation': Channel('tripenablevphaserotation', 'TripEnable_V_PhaseRotation', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenablevunderfrequency': Channel('tripenablevunderfrequency', 'TripEnable_V_Underfrequency', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenablevundervoltage': Channel('tripenablevundervoltage', 'TripEnable_V_Undervoltage', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripenablevvoltageunbalance': Channel('tripenablevvoltageunbalance', 'TripEnable_V_VoltageUnbalance', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripresetcmd': Channel('tripresetcmd', 'TripResetCmd', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'tripstatus': Channel('tripstatus', 'TripStatus', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'tripstatuscontrolint': Channel('tripstatuscontrolint', 'TripStatusControl_INT', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False, map_obj=e300_control),
            'tripstatuscurrentint': Channel('tripstatuscurrentint', 'TripStatusCurrent_INT', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False, map_obj=e300_current),
            'tripstatuspowerint': Channel('tripstatuspowerint', 'TripStatusPower_INT', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False, map_obj=e300_power),
            'tripstatusvoltageint': Channel('tripstatusvoltageint', 'TripStatusVoltage_INT', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False, map_obj=e300_voltage),
            'valoverloadtripcount': Channel('valoverloadtripcount', 'val_OverloadTripCount', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'valtripcount': Channel('valtripcount', 'val_TripCount', 3600, self.sendtodbJSON, writeable=False, change_threshold=1.0, e300_param=False),
            'voltageok': Channel('voltageok', 'VoltageOK', 3600, self.sendtodbJSON, writeable=False, e300_param=False),
            'warningenabledicurrentimbalanc': Channel('warningenabledicurrentimbalanc', 'WarningEnabled_I_CurrentImbalance', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenabledigroundfault': Channel('warningenabledigroundfault', 'WarningEnabled_I_GroundFault', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenabledijam': Channel('warningenabledijam', 'WarningEnabled_I_Jam', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenabledilineloss': Channel('warningenabledilineloss', 'WarningEnabled_I_LineLoss', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenablediovercurrent': Channel('warningenablediovercurrent', 'WarningEnabled_I_Overcurrent', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenabledioverload': Channel('warningenabledioverload', 'WarningEnabled_I_Overload', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenablediphaseloss': Channel('warningenablediphaseloss', 'WarningEnabled_I_PhaseLoss', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenabledistall': Channel('warningenabledistall', 'WarningEnabled_I_Stall', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenablediundercurrent': Channel('warningenablediundercurrent', 'WarningEnabled_I_Undercurrent', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenablediunderload': Channel('warningenablediunderload', 'WarningEnabled_I_Underload', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenablevoverfrequency': Channel('warningenablevoverfrequency', 'WarningEnable_V_Overfrequency', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenablevovervoltage': Channel('warningenablevovervoltage', 'WarningEnable_V_Overvoltage', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenablevphaserotation': Channel('warningenablevphaserotation', 'WarningEnable_V_PhaseRotation', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenablevunderfrequency': Channel('warningenablevunderfrequency', 'WarningEnable_V_Underfrequency', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenablevundervoltage': Channel('warningenablevundervoltage', 'WarningEnable_V_Undervoltage', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningenablevvoltageunbalance': Channel('warningenablevvoltageunbalance', 'WarningEnable_V_VoltageUnbalance', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningstatus': Channel('warningstatus', 'WarningStatus', 3600, self.sendtodbJSON, writeable=True, e300_param=False),
            'warningstatuscontrolint': Channel('warningstatuscontrolint', 'WarningStatusControl_INT', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False, map_obj=e300_control),
            'warningstatuscurrentint': Channel('warningstatuscurrentint', 'WarningStatusCurrent_INT', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False, map_obj=e300_current),
            'warningstatuspowerint': Channel('warningstatuspowerint', 'WarningStatusPower_INT', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False, map_obj=e300_power),
            'warningstatusvoltageint': Channel('warningstatusvoltageint', 'WarningStatusVoltage_INT', 3600, self.sendtodbJSON, writeable=True, change_threshold=1.0, e300_param=False, map_obj=e300_voltage),
        }

    def __init__(self, name=None, number=None, mac=None, Q=None, mcu=None, companyId=None, offset=None, mqtt=None, Nodes=None):
        global addr
        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.daemon = True
        self.version = "3"
        self.device_address = addr
        self.finished = threading.Event()
        threading.Thread.start(self)
        self.sendtodbJSON("device_address", self.device_address, 0)
        self.setupChannels()
        self.e300_warning = ""
        self.e300_trip = ""
        # self.updateGPS()

    # 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):
        self.channels["status"]["last_value"] = ""

    def run(self):
        global channels
        print("****************\n*************\nEXECUTING RUN\n********************\n****************")
        self.runLoopStatus = ""
        last_OK_state = 0
        while True:
            if len(channels) > 0:
                try:
                    for i in channels:
                        channels[i].read()
                        runLoopStatus = i
                        time.sleep(0.25)

                    if not (channels['tripstatuscurrentint'].last_value == "None"):
                        if not (self.e300_trip == channels['tripstatuscurrentint'].last_value):
                            self.e300_trip = channels['tripstatuscurrentint'].last_value
                            self.sendtodb("e300tripstatus", self.e300_trip, time.time())
                    elif not (channels['tripstatusvoltageint'].last_value == "None"):
                        if not (self.e300_trip == channels['tripstatusvoltageint'].last_value):
                            self.e300_trip = channels['tripstatusvoltageint'].last_value
                            self.sendtodb("e300tripstatus", self.e300_trip, time.time())
                    elif not (channels['tripstatuscontrolint'].last_value == "None"):
                        if not (self.e300_trip == channels['tripstatuscontrolint'].last_value):
                            self.e300_trip = channels['tripstatuscontrolint'].last_value
                            self.sendtodb("e300tripstatus", self.e300_trip, time.time())
                    elif not (channels['tripstatuspowerint'].last_value == "None"):
                        if not (self.e300_trip == channels['tripstatuspowerint'].last_value):
                            self.e300_trip = channels['tripstatuspowerint'].last_value
                            self.sendtodb("e300tripstatus", self.e300_trip, time.time())
                    else:
                        if not (self.e300_trip == "None"):
                            self.e300_trip = "None"
                            self.sendtodb("e300tripstatus", self.e300_trip, time.time())

                    if not (channels['warningstatuscurrentint'].last_value == "None"):
                        if not (self.e300_warning == channels['warningstatuscurrentint'].last_value):
                            self.e300_warning = channels['warningstatuscurrentint'].last_value
                            self.sendtodb("e300warningstatus", self.e300_warning, time.time())
                    elif not (channels['warningstatusvoltageint'].last_value == "None"):
                        if not (self.e300_warning == channels['warningstatusvoltageint'].last_value):
                            self.e300_warning = channels['warningstatusvoltageint'].last_value
                            self.sendtodb("e300warningstatus", self.e300_warning, time.time())
                    elif not (channels['warningstatuscontrolint'].last_value == "None"):
                        if not (self.e300_warning == channels['warningstatuscontrolint'].last_value):
                            self.e300_warning = channels['warningstatuscontrolint'].last_value
                            self.sendtodb("e300warningstatus", self.e300_warning, time.time())
                    elif not (channels['warningstatuspowerint'].last_value == "None"):
                        if not (self.e300_warning == channels['warningstatuspowerint'].last_value):
                            self.e300_warning = channels['warningstatuspowerint'].last_value
                            self.sendtodb("e300warningstatus", self.e300_warning, time.time())
                    else:
                        if not (self.e300_warning == "None"):
                            self.e300_warning = "None"
                            self.sendtodb("e300warningstatus", self.e300_warning, time.time())

                    runLoopStatus = "Complete"
                    OK_state = 1
                    if not OK_state == last_OK_state:
                        self.sendtodbJSON("driver_ok", OK_state, 0)
                        last_OK_state = OK_state
                    time.sleep(10)
                except Exception, e:
                    OK_state = 0
                    if not OK_state == last_OK_state:
                        self.sendtodbJSON("driver_ok", OK_state, 0)
                        last_OK_state = OK_state
                    sleep_timer = 30
                    print "Error during {0} of run loop: {1}\nWill try again in {2} seconds...".format(runLoopStatus, e, sleep_timer)
                    time.sleep(sleep_timer)
            else:
                print("Apparently no channels... length shows {0}".format(len(channels)))
                self.setupChannels()
                time.sleep(30)

    def ipp_sync(self, name, value):
        self.sendtodb("connected", "true", 0)
        return True

    def genericSet(self, name, value, id):
        global channels
        try:
            print("Trying to set {} to {}".format(channels[name].tag, value))
            return channels[name].write(value)
        except Exception, e:
            print("Exception during genericSet: {}".format(e))
