随笔-239  评论-1203  文章-1 

Microsoft Azure IoTHub Serials 2 - 如何为android应用添加IoTHub支持

1. 在build.gradle(app)文件的dependencies中添加对以下项的依赖:

'com.microsoft.azure.sdk.iot:iot-device-client:1.5.37'

 

其中后面的1.5.37是版本号,最新的版本可以到这里查:

http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.microsoft.azure.sdk.iot%22

 

 

2. 在build.gradle(app)文件的packagingOptions中添加如下内容

packagingOptions {

    exclude "META-INF/MSFTSIG.SF"

    exclude "META-INF/MSFTSIG.RSA"

    exclude 'META-INF/DEPENDENCIES'

    exclude 'META-INF/NOTICE'

    exclude 'META-INF/LICENSE'

    exclude 'META-INF/LICENSE.txt'

    exclude 'META-INF/NOTICE.txt'

    exclude 'thirdpartynotice.txt'

}

 

如下图所示。

 

 

3. 在需要与IoTHub交互的java文件中,引入如下package

//Azure IoTHub packages

import com.microsoft.azure.sdk.iot.device.DeviceClient;

import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol;

import com.microsoft.azure.sdk.iot.device.IotHubEventCallback;

import com.microsoft.azure.sdk.iot.device.IotHubMessageResult;

import com.microsoft.azure.sdk.iot.device.IotHubStatusCode;

import com.microsoft.azure.sdk.iot.device.Message;

 

 

4. 添加如下全局的连接字符串

//Azure IoTHub

private final String connString = "HostName=************.azure-devices.net;DeviceId=***********;SharedAccessKey=*********************";

private final String deviceId = "*****************";

 

 

5. 在java文件中添加如下3个类(MessageCallbackMqtt、EventCallback、MessageCallback和Counter)的声明

// Our MQTT doesn't support abandon/reject, so we will only display the messaged received

// from IoTHub and return COMPLETE

static class MessageCallbackMqtt implements com.microsoft.azure.sdk.iot.device.MessageCallback

{

    public IotHubMessageResult execute(Message msg, Object context)

    {

        Counter counter = (Counter) context;

        System.out.println(

                "Received message " + counter.toString()

                        + " with content: " + new String(msg.getBytes(), Message.DEFAULT_IOTHUB_MESSAGE_CHARSET));



        counter.increment();



        return IotHubMessageResult.COMPLETE;

    }

}



static class EventCallback implements IotHubEventCallback

{

    public void execute(IotHubStatusCode status, Object context)

    {

        Integer i = (Integer) context;

        System.out.println("IoT Hub responded to message " + i.toString()

                + " with status " + status.name());

    }

}



static class MessageCallback implements com.microsoft.azure.sdk.iot.device.MessageCallback

{

    public IotHubMessageResult execute(Message msg, Object context)

    {

        Counter counter = (Counter) context;

        System.out.println(

                "Received message " + counter.toString()

                        + " with content: " + new String(msg.getBytes(), Message.DEFAULT_IOTHUB_MESSAGE_CHARSET));



        int switchVal = counter.get() % 3;

        IotHubMessageResult res;

        switch (switchVal)

        {

            case 0:

                res = IotHubMessageResult.COMPLETE;

                break;

            case 1:

                res = IotHubMessageResult.ABANDON;

                break;

            case 2:

                res = IotHubMessageResult.REJECT;

                break;

            default:

                // should never happen.

                throw new IllegalStateException("Invalid message result specified.");

        }



        System.out.println("Responding to message " + counter.toString() + " with " + res.name());



        counter.increment();



        return res;

    }

}



/**

 * Used as a counter in the message callback.

 */

static class Counter

{

    int num;



    Counter(int num) {

        this.num = num;

    }



    int get() {

        return this.num;

    }



    void increment() {

        this.num++;

    }



    @Override

    public String toString() {

        return Integer.toString(this.num);

    }

}

 

 

6.需要发送数据时,调用以下代码段

 

private void SendMessage() throws URISyntaxException, IOException
    {
        // Comment/uncomment from lines below to use HTTPS or MQTT protocol
        // IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
        IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;

        DeviceClient client = new DeviceClient(connString, protocol);

        try
        {
            client.open();
        } catch (Exception e2)
        {
            System.err.println("Exception while opening IoTHub connection: " + e2.toString());
        }

//发送message填充
            String msgStr = "{\"deviceId\":\"" + deviceId + ",\"PM25\":" + PM25 + ",\"PM10\":" + PM10 + "}";
            try
            {
                Message msg = new Message(msgStr);
                msg.setProperty("PMAlert", PM25 > 100 ? "true" : "false");
                msg.setMessageId(java.util.UUID.randomUUID().toString());
                System.out.println(msgStr);
                EventCallback eventCallback = new EventCallback();
                client.sendEventAsync(msg, eventCallback, null);
            } catch (Exception e)
            {
                System.err.println("Exception while sending event: " + e.getMessage());
            }
            try
            {
                Thread.sleep(2000);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }


        client.closeNow();
    }

 

posted on 2018-05-23 15:47 施炯 阅读(...) 评论(...) 编辑 收藏