FrostClient.js 14 KB
Newer Older
Hanadi's avatar
Hanadi committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FrostClient = void 0;
const node_fetch_1 = __importDefault(require("node-fetch"));
const logger_1 = require("../logger/logger");
const THINGS_PATH = "Things";
const LOCATIONS_PATH = "Locations";
const FEATURES_OF_INTEREST_PATH = "FeaturesOfInterest";
const DATASTREAMS_PATH = "Datastreams";
const OBSERVATIONS_PATH = "Observations";
const SENSORS_PATH = "Sensors";
const OBSERVED_PROPERTIES_PATH = "ObservedProperties";
const getPathFromType = (type) => {
    switch (type) {
        case "thing":
            return THINGS_PATH;
        case "location":
            return LOCATIONS_PATH;
        case "featureOfInterest":
            return FEATURES_OF_INTEREST_PATH;
        case "datastream":
            return DATASTREAMS_PATH;
        case "observation":
            return OBSERVATIONS_PATH;
        case "sensor":
            return SENSORS_PATH;
        case "observedProperty":
            return OBSERVED_PROPERTIES_PATH;
    }
    throw new Error(`Unknown type ${type}!`);
};
const DEFAULT_PROJECTION = ["@iot.id"];
class FrostClient {
    constructor(baseUrl) {
        this.baseUrl = baseUrl;
        // Initialize Here sensor and Speed observed property if they are not already inserted
        this.insertItemIfNotExists("sensor", {
            "@iot.id": "here",
            name: "Here",
            description: "Here - Traffic Flow API",
            encodingType: "text/html",
            metadata: "https://developer.here.com/documentation/traffic/dev_guide/topics_v6.1/example-flow.html"
        })
            .then(inserted => {
            if (inserted)
                console.log("Here sensor was inserted.");
        })
            .catch(err => console.error(err));
        this.insertItemIfNotExists("observedProperty", {
            "@iot.id": "speed",
            name: "Speed",
            definition: "http://www.qudt.org/qudt/owl/1.0.0/quantity/Instances.html#Speed",
            description: "The Speed."
        })
            .then(inserted => {
            if (inserted)
                console.log("Speed observed property was inserted.");
        })
            .catch(err => console.error(err));
    }
    /**
     * Returns the first thing with the specified id, or null if not found.
     * @param id
     * @param projection
     */
    getSingleThingById(id, projection) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.getSingleItemById("thing", id, projection);
        });
    }
    /**
     * Returns the first location with the specified id, or null if not found.
     * @param id
     * @param projection
     */
    getSingleLocationById(id, projection) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.getSingleItemById("location", id, projection);
        });
    }
    /**
     * Returns the first feature of interest with the specified id, or null if not found.
     * @param id
     * @param projection
     */
    getSingleFeatureOfInterestById(id, projection) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.getSingleItemById("featureOfInterest", id, projection);
        });
    }
    getSingleDatastreamById(id, projection) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.getSingleItemById("datastream", id, projection);
        });
    }
    /**
     * Returns the number of inserted observations
     * @param hereFlow
     * @param forceUpdateLocations
     */
    mapAndInsertHereFlowResponse(hereFlow, forceUpdateLocations = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const data = hereFlow.RWS
                .flatMap(rws => rws.RW)
                .flatMap(rw => {
                const timeStamp = rw.PBT;
                const locationsAndResults = rw.FIS
                    .flatMap(fis => fis.FI)
                    .map(fi => {
                    var _a, _b, _c;
                    const thingId = `${rw.LI}-${fi.TMC.DE}-${fi.TMC.PC}`;
                    const thingDescription = `${rw.DE} direction to ${fi.TMC.DE}`;
                    const thing = {
                        "@iot.id": thingId,
                        name: thingId,
                        description: thingDescription
                    };
                    const location = {
                        "@iot.id": thingId,
                        name: thingId,
                        description: thingDescription,
                        encodingType: "application/vnd.geo+json",
                        location: {
                            type: "MultiLineString",
                            coordinates: fi.SHP
                                .map(v => v.value.toString())
                                .map(str => str
                                .trim()
                                .split(" ")
                                .map(coord => coord.split(",").reverse().map(x => +x)))
                        },
                        properties: {
                            length: fi.TMC.LE //In Kilometers
                        },
                        Things: [{
                                "@iot.id": thingId
                            }],
                    };
                    const featureOfInterest = {
                        "@iot.id": location["@iot.id"],
                        name: location.name,
                        description: location.description,
                        encodingType: location.encodingType,
                        feature: location.location,
                        properties: location.properties,
                    };
                    const speed = (_a = fi.CF[0]) === null || _a === void 0 ? void 0 : _a.SP;
                    const confidence = (_b = fi.CF[0]) === null || _b === void 0 ? void 0 : _b.CN;
                    const jamFactor = (_c = fi.CF[0]) === null || _c === void 0 ? void 0 : _c.JF;
                    return { thing, location, featureOfInterest, timeStamp, speed, confidence, jamFactor };
                })
                    .filter(data => !!data.speed); // if failed to obtain speed data, don't consider it
                /***** Log if ID repetitions Found *****/
                Object.entries(locationsAndResults.map(data => data.featureOfInterest["@iot.id"])
                    .reduce(function (prev, cur) {
                    prev[cur] = (prev[cur] || 0) + 1;
                    return prev;
                }, {}))
                    .forEach(([foiId, repetitions]) => {
                    if (repetitions > 1) {
                        console.error(`FeaturesOfInterest: ${foiId} is repeated ${repetitions} times`);
                    }
                });
                /***** *************************** *****/
                return locationsAndResults;
            });
            return Promise.all(data.map(roadwayData => {
                const datastreamId = `here-${roadwayData.thing["@iot.id"]}`;
                return this.insertItemIfNotExists("thing", roadwayData.thing)
                    .then(() => {
                    const datastream = {
                        "@iot.id": datastreamId,
                        name: datastreamId,
                        description: `Speed readings from Here for roadway ${roadwayData.thing.description}`,
                        observationType: "http://www.opengis.net/def/observationType/OGC-OM/2.0/OM_Measurement",
                        unitOfMeasurement: {
                            name: "Kilometers per hour",
                            symbol: "km/h",
                            definition: "http://www.qudt.org/qudt/owl/1.0.0/unit/Instances.html#KilometerPerHour"
                        },
                        ObservedProperty: {
                            "@iot.id": "speed"
                        },
                        Sensor: {
                            "@iot.id": "here"
                        },
                        Thing: {
                            "@iot.id": roadwayData.thing["@iot.id"]
                        },
                    };
                    return this.insertItemIfNotExists("datastream", datastream);
                })
                    .then(() => this.insertItemIfNotExists("location", roadwayData.location, forceUpdateLocations))
                    .then(() => this.insertItemIfNotExists("featureOfInterest", roadwayData.featureOfInterest, forceUpdateLocations))
                    .then(() => {
                    const observation = {
                        phenomenonTime: roadwayData.timeStamp,
                        result: roadwayData.speed,
                        resultQuality: roadwayData.confidence,
                        resultTime: roadwayData.timeStamp,
                        FeatureOfInterest: {
                            "@iot.id": roadwayData.featureOfInterest["@iot.id"]
                        },
                        Datastream: {
                            "@iot.id": datastreamId
                        },
                        parameters: {
                            jamFactor: roadwayData.jamFactor
                        }
                    };
                    return this.insertItem("observation", observation);
                })
                    .then(() => 1);
            })).then(length => length.reduce((a, b) => a + b, 0));
        });
    }
    insertItemIfNotExists(type, frostItemWithId, forceUpdate = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const existingThing = yield this.getSingleItemById(type, frostItemWithId["@iot.id"]);
            if (existingThing && forceUpdate) {
                logger_1.info(`Force updating item ${frostItemWithId["@iot.id"]} with type ${type}`);
                return this.updateItem(type, frostItemWithId);
            }
            if (existingThing)
                return false;
            return this.insertItem(type, frostItemWithId);
        });
    }
    insertItem(type, frostItem) {
        return __awaiter(this, void 0, void 0, function* () {
            // if (type == "location")
            //     console.debug(`inserting item with type ${type}`);
            const path = getPathFromType(type);
            let url = `${this.baseUrl}/${path}`;
            return node_fetch_1.default(url, {
                method: "POST",
                body: JSON.stringify(frostItem)
            })
                .then(res => {
                if (!res.ok) {
                    console.error(`Error inserting item ${JSON.stringify(frostItem)} with type ${type}`);
                    res.text().then(text => console.error(text));
                    const err = new Error(`Error inserting item ${JSON.stringify(frostItem)} with type ${type}`);
                    err.name = "COULD_NOT_INSERT_ITEM";
                    throw err;
                }
                return res.ok;
            });
        });
    }
    updateItem(type, frostItem) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            // if (type == "location")
            //     console.debug(`inserting item with type ${type}`);
            const path = getPathFromType(type);
            const encodedId = (_a = frostItem["@iot.id"]) === null || _a === void 0 ? void 0 : _a.split("/").map(x => encodeURIComponent(x)).join("/");
            let url = `${this.baseUrl}/${path}('${encodedId}')`;
            return node_fetch_1.default(url, {
                method: "PATCH",
                body: JSON.stringify(frostItem)
            })
                .then(res => {
                if (!res.ok) {
                    console.error(`Error updating item ${JSON.stringify(frostItem)} with type ${type}`);
                    res.text().then(text => console.error(text));
                    const err = new Error(`Error inserting item ${JSON.stringify(frostItem)} with type ${type}`);
                    err.name = "COULD_NOT_INSERT_ITEM";
                    throw err;
                }
                return res.ok;
            });
        });
    }
    getSingleItemById(type, id, projection = DEFAULT_PROJECTION) {
        return __awaiter(this, void 0, void 0, function* () {
            const path = getPathFromType(type);
            const params = Object.assign({ "$filter": `id eq '${id}'`, "$top": 1 }, (projection ? { "$select": projection === null || projection === void 0 ? void 0 : projection.join(",") } : {}));
            return this.get(path, params).then(res => res.value[0]);
        });
    }
    get(urlPath, params) {
        return __awaiter(this, void 0, void 0, function* () {
            let url = `${this.baseUrl}/${urlPath}`;
            if (!params)
                params = {};
            if (Object.keys(params)) {
                url += "?";
                url += Object.entries(params)
                    .map(([key, value]) => [key, encodeURIComponent(value)])
                    .map(([key, value]) => `${key}=${value}`)
                    .join("&");
            }
            return node_fetch_1.default(url)
                .then(res => res.json())
                .then(json => {
                // console.debug(`Getting url "${url}"`);
                // console.debug(json);
                return json;
            });
        });
    }
}
exports.FrostClient = FrostClient;
//# sourceMappingURL=FrostClient.js.map