esp8266根据httpserver状态,调用网络唤醒,实现一键开机
一.开发板程序
# include <ESP8266WiFi.h>
# include <ESP8266HTTPClient.h>
# include <WiFiUdp.h>
# include <ArduinoJson.h>
const char * ssid = "wifiname" ;
const char * password = "password" ; void setup ( ) { Serial. begin ( 115200 ) ; WiFi. begin ( ssid, password) ; while ( WiFi. status ( ) != WL_CONNECTED) { delay ( 500 ) ; Serial. print ( "WiFi not connected" ) ; } Serial. println ( "" ) ; Serial. println ( "WiFi connected" ) ; Serial. print ( "IP address: " ) ; Serial. println ( WiFi. localIP ( ) ) ;
}
void loop ( ) { checkFlag ( ) ; delay ( 10000 ) ;
} void test ( ) { Serial. println ( "fx call successd" ) ;
} void wakeUpComputer ( ) { WiFiUDP udp; udp. begin ( 9 ) ; byte mac[ 6 ] = { 0x77 , 0x77 , 0x77 , 0x77 , 0x77 , 0x77 } ; byte packet[ 102 ] ; memset ( packet, 0xFF , 6 ) ; for ( int i = 6 ; i < 102 ; i += 6 ) { memcpy ( packet + i, mac, 6 ) ; } udp. beginPacket ( "255.255.255.255" , 9 ) ; udp. write ( packet, 102 ) ; udp. endPacket ( ) ; Serial. println ( "Magic Packet Sent!" ) ;
} void checkFlag ( ) { Serial. println ( "start checkflag" ) ; if ( WiFi. status ( ) == WL_CONNECTED) { HTTPClient http; WiFiClient client; http. begin ( client, "http://192.168.1.1:4050/api/endpoint" ) ; int httpCode = http. GET ( ) ; Serial. println ( httpCode) ; if ( httpCode > 0 ) { Serial. println ( "HTTP GET OK" ) ; String payload = http. getString ( ) ; DynamicJsonDocument doc ( 1024 ) ; deserializeJson ( doc, payload) ; String flag = doc[ "flag" ] ; String additionalInfo = doc[ "additional_info" ] ; if ( flag == "wake" ) { Serial. println ( "start wakeup" ) ; wakeUpComputer ( ) ; } else { Serial. println ( "HTTP GET not wakeup" ) ; } } else { Serial. println ( "HTTP GET failed" ) ; } http. end ( ) ; }
}
二. 服务端
from flask import Flask, jsonify, request
app = Flask( __name__)
flag_data = { "flag" : "idle" , "additional_info" : ""
}
@app. route ( '/api/endpoint' , methods= [ 'GET' ] )
def get_flag ( ) : """返回当前flag值和附加信息""" return jsonify( flag_data)
@app. route ( '/api/update_flag' , methods= [ 'POST' ] )
def update_flag ( ) : """更新flag值和附加信息""" global flag_datadata = request. jsonif 'flag' in data: flag_data[ 'flag' ] = data[ 'flag' ] if 'additional_info' in data: flag_data[ 'additional_info' ] = data[ 'additional_info' ] return jsonify( flag_data) , 200
if __name__ == '__main__' : app. run( host= '0.0.0.0' , port= 4050 )
三.服务端状态变更
curl http://192.168.1.1:4050/api/endpoint
curl -X POST http://192.168.1.1:4050/api/update_flag -H "Content-Type: application/json" -d '{"flag": "wake", "additional_info": "some info"}'
curl -X POST http://192.168.1.1:4050/api/update_flag -H "Content-Type: application/json" -d '{"flag": "idle", "additional_info": "some info"}'