%% UMD SSL BPP Rocksat-X (Project STAR) Sensor Data Analysis Script
% Luke Renegar
% Modified 28/AUG/17

clear; close all;

%% Import data from text file.
% Importing code was Auto-generated by MATLAB on 2017/08/28 17:23:58

%% Initialize variables.
filename = 'RSX Datalog 7.csv';
delimiter = ',';

%% Read columns of data as text:
% For more information, see the TEXTSCAN documentation.
formatSpec = '%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%[^\n\r]';

%% Open the text file.
fileID = fopen(filename,'r');

%% Read columns of data according to the format.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter,  'ReturnOnError', false);

%% Close the text file.
fclose(fileID);

%% Convert the contents of columns containing numeric text to numbers.
% Replace non-numeric text with NaN.
raw = repmat({''},length(dataArray{1}),length(dataArray)-1);
for col=1:length(dataArray)-1
    raw(1:length(dataArray{col}),col) = dataArray{col};
end
numericData = NaN(size(dataArray{1},1),size(dataArray,2));

for col=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]
    % Converts text in the input cell array to numbers. Replaced non-numeric
    % text with NaN.
    rawData = dataArray{col};
    for row=1:size(rawData, 1);
        % Create a regular expression to detect and remove non-numeric prefixes and
        % suffixes.
        regexstr = '(?<prefix>.*?)(?<numbers>([-]*(\d+[\,]*)+[\.]{0,1}\d*[eEdD]{0,1}[-+]*\d*[i]{0,1})|([-]*(\d+[\,]*)*[\.]{1,1}\d+[eEdD]{0,1}[-+]*\d*[i]{0,1}))(?<suffix>.*)';
        try
            result = regexp(rawData{row}, regexstr, 'names');
            numbers = result.numbers;
            
            % Detected commas in non-thousand locations.
            invalidThousandsSeparator = false;
            if any(numbers==',');
                thousandsRegExp = '^\d+?(\,\d{3})*\.{0,1}\d*$';
                if isempty(regexp(numbers, thousandsRegExp, 'once'));
                    numbers = NaN;
                    invalidThousandsSeparator = true;
                end
            end
            % Convert numeric text to numbers.
            if ~invalidThousandsSeparator;
                numbers = textscan(strrep(numbers, ',', ''), '%f');
                numericData(row, col) = numbers{1};
                raw{row, col} = numbers{1};
            end
        catch me
        end
    end
end


%% Replace non-numeric cells with NaN
R = cellfun(@(x) ~isnumeric(x) && ~islogical(x),raw); % Find non-numeric cells
raw(R) = {NaN}; % Replace non-numeric cells

%% Allocate imported array to column variable names
timeStamp = cell2mat(raw(:, 1));
portADir = cell2mat(raw(:, 2));
portBDir = cell2mat(raw(:, 3));
portAOut = cell2mat(raw(:, 4));
portBOut = cell2mat(raw(:, 5));
adcVoltageReading = cell2mat(raw(:, 6));
adcCurrentReading = cell2mat(raw(:, 7));
adxlAccelerometerXReading = cell2mat(raw(:, 8));
adxlAccelerometerYReading = cell2mat(raw(:, 9));
adxlAccelerometerZReading = cell2mat(raw(:, 10));
maximTemperatureReading = cell2mat(raw(:, 11));
bmxAccelerometerXReading = cell2mat(raw(:, 12));
bmxAccelerometerYReading = cell2mat(raw(:, 13));
bmxAccelerometerZReading = cell2mat(raw(:, 14));
bmxAccelerometerTemperatureReading = cell2mat(raw(:, 15));
bmxGyroscopeXReading = cell2mat(raw(:, 16));
bmxGyroscopeYReading = cell2mat(raw(:, 17));
bmxGyroscopeZReading = cell2mat(raw(:, 18));
bmxMagnetometerXReading = cell2mat(raw(:, 19));
bmxMagnetometerYReading = cell2mat(raw(:, 20));
bmxMagnetometerZReading = cell2mat(raw(:, 21));
bmxMagnetometerHallReading = cell2mat(raw(:, 22));

%% Clear temporary variables
clearvars filename delimiter formatSpec fileID dataArray ans raw col numericData rawData row regexstr result numbers invalidThousandsSeparator thousandsRegExp me R;

%% Convert the time to seconds
timeScaleSeconds = timeStamp/1000;

%% Convert register values to integers
portADir = int32(portADir);
portBDir = int32(portBDir);
portAOut = int32(portAOut);
portBOut = int32(portBOut);

%% Plot external kill status
figure; hold on;
plot(timeScaleSeconds, bitget(portADir, 14));
plot(timeScaleSeconds, bitget(portAOut, 14));

title('External Kill Status vs. Time');
xlabel('time (s)');
ylabel('Bit status');
legend('DIR', 'OUT');

%% Plot LED status
figure; hold on;
plot(timeScaleSeconds, bitget(portADir, 10));
plot(timeScaleSeconds, bitget(portAOut, 10));

title('LED Status vs. Time');
xlabel('time (s)');
ylabel('Bit status');
legend('DIR', 'OUT');

%% Plot bias status
figure; hold on;
plot(timeScaleSeconds, bitget(portADir, 29));
plot(timeScaleSeconds, bitget(portAOut, 29));

title('Bias Status vs. Time');
xlabel('time (s)');
ylabel('Bit status');
legend('DIR', 'OUT');

%% Plot voltage data
voltageVolts = 3.3*adcVoltageReading/1023*(3.6 + 6.8)/6.8; % 3.3 V VREF, 10-bit ADC, 3.3k + 6.8k ohm voltage divider

figure; hold on;
plot(timeScaleSeconds, voltageVolts);
plot([0, 390], [5.047, 5.047]);

title('5V Bus Voltage vs. Time');
xlabel('time (s)');
ylabel('5V Bus Voltage (V)');
legend('5V Bus Voltage', 'Sensor Saturation Limit');


%% Plot ADXL aceleration data
adxlXAccelG = adxlAccelerometerXReading * 49e-3; % 49 mG/LSB, per datasheet
adxlYAccelG = adxlAccelerometerYReading * 49e-3;
adxlZAccelG = adxlAccelerometerZReading * 49e-3;
adxlAccelMagG = sqrt(adxlXAccelG.^2 + adxlYAccelG.^2 + adxlZAccelG.^2);

figure; hold on;
plot(timeScaleSeconds, adxlXAccelG);
plot(timeScaleSeconds, adxlYAccelG);
plot(timeScaleSeconds, adxlZAccelG);
plot(timeScaleSeconds, adxlAccelMagG);

title('ADXL Acceleration vs. Time');
xlabel('time (s)');
ylabel('Acceleration (g)');
legend('x', 'y', 'z', 'magnitude');

%% Plot temperature data
maximTemperatureDegreesC = maximTemperatureReading * 2^-8; % 2^-8 deg C/LSB, per datasheet
bmxTemperatureDegreesC = 23 + 0.5*bmxAccelerometerTemperatureReading; % 0.5 K/LSB, two's complement, 0 = 23 deg C per datasheet

figure; hold on;
plot(timeScaleSeconds, maximTemperatureDegreesC);
plot(timeScaleSeconds, bmxTemperatureDegreesC);
title('Maxim Temperature vs. Time');
xlabel('time (s)');
ylabel('Temperature (°C)');
legend('Maxim', 'BMX');


%% Plot BMX acceleration data
bmxXAccelG = bmxAccelerometerXReading * 0.98e-3; % 0.98 mG/LSB per datasheet
bmxYAccelG = bmxAccelerometerYReading * 0.98e-3;
bmxZAccelG = bmxAccelerometerZReading * 0.98e-3;
bmxAccelMagG = sqrt(bmxXAccelG.^2 + bmxYAccelG.^2 + bmxZAccelG.^2);

figure; hold on;
plot(timeScaleSeconds, bmxXAccelG);
plot(timeScaleSeconds, bmxYAccelG);
plot(timeScaleSeconds, bmxZAccelG);
plot(timeScaleSeconds, bmxAccelMagG);

title('BMX Acceleration vs. Time');
xlabel('time (s)');
ylabel('Acceleration (g)');
legend('x', 'y', 'z', 'magnitude');

%% Plot BMX gyro data
bmxXGyroConverted = bmxGyroscopeXReading * 2000/32767; % -2000 deg/s to + 2000 deg/s mapped to a 32-bit signed int, per datasheet
bmxYGyroConverted = bmxGyroscopeYReading * 2000/32767;
bmxZGyroConverted = bmxGyroscopeZReading * 2000/32767;

figure; hold on;
plot(timeScaleSeconds, bmxXGyroConverted);
plot(timeScaleSeconds, bmxYGyroConverted);
plot(timeScaleSeconds, bmxZGyroConverted);

title('BMX Angular Rate vs. Time');
xlabel('time (s)');
ylabel('Angular rate (deg/s)');
legend('x', 'y', 'z')