зеркало из
1
0
Форкнуть 0

Update cloudtodevice from sdk to api

This commit is contained in:
Elsie Ju 2022-09-12 15:55:18 -07:00
Родитель 6b1f744db2
Коммит 556be706cd
6 изменённых файлов: 53 добавлений и 45 удалений

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

@ -7,7 +7,6 @@ export const PLATFORMS = {
};
export const MESSAGE_CHANNELS = {
DEVICE_SEND_MESSAGE: 'device_sendMessage',
DIRECTORY_GET_DIRECTORIES: 'directory_getDirectories',
EVENTHUB_START_MONITORING: 'eventhub_startMonitoring',
EVENTHUB_STOP_MONITORING: 'eventhub_stopMonitoring',

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

@ -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 '../dist/server/serverElectron';
@ -32,7 +31,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);
}

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

@ -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[]) => {

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

@ -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}`,
@ -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);
});
});
@ -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,

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

@ -3,6 +3,7 @@
* Licensed under the MIT License
**********************************************************/
import {
CloudToDeviceMessageParameters,
FetchDeviceTwinParameters,
InvokeMethodParameters,
FetchDevicesParameters,
@ -10,8 +11,7 @@ import {
FetchDeviceParameters,
DeleteDevicesParameters,
AddDeviceParameters,
UpdateDeviceParameters,
CloudToDeviceMessageParameters
UpdateDeviceParameters
} from '../parameters/deviceParameters';
import {
HEADERS,
@ -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';
const PAGE_SIZE = 100;
@ -99,16 +100,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();
const authorization = connectionInfo.sasToken;
const uri = `https://${connectionInfo.connectionInfo.hostName}/devices/${encodeURIComponent(deviceId)}/messages/deviceBound?api-version=${HUB_DATA_PLANE_API_VERSION}`;
await api.sendMessageToDevice({
connectionString: connectionInfo.connectionString,
deviceId: parameters.deviceId,
messageBody: parameters.body,
messageProperties: parameters.properties
});
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> => {

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

@ -55,4 +55,4 @@ export const deviceEventsReducer = reducerWithInitialState<DeviceEventsStateInte
return state.merge({
payload: []
});
});
});