classdef AnalogInput < handle
    properties
        mux;
        channel;
        rawValue;
        lastValue;
        lastStored=0;
        rawMax,rawMin,euMax,euMin;
        history=zeros(1, 100, 'double');
        badReads=0;
        
    end
    
    properties(Access=private)
        m,b;
    end
    
    methods
        function obj = AnalogInput(mux, channel, rawMin, rawMax, euMin, euMax)
            obj.mux = mux;
            obj.channel = channel;
            obj.rawMin = double(rawMin);
            obj.rawMax = double(rawMax);
            obj.euMin = double(euMin);
            obj.euMax = double(euMax);
            
            obj.m = (obj.euMax - obj.euMin) / (obj.rawMax - obj.rawMin);
            obj.b = obj.euMax - obj.m * (obj.rawMax);
        end
        
        function value = setValue(obj, inValue)
            obj.rawValue = inValue;
            value = obj.m * inValue + obj.b;
            obj.lastValue = value;
            obj.lastStored = now;
            obj.history = [value, obj.history(1:end-1)];
        end
        
        function value = read(obj)
            value = obj.lastValue;
            rawIn = obj.mux.readAnalogSPI();
            if (rawIn ~= -1)
                obj.badReads = 0;
                value = obj.setValue(double(rawIn));
            else
                obj.badReads = obj.badReads + 1;
            end
            
            if (obj.badReads > 10)
                pause(10);
            end
        end
        
        function value = readSim(obj, simRaw)
            value  = obj.m * simRaw + obj.b;
            obj.lastValue = pv;
            obj.lastValue = value;
            obj.lastStored = now;
            obj.history = [value, obj.history(1:end-1)];
        end
    end
    
    methods(Static)
        function test
            pi = raspi('10.0.0.104', 'pi', 'HenryPump@1903');
            mux = MuxSetup(pi);
            anInput1 = AnalogInput(mux, 1, 0.0, 65535.0, 0.0, 100.0);
            anInput2 = AnalogInput(mux, 2, 0.0, 65535.0, 0.0, 100.0);
            
            anInput1.read()
            anInput2.read()
        end
        
    end
    
    
end
