import random
from enum import Enum
from math import fabs
import matplotlib.pyplot as plt


class Hyst(Enum):
    
    HYST_IDLE   = 0
    HYST_UP     = 1
    HYST_DOWN   = 2


hyst_high_state = Hyst.HYST_IDLE.name
hyst_low_state = Hyst.HYST_IDLE.name


def grapth():
    hyst_high_limit = 6.0
    hyst_low_limit = 1.0
    x = []
    in_data = []
    hyst_high = []    
    hyst_low = []    
    hyst_value_low = []
    hyst_value_high = []

    for i in range(200):
        x.append(i)
        in_data.append(random.uniform(0.0, 7.0))
        hyst_high.append(hyst_high_limit)
        hyst_low.append(hyst_low_limit)

        hyst_value_low.append(trig_low_value(in_data[i], hyst_low_limit, 1.5))
        hyst_value_high.append(trig_high_value(in_data[i], hyst_high_limit, 1.5))


    plt.plot(x, in_data, x, hyst_high, x, hyst_low, x, hyst_value_low, x, hyst_value_high)
    plt.title('Тестовые данные для гистерезиса')
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.show()


def trig_low_value(value: float, lowlevel: float, hyst: float):
    global hyst_low_state
    if hyst_low_state == Hyst.HYST_IDLE.name:
        if value <= lowlevel:
            hyst_low_state = Hyst.HYST_DOWN.name
            return True
        else:
            return False
    elif hyst_low_state == Hyst.HYST_DOWN.name:
        if value > (lowlevel + fabs(hyst)):
            hyst_low_state = Hyst.HYST_IDLE.name
            return False
        else:
            return True
    return False


def trig_high_value(value: float, highlevel: float, hyst: float):
    global hyst_high_state
    if hyst_high_state == Hyst.HYST_IDLE.name:
        if value >= highlevel:
            hyst_high_state = Hyst.HYST_UP.name
            return True
        else:
            return False
    elif hyst_high_state == Hyst.HYST_UP.name:
        if value < (highlevel - fabs(hyst)):
            hyst_high_state = Hyst.HYST_IDLE.name
            return False
        else:
            return True
    return False


def main():
    grapth()


if __name__ == '__main__':
    main()