UNPKG

nativescript-particle

Version:

Control your Particle.io devices from a NativeScript app!

82 lines (81 loc) 2.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); require("globals"); var particle_worker_base_1 = require("./particle-worker-base"); var cachedDevices; var eventIds = new Map(); var listDevices = function () { try { var particleDevices = io.particle.android.sdk.cloud.ParticleCloudSDK.getCloud().getDevices(); cachedDevices = []; for (var i = 0; i < particleDevices.size(); i++) { cachedDevices.push(new particle_worker_base_1.MyTNSParticleDevice(particleDevices.get(i))); } } catch (e) { } }; var subscribeFunction = function (prefix, handlerId) { try { var handler = new io.particle.android.sdk.cloud.ParticleEventHandler({ onEventError: function (exception) { global.postMessage({ success: false }); }, onEvent: function (eventName, event) { if (event) { global.postMessage({ success: true, handlerId: handlerId, data: { prefix: prefix, event: eventName, data: event.dataPayload, date: new Date(event.publishedAt.getTime()), deviceID: event.deviceId } }); } } }); var id = io.particle.android.sdk.cloud.ParticleCloudSDK.getCloud().subscribeToAllEvents(prefix, handler); eventIds.set(prefix, id); } catch (e) { console.log(e.nativeException.getBestMessage()); } }; var unsubscribeFunction = function (prefix) { if (eventIds.has(prefix)) { io.particle.android.sdk.cloud.ParticleCloudSDK.getCloud().unsubscribeFromEventWithID(eventIds.get(prefix)); eventIds.delete(prefix); } }; var getDevice = function (id) { return cachedDevices.filter(function (cachedDevice) { return cachedDevice.id === id; })[0]; }; global.onmessage = function (msg) { var request = msg.data; if (request.action === "listDevices") { listDevices(); return; } else if (request.action === "subscribe") { subscribeFunction(request.options.prefix, request.options.handlerId); return; } else if (request.action === "unsubscribe") { unsubscribeFunction(request.options.prefix); return; } else if (request.action === "subscribeDevice") { (getDevice(request.options.deviceId)).subscribe(request.options.prefix, null, request.options.handlerId); return; } else if (request.action === "unsubscribeDevice") { (getDevice(request.options.deviceId)).unsubscribe(request.options.prefix, request.options.handlerId); return; } else { global.postMessage({ success: false, error: "Unsupported action sent to worker: '" + request.action + "'" }); } };