function varargout = ControleOPC(varargin)
%8888888888888888888888888888 DESCRIPÇÃO 8888888888888888888888888888888888
% A aplicação desenvolvida é feita para trabalhar com a Planta Didatica 3  
% da Smar 
% Usuario   <===> Computador "fielbus" <===> Planta Didadica 3 da Smar(FF)
% cualquera       IP 164.41.17.129           IP 164.41.17.130
% Maltab 7        Smar.DfiOleServer.0        Fielbus Foundation DFI 51
%                 Smar.DF65Server.1          CLP DF 65 da Smar
% Dicas para o Funcionamento:
% Desativar a Proteção do Firewall dos dois computadores
% O Usuario e a senha dos dois computadores tem que ser os mesmos
% Configurar o COM e DCOM seguindo os pasos do arquivo 
% DFI302M04P- COM-DCOM.doc
% Aluno: Edgar Amaya Simeón Matricula: 07/11951
% Prof.: Dr. Alberto Jose Alvares
% Curso: Topicos Avançados de Sistemas Mecatronicos
%88888888888888888888888888888888888888888888888888888888888888888888888888
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @ControleOPC_OpeningFcn, ...
                   'gui_OutputFcn',  @ControleOPC_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

% --- Executes just before ControleOPC is made visible.
function ControleOPC_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
guidata(hObject, handles);

function varargout = ControleOPC_OutputFcn(hObject, eventdata, handles) 
varargout{1} = handles.output;  

%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%**************************     INICIO      *******************************
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888

function cmdIniciar_Callback(hObject, eventdata, handles)
%XXXXXXXXXXXXXXXX Variaveis para Disconnect ao Sair do Sistema XXXXXXXXXXXX
global daDfi daDf65
%XXXXXX Variaveis Globais das Bombas, Aquecedor, Lampadas e Sirene XXXXXXXX
global ItmLigaBBA1 ItmDesligaBBA1
global ItmLigaBBA2 ItmDesligaBBA2
global ItmLiberaAquec ItmInhibeAquec
global ItmLigaTesteLamp ItmCalaSirene
global ItmManAutoTIC31
global ValManAutoTIC32
global ItmResetConsumoTq1
global ItmResetConsumoTq2
global ItmResetConsumoTotal
global ItmEmergenciaSup
%XXXXXX Variaveis Globais dos Modos de Controle Manual e Automatico d XXXXX
global lblTipodeControle
global ValTy31Pid ItmTy31Pid
global ValTy31SpPid ItmTy31SpPid
global ValFy31Ao ItmFy31Ao
global ValFy32Sp 
global ValFy32Ao ItmFy32Ao
global BitStop
ValManAutoTIC32 = 16;
a=0;
BitStop = 1;
lblTipodeControle = 1;
ValFy32Sp = str2num(get(handles.txtSPTic32,'String'));
%XXXXXXXXXXXXXXXXX Variáveis de auxílio so PID XXXXXXXXXXXXXXXXXXXXXXXXXXXX
newErro = 0;
oldErro = 0;
oldAcao = 0;
newAcao = 0;
%XXXXXXXXXXXXXXXXX Variáveis de auxílio so PID XXXXXXXXXXXXXXXXXXXXXXXXXXXX
global W Wo V Vo yk_1 yk_2
load pesos;
yk_1 = 0;
yk_2 = 0;
OldValFy32Ao = 0;
% contador = 0;
% k=0;
% VtrFy32Sp = zeros(1,800);
% VtrTit32Ai = zeros(1,800);
% VtrFy32Ao = zeros(1,800);
%**************************************************************************
%************************ Inicialização do OPC ****************************
%**************************************************************************
%XXXXXXXXXXXXXXXXX Creando um OPC Data Access Client Object XXXXXXXXXXXXXXX
daDfi = opcda('fieldbus.graco.unb.br', 'Smar.DfiOleServer.0');
daDf65=opcda('fieldbus.graco.unb.br', 'Smar.DF65Server.1');
%XXXXXXXXXXXXXXXXXXXX Conectando o Cliente com o Server XXXXXXXXXXXXXXXXXXX
connect(daDfi);
connect(daDf65);
%XXXXXXXXXXXXXXXXXXXXX Grupo de trabalho para os TAGs XXXXXXXXXXXXXXXXXXXXX
grp_Inp = addgroup(daDfi,'AnalogInput');
grp_Out = addgroup(daDfi,'AnalogOutput');
grp_Ctrl = addgroup(daDfi,'Controle');
grp_Di = addgroup(daDf65,'DigitalInput');
grp_Do = addgroup(daDf65,'DigitalOutput');
%XXXXXXXXXXXXXXXXXXXXXXXXX ITEMS DO DFIOLESERVER XXXXXXXXXXXXXXXXXXXXXXXXXX
%---------------------- Add Items ao Grupo Entradas -----------------------
ItmFit31Ai = additem(grp_Inp,'FIT-31_AI1.OUT.VALUE','single');
ItmFit32Ai = additem(grp_Inp,'FIT-32_AI1.OUT.VALUE','single');
ItmLit31Ai = additem(grp_Inp,'LIT-31_AI1.OUT.VALUE','single');
ItmFit31Intg1 = additem(grp_Inp,'FIT-31_INTG1.OUT.VALUE','single');
ItmFit32Intg2 = additem(grp_Inp,'FIT-32_INTG2.OUT.VALUE','single');
ItmFit32Intg1 = additem(grp_Inp,'FIT-32_INTG1.OUT.VALUE','single');
ItmTy31Ao = additem(grp_Inp,'TY-31_AO1.OUT.VALUE','single');
ItmFy31Ao = additem(grp_Inp,'FY-31_AO1.OUT.VALUE','single');
ItmTy31Pid = additem(grp_Inp,'TY-31_PID1.OUT.VALUE','single');
ItmTy31SpPid = additem(grp_Inp,'TY-31_PID1.SP.VALUE','single');
ItmManAutoTIC31 = additem(grp_Inp,'TY-31_PID1.MODE_BLK.TARGET','single');
%---------------------- Add Items ao Grupo Saidas  ------------------------
ItmResetConsumoTq1 = additem(grp_Out,'FIT-31_INTG1.OP_CMD_INT','single');
ItmResetConsumoTq2 = additem(grp_Out,'FIT-32_INTG2.OP_CMD_INT','single');
ItmResetConsumoTotal = additem(grp_Out,'FIT-32_INTG1.OP_CMD_INT','single');
%--------------------- Add Items ao Grupo Controle ------------------------
ItmTit31Ai = additem(grp_Ctrl,'TIT-31_AI1.OUT.VALUE','single');
ItmTit32Ai = additem(grp_Ctrl,'TIT-32_AI1.OUT.VALUE','single');
ItmFy32Ao = additem(grp_Ctrl,'FY-32_AO1.OUT.VALUE','single');
%XXXXXXXXXXXXXXXXXXXXXXXXX ITEMS DO SERVER DF65 XXXXXXXXXXXXXXXXXXXXXXXXXXX
%-------------------- Add Items ao Grupo Digital Input --------------------
ItmNivelBaixo = additem(grp_Di,'PD3.A.001.00','int8');
ItmTempHiTqAquec = additem(grp_Di,'PD3.A.001.01','int8');
ItmEmergencia = additem(grp_Di,'PD3.A.001.04','int8');
ItmTempHiTqMist = additem(grp_Di,'PD3.A.002.05','int8');
ItmLocalBBA1 = additem(grp_Di,'PD3.E.010.00','int8');
ItmLocalBBA2 = additem(grp_Di,'PD3.E.010.01','int8');
ItmTermostato = additem(grp_Di,'PD3.E.011.00','int8');
ItmChavedeNivel = additem(grp_Di,'PD3.E.011.01','int8');
ItmSeloBBA1 = additem(grp_Di,'PD3.E.011.04','int8');
ItmDefeitoBBA1 = additem(grp_Di,'PD3.E.011.05','int8');
ItmSeloBBA2 = additem(grp_Di,'PD3.E.011.10','int8');
ItmDefeitoBBA2 = additem(grp_Di,'PD3.E.011.11','int8');
ItmAquecInhibido = additem(grp_Di,'PD3.S.012.00','int8');
ItmBBA1Deslig = additem(grp_Di,'PD3.S.012.01','int8');
ItmBBA2Deslig = additem(grp_Di,'PD3.S.012.02','int8');
ItmBBA1 = additem(grp_Di,'PD3.S.012.03','int8');
ItmBBA2 = additem(grp_Di,'PD3.S.012.04','int8');
ItmTemp = additem(grp_Di,'PD3.S.012.05','int8');
ItmNivel = additem(grp_Di,'PD3.S.012.06','int8');
ItmSirene = additem(grp_Di,'PD3.S.012.10','int8');
%------------------- Add Items ao Grupo Digital Output --------------------
ItmLigaBBA1 = additem(grp_Do,'PD3.A.000.01','int8');
ItmDesligaBBA1 = additem(grp_Do,'PD3.A.000.02','int8');
ItmLigaBBA2 = additem(grp_Do,'PD3.A.000.03','int8');
ItmDesligaBBA2 = additem(grp_Do,'PD3.A.000.04','int8');
ItmEmergenciaSup = additem(grp_Do,'PD3.A.000.05','int8');
ItmLigaTesteLamp = additem(grp_Do,'PD3.A.000.06','int8');
ItmLiberaAquec = additem(grp_Do,'PD3.A.001.03','int8');
ItmInhibeAquec = additem(grp_Do,'PD3.A.001.05','int8');
ItmCalaSirene = additem(grp_Do,'PD3.A.001.06','int8');

%XXXXXXXXXXXXXXXXXXXX LEENDO AS REGRAS DIFUSSAS FEITAS XXXXXXXXXXXXXXXXXXXX
victor = readfis('controlfuzzy');
%**************************************************************************
%********************** Inicio do Bucle Fechado ***************************
%**************************************************************************
while BitStop
%XXXXXXXXXXXXXXXXXXXXXX LENDO OS ITEMS DO SERVER DF65 XXXXXXXXXXXXXXXXXXXXX
Rdgrp_Di = read(grp_Di);
[ValNivelBaixo ValTempHiTqAquec ValEmergencia ValTempHiTqMist ...
    ValLocalBBA1 ValLocalBBA2 ValTermostato ValChavedeNivel ...
    ValSeloBBA1 ValDefeitoBBA1 ValSeloBBA2 ValDefeitoBBA2 ...
    ValAquecInhibido ValBBA1Deslig ValBBA2Deslig ValBBA1 ...
    ValBBA2 ValTemp ValNivel ValSirene] = Rdgrp_Di.Value;
%XXXXXXXXXXXXXXXXXXXXXX LENDO OS ITEMS DO DFIOLESERVER XXXXXXXXXXXXXXXXXXXX
%-------------- Lendo Os Valores dos Sensores e Atuadores  ----------------
Rdgrp_Inp = read(grp_Inp);
[ValFit31Ai ValFit32Ai ValLit31Ai ValFit31Intg1 ValFit32Intg2 ...
    ValFit32Intg1 ValTy31Ao ValFy31Ao ValTy31Pid ValTy31SpPid ...
    ValManAutoTIC31] = Rdgrp_Inp.Value;
%-------------- Qualidade dos Valores dos Sensores e Atuadores ------------
[QlyFit31Ai QlyFit32Ai QlyLit31Ai QlyFit31Intg1 QlyFit32Intg2 ...
   QlyFit32Intg1  QlyTy31Ao QlyFy31Ao QlyTy31Pid QlyTy31SpPid ...
   QlyManAutoTIC31] = Rdgrp_Inp.Quality;
%-------------- Lendo Os Valores das TAGs para o Controle  ----------------
Rdgrp_Ctrl = read(grp_Ctrl);
[ValTit31Ai ValTit32Ai ValFy32Ao] = Rdgrp_Ctrl.Value;
[QlyTit31Ai QlyTit32Ai QlyFy32Ao] = Rdgrp_Ctrl.Quality;
%XXXXXXXXXXXXXXXXXX ATUALIZANDO OS VALORES DOS ATUADORES XXXXXXXXXXXXXXXXXX
set(handles.txtFiy31,'String',ValFy31Ao); % Valvula pro Tq. de Aquec.
set(handles.txtFiy32,'String',ValFy32Ao); % Valvula pro Tq. de Mist.
set(handles.txtMVTic32,'String',ValFy32Ao); % Valvula pro Tq. de Mist.
set(handles.txtMVTic31,'String',ValTy31Pid); % %de Corrente Tq. de aquec.
set(handles.txtSPTic31,'String',ValTy31SpPid); % SP de Temp Tq. de Aquec.
set(handles.txtTiy31,'String',ValTy31Ao); % Corrente 4-20mA Tq. de aquec.
%XXXXXXXXXXXXX ATUALIZANDO OS VALORES DOS TRANSMISORES NA TELA XXXXXXXXXXXX
set(handles.txtFit31,'String',ValFit31Ai); % Vazão Tq. de Aquec.
set(handles.txtFit32,'String',ValFit32Ai); % Vazão Tq. de Mist.
set(handles.txtTit31,'String',ValTit31Ai); % Temp. Tq. de Aquec.
set(handles.txtPVTic31,'String',ValTit31Ai); % Temp. Tq. de Aquec.
set(handles.txtTit32,'String',ValTit32Ai); % Temp. Tq. de Mist.
set(handles.txtPVTic32,'String',ValTit32Ai); % Temp. Tq. de Mist.
set(handles.txtLit31,'String',ValLit31Ai); % Nivel Tq. de Aquec.
set(handles.txtConsumoTq1,'String',ValFit31Intg1); % Consumo Tq. de Aquec.
set(handles.txtConsumoTq2,'String',ValFit32Intg2); % Consumo Tq. de Mist.
set(handles.txtConsumoTotal,'String',ValFit32Intg1); % Consumo Total
%XXXXXX SIMULAÇÃO DO COR DA RESISTENCIA DE AQUECIMENTO TQ AQUECIMENTO XXXXX
if strcmp(QlyTy31Ao,'Good: Non-specific')
    [G,B] = cor_resistencia(ValTy31Ao);
    set(handles.grfResistencia,'BackgroundColor',[1 G B]);
end
%XXXXXXXXXXX SIMULAÇÃO DO NIVEL DA AGUA DO TANQUE AQUECIMENTO XXXXXXXXXXXXX
if strcmp(QlyLit31Ai,'Good: Non-specific')
    set(handles.activex2,'PortionPercent',ValLit31Ai)
end
%**************************************************************************
%*******  MODOS DE OPERAÇÃO MANUAL AUTOMATICO DOS CONTROLADORES  **********
%**************************************************************************
%------------------------ Para os dos modos  ------------------------------
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX TIC 31  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
if strcmp(QlyManAutoTIC31,'Good: Non-specific')
    if ValManAutoTIC31 == 8 % Automatico
        set(handles.cmdManTic31,'BackgroundColor',[0.9 0.9 0.85]);
        set(handles.cmdAutoTic31,'BackgroundColor',[0 1 0]);
        set(handles.txtMVTic31,'Style','text');
        set(handles.txtMVTic31,'String',ValTy31Pid);
    elseif ValManAutoTIC31 == 16 % Manual
        set(handles.cmdManTic31,'BackgroundColor',[0 1 0]);
        set(handles.cmdAutoTic31,'BackgroundColor',[0.9 0.9 0.85]);
        set(handles.txtMVTic31,'Style','edit');
    end
end
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX TIC 32  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
% *************** Controle Automatico feito por a gente *******************
if ValManAutoTIC32 == 8
    set(handles.txtMVTic32,'Style','text');
    set(handles.cmdAutoTic32,'BackgroundColor',[0 1 0]);
    set(handles.cmdManTic32,'BackgroundColor',[0.9 0.9 0.85]);
    %-------------------  TIPO DE CONTROLADOR EM USO  ---------------------
    switch lblTipodeControle
        case 1, %-------------- Controle com Redes Neurais ----------------   
            ValFy32Ao = controlneural(ValFy32Sp,ValTit32Ai);  
        case 2, %---------------- Controle com Logica Fuzzy ---------------
            ValTit31Ai = double(ValTit31Ai);
            ValTit32Ai = double(ValTit32Ai);
            ValFy32Sp = double(ValFy32Sp);
            ValFy32Ao = evalfis([ValTit31Ai,ValTit32Ai,ValFy32Sp],victor);
        case 3, %---------------------- Controle PID ----------------------
            newErro=ValFy32Sp - ValTit32Ai;
            newAcao=controlpid(newErro,oldErro,oldAcao)% Chamada função PID 
            ValFy32Ao = abs(newAcao);
            oldErro = newErro; % atualização de valores de erro
            oldAcao = newAcao; % atualizaçao de valores de ação de controle
    end
    % --------- Atualiza o valor Antigo e Escreve o Valor da TAG ----------
    % ----quando o valor absoluto erro=OldValFy32Ao-NewValFy32Ao > 0.1 ----
    NewValFy32Ao = ValFy32Ao;
    if abs(OldValFy32Ao-NewValFy32Ao) > 0.05
       write(ItmFy32Ao,ValFy32Ao)
       OldValFy32Ao = NewValFy32Ao;
    end
    write(ItmFy32Ao,ValFy32Ao);  
    % ------- Salvar os Dados de Controle em um arquivo data.mat ----------
%     contador = contador + 1;
%     k = k + 1;
%     VtrTit32Ai(1,k) = ValTit32Ai;
%     VtrFy32Sp(1,k) = ValFy32Sp;
%     VtrFy32Ao(1,k) = ValFy32Ao;
%     if contador == 10
%         save data VtrTit32Ai VtrFy32Sp VtrFy32Ao
%         contador = 0;
%     end

% ************************ Controle Manual  ***************************
elseif ValManAutoTIC32 == 16
    set(handles.txtMVTic32,'Style','edit');
    set(handles.popTipodeControle,'Style','popupmenu');
    set(handles.cmdManTic32,'BackgroundColor',[0 1 0]);
    ValFy32Ao = str2num(get(handles.txtMVTic32,'String'));
    set(handles.cmdAutoTic32,'BackgroundColor',[0.9 0.9 0.85]);

end

%**************************************************************************
%******************  GRAFICO DE TENDENCIAS DAS GRANDEZAS ******************
%**************************************************************************
if get(handles.OptTic31,'Value') 
    if strcmp(QlyTy31SpPid,'Good: Non-specific') & ...
       strcmp(QlyTit31Ai,'Good: Non-specific') & ...
       strcmp(QlyTy31Pid,'Good: Non-specific')
        %----------------------  Set Point ( SP ) -------------------------
        graficar(handles.activex1,0,ValTy31SpPid);
        %-----------------  Variavel de Processo ( PV ) -------------------
        graficar(handles.activex1,1,ValTit31Ai);
        %------------------  Variavel Manipulada ( MV ) -------------------
        graficar(handles.activex1,2,ValTy31Pid);
    end 
elseif get(handles.OptTic32,'Value') 
    if strcmp(QlyFit32Ai,'Good: Non-specific') & ...
       strcmp(QlyFy32Ao,'Good: Non-specific')
        %----------------------  Set Point ( SP ) -------------------------
        graficar(handles.activex1,0,ValFy32Sp);
        %-----------------  Variavel de Processo ( PV ) -------------------
        graficar(handles.activex1,1,ValTit32Ai);
        %------------------  Variavel Manipulada ( MV ) -------------------
        graficar(handles.activex1,2,ValFy32Ao);
     end 
end

%**************************************************************************
%***************  VISUALIZAÇÃO DOS LEDS NO SUPERVISORIO  ******************
%**************************************************************************
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX  BOMBA 1 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
%--------------------------  Bomba Desligada ------------------------------
if ValBBA1Deslig
    set(handles.LedBBA1Deslig,'BackgroundColor',[0 1 0]);
    set(handles.grfBBA1,'BackgroundColor',[0 1 0]);
    set(handles.txtBBA1Deslig,'String','Bomba Ligada');
else
    set(handles.LedBBA1Deslig,'BackgroundColor',[0 0.5 0]);
    set(handles.grfBBA1,'BackgroundColor',[1 0 0]);
    set(handles.txtBBA1Deslig,'String','Bomba Desligada');
end
%-----------------------  Local ou Remoto BBA 01 --------------------------
if ValLocalBBA1
    set(handles.LedLocalBBA1,'BackgroundColor',[0 1 0]);
    set(handles.txtLocalBBA1,'String','Remoto BBA 01');
else
    set(handles.LedLocalBBA1,'BackgroundColor',[0 0.5 0]);
    set(handles.txtLocalBBA1,'String','Local BBA 01');
end
%----------------------------  Selo BBA 01 --------------------------------
if ValSeloBBA1
    set(handles.LedSeloBBA1,'BackgroundColor',[0 1 0]);
else
    set(handles.LedSeloBBA1,'BackgroundColor',[0 0.5 0]);
end
%--------------------------  Defeito BBA 01 -------------------------------
if ValDefeitoBBA1
    set(handles.LedDefeitoBBA1,'BackgroundColor',[1 0 0]);
else
    set(handles.LedDefeitoBBA1,'BackgroundColor',[0.5 0 0]);
end
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX  BOMBA 2 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
%--------------------------  Bomba Desligada ------------------------------
if ValBBA2Deslig
    set(handles.LedBBA2Deslig,'BackgroundColor',[0 1 0]);
    set(handles.grfBBA2,'BackgroundColor',[0 1 0]);
    set(handles.txtBBA2Deslig,'String','Bomba Ligada');
else
    set(handles.LedBBA2Deslig,'BackgroundColor',[0 0.5 0]);
    set(handles.grfBBA2,'BackgroundColor',[1 0 0]);
    set(handles.txtBBA2Deslig,'String','Bomba Desligada');
end
%-----------------------  Local ou Remoto BBA 02 --------------------------
if ValLocalBBA2
    set(handles.LedLocalBBA2,'BackgroundColor',[0 1 0]);
    set(handles.txtLocalBBA2,'String','Remoto BBA 02');
else
    set(handles.LedLocalBBA2,'BackgroundColor',[0 0.5 0]);
    set(handles.txtLocalBBA2,'String','Local BBA 02');
end
%----------------------------  Selo BBA 02 --------------------------------
if ValSeloBBA2
    set(handles.LedSeloBBA2,'BackgroundColor',[0 1 0]);
else
    set(handles.LedSeloBBA2,'BackgroundColor',[0 0.5 0]);
end
%--------------------------  Defeito BBA 02 -------------------------------
if ValDefeitoBBA2
    set(handles.LedDefeitoBBA2,'BackgroundColor',[1 0 0]);
else
    set(handles.LedDefeitoBBA2,'BackgroundColor',[0.5 0 0]);
end
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX  SIRENE  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
%----------------------  Sirene e Sirene Calada ---------------------------
if ValSirene
    if a==1
        set(handles.LedSirene,'BackgroundColor',[1 0 0]);
    else
        set(handles.LedSirene,'BackgroundColor',[0.5 0.5 0.5]);
    end
    set(handles.LedSireneCalada,'BackgroundColor',[1 0 0]);
else
    set(handles.LedSirene,'BackgroundColor',[0.5 0 0]);
    set(handles.LedSireneCalada,'BackgroundColor',[0.5 0 0]);
end
%XXXXXXXXXXXXXXXXXXXXXXXXXXX TESTE LAMPADAS XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
%-------------------------  Sinaleiro BBA 01 ------------------------------
if ValBBA1
    set(handles.LedBBA1,'BackgroundColor',[0 1 0]);
else
    set(handles.LedBBA1,'BackgroundColor',[0 0.5 0]);
end
%-------------------------  Sinaleiro BBA 02 ------------------------------
if ValBBA2
    set(handles.LedBBA2,'BackgroundColor',[0 1 0]);
else
    set(handles.LedBBA2,'BackgroundColor',[0 0.5 0]);
end
%-----------------------  Sinaleiro Temperatua ----------------------------
if ValTemp
    set(handles.LedTemp,'BackgroundColor',[0 1 0]);
else
    set(handles.LedTemp,'BackgroundColor',[0 0.5 0]);
end
%--------------------------  Sinaleiro Nivel ------------------------------
if ValNivel
    set(handles.LedNivel,'BackgroundColor',[0 1 0]);
else
    set(handles.LedNivel,'BackgroundColor',[0 0.5 0]);
end
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX  AQUECEDOR  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
%------------------------- Aquedecedor Inhibido  --------------------------
if ValAquecInhibido
    set(handles.LedAquecInhibido,'BackgroundColor',[0.75 0.75 0.75]);
    set(handles.txtAquecInhibido,'String','Aquecedor Inhibido');
else
    set(handles.LedAquecInhibido,'BackgroundColor',[0 1 0]);
    set(handles.txtAquecInhibido,'String','Aquecedor Liberado');
end
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX  SEGURANÇA  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
%------------------------------ Termostato --------------------------------
if ValTermostato
    set(handles.LedTermostato,'BackgroundColor',[1 0 0]);
else
    set(handles.LedTermostato,'BackgroundColor',[0.5 0 0]);
end
%----------------------------- Chave de Nivel -----------------------------
if ValChavedeNivel
    set(handles.LedChavedeNivel,'BackgroundColor',[1 0 0]);
else
    set(handles.LedChavedeNivel,'BackgroundColor',[0.5 0 0]);
end
%XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX  ALARMES  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
%--------------------- Temp. Alta Tanque de Aquecimiento ------------------
if ValTempHiTqAquec
    set(handles.LedTempHiTqAquec,'BackgroundColor',[1 0 0]);
else
    set(handles.LedTempHiTqAquec,'BackgroundColor',[0.5 0 0]);
end
%----------------------- Temp. Alta Tanque de Mistura ---------------------
if ValTempHiTqMist
    set(handles.LedTempHiTqMist,'BackgroundColor',[1 0 0]);
else
    set(handles.LedTempHiTqMist,'BackgroundColor',[0.5 0 0]);
end
%------------------------------- Nivel Baixo ------------------------------
if ValNivelBaixo
    set(handles.LedNivelBaixo,'BackgroundColor',[1 0 0]);
else
    set(handles.LedNivelBaixo,'BackgroundColor',[0.5 0 0]);
end
%--------------------------- Aquecimento Inhibido -------------------------
if ValAquecInhibido
    set(handles.LedAquecInhibido1,'BackgroundColor',[1 0 0]);
else
    set(handles.LedAquecInhibido1,'BackgroundColor',[0.5 0 0]);
end
%------------------------------- Emergencia -------------------------------
if ValEmergencia
    set(handles.LedEmergencia,'BackgroundColor',[1 0 0]);
else
    set(handles.LedEmergencia,'BackgroundColor',[0.5 0 0]);
end

if a==0
    a=1;
    set(handles.LedCiclo,'BackgroundColor',[0.5 0 0]);
else
    a=0;
    set(handles.LedCiclo,'BackgroundColor',[1 0 0]);
end
pause(1)

end %fim do while

%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%************ Funções de Ligações de variaveis Discretas ******************
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
function cmdLigaBBA1_Callback(hObject, eventdata, handles)
global ItmLigaBBA1 ItmDesligaBBA1
write(ItmDesligaBBA1,0);
pause(0.1);
write(ItmLigaBBA1,1);

function cmdDesligaBBA1_Callback(hObject, eventdata, handles)
global ItmLigaBBA1 ItmDesligaBBA1
write(ItmLigaBBA1,0);
pause(0.1);
write(ItmDesligaBBA1,1);

function cmdLigaBBA2_Callback(hObject, eventdata, handles)
global ItmLigaBBA2 ItmDesligaBBA2
write(ItmDesligaBBA2,0);
pause(0.1)
write(ItmLigaBBA2,1);

function cmdDesligaBBA2_Callback(hObject, eventdata, handles)
global ItmLigaBBA2 ItmDesligaBBA2
write(ItmLigaBBA2,0);
pause(0.1)
write(ItmDesligaBBA2,1);

function cmdLigaTesteLamp_Callback(hObject, eventdata, handles)
global ItmLigaTesteLamp
write(ItmLigaTesteLamp,1);

function cmdDesligaTesteLamp_Callback(hObject, eventdata, handles)
global ItmLigaTesteLamp
write(ItmLigaTesteLamp,0);

function cmdLiberaAquec_Callback(hObject, eventdata, handles)
global ItmLiberaAquec
write(ItmLiberaAquec,1);
pause(0.2)
write(ItmLiberaAquec,0);

function cmdInhibeAquec_Callback(hObject, eventdata, handles)
global ItmInhibeAquec
write(ItmInhibeAquec,1);
pause(0.0)
write(ItmInhibeAquec,0);

function cmdCalaSirene_Callback(hObject, eventdata, handles)
global ItmCalaSirene
write(ItmCalaSirene,1);
pause(0.1)
write(ItmCalaSirene,0);

%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%************ Funções para Acionar Emergencia do Supervisorio *************
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
function cmdAcionarEmergencia_Callback(hObject, eventdata, handles)
global ItmEmergenciaSup
write(ItmEmergenciaSup,1);

function cmdDesativarEmergencia_Callback(hObject, eventdata, handles)
global ItmEmergenciaSup
write(ItmEmergenciaSup,0);

%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%************ Funções para Resetear os Consumos dos Tanques ***************
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
function cmdResetConsumoTq1_Callback(hObject, eventdata, handles)
global ItmResetConsumoTq1
write(ItmResetConsumoTq1,1);

function cmdResetConsumoTq2_Callback(hObject, eventdata, handles)
global ItmResetConsumoTq2
write(ItmResetConsumoTq2,1);

function cmdResetConsumoTotal_Callback(hObject, eventdata, handles)
global ItmResetConsumoTotal
write(ItmResetConsumoTotal,1);

%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%************* Função para selecionar o Tipo de Controlador  **************
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
function popTipodeControle_Callback(hObject, eventdata, handles)
global lblTipodeControle
lblTipodeControle = get(hObject,'Value');

%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%*********** Funções de Tipo de Controle Manual ou Automatico *************
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
function cmdAutoTic31_Callback(hObject, eventdata, handles)
global ItmManAutoTIC31
write(ItmManAutoTIC31,8);

function cmdManTic31_Callback(hObject, eventdata, handles)
global ItmManAutoTIC31
write(ItmManAutoTIC31,16);

function cmdAutoTic32_Callback(hObject, eventdata, handles)
global ValManAutoTIC32
ValManAutoTIC32 = 8;

function cmdManTic32_Callback(hObject, eventdata, handles)
global ValManAutoTIC32
ValManAutoTIC32 = 16;
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%************** OBTINDO VALORES DOS CUADROS DO TEXTO **********************
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
function txtFiy31_Callback(hObject, eventdata, handles)
global ValFy31Ao ItmFy31Ao
ValFy31Ao = get(hObject,'String');
write(ItmFy31Ao,ValFy31Ao); % % de Apertura da valvula TQ Aquec
set(hObject,'String',ValFy31Ao);

function txtSPTic31_Callback(hObject, eventdata, handles)
global ValTy31SpPid ItmTy31SpPid
ValTy31SpPid = get(hObject,'String');
write(ItmTy31SpPid,ValTy31SpPid); % SP de Temp. do Controle Tq Aquec
set(hObject,'String',ValTy31SpPid);

function txtMVTic31_Callback(hObject, eventdata, handles)
global ValTy31Pid ItmTy31Pid
ValTy31Pid = get(hObject,'String');
write(ItmTy31Pid,ValTy31Pid); % %Corrente às Resist. de Aquecimento
set(hObject,'String',ValTy31Pid);

function txtSPTic32_Callback(hObject, eventdata, handles)
global ValFy32Sp
ValFy32Sp = str2num(get(hObject,'String'));

function txtMVTic32_Callback(hObject, eventdata, handles)
global ValFy32Ao ItmFy32Ao
ValFy32Ao = get(hObject,'String');
write(ItmFy32Ao,ValFy32Ao); %  de Apertura da valvula TQ Mistura

%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%********************* FUNÇÕES DOS CONTROLADORES **************************
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%XXXXXXXXXXXXXXXXXXXX CONTROLE POR REDES NEURAIS XXXXXXXXXXXXXXXXXXXXXXXXXX
function vm = controlneural(sp,pv)
global W Wo V Vo yk_1 yk_2
sp = double(sp);
pv = double(pv);
alpha=0.01;%Fator de Apredizagem
e = sp - pv; %e:Erro da Saida Desejada
x = [yk_1 yk_2 e]';
%--------------------- Saida das Neuronas Ocultas -------------------------
Zin = V*x;
Z = tansig(Zin+Vo);
%-------------------------- Saida da Rede ---------------------------------
Yin = W'*Z;
Y = logsig(Yin+Wo); %Se as Saidas são nodos
vm = 100*Y;
yk_1 = Y;
yk_2 = yk_1;

%XXXXXXXXXXXXXXXXXXXXXXXXXXXXX CONTROLE PID XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
function aNewAcao = controlpid(aNewErro,aOldErro, aOldAcao)
Kp = 3.6;
Tr = 9;
Td = 1;
K1 = Kp;
K2 = (Kp/Tr);
K3 = Td*Kp;
Bias = -9;
aNewAcaoAux=(K1+2*K2+K3/2)*aNewErro+K3*2*aOldErro+K2*aOldAcao+Bias;
if aNewAcaoAux < 0
    if aNewAcaoAux < -105
        aNewAcao = -105;
    else
    aNewAcao = aNewAcaoAux;
    end
else
    aNewAcao = 0;
end

%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%****************** FUNÇÕES DO USUARIO PARA VISUALIZAÇÂO ******************
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%XXXXXXXXX Calcula o Nivel de Cor para a Temo. do Tanque de Aquec XXXXXXXXX
function [verde,azul] = cor_resistencia(x)
verde = 1 - 0.05*x;
azul = 0.5 - 0.025*x;

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

%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%******************************* SAIR *************************************
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888

function cmdSair_Callback(hObject, eventdata, handles)
global BitStop
BitStop = 0;
pos_size = get(handles.figure1,'Position');
user_response = modaldlg([pos_size(1)+pos_size(3)/2 pos_size(2)+pos_size(4)/2]);
switch user_response
    case {'no','cancel'}
        BitStop = 1;
        % take no action
    case 'yes'
        delete(handles.figure1);
        clear all;
end

%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
%****************** Funções não Utilisadas ********************************
%88888888888888888888888888888888888888888888888888888888888888888888888888
%88888888888888888888888888888888888888888888888888888888888888888888888888
function txtFit31_CreateFcn(hObject, eventdata, handles)

function txtConsumoTq1_CreateFcn(hObject, eventdata, handles)

function txtFiy31_CreateFcn(hObject, eventdata, handles)

function txtTiy31_CreateFcn(hObject, eventdata, handles)

function txtLit31_CreateFcn(hObject, eventdata, handles)

function txtTit31_CreateFcn(hObject, eventdata, handles)

function txtTit32_CreateFcn(hObject, eventdata, handles)

function txtFiy32_CreateFcn(hObject, eventdata, handles)

function txtConsumoTq2_CreateFcn(hObject, eventdata, handles)

function txtFit32_CreateFcn(hObject, eventdata, handles)

function txtSPTic31_CreateFcn(hObject, eventdata, handles)

function txtPVTic31_CreateFcn(hObject, eventdata, handles)

function txtMVTic31_CreateFcn(hObject, eventdata, handles)

function txtSPTic32_CreateFcn(hObject, eventdata, handles)

function txtPVTic32_CreateFcn(hObject, eventdata, handles)

function txtMVTic32_CreateFcn(hObject, eventdata, handles)

function popTipodeControle_CreateFcn(hObject, eventdata, handles)

function figure1_DeleteFcn(hObject, eventdata, handles)
global daDfi daDf65 
disconnect(daDfi);
disconnect(daDf65);
delete(daDfi);
delete(daDf65);
opcreset;   
