Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_pub_sub(self):
connection = self._test_connection()
received = Future()
def on_message(**kwargs):
received.set_result(kwargs)
# subscribe
subscribed, packet_id = connection.subscribe(self.TEST_TOPIC, QoS.AT_LEAST_ONCE, on_message)
suback = subscribed.result(TIMEOUT)
self.assertEqual(packet_id, suback['packet_id'])
self.assertEqual(self.TEST_TOPIC, suback['topic'])
self.assertIs(QoS.AT_LEAST_ONCE, suback['qos'])
# publish
published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
puback = published.result(TIMEOUT)
self.assertEqual(packet_id, puback['packet_id'])
# receive message
rcv = received.result(TIMEOUT)
self.assertEqual(self.TEST_TOPIC, rcv['topic'])
self.assertEqual(self.TEST_MSG, rcv['payload'])
# unsubscribe
unsubscribed, packet_id = connection.unsubscribe(self.TEST_TOPIC)
unsuback = unsubscribed.result(TIMEOUT)
self.assertEqual(packet_id, unsuback['packet_id'])
# disconnect
connection.disconnect().result(TIMEOUT)
def test_pub_sub(self):
connection = self._test_connection()
received = Future()
def on_message(**kwargs):
received.set_result(kwargs)
# subscribe
subscribed, packet_id = connection.subscribe(self.TEST_TOPIC, QoS.AT_LEAST_ONCE, on_message)
suback = subscribed.result(TIMEOUT)
self.assertEqual(packet_id, suback['packet_id'])
self.assertEqual(self.TEST_TOPIC, suback['topic'])
self.assertIs(QoS.AT_LEAST_ONCE, suback['qos'])
# publish
published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
puback = published.result(TIMEOUT)
self.assertEqual(packet_id, puback['packet_id'])
# receive message
rcv = received.result(TIMEOUT)
self.assertEqual(self.TEST_TOPIC, rcv['topic'])
self.assertEqual(self.TEST_MSG, rcv['payload'])
# unsubscribe
# This step is skipped if message is blank.
# This step loops forever if count was set to 0.
if args.message:
if args.count == 0:
print ("Sending messages until program killed")
else:
print ("Sending {} message(s)".format(args.count))
publish_count = 1
while (publish_count <= args.count) or (args.count == 0):
message = "{} [{}]".format(args.message, publish_count)
print("Publishing message to topic '{}': {}".format(args.topic, message))
mqtt_connection.publish(
topic=args.topic,
payload=message,
qos=mqtt.QoS.AT_LEAST_ONCE)
time.sleep(1)
publish_count += 1
# Wait for all messages to be received.
# This waits forever if count was set to 0.
if args.count != 0 and not received_all_event.is_set():
print("Waiting for all messages to be received...")
received_all_event.wait()
print("{} message(s) received.".format(received_count))
# Disconnect
print("Disconnecting...")
disconnect_future = mqtt_connection.disconnect()
disconnect_future.result()
print("Disconnected!")
except Exception as e:
print('Connection failed with exception {}'.format(e))
continue
exit('All connection attempts failed')
mqtt_connection = try_iot_endpoints()
if args.mode == 'both' or args.mode == 'subscribe':
def on_publish(topic, payload, **kwargs):
print('Publish received on topic {}'.format(topic))
print(payload)
subscribe_future, _ = mqtt_connection.subscribe(args.topic, QoS.AT_MOST_ONCE, on_publish)
subscribe_result = subscribe_future.result()
loop_count = 0
while loop_count < args.max_pub_ops:
if args.mode == 'both' or args.mode == 'publish':
message = {}
message['message'] = args.message
message['sequence'] = loop_count
messageJson = json.dumps(message)
pub_future, _ = mqtt_connection.publish(args.topic, messageJson, QoS.AT_MOST_ONCE)
pub_future.result()
print('Published topic {}: {}\n'.format(args.topic, messageJson))
loop_count += 1
time.sleep(1)
request=iotidentity.CreateCertificateFromCsrRequest(certificate_signing_request=csrPath),
qos=mqtt.QoS.AT_LEAST_ONCE)
publish_future.add_done_callback(on_publish_create_certificate_from_csr)
waitForCreateCertificateFromCsrResponse()
if createCertificateFromCsrResponse is None:
raise Exception('CreateCertificateFromCsr API did not succeed')
registerThingRequest = iotidentity.RegisterThingRequest(
template_name=args.templateName,
certificate_ownership_token=createCertificateFromCsrResponse.certificate_ownership_token,
parameters=json.loads(args.templateParameters))
print("Publishing to RegisterThing topic...")
registerthing_publish_future = identity_client.publish_register_thing(registerThingRequest, mqtt.QoS.AT_LEAST_ONCE)
registerthing_publish_future.add_done_callback(on_publish_register_thing)
waitForRegisterThingResponse()
exit("success")
except Exception as e:
exit(e)
# Wait for the sample to finish
is_sample_done.wait()
def _try_qos(qos_value):
"""Return None if the value cannot be converted to Qos (ex: 0x80 subscribe failure)"""
try:
return QoS(qos_value)
except Exception:
return None
if error_code:
future.set_exception(awscrt.exceptions.from_code(error_code))
else:
qos = _try_qos(qos)
if qos is None:
future.set_exception(SubscribeError(topic))
else:
future.set_result(dict(
packet_id=packet_id,
topic=topic,
qos=qos,
))
try:
assert callable(callback) or callback is None
assert isinstance(qos, QoS)
packet_id = _awscrt.mqtt_client_connection_subscribe(
self._binding, topic, qos.value, callback_wrapper, suback)
except Exception as e:
future.set_exception(e)
return future, packet_id
def on_publish(topic, payload, **kwargs):
print('Publish received on topic {}'.format(topic))
print(payload)
subscribe_future, _ = mqtt_connection.subscribe(args.topic, QoS.AT_MOST_ONCE, on_publish)
subscribe_result = subscribe_future.result()
loop_count = 0
while loop_count < args.max_pub_ops:
if args.mode == 'both' or args.mode == 'publish':
message = {}
message['message'] = args.message
message['sequence'] = loop_count
messageJson = json.dumps(message)
pub_future, _ = mqtt_connection.publish(args.topic, messageJson, QoS.AT_MOST_ONCE)
pub_future.result()
print('Published topic {}: {}\n'.format(args.topic, messageJson))
loop_count += 1
time.sleep(1)
print("Local value is already '{}'.".format(value))
print("Enter desired value: ") # remind user they can input new values
return
print("Changed local shadow value to '{}'.".format(value))
locked_data.shadow_value = value
print("Updating reported shadow value to '{}'...".format(value))
request = iotshadow.UpdateShadowRequest(
thing_name=thing_name,
state=iotshadow.ShadowState(
reported={ shadow_property: value },
desired={ shadow_property: value },
)
)
future = shadow_client.publish_update_shadow(request, mqtt.QoS.AT_LEAST_ONCE)
future.add_done_callback(on_publish_update_shadow)