使用AJAX和Django进行GPIO控制

时间:2018-09-29 14:27:28

标签: jquery ajax django raspberry-pi gpio

所以我遇到了一个问题,即使搜索堆栈的资源和Google也无法解决。让我与您分享。

我的配置/工具是Raspberry Pi Zero W,Raspbian,python 3.5,Django框架,Bootstrap。

我正在通过Web浏览器(Chrome)通过RPi上的GPIO进行通信并对其进行控制。

我的测试台是一组LED,我可以使用外壳以及简单的MVC(电路正确)来打开和关闭这些LED。

同时,我的目标和问题是使用AJAX打开和关闭LED,以便每次按下按钮时都不会重新加载页面(当我不使用jquery / AJAX时会发生这种情况)。

在当前阶段,按下按钮后,似乎所有代码都已执行,除了 views.py 中的功能 control_button

单击按钮后我的日志:

"GET /vendapp/ HTTP/1.1" 200 6027
"POST /vendapp/ HTTP/1.1" 200 6027

AJAX也可以执行成功:功能...

代码如下:

html 1

<!doctype html>
{% load static %}
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../../../favicon.ico">

    <title>FP</title>

    <meta charset="utf-8" />
    {% load staticfiles %}
    <link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/>
    <link rel="stylesheet" href="{% static 'personal/css/custom1.css' %}" type = "text/css"/>
    <link rel="stylesheet" href="{% static 'personal/css/conti1.css' %}" type = "text/css"/>
    <meta name="viewport" content = "width=device-width, initial-scale=1.0">

    <style type="text/css">
        html,
        body {
          height:100%
        }
    </style>
  </head>

  <body>
    <header>
      <div class="container-fluid p-0 px-md-0 mb-0">
        <div class="d-flex flex-row flex-md-row align-items-center p-0 px-md-0 mb-0 border-bottom box-shadow">  
            <div class="col">
                <div class="media align-items-center p-2 px-md-0 mb-0">
                    <img class="mb-1" src="{% static '/personal/img/c.png' %}" class="responsive-img" style='max-height: 64px; max-width: 64px;' alt="c1">
                    <div class="media-body">
                    <h5 class="mt-0">TITLE</h5>
                    <h6><em>Cliche</em></h6>
                    </div>
                </div>
            </div>
        </div>
      </div>

    </header>

    <main>
      {% block content %}
      {% endblock %}
    </main>

    <footer>
      ...
    </footer>

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->

    <!-- jQuery library -->
    <script src="{% static 'personal/jquery/jquery.js' %}"></script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>   
    <script src="{% static 'personal/js/bootstrap.js' %}"></script>
    {% block javascript %}{% endblock %}
  </body>
</html>

html 2

{% extends "personal/header3.html" %}

{% block javascript %}

<script>

$(function() {

    function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    $('.btn-outline-primary').click(function(){
            var pinID = $(this).attr('data-pinID');
            alert(pinID);

        $.ajax({
            type: "POST",
            url: "{% url 'control_button' %}",
            data: {'getdata': JSON.stringify(pinID)},
            datatype: 'json',
            success: function(){
                alert(pinID);
                console.log(pinID);
            },
            error: function() {
                alert('error');
            }
        });

    });

});
</script>

{% endblock %}

{% block content %}
{% load static %}

<form method="post">
{% csrf_token %}
<div class="container-fluid p-0 px-md-0 mb-0 " id="main">


    <div class="d-flex flex-row flex-md-row align-items-center p-0 px-md-0 mb-0">
        <div class="col-sm-8">

            <div class="container-fluid">

                    <button type="button" id="btn4" data-pinID="127" class="btn btn-lg btn-outline-primary border-0 mt-4 mr-3 ml-3 mb-3 pt-4 pl-3 pr-3 pb-3" style="background: url({% static '/personal/img/blk.jpg'%}) center">
                    </button>   

                    <button type="button" id="btn5" data-pinID="191" class="btn btn-lg btn-outline-primary border-0 mt-4 mr-3 ml-3 mb-3 pt-4 pl-3 pr-3 pb-3" style="background: url({% static '/personal/img/blk.jpg'%}) center">
                    </button>

                    <button type="button" id="btn6" data-pinID="223" class="btn btn-lg btn-outline-primary border-0 mt-4 mr-3 ml-3 mb-3 pt-4 pl-3 pr-3 pb-3" style="background: url({% static '/personal/img/blk.jpg'%}) center">
                    </button>                               
            </div>
        </div>
        <div class="col-sm-4"></div>
    </div>  

</div>
</form>
{% endblock %}

views.py

from django.shortcuts import render, get_object_or_404
from time import sleep
from smbus2 import SMBusWrapper
import json, sys
from django.http import JsonResponse, HttpResponse

DURATION = 4.0

def index(request):
    return render(request, 'personal/home.html')

def control_button(request):
    if request.method == 'POST':
        btn_pin = int(request.POST.get('getdata', None))
        with SMBusWrapper(1) as bus:
        #write a button pin as 8-bit to adress 38, offset 0
        bus.write_byte_data(0x38, 0, btn_pin)
        sleep(DURATION)
        data = 255
        bus.write_byte_data(0x38, 0, data)  
    return JsonResponse()

urls.py

from django.urls import path
from . import views


urlpatterns = [
    path('', views.index, name = 'index'),
    path('', views.control_button, name = 'control_button'),
]

非常感谢您的帮助。

0 个答案:

没有答案