function [rssi_out_dBm] = max8_rssi_est(rssi_in_dBm, s, RSSI_SMOOTHING_COEF)
%-------------------------------------------------------------------------------
% $Id: max8_rssi_est.m,v 1.3 2023/07/26 21:49:41 ddelore Exp $
%
%  David S. De Lorenzo
%  12 December 2019
%
%  Signal power estimate & low-pass filter
%
%-------------------------------------------------------------------------------

% Calculate the signal variance
%   --> Assumes zero-mean signal -- i.e., no DC bias
signal_variance = 1/length(s) * sum(s .* conj(s));

% Calculate the signal power
%
%   Power = V^2 / R
%
%         convert from   squared    50 ohm     Watts
%          mW to dBm     voltage   impedance   to mW
%           ___|___         |           |        |
%          /       \        v           v        v
rssi_dBm = 10*log10((signal_variance / 50.0) * 1000);

% Check if the input value is "invalid"
if isempty(rssi_in_dBm) || ~isfinite(rssi_in_dBm)
    % Just output the new RSSI reading
    rssi_out_dBm = rssi_dBm;
else
    % Apply a low-pass filter to this RSSI reading
    rssi_out_dBm = (1-RSSI_SMOOTHING_COEF) * rssi_in_dBm ...
                 +   RSSI_SMOOTHING_COEF   *  rssi_dBm;
end

return
%===============================================================================