%% Measure Power on a Keysight(R) RF Power Meter using the IVI-C Driver
% This example shows how to initialize the driver, read a few properties of 
% the driver and make power measurements using Keysight RF Power Meter and
% output the result in MATLAB(R).

%%
% Copyright 2015 The MathWorks, Inc.

%% Requirements
% This example requires the following:
%
% * Keysight (Agilent) IO libraries version 17.1 or newer
% * Keysight (Agilent) RF Power Meter IVI version 1.0.9.0 or newer
%

%% Enumerate Available IVI-C Drivers On The Computer
% This enumerates the IVI drivers that have been installed on the computer.
IviInfo = instrhwinfo('ivi');
IviInfo.Modules

%% Create a MATLAB Instrument Driver and Connect to the Simulated Instrument

% Create the MATLAB instrument driver
makemid('KtRFPowerMeter','KtRFPowerMeter.mdd')

% Use icdevice with the MATLAB instrument driver name and instrument's 
% resource name to create a device object. In this example the instrument 
% is connected by GPIB at board index 0 and primary address 1.
myInstrument = icdevice('KtRFPowerMeter.mdd', 'GPIB0::01::INSTR','optionstring','simulate=true');

% Connect driver instance
connect(myInstrument);

%% Attributes and Variables Definition

% These values are defined in the driver's header file 'KtRFPowerMeter.h'
IVI_ATTR_BASE = 1000000;
IVI_CLASS_ATTR_BASE = IVI_ATTR_BASE + 250000;
IVI_SPECIFIC_ATTR_BASE = IVI_ATTR_BASE + 150000;
KTRFPOWERMETER_ATTR_CALIBRATOR_ENABLED = IVI_SPECIFIC_ATTR_BASE + 189; % 1150189
KTRFPOWERMETER_ATTR_OFFSET = IVI_CLASS_ATTR_BASE + 5; % 1250005
KTRFPOWERMETER_ATTR_CHANNELS_ITEM_TRIGGER_CONTINUOUS_ENABLED = IVI_SPECIFIC_ATTR_BASE + 49;
KTRFPOWERMETER_ATTR_MEASUREMENTS_ITEM_OFFSET_ENABLED = IVI_SPECIFIC_ATTR_BASE + 79;
    
%% Get General Device Properties
% Query information about the driver and instrument
DriverIdentification = get(myInstrument,'Inherentiviattributesdriveridentification');
InstrumentIdentification = get(myInstrument,'Inherentiviattributesinstrumentidentification');
Utility = get(myInstrument, 'Utility');
Revision = invoke(Utility, 'revisionquery');
Vendor = get(DriverIdentification, 'Specific_Driver_Vendor');
Description = get(DriverIdentification, 'Specific_Driver_Description');
InstrumentModel = get(InstrumentIdentification, 'Instrument_Model');
FirmwareRev = get(InstrumentIdentification, 'Instrument_Firmware_Revision');

% Print the queried driver properties
fprintf('Revision:        %s\n', Revision);
fprintf('Vendor:          %s\n', Vendor);
fprintf('Description:     %s\n', Description);
fprintf('InstrumentModel: %s\n', InstrumentModel);
fprintf('FirmwareRev:     %s\n', FirmwareRev);
fprintf(' \n');

%% Configure Power Meter

% Perform the default preset on the power meter
InstrumentSpecificSystem = get(myInstrument, 'Instrumentspecificsystem');
invoke(InstrumentSpecificSystem, 'systempreset');
% Wait until all instrument operations complete or until MaxTimeMilliseconds has expired
invoke(InstrumentSpecificSystem, 'systemwaitforoperationcomplete', 20000);
% Disables continuous triggering
AttributeAccessors = get(myInstrument, 'Attributeaccessors');   
invoke(AttributeAccessors, 'setattributeviboolean', 'A', KTRFPOWERMETER_ATTR_CHANNELS_ITEM_TRIGGER_CONTINUOUS_ENABLED, 0);
% Get the number of channels available on the instrument
BasicOperation = get(myInstrument, 'Basicoperation');
ChannelCount = get(BasicOperation, 'Channel_Count');
% Get the model number or name reported by the physical instrument
InherentIviAttributesInstrumentIdentification = get(myInstrument, 'Inherentiviattributesinstrumentidentification');
InstrumentModel = get(InherentIviAttributesInstrumentIdentification, 'Instrument_Model');
if (ChannelCount >= 2) && not(strcmpi(InstrumentModel,'N1913A')) && not(strcmpi(InstrumentModel,'N1914A'))
    % Disables continuous triggering
    invoke(AttributeAccessors, 'setattributeviboolean', 'B', KTRFPOWERMETER_ATTR_CHANNELS_ITEM_TRIGGER_CONTINUOUS_ENABLED, 0);
end
% Enables the POWER REF output
invoke(AttributeAccessors, 'setattributeviboolean', 'A', KTRFPOWERMETER_ATTR_CALIBRATOR_ENABLED, 1);

%% Make Measurements

% Initiates a measurement on all enabled channels
MeasurementLowLevelMeasurement = get(myInstrument, 'Measurementlowlevelmeasurement');
invoke(MeasurementLowLevelMeasurement, 'initiate');
% Wait until all instrument operations complete or MaxTimeMilliseconds has expired
invoke(InstrumentSpecificSystem, 'systemwaitforoperationcomplete', 10000);
for iLoop = 1:4
    % Specifying an offset to be added to the measured value in units of dB
    invoke(AttributeAccessors, 'setattributevireal64', 'A', KTRFPOWERMETER_ATTR_OFFSET, -10*iLoop);
    % Initiates a measurement
    InstrumentSpecificMeasurement = get(myInstrument, 'Instrumentspecificmeasurement');
    ReadResult = invoke(InstrumentSpecificMeasurement, 'measurementsitemread', '1',50000);
    % Disable the display offset		
    invoke(AttributeAccessors, 'setattributeviboolean', '1', KTRFPOWERMETER_ATTR_MEASUREMENTS_ITEM_OFFSET_ENABLED,0);
    % Fetch the result of a previously initiated measurement 
    FetchResult = invoke(InstrumentSpecificMeasurement, 'measurementsitemfetch', '1',50000);
    % Enable the display offset			
    invoke(AttributeAccessors, 'setattributeviboolean', '1', KTRFPOWERMETER_ATTR_MEASUREMENTS_ITEM_OFFSET_ENABLED,1);
    % Perform a power measurement
    MeasResult = invoke(InstrumentSpecificMeasurement, 'measurementsitemmeasure', '1',50000);
    fprintf('Read result: %.3f, Fetch Result: %g, Measure Result: %g\n', ReadResult, FetchResult, MeasResult);
end
fprintf('\n');

%% Display Any Errors from the Driver

% If there are any errors, query the driver to retrieve and display them.
ErrorNum = 1;
while (ErrorNum ~= 0)
    [ErrorNum, ErrorMsg] = invoke(Utility, 'errorquery');
    fprintf('ErrorQuery: %d, %s\n', ErrorNum, ErrorMsg);
end

%% Disconnect Device Object and Clean Up
disconnect(myInstrument);
% Remove instrument objects from memory.
delete(myInstrument);

%%



%% Additional Information:
% This example shows the setup and measuring of power from a RF power meter
% using the IVI driver. Once the measured data is retrieved from the 
% instrument, MATLAB can be used to visualize and perform analyses on the 
% data using the rich library of functions in the Signal Processing
% Toolbox(TM) and Communications Systems Toolbox(TM). Using Instrument
% Control Toolbox(TM), it is possible to automate control of instruments,
% and, build test systems that use MATLAB to perform analyses that may not
% be possible using the built-in capability of the hardware.
