function response = pumpobjcomm(type, serialObject, command)
% PUMPOBJCOMM Reads and writes data from Jasco pumps
% pumpobjcomm(type, serialObject, command) reads from or writes information
% to Jasco pumps connected via RS232 serial ports. type is 'read' or
% 'write', serialObject is the valid serial object and command the command
% to be sent (string). Automatically leaves a 0.15 s pause after any
% commands where there is no response expected to prevent communications
% issues.
% Normal usage:
% e.g. 1 pumpobjcomm('read', serialObject, 'a_flow load p') - returns the
% current flow rate from the pump on COM9.
% e.g. 2 pumpobjcomm('write', serialObject, '0.200 flowrate set') - sets the
% flow rate to 0.200 mL min-1.
% Range:
% type = 'read' or 'write'
% serialObject = valid serial object
% command = string with maximum 4 parts
% error handling of arguments as arguments must be a number and in the
% correct range. Text can still be classed as an acceptable uint8/16 object
% so both logical decisions are necessary
% checks the number of arguments
error(nargchk(3, 3, nargin))
% pre-parses command for error checking
if nargin >= 3
% splits it up into words
commandParse = textscan(command, '%s');
end
% error checking here
if ~isequal(type, 'read') && ~isequal(type, 'write')
% errors
error('type must be "read" or "write".')
% checks serial object
elseif ~isa(serialObject, 'serial') || ~isvalid(serialObject) || ~strcmp(serialObject.Status, 'open')
% errors
error('serialObject must be a valid closed serial object.')
elseif ~ischar(command) || ~isvector(command) || length(commandParse{1}) > 4
% Pump will ignore any additional spaces between the words so it is not
% necessary to remove them if they are there
error('command must a string with no more than 4 words.')
end
% flushes everything in the buffer
fread(serialObject);
% sends command
fprintf(serialObject, command, 'async')
% if reading data, expecting a response
if strcmp(type, 'read')
% initialises loop
response = '%%';
% keeps on requesting a response until there is no '%%' in the
% output - this cancels through any errors there may be
while ~isempty(strfind(response, '%%'))
% reads data
response = fscanf(serialObject);
% if the response was empty, error
if isempty(response)
% errors
error(['No response from Jasco pump to "', command, '".'])
else
% strips off the terminators
response = response(1:end - 2);
end
end
else
% Must pause 150 ms after command before the next command is sent to
% avoid issues with pump not processing commands quickly enough -
% if a response has been retrieved then by definition its ready for
% another command so this pause is ONLY required for writing data
% when no response is given
pause(0.15)
end