微信硬件平台(八)7 综合合并版本

尚未加入自动获取token

 

#include <ESP8266WiFi.h>


#define WEIXIN_TOKEN  "19_69S6lnr6S-j1Zbmy1XYwx8LqYbKIT2PfmwJUofoBG2fNv_UvfCQmgYdh9TE_m1jJUPimQ7jRVe87h6pmS4Zdl2vCc7ZVx9aRgC0S-3eACtqMTd77VzWX1-p_PjQWBRqkIJAI7OOOPI3bY4xaZNXhAEAMAK"

#define PRODUCT_TYPE  "gh_e93c1b3098b9"                     // 设备种类
#define PRODUCT_ID    "gh_e93c1b3098b9_dae1c2072212185c"    // 设备ID

#define host         "api.weixin.qq.com"                    //微信服务器
#define  httpPort     80                                    //端口
  
#define ssid      "HUAWEI-H3VBKZ"                          // WIFI名字
#define password  "13991320168"                            // WIFI密码
 
void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password); //works!
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 
  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

  
/*
功能:5 请求设备绑定的用户ID
输入:
String UESRID    微信用户ID
String CONTENT   要发送的内容
输出:           无
*/
String RequestUserId(){
  Serial.println("/**************************************************/");
  Serial.println("5 request userID! ");


  Serial.print("connecting to ");
  Serial.println(host);
 
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
 
  if (!client.connect(host, httpPort)) { //works!
    Serial.println("connection failed");
    return "fail";
  }
 
  // We now create a URI for the request
  String url = "/device/get_openid";
  url += "?access_token=";
  url +=  WEIXIN_TOKEN;
  url += "&device_type=";
  url += PRODUCT_TYPE;
  url += "&device_id=";
  url += PRODUCT_ID;
 
  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
    delay(600);
      Serial.println();
    //处理返回信息
    String line = client.readStringUntil('\n');
    while (client.available() > 0) {
      line +='\n';
      line += client.readStringUntil('\n');
    
    }
   //Serial.println(line);
    client.stop();

    
     if(line.indexOf("errcode")>0){ 
         Serial.println(line);
         return "fail";
      }

      
    if(line.indexOf("open_id")>0){     
      //{"open_id":["ognVI6JsmBGd7lxYTZY4GH29LcNg","ognVI6GpDeseo6Qe_S7hGPgwlt8E","ognVI6CC8_HsPH5zgydb-PZFmxqU","ognVI6FxhqhGVuGhsZbmDyutgsMQ"],"resp_msg":{"ret_code":0,"error_info":"ok"}
     int datebegin= line.indexOf("{");
   //  int dateend=line.length();
     int dateend=line.lastIndexOf("}");
     String datajson=line.substring(datebegin,dateend);

     Serial.println(datajson);
     return datajson;
      }
      else{      
           Serial.println("fail");
           return "fail";
      }
    
  Serial.println();
  Serial.println("closing connection \n");
  
}


/*
功能:5-1 对用户ID组进行解析拆分
输入:
String json              用户ID组   "ognVI6JsmBGd7lxYTZY4GH29LcNg","ognVI6GpDeseo6Qe_S7hGPgwlt8E","ognVI6CC8_HsPH5zgydb-PZFmxqU","ognVI6FxhqhGVuGhsZbmDyutgsMQ",
String json_ruselt[]     拆分存放的数组
int sizejson             拆分存放的数组大小 默认10
输出:           成功返回1
*/


bool RequestUserId_json(String json,String json_ruselt[],int sizejson){

//    if(json.length()<1){return 0;}
//    DynamicJsonDocument  jsonBuffer(json.length());  
//    deserializeJson(jsonBuffer, json);
//    JsonObject root = jsonBuffer.as<JsonObject>();
//
//  String  ueserid1 = root[String("open_id")][0];
//  String  ueserid2 = root[String("open_id")][1];
//  String  ueserid3 = root[String("open_id")][2];
//  String  ueserid4 = root[String("open_id")][3];
//  Serial.println();
//  Serial.println(ueserid1);
//  Serial.println(ueserid2);
//  Serial.println(ueserid3);
//  Serial.println(ueserid4);

     int datebegin= json.indexOf("[")+1;
     int dateend=json.indexOf("]");
     String datajson=json.substring(datebegin,dateend);
     datajson= datajson+',';
  
    // Serial.println(datajson);


      /*
      ognVI6JsmBGd7lxYTZY4GH29LcNg   dongdong
      ognVI6GpDeseo6Qe_S7hGPgwlt8E
      ognVI6CC8_HsPH5zgydb-PZFmxqU
      ognVI6FxhqhGVuGhsZbmDyutgsMQ
      
      */
      int i=0;
     while(datajson.length()>0){
      int idbegin=0;
      int idend=datajson.indexOf(",");
      String id=datajson.substring(idbegin,idend);
      id=id.substring(1,id.length()-1);
      
      if(i<sizejson){
      json_ruselt[i]=id;
      i++;}
      
    //  Serial.println(id);
      datajson=datajson.substring(idend+1,datajson.length());
     }
     
     return 1;
  }



  
/*
功能:6 给制定用户推送消息
输入:
String UESRID    微信用户ID
String CONTENT   要发送的内容
输出:           无
*/
void SendMsgToUser(String UESRID,String CONTENT){
  Serial.println("/**************************************************/");
    Serial.println("6 send msg to user! ");
    
    String data =(String) "{"    
   + " \"touser\":\""+UESRID+"\"," 
   + " \"msgtype\":\"text\","  
   +  "\"text\" :"  
   +  "{ \"content\":\""+CONTENT+"\", }"   
   + "}"  ;

  
  Serial.print("connecting to ");
  Serial.println(host);
 
  // Use WiFiClient class to create TCP connections
  WiFiClient client;

  if (!client.connect(host, httpPort)) { //works!
    Serial.println("connection failed");
    return;
  }
 
  // We now create a URI for the request
  String url = "/cgi-bin/message/custom/send";
  url += "?access_token=";
  url += WEIXIN_TOKEN;

      int length = data.length();
      
      String postRequest =(String)("POST ") + url + " HTTP/1.1\r\n" +
          "Content-Type: application/json;charset=utf-8\r\n" +
          "Host: " + host + ":" + httpPort + "\r\n" +          
          "Content-Length: " + length + "\r\n" +
          "Connection: Keep Alive \r\n" +
          +"\r\n"
          +data
          +"\r\n";
      // Serial.println(postRequest);
       client.print(postRequest);

    delay(600);
    //处理返回信息
    String line = client.readStringUntil('\n');
  
    while (client.available() > 0) {
      line +='\n';
      line += client.readStringUntil('\n');
     
    }
    
    Serial.println(line);
    client.stop();

    
  Serial.println();
  Serial.println("closing connection!");
  
  
  }


int msgnum=0;

void loop() {


 
  if(msgnum<100){
  msgnum++;}
  else { msgnum=0;  }
  
  delay(10000);
  
 
  String json_alluser_id= RequestUserId(); // 得到用户ID组
   if(json_alluser_id!="fail"){
            String json_user_id[10];  // 用户ID组解析,存放到数组json_user_id
            RequestUserId_json(json_alluser_id,json_user_id,10); // 用户ID组解析,存放到数组json_user_id
            
                for(int i=0;i<10;i++){
                if(json_user_id[i]!=""){
                Serial.println(json_user_id[i]);
               // String UESRID="ognVI6JsmBGd7lxYTZY4GH29LcNg";
                String CONTENT=(String)"这是来自ESP8266发送的第"+msgnum+"条消息:\r\n  电量统计: 98\r\n 空气质量: 89\r\n 连接地址:<a href=http://www.qq.com >!";
                SendMsgToUser(json_user_id[i],CONTENT);
                }
                else{
              
                  
                  }
              }
           
  }
}

  

猜你喜欢

转载自www.cnblogs.com/kekeoutlook/p/10468625.html