在Django网站中显示传感器读数 [英] Showing sensor reading in a django website

查看:65
本文介绍了在Django网站中显示传感器读数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设计一个基于Web的应用程序,以显示声音传感器的读数,这些读数是从基于Arduino的设置中收集的(还显示了一些分析结果).为了使我的arduino设置工作,我开发了一个名为"ard_sensor_project.py"的python程序,该程序收集读数并将其存储在.csv文件中并创建图形.

I want to design a web based application for showing sound sensor readings, collected from an Arduino based setup (and also show some analysis results). For making my arduino setup work I had developed a python program named 'ard_sensor_project.py' which collects readings and store in .csv file and create a graph.

现在,我想显示在django网站中生成的读数.为此,我在django网站的views.py中导入了"ard_sensor_project.py",并调用了一种实时打印传感器读数的方法.

Now I want to display the readings generated in a django website. For that I have imported 'ard_sensor_project.py' in views.py of my django site and called a method to print the sensor reading at real time.

但是在运行该程序时,尽管阅读收集​​模块已经启动,但站点尚未启动,并且我也看不到网页和任何阅读内容.

But on running the program, it seems that though the reading collecting module has started, the site has not started yet and I can neither see the web page nor any reading.

有什么方法可以让我在django网站上显示读数吗?

Is there any way such that I can show the readings on the django site?

这是我的 ard_sensor_project.py

import matplotlib.pyplot as plt
from datetime import datetime

#necessary declarations
sr = serial.Serial("COM6",9600)

#self declared methods

def getsensordata():
    st = list(str(sr.readline(),'utf-8'))
    return int(str(''.join(st[:])))


def storedata(fname,val1,val2):
    #stores data in a .csv file, will update if required

def plotgraph():
    #method for plotting data in a matplotlib graph, will update if required


#codes as part of main execution + function calls

print("------Reading collection starts now------")

while True:
    try:
        timeNow = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
        storedata('op.csv', timeNow, getsensordata())
        #plotgraph()

    except KeyboardInterrupt:
        break

sr.close()
print("------Reading collection ends successfully------")

这是我的Django网站的 views.py

Here is views.py of my django site

from django.shortcuts import render

# Create your views here.

from django.template.loader import get_template
from django.http import HttpResponse
from . import ard_sensor_project as ard

def index(request):
    return render(request,'start.html',{'noise_level':ard.getsenordata})

我的运行时输出:

因此,似乎服务器根本没有运行.当我将 ard.getsensordata 替换为0(同时也删除了 ard 导入)时,我得到:

So it seems that the server is not at all running. When I replace ard.getsensordata by 0 (also removing ard import), I get :

现在我要读取而不是0.我应该如何进行?

Now instead of 0, I want the reading. How should I proceed?

推荐答案

在Web应用程序的上下文中,我认为您的数据收集程序必须具有不同的理念.

In a context of a web application, I think your data collection program must have a different philosophy.

您会看到 print("------现在开始读取集合------"),因为当您使用来自.导入ard_sensor_project作为ard

You see the print("------Reading collection starts now------") because all you top level code is executed when you import your module with from . import ard_sensor_project as ard

它会打印消息,但还会打开串行端口并启动 while True 无限循环.

It prints the message but it also opens the serial port and start the while True infinite loop.

Web服务器和此循环位于同一线程中.因此,直到循环结束,服务器才启动.

The web server and this loop are in the same thread. So the server will not start until the loop ends.

您可能有不同的策略

1)如果从Arduino读取速度很快,而您只有一个用户访问

您可以重新组织模块并将所有数据读取内容放入一个函数中

You can reorganize your module and put all the data reading stuff in a function

def getsensordata():
    print("------Reading collection starts now------")
    sr = serial.Serial("COM6",9600)
    st = list(str(sr.readline(),'utf-8'))
    sr.close() 
    print("------Reading collection ends successfully------")
    return int(str(''.join(st[:])))

然后您的django视图可以调用此函数

Then your django view can call this function

from . import ard_sensor_project as ard

def index(request):
    return render(request, 'start.html', {'noise_level':ard.getsenordata()})

请注意,在您的示例中,您在 ard.getsenordata 之后忘记了(),如果是,则不会调用该函数

Note that your forgot the () after ard.getsenordata in your example and if so, the function is not called

访问索引视图时,将调用 ard.getsenordata ,从Arduino读取数据并将其放入您的上下文中.您可以在 start.html 模板

When you access your index view, the ard.getsenordata is called, the data is read from the Arduino and put in your context. You can display in correctly in the start.html template

2)如果从Arduino读取速度很快,并且您希望数据自动更新,并且仍然有一个用户正在访问

在前面的示例中,仅在显示页面时读取数据.如果要刷新它,则需要刷新浏览器上的页面.

In the previous example, the data is just read when the page is displayed. If you want to refresh it, you need to refresh the page on your browser.

如果要自动更新数据,则需要使用ajax实现某些功能

If you want an automatic update of the data, you need to implement something with ajax

from . import ard_sensor_project as ard

def index(request):
    return render(request, 'start.html', {})

def ajax_data(request):
    data = {'noise_level':ard.getsenordata()}
    json_data = json.dumps(data)
    return Response(json_data, mimetypes='application/json')

然后,在您的 start.html 中,您需要实现一个javascript函数,该函数将定期使用AJAX调用此 ajax_data 视图

Then in your start.html, you need to implement a javascript function that will call this ajax_data view with AJAX on periodic basis

3)如果从Arduino读取速度不快或您有多个用户访问

先前的代码假定从Arduino读取速度很快.您的视图将等待读取结束,然后再发送响应.

The previous codes assume that reading from Arduino is fast. Your view will wait for the reading to end before sending a response.

如果有多个人访问同一页面,则必须对 getsensordata 实施锁定,否则读取可能会失败.

If you have several people accessing the same page, you will have to implement a lock on the getsensordata otherwise the reading may fail.

然后,我建议通过数据库使用另一种策略.

Then, I would recommend to use another strategy by using a Database.

您可以开发一个外部程序,以定期收集数据并将其存储到数据库中.将其开发为Django命令可能是一个好主意请参阅文档,然后能够通过Django ORM访问数据库.

You can develop an external program with collects the data on a periodic basis and store it into a database. It might be a good idea to develop it as a Django command See the docs and then to be able to access the database through Django ORM.

例如,如果您定义了 MyNoiseLevelModel 模型

For exemple if you have defined a MyNoiseLevelModel model

class Command(BaseCommand):
    def handle(self, *args, **options):
         while True:
         try:
              now = datetime.now()
              noise_level = getsenordata()
              MyNoiseLevelModel.objects.create(timestamp=now(), value=noise_level)
              # maybe wait a little bit here
              # time.sleep(1) # 1 sec
         except KeyboardInterrupt:
              break

然后,您可以在Web服务器上并行运行此命令.它会收集数据,您可以在视图中查看它

Then you can run this command in parallel of your web server. It collects the data and you can get it in your view

def index(request):
    return render(request, 'start.html', {})

def ajax_data(request):
    values = MyNoiseLevelModel.objects.all().values('value')
    json_data = json.dumps(data)
    return Response(json_data, mimetypes='application/json')

这篇关于在Django网站中显示传感器读数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆