diff --git a/iotDashboard/forms.py b/iotDashboard/forms.py index 8c09f2e..9648423 100644 --- a/iotDashboard/forms.py +++ b/iotDashboard/forms.py @@ -1,26 +1,14 @@ from django import forms from .models import Device, Sensor, SensorType -class DeviceForm(forms.ModelForm): - # Optionally include sensors as choices in the form if relevant - sensors = forms.ModelMultipleChoiceField( - queryset=Sensor.objects.all(), - required=False, - widget=forms.CheckboxSelectMultiple, - label='Sensors' - ) +class DeviceForm(forms.ModelForm): class Meta: model = Device - fields = ['name', 'ip', 'protocol'] + fields = ['name', 'ip', 'protocol'] # Exclude sensors from the fields def __init__(self, *args, **kwargs): - # Optionally pass initial sensors for editing an existing device - if 'instance' in kwargs: - initial_sensors = kwargs['instance'].sensors.all() if kwargs['instance'] else None - initial = kwargs.get('initial', {}) - initial['sensors'] = initial_sensors - kwargs['initial'] = initial + # No need to handle sensors in the form super(DeviceForm, self).__init__(*args, **kwargs) def save(self, commit=True): @@ -29,7 +17,6 @@ class DeviceForm(forms.ModelForm): if commit: device.save() - self.save_m2m() # Ensure M2M save happens return device class SensorWithTypeForm(forms.ModelForm): @@ -45,7 +32,11 @@ class SensorWithTypeForm(forms.ModelForm): class Meta: model = Sensor - fields = ['device', 'enabled'] + fields = ['enabled'] # Exclude 'device' from the form fields + + def __init__(self, *args, **kwargs): + self.device = kwargs.pop('device', None) # Get the device from kwargs + super(SensorWithTypeForm, self).__init__(*args, **kwargs) def save(self, commit=True): # Create or get the SensorType @@ -65,8 +56,9 @@ class SensorWithTypeForm(forms.ModelForm): # Create Sensor with the SensorType found or created sensor = super(SensorWithTypeForm, self).save(commit=False) sensor.type = sensor_type + sensor.device = self.device # Associate the sensor with the device if commit: sensor.save() - return sensor \ No newline at end of file + return sensor diff --git a/iotDashboard/tasks.py b/iotDashboard/tasks.py index 44e29ab..874451f 100644 --- a/iotDashboard/tasks.py +++ b/iotDashboard/tasks.py @@ -11,6 +11,7 @@ from .models import Device, Sensor, SensorType # Initialize Redis client redis_client = redis.StrictRedis(host='10.10.0.1', port=6379, db=0) + def devices_to_redis(): """Fetch devices and their sensors' topics from Django and store them in Redis.""" devices = Device.objects.all() @@ -26,6 +27,7 @@ def devices_to_redis(): redis_client.set('mqtt_devices', json.dumps(devices_list)) print("Devices with sensors stored in Redis.") + def fetch_data_http(device, sensor): """Fetch data from an HTTP sensor.""" sensor_type_name = sensor.type.name.lower() @@ -47,6 +49,7 @@ def fetch_data_http(device, sensor): print(f"HTTP request failed for {device.name}: {e}") return None + def fetch_data_mqtt(device, sensor): """Fetch data from Redis for a specific MQTT device and sensor.""" # Get the data for the specific device from Redis @@ -70,9 +73,10 @@ def fetch_data_mqtt(device, sensor): def is_recent_data(timestamp): - """Check if data is within a 2-minute freshness window.""" + """Check if data is within a 1-minute freshness window.""" data_time = datetime.datetime.fromisoformat(timestamp) - return data_time > datetime.datetime.utcnow() - datetime.timedelta(minutes=2) + return data_time > datetime.datetime.utcnow() - datetime.timedelta(minutes=1) + def insert_data(data, sensor_type): """Insert parsed data into the PostgreSQL database.""" @@ -105,7 +109,8 @@ def insert_data(data, sensor_type): except Exception as e: print(f"Failed to insert data: {e}") -@periodi c_task(crontab(minute='*/1')) + +@periodic_task(crontab(minute='*/1')) def fetch_data_from_all_devices(): """Fetch and insert data for all devices based on their protocol.""" devices = Device.objects.all() @@ -123,6 +128,7 @@ def fetch_data_from_all_devices(): else: print(f"No recent or valid data for {device.name}. Skipping.") + @periodic_task(crontab(minute='*/5')) def last_5_minutes(): """Fetch the last 5 readings from TimescaleDB and store them in Redis.""" @@ -151,5 +157,6 @@ def last_5_minutes(): except Exception as e: print(f"Error fetching or storing the last 5 readings: {e}") + # Initialize device data in Redis devices_to_redis() diff --git a/iotDashboard/templates/chart.html b/iotDashboard/templates/chart.html index 2079096..04a260e 100644 --- a/iotDashboard/templates/chart.html +++ b/iotDashboard/templates/chart.html @@ -3,142 +3,280 @@
-