我已经编写了一个代码,用于在python中使用旧的API客户端库在Google Cloud Platform上实现pub / sub。我需要从pubsub服务器向MQTT客户端发布消息。我写的代码 -
PRIVATE_KEY_JSON = 'My First Project-ac2738b37b2b.json'
API_SCOPES = ['https://www.googleapis.com/auth/pubsub']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
PRIVATE_KEY_JSON, scopes=API_SCOPES)
pubsub = discovery.build('pubsub', 'v1', credentials=credentials)
PROJECT_NAME = 'sonorous-treat-167211'
PROJECT = 'projects/{0}'.format(PROJECT_NAME)
topics = pubsub.projects().topics().list(project=PROJECT)
topic_name = "to-gateway"
sub_name = "my_test2"
response = pubsub.projects().topics().publish(topic='{0}/topics/{1}'.format(PROJECT, topic_name), body={ "messages" :[{ "attributes" : {"key":"topic","value" : "gateway-command/foo4",}, "data" : "HIII",},], }).execute()
#response = pubsub.projects().subscriptions().create(name ='{0}/subscriptions/{1}'.format(PROJECT, sub_name),body = { "ackDeadlineSeconds": 42, "topic" : '{0}/topics/{1}'.format(PROJECT, topic_name) , "name" : '{0}/subscriptions/{1}'.format(PROJECT, sub_name), }).execute()
##response = pubsub.projects().topics().create(name ='{0}/topics/{1}'.format(PROJECT, topic_name),body = {}).execute()
string = response
@app.route('/')
def form():
#string1 = list_topics()
#publish_message("projects/sonorous-treat-167211/topics/to-gateway", "HII")
return render_template('submitted_form.html',mydict = string)
目前我的代码中没有出现任何错误。但在发布消息后,我没有收到客户端的消息。我没有得到问题所在。可能是pub / sub api无法与IOT适配器交互。我也使用了新的谷歌云发布/子库(目前处于alpha版本),但遇到了同样的问题。
以下是publish() -
的文档publish(topic=None, body=*, x__xgafv=None)
Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic
does not exist. The message payload must not be empty; it must contain
either a non-empty data field, or at least one attribute.
Args:
topic: string, The messages in the request will be published on this topic.
Format is `projects/{project}/topics/{topic}`. (required)
body: object, The request body. (required)
The object takes the form of:
{ # Request for the Publish method.
"messages": [ # The messages to publish.
{ # A message data and its attributes. The message payload must not be empty;
# it must contain either a non-empty data field, or at least one attribute.
"attributes": { # Optional attributes for this message.
"a_key": "A String",
},
"data": "A String", # The message payload.
"publishTime": "A String", # The time at which the message was published, populated by the server when
# it receives the `Publish` call. It must not be populated by the
# publisher in a `Publish` call.
"messageId": "A String", # ID of this message, assigned by the server when the message is published.
# Guaranteed to be unique within the topic. This value may be read by a
# subscriber that receives a `PubsubMessage` via a `Pull` call or a push
# delivery. It must not be populated by the publisher in a `Publish` call.
},
],
}