function cfg = IASZoneFrameDecoder(zclPayload)
%IASZoneFrameDecoder Decode Intruder Alarm System Zone cluster library frames
%   CFG = IASZONEFRAMEDECODER(ZCLPAYLOAD) decodes the ZigBee Cluster
%   Library payload ZCLPAYLOAD and outputs the corresponding Intruder Alarm
%   System Zone cluster configuration to the object CFG.
%
%   See also zigbee.IASZoneFrameConfig, zigbee.IASZoneFrameGenerator.

%   Copyright 2017-2023 The MathWorks, Inc.

  % convert bytes to bits
  zclPayloadBin = zigbee.internal.bytes2bits(zclPayload);

  % 0. Initialize
  cfg = zigbee.IASZoneFrameConfig;

  % 1. Zone Status (2 octets)
  cfg = decodeZoneStatus(cfg, zclPayloadBin(1:2*8));

  % 2. Extended status (1 octet, reserved, ignore)

  % 3. Zone ID (1 octet)
  cfg.ZoneID = bit2int(zclPayloadBin(1+3*8 : 4*8)', 8, false);

  % 4. Delay (2 octets)
  cfg.Delay = bit2int(zclPayloadBin(1+4*8 : 6*8)', 16, false);
end

function cfg = decodeZoneStatus(cfg, zoneStatus)
  
  % 1. Alarm1
  if zoneStatus(1)
    cfg.Alarm1 = 'Alarmed';
  else
    cfg.Alarm1 = 'Not alarmed';
  end
  
  % 2. Alarm2
  if zoneStatus(2)
    cfg.Alarm2 = 'Alarmed';
  else
    cfg.Alarm2 = 'Not alarmed';
  end
  
  % 3. Tamper
  cfg.Tampered = logical(zoneStatus(3));
  
  % 4. Low battery
  cfg.LowBattery = logical(zoneStatus(4));
  
  % 5. Supervision reports
  cfg.PeriodicReports = logical(zoneStatus(5));
  
  % 6. Restore reports
  cfg.RestoreReports = logical(zoneStatus(6));
  
  % 7. Trouble
  cfg.Trouble = logical(zoneStatus(7));
  
  % 8. AC fault
  cfg.ACFault = logical(zoneStatus(8));
  
  % 9. Test mode
  cfg.TestMode = logical(zoneStatus(9));
  
  % 10. BatteryDefect
  cfg.BatteryDefect = logical(zoneStatus(10));
end