• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
MKT-porter
博客园    首页    新随笔    联系   管理    订阅  订阅
arduino开发你好小智(2-2)外设定时提醒任务

、

arduino单独代码

#include <WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <TimeLib.h>
#include <TaskScheduler.h>

// WiFi配置
const char* ssid = "CMCC-yaoyao";
const char* password = "love123456";

// NTP配置
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 8 * 3600, 60000);

// 任务调度器
Scheduler runner;

// 任务结构体 - 添加倒计时相关字段
struct ScheduledTask {
    String name;
    int triggerDay;
    int triggerHour;
    int triggerMinute;
    bool isRecurring;
    bool hasExecuted;
    Task* task;
    void (*callback)();
    bool isCountdown;
    unsigned long countdownSeconds;
    unsigned long startTime;        // 任务开始时间(毫秒)
    unsigned long scheduledTime;    // 计划执行时间(毫秒)
};

// 任务回调函数声明
void mondayTaskCallback();
void tuesdayTaskCallback();
void countdownTaskCallback();

// 创建任务
ScheduledTask mondayTask = {
    "周一8点任务", 1, 8, 0, true, false, nullptr, mondayTaskCallback, false, 0, 0, 0
};

ScheduledTask tuesdayTask = {
    "周二15:30任务", 2, 15, 30, false, false, nullptr, tuesdayTaskCallback, false, 0, 0, 0
};

ScheduledTask countdownTask = {
    "3分钟倒计时任务", -1, 0, 0, false, false, nullptr, countdownTaskCallback, true, 180, 0, 0
};

ScheduledTask* allTasks[] = {&mondayTask, &tuesdayTask, &countdownTask};
const int taskCount = 3;

void setup() {
    Serial.begin(115200);
    
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nWiFi已连接");
    
    timeClient.begin();
    timeClient.update();
    
    unsigned long epochTime = timeClient.getEpochTime();
    setTime(epochTime);
    
    Serial.print("当前时间: ");
    printCurrentTime();
    
    initializeTasks();
    Serial.println("任务初始化完成");
}

void loop() {
    timeClient.update();
    runner.execute();
    
    // 更新倒计时显示
    static unsigned long lastDisplayTime = 0;
    if (millis() - lastDisplayTime > 1000) {
        displayCountdownRemaining();
        lastDisplayTime = millis();
    }
    
    delay(100);
}

void initializeTasks() {
    for (int i = 0; i < taskCount; i++) {
        ScheduledTask* task = allTasks[i];
        
        if (task->isCountdown) {
            // 记录开始时间和计划执行时间
            task->startTime = millis();
            task->scheduledTime = task->startTime + task->countdownSeconds * 1000;
            
            task->task = new Task(task->countdownSeconds * 1000, 
                                task->isRecurring ? TASK_FOREVER : 1, 
                                task->callback, &runner, false);
            
            Serial.print("倒计时任务 '");
            Serial.print(task->name);
            Serial.print("' 设置: ");
            Serial.print(task->countdownSeconds);
            Serial.println("秒后执行");
        } else {
            task->task = new Task(60 * 60 * 1000, 
                                task->isRecurring ? TASK_FOREVER : 1, 
                                task->callback, &runner, false);
            updateTaskSchedule(task);
        }
        
        task->task->enable();
        Serial.println("已初始化任务: " + task->name);
    }
}

// 显示倒计时任务的剩余时间(修正版本)
void displayCountdownRemaining() {
    for (int i = 0; i < taskCount; i++) {
        ScheduledTask* task = allTasks[i];
        
        if (task->isCountdown && task->task->isEnabled() && !task->hasExecuted) {
            unsigned long currentTime = millis();
            unsigned long remainingMs = task->scheduledTime - currentTime;
            
            if (remainingMs > 0) {
                unsigned long remainingSeconds = remainingMs / 1000;
                
                if (remainingSeconds <= 60 || remainingSeconds % 10 == 0) {
                    Serial.print("倒计时任务 '");
                    Serial.print(task->name);
                    Serial.print("' 剩余: ");
                    
                    // 格式化显示时间
                    if (remainingSeconds >= 60) {
                        Serial.print(remainingSeconds / 60);
                        Serial.print("分");
                        Serial.print(remainingSeconds % 60);
                        Serial.println("秒");
                    } else {
                        Serial.print(remainingSeconds);
                        Serial.println("秒");
                    }
                }
            }
        }
    }
}

// 其他函数保持不变...
void updateTaskSchedule(ScheduledTask* task) {
    if (task->isCountdown) return;
    
    time_t now = timeClient.getEpochTime();
    tm* timeInfo = localtime(&now);
    
    time_t nextExecution = calculateNextExecution(task, timeInfo);
    long delayMs = (nextExecution - now) * 1000;
    
    if (delayMs < 0) {
        delayMs += 7 * 24 * 3600 * 1000;
    }
    
    task->task->setInterval(delayMs);
    task->task->setIterations(task->isRecurring ? TASK_FOREVER : 1);
    
    Serial.print("定时任务 '");
    Serial.print(task->name);
    Serial.print("' 下一次执行: ");
    printTime(nextExecution);
}

time_t calculateNextExecution(ScheduledTask* task, tm* currentTime) {
    tm nextTime = *currentTime;
    nextTime.tm_hour = task->triggerHour;
    nextTime.tm_min = task->triggerMinute;
    nextTime.tm_sec = 0;
    
    int dayDifference = task->triggerDay - (currentTime->tm_wday == 0 ? 7 : currentTime->tm_wday);
    if (dayDifference < 0) dayDifference += 7;
    
    nextTime.tm_mday += dayDifference;
    return mktime(&nextTime);
}

// 任务回调函数
void mondayTaskCallback() {
    Serial.println("【执行任务】周一8:00任务 - 每周提醒");
    mondayTask.hasExecuted = true;
    updateTaskSchedule(&mondayTask);
}

void tuesdayTaskCallback() {
    Serial.println("【执行任务】周二15:30任务 - 单次执行");
    tuesdayTask.hasExecuted = true;
    
    if (!tuesdayTask.isRecurring) {
        tuesdayTask.task->disable();
        Serial.println("单次任务已执行并禁用");
    }
    updateTaskSchedule(&tuesdayTask);
}

void countdownTaskCallback() {
    Serial.println("【执行任务】3分钟倒计时任务 - 时间到!");
    countdownTask.hasExecuted = true;
    countdownTask.task->disable();
    Serial.println("倒计时任务执行完成");
}

void printCurrentTime() {
    time_t now = timeClient.getEpochTime();
    printTime(now);
}

void printTime(time_t timestamp) {
    tm* timeInfo = localtime(&timestamp);
    char buffer[30];
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S %A", timeInfo);
    Serial.println(buffer);
}

  

 

 

语音交互示例

  1. 1.

    ​​添加任务​​

    "添加一个每天上午8点的起床提醒,消息内容为'该起床了'"

  2. 2.

    ​​删除任务​​

    "删除ID为task002的提醒任务"

  3. 3.

    ​​查询任务​​

    "列出所有未完成的提醒"

    "显示今天的全部任务"

  4. 4.

    ​​更新任务状态​​

    "将服药提醒标记为已完成"

  5. 5.

    ​​推迟提醒​​

    "把当前提醒推迟10分钟"

这个简化版本完全专注于提醒功能的核心要素:

  • •

    任务管理(添加/删除/更新)

  • •

    时间触发机制

  • •

    重复模式设置

  • •

    状态跟踪(完成/未完成)

  • •

    提醒消息内容

  • •

    推迟功能

 

image

 

、定义

{
  "session_id": "",
  "type": "iot",
  "update": true,
  "descriptors": [
    {
      "name": "ReminderSystem",
      "description": "智能提醒任务系统",
      "properties": {
        "totalTasks": {
          "description": "当前任务总数",
          "type": "number"
        },
        "activeTasks": {
          "description": "活跃任务数量",
          "type": "number"
        },
        "nextTriggerTime": {
          "description": "下一个即将触发的任务时间",
          "type": "string"
        }
      },
      "methods": {
        "AddTask": {
          "description": "添加新提醒任务",
          "parameters": {
            "taskName": {
              "description": "任务名称",
              "type": "string"
            },
            "triggerTime": {
              "description": "触发时间(格式:YYYY-MM-DD HH:MM)",
              "type": "string"
            },
            "isRecurring": {
              "description": "是否重复任务(true/false)",
              "type": "boolean"
            },
            "recurrencePattern": {
              "description": "重复模式(daily/weekly/monthly)",
              "type": "string",
              "optional": true
            },
            "notificationMessage": {
              "description": "提醒时显示的消息",
              "type": "string",
              "optional": true
            }
          }
        },
        "DeleteTask": {
          "description": "删除指定任务",
          "parameters": {
            "taskId": {
              "description": "任务ID",
              "type": "string"
            }
          }
        },
        "ListTasks": {
          "description": "列出所有任务",
          "parameters": {
            "filter": {
              "description": "过滤条件(active/completed/all)",
              "type": "string",
              "optional": true
            }
          }
        },
        "UpdateTask": {
          "description": "更新任务状态",
          "parameters": {
            "taskId": {
              "description": "任务ID",
              "type": "string"
            },
            "isCompleted": {
              "description": "是否标记为已完成",
              "type": "boolean"
            }
          }
        },
        "SnoozeTask": {
          "description": "推迟提醒任务",
          "parameters": {
            "taskId": {
              "description": "任务ID",
              "type": "string"
            },
            "minutes": {
              "description": "推迟分钟数",
              "type": "number"
            }
          }
        }
      }
    }
  ]
}

  

示例状态信息

{
  "session_id": "",
  "type": "iot",
  "update": true,
  "states": [
    {
      "name": "ReminderSystem",
      "state": {
        "totalTasks": 3,
        "activeTasks": 2,
        "nextTriggerTime": "2025-08-19 08:00",
        "tasks": [
          {
            "taskId": "task001",
            "taskName": "早晨起床",
            "triggerTime": "2025-08-19 08:00",
            "isRecurring": true,
            "recurrencePattern": "daily",
            "isCompleted": false,
            "notificationMessage": "该起床了!"
          },
          {
            "taskId": "task002",
            "taskName": "重要会议",
            "triggerTime": "2025-08-19 14:30",
            "isRecurring": false,
            "isCompleted": false,
            "notificationMessage": "会议即将开始"
          },
          {
            "taskId": "task003",
            "taskName": "服药提醒",
            "triggerTime": "2025-08-18 20:00",
            "isRecurring": true,
            "recurrencePattern": "daily",
            "isCompleted": true
          }
        ]
      }
    }
  ]
}

  

如何使用

image

 

image

 

{
  "method": "UpdateTask",
  "parameters": {
    "taskId": "task001",
    "isCompleted": true
  }
}

  

image

 

{
  "method": "SnoozeTask",
  "parameters": {
    "taskId": "task002",
    "minutes": 30
  }
}

  

image

 

{
  "method": "ListTasks",
  "parameters": {
    "filter": "all"
  }
}

  

 

image

 

{
  "method": "UpdateTask",
  "parameters": {
    "taskId": "task003",
    "isCompleted": true
  }
}

  

image

 

{
  "totalTasks": 3,
  "activeTasks": 1,  // 仅剩 "重要会议" 是活跃的
  "nextTriggerTime": "2025-08-19 15:00",  // 推迟后的会议时间
  "tasks": [
    {
      "taskId": "task001",
      "taskName": "早晨起床",
      "triggerTime": "2025-08-19 08:00",
      "isRecurring": true,
      "recurrencePattern": "daily",
      "isCompleted": true,
      "notificationMessage": "该起床了!"
    },
    {
      "taskId": "task002",
      "taskName": "重要会议",
      "triggerTime": "2025-08-19 15:00",  // 推迟 30 分钟
      "isRecurring": false,
      "isCompleted": false,
      "notificationMessage": "会议即将开始"
    },
    {
      "taskId": "task003",
      "taskName": "服药提醒",
      "triggerTime": "2025-08-18 20:00",
      "isRecurring": true,
      "recurrencePattern": "daily",
      "isCompleted": true
    }
  ]
}

  

posted on 2025-08-18 22:32  MKT-porter  阅读(19)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3