如何从谷歌云功能向物联网设备发送发送命令

时间:2019-05-17 14:17:52

标签: google-cloud-functions iot publish-subscribe google-cloud-iot

我正在尝试使用python编写的google cloud函数使用google cloudiot api。向Cloud IoT API发出http请求时,出现403“禁止”错误。我已使用具有完全权限的服务帐户进行了身份验证。

导入操作系统 从烧瓶导入json 导入base64

导入firebase_admin 从firebase_admin导入数据库

导入googleapiclient 从googleapiclient导入发现 从google.oauth2导入service_account

default_app = firebase_admin.initialize_app(options = {'databaseURL':'https://lucid-v2-1.firebaseio.com/'})

def get_client(service_account_json):     “”“通过发现IoT API并创建一个授权API客户端     使用服务帐户凭据JSON的服务对象。“”“     api_scopes = ['https://www.googleapis.com/auth/cloud-platform','https://www.googleapis.com/auth/cloudiot']     api_version ='v1'     Discovery_api ='https://cloudiot.googleapis.com/ $发现/休息'     service_name ='cloudiotcore'

#credentials = service_account.Credentials.from_service_account_file(service_account_json)
credentials = service_account.Credentials.from_service_account_file(service_account_json)
scoped_credentials = credentials.with_scopes(api_scopes)

discovery_url = '{}?version={}'.format(
        discovery_api, api_version)

print(credentials.service_account_email)

return discovery.build(
        service_name,
        api_version,
        discoveryServiceUrl=discovery_url,
        credentials=scoped_credentials,
        cache_discovery=False)

def request_posted(事件,上下文):

print(os.environ)
#
client = get_client(os.environ.get('GOOGLE_APPLICATION_CREDENTIALS'))
"""Triggered by a change to a Firebase RTDB reference.
Args:
     event (dict): Event payload.
     context (google.cloud.functions.Context): Metadata for the event.

"""

print(client)

resources = context.resource.split('/')
request_id = resources[-1]
request_values = event['delta']

response_ref = db.reference("experience_channel/responses/" + str(request_id))
response_ref.update({"ack":True})

db.reference("experience_channel/experience_data")

device_id = "2593786060198708"
project_id = "lucid-iOS-v2-1"
cloud_region = "us-central1"
registry_id = "Lucid_IoT_Registry"
device_path = 'projects/{}/locations/{}/registries/{}/devices/{}'.format(project_id, cloud_region, registry_id, device_id)

print(device_path)
epoch_length = 20

message_contents = {
"experience_id":request_id,
"epoch_length":epoch_length,
"experience_length":request_values['length']
}

message_json = json.dumps(message_contents)

test_body = "test_body"

command_body = {
    'binaryData': base64.urlsafe_b64encode(
        message_json.encode('utf-8')).decode('ascii'),
    'subfolder' : 'commands'
}

#client.projects().locations().registries().testIamPermissions(resource = )


print(client.projects(
    ).locations().registries(
    ).devices().list(parent = "projects/lucid-iOS-v2-1/locations/us-central1/registries/Lucid_IoT_Registry").execute())

resp = client.projects(
    ).locations().registries(
    ).devices().sendCommandToDevice(
    name = device_path, body = command_body).execute()

print(resp)

return resp

0 个答案:

没有答案