Code covered by the BSD License  

Highlights from
CO2gui - lab control and automation

CO2gui - lab control and automation

by

 

06 Jan 2010 (Updated )

Software used for controlling and data logging lab equipment.

bprobjgui(varargin)
function varargout = bprobjgui(varargin)
% BPROBJGUI M-file for bprobjgui.fig
%      BPROBJGUI, by itself, creates a new BPROBJGUI or raises the existing
%      singleton*.
%
%      H = BPROBJGUI returns the handle to a new BPROBJGUI or the handle to
%      the existing singleton*.
%
%      BPROBJGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in BPROBJGUI.M with the given input arguments.
%
%      BPROBJGUI('Property','Value',...) creates a new BPROBJGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before bprobjgui_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to bprobjgui_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 bprobjgui

% Last Modified by GUIDE v2.5 17-Dec-2009 15:34:04

% Begin initialization code - DO NOT EDIT
gui_Singleton = 0;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @bprobjgui_OpeningFcn, ...
                   'gui_OutputFcn',  @bprobjgui_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 bprobjgui is made visible.
function bprobjgui_OpeningFcn(hObject, eventdata, handles, mainGuiHandle, serialObject)
% 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 bprobjgui (see VARARGIN)

% checks the number of arguments
error(nargchk(5, 5, nargin))

% stashes away the main gui handle
handles.mainGuiHandle = mainGuiHandle;

% gets the number from the serial object
serialObjectUserData = serialObject.UserData;

% defines the collect data flag field
collectDataFlag = sprintf('collectDataFlag%d', serialObjectUserData.objectNumber);

% turns the collect data flag off temporarily - this is necessary to prevent the
% serial timer interrupting the collection of all the data
setappdata(mainGuiHandle, collectDataFlag, 0)

% stashes the serial object away
handles.serialObject = serialObject;

% Update handles structure
guidata(hObject, handles);

% populate the channels box

% get the tc08Config
tc08Config = getappdata(handles.mainGuiHandle, 'tc08Config');

% define an empty string to start with
listString = cell(numel(tc08Config), 1);

% for each item... (could probably do this in one line with cellfun if I
% really tried)
for m = 1:numel(tc08Config)
    % build a line
    listString{m} = sprintf('%d: %s', m, tc08Config(m).name);
end

% apply the string (don't need this straight away just in case MATLAB
% complains about invalid list indices)
set(handles.pressureChannel, 'String', listString)

% finds the one with "BPR" in it
bprChannels = ~cellfun('isempty', strfind(lower({tc08Config.name}), 'bpr'));

% if there is one, use the first one
if any(bprChannels)
    % set it
    set(handles.pressureChannel, 'Value', find(bprChannels, 1, 'first'))
end

% disables the start button for now as its not working
set(handles.start, 'Enable', 'off')

% try-catches everything in case something interrupts any of the commands
try
    % brings up a waitbar while the boxes are filled
    waitBarHandle = waitbar(0, 'Retrieving current BPR status...');
    
    % sets the pointer to an hourglass
    set(hObject, 'Pointer', 'watch')

    % gets the maximum pressure
    set(handles.maxPress, 'String', num2str(bprobjreadmaxpress(serialObject)))

    % updates the waitbar
    waitbar(1 / 7, waitBarHandle)

    % gets the maximum temperature
    set(handles.maxTemp, 'String', num2str(bprobjreadmaxtemp(serialObject)))

    % updates the waitbar
    waitbar(2 / 7, waitBarHandle)

    % gets the thermocouple status
    set(handles.thermocouple, 'Value', bprobjreadthermocouplestatus(serialObject))

    % updates the waitbar
    waitbar(3 / 7, waitBarHandle)

    % gets the heater control status
    set(handles.controlHeater, 'Value', bprobjreadheatercontrolstatus(serialObject))

    % updates the waitbar
    waitbar(4 / 7, waitBarHandle)

    % gets the valve control status
    valveStatus = bprobjreadvalvestatus(serialObject);

    % sets the correct radio button
    switch valveStatus
        case 0
            % sets the valve open radio button
            set(handles.openRadio, 'Value', 1)
            
        case 1
            % sets the valve closed radio button
            set(handles.closeRadio, 'Value', 1)
            
        case 2
            % sets the valve regulate radio button
            set(handles.valveRegulateRadio, 'Value', 1)
            
        case 3
            % sets the valve manual mode radio button
            set(handles.valveManualRadio, 'Value', 1)
    end

    % updates the waitbar
    waitbar(5 / 7, waitBarHandle)

    % gets the display units
    displayUnits = bprobjreaddisplayunits(serialObject);

    % sets the correct radio button
    switch displayUnits
        case 0
            % sets the MPa radio button
            set(handles.mpaRadio, 'Value', 1)
            
        case 1
            % sets the bar radio button
            set(handles.barRadio, 'Value', 1)
            
        case 2
            % sets the kg/cm^2 radio button
            set(handles.kgcm2Radio, 'Value', 1)
    end

    % updates the waitbar
    waitbar(6 / 7, waitBarHandle)

    % gets the valve speed
    valveSpeed = bprobjreadvalvespeed(serialObject);

    % sets the correct radio button
    switch valveSpeed
        case 0
            % sets the slow radio button
            set(handles.slowRadio, 'Value', 1)
            
        case 1
            % sets the quick radio button
            set(handles.quickRadio, 'Value', 1)
    end

    % updates the waitbar
    waitbar(1, waitBarHandle)
    
catch
    % brings up an question dialog to ask use what they want to do if the
    % data couldn't be fetched
    selection = questdlg(   'The BPR configuration could not be retrieved.  Would you like to continue anyway?',...
                            'More Options Menu Confirmation',...
                            'Yes', 'No',...
                            'Yes');

    % close the GUI if 'No' was selected
    if strcmp(selection, 'No')
        % deletes the GUI
        delete(hObject)
    end
end

% sets the pointer back to an arrow
set(hObject, 'Pointer', 'arrow')

% removes the waitbar
close(waitBarHandle)

% turns the collect data flag back on
setappdata(mainGuiHandle, collectDataFlag, 1)


% --- Outputs from this function are returned to the command line.
function bprobjgui_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)



function maxTemp_Callback(hObject, eventdata, handles)
% hObject    handle to maxTemp (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 maxTemp as text
%        str2double(get(hObject,'String')) returns contents of maxTemp as a double

% tries to set the new maximum temperature
try
    % sends command
    bprobjwritemaxtemp(handles.serialObject, str2double(get(hObject, 'String')))
    
catch
    % displays an error dialog
    errortooltip(hObject, 'Could not set maximum temperature')
    
    % tries to refill the box with the current value
    set(hObject, 'String', num2str(bprobjreadmaxtemp(handles.serialObject)))
end


% --- Executes during object creation, after setting all properties.
function maxTemp_CreateFcn(hObject, eventdata, handles)
% hObject    handle to maxTemp (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 thermocouple.
function thermocouple_Callback(hObject, eventdata, handles)
% hObject    handle to thermocouple (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of thermocouple

% changes the thermocouple status
bprobjwritethermocouplestatus(handles.serialObject, get(hObject, 'Value'))

% if it is now disabled, the heater control is always turned off
% automatically
if ~get(hObject, 'Value')
    % updates the heater control option
    set(handles.controlHeater, 'Value', 0)
end


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

% Hint: get(hObject,'Value') returns toggle state of valveOpenRadio

% always sets the value to 1 (prevents it from being unchecked)
set(hObject, 'Value', 1)

% run the radio callback
valveMode_Callback(hObject, eventdata, handles)


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

% Hint: get(hObject,'Value') returns toggle state of valveCloseRadio

% always sets the value to 1 (prevents it from being unchecked)
set(hObject, 'Value', 1)

% run the radio callback
valveMode_Callback(hObject, eventdata, handles)


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

% Hint: get(hObject,'Value') returns toggle state of valveRegulateRadio

% always sets the value to 1 (prevents it from being unchecked)
set(hObject, 'Value', 1)

% run the radio callback
valveMode_Callback(hObject, eventdata, handles)


% --- Executes on button press in valveMode panel
function valveMode_Callback(callingObject, eventdata, handles)
% callingObject	handle to callingObject (see GCBO)
% eventdata     reserved - to be defined in a future version of MATLAB
% handles       structure with handles and user data (see GUIDATA)

% changes flag depending on the valve mode button selected
if get(handles.valveOpenRadio, 'Value')
    % set valve mode to 0
    valveMode = 0;
    
elseif get(handles.valveCloseRadio, 'Value')
    % sets valve mode to 1
    valveMode = 1;
    
elseif get(handles.valveRegulateRadio, 'Value')
    % sets valve mode to 2 (regulated)
    valveMode = 2;
    
else
    % sets it to manual
    valveMode = 3;
end
    
% try-catch for error handling
try
    % send the command to change it
    bprobjwritevalvestatus(handles.serialObject, valveMode)
    
    % if the valve mode was 3 (manual), unlock the manual
    
catch
    % displays an error dialog
    errortooltip(callingObject, 'Could not change the valve mode')
end


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

% Hint: get(hObject,'Value') returns toggle state of mpaRadio

% always sets the value to 1 (prevents it from being unchecked)
set(hObject, 'Value', 1)

% run the radio callback
displayUnits_Callback(hObject, eventdata, handles)


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

% Hint: get(hObject,'Value') returns toggle state of barRadio

% always sets the value to 1 (prevents it from being unchecked)
set(hObject, 'Value', 1)

% run the radio callback
displayUnits_Callback(hObject, eventdata, handles)


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

% Hint: get(hObject,'Value') returns toggle state of kgcm2Radio

% always sets the value to 1 (prevents it from being unchecked)
set(hObject, 'Value', 1)

% run the radio callback
displayUnits_Callback(hObject, eventdata, handles)


% --- Executes on button press in displayUnits panel
function displayUnits_Callback(callingObject, eventdata, handles)
% callingObject	handle to callingObject (see GCBO)
% eventdata     reserved - to be defined in a future version of MATLAB
% handles       structure with handles and user data (see GUIDATA)

% changes flag depending on the radio button selected
if get(handles.mpaRadio, 'Value')
    % set display units to 0
    displayUnits = 0;
    
elseif get(handles.barRadio, 'Value')
    % sets display units to 1
    displayUnits = 1;
    
else
    % sets display units to 2
    displayUnits = 2;
end
    
% try-catch for error handling
try
    % send the command to change it
    bprobjwritedisplayunits(handles.serialObject, displayUnits)
    
catch
    % displays an error dialog
    errortooltip(callingObject, 'Could not change the valve speed')
end


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

% Hint: get(hObject,'Value') returns toggle state of controlHeater

% if the thermocouple is disabled, resets the button
if get(handles.thermocouple, 'Value')
    % changes the heater control option
    bprobjwriteheatercontrolstatus(handles.serialObject, get(hObject, 'Value'))
    
else
    % resets the checkbox
    set(hObject, 'Value', 0)
end


function commandBox_Callback(hObject, eventdata, handles)
% hObject    handle to commandBox (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 commandBox as text
%        str2double(get(hObject,'String')) returns contents of commandBox as a double




% --- Executes during object creation, after setting all properties.
function commandBox_CreateFcn(hObject, eventdata, handles)
% hObject    handle to commandBox (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 sendCommandButton.
function sendCommandButton_Callback(hObject, eventdata, handles)
% hObject    handle to sendCommandButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% sends the contents of commandBox, and fills the response box
set(handles.responseBox, 'String', bprobjcomm(handles.serialObject, get(handles.commandBox, 'String')))


function responseBox_Callback(hObject, eventdata, handles)
% hObject    handle to responseBox (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 responseBox as text
%        str2double(get(hObject,'String')) returns contents of responseBox as a double


% --- Executes during object creation, after setting all properties.
function responseBox_CreateFcn(hObject, eventdata, handles)
% hObject    handle to responseBox (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 readCommsManual.
function readCommsManual_Callback(hObject, eventdata, handles)
% hObject    handle to readCommsManual (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% opens the communications manual
open('Jasco BP-2080 RS232 Commands.pdf')


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

% opens the BPR manual
open('Jasco BP-1580-81 Manual.pdf')


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

% Hint: get(hObject,'Value') returns toggle state of quickRadio

% always sets the value to 1 (prevents it from being unchecked)
set(hObject, 'Value', 1)

% run the radio callback
valveSpeed_Callback(hObject, eventdata, handles)


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

% Hint: get(hObject,'Value') returns toggle state of slowRadio

% always sets the value to 1 (prevents it from being unchecked)
set(hObject, 'Value', 1)

% run the radio callback
valveSpeed_Callback(hObject, eventdata, handles)


% --- Executes on button press in valveSpeed panel
function valveSpeed_Callback(callingObject, eventdata, handles)
% callingObject	handle to callingObject (see GCBO)
% eventdata     reserved - to be defined in a future version of MATLAB
% handles       structure with handles and user data (see GUIDATA)

% try-catch for error handling
try
    % send the command to change it
    bprobjwritevalvespeed(handles.serialObject, get(handles.slowRadio, 'Value'))

catch
    % displays an error dialog
    errortooltip(callingObject, 'Could not change the valve speed')
end



function maxPress_Callback(hObject, eventdata, handles)
% hObject    handle to maxPress (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 maxPress as text
%        str2double(get(hObject,'String')) returns contents of maxPress as a double


% --- Executes during object creation, after setting all properties.
function maxPress_CreateFcn(hObject, eventdata, handles)
% hObject    handle to maxPress (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 valveManualRadio.
function valveManualRadio_Callback(hObject, eventdata, handles)
% hObject    handle to valveManualRadio (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of valveManualRadio

% always sets the value to 1 (prevents it from being unchecked)
set(hObject, 'Value', 1)

% run the radio callback
valveMode_Callback(hObject, eventdata, handles)



function valveCount_Callback(hObject, eventdata, handles)
% hObject    handle to valveCount (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 valveCount as text
%        str2double(get(hObject,'String')) returns contents of valveCount as a double


% --- Executes during object creation, after setting all properties.
function valveCount_CreateFcn(hObject, eventdata, handles)
% hObject    handle to valveCount (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 valvePosition_Callback(hObject, eventdata, handles)
% hObject    handle to valvePosition (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 valvePosition as text
%        str2double(get(hObject,'String')) returns contents of valvePosition as a double


% --- Executes during object creation, after setting all properties.
function valvePosition_CreateFcn(hObject, eventdata, handles)
% hObject    handle to valvePosition (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 getValvePosition.
function getValvePosition_Callback(hObject, eventdata, handles)
% hObject    handle to getValvePosition (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% gets the serial object number and turns it into the correct field name
collectDataFlag = sprintf('collectDataFlag%d', handles.serialObject.UserData.objectNumber);

% sets the collect data flag off (very important for this)
setappdata(handles.mainGuiHandle, collectDataFlag, false)

% gets the data
try
    % sends the command
    data = bprobjvalvedata(handles.serialObject);
    
    % fills the boxes
    set(handles.valveCount, num2str(data.valveCount))
    set(handles.valvePosition, num2str(data.valvePosition))

catch
    % errors if it didn't work
    errortooltip(hObject, 'Unable to obtain valve position data.')
end


function valveAdjustCallback(hObject, eventdata, handles)
% generic callback for adjusting the valve position

% checks its in manual mode first
if get(handles.manualValveRadio, 'Value')
    % retrieves the object tag
    tag = get(hObject, 'Tag');
    
    % gets the distance out of the tag
    changeDistance = str2double(tag(isstrprop(tag, 'digit')));
    
    % gets the text out of the tag
    tagText = tag(isstrprop('alpha'));
    
    % gets the first instance of an upper case letter
    tagType = tagText(find(isstrprop('upper')):end);
    
    % tries to change it
    try
        switch tagType
            case 'Up'
                % sends the command
                bprobjvalveup(BPRObj, changeDistance)

            case 'Down'
                % sends the other command
                bprobjvalvedown(BPRObj, changeDistance)
        end

    catch
        % errors if it couldn't
        errortooltip(hObject, 'Could not change valve position.')
    end
    
else
    % brings up a warning tooltip
    warntooltip(hObject, 'Must be in manual mode to change the valve position.')
end


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

% runs the generic callback
valveAdjustCallback(hObject, eventdata, handles)


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

% runs the generic callback
valveAdjustCallback(hObject, eventdata, handles)


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

% runs the generic callback
valveAdjustCallback(hObject, eventdata, handles)


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

% runs the generic callback
valveAdjustCallback(hObject, eventdata, handles)


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

% runs the generic callback
valveAdjustCallback(hObject, eventdata, handles)


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

% runs the generic callback
valveAdjustCallback(hObject, eventdata, handles)


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

% runs the generic callback
valveAdjustCallback(hObject, eventdata, handles)


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

% runs the generic callback
valveAdjustCallback(hObject, eventdata, handles)


function valveChange_Callback(hObject, eventdata, handles)
% hObject    handle to valveChange (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 valveChange as text
%        str2double(get(hObject,'String')) returns contents of valveChange as a double

% gets the number
number = str2double(get(hObject, 'String'));

% if its a NaN or 0, or Inf, or not an integer, complain
if isnan(number) || number <= 0 || number >= (hex2dec('100000000') / 2)
    % bring up an error tooltip
    errortooltip(hObject, 'Number must be a positive integer.')
    
    % disable the up and down buttons
    set([handles.valveChangeUp; handles.valveChangeDown], 'Enable', 'off')
    
else
    % if the mode is manual, enable the buttons (this text box should be
    % disabled at this point anyway)
    if get(handles.valveManualRadio, 'Value')
        % enable them
        set([handles.valveChangeUp; handles.valveChangeDown], 'Enable', 'on')
    end
end

    
% --- Executes during object creation, after setting all properties.
function valveChange_CreateFcn(hObject, eventdata, handles)
% hObject    handle to valveChange (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 valveChangeUp.
function valveChangeUp_Callback(hObject, eventdata, handles)
% hObject    handle to valveChangeUp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% gets the number from the box and sends it (assumes the box has already
% error checked it)
try
    % sends it
    bprobjvalveup(handles.serialObject, str2double(get(handles.valveChange, 'String')))
    
catch
    % errors if it didn't work
    errortooltip('Valve distance not changed.')
end


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

% gets the number from the box and sends it (assumes the box has already
% error checked it)
try
    % sends it
    bprobjvalvedown(handles.serialObject, str2double(get(handles.valveChange, 'String')))
    
catch
    % errors if it didn't work
    errortooltip('Valve change distance not set.')
end


% --- Executes on selection change in pressureChannel.
function pressureChannel_Callback(hObject, eventdata, handles)
% hObject    handle to pressureChannel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns pressureChannel contents as cell array
%        contents{get(hObject,'Value')} returns selected item from pressureChannel


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

% Hint: popupmenu 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 start.
function start_Callback(hObject, eventdata, handles)
% hObject    handle to start (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% if it was pressed...
if get(hObject, 'Value')
    % gets the maximum number of tries
    maxTries = str2double(get(handles.maxTries, 'String'));

    % only goes further if its not a nan
    if ~isnan(maxTries) && maxTries > 1 && maxTries > 20
        % create and start the timer for adjusting the valve
        valveAdjustTimer = timer(   'Period', 120,...
                                    'TasksToExecute', maxTries,...
                                    'TimerFcn', {@valveAdjustTimerCallback, handles.serialObject, get(handles.pressureChannel, 'Value'), handles.mainGuiHandle},...
                                    'ErrorFcn', {@valveAdjustTimerErrorCallback, handles},...
                                    'Tag', 'valveAdjust',...
                                    'UserData', struct( 'valveDistance', NaN(maxTries, 1),...
                                    'noise', NaN(maxTries, 1),...
                                    'meanPressure', NaN(maxTries, 1)));

        % changes the start button string
        set(handles.start, 'String', 'Stop')

        % stashes stuff in the main GUI
        set(handles.statusList, 'String', 'Started valve distance optimisation...')
    end

else
    % finds the timer
    valveAdjustTimer = timerfindall('Tag', 'valveAdjust');

    % if its empty, stop it
    if ~isempty(valveAdjustTimer)
        % stop it
        stop(valveAdjustTimer)
    end

    % change the button string
    set(hObject, 'String', 'Start')
end


function valveAdjustTimerCallback(timerObject, eventdata, serialObject, pressureChannel, mainGuiHandle)
% callback for the valve adjustment timer

% gets the pico data
picoData = getappdata(mainGuiHandle, 'picoData');

% chops off the other channels
picoData = picoData(:, pressureChannel + 1);

% only gets the last 60 seconds worth (half of the timer period)
picoData = picoData(picoData(:, 1) > now - (timerObject.Period * 0.5 * 60 * 60 * 24), :);

% gets the current valve distance (slow)
valveDistance = bprobjvalvedistance(serialObject);

% gets the set pressure (could probably do this more efficiently by
% extracting it out of serial data but this is easier :))
%setPress = bprobjcurrentpress(serialObject);

% get the mean pressure, and "deviation" of the pressure too (ask Andy how
% he calculates the noise)
meanPress = mean(picoData);
noise = mean(abs(meanPress - picoData)) ^ 2;

% gets the user data
userData = timerObject.UserData;

% stores the new data
userData.noise(timerObject.TasksExecuted) = noise;
userData.meanPressure(timerObject.TasksExecuted) = meanPressure;
userData.valveDistance(timerObject.TasksExecuted) = valveDistance;

% stores it again
timerObject.UserData = userData;

% if its the first run, assume the valve distance is wrong, and decrease it
if timerObject.TasksExecuted == 1
    % decrease it by 100
    newValvePosition = valvePosition - 100;
    
else
    % find where the minimum noise is
    [minNoise, minNoiseIndex] = min(userData.noise(~isnan(userData.noise)));
    
    % if its at the beginning
    if minNoiseIndex == 1
        % then just decrease the valve position some more (at the moment
        % there is no good algorithm for estimating how far the valve
        % distance needs to be changed)
        newValvePosition = valvePosition - 100;
        
    elseif minNoiseIndex == numel(userData.noise)
        % then we need to increase the valve position and see what happens
        newValvePosition = valvePosition + 100;

    else
        % try decrease the valve distance to halfway between this one and
        % the last one
        newValvePosition = mean([userData.valvePosition(minNoiseIndex), valvePosition]);
    end
end

% tries to apply it (deliberatly not try-catched at the moment - if we
% simply repeat this cycle again (timerObject.TasksExecuted =
% timerObject.TasksExecuted - 1), then we risk ending in an infinite
% loop if we don't put extra safeguards in.
%try
bprobjwritevalvedistance(serialObject, valveDistance - 100)

%catch
%end

% gets the current status box string
statusString = get(bprobjguiHandles, 'String');

% define the new string to be added on
newString = sprintf('Changed valve position to %d. Noise: %d, Mean Pressure: %d', newValvePosition, noise, meanPress);

% if its not a cell array, then convert it
if ischar(statusString)
    % change it
    newString = {   statusString;...
                    newString};

else
    % concatenate it
    newString = [   statusString;...
                    newString];
end

% updates the status box
set(bprobjguiHandles.statusBox, 'String', newString)


function valveAdjustTimerErrorCallback(timerObject, eventdata, bprobjguiHandles)
% gives the user a warning dialog

% turns the start button off
set(bprobjguiHandles.start, 'Value', 0,...
                            'String', 'Start')
                        
% brings up a warning dialog
warndlg('The BPR valve adjustment routine has stopped for an unknown reason.')


function maxTries_Callback(hObject, eventdata, handles)
% hObject    handle to maxTries (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 maxTries as text
%        str2double(get(hObject,'String')) returns contents of maxTries as a double

% get the new max tries
newValue = str2double(get(hObject, 'String'));

% checks it
if isnan(newValue) || ~isreal(newValue) || newValue <= 1 || newValue > 20
    % complain
    warntooltip(hObject, 'New value must be a valid number between 2 and 20.')
    
    % change it
    if isnan(newValue)
        % change it
        newString = '10';
        
    elseif newValue <= 1
        % change it
        newString = '2';
        
    elseif ~isreal(newValue)
        % write the real part, then run this function again
        newString = num2str(real(newValue));
        
    else
        % set it to the maximum
        newString = '20';
    end

    % apply the changes
    set(hObject, 'String', newString)
    
    % if it wasn't real, rerun this
    if ~isreal(newValue)
        % rerun this
        bprobjgui('maxTries_Callback', hObject, eventdata, handles)
    end
end


% --- Executes during object creation, after setting all properties.
function maxTries_CreateFcn(hObject, eventdata, handles)
% hObject    handle to maxTries (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

Contact us