Сравнение данных датчиков и отправка предупреждения на веб-сайт Django при превышении порогового значения

Я смог считать данные с датчика расхода в терминале python, и теперь мне нужно сравнить их с пороговым значением и, если оно ниже, отправить предупреждение на созданный мной сайт Django. Может ли кто-нибудь помочь с этим? Спасибо

Кажется очень несправедливым, что они ожидают, что вы создадите все это, а вы никогда не работали с Django или Python... Когда это должно произойти? Если вам нужна помощь, создайте проект на GitHub, пригласите меня, и я смогу написать немного кода, чтобы помочь вам.

Если нет, то вот что у меня получилось. Я просто предоставил Обзор последнего часа, с некоторыми основными фильтрами и подсчетами, которые потребуют обновления для получения подсчета ошибок.

<

Для получения данных из python в базу данных я думаю, что самый простой путь - это перенести весь текущий код чтения датчиков в Django management command. Таким образом, вы получите доступ ко всем командам Django

models.py (Пример БД)

from django.db import models

class SensorData(models.Model):
    datetime = models.DateTimeField('Creation Date')

    # Store the field, idk what it is.. so I'll say a decimal
    value = models.DecimalField(max_digits=6, decimal_places=2)

    # Make threshold a model method (see template example for use)
    def is_valid(self):
        lower_threshold = 1000
        upper_threshold = 1200
        if self.value < lower_threshold or self.value > upper_threshold:
            return False
        return True

{myapp}/management/commands/readsensor.py (Команда управления)

  • Пробежал с python manage.py readsensor
from datetime import datetime
from django.core.management.base import BaseCommand

#     \/ needs to change
from myapp.models import SensorData

def parseRaw(val):
    # Do something to get it in a normalized format & validate it's a 'good' input
    #   ex: ints are ints
    return val

class Command(BaseCommand):
    help = 'Reads Sensor & Inputs Value into Database'

    def handle(self, *args, **kwargs):

        # Insert some code to connect to sensor
        import serial
        serial_port = serial.Serial(4, timeout=2)
        serial_port.flushInput()

        # Normally any reading is done in a loop
        while True:
            # read in
            raw = serial_port.readline().decode('utf-8').strip()

            if raw:
                # clean the data
                cleaned = parseRaw(raw)

                # here we have to decide..
                #   Are we putting every input into the db?
                #   or just ones that failed?
                #   or average of 10 (I assume 1 every second)

                # Creating the DB entry
                SensorData.objects.create(datetime=datetime.now(), value=cleaned)

views.py (пример представления)

from django.shortcuts import render

#     \/ needs to change
from myapp.models import SensorData

@login_required
def sensorData(request, lot):
    # fetching from db
    # all_points = SensorData.objects.all()

    # filter by last hour
    from datetime import datetime, timedelta
    hour_ago = datetime.now() - timedelta(hours=1)
    last_hour = SensorData.objects.filter(datetime__gte=hour_ago)

    # Invalid in the last hour?
    from django.db.models import Q # Q for Complex Queries

    lower_threshold = 1000
    upper_threshold = 1200
    invalid_last_hour = last_hour.filter(Q(Q(value__lt=lower_threshold) | Q(value__gt=upper_threshold)))

    # Getting last hour errors from scratch
    invalid_last_hour_from_scratch = SensorData.objects.filter(
        Q(
            Q(datetime__gte=hour_ago) & 
            Q(Q(value__lt=lower_threshold) | Q(value__gt=upper_threshold))
        )
    )

    data = {
        'last_hour': last_hour,
        'last_hour_count': last_hour.count(),
        'invalid_last_hour': invalid_last_hour,
        'invalid_last_hour_count': invalid_last_hour_count.count(),
    }

    return render(request, 'sensordata_overview.html', data)

<
<!DOCTYPE html>
<html>
    {% load static %}
    <head>
        <title>Last Hour</title>
    </head>
    <body>
        <h3>Last Hour Overview</h3>

        <table>
            <tbody>
                <tr>
                    <th scope="row">Last Hour Total Count</th>
                    <th>{{i.last_hour_count}}</th>
                </tr>
                <tr>
                    <th scope="row">Last Hour Error Count</th>
                    <th>{{i.invalid_last_hour_count}}</th>
                </tr>
            </tbody>
        </table>


        <hr>
        <h3>Error Data</h3>

        <table>
            <thead>
                <tr>
                    <th scope="col">Datetime</th>
                    <th scope="col">Value</th>
                    <th scope="col">is_Value</th>
                </tr>
            </thead>
            <tbody>
                {% for i in invalid_last_hour %}
                <tr>
                    <th>{{i.datetime}}</th>
                    <th>{{i.value}}</th>
                    <th style="background-color:{% if i.is_valid %}green{% else %}red{% endif %}>
                        {{i.is_value}}
                    </th>
                </tr>
                {% endfor %}
            </tbody>
        </table>

        <hr>
        <h3>Raw Data</h3>

        <table>
            <thead>
                <tr>
                    <th scope="col">Datetime</th>
                    <th scope="col">Value</th>
                    <th scope="col">is_Value</th>
                </tr>
            </thead>
            <tbody>
                {% for i in last_hour %}
                <tr>
                    <th>{{i.datetime}}</th>
                    <th>{{i.value}}</th>
                    <th style="background-color:{% if i.is_valid %}green{% else %}red{% endif %}>
                        {{i.is_value}}
                    </th>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </body>
</html>
Вернуться на верх