def iothub_client_init(transport, device_name, device_key):
    # prepare iothub client with transport
    config = IoTHubConfig(PROTOCOL, device_name, device_key, "", IOTHUBNAME, IOTHUBSUFFIX, "")
    client = IoTHubClient(transport, config)

    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)

    client.set_connection_status_callback(connection_status_callback, CONNECTION_STATUS_CONTEXT)

    return client
def iothub_client_prov_hsm_sample_run():
    client = IoTHubClient(IOTHUB_URI, DEVICE_ID, SECURITY_TYPE, PROTOCOL)

    print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT )

    for message_counter in range(0, MESSAGE_COUNT):
        message = create_message(message_counter)

        client.send_event_async(message, send_confirmation_callback, message_counter)
        print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % message_counter )

    # Wait for Commands or exit
    print ( "IoTHubClient waiting for commands, press Ctrl-C to exit" )

    status_counter = 0
    while status_counter <= MESSAGE_COUNT:
        status = client.get_send_status()
        print ( "Send status: %s" % status )
        time.sleep(10)
        status_counter += 1
 def __init__(
         self,
         connection_string,
         protocol=IoTHubTransportProvider.MQTT):
     self.client_protocol = protocol
     self.client = IoTHubClient(connection_string, protocol)
     if protocol == IoTHubTransportProvider.HTTP:
         self.client.set_option("timeout", TIMEOUT)
         self.client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
     # set the time until a message times out
     self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
     # some embedded platforms need certificate information
     # self.set_certificates()
     self.client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
     self.client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT)
     self.client.set_device_method_callback(device_method_callback, METHOD_CONTEXT)
Example #4
0
def set_up_azure_connection(connection):
    # Create an IoT Hub client
    client = IoTHubClient(connection, PROTOCOL)
    return client
def run_e2e_devicemethod(iothub_connection_string):
    global DEVICE_METHOD_USER_CONTEXT
    global DEVICE_METHOD_NAME
    global DEVICE_METHOD_PAYLOAD
    global DEVICE_METHOD_TIMEOUT

    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        iothub_registry_manager = IoTHubRegistryManager(iothub_connection_string)
        new_device = iothub_registry_manager.create_device(device_id, primary_key, secondary_key, auth_method)

        device_connection_string = get_device_connection_string(iothub_registry_manager, IOTHUB_CONNECTION_STRING, device_id)


        device_client = IoTHubClient(device_connection_string, IoTHubTransportProvider.MQTT)
        assert isinstance(device_client, IoTHubClient), 'Invalid type returned!'
        assert device_client != None, "device_client is NULL"

        device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client.set_device_method_callback(device_method_callback, DEVICE_METHOD_USER_CONTEXT)

        ###########################################################################
        # IoTHubDeviceMethod

        # prepare
        # act
        iothub_device_method = IoTHubDeviceMethod(IOTHUB_CONNECTION_STRING)

        # verify
        assert iothub_device_method != None, "iothub_device_method is NULL"
        ###########################################################################

        # Wait before invoke...
        time.sleep(SLEEP_BEFORE_DEVICE_ACTION)

        ############################################################################
        # invoke
        
        # prepare
        # act
        response = iothub_device_method.invoke(device_id, DEVICE_METHOD_NAME, DEVICE_METHOD_PAYLOAD, DEVICE_METHOD_TIMEOUT)
        assert response != None, "response is NULL"
        assert isinstance(response, IoTHubDeviceMethodResponse), 'Invalid type returned!'

        # verify
        response_ok = response.payload.find(DEVICE_CLIENT_RESPONSE)
        assert response_ok > 0, "response does not contain " + DEVICE_CLIENT_RESPONSE
        assert response.status == 200, "response status is : " + response.status
        DEVICE_METHOD_EVENT.wait(DEVICE_METHOD_CALLBACK_TIMEOUT)
        assert DEVICE_CLIENT_RESPONSE.find(DEVICE_METHOD_RESPONSE_PREFIX) >= 0, "Timeout expired and device method has not been called!"
        ############################################################################

        print ( "" )
        retval = 0
    except Exception as e:
        print ( "" )
        print ("run_e2e_devicemethod() failed with exception: {0}".format(e))
        retval = 1
    finally:
        # clean-up
        iothub_registry_manager.delete_device(device_id)

    return retval
Example #6
0
class HubManager(object):
    def __init__(self,
                 connection_string,
                 protocol=IoTHubTransportProvider.MQTT):
        self.client_protocol = protocol
        self.client = IoTHubClient(connection_string, protocol)
        if protocol == IoTHubTransportProvider.HTTP:
            self.client.set_option("timeout", TIMEOUT)
            self.client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
        # some embedded platforms need certificate information
        # self.set_certificates()
        self.client.set_message_callback(receive_message_callback,
                                         RECEIVE_CONTEXT)
        self.client.set_device_twin_callback(device_twin_callback,
                                             TWIN_CONTEXT)
        self.client.set_device_method_callback(device_method_callback,
                                               METHOD_CONTEXT)

    def set_certificates(self):
        from iothub_client_cert import CERTIFICATES
        try:
            self.client.set_option("TrustedCerts", CERTIFICATES)
            print("set_option TrustedCerts successful")
        except IoTHubClientError as iothub_client_error:
            print("set_option TrustedCerts failed (%s)" % iothub_client_error)

    def send_event(self, event, properties, send_context):
        if not isinstance(event, IoTHubMessage):
            event = IoTHubMessage(bytearray(event, 'utf8'))

        if len(properties) > 0:
            prop_map = event.properties()
            for key in properties:
                prop_map.add_or_update(key, properties[key])

        self.client.send_event_async(event, send_confirmation_callback,
                                     send_context)

    def send_reported_state(self, reported_state, size, user_context):
        self.client.send_reported_state(reported_state, size,
                                        send_reported_state_callback,
                                        user_context)

    def upload_to_blob(self, destinationfilename, source, size, usercontext):
        self.client.upload_blob_async(destinationfilename, source, size,
                                      blob_upload_conf_callback, usercontext)
Example #7
0
def initialize_client(connection_string):
    # prepare iothub client
    client = IoTHubClient(connection_string, PROTOCOL)
    client.set_option("product_info", "HappyPath_RaspberryPi-Python")
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(device_method_callback,
                                          METHOD_CONTEXT)
    return client
from iothub_client import IoTHubClient, IoTHubTransportProvider, IoTHubMessage
import time

CONNECTION_STRING = "HostName=testnumber2-hub.azure-devices.net;DeviceId=myRaspberryPi;SharedAccessKey=cw4WSWuwSCbbaBCrO2YRRj4z0rt+8SCRtJuD1yI6dxA="
PROTOCOL = IoTHubTransportProvider.MQTT


# output confirmation message
def send_confirmation_callback(message, result, user_context):
    print("Confirmation received for message with result = %s" % (result))


# main function
# send a message to the Auzre IoT hub
if __name__ == '__main__':
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    message = IoTHubMessage("test message")
    client.send_event_async(message, send_confirmation_callback, None)
    print("Message transmitted to IoT Hub")

    while True:
        time.sleep(1)
Example #9
0
import subprocess
import sys
import termios
import time
import tty
import zipfile
from datetime import datetime, timedelta
from azure.storage.blob import BlockBlobService, ContentSettings, PublicAccess
from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult, IoTHubError, DeviceMethodReturnValue
from iothub_service_client import IoTHubRegistryManager, IoTHubRegistryManagerAuthMethod
from iothub_service_client import IoTHubDeviceTwin, IoTHubError
SCRIPT_DIR = os.path.split(os.path.realpath(__file__))[0]

CONNECTION_STRING = ""
PROTOCOL = IoTHubTransportProvider.MQTT
CLIENT = IoTHubClient(CONNECTION_STRING, PROTOCOL)
SEND_REPORTED_STATE_CONTEXT = 0
METHOD_CONTEXT = 0
SEND_REPORTED_STATE_CALLBACKS = 0
METHOD_CALLBACKS = 0

class PiImageDetection():
    
    def __init__(self):
        # Intialize Azure Blob Container Properties
        self.picture_container_name = 'edgeimages'
        self.video_container_name = 'edgevideos'
        self.model_container_name = 'edgemodels'
        self.json_container_name = 'edgejson'

        # Intialize Azure IoTHub Config Properties
Example #10
0
def iothub_client_init(conn):
    # Create an IoT Hub client
    client = IoTHubClient(conn, PROTOCOL)
    return client
Example #11
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(AzureHubConnectionString, PROTOCOL)
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    # if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
    #     client.set_device_method_callback(
    #         device_method_callback, METHOD_CONTEXT)
    return client
Example #12
0
    def iothubClientInit(self):
        # prepare iothub client
        client = IoTHubClient(self.CONNECTION_STRING, PROTOCOL)
        client.set_option("product_info", "HappyPath_RaspberryPi-Python")

        if client.protocol == IoTHubTransportProvider.HTTP:
            client.set_option("timeout", TIMEOUT)
            client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)

        # set the time until a message times out
        client.set_option("messageTimeout", MESSAGE_TIMEOUT)

        # to enable MQTT logging set to 1
        if client.protocol == IoTHubTransportProvider.MQTT:
            client.set_option("logtrace", 0)

        # set callback after a message is received
        client.set_message_callback(self.receiveMessageCallback, RECEIVE_CONTEXT)

        # if MQTT or MQTT_WS is used -> set device twin callback
        if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
            client.set_device_twin_callback(self.deviceTwinCallback, TWIN_CONTEXT)
            client.set_device_method_callback(self.deviceMethodCallback, METHOD_CONTEXT)
            
        return client
Example #13
0
import cv2
import cognitive_face as CF
import numpy as np
from datetime import datetime as dt
import time
from iothub_client import IoTHubClient, IoTHubTransportProvider, IoTHubMessage
import json

######### hub connection #############
protocol = IoTHubTransportProvider.HTTP
connection_string = 'HostName=friothub.azure-devices.net;DeviceId=frdevice;SharedAccessKey=IjdRpgo9EbOhGKVuCbHvu85hE9MkLPgM6/uygk9CSNs='
client = IoTHubClient(connection_string, protocol)

# cognitive Face variables
SUBSCRIPTION_KEY = 'f14a1dc6045148ca951ab5c1d1655e1c'
BASE_URL = 'https://faceregdemo.cognitiveservices.azure.com/face/v1.0'
# cognitive Face init
CF.BaseUrl.set(BASE_URL)
CF.Key.set(SUBSCRIPTION_KEY)
# time control variables
start_time = dt.now()
# 30 seconds interval
interval_time = 30

#init capture
cap = cv2.VideoCapture(0)


# parse json
def send_emotions(data):
    for i in range(len(data)):
Example #14
0
class PlayCommands(object):
    def __init__(self, Name):

        CONNECTION_STRING = "HostName=RobotForman.azure-devices.net;DeviceId=PythonTest;SharedAccessKey=oh9Fj0mAMWJZpNNyeJ+bSecVH3cBQwbzjDnoVmeSV5g="

        self.protocol = IoTHubTransportProvider.HTTP
        self.client = IoTHubClient(CONNECTION_STRING, self.protocol)
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
        self.client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)

        self.client.set_message_callback(receive_message_callback,
                                         RECEIVE_CONTEXT)

        moveit_commander.roscpp_initialize(sys.argv)
        rospy.init_node('mid' + str(uuid.uuid4().hex), anonymous=True)
        print 'mid' + str(uuid.uuid4().hex)
        self.head_display = intera_interface.HeadDisplay()
        self.head_display.display_image("/home/microshak/Pictures/Ready.png",
                                        False, 1.0)
        self.head = intera_interface.Head()
        rp = RobotParams()
        valid_limbs = rp.get_limb_names()

        robot = moveit_commander.RobotCommander()
        rp.max_velocity_scaling_factor = .5
        scene = moveit_commander.PlanningSceneInterface()

        self.group = moveit_commander.MoveGroupCommander("right_arm")

        display_trajectory_publisher = rospy.Publisher(
            '/move_group/display_planned_path',
            moveit_msgs.msg.DisplayTrajectory,
            queue_size=20)

        self.light = Lights()
        self.headLight("green")

        #  rs = intera_interface.RobotEnable(CHECK_VERSION)

        self.group.clear_pose_targets()
        self.endeffector = intera_interface.Gripper("right")

        self.uri = "mongodb://*****:*****@sawyer-mongo.documents.azure.com:10255/?ssl=true"
        self.Mongoclient = MongoClient(self.uri)

        if Name == None:
            self.poleIoTHub()
        else:
            self.completeCommands(Name)

    def poleIoTHub(self):

        while True:
            if len(IoTHubMessages) > 0:
                self.handleIoT()
            #rospy.sleep(2)

    def completeCommands(self, Name):
        db = self.Mongoclient.SawyerDB
        collection = db.Command

        data = collection.find({"Name": Name}).sort("Order", pymongo.ASCENDING)

        switch = {
            "Move": lambda x: self.move(x),
            "Gripper": lambda x: self.gripper(x)
        }

        print "============Start"
        #rospy.sleep(1)
        ps = self.group.get_current_pose("right_gripper")
        self.neutral()

        for record in data:
            print IoTHubMessages
            if len(IoTHubMessages) > 0:
                self.handleIoT()
            self.headLight("green")
            #rospy.sleep(1)
            switch[record["Action"]](record)

    ## When finished shut down moveit_commander.
        moveit_commander.roscpp_shutdown()

    def neutral(self):
        limb = intera_interface.Limb("right")
        limb.move_to_neutral()
        self.headLight("blue")
        self.head_display.display_image("/home/microshak/Pictures/Neutral.png",
                                        False, 1.0)

    def headLight(self, value):
        colors = ["red", "blue", "green"]
        for color in colors:
            self.light.set_light_state('head_{0}_light'.format(color),
                                       on=bool(value == color))

    def gripper(self, data):
        if data["Open"]:
            self.endeffector.open()
            self.head_display.display_image(
                "/home/microshak/Pictures/GripperO.png", False, 1.0)
        else:
            self.endeffector.close()
            self.head_display.display_image(
                "/home/microshak/Pictures/GripperC.png", False, 1.0)

    def handleIoT(self):
        while len(IoTHubMessages) > 0:
            self.headLight("red")
            rospy.sleep(1)

            temp = IoTHubMessages.pop()
            message = {}
            message["Cartisian"] = {}
            message["Cartisian"]["orientation"] = {}
            message["Cartisian"]["position"] = {}
            message["Action"] = temp["Action"]
            message["Order"] = temp["Order"]
            message["FriendlyName"] = temp["FriendlyName"]
            message["Cartisian"]["orientation"]["x"] = float(
                temp["Cartisian.orientation.x"])
            message["Cartisian"]["orientation"]["y"] = float(
                temp["Cartisian.orientation.y"])
            message["Cartisian"]["orientation"]["z"] = float(
                temp["Cartisian.orientation.z"])
            message["Cartisian"]["orientation"]["w"] = float(
                temp["Cartisian.orientation.w"])
            message["Cartisian"]["position"]["x"] = float(
                temp["Cartisian.position.x"])
            message["Cartisian"]["position"]["y"] = float(
                temp["Cartisian.position.y"])
            message["Cartisian"]["position"]["z"] = float(
                temp["Cartisian.position.z"])

            #  print(message)
            print(message.keys())

            if (message["Action"] == "Run"):
                #  message = IoTHubMessages.pop()
                self.completeCommands("Test2")

            if (message["Action"] == "Neutral"):
                self.neutral()
            if (message["Action"] == "Move"):
                self.move(message)

            if (message["Action"] == "Stop"):
                stop = True
                self.head_display.display_image(
                    "/home/microshak/Pictures/Stop.png", False, 1.0)

                while stop:
                    if len(IoTHubMessages) > 0:
                        message = IoTHubMessages.pop()
                        if message["Action"] == "Continue":
                            stop = False
                            self.head_display.display_image(
                                "/home/microshak/Pictures/Resume.png", False,
                                1.0)

    def receive_message_callback(message, counter):
        global RECEIVE_CALLBACKS
        print "Listening"
        message_buffer = message.get_bytearray()
        size = len(message_buffer)
        lit = ast.literal_eval(message_buffer[:size].decode('utf-8'))
        for key in lit:
            self.IotHubMessages.insert({key: lit[key]})
            print key + "---" + str(lit[key])

        counter += 1
        RECEIVE_CALLBACKS += 1
        return IoTHubMessageDispositionResult.ACCEPTED

    def receive_message_callback(message):
        global RECEIVE_CALLBACKS
        message_buffer = message.get_bytearray()
        size = len(message_buffer)
        print("Received Message [%d]:" % counter)
        print("    Data: <<<%s>>> & Size=%d" %
              (message_buffer[:size].decode('utf-8'), size))
        map_properties = message.properties()
        key_value_pair = map_properties.get_internals()

        print("    Properties: %s" % key_value_pair)
        counter += 1
        RECEIVE_CALLBACKS += 1
        print("    Total calls received: %d" % RECEIVE_CALLBACKS)
        return IoTHubMessageDispositionResult.ACCEPTED

    def move(self, jointpos):
        self.head_display.display_image("/home/microshak/Pictures/Moving.png",
                                        False, 1.0)

        print "MOVING!!!!!!!!!!!!!!!!!"

        position = ast.literal_eval(json.dumps(jointpos['Cartisian']))
        print(position)
        p = position["position"]
        o = position["orientation"]
        pose_target = geometry_msgs.msg.Pose()
        pose_target.orientation.w = o["w"]
        pose_target.orientation.x = o["x"]
        pose_target.orientation.y = o["y"]
        pose_target.orientation.z = o["z"]
        pose_target.position.x = p["x"]
        pose_target.position.y = p["y"]
        pose_target.position.z = p["z"]
        print pose_target
        group = moveit_commander.MoveGroupCommander("right_arm")
        limb = intera_interface.Limb("right")
        limb.set_joint_position_speed(.1)

        #   limb.set_joint_position_speed(.1)
        group.set_pose_target(pose_target)
        # group.set_joint_value_target(pose_target)
        plan2 = group.plan()
        group.go(wait=True)
        '''  
Example #15
0
class DeviceClient(object):
    def __init__(self,
                 connection_string,
                 protocol=IoTHubTransportProvider.MQTT):
        self.client_protocol = protocol
        self.client = IoTHubClient(connection_string, protocol)
        if protocol == IoTHubTransportProvider.HTTP:
            self.client.set_option("timeout", TIMEOUT)
            self.client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
        # some embedded platforms need certificate information
        # self.set_certificates()
        self.client.set_message_callback(self.receive_message_callback,
                                         RECEIVE_CONTEXT)
        self.client.set_device_twin_callback(self.device_twin_callback,
                                             TWIN_CONTEXT)
        self.client.set_device_method_callback(self.device_method_callback,
                                               METHOD_CONTEXT)

    def set_certificates(self):
        from iothub_client_cert import CERTIFICATES
        try:
            self.client.set_option("TrustedCerts", CERTIFICATES)
            print("set_option TrustedCerts successful")
        except IoTHubClientError as iothub_client_error:
            print("set_option TrustedCerts failed (%s)" % iothub_client_error)

    def send_event(self, event, properties, send_context):
        if not isinstance(event, IoTHubMessage):
            event = IoTHubMessage(bytearray(event, 'utf8'))

        if len(properties) > 0:
            prop_map = event.properties()
            for key in properties:
                prop_map.add_or_update(key, properties[key])

        self.client.send_event_async(event, self.send_confirmation_callback,
                                     send_context)

    def send_reported_state(self, reported_state, size, user_context):
        self.client.send_reported_state(reported_state, size,
                                        self.send_reported_state_callback,
                                        user_context)

    def upload_to_blob(self, destinationfilename, source, size, usercontext):
        self.client.upload_blob_async(destinationfilename, source, size,
                                      self.blob_upload_conf_callback,
                                      usercontext)

    def send_confirmation_callback(self, message, result, user_context):
        global SEND_CALLBACKS
        print("Confirmation[%d] received for message with result = %s" %
              (user_context, result))
        map_properties = message.properties()
        key_value_pair = map_properties.get_internals()
        print("    Properties: %s" % key_value_pair)
        SEND_CALLBACKS += 1
        print("    Total calls confirmed: %d" % SEND_CALLBACKS)

    def receive_message_callback(self, message, counter):
        global RECEIVE_CALLBACKS
        message_buffer = message.get_bytearray()
        size = len(message_buffer)
        print("Received Message [%d]:" % counter)
        print("    Data: <<<%s>>> & Size=%d" %
              (message_buffer[:size].decode('utf-8'), size))
        map_properties = message.properties()
        key_value_pair = map_properties.get_internals()
        print("    Properties: %s" % key_value_pair)
        counter += 1
        RECEIVE_CALLBACKS += 1
        print("    Total calls received: %d" % RECEIVE_CALLBACKS)
        return IoTHubMessageDispositionResult.ACCEPTED

    def device_twin_callback(self, update_state, payload, user_context):
        global TWIN_CALLBACKS
        print(
            "\nTwin callback called with:\nupdateStatus = %s\npayload = %s\ncontext = %s"
            % (update_state, payload, user_context))
        TWIN_CALLBACKS += 1
        print("Total calls confirmed: %d\n" % TWIN_CALLBACKS)

    def send_reported_state_callback(self, status_code, user_context):
        global SEND_REPORTED_STATE_CALLBACKS
        print(
            "Confirmation for reported state received with:\nstatus_code = [%d]\ncontext = %s"
            % (status_code, user_context))
        SEND_REPORTED_STATE_CALLBACKS += 1
        print("    Total calls confirmed: %d" % SEND_REPORTED_STATE_CALLBACKS)

    def device_method_callback(self, method_name, payload, user_context):
        global METHOD_CALLBACKS
        print(
            "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s"
            % (method_name, payload, user_context))
        METHOD_CALLBACKS += 1
        print("Total calls confirmed: %d\n" % METHOD_CALLBACKS)
        device_method_return_value = DeviceMethodReturnValue()
        device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }"
        device_method_return_value.status = 200
        return device_method_return_value

    def blob_upload_conf_callback(self, result, user_context):
        global BLOB_CALLBACKS
        print(
            "Blob upload confirmation[%d] received for message with result = %s"
            % (user_context, result))
        BLOB_CALLBACKS += 1

    print("    Total calls confirmed: %d" % BLOB_CALLBACKS)
Example #16
0
        device_method_return_value.response = "{ \"Response\": \"Direct method not defined: %s\" }" % method_name
        device_method_return_value.status = 404
    return device_method_return_value


def send_confirmation_callback(message, result, user_context):
    print("IoT Hub responded to message with status: %s" % (result))


print("Parsing Args")
args = build_argparser().parse_args()
print("connectionstring")
print(args.connectionstring)

if enable_cloud_output:
    client = IoTHubClient(args.connectionstring, PROTOCOL)
    client.set_device_method_callback(device_method_callback, None)

if enable_local_jpeg_output:
    local_output_dir = os.environ.get("OUTPUT_DIR")
    assert os.path.isdir(
        local_output_dir), "Specified output directory doesn't exist"
    print("writing output jpeg frames to " + local_output_dir)


# Define the JSON message to send to IoT Hub.
def report_output(frame, res_json):
    json_string = json.dumps(res_json)
    print("Detections: " + json_string)
    if enable_cloud_output:
        message = IoTHubMessage(json_string)
class HubManager(object):

    def __init__(
            self,
            connection_string,
            protocol=IoTHubTransportProvider.MQTT):
        self.client_protocol = protocol
        self.client = IoTHubClient(connection_string, protocol)
        if protocol == IoTHubTransportProvider.HTTP:
            self.client.set_option("timeout", TIMEOUT)
            self.client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
        # some embedded platforms need certificate information
        # self.set_certificates()
        self.client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
        self.client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT)
        self.client.set_device_method_callback(device_method_callback, METHOD_CONTEXT)

    def set_certificates(self):
        from iothub_client_cert import CERTIFICATES
        try:
            self.client.set_option("TrustedCerts", CERTIFICATES)
            print ( "set_option TrustedCerts successful" )
        except IoTHubClientError as iothub_client_error:
            print ( "set_option TrustedCerts failed (%s)" % iothub_client_error )

    def send_event(self, event, properties, send_context):
        if not isinstance(event, IoTHubMessage):
            event = IoTHubMessage(bytearray(event, 'utf8'))

        if len(properties) > 0:
            prop_map = event.properties()
            for key in properties:
                prop_map.add_or_update(key, properties[key])

        self.client.send_event_async(
            event, send_confirmation_callback, send_context)

    def send_reported_state(self, reported_state, size, user_context):
        self.client.send_reported_state(
            reported_state, size,
            send_reported_state_callback, user_context)

    def upload_to_blob(self, destinationfilename, source, size, usercontext):
        self.client.upload_blob_async(
            destinationfilename, source, size,
            blob_upload_conf_callback, usercontext)
Example #18
0
class IotHub:
    def __init__(self, hardware, queue):
        self.method_callbacks = 0
        self.hardware = hardware
        self.queue = queue
        self._init_client()

    def _init_client(self):
        # Connect to iot-hub
        self.client = IoTHubClient(IOTHUB_CONNECTION,
                                   IoTHubTransportProvider.AMQP)
        # Settings
        self.client.set_option("messageTimeout", IOTHUB_MESSAGE_TIMEOUT)
        self.client.set_device_method_callback(self.device_method_callback, 0)

    def send_confirmation_callback(self, message, result, user_context):
        print(
            "Confirmation received for message with result {}".format(result))
        print("    message_id: %s" % message.message_id)
        print("    correlation_id: %s" % message.correlation_id)

    def send_message(self, payload):
        message_id = uuid4()
        message = IoTHubMessage(bytearray(payload, 'utf8'))
        self.client.send_event_async(message, self.send_confirmation_callback,
                                     message_id)
        print("Message {} accepted for transmission to IoT Hub.".format(
            message_id))
        return self.client.get_send_status()

    # Gets invoked by message from the cloud
    def device_method_callback(self, method_name, payload, user_context):
        print(
            "Method callback called with: methodName = {}, payload = {}, context = {}"
            .format(method_name, payload, user_context))

        msg = json.loads(payload)

        try:
            if method_name == 'list':
                response = self.hardware.list_methods()
            elif method_name == 'cancel':
                self.queue.cancel()
                response = "ok"
            else:
                method_payload = msg['payload'] if 'payload' in msg else {}
                self.queue.append("invoke_method", {
                    "method": method_name,
                    "payload": method_payload,
                })
                response = "ok"

            status = 200

        except NotImplementedError:
            response = 'Method not defined'
            status = 404

        except ValueError as inst:
            response = inst.args
            status = 400

        except queue.Full:
            response = "Too many items in queue"
            status = 503

        except Exception as inst:
            response = inst.args
            status = 500

        return_value = DeviceMethodReturnValue()
        return_value.status = status
        return_value.response = json_dumps({'Response': response})

        return return_value
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    client.set_option("logtrace", 0)
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
    retryInterval = 100
    client.set_retry_policy(retryPolicy, retryInterval)
    print ( "SetRetryPolicy to: retryPolicy = %d" %  retryPolicy)
    print ( "SetRetryPolicy to: retryTimeoutLimitInSeconds = %d" %  retryInterval)
    retryPolicyReturn = client.get_retry_policy()
    print ( "GetRetryPolicy returned: retryPolicy = %d" %  retryPolicyReturn.retryPolicy)
    print ( "GetRetryPolicy returned: retryTimeoutLimitInSeconds = %d" %  retryPolicyReturn.retryTimeoutLimitInSeconds)
    return client
def run_e2e_devicemethod(iothub_connection_string):
    global DEVICE_METHOD_USER_CONTEXT
    global DEVICE_METHOD_NAME
    global DEVICE_METHOD_PAYLOAD
    global DEVICE_METHOD_TIMEOUT

    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        iothub_registry_manager = IoTHubRegistryManager(
            iothub_connection_string)
        new_device = iothub_registry_manager.create_device(
            device_id, primary_key, secondary_key, auth_method)

        device_connection_string = get_device_connection_string(
            iothub_registry_manager, IOTHUB_CONNECTION_STRING, device_id)

        device_client = IoTHubClient(device_connection_string,
                                     IoTHubTransportProvider.MQTT)
        assert isinstance(device_client,
                          IoTHubClient), 'Invalid type returned!'
        assert device_client != None, "device_client is NULL"

        device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client.set_device_method_callback(device_method_callback,
                                                 DEVICE_METHOD_USER_CONTEXT)

        ###########################################################################
        # IoTHubDeviceMethod

        # prepare
        # act
        iothub_device_method = IoTHubDeviceMethod(IOTHUB_CONNECTION_STRING)

        # verify
        assert iothub_device_method != None, "iothub_device_method is NULL"
        ###########################################################################

        # Wait before invoke...
        time.sleep(SLEEP_BEFORE_DEVICE_ACTION)

        ############################################################################
        # invoke

        # prepare
        # act
        response = iothub_device_method.invoke(device_id, DEVICE_METHOD_NAME,
                                               DEVICE_METHOD_PAYLOAD,
                                               DEVICE_METHOD_TIMEOUT)
        assert response != None, "response is NULL"
        assert isinstance(response,
                          IoTHubDeviceMethodResponse), 'Invalid type returned!'

        # verify
        response_ok = response.payload.find(DEVICE_CLIENT_RESPONSE)
        assert response_ok > 0, "response does not contain " + DEVICE_CLIENT_RESPONSE
        assert response.status == 200, "response status is : " + response.status
        DEVICE_METHOD_EVENT.wait(DEVICE_METHOD_CALLBACK_TIMEOUT)
        assert DEVICE_CLIENT_RESPONSE.find(
            DEVICE_METHOD_RESPONSE_PREFIX
        ) >= 0, "Timeout expired and device method has not been called!"
        ############################################################################

        print("")
        retval = 0
    except Exception as e:
        print("")
        print("run_e2e_devicemethod() failed with exception: {0}".format(e))
        retval = 1
    finally:
        # clean-up
        iothub_registry_manager.delete_device(device_id)

    return retval
Example #21
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # some embedded platforms need certificate information
    set_certificates(client)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(
        receive_message_callback, RECEIVE_CONTEXT)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(
            device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(
            device_method_callback, METHOD_CONTEXT)
    if client.protocol == IoTHubTransportProvider.AMQP or client.protocol == IoTHubTransportProvider.AMQP_WS:
        client.set_connection_status_callback(
            connection_status_callback, CONNECTION_STATUS_CONTEXT)

    retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
    retryInterval = 100
    client.set_retry_policy(retryPolicy, retryInterval)
    print ( "SetRetryPolicy to: retryPolicy = %d" %  retryPolicy)
    print ( "SetRetryPolicy to: retryTimeoutLimitInSeconds = %d" %  retryInterval)
    retryPolicyReturn = client.get_retry_policy()
    print ( "GetRetryPolicy returned: retryPolicy = %d" %  retryPolicyReturn.retryPolicy)
    print ( "GetRetryPolicy returned: retryTimeoutLimitInSeconds = %d" %  retryPolicyReturn.retryTimeoutLimitInSeconds)

    return client
def run_e2e_messaging(iothub_connection_string):
    global RECEIVE_CALLBACKS
    global MESSAGING_MESSAGE

    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        iothub_registry_manager = IoTHubRegistryManager(
            iothub_connection_string)
        new_device = iothub_registry_manager.create_device(
            device_id, primary_key, secondary_key, auth_method)

        device_connection_string = get_device_connection_string(
            iothub_registry_manager, IOTHUB_CONNECTION_STRING, device_id)

        device_client = IoTHubClient(device_connection_string,
                                     IoTHubTransportProvider.MQTT)
        assert isinstance(device_client,
                          IoTHubClient), 'Invalid type returned!'
        assert device_client != None, "device_client is NULL"

        device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client.set_message_callback(receive_message_callback,
                                           MESSAGING_CONTEXT)

        ###########################################################################
        # IoTHubMessaging

        # prepare
        # act
        iothub_messaging = IoTHubMessaging(IOTHUB_CONNECTION_STRING)

        # verify
        assert iothub_messaging != None, "iothub_messaging is NULL"
        ###########################################################################

        # Wait before open...
        time.sleep(SLEEP_BEFORE_DEVICE_ACTION)

        ############################################################################
        # open

        # act
        iothub_messaging.open(open_complete_callback, None)
        ############################################################################

        ############################################################################
        # invoke

        # prepare
        MESSAGING_MESSAGE = ''.join(
            [random.choice(string.ascii_letters) for n in range(12)])
        message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))

        # act
        iothub_messaging.send_async(device_id, message, send_complete_callback,
                                    MESSAGING_CONTEXT)
        MESSAGE_RECEIVED_EVENT.wait(MESSAGE_RECEIVE_CALLBACK_TIMEOUT)

        # verify
        assert RECEIVE_CALLBACKS == 1, "message has not been received"
        ############################################################################

        print("")
        retval = 0
    except Exception as e:
        print("")
        print("run_e2e_messaging() failed with exception: {0}".format(e))
        retval = 1
    finally:
        # clean-up
        iothub_messaging.close()
        iothub_registry_manager.delete_device(device_id)

    return retval
Example #23
0
def connectIoTHub():
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    return client
Example #24
0
 def __init__(self, iothub_name, device_id, device_key, suffix='.azure-devices.net'):
     self.device_id = device_id
     device_connection_string = 'HostName={0}{1};DeviceId={2};SharedAccessKey={3}'.format(
         iothub_name, suffix, device_id, device_key
     )
     self.client = IoTHubClient(device_connection_string, IoTHubTransportProvider.MQTT) # HTTP, AMQP, MQTT ?
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)

    # HTTP specific settings
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)

    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)

    # this brings in x509 privateKey and certificate
    client.set_option("x509certificate", X509_CERTIFICATE)
    client.set_option("x509privatekey", X509_PRIVATEKEY)

    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)

    client.set_message_callback(
        receive_message_callback, RECEIVE_CONTEXT)
    return client
Example #26
0
def iothub_client_init():
    # Create an IoT Hub client
   # client.set_option("auto_url_encode_decode", True)
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    return client
Example #27
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(device_method_callback,
                                          METHOD_CONTEXT)
    return client
Example #28
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    #Turn on and off log tracing for the transport
    client.set_option("logtrace", 0)
    #Anger vilken metod som anropas för att ta emot Method
    client.set_device_method_callback(device_method_callback, METHOD_CONTEXT)
    #Anger vilken medotd för hantering av meddelanden
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    client.set_device_twin_callback(device_twin_callback, METHOD_CONTEXT)
    #client.upload_blob_async(upload_to_blob, RECEIVE_CALLBACKS)
    return client
def iothub_client_init():
    # Create an IoT Hub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    return client
def iothubClientInit(protocol,connection_string):
    # Create an IoT Hub client
    client = IoTHubClient(connection_string, protocol)
    return client
Example #31
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    client.set_option("product_info", "HappyPath_RaspberryPi-Python")
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(
        receive_message_callback, RECEIVE_CONTEXT)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(
            device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(
            device_method_callback, METHOD_CONTEXT)
    return client
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # some embedded platforms need certificate information
    set_certificates(client)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(
        receive_message_callback, RECEIVE_CONTEXT)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(
            device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(
            device_method_callback, METHOD_CONTEXT)
    if client.protocol == IoTHubTransportProvider.AMQP or client.protocol == IoTHubTransportProvider.AMQP_WS:
        client.set_connection_status_callback(
            connection_status_callback, CONNECTION_STATUS_CONTEXT)

    retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
    retryInterval = 100
    client.set_retry_policy(retryPolicy, retryInterval)
    print ( "SetRetryPolicy to: retryPolicy = %d" %  retryPolicy)
    print ( "SetRetryPolicy to: retryTimeoutLimitInSeconds = %d" %  retryInterval)
    retryPolicyReturn = client.get_retry_policy()
    print ( "GetRetryPolicy returned: retryPolicy = %d" %  retryPolicyReturn.retryPolicy)
    print ( "GetRetryPolicy returned: retryTimeoutLimitInSeconds = %d" %  retryPolicyReturn.retryTimeoutLimitInSeconds)

    return client
def run_e2e_messaging(iothub_connection_string):
    global RECEIVE_CALLBACKS
    global MESSAGING_MESSAGE

    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        iothub_registry_manager = IoTHubRegistryManager(iothub_connection_string)
        new_device = iothub_registry_manager.create_device(device_id, primary_key, secondary_key, auth_method)

        device_connection_string = get_device_connection_string(iothub_registry_manager, IOTHUB_CONNECTION_STRING, device_id)

        device_client = IoTHubClient(device_connection_string, IoTHubTransportProvider.MQTT)
        assert isinstance(device_client, IoTHubClient), 'Invalid type returned!'
        assert device_client != None, "device_client is NULL"

        device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client.set_message_callback(receive_message_callback, MESSAGING_CONTEXT)

        ###########################################################################
        # IoTHubMessaging

        # prepare
        # act
        iothub_messaging = IoTHubMessaging(IOTHUB_CONNECTION_STRING)

        # verify
        assert iothub_messaging != None, "iothub_messaging is NULL"
        ###########################################################################

        # Wait before open...
        time.sleep(SLEEP_BEFORE_DEVICE_ACTION)

        ############################################################################
        # open

        # act
        iothub_messaging.open(open_complete_callback, None)
        ############################################################################

        ############################################################################
        # invoke

        # prepare
        MESSAGING_MESSAGE = ''.join([random.choice(string.ascii_letters) for n in range(12)])
        message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))

        # act
        iothub_messaging.send_async(device_id, message, send_complete_callback, MESSAGING_CONTEXT)
        MESSAGE_RECEIVED_EVENT.wait(MESSAGE_RECEIVE_CALLBACK_TIMEOUT)

        # verify
        assert RECEIVE_CALLBACKS == 1, "message has not been received"
        ############################################################################

        print ( "" )
        retval = 0
    except Exception as e:
        print ( "" )
        print ("run_e2e_messaging() failed with exception: {0}".format(e))
        retval = 1
    finally:
        # clean-up
        iothub_messaging.close()
        iothub_registry_manager.delete_device(device_id)
    
    return retval
def run_e2e_shared_transport(iothub_registry_manager, iothub_service_client_messaging, iothub_device_method, iothub_device_twin, protocol, authMethod):
    global IOTHUB_CONNECTION_STRING
    global IOTHUB_E2E_X509_CERT
    global IOTHUB_E2E_X509_THUMBPRINT
    global IOTHUB_E2E_X509_PRIVATE_KEY
    global CERTIFICATES
    global DEVICE_MESSAGE_TIMEOUT
    global MESSAGING_MESSAGE
    global MESSAGE_RECEIVE_EVENT
    global MESSAGE_RECEIVE_CALLBACK_COUNTER

    print ("********************* run_e2e({0}, {1}) E2E test with shared transport started".format(protocol, authMethod))
    try:
        # Process connection string
        host_name_start = IOTHUB_CONNECTION_STRING.find("HostName")
        host_name_end = IOTHUB_CONNECTION_STRING.find(";", host_name_start)
        host_name_equal_sign = IOTHUB_CONNECTION_STRING.find("=", host_name_start)
        host_name_suffix_separator = IOTHUB_CONNECTION_STRING.find(".", host_name_equal_sign)

        iothub_name = IOTHUB_CONNECTION_STRING[host_name_equal_sign+1:host_name_suffix_separator]
        iothub_suffix = IOTHUB_CONNECTION_STRING[host_name_suffix_separator+1:host_name_end]

        # Create transport
        transport = IoTHubTransport(protocol, iothub_name, iothub_suffix)

        # Create first device
        device_id1 = generate_device_name()
        device = sc_create_device(iothub_registry_manager, device_id1, authMethod)
        iothub_device1 = iothub_registry_manager.get_device(device_id1)
        assert isinstance(iothub_device1, IoTHubDevice), 'Invalid type returned!'
        assert iothub_device1 != None, "iothub_device is NULL"
        device_key1 = iothub_device1.primaryKey
        device_sas_token1 = ""
        protocol_gateway_host_name1 = ""
        config1 = IoTHubConfig(protocol, device_id1, device_key1, device_sas_token1, iothub_name, iothub_suffix, protocol_gateway_host_name1)

        # Create second device
        device_id2 = generate_device_name()
        device = sc_create_device(iothub_registry_manager, device_id2, authMethod)
        iothub_device2 = iothub_registry_manager.get_device(device_id2)
        assert isinstance(iothub_device2, IoTHubDevice), 'Invalid type returned!'
        assert iothub_device2 != None, "iothub_device is NULL"
        device_key2 = iothub_device2.primaryKey
        device_sas_token2 = ""
        protocol_gateway_host_name3 = ""
        config2 = IoTHubConfig(protocol, device_id2, device_key2, device_sas_token2, iothub_name, iothub_suffix, protocol_gateway_host_name3)

        device_client1 = IoTHubClient(transport, config1)
        device_client2 = IoTHubClient(transport, config2)

        device_client1.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)
        device_client2.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client1.set_message_callback(receive_message_callback, MESSAGING_CONTEXT)
        device_client2.set_message_callback(receive_message_callback, MESSAGING_CONTEXT)

        device_client1.set_connection_status_callback(connection_status_callback, CONNECTION_STATUS_CONTEXT)
        device_client2.set_connection_status_callback(connection_status_callback, CONNECTION_STATUS_CONTEXT)

        ###########################################################################
        # send_event_async

        # prepare
        MESSAGING_MESSAGE = ''.join([random.choice(string.ascii_letters) for n in range(12)])
        message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))
        MESSAGE_RECEIVE_EVENT.clear()
        MESSAGE_RECEIVE_CALLBACK_COUNTER = 0

        # act
        sc_send_message(iothub_service_client_messaging, device_id1, message)
        MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

        MESSAGE_RECEIVE_EVENT.clear()
        sc_send_message(iothub_service_client_messaging, device_id2, message)
        MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert MESSAGE_RECEIVE_CALLBACK_COUNTER > 1, "Error: message has not been received"
        ###########################################################################

        retval = 0
    except Exception as e:
        print ("(********************* run_e2e({0}, {1}) E2E test with shared transport failed with exception: {2}".format(protocol, authMethod, e))
        retval = 1
    finally:
        sc_delete_device(iothub_registry_manager, device_id1)
        sc_delete_device(iothub_registry_manager, device_id2)

    print ("********************* run_e2e({0}, {1}) E2E test with shared transport finished".format(protocol, authMethod))
    return retval
def iothub_client_init():
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)

    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)

    return client
Example #36
0
 def catfood_client_init(self):
     client = IoTHubClient(self.CONNECTION_STRING, self.PROTOCOL)
     return client
def run_e2e_device_client(iothub_service_client_messaging, iothub_device_method, iothub_device_twin, device_id, device_connection_string, protocol, authMethod):
    global IOTHUB_E2E_X509_CERT
    global IOTHUB_E2E_X509_THUMBPRINT
    global IOTHUB_E2E_X509_PRIVATE_KEY
    global CERTIFICATES
    global MESSAGING_CONTEXT

    ###########################################################################
    # IoTHubClient

    # prepare
    # act
    device_client = IoTHubClient(device_connection_string, protocol)

    # verify
    assert isinstance(device_client, IoTHubClient), 'Error: Invalid type returned!'
    assert device_client != None, "Error: device_client is NULL"
    ###########################################################################

    ###########################################################################
    # set_option

    # prepare
    # act
    device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

    if authMethod == IoTHubRegistryManagerAuthMethod.X509_THUMBPRINT:
        device_client.set_option("x509certificate", IOTHUB_E2E_X509_CERT)
        device_client.set_option("x509privatekey", IOTHUB_E2E_X509_PRIVATE_KEY)

    if device_client.protocol == IoTHubTransportProvider.HTTP:
        device_client.set_option("timeout", HTTP_TIMEOUT)
        device_client.set_option("MinimumPollingTime", HTTP_MINIMUM_POLLING_TIME)

    device_client.set_option("TrustedCerts", CERTIFICATES)
    device_client.set_option("logtrace", True)

    # verify
    ###########################################################################

    ###########################################################################
    # set_message_callback
    
    # prepare
    # act
    device_client.set_message_callback(receive_message_callback, MESSAGING_CONTEXT)
    ###########################################################################

    ###########################################################################
    # set_connection_status_callback
    
    # prepare
    # act
    device_client.set_connection_status_callback(connection_status_callback, CONNECTION_STATUS_CONTEXT)
    ###########################################################################

    # verify
    ###########################################################################

    if protocol == IoTHubTransportProvider.MQTT or protocol == IoTHubTransportProvider.MQTT_WS:
        ###########################################################################
        # set_device_twin_callback
    
        # prepare
        # act
        device_client.set_device_twin_callback(device_twin_callback, MESSAGING_CONTEXT)

        # verify
        ###########################################################################

        ###########################################################################
        # set_device_method_callback
    
        # prepare
        # act
        device_client.set_device_method_callback(device_method_callback, MESSAGING_CONTEXT)

        # verify
        ###########################################################################

        ###########################################################################
        # update device twin

        # prepare
        global TWIN_CALLBACK_EVENT
        global TWIN_CALLBACK_COUNTER

        TWIN_CALLBACK_EVENT.clear()
        TWIN_CALLBACK_COUNTER = 0

        # act
        sc_update_twin(iothub_device_twin, device_id)
        TWIN_CALLBACK_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert TWIN_CALLBACK_COUNTER > 0, "Error: device_twin_callback callback has not been called"
        ###########################################################################

        ###########################################################################
        # call device method

        # prepare
        global DEVICE_METHOD_EVENT
        global DEVICE_METHOD_CALLBACK_COUNTER

        DEVICE_METHOD_EVENT.clear()
        DEVICE_METHOD_CALLBACK_COUNTER = 0

        method_name = "E2EMethodName"
        payload_json = "{\"method_number\":\"42\"}"

        # act
        sc_invoke_device_method(iothub_device_method, device_id, method_name, payload_json)
        DEVICE_METHOD_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert DEVICE_METHOD_CALLBACK_COUNTER > 0, "Error: device_twin_callback callback has not been called"
        ###########################################################################

    if protocol == IoTHubTransportProvider.AMQP \
       or protocol == IoTHubTransportProvider.AMQP_WS \
       or protocol == IoTHubTransportProvider.MQTT \
       or protocol == IoTHubTransportProvider.MQTT_WS:
        ###########################################################################
        # send_reported_state
    
        # prepare
        global REPORTED_STATE_EVENT
        global REPORTED_STATE_CALLBACK_COUNTER

        reported_state = "{\"newState\":\"standBy\"}"
        REPORTED_STATE_EVENT.clear()
        REPORTED_STATE_CALLBACK_COUNTER = 0

        # act
        device_client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, REPORTED_STATE_CONTEXT)
        REPORTED_STATE_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert REPORTED_STATE_CALLBACK_COUNTER > 0, "Error: send_reported_state_callback has not been called"
        ###########################################################################

    ###########################################################################
    # set_retry_policy
    # get_retry_policy
   
    # prepare
    # act
    retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
    retryInterval = 100
    device_client.set_retry_policy(retryPolicy, retryInterval)
    print ( "SetRetryPolicy to: retryPolicy = %d" %  retryPolicy)
    print ( "SetRetryPolicy to: retryTimeoutLimitInSeconds = %d" %  retryInterval)
    # verify
    retryPolicyReturn = device_client.get_retry_policy()
    assert retryPolicyReturn.retryPolicy == IoTHubClientRetryPolicy.RETRY_INTERVAL, "Error: set_retry_policy/get_retry_policy failed"
    assert retryPolicyReturn.retryTimeoutLimitInSeconds == 100, "Error: set_retry_policy/get_retry_policy failed"
    print ( "GetRetryPolicy returned: retryPolicy = %d" %  retryPolicyReturn.retryPolicy)
    print ( "GetRetryPolicy returned: retryTimeoutLimitInSeconds = %d" %  retryPolicyReturn.retryTimeoutLimitInSeconds)

    ###########################################################################
    # send_event_async

    # prepare
    global MESSAGING_MESSAGE
    global MESSAGE_RECEIVE_EVENT
    global MESSAGE_RECEIVE_CALLBACK_COUNTER

    MESSAGING_MESSAGE = ''.join([random.choice(string.ascii_letters) for n in range(12)])
    message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))
    MESSAGE_RECEIVE_EVENT.clear()
    MESSAGE_RECEIVE_CALLBACK_COUNTER = 0

    # act
    sc_send_message(iothub_service_client_messaging, device_id, message)
    MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

    # verify
    assert MESSAGE_RECEIVE_CALLBACK_COUNTER > 0, "Error: message has not been received"
    ###########################################################################

    ###########################################################################
    # get_send_status

    # prepare
    status_counter = 0
    status = -1;

    # act
    while status_counter < 1:
        status = device_client.get_send_status()
        print ( "Send status: {0}".format(status) )

        # verify
        assert status == 0, "get_send_status reported status is not IDLE"
        status_counter += 1
    ###########################################################################


    if protocol != IoTHubTransportProvider.AMQP \
       and protocol != IoTHubTransportProvider.AMQP_WS:
        ###########################################################################
        # get_last_message_receive_time

        # prepare
        last_receive_time = -1
        # act
        last_receive_time = device_client.get_last_message_receive_time()

        # verify
        assert last_receive_time > 0, "Error: get_last_message_receive_time failed"
        ###########################################################################


    ###########################################################################
    # upload_blob_async
    
    # prepare
    global BLOB_UPLOAD_CONTEXT
    global BLOB_UPLOAD_EVENT
    global BLOB_UPLOAD_CALLBACK_COUNTER

    destination_file_name = ''.join([random.choice(string.ascii_letters) for n in range(12)])
    source = "Blob content for file upload test!"
    size = 34
    BLOB_UPLOAD_EVENT.clear()
    BLOB_UPLOAD_CALLBACK_COUNTER = 0

    # act
    device_client.upload_blob_async(destination_file_name, source, size, blob_upload_conf_callback, BLOB_UPLOAD_CONTEXT)
    BLOB_UPLOAD_EVENT.wait(CALLBACK_TIMEOUT)

    # verify
    assert BLOB_UPLOAD_CALLBACK_COUNTER > 0, "Error: blob_upload_conf_callback callback has not been called"
Example #38
0
def run_e2e_shared_transport(iothub_registry_manager, iothub_service_client_messaging, iothub_device_method, iothub_device_twin, protocol, authMethod):
    global IOTHUB_CONNECTION_STRING
    global IOTHUB_E2E_X509_CERT
    global IOTHUB_E2E_X509_THUMBPRINT
    global IOTHUB_E2E_X509_PRIVATE_KEY
    global CERTIFICATES
    global DEVICE_MESSAGE_TIMEOUT
    global MESSAGING_MESSAGE
    global MESSAGE_RECEIVE_EVENT
    global MESSAGE_RECEIVE_CALLBACK_COUNTER

    print ("********************* run_e2e({0}, {1}) E2E test with shared transport started".format(protocol, authMethod))
    try:
        # Process connection string
        host_name_start = IOTHUB_CONNECTION_STRING.find("HostName")
        host_name_end = IOTHUB_CONNECTION_STRING.find(";", host_name_start)
        host_name_equal_sign = IOTHUB_CONNECTION_STRING.find("=", host_name_start)
        host_name_suffix_separator = IOTHUB_CONNECTION_STRING.find(".", host_name_equal_sign)

        iothub_name = IOTHUB_CONNECTION_STRING[host_name_equal_sign+1:host_name_suffix_separator]
        iothub_suffix = IOTHUB_CONNECTION_STRING[host_name_suffix_separator+1:host_name_end]

        # Create transport
        transport = IoTHubTransport(protocol, iothub_name, iothub_suffix)

        # Create first device
        device_id1 = generate_device_name()
        sc_create_device_and_module_if_needed(iothub_registry_manager, device_id1, authMethod, False)
        iothub_device1 = iothub_registry_manager.get_device(device_id1)
        assert isinstance(iothub_device1, IoTHubDevice), 'Invalid type returned!'
        assert iothub_device1 != None, "iothub_device is NULL"
        device_key1 = iothub_device1.primaryKey
        device_sas_token1 = ""
        protocol_gateway_host_name1 = ""
        config1 = IoTHubConfig(protocol, device_id1, device_key1, device_sas_token1, iothub_name, iothub_suffix, protocol_gateway_host_name1)

        # Create second device
        device_id2 = generate_device_name()
        sc_create_device_and_module_if_needed(iothub_registry_manager, device_id2, authMethod, False)
        iothub_device2 = iothub_registry_manager.get_device(device_id2)
        assert isinstance(iothub_device2, IoTHubDevice), 'Invalid type returned!'
        assert iothub_device2 != None, "iothub_device is NULL"
        device_key2 = iothub_device2.primaryKey
        device_sas_token2 = ""
        protocol_gateway_host_name3 = ""
        config2 = IoTHubConfig(protocol, device_id2, device_key2, device_sas_token2, iothub_name, iothub_suffix, protocol_gateway_host_name3)

        device_client1 = IoTHubClient(transport, config1)
        device_client2 = IoTHubClient(transport, config2)

        device_client1.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)
        device_client2.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client1.set_message_callback(receive_message_callback, MESSAGING_CONTEXT)
        device_client2.set_message_callback(receive_message_callback, MESSAGING_CONTEXT)

        device_client1.set_connection_status_callback(connection_status_callback, CONNECTION_STATUS_CONTEXT)
        device_client2.set_connection_status_callback(connection_status_callback, CONNECTION_STATUS_CONTEXT)

        ###########################################################################
        # send_event_async

        # prepare
        MESSAGING_MESSAGE = ''.join([random.choice(string.ascii_letters) for n in range(12)])
        message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))
        MESSAGE_RECEIVE_EVENT.clear()
        MESSAGE_RECEIVE_CALLBACK_COUNTER = 0

        # act
        sc_send_message(iothub_service_client_messaging, device_id1, message, False)
        MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

        MESSAGE_RECEIVE_EVENT.clear()
        sc_send_message(iothub_service_client_messaging, device_id2, message, False)
        MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert MESSAGE_RECEIVE_CALLBACK_COUNTER > 1, "Error: message has not been received"
        ###########################################################################

        retval = 0
    except Exception as e:
        print ("(********************* run_e2e({0}, {1}) E2E test with shared transport failed with exception: {2}".format(protocol, authMethod, e))
        retval = 1
    finally:
        sc_delete_device(iothub_registry_manager, device_id1)
        sc_delete_device(iothub_registry_manager, device_id2)

    print ("********************* run_e2e({0}, {1}) E2E test with shared transport finished".format(protocol, authMethod))
    return retval
Example #39
0
def iothub_client_init():
    # Create an IoT Hub client
    client = IoTHubClient(config['connectionString'], PROTOCOL)
    return client
Example #40
0
    global SEND_CALLBACKS
    print ( "Confirmation[%d] received for message with result = %s" % (user_context, result) )
    print ( "    message_id: %s" % message.message_id )
    print ( "    correlation_id: %s" % message.correlation_id )
    SEND_CALLBACKS += 1
    print ( "    Total calls confirmed: %d" % SEND_CALLBACKS )    
    
status, result, connect_string = sas_token.get_connection_string()

if status != return_values.OK:
    print("Connection request has failed. Response: {}".format(return_values.RetValDescription(result)))
    print("Quitting")
    
else:
    print("Connection request success. String: {}".format(connect_string))
    client = IoTHubClient(connect_string.encode("utf-8"), IoTHubTransportProvider.MQTT)
    client.set_option("logtrace", 0)
    client.set_message_callback( receive_message_callback, CONTEXT)        
    client.set_device_twin_callback( device_twin_callback, CONTEXT)
    client.set_device_method_callback( device_method_callback, CONTEXT) 

    message_counter = 0
    while True:
        val = raw_input("Press a key\n")
        if val == 'q':
            break
        else:
            print("Sending message")
            message = IoTHubMessage("Test Message")
            message.message_id = "message_%d" % message_counter
            message.correlation_id = "correlation_%d" % message_counter