function varargout = TanqueDeMistura(varargin)
% TANQUEDEMISTURA M-file for TanqueDeMistura.fig
%      TANQUEDEMISTURA, by itself, creates a new TANQUEDEMISTURA or raises the existing
%      singleton*.
%
%      H = TANQUEDEMISTURA returns the handle to a new TANQUEDEMISTURA or the handle to
%      the existing singleton*.
%
%      TANQUEDEMISTURA('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in TANQUEDEMISTURA.M with the given input arguments.
%
%      TANQUEDEMISTURA('Property','Value',...) creates a new TANQUEDEMISTURA or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before TanqueDeMistura_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to TanqueDeMistura_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help TanqueDeMistura

% Last Modified by GUIDE v2.5 10-Nov-2014 17:00:46

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @TanqueDeMistura_OpeningFcn, ...
                   'gui_OutputFcn',  @TanqueDeMistura_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

                                %XXXXXXXXXXXXXXXXXXXX Grafica uma variavel no activex1  XXXXXXXXXXXXXXXXXXX
                                function graficar(hand,id,valor)
                                set(hand,'VariableID',id);
                                switch id     
                                    case 0,
                                        set(hand,'VariableLineWidth',3);
                                    case 1,
                                        set(hand,'VariableLineWidth',2);
                                    case 2,
                                        set(hand,'VariableLineWidth',2);
                                end
                                set(hand,'Y',valor);



% --- Executes just before TanqueDeMistura is made visible.
function TanqueDeMistura_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to TanqueDeMistura (see VARARGIN)

% Choose default command line output for TanqueDeMistura
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes TanqueDeMistura wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = TanqueDeMistura_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pbiniciar.
function pbiniciar_Callback(hObject, eventdata, handles)
% hObject    handle to pbiniciar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%% Global Variables
global stop spplot ukplot;
global Tplot cont;
global daDfi daDf65;
global ItmLigaBBA2 ItmDesligaBBA2 ItmCalaSirene ItmLigaBBA1 ItmDesligaBBA1;
global ItmFy32SpPid ItmTy31Pid; %ValFy32Sp ValFy32Ao
global ItmFy32Ao ItmTit32Ai;
%% OPC Servers
daDfi=opcda('164.41.17.129','Smar.DfiOleServer.0');
set(daDfi, 'Timeout', 100);
daDf65=opcda('164.41.17.129','Smar.DF65Server.1');
set(daDf65, 'Timeout', 100);
%% Connecting to OPC Servers
connect(daDfi);
connect(daDf65);
%% Creating Groups
grp1 = addgroup(daDfi,'Analoga');
grp2 = addgroup(daDf65,'Discreta');
%% Add Items
ItmTit32Ai = additem(grp1,'TIT-32_AI1.PV.VALUE','single'); %Temperatura malha 32
ItmTy31Pid = additem(grp1,'TY-31_PID1.SP.VALUE','single'); %Temperatura malha 31
ItmFy32SpPid = additem(grp1,'FY-32_PID1.SP.VALUE','single'); %Valvula de controle fluxo Bomba dois
ItmFy32Ao = additem(grp1,'FY-32_PID1.OUT.VALUE','single'); %Valvula de controle fluxo Bomba dois
ItmLigaBBA1 = additem(grp2,'PD3.A.000.01','int8'); %tag para ligar bomba 1
ItmDesligaBBA1 = additem(grp2,'PD3.A.000.02','int8'); %tag para desligar bomba 1
ItmLigaBBA2 = additem(grp2,'PD3.A.000.03','int8'); %tag para ligar bomba 2
ItmDesligaBBA2 = additem(grp2,'PD3.A.000.04','int8'); %tag para desligar bomba 2
ItmCalaSirene = additem(grp2,'PD3.S.012.10','int8'); %tag para desligar sirene
%% Init Variables
stop = 1;
ek_1 = 0;
ss = 0;
uk=0;  
cont =1;
Tplot=0:1;
ukplot=0:1;
spplot=0:1;
%% Close Loop

while stop    
    tit31ai=read(ItmTy31Pid);
    t_quente=tit31ai.Value;
    kp=0.008*(t_quente^3)-1.02*(t_quente)^2.+42.3*(t_quente)-555;
    ki=-0.0008*(t_quente^2) + 0.0592*t_quente - 0.556;
    kd=-0.02*(t_quente^2) + 1.18*t_quente - 2.9;
    
    kps=num2str(kp,3);
    kis=num2str(ki,2);
    kds=num2str(kd,2);
    
    
    set(handles.txtkp,'String',kps);
    set(handles.txtki,'String',kis);
    set(handles.txtkd,'String',kds);
   
    sp = get(handles.txtsp,'String');
   
 
    sp = str2num(sp);
    
    tit32ai = read(ItmTit32Ai); %temperatura 32
    fy32ao = read(ItmFy32Ao); %vazão valve
    abertura = fy32ao.Value; 
    valortemperatura = tit32ai.Value; %define valor de temperatura 
    set(handles.txtnivel,'String',valortemperatura);
    set(handles.txtquente,'String',t_quente);
    set(handles.txtvalvula,'String',abertura);
    QlyFy32Ao = fy32ao.Quality;
    write(ItmFy32SpPid,sp);
    
  if  strcmp(QlyFy32Ao,'Good: Non-specific')
        ek = sp - valortemperatura;  
        ss  = ss + ek;
        uk  = kp*ek + ki*ss + kd*(ek - ek_1); %PID
        uk  = -uk;
        if uk < 0 
        uk  = 0;
        ss  = 0;
        end
        if uk > 100 
        uk=100;
        ss=200;
        end
        uk
        write(ItmFy32Ao,uk);
        ek_1 = ek;
  end
  
  ukplot(cont)=uk;
  spplot(cont)=sp;
  Tplot(cont)=valortemperatura;
  cont=cont+1;

        %----------------------  Set Point ( SP ) -------------------------
        graficar(handles.activex6,0,sp);
        %-----------------  Variavel de Processo ( PV ) -------------------
        graficar(handles.activex6,1,valortemperatura);
        %------------------  Variavel Manipulada ( MV ) -------------------
        graficar(handles.activex6,2,uk);
        %------------------  Erro ( Error ) -------------------
        graficar(handles.activex9,0,ek);
        
        
        
        pause(1); %tick 1 segundo
end
% --- Executes on button press in pbsair.
function pbsair_Callback(hObject, eventdata, handles)
% hObject    handle to pbsair (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    global stop spplot ukplot;
    global Tplot;
    global daDfi daDf65;
    tempo=0:length(Tplot)-1;
    stop = 0;
    disconnect(daDfi);
    disconnect(daDf65);
    delete(daDfi);
    delete(daDf65);
    opcreset
close
figure
plot (tempo,Tplot,tempo,spplot,tempo,ukplot)
%plot (sp)
xlabel('Tempo [s]');
ylabel('Temperatura [C]');
title('Temperatura x Tempo');



% --- Executes on button press in pbliga.
function pbliga_Callback(hObject, eventdata, handles)
global ItmLigaBBA1 ItmDesligaBBA1
write(ItmDesligaBBA1,0);
pause(0.1);
write(ItmLigaBBA1,1);
set(handles.figbomba,'BackgroundColor', [0 1 0]);

% --- Executes on button press in pbdesliga.
function pbdesliga_Callback(hObject, eventdata, handles)
global ItmLigaBBA1 ItmDesligaBBA1
write(ItmLigaBBA1,0);
pause(0.1);
write(ItmDesligaBBA1,1);
set(handles.figbomba,'BackgroundColor', [0.5 0 0]);
         
% --- Executes on button press in pbliga2.
function pbliga2_Callback(hObject, eventdata, handles)
global ItmLigaBBA2 ItmDesligaBBA2
write(ItmDesligaBBA2,0);
pause(0.1);
write(ItmLigaBBA2,1);
set(handles.figbomba2,'BackgroundColor', [0 1 0]);

% --- Executes on button press in pbdesliga2.
function pbdesliga2_Callback(hObject, eventdata, handles)
global ItmLigaBBA2 ItmDesligaBBA2
write(ItmLigaBBA2,0);
pause(0.1);
write(ItmDesligaBBA2,1);
set(handles.figbomba2,'BackgroundColor', [0.5 0 0]);

function txtsp_Callback(hObject, eventdata, handles)

% --- Executes during object creation, after setting all properties.
function txtsp_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function txtkp_Callback(hObject, eventdata, handles)
% hObject    handle to txtkp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtkp as text
%        str2double(get(hObject,'String')) returns contents of txtkp as a double


% --- Executes during object creation, after setting all properties.
function txtkp_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtkp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function txtki_Callback(hObject, eventdata, handles)
% hObject    handle to txtki (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtki as text
%        str2double(get(hObject,'String')) returns contents of txtki as a double


% --- Executes during object creation, after setting all properties.
function txtki_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtki (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function txtkd_Callback(hObject, eventdata, handles)
% hObject    handle to txtkd (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtkd as text
%        str2double(get(hObject,'String')) returns contents of txtkd as a double


% --- Executes during object creation, after setting all properties.
function txtkd_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtkd (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in cmdCalaSirene.
function cmdCalaSirene_Callback(hObject, eventdata, handles)
% hObject    handle to cmdCalaSirene (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global ItmCalaSirene
write(ItmCalaSirene,1);
pause(0.1)
write(ItmCalaSirene,0);

% --- Executes on button press in pbdesliga2.
function pbdesliga1_Callback(hObject, eventdata, handles)
% hObject    handle to pbdesliga2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in pbliga2.
function pbliga1_Callback(hObject, eventdata, handles)
% hObject    handle to pbliga2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)



% --- Executes on button press in pbdesliga2.
function pbdesliga2_Callback(hObject, eventdata, handles)
% hObject    handle to pbdesliga2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in pbliga2.
function pbliga2_Callback(hObject, eventdata, handles)
% hObject    handle to pbliga2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
