栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

WeMos和树莓派的通信

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

WeMos和树莓派的通信

文章目录
      • 树莓派上操作
        • 使用Python创建Http服务器
        • 使用树莓派做WeMos的后台
          • 树莓派做http服务器
            • 代码
          • WeMos发送HTTP请求
          • WeMos连接wifi
          • WeMos发送HTTP请求

树莓派上操作 使用Python创建Http服务器
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(host = "0.0.0.0", port = '3009')
  • 定义根目录的返回内容
使用树莓派做WeMos的后台 树莓派做http服务器
  • 作用
    • 使用flask,在树莓派上创建一个简单的web服务器
    • wemos提出HTTP的get请求取汇报数据
代码
# 默认访问‘/data’路径时会调用下属的函数
""" pi_backend.py

This is a REST relay server running on the Pi for the Arduino to relay data 
to on the way to the Cloud. Effectively functions as a gateway for
the edge devices.

"""

from flask import Flask, request, render_template, Response
#import client           #uncomment when integrating with the client.py API

# Create the flask app
app = Flask(__name__)

# This is for the callback, which should be defined to
# with the following signature:
# def callback(temp, humid, light)
#

_callback_ = None

# Create just a single route to read data from the Arduino
@app.route('/data', methods = ['GET'])
def addData():
    ''' The one and only route. It extracts the
    data from the request, converts to float if the
    data is not None, then calls the callback if it is set
    '''

    global _callback_

    tempStr = request.args.get('temp')
    humidStr = request.args.get('humid')
    lightStr = request.args.get('light')

    temp = float(tempStr) if tempStr else None
    humid = float(humidStr) if humidStr else None
    light = float(lightStr) if lightStr else None

    if _callback_:
        _callback_(temp = temp, humid = humid, light = light)
    
    return "OK", 200


def set_callback(callback):
    ''' Sets the callback.

    @param callback The callback with signature def callback(temp, humid,
    light)

    '''

    global _callback_

    _callback_ = callback

def demo_callback(temp, humid, light):
    ''' Demo callback that just prints the data passed in.
    '''

    if temp is not None:
        print("nTemperature = %3.2f" % temp)

    if humid is not None:
        print("Humidity = %3.2f" % humid)

    if light is not None:
        print("Light = %3.2f" % light)

    if temp is None and humid is None and light is None:
        print("n*** Called without any parameters. ***")

    print("n")

def main():
    set_callback(demo_callback)
    app.run(host = "0.0.0.0", port = '3009')


if __name__ == '__main__':
    main()

WeMos发送HTTP请求
  • 说明
    • WeMos和Pi能够通过局域网实现互通,上文中已经设置了树莓派作为服务器,当前部分需要通过WeMos发送HTTP请求
WeMos连接wifi
  • 将下述代码烧入wemos模块
#include 
#include 
#include 

const char* ssid = "ChinaNet-G3GN201"; //Your Wifi's SSID
const char* password = "qq7729577855"; //Wifi Password

void setup(void){
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");
  
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop(void){

}

WeMos发送HTTP请求
  • 在之前的例子上,创建http请求的相关代码,为了模仿实际传感器产生数据的过程,每5秒发送一个数据。
#include 
#include 
#include 

const char* ssid = "ChinaNet-G3GN201"; //Your Wifi's SSID
const char* password = "qq7729577855"; //Wifi Password

WiFiClient wifiClient;
const char* piAt = "http://192.168.1.248:3009/"; //change to your Pi's IP

void setup(void){
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");
  
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop(void){
  Serial.print("Sending...");
  if (WiFi.status() == WL_CONNECTED){
    HTTPClient http;
    
    String url = piAt;
    url += "data?temp=31.2&humid=76&light=87"; //hardcoded values for example only
    
    http.begin(wifiClient,url);
    int returnCode = http.GET();   //perform a HTTP GET request
    
    if (returnCode > 0){
      String payload = http.getString();
      Serial.println(payload);
    }
    http.end();
    
  } else {
    Serial.println("WiFi disconnected");
  }
  delay(5000);  //Five second delay
}
暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1015841.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号