This commit is contained in:
formulahendry 2016-10-28 13:46:08 +08:00
Коммит cc34cdd8ad
17 изменённых файлов: 515 добавлений и 0 удалений

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

@ -0,0 +1,2 @@
out
node_modules

28
.vscode/launch.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,28 @@
// A launch configuration that compiles the extension and then opens it inside a new window
{
"version": "0.1.0",
"configurations": [
{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}" ],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out/src",
"preLaunchTask": "npm"
},
{
"name": "Launch Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}", "--extensionTestsPath=${workspaceRoot}/out/test" ],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out/test",
"preLaunchTask": "npm"
}
]
}

10
.vscode/settings.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,10 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false // set this to true to hide the "out" folder with the compiled JS files
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
"typescript.tsdk": "./node_modules/typescript/lib" // we want to use the TS server from our node_modules folder to control its version
}

30
.vscode/tasks.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,30 @@
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process
// A task runner that calls a custom npm script that compiles the extension.
{
"version": "0.1.0",
// we want to run npm
"command": "npm",
// the command is a shell script
"isShellCommand": true,
// show the output window only if unrecognized errors occur.
"showOutput": "silent",
// we run the custom script "compile" as defined in package.json
"args": ["run", "compile", "--loglevel", "silent"],
// The tsc compiler is started in watching mode
"isWatching": true,
// use the standard tsc in watch mode problem matcher to find compile problems in the output.
"problemMatcher": "$tsc-watch"
}

9
.vscodeignore Normal file
Просмотреть файл

@ -0,0 +1,9 @@
.vscode/**
typings/**
out/test/**
test/**
src/**
**/*.map
.gitignore
tsconfig.json
vsc-extension-quickstart.md

65
README.md Normal file
Просмотреть файл

@ -0,0 +1,65 @@
# azure-iot-toolkit README
This is the README for your extension "azure-iot-toolkit". After writing up a brief description, we recommend including the following sections.
## Features
Describe specific features of your extension including screenshots of your extension in action. Image paths are relative to this README file.
For example if there is an image subfolder under your extension project workspace:
\!\[feature X\]\(images/feature-x.png\)
> Tip: Many popular extensions utilize animations. This is an excellent way to show off your extension! We recommend short, focused animations that are easy to follow.
## Requirements
If you have any requirements or dependencies, add a section describing those and how to install and configure them.
## Extension Settings
Include if your extension adds any VS Code settings through the `contributes.configuration` extension point.
For example:
This extension contributes the following settings:
* `myExtension.enable`: enable/disable this extension
* `myExtension.thing`: set to `blah` to do something
## Known Issues
Calling out known issues can help limit users opening duplicate issues against your extension.
## Release Notes
Users appreciate release notes as you update your extension.
### 1.0.0
Initial release of ...
### 1.0.1
Fixed issue #.
### 1.1.0
Added features X, Y, and Z.
-----------------------------------------------------------------------------------------------------------
## Working with Markdown
**Note:** You can author your README using Visual Studio Code. Here are some useful editor keyboard shortcuts:
* Split the editor (`Cmd+\` on OSX or `Ctrl+\` on Windows and Linux)
* Toggle preview (`Shift+CMD+V` on OSX or `Shift+Ctrl+V` on Windows and Linux)
* Press `Ctrl+Space` (Windows, Linux) or `Cmd+Space` (OSX) to see a list of Markdown snippets
### For more information
* [Visual Studio Code's Markdown Support](http://code.visualstudio.com/docs/languages/markdown)
* [Markdown Syntax Reference](https://help.github.com/articles/markdown-basics/)
**Enjoy!**

105
package.json Normal file
Просмотреть файл

@ -0,0 +1,105 @@
{
"name": "azure-iot-toolkit",
"displayName": "Azure IoT Toolkit",
"description": "Send messages to Azure IoT Hub, monitor device-to-cloud messages",
"version": "0.0.1",
"publisher": "formulahendry",
"engines": {
"vscode": "^1.0.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:azure-iot-explorer.sendD2CMessage",
"onCommand:azure-iot-explorer.startMonitoringMessage"
],
"main": "./out/src/extension",
"contributes": {
"commands": [
{
"command": "azure-iot-explorer.sendD2CMessage",
"title": "Send message to IoT Hub"
},
{
"command": "azure-iot-explorer.startMonitoringMessage",
"title": "Start monitoring"
},
{
"command": "azure-iot-explorer.stopMonitoringMessage",
"title": "Stop monitoring"
}
],
"keybindings": [
{
"command": "azure-iot-explorer.sendD2CMessage",
"key": "ctrl+alt+f9"
},
{
"command": "azure-iot-explorer.startMonitoringMessage",
"key": "ctrl+alt+f10"
},
{
"command": "azure-iot-explorer.stopMonitoringMessage",
"key": "ctrl+alt+f11"
}
],
"menus": {
"editor/context": [
{
"command": "azure-iot-explorer.sendD2CMessage",
"group": "azure-iot-explorer"
},
{
"command": "azure-iot-explorer.startMonitoringMessage",
"group": "azure-iot-explorer"
},
{
"command": "azure-iot-explorer.stopMonitoringMessage",
"group": "azure-iot-explorer"
}
]
},
"configuration": {
"type": "object",
"title": "Azure IoT Explorer configuration",
"properties": {
"azure-iot-explorer.deviceConnectionString": {
"type": "string",
"default": "<<insert your Device Connection String>>",
"description": "Device Connection String"
},
"azure-iot-explorer.iotHubConnectionString": {
"type": "string",
"default": "<<insert your IoT Hub Connection String>>",
"description": "IoT Hub Connection String"
},
"azure-iot-explorer.consumerGroup": {
"type": "string",
"default": "$Default",
"description": "IoT Hub Consumer Group"
},
"azure-iot-explorer.enableAppInsights": {
"type": "boolean",
"default": true,
"description": "Whether to enable AppInsights to track anonymous telemetry data."
}
}
}
},
"scripts": {
"vscode:prepublish": "node ./node_modules/vscode/bin/compile",
"compile": "node ./node_modules/vscode/bin/compile -watch -p ./",
"postinstall": "node ./node_modules/vscode/bin/install"
},
"devDependencies": {
"typescript": "^1.8.5",
"vscode": "^0.11.0"
},
"dependencies": {
"applicationinsights": "^0.16.0",
"azure-event-hubs": "^0.0.4",
"azure-iot-device": "^1.0.16",
"azure-iot-device-http": "^1.0.16"
}
}

22
src/appInsightsClient.ts Normal file
Просмотреть файл

@ -0,0 +1,22 @@
'use strict';
import * as vscode from 'vscode';
import { Utility } from './utility';
const appInsights = require("applicationinsights");
export class AppInsightsClient {
private _client;
private _enableAppInsights;
constructor() {
this._client = appInsights.getClient('6ada6440-d926-4331-b914-d8f1ea3b012f');
let config = Utility.getConfiguration();
this._enableAppInsights = config.get<boolean>('enableAppInsights');
}
public sendEvent(eventName: string, properties?: { [key: string]: string; }): void {
if (this._enableAppInsights) {
this._client.trackEvent(eventName, properties);
}
}
}

27
src/azureIoTExplorer.ts Normal file
Просмотреть файл

@ -0,0 +1,27 @@
'use strict';
import * as vscode from 'vscode';
import { MessageExplorer } from './messageExplorer';
import { AppInsightsClient } from './appInsightsClient';
export class AzureIoTExplorer {
private _messageExplorer: MessageExplorer;
constructor() {
let outputChannel = vscode.window.createOutputChannel('Azure IoT Explorer');
let appInsightsClient = new AppInsightsClient();
this._messageExplorer = new MessageExplorer(outputChannel, appInsightsClient);
}
public sendD2CMessage(): void {
this._messageExplorer.sendD2CMessage();
}
public startMonitoringMessage(): void {
this._messageExplorer.startMonitoringMessage();
}
public stopMonitoringMessage(): void {
this._messageExplorer.stopMonitoringMessage();
}
}

26
src/extension.ts Normal file
Просмотреть файл

@ -0,0 +1,26 @@
'use strict';
import * as vscode from 'vscode';
import { AzureIoTExplorer } from './azureIoTExplorer';
export function activate(context: vscode.ExtensionContext) {
let azureIoTExplorer = new AzureIoTExplorer();
let sendD2CMessage = vscode.commands.registerCommand('azure-iot-explorer.sendD2CMessage', () => {
azureIoTExplorer.sendD2CMessage();
});
let startMonitoringMessage = vscode.commands.registerCommand('azure-iot-explorer.startMonitoringMessage', () => {
azureIoTExplorer.startMonitoringMessage();
});
let stopMonitoringMessage = vscode.commands.registerCommand('azure-iot-explorer.stopMonitoringMessage', () => {
azureIoTExplorer.stopMonitoringMessage();
});
context.subscriptions.push(sendD2CMessage);
context.subscriptions.push(startMonitoringMessage);
context.subscriptions.push(stopMonitoringMessage);
}
export function deactivate() {
}

119
src/messageExplorer.ts Normal file
Просмотреть файл

@ -0,0 +1,119 @@
'use strict';
import * as vscode from 'vscode';
import { Utility } from './utility';
import { clientFromConnectionString } from 'azure-iot-device-http';
import { Message, Client } from 'azure-iot-device';
import { AppInsightsClient } from './appInsightsClient';
let EventHubClient = require('azure-event-hubs').Client;
export class MessageExplorer {
private _outputChannel: vscode.OutputChannel;
private _appInsightsClient: AppInsightsClient;
private _eventHubClient;
constructor(outputChannel: vscode.OutputChannel, appInsightsClient: AppInsightsClient) {
this._outputChannel = outputChannel;
this._appInsightsClient = appInsightsClient;
}
public sendD2CMessage(): void {
let label = 'D2CMessage';
let config = Utility.getConfiguration();
let deviceConnectionString = config.get<string>('deviceConnectionString');
if (!deviceConnectionString || deviceConnectionString.startsWith('<<insert')) {
vscode.window.showErrorMessage('Please set your Device Connection String in settings.json');
return;
}
vscode.window.showInputBox({ prompt: 'Enter message to send' }).then((message: string) => {
if (message !== undefined) {
try {
let client = clientFromConnectionString(deviceConnectionString);
client.sendEvent(new Message(JSON.stringify(message)), this.sendEventDone(true, client, label));
}
catch (e) {
Utility.output(this._outputChannel, label, e);
}
}
});
}
public startMonitoringMessage(): void {
let label = 'Monitor';
let config = Utility.getConfiguration();
let iotHubConnectionString = config.get<string>('iotHubConnectionString');
if (!iotHubConnectionString || iotHubConnectionString.startsWith('<<insert')) {
vscode.window.showErrorMessage('Please set your IoT Hub Connection String in settings.json');
return;
}
let consumerGroup = config.get<string>('consumerGroup');
try {
this._eventHubClient = EventHubClient.fromConnectionString(iotHubConnectionString);
this._outputChannel.show();
Utility.output(this._outputChannel, label, 'Start monitoring...');
this._appInsightsClient.sendEvent('D2C.startMonitoring')
this._eventHubClient.open()
.then(this._eventHubClient.getPartitionIds.bind(this._eventHubClient))
.then((partitionIds) => {
return partitionIds.map((partitionId) => {
return this._eventHubClient.createReceiver(consumerGroup, partitionId, { 'startAfterTime': Date.now() }).then((receiver) => {
Utility.output(this._outputChannel, label, `Created partition receiver [${partitionId}] for consumerGroup [${consumerGroup}]`);
receiver.on('errorReceived', this.printError(this._outputChannel, label, this._eventHubClient));
receiver.on('message', this.printMessage(this._outputChannel, label));
});
});
})
.catch(this.printError(this._outputChannel, label, this._eventHubClient));
}
catch (e) {
Utility.output(this._outputChannel, label, e);
}
}
public stopMonitoringMessage(): void {
if (this._eventHubClient) {
Utility.output(this._outputChannel, 'Monitor', 'Stop monitoring...');
this._appInsightsClient.sendEvent('D2C.stopMonitoring')
this._eventHubClient.close();
}
}
private sendEventDone(close: boolean, client: Client, label: string) {
this._outputChannel.show();
Utility.output(this._outputChannel, label, 'Sending message to IoT Hub...');
return (err, result) => {
if (err) {
Utility.output(this._outputChannel, label, 'Failed to send message to IoT Hub');
Utility.output(this._outputChannel, label, err.toString());
this._appInsightsClient.sendEvent('D2C.Send', { Result: 'Fail' })
}
if (result) {
Utility.output(this._outputChannel, label, '[Success] Message sent to IoT Hub');
this._appInsightsClient.sendEvent('D2C.Send', { Result: 'Success' })
}
if (close) {
client.close((err, result) => { console.log('client close') });
}
};
}
private printError(outputChannel: vscode.OutputChannel, label: string, eventHubClient) {
return (err) => {
Utility.output(this._outputChannel, label, err.message);
Utility.output(this._outputChannel, label, 'Stop monitoring...');
if (eventHubClient) {
eventHubClient.close();
}
};
};
private printMessage(outputChannel: vscode.OutputChannel, label: string) {
return (message) => {
Utility.output(this._outputChannel, label, 'Message received: ');
Utility.output(this._outputChannel, label, JSON.stringify(message.body));
};
};
}

12
src/utility.ts Normal file
Просмотреть файл

@ -0,0 +1,12 @@
'use strict';
import * as vscode from 'vscode';
export class Utility {
static output(outputChannel: vscode.OutputChannel, label: string, message: string): void {
outputChannel.appendLine(`[${label}] ${message}`);
}
static getConfiguration(): vscode.WorkspaceConfiguration {
return vscode.workspace.getConfiguration('azure-iot-explorer');
}
}

22
test/extension.test.ts Normal file
Просмотреть файл

@ -0,0 +1,22 @@
//
// Note: This example test is leveraging the Mocha test framework.
// Please refer to their documentation on https://mochajs.org/ for help.
//
// The module 'assert' provides assertion methods from node
import * as assert from 'assert';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
import * as myExtension from '../src/extension';
// Defines a Mocha test suite to group tests of similar kind together
suite("Extension Tests", () => {
// Defines a Mocha unit test
test("Something 1", () => {
assert.equal(-1, [1, 2, 3].indexOf(5));
assert.equal(-1, [1, 2, 3].indexOf(0));
});
});

22
test/index.ts Normal file
Просмотреть файл

@ -0,0 +1,22 @@
//
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// This file is providing the test runner to use when running extension tests.
// By default the test runner in use is Mocha based.
//
// You can provide your own test runner if you want to override it by exporting
// a function run(testRoot: string, clb: (error:Error) => void) that the extension
// host can call to run the tests. The test runner is expected to use console.log
// to report the results back to the caller. When the tests are finished, return
// a possible error to the callback or null if none.
var testRunner = require('vscode/lib/testrunner');
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
});
module.exports = testRunner;

14
tsconfig.json Normal file
Просмотреть файл

@ -0,0 +1,14 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"outDir": "out",
"noLib": true,
"sourceMap": true,
"rootDir": "."
},
"exclude": [
"node_modules",
".vscode-test"
]
}

1
typings/node.d.ts поставляемый Normal file
Просмотреть файл

@ -0,0 +1 @@
/// <reference path="../node_modules/vscode/typings/node.d.ts" />

1
typings/vscode-typings.d.ts поставляемый Normal file
Просмотреть файл

@ -0,0 +1 @@
/// <reference path="../node_modules/vscode/typings/index.d.ts" />