boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

使用脚本通过身份验证控制 Shelly 设备


avatar
站长 2025年8月15日 4

使用脚本通过身份验证控制 Shelly 设备

本文档介绍了如何使用 Shelly Plus 1 PM 上的脚本,通过用户名和密码验证来控制另一个 Shelly 设备。由于 Shelly.call(“http.get”) 不会自动将 URL 中的凭据转换为 HTTP 身份验证标头,因此我们需要使用 HTTP.Request 并手动生成 Authorization: Basic 标头。本文提供了详细的代码示例,展示了如何实现这一目标,并解释了关键步骤和注意事项。

使用 HTTP.Request 进行身份验证

当需要通过用户名和密码验证来控制 Shelly 设备时,直接在 Shelly.call(“http.get”) 的 URL 中包含用户名和密码可能无法正常工作。这是因为 Shelly 的 http.get 方法不会自动将 URL 中的凭据转换为 HTTP Authorization: Basic 标头。为了解决这个问题,我们需要使用 HTTP.Request 方法,并手动构建包含身份验证信息的 HTTP 标头。

以下是如何使用 HTTP.Request 方法进行身份验证的步骤:

  1. 定义配置信息: 首先,我们需要定义包含目标 Shelly 设备的 IP 地址、用户名和密码的配置对象。

    let CONFIG = {   host: "your_shelly_ip", // 替换为目标 Shelly 设备的 IP 地址   username: "your_username", // 替换为用户名   password: "your_password", // 替换为密码 }
  2. 构建 URL: 接下来,构建要发送到目标 Shelly 设备的 URL。

    let shelly_url = "http://" + CONFIG.host + "/relay/0?turn=on&timer=10"; // 示例:打开 relay 0 并设置 10 秒定时器
  3. 创建 Authorization 标头: 使用 btoa() 函数将用户名和密码编码为 Base64 字符串,并将其添加到 Authorization 标头中。

    let user_pass = btoa(CONFIG.username + ":" + CONFIG.password); let header = {   method: "GET",   url: shelly_url,   headers: {},   timeout: 20, }; if (CONFIG.username) {   header.headers.Authorization = "Basic " + user_pass; }
  4. 使用 HTTP.Request 发送请求: 使用 Shelly.call(“HTTP.Request”, header, callback, null) 发送带有身份验证标头的 HTTP 请求。

    Shelly.call("HTTP.Request", header, function (result, error_code, error_message) {   if (error_code === 200) {     print("Success: " + result);   } else {     print("Error code: " + error_code);     print("Errormessage: " + error_message)   } }, null);

完整示例代码

以下是一个完整的示例代码,展示了如何使用 HTTP.Request 方法通过身份验证来控制 Shelly 设备:

let CONFIG = {   host: "your_shelly_ip", // 替换为目标 Shelly 设备的 IP 地址   username: "your_username", // 替换为用户名   password: "your_password", // 替换为密码 }  function turnOnShelly() {   let shelly_url = "http://" + CONFIG.host + "/relay/0?turn=on&timer=10";   let user_pass = btoa(CONFIG.username + ":" + CONFIG.password);    let header = {     method: "GET",     url: shelly_url,     headers: {},     timeout: 20,   };    if (CONFIG.username) {     header.headers.Authorization = "Basic " + user_pass;   }    Shelly.call("HTTP.Request", header, function (result, error_code, error_message) {     if (error_code === 200) {       print("Success: " + result);     } else {       print("Error code: " + error_code);       print("Errormessage: " + error_message)     }   }, null); }  // 调用 turnOnShelly 函数来打开 Shelly 设备 turnOnShelly();

注意事项

  • 替换占位符: 务必将 your_shelly_ip、your_username 和 your_password 替换为实际的值。
  • 错误处理: 示例代码包含基本的错误处理。在生产环境中,建议添加更完善的错误处理机制。
  • 安全性: 尽量避免在代码中硬编码用户名和密码。可以考虑使用环境变量或其他更安全的存储方式。
  • URL 编码: 如果 URL 中包含特殊字符,请确保对其进行正确编码。

总结

通过使用 HTTP.Request 方法并手动构建 Authorization: Basic 标头,我们可以成功地通过身份验证来控制 Shelly 设备。这种方法提供了更大的灵活性和控制权,可以满足各种复杂的身份验证需求。希望本文档能够帮助您更好地理解和应用 Shelly 脚本编程。



评论(已关闭)

评论已关闭