def __init__(self): self.config = Config() self.config_data = self.config.get_config_data() try: self.dht22 = DHT22(int(self.config_data['DHT22']['pin'])) except Exception as e: self.log.write_log("Failed to initialize DHT22: {}".format(e)) try: self.scale = Scale() except Exception as e: self.log.write_log("Failed to initialize scale: {}".format(e)) try: self.DS18B20 = DS18B20() except Exception as e: self.log.write_log("Failed to initialize DS18B20: {}".format(e)) self.api = SamsApi() self.log = Log() self.median_interval = int(self.config_data['INTERVAL']['median']) self.wait_time = int(self.config_data['INTERVAL']['wait_time_seconds']) self.dataset = [] self.temp = [] self.hum = [] self.weight = [] self.ds_temp = [] self.median_temp = 0 self.median_hum = 0 self.median_weight = 0 self.median_ds_temp = 0 self.duration = int(self.config_data['AUDIO']['duration'])
class App: def __init__(self): # CONFIG DATA self.config = Config() self.config_data = self.config.get_config_data() # RELAY PIN self.relay_pin = int(self.config_data['DEFAULT']['relay_pin']) # DHT 22 PIN self.dht22_pin = int(self.config_data['DEFAULT']['dht22_pin']) # INIT RELAY self.relay = Device(self.relay_pin, "relay") # INIT DHT22 SENSOR self.dht22 = DHT22(self.dht22_pin) # INIT SCALE self.scale = Scale() def calibrate_scale( self): # QUICK AND EASY CALIBRATE FUNCTION FOR THE SCALE input("Remove any items from scale and press Enter...") self.scale.setup() input( "Please place an item of known weight on the scale and press Enter..." ) weight = input("Please enter the item's weight in grams: ") self.scale.calibrate(int(weight)) print( "The scale is now calibrated and the offset ist saved in the config.ini" ) # GET SCALE DATA (QUICK AND EASY!) print("Weight: {}g".format(self.scale.get_data())) def start(self): temperature, humidity = self.dht22.get_data() print("Temperature: {}".format(temperature)) print("Humidity: {}".format(humidity)) if temperature > 22: print("Relay is on!") self.relay.on() else: print("Relay is off!") self.relay.off()
def __init__(self): # CONFIG DATA self.config = Config() self.config_data = self.config.get_config_data() # RELAY PIN self.relay_pin = int(self.config_data['DEFAULT']['relay_pin']) # DHT 22 PIN self.dht22_pin = int(self.config_data['DEFAULT']['dht22_pin']) # INIT RELAY self.relay = Device(self.relay_pin, "relay") # INIT DHT22 SENSOR self.dht22 = DHT22(self.dht22_pin) # INIT SCALE self.scale = Scale()
def __init__(self): self.config = LocalConfig() self.user_credentials = UserConfig() self.config.get_config_data() try: self.dht22 = DHT22(int(self.config.dht22_pin)) except Exception as e: send_log("Failed to initialize DHT22: {}".format(e), "error") try: self.scale = Scale() except Exception as e: send_log("Failed to initialize scale: {}".format(e), "error") try: self.DS18B20 = DS18B20() except Exception as e: send_log("Failed to initialize DS18B20: {}".format(e), "error") self.last_measured_weight = 0 self.median_weight = 0
def __init__(self): self.config = LocalConfig() self.config.get_config_data() self.sensors = self.config.data self.error = ErrorHandler() # deprecated if self.config.data["dht22"]: from sensorlib.dht22 import DHT22 self.dht22 = DHT22() if self.config.data["ds18b20"]: from sensorlib.ds1820 import DS18B20 self.temp_sensor = DS18B20() if self.config.data["fft"] or self.config.data["wav"]: from sensorlib.microphone import Microphone self.microphone = Microphone() if self.config.data["scale"]: from sensorlib.scale import Scale self.scale = Scale() if self.config.data["aht20"]: from sensorlib.aht20 import AHT20 self.aht20 = AHT20() self.data = dict() self.timestamp = ""
class Dataset: def __init__(self): self.config = Config() self.config_data = self.config.get_config_data() try: self.dht22 = DHT22(int(self.config_data['DHT22']['pin'])) except Exception as e: self.log.write_log("Failed to initialize DHT22: {}".format(e)) try: self.scale = Scale() except Exception as e: self.log.write_log("Failed to initialize scale: {}".format(e)) try: self.DS18B20 = DS18B20() except Exception as e: self.log.write_log("Failed to initialize DS18B20: {}".format(e)) self.api = SamsApi() self.log = Log() self.median_interval = int(self.config_data['INTERVAL']['median']) self.wait_time = int(self.config_data['INTERVAL']['wait_time_seconds']) self.dataset = [] self.temp = [] self.hum = [] self.weight = [] self.ds_temp = [] self.median_temp = 0 self.median_hum = 0 self.median_weight = 0 self.median_ds_temp = 0 self.duration = int(self.config_data['AUDIO']['duration']) @staticmethod def get_time(): now = datetime.datetime.utcnow() return now.strftime('%Y-%m-%dT%H:%M:%S') + now.strftime( '.%f')[:0] + 'Z' def error(self, device, error): if not device == "audio": self.dataset.append({ "sourceId": "{0}-{1}".format(device, self.api.client_id), "value": [ { "ts": self.get_time(), "value": 0 }, ] }) else: self.dataset.append({ "sourceId": "{0}-{1}".format("audio", self.api.client_id), "value": [ { "ts": self.get_time(), "value": [0, 0] }, ] }) self.log.write_log( "something went wrong by collecting the {0} dataset! Error: {1}". format(device, error)) def get_fft_data(self): n_window = pow(2, 12) n_overlap = n_window / 2 n_fft = n_window fs = 16000 try: audiodata = sd.rec(self.duration * fs, samplerate=fs, channels=1, dtype='float64') sd.wait() data = audiodata.transpose() [F, pxx] = scipy.signal.welch(data, fs=fs, window='hanning', nperseg=n_window, noverlap=n_overlap, nfft=n_fft, detrend=False, return_onesided=True, scaling='density') temp_data = np.array(pxx).astype(float) data = temp_data.tolist() self.dataset.append({ "sourceId": "audio-{0}".format(self.api.client_id), "values": [ { "ts": self.get_time(), "values": data[0] }, ] }) except Exception as e: self.error("audio", e) return True def get_ds18b20_data(self): sensor_counter = self.DS18B20.device_count() try: if sensor_counter != 0: for x in range(sensor_counter): self.median_ds_temp = [] for i in range(self.median_interval): value = self.DS18B20.tempC(x) if value == 998 or value == 85.0: self.log.write_log( "DS18B20 does not work properly...") else: self.ds_temp.append(self.DS18B20.tempC(x)) time.sleep(self.wait_time) if len(self.ds_temp) != 0: self.median_ds_temp = median(self.ds_temp) del self.ds_temp[:] self.dataset.append({ "sourceId": "dsb18b20-{0}-{1}".format(x, self.api.client_id), "values": [ { "ts": self.get_time(), "value": float(self.median_ds_temp) }, ] }) self.median_ds_temp = "" except Exception as e: self.error("ds18b20", e) def get_dht22_data(self): try: for i in range(self.median_interval): dhtdata = self.dht22.get_data() self.temp.append(dhtdata['temp']) self.hum.append(dhtdata['hum']) time.sleep(self.wait_time) self.median_temp = median(self.temp) self.median_hum = median(self.hum) self.dataset.append({ "sourceId": "dht22-temperature-{0}".format(self.api.client_id), "values": [ { "ts": self.get_time(), "value": float(self.median_temp) }, ] }) self.dataset.append({ "sourceId": "dht22-humidity-{0}".format(self.api.client_id), "values": [ { "ts": self.get_time(), "value": float(self.median_hum) }, ] }) del self.temp[:] del self.hum[:] except Exception as e: self.error("dht22", e) def get_scale_data(self): try: for i in range(self.median_interval): self.weight.append(self.scale.get_data()) print(self.weight) time.sleep(self.wait_time) self.median_weight = median(self.weight) del self.weight[:] self.dataset.append({ "sourceId": "scale-{0}".format(self.api.client_id), "values": [{ "ts": self.get_time(), "value": float(self.median_weight) }] }) except Exception as e: self.error("scale", e) def get_dataset(self): try: self.dataset[:] = [] # empty the dataset before take new data self.get_fft_data() self.get_scale_data() self.get_dht22_data() self.get_ds18b20_data() return self.dataset except Exception as e: self.log.write_log("Dataset error: {}".format(e)) return False
def prepare_usb_drive(self): is_config = False is_scale_reset = False is_wittypi_script = False is_tara = False is_update = False is_wpa = False try: # init if self.config.settings["device_id"] == "init": dirs = os.listdir(mapping.usb_path) for stick_dir in dirs: if "." not in stick_dir: self.config.set_config_data("SETTINGS", "device_id", stick_dir) self.config.get_config_data() # create device dir on usb stick if not os.path.exists(self.config.usb_path): os.mkdir(self.config.usb_path) os.system( f"touch {os.path.join(self.config.usb_path, 'error.log')}") self.info_helper.calc(self.config.usb_path) # create fft dir on usb stick if not os.path.exists(os.path.join(self.config.usb_path, "fft")): os.mkdir(os.path.join(self.config.usb_path, "fft")) # create wav dir on usb stick if not os.path.exists(os.path.join(self.config.usb_path, "wav")): os.mkdir(os.path.join(self.config.usb_path, "wav")) # list usb files device_stick_files = os.listdir(self.config.usb_path) for stick_files in device_stick_files: if "conf.ini" in stick_files: is_config = True if "schedule.wpi" in stick_files: is_wittypi_script = True if "tara" in stick_files: is_tara = True if "reset" in stick_files: is_scale_reset = True if "update.sh" in stick_files: is_update = True if "wpa_supplicant.conf" in stick_files: is_wpa = True if is_update: self.update_system() if is_config: self.update_config() if is_wittypi_script: shutil.copy(os.path.join(self.config.usb_path, "schedule.wpi"), mapping.witty_pi) call("/home/pi/wittypi/syncTime.sh") call("/home/pi/wittypi/runScript.sh") if is_tara: from sensorlib.scale import Scale scale = Scale() scale.tare() os.system(f"sudo rm {self.config.usb_path}/tara") print("restart") time.sleep(5) os.system("sudo reboot") if is_scale_reset: self.reset_scale() if is_wpa: shutil.copy( os.path.join(self.config.usb_path, "wpa_supplicant.conf"), mapping.wpa_path) os.system( f"rm {os.path.join(self.config.usb_path, 'wpa_supplicant.conf')}" ) time.sleep(5) os.system("sudo reboot") except Exception as e: print(e)
#!/usr/bin/python3 from main.application import Application from config.config import Config from sensorlib.scale import Scale config = Config() config_data = config.get_config_data() is_calibrated = config_data['SCALE'].getboolean("calibrated") print(is_calibrated) app = Application() scale = Scale() if __name__ == '__main__': if is_calibrated: app.start() else: scale.calibrate(5000)
from flask import Flask, render_template, request from main.configuration.user_config import UserConfig from main.configuration.app_config import ApplicationConfig from sensorlib.scale import Scale from main.helper.wifi_helper import WifiHelper from main.helper.test_helper import AppTest from main.helper.time_helper import set_timezone from main.helper.error_helper import ErrorHelper import os import time app = Flask(__name__) user_config = UserConfig() app_config = ApplicationConfig() scale = Scale() wifi = WifiHelper() testing = AppTest() error_helper = ErrorHelper() @app.route('/') def start(): user = user_config.get_user_data() app_config.local_config.get_config_data() is_start = app_config.local_config.start is_scale = app_config.local_config.is_scale return render_template("start.html", title="start", user_data=user, calibrated=app_config.local_config.scale_calibrated, is_start=is_start,
class Dataset: def __init__(self): self.config = LocalConfig() self.config.get_config_data() self.sensors = self.config.data self.error = ErrorHandler() # deprecated if self.config.data["dht22"]: from sensorlib.dht22 import DHT22 self.dht22 = DHT22() if self.config.data["ds18b20"]: from sensorlib.ds1820 import DS18B20 self.temp_sensor = DS18B20() if self.config.data["fft"] or self.config.data["wav"]: from sensorlib.microphone import Microphone self.microphone = Microphone() if self.config.data["scale"]: from sensorlib.scale import Scale self.scale = Scale() if self.config.data["aht20"]: from sensorlib.aht20 import AHT20 self.aht20 = AHT20() self.data = dict() self.timestamp = "" def get_data(self, sensor): try: self.config.get_config_data() return getattr(self, 'get_' + sensor)() except Exception as e: self.error.log.exception(e) def get_ds18b20(self): try: sensor_counter = self.temp_sensor.device_count() ds_temp = [] if sensor_counter != 0 and sensor_counter != "NoneType": for x in range(sensor_counter): for i in range(int(self.config.settings["median"])): value = self.temp_sensor.tempC(x) if value == 998 or value == 85.0: raise SensorDataError("DS18B20") else: ds_temp.append(self.temp_sensor.tempC(x)) time.sleep(1) if range(len(ds_temp)) != 0 or ds_temp != "nan": median_ds_temp = median(ds_temp) self.data[f"ds18b20-{x}"] = median_ds_temp return True else: raise SensorDataError("DS18B20") except Exception as e: print(e) self.error.log.exception(e) return False def get_aht20(self): try: aht_data = self.aht20.get_data() if aht_data["status"]: self.data["temp"] = aht_data["temp"] self.data["hum"] = aht_data["hum"] return True else: raise SensorDataError("AHT20") except Exception as e: self.error.log.exception(e) def get_dht22(self): try: dht_data = self.dht22.get_data() if dht_data: self.data["temp"] = dht_data["temp"] self.data["hum"] = dht_data["hum"] return True else: raise SensorDataError("DHT22") except Exception as e: self.error.log.exception(e) def get_scale(self): try: weight = self.scale.get_data() if weight: self.data["weight"] = weight return True else: raise SensorDataError("SCALE") except Exception as e: self.error.log.exception(e) def get_fft(self): try: fft_data = self.microphone.get_fft_data() if fft_data["status"]: dir_name = get_dir_time() dir_path = f"{self.config.usb_path}/fft/{dir_name}" file_name = self.timestamp file_path = f"{dir_path}/{file_name}.json" if not os.path.exists(dir_path): os.mkdir(dir_path) os.system(f"sudo touch {file_path}") db = TinyDB(file_path) db.insert({ "source": "microphone", "time": get_time(), "data": str(fft_data["data"]), }) return True else: raise SensorDataError("MICROPHONE") except Exception as e: print(e) self.error.log.exception(e) def get_wav(self): try: dir_name = get_dir_time() dir_path = f"{self.config.usb_path}/wav/{dir_name}" filename = self.timestamp filepath = f"{dir_path}/{filename}.wav" if not os.path.exists(dir_path): os.mkdir(dir_path) if self.microphone.write_wav_data(filepath): return True else: raise SensorDataError("MICROPHONE") except Exception as e: self.error.log.exception(e) return False
from flask import Flask, render_template, jsonify, request from sensorlib.scale import Scale from helper.logging_activity import Log from helper.api_data import ApiData log = Log() try: scale = Scale() # Scale for /api data except Exception as e: log.write_log("something went wrong with the scale!: {}".format(e)) app = Flask(__name__) @app.route('/') def start(): cal = scale.calibrated() error = scale.has_error() return render_template('start.html', title="start", calibrated=cal, error=error) @app.route('/log') # reading log file def read_log(): file = open("/var/www/upload/log.txt", "r") f = file.readlines() print(f) return render_template('log.html', title="debug mode", log_content=f) @app.route('/calibrate') # start calibrate the scale def calibrate():
def prepare_usb_drive(self): is_config = False is_scale_reset = False is_wittypi_script = False is_tara = False is_update = False is_wpa = False is_test = False is_sync_time = False try: # init if self.config.settings["device_id"] == "init": dirs = os.listdir(mapping.usb_path) for stick_dir in dirs: if "." not in stick_dir and "System" not in stick_dir: self.config.set_config_data("SETTINGS", "device_id", stick_dir) self.config.get_config_data() # create device dir on usb stick if not os.path.exists(self.config.usb_path): os.mkdir(self.config.usb_path) os.system( f"touch {os.path.join(self.config.usb_path, 'error.log')}") # calc information and write to stick self.info_helper.calc(self.config.usb_path) # create fft dir on usb stick if not os.path.exists(os.path.join(self.config.usb_path, "fft")): os.mkdir(os.path.join(self.config.usb_path, "fft")) # create wav dir on usb stick if not os.path.exists(os.path.join(self.config.usb_path, "wav")): os.mkdir(os.path.join(self.config.usb_path, "wav")) # list usb files device_stick_files = os.listdir(self.config.usb_path) for stick_files in device_stick_files: if "test" in stick_files: is_test = True if "sync" in stick_files: is_sync_time = True if "conf.ini" in stick_files: is_config = True if "schedule.wpi" in stick_files: is_wittypi_script = True if "tara" in stick_files: is_tara = True if "reset" in stick_files: is_scale_reset = True if "update.sh" in stick_files: is_update = True if "wpa_supplicant.conf" in stick_files: is_wpa = True if is_update: self.update_system() if is_sync_time: try: call("/home/pi/wittypi/syncTime.sh") os.system( f"sudo rm {os.path.join(self.config.usb_path, 'sync')}" ) except Exception as e: self.error.log.exception(e) if is_test: from sensorlib.rgb import RGB os.system( f"sudo rm {os.path.join(self.config.usb_path, 'test')}") led = RGB() if not self.test_system(): led.red() time.sleep(3600) else: led.blink("green", 5, 1) os.system("sudo reboot") if is_config: self.update_config() if is_wittypi_script: # todo wittipy log wird voll shutil.copy(os.path.join(self.config.usb_path, "schedule.wpi"), mapping.witty_pi) os.system( f"sudo rm {os.path.join(self.config.usb_path, 'schedule.wpi')}" ) call("/home/pi/wittypi/runScript.sh") if is_tara: from sensorlib.scale import Scale scale = Scale() scale.tare() os.system(f"sudo rm {self.config.usb_path}/tara") time.sleep(5) os.system("sudo reboot") if is_scale_reset: self.reset_scale() if is_wpa: shutil.copy( os.path.join(self.config.usb_path, "wpa_supplicant.conf"), mapping.wpa_path) os.system( f"rm {os.path.join(self.config.usb_path, 'wpa_supplicant.conf')}" ) time.sleep(5) os.system("sudo reboot") except Exception as e: print(e)
class Dataset: def __init__(self): self.config = LocalConfig() self.user_credentials = UserConfig() self.config.get_config_data() try: self.dht22 = DHT22(int(self.config.dht22_pin)) except Exception as e: send_log("Failed to initialize DHT22: {}".format(e), "error") try: self.scale = Scale() except Exception as e: send_log("Failed to initialize scale: {}".format(e), "error") try: self.DS18B20 = DS18B20() except Exception as e: send_log("Failed to initialize DS18B20: {}".format(e), "error") self.last_measured_weight = 0 self.median_weight = 0 def get_data(self, sensor_type): dataset = False if sensor_type == "ds18b20": dataset = self.get_ds18b20_data() elif sensor_type == "dht22": dataset = self.get_dht22_data() elif sensor_type == "microphone": dataset = self.get_microphone_data() elif sensor_type == "scale": dataset = self.get_scale_data() return dataset def get_microphone_data(self): self.config.get_config_data() n_window = pow(2, 12) n_overlap = n_window / 2 n_fft = n_window fs = int(self.config.audio_fs) try: audiodata = sd.rec(int(self.config.audio_duration) * fs, samplerate=fs, channels=1, dtype='float64') sd.wait() data = audiodata.transpose() [F, pxx] = scipy.signal.welch(data, fs=fs, window='hanning', nperseg=n_window, noverlap=n_overlap, nfft=n_fft, detrend=False, return_onesided=True, scaling='density') temp_data = np.array(pxx).astype(float) data = temp_data.tolist() dataset = [[{ "sourceId": "audio-{0}".format(self.user_credentials.client_id), "values": [ { "ts": get_time(is_dataset=True), "values": data[0] }, ] }]] if median(data[0]) == 0: # no microphone available return False else: return dataset except Exception: return False def get_ds18b20_data(self): self.config.get_config_data() try: sensor_counter = self.DS18B20.device_count() dataset = [] ds_temp = [] if sensor_counter != 0 and sensor_counter != "NoneType": for x in range(sensor_counter): for i in range(int(self.config.interval_median)): value = self.DS18B20.tempC(x) if value == 998 or value == 85.0: return False else: ds_temp.append(self.DS18B20.tempC(x)) time.sleep(3) if range(len(ds_temp)) != 0 or ds_temp != "nan": median_ds_temp = median(ds_temp) dataset.append([{ "sourceId": "ds18b20-{0}-{1}".format( x, self.user_credentials.client_id), "values": [ { "ts": get_time(is_dataset=True), "value": float(median_ds_temp) }, ] }]) return dataset else: return False except Exception: return False def get_dht22_data(self): self.config.get_config_data() try: temp = [] hum = [] dataset = [] for i in range(int(self.config.interval_median)): dhtdata = self.dht22.get_data() temp.append(dhtdata['temp']) hum.append(dhtdata['hum']) time.sleep(1) median_temp = median(temp) median_hum = median(hum) dataset.append([{ "sourceId": "dht22-temperature-{0}".format( self.user_credentials.client_id), "values": [ { "ts": get_time(is_dataset=True), "value": float(median_temp) }, ] }]) dataset.append([{ "sourceId": "dht22-humidity-{0}".format(self.user_credentials.client_id), "values": [ { "ts": get_time(is_dataset=True), "value": float(median_hum) }, ] }]) return dataset except Exception: return False def get_scale_data(self): self.config.get_config_data() weight = [] control_measure = 0 try: while control_measure < 2: control_measure += 1 for i in range(int(self.config.interval_median)): weight.append(self.scale.get_data()) self.median_weight = median(weight) if self.last_measured_weight == self.median_weight: control_measure += 1 self.last_measured_weight = self.median_weight dataset = [[{ "sourceId": "scale-{0}".format(self.user_credentials.client_id), "values": [{ "ts": get_time(is_dataset=True), "value": self.median_weight }] }]] return dataset except Exception: return False