<commit_before>'use strict';

angular.module('app')

    .factory('SensorData', ['$http', '$rootScope', '$location', '$q', 'APP_CONFIG', 'Notifications', 'Vehicles', 'Shipments',
        function ($http, $rootScope, $location, $q, APP_CONFIG, Notifications, Vehicles, Shipments) {
        var factory = {},
            client = null,
            msgproto = null,
            listeners = [],
            topicRegex = /Red-Hat\/([^\/]*)\/iot-demo\/([^\/]*)\/([^\/]*)$/,
            alertRegex = /Red-Hat\/([^\/]*)\/iot-demo\/([^\/]*)\/([^\/]*)\/alerts$/;

            function setFromISO8601(isostr) {
            var parts = isostr.match(/\d+/g);
            return new Date(Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]));
        }

        function onConnectionLost(responseObject) {
            if (responseObject.errorCode !== 0) {
                console.log("onConnectionLost:"+responseObject.errorMessage);
            }
        }

        function handleAlert(destination, alertPayload) {
            var matches = alertRegex.exec(destination);
            var objType = matches[2];
            var objId = matches[3];

            switch (objType) {
                case 'trucks':
                    $rootScope.$broadcast('vehicle:alert', {
                        vin: objId
                    });
                    break;
                case 'packages':
                    Shipments.getAllShipments(function(allShipments) {
                        console.log("got ALL shipments (" + allShipments.length + ")");
                        allShipments.forEach(function(shipment) {
                            if (shipment.sensor_id == objId) {
                                console.log("broadcasting alert ");
                                $rootScope.$broadcast('package:alert', {
                                    vin: shipment.cur_vehicle.vin,
                                    sensor_id: objId
                                });
                            }
                        });
                    });
                    break;
                default:
                    console.log("ignoring alert: " + destination);
            }

        }

        var count = 1;
        function onMessageArrived(message) {
            var destination = message.destinationName;
            console.log(count++ + "RECEIVED on " + destination);

            if (alertRegex.test(destination)) {
                handleAlert(destination, decoded);
            } else {
                var payload = message.payloadBytes;
                var decoded =  msgproto.decode(payload);
                var matches = topicRegex.exec(destination);
                var objType = matches[2];
                var objId = matches[3];

                listeners.filter(function(listener) {
                    return (listener.objType == objType && listener.objId == objId);
                }).forEach(function(listener) {
                    var targetObj = listener.pkg || listener.vehicle;
                    var cb = listener.listener;

                    var data = [];

                    decoded.metric.forEach(function(decodedMetric) {
                        targetObj.telemetry.forEach(function(objTel) {
                            var telName = objTel.name;
                            var telMetricName = objTel.metricName;
                            if (telMetricName == decodedMetric.name) {
                                data.push({
                                    name: telName,
                                    value: decodedMetric.doubleValue.toFixed(1),
                                    timestamp: new Date()
                                });
                            }
                        });
                    });

                    cb(data);
                });
            }
        }

        function onConnect() {
            console.log("Connected to server");
            var topicName = "Red-Hat/+/iot-demo/+/+/alerts";
            client.subscribe(topicName);

        }

        function connectClient() {

            var brokerHostname = APP_CONFIG.BROKER_WEBSOCKET_HOSTNAME + '.' + $location.host().replace(/^.*?\.(.*)/g,"$1");
            client = new Paho.MQTT.Client(brokerHostname, Number(APP_CONFIG.BROKER_WEBSOCKET_PORT), "demo-client-id");

            client.onConnectionLost = onConnectionLost;
            client.onMessageArrived = onMessageArrived;

            protobuf.load("kurapayload.proto", function(err, root) {
                if (err) throw err;

                msgproto = root.lookup("kuradatatypes.KuraPayload");
                // connect the client
                client.connect({
                    onSuccess:onConnect,
                    userName: APP_CONFIG.BROKER_USERNAME,
                    password: <PASSWORD>
                });
            });
        }

        factory.subscribePkg = function (pkg, listener) {

            var topicName = "Red-Hat/+/iot-demo/packages/" + pkg.sensor_id;
            client.subscribe(topicName);
            console.log("subscribed to " + topicName);
            listeners.push({
                pkg: pkg,
                topic: topicName,
                objType: 'packages',
                objId: pkg.sensor_id,
                listener: listener
            });
        };

        factory.subscribeVehicle = function (vehicle, listener) {

            var topicName = "Red-Hat/+/iot-demo/trucks/" + vehicle.vin;
            client.subscribe(topicName);
            console.log("subscribed to " + topicName);
            listeners.push({
                vehicle: vehicle,
                topic: topicName,
                objType: 'trucks',
                objId: vehicle.vin,<commit_msg>Generate unique client ID for websocket connections<commit_after>'use strict';

angular.module('app')

    .factory('SensorData', ['$http', '$rootScope', '$location', '$q', 'APP_CONFIG', 'Notifications', 'Vehicles', 'Shipments',
        function ($http, $rootScope, $location, $q, APP_CONFIG, Notifications, Vehicles, Shipments) {
        var factory = {},
            client = null,
            msgproto = null,
            listeners = [],
            topicRegex = /Red-Hat\/([^\/]*)\/iot-demo\/([^\/]*)\/([^\/]*)$/,
            alertRegex = /Red-Hat\/([^\/]*)\/iot-demo\/([^\/]*)\/([^\/]*)\/alerts$/;

            function setFromISO8601(isostr) {
            var parts = isostr.match(/\d+/g);
            return new Date(Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]));
        }

        function onConnectionLost(responseObject) {
            if (responseObject.errorCode !== 0) {
                console.log("onConnectionLost:"+responseObject.errorMessage);
            }
        }

        function handleAlert(destination, alertPayload) {
            var matches = alertRegex.exec(destination);
            var objType = matches[2];
            var objId = matches[3];

            switch (objType) {
                case 'trucks':
                    $rootScope.$broadcast('vehicle:alert', {
                        vin: objId
                    });
                    break;
                case 'packages':
                    Shipments.getAllShipments(function(allShipments) {
                        console.log("got ALL shipments (" + allShipments.length + ")");
                        allShipments.forEach(function(shipment) {
                            if (shipment.sensor_id == objId) {
                                console.log("broadcasting alert ");
                                $rootScope.$broadcast('package:alert', {
                                    vin: shipment.cur_vehicle.vin,
                                    sensor_id: objId
                                });
                            }
                        });
                    });
                    break;
                default:
                    console.log("ignoring alert: " + destination);
            }

        }

        var count = 1;
        function onMessageArrived(message) {
            var destination = message.destinationName;
            console.log(count++ + "RECEIVED on " + destination);

            if (alertRegex.test(destination)) {
                handleAlert(destination, decoded);
            } else {
                var payload = message.payloadBytes;
                var decoded =  msgproto.decode(payload);
                var matches = topicRegex.exec(destination);
                var objType = matches[2];
                var objId = matches[3];

                listeners.filter(function(listener) {
                    return (listener.objType == objType && listener.objId == objId);
                }).forEach(function(listener) {
                    var targetObj = listener.pkg || listener.vehicle;
                    var cb = listener.listener;

                    var data = [];

                    decoded.metric.forEach(function(decodedMetric) {
                        targetObj.telemetry.forEach(function(objTel) {
                            var telName = objTel.name;
                            var telMetricName = objTel.metricName;
                            if (telMetricName == decodedMetric.name) {
                                data.push({
                                    name: telName,
                                    value: decodedMetric.doubleValue.toFixed(1),
                                    timestamp: new Date()
                                });
                            }
                        });
                    });

                    cb(data);
                });
            }
        }

        function onConnect() {
            console.log("Connected to server");
            var topicName = "Red-Hat/+/iot-demo/+/+/alerts";
            client.subscribe(topicName);

        }

        function connectClient() {

            var brokerHostname = APP_CONFIG.BROKER_WEBSOCKET_HOSTNAME + '.' + $location.host().replace(/^.*?\.(.*)/g,"$1");
            client = new Paho.MQTT.Client(brokerHostname, Number(APP_CONFIG.BROKER_WEBSOCKET_PORT), "demo-client-" + guid());

            client.onConnectionLost = onConnectionLost;
            client.onMessageArrived = onMessageArrived;

            protobuf.load("kurapayload.proto", function(err, root) {
                if (err) throw err;

                msgproto = root.lookup("kuradatatypes.KuraPayload");
                // connect the client
                client.connect({
                    onSuccess:onConnect,
                    userName: APP_CONFIG.BROKER_USERNAME,
                    password: <PASSWORD>
                });
            });
        }

        function guid() {
            function s4() {
                return Math.floor((1 + Math.random()) * 0x10000)
                    .toString(16)
                    .substring(1);
            }
            return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
                s4() + '-' + s4() + s4() + s4();
        }

        factory.subscribePkg = function (pkg, listener) {

            var topicName = "Red-Hat/+/iot-demo/packages/" + pkg.sensor_id;
            client.subscribe(topicName);
            console.log("subscribed to " + topicName);
            listeners.push({
                pkg: pkg,
                topic: topicName,
                objType: 'packages',
                objId: pkg.sensor_id,
                listener: listener
            });
        };

        factory.subscribeVehicle = function (vehicle, listener) {

            var topicName = "Red-Hat/+/iot-demo/trucks/" + vehicle.vin;
            client.subscribe(topicName);
            console.log("subscribed to " + topicName);
            listeners.push({
                vehicle: vehicle,
                topic: topicName,
                objType: 'trucks',
                objId: vehicle.vin,
{'fraction_non_alphanumeric': 0.12018826693561943, 'fraction_numerical': 0.004790721129601614, 'mean_word_length': 1.2561623056503604, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6322487', 'n_tokens_mistral': 3126, 'n_tokens_neox': 2893, 'n_words': 523}