v0.14.0
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
use super::crypto::{
|
||||
decrypt_v1, decrypt_v2, encrypt_v1, encrypt_v2, GENERIC_GREE_V1_KEY, GENERIC_GREE_V2_KEY,
|
||||
};
|
||||
use crate::models::{ApiEvent, Device, DeviceCommand};
|
||||
use crate::models::{ApiEvent, ConnectionStatus, ConnectionType, Device, DeviceCommand};
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use chrono::Utc;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
@@ -179,6 +179,11 @@ impl GreeClient {
|
||||
id: format!("gree-{}", mac.to_ascii_lowercase()),
|
||||
mac,
|
||||
name,
|
||||
connection_type: ConnectionType::Local,
|
||||
connection_status: ConnectionStatus::Unknown,
|
||||
cloud_device_id: None,
|
||||
cloud_parent_mac: None,
|
||||
cloud_account_id: None,
|
||||
ip: source.ip().to_string(),
|
||||
port: if source.port() == 0 {
|
||||
7000
|
||||
@@ -213,6 +218,11 @@ impl GreeClient {
|
||||
supports_xfan: None,
|
||||
supports_health: None,
|
||||
supports_sleep: None,
|
||||
supports_buzzer_control: None,
|
||||
supports_energy_meter: None,
|
||||
total_energy_kwh: None,
|
||||
compressor_frequency_hz: None,
|
||||
last_cloud_sync: None,
|
||||
current_temperature: None,
|
||||
outdoor_temperature: None,
|
||||
temperature_sensor_offset: None,
|
||||
@@ -221,6 +231,13 @@ impl GreeClient {
|
||||
last_seen: Some(now),
|
||||
last_error: None,
|
||||
communication_failures: 0,
|
||||
pending_command: false,
|
||||
capabilities: crate::models::DeviceCapabilities::default(),
|
||||
energy_source: crate::models::EnergySourcePreference::Auto,
|
||||
ha_energy_entity_id: None,
|
||||
ha_energy_unit: None,
|
||||
ha_energy_device_class: None,
|
||||
ha_energy_state_class: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}))
|
||||
|
||||
@@ -0,0 +1,476 @@
|
||||
use super::crypto::decrypt_v1;
|
||||
use aes::{
|
||||
cipher::{generic_array::GenericArray, BlockEncrypt, KeyInit},
|
||||
Aes128,
|
||||
};
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use base64::{engine::general_purpose::STANDARD, Engine as _};
|
||||
use chrono::Utc;
|
||||
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::collections::HashMap;
|
||||
|
||||
const APP_ID: &str = "4920681951525131286";
|
||||
const APP_HASH: &str = "0fa513124aa97781d1f3f40d61ca1a89";
|
||||
const API_AES_KEY: &str = "#G$&^jgfujy6ujxt";
|
||||
const GAEN1: &str = "5ac2bdf935bcca70";
|
||||
|
||||
pub fn region_base_url(region: &str) -> Option<&'static str> {
|
||||
match region {
|
||||
"Australia" => Some("https://augrih.gree.com"),
|
||||
"China Mainland" => Some("https://grih.gree.com"),
|
||||
"East South Asia" => Some("https://hkgrih.gree.com"),
|
||||
"Europe" => Some("https://eugrih.gree.com"),
|
||||
"India" => Some("https://ingrih.gree.com"),
|
||||
"Latin American" => Some("https://lagrih.gree.com"),
|
||||
"Middle East" => Some("https://megrih.gree.com"),
|
||||
"North American" => Some("https://nagrih.gree.com"),
|
||||
"Russia" => Some("https://rugrih.gree.com"),
|
||||
"South American" => Some("https://sagrih.gree.com"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parent_mac(mac: &str) -> String {
|
||||
let compact = mac.trim().replace([':', '-'], "").to_ascii_uppercase();
|
||||
if compact.len() > 12 && compact.ends_with("00") {
|
||||
compact[..compact.len() - 2].to_string()
|
||||
} else {
|
||||
compact
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CloudCredentials {
|
||||
pub user_id: i64,
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CloudDeviceInfo {
|
||||
pub name: String,
|
||||
pub mac: String,
|
||||
pub key: String,
|
||||
pub model: Option<String>,
|
||||
pub version: Option<String>,
|
||||
pub online: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CloudDeviceView {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub mac: String,
|
||||
pub parent_mac: String,
|
||||
pub model: Option<String>,
|
||||
pub version: Option<String>,
|
||||
pub online: bool,
|
||||
pub already_added: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GreeCloudApi {
|
||||
http: reqwest::Client,
|
||||
base_url: String,
|
||||
username: String,
|
||||
password: String,
|
||||
credentials: Option<CloudCredentials>,
|
||||
}
|
||||
|
||||
impl GreeCloudApi {
|
||||
pub fn for_region(
|
||||
http: reqwest::Client,
|
||||
region: &str,
|
||||
username: &str,
|
||||
password: &str,
|
||||
) -> Result<Self> {
|
||||
let base_url = region_base_url(region)
|
||||
.ok_or_else(|| anyhow!("unknown GREE Cloud region: {region}"))?;
|
||||
if username.trim().is_empty() {
|
||||
bail!("GREE Cloud login/email is required");
|
||||
}
|
||||
if password.is_empty() {
|
||||
bail!("GREE Cloud password is required");
|
||||
}
|
||||
Ok(Self {
|
||||
http,
|
||||
base_url: base_url.to_string(),
|
||||
username: username.trim().to_string(),
|
||||
password: password.to_string(),
|
||||
credentials: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn login(&mut self) -> Result<CloudCredentials> {
|
||||
let now = Utc::now();
|
||||
let time = now.format("%Y-%m-%d %H:%M:%S").to_string();
|
||||
let h = md5_hex(&(md5_hex(&self.password) + &self.password));
|
||||
let psw = md5_hex(&(h + &time));
|
||||
let payload = json!({
|
||||
"psw": psw,
|
||||
"t": time,
|
||||
"user": self.username,
|
||||
});
|
||||
let data = self
|
||||
.request_at("/App/UserLoginV2", payload, &["user", "psw", "t"], now)
|
||||
.await
|
||||
.context("GREE Cloud login request failed")?;
|
||||
|
||||
if data.get("r").and_then(Value::as_i64).is_some_and(|r| r != 200) {
|
||||
let message = data
|
||||
.get("msg")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown authentication error");
|
||||
bail!("GREE Cloud authentication failed: {message}");
|
||||
}
|
||||
let body = data
|
||||
.get("data")
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| data.as_object().cloned().unwrap_or_default());
|
||||
let user_id = value_i64(body.get("uid"))
|
||||
.ok_or_else(|| anyhow!("GREE Cloud login response is missing uid"))?;
|
||||
let token = body
|
||||
.get("token")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or_else(|| anyhow!("GREE Cloud login response is missing token"))?
|
||||
.to_string();
|
||||
let credentials = CloudCredentials { user_id, token };
|
||||
self.credentials = Some(credentials.clone());
|
||||
Ok(credentials)
|
||||
}
|
||||
|
||||
pub async fn get_all_devices(&self) -> Result<Vec<CloudDeviceInfo>> {
|
||||
let credentials = self
|
||||
.credentials
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow!("GREE Cloud session is not authenticated"))?;
|
||||
let homes = self.get_homes(credentials).await?;
|
||||
let mut all = Vec::new();
|
||||
for home_id in homes {
|
||||
all.extend(self.get_devices(credentials, home_id).await?);
|
||||
}
|
||||
Ok(filter_duplicate_devices(all))
|
||||
}
|
||||
|
||||
async fn get_homes(&self, credentials: &CloudCredentials) -> Result<Vec<i64>> {
|
||||
let payload = json!({
|
||||
"token": credentials.token,
|
||||
"uid": credentials.user_id,
|
||||
});
|
||||
let data = self
|
||||
.request_now("/App/GetHomes", payload, &["token", "uid"])
|
||||
.await
|
||||
.context("GREE Cloud home discovery failed")?;
|
||||
let homes = data
|
||||
.get("home")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| anyhow!("GREE Cloud homes response has no home list"))?;
|
||||
Ok(homes
|
||||
.iter()
|
||||
.filter_map(|home| value_i64(home.get("id")))
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn get_devices(
|
||||
&self,
|
||||
credentials: &CloudCredentials,
|
||||
home_id: i64,
|
||||
) -> Result<Vec<CloudDeviceInfo>> {
|
||||
let payload = json!({
|
||||
"token": credentials.token,
|
||||
"homeId": home_id,
|
||||
"uid": credentials.user_id,
|
||||
});
|
||||
let data = self
|
||||
.request_now(
|
||||
"/App/GetDevsInRoomsOfHomeV2",
|
||||
payload,
|
||||
&["token", "uid", "homeId"],
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("GREE Cloud device discovery failed for home {home_id}"))?;
|
||||
let rooms = data
|
||||
.get("rooms")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| anyhow!("GREE Cloud devices response has no rooms list"))?;
|
||||
let mut devices = Vec::new();
|
||||
for room in rooms {
|
||||
let Some(items) = room.get("devs").and_then(Value::as_array) else {
|
||||
continue;
|
||||
};
|
||||
for item in items {
|
||||
let Some(mac) = item.get("mac").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
let Some(key) = item.get("key").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
// Keep the exact MAC casing returned by GREE for MQTT. MQTT topics are
|
||||
// case-sensitive and the reference client deliberately publishes/subscribes
|
||||
// with the API value unchanged. Stable application IDs are normalized later.
|
||||
let cloud_mac = mac.trim().replace([':', '-'], "");
|
||||
devices.push(CloudDeviceInfo {
|
||||
name: item
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("GREE Cloud")
|
||||
.trim()
|
||||
.to_string(),
|
||||
mac: cloud_mac,
|
||||
key: key.trim().to_string(),
|
||||
model: optional_trimmed(item.get("model")),
|
||||
version: optional_trimmed(item.get("ver")),
|
||||
online: item.get("online").map(value_bool).unwrap_or(true),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
async fn request_now(&self, endpoint: &str, payload: Value, hash_props: &[&str]) -> Result<Value> {
|
||||
self.request_at(endpoint, payload, hash_props, Utc::now()).await
|
||||
}
|
||||
|
||||
async fn request_at(
|
||||
&self,
|
||||
endpoint: &str,
|
||||
payload: Value,
|
||||
hash_props: &[&str],
|
||||
now: chrono::DateTime<Utc>,
|
||||
) -> Result<Value> {
|
||||
let time = now.format("%Y-%m-%d %H:%M:%S").to_string();
|
||||
let epoch = now.timestamp();
|
||||
let vc = md5_hex(&format!("{APP_ID}_{APP_HASH}_{time}_{epoch}"));
|
||||
let payload_object = payload
|
||||
.as_object()
|
||||
.ok_or_else(|| anyhow!("GREE Cloud request payload must be an object"))?;
|
||||
let hash_values = hash_props
|
||||
.iter()
|
||||
.map(|key| python_string(payload_object.get(*key).unwrap_or(&Value::Null)))
|
||||
.collect::<Vec<_>>()
|
||||
.join("_");
|
||||
let dat_vc = md5_hex(&format!("{APP_HASH}_{hash_values}"));
|
||||
let mut body = Map::new();
|
||||
body.insert(
|
||||
"api".into(),
|
||||
json!({"appId": APP_ID, "r": epoch, "t": time, "vc": vc}),
|
||||
);
|
||||
body.insert("datVc".into(), Value::String(dat_vc));
|
||||
for (key, value) in payload_object {
|
||||
body.insert(key.clone(), value.clone());
|
||||
}
|
||||
let encrypted = encrypt_cloud_api(&serde_json::to_vec(&Value::Object(body))?)?;
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
CONTENT_TYPE,
|
||||
HeaderValue::from_static("application/x-www-form-urlencoded"),
|
||||
);
|
||||
headers.insert("gaen1", HeaderValue::from_static(GAEN1));
|
||||
headers.insert("charset", HeaderValue::from_static("utf-8"));
|
||||
let response = self
|
||||
.http
|
||||
.post(format!("{}{}", self.base_url, endpoint))
|
||||
.headers(headers)
|
||||
.body(encrypted)
|
||||
.send()
|
||||
.await
|
||||
.context("cannot connect to GREE Cloud")?;
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
bail!("GREE Cloud API returned HTTP {status}");
|
||||
}
|
||||
let envelope: Value = response
|
||||
.json()
|
||||
.await
|
||||
.context("invalid GREE Cloud API envelope")?;
|
||||
let encrypted_response = envelope
|
||||
.get("enRes")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| anyhow!("GREE Cloud response has no enRes field"))?;
|
||||
let decrypted = decrypt_v1(API_AES_KEY, encrypted_response)
|
||||
.context("cannot decrypt GREE Cloud response")?;
|
||||
serde_json::from_slice(&decrypted).context("invalid decrypted GREE Cloud JSON")
|
||||
}
|
||||
}
|
||||
|
||||
fn filter_duplicate_devices(devices: Vec<CloudDeviceInfo>) -> Vec<CloudDeviceInfo> {
|
||||
let mut groups: HashMap<String, Vec<CloudDeviceInfo>> = HashMap::new();
|
||||
for device in devices {
|
||||
groups.entry(device.key.clone()).or_default().push(device);
|
||||
}
|
||||
let mut filtered = Vec::new();
|
||||
for mut group in groups.into_values() {
|
||||
if group.len() == 1 {
|
||||
filtered.push(group.remove(0));
|
||||
continue;
|
||||
}
|
||||
let preferred: Vec<_> = group
|
||||
.iter()
|
||||
.filter(|device| device.mac.len() > 12 && device.mac.ends_with("00"))
|
||||
.cloned()
|
||||
.collect();
|
||||
if preferred.is_empty() {
|
||||
filtered.extend(group);
|
||||
} else {
|
||||
filtered.extend(preferred);
|
||||
}
|
||||
}
|
||||
filtered.sort_by(|a, b| a.name.to_ascii_lowercase().cmp(&b.name.to_ascii_lowercase()));
|
||||
filtered
|
||||
}
|
||||
|
||||
fn optional_trimmed(value: Option<&Value>) -> Option<String> {
|
||||
value
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
fn value_i64(value: Option<&Value>) -> Option<i64> {
|
||||
value.and_then(|value| {
|
||||
value
|
||||
.as_i64()
|
||||
.or_else(|| value.as_u64().and_then(|v| i64::try_from(v).ok()))
|
||||
.or_else(|| value.as_str().and_then(|v| v.parse::<i64>().ok()))
|
||||
})
|
||||
}
|
||||
|
||||
fn value_bool(value: &Value) -> bool {
|
||||
value
|
||||
.as_bool()
|
||||
.or_else(|| value.as_i64().map(|v| v != 0))
|
||||
.or_else(|| {
|
||||
value
|
||||
.as_str()
|
||||
.map(|v| !matches!(v.trim().to_ascii_lowercase().as_str(), "0" | "false" | "off" | ""))
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn python_string(value: &Value) -> String {
|
||||
match value {
|
||||
Value::String(v) => v.clone(),
|
||||
Value::Bool(true) => "True".into(),
|
||||
Value::Bool(false) => "False".into(),
|
||||
Value::Null => "None".into(),
|
||||
Value::Number(v) => v.to_string(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn encrypt_cloud_api(plaintext: &[u8]) -> Result<String> {
|
||||
let key = API_AES_KEY.as_bytes();
|
||||
let cipher = Aes128::new_from_slice(key).map_err(|_| anyhow!("invalid cloud AES key"))?;
|
||||
let pad = 16 - (plaintext.len() % 16);
|
||||
let mut data = Vec::with_capacity(plaintext.len() + pad);
|
||||
data.extend_from_slice(plaintext);
|
||||
data.extend(std::iter::repeat(pad as u8).take(pad));
|
||||
for block in data.chunks_exact_mut(16) {
|
||||
cipher.encrypt_block(GenericArray::from_mut_slice(block));
|
||||
}
|
||||
Ok(STANDARD.encode(data))
|
||||
}
|
||||
|
||||
// Small self-contained MD5 implementation avoids introducing another package/lockfile dependency.
|
||||
fn md5_hex(input: &str) -> String {
|
||||
let digest = md5(input.as_bytes());
|
||||
digest.iter().map(|byte| format!("{byte:02x}")).collect()
|
||||
}
|
||||
|
||||
fn md5(input: &[u8]) -> [u8; 16] {
|
||||
const S: [u32; 64] = [
|
||||
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9,
|
||||
14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4,
|
||||
11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
|
||||
];
|
||||
const K: [u32; 64] = [
|
||||
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613,
|
||||
0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,
|
||||
0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,
|
||||
0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
|
||||
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
|
||||
0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,
|
||||
0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244,
|
||||
0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
|
||||
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,
|
||||
0xeb86d391,
|
||||
];
|
||||
|
||||
let bit_len = (input.len() as u64).wrapping_mul(8);
|
||||
let mut message = input.to_vec();
|
||||
message.push(0x80);
|
||||
while message.len() % 64 != 56 {
|
||||
message.push(0);
|
||||
}
|
||||
message.extend_from_slice(&bit_len.to_le_bytes());
|
||||
|
||||
let mut a0 = 0x67452301u32;
|
||||
let mut b0 = 0xefcdab89u32;
|
||||
let mut c0 = 0x98badcfeu32;
|
||||
let mut d0 = 0x10325476u32;
|
||||
|
||||
for chunk in message.chunks_exact(64) {
|
||||
let mut m = [0u32; 16];
|
||||
for (index, word) in m.iter_mut().enumerate() {
|
||||
let start = index * 4;
|
||||
*word = u32::from_le_bytes([
|
||||
chunk[start],
|
||||
chunk[start + 1],
|
||||
chunk[start + 2],
|
||||
chunk[start + 3],
|
||||
]);
|
||||
}
|
||||
let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
|
||||
for i in 0..64 {
|
||||
let (f, g) = match i {
|
||||
0..=15 => ((b & c) | ((!b) & d), i),
|
||||
16..=31 => ((d & b) | ((!d) & c), (5 * i + 1) % 16),
|
||||
32..=47 => (b ^ c ^ d, (3 * i + 5) % 16),
|
||||
_ => (c ^ (b | (!d)), (7 * i) % 16),
|
||||
};
|
||||
let next = a
|
||||
.wrapping_add(f)
|
||||
.wrapping_add(K[i])
|
||||
.wrapping_add(m[g]);
|
||||
a = d;
|
||||
d = c;
|
||||
c = b;
|
||||
b = b.wrapping_add(next.rotate_left(S[i]));
|
||||
}
|
||||
a0 = a0.wrapping_add(a);
|
||||
b0 = b0.wrapping_add(b);
|
||||
c0 = c0.wrapping_add(c);
|
||||
d0 = d0.wrapping_add(d);
|
||||
}
|
||||
let mut output = [0u8; 16];
|
||||
output[0..4].copy_from_slice(&a0.to_le_bytes());
|
||||
output[4..8].copy_from_slice(&b0.to_le_bytes());
|
||||
output[8..12].copy_from_slice(&c0.to_le_bytes());
|
||||
output[12..16].copy_from_slice(&d0.to_le_bytes());
|
||||
output
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn md5_matches_standard_vectors() {
|
||||
assert_eq!(md5_hex(""), "d41d8cd98f00b204e9800998ecf8427e");
|
||||
assert_eq!(md5_hex("abc"), "900150983cd24fb0d6963f7d28e17f72");
|
||||
assert_eq!(
|
||||
md5_hex("The quick brown fox jumps over the lazy dog"),
|
||||
"9e107d9d372bb6826bd81d3542a419d6"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parent_mac_matches_cloud_reference() {
|
||||
assert_eq!(parent_mac("AABBCCDDEEFF00"), "AABBCCDDEEFF");
|
||||
assert_eq!(parent_mac("AABBCCDDEEFF"), "AABBCCDDEEFF");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,525 @@
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
sync::{
|
||||
atomic::{AtomicBool, AtomicU16, AtomicU64, Ordering},
|
||||
Arc,
|
||||
},
|
||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
|
||||
net::TcpStream,
|
||||
sync::{broadcast, mpsc},
|
||||
time::{interval, timeout},
|
||||
};
|
||||
use tokio_rustls::{rustls, TlsConnector};
|
||||
use tokio_rustls::rustls::pki_types::ServerName;
|
||||
|
||||
pub const MQTT_PORT: u16 = 1984;
|
||||
pub const MQTT_KEEPALIVE_SECONDS: u16 = 60;
|
||||
const MQTT_QUEUE_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
const MQTT_WRITE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const MQTT_DISCONNECT_TIMEOUT: Duration = Duration::from_millis(750);
|
||||
|
||||
pub fn broker_for_region(region: &str) -> Option<&'static str> {
|
||||
match region {
|
||||
"Australia" => Some("mqtt-au.gree.com"),
|
||||
// greeclimate 1.2.1 regional broker mapping.
|
||||
"China Mainland" => Some("mqtt-cn.gree.com"),
|
||||
"East South Asia" => Some("mqtt-as.gree.com"),
|
||||
"Europe" => Some("mqtt-eu.gree.com"),
|
||||
"India" => Some("mqtt-in.gree.com"),
|
||||
"Latin American" => Some("mqtt-la.gree.com"),
|
||||
"Middle East" => Some("mqtt-me.gree.com"),
|
||||
"North American" => Some("mqtt-na.gree.com"),
|
||||
"Russia" => Some("mqtt-ru.gree.com"),
|
||||
"South American" => Some("mqtt-sa.gree.com"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MqttDeviceEnvelope {
|
||||
#[serde(default)]
|
||||
pub cid: String,
|
||||
#[serde(default)]
|
||||
pub i: i64,
|
||||
#[serde(default)]
|
||||
pub pack: String,
|
||||
#[serde(default)]
|
||||
pub t: String,
|
||||
#[serde(default)]
|
||||
pub tcid: String,
|
||||
#[serde(default)]
|
||||
pub uid: serde_json::Value,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tag: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub ts: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum MqttEvent {
|
||||
Message { topic: String, payload: Vec<u8> },
|
||||
/// Broker-level traffic such as SUBACK/PUBACK/PINGRESP. This proves the MQTT
|
||||
/// session is alive without being mistaken for a response from the HVAC unit.
|
||||
Traffic { kind: &'static str },
|
||||
Disconnected { reason: String },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum WireCommand {
|
||||
Subscribe(Vec<String>),
|
||||
Publish { topic: String, payload: Vec<u8> },
|
||||
Raw(Vec<u8>),
|
||||
Ping,
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MqttConnection {
|
||||
tx: mpsc::Sender<WireCommand>,
|
||||
connected: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl MqttConnection {
|
||||
pub async fn connect(
|
||||
host: &str,
|
||||
port: u16,
|
||||
user_id: i64,
|
||||
token: &str,
|
||||
connect_timeout: Duration,
|
||||
events: broadcast::Sender<MqttEvent>,
|
||||
) -> Result<Self> {
|
||||
let tcp = timeout(connect_timeout, TcpStream::connect((host, port)))
|
||||
.await
|
||||
.context("GREE Cloud MQTT TCP connect timed out")?
|
||||
.with_context(|| format!("cannot connect to GREE Cloud MQTT {host}:{port}"))?;
|
||||
tcp.set_nodelay(true).ok();
|
||||
|
||||
// Do not inherit the reference library's CERT_NONE workaround: certificate and
|
||||
// hostname verification are intentionally enabled here.
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||
let tls_config = rustls::ClientConfig::builder()
|
||||
.with_root_certificates(roots)
|
||||
.with_no_client_auth();
|
||||
let connector = TlsConnector::from(Arc::new(tls_config));
|
||||
let server_name = ServerName::try_from(host.to_string())
|
||||
.map_err(|_| anyhow!("invalid GREE Cloud MQTT hostname"))?;
|
||||
let mut stream = timeout(connect_timeout, connector.connect(server_name, tcp))
|
||||
.await
|
||||
.context("GREE Cloud MQTT TLS handshake timed out")?
|
||||
.context("GREE Cloud MQTT TLS handshake failed")?;
|
||||
|
||||
let client_id = format!("app_{:016x}", rand::random::<u64>());
|
||||
let connect_packet = encode_connect(
|
||||
&client_id,
|
||||
&user_id.to_string(),
|
||||
token,
|
||||
MQTT_KEEPALIVE_SECONDS,
|
||||
)?;
|
||||
timeout(connect_timeout, stream.write_all(&connect_packet))
|
||||
.await
|
||||
.context("GREE Cloud MQTT CONNECT write timed out")??;
|
||||
timeout(connect_timeout, stream.flush())
|
||||
.await
|
||||
.context("GREE Cloud MQTT CONNECT flush timed out")??;
|
||||
let (packet_type, payload) = timeout(connect_timeout, read_packet(&mut stream))
|
||||
.await
|
||||
.context("GREE Cloud MQTT CONNACK timed out")??;
|
||||
if packet_type >> 4 != 2 || payload.len() != 2 {
|
||||
bail!("invalid GREE Cloud MQTT CONNACK");
|
||||
}
|
||||
if payload[1] != 0 {
|
||||
let reason = match payload[1] {
|
||||
1 => "unacceptable protocol version",
|
||||
2 => "identifier rejected",
|
||||
3 => "server unavailable",
|
||||
4 => "invalid username/password",
|
||||
5 => "not authorized",
|
||||
_ => "unknown broker error",
|
||||
};
|
||||
bail!("GREE Cloud MQTT authentication/connect rejected: {reason}");
|
||||
}
|
||||
|
||||
let (reader, writer) = tokio::io::split(stream);
|
||||
let (tx, rx) = mpsc::channel(64);
|
||||
let connected = Arc::new(AtomicBool::new(true));
|
||||
let packet_ids = Arc::new(AtomicU16::new(1));
|
||||
let last_rx_ms = Arc::new(AtomicU64::new(unix_millis()));
|
||||
spawn_writer(
|
||||
writer,
|
||||
rx,
|
||||
connected.clone(),
|
||||
events.clone(),
|
||||
packet_ids,
|
||||
);
|
||||
spawn_reader(
|
||||
reader,
|
||||
tx.clone(),
|
||||
connected.clone(),
|
||||
events.clone(),
|
||||
last_rx_ms.clone(),
|
||||
);
|
||||
spawn_keepalive(tx.clone(), connected.clone(), events.clone(), last_rx_ms);
|
||||
|
||||
Ok(Self {
|
||||
tx,
|
||||
connected,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_connected(&self) -> bool {
|
||||
self.connected.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub async fn subscribe_device(&self, parent_mac: &str) -> Result<()> {
|
||||
if !self.is_connected() {
|
||||
bail!("GREE Cloud MQTT is not connected");
|
||||
}
|
||||
let topics = [
|
||||
format!("response/{parent_mac}/#"),
|
||||
format!("status/{parent_mac}/#"),
|
||||
format!("connect/{parent_mac}"),
|
||||
];
|
||||
// Match the reference client: one QoS1 SUBSCRIBE per topic. This is slightly more
|
||||
// verbose than a multi-filter packet but avoids broker-specific handling differences.
|
||||
for topic in topics {
|
||||
timeout(
|
||||
MQTT_QUEUE_TIMEOUT,
|
||||
self.tx.send(WireCommand::Subscribe(vec![topic])),
|
||||
)
|
||||
.await
|
||||
.context("GREE Cloud MQTT subscribe queue timed out")?
|
||||
.map_err(|_| anyhow!("GREE Cloud MQTT writer stopped"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn publish(&self, topic: String, payload: Vec<u8>) -> Result<()> {
|
||||
if !self.is_connected() {
|
||||
bail!("GREE Cloud MQTT is not connected");
|
||||
}
|
||||
timeout(
|
||||
MQTT_QUEUE_TIMEOUT,
|
||||
self.tx.send(WireCommand::Publish { topic, payload }),
|
||||
)
|
||||
.await
|
||||
.context("GREE Cloud MQTT publish queue timed out")?
|
||||
.map_err(|_| anyhow!("GREE Cloud MQTT writer stopped"))
|
||||
}
|
||||
|
||||
pub async fn disconnect(&self) {
|
||||
// Mark disconnected first so no new work can enter the queue while shutdown is in
|
||||
// progress. A wedged/full writer queue must never prevent process termination.
|
||||
self.connected.store(false, Ordering::Release);
|
||||
let _ = timeout(
|
||||
MQTT_DISCONNECT_TIMEOUT,
|
||||
self.tx.send(WireCommand::Disconnect),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_keepalive(
|
||||
tx: mpsc::Sender<WireCommand>,
|
||||
connected: Arc<AtomicBool>,
|
||||
events: broadcast::Sender<MqttEvent>,
|
||||
last_rx_ms: Arc<AtomicU64>,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
let mut tick = interval(Duration::from_secs(30));
|
||||
tick.tick().await;
|
||||
while connected.load(Ordering::Acquire) {
|
||||
tick.tick().await;
|
||||
let idle_ms = unix_millis().saturating_sub(last_rx_ms.load(Ordering::Acquire));
|
||||
if idle_ms > 90_000 {
|
||||
mark_disconnected(
|
||||
&connected,
|
||||
&events,
|
||||
"MQTT heartbeat timed out waiting for broker traffic".into(),
|
||||
);
|
||||
let _ = timeout(MQTT_DISCONNECT_TIMEOUT, tx.send(WireCommand::Disconnect)).await;
|
||||
break;
|
||||
}
|
||||
match timeout(MQTT_QUEUE_TIMEOUT, tx.send(WireCommand::Ping)).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(_)) => {
|
||||
mark_disconnected(&connected, &events, "MQTT writer stopped".into());
|
||||
break;
|
||||
}
|
||||
Err(_) => {
|
||||
mark_disconnected(&connected, &events, "MQTT ping queue timed out".into());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn_writer<W>(
|
||||
mut writer: W,
|
||||
mut rx: mpsc::Receiver<WireCommand>,
|
||||
connected: Arc<AtomicBool>,
|
||||
events: broadcast::Sender<MqttEvent>,
|
||||
packet_ids: Arc<AtomicU16>,
|
||||
) where
|
||||
W: AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
tokio::spawn(async move {
|
||||
while let Some(command) = rx.recv().await {
|
||||
let result = match command {
|
||||
WireCommand::Subscribe(topics) => {
|
||||
let packet_id = next_packet_id(&packet_ids);
|
||||
encode_subscribe(packet_id, &topics)
|
||||
}
|
||||
WireCommand::Publish { topic, payload } => {
|
||||
let packet_id = next_packet_id(&packet_ids);
|
||||
encode_publish(packet_id, &topic, &payload)
|
||||
}
|
||||
WireCommand::Raw(packet) => Ok(packet),
|
||||
WireCommand::Ping => Ok(vec![0xC0, 0x00]),
|
||||
WireCommand::Disconnect => {
|
||||
let _ = timeout(MQTT_DISCONNECT_TIMEOUT, writer.write_all(&[0xE0, 0x00])).await;
|
||||
let _ = timeout(MQTT_DISCONNECT_TIMEOUT, writer.flush()).await;
|
||||
connected.store(false, Ordering::Release);
|
||||
break;
|
||||
}
|
||||
};
|
||||
let packet = match result {
|
||||
Ok(packet) => packet,
|
||||
Err(err) => {
|
||||
mark_disconnected(&connected, &events, err.to_string());
|
||||
break;
|
||||
}
|
||||
};
|
||||
match timeout(MQTT_WRITE_TIMEOUT, writer.write_all(&packet)).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(err)) => {
|
||||
mark_disconnected(&connected, &events, format!("MQTT write failed: {err}"));
|
||||
break;
|
||||
}
|
||||
Err(_) => {
|
||||
mark_disconnected(&connected, &events, "MQTT write timed out".into());
|
||||
break;
|
||||
}
|
||||
}
|
||||
match timeout(MQTT_WRITE_TIMEOUT, writer.flush()).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(err)) => {
|
||||
mark_disconnected(&connected, &events, format!("MQTT flush failed: {err}"));
|
||||
break;
|
||||
}
|
||||
Err(_) => {
|
||||
mark_disconnected(&connected, &events, "MQTT flush timed out".into());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn_reader<R>(
|
||||
mut reader: R,
|
||||
tx: mpsc::Sender<WireCommand>,
|
||||
connected: Arc<AtomicBool>,
|
||||
events: broadcast::Sender<MqttEvent>,
|
||||
last_rx_ms: Arc<AtomicU64>,
|
||||
) where
|
||||
R: AsyncRead + Unpin + Send + 'static,
|
||||
{
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
match read_packet(&mut reader).await {
|
||||
Ok((header, payload)) => {
|
||||
last_rx_ms.store(unix_millis(), Ordering::Release);
|
||||
match header >> 4 {
|
||||
3 => {
|
||||
if let Err(err) = handle_publish(header, &payload, &tx, &events).await {
|
||||
tracing::warn!(error=?err, "invalid GREE Cloud MQTT PUBLISH");
|
||||
}
|
||||
}
|
||||
9 => { let _ = events.send(MqttEvent::Traffic { kind: "SUBACK" }); }
|
||||
4 => { let _ = events.send(MqttEvent::Traffic { kind: "PUBACK" }); }
|
||||
13 => { let _ = events.send(MqttEvent::Traffic { kind: "PINGRESP" }); }
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
mark_disconnected(&connected, &events, format!("MQTT read failed: {err}"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn handle_publish(
|
||||
header: u8,
|
||||
payload: &[u8],
|
||||
tx: &mpsc::Sender<WireCommand>,
|
||||
events: &broadcast::Sender<MqttEvent>,
|
||||
) -> Result<()> {
|
||||
if payload.len() < 2 {
|
||||
bail!("short MQTT publish packet");
|
||||
}
|
||||
let topic_len = u16::from_be_bytes([payload[0], payload[1]]) as usize;
|
||||
if payload.len() < 2 + topic_len {
|
||||
bail!("truncated MQTT publish topic");
|
||||
}
|
||||
let topic = std::str::from_utf8(&payload[2..2 + topic_len])?.to_string();
|
||||
let qos = (header >> 1) & 0x03;
|
||||
let mut offset = 2 + topic_len;
|
||||
if qos > 0 {
|
||||
if payload.len() < offset + 2 {
|
||||
bail!("truncated MQTT publish packet id");
|
||||
}
|
||||
let packet_id = u16::from_be_bytes([payload[offset], payload[offset + 1]]);
|
||||
offset += 2;
|
||||
if qos == 1 {
|
||||
// MQTT QoS1 requires a PUBACK for every incoming publish. Send the raw four-byte
|
||||
// acknowledgement through the single writer task so frame writes never interleave.
|
||||
let ack = vec![0x40, 0x02, (packet_id >> 8) as u8, packet_id as u8];
|
||||
send_raw_ack(tx, ack).await?;
|
||||
}
|
||||
}
|
||||
let body = payload[offset..].to_vec();
|
||||
let _ = events.send(MqttEvent::Message { topic, payload: body });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// MQTT QoS1 delivery requires PUBACK. To keep WireCommand's public operations minimal, encode
|
||||
// acknowledgement as a synthetic command handled by a reserved topic marker.
|
||||
async fn send_raw_ack(tx: &mpsc::Sender<WireCommand>, ack: Vec<u8>) -> Result<()> {
|
||||
timeout(MQTT_QUEUE_TIMEOUT, tx.send(WireCommand::Raw(ack)))
|
||||
.await
|
||||
.context("GREE Cloud MQTT ACK queue timed out")?
|
||||
.map_err(|_| anyhow!("GREE Cloud MQTT writer stopped"))
|
||||
}
|
||||
|
||||
fn unix_millis() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis()
|
||||
.min(u128::from(u64::MAX)) as u64
|
||||
}
|
||||
|
||||
fn next_packet_id(ids: &AtomicU16) -> u16 {
|
||||
let id = ids.fetch_add(1, Ordering::Relaxed);
|
||||
if id == 0 { 1 } else { id }
|
||||
}
|
||||
|
||||
fn mark_disconnected(
|
||||
connected: &AtomicBool,
|
||||
events: &broadcast::Sender<MqttEvent>,
|
||||
reason: String,
|
||||
) {
|
||||
if connected.swap(false, Ordering::AcqRel) {
|
||||
let _ = events.send(MqttEvent::Disconnected { reason });
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_connect(client_id: &str, username: &str, password: &str, keepalive: u16) -> Result<Vec<u8>> {
|
||||
let mut body = Vec::new();
|
||||
push_utf8(&mut body, "MQTT")?;
|
||||
body.push(4); // MQTT 3.1.1
|
||||
body.push(0xC2); // username + password + clean session
|
||||
body.extend_from_slice(&keepalive.to_be_bytes());
|
||||
push_utf8(&mut body, client_id)?;
|
||||
push_utf8(&mut body, username)?;
|
||||
push_utf8(&mut body, password)?;
|
||||
frame(0x10, body)
|
||||
}
|
||||
|
||||
fn encode_subscribe(packet_id: u16, topics: &[String]) -> Result<Vec<u8>> {
|
||||
let mut body = Vec::new();
|
||||
body.extend_from_slice(&packet_id.to_be_bytes());
|
||||
for topic in topics {
|
||||
push_utf8(&mut body, topic)?;
|
||||
body.push(1); // requested QoS 1
|
||||
}
|
||||
frame(0x82, body)
|
||||
}
|
||||
|
||||
fn encode_publish(packet_id: u16, topic: &str, payload: &[u8]) -> Result<Vec<u8>> {
|
||||
let mut body = Vec::new();
|
||||
push_utf8(&mut body, topic)?;
|
||||
body.extend_from_slice(&packet_id.to_be_bytes());
|
||||
body.extend_from_slice(payload);
|
||||
frame(0x32, body) // PUBLISH QoS1
|
||||
}
|
||||
|
||||
fn frame(header: u8, body: Vec<u8>) -> Result<Vec<u8>> {
|
||||
let mut out = Vec::with_capacity(body.len() + 5);
|
||||
out.push(header);
|
||||
encode_remaining_length(body.len(), &mut out)?;
|
||||
out.extend_from_slice(&body);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn push_utf8(out: &mut Vec<u8>, value: &str) -> Result<()> {
|
||||
let len = u16::try_from(value.as_bytes().len()).context("MQTT string is too long")?;
|
||||
out.extend_from_slice(&len.to_be_bytes());
|
||||
out.extend_from_slice(value.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn encode_remaining_length(mut len: usize, out: &mut Vec<u8>) -> Result<()> {
|
||||
if len > 268_435_455 {
|
||||
bail!("MQTT packet is too large");
|
||||
}
|
||||
loop {
|
||||
let mut digit = (len % 128) as u8;
|
||||
len /= 128;
|
||||
if len > 0 {
|
||||
digit |= 0x80;
|
||||
}
|
||||
out.push(digit);
|
||||
if len == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_packet<R: AsyncRead + Unpin>(reader: &mut R) -> Result<(u8, Vec<u8>)> {
|
||||
let header = reader.read_u8().await?;
|
||||
let mut multiplier = 1usize;
|
||||
let mut remaining = 0usize;
|
||||
for _ in 0..4 {
|
||||
let digit = reader.read_u8().await?;
|
||||
remaining = remaining
|
||||
.checked_add(((digit & 0x7f) as usize).saturating_mul(multiplier))
|
||||
.ok_or_else(|| anyhow!("invalid MQTT remaining length"))?;
|
||||
if digit & 0x80 == 0 {
|
||||
let mut payload = vec![0_u8; remaining];
|
||||
reader.read_exact(&mut payload).await?;
|
||||
return Ok((header, payload));
|
||||
}
|
||||
multiplier = multiplier.saturating_mul(128);
|
||||
}
|
||||
bail!("invalid MQTT remaining length encoding")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn mqtt_connect_uses_v311_and_credentials() {
|
||||
let packet = encode_connect("app_123", "42", "secret", 60).unwrap();
|
||||
assert_eq!(packet[0], 0x10);
|
||||
assert!(packet.windows(6).any(|w| w == b"\0\x04MQTT"));
|
||||
assert!(packet.windows(3).any(|w| w == b"\0\x0242"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_brokers_match_cloud_reference() {
|
||||
assert_eq!(broker_for_region("Europe"), Some("mqtt-eu.gree.com"));
|
||||
assert_eq!(broker_for_region("North American"), Some("mqtt-na.gree.com"));
|
||||
assert_eq!(broker_for_region("China Mainland"), Some("mqtt-cn.gree.com"));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
pub mod crypto;
|
||||
pub mod gree;
|
||||
pub mod gree_cloud;
|
||||
pub mod gree_cloud_mqtt;
|
||||
|
||||
pub use gree::{merge_discovered, GreeClient};
|
||||
|
||||
Reference in New Issue
Block a user