├── .gitignore ├── IoTCIntegration ├── converters │ └── sigfox.js ├── error.js ├── function.json ├── index.js ├── lib │ └── engine.js └── package.json ├── LICENSE ├── README.md ├── SECURITY.md ├── assets ├── associate.PNG ├── editTemplate.PNG ├── getFunctionUrl.PNG ├── migrate.PNG ├── npmInstall.PNG ├── restart.PNG ├── sasEnrollmentGroup.PNG └── scopeIdAndKey.PNG ├── azuredeploy.json └── iotc-bridge-az-function.zip /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /IoTCIntegration/converters/sigfox.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. 4 | */ 5 | 6 | const StatusError = require('../error').StatusError; 7 | 8 | const supportedTypes = ['int', 'uint', 'float']; 9 | const supportedSizes = [8, 16, 32, 64]; 10 | const supportedEndianess = ['little-endian', 'big-endian']; 11 | 12 | /** 13 | * Converts Sigfox device data in HEX format to a map of measurement field names to values. 14 | * 15 | * Supports: 16 | * - 'int', 'uint', and 'float' types 17 | * - 8, 16, 32, and 64 bit sizes 18 | * - 'little-endian' and 'big-endian' 19 | * 20 | * @param payloadDefinition Sigfox payload definition 21 | * @param payload HEX device data 22 | */ 23 | module.exports = function (payloadDefinition, payload) { 24 | const measurements = {}; 25 | const fields = parseSigfoxPayloadDefinition(payloadDefinition); 26 | const data = new Buffer(payload, 'hex'); 27 | let offset = 0; 28 | 29 | for (const field of fields) { 30 | const size = field.size / 8; 31 | 32 | switch (field.type) { 33 | case 'int': 34 | measurements[field.name] = field.littleEndian ? data.readIntLE(offset, size) : data.readIntBE(offset, size); 35 | break; 36 | case 'uint': 37 | measurements[field.name] = field.littleEndian ? data.readUIntLE(offset, size) : data.readUIntBE(offset, size); 38 | break; 39 | case 'float': 40 | if (size === 4) { 41 | measurements[field.name] = field.littleEndian ? data.readFloatLE(offset) : data.readFloatBE(offset); 42 | } else if (size === 8) { 43 | measurements[field.name] = field.littleEndian ? data.readDoubleLE(offset) : data.readDoubleBE(offset); 44 | } 45 | 46 | break; 47 | } 48 | 49 | offset += size; 50 | } 51 | 52 | return measurements; 53 | } 54 | 55 | function parseSigfoxPayloadDefinition(definition) { 56 | const fields = []; 57 | definition = definition.trim(); 58 | 59 | for (const field of definition.split(' ').filter(s => s)) { 60 | let name, type, size, endianess; 61 | 62 | try { 63 | [name, remainder] = field.split('::'); 64 | const parts = remainder.split(':'); 65 | type = parts[0]; 66 | size = parseInt(parts[1]); 67 | endianess = (parts.length >= 3) ? parts[2] : null; 68 | } catch (e) { 69 | throw new StatusError('Malformed payload definition', 400); 70 | } 71 | 72 | if (!name) { 73 | throw new StatusError('Malformed payload definition', 400); 74 | } 75 | 76 | if (!supportedTypes.includes(type)) { 77 | throw new StatusError(`Malformed payload definition: only 'int', 'uint', and 'float' field types are supported`, 400); 78 | } 79 | 80 | if (!supportedSizes.includes(size)) { 81 | throw new StatusError('Malformed payload definition: field size must be 8, 16, 32, or 64 bits', 400); 82 | } 83 | 84 | if (type === 'float' && size !== 32 && size !== 64) { 85 | throw new StatusError('Malformed payload definition: float fields must be 32 or 64 bits in size', 400); 86 | } 87 | 88 | if (endianess && !supportedEndianess.includes(endianess)) { 89 | throw new StatusError('Malformed payload definition: invalid endianess', 400); 90 | } 91 | 92 | fields.push({ 93 | name, 94 | type, 95 | size, 96 | littleEndian: !!endianess && endianess === 'little-endian' 97 | }); 98 | } 99 | 100 | return fields; 101 | } -------------------------------------------------------------------------------- /IoTCIntegration/error.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. 4 | */ 5 | 6 | module.exports = { 7 | StatusError: class extends Error { 8 | constructor (message, statusCode) { 9 | super(message); 10 | this.statusCode = statusCode; 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /IoTCIntegration/function.json: -------------------------------------------------------------------------------- 1 | { 2 | "bindings": [ 3 | { 4 | "authLevel": "function", 5 | "type": "httpTrigger", 6 | "direction": "in", 7 | "name": "req", 8 | "methods": [ 9 | "get", 10 | "post" 11 | ] 12 | }, 13 | { 14 | "type": "http", 15 | "direction": "out", 16 | "name": "res" 17 | } 18 | ] 19 | } -------------------------------------------------------------------------------- /IoTCIntegration/index.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. 4 | */ 5 | 6 | const fetch = require('node-fetch'); 7 | const handleMessage = require('./lib/engine'); 8 | 9 | const msiEndpoint = process.env.MSI_ENDPOINT; 10 | const msiSecret = process.env.MSI_SECRET; 11 | 12 | const parameters = { 13 | idScope: process.env.ID_SCOPE, 14 | primaryKeyUrl: process.env.IOTC_KEY_URL 15 | }; 16 | 17 | let kvToken; 18 | 19 | module.exports = async function (context, req) { 20 | try { 21 | await handleMessage({ ...parameters, log: context.log, getSecret: getKeyVaultSecret }, req.body.device, req.body.measurements, req.body.timestamp); 22 | } catch (e) { 23 | context.log('[ERROR]', e.message); 24 | 25 | context.res = { 26 | status: e.statusCode ? e.statusCode : 500, 27 | body: e.message 28 | }; 29 | } 30 | } 31 | 32 | /** 33 | * Fetches a Key Vault secret. Attempts to refresh the token on authorization errors. 34 | */ 35 | async function getKeyVaultSecret(context, secretUrl, forceTokenRefresh = false) { 36 | if (!kvToken || forceTokenRefresh) { 37 | const url = `${msiEndpoint}/?resource=https://vault.azure.net&api-version=2017-09-01`; 38 | const options = { 39 | method: 'GET', 40 | headers: { 'Secret': msiSecret } 41 | }; 42 | 43 | try { 44 | context.log('[HTTP] Requesting new Key Vault token'); 45 | const response = await fetch(url, options).then(res => res.json()) 46 | kvToken = response.access_token; 47 | } catch (e) { 48 | context.log('fail: ' + e); 49 | throw new Error('Unable to get Key Vault token'); 50 | } 51 | } 52 | 53 | url = `${secretUrl}?api-version=2016-10-01`; 54 | var options = { 55 | method : 'GET', 56 | headers : { 'Authorization' : `Bearer ${kvToken}` }, 57 | }; 58 | 59 | try { 60 | context.log('[HTTP] Requesting Key Vault secret', secretUrl); 61 | const response = await fetch(url, options).then(res => res.json()) 62 | return response && response.value; 63 | } catch(e) { 64 | if (e.statusCode === 401 && !forceTokenRefresh) { 65 | return await getKeyVaultSecret(context, secretUrl, true); 66 | } else { 67 | throw new Error('Unable to fetch secret'); 68 | } 69 | } 70 | } -------------------------------------------------------------------------------- /IoTCIntegration/lib/engine.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. 4 | */ 5 | 6 | const crypto = require('crypto'); 7 | const fetch = require('node-fetch'); 8 | const Device = require('azure-iot-device'); 9 | const DeviceTransport = require('azure-iot-device-http'); 10 | 11 | const StatusError = require('../error').StatusError; 12 | 13 | const registrationHost = 'global.azure-devices-provisioning.net'; 14 | const registrationSasTtl = 3600; // 1 hour 15 | const registrationApiVersion = `2019-03-31`; 16 | const registrationStatusQueryAttempts = 10; 17 | const registrationStatusQueryTimeout = 2000; 18 | const minDeviceRegistrationTimeout = 60*1000; // 1 minute 19 | 20 | const deviceCache = {}; 21 | 22 | /** 23 | * Forwards external telemetry messages for IoT Central devices. 24 | * @param {{ idScope: string, primaryKeyUrl: string, log: Function, getSecret: (context: Object, secretUrl: string) => string }} context 25 | * @param {{ deviceId: string }} device 26 | * @param {{ [field: string]: number }} measurements 27 | */ 28 | module.exports = async function (context, device, measurements, timestamp) { 29 | if (device) { 30 | if (!device.deviceId || !/^[a-zA-Z0-9-._:]*[a-zA-Z0-9-]+$/.test(device.deviceId)) { 31 | throw new StatusError("Invalid format: deviceId must be alphanumeric and may contain '-', '.', '_', ':'. Last character must be alphanumeric or hyphen.", 400); 32 | } 33 | } else { 34 | throw new StatusError('Invalid format: a device specification must be provided.', 400); 35 | } 36 | 37 | if (!validateMeasurements(measurements)) { 38 | throw new StatusError('Invalid format: invalid measurement list.', 400); 39 | } 40 | 41 | if (timestamp && isNaN(Date.parse(timestamp))) { 42 | throw new StatusError('Invalid format: if present, timestamp must be in ISO format (e.g., YYYY-MM-DDTHH:mm:ss.sssZ)', 400); 43 | } 44 | 45 | const client = Device.Client.fromConnectionString(await getDeviceConnectionString(context, device), DeviceTransport.Http); 46 | 47 | try { 48 | const message = new Device.Message(JSON.stringify(measurements)); 49 | message.contentEncoding = 'utf-8'; 50 | message.contentType = 'application/json'; 51 | 52 | if (timestamp) { 53 | message.properties.add('iothub-creation-time-utc', timestamp); 54 | } 55 | 56 | await client.open(); 57 | context.log('[HTTP] Sending telemetry for device', device.deviceId); 58 | await client.sendEvent(message); 59 | await client.close(); 60 | } catch (e) { 61 | // If the device was deleted, we remove its cached connection string 62 | if (e.name === 'DeviceNotFoundError' && deviceCache[device.deviceId]) { 63 | delete deviceCache[device.deviceId].connectionString; 64 | } 65 | 66 | throw new Error(`Unable to send telemetry for device ${device.deviceId}: ${e.message}`); 67 | } 68 | }; 69 | 70 | /** 71 | * @returns true if measurements object is valid, i.e., a map of field names to numbers or strings. 72 | */ 73 | function validateMeasurements(measurements) { 74 | if (!measurements || typeof measurements !== 'object') { 75 | return false; 76 | } 77 | 78 | return true; 79 | } 80 | 81 | async function getDeviceConnectionString(context, device) { 82 | const deviceId = device.deviceId; 83 | 84 | if (deviceCache[deviceId] && deviceCache[deviceId].connectionString) { 85 | return deviceCache[deviceId].connectionString; 86 | } 87 | 88 | const connStr = `HostName=${await getDeviceHub(context, device)};DeviceId=${deviceId};SharedAccessKey=${await getDeviceKey(context, deviceId)}`; 89 | deviceCache[deviceId].connectionString = connStr; 90 | return connStr; 91 | } 92 | 93 | /** 94 | * Registers this device with DPS, returning the IoT Hub assigned to it. 95 | */ 96 | async function getDeviceHub(context, device) { 97 | const deviceId = device.deviceId; 98 | const now = Date.now(); 99 | 100 | // A 1 minute backoff is enforced for registration attempts, to prevent unauthorized devices 101 | // from trying to re-register too often. 102 | if (deviceCache[deviceId] && deviceCache[deviceId].lasRegisterAttempt && (now - deviceCache[deviceId].lasRegisterAttempt) < minDeviceRegistrationTimeout) { 103 | const backoff = Math.floor((minDeviceRegistrationTimeout - (now - deviceCache[deviceId].lasRegisterAttempt)) / 1000); 104 | throw new StatusError(`Unable to register device ${deviceId}. Minimum registration timeout not yet exceeded. Please try again in ${backoff} seconds`, 403); 105 | } 106 | 107 | deviceCache[deviceId] = { 108 | ...deviceCache[deviceId], 109 | lasRegisterAttempt: Date.now() 110 | } 111 | 112 | const sasToken = await getRegistrationSasToken(context, deviceId); 113 | 114 | const registrationUrl = `https://${registrationHost}/${context.idScope}/registrations/${deviceId}/register?api-version=${registrationApiVersion}`; 115 | const registrationOptions = { 116 | method: 'PUT', 117 | headers: { 'Content-Type': 'application/json', Authorization: sasToken }, 118 | body: JSON.stringify({ registrationId: deviceId, payload: { iotcModelId: device.modelId } }) 119 | }; 120 | 121 | try { 122 | context.log('[HTTP] Initiating device registration'); 123 | const response = await fetch(registrationUrl, registrationOptions).then(res => res.json()); 124 | 125 | if (response.status !== 'assigning' || !response.operationId) { 126 | throw new Error('Unknown server response'); 127 | } 128 | 129 | const statusUrl = `https://${registrationHost}/${context.idScope}/registrations/${deviceId}/operations/${response.operationId}?api-version=${registrationApiVersion}`; 130 | const statusOptions = { 131 | method: 'GET', 132 | headers: { Authorization: sasToken } 133 | }; 134 | 135 | // The first registration call starts the process, we then query the registration status 136 | // every 2 seconds, up to 10 times. 137 | for (let i = 0; i < registrationStatusQueryAttempts; ++i) { 138 | await new Promise(resolve => setTimeout(resolve, registrationStatusQueryTimeout)); 139 | 140 | context.log('[HTTP] Querying device registration status'); 141 | const statusResponse = await fetch(statusUrl, statusOptions).then(res => res.json()); 142 | 143 | if (statusResponse.status === 'assigning') { 144 | continue; 145 | } else if (statusResponse.status === 'assigned' && statusResponse.registrationState && statusResponse.registrationState.assignedHub) { 146 | return statusResponse.registrationState.assignedHub; 147 | } else if (statusResponse.status === 'failed' && statusResponse.registrationState && statusResponse.registrationState.errorCode === 400209) { 148 | throw new StatusError('The device may be unassociated or blocked', 403); 149 | } else { 150 | throw new Error('Unknown server response'); 151 | } 152 | } 153 | 154 | throw new Error('Registration was not successful after maximum number of attempts'); 155 | } catch (e) { 156 | throw new StatusError(`Unable to register device ${deviceId}: ${e.message}`, e.statusCode); 157 | } 158 | } 159 | 160 | async function getRegistrationSasToken(context, deviceId) { 161 | const uri = encodeURIComponent(`${context.idScope}/registrations/${deviceId}`); 162 | const ttl = Math.round(Date.now() / 1000) + registrationSasTtl; 163 | const signature = crypto.createHmac('sha256', new Buffer(await getDeviceKey(context, deviceId), 'base64')) 164 | .update(`${uri}\n${ttl}`) 165 | .digest('base64'); 166 | return`SharedAccessSignature sr=${uri}&sig=${encodeURIComponent(signature)}&skn=registration&se=${ttl}`; 167 | } 168 | 169 | /** 170 | * Computes a derived device key using the primary key. 171 | */ 172 | async function getDeviceKey(context, deviceId) { 173 | if (deviceCache[deviceId] && deviceCache[deviceId].deviceKey) { 174 | return deviceCache[deviceId].deviceKey; 175 | } 176 | 177 | const key = crypto.createHmac('SHA256', Buffer.from(await context.getSecret(context, context.primaryKeyUrl), 'base64')) 178 | .update(deviceId) 179 | .digest() 180 | .toString('base64'); 181 | 182 | deviceCache[deviceId].deviceKey = key; 183 | return key; 184 | } -------------------------------------------------------------------------------- /IoTCIntegration/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "iotc-integration-azure-function", 3 | "version": "1.0.1", 4 | "private": true, 5 | "description": "Sample Azure Function for cloud to cloud integration with Azure IoT Central", 6 | "main": "index.js", 7 | "dependencies": { 8 | "azure-iot-device": "^1.18.2", 9 | "azure-iot-device-http": "^1.14.2", 10 | "node-fetch": "^2.6.0" 11 | }, 12 | "devDependencies": {}, 13 | "scripts": {}, 14 | "author": "", 15 | "license": "MIT" 16 | } 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | description: "A sample that shows how to create a device bridge to connect other IoT clouds such as Sigfox, Particle, and The Things Network to IoT Central" 4 | languages: 5 | - javascript 6 | products: 7 | - azure-iot-central 8 | - azure-iot 9 | urlFragment: iot-central-device-bridge-sample 10 | --- 11 | 12 | 13 | # Azure IoT Central Device Bridge 14 | This repository contains everything you need create a device bridge to connect other IoT clouds such as Sigfox, Particle, and The Things Network (TTN) to IoT Central. The device bridge forwards the messages your devices send to other clouds to your IoT Central app. In your IoT Central app, you can build rules and run analytics on that data, create workflows in Microsoft Flow and Azure Logic apps, export that data, and much more. This solution will provision several Azure resources into your Azure subscription that work together to transform and forward device messages through a webhook integration in Azure Functions. 15 | 16 | To use the device bridge solution, you will need the following: 17 | - An Azure account. You can create a free Azure account from [here](https://aka.ms/aft-iot). 18 | - An Azure IoT Central application to connect the devices. Create a free app by following [these instructions](https://docs.microsoft.com/azure/iot-central/quick-deploy-iot-central). 19 | 20 | [![Deploy to Azure](https://aka.ms/deploytoazurebutton)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fiotc-device-bridge%2Fmaster%2Fazuredeploy.json) 21 | 22 | ## Instructions 23 | For detailed instructions on how to deploy and configure the device bridge, see [Use the IoT Central device bridge to connect other IoT clouds to IoT Central](https://docs.microsoft.com/en-us/azure/iot-central/core/howto-build-iotc-device-bridge). 24 | 25 | ## Limitations 26 | This device bridge only forwards messages to IoT Central, and does not send messages back to devices. Due to the unidirectional nature of this solution, `settings` and `commands` will **not** work for devices that connect to IoT Central through this device bridge. Because device twin operations are also not supported, it's **not** possible to update `device properties` through this setup. To use these features, a device must be connected directly to IoT Central using one of the [Azure IoT device SDKs](https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-sdks). 27 | 28 | ## Package integrity 29 | The template provided here deploys a packaged version of the code in this repository to an Azure 30 | Function. You can check the integrity of the code being deployed by verifying that the `SHA256` hash 31 | of the `iotc-bridge-az-function.zip` file in the root of this repository matches the following: 32 | 33 | ``` 34 | 22dcf01e985a16d9a9500a382da9f022fe65cacb6b5945e844ab10ec326827d3 35 | ``` 36 | 37 | # Contributing 38 | 39 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 40 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 41 | the rights to use your contribution. For details, visit https://cla.microsoft.com. 42 | 43 | When you submit a pull request, a CLA-bot will automatically determine whether you need to provide 44 | a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions 45 | provided by the bot. You will only need to do this once across all repos using our CLA. 46 | 47 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 48 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 49 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 50 | 51 | ## Updating the package 52 | The code in the repository is deployed to the Azure Function from the `iotc-bridge-az-function.zip` package at the repository root. 53 | When updating the source code, this package also needs to be updated and tested. To update, simply make a zip file from the `IoTCIntegration` 54 | folder that contains your source changes. Make sure to exclude non-source files, such as `node_modules`. 55 | 56 | To test your changes, use the `azuredeploy.json` ARM template in the repository root. Change the `packageUri` 57 | variable to point to your modified zip package location (zip package URL can be obtained from your GitHub branch) and deploy the template in the Azure Portal. 58 | Make sure that the function deploys correctly and that you're able to send device data through the test tab in the Azure Portal. 59 | 60 | ## Updating the README 61 | Change this README to document any user-facing changes, e.g., changes in the incoming payload format. 62 | Also update the SHA256 hash in the _Package integrity_ section above with the hash of your new zip package, for integrity verification. -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Security 4 | 5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). 6 | 7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. 8 | 9 | ## Reporting Security Issues 10 | 11 | **Please do not report security vulnerabilities through public GitHub issues.** 12 | 13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). 14 | 15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). 16 | 17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). 18 | 19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 20 | 21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 22 | * Full paths of source file(s) related to the manifestation of the issue 23 | * The location of the affected source code (tag/branch/commit or direct URL) 24 | * Any special configuration required to reproduce the issue 25 | * Step-by-step instructions to reproduce the issue 26 | * Proof-of-concept or exploit code (if possible) 27 | * Impact of the issue, including how an attacker might exploit the issue 28 | 29 | This information will help us triage your report more quickly. 30 | 31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. 32 | 33 | ## Preferred Languages 34 | 35 | We prefer all communications to be in English. 36 | 37 | ## Policy 38 | 39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). 40 | 41 | 42 | -------------------------------------------------------------------------------- /assets/associate.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/iotc-device-bridge/60b3cc052e7fda07c005a0935bf9c080825e17ef/assets/associate.PNG -------------------------------------------------------------------------------- /assets/editTemplate.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/iotc-device-bridge/60b3cc052e7fda07c005a0935bf9c080825e17ef/assets/editTemplate.PNG -------------------------------------------------------------------------------- /assets/getFunctionUrl.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/iotc-device-bridge/60b3cc052e7fda07c005a0935bf9c080825e17ef/assets/getFunctionUrl.PNG -------------------------------------------------------------------------------- /assets/migrate.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/iotc-device-bridge/60b3cc052e7fda07c005a0935bf9c080825e17ef/assets/migrate.PNG -------------------------------------------------------------------------------- /assets/npmInstall.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/iotc-device-bridge/60b3cc052e7fda07c005a0935bf9c080825e17ef/assets/npmInstall.PNG -------------------------------------------------------------------------------- /assets/restart.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/iotc-device-bridge/60b3cc052e7fda07c005a0935bf9c080825e17ef/assets/restart.PNG -------------------------------------------------------------------------------- /assets/sasEnrollmentGroup.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/iotc-device-bridge/60b3cc052e7fda07c005a0935bf9c080825e17ef/assets/sasEnrollmentGroup.PNG -------------------------------------------------------------------------------- /assets/scopeIdAndKey.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/iotc-device-bridge/60b3cc052e7fda07c005a0935bf9c080825e17ef/assets/scopeIdAndKey.PNG -------------------------------------------------------------------------------- /azuredeploy.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", 3 | "contentVersion": "1.0.0.1", 4 | "parameters": { 5 | "scopeID": { 6 | "type": "string" 7 | }, 8 | "iotCentralSASKey": { 9 | "type": "string" 10 | } 11 | }, 12 | "variables": { 13 | "planName": "[concat('iotc-pln', uniqueString(resourceGroup().id))]", 14 | "storageName": "[concat('iotcsa', uniqueString(resourceGroup().id))]", 15 | "functionAppName": "[concat('iotc-fn', uniqueString(resourceGroup().id))]", 16 | "keyVaultName": "[concat('iotcvlt', uniqueString(resourceGroup().id))]", 17 | "iotcKeyName": "iotckey" 18 | }, 19 | "resources": [ 20 | { 21 | "type": "Microsoft.Storage/storageAccounts", 22 | "sku": { 23 | "name": "Standard_LRS", 24 | "tier": "Standard" 25 | }, 26 | "kind": "Storage", 27 | "name": "[variables('storageName')]", 28 | "apiVersion": "2022-09-01", 29 | "location": "[resourceGroup().location]" 30 | }, 31 | { 32 | "type": "Microsoft.Web/serverfarms", 33 | "apiVersion": "2022-09-01", 34 | "name": "[variables('planName')]", 35 | "location": "[resourceGroup().location]", 36 | "sku": { 37 | "name": "Y1" 38 | } 39 | }, 40 | { 41 | "type": "Microsoft.Web/sites", 42 | "kind": "functionapp", 43 | "name": "[variables('functionAppName')]", 44 | "apiVersion": "2022-09-01", 45 | "location": "[resourceGroup().location]", 46 | "tags": { 47 | "iotCentral": "device-bridge", 48 | "iotCentralDeviceBridge": "function-app" 49 | }, 50 | "identity": { 51 | "type": "SystemAssigned" 52 | }, 53 | "properties": { 54 | "enabled": true, 55 | "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('planName'))]", 56 | "siteConfig": { 57 | "appSettings": [ 58 | { 59 | "name": "AzureWebJobsDashboard", 60 | "value": "[concat('DefaultEndpointsProtocol=https;AccountName=',variables('storageName'),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageName')), providers('Microsoft.Storage', 'storageAccounts').apiVersions[0]).keys[0].value)]" 61 | }, 62 | { 63 | "name": "AzureWebJobsStorage", 64 | "value": "[concat('DefaultEndpointsProtocol=https;AccountName=',variables('storageName'),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageName')), providers('Microsoft.Storage', 'storageAccounts').apiVersions[0]).keys[0].value)]" 65 | }, 66 | { 67 | "name": "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING", 68 | "value": "[concat('DefaultEndpointsProtocol=https;AccountName=',variables('storageName'),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageName')), providers('Microsoft.Storage', 'storageAccounts').apiVersions[0]).keys[0].value)]" 69 | }, 70 | { 71 | "name": "WEBSITE_CONTENTSHARE", 72 | "value": "[toLower(variables('functionAppName'))]" 73 | }, 74 | { 75 | "name": "FUNCTIONS_EXTENSION_VERSION", 76 | "value": "~4" 77 | }, 78 | { 79 | "name": "WEBSITE_NODE_DEFAULT_VERSION", 80 | "value": "~18" 81 | }, 82 | { 83 | "name": "WEBSITE_HTTPSCALEV2_ENABLED", 84 | "value": 0 85 | }, 86 | { 87 | "name": "ID_SCOPE", 88 | "value": "[parameters('scopeID')]" 89 | }, 90 | { 91 | "name": "IOTC_KEY_URL", 92 | "value": "[concat('https://', variables('keyVaultName'), '.vault.azure.net/secrets/', variables('iotcKeyName'), '/')]" 93 | } 94 | ] 95 | } 96 | }, 97 | "resources": [ 98 | { 99 | "name": "MSDeploy", 100 | "type": "extensions", 101 | "location": "[resourceGroup().location]", 102 | "apiVersion": "2022-09-01", 103 | "dependsOn": [ 104 | "[concat('Microsoft.Web/sites/', variables('functionAppName'))]" 105 | ], 106 | "properties": { 107 | "packageUri": "https://raw.githubusercontent.com/Azure/iotc-device-bridge/master/iotc-bridge-az-function.zip" 108 | } 109 | } 110 | ], 111 | "dependsOn": [ 112 | "[resourceId('Microsoft.Storage/storageAccounts', variables('storageName'))]", 113 | "[resourceId('Microsoft.Web/serverfarms', variables('planName'))]" 114 | ] 115 | }, 116 | { 117 | "type": "Microsoft.KeyVault/vaults", 118 | "name": "[variables('keyVaultName')]", 119 | "apiVersion": "2022-07-01", 120 | "location": "[resourceGroup().location]", 121 | "properties": { 122 | "sku": { 123 | "family": "A", 124 | "name": "standard" 125 | }, 126 | "tenantId": "[subscription().tenantId]", 127 | "accessPolicies": [ 128 | { 129 | "tenantId": "[reference(concat('Microsoft.Web/sites/', variables('functionAppName')), '2016-08-01', 'Full').identity.tenantId]", 130 | "objectId": "[reference(concat('Microsoft.Web/sites/', variables('functionAppName')), '2016-08-01', 'Full').identity.principalId]", 131 | "permissions": { 132 | "keys": [], 133 | "secrets": [ 134 | "get", 135 | "list", 136 | "recover" 137 | ], 138 | "certificates": [] 139 | } 140 | } 141 | ] 142 | }, 143 | "resources": [ 144 | { 145 | "type": "secrets", 146 | "name": "[variables('iotcKeyName')]", 147 | "apiVersion": "2022-07-01", 148 | "tags": {}, 149 | "properties": { 150 | "value": "[parameters('iotCentralSASKey')]" 151 | }, 152 | "dependsOn": [ 153 | "[concat('Microsoft.KeyVault/vaults/', variables('keyVaultName'))]" 154 | ] 155 | } 156 | ], 157 | "dependsOn": [ 158 | "[resourceId('Microsoft.Web/sites', variables('functionAppName'))]" 159 | ] 160 | } 161 | ] 162 | } -------------------------------------------------------------------------------- /iotc-bridge-az-function.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/iotc-device-bridge/60b3cc052e7fda07c005a0935bf9c080825e17ef/iotc-bridge-az-function.zip --------------------------------------------------------------------------------