要将状态报告给Home Graph,您必须:
JSON
获得有效 的 签名的JWT令牌 强> :
credentials = service_account.Credentials.from_service_account_file(service_account_file, scopes="https://www.googleapis.com/auth/homegraph") now = int(time.time()) expires = now + 3600 # One hour in seconds payload = { 'iat': now, 'exp': expires, 'aud': "https://accounts.google.com/o/oauth2/token", 'scope': SCOPE, 'iss': credentials.service_account_email } signed_jwt = google.auth.jwt.encode(credentials.signer, payload)
获得有效 的 访问令牌 强> :
headers = {"Authorization": "Bearer {}".format(signed_jwt.decode("utf-8")), "Content-Type": "application/x-www-form-urlencoded"} data = {"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": signed_jwt} access_token = requests.post("https://accounts.google.com/o/oauth2/token", data=data, headers=headers).get("access_token")
发送报告的状态:
headers = {"Authorization": "Bearer {}".format(access_token), "X-GFE-SSL": "yes"} data = {"requestId": request_id, "agent_user_id": agent_user_id, "payload": {"devices": {"states": states}}} requests.post("https://homegraph.googleapis.com/v1/devices:reportStateAndNotification", data=json.dumps(data), headers=headers)
的 注意 强> :为了工作这些片段需要 import google.auth.jwt , from google.oauth2 import service_account 和 import requests 从 google-auth , google-auth-httplib2 和 requests 包。
import google.auth.jwt
from google.oauth2 import service_account
import requests
google-auth
google-auth-httplib2
requests