def __init__(self): # BME280 temperature/pressure/humidity sensor self.bme280 = BME280() # Light sensor self.ltr559 = LTR559() self.noise = Noise() self.cpu_temps = None self.factor = 2.25
def __init__(self, soundLevelToReach, interval, frequency_ranges, onSoundEventCallback): self.soundLevelToReach = soundLevelToReach self.interval = interval self.onSoundEvent = onSoundEventCallback self.frequency_ranges = frequency_ranges self.noise = Noise() # init and start thread: Thread.__init__(self) self.daemon = True self.start()
def test_noise_get_amplitudes_at_frequency_ranges(sounddevice, numpy): from enviroplus.noise import Noise noise = Noise(sample_rate=16000, duration=0.1) noise.get_amplitudes_at_frequency_ranges([(100, 500), (501, 1000)]) sounddevice.rec.assert_called_with(0.1 * 16000, samplerate=16000, blocking=True, channels=1, dtype='float64')
class SoundDetector(Thread): def __init__(self, soundLevelToReach, interval, frequency_ranges, onSoundEventCallback): self.soundLevelToReach = soundLevelToReach self.interval = interval self.onSoundEvent = onSoundEventCallback self.frequency_ranges = frequency_ranges self.noise = Noise() # init and start thread: Thread.__init__(self) self.daemon = True self.start() def get_noise(self, frequency_ranges): amps = self.noise.get_amplitudes_at_frequency_ranges(frequency_ranges) return amps def is_shouting(self, amps): for i in range(len(amps)): if amps[i] > self.soundLevelToReach: return amps[i] def run(self): while True: amps = self.get_noise(self.frequency_ranges) reachedValue = self.is_shouting(amps) if reachedValue and self.onSoundEvent: self.onSoundEvent(amps, reachedValue) time.sleep(self.interval)
def test_noise_get_noise_profile(sounddevice, numpy): from enviroplus.noise import Noise numpy.mean.return_value = 10.0 noise = Noise(sample_rate=16000, duration=0.1) amp_low, amp_mid, amp_high, amp_total = noise.get_noise_profile( noise_floor=100, low=0.12, mid=0.36, high=None) sounddevice.rec.assert_called_with(0.1 * 16000, samplerate=16000, blocking=True, channels=1, dtype='float64') assert amp_total == 10.0
class Sensors: def __init__(self): # BME280 temperature/pressure/humidity sensor self.bme280 = BME280() # Light sensor self.ltr559 = LTR559() self.noise = Noise() self.cpu_temps = None self.factor = 2.25 # Get the temperature of the CPU for compensation def get_cpu_temperature(self): process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE, universal_newlines=True) output, _error = process.communicate() return float(output[output.index('=') + 1:output.rindex("'")]) def get_temperature(self): return self.bme280.get_temperature() def get_correct_temperature(self): if self.cpu_temps is None: self.cpu_temps = [self.get_cpu_temperature()] * 5 cpu_temp = self.get_cpu_temperature() # Smooth out with some averaging to decrease jitter self.cpu_temps = self.cpu_temps[1:] + [cpu_temp] avg_cpu_temp = sum(self.cpu_temps) / float(len(self.cpu_temps)) raw_temp = self.get_temperature() raw_data = raw_temp - ((avg_cpu_temp - raw_temp) / self.factor) return raw_data def get_pressure(self): return self.bme280.get_pressure() def get_humidity(self): return self.bme280.get_humidity() def get_correct_humidity(self): dewpoint = self.get_temperature() - ((100 - self.get_humidity()) / 5) corr_humidity = 100 - (5 * (self.get_correct_temperature() - dewpoint)) return min(100, corr_humidity) def get_lux(self): return self.ltr559.get_lux() def get_proximity(self): return self.ltr559.get_proximity() def get_noise_amp(self): amps = self.noise.get_amplitudes_at_frequency_ranges([(100, 200), (500, 600), (1000, 1200), (2000, 3000)]) amps = [n * 32 for n in amps] return amps
def read_values(): values = {} cpu_temp = get_cpu_temperature() raw_temp = bme280.get_temperature() comp_temp = raw_temp - ((cpu_temp - raw_temp) / comp_factor) lux = ltr559.get_lux() proximity = ltr559.get_proximity() readings = gas.read_all() oxidising = readings.oxidising nh3 = readings.nh3 reducing = readings.reducing adc = readings.adc noise = Noise() amps = noise.get_amplitudes_at_frequency_ranges([(100, 200), (500, 600), (1000, 1200)]) amps = [n * 32 for n in amps] values["temperature"] = "{:.2f}".format(comp_temp) values["cpu_temp"] = "{:.2f}".format(cpu_temp) values["pressure"] = "{:.2f}".format(bme280.get_pressure() * 100) values["humidity"] = "{:.2f}".format(bme280.get_humidity()) values["lux"] = "{:05.02f}".format(lux) values["proximity"] = "{:05.02f}".format(proximity) values["nh3"] = "{:05.02f}".format(nh3) values["oxidising"] = "{:05.02f}".format(oxidising) values["reducing"] = "{:05.02f}".format(reducing) values["adc"] = "{:05.02f}".format(adc) values["amp_100_200"] = "{:05.02f}".format(amps[0]) values["amp_500_600"] = "{:05.02f}".format(amps[1]) values["amp_1000_1200"] = "{:05.02f}".format(amps[2]) try: pm_values = pms5003.read() values["P2"] = str(pm_values.pm_ug_per_m3(2.5)) values["P1"] = str(pm_values.pm_ug_per_m3(10)) except ReadTimeoutError: pms5003.reset() pm_values = pms5003.read() values["P2"] = str(pm_values.pm_ug_per_m3(2.5)) values["P1"] = str(pm_values.pm_ug_per_m3(10)) return values
def test_get_amplitude_at_frequency_range(sounddevice, numpy): from enviroplus.noise import Noise noise = Noise(sample_rate=16000, duration=0.1) noise.get_amplitude_at_frequency_range(0, 8000) with pytest.raises(ValueError): noise.get_amplitude_at_frequency_range(0, 16000)
# Set up BME280 weather sensor bus = SMBus(1) bme280 = BME280(i2c_dev=bus) min_temp = None max_temp = None factor = 1.70 cpu_temps = [get_cpu_temperature()] * 5 # Set up light sensor ltr559 = LTR559() # Set up microphone noise = Noise() # Pressure variables pressure_vals = [] time_vals = [] num_vals = 1000 interval = 1 trend = "-" # Keep track of time elapsed start_time = time.time() while True: try: path = os.path.dirname(os.path.realpath(__file__))
ltr559 = LTR559() except ImportError: import ltr559 from bme280 import BME280 from enviroplus import gas from enviroplus.noise import Noise from subprocess import PIPE, Popen from fonts.ttf import RobotoMedium as UserFont from threading import Thread, Event # BME280 temperature/pressure/humidity sensor bme280 = BME280() # MEMS microphone noise = Noise() # initialise audio audio = pyaudio.PyAudio() # This is the url that sensor data will be posted to sensorsurl = "http://192.168.0.156:5000/sensordata" #Full-scale dB range of microphone WAIT_TIME = 10 stop_threads = False # function to convert from PCM to dbSPL def PCM_to_dbSPL(pcm): FSdbSPL = 120
def test_noise_setup(sounddevice, numpy): from enviroplus.noise import Noise noise = Noise(sample_rate=16000, duration=0.1) del noise
import os import time import rrdtool from enviroplus.noise import Noise noise = Noise() dir_path = os.path.dirname(os.path.realpath(__file__)) starttime = time.time() # TODO XXX this data doesn't look great as 4 line plots overlapping, make better # possibly use the other amplitude @ frequency API and use several RRDs # rrdtool can only support 1 Hz data, so if this isn't the right tool for this particular job... # run roughly 1 Hz every ~minute scheduled by cron while time.time() - starttime < 55: amp = noise.get_noise_profile() print(amp) rrdtool.update(dir_path + "/rrd/noise.rrd", "N:{}:{}:{}:{}".format(*amp)) time.sleep(1)
oxidising = Gauge("oxidising", "oxidising gases in Ohms") ammonia = Gauge("ammonia", "ammonia in Ohms") def update_gas(): mixture = gas.read_all() reducing.set(mixture.reducing) oxidising.set(mixture.oxidising) ammonia.set(mixture.nh3) # Noise # # Noise is measured in different frequency groups. The default uses 3: # low, mid and high, and a total which is actually the average of all 3. noise = Gauge("noise", "noise in amps", ["level"]) noise_measure = Noise() # This takes a little longer --- by default listens for 0.5 seconds def update_noise(): amp_low, amp_mid, amp_high, amp_total = noise_measure.get_noise_profile() noise.labels(level="low").set(amp_low) noise.labels(level="mid").set(amp_mid) noise.labels(level="high").set(amp_high) noise.labels(level="total").set(amp_total) # Particulates # # This sensor also allows for measuring a variant "atmospheric environment". # It's not clear to me what this means, so I'm sticking to the code as # used in the examples in the module Github repository. pms5003_measure = PMS5003() particulates = Gauge("particulates", "particulates in µg/m³", ["diameter"])
import ST7735 from PIL import Image, ImageDraw from enviroplus.noise import Noise print("""noise-profile.py - Get a simple noise profile. This example grabs a basic 3-bin noise profile of low, medium and high frequency noise, plotting the noise characteristics as coloured bars. Press Ctrl+C to exit! """) noise = Noise() disp = ST7735.ST7735(port=0, cs=ST7735.BG_SPI_CS_FRONT, dc=9, backlight=12, rotation=90) disp.begin() img = Image.new('RGB', (disp.width, disp.height), color=(0, 0, 0)) draw = ImageDraw.Draw(img) while True: low, mid, high, amp = noise.get_noise_profile() low *= 128 mid *= 128 high *= 128 amp *= 64