Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update cloudtodevice from sdk to api #547

Merged
merged 3 commits into from
Sep 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion public/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export const MESSAGE_CHANNELS = {
AUTHENTICATION_GET_PROFILE_TOKEN: 'authentication_get_profile_token',
AUTHENTICATION_LOGIN: 'authentication_login',
AUTHENTICATION_LOGOUT: 'authentication_logout',
DEVICE_SEND_MESSAGE: 'device_sendMessage',
DIRECTORY_GET_DIRECTORIES: 'directory_getDirectories',
EVENTHUB_START_MONITORING: 'eventhub_startMonitoring',
EVENTHUB_STOP_MONITORING: 'eventhub_stopMonitoring',
Expand Down
2 changes: 0 additions & 2 deletions public/contextBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@ import { contextBridge } from 'electron';
import { generateSettingsInterface } from './factories/settingsInterfaceFactory';
import { generateDirectoryInterface } from './factories/directoryInterfaceFactory';
import { generateModelRepositoryInterface } from './factories/modelRepositoryInterfaceFactory';
import { generateDeviceInterface } from './factories/deviceInterfaceFactory';
import { generateEventHubInterface } from './factories/eventHubInterfaceFactory';
import { generateAuthenticationInterface } from './factories/authenticationInterfaceFactory';
import { API_INTERFACES } from './constants';

contextBridge.exposeInMainWorld(API_INTERFACES.DEVICE, generateDeviceInterface());
contextBridge.exposeInMainWorld(API_INTERFACES.DIRECTORY, generateDirectoryInterface());
contextBridge.exposeInMainWorld(API_INTERFACES.EVENTHUB, generateEventHubInterface());
contextBridge.exposeInMainWorld(API_INTERFACES.MODEL_DEFINITION, generateModelRepositoryInterface());
Expand Down
2 changes: 0 additions & 2 deletions public/electron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { PLATFORMS, MESSAGE_CHANNELS } from './constants';
import { onSettingsHighContrast } from './handlers/settingsHandler';
import { onGetInterfaceDefinition } from './handlers/modelRepositoryHandler';
import { onGetDirectories } from './handlers/directoryHandler';
import { onSendMessageToDevice } from './handlers/deviceHandler';
import { onStartMonitoring, onStopMonitoring } from './handlers/eventHubHandler';
import { formatError } from './utils/errorHelper';
import { AuthProvider } from './utils/authProvider';
Expand All @@ -34,7 +33,6 @@ class Main {
Main.registerHandler(MESSAGE_CHANNELS.SETTING_HIGH_CONTRAST, onSettingsHighContrast);
Main.registerHandler(MESSAGE_CHANNELS.MODEL_REPOSITORY_GET_DEFINITION, onGetInterfaceDefinition);
Main.registerHandler(MESSAGE_CHANNELS.DIRECTORY_GET_DIRECTORIES, onGetDirectories);
Main.registerHandler(MESSAGE_CHANNELS.DEVICE_SEND_MESSAGE, onSendMessageToDevice);
Main.registerHandler(MESSAGE_CHANNELS.EVENTHUB_START_MONITORING, onStartMonitoring);
Main.registerHandler(MESSAGE_CHANNELS.EVENTHUB_STOP_MONITORING, onStopMonitoring);
Main.registerHandler(MESSAGE_CHANNELS.AUTHENTICATION_LOGIN, Main.onLogin);
Expand Down
15 changes: 0 additions & 15 deletions public/factories/deviceInterfaceFactory.ts

This file was deleted.

19 changes: 1 addition & 18 deletions public/handlers/deviceHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,8 @@
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License
**********************************************************/
import { IpcMainInvokeEvent } from 'electron';
import { Client } from 'azure-iothub';
import { Message as CloudToDeviceMessage } from 'azure-iot-common';
import { SendMessageToDeviceParameters, MessageProperty } from '../interfaces/deviceInterface';

export const onSendMessageToDevice = async (event: IpcMainInvokeEvent, params: SendMessageToDeviceParameters): Promise<void> => {
const { deviceId, messageProperties, messageBody, connectionString } = params;
const hubClient = Client.fromConnectionString(connectionString);

try {
const message = new CloudToDeviceMessage(messageBody);
addPropertiesToCloudToDeviceMessage(message, messageProperties || []);

await hubClient.open();
await hubClient.send(deviceId, message);
} finally {
await hubClient.close();
}
};
import { MessageProperty } from '../interfaces/deviceInterface';

// tslint:disable-next-line:cyclomatic-complexity
export const addPropertiesToCloudToDeviceMessage = (message: CloudToDeviceMessage, properties: MessageProperty[]) => {
Expand Down
37 changes: 25 additions & 12 deletions src/app/api/services/devicesService.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ describe('deviceTwinService', () => {

const connectionInformation = mockDataPlaneConnectionHelper();
const dataPlaneRequest: DataplaneService.DataPlaneRequest = {
apiVersion: HUB_DATA_PLANE_API_VERSION,
apiVersion: HUB_DATA_PLANE_API_VERSION,
hostName: connectionInformation.connectionInfo.hostName,
httpMethod: HTTP_OPERATION_TYPES.Get,
path: `twins/${deviceId}`,
Expand Down Expand Up @@ -242,18 +242,31 @@ describe('deviceTwinService', () => {
};

it('calls sendMessageToDevice with expected parameters', async () => {
const sendMessageToDevice = jest.fn();
jest.spyOn(interfaceUtils, 'getDeviceInterface').mockReturnValue({
sendMessageToDevice
});

jest.spyOn(DataplaneService, 'dataPlaneConnectionHelper').mockResolvedValue({
connectionInfo, connectionString, sasToken});

const fetch = jest.spyOn(window, "fetch").mockResolvedValue({
json: () => {
return {};
},
ok: true,
} as any);

await DevicesService.cloudToDeviceMessage(parameters);
expect(sendMessageToDevice).toBeCalledWith({
connectionString,
deviceId: 'deviceId',
messageBody: 'body',
messageProperties: []
});

const resourceUrl = `https://test-string.azure-devices.net/devices/deviceId/messages/deviceBound?api-version=2020-06-30-preview`;
const serviceRequestParams = {
body: 'body',
cache: 'no-cache',
headers: {
'authorization': `testSasToken`,
['Content-Encoding']: 'utf-8'
},
method: HTTP_OPERATION_TYPES.Post
};

expect(fetch).toHaveBeenLastCalledWith(resourceUrl, serviceRequestParams);
});
});

Expand Down Expand Up @@ -290,7 +303,7 @@ describe('deviceTwinService', () => {

const connectionInformation = mockDataPlaneConnectionHelper();
const dataPlaneRequest: DataplaneService.DataPlaneRequest = {
apiVersion: HUB_DATA_PLANE_API_VERSION,
apiVersion: HUB_DATA_PLANE_API_VERSION,
body: JSON.stringify(deviceIdentity),
hostName: connectionInformation.connectionInfo.hostName,
httpMethod: HTTP_OPERATION_TYPES.Put,
Expand Down
39 changes: 27 additions & 12 deletions src/app/api/services/devicesService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
* Licensed under the MIT License
**********************************************************/
import {
CloudToDeviceMessageParameters,
FetchDeviceTwinParameters,
InvokeMethodParameters,
FetchDevicesParameters,
MonitorEventsParameters,
FetchDeviceParameters,
DeleteDevicesParameters,
AddDeviceParameters,
UpdateDeviceParameters,
CloudToDeviceMessageParameters
UpdateDeviceParameters
} from '../parameters/deviceParameters';
import {
HEADERS,
Expand All @@ -23,8 +23,9 @@ import { Message } from '../models/messages';
import { Twin, Device, DataPlaneResponse } from '../models/device';
import { DeviceIdentity } from '../models/deviceIdentity';
import { dataPlaneConnectionHelper, dataPlaneResponseHelper, request, DATAPLANE_CONTROLLER_ENDPOINT, DataPlaneRequest } from './dataplaneServiceHelper';
import { getDeviceInterface, getEventHubInterface } from '../shared/interfaceUtils';
import { getEventHubInterface } from '../shared/interfaceUtils';
import { parseEventHubMessage } from './eventHubMessageHelper';
import { HttpError } from '../models/httpError';
import { AppInsightsClient } from '../../shared/appTelemetry/appInsightsClient';
import { TELEMETRY_EVENTS } from '../../constants/telemetry';

Expand Down Expand Up @@ -101,16 +102,30 @@ export const invokeDirectMethod = async (parameters: InvokeMethodParameters): Pr
return result && result.body;
};

export const cloudToDeviceMessage = async (parameters: CloudToDeviceMessageParameters) => {
export const cloudToDeviceMessage = async (params: CloudToDeviceMessageParameters) => {
const { deviceId, body, properties } = params;
const connectionInfo = await dataPlaneConnectionHelper();
const api = getDeviceInterface();

await api.sendMessageToDevice({
connectionString: connectionInfo.connectionString,
deviceId: parameters.deviceId,
messageBody: parameters.body,
messageProperties: parameters.properties
});
const authorization = connectionInfo.sasToken;
const uri = `https://${connectionInfo.connectionInfo.hostName}/devices/${encodeURIComponent(deviceId)}/messages/deviceBound?api-version=${HUB_DATA_PLANE_API_VERSION}`;

const formattedProperties: Record<string, string> = {};
properties.forEach(s => formattedProperties[`iothub-app-${s.key}`] = s.value);

const requestParams: RequestInit = {
body,
cache: 'no-cache',
headers: {
...formattedProperties,
authorization,
['Content-Encoding']: 'utf-8'
},
method: HTTP_OPERATION_TYPES.Post
};

const response = await fetch(uri, requestParams);
if (!response.ok) {
throw new HttpError(response.status);
}
};

export const addDevice = async (parameters: AddDeviceParameters): Promise<DeviceIdentity> => {
Expand Down