Initial commit: moving environmental sensor to use IoT Hub SDK & Pnp Serialization Library

This commit is contained in:
Dipannita Shaw 2020-07-21 18:59:15 -07:00
Родитель 477484965b
Коммит f921f8a807
45 изменённых файлов: 1280 добавлений и 1128 удалений

2
.gitmodules поставляемый
Просмотреть файл

@ -1,4 +1,4 @@
[submodule "azure-iot-sdk-c-pnp"] [submodule "azure-iot-sdk-c-pnp"]
path = pnpbridge/deps/azure-iot-sdk-c-pnp path = pnpbridge/deps/azure-iot-sdk-c-pnp
url = https://github.com/Azure/azure-iot-sdk-c url = https://github.com/Azure/azure-iot-sdk-c
branch = public-preview-pnp branch = master

@ -1 +1 @@
Subproject commit 84c8c2e11b967a855a0ab94ddb0a56d0bda56fc5 Subproject commit b57f259eb22fe0715f9dc7a3e68d879253581685

Просмотреть файл

@ -53,6 +53,7 @@ include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/deps/azure-macro-ut
include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/deps/umock-c/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/deps/umock-c/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/digitaltwin_client/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/digitaltwin_client/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/samples/pnp/common)
include_directories(${pnp_bridge_INC_FOLDER}) include_directories(${pnp_bridge_INC_FOLDER})

Просмотреть файл

@ -32,8 +32,9 @@ include_directories(../../deps/azure-iot-sdk-c-pnp/deps/parson)
include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/deps/azure-macro-utils-c/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/deps/azure-macro-utils-c/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/deps/umock-c/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/deps/umock-c/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/digitaltwin_client/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/samples/pnp/common)
include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/samples/pnp/pnp_temperature_controller)
include_directories(${pnp_bridge_INC_FOLDER}) include_directories(${pnp_bridge_INC_FOLDER})
@ -67,7 +68,6 @@ set(pnp_bridge_common_libs
prov_device_client prov_device_client
prov_mqtt_transport prov_mqtt_transport
utpm utpm
digitaltwin_client
) )
add_executable(${PROJECT_NAME} add_executable(${PROJECT_NAME}

Просмотреть файл

@ -19,7 +19,7 @@
"_comment_devices": "Array of devices for Azure Pnp interface should be published", "_comment_devices": "Array of devices for Azure Pnp interface should be published",
"pnp_bridge_interface_components": [ "pnp_bridge_interface_components": [
{ {
"_comment": "Environment Sensor Sample Device", "_comment": "Environment Sensor Device Component",
"pnp_bridge_component_name": "environmentalSensor", "pnp_bridge_component_name": "environmentalSensor",
"pnp_bridge_adapter_id": "environment-sensor-sample-pnp-adapter", "pnp_bridge_adapter_id": "environment-sensor-sample-pnp-adapter",
"pnp_bridge_adapter_config": { "pnp_bridge_adapter_config": {

Просмотреть файл

@ -65,49 +65,37 @@ static const unsigned char digitaltwinSample_EnviromentalSensor_NotImplemented[]
static const char digitaltwinSample_EnvironmentalSensorPropertyCustomerName[] = "name"; static const char digitaltwinSample_EnvironmentalSensorPropertyCustomerName[] = "name";
static const char digitaltwinSample_EnvironmentalSensorPropertyBrightness[] = "brightness"; static const char digitaltwinSample_EnvironmentalSensorPropertyBrightness[] = "brightness";
// Response description is an optional, human readable message including more information
// about the setting of the property.
static const char g_environmentalSensorPropertyResponseDescription[] = "success";
// // Format of the body when responding to a targetTemperature
// Application state associated with the particular interface. In particular it contains static const char g_environmentalSensorBrightnessResponseFormat[] = "%.2f";
// the DIGITALTWIN_INTERFACE_CLIENT_HANDLE used for responses in callbacks along with properties set
// and representations of the property update and command callbacks invoked on given interface
//
typedef struct DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE_TAG
{
DIGITALTWIN_INTERFACE_CLIENT_HANDLE interfaceClientHandle;
int brightness;
char* customerName;
int numTimesBlinkCommandCalled;
} DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE;
// State for interface. For simplicity we set this as a global and set during DigitalTwin_InterfaceClient_Create
// but callbacks of this interface don't reference it directly but instead use userContextCallback passed to them
static DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE digitaltwinSample_EnvironmentalSensorState; // DigitalTwinSampleEnvironmentalSensor_SetCommandResponse is a helper that fills out a command request
// DigitalTwinSampleEnvironmentalSensor_SetCommandResponse is a helper that fills out a DIGITALTWIN_CLIENT_COMMAND_RESPONSE
static int DigitalTwinSampleEnvironmentalSensor_SetCommandResponse( static int DigitalTwinSampleEnvironmentalSensor_SetCommandResponse(
DIGITALTWIN_CLIENT_COMMAND_RESPONSE* dtCommandResponse, unsigned char** CommandResponse,
const unsigned char* responseData, size_t* CommandResponseSize,
int status) const unsigned char* ResponseData)
{ {
size_t responseLen = strlen((char*)responseData); int result = PNP_STATUS_SUCCESS;
memset(dtCommandResponse, 0, sizeof(*dtCommandResponse)); if (ResponseData == NULL)
dtCommandResponse->version = DIGITALTWIN_CLIENT_COMMAND_RESPONSE_VERSION_1; {
int result; LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Response Data is empty");
*CommandResponseSize = 0;
return PNP_STATUS_INTERNAL_ERROR;
}
// Allocate a copy of the response data to return to the invoker. The DigitalTwin layer that invoked the application callback *CommandResponseSize = strlen((char*)ResponseData);
// takes responsibility for freeing this data. memset(CommandResponse, 0, sizeof(*CommandResponse));
if (mallocAndStrcpy_s((char**)&dtCommandResponse->responseData, (char*)responseData) != 0)
// Allocate a copy of the response data to return to the invoker. Caller will free this.
if (mallocAndStrcpy_s((char**)CommandResponse, (char*)ResponseData) != 0)
{ {
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Unable to allocate response data"); LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Unable to allocate response data");
dtCommandResponse->status = commandStatusFailure; result = PNP_STATUS_INTERNAL_ERROR;
result = MU_FAILURE;
}
else
{
dtCommandResponse->responseDataLen = responseLen;
dtCommandResponse->status = status;
result = DIGITALTWIN_CLIENT_OK;
} }
return result; return result;
@ -117,358 +105,342 @@ static int DigitalTwinSampleEnvironmentalSensor_SetCommandResponse(
// specified in DIGITALTWIN_CLIENT_COMMAND_REQUEST, and the callback fills out data it wishes to // specified in DIGITALTWIN_CLIENT_COMMAND_REQUEST, and the callback fills out data it wishes to
// return to the caller on the service in DIGITALTWIN_CLIENT_COMMAND_RESPONSE. // return to the caller on the service in DIGITALTWIN_CLIENT_COMMAND_RESPONSE.
static void DigitalTwinSampleEnvironmentalSensor_BlinkCallback( static int DigitalTwinSampleEnvironmentalSensor_BlinkCallback(
const DIGITALTWIN_CLIENT_COMMAND_REQUEST* dtCommandRequest, PENVIRONMENT_SENSOR EnvironmentalSensor,
DIGITALTWIN_CLIENT_COMMAND_RESPONSE* dtCommandResponse, JSON_Value* CommandValue,
void* userInterfaceContext) unsigned char** CommandResponse,
size_t* CommandResponseSize)
{ {
DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE* sensorState = (DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE*)userInterfaceContext; int result = PNP_STATUS_SUCCESS;
const char * BlinkRequest;
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Blink command invoked. It has been invoked %d times previously", sensorState->numTimesBlinkCommandCalled); LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Blink command invoked. It has been invoked %d times previously", EnvironmentalSensor->SensorState->numTimesBlinkCommandCalled);
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Blink data=<%.*s>", (int)dtCommandRequest->requestDataLen, dtCommandRequest->requestData);
if ((BlinkRequest = json_value_get_string(CommandValue)) == NULL)
{
LogError("Cannot retrieve JSON string for command");
result = PNP_STATUS_BAD_FORMAT;
}
else
{
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Blink data=<%.*s>", (int)strlen(BlinkRequest), BlinkRequest);
EnvironmentalSensor->SensorState->numTimesBlinkCommandCalled++;
result = DigitalTwinSampleEnvironmentalSensor_SetCommandResponse(CommandResponse, CommandResponseSize, digitaltwinSample_EnviromentalSensor_BlinkResponse);
}
sensorState->numTimesBlinkCommandCalled++; return result;
(void)DigitalTwinSampleEnvironmentalSensor_SetCommandResponse(dtCommandResponse, digitaltwinSample_EnviromentalSensor_BlinkResponse, commandStatusSuccess);
} }
// Implement the callback to process the command "turnon". // Implement the callback to process the command "turnon".
static void DigitalTwinSampleEnvironmentalSensor_TurnOnLightCallback( static int DigitalTwinSampleEnvironmentalSensor_TurnOnLightCallback(
const DIGITALTWIN_CLIENT_COMMAND_REQUEST* dtCommandRequest, PENVIRONMENT_SENSOR EnvironmentalSensor,
DIGITALTWIN_CLIENT_COMMAND_RESPONSE* dtCommandResponse, JSON_Value* CommandValue,
void* userInterfaceContext) unsigned char** CommandResponse,
size_t* CommandResponseSize)
{ {
DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE* sensorState = (DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE*)userInterfaceContext; int result = PNP_STATUS_SUCCESS;
(void)sensorState; // Sensor state not used in this sample const char * TurnOnLightRequest;
AZURE_UNREFERENCED_PARAMETER(EnvironmentalSensor);
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Turn on light command invoked"); LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Turn on light command invoked");
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Turn on light data=<%.*s>", (int)dtCommandRequest->requestDataLen, dtCommandRequest->requestData); if ((TurnOnLightRequest = json_value_get_string(CommandValue)) == NULL)
{
LogError("Cannot retrieve JSON string for command");
result = PNP_STATUS_BAD_FORMAT;
}
else
{
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Turn on light data=<%.*s>", (int)strlen(TurnOnLightRequest), TurnOnLightRequest);
result = DigitalTwinSampleEnvironmentalSensor_SetCommandResponse(CommandResponse, CommandResponseSize, digitaltwinSample_EnviromentalSensor_TurnOnLightResponse);
}
(void)DigitalTwinSampleEnvironmentalSensor_SetCommandResponse(dtCommandResponse, digitaltwinSample_EnviromentalSensor_TurnOnLightResponse, commandStatusSuccess); return result;
} }
// Implement the callback to process the command "turnoff". // Implement the callback to process the command "turnoff".
static void DigitalTwinSampleEnvironmentalSensor_TurnOffLightCallback( static int DigitalTwinSampleEnvironmentalSensor_TurnOffLightCallback(
const DIGITALTWIN_CLIENT_COMMAND_REQUEST* dtCommandRequest, PENVIRONMENT_SENSOR EnvironmentalSensor,
DIGITALTWIN_CLIENT_COMMAND_RESPONSE* dtCommandResponse, JSON_Value* CommandValue,
void* userInterfaceContext) unsigned char** CommandResponse,
size_t* CommandResponseSize)
{ {
DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE* sensorState = (DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE*)userInterfaceContext; int result = PNP_STATUS_SUCCESS;
(void)sensorState; // Sensor state not used in this sample const char * TurnOffLightRequest;
AZURE_UNREFERENCED_PARAMETER(EnvironmentalSensor);
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Turn off light command invoked"); LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Turn off light command invoked");
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Turn off light data=<%.*s>", (int)dtCommandRequest->requestDataLen, dtCommandRequest->requestData);
(void)DigitalTwinSampleEnvironmentalSensor_SetCommandResponse(dtCommandResponse, digitaltwinSample_EnviromentalSensor_TurnOffLightResponse, commandStatusSuccess); if ((TurnOffLightRequest = json_value_get_string(CommandValue)) == NULL)
{
LogError("Cannot retrieve JSON string for command");
result = PNP_STATUS_BAD_FORMAT;
}
else
{
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Turn off light data=<%.*s>", (int)strlen(TurnOffLightRequest), TurnOffLightRequest);
result = DigitalTwinSampleEnvironmentalSensor_SetCommandResponse(CommandResponse, CommandResponseSize, digitaltwinSample_EnviromentalSensor_TurnOffLightResponse);
}
return result;
} }
// DigitalTwinSampleEnvironmentalSensor_PropertyCallback is invoked when a property is updated (or failed) going to server. // DigitalTwinSampleEnvironmentalSensor_PropertyCallback is invoked when a property is updated (or failed) going to server.
// In this sample, we route ALL property callbacks to this function and just have the userContextCallback set // In this sample, we route ALL property callbacks to this function and just have the userContextCallback set
// to the propertyName. Product code will potentially have context stored in this userContextCallback. // to the propertyName. Product code will potentially have context stored in this userContextCallback.
static void DigitalTwinSampleEnvironmentalSensor_PropertyCallback( static void DigitalTwinSampleEnvironmentalSensor_PropertyCallback(
DIGITALTWIN_CLIENT_RESULT dtReportedStatus, int ReportedStatus,
void* userContextCallback) void* UserContextCallback)
{ {
if (dtReportedStatus == DIGITALTWIN_CLIENT_OK) if (ReportedStatus == IOTHUB_CLIENT_OK)
{ {
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Updating property=<%s> succeeded", (const char*)userContextCallback); LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Updating property=<%s> succeeded", (const char*)UserContextCallback);
} }
else else
{ {
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Updating property property=<%s> failed, error=<%d>", (const char*)userContextCallback, dtReportedStatus); LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Updating property property=<%s> failed, error=<%d>", (const char*)UserContextCallback, ReportedStatus);
} }
} }
// Processes a property update, which the server initiated, for customer name. // Processes a property update, which the server initiated, for customer name.
static void DigitalTwinSampleEnvironmentalSensor_CustomerNameCallback( static void DigitalTwinSampleEnvironmentalSensor_CustomerNameCallback(
const DIGITALTWIN_CLIENT_PROPERTY_UPDATE* dtClientPropertyUpdate, PENVIRONMENT_SENSOR EnvironmentalSensor,
void* userInterfaceContext) IOTHUB_DEVICE_CLIENT_HANDLE DeviceClient,
const char* PropertyName,
JSON_Value* PropertyValue,
int version)
{ {
DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE* sensorState = (DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE*)userInterfaceContext; IOTHUB_CLIENT_RESULT iothubClientResult;
DIGITALTWIN_CLIENT_RESULT result; STRING_HANDLE jsonToSend = NULL;
size_t PropertyValueLen = json_value_get_string_len(PropertyValue);
const char * PropertyValueString = json_value_get_string(PropertyValue);
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: CustomerName property invoked..."); LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: CustomerName property invoked...");
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: CustomerName data=<%.*s>", (int)dtClientPropertyUpdate->propertyDesiredLen, dtClientPropertyUpdate->propertyDesired); LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: CustomerName data=<%.*s>", (int)PropertyValueLen, PropertyValueString);
DIGITALTWIN_CLIENT_PROPERTY_RESPONSE propertyResponse; if (EnvironmentalSensor->SensorState != NULL)
// Version of this structure for C SDK.
propertyResponse.version = DIGITALTWIN_CLIENT_PROPERTY_RESPONSE_VERSION_1;
propertyResponse.responseVersion = dtClientPropertyUpdate->desiredVersion;
free(sensorState->customerName);
if ((sensorState->customerName = (char*)malloc(dtClientPropertyUpdate->propertyDesiredLen + 1)) == NULL)
{ {
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Out of memory updating CustomerName..."); if (EnvironmentalSensor->SensorState->customerName != NULL)
{
free (EnvironmentalSensor->SensorState->customerName);
}
// Indicates failure if ((EnvironmentalSensor->SensorState->customerName = (char*)malloc(PropertyValueLen + 1)) == NULL)
propertyResponse.statusCode = 500; {
// Optional additional human readable information about status. LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Out of memory updating CustomerName...");
propertyResponse.statusDescription = "Out of memory"; }
} else
else {
{ strncpy(EnvironmentalSensor->SensorState->customerName, (char*) PropertyValueString, PropertyValueLen);
strncpy(sensorState->customerName, (char*)dtClientPropertyUpdate->propertyDesired, dtClientPropertyUpdate->propertyDesiredLen); EnvironmentalSensor->SensorState->customerName[PropertyValueLen] = 0;
sensorState->customerName[dtClientPropertyUpdate->propertyDesiredLen] = 0; LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: CustomerName sucessfully updated...");
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: CustomerName sucessfully updated...");
// Indicates success if ((jsonToSend = PnPHelper_CreateReportedPropertyWithStatus(EnvironmentalSensor->SensorState->componentName, PropertyName, PropertyValueString,
propertyResponse.statusCode = 200; PNP_STATUS_SUCCESS, g_environmentalSensorPropertyResponseDescription, version)) == NULL)
// Optional additional human readable information about status. {
propertyResponse.statusDescription = "Property Updated Successfully"; LogError("Unable to build reported property response");
} }
else
{
const char* jsonToSendStr = STRING_c_str(jsonToSend);
size_t jsonToSendStrLen = strlen(jsonToSendStr);
// if ((iothubClientResult = IoTHubDeviceClient_SendReportedState(DeviceClient, (const unsigned char*)jsonToSendStr, jsonToSendStrLen,
// DigitalTwin_InterfaceClient_ReportPropertyAsync takes the DIGITALTWIN_CLIENT_PROPERTY_RESPONSE and returns information back to service. DigitalTwinSampleEnvironmentalSensor_PropertyCallback,
// (void*) EnvironmentalSensor->SensorState->customerName)) != IOTHUB_CLIENT_OK)
result = DigitalTwin_InterfaceClient_ReportPropertyAsync(sensorState->interfaceClientHandle, digitaltwinSample_EnvironmentalSensorPropertyCustomerName, dtClientPropertyUpdate->propertyDesired, dtClientPropertyUpdate->propertyDesiredLen, {
&propertyResponse, DigitalTwinSampleEnvironmentalSensor_PropertyCallback, (void*)digitaltwinSample_EnvironmentalSensorPropertyCustomerName); LogError("ENVIRONMENTAL_SENSOR_INTERFACE: IoTHubDeviceClient_SendReportedState for customer name failed, error=%d", iothubClientResult);
if (result != DIGITALTWIN_CLIENT_OK) }
{ else
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: DigitalTwin_InterfaceClient_ReportPropertyAsync for CustomerName failed, error=<%d>", result); {
} LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Successfully queued Property update for CustomerName for component=%s", EnvironmentalSensor->SensorState->componentName);
else }
{
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Successfully queued Property update for CustomerName"); STRING_delete(jsonToSend);
}
}
} }
} }
// Processes a property update, which the server initiated, for brightness. // Validate Brightness Levels
static int DigitalTwinSampleEnvironmentalSensor_ParseBrightness( static bool DigitalTwinSampleEnvironmentalSensor_ValidateBrightness(
const char* propertyDesired, double brightness)
int* brightness)
{ {
int result; if (brightness < 0 || brightness > INT_MAX)
char* next;
*brightness = (int)strtol(propertyDesired, &next, 0);
if ((propertyDesired == next) || ((((*brightness) == INT_MAX) || ((*brightness) == INT_MIN)) && (errno != 0)))
{ {
LogError("Could not parse data=<%s> specified", propertyDesired); return false;
result = MU_FAILURE;
} }
else return true;
{
result = DIGITALTWIN_CLIENT_OK;
}
return result;
} }
// Process a property update for bright level. // Process a property update for bright level.
static void DigitalTwinSampleEnvironmentalSensor_BrightnessCallback( static void DigitalTwinSampleEnvironmentalSensor_BrightnessCallback(
const DIGITALTWIN_CLIENT_PROPERTY_UPDATE* dtClientPropertyUpdate, PENVIRONMENT_SENSOR EnvironmentalSensor,
void* userInterfaceContext) IOTHUB_DEVICE_CLIENT_HANDLE DeviceClient,
const char* PropertyName,
JSON_Value* PropertyValue,
int version)
{ {
DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE* sensorState = (DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE*)userInterfaceContext; IOTHUB_CLIENT_RESULT iothubClientResult;
DIGITALTWIN_CLIENT_RESULT result; STRING_HANDLE jsonToSend = NULL;
char targetBrightnessString[32];
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Brightness property invoked..."); LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Brightness property invoked...");
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Brightness data=<%.*s>", (int)dtClientPropertyUpdate->propertyDesiredLen, dtClientPropertyUpdate->propertyDesired);
DIGITALTWIN_CLIENT_PROPERTY_RESPONSE propertyResponse; if (json_value_get_type(PropertyValue) != JSONNumber)
int brightness;
// Version of this structure for C SDK.
propertyResponse.version = DIGITALTWIN_CLIENT_PROPERTY_RESPONSE_VERSION_1;
propertyResponse.responseVersion = dtClientPropertyUpdate->desiredVersion;
if (DigitalTwinSampleEnvironmentalSensor_ParseBrightness((const char*)dtClientPropertyUpdate->propertyDesired, &brightness) != 0)
{ {
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Invalid brightness data=<%.*s> specified", (int)dtClientPropertyUpdate->propertyDesiredLen, dtClientPropertyUpdate->propertyDesired); LogError("JSON field %s is not a number", PropertyName);
// Indicates failure
propertyResponse.statusCode = 500;
// Optional additional human readable information about status.
propertyResponse.statusDescription = "Invalid brightness setting";
} }
else else if(EnvironmentalSensor == NULL || EnvironmentalSensor->SensorState == NULL)
{ {
sensorState->brightness = brightness; LogError("Environmental sensor device context not initialized correctly.");
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Brightness successfully updated to %d...", sensorState->brightness);
// Indicates success
propertyResponse.statusCode = 200;
// Optional additional human readable information about status.
propertyResponse.statusDescription = "Brightness updated";
} }
else if (DigitalTwinSampleEnvironmentalSensor_ValidateBrightness(json_value_get_number(PropertyValue)))
{
EnvironmentalSensor->SensorState->brightness = (int) json_value_get_number(PropertyValue);
if (snprintf(targetBrightnessString, sizeof(targetBrightnessString),
g_environmentalSensorBrightnessResponseFormat, EnvironmentalSensor->SensorState->brightness) < 0)
{
LogError("Unable to create target brightness string for reporting result");
}
else if ((jsonToSend = PnPHelper_CreateReportedPropertyWithStatus(EnvironmentalSensor->SensorState->componentName,
PropertyName, targetBrightnessString, PNP_STATUS_SUCCESS, g_environmentalSensorPropertyResponseDescription,
version)) == NULL)
{
LogError("Unable to build reported property response");
}
else
{
const char* jsonToSendStr = STRING_c_str(jsonToSend);
size_t jsonToSendStrLen = strlen(jsonToSendStr);
// if ((iothubClientResult = IoTHubDeviceClient_SendReportedState(DeviceClient, (const unsigned char*)jsonToSendStr, jsonToSendStrLen,
// DigitalTwin_InterfaceClient_ReportPropertyAsync takes the DIGITALTWIN_CLIENT_PROPERTY_RESPONSE and returns information back to service. DigitalTwinSampleEnvironmentalSensor_PropertyCallback,
// (void*) &EnvironmentalSensor->SensorState->brightness)) != IOTHUB_CLIENT_OK)
result = DigitalTwin_InterfaceClient_ReportPropertyAsync(sensorState->interfaceClientHandle, digitaltwinSample_EnvironmentalSensorPropertyBrightness, dtClientPropertyUpdate->propertyDesired, dtClientPropertyUpdate->propertyDesiredLen, {
&propertyResponse, DigitalTwinSampleEnvironmentalSensor_PropertyCallback, (void*)digitaltwinSample_EnvironmentalSensorPropertyBrightness); LogError("ENVIRONMENTAL_SENSOR_INTERFACE: IoTHubDeviceClient_SendReportedState for brightness failed, error=%d", iothubClientResult);
if (result != DIGITALTWIN_CLIENT_OK) }
{ else
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: DigitalTwin_InterfaceClient_ReportPropertyAsync for Brightness failed, error=<%d>", result); {
} LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Successfully queued Property update for Brightness for component=%s", EnvironmentalSensor->SensorState->componentName);
else }
{
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Successfully queued Property update for Brightness"); STRING_delete(jsonToSend);
}
} }
} }
// Sends a reported property for device state of this simulated device. // Sends a reported property for device state of this simulated device.
static DIGITALTWIN_CLIENT_RESULT DigitalTwinSampleEnvironmentalSensor_ReportDeviceStateAsync( IOTHUB_CLIENT_RESULT DigitalTwinSampleEnvironmentalSensor_ReportDeviceStateAsync(
DIGITALTWIN_INTERFACE_CLIENT_HANDLE interfaceHandle) IOTHUB_DEVICE_CLIENT_HANDLE DeviceClient,
const char * ComponentName)
{ {
DIGITALTWIN_CLIENT_RESULT result;
result = DigitalTwin_InterfaceClient_ReportPropertyAsync(interfaceHandle, digitaltwinSample_DeviceStateProperty, digitaltwinSample_DeviceStateData, IOTHUB_CLIENT_RESULT iothubClientResult = IOTHUB_CLIENT_OK;
digitaltwinSample_DeviceStateDataLen, NULL, DigitalTwinSampleEnvironmentalSensor_PropertyCallback, (void*)digitaltwinSample_DeviceStateProperty); STRING_HANDLE jsonToSend = NULL;
if (result != DIGITALTWIN_CLIENT_OK) if ((jsonToSend = PnPHelper_CreateReportedProperty(ComponentName, digitaltwinSample_DeviceStateProperty, (const char*) digitaltwinSample_DeviceStateData)) == NULL)
{ {
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Reporting property=<%s> failed, error=<%d>", digitaltwinSample_DeviceStateProperty, result); LogError("Unable to build reported property response for propertyName=%s, propertyValue=%s", digitaltwinSample_DeviceStateProperty, digitaltwinSample_DeviceStateData);
} }
else else
{ {
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Queued async report read only property for %s", digitaltwinSample_DeviceStateProperty); const char* jsonToSendStr = STRING_c_str(jsonToSend);
size_t jsonToSendStrLen = strlen(jsonToSendStr);
if ((iothubClientResult = IoTHubDeviceClient_SendReportedState(DeviceClient, (const unsigned char*)jsonToSendStr, jsonToSendStrLen,
DigitalTwinSampleEnvironmentalSensor_PropertyCallback, (void*)digitaltwinSample_DeviceStateProperty)) != IOTHUB_CLIENT_OK)
{
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Unable to send reported state for property=%s, error=%d",
digitaltwinSample_DeviceStateProperty, iothubClientResult);
}
else
{
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Sending device information property to IoTHub. propertyName=%s, propertyValue=%s",
digitaltwinSample_DeviceStateProperty, digitaltwinSample_DeviceStateData);
}
STRING_delete(jsonToSend);
} }
return result; return iothubClientResult;
}
// DigitalTwinSampleEnvironmentalSensor_InterfaceRegisteredCallback is invoked when this interface
// is successfully or unsuccessfully registered with the service, and also when the interface is deleted.
static void DigitalTwinSampleEnvironmentalSensor_InterfaceRegisteredCallback(
DIGITALTWIN_CLIENT_RESULT dtInterfaceStatus,
void* userInterfaceContext)
{
DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE* sensorState = (DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR_STATE*)userInterfaceContext;
if (dtInterfaceStatus == DIGITALTWIN_CLIENT_OK)
{
// Once the interface is registered, send our reported properties to the service.
// It *IS* safe to invoke most DigitalTwin API calls from a callback thread like this, though it
// is NOT safe to create/destroy/register interfaces now.
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Interface successfully registered.");
DigitalTwinSampleEnvironmentalSensor_ReportDeviceStateAsync(sensorState->interfaceClientHandle);
}
else if (dtInterfaceStatus == DIGITALTWIN_CLIENT_ERROR_INTERFACE_UNREGISTERING)
{
// Once an interface is marked as unregistered, it cannot be used for any DigitalTwin SDK calls.
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Interface received unregistering callback.");
}
else
{
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Interface received failed, status=<%d>.", dtInterfaceStatus);
}
} }
// DigitalTwinSample_ProcessCommandUpdate receives commands from the server. This implementation acts as a simple dispatcher // DigitalTwinSample_ProcessCommandUpdate receives commands from the server. This implementation acts as a simple dispatcher
// to the functions to perform the actual processing. // to the functions to perform the actual processing.
void DigitalTwinSample_ProcessCommandUpdate( int DigitalTwinSample_ProcessCommandUpdate(
const DIGITALTWIN_CLIENT_COMMAND_REQUEST* dtCommandRequest, PENVIRONMENT_SENSOR EnvironmentalSensor,
DIGITALTWIN_CLIENT_COMMAND_RESPONSE* dtCommandResponse, const char* CommandName,
void* userInterfaceContext) JSON_Value* CommandValue,
unsigned char** CommandResponse,
size_t* CommandResponseSize)
{ {
if (strcmp(dtCommandRequest->commandName, digitaltwinSample_EnvironmentalSensorCommandBlink) == 0) if (strcmp(CommandName, digitaltwinSample_EnvironmentalSensorCommandBlink) == 0)
{ {
DigitalTwinSampleEnvironmentalSensor_BlinkCallback(dtCommandRequest, dtCommandResponse, userInterfaceContext); return DigitalTwinSampleEnvironmentalSensor_BlinkCallback(EnvironmentalSensor, CommandValue, CommandResponse, CommandResponseSize);
} }
else if (strcmp(dtCommandRequest->commandName, digitaltwinSample_EnvironmentalSensorCommandTurnOn) == 0) else if (strcmp(CommandName, digitaltwinSample_EnvironmentalSensorCommandTurnOn) == 0)
{ {
DigitalTwinSampleEnvironmentalSensor_TurnOnLightCallback(dtCommandRequest, dtCommandResponse, userInterfaceContext); return DigitalTwinSampleEnvironmentalSensor_TurnOnLightCallback(EnvironmentalSensor, CommandValue, CommandResponse, CommandResponseSize);
} }
else if (strcmp(dtCommandRequest->commandName, digitaltwinSample_EnvironmentalSensorCommandTurnOff) == 0) else if (strcmp(CommandName, digitaltwinSample_EnvironmentalSensorCommandTurnOff) == 0)
{ {
DigitalTwinSampleEnvironmentalSensor_TurnOffLightCallback(dtCommandRequest, dtCommandResponse, userInterfaceContext); return DigitalTwinSampleEnvironmentalSensor_TurnOffLightCallback(EnvironmentalSensor, CommandValue, CommandResponse, CommandResponseSize);
} }
else else
{ {
// If the command is not implemented by this interface, by convention we return a 404 error to server. // If the command is not implemented by this interface, by convention we return a 404 error to server.
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Command name <%s> is not associated with this interface", dtCommandRequest->commandName); LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Command name <%s> is not associated with this interface", CommandName);
(void)DigitalTwinSampleEnvironmentalSensor_SetCommandResponse(dtCommandResponse, digitaltwinSample_EnviromentalSensor_NotImplemented, commandStatusNotPresent); return DigitalTwinSampleEnvironmentalSensor_SetCommandResponse(CommandResponse, CommandResponseSize, digitaltwinSample_EnviromentalSensor_NotImplemented);
} }
} }
// DigitalTwinSampleEnvironmentalSensor_ProcessPropertyUpdate receives updated properties from the server. This implementation // DigitalTwinSampleEnvironmentalSensor_ProcessPropertyUpdate receives updated properties from the server. This implementation
// acts as a simple dispatcher to the functions to perform the actual processing. // acts as a simple dispatcher to the functions to perform the actual processing.
static void DigitalTwinSampleEnvironmentalSensor_ProcessPropertyUpdate( void DigitalTwinSampleEnvironmentalSensor_ProcessPropertyUpdate(
const DIGITALTWIN_CLIENT_PROPERTY_UPDATE* dtClientPropertyUpdate, PENVIRONMENT_SENSOR EnvironmentalSensor,
void* userInterfaceContext) IOTHUB_DEVICE_CLIENT_HANDLE DeviceClient,
const char* PropertyName,
JSON_Value* PropertyValue,
int version)
{ {
if (strcmp(dtClientPropertyUpdate->propertyName, digitaltwinSample_EnvironmentalSensorPropertyCustomerName) == 0) if (strcmp(PropertyName, digitaltwinSample_EnvironmentalSensorPropertyCustomerName) == 0)
{ {
DigitalTwinSampleEnvironmentalSensor_CustomerNameCallback(dtClientPropertyUpdate, userInterfaceContext); DigitalTwinSampleEnvironmentalSensor_CustomerNameCallback(EnvironmentalSensor, DeviceClient, PropertyName, PropertyValue, version);
} }
else if (strcmp(dtClientPropertyUpdate->propertyName, digitaltwinSample_EnvironmentalSensorPropertyBrightness) == 0) else if (strcmp(PropertyName, digitaltwinSample_EnvironmentalSensorPropertyBrightness) == 0)
{ {
DigitalTwinSampleEnvironmentalSensor_BrightnessCallback(dtClientPropertyUpdate, userInterfaceContext); DigitalTwinSampleEnvironmentalSensor_BrightnessCallback(EnvironmentalSensor, DeviceClient, PropertyName, PropertyValue, version);
} }
else if (strcmp(dtClientPropertyUpdate->propertyName, digitaltwinSample_DeviceStateProperty) == 0) else if (strcmp(PropertyName, digitaltwinSample_DeviceStateProperty) == 0)
{ {
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Property name <%s>, last reported value=<%.*s>", LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Property name <%s>, last reported value=<%.*s>",
dtClientPropertyUpdate->propertyName, (int)dtClientPropertyUpdate->propertyReportedLen, dtClientPropertyUpdate->propertyReported); PropertyName, (int)json_value_get_string_len(PropertyValue), json_value_get_string(PropertyValue));
} }
else else
{ {
// If the property is not implemented by this interface, presently we only record a log message but do not have a mechanism to report back to the service // If the property is not implemented by this interface, presently we only record a log message but do not have a mechanism to report back to the service
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Property name <%s> is not associated with this interface", dtClientPropertyUpdate->propertyName); LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Property name <%s> is not associated with this interface", PropertyName);
} }
} }
//
// DigitalTwinSampleEnvironmentalSensor_CreateInterface is the initial entry point into the DigitalTwin Sample Environmental Sensor interface.
// It simply creates a DIGITALTWIN_INTERFACE_CLIENT_HANDLE that is mapped to the environmental sensor component.
// This call is synchronous, as simply creating an interface only performs initial allocations.
//
// NOTE: The actual registration of this interface is left to the caller, which may register
// multiple interfaces on one DIGITALTWIN_DEVICE_CLIENT_HANDLE.
//
DIGITALTWIN_INTERFACE_CLIENT_HANDLE DigitalTwinSampleEnvironmentalSensor_CreateInterface(
const char* ComponentName)
{
DIGITALTWIN_INTERFACE_CLIENT_HANDLE interfaceHandle;
DIGITALTWIN_CLIENT_RESULT result;
memset(&digitaltwinSample_EnvironmentalSensorState, 0, sizeof(digitaltwinSample_EnvironmentalSensorState));
if ((result = DigitalTwin_InterfaceClient_Create(ComponentName, DigitalTwinSampleEnvironmentalSensor_InterfaceRegisteredCallback, (void*)&digitaltwinSample_EnvironmentalSensorState, &interfaceHandle)) != DIGITALTWIN_CLIENT_OK)
{
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Unable to allocate interface client handle for componentName=<%s>, error=<%d>", ComponentName, result);
interfaceHandle = NULL;
}
else if ((result = DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback(interfaceHandle, DigitalTwinSampleEnvironmentalSensor_ProcessPropertyUpdate, (void*)&digitaltwinSample_EnvironmentalSensorState)) != DIGITALTWIN_CLIENT_OK)
{
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback failed. error=<%d>", result);
DigitalTwinSampleEnvironmentalSensor_Close(interfaceHandle);
interfaceHandle = NULL;
}
else if ((result = DigitalTwin_InterfaceClient_SetCommandsCallback(interfaceHandle, DigitalTwinSample_ProcessCommandUpdate, (void*)&digitaltwinSample_EnvironmentalSensorState)) != DIGITALTWIN_CLIENT_OK)
{
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: DigitalTwin_InterfaceClient_SetCommandsCallback failed. error=<%d>", result);
DigitalTwinSampleEnvironmentalSensor_Close(interfaceHandle);
interfaceHandle = NULL;
}
else
{
LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Created DIGITALTWIN_INTERFACE_CLIENT_HANDLE. componentName=<%s>, handle=<%p>", ComponentName, interfaceHandle);
digitaltwinSample_EnvironmentalSensorState.interfaceClientHandle = interfaceHandle;
}
return interfaceHandle;
}
// DigitalTwinSampleEnvironmentalSensor_TelemetryCallback is invoked when a DigitalTwin telemetry message // DigitalTwinSampleEnvironmentalSensor_TelemetryCallback is invoked when a DigitalTwin telemetry message
// is either successfully delivered to the service or else fails. For this sample, the userContextCallback // is either successfully delivered to the service or else fails. For this sample, the userContextCallback
// is simply a string pointing to the name of the message sent. More complex scenarios may include // is simply a string pointing to the name of the message sent. More complex scenarios may include
// more detailed state information as part of this callback. // more detailed state information as part of this callback.
static void DigitalTwinSampleEnvironmentalSensor_TelemetryCallback( static void DigitalTwinSampleEnvironmentalSensor_TelemetryCallback(
DIGITALTWIN_CLIENT_RESULT dtTelemetryStatus, IOTHUB_CLIENT_CONFIRMATION_RESULT TelemetryStatus,
void* userContextCallback) void* UserContextCallback)
{ {
if (dtTelemetryStatus == DIGITALTWIN_CLIENT_OK) PENVIRONMENT_SENSOR device = (PENVIRONMENT_SENSOR) UserContextCallback;
if (TelemetryStatus == IOTHUB_CLIENT_CONFIRMATION_OK)
{ {
// This tends to overwhelm the logging on output based on how frequently this function is invoked, so removing by default. LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: Successfully delivered telemetry message for <%s>", (const char*)device->SensorState->componentName);
// LogInfo("ENVIRONMENTAL_SENSOR_INTERFACE: DigitalTwin successfully delivered telemetry message for <%s>", (const char*)userContextCallback);
} }
else else
{ {
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: DigitalTwin failed delivered telemetry message for <%s>, error=<%d>", (const char*)userContextCallback, dtTelemetryStatus); LogError("ENVIRONMENTAL_SENSOR_INTERFACE: Failed delivered telemetry message for <%s>, error=<%d>", (const char*)device->SensorState->componentName, TelemetryStatus);
} }
} }
@ -477,43 +449,31 @@ static void DigitalTwinSampleEnvironmentalSensor_TelemetryCallback(
// send telemetry containing the current temperature and humidity (in both cases random numbers // send telemetry containing the current temperature and humidity (in both cases random numbers
// so this sample will work on platforms without these sensors). // so this sample will work on platforms without these sensors).
// //
DIGITALTWIN_CLIENT_RESULT DigitalTwinSampleEnvironmentalSensor_SendTelemetryMessagesAsync( IOTHUB_CLIENT_RESULT DigitalTwinSampleEnvironmentalSensor_SendTelemetryMessagesAsync(
DIGITALTWIN_INTERFACE_CLIENT_HANDLE interfaceHandle) PENVIRONMENT_SENSOR EnvironmentalSensor)
{ {
DIGITALTWIN_CLIENT_RESULT result; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
IOTHUB_MESSAGE_HANDLE messageHandle = NULL;
float currentTemperature = 20.0f + ((float)rand() / RAND_MAX) * 15.0f; float currentTemperature = 20.0f + ((float)rand() / RAND_MAX) * 15.0f;
float currentHumidity = 60.0f + ((float)rand() / RAND_MAX) * 20.0f; float currentHumidity = 60.0f + ((float)rand() / RAND_MAX) * 20.0f;
char currentMessage[128]; char currentMessage[128];
sprintf(currentMessage, "{\"%s\":%.3f, \"%s\":%.3f}", DigitalTwinSampleEnvironmentalSensor_TemperatureTelemetry, currentTemperature, DigitalTwinSampleEnvironmentalSensor_HumidityTelemetry, currentHumidity); sprintf(currentMessage, "{\"%s\":%.3f, \"%s\":%.3f}", DigitalTwinSampleEnvironmentalSensor_TemperatureTelemetry,
currentTemperature, DigitalTwinSampleEnvironmentalSensor_HumidityTelemetry, currentHumidity);
if ((result = DigitalTwin_InterfaceClient_SendTelemetryAsync(interfaceHandle, (unsigned char*)currentMessage, strlen(currentMessage),
DigitalTwinSampleEnvironmentalSensor_TelemetryCallback, NULL)) != DIGITALTWIN_CLIENT_OK) if ((messageHandle = PnPHelper_CreateTelemetryMessageHandle(EnvironmentalSensor->SensorState->componentName, currentMessage)) == NULL)
{ {
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: DigitalTwin_InterfaceClient_SendTelemetryAsync failed for sending."); LogError("ENVIRONMENTAL_SENSOR_INTERFACE: PnPHelper_CreateTelemetryMessageHandle failed.");
}
else if ((result = IoTHubDeviceClient_SendEventAsync(EnvironmentalSensor->DeviceClient, messageHandle,
DigitalTwinSampleEnvironmentalSensor_TelemetryCallback, EnvironmentalSensor)) != IOTHUB_CLIENT_OK)
{
LogError("ENVIRONMENTAL_SENSOR_INTERFACE: IoTHubDeviceClient_SendEventAsync failed, error=%d", result);
} }
IoTHubMessage_Destroy(messageHandle);
return result; return result;
} }
//
// DigitalTwinSampleEnvironmentalSensor_Close is invoked when the sample device is shutting down.
//
void DigitalTwinSampleEnvironmentalSensor_Close(
DIGITALTWIN_INTERFACE_CLIENT_HANDLE interfaceHandle)
{
// On shutdown, in general the first call made should be to DigitalTwin_InterfaceClient_Destroy.
// This will block if there are any active callbacks in this interface, and then
// mark the underlying handle such that no future callbacks shall come to it.
DigitalTwin_InterfaceClient_Destroy(interfaceHandle);
// After DigitalTwin_InterfaceClient_Destroy returns, it is safe to assume
// no more callbacks shall arrive for this interface and it is OK to free
// resources callbacks otherwise may have needed.
free(digitaltwinSample_EnvironmentalSensorState.customerName);
digitaltwinSample_EnvironmentalSensorState.customerName = NULL;
}

Просмотреть файл

@ -2,25 +2,60 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
// Header file for sample for manipulating DigitalTwin Interface for device info. // Header file for sample for manipulating DigitalTwin Interface for device info.
#pragma once
#ifndef DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR #ifndef DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR
#define DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR #define DIGITALTWIN_SAMPLE_ENVIRONMENTAL_SENSOR
#include "digitaltwin_interface_client.h" #include "environmental_sensor_pnpbridge.h"
// PnP helper utilities.
#include "pnp_device_client_helpers.h"
#include "pnp_protocol_helpers.h"
//
// Application state associated with the particular interface. In particular it contains
// the DIGITALTWIN_INTERFACE_CLIENT_HANDLE used for responses in callbacks along with properties set
// and representations of the property update and command callbacks invoked on given interface
//
typedef struct ENVIRONMENTAL_SENSOR_STATE_TAG
{
char componentName[PNP_MAXIMUM_COMPONENT_LENGTH + 1];
int brightness;
char* customerName;
int numTimesBlinkCommandCalled;
} ENVIRONMENTAL_SENSOR_STATE, * PENVIRONMENTAL_SENSOR_STATE;
typedef struct _ENVIRONMENT_SENSOR {
THREAD_HANDLE WorkerHandle;
volatile bool ShuttingDown;
PENVIRONMENTAL_SENSOR_STATE SensorState;
IOTHUB_DEVICE_CLIENT_HANDLE DeviceClient;
} ENVIRONMENT_SENSOR, * PENVIRONMENT_SENSOR;
#ifdef __cplusplus #ifdef __cplusplus
extern "C" extern "C"
{ {
#endif #endif
// Creates a new DIGITALTWIN_INTERFACE_CLIENT_HANDLE for this interface.
DIGITALTWIN_INTERFACE_CLIENT_HANDLE DigitalTwinSampleEnvironmentalSensor_CreateInterface(const char* ComponentName);
// Sends DigitalTwin telemetry messages about current environment // Sends DigitalTwin telemetry messages about current environment
DIGITALTWIN_CLIENT_RESULT DigitalTwinSampleEnvironmentalSensor_SendTelemetryMessagesAsync(DIGITALTWIN_INTERFACE_CLIENT_HANDLE interfaceHandle); IOTHUB_CLIENT_RESULT DigitalTwinSampleEnvironmentalSensor_SendTelemetryMessagesAsync(
PENVIRONMENT_SENSOR EnvironmentalSensor);
// Closes down resources associated with device info interface. IOTHUB_CLIENT_RESULT DigitalTwinSampleEnvironmentalSensor_ReportDeviceStateAsync(
void DigitalTwinSampleEnvironmentalSensor_Close(DIGITALTWIN_INTERFACE_CLIENT_HANDLE interfaceHandle); IOTHUB_DEVICE_CLIENT_HANDLE DeviceClient,
const char * ComponentName);
void DigitalTwinSampleEnvironmentalSensor_ProcessPropertyUpdate(
PENVIRONMENT_SENSOR EnvironmentalSensor,
IOTHUB_DEVICE_CLIENT_HANDLE DeviceClient,
const char* PropertyName,
JSON_Value* PropertyValue,
int version);
int DigitalTwinSample_ProcessCommandUpdate(
PENVIRONMENT_SENSOR EnvironmentalSensor,
const char* CommandName,
JSON_Value* CommandValue,
unsigned char** CommandResponse,
size_t* CommandResponseSize);
#ifdef __cplusplus #ifdef __cplusplus
} }

Просмотреть файл

@ -1,28 +1,7 @@
// Copyright (c) Microsoft. All rights reserved. // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include <pnpbridge.h>
#include "azure_c_shared_utility/azure_base32.h"
#include "azure_c_shared_utility/gballoc.h"
#include "azure_c_shared_utility/xlogging.h"
#include "azure_c_shared_utility/threadapi.h"
#include "azure_c_shared_utility/singlylinkedlist.h"
#include "azure_c_shared_utility/lock.h"
#include "azure_c_shared_utility/const_defines.h"
#include "parson.h"
#include "environmental_sensor_pnpbridge.h" #include "environmental_sensor_pnpbridge.h"
#include "environmental_sensor.h"
typedef struct _ENVIRONMENT_SENSOR {
DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpinterfaceHandle;
THREAD_HANDLE WorkerHandle;
volatile bool ShuttingDown;
} ENVIRONMENT_SENSOR, * PENVIRONMENT_SENSOR;
int EnvironmentSensor_TelemetryWorker( int EnvironmentSensor_TelemetryWorker(
void* context) void* context)
@ -32,34 +11,41 @@ int EnvironmentSensor_TelemetryWorker(
// Report telemetry every 5 minutes till we are asked to stop // Report telemetry every 5 minutes till we are asked to stop
while (true) { while (true) {
if (device->ShuttingDown) { if (device->ShuttingDown) {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DigitalTwinSampleEnvironmentalSensor_SendTelemetryMessagesAsync(device->pnpinterfaceHandle); DigitalTwinSampleEnvironmentalSensor_SendTelemetryMessagesAsync(device);
// Sleep for 5 sec // Sleep for 5 sec
ThreadAPI_Sleep(5000); ThreadAPI_Sleep(5000);
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT EnvironmentSensor_StartPnpInterface( IOTHUB_CLIENT_RESULT EnvironmentSensor_StartPnpInterface(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
AZURE_UNREFERENCED_PARAMETER(AdapterHandle); AZURE_UNREFERENCED_PARAMETER(AdapterHandle);
PENVIRONMENT_SENSOR device = PnpInterfaceHandleGetContext(PnpInterfaceHandle); PENVIRONMENT_SENSOR device = PnpInterfaceHandleGetContext(PnpInterfaceHandle);
IOTHUB_DEVICE_CLIENT_HANDLE deviceHandle = PnpInterfaceHandleGetIotHubDeviceClient(PnpInterfaceHandle);
device->DeviceClient = deviceHandle;
// Report Device State Async
result = DigitalTwinSampleEnvironmentalSensor_ReportDeviceStateAsync(deviceHandle, device->SensorState->componentName);
device->ShuttingDown = false;
// Create a thread to periodically publish telemetry // Create a thread to periodically publish telemetry
if (ThreadAPI_Create(&device->WorkerHandle, EnvironmentSensor_TelemetryWorker, device) != THREADAPI_OK) { if (ThreadAPI_Create(&device->WorkerHandle, EnvironmentSensor_TelemetryWorker, device) != THREADAPI_OK) {
LogError("ThreadAPI_Create failed"); LogError("ThreadAPI_Create failed");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT EnvironmentSensor_StopPnpInterface( IOTHUB_CLIENT_RESULT EnvironmentSensor_StopPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
PENVIRONMENT_SENSOR device = PnpInterfaceHandleGetContext(PnpInterfaceHandle); PENVIRONMENT_SENSOR device = PnpInterfaceHandleGetContext(PnpInterfaceHandle);
@ -68,76 +54,116 @@ DIGITALTWIN_CLIENT_RESULT EnvironmentSensor_StopPnpInterface(
device->ShuttingDown = true; device->ShuttingDown = true;
ThreadAPI_Join(device->WorkerHandle, NULL); ThreadAPI_Join(device->WorkerHandle, NULL);
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT EnvironmentSensor_DestroyPnpInterface( IOTHUB_CLIENT_RESULT EnvironmentSensor_DestroyPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
PENVIRONMENT_SENSOR device = PnpInterfaceHandleGetContext(PnpInterfaceHandle); PENVIRONMENT_SENSOR device = PnpInterfaceHandleGetContext(PnpInterfaceHandle);
if (device) if (device != NULL)
{ {
DigitalTwinSampleEnvironmentalSensor_Close(device->pnpinterfaceHandle); if (device->SensorState != NULL)
{
if (device->SensorState->customerName != NULL)
{
free(device->SensorState->customerName);
}
free(device->SensorState);
}
free(device); free(device);
PnpInterfaceHandleSetContext(PnpInterfaceHandle, NULL); PnpInterfaceHandleSetContext(PnpInterfaceHandle, NULL);
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT IOTHUB_CLIENT_RESULT
EnvironmentSensor_CreatePnpInterface( EnvironmentSensor_CreatePnpInterface(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
const char* ComponentName, const char* ComponentName,
const JSON_Object* AdapterInterfaceConfig, const JSON_Object* AdapterInterfaceConfig,
PNPBRIDGE_INTERFACE_HANDLE BridgeInterfaceHandle, PNPBRIDGE_INTERFACE_HANDLE BridgeInterfaceHandle)
DIGITALTWIN_INTERFACE_CLIENT_HANDLE* PnpInterfaceClient)
{ {
AZURE_UNREFERENCED_PARAMETER(AdapterInterfaceConfig); AZURE_UNREFERENCED_PARAMETER(AdapterInterfaceConfig);
AZURE_UNREFERENCED_PARAMETER(AdapterHandle); AZURE_UNREFERENCED_PARAMETER(AdapterHandle);
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterfaceClient;
PENVIRONMENT_SENSOR device = NULL; PENVIRONMENT_SENSOR device = NULL;
device = calloc(1, sizeof(ENVIRONMENT_SENSOR)); if (strlen(ComponentName) > PNP_MAXIMUM_COMPONENT_LENGTH)
if (NULL == device) { {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; LogError("ComponentName=%s is too long. Maximum length is=%d", ComponentName, PNP_MAXIMUM_COMPONENT_LENGTH);
goto exit; BridgeInterfaceHandle = NULL;
} result = IOTHUB_CLIENT_ERROR;
device->ShuttingDown = false;
pnpInterfaceClient = DigitalTwinSampleEnvironmentalSensor_CreateInterface(ComponentName);
if (NULL == pnpInterfaceClient) {
result = DIGITALTWIN_CLIENT_ERROR;
goto exit; goto exit;
} }
device->pnpinterfaceHandle = pnpInterfaceClient; device = calloc(1, sizeof(ENVIRONMENT_SENSOR));
if (NULL == device) {
LogError("Unable to allocate memory for environmental sensor.");
result = IOTHUB_CLIENT_ERROR;
goto exit;
}
device->SensorState = calloc(1, sizeof(ENVIRONMENTAL_SENSOR_STATE));
if (NULL == device) {
LogError("Unable to allocate memory for environmental sensor state.");
result = IOTHUB_CLIENT_ERROR;
goto exit;
}
memset(&device->SensorState, 0, sizeof(device->SensorState));
strcpy(device->SensorState->componentName, ComponentName);
PnpInterfaceHandleSetContext(BridgeInterfaceHandle, device); PnpInterfaceHandleSetContext(BridgeInterfaceHandle, device);
*PnpInterfaceClient = pnpInterfaceClient;
exit: exit:
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT EnvironmentSensor_CreatePnpAdapter( IOTHUB_CLIENT_RESULT EnvironmentSensor_CreatePnpAdapter(
const JSON_Object* AdapterGlobalConfig, const JSON_Object* AdapterGlobalConfig,
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle) PNPBRIDGE_ADAPTER_HANDLE AdapterHandle)
{ {
AZURE_UNREFERENCED_PARAMETER(AdapterGlobalConfig); AZURE_UNREFERENCED_PARAMETER(AdapterGlobalConfig);
AZURE_UNREFERENCED_PARAMETER(AdapterHandle); AZURE_UNREFERENCED_PARAMETER(AdapterHandle);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT EnvironmentSensor_DestroyPnpAdapter( IOTHUB_CLIENT_RESULT EnvironmentSensor_DestroyPnpAdapter(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle) PNPBRIDGE_ADAPTER_HANDLE AdapterHandle)
{ {
AZURE_UNREFERENCED_PARAMETER(AdapterHandle); AZURE_UNREFERENCED_PARAMETER(AdapterHandle);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
}
void EnvironmentSensor_ProcessPropertyUpdate(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle,
const char* PropertyName,
JSON_Value* PropertyValue,
int version,
void* userContextCallback
)
{
PENVIRONMENT_SENSOR device = PnpInterfaceHandleGetContext(PnpInterfaceHandle);
IOTHUB_DEVICE_CLIENT_HANDLE deviceClient = (IOTHUB_DEVICE_CLIENT_HANDLE)userContextCallback;
DigitalTwinSampleEnvironmentalSensor_ProcessPropertyUpdate(device, deviceClient, PropertyName, PropertyValue, version);
}
int EnvironmentalSensor_ProcessCommand(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle,
const char* CommandName,
JSON_Value* CommandValue,
unsigned char** CommandResponse,
size_t* CommandResponseSize
)
{
PENVIRONMENT_SENSOR device = PnpInterfaceHandleGetContext(PnpInterfaceHandle);
return DigitalTwinSample_ProcessCommandUpdate(device, CommandName, CommandValue, CommandResponse, CommandResponseSize);
} }
PNP_ADAPTER EnvironmentSensorInterface = { PNP_ADAPTER EnvironmentSensorInterface = {
@ -148,6 +174,8 @@ PNP_ADAPTER EnvironmentSensorInterface = {
.stopPnpInterface = EnvironmentSensor_StopPnpInterface, .stopPnpInterface = EnvironmentSensor_StopPnpInterface,
.destroyPnpInterface = EnvironmentSensor_DestroyPnpInterface, .destroyPnpInterface = EnvironmentSensor_DestroyPnpInterface,
.destroyAdapter = EnvironmentSensor_DestroyPnpAdapter, .destroyAdapter = EnvironmentSensor_DestroyPnpAdapter,
.processPropertyUpdate = EnvironmentSensor_ProcessPropertyUpdate,
.processCommand = EnvironmentalSensor_ProcessCommand
}; };
int main(int argc, char *argv[]) int main(int argc, char *argv[])

Просмотреть файл

@ -7,7 +7,19 @@
extern "C" extern "C"
{ {
#endif #endif
#include <pnpbridge.h>
#include "azure_c_shared_utility/azure_base32.h"
#include "azure_c_shared_utility/gballoc.h"
#include "azure_c_shared_utility/xlogging.h"
#include "azure_c_shared_utility/threadapi.h"
#include "azure_c_shared_utility/singlylinkedlist.h"
#include "azure_c_shared_utility/lock.h"
#include "azure_c_shared_utility/const_defines.h"
#include "parson.h"
#include "environmental_sensor.h"
#ifdef __cplusplus #ifdef __cplusplus
} }

Просмотреть файл

@ -121,7 +121,7 @@ HRESULT CameraIotPnpDevice::ReportProperty(
{ {
AutoLock lock(&m_lock); AutoLock lock(&m_lock);
DIGITALTWIN_CLIENT_RESULT result; IOTHUB_CLIENT_RESULT result;
AZURE_UNREFERENCED_PARAMETER(readOnly); AZURE_UNREFERENCED_PARAMETER(readOnly);
AZURE_UNREFERENCED_PARAMETER(propertyDataLen); AZURE_UNREFERENCED_PARAMETER(propertyDataLen);
@ -135,7 +135,7 @@ HRESULT CameraIotPnpDevice::ReportProperty(
nullptr, nullptr,
CameraIotPnpDevice_PropertyCallback, CameraIotPnpDevice_PropertyCallback,
(void*)propertyName); (void*)propertyName);
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
LogError("DEVICE_INFO: Reporting property=<%s> failed, error=<%d>", propertyName, result); LogError("DEVICE_INFO: Reporting property=<%s> failed, error=<%d>", propertyName, result);
} }
@ -154,7 +154,7 @@ HRESULT CameraIotPnpDevice::ReportTelemetry(
{ {
AutoLock lock(&m_lock); AutoLock lock(&m_lock);
DIGITALTWIN_CLIENT_RESULT result; IOTHUB_CLIENT_RESULT result;
RETURN_HR_IF_NULL (HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE), m_PnpClientInterface); RETURN_HR_IF_NULL (HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE), m_PnpClientInterface);
@ -168,7 +168,7 @@ HRESULT CameraIotPnpDevice::ReportTelemetry(
strlen(telemetryMessage), strlen(telemetryMessage),
CameraIotPnpDevice_TelemetryCallback, CameraIotPnpDevice_TelemetryCallback,
(void*)telemetryName); (void*)telemetryName);
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
LogError("DEVICE_INFO: Reporting telemetry=<%s> failed, error=<%d>", telemetryName, result); LogError("DEVICE_INFO: Reporting telemetry=<%s> failed, error=<%d>", telemetryName, result);
} }
@ -184,7 +184,7 @@ HRESULT CameraIotPnpDevice::ReportTelemetry(_In_ std::string& telemetryName, _In
{ {
AutoLock lock(&m_lock); AutoLock lock(&m_lock);
DIGITALTWIN_CLIENT_RESULT result; IOTHUB_CLIENT_RESULT result;
RETURN_HR_IF_NULL(HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE), m_PnpClientInterface); RETURN_HR_IF_NULL(HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE), m_PnpClientInterface);
@ -196,7 +196,7 @@ HRESULT CameraIotPnpDevice::ReportTelemetry(_In_ std::string& telemetryName, _In
strlen(telemetryMessage), strlen(telemetryMessage),
CameraIotPnpDevice_TelemetryCallback, CameraIotPnpDevice_TelemetryCallback,
(void*)telemetryName.c_str()); (void*)telemetryName.c_str());
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
LogError("DEVICE_INFO: Reporting telemetry=<%s> failed, error=<%d>", telemetryName.c_str(), result); LogError("DEVICE_INFO: Reporting telemetry=<%s> failed, error=<%d>", telemetryName.c_str(), result);
} }
@ -402,7 +402,7 @@ catch (std::exception e)
return E_UNEXPECTED; return E_UNEXPECTED;
} }
HRESULT HRESULT
CameraIotPnpDevice::TakePhotoOp(_Out_ std::string& strResponse) try CameraIotPnpDevice::TakePhotoOp(_Out_ std::string& strResponse) try
{ {
ComPtr<IStorageFile> spStorageFile; ComPtr<IStorageFile> spStorageFile;
@ -462,7 +462,7 @@ catch (std::exception e)
void __cdecl void __cdecl
CameraIotPnpDevice::CameraIotPnpDevice_PropertyCallback( CameraIotPnpDevice::CameraIotPnpDevice_PropertyCallback(
_In_ DIGITALTWIN_CLIENT_RESULT pnpReportedStatus, _In_ IOTHUB_CLIENT_RESULT pnpReportedStatus,
_In_opt_ void* userContextCallback) _In_opt_ void* userContextCallback)
{ {
LogInfo("%s:%d pnpstatus=%d,context=0x%p", __FUNCTION__, __LINE__, pnpReportedStatus, userContextCallback); LogInfo("%s:%d pnpstatus=%d,context=0x%p", __FUNCTION__, __LINE__, pnpReportedStatus, userContextCallback);
@ -470,7 +470,7 @@ CameraIotPnpDevice::CameraIotPnpDevice_PropertyCallback(
void __cdecl void __cdecl
CameraIotPnpDevice::CameraIotPnpDevice_TelemetryCallback( CameraIotPnpDevice::CameraIotPnpDevice_TelemetryCallback(
_In_ DIGITALTWIN_CLIENT_RESULT pnpTelemetryStatus, _In_ IOTHUB_CLIENT_RESULT pnpTelemetryStatus,
_In_opt_ void* userContextCallback) _In_opt_ void* userContextCallback)
{ {
UNREFERENCED_PARAMETER(pnpTelemetryStatus); UNREFERENCED_PARAMETER(pnpTelemetryStatus);

Просмотреть файл

@ -38,8 +38,8 @@ public:
virtual HRESULT GetURIOp(_Out_ std::string& strResponse); virtual HRESULT GetURIOp(_Out_ std::string& strResponse);
static void __cdecl CameraIotPnpDevice_PropertyCallback(_In_ DIGITALTWIN_CLIENT_RESULT pnpReportedStatus, _In_opt_ void* userContextCallback); static void __cdecl CameraIotPnpDevice_PropertyCallback(_In_ IOTHUB_CLIENT_RESULT pnpReportedStatus, _In_opt_ void* userContextCallback);
static void __cdecl CameraIotPnpDevice_TelemetryCallback(_In_ DIGITALTWIN_CLIENT_RESULT pnpTelemetryStatus, _In_opt_ void* userContextCallback); static void __cdecl CameraIotPnpDevice_TelemetryCallback(_In_ IOTHUB_CLIENT_RESULT pnpTelemetryStatus, _In_opt_ void* userContextCallback);
static void __cdecl CameraIotPnpDevice_BlobUploadCallback(IOTHUB_CLIENT_FILE_UPLOAD_RESULT result, void* userContextCallback); static void __cdecl CameraIotPnpDevice_BlobUploadCallback(IOTHUB_CLIENT_FILE_UPLOAD_RESULT result, void* userContextCallback);
HRESULT UploadStorageFileToBlob(ABI::Windows::Storage::IStorageFile* pStorageFile); HRESULT UploadStorageFileToBlob(ABI::Windows::Storage::IStorageFile* pStorageFile);

Просмотреть файл

@ -21,7 +21,7 @@ std::unique_ptr<CameraIotPnpDeviceAdapter> CameraIotPnpDeviceAdapter::MakeUnique
nullptr, nullptr,
newCameraDevice.get(), newCameraDevice.get(),
interfaceClient); interfaceClient);
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
throw std::exception("Failed to create digital twin interface"); throw std::exception("Failed to create digital twin interface");
} }
@ -30,7 +30,7 @@ std::unique_ptr<CameraIotPnpDeviceAdapter> CameraIotPnpDeviceAdapter::MakeUnique
*interfaceClient, *interfaceClient,
CameraIotPnpDeviceAdapter::CameraPnpCallback_ProcessCommandUpdate, CameraIotPnpDeviceAdapter::CameraPnpCallback_ProcessCommandUpdate,
static_cast<void*>(newCameraDevice.get())); static_cast<void*>(newCameraDevice.get()));
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
throw std::exception("Failed to set digital twin command callback"); throw std::exception("Failed to set digital twin command callback");
} }
@ -39,7 +39,7 @@ std::unique_ptr<CameraIotPnpDeviceAdapter> CameraIotPnpDeviceAdapter::MakeUnique
*interfaceClient, *interfaceClient,
CameraIotPnpDeviceAdapter::CameraPnpCallback_ProcessPropertyUpdate, CameraIotPnpDeviceAdapter::CameraPnpCallback_ProcessPropertyUpdate,
static_cast<void*>(newCameraDevice.get())); static_cast<void*>(newCameraDevice.get()));
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
throw std::exception("Failed to set digital twin property callback"); throw std::exception("Failed to set digital twin property callback");
} }

Просмотреть файл

@ -6,7 +6,7 @@
#include "CameraPnPBridgeInterface.h" #include "CameraPnPBridgeInterface.h"
#include "CameraIotPnpDeviceAdapter.h" #include "CameraIotPnpDeviceAdapter.h"
DIGITALTWIN_CLIENT_RESULT Camera_StartPnpInterface( IOTHUB_CLIENT_RESULT Camera_StartPnpInterface(
PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */, PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */,
PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept
{ {
@ -18,14 +18,14 @@ DIGITALTWIN_CLIENT_RESULT Camera_StartPnpInterface(
{ {
if (cameraDevice->Start() != S_OK) if (cameraDevice->Start() != S_OK)
{ {
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT Camera_StopPnpInterface( IOTHUB_CLIENT_RESULT Camera_StopPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept
{ {
LogInfo("Stopping PnP interface: %p", pnpInterfaceHandle); LogInfo("Stopping PnP interface: %p", pnpInterfaceHandle);
@ -38,10 +38,10 @@ DIGITALTWIN_CLIENT_RESULT Camera_StopPnpInterface(
cameraDevice->Stop(); cameraDevice->Stop();
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT Camera_DestroyPnpInterface( IOTHUB_CLIENT_RESULT Camera_DestroyPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept
{ {
LogInfo("Destroying PnP interface: %p", pnpInterfaceHandle); LogInfo("Destroying PnP interface: %p", pnpInterfaceHandle);
@ -58,10 +58,10 @@ DIGITALTWIN_CLIENT_RESULT Camera_DestroyPnpInterface(
delete cameraDevice; delete cameraDevice;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT Camera_CreatePnpInterface( IOTHUB_CLIENT_RESULT Camera_CreatePnpInterface(
PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */, PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */,
const char* componentName, const char* componentName,
const JSON_Object* adapterInterfaceConfig, const JSON_Object* adapterInterfaceConfig,
@ -73,7 +73,7 @@ DIGITALTWIN_CLIENT_RESULT Camera_CreatePnpInterface(
if (!cameraId) if (!cameraId)
{ {
LogError("Failed to get camera hardware ID from interface defined in config"); LogError("Failed to get camera hardware ID from interface defined in config");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
std::string cameraIdStr(cameraId); std::string cameraIdStr(cameraId);
@ -89,24 +89,24 @@ DIGITALTWIN_CLIENT_RESULT Camera_CreatePnpInterface(
// Interface context now owns object // Interface context now owns object
newCameraDevice.release(); newCameraDevice.release();
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT Camera_CreatePnpAdapter( IOTHUB_CLIENT_RESULT Camera_CreatePnpAdapter(
const JSON_Object* /* adapterGlobalConfig */, const JSON_Object* /* adapterGlobalConfig */,
PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */) noexcept PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */) noexcept
{ {
LogInfo("Creating the camera PnP adapter."); LogInfo("Creating the camera PnP adapter.");
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT Camera_DestroyPnpAdapter( IOTHUB_CLIENT_RESULT Camera_DestroyPnpAdapter(
PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */) noexcept PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */) noexcept
{ {
LogInfo("Destroying the camera PnP adapter."); LogInfo("Destroying the camera PnP adapter.");
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
PNP_ADAPTER CameraPnpInterface = { PNP_ADAPTER CameraPnpInterface = {

Просмотреть файл

@ -246,30 +246,17 @@ __inline HRESULT HResultFromIotHub(_In_ IOTHUB_CLIENT_RESULT r)
} }
} }
__inline HRESULT HResultFromPnpClient(_In_ DIGITALTWIN_CLIENT_RESULT r) __inline HRESULT HResultFromPnpClient(_In_ IOTHUB_CLIENT_RESULT r)
{ {
switch (r) switch (r)
{ {
case DIGITALTWIN_CLIENT_OK: case IOTHUB_CLIENT_OK:
return S_OK; return S_OK;
case DIGITALTWIN_CLIENT_ERROR_INVALID_ARG: case IOTHUB_CLIENT_INVALID_ARG:
return E_INVALIDARG; return E_INVALIDARG;
case DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY: case IOTHUB_CLIENT_INDEFINITE_TIME:
return E_OUTOFMEMORY;
case DIGITALTWIN_CLIENT_ERROR_INTERFACE_NOT_REGISTERED:
return HRESULT_FROM_WIN32(ERROR_ADDRESS_NOT_ASSOCIATED);
case DIGITALTWIN_CLIENT_ERROR_REGISTRATION_PENDING:
return HRESULT_FROM_WIN32(ERROR_CONNECTION_ACTIVE);
case DIGITALTWIN_CLIENT_ERROR_INTERFACE_ALREADY_REGISTERED:
return HRESULT_FROM_WIN32(ERROR_ADDRESS_ALREADY_ASSOCIATED);
case DIGITALTWIN_CLIENT_ERROR_COMMAND_NOT_PRESENT:
//case DIGITALTWIN_CLIENT_ERROR_INTERFACE_NOT_PRESENT:
return HRESULT_FROM_WIN32(ERROR_SET_NOT_FOUND);
case DIGITALTWIN_CLIENT_ERROR_SHUTTING_DOWN:
return SEC_E_SHUTDOWN_IN_PROGRESS;
case DIGITALTWIN_CLIENT_ERROR_TIMEOUT:
return HRESULT_FROM_WIN32(WAIT_TIMEOUT); return HRESULT_FROM_WIN32(WAIT_TIMEOUT);
case DIGITALTWIN_CLIENT_ERROR: case IOTHUB_CLIENT_ERROR:
default: default:
return E_UNEXPECTED; return E_UNEXPECTED;
} }

Просмотреть файл

@ -36,7 +36,7 @@ BluetoothSensorDeviceAdapterBase::BluetoothSensorDeviceAdapterBase(
this, this,
&m_handle); &m_handle);
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
throw std::runtime_error( throw std::runtime_error(
("Failed to create digital twin interface: " + std::to_string(result)).c_str()); ("Failed to create digital twin interface: " + std::to_string(result)).c_str());
@ -47,7 +47,7 @@ BluetoothSensorDeviceAdapterBase::BluetoothSensorDeviceAdapterBase(
OnPropertyCallback, OnPropertyCallback,
this); this);
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
throw std::runtime_error( throw std::runtime_error(
("Failed to register for property callbacks: " + std::to_string(result)).c_str()); ("Failed to register for property callbacks: " + std::to_string(result)).c_str());
@ -58,7 +58,7 @@ BluetoothSensorDeviceAdapterBase::BluetoothSensorDeviceAdapterBase(
OnCommandCallback, OnCommandCallback,
this); this);
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
throw std::runtime_error( throw std::runtime_error(
("Failed to register for command callbacks: " + std::to_string(result)).c_str()); ("Failed to register for command callbacks: " + std::to_string(result)).c_str());
@ -85,7 +85,7 @@ void BluetoothSensorDeviceAdapterBase::ReportSensorDataTelemetry(
OnTelemetryCallback, OnTelemetryCallback,
static_cast<void*>(telemetryNameBuffer.data())); static_cast<void*>(telemetryNameBuffer.data()));
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
LogError("Failed to report sensor data telemetry for %s: %d", LogError("Failed to report sensor data telemetry for %s: %d",
telemetryName.c_str(), result); telemetryName.c_str(), result);
@ -100,10 +100,10 @@ DIGITALTWIN_INTERFACE_CLIENT_HANDLE BluetoothSensorDeviceAdapterBase::GetPnpInte
// static // static
void BluetoothSensorDeviceAdapterBase::OnInterfaceRegisteredCallback( void BluetoothSensorDeviceAdapterBase::OnInterfaceRegisteredCallback(
DIGITALTWIN_CLIENT_RESULT interfaceStatus, IOTHUB_CLIENT_RESULT interfaceStatus,
void* /* userInterfaceContext */) void* /* userInterfaceContext */)
{ {
if (interfaceStatus == DIGITALTWIN_CLIENT_OK) if (interfaceStatus == IOTHUB_CLIENT_OK)
{ {
LogInfo("Bluetooth sensor interface successfully registered."); LogInfo("Bluetooth sensor interface successfully registered.");
} }
@ -116,10 +116,10 @@ void BluetoothSensorDeviceAdapterBase::OnInterfaceRegisteredCallback(
// static // static
void BluetoothSensorDeviceAdapterBase::OnTelemetryCallback( void BluetoothSensorDeviceAdapterBase::OnTelemetryCallback(
DIGITALTWIN_CLIENT_RESULT telemetryStatus, IOTHUB_CLIENT_RESULT telemetryStatus,
void* /* userContextCallback */) void* /* userContextCallback */)
{ {
if (telemetryStatus != DIGITALTWIN_CLIENT_OK) if (telemetryStatus != IOTHUB_CLIENT_OK)
{ {
LogError("Telemetry callback reported error: %d", LogError("Telemetry callback reported error: %d",
telemetryStatus); telemetryStatus);

Просмотреть файл

@ -28,11 +28,11 @@ protected:
private: private:
static void OnInterfaceRegisteredCallback( static void OnInterfaceRegisteredCallback(
DIGITALTWIN_CLIENT_RESULT interfaceStatus, IOTHUB_CLIENT_RESULT interfaceStatus,
_In_ void* userInterfaceContext); _In_ void* userInterfaceContext);
static void OnTelemetryCallback( static void OnTelemetryCallback(
_In_ DIGITALTWIN_CLIENT_RESULT telemetryStatus, _In_ IOTHUB_CLIENT_RESULT telemetryStatus,
_In_ void* userContextCallback); _In_ void* userContextCallback);
static void OnPropertyCallback( static void OnPropertyCallback(

Просмотреть файл

@ -15,7 +15,7 @@
InterfaceDescriptorMap g_interfaceDescriptorMap; InterfaceDescriptorMap g_interfaceDescriptorMap;
DIGITALTWIN_CLIENT_RESULT BluetoothSensor_StartPnpInterface( IOTHUB_CLIENT_RESULT BluetoothSensor_StartPnpInterface(
PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */, PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */,
PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept
{ {
@ -33,12 +33,12 @@ DIGITALTWIN_CLIENT_RESULT BluetoothSensor_StartPnpInterface(
pnpInterfaceHandle, pnpInterfaceHandle,
e.what()); e.what());
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT BluetoothSensor_StopPnpInterface( IOTHUB_CLIENT_RESULT BluetoothSensor_StopPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept
{ {
LogInfo("Stopping PnP interface: %p", pnpInterfaceHandle); LogInfo("Stopping PnP interface: %p", pnpInterfaceHandle);
@ -55,12 +55,12 @@ DIGITALTWIN_CLIENT_RESULT BluetoothSensor_StopPnpInterface(
pnpInterfaceHandle, pnpInterfaceHandle,
e.what()); e.what());
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT BluetoothSensor_DestroyPnpInterface( IOTHUB_CLIENT_RESULT BluetoothSensor_DestroyPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept PNPBRIDGE_INTERFACE_HANDLE pnpInterfaceHandle) noexcept
{ {
LogInfo("Destroying PnP interface: %p", pnpInterfaceHandle); LogInfo("Destroying PnP interface: %p", pnpInterfaceHandle);
@ -69,10 +69,10 @@ DIGITALTWIN_CLIENT_RESULT BluetoothSensor_DestroyPnpInterface(
delete static_cast<BluetoothSensorDeviceAdapter*>(PnpInterfaceHandleGetContext( delete static_cast<BluetoothSensorDeviceAdapter*>(PnpInterfaceHandleGetContext(
pnpInterfaceHandle)); pnpInterfaceHandle));
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT BluetoothSensor_CreatePnpInterface( IOTHUB_CLIENT_RESULT BluetoothSensor_CreatePnpInterface(
PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */, PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */,
const char* componentName, const char* componentName,
const JSON_Object* adapterInterfaceConfig, const JSON_Object* adapterInterfaceConfig,
@ -88,7 +88,7 @@ DIGITALTWIN_CLIENT_RESULT BluetoothSensor_CreatePnpInterface(
if (!bluetoothAddressStr) if (!bluetoothAddressStr)
{ {
LogError("Failed to get bluetooth address from interface defined in config"); LogError("Failed to get bluetooth address from interface defined in config");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
const uint64_t bluetoothAddress = std::stoull(bluetoothAddressStr); const uint64_t bluetoothAddress = std::stoull(bluetoothAddressStr);
@ -97,14 +97,14 @@ DIGITALTWIN_CLIENT_RESULT BluetoothSensor_CreatePnpInterface(
if (!identity) if (!identity)
{ {
LogError("Failed to get interface identity defined in config"); LogError("Failed to get interface identity defined in config");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
const auto interfaceDescriptor = g_interfaceDescriptorMap.find(std::string(identity)); const auto interfaceDescriptor = g_interfaceDescriptorMap.find(std::string(identity));
if (interfaceDescriptor == g_interfaceDescriptorMap.end()) if (interfaceDescriptor == g_interfaceDescriptorMap.end())
{ {
LogError("Could not find an interface identity for %s", identity); LogError("Could not find an interface identity for %s", identity);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
std::unique_ptr<BluetoothSensorDeviceAdapter> newDeviceAdapter; std::unique_ptr<BluetoothSensorDeviceAdapter> newDeviceAdapter;
@ -121,7 +121,7 @@ DIGITALTWIN_CLIENT_RESULT BluetoothSensor_CreatePnpInterface(
pnpInterfaceHandle, pnpInterfaceHandle,
e.what()); e.what());
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
*pnpInterfaceClient = newDeviceAdapter->GetPnpInterfaceClientHandle(); *pnpInterfaceClient = newDeviceAdapter->GetPnpInterfaceClientHandle();
@ -129,10 +129,10 @@ DIGITALTWIN_CLIENT_RESULT BluetoothSensor_CreatePnpInterface(
// PnP interface now owns the pointer // PnP interface now owns the pointer
newDeviceAdapter.release(); newDeviceAdapter.release();
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT BluetoothSensor_CreatePnpAdapter( IOTHUB_CLIENT_RESULT BluetoothSensor_CreatePnpAdapter(
const JSON_Object* adapterGlobalConfig, const JSON_Object* adapterGlobalConfig,
PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */) noexcept PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */) noexcept
{ {
@ -146,18 +146,18 @@ DIGITALTWIN_CLIENT_RESULT BluetoothSensor_CreatePnpAdapter(
{ {
LogError("Failed to create BLE sensor adapter: %s", e.what()); LogError("Failed to create BLE sensor adapter: %s", e.what());
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT BluetoothSensor_DestroyPnpAdapter( IOTHUB_CLIENT_RESULT BluetoothSensor_DestroyPnpAdapter(
PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */) noexcept PNPBRIDGE_ADAPTER_HANDLE /* adapterHandle */) noexcept
{ {
LogInfo("Destroying the bluetooth sensor PnP adapter."); LogInfo("Destroying the bluetooth sensor PnP adapter.");
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
PNP_ADAPTER BluetoothSensorPnpInterface = { PNP_ADAPTER BluetoothSensorPnpInterface = {

Просмотреть файл

@ -26,7 +26,7 @@ static const unsigned char coreDeviceHealth_DeviceStateActive[] = "true";
static const unsigned char coreDeviceHealth_DeviceStateInactive[] = "false"; static const unsigned char coreDeviceHealth_DeviceStateInactive[] = "false";
void CoreDevice_SetActive( void CoreDevice_SetActive(
DIGITALTWIN_CLIENT_RESULT pnpReportedStatus, IOTHUB_CLIENT_RESULT pnpReportedStatus,
void* userContextCallback) void* userContextCallback)
{ {
LogInfo("CoreDevice_ReportPropertyUpdatedCallback called, result=%d, userContextCallback=%p", pnpReportedStatus, userContextCallback); LogInfo("CoreDevice_ReportPropertyUpdatedCallback called, result=%d, userContextCallback=%p", pnpReportedStatus, userContextCallback);
@ -35,7 +35,7 @@ void CoreDevice_SetActive(
} }
void CoreDevice_SetInactive( void CoreDevice_SetInactive(
DIGITALTWIN_CLIENT_RESULT pnpReportedStatus, IOTHUB_CLIENT_RESULT pnpReportedStatus,
void* userContextCallback) void* userContextCallback)
{ {
LogInfo("CoreDevice_ReportPropertyUpdatedCallback called, result=%d, userContextCallback=%p", pnpReportedStatus, userContextCallback); LogInfo("CoreDevice_ReportPropertyUpdatedCallback called, result=%d, userContextCallback=%p", pnpReportedStatus, userContextCallback);
@ -52,7 +52,7 @@ CoreDevice_OnDeviceNotification(
_In_reads_bytes_(eventDataSize) PCM_NOTIFY_EVENT_DATA eventData, _In_reads_bytes_(eventDataSize) PCM_NOTIFY_EVENT_DATA eventData,
_In_ DWORD eventDataSize) _In_ DWORD eventDataSize)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
PCORE_DEVICE_TAG device = context; PCORE_DEVICE_TAG device = context;
UNREFERENCED_PARAMETER(hNotify); UNREFERENCED_PARAMETER(hNotify);
@ -63,7 +63,7 @@ CoreDevice_OnDeviceNotification(
CoreDevice_SendConnectionEventAsync(device->DigitalTwinInterface, "DeviceStatus", "Connected"); CoreDevice_SendConnectionEventAsync(device->DigitalTwinInterface, "DeviceStatus", "Connected");
result = DigitalTwin_InterfaceClient_ReportPropertyAsync(device->DigitalTwinInterface, coreDeviceHealth_DeviceStateProperty, coreDeviceHealth_DeviceStateActive, result = DigitalTwin_InterfaceClient_ReportPropertyAsync(device->DigitalTwinInterface, coreDeviceHealth_DeviceStateProperty, coreDeviceHealth_DeviceStateActive,
sizeof((char*)coreDeviceHealth_DeviceStateActive), NULL, CoreDevice_SetActive, (void*)device); sizeof((char*)coreDeviceHealth_DeviceStateActive), NULL, CoreDevice_SetActive, (void*)device);
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
LogError("CoreDevice_OnDeviceNotification: Reporting property=<%s> failed, error=<%d>", coreDeviceHealth_DeviceStateProperty, result); LogError("CoreDevice_OnDeviceNotification: Reporting property=<%s> failed, error=<%d>", coreDeviceHealth_DeviceStateProperty, result);
} }
@ -78,7 +78,7 @@ CoreDevice_OnDeviceNotification(
CoreDevice_SendConnectionEventAsync(device->DigitalTwinInterface, "DeviceStatus", "Disconnected"); CoreDevice_SendConnectionEventAsync(device->DigitalTwinInterface, "DeviceStatus", "Disconnected");
result = DigitalTwin_InterfaceClient_ReportPropertyAsync(device->DigitalTwinInterface, coreDeviceHealth_DeviceStateProperty, coreDeviceHealth_DeviceStateInactive, result = DigitalTwin_InterfaceClient_ReportPropertyAsync(device->DigitalTwinInterface, coreDeviceHealth_DeviceStateProperty, coreDeviceHealth_DeviceStateInactive,
strlen((char*)coreDeviceHealth_DeviceStateInactive), NULL, CoreDevice_SetInactive, (void*)device); strlen((char*)coreDeviceHealth_DeviceStateInactive), NULL, CoreDevice_SetInactive, (void*)device);
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
LogError("CoreDevice_OnDeviceNotification: Reporting property=<%s> failed, error=<%d>", coreDeviceHealth_DeviceStateProperty, result); LogError("CoreDevice_OnDeviceNotification: Reporting property=<%s> failed, error=<%d>", coreDeviceHealth_DeviceStateProperty, result);
} }
@ -93,7 +93,7 @@ CoreDevice_OnDeviceNotification(
void void
CoreDevice_EventCallbackSent( CoreDevice_EventCallbackSent(
DIGITALTWIN_CLIENT_RESULT pnpSendEventStatus, IOTHUB_CLIENT_RESULT pnpSendEventStatus,
void* userContextCallback) void* userContextCallback)
{ {
LogInfo("CoreDevice_EventCallbackSent called, result=%d, userContextCallback=%p", LogInfo("CoreDevice_EventCallbackSent called, result=%d, userContextCallback=%p",
@ -108,7 +108,7 @@ CoreDevice_SendConnectionEventAsync(
{ {
int result = 0; int result = 0;
char msg[CONN_EVENT_SIZE] = { 0 }; char msg[CONN_EVENT_SIZE] = { 0 };
DIGITALTWIN_CLIENT_RESULT dtResult; IOTHUB_CLIENT_RESULT dtResult;
sprintf_s(msg, CONN_EVENT_SIZE, CONN_FORMAT, EventName, EventData); sprintf_s(msg, CONN_EVENT_SIZE, CONN_FORMAT, EventName, EventData);
@ -118,7 +118,7 @@ CoreDevice_SendConnectionEventAsync(
strlen(msg), strlen(msg),
CoreDevice_EventCallbackSent, CoreDevice_EventCallbackSent,
(void*)EventName); (void*)EventName);
if (DIGITALTWIN_CLIENT_OK != dtResult) { if (IOTHUB_CLIENT_OK != dtResult) {
LogError("CoreDevice_SendEventAsync failed, result=%d\n", dtResult); LogError("CoreDevice_SendEventAsync failed, result=%d\n", dtResult);
result = -1; result = -1;
} }
@ -148,13 +148,13 @@ CoreDevice_DeviceNotification(
return 0; return 0;
} }
DIGITALTWIN_CLIENT_RESULT IOTHUB_CLIENT_RESULT
CoreDevice_EnumerateDevices( CoreDevice_EnumerateDevices(
_In_ GUID* InterfaceClassGuid, _In_ GUID* InterfaceClassGuid,
_Inout_ SINGLYLINKEDLIST_HANDLE SupportedInterfaces _Inout_ SINGLYLINKEDLIST_HANDLE SupportedInterfaces
) )
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
CONFIGRET cmret = CR_SUCCESS; CONFIGRET cmret = CR_SUCCESS;
ULONG cchInterfaceIds = 0; ULONG cchInterfaceIds = 0;
wchar_t* interfaceIds = NULL; wchar_t* interfaceIds = NULL;
@ -177,20 +177,20 @@ CoreDevice_EnumerateDevices(
singlylinkedlist_add(SupportedInterfaces, interfaceIds); singlylinkedlist_add(SupportedInterfaces, interfaceIds);
if (cmret == CR_FAILURE) { if (cmret == CR_FAILURE) {
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
LogInfo("CoreDevice_EnumerateDevices: CM_Get_Device_Interface_List failed"); LogInfo("CoreDevice_EnumerateDevices: CM_Get_Device_Interface_List failed");
} }
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT CoreDevice_DestroyPnpAdapter( IOTHUB_CLIENT_RESULT CoreDevice_DestroyPnpAdapter(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle) PNPBRIDGE_ADAPTER_HANDLE AdapterHandle)
{ {
PCORE_DEVICE_ADAPTER_CONTEXT adapterContext = PnpAdapterHandleGetContext(AdapterHandle); PCORE_DEVICE_ADAPTER_CONTEXT adapterContext = PnpAdapterHandleGetContext(AdapterHandle);
if (adapterContext == NULL) if (adapterContext == NULL)
{ {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
if (adapterContext->DeviceWatchers != NULL) if (adapterContext->DeviceWatchers != NULL)
@ -221,14 +221,14 @@ DIGITALTWIN_CLIENT_RESULT CoreDevice_DestroyPnpAdapter(
} }
free (adapterContext); free (adapterContext);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT CoreDevice_CreatePnpAdapter( IOTHUB_CLIENT_RESULT CoreDevice_CreatePnpAdapter(
const JSON_Object* AdapterGlobalConfig, const JSON_Object* AdapterGlobalConfig,
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle) PNPBRIDGE_ADAPTER_HANDLE AdapterHandle)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
CM_NOTIFY_FILTER cmFilter; CM_NOTIFY_FILTER cmFilter;
HCMNOTIFICATION notifyHandle = NULL; HCMNOTIFICATION notifyHandle = NULL;
DWORD cmRet; DWORD cmRet;
@ -236,7 +236,7 @@ DIGITALTWIN_CLIENT_RESULT CoreDevice_CreatePnpAdapter(
if (NULL == adapterContext) if (NULL == adapterContext)
{ {
LogError("CoreDevice_CreatePnpAdapter: Could not allocate memory for device context."); LogError("CoreDevice_CreatePnpAdapter: Could not allocate memory for device context.");
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -246,14 +246,14 @@ DIGITALTWIN_CLIENT_RESULT CoreDevice_CreatePnpAdapter(
if (NULL == adapterContext->DeviceWatchers || NULL == adapterContext->SupportedInterfaces) if (NULL == adapterContext->DeviceWatchers || NULL == adapterContext->SupportedInterfaces)
{ {
LogError("CoreDevice_CreatePnpAdapter: Could not allocate device watcher or supported interfaces list"); LogError("CoreDevice_CreatePnpAdapter: Could not allocate device watcher or supported interfaces list");
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
if (AdapterGlobalConfig == NULL) if (AdapterGlobalConfig == NULL)
{ {
LogError("CoreDevice_CreatePnpAdapter: Missing associated global parameters in config"); LogError("CoreDevice_CreatePnpAdapter: Missing associated global parameters in config");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -264,7 +264,7 @@ DIGITALTWIN_CLIENT_RESULT CoreDevice_CreatePnpAdapter(
const char *interfaceClass = json_array_get_string(interfaceClasses, j); const char *interfaceClass = json_array_get_string(interfaceClasses, j);
if (UuidFromStringA((RPC_CSTR)interfaceClass, &guid) != RPC_S_OK) { if (UuidFromStringA((RPC_CSTR)interfaceClass, &guid) != RPC_S_OK) {
LogError("CoreDevice_CreatePnpAdapter: UuidFromStringA failed"); LogError("CoreDevice_CreatePnpAdapter: UuidFromStringA failed");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -282,7 +282,7 @@ DIGITALTWIN_CLIENT_RESULT CoreDevice_CreatePnpAdapter(
if (cmRet != CR_SUCCESS) { if (cmRet != CR_SUCCESS) {
LogError("CoreDevice_CreatePnpAdapter: CM_Register_Notification failed"); LogError("CoreDevice_CreatePnpAdapter: CM_Register_Notification failed");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -294,7 +294,7 @@ DIGITALTWIN_CLIENT_RESULT CoreDevice_CreatePnpAdapter(
PnpAdapterHandleSetContext(AdapterHandle, (void*)adapterContext); PnpAdapterHandleSetContext(AdapterHandle, (void*)adapterContext);
exit: exit:
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
result = CoreDevice_DestroyPnpAdapter(AdapterHandle); result = CoreDevice_DestroyPnpAdapter(AdapterHandle);
} }
@ -302,15 +302,15 @@ exit:
} }
static void CoreDevice_InterfaceRegisteredCallback( static void CoreDevice_InterfaceRegisteredCallback(
DIGITALTWIN_CLIENT_RESULT dtInterfaceStatus, IOTHUB_CLIENT_RESULT dtInterfaceStatus,
void* userInterfaceContext) void* userInterfaceContext)
{ {
UNREFERENCED_PARAMETER(userInterfaceContext); UNREFERENCED_PARAMETER(userInterfaceContext);
if (dtInterfaceStatus == DIGITALTWIN_CLIENT_OK) if (dtInterfaceStatus == IOTHUB_CLIENT_OK)
{ {
LogInfo("Core Device Health: Interface registered."); LogInfo("Core Device Health: Interface registered.");
} }
else if (dtInterfaceStatus == DIGITALTWIN_CLIENT_ERROR_INTERFACE_UNREGISTERING) else if (dtInterfaceStatus == IOTHUB_CLIENT_ERROR)
{ {
LogInfo("Core Device Health: Interface received unregistering callback."); LogInfo("Core Device Health: Interface received unregistering callback.");
} }
@ -340,13 +340,13 @@ static void CoreDevice_ProcessCommandUpdate(
LogInfo("CoreDevice_ProcessCommandUpdate called."); LogInfo("CoreDevice_ProcessCommandUpdate called.");
} }
DIGITALTWIN_CLIENT_RESULT CoreDevice_DestroyPnpInterface( IOTHUB_CLIENT_RESULT CoreDevice_DestroyPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
PCORE_DEVICE_TAG deviceContext = PnpInterfaceHandleGetContext(PnpInterfaceHandle); PCORE_DEVICE_TAG deviceContext = PnpInterfaceHandleGetContext(PnpInterfaceHandle);
if (NULL == deviceContext) { if (NULL == deviceContext) {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
if (NULL != deviceContext->DigitalTwinInterface) { if (NULL != deviceContext->DigitalTwinInterface) {
@ -363,10 +363,10 @@ DIGITALTWIN_CLIENT_RESULT CoreDevice_DestroyPnpInterface(
free(deviceContext); free(deviceContext);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT CoreDevice_FindMatchingDeviceInstance( IOTHUB_CLIENT_RESULT CoreDevice_FindMatchingDeviceInstance(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
const char* HardwareId, const char* HardwareId,
char* SymbolicLink char* SymbolicLink
@ -384,7 +384,7 @@ DIGITALTWIN_CLIENT_RESULT CoreDevice_FindMatchingDeviceInstance(
PCORE_DEVICE_ADAPTER_CONTEXT adapterContext = PnpAdapterHandleGetContext(AdapterHandle); PCORE_DEVICE_ADAPTER_CONTEXT adapterContext = PnpAdapterHandleGetContext(AdapterHandle);
if (adapterContext == NULL) if (adapterContext == NULL)
{ {
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
if (adapterContext->SupportedInterfaces) if (adapterContext->SupportedInterfaces)
@ -442,13 +442,13 @@ DIGITALTWIN_CLIENT_RESULT CoreDevice_FindMatchingDeviceInstance(
if (symbolicLinkFound) if (symbolicLinkFound)
{ {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
DIGITALTWIN_CLIENT_RESULT IOTHUB_CLIENT_RESULT
CoreDevice_CreatePnpInterface( CoreDevice_CreatePnpInterface(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
const char* ComponentName, const char* ComponentName,
@ -456,7 +456,7 @@ CoreDevice_CreatePnpInterface(
PNPBRIDGE_INTERFACE_HANDLE BridgeInterfaceHandle, PNPBRIDGE_INTERFACE_HANDLE BridgeInterfaceHandle,
DIGITALTWIN_INTERFACE_CLIENT_HANDLE* PnpInterfaceClient) DIGITALTWIN_INTERFACE_CLIENT_HANDLE* PnpInterfaceClient)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
CM_NOTIFY_FILTER cmFilter; CM_NOTIFY_FILTER cmFilter;
CONFIGRET cmResult; CONFIGRET cmResult;
DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterfaceClient; DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterfaceClient;
@ -464,7 +464,7 @@ CoreDevice_CreatePnpInterface(
if (NULL == deviceContext) if (NULL == deviceContext)
{ {
LogError("Could not allocate memory for device context."); LogError("Could not allocate memory for device context.");
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
const char* hardwareId = json_object_dotget_string(AdapterInterfaceConfig, DEVICE_INSTANCE_HARDWARE_ID); const char* hardwareId = json_object_dotget_string(AdapterInterfaceConfig, DEVICE_INSTANCE_HARDWARE_ID);
@ -472,14 +472,14 @@ CoreDevice_CreatePnpInterface(
if (NULL == hardwareId) if (NULL == hardwareId)
{ {
LogError("Device adapter config needs to specify hardware ID for device."); LogError("Device adapter config needs to specify hardware ID for device.");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
deviceContext->DeviceActive = false; deviceContext->DeviceActive = false;
result = DigitalTwin_InterfaceClient_Create(ComponentName, result = DigitalTwin_InterfaceClient_Create(ComponentName,
CoreDevice_InterfaceRegisteredCallback, (void*)deviceContext, &pnpInterfaceClient); CoreDevice_InterfaceRegisteredCallback, (void*)deviceContext, &pnpInterfaceClient);
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("Core Device Health: Error registering pnp interface component %s", ComponentName); LogError("Core Device Health: Error registering pnp interface component %s", ComponentName);
goto exit; goto exit;
@ -487,7 +487,7 @@ CoreDevice_CreatePnpInterface(
else if ((result = DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback( else if ((result = DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback(
pnpInterfaceClient, pnpInterfaceClient,
CoreDevice_ProcessPropertyUpdate, CoreDevice_ProcessPropertyUpdate,
(void*)&deviceContext)) != DIGITALTWIN_CLIENT_OK) (void*)&deviceContext)) != IOTHUB_CLIENT_OK)
{ {
LogError("Core Device Health: DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback failed. error=<%d>", result); LogError("Core Device Health: DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback failed. error=<%d>", result);
goto exit; goto exit;
@ -495,7 +495,7 @@ CoreDevice_CreatePnpInterface(
else if ((result = DigitalTwin_InterfaceClient_SetCommandsCallback( else if ((result = DigitalTwin_InterfaceClient_SetCommandsCallback(
pnpInterfaceClient, pnpInterfaceClient,
CoreDevice_ProcessCommandUpdate, CoreDevice_ProcessCommandUpdate,
(void*)&deviceContext)) != DIGITALTWIN_CLIENT_OK) (void*)&deviceContext)) != IOTHUB_CLIENT_OK)
{ {
LogError("Core Device Health: DigitalTwin_InterfaceClient_SetCommandsCallback failed. error=<%d>", result); LogError("Core Device Health: DigitalTwin_InterfaceClient_SetCommandsCallback failed. error=<%d>", result);
goto exit; goto exit;
@ -503,7 +503,7 @@ CoreDevice_CreatePnpInterface(
result = CoreDevice_FindMatchingDeviceInstance(AdapterHandle, hardwareId, deviceContext->SymbolicLink); result = CoreDevice_FindMatchingDeviceInstance(AdapterHandle, hardwareId, deviceContext->SymbolicLink);
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("Core Device Health: Couldn't find device with hardware ID %s", hardwareId); LogError("Core Device Health: Couldn't find device with hardware ID %s", hardwareId);
goto exit; goto exit;
@ -524,7 +524,7 @@ CoreDevice_CreatePnpInterface(
if (CR_SUCCESS != cmResult) if (CR_SUCCESS != cmResult)
{ {
LogError("Core Device Health: CM_Register_Notification failed"); LogError("Core Device Health: CM_Register_Notification failed");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -534,7 +534,7 @@ CoreDevice_CreatePnpInterface(
PnpInterfaceHandleSetContext(BridgeInterfaceHandle, deviceContext); PnpInterfaceHandleSetContext(BridgeInterfaceHandle, deviceContext);
exit: exit:
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
CoreDevice_DestroyPnpInterface(BridgeInterfaceHandle); CoreDevice_DestroyPnpInterface(BridgeInterfaceHandle);
} }
@ -542,7 +542,7 @@ exit:
} }
DIGITALTWIN_CLIENT_RESULT CoreDevice_StartPnpInterface( IOTHUB_CLIENT_RESULT CoreDevice_StartPnpInterface(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
@ -550,14 +550,14 @@ DIGITALTWIN_CLIENT_RESULT CoreDevice_StartPnpInterface(
PCORE_DEVICE_TAG device = PnpInterfaceHandleGetContext(PnpInterfaceHandle); PCORE_DEVICE_TAG device = PnpInterfaceHandleGetContext(PnpInterfaceHandle);
CoreDevice_SendConnectionEventAsync(device->DigitalTwinInterface, "DeviceStatus", "Connected"); CoreDevice_SendConnectionEventAsync(device->DigitalTwinInterface, "DeviceStatus", "Connected");
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT CoreDevice_StopPnpInterface( IOTHUB_CLIENT_RESULT CoreDevice_StopPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
UNREFERENCED_PARAMETER(PnpInterfaceHandle); UNREFERENCED_PARAMETER(PnpInterfaceHandle);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
PNP_ADAPTER CoreDeviceHealth = { PNP_ADAPTER CoreDeviceHealth = {

Просмотреть файл

@ -146,7 +146,7 @@ void ModbusPnp_PropertyHandler(
#pragma region ReadOnlyProperty #pragma region ReadOnlyProperty
void ModbusPnp_ReportPropertyUpdatedCallback( void ModbusPnp_ReportPropertyUpdatedCallback(
DIGITALTWIN_CLIENT_RESULT pnpReportedStatus, IOTHUB_CLIENT_RESULT pnpReportedStatus,
void* userContextCallback) void* userContextCallback)
{ {
LogInfo("ModbusPnp_ReportPropertyUpdatedCallback called, result=%d, userContextCallback=%p", pnpReportedStatus, userContextCallback); LogInfo("ModbusPnp_ReportPropertyUpdatedCallback called, result=%d, userContextCallback=%p", pnpReportedStatus, userContextCallback);
@ -157,13 +157,13 @@ int ModbusPnp_ReportReadOnlyProperty(
char* propertyName, char* propertyName,
char* data) char* data)
{ {
DIGITALTWIN_CLIENT_RESULT pnpClientResult = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT pnpClientResult = IOTHUB_CLIENT_OK;
if (pnpInterface == NULL) { if (pnpInterface == NULL) {
return pnpClientResult; return pnpClientResult;
} }
if ((pnpClientResult = DigitalTwin_InterfaceClient_ReportPropertyAsync(pnpInterface, propertyName, (unsigned char*)data, strlen(data), NULL, ModbusPnp_ReportPropertyUpdatedCallback, (void*)propertyName)) != DIGITALTWIN_CLIENT_OK) if ((pnpClientResult = DigitalTwin_InterfaceClient_ReportPropertyAsync(pnpInterface, propertyName, (unsigned char*)data, strlen(data), NULL, ModbusPnp_ReportPropertyUpdatedCallback, (void*)propertyName)) != IOTHUB_CLIENT_OK)
{ {
LogError("PnP_InterfaceClient_ReportReadOnlyPropertyStatusAsync failed, result=%d\n", pnpClientResult); LogError("PnP_InterfaceClient_ReportReadOnlyPropertyStatusAsync failed, result=%d\n", pnpClientResult);
} }
@ -199,7 +199,7 @@ int ModbusPnp_PollingSingleProperty(
LogInfo("Stopped polling task for property \"%s\".", property->Name); LogInfo("Stopped polling task for property \"%s\".", property->Name);
free(context); free(context);
ThreadAPI_Exit(THREADAPI_OK); ThreadAPI_Exit(THREADAPI_OK);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
#pragma endregion #pragma endregion
@ -207,7 +207,7 @@ int ModbusPnp_PollingSingleProperty(
#pragma region SendTelemetry #pragma region SendTelemetry
void ModbusPnp_ReportTelemetryCallback( void ModbusPnp_ReportTelemetryCallback(
DIGITALTWIN_CLIENT_RESULT pnpSendEventStatus, IOTHUB_CLIENT_RESULT pnpSendEventStatus,
void* userContextCallback) void* userContextCallback)
{ {
LogInfo("ModbusPnp_ReportTelemetryCallback called, result=%d, userContextCallback=%p", pnpSendEventStatus, userContextCallback); LogInfo("ModbusPnp_ReportTelemetryCallback called, result=%d, userContextCallback=%p", pnpSendEventStatus, userContextCallback);
@ -218,7 +218,7 @@ int ModbusPnp_ReportTelemetry(
char* eventName, char* eventName,
char* data) char* data)
{ {
DIGITALTWIN_CLIENT_RESULT pnpClientResult = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT pnpClientResult = IOTHUB_CLIENT_OK;
if (pnpInterface == NULL) { if (pnpInterface == NULL) {
return pnpClientResult; return pnpClientResult;
@ -227,7 +227,7 @@ int ModbusPnp_ReportTelemetry(
char telemetryMessageData[512] = {0}; char telemetryMessageData[512] = {0};
sprintf(telemetryMessageData, "{\"%s\":%s}", eventName, data); sprintf(telemetryMessageData, "{\"%s\":%s}", eventName, data);
if ((pnpClientResult = DigitalTwin_InterfaceClient_SendTelemetryAsync(pnpInterface, (unsigned char*)telemetryMessageData, strlen(telemetryMessageData), ModbusPnp_ReportTelemetryCallback, (void*)eventName)) != DIGITALTWIN_CLIENT_OK) if ((pnpClientResult = DigitalTwin_InterfaceClient_SendTelemetryAsync(pnpInterface, (unsigned char*)telemetryMessageData, strlen(telemetryMessageData), ModbusPnp_ReportTelemetryCallback, (void*)eventName)) != IOTHUB_CLIENT_OK)
{ {
LogError("ModbusPnp_ReportTelemetry failed, result=%d\n", pnpClientResult); LogError("ModbusPnp_ReportTelemetry failed, result=%d\n", pnpClientResult);
} }
@ -262,7 +262,7 @@ int ModbusPnp_PollingSingleTelemetry(
LogInfo("Stopped polling task for telemetry \"%s\".", telemetry->Name); LogInfo("Stopped polling task for telemetry \"%s\".", telemetry->Name);
free(context); free(context);
ThreadAPI_Exit(THREADAPI_OK); ThreadAPI_Exit(THREADAPI_OK);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
#pragma endregion #pragma endregion
@ -276,7 +276,7 @@ void StopPollingTasks()
} }
} }
DIGITALTWIN_CLIENT_RESULT ModbusPnp_StartPollingAllTelemetryProperty( IOTHUB_CLIENT_RESULT ModbusPnp_StartPollingAllTelemetryProperty(
void* context) void* context)
{ {
PMODBUS_DEVICE_CONTEXT deviceContext = (PMODBUS_DEVICE_CONTEXT)context; PMODBUS_DEVICE_CONTEXT deviceContext = (PMODBUS_DEVICE_CONTEXT)context;
@ -296,7 +296,7 @@ DIGITALTWIN_CLIENT_RESULT ModbusPnp_StartPollingAllTelemetryProperty(
{ {
deviceContext->PollingTasks = calloc((telemetryCount + propertyCount), sizeof(THREAD_HANDLE)); deviceContext->PollingTasks = calloc((telemetryCount + propertyCount), sizeof(THREAD_HANDLE));
if (NULL == deviceContext->PollingTasks) { if (NULL == deviceContext->PollingTasks) {
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
} }
@ -371,5 +371,5 @@ DIGITALTWIN_CLIENT_RESULT ModbusPnp_StartPollingAllTelemetryProperty(
} }
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }

Просмотреть файл

@ -68,7 +68,7 @@ typedef struct CapabilityContext {
DIGITALTWIN_INTERFACE_CLIENT_HANDLE InterfaceClient; DIGITALTWIN_INTERFACE_CLIENT_HANDLE InterfaceClient;
}CapabilityContext; }CapabilityContext;
DIGITALTWIN_CLIENT_RESULT ModbusPnp_StartPollingAllTelemetryProperty(void* context); IOTHUB_CLIENT_RESULT ModbusPnp_StartPollingAllTelemetryProperty(void* context);
void StopPollingTasks(); void StopPollingTasks();
void ModbusPnp_CommandHandler(const DIGITALTWIN_CLIENT_COMMAND_REQUEST* dtClientCommandContext, void ModbusPnp_CommandHandler(const DIGITALTWIN_CLIENT_COMMAND_REQUEST* dtClientCommandContext,

Просмотреть файл

@ -294,12 +294,12 @@ bool ModbusPnp_CloseDevice(
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT ModbusPnp_SetReadRequest( IOTHUB_CLIENT_RESULT ModbusPnp_SetReadRequest(
ModbusDeviceConfig* deviceConfig, ModbusDeviceConfig* deviceConfig,
CapabilityType capabilityType, CapabilityType capabilityType,
void* capability) void* capability)
{ {
int result = DIGITALTWIN_CLIENT_ERROR; int result = IOTHUB_CLIENT_ERROR;
switch (deviceConfig->ConnectionType) switch (deviceConfig->ConnectionType)
{ {
case TCP: case TCP:
@ -314,13 +314,13 @@ DIGITALTWIN_CLIENT_RESULT ModbusPnp_SetReadRequest(
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT ModbusPnp_SetWriteRequest( IOTHUB_CLIENT_RESULT ModbusPnp_SetWriteRequest(
MODBUS_CONNECTION_TYPE connectionType, MODBUS_CONNECTION_TYPE connectionType,
CapabilityType capabilityType, CapabilityType capabilityType,
void* capability, void* capability,
char* valueStr) char* valueStr)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_ERROR; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_ERROR;
switch (connectionType) switch (connectionType)
{ {
case TCP: case TCP:
@ -507,7 +507,7 @@ int ModbusPnp_WriteToCapability(
{ {
ModbusCommand* command = (ModbusCommand*)(capabilityContext->capability); ModbusCommand* command = (ModbusCommand*)(capabilityContext->capability);
capabilityName = command->Name; capabilityName = command->Name;
if (DIGITALTWIN_CLIENT_OK != ModbusPnp_SetWriteRequest(capabilityContext->connectionType, Command, command, requestStr)) if (IOTHUB_CLIENT_OK != ModbusPnp_SetWriteRequest(capabilityContext->connectionType, Command, command, requestStr))
{ {
LogError("Failed to create write request for command \"%s\".", capabilityName); LogError("Failed to create write request for command \"%s\".", capabilityName);
return -1; return -1;
@ -532,7 +532,7 @@ int ModbusPnp_WriteToCapability(
{ {
ModbusProperty* property = (ModbusProperty*)(capabilityContext->capability); ModbusProperty* property = (ModbusProperty*)(capabilityContext->capability);
capabilityName = property->Name; capabilityName = property->Name;
if (DIGITALTWIN_CLIENT_OK != ModbusPnp_SetWriteRequest(capabilityContext->connectionType, Property, property, requestStr)) if (IOTHUB_CLIENT_OK != ModbusPnp_SetWriteRequest(capabilityContext->connectionType, Property, property, requestStr))
{ {
LogError("Failed to create write request for writable property \"%s\".", capabilityName); LogError("Failed to create write request for writable property \"%s\".", capabilityName);
return -1; return -1;

Просмотреть файл

@ -14,7 +14,7 @@ extern "C"
// ModbusConnection "Public" methods // ModbusConnection "Public" methods
bool ModbusPnp_CloseDevice(MODBUS_CONNECTION_TYPE connectionType, HANDLE hDevice, LOCK_HANDLE lock); bool ModbusPnp_CloseDevice(MODBUS_CONNECTION_TYPE connectionType, HANDLE hDevice, LOCK_HANDLE lock);
DIGITALTWIN_CLIENT_RESULT ModbusPnp_SetReadRequest(ModbusDeviceConfig* deviceConfig, CapabilityType capabilityType, void* capability); IOTHUB_CLIENT_RESULT ModbusPnp_SetReadRequest(ModbusDeviceConfig* deviceConfig, CapabilityType capabilityType, void* capability);
int ModbusPnp_ReadCapability(CapabilityContext* capabilityContext, CapabilityType capabilityType, uint8_t* resultedData); int ModbusPnp_ReadCapability(CapabilityContext* capabilityContext, CapabilityType capabilityType, uint8_t* resultedData);
int ModbusPnp_WriteToCapability(CapabilityContext* capabilityContext, CapabilityType capabilityType, char* requestStr, uint8_t* resultedData); int ModbusPnp_WriteToCapability(CapabilityContext* capabilityContext, CapabilityType capabilityType, char* requestStr, uint8_t* resultedData);

Просмотреть файл

@ -60,7 +60,7 @@ bool ModbusRtu_CloseDevice(
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT ModbusRtu_SetReadRequest( IOTHUB_CLIENT_RESULT ModbusRtu_SetReadRequest(
CapabilityType capabilityType, CapabilityType capabilityType,
void* capability, void* capability,
uint8_t unitId) uint8_t unitId)
@ -75,7 +75,7 @@ DIGITALTWIN_CLIENT_RESULT ModbusRtu_SetReadRequest(
if (!ModbusConnectionHelper_GetFunctionCode(telemetry->StartAddress, true, &(telemetry->ReadRequest.RtuRequest.Payload.FunctionCode), &modbusAddress)) if (!ModbusConnectionHelper_GetFunctionCode(telemetry->StartAddress, true, &(telemetry->ReadRequest.RtuRequest.Payload.FunctionCode), &modbusAddress))
{ {
LogError("Failed to get Modbus function code for telemetry \"%s\".", telemetry->Name); LogError("Failed to get Modbus function code for telemetry \"%s\".", telemetry->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
telemetry->ReadRequest.RtuRequest.UnitID = unitId; telemetry->ReadRequest.RtuRequest.UnitID = unitId;
@ -93,7 +93,7 @@ DIGITALTWIN_CLIENT_RESULT ModbusRtu_SetReadRequest(
if (!ModbusConnectionHelper_GetFunctionCode(property->StartAddress, true, &(property->ReadRequest.RtuRequest.Payload.FunctionCode), &modbusAddress)) if (!ModbusConnectionHelper_GetFunctionCode(property->StartAddress, true, &(property->ReadRequest.RtuRequest.Payload.FunctionCode), &modbusAddress))
{ {
LogError("Failed to get Modbus function code for property \"%s\".", property->Name); LogError("Failed to get Modbus function code for property \"%s\".", property->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
property->ReadRequest.RtuRequest.UnitID = unitId; property->ReadRequest.RtuRequest.UnitID = unitId;
@ -106,13 +106,13 @@ DIGITALTWIN_CLIENT_RESULT ModbusRtu_SetReadRequest(
} }
default: default:
LogError("Modbus read if not supported for the capability."); LogError("Modbus read if not supported for the capability.");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT ModbusRtu_SetWriteRequest( IOTHUB_CLIENT_RESULT ModbusRtu_SetWriteRequest(
CapabilityType capabilityType, CapabilityType capabilityType,
void* capability, void* capability,
char* valueStr) char* valueStr)
@ -130,13 +130,13 @@ DIGITALTWIN_CLIENT_RESULT ModbusRtu_SetWriteRequest(
if (!ModbusConnectionHelper_GetFunctionCode(command->StartAddress, false, &(command->WriteRequest.RtuRequest.Payload.FunctionCode), &modbusAddress)) if (!ModbusConnectionHelper_GetFunctionCode(command->StartAddress, false, &(command->WriteRequest.RtuRequest.Payload.FunctionCode), &modbusAddress))
{ {
LogError("Failed to get Modbus function code for command \"%s\".", command->Name); LogError("Failed to get Modbus function code for command \"%s\".", command->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
if (!ModbusConnectionHelper_ConvertValueStrToUInt16(command->DataType, command->WriteRequest.RtuRequest.Payload.FunctionCode, valueStr, &binaryData)) if (!ModbusConnectionHelper_ConvertValueStrToUInt16(command->DataType, command->WriteRequest.RtuRequest.Payload.FunctionCode, valueStr, &binaryData))
{ {
LogError("Failed to convert data \"%s\" to byte array command \"%s\".", valueStr, command->Name); LogError("Failed to convert data \"%s\" to byte array command \"%s\".", valueStr, command->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
command->WriteRequest.RtuRequest.Payload.RegAddr_Hi = (modbusAddress >> 8) & 0xff; command->WriteRequest.RtuRequest.Payload.RegAddr_Hi = (modbusAddress >> 8) & 0xff;
@ -153,13 +153,13 @@ DIGITALTWIN_CLIENT_RESULT ModbusRtu_SetWriteRequest(
if (!ModbusConnectionHelper_GetFunctionCode(property->StartAddress, false, &(property->WriteRequest.RtuRequest.Payload.FunctionCode), &modbusAddress)) if (!ModbusConnectionHelper_GetFunctionCode(property->StartAddress, false, &(property->WriteRequest.RtuRequest.Payload.FunctionCode), &modbusAddress))
{ {
LogError("Failed to get Modbus function code for property \"%s\".", property->Name); LogError("Failed to get Modbus function code for property \"%s\".", property->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
if (!ModbusConnectionHelper_ConvertValueStrToUInt16(property->DataType, property->WriteRequest.RtuRequest.Payload.FunctionCode, valueStr, &binaryData)) if (!ModbusConnectionHelper_ConvertValueStrToUInt16(property->DataType, property->WriteRequest.RtuRequest.Payload.FunctionCode, valueStr, &binaryData))
{ {
LogError("Failed to convert data \"%s\" to byte array command \"%s\".", valueStr, property->Name); LogError("Failed to convert data \"%s\" to byte array command \"%s\".", valueStr, property->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
property->WriteRequest.RtuRequest.Payload.RegAddr_Hi = (modbusAddress >> 8) & 0xff; property->WriteRequest.RtuRequest.Payload.RegAddr_Hi = (modbusAddress >> 8) & 0xff;
@ -171,10 +171,10 @@ DIGITALTWIN_CLIENT_RESULT ModbusRtu_SetWriteRequest(
} }
default: default:
LogError("Modbus read if not supported for the capability."); LogError("Modbus read if not supported for the capability.");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
int ModbusRtu_SendRequest( int ModbusRtu_SendRequest(

Просмотреть файл

@ -14,8 +14,8 @@ extern "C"
int ModbusRtu_GetHeaderSize(void); int ModbusRtu_GetHeaderSize(void);
bool ModbusRtu_CloseDevice(HANDLE hDevice, LOCK_HANDLE lock); bool ModbusRtu_CloseDevice(HANDLE hDevice, LOCK_HANDLE lock);
DIGITALTWIN_CLIENT_RESULT ModbusRtu_SetReadRequest(CapabilityType capabilityType, void* capability, uint8_t unitId); IOTHUB_CLIENT_RESULT ModbusRtu_SetReadRequest(CapabilityType capabilityType, void* capability, uint8_t unitId);
DIGITALTWIN_CLIENT_RESULT ModbusRtu_SetWriteRequest(CapabilityType capabilityType, void* capability, char* valueStr); IOTHUB_CLIENT_RESULT ModbusRtu_SetWriteRequest(CapabilityType capabilityType, void* capability, char* valueStr);
int ModbusRtu_SendRequest(HANDLE handler, uint8_t *requestArr, uint32_t arrLen); int ModbusRtu_SendRequest(HANDLE handler, uint8_t *requestArr, uint32_t arrLen);
int ModbusRtu_ReadResponse(HANDLE handler, uint8_t *response, uint32_t arrLen); int ModbusRtu_ReadResponse(HANDLE handler, uint8_t *response, uint32_t arrLen);

Просмотреть файл

@ -45,7 +45,7 @@ bool ModbusTcp_CloseDevice(
return true; return true;
} }
DIGITALTWIN_CLIENT_RESULT ModbusTcp_SetReadRequest( IOTHUB_CLIENT_RESULT ModbusTcp_SetReadRequest(
CapabilityType capabilityType, CapabilityType capabilityType,
void* capability, void* capability,
uint8_t unitId) uint8_t unitId)
@ -60,7 +60,7 @@ DIGITALTWIN_CLIENT_RESULT ModbusTcp_SetReadRequest(
if (!ModbusConnectionHelper_GetFunctionCode(telemetry->StartAddress, true, &(telemetry->ReadRequest.TcpRequest.Payload.FunctionCode), &modbusAddress)) if (!ModbusConnectionHelper_GetFunctionCode(telemetry->StartAddress, true, &(telemetry->ReadRequest.TcpRequest.Payload.FunctionCode), &modbusAddress))
{ {
LogError("Failed to get Modbus function code for telemetry \"%s\".", telemetry->Name); LogError("Failed to get Modbus function code for telemetry \"%s\".", telemetry->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
telemetry->ReadRequest.TcpRequest.MBAP.ProtocolID_Hi = 0x00; telemetry->ReadRequest.TcpRequest.MBAP.ProtocolID_Hi = 0x00;
@ -82,7 +82,7 @@ DIGITALTWIN_CLIENT_RESULT ModbusTcp_SetReadRequest(
if (!ModbusConnectionHelper_GetFunctionCode(property->StartAddress, true, &(property->ReadRequest.TcpRequest.Payload.FunctionCode), &modbusAddress)) if (!ModbusConnectionHelper_GetFunctionCode(property->StartAddress, true, &(property->ReadRequest.TcpRequest.Payload.FunctionCode), &modbusAddress))
{ {
LogError("Failed to get Modbus function code for property \"%s\".", property->Name); LogError("Failed to get Modbus function code for property \"%s\".", property->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
property->ReadRequest.TcpRequest.MBAP.ProtocolID_Hi = 0x00; property->ReadRequest.TcpRequest.MBAP.ProtocolID_Hi = 0x00;
@ -99,13 +99,13 @@ DIGITALTWIN_CLIENT_RESULT ModbusTcp_SetReadRequest(
} }
default: default:
LogError("Modbus read if not supported for the capability."); LogError("Modbus read if not supported for the capability.");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT ModbusTcp_SetWriteRequest( IOTHUB_CLIENT_RESULT ModbusTcp_SetWriteRequest(
CapabilityType capabilityType, CapabilityType capabilityType,
void* capability, void* capability,
char* valueStr) char* valueStr)
@ -122,13 +122,13 @@ DIGITALTWIN_CLIENT_RESULT ModbusTcp_SetWriteRequest(
if (!ModbusConnectionHelper_GetFunctionCode(command->StartAddress, false, &(command->WriteRequest.TcpRequest.Payload.FunctionCode), &modbusAddress)) if (!ModbusConnectionHelper_GetFunctionCode(command->StartAddress, false, &(command->WriteRequest.TcpRequest.Payload.FunctionCode), &modbusAddress))
{ {
LogError("Failed to get Modbus function code for command \"%s\".", command->Name); LogError("Failed to get Modbus function code for command \"%s\".", command->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
if (!ModbusConnectionHelper_ConvertValueStrToUInt16(command->DataType, command->WriteRequest.TcpRequest.Payload.FunctionCode, valueStr, &binaryData)) if (!ModbusConnectionHelper_ConvertValueStrToUInt16(command->DataType, command->WriteRequest.TcpRequest.Payload.FunctionCode, valueStr, &binaryData))
{ {
LogError("Failed to convert data \"%s\" to byte array command \"%s\".", valueStr, command->Name); LogError("Failed to convert data \"%s\" to byte array command \"%s\".", valueStr, command->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
command->WriteRequest.TcpRequest.MBAP.ProtocolID_Hi = 0x00; command->WriteRequest.TcpRequest.MBAP.ProtocolID_Hi = 0x00;
@ -150,13 +150,13 @@ DIGITALTWIN_CLIENT_RESULT ModbusTcp_SetWriteRequest(
if (!ModbusConnectionHelper_GetFunctionCode(property->StartAddress, false, &(property->WriteRequest.TcpRequest.Payload.FunctionCode), &modbusAddress)) if (!ModbusConnectionHelper_GetFunctionCode(property->StartAddress, false, &(property->WriteRequest.TcpRequest.Payload.FunctionCode), &modbusAddress))
{ {
LogError("Failed to get Modbus function code for property \"%s\".", property->Name); LogError("Failed to get Modbus function code for property \"%s\".", property->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
if (!ModbusConnectionHelper_ConvertValueStrToUInt16(property->DataType, property->WriteRequest.TcpRequest.Payload.FunctionCode, valueStr, &binaryData)) if (!ModbusConnectionHelper_ConvertValueStrToUInt16(property->DataType, property->WriteRequest.TcpRequest.Payload.FunctionCode, valueStr, &binaryData))
{ {
LogError("Failed to convert data \"%s\" to byte array command \"%s\".", valueStr, property->Name); LogError("Failed to convert data \"%s\" to byte array command \"%s\".", valueStr, property->Name);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
property->WriteRequest.TcpRequest.MBAP.ProtocolID_Hi = 0x00; property->WriteRequest.TcpRequest.MBAP.ProtocolID_Hi = 0x00;
@ -172,10 +172,10 @@ DIGITALTWIN_CLIENT_RESULT ModbusTcp_SetWriteRequest(
} }
default: default:
LogError("Modbus read if not supported for the capability."); LogError("Modbus read if not supported for the capability.");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
int ModbusTcp_SendRequest( int ModbusTcp_SendRequest(

Просмотреть файл

@ -25,8 +25,8 @@ typedef int SOCKET;
int ModbusTcp_GetHeaderSize(void); int ModbusTcp_GetHeaderSize(void);
bool ModbusTcp_CloseDevice(SOCKET hDevice, LOCK_HANDLE lock); bool ModbusTcp_CloseDevice(SOCKET hDevice, LOCK_HANDLE lock);
DIGITALTWIN_CLIENT_RESULT ModbusTcp_SetReadRequest(CapabilityType capabilityType, void* capability, uint8_t unitId); IOTHUB_CLIENT_RESULT ModbusTcp_SetReadRequest(CapabilityType capabilityType, void* capability, uint8_t unitId);
DIGITALTWIN_CLIENT_RESULT ModbusTcp_SetWriteRequest(CapabilityType capabilityType, void* capability, char* valueStr); IOTHUB_CLIENT_RESULT ModbusTcp_SetWriteRequest(CapabilityType capabilityType, void* capability, char* valueStr);
int ModbusTcp_SendRequest(SOCKET handler, uint8_t *requestArr, uint32_t arrLen); int ModbusTcp_SendRequest(SOCKET handler, uint8_t *requestArr, uint32_t arrLen);
int ModbusTcp_ReadResponse(SOCKET handler, uint8_t *response, uint32_t arrLen); int ModbusTcp_ReadResponse(SOCKET handler, uint8_t *response, uint32_t arrLen);

Просмотреть файл

@ -62,14 +62,14 @@ ModbusDataType ToModbusDataTypeEnum(
return INVALID; return INVALID;
} }
DIGITALTWIN_CLIENT_RESULT ModbusPnp_ParseInterfaceConfig( IOTHUB_CLIENT_RESULT ModbusPnp_ParseInterfaceConfig(
ModbusInterfaceConfig* ModbusInterfaceConfig, ModbusInterfaceConfig* ModbusInterfaceConfig,
JSON_Object* ConfigObj) JSON_Object* ConfigObj)
{ {
if (NULL == ModbusInterfaceConfig) if (NULL == ModbusInterfaceConfig)
{ {
LogError("Cannot populate interface config for modbus adapter."); LogError("Cannot populate interface config for modbus adapter.");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
ModbusInterfaceConfig->Events = singlylinkedlist_create(); ModbusInterfaceConfig->Events = singlylinkedlist_create();
@ -85,14 +85,14 @@ DIGITALTWIN_CLIENT_RESULT ModbusPnp_ParseInterfaceConfig(
if (NULL == telemetryArgs) if (NULL == telemetryArgs)
{ {
LogError("ERROR: Telemetry \"%s\" definition is empty.", name); LogError("ERROR: Telemetry \"%s\" definition is empty.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
ModbusTelemetry* telemetry = calloc(1, sizeof(ModbusTelemetry)); ModbusTelemetry* telemetry = calloc(1, sizeof(ModbusTelemetry));
if (NULL == telemetry) if (NULL == telemetry)
{ {
LogError("Failed to allocation memory for telemetry configuration: \"%s\". ", name); LogError("Failed to allocation memory for telemetry configuration: \"%s\". ", name);
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
telemetry->Name = name; telemetry->Name = name;
@ -101,40 +101,40 @@ DIGITALTWIN_CLIENT_RESULT ModbusPnp_ParseInterfaceConfig(
if (0 == telemetry->StartAddress) if (0 == telemetry->StartAddress)
{ {
LogError("\"startAddress\" of telemetry \"%s\" is in valid. ", name); LogError("\"startAddress\" of telemetry \"%s\" is in valid. ", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
telemetry->Length = (uint8_t)json_object_dotget_number(telemetryArgs, "length"); telemetry->Length = (uint8_t)json_object_dotget_number(telemetryArgs, "length");
if (0 == telemetry->Length) if (0 == telemetry->Length)
{ {
LogError("\"length\" of telemetry \"%s\" is in valid. ", name); LogError("\"length\" of telemetry \"%s\" is in valid. ", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
const char* dataTypeStr = (const char*)json_object_dotget_string(telemetryArgs, "dataType"); const char* dataTypeStr = (const char*)json_object_dotget_string(telemetryArgs, "dataType");
if (NULL == dataTypeStr) if (NULL == dataTypeStr)
{ {
LogError("\"dataType\" of telemetry \"%s\" is in valid. ", name); LogError("\"dataType\" of telemetry \"%s\" is in valid. ", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
telemetry->DataType = ToModbusDataTypeEnum(dataTypeStr); telemetry->DataType = ToModbusDataTypeEnum(dataTypeStr);
if (telemetry->DataType == INVALID) if (telemetry->DataType == INVALID)
{ {
LogError("\"dataType\" of telemetry \"%s\" is in valid.", name); LogError("\"dataType\" of telemetry \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
telemetry->DefaultFrequency = (int)json_object_dotget_number(telemetryArgs, "defaultFrequency"); telemetry->DefaultFrequency = (int)json_object_dotget_number(telemetryArgs, "defaultFrequency");
if (0 == telemetry->DefaultFrequency) if (0 == telemetry->DefaultFrequency)
{ {
LogError("\"defaultFrequency\" of telemetry \"%s\" is in valid.", name); LogError("\"defaultFrequency\" of telemetry \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
telemetry->ConversionCoefficient = json_object_dotget_number(telemetryArgs, "conversionCoefficient"); telemetry->ConversionCoefficient = json_object_dotget_number(telemetryArgs, "conversionCoefficient");
if (0 == telemetry->ConversionCoefficient) if (0 == telemetry->ConversionCoefficient)
{ {
LogError("\"conversionCoefficient\" of telemetry \"%s\" is in valid.", name); LogError("\"conversionCoefficient\" of telemetry \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
singlylinkedlist_add(ModbusInterfaceConfig->Events, telemetry); singlylinkedlist_add(ModbusInterfaceConfig->Events, telemetry);
@ -149,14 +149,14 @@ DIGITALTWIN_CLIENT_RESULT ModbusPnp_ParseInterfaceConfig(
if (NULL == propertyArgs) if (NULL == propertyArgs)
{ {
LogError("ERROR: Property \"%s\" definition is empty.", name); LogError("ERROR: Property \"%s\" definition is empty.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
ModbusProperty* property = calloc(1, sizeof(ModbusProperty)); ModbusProperty* property = calloc(1, sizeof(ModbusProperty));
if (NULL == property) if (NULL == property)
{ {
LogError("Failed to allocation memory for property configuration: \"%s\".", name); LogError("Failed to allocation memory for property configuration: \"%s\".", name);
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
property->Name = name; property->Name = name;
@ -165,48 +165,48 @@ DIGITALTWIN_CLIENT_RESULT ModbusPnp_ParseInterfaceConfig(
if (0 == property->StartAddress) if (0 == property->StartAddress)
{ {
LogError("\"startAddress\" of property \"%s\" is in valid.", name); LogError("\"startAddress\" of property \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
property->Length = (uint8_t)json_object_dotget_number(propertyArgs, "length"); property->Length = (uint8_t)json_object_dotget_number(propertyArgs, "length");
if (0 == property->Length) if (0 == property->Length)
{ {
LogError("\"length\" of property \"%s\" is in valid.", name); LogError("\"length\" of property \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
const char* dataTypeStr = (const char*)json_object_dotget_string(propertyArgs, "dataType"); const char* dataTypeStr = (const char*)json_object_dotget_string(propertyArgs, "dataType");
if (NULL == dataTypeStr) if (NULL == dataTypeStr)
{ {
LogError("\"dataType\" of property \"%s\" is in valid.", name); LogError("\"dataType\" of property \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
property->DataType = ToModbusDataTypeEnum(dataTypeStr); property->DataType = ToModbusDataTypeEnum(dataTypeStr);
if (property->DataType == INVALID) if (property->DataType == INVALID)
{ {
LogError("\"dataType\" of telemetry \"%s\" is in valid.", name); LogError("\"dataType\" of telemetry \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
property->DefaultFrequency = (int)json_object_dotget_number(propertyArgs, "defaultFrequency"); property->DefaultFrequency = (int)json_object_dotget_number(propertyArgs, "defaultFrequency");
if (0 == property->DefaultFrequency) if (0 == property->DefaultFrequency)
{ {
LogError("\"defaultFrequency\" of property \"%s\" is in valid.", name); LogError("\"defaultFrequency\" of property \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
property->ConversionCoefficient = json_object_dotget_number(propertyArgs, "conversionCoefficient"); property->ConversionCoefficient = json_object_dotget_number(propertyArgs, "conversionCoefficient");
if (0 == property->ConversionCoefficient) if (0 == property->ConversionCoefficient)
{ {
LogError("\"conversionCoefficient\" of property \"%s\" is in valid.", name); LogError("\"conversionCoefficient\" of property \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
property->Access = (int)json_object_dotget_number(propertyArgs, "access"); property->Access = (int)json_object_dotget_number(propertyArgs, "access");
if (0 == property->Access) if (0 == property->Access)
{ {
LogError("\"conversionCoefficient\" of property \"%s\" is in valid.", name); LogError("\"conversionCoefficient\" of property \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
singlylinkedlist_add(ModbusInterfaceConfig->Properties, property); singlylinkedlist_add(ModbusInterfaceConfig->Properties, property);
@ -221,7 +221,7 @@ DIGITALTWIN_CLIENT_RESULT ModbusPnp_ParseInterfaceConfig(
if (NULL == commandArgs) if (NULL == commandArgs)
{ {
LogError("ERROR: Command \"%s\" definition is empty.", name); LogError("ERROR: Command \"%s\" definition is empty.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
ModbusCommand* command = calloc(1, sizeof(ModbusCommand)); ModbusCommand* command = calloc(1, sizeof(ModbusCommand));
@ -229,7 +229,7 @@ DIGITALTWIN_CLIENT_RESULT ModbusPnp_ParseInterfaceConfig(
if (NULL == command) if (NULL == command)
{ {
LogError("Failed to allocation memory for command configuration: \"%s\".", name); LogError("Failed to allocation memory for command configuration: \"%s\".", name);
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
command->Name = name; command->Name = name;
@ -238,40 +238,40 @@ DIGITALTWIN_CLIENT_RESULT ModbusPnp_ParseInterfaceConfig(
if (0 == command->StartAddress) if (0 == command->StartAddress)
{ {
LogError("\"startAddress\" of command \"%s\" is in valid.", name); LogError("\"startAddress\" of command \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
command->Length = (uint8_t)json_object_dotget_number(commandArgs, "length"); command->Length = (uint8_t)json_object_dotget_number(commandArgs, "length");
if (0 == command->Length) if (0 == command->Length)
{ {
LogError("\"length\" of command \"%s\" is in valid.", name); LogError("\"length\" of command \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
const char* dataTypeStr = (const char*)json_object_dotget_string(commandArgs, "dataType"); const char* dataTypeStr = (const char*)json_object_dotget_string(commandArgs, "dataType");
if (NULL == dataTypeStr) if (NULL == dataTypeStr)
{ {
LogError("\"dataType\" of command \"%s\" is in valid.", name); LogError("\"dataType\" of command \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
command->DataType = ToModbusDataTypeEnum(dataTypeStr); command->DataType = ToModbusDataTypeEnum(dataTypeStr);
if (command->DataType == INVALID) if (command->DataType == INVALID)
{ {
LogError("\"dataType\" of telemetry \"%s\" is in valid.", name); LogError("\"dataType\" of telemetry \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
command->ConversionCoefficient = json_object_dotget_number(commandArgs, "conversionCoefficient"); command->ConversionCoefficient = json_object_dotget_number(commandArgs, "conversionCoefficient");
if (0 == command->ConversionCoefficient) if (0 == command->ConversionCoefficient)
{ {
LogError("\"conversionCoefficient\" of command \"%s\" is in valid.", name); LogError("\"conversionCoefficient\" of command \"%s\" is in valid.", name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
singlylinkedlist_add(ModbusInterfaceConfig->Commands, command); singlylinkedlist_add(ModbusInterfaceConfig->Commands, command);
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
int ModbusPnp_ParseRtuSettings( int ModbusPnp_ParseRtuSettings(
@ -282,14 +282,14 @@ int ModbusPnp_ParseRtuSettings(
deviceConfig->ConnectionConfig.RtuConfig.Port = (char*)json_object_dotget_string(configObj, "port"); deviceConfig->ConnectionConfig.RtuConfig.Port = (char*)json_object_dotget_string(configObj, "port");
if (NULL == deviceConfig->ConnectionConfig.RtuConfig.Port) { if (NULL == deviceConfig->ConnectionConfig.RtuConfig.Port) {
LogError("ComPort parameter is missing in RTU configuration"); LogError("ComPort parameter is missing in RTU configuration");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
// Get serial baudRate // Get serial baudRate
const char* baudRateStr = (const char*)json_object_dotget_string(configObj, "baudRate"); const char* baudRateStr = (const char*)json_object_dotget_string(configObj, "baudRate");
if (NULL == baudRateStr) { if (NULL == baudRateStr) {
LogError("BaudRate parameter is missing in RTU configuration"); LogError("BaudRate parameter is missing in RTU configuration");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
deviceConfig->ConnectionConfig.RtuConfig.BaudRate = atoi(baudRateStr); deviceConfig->ConnectionConfig.RtuConfig.BaudRate = atoi(baudRateStr);
@ -297,7 +297,7 @@ int ModbusPnp_ParseRtuSettings(
deviceConfig->ConnectionConfig.RtuConfig.DataBits = (uint8_t)json_object_dotget_number(configObj, "dataBits"); deviceConfig->ConnectionConfig.RtuConfig.DataBits = (uint8_t)json_object_dotget_number(configObj, "dataBits");
if (7 != deviceConfig->ConnectionConfig.RtuConfig.DataBits && 8 != deviceConfig->ConnectionConfig.RtuConfig.DataBits) { if (7 != deviceConfig->ConnectionConfig.RtuConfig.DataBits && 8 != deviceConfig->ConnectionConfig.RtuConfig.DataBits) {
LogError("data Bits parameter is missing or invalid in RTU configuration. Valid Input: {7, 8}"); LogError("data Bits parameter is missing or invalid in RTU configuration. Valid Input: {7, 8}");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
// Get serial stopBits // Get serial stopBits
@ -314,7 +314,7 @@ int ModbusPnp_ParseRtuSettings(
} }
else { else {
LogError("Invalide Stop Bit parameter in RTU configuration. Valid Input: {\"ONE\", \"TWO\", \"OnePointFive\"}"); LogError("Invalide Stop Bit parameter in RTU configuration. Valid Input: {\"ONE\", \"TWO\", \"OnePointFive\"}");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
} }
else { else {
@ -322,7 +322,7 @@ int ModbusPnp_ParseRtuSettings(
uint8_t stopBitInput = (uint8_t)json_object_dotget_number(configObj, "stopBits"); uint8_t stopBitInput = (uint8_t)json_object_dotget_number(configObj, "stopBits");
if (0 == stopBitInput) { if (0 == stopBitInput) {
LogError("Stop Bit parameter is missing in RTU configuration."); LogError("Stop Bit parameter is missing in RTU configuration.");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
switch (stopBitInput) { switch (stopBitInput) {
@ -337,7 +337,7 @@ int ModbusPnp_ParseRtuSettings(
break; break;
default: default:
LogError("Invalide Stop Bit parameter in RTU configuration. Valid Input: {\"ONE\", \"TWO\", \"OnePointFive\", 1, 2, 3}"); LogError("Invalide Stop Bit parameter in RTU configuration. Valid Input: {\"ONE\", \"TWO\", \"OnePointFive\", 1, 2, 3}");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
break; break;
} }
} }
@ -370,7 +370,7 @@ int ModbusPnp_ParseRtuSettings(
} }
deviceConfig->ConnectionType = RTU; deviceConfig->ConnectionType = RTU;
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
int ModbusPnP_ParseTcpSettings( int ModbusPnP_ParseTcpSettings(
@ -381,19 +381,19 @@ int ModbusPnP_ParseTcpSettings(
deviceConfig->ConnectionConfig.TcpConfig.Host = (char*)json_object_dotget_string(configObj, "host"); deviceConfig->ConnectionConfig.TcpConfig.Host = (char*)json_object_dotget_string(configObj, "host");
if (NULL == deviceConfig->ConnectionConfig.TcpConfig.Host) { if (NULL == deviceConfig->ConnectionConfig.TcpConfig.Host) {
LogError("\"Host\" parameter is missing in TCP configuration"); LogError("\"Host\" parameter is missing in TCP configuration");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
// Get serial dataBits // Get serial dataBits
deviceConfig->ConnectionConfig.TcpConfig.Port = (uint16_t)json_object_dotget_number(configObj, "port"); deviceConfig->ConnectionConfig.TcpConfig.Port = (uint16_t)json_object_dotget_number(configObj, "port");
if (0 == deviceConfig->ConnectionConfig.TcpConfig.Port) { if (0 == deviceConfig->ConnectionConfig.TcpConfig.Port) {
LogError("\"Port\" is invalide in TCP configuration: Cannot be 0."); LogError("\"Port\" is invalide in TCP configuration: Cannot be 0.");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
deviceConfig->ConnectionType = TCP; deviceConfig->ConnectionType = TCP;
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
#pragma endregion #pragma endregion
@ -422,7 +422,7 @@ int ModbusPnp_OpenSerial(
if (*serialHandle == INVALID_HANDLE_VALUE) { if (*serialHandle == INVALID_HANDLE_VALUE) {
// Handle the error // Handle the error
LogError("Failed to open com port %s", rtuConfig->Port); LogError("Failed to open com port %s", rtuConfig->Port);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
#ifdef WIN32 #ifdef WIN32
@ -432,7 +432,7 @@ int ModbusPnp_OpenSerial(
dcbSerialParams.DCBlength = sizeof(DCB); dcbSerialParams.DCBlength = sizeof(DCB);
if (!GetCommState(*serialHandle, &dcbSerialParams)) { if (!GetCommState(*serialHandle, &dcbSerialParams)) {
LogError("Failed to open com port %s, %x", rtuConfig->Port, GetLastError()); LogError("Failed to open com port %s, %x", rtuConfig->Port, GetLastError());
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
dcbSerialParams.BaudRate = rtuConfig->BaudRate; dcbSerialParams.BaudRate = rtuConfig->BaudRate;
dcbSerialParams.ByteSize = rtuConfig->DataBits; dcbSerialParams.ByteSize = rtuConfig->DataBits;
@ -441,7 +441,7 @@ int ModbusPnp_OpenSerial(
if (!SetCommState(*serialHandle, &dcbSerialParams)) { if (!SetCommState(*serialHandle, &dcbSerialParams)) {
// Error setting serial port state // Error setting serial port state
LogError("Failed to open com port %s, %x", rtuConfig->Port, GetLastError()); LogError("Failed to open com port %s, %x", rtuConfig->Port, GetLastError());
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
LogInfo("Opened com port %s", rtuConfig->Port); LogInfo("Opened com port %s", rtuConfig->Port);
@ -456,7 +456,7 @@ int ModbusPnp_OpenSerial(
{ {
int error = GetLastError(); int error = GetLastError();
printf("Set timeout failed on com port %s, %x", rtuConfig->Port, error); printf("Set timeout failed on com port %s, %x", rtuConfig->Port, error);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
#else #else
struct termios settings; struct termios settings;
@ -492,7 +492,7 @@ int ModbusPnp_OpenSerial(
tcsetattr(*serialHandle, TCSANOW, &settings); tcsetattr(*serialHandle, TCSANOW, &settings);
tcflush(*serialHandle, TCOFLUSH); tcflush(*serialHandle, TCOFLUSH);
#endif #endif
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
int ModbusPnp_OpenSocket( int ModbusPnp_OpenSocket(
@ -506,7 +506,7 @@ int ModbusPnp_OpenSocket(
result = WSAStartup(MAKEWORD(2, 2), &wsaData); result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) { if (result != 0) {
LogError("WSAStartup failed: %d\n", result); LogError("WSAStartup failed: %d\n", result);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
#endif #endif
@ -550,13 +550,13 @@ int ModbusPnp_OpenSocket(
goto ExitOnError; goto ExitOnError;
} }
LogInfo("Connected to device at \"%s:%d\".", tcpConfig->Host, tcpConfig->Port); LogInfo("Connected to device at \"%s:%d\".", tcpConfig->Host, tcpConfig->Port);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
ExitOnError: ExitOnError:
#ifdef WIN32 #ifdef WIN32
WSACleanup(); WSACleanup();
#endif #endif
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
#pragma endregion #pragma endregion
@ -633,7 +633,7 @@ void Modbus_CleanupPollingTasks(
} }
} }
DIGITALTWIN_CLIENT_RESULT IOTHUB_CLIENT_RESULT
Modbus_StartPnpInterface( Modbus_StartPnpInterface(
_In_ PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, _In_ PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
_In_ PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) _In_ PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
@ -643,16 +643,16 @@ Modbus_StartPnpInterface(
if (deviceContext == NULL) if (deviceContext == NULL)
{ {
LogError("Modbus_StartPnpInterface: Device context is null, cannot start interface."); LogError("Modbus_StartPnpInterface: Device context is null, cannot start interface.");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
// Start polling all telemetry // Start polling all telemetry
return ModbusPnp_StartPollingAllTelemetryProperty(deviceContext); return ModbusPnp_StartPollingAllTelemetryProperty(deviceContext);
} }
DIGITALTWIN_CLIENT_RESULT Modbus_DestroyPnpAdapter( IOTHUB_CLIENT_RESULT Modbus_DestroyPnpAdapter(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle) PNPBRIDGE_ADAPTER_HANDLE AdapterHandle)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
PMODBUS_ADAPTER_CONTEXT adapterContext = PnpAdapterHandleGetContext(AdapterHandle); PMODBUS_ADAPTER_CONTEXT adapterContext = PnpAdapterHandleGetContext(AdapterHandle);
if (adapterContext == NULL) if (adapterContext == NULL)
{ {
@ -677,16 +677,16 @@ DIGITALTWIN_CLIENT_RESULT Modbus_DestroyPnpAdapter(
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT Modbus_CreatePnpAdapter( IOTHUB_CLIENT_RESULT Modbus_CreatePnpAdapter(
const JSON_Object* AdapterGlobalConfig, const JSON_Object* AdapterGlobalConfig,
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle) PNPBRIDGE_ADAPTER_HANDLE AdapterHandle)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
PMODBUS_ADAPTER_CONTEXT adapterContext = calloc(1, sizeof(MODBUS_ADAPTER_CONTEXT)); PMODBUS_ADAPTER_CONTEXT adapterContext = calloc(1, sizeof(MODBUS_ADAPTER_CONTEXT));
if (!adapterContext) if (!adapterContext)
{ {
LogError("Could not allocate memory for adapter context."); LogError("Could not allocate memory for adapter context.");
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -695,7 +695,7 @@ DIGITALTWIN_CLIENT_RESULT Modbus_CreatePnpAdapter(
if (AdapterGlobalConfig == NULL) if (AdapterGlobalConfig == NULL)
{ {
LogError("Modbus adapter requires associated global parameters in config"); LogError("Modbus adapter requires associated global parameters in config");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -706,24 +706,24 @@ DIGITALTWIN_CLIENT_RESULT Modbus_CreatePnpAdapter(
if (!interfaceConfig) if (!interfaceConfig)
{ {
LogError("Could not allocate memory for interface configuration."); LogError("Could not allocate memory for interface configuration.");
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
if (0 != mallocAndStrcpy_s((char**)(&interfaceConfig->Id), modbusConfigIdentity)) if (0 != mallocAndStrcpy_s((char**)(&interfaceConfig->Id), modbusConfigIdentity))
{ {
LogError("Could not allocate memory for interface configuration's identity"); LogError("Could not allocate memory for interface configuration's identity");
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
free(interfaceConfig); free(interfaceConfig);
goto exit; goto exit;
} }
JSON_Object* interfaceConfigJson = json_object_get_object(AdapterGlobalConfig, modbusConfigIdentity); JSON_Object* interfaceConfigJson = json_object_get_object(AdapterGlobalConfig, modbusConfigIdentity);
if (DIGITALTWIN_CLIENT_OK != ModbusPnp_ParseInterfaceConfig(interfaceConfig, interfaceConfigJson)) if (IOTHUB_CLIENT_OK != ModbusPnp_ParseInterfaceConfig(interfaceConfig, interfaceConfigJson))
{ {
LogError("Could not parse interface config definition for %s", (char*)interfaceConfig->Id); LogError("Could not parse interface config definition for %s", (char*)interfaceConfig->Id);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -734,19 +734,19 @@ DIGITALTWIN_CLIENT_RESULT Modbus_CreatePnpAdapter(
PnpAdapterHandleSetContext(AdapterHandle, (void*)adapterContext); PnpAdapterHandleSetContext(AdapterHandle, (void*)adapterContext);
exit: exit:
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
result = Modbus_DestroyPnpAdapter(AdapterHandle); result = Modbus_DestroyPnpAdapter(AdapterHandle);
} }
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT Modbus_RetrieveMatchingInterfaceConfig( IOTHUB_CLIENT_RESULT Modbus_RetrieveMatchingInterfaceConfig(
const char* ModbusId, const char* ModbusId,
SINGLYLINKEDLIST_HANDLE InterfaceDefinitions, SINGLYLINKEDLIST_HANDLE InterfaceDefinitions,
PMODBUS_DEVICE_CONTEXT DeviceContext) PMODBUS_DEVICE_CONTEXT DeviceContext)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_INVALID_ARG;
if (ModbusId == NULL || InterfaceDefinitions == NULL || DeviceContext == NULL) if (ModbusId == NULL || InterfaceDefinitions == NULL || DeviceContext == NULL)
{ {
LogError("Modbus_RetrieveMatchingInterfaceConfig: Invalid arguments."); LogError("Modbus_RetrieveMatchingInterfaceConfig: Invalid arguments.");
@ -761,7 +761,7 @@ DIGITALTWIN_CLIENT_RESULT Modbus_RetrieveMatchingInterfaceConfig(
if (strcmp(interfaceConfig->Id, ModbusId) == 0) if (strcmp(interfaceConfig->Id, ModbusId) == 0)
{ {
DeviceContext->InterfaceConfig = interfaceConfig; DeviceContext->InterfaceConfig = interfaceConfig;
result = DIGITALTWIN_CLIENT_OK; result = IOTHUB_CLIENT_OK;
} }
interfaceDefinition = singlylinkedlist_get_next_item(interfaceDefinition); interfaceDefinition = singlylinkedlist_get_next_item(interfaceDefinition);
} }
@ -769,11 +769,11 @@ DIGITALTWIN_CLIENT_RESULT Modbus_RetrieveMatchingInterfaceConfig(
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT Modbus_ParseDeviceConfig( IOTHUB_CLIENT_RESULT Modbus_ParseDeviceConfig(
const JSON_Object* AdapterInterfaceConfig, const JSON_Object* AdapterInterfaceConfig,
PModbusDeviceConfig DeviceConfig) PModbusDeviceConfig DeviceConfig)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
if (AdapterInterfaceConfig == NULL || DeviceConfig == NULL) if (AdapterInterfaceConfig == NULL || DeviceConfig == NULL)
{ {
LogError("Modbus_ParseDeviceConfig: Invalid arguments."); LogError("Modbus_ParseDeviceConfig: Invalid arguments.");
@ -782,35 +782,35 @@ DIGITALTWIN_CLIENT_RESULT Modbus_ParseDeviceConfig(
DeviceConfig->UnitId = (uint8_t)json_object_get_number(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_INTERFACE_UNITID); DeviceConfig->UnitId = (uint8_t)json_object_get_number(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_INTERFACE_UNITID);
JSON_Object* rtuArgs = json_object_get_object(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_INTERFACE_RTU); JSON_Object* rtuArgs = json_object_get_object(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_INTERFACE_RTU);
if (NULL != rtuArgs && ModbusPnp_ParseRtuSettings(DeviceConfig, rtuArgs) != DIGITALTWIN_CLIENT_OK) { if (NULL != rtuArgs && ModbusPnp_ParseRtuSettings(DeviceConfig, rtuArgs) != IOTHUB_CLIENT_OK) {
LogError("Failed to parse RTU connection settings."); LogError("Failed to parse RTU connection settings.");
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
JSON_Object* tcpArgs = json_object_get_object(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_INTERFACE_TCP); JSON_Object* tcpArgs = json_object_get_object(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_INTERFACE_TCP);
if (NULL != tcpArgs && ModbusPnP_ParseTcpSettings(DeviceConfig, tcpArgs) != DIGITALTWIN_CLIENT_OK) { if (NULL != tcpArgs && ModbusPnP_ParseTcpSettings(DeviceConfig, tcpArgs) != IOTHUB_CLIENT_OK) {
LogError("Failed to parse RTU connection settings."); LogError("Failed to parse RTU connection settings.");
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
if (UNKOWN == DeviceConfig->ConnectionType) { if (UNKOWN == DeviceConfig->ConnectionType) {
LogError("Missing Modbus connection settings."); LogError("Missing Modbus connection settings.");
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
exit: exit:
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT Modbus_DestroyPnpInterface( IOTHUB_CLIENT_RESULT Modbus_DestroyPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
PMODBUS_DEVICE_CONTEXT deviceContext = PnpInterfaceHandleGetContext(PnpInterfaceHandle); PMODBUS_DEVICE_CONTEXT deviceContext = PnpInterfaceHandleGetContext(PnpInterfaceHandle);
if (NULL == deviceContext) { if (NULL == deviceContext) {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
// Call DigitalTwin_InterfaceClient_Destroy. // Call DigitalTwin_InterfaceClient_Destroy.
@ -828,10 +828,10 @@ DIGITALTWIN_CLIENT_RESULT Modbus_DestroyPnpInterface(
free(deviceContext); free(deviceContext);
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT IOTHUB_CLIENT_RESULT
Modbus_CreatePnpInterface( Modbus_CreatePnpInterface(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
const char* ComponentName, const char* ComponentName,
@ -839,13 +839,13 @@ Modbus_CreatePnpInterface(
PNPBRIDGE_INTERFACE_HANDLE BridgeInterfaceHandle, PNPBRIDGE_INTERFACE_HANDLE BridgeInterfaceHandle,
DIGITALTWIN_INTERFACE_CLIENT_HANDLE* PnpInterfaceClient) DIGITALTWIN_INTERFACE_CLIENT_HANDLE* PnpInterfaceClient)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterfaceClient; DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterfaceClient;
PMODBUS_DEVICE_CONTEXT deviceContext = calloc(1, sizeof(MODBUS_DEVICE_CONTEXT)); PMODBUS_DEVICE_CONTEXT deviceContext = calloc(1, sizeof(MODBUS_DEVICE_CONTEXT));
if (!deviceContext) if (!deviceContext)
{ {
LogError("Could not allocate memory for device context."); LogError("Could not allocate memory for device context.");
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
// Populate interface config from adapter's supported interface definitions // Populate interface config from adapter's supported interface definitions
@ -853,7 +853,7 @@ Modbus_CreatePnpInterface(
PMODBUS_ADAPTER_CONTEXT adapterContext = PnpAdapterHandleGetContext(AdapterHandle); PMODBUS_ADAPTER_CONTEXT adapterContext = PnpAdapterHandleGetContext(AdapterHandle);
const char* modbusIdentity = json_object_dotget_string(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_MODBUS_IDENTITY); const char* modbusIdentity = json_object_dotget_string(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_MODBUS_IDENTITY);
result = Modbus_RetrieveMatchingInterfaceConfig(modbusIdentity, adapterContext->InterfaceDefinitions, deviceContext); result = Modbus_RetrieveMatchingInterfaceConfig(modbusIdentity, adapterContext->InterfaceDefinitions, deviceContext);
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("Could not find matching modbus interface configuration for this interface"); LogError("Could not find matching modbus interface configuration for this interface");
goto exit; goto exit;
@ -864,7 +864,7 @@ Modbus_CreatePnpInterface(
deviceContext->hConnectionLock = Lock_Init(); deviceContext->hConnectionLock = Lock_Init();
if (NULL == deviceContext->hConnectionLock) if (NULL == deviceContext->hConnectionLock)
{ {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
LogError("Failed to create a valid lock handle for device connection."); LogError("Failed to create a valid lock handle for device connection.");
goto exit; goto exit;
} }
@ -874,12 +874,12 @@ Modbus_CreatePnpInterface(
if (!deviceConfig) if (!deviceConfig)
{ {
LogError("Could not allocate memory for device config."); LogError("Could not allocate memory for device config.");
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
deviceConfig->ConnectionType = UNKOWN; deviceConfig->ConnectionType = UNKOWN;
result = Modbus_ParseDeviceConfig(AdapterInterfaceConfig, deviceConfig); result = Modbus_ParseDeviceConfig(AdapterInterfaceConfig, deviceConfig);
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
LogError("Could not parse device configuration for this modbus interface."); LogError("Could not parse device configuration for this modbus interface.");
goto exit; goto exit;
@ -890,7 +890,7 @@ Modbus_CreatePnpInterface(
{ {
result = ModbusPnp_OpenSerial(&(deviceConfig->ConnectionConfig.RtuConfig), result = ModbusPnp_OpenSerial(&(deviceConfig->ConnectionConfig.RtuConfig),
&(deviceContext->hDevice)); &(deviceContext->hDevice));
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("Failed to open serial connection to \"%s\".", LogError("Failed to open serial connection to \"%s\".",
deviceConfig->ConnectionConfig.RtuConfig.Port); deviceConfig->ConnectionConfig.RtuConfig.Port);
@ -901,7 +901,7 @@ Modbus_CreatePnpInterface(
{ {
result = ModbusPnp_OpenSocket(&(deviceConfig->ConnectionConfig.TcpConfig), result = ModbusPnp_OpenSocket(&(deviceConfig->ConnectionConfig.TcpConfig),
(SOCKET*)&(deviceContext->hDevice)); (SOCKET*)&(deviceContext->hDevice));
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("Failed to open socket connection to \"%s:%d\".", LogError("Failed to open socket connection to \"%s:%d\".",
deviceConfig->ConnectionConfig.TcpConfig.Host, deviceConfig->ConnectionConfig.TcpConfig.Host,
@ -924,10 +924,10 @@ Modbus_CreatePnpInterface(
while (NULL != telemetryHandle) { while (NULL != telemetryHandle) {
PModbusTelemetry telemetry = (PModbusTelemetry)singlylinkedlist_item_get_value(telemetryHandle); PModbusTelemetry telemetry = (PModbusTelemetry)singlylinkedlist_item_get_value(telemetryHandle);
result = ModbusPnp_SetReadRequest(deviceConfig, Telemetry, telemetry); result = ModbusPnp_SetReadRequest(deviceConfig, Telemetry, telemetry);
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("Failed to create read request for telemetry \"%s\".", telemetry->Name); LogError("Failed to create read request for telemetry \"%s\".", telemetry->Name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
telemetryHandle = singlylinkedlist_get_next_item(telemetryHandle); telemetryHandle = singlylinkedlist_get_next_item(telemetryHandle);
} }
@ -953,10 +953,10 @@ Modbus_CreatePnpInterface(
} }
result = ModbusPnp_SetReadRequest(deviceConfig, Property, property); result = ModbusPnp_SetReadRequest(deviceConfig, Property, property);
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("Failed to create read request for telemetry \"%s\".", property->Name); LogError("Failed to create read request for telemetry \"%s\".", property->Name);
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
propertyhandle = singlylinkedlist_get_next_item(propertyhandle); propertyhandle = singlylinkedlist_get_next_item(propertyhandle);
} }
@ -1023,13 +1023,13 @@ Modbus_CreatePnpInterface(
{ {
propertyNames = calloc(1, sizeof(char*) * readWritePropertyCount); propertyNames = calloc(1, sizeof(char*) * readWritePropertyCount);
if (NULL == propertyNames) { if (NULL == propertyNames) {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
propertyUpdateTable = calloc(1, sizeof(DIGITALTWIN_PROPERTY_UPDATE_CALLBACK*) * readWritePropertyCount); propertyUpdateTable = calloc(1, sizeof(DIGITALTWIN_PROPERTY_UPDATE_CALLBACK*) * readWritePropertyCount);
if (NULL == propertyUpdateTable) { if (NULL == propertyUpdateTable) {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -1065,13 +1065,13 @@ Modbus_CreatePnpInterface(
{ {
commandNames = calloc(1, sizeof(char*) * commandCount); commandNames = calloc(1, sizeof(char*) * commandCount);
if (NULL == commandNames) { if (NULL == commandNames) {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
commandUpdateTable = calloc(1, sizeof(DIGITALTWIN_COMMAND_EXECUTE_CALLBACK*) * commandCount); commandUpdateTable = calloc(1, sizeof(DIGITALTWIN_COMMAND_EXECUTE_CALLBACK*) * commandCount);
if (NULL == commandUpdateTable) { if (NULL == commandUpdateTable) {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -1099,9 +1099,9 @@ Modbus_CreatePnpInterface(
// Call DigitalTwinClient Create and assign pnpInterfaceClient to deviceContext's pnpInterfaceClient // Call DigitalTwinClient Create and assign pnpInterfaceClient to deviceContext's pnpInterfaceClient
result = DigitalTwin_InterfaceClient_Create(ComponentName, NULL, deviceContext, result = DigitalTwin_InterfaceClient_Create(ComponentName, NULL, deviceContext,
&pnpInterfaceClient); &pnpInterfaceClient);
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
LogError("Modbus_CreatePnpInterface: DigitalTwin_InterfaceClient_Create failed."); LogError("Modbus_CreatePnpInterface: DigitalTwin_InterfaceClient_Create failed.");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -1109,9 +1109,9 @@ Modbus_CreatePnpInterface(
result = DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback(pnpInterfaceClient, result = DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback(pnpInterfaceClient,
ModbusPnp_PropertyHandler, ModbusPnp_PropertyHandler,
(void*) deviceContext); (void*) deviceContext);
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
LogError("Modbus_CreatePnpInterface: DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback failed."); LogError("Modbus_CreatePnpInterface: DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback failed.");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
} }
@ -1119,9 +1119,9 @@ Modbus_CreatePnpInterface(
if (commandCount > 0) { if (commandCount > 0) {
result = DigitalTwin_InterfaceClient_SetCommandsCallback(pnpInterfaceClient, result = DigitalTwin_InterfaceClient_SetCommandsCallback(pnpInterfaceClient,
ModbusPnp_CommandHandler, (void*)deviceContext); ModbusPnp_CommandHandler, (void*)deviceContext);
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
LogError("Modbus_CreatePnpInterface: DigitalTwin_InterfaceClient_SetCommandsCallback failed."); LogError("Modbus_CreatePnpInterface: DigitalTwin_InterfaceClient_SetCommandsCallback failed.");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
} }
@ -1132,7 +1132,7 @@ Modbus_CreatePnpInterface(
PnpInterfaceHandleSetContext(BridgeInterfaceHandle, deviceContext); PnpInterfaceHandleSetContext(BridgeInterfaceHandle, deviceContext);
exit: exit:
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
Modbus_DestroyPnpInterface(BridgeInterfaceHandle); Modbus_DestroyPnpInterface(BridgeInterfaceHandle);
} }
@ -1140,12 +1140,12 @@ exit:
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT Modbus_StopPnpInterface( IOTHUB_CLIENT_RESULT Modbus_StopPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
PMODBUS_DEVICE_CONTEXT deviceContext = PnpInterfaceHandleGetContext(PnpInterfaceHandle); PMODBUS_DEVICE_CONTEXT deviceContext = PnpInterfaceHandleGetContext(PnpInterfaceHandle);
if (NULL == deviceContext) { if (NULL == deviceContext) {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
Modbus_CleanupPollingTasks(deviceContext); Modbus_CleanupPollingTasks(deviceContext);
@ -1160,7 +1160,7 @@ DIGITALTWIN_CLIENT_RESULT Modbus_StopPnpInterface(
Lock_Deinit(deviceContext->hConnectionLock); Lock_Deinit(deviceContext->hConnectionLock);
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
#pragma endregion #pragma endregion

Просмотреть файл

@ -187,7 +187,7 @@ JsonRpcProtocolHandler::RpcNotificationCallback(
if (tname) { if (tname) {
// Publish telemetry // Publish telemetry
char *out = json_serialize_to_string(Parameters); char *out = json_serialize_to_string(Parameters);
DIGITALTWIN_CLIENT_RESULT res = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT res = IOTHUB_CLIENT_OK;
const char* telemetryMessageFormat = "{\"%s\":%s}"; const char* telemetryMessageFormat = "{\"%s\":%s}";
size_t telemetryMessageLen = (strlen(tname) + strlen(out) + strlen(telemetryMessageFormat) + 1); size_t telemetryMessageLen = (strlen(tname) + strlen(out) + strlen(telemetryMessageFormat) + 1);
char * telemetryMessage = (char*) malloc(sizeof(char) * telemetryMessageLen); char * telemetryMessage = (char*) malloc(sizeof(char) * telemetryMessageLen);
@ -200,7 +200,7 @@ JsonRpcProtocolHandler::RpcNotificationCallback(
reinterpret_cast<const unsigned char*> (telemetryMessage), reinterpret_cast<const unsigned char*> (telemetryMessage),
telemetryMessageLen, telemetryMessageLen,
nullptr, nullptr,
nullptr)) != DIGITALTWIN_CLIENT_OK) { nullptr)) != IOTHUB_CLIENT_OK) {
LogError("mqtt-pnp: Error sending telemetry %s, result=%d", tname, res); LogError("mqtt-pnp: Error sending telemetry %s, result=%d", tname, res);
} else { } else {

Просмотреть файл

@ -41,40 +41,40 @@ public:
std::map<std::string, JSON_Value*> s_AdapterConfigs; std::map<std::string, JSON_Value*> s_AdapterConfigs;
}; };
DIGITALTWIN_CLIENT_RESULT MqttPnp_DestroyPnpInterface( IOTHUB_CLIENT_RESULT MqttPnp_DestroyPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
printf("mqtt-pnp: destroying interface component\n"); printf("mqtt-pnp: destroying interface component\n");
MqttPnpInstance* context = static_cast<MqttPnpInstance*>(PnpInterfaceHandleGetContext(PnpInterfaceHandle)); MqttPnpInstance* context = static_cast<MqttPnpInstance*>(PnpInterfaceHandleGetContext(PnpInterfaceHandle));
if (NULL == context) if (NULL == context)
{ {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DigitalTwin_InterfaceClient_Destroy((context->s_ProtocolHandler)->GetDigitalTwin()); DigitalTwin_InterfaceClient_Destroy((context->s_ProtocolHandler)->GetDigitalTwin());
context->s_ConnectionManager.Disconnect(); context->s_ConnectionManager.Disconnect();
delete context; delete context;
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT MqttPnp_DestroyPnpAdapter( IOTHUB_CLIENT_RESULT MqttPnp_DestroyPnpAdapter(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle PNPBRIDGE_ADAPTER_HANDLE AdapterHandle
) )
{ {
MqttPnpAdapter* adapterContext = reinterpret_cast<MqttPnpAdapter*>(PnpAdapterHandleGetContext(AdapterHandle)); MqttPnpAdapter* adapterContext = reinterpret_cast<MqttPnpAdapter*>(PnpAdapterHandleGetContext(AdapterHandle));
if (adapterContext == NULL) if (adapterContext == NULL)
{ {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
adapterContext->s_AdapterConfigs.clear(); adapterContext->s_AdapterConfigs.clear();
delete adapterContext; delete adapterContext;
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT IOTHUB_CLIENT_RESULT
MqttPnp_CreatePnpInterface( MqttPnp_CreatePnpInterface(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
const char* ComponentName, const char* ComponentName,
@ -82,7 +82,7 @@ MqttPnp_CreatePnpInterface(
PNPBRIDGE_INTERFACE_HANDLE BridgeInterfaceHandle, PNPBRIDGE_INTERFACE_HANDLE BridgeInterfaceHandle,
DIGITALTWIN_INTERFACE_CLIENT_HANDLE* PnpInterfaceClient) DIGITALTWIN_INTERFACE_CLIENT_HANDLE* PnpInterfaceClient)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterfaceClient; DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterfaceClient;
JSON_Value* adapterConfig = NULL; JSON_Value* adapterConfig = NULL;
std::map<std::string, JSON_Value*>::iterator mapItem; std::map<std::string, JSON_Value*>::iterator mapItem;
@ -90,7 +90,7 @@ MqttPnp_CreatePnpInterface(
if (NULL!= AdapterInterfaceConfig) if (NULL!= AdapterInterfaceConfig)
{ {
LogError("Each component requiring the Mqtt adapter needs to specify local adapter args (pnp_bridge_adapter_config)"); LogError("Each component requiring the Mqtt adapter needs to specify local adapter args (pnp_bridge_adapter_config)");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
const char* mqtt_server = json_object_get_string(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_MQTT_SERVER); const char* mqtt_server = json_object_get_string(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_MQTT_SERVER);
int mqtt_port = (int) json_object_get_number(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_MQTT_PORT); int mqtt_port = (int) json_object_get_number(AdapterInterfaceConfig, PNP_CONFIG_ADAPTER_MQTT_PORT);
@ -100,7 +100,7 @@ MqttPnp_CreatePnpInterface(
MqttPnpAdapter* adapterContext = reinterpret_cast<MqttPnpAdapter*>(PnpAdapterHandleGetContext(AdapterHandle)); MqttPnpAdapter* adapterContext = reinterpret_cast<MqttPnpAdapter*>(PnpAdapterHandleGetContext(AdapterHandle));
if (adapterContext == NULL) if (adapterContext == NULL)
{ {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
MqttPnpInstance* context = new MqttPnpInstance(); MqttPnpInstance* context = new MqttPnpInstance();
@ -139,10 +139,10 @@ MqttPnp_CreatePnpInterface(
nullptr, nullptr,
context, context,
&pnpInterfaceClient); &pnpInterfaceClient);
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("mqtt-pnp: Error registering pnp interface component %s", ComponentName); LogError("mqtt-pnp: Error registering pnp interface component %s", ComponentName);
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -157,10 +157,10 @@ MqttPnp_CreatePnpInterface(
(void*)context (void*)context
); );
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("mqtt-pnp: Error binding property update callback for %s", ComponentName); LogError("mqtt-pnp: Error binding property update callback for %s", ComponentName);
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -176,10 +176,10 @@ MqttPnp_CreatePnpInterface(
(void*)context (void*)context
); );
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("mqtt-pnp: Error binding commands callback for %s", ComponentName); LogError("mqtt-pnp: Error binding commands callback for %s", ComponentName);
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -188,7 +188,7 @@ MqttPnp_CreatePnpInterface(
PnpInterfaceHandleSetContext(BridgeInterfaceHandle, context); PnpInterfaceHandleSetContext(BridgeInterfaceHandle, context);
exit: exit:
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
MqttPnp_DestroyPnpInterface(BridgeInterfaceHandle); MqttPnp_DestroyPnpInterface(BridgeInterfaceHandle);
} }
@ -200,16 +200,16 @@ exit:
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT MqttPnp_CreatePnpAdapter( IOTHUB_CLIENT_RESULT MqttPnp_CreatePnpAdapter(
const JSON_Object* AdapterGlobalConfig, const JSON_Object* AdapterGlobalConfig,
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle) PNPBRIDGE_ADAPTER_HANDLE AdapterHandle)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
MqttPnpAdapter* adapterContext = new MqttPnpAdapter(); MqttPnpAdapter* adapterContext = new MqttPnpAdapter();
if (AdapterGlobalConfig == NULL) if (AdapterGlobalConfig == NULL)
{ {
LogError("Mqtt adapter requires associated global parameters in config"); LogError("Mqtt adapter requires associated global parameters in config");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -223,28 +223,28 @@ DIGITALTWIN_CLIENT_RESULT MqttPnp_CreatePnpAdapter(
PnpAdapterHandleSetContext(AdapterHandle, (void*)adapterContext); PnpAdapterHandleSetContext(AdapterHandle, (void*)adapterContext);
exit: exit:
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
result = MqttPnp_DestroyPnpAdapter(AdapterHandle); result = MqttPnp_DestroyPnpAdapter(AdapterHandle);
} }
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT IOTHUB_CLIENT_RESULT
MqttPnp_StartPnpInterface( MqttPnp_StartPnpInterface(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
AZURE_UNREFERENCED_PARAMETER(AdapterHandle); AZURE_UNREFERENCED_PARAMETER(AdapterHandle);
AZURE_UNREFERENCED_PARAMETER(PnpInterfaceHandle); AZURE_UNREFERENCED_PARAMETER(PnpInterfaceHandle);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT MqttPnp_StopPnpInterface( IOTHUB_CLIENT_RESULT MqttPnp_StopPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
AZURE_UNREFERENCED_PARAMETER(PnpInterfaceHandle); AZURE_UNREFERENCED_PARAMETER(PnpInterfaceHandle);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
PNP_ADAPTER MqttPnpInterface = { PNP_ADAPTER MqttPnpInterface = {

Просмотреть файл

@ -57,10 +57,10 @@ int SerialPnp_UartReceiver(
} }
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT SerialPnp_TxPacket( IOTHUB_CLIENT_RESULT SerialPnp_TxPacket(
PSERIAL_DEVICE_CONTEXT serialDevice, PSERIAL_DEVICE_CONTEXT serialDevice,
byte* OutPacket, byte* OutPacket,
int Length) int Length)
@ -83,7 +83,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_TxPacket(
if (!SerialPnp_TxPacket) if (!SerialPnp_TxPacket)
{ {
LogError("Error out of memory"); LogError("Error out of memory");
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
txLength = 1; txLength = 1;
SerialPnp_TxPacket[0] = 0x5A; // Start of frame SerialPnp_TxPacket[0] = 0x5A; // Start of frame
@ -110,7 +110,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_TxPacket(
{ {
// Write returned actual error and not just pending // Write returned actual error and not just pending
LogError("write failed: %d", error); LogError("write failed: %d", error);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
else else
{ {
@ -118,7 +118,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_TxPacket(
{ {
error = GetLastError(); error = GetLastError();
LogError("write failed: %d", error); LogError("write failed: %d", error);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
} }
} }
@ -133,10 +133,10 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_TxPacket(
if (write_size != txLength) if (write_size != txLength)
{ {
LogError("Timeout while writing"); LogError("Timeout while writing");
return DIGITALTWIN_CLIENT_ERROR_TIMEOUT; return IOTHUB_CLIENT_INDEFINITE_TIME;
} }
free(SerialPnp_TxPacket); free(SerialPnp_TxPacket);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
const EventDefinition* SerialPnp_LookupEvent( const EventDefinition* SerialPnp_LookupEvent(
@ -405,7 +405,7 @@ const CommandDefinition* SerialPnp_LookupCommand(
return NULL; return NULL;
} }
DIGITALTWIN_CLIENT_RESULT SerialPnp_PropertyHandler( IOTHUB_CLIENT_RESULT SerialPnp_PropertyHandler(
PSERIAL_DEVICE_CONTEXT serialDevice, PSERIAL_DEVICE_CONTEXT serialDevice,
const char* property, const char* property,
char* data) char* data)
@ -415,7 +415,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_PropertyHandler(
if (NULL == prop) if (NULL == prop)
{ {
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
// Otherwise serialize data // Otherwise serialize data
@ -423,7 +423,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_PropertyHandler(
byte* inputPayload = SerialPnp_StringSchemaToBinary(prop->DataSchema, input, &dataLength); byte* inputPayload = SerialPnp_StringSchemaToBinary(prop->DataSchema, input, &dataLength);
if (!inputPayload) if (!inputPayload)
{ {
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
int nameLength = (int)strlen(property); int nameLength = (int)strlen(property);
@ -433,7 +433,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_PropertyHandler(
{ {
LogError("Error out of memory"); LogError("Error out of memory");
free(inputPayload); free(inputPayload);
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
txPacket[SERIALPNP_PACKET_PACKET_LENGTH_OFFSET] = (byte)(txlength & 0xFF); txPacket[SERIALPNP_PACKET_PACKET_LENGTH_OFFSET] = (byte)(txlength & 0xFF);
@ -453,10 +453,10 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_PropertyHandler(
free(inputPayload); free(inputPayload);
free(txPacket); free(txPacket);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT SerialPnp_CommandHandler( IOTHUB_CLIENT_RESULT SerialPnp_CommandHandler(
PSERIAL_DEVICE_CONTEXT serialDevice, PSERIAL_DEVICE_CONTEXT serialDevice,
const char* command, const char* command,
char* data, char* data,
@ -470,7 +470,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_CommandHandler(
if (NULL == cmd) if (NULL == cmd)
{ {
Unlock(serialDevice->CommandLock); Unlock(serialDevice->CommandLock);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
// Otherwise serialize data // Otherwise serialize data
@ -479,7 +479,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_CommandHandler(
if (!inputPayload) if (!inputPayload)
{ {
Unlock(serialDevice->CommandLock); Unlock(serialDevice->CommandLock);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
int nameLength = (int)strlen(command); int nameLength = (int)strlen(command);
@ -490,7 +490,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_CommandHandler(
LogError("Error out of memory"); LogError("Error out of memory");
free(inputPayload); free(inputPayload);
Unlock(serialDevice->CommandLock); Unlock(serialDevice->CommandLock);
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
txPacket[SERIALPNP_PACKET_PACKET_LENGTH_OFFSET] = (byte)(txlength & 0xFF); txPacket[SERIALPNP_PACKET_PACKET_LENGTH_OFFSET] = (byte)(txlength & 0xFF);
@ -505,13 +505,13 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_CommandHandler(
LogInfo("Invoking command %s to %s", command, input); LogInfo("Invoking command %s to %s", command, input);
if (DIGITALTWIN_CLIENT_OK != SerialPnp_TxPacket(serialDevice, txPacket, txlength)) if (IOTHUB_CLIENT_OK != SerialPnp_TxPacket(serialDevice, txPacket, txlength))
{ {
LogError("Error: command not sent to device."); LogError("Error: command not sent to device.");
free(inputPayload); free(inputPayload);
free(txPacket); free(txPacket);
Unlock(serialDevice->CommandLock); Unlock(serialDevice->CommandLock);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
Lock(serialDevice->CommandResponseWaitLock); Lock(serialDevice->CommandResponseWaitLock);
@ -522,7 +522,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_CommandHandler(
free(txPacket); free(txPacket);
Unlock(serialDevice->CommandLock); Unlock(serialDevice->CommandLock);
Unlock(serialDevice->CommandResponseWaitLock); Unlock(serialDevice->CommandResponseWaitLock);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
Unlock(serialDevice->CommandResponseWaitLock); Unlock(serialDevice->CommandResponseWaitLock);
@ -537,12 +537,12 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_CommandHandler(
if (!stval) if (!stval)
{ {
Unlock(serialDevice->CommandLock); Unlock(serialDevice->CommandLock);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
*response = stval; *response = stval;
Unlock(serialDevice->CommandLock); Unlock(serialDevice->CommandLock);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
void SerialPnp_ParseDescriptor( void SerialPnp_ParseDescriptor(
@ -787,7 +787,7 @@ SINGLYLINKEDLIST_HANDLE SerialDeviceList = NULL;
int SerialDeviceCount = 0; int SerialDeviceCount = 0;
#ifdef WIN32 #ifdef WIN32
DIGITALTWIN_CLIENT_RESULT SerialPnp_FindSerialDevices() IOTHUB_CLIENT_RESULT SerialPnp_FindSerialDevices()
{ {
CONFIGRET cmResult = CR_SUCCESS; CONFIGRET cmResult = CR_SUCCESS;
char* deviceInterfaceList; char* deviceInterfaceList;
@ -802,14 +802,14 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_FindSerialDevices()
CM_GET_DEVICE_INTERFACE_LIST_PRESENT); CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
if (CR_SUCCESS != cmResult) if (CR_SUCCESS != cmResult)
{ {
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
deviceInterfaceList = malloc(bufferSize * sizeof(char)); deviceInterfaceList = malloc(bufferSize * sizeof(char));
if (!deviceInterfaceList) if (!deviceInterfaceList)
{ {
LogError("Error out of memory"); LogError("Error out of memory");
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
cmResult = CM_Get_Device_Interface_ListA( cmResult = CM_Get_Device_Interface_ListA(
@ -820,7 +820,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_FindSerialDevices()
CM_GET_DEVICE_INTERFACE_LIST_PRESENT); CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
if (CR_SUCCESS != cmResult) if (CR_SUCCESS != cmResult)
{ {
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
for (PCHAR currentDeviceInterface = deviceInterfaceList; for (PCHAR currentDeviceInterface = deviceInterfaceList;
@ -832,7 +832,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_FindSerialDevices()
{ {
LogError("Error out of memory"); LogError("Error out of memory");
free(deviceInterfaceList); free(deviceInterfaceList);
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
serialDevs->InterfaceName = malloc((strlen(currentDeviceInterface) + 1) * sizeof(char)); serialDevs->InterfaceName = malloc((strlen(currentDeviceInterface) + 1) * sizeof(char));
if (!serialDevs->InterfaceName) if (!serialDevs->InterfaceName)
@ -840,14 +840,14 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_FindSerialDevices()
LogError("Error out of memory"); LogError("Error out of memory");
free(deviceInterfaceList); free(deviceInterfaceList);
free(serialDevs); free(serialDevs);
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
strcpy_s(serialDevs->InterfaceName, strlen(currentDeviceInterface) + 1, currentDeviceInterface); strcpy_s(serialDevs->InterfaceName, strlen(currentDeviceInterface) + 1, currentDeviceInterface);
singlylinkedlist_add(SerialDeviceList, serialDevs); singlylinkedlist_add(SerialDeviceList, serialDevs);
SerialDeviceCount++; SerialDeviceCount++;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
#endif #endif
@ -858,30 +858,30 @@ int SerialPnp_ParseInterfaceConfig(
DWORD length; DWORD length;
PSERIAL_DEVICE_CONTEXT deviceContext = context; PSERIAL_DEVICE_CONTEXT deviceContext = context;
int retries = SERIALPNP_RESET_OR_DESCRIPTOR_MAX_RETRIES; int retries = SERIALPNP_RESET_OR_DESCRIPTOR_MAX_RETRIES;
while (DIGITALTWIN_CLIENT_OK != SerialPnp_ResetDevice(deviceContext)) while (IOTHUB_CLIENT_OK != SerialPnp_ResetDevice(deviceContext))
{ {
LogError("Error sending reset request. Retrying..."); LogError("Error sending reset request. Retrying...");
if (0 == --retries) if (0 == --retries)
{ {
LogError("Error exceeded max number of reset request retries. "); LogError("Error exceeded max number of reset request retries. ");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
ThreadAPI_Sleep(5000); ThreadAPI_Sleep(5000);
} }
retries = SERIALPNP_RESET_OR_DESCRIPTOR_MAX_RETRIES; retries = SERIALPNP_RESET_OR_DESCRIPTOR_MAX_RETRIES;
while (DIGITALTWIN_CLIENT_OK != SerialPnp_DeviceDescriptorRequest(deviceContext, &desc, &length)) while (IOTHUB_CLIENT_OK != SerialPnp_DeviceDescriptorRequest(deviceContext, &desc, &length))
{ {
LogError("Descriptor response not received. Retrying..."); LogError("Descriptor response not received. Retrying...");
if (0 == --retries) if (0 == --retries)
{ {
LogError("Error exceeded max number of descriptor request retries. "); LogError("Error exceeded max number of descriptor request retries. ");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
ThreadAPI_Sleep(5000); ThreadAPI_Sleep(5000);
} }
SerialPnp_ParseDescriptor(deviceContext->InterfaceDefinitions, desc, length); SerialPnp_ParseDescriptor(deviceContext->InterfaceDefinitions, desc, length);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
#ifndef WIN32 #ifndef WIN32
@ -925,7 +925,7 @@ int set_interface_attribs(
LogError("error %d from tcsetattr", errno); LogError("error %d from tcsetattr", errno);
return -1; return -1;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
void void
@ -949,12 +949,12 @@ set_blocking(
} }
#endif #endif
DIGITALTWIN_CLIENT_RESULT SerialPnp_OpenDevice( IOTHUB_CLIENT_RESULT SerialPnp_OpenDevice(
const char* port, const char* port,
DWORD baudRate, DWORD baudRate,
PSERIAL_DEVICE_CONTEXT deviceContext) PSERIAL_DEVICE_CONTEXT deviceContext)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
#ifdef WIN32 #ifdef WIN32
HANDLE hSerial = CreateFileA(port, HANDLE hSerial = CreateFileA(port,
GENERIC_READ | GENERIC_WRITE, GENERIC_READ | GENERIC_WRITE,
@ -971,10 +971,10 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_OpenDevice(
LogError("Failed to open com port %s, %x", port, error); LogError("Failed to open com port %s, %x", port, error);
if (error == ERROR_FILE_NOT_FOUND) if (error == ERROR_FILE_NOT_FOUND)
{ {
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -1032,7 +1032,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_OpenDevice(
{ {
CloseHandle(deviceContext->osReader.hEvent); CloseHandle(deviceContext->osReader.hEvent);
} }
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
#else #else
@ -1043,7 +1043,7 @@ exit:
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT SerialPnp_RxPacket( IOTHUB_CLIENT_RESULT SerialPnp_RxPacket(
PSERIAL_DEVICE_CONTEXT serialDevice, PSERIAL_DEVICE_CONTEXT serialDevice,
byte** receivedPacket, byte** receivedPacket,
DWORD* length, DWORD* length,
@ -1064,7 +1064,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_RxPacket(
{ {
// Read returned actual error and not just pending // Read returned actual error and not just pending
LogError("read failed: %d", error); LogError("read failed: %d", error);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
else else
{ {
@ -1072,7 +1072,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_RxPacket(
{ {
error = GetLastError(); error = GetLastError();
LogError("read failed: %d", error); LogError("read failed: %d", error);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
} }
@ -1115,7 +1115,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_RxPacket(
if (serialDevice->RxBufferIndex >= MAX_BUFFER_SIZE) if (serialDevice->RxBufferIndex >= MAX_BUFFER_SIZE)
{ {
LogError("Filled Rx buffer. Protocol is bad."); LogError("Filled Rx buffer. Protocol is bad.");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
// Minimum packet length is 4, so once we are >= 4 begin checking // Minimum packet length is 4, so once we are >= 4 begin checking
@ -1130,7 +1130,7 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_RxPacket(
if (NULL == *receivedPacket) if (NULL == *receivedPacket)
{ {
LogError("Error out of memory"); LogError("Error out of memory");
return DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; return IOTHUB_CLIENT_ERROR;
} }
*length = serialDevice->RxBufferIndex; *length = serialDevice->RxBufferIndex;
memcpy(*receivedPacket, serialDevice->RxBuffer, serialDevice->RxBufferIndex); memcpy(*receivedPacket, serialDevice->RxBuffer, serialDevice->RxBufferIndex);
@ -1153,13 +1153,13 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_RxPacket(
} }
} }
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT SerialPnp_ResetDevice( IOTHUB_CLIENT_RESULT SerialPnp_ResetDevice(
PSERIAL_DEVICE_CONTEXT serialDevice) PSERIAL_DEVICE_CONTEXT serialDevice)
{ {
DIGITALTWIN_CLIENT_RESULT error = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT error = IOTHUB_CLIENT_OK;
// Prepare packet // Prepare packet
byte resetPacket[3] = { 0 }; // packet header byte resetPacket[3] = { 0 }; // packet header
byte* responsePacket = NULL; byte* responsePacket = NULL;
@ -1168,36 +1168,36 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_ResetDevice(
resetPacket[SERIALPNP_PACKET_PACKET_TYPE_OFFSET] = SERIALPNP_PACKET_TYPE_RESET_REQUEST; resetPacket[SERIALPNP_PACKET_PACKET_TYPE_OFFSET] = SERIALPNP_PACKET_TYPE_RESET_REQUEST;
// Send the new packet // Send the new packet
if (DIGITALTWIN_CLIENT_OK != SerialPnp_TxPacket(serialDevice, resetPacket, 4)) if (IOTHUB_CLIENT_OK != SerialPnp_TxPacket(serialDevice, resetPacket, 4))
{ {
LogError("Error sending request packet"); LogError("Error sending request packet");
error = DIGITALTWIN_CLIENT_ERROR; error = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
LogInfo("Sent reset request"); LogInfo("Sent reset request");
DWORD length; DWORD length;
if (DIGITALTWIN_CLIENT_OK != SerialPnp_RxPacket(serialDevice, &responsePacket, &length, 0x02)) if (IOTHUB_CLIENT_OK != SerialPnp_RxPacket(serialDevice, &responsePacket, &length, 0x02))
{ {
LogError("Error receiving response packet"); LogError("Error receiving response packet");
error = DIGITALTWIN_CLIENT_ERROR; error = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
if (NULL == responsePacket) if (NULL == responsePacket)
{ {
LogError("received NULL for response packet"); LogError("received NULL for response packet");
error = DIGITALTWIN_CLIENT_ERROR; error = IOTHUB_CLIENT_ERROR;
} }
if (SERIALPNP_PACKET_TYPE_RESET_RESPONSE != responsePacket[2]) if (SERIALPNP_PACKET_TYPE_RESET_RESPONSE != responsePacket[2])
{ {
LogError("Bad reset response"); LogError("Bad reset response");
error = DIGITALTWIN_CLIENT_ERROR; error = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
if (DIGITALTWIN_CLIENT_OK == error) if (IOTHUB_CLIENT_OK == error)
{ {
LogInfo("Receieved reset response"); LogInfo("Receieved reset response");
} }
@ -1210,7 +1210,7 @@ exit:
return error; return error;
} }
DIGITALTWIN_CLIENT_RESULT SerialPnp_DeviceDescriptorRequest( IOTHUB_CLIENT_RESULT SerialPnp_DeviceDescriptorRequest(
PSERIAL_DEVICE_CONTEXT serialDevice, PSERIAL_DEVICE_CONTEXT serialDevice,
byte** desc, byte** desc,
DWORD* length) DWORD* length)
@ -1222,18 +1222,18 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_DeviceDescriptorRequest(
txPacket[SERIALPNP_PACKET_PACKET_TYPE_OFFSET] = SERIALPNP_PACKET_TYPE_DESCRIPTOR_REQUEST; txPacket[SERIALPNP_PACKET_PACKET_TYPE_OFFSET] = SERIALPNP_PACKET_TYPE_DESCRIPTOR_REQUEST;
// Send the new packets // Send the new packets
if (DIGITALTWIN_CLIENT_OK != SerialPnp_TxPacket(serialDevice, txPacket, 4)) if (IOTHUB_CLIENT_OK != SerialPnp_TxPacket(serialDevice, txPacket, 4))
{ {
LogError("Error sending request packet"); LogError("Error sending request packet");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
LogInfo("Sent descriptor request"); LogInfo("Sent descriptor request");
if (DIGITALTWIN_CLIENT_OK != SerialPnp_RxPacket(serialDevice, desc, length, 0x04)) if (IOTHUB_CLIENT_OK != SerialPnp_RxPacket(serialDevice, desc, length, 0x04))
{ {
LogError("Error receiving response packet"); LogError("Error receiving response packet");
free(*desc); free(*desc);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
if (NULL == *desc) if (NULL == *desc)
@ -1241,43 +1241,43 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_DeviceDescriptorRequest(
LogError("received NULL for response packet"); LogError("received NULL for response packet");
free(*desc); free(*desc);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
if (SERIALPNP_PACKET_TYPE_DESCRIPTOR_RESPONSE != (*desc)[2]) if (SERIALPNP_PACKET_TYPE_DESCRIPTOR_RESPONSE != (*desc)[2])
{ {
LogError("Bad descriptor response"); LogError("Bad descriptor response");
free(*desc); free(*desc);
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
LogInfo("Receieved descriptor response, of length %d", *length); LogInfo("Receieved descriptor response, of length %d", *length);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
void SerialPnp_SendEventCallback( void SerialPnp_SendEventCallback(
DIGITALTWIN_CLIENT_RESULT pnpSendEventStatus, IOTHUB_CLIENT_RESULT pnpSendEventStatus,
void* userContextCallback) void* userContextCallback)
{ {
LogInfo("SerialDataSendEventCallback called, result=%d, userContextCallback=%p", pnpSendEventStatus, userContextCallback); LogInfo("SerialDataSendEventCallback called, result=%d, userContextCallback=%p", pnpSendEventStatus, userContextCallback);
} }
DIGITALTWIN_CLIENT_RESULT SerialPnp_SendEventAsync( IOTHUB_CLIENT_RESULT SerialPnp_SendEventAsync(
DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterface, DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterface,
char* eventName, char* eventName,
char* data) char* data)
{ {
DIGITALTWIN_CLIENT_RESULT pnpClientResult; IOTHUB_CLIENT_RESULT pnpClientResult;
if (pnpInterface == NULL) if (pnpInterface == NULL)
{ {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
char telemetryMessageData[512] = { 0 }; char telemetryMessageData[512] = { 0 };
sprintf(telemetryMessageData, "{\"%s\":%s}", eventName, data); sprintf(telemetryMessageData, "{\"%s\":%s}", eventName, data);
if ((pnpClientResult = DigitalTwin_InterfaceClient_SendTelemetryAsync(pnpInterface, (unsigned char*)telemetryMessageData, strlen(telemetryMessageData), SerialPnp_SendEventCallback, (void*)eventName)) != DIGITALTWIN_CLIENT_OK) if ((pnpClientResult = DigitalTwin_InterfaceClient_SendTelemetryAsync(pnpInterface, (unsigned char*)telemetryMessageData, strlen(telemetryMessageData), SerialPnp_SendEventCallback, (void*)eventName)) != IOTHUB_CLIENT_OK)
{ {
LogError("PnP_InterfaceClient_SendEventAsync failed, result=%d\n", pnpClientResult); LogError("PnP_InterfaceClient_SendEventAsync failed, result=%d\n", pnpClientResult);
} }
@ -1307,7 +1307,7 @@ static void SerialPnp_PropertyUpdateHandler(
const DIGITALTWIN_CLIENT_PROPERTY_UPDATE* dtClientPropertyUpdate, const DIGITALTWIN_CLIENT_PROPERTY_UPDATE* dtClientPropertyUpdate,
void* userContextCallback) void* userContextCallback)
{ {
DIGITALTWIN_CLIENT_RESULT pnpClientResult; IOTHUB_CLIENT_RESULT pnpClientResult;
DIGITALTWIN_CLIENT_PROPERTY_RESPONSE propertyResponse; DIGITALTWIN_CLIENT_PROPERTY_RESPONSE propertyResponse;
PSERIAL_DEVICE_CONTEXT deviceContext = (PSERIAL_DEVICE_CONTEXT)userContextCallback; PSERIAL_DEVICE_CONTEXT deviceContext = (PSERIAL_DEVICE_CONTEXT)userContextCallback;
int propertyCount = 0; int propertyCount = 0;
@ -1385,7 +1385,7 @@ SerialPnp_CommandUpdateHandler(
} }
DIGITALTWIN_CLIENT_RESULT IOTHUB_CLIENT_RESULT
SerialPnp_StartPnpInterface( SerialPnp_StartPnpInterface(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
@ -1395,15 +1395,15 @@ SerialPnp_StartPnpInterface(
if (deviceContext == NULL) if (deviceContext == NULL)
{ {
LogError("Device context is null"); LogError("Device context is null");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
// Start telemetry thread // Start telemetry thread
if (ThreadAPI_Create(&deviceContext->TelemetryWorkerHandle, SerialPnp_UartReceiver, deviceContext) != THREADAPI_OK) { if (ThreadAPI_Create(&deviceContext->TelemetryWorkerHandle, SerialPnp_UartReceiver, deviceContext) != THREADAPI_OK) {
LogError("ThreadAPI_Create failed"); LogError("ThreadAPI_Create failed");
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
@ -1488,14 +1488,14 @@ void SerialPnp_FreePropertiesDefinition(
} }
} }
DIGITALTWIN_CLIENT_RESULT SerialPnp_StopPnpInterface( IOTHUB_CLIENT_RESULT SerialPnp_StopPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
PSERIAL_DEVICE_CONTEXT deviceContext = PnpInterfaceHandleGetContext(PnpInterfaceHandle); PSERIAL_DEVICE_CONTEXT deviceContext = PnpInterfaceHandleGetContext(PnpInterfaceHandle);
if (NULL == deviceContext) if (NULL == deviceContext)
{ {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
#ifdef WIN32 #ifdef WIN32
@ -1518,16 +1518,16 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_StopPnpInterface(
} }
#endif #endif
ThreadAPI_Join(deviceContext->TelemetryWorkerHandle, NULL); ThreadAPI_Join(deviceContext->TelemetryWorkerHandle, NULL);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT SerialPnp_DestroyPnpInterface( IOTHUB_CLIENT_RESULT SerialPnp_DestroyPnpInterface(
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle) PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle)
{ {
PSERIAL_DEVICE_CONTEXT deviceContext = PnpInterfaceHandleGetContext(PnpInterfaceHandle); PSERIAL_DEVICE_CONTEXT deviceContext = PnpInterfaceHandleGetContext(PnpInterfaceHandle);
if (NULL == deviceContext) { if (NULL == deviceContext) {
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
// Call DigitalTwin_InterfaceClient_Destroy. // Call DigitalTwin_InterfaceClient_Destroy.
@ -1558,10 +1558,10 @@ DIGITALTWIN_CLIENT_RESULT SerialPnp_DestroyPnpInterface(
free(deviceContext); free(deviceContext);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT IOTHUB_CLIENT_RESULT
SerialPnp_CreatePnpInterface( SerialPnp_CreatePnpInterface(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
const char* ComponentName, const char* ComponentName,
@ -1570,7 +1570,7 @@ SerialPnp_CreatePnpInterface(
DIGITALTWIN_INTERFACE_CLIENT_HANDLE* PnpInterfaceClient) DIGITALTWIN_INTERFACE_CLIENT_HANDLE* PnpInterfaceClient)
{ {
AZURE_UNREFERENCED_PARAMETER(AdapterHandle); AZURE_UNREFERENCED_PARAMETER(AdapterHandle);
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
// Get device connection information // Get device connection information
@ -1591,7 +1591,7 @@ SerialPnp_CreatePnpInterface(
if (NULL == port) if (NULL == port)
{ {
LogError("COM port parameter is missing in configuration"); LogError("COM port parameter is missing in configuration");
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
} }
@ -1600,7 +1600,7 @@ SerialPnp_CreatePnpInterface(
if (NULL == baudRateParam) if (NULL == baudRateParam)
{ {
LogError("Baud rate parameter is missing in configuration"); LogError("Baud rate parameter is missing in configuration");
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -1609,11 +1609,11 @@ SerialPnp_CreatePnpInterface(
if (useComDeviceInterface) if (useComDeviceInterface)
{ {
#ifdef WIN32 #ifdef WIN32
if (SerialPnp_FindSerialDevices() != DIGITALTWIN_CLIENT_OK) if (SerialPnp_FindSerialDevices() != IOTHUB_CLIENT_OK)
#endif #endif
{ {
LogError("Failed to get com port %s", port); LogError("Failed to get com port %s", port);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -1621,7 +1621,7 @@ SerialPnp_CreatePnpInterface(
if (NULL == item) if (NULL == item)
{ {
LogError("No serial device was found %s", port); LogError("No serial device was found %s", port);
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -1635,7 +1635,7 @@ SerialPnp_CreatePnpInterface(
if (!deviceContext) if (!deviceContext)
{ {
LogError("Error out of memory"); LogError("Error out of memory");
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
memset(deviceContext, 0, sizeof(SERIAL_DEVICE_CONTEXT)); memset(deviceContext, 0, sizeof(SERIAL_DEVICE_CONTEXT));
@ -1661,7 +1661,7 @@ SerialPnp_CreatePnpInterface(
{ {
Lock_Deinit(deviceContext->CommandResponseWaitCondition); Lock_Deinit(deviceContext->CommandResponseWaitCondition);
} }
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
deviceContext->PnpInterfaceHandle = NULL; deviceContext->PnpInterfaceHandle = NULL;
@ -1680,10 +1680,10 @@ SerialPnp_CreatePnpInterface(
DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterfaceClient = NULL; DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterfaceClient = NULL;
result = DigitalTwin_InterfaceClient_Create(ComponentName, NULL, deviceContext, &pnpInterfaceClient); result = DigitalTwin_InterfaceClient_Create(ComponentName, NULL, deviceContext, &pnpInterfaceClient);
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("SerialPnp_CreatePnpInterface: DigitalTwin_InterfaceClient_Create failed."); LogError("SerialPnp_CreatePnpInterface: DigitalTwin_InterfaceClient_Create failed.");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -1691,10 +1691,10 @@ SerialPnp_CreatePnpInterface(
result = DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback(pnpInterfaceClient, result = DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback(pnpInterfaceClient,
SerialPnp_PropertyUpdateHandler, SerialPnp_PropertyUpdateHandler,
(void*) deviceContext); (void*) deviceContext);
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("SerialPnp_CreatePnpInterface: DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback failed."); LogError("SerialPnp_CreatePnpInterface: DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback failed.");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
} }
@ -1703,10 +1703,10 @@ SerialPnp_CreatePnpInterface(
result = DigitalTwin_InterfaceClient_SetCommandsCallback(pnpInterfaceClient, result = DigitalTwin_InterfaceClient_SetCommandsCallback(pnpInterfaceClient,
SerialPnp_CommandUpdateHandler, SerialPnp_CommandUpdateHandler,
(void*)deviceContext); (void*)deviceContext);
if (DIGITALTWIN_CLIENT_OK != result) if (IOTHUB_CLIENT_OK != result)
{ {
LogError("SerialPnp_CreatePnpInterface: DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback failed."); LogError("SerialPnp_CreatePnpInterface: DigitalTwin_InterfaceClient_SetPropertiesUpdatedCallback failed.");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
} }
@ -1717,7 +1717,7 @@ SerialPnp_CreatePnpInterface(
PnpInterfaceHandleSetContext(BridgeInterfaceHandle, deviceContext); PnpInterfaceHandleSetContext(BridgeInterfaceHandle, deviceContext);
exit: exit:
if (result != DIGITALTWIN_CLIENT_OK) if (result != IOTHUB_CLIENT_OK)
{ {
SerialPnp_DestroyPnpInterface(BridgeInterfaceHandle); SerialPnp_DestroyPnpInterface(BridgeInterfaceHandle);
} }
@ -1725,20 +1725,20 @@ exit:
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT SerialPnp_CreatePnpAdapter( IOTHUB_CLIENT_RESULT SerialPnp_CreatePnpAdapter(
const JSON_Object* AdapterGlobalConfig, const JSON_Object* AdapterGlobalConfig,
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle) PNPBRIDGE_ADAPTER_HANDLE AdapterHandle)
{ {
AZURE_UNREFERENCED_PARAMETER(AdapterGlobalConfig); AZURE_UNREFERENCED_PARAMETER(AdapterGlobalConfig);
AZURE_UNREFERENCED_PARAMETER(AdapterHandle); AZURE_UNREFERENCED_PARAMETER(AdapterHandle);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT SerialPnp_DestroyPnpAdapter( IOTHUB_CLIENT_RESULT SerialPnp_DestroyPnpAdapter(
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle) PNPBRIDGE_ADAPTER_HANDLE AdapterHandle)
{ {
AZURE_UNREFERENCED_PARAMETER(AdapterHandle); AZURE_UNREFERENCED_PARAMETER(AdapterHandle);
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
PNP_ADAPTER SerialPnpInterface = { PNP_ADAPTER SerialPnpInterface = {

Просмотреть файл

@ -128,19 +128,19 @@ extern "C"
SINGLYLINKEDLIST_HANDLE InterfaceDefinitions; SINGLYLINKEDLIST_HANDLE InterfaceDefinitions;
} SERIAL_DEVICE_CONTEXT, *PSERIAL_DEVICE_CONTEXT; } SERIAL_DEVICE_CONTEXT, *PSERIAL_DEVICE_CONTEXT;
DIGITALTWIN_CLIENT_RESULT SerialPnp_RxPacket(PSERIAL_DEVICE_CONTEXT serialDevice, byte** receivedPacket, DWORD* length, char packetType); IOTHUB_CLIENT_RESULT SerialPnp_RxPacket(PSERIAL_DEVICE_CONTEXT serialDevice, byte** receivedPacket, DWORD* length, char packetType);
DIGITALTWIN_CLIENT_RESULT SerialPnp_TxPacket(PSERIAL_DEVICE_CONTEXT serialDevice, byte* OutPacket, int Length); IOTHUB_CLIENT_RESULT SerialPnp_TxPacket(PSERIAL_DEVICE_CONTEXT serialDevice, byte* OutPacket, int Length);
void SerialPnp_UnsolicitedPacket(PSERIAL_DEVICE_CONTEXT device, byte* packet, DWORD length); void SerialPnp_UnsolicitedPacket(PSERIAL_DEVICE_CONTEXT device, byte* packet, DWORD length);
DIGITALTWIN_CLIENT_RESULT SerialPnp_ResetDevice(PSERIAL_DEVICE_CONTEXT serialDevice); IOTHUB_CLIENT_RESULT SerialPnp_ResetDevice(PSERIAL_DEVICE_CONTEXT serialDevice);
DIGITALTWIN_CLIENT_RESULT SerialPnp_DeviceDescriptorRequest(PSERIAL_DEVICE_CONTEXT serialDevice, byte** desc, DWORD* length); IOTHUB_CLIENT_RESULT SerialPnp_DeviceDescriptorRequest(PSERIAL_DEVICE_CONTEXT serialDevice, byte** desc, DWORD* length);
byte* SerialPnp_StringSchemaToBinary(Schema Schema, byte* data, int* length); byte* SerialPnp_StringSchemaToBinary(Schema Schema, byte* data, int* length);
DIGITALTWIN_CLIENT_RESULT SerialPnp_SendEventAsync(DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterface, char* eventName, char* data); IOTHUB_CLIENT_RESULT SerialPnp_SendEventAsync(DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterface, char* eventName, char* data);
// Serial Pnp Adapter Config // Serial Pnp Adapter Config
#define PNP_CONFIG_ADAPTER_SERIALPNP_COMPORT "com_port" #define PNP_CONFIG_ADAPTER_SERIALPNP_COMPORT "com_port"

Просмотреть файл

@ -60,6 +60,7 @@ include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/deps/umock-c/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/digitaltwin_client/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/digitaltwin_client/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/provisioning_client/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/provisioning_client/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/samples/pnp/common)
include_directories(${pnp_bridge_INC_FOLDER}) include_directories(${pnp_bridge_INC_FOLDER})
if(WIN32) if(WIN32)

Просмотреть файл

@ -97,18 +97,18 @@ typedef struct PNPBRIDGE_CONFIGURATION {
* *
* @param Config JSON_Value representing the root of the config file * @param Config JSON_Value representing the root of the config file
* *
* @returns DIGITALTWIN_CLIENT_OK on success and other DIGITALTWIN_CLIENT_RESULT values on failure. * @returns IOTHUB_CLIENT_OK on success and other IOTHUB_CLIENT_RESULT values on failure.
*/ */
DIGITALTWIN_CLIENT_RESULT PnpBridgeConfig_GetJsonValueFromConfigFile(const char* Filename, JSON_Value** Config); IOTHUB_CLIENT_RESULT PnpBridgeConfig_GetJsonValueFromConfigFile(const char* Filename, JSON_Value** Config);
/** /**
* @brief PnpBridgeConfig_GetJsonValueFromString reads a PnpBridge JSON config from string. * @brief PnpBridgeConfig_GetJsonValueFromString reads a PnpBridge JSON config from string.
* *
* @param ConfigString String containing JSON config * @param ConfigString String containing JSON config
* *
* @returns DIGITALTWIN_CLIENT_OK on success and other DIGITALTWIN_CLIENT_RESULT values on failure. * @returns IOTHUB_CLIENT_OK on success and other IOTHUB_CLIENT_RESULT values on failure.
*/ */
DIGITALTWIN_CLIENT_RESULT PnpBridgeConfig_GetJsonValueFromString(const char *ConfigString, JSON_Value** Config); IOTHUB_CLIENT_RESULT PnpBridgeConfig_GetJsonValueFromString(const char *ConfigString, JSON_Value** Config);
/** /**
* @brief PnpBridgeConfig_GetConnectionDetails parses the connection parameters from * @brief PnpBridgeConfig_GetConnectionDetails parses the connection parameters from
@ -116,7 +116,7 @@ DIGITALTWIN_CLIENT_RESULT PnpBridgeConfig_GetJsonValueFromString(const char *Con
* *
* @param config String containing JSON config * @param config String containing JSON config
* *
* @returns DIGITALTWIN_CLIENT_OK on success and other DIGITALTWIN_CLIENT_RESULT values on failure. * @returns IOTHUB_CLIENT_OK on success and other IOTHUB_CLIENT_RESULT values on failure.
*/ */
PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* ConnectionParams); PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* ConnectionParams);
@ -126,10 +126,10 @@ PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* Connect
* *
* @param config JSON value of the config file from parson * @param config JSON value of the config file from parson
* *
* @returns DIGITALTWIN_CLIENT_OK on success and other DIGITALTWIN_CLIENT_RESULT values on failure. * @returns IOTHUB_CLIENT_OK on success and other IOTHUB_CLIENT_RESULT values on failure.
*/ */
MOCKABLE_FUNCTION(, MOCKABLE_FUNCTION(,
DIGITALTWIN_CLIENT_RESULT, IOTHUB_CLIENT_RESULT,
PnpBridgeConfig_RetrieveConfiguration, PnpBridgeConfig_RetrieveConfiguration,
JSON_Value*, ConfigJson, JSON_Value*, ConfigJson,
PNPBRIDGE_CONFIGURATION*, BridgeConfig PNPBRIDGE_CONFIGURATION*, BridgeConfig

Просмотреть файл

@ -8,18 +8,9 @@ extern "C"
{ {
#endif #endif
#include <pnpadapter_manager.h>
int IOTHUB_CLIENT_RESULT IotComms_InitializeIotHandle(MX_IOT_HANDLE_TAG* IotHandle, bool TraceOn, PCONNECTION_PARAMETERS ConnectionParams);
IotComms_RegisterPnPInterfaces(
MX_IOT_HANDLE_TAG* IotHandle,
const char* ModelRepoId,
DIGITALTWIN_INTERFACE_CLIENT_HANDLE* interfaces,
int InterfaceCount
);
DIGITALTWIN_CLIENT_RESULT IotComms_InitializeIotHandle(MX_IOT_HANDLE_TAG* IotHandle, bool TraceOn, PCONNECTION_PARAMETERS ConnectionParams);
void IotComms_DigitalTwinClient_Destroy(MX_IOT_HANDLE_TAG* IotHandle);
#ifdef __cplusplus #ifdef __cplusplus
} }

Просмотреть файл

@ -1,6 +1,8 @@
// Copyright (c) Microsoft. All rights reserved. // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
#pragma once
#ifndef PNPBRIDGE_PNP_ADAPTER_INTERFACE_H #ifndef PNPBRIDGE_PNP_ADAPTER_INTERFACE_H
#define PNPBRIDGE_PNP_ADAPTER_INTERFACE_H #define PNPBRIDGE_PNP_ADAPTER_INTERFACE_H
@ -39,9 +41,9 @@ extern "C"
* *
* @param AdapterHandle Handle to the pnp adapter * @param AdapterHandle Handle to the pnp adapter
* *
* @returns DIGITALTWIN_CLIENT_OK on success and other values on failure * @returns IOTHUB_CLIENT_OK on success and other values on failure
*/ */
typedef DIGITALTWIN_CLIENT_RESULT(*PNPBRIDGE_ADAPTER_CREATE) (const JSON_Object* AdapterGlobalConfig, typedef IOTHUB_CLIENT_RESULT(*PNPBRIDGE_ADAPTER_CREATE) (const JSON_Object* AdapterGlobalConfig,
PNPBRIDGE_ADAPTER_HANDLE AdapterHandle); PNPBRIDGE_ADAPTER_HANDLE AdapterHandle);
@ -54,9 +56,9 @@ extern "C"
* *
* @param AdapterHandle Handle to the pnp adapter * @param AdapterHandle Handle to the pnp adapter
* *
* @returns DIGITALTWIN_CLIENT_OK on success and other values on failure * @returns IOTHUB_CLIENT_OK on success and other values on failure
*/ */
typedef DIGITALTWIN_CLIENT_RESULT(*PNPBRIDGE_ADAPTER_DESTOY)(PNPBRIDGE_ADAPTER_HANDLE AdapterHandle); typedef IOTHUB_CLIENT_RESULT(*PNPBRIDGE_ADAPTER_DESTOY)(PNPBRIDGE_ADAPTER_HANDLE AdapterHandle);
/* /*
@ -85,14 +87,14 @@ extern "C"
* *
* @param PnpInterfaceHandle Handle to Pnp interface * @param PnpInterfaceHandle Handle to Pnp interface
* *
* @returns DIGITALTWIN_CLIENT_OK on success and other values on failure. If this call fails the bridge * @returns IOTHUB_CLIENT_OK on success and other values on failure. If this call fails the bridge
* will consider it fatal and fail to start. If this call succeeds it is expected that * will consider it fatal and fail to start. If this call succeeds it is expected that
* PnpInterfaceClient is set to a valid DIGITALTWIN_INTERFACE_CLIENT_HANDLE. * PnpInterfaceClient is set to a valid DIGITALTWIN_INTERFACE_CLIENT_HANDLE.
*/ */
typedef DIGITALTWIN_CLIENT_RESULT(*PNPBRIDGE_INTERFACE_CREATE)(PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, typedef IOTHUB_CLIENT_RESULT(*PNPBRIDGE_INTERFACE_CREATE)(PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
const char* ComponentName, const JSON_Object* AdapterInterfaceConfig, const char* ComponentName, const JSON_Object* AdapterInterfaceConfig,
PNPBRIDGE_INTERFACE_HANDLE BridgeInterfaceHandle, DIGITALTWIN_INTERFACE_CLIENT_HANDLE* PnpInterfaceClient); PNPBRIDGE_INTERFACE_HANDLE BridgeInterfaceHandle);
/* /*
* @brief PNPBRIDGE_INTERFACE_START starts the pnp interface after it has been registered with Azure Pnp. * @brief PNPBRIDGE_INTERFACE_START starts the pnp interface after it has been registered with Azure Pnp.
@ -101,10 +103,10 @@ extern "C"
* *
* @param PnpInterfaceHandle Handle to Pnp interface * @param PnpInterfaceHandle Handle to Pnp interface
* *
* @returns DIGITALTWIN_CLIENT_OK on success and other values on failure * @returns IOTHUB_CLIENT_OK on success and other values on failure
*/ */
typedef DIGITALTWIN_CLIENT_RESULT(*PNPBRIDGE_INTERFACE_START)(PNPBRIDGE_ADAPTER_HANDLE AdapterHandle, typedef IOTHUB_CLIENT_RESULT(*PNPBRIDGE_INTERFACE_START)(PNPBRIDGE_ADAPTER_HANDLE AdapterHandle,
PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle); PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle);
/* /*
@ -115,9 +117,9 @@ extern "C"
* *
* @param PnpInterfaceHandle Handle to Pnp interface * @param PnpInterfaceHandle Handle to Pnp interface
* *
* @returns DIGITALTWIN_CLIENT_OK on success and other values on failure * @returns IOTHUB_CLIENT_OK on success and other values on failure
*/ */
typedef DIGITALTWIN_CLIENT_RESULT(*PNPBRIDGE_INTERFACE_STOP)(PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle); typedef IOTHUB_CLIENT_RESULT(*PNPBRIDGE_INTERFACE_STOP)(PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle);
/* /*
* @brief PNPBRIDGE_INTERFACE_DESTROY cleans up the pnp interface context and calls * @brief PNPBRIDGE_INTERFACE_DESTROY cleans up the pnp interface context and calls
@ -127,9 +129,50 @@ extern "C"
* *
* @param PnpInterfaceHandle Handle to Pnp interface * @param PnpInterfaceHandle Handle to Pnp interface
* *
* @returns DIGITALTWIN_CLIENT_OK on success and other values on failure * @returns IOTHUB_CLIENT_OK on success and other values on failure
*/ */
typedef DIGITALTWIN_CLIENT_RESULT(*PNPBRIDGE_INTERFACE_DESTROY)(PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle); typedef IOTHUB_CLIENT_RESULT(*PNPBRIDGE_INTERFACE_DESTROY)(PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle);
/*
* @brief PNPBRIDGE_ADAPTER_PROPERTY_UPDATE calls the property update callback for
* a certain adapter type based on the interface handle
*
*
* @param PnpInterfaceHandle Handle to Pnp interface
*
* @param PropertyName Name of property for which property updated callback needs to be called
*
* @param PropertyValue JSON_Value Property update
*
* @param version Version
*
* @param userContextCallback User context callback
*
* @returns IOTHUB_CLIENT_OK on success and other values on failure
*/
typedef void (*PNPBRIDGE_ADAPTER_PROPERTY_UPDATE)(PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle,
const char* PropertyName, JSON_Value* PropertyValue, int version, void* userContextCallback);
/*
* @brief PNPBRIDGE_ADAPTER_PROCESS_COMMAND calls the process command callback for
* a certain adapter type based on the interface handle
*
*
* @param PnpInterfaceHandle Handle to Pnp interface
*
* @param CommandName Name of command which needs to be processed
*
* @param CommandValue JSON_Value Command root value
*
* @param CommandResponse The resonse to the command which the adapter allocates and populates
*
* @param CommandResponseSize Size of the command response buffer
*
* @returns IOTHUB_CLIENT_OK on success and other values on failure
*/
typedef int (*PNPBRIDGE_ADAPTER_PROCESS_COMMAND)(PNPBRIDGE_INTERFACE_HANDLE PnpInterfaceHandle,
const char* CommandName, JSON_Value* CommandValue, unsigned char** CommandResponse, size_t* CommandResponseSize);
/* /*
PnpAdapter and Interface Methods PnpAdapter and Interface Methods
@ -168,7 +211,7 @@ extern "C"
/** /**
* @brief PnpInterfaceHandleSetContext sets context on an interface handle * @brief PnpInterfaceHandleSetContext sets context on an interface handle
* @param InterfaceHandle Handle to pnp adapter * @param InterfaceHandle Handle to pnp interface
* *
* @param InterfaceContext Interface context to set * @param InterfaceContext Interface context to set
* *
@ -182,9 +225,9 @@ extern "C"
); );
/** /**
* @brief PnpInterfaceHandleGetContext gets adapter context from an adapter handle * @brief PnpInterfaceHandleGetContext gets interface context from an interface handle
* @param AdapterHandle Handle to pnp interface * @param InterfaceHandle Handle to pnp interface
* *
* @returns void * Interface context * @returns void * Interface context
*/ */
@ -194,6 +237,20 @@ extern "C"
PNPBRIDGE_INTERFACE_HANDLE, InterfaceHandle PNPBRIDGE_INTERFACE_HANDLE, InterfaceHandle
); );
/**
* @brief PnpInterfaceHandleGetContext gets adapter context from an adapter handle
* @param InterfaceHandle Handle to pnp interface
*
* @returns IOTHUB_DEVICE_CLIENT_HANDLE IoTHub Device Client handle
*/
MOCKABLE_FUNCTION(,
IOTHUB_DEVICE_CLIENT_HANDLE,
PnpInterfaceHandleGetIotHubDeviceClient,
PNPBRIDGE_INTERFACE_HANDLE, InterfaceHandle
);
/* /*
PnpAdapter Binding info PnpAdapter Binding info
@ -208,6 +265,8 @@ extern "C"
PNPBRIDGE_INTERFACE_STOP stopPnpInterface; PNPBRIDGE_INTERFACE_STOP stopPnpInterface;
PNPBRIDGE_INTERFACE_DESTROY destroyPnpInterface; PNPBRIDGE_INTERFACE_DESTROY destroyPnpInterface;
PNPBRIDGE_ADAPTER_DESTOY destroyAdapter; PNPBRIDGE_ADAPTER_DESTOY destroyAdapter;
PNPBRIDGE_ADAPTER_PROPERTY_UPDATE processPropertyUpdate;
PNPBRIDGE_ADAPTER_PROCESS_COMMAND processCommand;
} PNP_ADAPTER, * PPNP_ADAPTER; } PNP_ADAPTER, * PPNP_ADAPTER;
#ifdef __cplusplus #ifdef __cplusplus

Просмотреть файл

@ -1,7 +1,7 @@
#pragma once #pragma once
// Copyright (c) Microsoft. All rights reserved. // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include <pnpbridge.h>
#pragma once #pragma once
#ifdef __cplusplus #ifdef __cplusplus
@ -31,7 +31,7 @@ extern "C"
typedef struct _PNP_ADAPTER_MANAGER { typedef struct _PNP_ADAPTER_MANAGER {
unsigned int NumInterfaces; unsigned int NumInterfaces;
SINGLYLINKEDLIST_HANDLE PnpAdapterHandleList; SINGLYLINKEDLIST_HANDLE PnpAdapterHandleList;
DIGITALTWIN_INTERFACE_CLIENT_HANDLE* PnpInterfacesRegistrationList; char ** ComponentsInModel;
} PNP_ADAPTER_MANAGER, * PPNP_ADAPTER_MANAGER; } PNP_ADAPTER_MANAGER, * PPNP_ADAPTER_MANAGER;
@ -40,7 +40,7 @@ extern "C"
void* context; void* context;
const char* interfaceName; const char* interfaceName;
const char* adapterIdentity; const char* adapterIdentity;
DIGITALTWIN_INTERFACE_CLIENT_HANDLE pnpInterfaceClient; IOTHUB_DEVICE_CLIENT_HANDLE deviceClient;
} PNPADAPTER_INTERFACE_TAG, * PPNPADAPTER_INTERFACE_TAG; } PNPADAPTER_INTERFACE_TAG, * PPNPADAPTER_INTERFACE_TAG;
@ -52,9 +52,9 @@ extern "C"
* @param adapter Pointer to get back an initialized PPNP_ADAPTER_MANAGER * @param adapter Pointer to get back an initialized PPNP_ADAPTER_MANAGER
* *
* @returns DIGITALTWIN_CLIENT_OK on success and other DIGITALTWIN_CLIENT_RESULT values on failure * @returns IOTHUB_CLIENT_OK on success and other IOTHUB_CLIENT_RESULT values on failure
*/ */
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateManager( IOTHUB_CLIENT_RESULT PnpAdapterManager_CreateManager(
PPNP_ADAPTER_MANAGER* adapter, PPNP_ADAPTER_MANAGER* adapter,
JSON_Value* config); JSON_Value* config);
@ -88,25 +88,50 @@ extern "C"
// PnpAdapterManager utility functions // PnpAdapterManager utility functions
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_GetAdapterFromManifest( IOTHUB_CLIENT_RESULT PnpAdapterManager_GetAdapterFromManifest(
const char* adapterId, const char* adapterId,
PPNP_ADAPTER* adapter); PPNP_ADAPTER* adapter);
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateAdapter( IOTHUB_CLIENT_RESULT PnpAdapterManager_CreateAdapter(
const char* adapterId, const char* adapterId,
PPNP_ADAPTER_CONTEXT_TAG* adapterContext, PPNP_ADAPTER_CONTEXT_TAG* adapterContext,
JSON_Value* config); JSON_Value* config);
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateInterfaces( IOTHUB_CLIENT_RESULT PnpAdapterManager_CreateInterfaces(
PPNP_ADAPTER_MANAGER adapterMgr, PPNP_ADAPTER_MANAGER adapterMgr,
JSON_Value* config); JSON_Value* config);
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_GetAdapterHandle( IOTHUB_CLIENT_RESULT PnpAdapterManager_GetAdapterHandle(
PPNP_ADAPTER_MANAGER adapterMgr, PPNP_ADAPTER_MANAGER adapterMgr,
const char* adapterIdentity, const char* adapterIdentity,
PPNP_ADAPTER_CONTEXT_TAG* adapterContext); PPNP_ADAPTER_CONTEXT_TAG* adapterContext);
DIGITALTWIN_CLIENT_RESULT PnPAdapterManager_RegisterInterfaces( IOTHUB_CLIENT_RESULT PnpAdapterManager_StartInterfaces(
PPNP_ADAPTER_MANAGER adapterMgr); PPNP_ADAPTER_MANAGER adapterMgr);
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_StartInterfaces(
IOTHUB_CLIENT_RESULT PnpAdapterManager_BuildComponentsInModel(
PPNP_ADAPTER_MANAGER adapterMgr); PPNP_ADAPTER_MANAGER adapterMgr);
// Device Twin callback is invoked by IoT SDK when a twin - either full twin or a PATCH update - arrives.
void PnpAdapterManager_DeviceTwinCallback(
DEVICE_TWIN_UPDATE_STATE updateState,
const unsigned char* payload,
size_t size,
void* userContextCallback);
// Device Method callback is invoked by IoT SDK when a device method arrives.
int PnpAdapterManager_DeviceMethodCallback(
const char* methodName,
const unsigned char* payload,
size_t size,
unsigned char** response,
size_t* responseSize,
void* userContextCallback);
// PnpAdapterManager_RoutePropertyCallback is the callback function that the PnP helper layer routes per property update.
static void PnpAdapterManager_RoutePropertyCallback(
const char* componentName,
const char* propertyName,
JSON_Value* propertyValue,
int version,
void* userContextCallback);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

Просмотреть файл

@ -9,6 +9,8 @@
|_| |___/ |_| |___/
*/ */
#pragma once
#ifndef PNPBRIDGE_H #ifndef PNPBRIDGE_H
#define PNPBRIDGE_H #define PNPBRIDGE_H
@ -19,8 +21,12 @@
#include "azure_macro_utils/macro_utils.h" #include "azure_macro_utils/macro_utils.h"
#include "umock_c/umock_c_prod.h" #include "umock_c/umock_c_prod.h"
#include <digitaltwin_interface_client.h> // PnP helper utilities.
#include "pnp_device_client_helpers.h"
#include "pnp_protocol_helpers.h"
#include <pnpadapter_api.h> #include <pnpadapter_api.h>
#include "pnpbridge_common.h"
#ifdef __cplusplus #ifdef __cplusplus
extern "C" extern "C"
@ -29,13 +35,6 @@ extern "C"
typedef void* MX_IOT_HANDLE; typedef void* MX_IOT_HANDLE;
// Getter method for DigitalTwin client handle from a device/module
MOCKABLE_FUNCTION(,
DIGITALTWIN_DEVICE_CLIENT_HANDLE,
IotHandle_GetPnpDeviceClient,
_In_ MX_IOT_HANDLE, IotHandle
);
MOCKABLE_FUNCTION(, int, PnpBridge_Main, const char*, ConfigurationFilePath); MOCKABLE_FUNCTION(, int, PnpBridge_Main, const char*, ConfigurationFilePath);
MOCKABLE_FUNCTION(, void, PnpBridge_Stop); MOCKABLE_FUNCTION(, void, PnpBridge_Stop);

Просмотреть файл

@ -41,15 +41,18 @@ extern "C"
#include <iothub_client_options.h> #include <iothub_client_options.h>
#include <iothubtransportmqtt.h> #include <iothubtransportmqtt.h>
#include <digitaltwin_device_client.h>
#include <digitaltwin_interface_client.h>
#include "parson.h" #include "parson.h"
// PnP helper utilities.
#include "pnp_device_client_helpers.h"
#include "pnp_protocol_helpers.h"
#include <assert.h> #include <assert.h>
#define DIGITALTWIN_MODULE_CLIENT_HANDLE void* #define DIGITALTWIN_MODULE_CLIENT_HANDLE void*
#define PNPBRIDGE_CLIENT_HANDLE void*
#define PNPBRIDGE_RESULT_VALUES \ #define PNPBRIDGE_RESULT_VALUES \
PNPBRIDGE_OK, \ PNPBRIDGE_OK, \
PNPBRIDGE_INSUFFICIENT_MEMORY, \ PNPBRIDGE_INSUFFICIENT_MEMORY, \
@ -62,8 +65,9 @@ extern "C"
MU_DEFINE_ENUM(PNPBRIDGE_RESULT, PNPBRIDGE_RESULT_VALUES); MU_DEFINE_ENUM(PNPBRIDGE_RESULT, PNPBRIDGE_RESULT_VALUES);
#define PNPBRIDGE_SUCCESS(Result) (Result == DIGITALTWIN_CLIENT_OK) #define PNPBRIDGE_SUCCESS(Result) (Result == IOTHUB_CLIENT_OK)
#include "configuration_parser.h" #include "configuration_parser.h"
#include "pnpadapter_manager.h"
MAP_RESULT Map_Add_Index(MAP_HANDLE handle, const char* key, int value); MAP_RESULT Map_Add_Index(MAP_HANDLE handle, const char* key, int value);
@ -125,8 +129,6 @@ typedef struct _MX_IOT_HANDLE_TAG {
// connection to iot device // connection to iot device
IOTHUB_DEVICE_CLIENT_HANDLE deviceHandle; IOTHUB_DEVICE_CLIENT_HANDLE deviceHandle;
// Handle representing PnpDeviceClient
DIGITALTWIN_DEVICE_CLIENT_HANDLE PnpDeviceClientHandle;
} IotDevice; } IotDevice;
struct IotModule { struct IotModule {
@ -144,11 +146,32 @@ typedef struct _MX_IOT_HANDLE_TAG {
bool DigitalTwinClientInitialized; bool DigitalTwinClientInitialized;
} MX_IOT_HANDLE_TAG; } MX_IOT_HANDLE_TAG;
DIGITALTWIN_CLIENT_RESULT typedef enum PNP_BRIDGE_STATE {
PnpBridge_RegisterInterfaces( PNP_BRIDGE_UNINITIALIZED,
DIGITALTWIN_INTERFACE_CLIENT_HANDLE* interfaces, PNP_BRIDGE_INITIALIZED,
unsigned int interfaceCount PNP_BRIDGE_TEARING_DOWN,
); PNP_BRIDGE_DESTROYED
} PNP_BRIDGE_STATE;
// Device aggregator context
typedef struct _PNP_BRIDGE {
MX_IOT_HANDLE_TAG IotHandle;
PPNP_ADAPTER_MANAGER PnpMgr;
PNPBRIDGE_CONFIGURATION Configuration;
COND_HANDLE ExitCondition;
LOCK_HANDLE ExitLock;
} PNP_BRIDGE, *PPNP_BRIDGE;
void PnpBridge_Release(PPNP_BRIDGE pnpBridge);
// Globals PNP bridge instance
PPNP_BRIDGE g_PnpBridge;
PNP_BRIDGE_STATE g_PnpBridgeState;
bool g_PnpBridgeShutdown;
#ifdef __cplusplus #ifdef __cplusplus
} }

Просмотреть файл

@ -6,28 +6,7 @@ extern "C"
{ {
#endif #endif
typedef enum PNP_BRIDGE_STATE {
PNP_BRIDGE_UNINITIALIZED,
PNP_BRIDGE_INITIALIZED,
PNP_BRIDGE_TEARING_DOWN,
PNP_BRIDGE_DESTROYED
} PNP_BRIDGE_STATE;
// Device aggregator context
typedef struct _PNP_BRIDGE {
MX_IOT_HANDLE_TAG IotHandle;
PPNP_ADAPTER_MANAGER PnpMgr;
PNPBRIDGE_CONFIGURATION Configuration;
COND_HANDLE ExitCondition;
LOCK_HANDLE ExitLock;
} PNP_BRIDGE, *PPNP_BRIDGE;
void PnpBridge_Release(PPNP_BRIDGE pnpBridge);
#ifdef __cplusplus #ifdef __cplusplus
} }

Просмотреть файл

@ -54,6 +54,7 @@ include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/deps/umock-c/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/digitaltwin_client/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/digitaltwin_client/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/provisioning_client/inc) include_directories(../../deps/azure-iot-sdk-c-pnp/provisioning_client/inc)
include_directories(../../deps/azure-iot-sdk-c-pnp/iothub_client/samples/pnp/common)
include_directories(${pnp_bridge_INC_FOLDER}) include_directories(${pnp_bridge_INC_FOLDER})
include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/pal/windows) include_directories(../../deps/azure-iot-sdk-c-pnp/c-utility/pal/windows)

Просмотреть файл

@ -8,13 +8,13 @@ char* getcwd(char* buf, size_t size);
PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* ConnectionParams) PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* ConnectionParams)
{ {
PCONNECTION_PARAMETERS connParams = NULL; PCONNECTION_PARAMETERS connParams = NULL;
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
{ {
connParams = (PCONNECTION_PARAMETERS)calloc(1, sizeof(CONNECTION_PARAMETERS)); connParams = (PCONNECTION_PARAMETERS)calloc(1, sizeof(CONNECTION_PARAMETERS));
if (NULL == connParams) { if (NULL == connParams) {
LogError("Failed to allocate CONNECTION_PARAMETERS"); LogError("Failed to allocate CONNECTION_PARAMETERS");
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -23,7 +23,7 @@ PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* Connect
const char* connectionTypeStr = json_object_get_string(ConnectionParams, PNP_CONFIG_CONNECTION_TYPE); const char* connectionTypeStr = json_object_get_string(ConnectionParams, PNP_CONFIG_CONNECTION_TYPE);
if (NULL == connectionTypeStr) { if (NULL == connectionTypeStr) {
LogError("%s is not specified in config", PNP_CONFIG_CONNECTION_TYPE); LogError("%s is not specified in config", PNP_CONFIG_CONNECTION_TYPE);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -38,7 +38,7 @@ PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* Connect
} }
else { else {
LogError("ConnectionType (%s) is not valid", connectionTypeStr); LogError("ConnectionType (%s) is not valid", connectionTypeStr);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -49,7 +49,7 @@ PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* Connect
connParams->RootInterfaceModelId = json_object_get_string(ConnectionParams, PNP_CONFIG_CONNECTION_ROOT_INTERFACE_MODEL_ID); connParams->RootInterfaceModelId = json_object_get_string(ConnectionParams, PNP_CONFIG_CONNECTION_ROOT_INTERFACE_MODEL_ID);
if (NULL == connParams->RootInterfaceModelId) { if (NULL == connParams->RootInterfaceModelId) {
LogError("%s is missing in config", PNP_CONFIG_CONNECTION_ROOT_INTERFACE_MODEL_ID); LogError("%s is missing in config", PNP_CONFIG_CONNECTION_ROOT_INTERFACE_MODEL_ID);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -59,7 +59,7 @@ PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* Connect
connParams->u1.ConnectionString = json_object_get_string(ConnectionParams, PNP_CONFIG_CONNECTION_TYPE_CONFIG_STRING); connParams->u1.ConnectionString = json_object_get_string(ConnectionParams, PNP_CONFIG_CONNECTION_TYPE_CONFIG_STRING);
if (NULL == connParams->u1.ConnectionString) { if (NULL == connParams->u1.ConnectionString) {
LogError("%s is missing", PNP_CONFIG_CONNECTION_TYPE_CONFIG_STRING); LogError("%s is missing", PNP_CONFIG_CONNECTION_TYPE_CONFIG_STRING);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
} }
@ -71,7 +71,7 @@ PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* Connect
JSON_Object* dpsSettings = json_object_get_object(ConnectionParams, PNP_CONFIG_CONNECTION_TYPE_CONFIG_DPS); JSON_Object* dpsSettings = json_object_get_object(ConnectionParams, PNP_CONFIG_CONNECTION_TYPE_CONFIG_DPS);
if (NULL == dpsSettings) { if (NULL == dpsSettings) {
LogError("%s are missing in config", PNP_CONFIG_CONNECTION_TYPE_CONFIG_DPS); LogError("%s are missing in config", PNP_CONFIG_CONNECTION_TYPE_CONFIG_DPS);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -80,21 +80,21 @@ PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* Connect
dpsParams->GlobalProvUri = json_object_get_string(dpsSettings, PNP_CONFIG_CONNECTION_DPS_GLOBAL_PROV_URI); dpsParams->GlobalProvUri = json_object_get_string(dpsSettings, PNP_CONFIG_CONNECTION_DPS_GLOBAL_PROV_URI);
if (NULL == dpsParams->GlobalProvUri) { if (NULL == dpsParams->GlobalProvUri) {
LogError("%s is missing in config", PNP_CONFIG_CONNECTION_DPS_GLOBAL_PROV_URI); LogError("%s is missing in config", PNP_CONFIG_CONNECTION_DPS_GLOBAL_PROV_URI);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
dpsParams->IdScope = json_object_get_string(dpsSettings, PNP_CONFIG_CONNECTION_DPS_ID_SCOPE); dpsParams->IdScope = json_object_get_string(dpsSettings, PNP_CONFIG_CONNECTION_DPS_ID_SCOPE);
if (NULL == dpsParams->IdScope) { if (NULL == dpsParams->IdScope) {
LogError("%s is missing in config", PNP_CONFIG_CONNECTION_DPS_ID_SCOPE); LogError("%s is missing in config", PNP_CONFIG_CONNECTION_DPS_ID_SCOPE);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
dpsParams->DeviceId = json_object_get_string(dpsSettings, PNP_CONFIG_CONNECTION_DPS_DEVICE_ID); dpsParams->DeviceId = json_object_get_string(dpsSettings, PNP_CONFIG_CONNECTION_DPS_DEVICE_ID);
if (NULL == dpsParams->DeviceId) { if (NULL == dpsParams->DeviceId) {
LogError("%s is missing in config", PNP_CONFIG_CONNECTION_DPS_DEVICE_ID); LogError("%s is missing in config", PNP_CONFIG_CONNECTION_DPS_DEVICE_ID);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -108,14 +108,14 @@ PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* Connect
JSON_Object* authParameters = json_object_get_object(ConnectionParams, PNP_CONFIG_CONNECTION_AUTH_PARAMETERS); JSON_Object* authParameters = json_object_get_object(ConnectionParams, PNP_CONFIG_CONNECTION_AUTH_PARAMETERS);
if (NULL == authParameters) { if (NULL == authParameters) {
LogError("%s is missing in config", PNP_CONFIG_CONNECTION_AUTH_PARAMETERS); LogError("%s is missing in config", PNP_CONFIG_CONNECTION_AUTH_PARAMETERS);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
const char* authType = json_object_get_string(authParameters, PNP_CONFIG_CONNECTION_AUTH_TYPE); const char* authType = json_object_get_string(authParameters, PNP_CONFIG_CONNECTION_AUTH_TYPE);
if (NULL == authType) { if (NULL == authType) {
LogError("%s is not specified in config", PNP_CONFIG_CONNECTION_AUTH_TYPE); LogError("%s is not specified in config", PNP_CONFIG_CONNECTION_AUTH_TYPE);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -127,7 +127,7 @@ PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* Connect
} }
else { else {
LogError("auth_type (%s) is not valid", authType); LogError("auth_type (%s) is not valid", authType);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -137,7 +137,7 @@ PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* Connect
const char* deviceKey = json_object_get_string(authParameters, PNP_CONFIG_CONNECTION_AUTH_TYPE_DEVICE_SYMM_KEY); const char* deviceKey = json_object_get_string(authParameters, PNP_CONFIG_CONNECTION_AUTH_TYPE_DEVICE_SYMM_KEY);
if (NULL == deviceKey) { if (NULL == deviceKey) {
LogError("%s is missing in config", PNP_CONFIG_CONNECTION_AUTH_TYPE_DEVICE_SYMM_KEY); LogError("%s is missing in config", PNP_CONFIG_CONNECTION_AUTH_TYPE_DEVICE_SYMM_KEY);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -148,7 +148,7 @@ PCONNECTION_PARAMETERS PnpBridgeConfig_GetConnectionDetails(JSON_Object* Connect
} }
exit: exit:
{ {
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
free(connParams); free(connParams);
connParams = NULL; connParams = NULL;
} }
@ -157,16 +157,16 @@ exit:
return connParams; return connParams;
} }
DIGITALTWIN_CLIENT_RESULT PnpBridgeConfig_GetJsonValueFromConfigFile(const char* filename, JSON_Value** config) IOTHUB_CLIENT_RESULT PnpBridgeConfig_GetJsonValueFromConfigFile(const char* filename, JSON_Value** config)
{ {
if (NULL == filename) { if (NULL == filename) {
LogError("filename is NULL"); LogError("filename is NULL");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
if (NULL == config) { if (NULL == config) {
LogError("config is NULL"); LogError("config is NULL");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
// Check if file exists // Check if file exists
@ -183,7 +183,7 @@ DIGITALTWIN_CLIENT_RESULT PnpBridgeConfig_GetJsonValueFromConfigFile(const char*
if (NULL != workingDir) { if (NULL != workingDir) {
free(workingDir); free(workingDir);
} }
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
} }
@ -191,28 +191,28 @@ DIGITALTWIN_CLIENT_RESULT PnpBridgeConfig_GetJsonValueFromConfigFile(const char*
*config = json_parse_file(filename); *config = json_parse_file(filename);
if (*config == NULL) { if (*config == NULL) {
LogError("Failed to parse the config file. Please validate the JSON file in a JSON vailidator"); LogError("Failed to parse the config file. Please validate the JSON file in a JSON vailidator");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT PnpBridgeConfig_RetrieveConfiguration(JSON_Value* JsonConfig, PNPBRIDGE_CONFIGURATION* BridgeConfig) IOTHUB_CLIENT_RESULT PnpBridgeConfig_RetrieveConfiguration(JSON_Value* JsonConfig, PNPBRIDGE_CONFIGURATION* BridgeConfig)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
PCONNECTION_PARAMETERS connParams = NULL; PCONNECTION_PARAMETERS connParams = NULL;
// Check for mandatory parameters // Check for mandatory parameters
{ {
if (NULL == JsonConfig) { if (NULL == JsonConfig) {
LogError("JsonConfig is NULL"); LogError("JsonConfig is NULL");
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
if (NULL == BridgeConfig) { if (NULL == BridgeConfig) {
LogError("BridgeConfig is NULL"); LogError("BridgeConfig is NULL");
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -223,13 +223,13 @@ DIGITALTWIN_CLIENT_RESULT PnpBridgeConfig_RetrieveConfiguration(JSON_Value* Json
JSON_Object* pnpBridgeConnectionParameters = json_object_get_object(jsonObject, PNP_CONFIG_CONNECTION_PARAMETERS); JSON_Object* pnpBridgeConnectionParameters = json_object_get_object(jsonObject, PNP_CONFIG_CONNECTION_PARAMETERS);
if (NULL == pnpBridgeConnectionParameters) { if (NULL == pnpBridgeConnectionParameters) {
LogError("%s is missing", PNP_CONFIG_CONNECTION_PARAMETERS); LogError("%s is missing", PNP_CONFIG_CONNECTION_PARAMETERS);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
connParams = PnpBridgeConfig_GetConnectionDetails(pnpBridgeConnectionParameters); connParams = PnpBridgeConfig_GetConnectionDetails(pnpBridgeConnectionParameters);
if (NULL == connParams) { if (NULL == connParams) {
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -242,7 +242,7 @@ DIGITALTWIN_CLIENT_RESULT PnpBridgeConfig_RetrieveConfiguration(JSON_Value* Json
JSON_Array* devices = Configuration_GetDevices(JsonConfig); JSON_Array* devices = Configuration_GetDevices(JsonConfig);
if (NULL == devices) { if (NULL == devices) {
LogError("No configured devices in the pnpbridge config"); LogError("No configured devices in the pnpbridge config");
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
@ -254,14 +254,14 @@ DIGITALTWIN_CLIENT_RESULT PnpBridgeConfig_RetrieveConfiguration(JSON_Value* Json
const char* interfaceName = json_object_dotget_string(device, PNP_CONFIG_COMPONENT_NAME); const char* interfaceName = json_object_dotget_string(device, PNP_CONFIG_COMPONENT_NAME);
if (NULL == interfaceName) { if (NULL == interfaceName) {
LogError("Device at index %zu is missing %s", i, PNP_CONFIG_COMPONENT_NAME); LogError("Device at index %zu is missing %s", i, PNP_CONFIG_COMPONENT_NAME);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
const char* adapterId = json_object_dotget_string(device, PNP_CONFIG_ADAPTER_ID); const char* adapterId = json_object_dotget_string(device, PNP_CONFIG_ADAPTER_ID);
if (NULL == adapterId) { if (NULL == adapterId) {
LogError("Device at index %zu is missing %s", i, PNP_CONFIG_ADAPTER_ID); LogError("Device at index %zu is missing %s", i, PNP_CONFIG_ADAPTER_ID);
result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; result = IOTHUB_CLIENT_INVALID_ARG;
goto exit; goto exit;
} }
} }
@ -284,20 +284,20 @@ exit:
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT PnpBridgeConfig_GetJsonValueFromString(const char* configString, JSON_Value** config) IOTHUB_CLIENT_RESULT PnpBridgeConfig_GetJsonValueFromString(const char* configString, JSON_Value** config)
{ {
if (NULL == configString || NULL == config) { if (NULL == configString || NULL == config) {
LogError("PnpBridgeConfig_GetJsonValueFromString: Invalid parameters"); LogError("PnpBridgeConfig_GetJsonValueFromString: Invalid parameters");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
*config = json_parse_string(configString); *config = json_parse_string(configString);
if (*config == NULL) { if (*config == NULL) {
LogError("PnpBridgeConfig_GetJsonValueFromString: Failed to parse config string"); LogError("PnpBridgeConfig_GetJsonValueFromString: Failed to parse config string");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
JSON_Array* Configuration_GetDevices(JSON_Value* config) { JSON_Array* Configuration_GetDevices(JSON_Value* config) {

Просмотреть файл

@ -17,12 +17,6 @@
#include "azure_prov_client/prov_transport_mqtt_client.h" #include "azure_prov_client/prov_transport_mqtt_client.h"
#include "azure_prov_client/prov_security_factory.h" #include "azure_prov_client/prov_security_factory.h"
DIGITALTWIN_CLIENT_RESULT
IotComms_DigitalTwinClient_Initalize(
MX_IOT_HANDLE_TAG* IotHandle,
const char * DigitalTwinModelId
);
// State of DPS registration process. We cannot proceed with DPS until we get into the state APP_DPS_REGISTRATION_SUCCEEDED. // State of DPS registration process. We cannot proceed with DPS until we get into the state APP_DPS_REGISTRATION_SUCCEEDED.
typedef enum APP_DPS_REGISTRATION_STATUS_TAG typedef enum APP_DPS_REGISTRATION_STATUS_TAG
{ {
@ -211,59 +205,18 @@ exit:
#endif // ENABLE_IOT_CENTRAL #endif // ENABLE_IOT_CENTRAL
// Invokes PnP_DeviceClient_RegisterInterfacesAsync, which indicates to Azure IoT which PnP interfaces this device supports.
// The PnP Handle *is not valid* until this operation has completed (as indicated by the callback appPnpInterfacesRegistered being invoked).
// In this sample, we block indefinitely but production code should include a timeout.
int
IotComms_RegisterPnPInterfaces(
MX_IOT_HANDLE_TAG* IotHandle,
const char* ModelRepoId,
DIGITALTWIN_INTERFACE_CLIENT_HANDLE* Interfaces,
int InterfaceCount
)
{
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK;
IotComms_DigitalTwinClient_Initalize(IotHandle, ModelRepoId);
if (!IotHandle->IsModule) {
result = DigitalTwin_DeviceClient_RegisterInterfaces(
IotHandle->u1.IotDevice.PnpDeviceClientHandle, Interfaces,
InterfaceCount);
}
else {
LogError("Module support is not present in public preview");
result = DIGITALTWIN_CLIENT_ERROR_COMMAND_NOT_PRESENT;
}
if (DIGITALTWIN_CLIENT_OK != result) {
result = DIGITALTWIN_CLIENT_ERROR;
}
return result;
}
// InitializeIotHubDeviceHandle initializes underlying IoTHub client, creates a device handle with the specified connection string, // InitializeIotHubDeviceHandle initializes underlying IoTHub client, creates a device handle with the specified connection string,
// and sets some options on this handle prior to beginning. // and sets some options on this handle prior to beginning.
IOTHUB_DEVICE_HANDLE IotComms_InitializeIotHubDeviceHandle(bool TraceOn, const char* ConnectionString) IOTHUB_DEVICE_HANDLE IotComms_InitializeIotHubDeviceHandle(bool TraceOn, const char* ConnectionString, const char* ModelId)
{ {
IOTHUB_DEVICE_HANDLE deviceHandle = NULL; IOTHUB_DEVICE_HANDLE deviceHandle = NULL;
IOTHUB_CLIENT_RESULT iothubClientResult;
// Get connection string from config // Get connection string from config
if ((deviceHandle = IoTHubDeviceClient_CreateFromConnectionString(ConnectionString, MQTT_Protocol)) == NULL) if ((deviceHandle = PnPHelper_CreateDeviceClientHandle(ConnectionString, ModelId, TraceOn,
{ (IOTHUB_CLIENT_DEVICE_METHOD_CALLBACK_ASYNC) PnpAdapterManager_DeviceMethodCallback,
LogError("Failed to create device handle\n"); (IOTHUB_CLIENT_DEVICE_TWIN_CALLBACK) PnpAdapterManager_DeviceTwinCallback)) == NULL)
}
else if ((iothubClientResult = IoTHubDeviceClient_SetOption(deviceHandle, OPTION_LOG_TRACE, &TraceOn)) != IOTHUB_CLIENT_OK)
{
LogError("Failed to set option %s, error=%d\n", OPTION_LOG_TRACE, iothubClientResult);
IoTHubDeviceClient_Destroy(deviceHandle);
deviceHandle = NULL;
}
if (deviceHandle == NULL)
{ {
LogError("Failed to create IoT hub device handle\n");
IoTHub_Deinit(); IoTHub_Deinit();
} }
@ -291,7 +244,7 @@ IOTHUB_DEVICE_HANDLE IotComms_InitializeIotDevice(bool TraceOn, PCONNECTION_PARA
sprintf(connectionString, format, ConnectionParams->u1.ConnectionString, ConnectionParams->AuthParameters.u1.DeviceKey); sprintf(connectionString, format, ConnectionParams->u1.ConnectionString, ConnectionParams->AuthParameters.u1.DeviceKey);
} }
handle = IotComms_InitializeIotHubDeviceHandle(TraceOn, connectionString); handle = IotComms_InitializeIotHubDeviceHandle(TraceOn, connectionString, ConnectionParams->RootInterfaceModelId);
if (NULL != format) { if (NULL != format) {
free(connectionString); free(connectionString);
@ -318,25 +271,25 @@ IOTHUB_DEVICE_HANDLE IotComms_InitializeIotDevice(bool TraceOn, PCONNECTION_PARA
return NULL; return NULL;
} }
DIGITALTWIN_CLIENT_RESULT IOTHUB_CLIENT_RESULT
IotComms_InitializeIotDeviceHandle( IotComms_InitializeIotDeviceHandle(
MX_IOT_HANDLE_TAG* IotHandle, MX_IOT_HANDLE_TAG* IotHandle,
bool TraceOn, bool TraceOn,
PCONNECTION_PARAMETERS ConnectionParams PCONNECTION_PARAMETERS ConnectionParams
) )
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
{ {
// Mark this as device handle // Mark this as device handle
IotHandle->IsModule = false; IotHandle->IsModule = false;
// Connect to Iot Hub Device // Connect to Iot Hub Device
IotHandle->u1.IotDevice.deviceHandle = IotComms_InitializeIotDevice(TraceOn, ConnectionParams); IotHandle->u1.IotDevice.deviceHandle = IotComms_InitializeIotDevice(TraceOn, ConnectionParams);
if (NULL == IotHandle->u1.IotDevice.deviceHandle) { if (NULL == IotHandle->u1.IotDevice.deviceHandle) {
LogError("IotComms_InitializeIotDevice failed\n"); LogError("IotComms_InitializeIotDevice failed\n");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
// We have completed initializing the pnp client // We have completed initializing the pnp client
@ -346,53 +299,11 @@ exit:
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT
IotComms_DigitalTwinClient_Initalize(
MX_IOT_HANDLE_TAG* IotHandle,
const char * DigitalTwinModelId
)
{
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK;
// Create PnpDeviceHandle IOTHUB_CLIENT_RESULT IotComms_InitializeIotHandle(MX_IOT_HANDLE_TAG* IotHandle, bool TraceOn, PCONNECTION_PARAMETERS ConnectionParams)
if (!IotHandle->IsModule) {
if (DIGITALTWIN_CLIENT_OK != DigitalTwin_DeviceClient_CreateFromDeviceHandle(
IotHandle->u1.IotDevice.deviceHandle, DigitalTwinModelId, &IotHandle->u1.IotDevice.PnpDeviceClientHandle))
{
LogError("DigitalTwin_DeviceClient_CreateFromDeviceHandle failed\n");
result = DIGITALTWIN_CLIENT_ERROR;
}
}
else {
result = DIGITALTWIN_CLIENT_ERROR_COMMAND_NOT_PRESENT;
}
IotHandle->DigitalTwinClientInitialized = (DIGITALTWIN_CLIENT_OK == result);
return result;
}
void
IotComms_DigitalTwinClient_Destroy(
MX_IOT_HANDLE_TAG* IotHandle
)
{
if (NULL != IotHandle->u1.IotDevice.PnpDeviceClientHandle) {
if (!IotHandle->IsModule) {
DigitalTwin_DeviceClient_Destroy(IotHandle->u1.IotDevice.PnpDeviceClientHandle);
}
else {
LogError("Module support is not present in public preview");
}
}
IotHandle->DigitalTwinClientInitialized = false;
}
DIGITALTWIN_CLIENT_RESULT IotComms_InitializeIotHandle(MX_IOT_HANDLE_TAG* IotHandle, bool TraceOn, PCONNECTION_PARAMETERS ConnectionParams)
{ {
if (ConnectionParams->ConnectionType == CONNECTION_TYPE_EDGE_MODULE) { if (ConnectionParams->ConnectionType == CONNECTION_TYPE_EDGE_MODULE) {
return DIGITALTWIN_CLIENT_ERROR_COMMAND_NOT_PRESENT; return IOTHUB_CLIENT_ERROR;
} }
else { else {
return IotComms_InitializeIotDeviceHandle(IotHandle, TraceOn, ConnectionParams); return IotComms_InitializeIotDeviceHandle(IotHandle, TraceOn, ConnectionParams);

Просмотреть файл

@ -30,9 +30,8 @@ void* PnpInterfaceHandleGetContext(PNPBRIDGE_INTERFACE_HANDLE InterfaceHandle)
return (void*)interfaceContextTag->context; return (void*)interfaceContextTag->context;
} }
DIGITALTWIN_DEVICE_CLIENT_HANDLE IOTHUB_DEVICE_CLIENT_HANDLE PnpInterfaceHandleGetIotHubDeviceClient(PNPBRIDGE_INTERFACE_HANDLE InterfaceHandle)
IotHandle_GetPnpDeviceClient(_In_ MX_IOT_HANDLE IotHandle)
{ {
MX_IOT_HANDLE_TAG* iotHandle = (MX_IOT_HANDLE_TAG*)IotHandle; PPNPADAPTER_INTERFACE_TAG interfaceContextTag = (PPNPADAPTER_INTERFACE_TAG)InterfaceHandle;
return iotHandle->u1.IotDevice.PnpDeviceClientHandle; return interfaceContextTag->deviceClient;
} }

Просмотреть файл

@ -12,29 +12,34 @@ extern const int PnpAdapterCount;
#include "pnpadapter_manager.h" #include "pnpadapter_manager.h"
#endif #endif
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_ValidatePnpAdapter(PPNP_ADAPTER pnpAdapter) { IOTHUB_CLIENT_RESULT PnpAdapterManager_ValidatePnpAdapter(
PPNP_ADAPTER pnpAdapter)
{
if (NULL == pnpAdapter->identity) { if (NULL == pnpAdapter->identity) {
LogError("PnpAdapter's Identity field is not initialized"); LogError("PnpAdapter's Identity field is not initialized");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
if (NULL == pnpAdapter->createAdapter || NULL == pnpAdapter->createPnpInterface || NULL == pnpAdapter->startPnpInterface || if (NULL == pnpAdapter->createAdapter || NULL == pnpAdapter->createPnpInterface || NULL == pnpAdapter->startPnpInterface ||
NULL == pnpAdapter->stopPnpInterface || NULL == pnpAdapter->destroyPnpInterface || NULL == pnpAdapter->destroyAdapter) { NULL == pnpAdapter->stopPnpInterface || NULL == pnpAdapter->destroyPnpInterface || NULL == pnpAdapter->destroyAdapter) {
LogError("PnpAdapter's callbacks are not initialized"); LogError("PnpAdapter's callbacks are not initialized");
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
} }
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_InitializeAdapter(PPNP_ADAPTER adapter, PPNP_ADAPTER_TAG adapterTag) { IOTHUB_CLIENT_RESULT PnpAdapterManager_InitializeAdapter(
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; PPNP_ADAPTER adapter,
PPNP_ADAPTER_TAG adapterTag)
{
IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
PPNP_ADAPTER_TAG adapterT = NULL; PPNP_ADAPTER_TAG adapterT = NULL;
adapterT = calloc(1, sizeof(PNP_ADAPTER_TAG)); adapterT = calloc(1, sizeof(PNP_ADAPTER_TAG));
if (NULL == adapterT) { if (NULL == adapterT) {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -42,7 +47,7 @@ DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_InitializeAdapter(PPNP_ADAPTER adapt
adapterT->InterfaceListLock = Lock_Init(); adapterT->InterfaceListLock = Lock_Init();
adapterT->pnpInterfaceList = singlylinkedlist_create(); adapterT->pnpInterfaceList = singlylinkedlist_create();
if (NULL == adapterT->InterfaceListLock) { if (NULL == adapterT->InterfaceListLock) {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
} }
adapterTag = adapterT; adapterTag = adapterT;
@ -50,7 +55,9 @@ exit:
return result; return result;
} }
void PnpAdapterManager_ReleaseAdapterInterfaces(PPNP_ADAPTER_TAG adapterTag) { void PnpAdapterManager_ReleaseAdapterInterfaces(
PPNP_ADAPTER_TAG adapterTag)
{
if (NULL == adapterTag) { if (NULL == adapterTag) {
return; return;
} }
@ -72,35 +79,40 @@ void PnpAdapterManager_ReleaseAdapterInterfaces(PPNP_ADAPTER_TAG adapterTag) {
} }
} }
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_GetAdapterFromManifest(const char* adapterId, PPNP_ADAPTER* adapter) IOTHUB_CLIENT_RESULT PnpAdapterManager_GetAdapterFromManifest(
const char* adapterId,
PPNP_ADAPTER* adapter)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_INVALID_ARG;
PPNP_ADAPTER pnpAdapter = NULL; PPNP_ADAPTER pnpAdapter = NULL;
for (int i = 0; i < PnpAdapterCount; i++) { for (int i = 0; i < PnpAdapterCount; i++) {
pnpAdapter = PNP_ADAPTER_MANIFEST[i]; pnpAdapter = PNP_ADAPTER_MANIFEST[i];
if (0 == strcmp(pnpAdapter->identity, adapterId)) if (0 == strcmp(pnpAdapter->identity, adapterId))
{ {
*adapter = pnpAdapter; *adapter = pnpAdapter;
result = DIGITALTWIN_CLIENT_OK; result = IOTHUB_CLIENT_OK;
} }
} }
// Validate Pnp Adapter Methods // Validate Pnp Adapter Methods
result = PnpAdapterManager_ValidatePnpAdapter(pnpAdapter); result = PnpAdapterManager_ValidatePnpAdapter(pnpAdapter);
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
LogError("PnpAdapter structure is not initialized properly"); LogError("PnpAdapter structure is not initialized properly");
} }
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateAdapter(const char* adapterId, PPNP_ADAPTER_CONTEXT_TAG* adapterContext, JSON_Value* config) IOTHUB_CLIENT_RESULT PnpAdapterManager_CreateAdapter(
const char* adapterId,
PPNP_ADAPTER_CONTEXT_TAG* adapterContext,
JSON_Value* config)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
PPNP_ADAPTER_CONTEXT_TAG pnpAdapterHandle = (PPNP_ADAPTER_CONTEXT_TAG)malloc(sizeof(PNP_ADAPTER_CONTEXT_TAG)); PPNP_ADAPTER_CONTEXT_TAG pnpAdapterHandle = (PPNP_ADAPTER_CONTEXT_TAG)malloc(sizeof(PNP_ADAPTER_CONTEXT_TAG));
if (pnpAdapterHandle == NULL) if (pnpAdapterHandle == NULL)
{ {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
LogError("Couldn't allocate memory for PNP_ADAPTER_CONTEXT_TAG"); LogError("Couldn't allocate memory for PNP_ADAPTER_CONTEXT_TAG");
goto exit; goto exit;
} }
@ -111,7 +123,7 @@ DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateAdapter(const char* adapterId,
pnpAdapterHandle->adapter = (PPNP_ADAPTER_TAG)malloc(sizeof(PNP_ADAPTER_TAG)); pnpAdapterHandle->adapter = (PPNP_ADAPTER_TAG)malloc(sizeof(PNP_ADAPTER_TAG));
if (pnpAdapterHandle->adapter == NULL) if (pnpAdapterHandle->adapter == NULL)
{ {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
LogError("Couldn't allocate memory for PNP_ADAPTER_TAG"); LogError("Couldn't allocate memory for PNP_ADAPTER_TAG");
goto exit; goto exit;
} }
@ -127,7 +139,7 @@ DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateAdapter(const char* adapterId,
pnpAdapterHandle->adapter->InterfaceListLock = Lock_Init(); pnpAdapterHandle->adapter->InterfaceListLock = Lock_Init();
pnpAdapterHandle->adapter->pnpInterfaceList = singlylinkedlist_create(); pnpAdapterHandle->adapter->pnpInterfaceList = singlylinkedlist_create();
if (NULL == pnpAdapterHandle->adapter->InterfaceListLock) { if (NULL == pnpAdapterHandle->adapter->InterfaceListLock) {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -149,7 +161,9 @@ exit:
return result; return result;
} }
bool PnpAdapterManager_AdapterCreated(PPNP_ADAPTER_MANAGER adapterMgr, const char* adapterId) bool PnpAdapterManager_AdapterCreated(
PPNP_ADAPTER_MANAGER adapterMgr,
const char* adapterId)
{ {
LIST_ITEM_HANDLE adapterListItem = singlylinkedlist_get_head_item(adapterMgr->PnpAdapterHandleList); LIST_ITEM_HANDLE adapterListItem = singlylinkedlist_get_head_item(adapterMgr->PnpAdapterHandleList);
@ -168,13 +182,16 @@ bool PnpAdapterManager_AdapterCreated(PPNP_ADAPTER_MANAGER adapterMgr, const cha
return false; return false;
} }
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateManager(PPNP_ADAPTER_MANAGER* adapterMgr, JSON_Value* config) { IOTHUB_CLIENT_RESULT PnpAdapterManager_CreateManager(
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; PPNP_ADAPTER_MANAGER* adapterMgr,
JSON_Value* config)
{
IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
PPNP_ADAPTER_MANAGER adapterManager = NULL; PPNP_ADAPTER_MANAGER adapterManager = NULL;
adapterManager = (PPNP_ADAPTER_MANAGER)malloc(sizeof(PNP_ADAPTER_MANAGER)); adapterManager = (PPNP_ADAPTER_MANAGER)malloc(sizeof(PNP_ADAPTER_MANAGER));
if (NULL == adapterManager) { if (NULL == adapterManager) {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -183,13 +200,10 @@ DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateManager(PPNP_ADAPTER_MANAGER*
JSON_Array* devices = Configuration_GetDevices(config); JSON_Array* devices = Configuration_GetDevices(config);
if (NULL == devices) { if (NULL == devices) {
LogError("No configured devices in the pnpbridge config"); LogError("No configured devices in the pnpbridge config");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
// Pre-allocate contiguous memory for maximum number of registerable devices
adapterManager->PnpInterfacesRegistrationList = calloc(json_array_get_count(devices), sizeof(DIGITALTWIN_INTERFACE_CLIENT_HANDLE));
for (size_t i = 0; i < json_array_get_count(devices); i++) { for (size_t i = 0; i < json_array_get_count(devices); i++) {
JSON_Object* device = json_array_get_object(devices, i); JSON_Object* device = json_array_get_object(devices, i);
const char* adapterId = json_object_dotget_string(device, PNP_CONFIG_ADAPTER_ID); const char* adapterId = json_object_dotget_string(device, PNP_CONFIG_ADAPTER_ID);
@ -202,7 +216,7 @@ DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateManager(PPNP_ADAPTER_MANAGER*
PPNP_ADAPTER_CONTEXT_TAG pnpAdapterHandle = NULL; PPNP_ADAPTER_CONTEXT_TAG pnpAdapterHandle = NULL;
result = PnpAdapterManager_CreateAdapter(adapterId, &pnpAdapterHandle, config); result = PnpAdapterManager_CreateAdapter(adapterId, &pnpAdapterHandle, config);
if (pnpAdapterHandle == NULL || result != DIGITALTWIN_CLIENT_OK) if (pnpAdapterHandle == NULL || result != IOTHUB_CLIENT_OK)
{ {
LogError("Adapter creation and initialization failed. Destroying all adapters previously created."); LogError("Adapter creation and initialization failed. Destroying all adapters previously created.");
goto exit; goto exit;
@ -225,7 +239,9 @@ exit:
return result; return result;
} }
void PnpAdapterManager_ReleaseManager(PPNP_ADAPTER_MANAGER adapterMgr) { void PnpAdapterManager_ReleaseManager(
PPNP_ADAPTER_MANAGER adapterMgr)
{
if (NULL != adapterMgr) if (NULL != adapterMgr)
{ {
LIST_ITEM_HANDLE adapterListItem = singlylinkedlist_get_head_item(adapterMgr->PnpAdapterHandleList); LIST_ITEM_HANDLE adapterListItem = singlylinkedlist_get_head_item(adapterMgr->PnpAdapterHandleList);
@ -248,17 +264,16 @@ void PnpAdapterManager_ReleaseManager(PPNP_ADAPTER_MANAGER adapterMgr) {
} }
singlylinkedlist_destroy(adapterMgr->PnpAdapterHandleList); singlylinkedlist_destroy(adapterMgr->PnpAdapterHandleList);
if (adapterMgr->PnpInterfacesRegistrationList)
{
free(adapterMgr->PnpInterfacesRegistrationList);
}
free(adapterMgr); free(adapterMgr);
} }
} }
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_GetAdapterHandle(PPNP_ADAPTER_MANAGER adapterMgr, const char* adapterIdentity, PPNP_ADAPTER_CONTEXT_TAG* adapterContext) IOTHUB_CLIENT_RESULT PnpAdapterManager_GetAdapterHandle(
PPNP_ADAPTER_MANAGER adapterMgr,
const char* adapterIdentity,
PPNP_ADAPTER_CONTEXT_TAG* adapterContext)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_INVALID_ARG;
if (NULL != adapterMgr) if (NULL != adapterMgr)
{ {
LIST_ITEM_HANDLE adapterListItem = singlylinkedlist_get_head_item(adapterMgr->PnpAdapterHandleList); LIST_ITEM_HANDLE adapterListItem = singlylinkedlist_get_head_item(adapterMgr->PnpAdapterHandleList);
@ -270,7 +285,7 @@ DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_GetAdapterHandle(PPNP_ADAPTER_MANAGE
if (!strcmp(adapterHandle->adapter->adapter->identity, adapterIdentity)) if (!strcmp(adapterHandle->adapter->adapter->identity, adapterIdentity))
{ {
*adapterContext = adapterHandle; *adapterContext = adapterHandle;
result = DIGITALTWIN_CLIENT_OK; result = IOTHUB_CLIENT_OK;
break; break;
} }
@ -282,14 +297,15 @@ DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_GetAdapterHandle(PPNP_ADAPTER_MANAGE
} }
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateInterfaces(PPNP_ADAPTER_MANAGER adapterMgr, JSON_Value* config) IOTHUB_CLIENT_RESULT PnpAdapterManager_CreateInterfaces(
PPNP_ADAPTER_MANAGER adapterMgr, JSON_Value* config)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
JSON_Array* devices = Configuration_GetDevices(config); JSON_Array* devices = Configuration_GetDevices(config);
if (NULL == devices) { if (NULL == devices) {
LogError("No configured devices in the pnpbridge config"); LogError("No configured devices in the pnpbridge config");
result = DIGITALTWIN_CLIENT_ERROR; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
@ -304,33 +320,21 @@ DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateInterfaces(PPNP_ADAPTER_MANAGE
result = PnpAdapterManager_GetAdapterHandle(adapterMgr, adapterId, &adapterHandle); result = PnpAdapterManager_GetAdapterHandle(adapterMgr, adapterId, &adapterHandle);
if (DIGITALTWIN_CLIENT_OK == result) if (IOTHUB_CLIENT_OK == result)
{ {
PPNPADAPTER_INTERFACE_TAG interfaceHandle = (PPNPADAPTER_INTERFACE_TAG)malloc(sizeof(PNPADAPTER_INTERFACE_TAG)); PPNPADAPTER_INTERFACE_TAG interfaceHandle = (PPNPADAPTER_INTERFACE_TAG)malloc(sizeof(PNPADAPTER_INTERFACE_TAG));
if (interfaceHandle != NULL) if (interfaceHandle != NULL)
{ {
DIGITALTWIN_INTERFACE_CLIENT_HANDLE digitalTwinInterfaceHandle;
interfaceHandle->interfaceName = interfaceName; interfaceHandle->interfaceName = interfaceName;
interfaceHandle->adapterIdentity = adapterHandle->adapter->adapter->identity; interfaceHandle->adapterIdentity = adapterHandle->adapter->adapter->identity;
result = adapterHandle->adapter->adapter->createPnpInterface(adapterHandle, interfaceName, deviceAdapterArgs, result = adapterHandle->adapter->adapter->createPnpInterface(adapterHandle, interfaceName, deviceAdapterArgs,
interfaceHandle, &digitalTwinInterfaceHandle); interfaceHandle);
if (result == DIGITALTWIN_CLIENT_OK) if (result == IOTHUB_CLIENT_OK)
{ {
if (digitalTwinInterfaceHandle != NULL) singlylinkedlist_add(adapterHandle->adapter->pnpInterfaceList, interfaceHandle);
{ adapterMgr->NumInterfaces++;
interfaceHandle->pnpInterfaceClient = digitalTwinInterfaceHandle;
singlylinkedlist_add(adapterHandle->adapter->pnpInterfaceList, interfaceHandle);
adapterMgr->PnpInterfacesRegistrationList[adapterMgr->NumInterfaces] = digitalTwinInterfaceHandle;
adapterMgr->NumInterfaces++;
}
else
{
LogError("The adapter returned from successful interface creation but interface client handle is invalid");
result = DIGITALTWIN_CLIENT_ERROR;
goto exit;
}
} }
else else
{ {
@ -341,7 +345,7 @@ DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_CreateInterfaces(PPNP_ADAPTER_MANAGE
} }
else else
{ {
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
} }
@ -351,27 +355,10 @@ exit:
return result; return result;
} }
DIGITALTWIN_CLIENT_RESULT PnPAdapterManager_RegisterInterfaces(PPNP_ADAPTER_MANAGER adapterMgr) IOTHUB_CLIENT_RESULT PnpAdapterManager_StartInterfaces(
PPNP_ADAPTER_MANAGER adapterMgr)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
if (NULL != adapterMgr)
{
LogInfo("Publishing %d Azure Pnp Interface(s)", adapterMgr->NumInterfaces);
result = PnpBridge_RegisterInterfaces(adapterMgr->PnpInterfacesRegistrationList, adapterMgr->NumInterfaces);
if (result != DIGITALTWIN_CLIENT_OK)
{
LogError("Registration failed.");
goto exit;
}
}
exit:
return result;
}
DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_StartInterfaces(PPNP_ADAPTER_MANAGER adapterMgr)
{
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK;
if (NULL != adapterMgr) if (NULL != adapterMgr)
{ {
LIST_ITEM_HANDLE adapterListItem = singlylinkedlist_get_head_item(adapterMgr->PnpAdapterHandleList); LIST_ITEM_HANDLE adapterListItem = singlylinkedlist_get_head_item(adapterMgr->PnpAdapterHandleList);
@ -384,6 +371,7 @@ DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_StartInterfaces(PPNP_ADAPTER_MANAGER
while (NULL != interfaceHandleItem) while (NULL != interfaceHandleItem)
{ {
PPNPADAPTER_INTERFACE_TAG interfaceHandle = (PPNPADAPTER_INTERFACE_TAG)singlylinkedlist_item_get_value(interfaceHandleItem); PPNPADAPTER_INTERFACE_TAG interfaceHandle = (PPNPADAPTER_INTERFACE_TAG)singlylinkedlist_item_get_value(interfaceHandleItem);
interfaceHandle->deviceClient = g_PnpBridge->IotHandle.u1.IotDevice.deviceHandle;
result = adapterHandle->adapter->adapter->startPnpInterface(adapterHandle, interfaceHandle); result = adapterHandle->adapter->adapter->startPnpInterface(adapterHandle, interfaceHandle);
interfaceHandleItem = singlylinkedlist_get_next_item(interfaceHandleItem); interfaceHandleItem = singlylinkedlist_get_next_item(interfaceHandleItem);
} }
@ -391,4 +379,170 @@ DIGITALTWIN_CLIENT_RESULT PnpAdapterManager_StartInterfaces(PPNP_ADAPTER_MANAGER
} }
} }
return result; return result;
}
IOTHUB_CLIENT_RESULT PnpAdapterManager_BuildComponentsInModel(
PPNP_ADAPTER_MANAGER adapterMgr)
{
IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
unsigned int componentNumber = 0;
if (NULL != adapterMgr)
{
adapterMgr->ComponentsInModel = malloc(adapterMgr->NumInterfaces * sizeof(char*));
if (NULL == adapterMgr->ComponentsInModel)
{
result = IOTHUB_CLIENT_ERROR;
goto exit;
}
LIST_ITEM_HANDLE adapterListItem = singlylinkedlist_get_head_item(adapterMgr->PnpAdapterHandleList);
while (NULL != adapterListItem) {
PPNP_ADAPTER_CONTEXT_TAG adapterHandle = (PPNP_ADAPTER_CONTEXT_TAG)singlylinkedlist_item_get_value(adapterListItem);
LIST_ITEM_HANDLE interfaceHandleItem = singlylinkedlist_get_head_item(adapterHandle->adapter->pnpInterfaceList);
while (NULL != interfaceHandleItem)
{
PPNPADAPTER_INTERFACE_TAG interfaceHandle = (PPNPADAPTER_INTERFACE_TAG)singlylinkedlist_item_get_value(interfaceHandleItem);
mallocAndStrcpy_s((char**)&adapterMgr->ComponentsInModel[componentNumber++], interfaceHandle->interfaceName);
interfaceHandleItem = singlylinkedlist_get_next_item(interfaceHandleItem);
}
adapterListItem = singlylinkedlist_get_next_item(adapterListItem);
}
if (componentNumber != adapterMgr->NumInterfaces)
{
result = IOTHUB_CLIENT_ERROR;
goto exit;
}
}
exit:
if (result != IOTHUB_CLIENT_OK && adapterMgr != NULL && adapterMgr->ComponentsInModel != NULL)
{
for (unsigned int i = 0; i < adapterMgr->NumInterfaces; i++)
{
free(adapterMgr->ComponentsInModel[i]);
}
free (adapterMgr->ComponentsInModel);
}
return result;
}
int PnpAdapterManager_DeviceMethodCallback(
const char* methodName,
const unsigned char* payload,
size_t size,
unsigned char** response,
size_t* responseSize,
void* userContextCallback)
{
const char *componentName;
size_t componentNameSize;
const char *pnpCommandName;
char* jsonStr = NULL;
JSON_Value* commandValue = NULL;
int result = PNP_STATUS_SUCCESS;
bool processCommandRouted = false;
// PnP APIs do not set userContextCallback for device method callbacks, ignore this
AZURE_UNREFERENCED_PARAMETER(userContextCallback);
// Parse the methodName into its PnP componentName and pnpCommandName.
PnPHelper_ParseCommandName(methodName, (const unsigned char**) (&componentName), &componentNameSize, &pnpCommandName);
// Parse the JSON of the payload request.
if ((jsonStr = PnPHelper_CopyPayloadToString(payload, size)) == NULL)
{
LogError("Unable to allocate twin buffer");
result = PNP_STATUS_INTERNAL_ERROR;
}
else if ((commandValue = json_parse_string(jsonStr)) == NULL)
{
LogError("Unable to parse twin JSON");
result = PNP_STATUS_INTERNAL_ERROR;
}
else
{
if (componentName != NULL)
{
LogInfo("Received PnP command for component=%.*s, command=%s", (int)componentNameSize, componentName, pnpCommandName);
if ((g_PnpBridge != NULL) && (PNP_BRIDGE_INITIALIZED == g_PnpBridgeState) && (g_PnpBridge->PnpMgr != NULL))
{
LIST_ITEM_HANDLE adapterListItem = singlylinkedlist_get_head_item(g_PnpBridge->PnpMgr->PnpAdapterHandleList);
while (NULL != adapterListItem && !processCommandRouted) {
PPNP_ADAPTER_CONTEXT_TAG adapterHandle = (PPNP_ADAPTER_CONTEXT_TAG)singlylinkedlist_item_get_value(adapterListItem);
LIST_ITEM_HANDLE interfaceHandleItem = singlylinkedlist_get_head_item(adapterHandle->adapter->pnpInterfaceList);
while (NULL != interfaceHandleItem)
{
PPNPADAPTER_INTERFACE_TAG interfaceHandle = (PPNPADAPTER_INTERFACE_TAG)singlylinkedlist_item_get_value(interfaceHandleItem);
if (0 == strcmp(componentName, interfaceHandle->interfaceName))
{
result = adapterHandle->adapter->adapter->processCommand(interfaceHandle, pnpCommandName, commandValue, response, responseSize);
processCommandRouted = true;
break;
}
interfaceHandleItem = singlylinkedlist_get_next_item(interfaceHandleItem);
}
adapterListItem = singlylinkedlist_get_next_item(adapterListItem);
}
}
}
}
return result;
}
void PnpAdapterManager_DeviceTwinCallback(
DEVICE_TWIN_UPDATE_STATE updateState,
const unsigned char* payload,
size_t size,
void* userContextCallback)
{
// Invoke PnPHelper_ProcessTwinData to actualy process the data. PnPHelper_ProcessTwinData uses a visitor pattern to parse
// the JSON and then visit each property, invoking PnpAdapterManager_RoutePropertyCallback on each element.
if (PnPHelper_ProcessTwinData(updateState, payload, size, g_PnpBridge->PnpMgr->ComponentsInModel,
g_PnpBridge->PnpMgr->NumInterfaces, PnpAdapterManager_RoutePropertyCallback, userContextCallback) == false)
{
// If we're unable to parse the JSON for any reason (typically because the JSON is malformed or we ran out of memory)
// there is no action we can take beyond logging.
LogError("Unable to process twin json. Ignoring any desired property update requests");
}
}
// PnpAdapterManager_RoutePropertyCallback is the callback function that the PnP helper layer invokes per property update.
static void PnpAdapterManager_RoutePropertyCallback(
const char* componentName,
const char* propertyName,
JSON_Value* propertyValue,
int version,
void* userContextCallback)
{
bool propertyUpdateRouted = false;
if ((g_PnpBridge != NULL) && (PNP_BRIDGE_INITIALIZED == g_PnpBridgeState) && (g_PnpBridge->PnpMgr != NULL))
{
LIST_ITEM_HANDLE adapterListItem = singlylinkedlist_get_head_item(g_PnpBridge->PnpMgr->PnpAdapterHandleList);
while (NULL != adapterListItem && !propertyUpdateRouted) {
PPNP_ADAPTER_CONTEXT_TAG adapterHandle = (PPNP_ADAPTER_CONTEXT_TAG)singlylinkedlist_item_get_value(adapterListItem);
LIST_ITEM_HANDLE interfaceHandleItem = singlylinkedlist_get_head_item(adapterHandle->adapter->pnpInterfaceList);
while (NULL != interfaceHandleItem)
{
PPNPADAPTER_INTERFACE_TAG interfaceHandle = (PPNPADAPTER_INTERFACE_TAG)singlylinkedlist_item_get_value(interfaceHandleItem);
if (0 == strcmp(componentName, interfaceHandle->interfaceName))
{
adapterHandle->adapter->adapter->processPropertyUpdate(interfaceHandle, propertyName, propertyValue, version, userContextCallback);
propertyUpdateRouted = true;
break;
}
interfaceHandleItem = singlylinkedlist_get_next_item(interfaceHandleItem);
}
adapterListItem = singlylinkedlist_get_next_item(adapterListItem);
}
}
} }

Просмотреть файл

@ -10,18 +10,14 @@
#include "pnpbridgeh.h" #include "pnpbridgeh.h"
#include <iothub_client.h> #include <iothub_client.h>
// Globals PNP bridge instance
PPNP_BRIDGE g_PnpBridge = NULL;
PNP_BRIDGE_STATE g_PnpBridgeState = PNP_BRIDGE_UNINITIALIZED;
bool g_PnpBridgeShutdown = false;
DIGITALTWIN_CLIENT_RESULT IOTHUB_CLIENT_RESULT
PnpBridge_Initialize( PnpBridge_Initialize(
PPNP_BRIDGE* PnpBridge, PPNP_BRIDGE* PnpBridge,
const char * ConfigFilePath const char * ConfigFilePath
) )
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
PPNP_BRIDGE pbridge = NULL; PPNP_BRIDGE pbridge = NULL;
JSON_Value* config = NULL; JSON_Value* config = NULL;
bool lockAcquired = false; bool lockAcquired = false;
@ -33,21 +29,21 @@ PnpBridge_Initialize(
pbridge = (PPNP_BRIDGE) calloc(1, sizeof(PNP_BRIDGE)); pbridge = (PPNP_BRIDGE) calloc(1, sizeof(PNP_BRIDGE));
if (NULL == pbridge) { if (NULL == pbridge) {
LogError("Failed to allocate memory for PnpBridge global"); LogError("Failed to allocate memory for PnpBridge global");
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
pbridge->ExitCondition = Condition_Init(); pbridge->ExitCondition = Condition_Init();
if (NULL == pbridge->ExitCondition) { if (NULL == pbridge->ExitCondition) {
LogError("Failed to init ExitCondition"); LogError("Failed to init ExitCondition");
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
pbridge->ExitLock = Lock_Init(); pbridge->ExitLock = Lock_Init();
if (NULL == pbridge->ExitLock) { if (NULL == pbridge->ExitLock) {
LogError("Failed to init ExitLock lock"); LogError("Failed to init ExitLock lock");
result = DIGITALTWIN_CLIENT_ERROR_OUT_OF_MEMORY; result = IOTHUB_CLIENT_ERROR;
goto exit; goto exit;
} }
Lock(pbridge->ExitLock); Lock(pbridge->ExitLock);
@ -55,35 +51,25 @@ PnpBridge_Initialize(
// Get the JSON VALUE of configuration file // Get the JSON VALUE of configuration file
result = PnpBridgeConfig_GetJsonValueFromConfigFile(ConfigFilePath, &config); result = PnpBridgeConfig_GetJsonValueFromConfigFile(ConfigFilePath, &config);
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
LogError("Failed to retrieve the bridge configuration from specified file location."); LogError("Failed to retrieve the bridge configuration from specified file location.");
goto exit; goto exit;
} }
// Check if config file has REQUIRED parameters // Check if config file has REQUIRED parameters
result = PnpBridgeConfig_RetrieveConfiguration(config, &pbridge->Configuration); result = PnpBridgeConfig_RetrieveConfiguration(config, &pbridge->Configuration);
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
LogError("Config file is invalid"); LogError("Config file is invalid");
goto exit; goto exit;
} }
// Connect to Iot Hub and create a PnP device client handle
{
result = IotComms_InitializeIotHandle(&pbridge->IotHandle, pbridge->Configuration.TraceOn, pbridge->Configuration.ConnParams);
if (DIGITALTWIN_CLIENT_OK != result) {
LogError("IotComms_InitializeIotHandle failed\n");
result = DIGITALTWIN_CLIENT_ERROR;
goto exit;
}
}
*PnpBridge = pbridge; *PnpBridge = pbridge;
g_PnpBridgeState = PNP_BRIDGE_INITIALIZED; g_PnpBridgeState = PNP_BRIDGE_INITIALIZED;
} }
exit: exit:
{ {
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
if (lockAcquired) { if (lockAcquired) {
Unlock(pbridge->ExitLock); Unlock(pbridge->ExitLock);
} }
@ -95,6 +81,22 @@ exit:
return result; return result;
} }
IOTHUB_CLIENT_RESULT
PnpBridge_RegisterIoTHubHandle()
{
IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
result = IotComms_InitializeIotHandle(&g_PnpBridge->IotHandle, g_PnpBridge->Configuration.TraceOn, g_PnpBridge->Configuration.ConnParams);
if (IOTHUB_CLIENT_OK != result) {
LogError("IotComms_InitializeIotHandle failed\n");
result = IOTHUB_CLIENT_ERROR;
goto exit;
}
exit:
return result;
}
void void
PnpBridge_Release( PnpBridge_Release(
PPNP_BRIDGE pnpBridge PPNP_BRIDGE pnpBridge
@ -126,68 +128,55 @@ PnpBridge_Release(
} }
} }
DIGITALTWIN_CLIENT_RESULT
PnpBridge_RegisterInterfaces(
DIGITALTWIN_INTERFACE_CLIENT_HANDLE* interfaces,
unsigned int interfaceCount
)
{
DIGITALTWIN_CLIENT_RESULT result;
PPNP_BRIDGE pnpBridge = g_PnpBridge;
result = IotComms_RegisterPnPInterfaces(&pnpBridge->IotHandle,
pnpBridge->Configuration.ConnParams->RootInterfaceModelId,
interfaces,
interfaceCount);
return result;
}
int int
PnpBridge_Main(const char * ConfigurationFilePath) PnpBridge_Main(const char * ConfigurationFilePath)
{ {
DIGITALTWIN_CLIENT_RESULT result = DIGITALTWIN_CLIENT_OK; IOTHUB_CLIENT_RESULT result = IOTHUB_CLIENT_OK;
PPNP_BRIDGE pnpBridge = NULL; PPNP_BRIDGE pnpBridge = NULL;
{ {
LogInfo("Starting Azure PnpBridge"); LogInfo("Starting Azure PnpBridge");
if (IoTHub_Init() != 0) {
LogError("IoTHub_Init failed\n");
result = DIGITALTWIN_CLIENT_ERROR;
goto exit;
}
result = PnpBridge_Initialize(&pnpBridge, ConfigurationFilePath); result = PnpBridge_Initialize(&pnpBridge, ConfigurationFilePath);
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
LogError("PnpBridge_Initialize failed: %d", result); LogError("PnpBridge_Initialize failed: %d", result);
goto exit; goto exit;
} }
g_PnpBridge = pnpBridge; g_PnpBridge = pnpBridge;
LogInfo("Connected to Azure IoT Hub"); LogInfo("Building Pnp Bridge Adapter Manager & Adapters");
// Create all the adapters that are required by configured devices // Create all the adapters that are required by configured devices
result = PnpAdapterManager_CreateManager(&pnpBridge->PnpMgr, pnpBridge->Configuration.JsonConfig); result = PnpAdapterManager_CreateManager(&pnpBridge->PnpMgr, pnpBridge->Configuration.JsonConfig);
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
LogError("PnpAdapterManager_Create failed: %d", result); LogError("PnpAdapterManager_CreateManager failed: %d", result);
goto exit; goto exit;
} }
result = PnpAdapterManager_CreateInterfaces(pnpBridge->PnpMgr, pnpBridge->Configuration.JsonConfig); result = PnpAdapterManager_CreateInterfaces(pnpBridge->PnpMgr, pnpBridge->Configuration.JsonConfig);
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
LogError("PnpAdapterManager_CreateInterfaces failed: %d", result); LogError("PnpAdapterManager_CreateInterfaces failed: %d", result);
goto exit; goto exit;
} }
result = PnPAdapterManager_RegisterInterfaces(pnpBridge->PnpMgr); result = PnpAdapterManager_BuildComponentsInModel(pnpBridge->PnpMgr);
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
LogError("PnPAdapterManager_RegisterInterfaces failed: %d", result); LogError("PnpAdapterManager_BuildComponentsInModel failed: %d", result);
goto exit; goto exit;
} }
result = PnpBridge_RegisterIoTHubHandle();
if (IOTHUB_CLIENT_OK != result) {
LogError("PnpAdapterManager_BuildComponentsInModel failed: %d", result);
goto exit;
}
LogInfo("Connected to Azure IoT Hub");
result = PnpAdapterManager_StartInterfaces(pnpBridge->PnpMgr); result = PnpAdapterManager_StartInterfaces(pnpBridge->PnpMgr);
if (DIGITALTWIN_CLIENT_OK != result) { if (IOTHUB_CLIENT_OK != result) {
LogError("PnpAdapterManager_StartInterfaces failed: %d", result); LogError("PnpAdapterManager_StartInterfaces failed: %d", result);
goto exit; goto exit;
} }
@ -202,13 +191,11 @@ PnpBridge_Main(const char * ConfigurationFilePath)
} }
exit: exit:
{ {
// Destroy the DigitalTwinClient and recreate it
IotComms_DigitalTwinClient_Destroy(&pnpBridge->IotHandle);
g_PnpBridge = NULL;
if (pnpBridge) { if (pnpBridge) {
PnpBridge_Release(pnpBridge); PnpBridge_Release(pnpBridge);
} }
g_PnpBridge = NULL;
} }
return result; return result;
@ -251,7 +238,7 @@ PnpBridge_UploadToBlobAsync(
if (!g_PnpBridge->IotHandle.DeviceClientInitialized) if (!g_PnpBridge->IotHandle.DeviceClientInitialized)
{ {
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
} }
handle = g_PnpBridge->IotHandle.IsModule ? g_PnpBridge->IotHandle.u1.IotModule.moduleHandle : handle = g_PnpBridge->IotHandle.IsModule ? g_PnpBridge->IotHandle.u1.IotModule.moduleHandle :
@ -261,7 +248,7 @@ PnpBridge_UploadToBlobAsync(
(NULL != pbData && cbData == 0) || (NULL != pbData && cbData == 0) ||
NULL == iotHubClientFileUploadCallback) NULL == iotHubClientFileUploadCallback)
{ {
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
} }
iotResult = IoTHubClient_UploadToBlobAsync(handle, iotResult = IoTHubClient_UploadToBlobAsync(handle,
@ -273,16 +260,16 @@ PnpBridge_UploadToBlobAsync(
switch (iotResult) switch (iotResult)
{ {
case IOTHUB_CLIENT_OK: case IOTHUB_CLIENT_OK:
return DIGITALTWIN_CLIENT_OK; return IOTHUB_CLIENT_OK;
break; break;
case IOTHUB_CLIENT_INVALID_ARG: case IOTHUB_CLIENT_INVALID_ARG:
case IOTHUB_CLIENT_INVALID_SIZE: case IOTHUB_CLIENT_INVALID_SIZE:
return DIGITALTWIN_CLIENT_ERROR_INVALID_ARG; return IOTHUB_CLIENT_INVALID_ARG;
break; break;
case IOTHUB_CLIENT_INDEFINITE_TIME: case IOTHUB_CLIENT_INDEFINITE_TIME:
case IOTHUB_CLIENT_ERROR: case IOTHUB_CLIENT_ERROR:
default: default:
return DIGITALTWIN_CLIENT_ERROR; return IOTHUB_CLIENT_ERROR;
break; break;
} }
} }