You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP8266 Arduino项目中如何将Pushsafer对象定义移至loop()函数并从EEPROM读取密钥

ESP8266 Arduino项目中如何将Pushsafer对象定义移至loop()函数并从EEPROM读取密钥

嘿,我明白你的需求了——要把Pushsafer的实例化移到loop()里,同时从EEPROM读取密钥而不是硬编码。咱们一步步来解决这个问题:

第一步:调整全局变量声明

首先,把原来全局定义的Pushsafer对象删掉,换成一个可动态初始化的指针,同时准备好存储密钥的变量:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <Pushsafer.h>

char ssid[] = "my_ssid";
char password[] = "my_pwd"; 

boolean notificationSent = false;
// 注释掉硬编码的宏定义,换成String存储密钥
// #define pushsaferKey "my_pushsafer_key"  
String pushsaferKey = "";             

WiFiClient wifiClient;
// 换成全局指针,初始为nullptr,待后续初始化
Pushsafer* pushsafer = nullptr;

第二步:修改loop()函数的初始化逻辑

因为loop()会反复执行,我们只需要初始化一次Pushsafer对象。可以结合notificationSent标志来控制:

void loop() {
  // 仅当Pushsafer未初始化且通知未发送时执行
  if (!pushsafer && !notificationSent) {  
    // 这里替换成你的EEPROM读取密钥代码
    // 示例:假设已经从EEPROM把密钥读到pushsaferKey中
    pushsaferKey = "pushsafer_key_from_eeprom";  

    // 动态初始化Pushsafer对象,注意把String转成const char*
    pushsafer = new Pushsafer(pushsaferKey.c_str(), wifiClient);

    // 发送通知并标记已发送
    sendNotification();  
    notificationSent = true;
  }
}

第三步:更新sendNotification()函数调用方式

现在pushsafer是指针类型,调用成员方法时要改用->符号:

void sendNotification() {
  struct PushSaferInput input;
  input.message = "This is a test message";
  input.title = "This is a Test Title";
  input.sound = "8";
  input.vibration = "1";
  input.icon = "1";
  input.iconcolor = "#FFCCCC";
  input.priority = "1";
  input.device = "a";
  input.url = "https://www.pushsafer.com";
  input.urlTitle = "Open Pushsafer.com";
  input.picture = "";
  input.picture2 = "";
  input.picture3 = "";
  input.time2live = "";
  input.retry = "";
  input.expire = "";
  input.confirm = "";
  input.answer = "";
  input.answeroptions = "";
  input.answerforce = "";

  // 用->调用sendEvent方法
  Serial.println(pushsafer->sendEvent(input));
  Serial.println("Notification Sent");
}

额外注意点

  • 如果之后需要重新读取密钥并重新初始化Pushsafer,记得先释放旧对象的内存,避免内存泄漏:
    if (pushsafer) {
      delete pushsafer;
      pushsafer = nullptr;
    }
    // 然后重新创建新对象
    pushsafer = new Pushsafer(newKeyFromEEPROM.c_str(), wifiClient);
    
  • 确保从EEPROM读取的密钥是完整的字符串,没有多余的空白字符或乱码,否则Pushsafer API可能无法正常调用。

备注:内容来源于stack exchange,提问作者BobC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 08:44:38