classdef MuxSetup < handle
    properties(Access=private)
        mux1Pin=5;
        mux2Pin=6;
        mux3Pin=13;
        digInPin=19;
        anOutTriggerPin=23;
        dev;
    end
    
    properties
        setup=[0 0 0; 1 0 0; 0 1 0; 1 1 0; 0 0 1; 1 0 1; 0 1 1; 1 1 1];
        spiDevice;
    end
    
    methods
        function obj = MuxSetup(dev)
            obj.dev = dev;
            configurePin(dev, obj.mux1Pin, 'DigitalOutput');
            configurePin(dev, obj.mux2Pin, 'DigitalOutput');
            configurePin(dev, obj.mux3Pin, 'DigitalOutput');
            configurePin(dev, obj.digInPin, 'DigitalInput');
            configurePin(dev, obj.anOutTriggerPin, 'DigitalOutput');
            obj.spiDevice = spidev(dev, 'CE0');
        end
        
        function set(obj, channel)
            % Set the mux up for reading from a channel
            if (channel > 0) && (channel <= 8)
                writeDigitalPin(obj.dev, obj.mux1Pin, obj.setup(channel, 1));
                writeDigitalPin(obj.dev, obj.mux2Pin, obj.setup(channel, 2));
                writeDigitalPin(obj.dev, obj.mux3Pin, obj.setup(channel, 3));
            end
            
        end
        
        function digInVal = readDigital(obj)
            % Read the value of a digital input after setting the Mux
            digInVal = ~readDigitalPin(obj.dev, obj.digInPin);
        end
        
        function analogValue = readAnalogSPI(obj)
            enableSPI(obj.dev);
            analogValue = -1;
            analogRaw = writeRead(obj.spiDevice,[hex2dec('00') hex2dec('00') hex2dec('00')]);
            if (analogRaw(3) == 13)
                x = uint16(analogRaw(1)) * 256;
                analogValue = x + uint16(analogRaw(2));
            end
%             disableSPI(obj.dev);
        end
    end
    methods(Static)
        function test
            pi = raspi('10.0.0.104', 'pi', 'HenryPump@1903');
            mux = MuxSetup(pi);
            mux.set(1);
            mux.readAnalogSPI()
            mux.set(2);
            mux.readAnalogSPI()
        end
    end
end