classdef applicationdecommande2 < matlab.apps.AppBase

    % Properties that correspond to app components
    properties (Access = public)
        UIFigure                        matlab.ui.Figure
        UIAxes                          matlab.ui.control.UIAxes
        ConnexionNucloPanel             matlab.ui.container.Panel
        GridLayout11                    matlab.ui.container.GridLayout
        Refresh                         matlab.ui.control.Button
        PortLabel                       matlab.ui.control.Label
        PortList                        matlab.ui.control.DropDown
        ConnectionButton                matlab.ui.control.Button
        ConnLamp                        matlab.ui.control.Lamp
        TempsdintgrationPanel           matlab.ui.container.Panel
        AugmenterButton                 matlab.ui.control.Button
        DiminuerButton                  matlab.ui.control.Button
        ensEditFieldLabel               matlab.ui.control.Label
        tempsIntegration                matlab.ui.control.NumericEditField
        MoyennagePanel                  matlab.ui.container.Panel
        nbderelevEditFieldLabel         matlab.ui.control.Label
        nbderelev                       matlab.ui.control.NumericEditField
        AcquisitionButton               matlab.ui.control.Button
        ConfigurationdelchellePanel     matlab.ui.container.Panel
        ndupicenpartantdelagaucheLabel  matlab.ui.control.Label
        position1                       matlab.ui.control.NumericEditField
        LongueurdondenmLabel            matlab.ui.control.Label
        lambda1                         matlab.ui.control.NumericEditField
        ndupicenpartantdelagaucheLabel_2  matlab.ui.control.Label
        position2                       matlab.ui.control.NumericEditField
        LongueurdondenmEditField_2Label  matlab.ui.control.Label
        lambda2                         matlab.ui.control.NumericEditField
        CalibrerButton                  matlab.ui.control.Button
        EnregistrementPanel             matlab.ui.container.Panel
        EnregistrerlafigureButton       matlab.ui.control.Button
        NomdufichieravecextensionLabel  matlab.ui.control.Label
        Adressedenregistrement          matlab.ui.control.EditField
        EnregistrerletableauButton      matlab.ui.control.Button
        AideButton                      matlab.ui.control.Button
    end

    
    properties (Access = private)
        GREEN_COLOR = [0 1 0];
        RED_COLOR = [1 0 0];
        s % serial port
        color_plot % color plot handlers
        is_connected = false;
        precisionY = 1000;

    end
    
    properties (Access = public)
        lambda = 1:64;
        resultat = zeros(64);
    end
    
    methods (Access = private)
        
        function resetApp(app, ~)
            % Communications
            app.is_connected = false;
            app.PortList.Items = serialportlist();
            % Default Coefficients
            app.nbderelev.Value = 1;
            app.tempsintegration.Value = 200;
            app.lambda1.Value = 500;
            app.lambda2.Value = 600;
            app.position1.Value = 1;
            app.position2.Value = 2;

        end
        
        function  conversionindicelongeuronde(app,x,y)
            app.lambda;
            l1 = app.lambda1.Value;
            l2 = app.lambda2.Value;
            
            minpic = 0.2*max(y);
            
            [~, position] = findpeaks(y,x,"MinPeakHeight",minpic,"MinPeakDistance",5); %test
            
            x1 = position(app.position1.Value);
            x2 = position(app.position2.Value);
            
            app.lambda = (l1-l2).*(x-x1)./(x1-x2) + l1;
        end
    end
    
    %rajouter un fonction à appeler au lancement

    % Callbacks that handle component events
    methods (Access = private)

        % Button pushed function: Refresh
        function rafraichirpush(app, event)
            app.PortList.Items = serialportlist("available");
        end

        % Button pushed function: ConnectionButton
        function connectionpush(app, event)
% on connect open serial port, start timer and change lamp color to green

            if not(app.is_connected)
                try
                    app.s = serialport(app.PortList.Value, 115200);
                    configureTerminator(app.s, "CR/LF");
                    %configureCallback(app.s, "terminator", @app.boardCommIT);
                catch
                    warning('Problem using serial.');
                end
                app.is_connected = true;
                app.Refresh.Enable = false;
                drawnow;
                app.ConnLamp.Color = app.GREEN_COLOR; 
                app.ConnectionButton.Text = 'Déconnexion';
            else
                delete(app.s);
                app.is_connected = false;
                app.Refresh.Enable = true;
                drawnow;
                app.ConnLamp.Color = app.RED_COLOR;
                app.ConnectionButton.Text = 'Connexion';
              
            end


        end

        % Button pushed function: EnregistrerlafigureButton
        function enregistrerpush(app, event)
            exportgraphics(app.UIAxes,app.Adressedenregistrement.Value)
        end

        % Button pushed function: AcquisitionButton
        function acquisitionpush(app, event)
            %Effectue la mesure et trace le graph
            
            nbcapture = app.nbderelev.Value;
            r = -1.*ones(nbcapture,64); %creation d'un vecteur de -1
            for k = 1:nbcapture
                writeline(app.s, 'a');  %demande une mesure à la carte
                for i = 1:64
                    x= readline(app.s); %recupere les valeurs une à une
                    r(k,i) = str2num(x)/1000; %conversion en double. Attention à modifier pour le bon code mbed (str2num normalement)
                end
                flush(app.s)
            end
            app.resultat = mean(r,1);
            
            plot(app.UIAxes, app.lambda ,app.resultat,'r'); %trace le graphique dans l'appli.
            


        end

        % Button pushed function: AugmenterButton
        function tpsintup(app, event)
            writeline(app.s, 'b'); %augmenter le temps d'intégration
            app.tempsIntegration.Value = app.tempsIntegration.Value + 100;
        end

        % Button pushed function: DiminuerButton
        function tpsintdown(app, event)
            writeline(app.s, 'c'); %diminuer le temps d'intégration
            app.tempsIntegration.Value = app.tempsIntegration.Value - 100;
        end

        % Callback function
        function augmentertint(app, event)
            %tps = num2str(app.tempsintegration.Value);
            %writeline(app.s, tps);
        end

        % Button pushed function: CalibrerButton
        function calibrer(app, event)
            conversionindicelongeuronde(app,1:64,app.resultat); %def des abscisses
            plot(app.UIAxes, app.lambda ,app.resultat,'r'); %trace le graphique dans l'appli.
        end

        % Button pushed function: EnregistrerletableauButton
        function enregistertab(app, event)
            l = num2str (app.lambda);
            r = num2str (app.resultat);
            save(app.Adressedenregistrement.Value, 'l', 'r', '-mat');
        end

        % Button pushed function: AideButton
        function Aide(app, event)
            open aideapplispectro.mlx
        end
    end

    % Component initialization
    methods (Access = private)

        % Create UIFigure and components
        function createComponents(app)

            % Create UIFigure and hide until all components are created
            app.UIFigure = uifigure('Visible', 'off');
            app.UIFigure.Color = [0.9373 0.9529 0.9608];
            app.UIFigure.Position = [100 100 643 560];
            app.UIFigure.Name = 'MATLAB App';

            % Create UIAxes
            app.UIAxes = uiaxes(app.UIFigure);
            title(app.UIAxes, 'Spectre')
            xlabel(app.UIAxes, 'Longueur d''onde')
            ylabel(app.UIAxes, 'Intensité')
            app.UIAxes.Color = [0.9373 0.9529 0.9608];
            app.UIAxes.BackgroundColor = [0.6784 0.8314 0.9529];
            app.UIAxes.Position = [15 277 378 274];

            % Create ConnexionNucloPanel
            app.ConnexionNucloPanel = uipanel(app.UIFigure);
            app.ConnexionNucloPanel.AutoResizeChildren = 'off';
            app.ConnexionNucloPanel.Title = 'Connexion Nucléo';
            app.ConnexionNucloPanel.BackgroundColor = [0.6784 0.8314 0.9529];
            app.ConnexionNucloPanel.Position = [409 411 226 97.922077922078];

            % Create GridLayout11
            app.GridLayout11 = uigridlayout(app.ConnexionNucloPanel);
            app.GridLayout11.ColumnWidth = {'1x', '3x'};
            app.GridLayout11.Padding = [5 5 5 5];

            % Create Refresh
            app.Refresh = uibutton(app.GridLayout11, 'push');
            app.Refresh.ButtonPushedFcn = createCallbackFcn(app, @rafraichirpush, true);
            app.Refresh.BackgroundColor = [0.3961 0.6039 0.7412];
            app.Refresh.Layout.Row = 2;
            app.Refresh.Layout.Column = [1 2];
            app.Refresh.Text = 'Rafraichir';

            % Create PortLabel
            app.PortLabel = uilabel(app.GridLayout11);
            app.PortLabel.HorizontalAlignment = 'center';
            app.PortLabel.Layout.Row = 1;
            app.PortLabel.Layout.Column = 1;
            app.PortLabel.Text = 'Port';

            % Create PortList
            app.PortList = uidropdown(app.GridLayout11);
            app.PortList.Items = {'COM?'};
            app.PortList.Editable = 'on';
            app.PortList.BackgroundColor = [0.9373 0.9529 0.9608];
            app.PortList.Layout.Row = 1;
            app.PortList.Layout.Column = 2;
            app.PortList.Value = 'COM?';

            % Create ConnectionButton
            app.ConnectionButton = uibutton(app.UIFigure, 'push');
            app.ConnectionButton.ButtonPushedFcn = createCallbackFcn(app, @connectionpush, true);
            app.ConnectionButton.BackgroundColor = [0.3961 0.6039 0.7412];
            app.ConnectionButton.Position = [452 518 106 34];
            app.ConnectionButton.Text = 'Connection';

            % Create ConnLamp
            app.ConnLamp = uilamp(app.UIFigure);
            app.ConnLamp.Position = [415 522 27 27];
            app.ConnLamp.Color = [1 0 0];

            % Create TempsdintgrationPanel
            app.TempsdintgrationPanel = uipanel(app.UIFigure);
            app.TempsdintgrationPanel.Title = 'Temps d''intégration';
            app.TempsdintgrationPanel.BackgroundColor = [0.6784 0.8314 0.9529];
            app.TempsdintgrationPanel.Position = [408 299 225 100];

            % Create AugmenterButton
            app.AugmenterButton = uibutton(app.TempsdintgrationPanel, 'push');
            app.AugmenterButton.ButtonPushedFcn = createCallbackFcn(app, @tpsintup, true);
            app.AugmenterButton.BackgroundColor = [0.3961 0.6039 0.7412];
            app.AugmenterButton.Position = [7 10 101 26];
            app.AugmenterButton.Text = 'Augmenter';

            % Create DiminuerButton
            app.DiminuerButton = uibutton(app.TempsdintgrationPanel, 'push');
            app.DiminuerButton.ButtonPushedFcn = createCallbackFcn(app, @tpsintdown, true);
            app.DiminuerButton.BackgroundColor = [0.3961 0.6039 0.7412];
            app.DiminuerButton.Position = [118 10 102 26];
            app.DiminuerButton.Text = 'Diminuer';

            % Create ensEditFieldLabel
            app.ensEditFieldLabel = uilabel(app.TempsdintgrationPanel);
            app.ensEditFieldLabel.HorizontalAlignment = 'center';
            app.ensEditFieldLabel.Position = [7 47 61 22];
            app.ensEditFieldLabel.Text = 'en µs';

            % Create tempsIntegration
            app.tempsIntegration = uieditfield(app.TempsdintgrationPanel, 'numeric');
            app.tempsIntegration.Editable = 'off';
            app.tempsIntegration.Position = [83 47 131 22];
            app.tempsIntegration.Value = 500;

            % Create MoyennagePanel
            app.MoyennagePanel = uipanel(app.UIFigure);
            app.MoyennagePanel.Title = 'Moyennage';
            app.MoyennagePanel.BackgroundColor = [0.6784 0.8314 0.9529];
            app.MoyennagePanel.Position = [408 222 224 67];

            % Create nbderelevEditFieldLabel
            app.nbderelevEditFieldLabel = uilabel(app.MoyennagePanel);
            app.nbderelevEditFieldLabel.HorizontalAlignment = 'right';
            app.nbderelevEditFieldLabel.Position = [4 13 77 22];
            app.nbderelevEditFieldLabel.Text = 'nb de relevé';

            % Create nbderelev
            app.nbderelev = uieditfield(app.MoyennagePanel, 'numeric');
            app.nbderelev.Limits = [0 Inf];
            app.nbderelev.RoundFractionalValues = 'on';
            app.nbderelev.BackgroundColor = [0.9373 0.9529 0.9608];
            app.nbderelev.Position = [118 13 102 22];
            app.nbderelev.Value = 1;

            % Create AcquisitionButton
            app.AcquisitionButton = uibutton(app.UIFigure, 'push');
            app.AcquisitionButton.ButtonPushedFcn = createCallbackFcn(app, @acquisitionpush, true);
            app.AcquisitionButton.BackgroundColor = [0.3961 0.6039 0.7412];
            app.AcquisitionButton.FontColor = [0.2706 0.0353 0.1255];
            app.AcquisitionButton.Position = [412 93 219 118];
            app.AcquisitionButton.Text = 'Acquisition';

            % Create ConfigurationdelchellePanel
            app.ConfigurationdelchellePanel = uipanel(app.UIFigure);
            app.ConfigurationdelchellePanel.Title = 'Configuration de l''échelle';
            app.ConfigurationdelchellePanel.BackgroundColor = [0.6784 0.8314 0.9529];
            app.ConfigurationdelchellePanel.Position = [15 93 378 173];

            % Create ndupicenpartantdelagaucheLabel
            app.ndupicenpartantdelagaucheLabel = uilabel(app.ConfigurationdelchellePanel);
            app.ndupicenpartantdelagaucheLabel.HorizontalAlignment = 'center';
            app.ndupicenpartantdelagaucheLabel.Position = [-16 89 191 54];
            app.ndupicenpartantdelagaucheLabel.Text = {'n° du pic '; '(en partant de la gauche)'};

            % Create position1
            app.position1 = uieditfield(app.ConfigurationdelchellePanel, 'numeric');
            app.position1.BackgroundColor = [0.9373 0.9529 0.9608];
            app.position1.Position = [148 105 46 22];
            app.position1.Value = 1;

            % Create LongueurdondenmLabel
            app.LongueurdondenmLabel = uilabel(app.ConfigurationdelchellePanel);
            app.LongueurdondenmLabel.HorizontalAlignment = 'center';
            app.LongueurdondenmLabel.Position = [193 98 109 37];
            app.LongueurdondenmLabel.Text = {'Longueur'; 'd''onde (nm)'};

            % Create lambda1
            app.lambda1 = uieditfield(app.ConfigurationdelchellePanel, 'numeric');
            app.lambda1.BackgroundColor = [0.9373 0.9529 0.9608];
            app.lambda1.Position = [301 105 60 22];
            app.lambda1.Value = 500;

            % Create ndupicenpartantdelagaucheLabel_2
            app.ndupicenpartantdelagaucheLabel_2 = uilabel(app.ConfigurationdelchellePanel);
            app.ndupicenpartantdelagaucheLabel_2.HorizontalAlignment = 'center';
            app.ndupicenpartantdelagaucheLabel_2.Position = [9 36 140 54];
            app.ndupicenpartantdelagaucheLabel_2.Text = {'n° du pic'; '(en partant de la gauche)'};

            % Create position2
            app.position2 = uieditfield(app.ConfigurationdelchellePanel, 'numeric');
            app.position2.BackgroundColor = [0.9373 0.9529 0.9608];
            app.position2.Position = [148 52 46 22];
            app.position2.Value = 2;

            % Create LongueurdondenmEditField_2Label
            app.LongueurdondenmEditField_2Label = uilabel(app.ConfigurationdelchellePanel);
            app.LongueurdondenmEditField_2Label.HorizontalAlignment = 'center';
            app.LongueurdondenmEditField_2Label.Position = [193 45 109 37];
            app.LongueurdondenmEditField_2Label.Text = {'Longueur'; 'd''onde (nm)'};

            % Create lambda2
            app.lambda2 = uieditfield(app.ConfigurationdelchellePanel, 'numeric');
            app.lambda2.BackgroundColor = [0.9373 0.9529 0.9608];
            app.lambda2.Position = [301 52 60 22];
            app.lambda2.Value = 600;

            % Create CalibrerButton
            app.CalibrerButton = uibutton(app.ConfigurationdelchellePanel, 'push');
            app.CalibrerButton.ButtonPushedFcn = createCallbackFcn(app, @calibrer, true);
            app.CalibrerButton.BackgroundColor = [0.3961 0.6039 0.7412];
            app.CalibrerButton.Position = [27 15 314 22];
            app.CalibrerButton.Text = 'Calibrer';

            % Create EnregistrementPanel
            app.EnregistrementPanel = uipanel(app.UIFigure);
            app.EnregistrementPanel.Title = 'Enregistrement';
            app.EnregistrementPanel.BackgroundColor = [0.6784 0.8314 0.9529];
            app.EnregistrementPanel.Position = [15 15 618 65];

            % Create EnregistrerlafigureButton
            app.EnregistrerlafigureButton = uibutton(app.EnregistrementPanel, 'push');
            app.EnregistrerlafigureButton.ButtonPushedFcn = createCallbackFcn(app, @enregistrerpush, true);
            app.EnregistrerlafigureButton.BackgroundColor = [0.3961 0.6039 0.7412];
            app.EnregistrerlafigureButton.Position = [320 6 142 33];
            app.EnregistrerlafigureButton.Text = 'Enregistrer la figure';

            % Create NomdufichieravecextensionLabel
            app.NomdufichieravecextensionLabel = uilabel(app.EnregistrementPanel);
            app.NomdufichieravecextensionLabel.HorizontalAlignment = 'center';
            app.NomdufichieravecextensionLabel.Position = [17 8 100 28];
            app.NomdufichieravecextensionLabel.Text = {'Nom du fichier '; '(avec extension)'};

            % Create Adressedenregistrement
            app.Adressedenregistrement = uieditfield(app.EnregistrementPanel, 'text');
            app.Adressedenregistrement.BackgroundColor = [0.9373 0.9529 0.9608];
            app.Adressedenregistrement.Position = [125 11 177 22];

            % Create EnregistrerletableauButton
            app.EnregistrerletableauButton = uibutton(app.EnregistrementPanel, 'push');
            app.EnregistrerletableauButton.ButtonPushedFcn = createCallbackFcn(app, @enregistertab, true);
            app.EnregistrerletableauButton.BackgroundColor = [0.3961 0.6039 0.7412];
            app.EnregistrerletableauButton.Position = [469 6 138 33];
            app.EnregistrerletableauButton.Text = 'Enregistrer le tableau';

            % Create AideButton
            app.AideButton = uibutton(app.UIFigure, 'push');
            app.AideButton.ButtonPushedFcn = createCallbackFcn(app, @Aide, true);
            app.AideButton.BackgroundColor = [0.3961 0.6039 0.7412];
            app.AideButton.Position = [568 518 66 34];
            app.AideButton.Text = 'Aide';

            % Show the figure after all components are created
            app.UIFigure.Visible = 'on';
        end
    end

    % App creation and deletion
    methods (Access = public)

        % Construct app
        function app = applicationdecommande2

            % Create UIFigure and components
            createComponents(app)

            % Register the app with App Designer
            registerApp(app, app.UIFigure)

            if nargout == 0
                clear app
            end
        end

        % Code that executes before app deletion
        function delete(app)

            % Delete UIFigure when app is deleted
            delete(app.UIFigure)
        end
    end
end