
本文介绍了如何通过 Shelly 脚本,在使用用户名和密码保护的 Shelly 设备上执行操作。核心在于利用 HTTP.Request 方法手动构建带有 Authorization: Basic 头的 HTTP 请求,从而绕过 HTTP.GET 方法无法传递认证信息的限制,并提供了详细的代码示例。
当目标 Shelly 设备启用了用户名和密码保护时,直接使用 Shelly.call("http.get", ...) 传递认证信息可能无法正常工作。这是因为 HTTP.GET 方法可能不会将 URL 中的用户名和密码转换为 Authorization: Basic HTTP 头。
解决此问题的方法是使用 HTTP.Request 方法,手动构建包含 Authorization: Basic 头的 HTTP 请求。
构建 URL: 首先,需要构建包含目标 Shelly 设备 IP 地址和所需操作的 URL。例如,要打开 relay 0 并设置定时器,URL 可能如下所示:http://<IP_ADDRESS>/relay/0?turn=on&timer=<DURATION>。
编码用户名和密码: 使用 btoa() 函数将用户名和密码编码为 Base64 字符串。 btoa() 函数是 JavaScript 内置的 Base64 编码函数。
let user_pass = btoa(CONFIG.username + ":" + CONFIG.password);
构建 HTTP 头: 创建一个包含 Authorization: Basic <BASE64_ENCODED_CREDENTIALS> 头的对象。
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);
}通过使用 HTTP.Request 方法并手动添加 Authorization: Basic 头,您可以轻松地通过 Shelly 脚本控制受密码保护的 Shelly 设备。这种方法提供了更大的灵活性和控制权,允许您处理各种认证场景。记住,安全性至关重要,请妥善保管您的用户名和密码。
以上就是通过脚本使用认证方式控制 Shelly 设备的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号