Created
October 28, 2016 18:35
-
-
Save tikluganguly/30cf34143ff47356df04d56c20e5c946 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import can | |
import iothub_client | |
from iothub_client import * | |
from can.interfaces.interface import Bus | |
#global vars | |
message_timeout = 10000 | |
protocol = IoTHubTransportProvider.AMQP | |
connection_string = "[add your connection string here]" | |
send_callbacks = 0 | |
message_count = 0 | |
def iothub_client_init(): | |
iotHubClient = IoTHubClient(connection_string, protocol) | |
iotHubClient.set_option("messageTimeout", message_timeout) | |
return iotHubClient | |
def send_confirmation_callback(message, result, user_context): | |
global send_callbacks | |
print("Confirmation[%d] received for message with result = %s" %(user_context, result)) | |
send_callbacks += 1 | |
print(" Total calls confirmed: %d" % send_callbacks) | |
def get_message_id(msg): | |
id_string = '' | |
if msg.id_type: | |
# Extended arbitrationID | |
id_string = "{0:08x}".format(msg.arbitration_id) | |
else: | |
id_string = "{0:04x}".format(msg.arbitration_id) | |
return id_string | |
def get_data(msg): | |
data_val='' | |
data_strings = [] | |
if msg.data is not None: | |
for index in range(0, msg.dlc): | |
data_strings.append("{0:02x}".format(msg.data[index])) | |
if len(data_strings) > 0: | |
data_val = " ".join(data_strings).ljust(24, " ") | |
return data_val | |
if __name__ == '__main__': | |
try: | |
bus = Bus() | |
iotHubClient = iothub_client_init() | |
for msg in bus: | |
print(msg) | |
message_count += 1 | |
print("sending message [%d] with %s" % (message_count, msg)) | |
msg_txt = "messge [%d]" % message_count | |
message = IoTHubMessage(msg_txt) | |
prop_map = message.properties() | |
prop_map.add('Id',get_message_id(msg)) | |
prop_map.add('data', get_data(msg)) | |
iotHubClient.send_event_async(message, send_confirmation_callback, message_count) | |
status = iotHubClient.get_send_status() | |
print("Send status: %s" % status) | |
except IoTHubError as e: | |
bus.shutdown() | |
print("Unexpected error %s from IoTHub" % e) | |
except KeyboardInterrupt: | |
bus.shutdown() | |
print("IoTHubClient sample stopped") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment