top of page

Azure Functions

Updated: Jul 6, 2020

I started learning Azure function to implement an IoT solution.I was thinking I am a java developer how do I use azure effectively,well Azure supports many languages which includes java,.Net,Node JS,python etc

My first use-case for azure function was after uploading data to IoT Hub I should stream data through stream analytics,In stream analytics query I want to trigger Azure function based on some alerts to take corrective actions.


ree



import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import java.io.IOException;
import com.microsoft.azure.sdk.iot.service.devicetwin.DeviceMethod;
import com.microsoft.azure.sdk.iot.service.devicetwin.MethodResult;
import com.microsoft.azure.sdk.iot.service.exceptions.IotHubException;
import java.util.concurrent.TimeUnit;
import com.microsoft.azure.eventhubs.EventData;
import com.microsoft.azure.eventhubs.EventHubException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.nio.charset.Charset;
import java.time.Instant;
import java.util.concurrent.ExecutionException;


/**
 * Azure Functions with HTTP Trigger.
 */
public class Function {
 public static final String iotHubConnectionString = "";
 public static final String eventHubConnectionString = "";
 public static final String deviceId = "";
 private static final String methodNameMax = "SetMax";
 private static final String methodNameMin = "SetMin";
 private static final String methodNameNormal = "SetNormal";
 private static final Long responseTimeout = TimeUnit.SECONDS.toSeconds(300);
 private static final Long connectTimeout = TimeUnit.SECONDS.toSeconds(5);
 final Gson gson = new GsonBuilder().create();

    /**
     * This function listens at endpoint "/api/max". Two ways to invoke it using
     * "curl" command in bash: 1. curl -d "HTTP Body" {your host}/api/max 2.
     * curl {your host}/api/max?name=HTTP%20Query
     */
    @FunctionName("max")
 public HttpResponseMessage<Stringmax(@HttpTrigger(name = "req"methods = { "get",
 "post" }, authLevel = AuthorizationLevel.ANONYMOUS) @EventHubOutput(name = "eventHubMessage"eventHubName = ""connection = ""OutputBinding<EventDataeventHubMessage,
 HttpRequestMessage<Optional<String>> requestfinal ExecutionContext context)
 throws EventHubExceptionExecutionExceptionInterruptedExceptionIOException {
 context.getLogger().info("max HTTP trigger processed a request.");
 // Parse query parameter
 String query = request.getQueryParameters().get("name");
 String name = request.getBody().orElse(query);
 
 if (name == null) {
 return request.createResponse(400"Please pass a name on the query string or in the request body");
        } else {
 DeviceMethod methodClient = DeviceMethod.createFromConnectionString(iotHubConnectionString);
 try {

 String payload = "{\"setSpeed\":\"max\"}";
 byte[] payloadBytes = gson.toJson(payload).getBytes(Charset.defaultCharset());
 
 EventData eventData = EventData.create(payloadBytes);
 
 eventData.getProperties().put("Speed","max"); 
 eventHubMessage.setValue(eventData);
 context.getLogger().info(Instant.now() + ": Send setMax Complete...");
 context.getLogger().info("Invoke SetMax direct method");
 MethodResult result = methodClient.invoke(deviceIdmethodNameMaxresponseTimeoutconnectTimeout,
 null);
 context.getLogger().info("MethodResult"+result);
 if (result == null) {
 throw new IOException("Invoke direct method SetMax returns null");
                }
 context.getLogger().info("Invoked SetMax on device");
 context.getLogger().info("Status for device:   " + result.getStatus());
 context.getLogger().info("Message from device: " + result.getPayload());

            } catch (IotHubException e) {
 context.getLogger().info(e.getMessage());
            } catch (Exception e) {
 context.getLogger().info(e.getMessage());
            }
 return request.createResponse(200name);
        }

    }
 
 @FunctionName("eventhubtrigger")
 public String eventhubtrigger(
            @EventHubTrigger(name = "eventHubMessage"eventHubName = ""connection = ""consumerGroup = "$Default"String eventHubMessage,
 ExecutionContext context) {
 context.getLogger().info("eventhubtrigger" + eventHubMessage);
 return String.format("eventhubtrigger"eventHubMessage);
    }
}

Finally I sucessfully created azure function using java.I used HttpTrigger template and added function name in stream analytics job

Comments


©2020 by Suneetha Yamani. Proudly created with Wix.com

bottom of page