text
stringlengths
1
93.6k
tls_context = mqtt.ssl.create_default_context()
mqtt_client.tls_set_context(tls_context)
if os.getenv('MQTT_USERNAME', None) and os.getenv('MQTT_PASSWORD', None):
mqtt_client.username_pw_set(os.getenv('MQTT_USERNAME'), os.getenv('MQTT_PASSWORD'))
try:
mqtt_client.connect(
os.getenv('MQTT_HOST'),
int(os.getenv('MQTT_PORT')),
keepalive=int(os.getenv('MQTT_KEEPALIVE', 60)),
)
except Exception as e:
logging.error(f"Failed to connect to MQTT broker: {e}")
exit(1)
# Configure the Processor and the Exporter
processor = MessageProcessor(registry, connection_pool)
mqtt_client.loop_forever()
# <FILESEP>
# Copyright (c) 2020. Jose M. Requena-Plens
"""
Octave-Band and Fractional Octave-Band filter.
"""
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
# Public methods
__all__ = ['octavefilter', 'getansifrequencies', 'normalizedfreq']
def octavefilter(x, fs, fraction=1, order=6, limits=None, show=0, sigbands =0):
"""
Filter a signal with octave or fractional octave filter bank. This
method uses a Butterworth filter with Second-Order Sections
coefficients. To obtain the correct coefficients, a subsampling is
applied to the signal in each filtered band.
:param x: Signal
:param fs: Sample rate
:param fraction: Bandwidth 'b'. Examples: 1/3-octave b=3, 1-octave b=1,
2/3-octave b = 3/2. [Optional] Default: 1.
:param order: Order of Butterworth filter. [Optional] Default: 6.
:param limits: Minimum and maximum limit frequencies. [Optional] Default
[12,20000]
:param show: Boolean for plot o not the filter response.
:param sigbands: Boolean to also return the signal in the time domain
divided into bands. A list with as many arrays as there are frequency bands.
:returns: Sound Pressure Level and Frequency array
"""
if limits is None:
limits = [12, 20000]
# List type for signal var
x = _typesignal(x)
# Generate frequency array
freq, freq_d, freq_u = _genfreqs(limits, fraction, fs)
# Calculate the downsampling factor (array of integers with size [freq])
factor = _downsamplingfactor(freq_u, fs)
# Get SOS filter coefficients (3D - matrix with size: [freq,order,6])
sos = _buttersosfilter(freq, freq_d, freq_u, fs, order, factor, show)
if sigbands:
# Create array with SPL for each frequency band
spl = np.zeros([len(freq)])
xb = []
for idx in range(len(freq)):
sd = signal.resample(x, round(len(x) / factor[idx]))
y = signal.sosfilt(sos[idx], sd)
spl[idx] = 20 * np.log10(np.std(y) / 2e-5)
xb.append(signal.resample_poly(y,factor[idx],1))
return spl.tolist(), freq, xb
else:
# Create array with SPL for each frequency band
spl = np.zeros([len(freq)])
for idx in range(len(freq)):
sd = signal.resample(x, round(len(x) / factor[idx]))
y = signal.sosfilt(sos[idx], sd)
spl[idx] = 20 * np.log10(np.std(y) / 2e-5)
return spl.tolist(), freq
def _typesignal(x):
if type(x) is list:
return x
elif type(x) is np.ndarray:
return x.tolist()
elif type(x) is tuple:
return list(x)
def _buttersosfilter(freq, freq_d, freq_u, fs, order, factor, show=0):