
本文介绍了如何通过 Shelly 脚本,在使用用户名和密码保护的 Shelly 设备上执行操作。核心在于利用 HTTP.Request 方法手动构建带有 Authorization: Basic 头的 HTTP 请求,从而绕过 HTTP.GET 方法无法传递认证信息的限制,并提供了详细的代码示例。
使用 HTTP.Request 进行认证控制
当目标 Shelly 设备启用了用户名和密码保护时,直接使用 Shelly.call("http.get", ...) 传递认证信息可能无法正常工作。这是因为 HTTP.GET 方法可能不会将 URL 中的用户名和密码转换为 Authorization: Basic HTTP 头。
解决此问题的方法是使用 HTTP.Request 方法,手动构建包含 Authorization: Basic 头的 HTTP 请求。
步骤详解
构建 URL: 首先,需要构建包含目标 Shelly 设备 IP 地址和所需操作的 URL。例如,要打开 relay 0 并设置定时器,URL 可能如下所示:http://
/relay/0?turn=on&timer= 。 -
编码用户名和密码: 使用 btoa() 函数将用户名和密码编码为 Base64 字符串。 btoa() 函数是 JavaScript 内置的 Base64 编码函数。
let user_pass = btoa(CONFIG.username + ":" + CONFIG.password);
-
构建 HTTP 头: 创建一个包含 Authorization: Basic
头的对象。 let header = { method: "GET", url: bsb_lan_url, headers: {}, timeout: 20, }; if (CONFIG.username) { header.headers.Authorization = "Basic " + user_pass; } -
发送请求: 使用 Shelly.call("HTTP.Request", ...) 方法发送带有自定义头的 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);
完整示例代码
let CONFIG = {
host: "bsb-lan.local",
username: "123",
password: "abc",
}
function sendTemperature() {
let temperature = Shelly.getComponentStatus("switch:0").temperature.tC;
let bsb_lan_url = "http://" + CONFIG.host + "/I10000=" + temperature;
let user_pass = btoa(CONFIG.username + ":" + CONFIG.password);
let header = {
method: "GET",
url: bsb_lan_url,
headers: {},
timeout: 20,
};
if (CONFIG.username) {
header.headers.Authorization = "Basic " + user_pass;
}
print("It is ", temperature, " degrees.");
print("Calling URL ", bsb_lan_url);
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);
}注意事项
- 确保目标 Shelly 设备已启用用户名和密码保护。
- 替换示例代码中的 CONFIG.host, CONFIG.username, CONFIG.password 为您的实际配置。
- 仔细检查 URL 是否正确,包括 IP 地址、端口号和 API 路径。
- timeout 属性控制请求的超时时间,单位为秒。
- Shelly.getComponentStatus("switch:0").temperature.tC 这段代码用于获取switch:0组件的温度,可以替换为其他需要的组件状态。
- 错误处理非常重要。检查 error_code 和 error_message 以诊断潜在问题。
总结
通过使用 HTTP.Request 方法并手动添加 Authorization: Basic 头,您可以轻松地通过 Shelly 脚本控制受密码保护的 Shelly 设备。这种方法提供了更大的灵活性和控制权,允许您处理各种认证场景。记住,安全性至关重要,请妥善保管您的用户名和密码。










