IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

TypeError: Cannot read property 'forEach' of undefined


Sujet :

JavaScript

  1. #1
    Nouveau membre du Club
    Homme Profil pro
    Consultant ERP
    Inscrit en
    Novembre 2007
    Messages
    40
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Consultant ERP

    Informations forums :
    Inscription : Novembre 2007
    Messages : 40
    Points : 26
    Points
    26
    Par défaut TypeError: Cannot read property 'forEach' of undefined
    Bonsoir à tous,

    Je suis novice sur le sujet JS, j'ai récupére un script afin de pouvoir communiquer avec mon alarme.

    Ce script tourne sur une Vm Ubuntu 18.4

    Lorsque je lance le script avec la commande :

    ./node-spc-jeedom.js

    j'ai le message d'erreur ci-après
    rodolphe@srvspcgwu:~/node-spc-jeedom$ ./node-spc-jeedom.js
    SPC WebSocket client connected
    /home/rodolphe/node-spc-jeedom/node-spc-jeedom.js:95
    data.zone.forEach(function(zone) {
    ^
    TypeError: Cannot read property 'forEach' of undefined
    at handleSpcZoneData (/home/rodolphe/node-spc-jeedom/node-spc-jeedom.js:95:15)
    at IncomingMessage.<anonymous> (/home/rodolphe/node-spc-jeedom/node-spc-jeedom.js:185:28)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
    Voici le code en question

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    #!/usr/bin/env node
    /*
    * Binding between SPC Web Gateway and Jeedom
    */
    /* Accept self signed certificate */
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    var config = require('./config.json');
    // SPC Websocket Client
    var ws_client = require('websocket').client;
    var spc_ws_client = new ws_client();
    // SPC Http Client
    var digest = require('./lib/http-digest-client');
    var spc_http_client = digest.createClient(config.spc_get_user, config.spc_get_password, true);
    // Jeedom Http Client
    var jeedom_http_client = require('http');
    // Update Jeedom with current SPC Areas and Zones status
    getSpcStatus('area', handleSpcAreaData);
    getSpcStatus('zone', handleSpcZoneData);
    // Listen on events from SPC
    spc_ws_client.connect('wss://' + config.spc_gw_host + ':' + config.spc_gw_port + '/ws/spc?username=' + config.spc_ws_user + '&password=' + config.spc_ws_password);
    spc_ws_client.on('connectFailed', function(error) {
        console.log('Connect Error: ' + error.toString());
    });
    spc_ws_client.on('connect', function(connection) {
        console.log('SPC WebSocket client connected');
        connection.on('error', function(error) {
            console.log("Connection Error: " + error.toString());
        });
        connection.on('close', function() {
            console.log('echo-protocol Connection Closed');
        });
        connection.on('message', function(message) {
            if (message.type === 'utf8') {
                manageSiaEvent(message.utf8Data);
            }
        });
    });
    /**********************************************************************
    * setJeedomVariable 
    **********************************************************************/
    function setJeedomVariable(Variable, value){
        var options = {
            hostname: config.jeedom_host,
            port: 80,
            path: '/core/api/jeeApi.php?apikey=' + config.jeedom_api + '&type=variable&name=' + Variable + '&value=' + value,
        };
        var req = jeedom_http_client.request(options);
        req.end();
    }
    /**********************************************************************
    * handleSpcAreaData
    **********************************************************************/
    function handleSpcAreaData(data) {
        data.area.forEach(function(area) {
            var area_mode = "unknown";
            switch (parseInt(area.mode)) {
                case 0:
                    area_mode = "unset";
                    break;
                case 1:
                    area_mode = "partset_a";
                    break;
                case 2:
                    area_mode = "partset_b";
                    break;
                case 3:
                    area_mode = "set";
                    break;
            }
            var modeVariable = 'Secteur_' + area.id;
            setJeedomVariable(modeVariable, area_mode);
        });
    }
    /**********************************************************************
    * handleSpcZoneData
    **********************************************************************/
    function handleSpcZoneData(data) {
        data.zone.forEach(function(zone) {
            if (zone.input != undefined) {
                var zone_input = "unknown";
                switch (parseInt(zone.input)) {
                    case 0:
                        zone_input = "0";
                        break;
                    case 1:
                        zone_input = "1";
                        break;
                    case 2:
                        zone_input = "1";
                        break;
                    case 3:
                        zone_input = "1";
                        break;
                    case 4:
                        zone_input = "1";
                        break;
                    case 5:
                        zone_input = "1";
                        break;
                    case 6:
                        zone_input = "1";
                        break;
                    case 7:
                        zone_input = "1";
                        break;
                }
                var inputVariable = 'ZONE_' + zone.id;
                setJeedomVariable(inputVariable, zone_input);
            }
            if (zone.status != undefined) {
                var zone_status = "unknown";
                switch (parseInt(zone.status)) {
                    case 0:
                        zone_status = "ok";
                        break;
                    case 1:
                        zone_status = "inhibit";
                        break;
                    case 2:
                        zone_status = "isolate";
                        break;
                    case 3:
                        zone_status = "soak";
                        break;
                    case 4:
                        zone_status = "tamper";
                        break;
                    case 5:
                        zone_status = "alarm";
                        break;
                    case 6:
                        zone_status = "ok";
                        break;
                    case 7:
                        zone_status = "trouble";
                        break;
                }
                var statusVariable = 'ZONE_' + zone.id + '_STATUS';
                setJeedomVariable(statusVariable, zone_status);
            }
        };
    }
    /**********************************************************************
    * getSpcStatus
    **********************************************************************/
    function getSpcStatus(uri, callback) {
        var options = {
            host: config.spc_gw_host,
            port: config.spc_gw_port,
            path: '/spc/' + uri,
            method: 'GET'
        }
        var reply = "";
        var req = spc_http_client.request(options, function(res) {
            res.setEncoding('utf8');
            res.on('data', function(chunk){
                reply += chunk;
            });
            res.on('end', function(){
                var data = JSON.parse(reply);
                if (data.status === 'success'){
                   callback && callback(data.data);
                }
                else {
                   console.log("Unable to get data from SPC: " + uri);
                }
            });
        });
    }
    /**********************************************************************
    * manageSiaEvent
    **********************************************************************/
    function manageSiaEvent(message){
        data = JSON.parse(message);
        if (data.status === 'success'){
            var sia = data.data.sia;
            sia_code    = sia.sia_code;
            sia_address = sia.sia_address;
            // Update status dependent on type of SIA event
            switch (sia_code){
                case 'BA': /* Burglar Alarm */
                case 'BR': /* Burglar Alarm Restore */
                    getSpcStatus('area', handleSpcAreaData);
                    getSpcStatus('zone', handleSpcZoneData);
                    break;
                case 'BB': /* Inhibited or Isolated */
                case 'BU': /* Deinhibited or Deisolated */
                    getSpcStatus('zone', handleSpcZoneData);
                    break;
                case 'CL': /* Area Activated (Full Set) - Closing Report - System armed normal */
                case 'NL': /* Area Activated (Part Set)  */
                case 'OP': /* Area Deactivated */
                case 'CQ': /* Close Area - System has been partially armed */
                case 'CG': /* Close Area - System has been partially armed */
                case 'OG': /* Area Deactivated (Part Set)  */
                case 'OQ': /* Area Deactivated */
                    getSpcStatus('area', handleSpcAreaData);
                    break;
                case 'ZC': /* Zone Closed */
                case 'ZO': /* Zone Opened */
                    var value = (sia_code == 'ZC') ? 0:1;
                    var data = {
                        zone: [
                            {
                                id: sia_address,
                                input: value
                            }
                        ]
                    }
                    handleSpcZoneData(data);
                    break;
            }
        }
    }
    D'avance merci pour votre aide

  2. #2
    Expert éminent
    Avatar de Watilin
    Homme Profil pro
    En recherche d'emploi
    Inscrit en
    Juin 2010
    Messages
    3 093
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : En recherche d'emploi

    Informations forums :
    Inscription : Juin 2010
    Messages : 3 093
    Points : 6 754
    Points
    6 754
    Par défaut
    Citation Envoyé par Nouss Voir le message
    data.zone.forEach(function(zone) {
    ^
    TypeError: Cannot read property 'forEach' of undefined
    Ça veut dire que data.zone est indéfini.

    Si j’en crois le code, data.zone est censé être un tableau. Peut-être est-ce data.zones avec un « s » ?
    La FAQ JavaScript – Les cours JavaScript
    Touche F12 = la console → l’outil indispensable pour développer en JavaScript !

  3. #3
    Nouveau membre du Club
    Homme Profil pro
    Consultant ERP
    Inscrit en
    Novembre 2007
    Messages
    40
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Consultant ERP

    Informations forums :
    Inscription : Novembre 2007
    Messages : 40
    Points : 26
    Points
    26
    Par défaut
    Bonjour @Watilin,


    J'ai essayer, mais pas mieux.

    Merci

  4. #4
    Expert éminent
    Avatar de Watilin
    Homme Profil pro
    En recherche d'emploi
    Inscrit en
    Juin 2010
    Messages
    3 093
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : En recherche d'emploi

    Informations forums :
    Inscription : Juin 2010
    Messages : 3 093
    Points : 6 754
    Points
    6 754
    Par défaut
    Même message d’erreur ? Et si tu ajoutes des console.log(data.zone) ou console.log(data), ça dit quoi ?
    La FAQ JavaScript – Les cours JavaScript
    Touche F12 = la console → l’outil indispensable pour développer en JavaScript !

  5. #5
    Nouveau membre du Club
    Homme Profil pro
    Consultant ERP
    Inscrit en
    Novembre 2007
    Messages
    40
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Consultant ERP

    Informations forums :
    Inscription : Novembre 2007
    Messages : 40
    Points : 26
    Points
    26
    Par défaut
    Oui même message d'erreur et rien avec les logs

    rodolphe@srvspcgwu:~/node-spc-jeedom$ ./node-spc-jeedom.js
    SPC WebSocket client connected
    /home/rodolphe/node-spc-jeedom/node-spc-jeedom.js:94
    data.zone.forEach(function(zone) {
    ^

    TypeError: Cannot read property 'forEach' of undefined
    at handleSpcZoneData (/home/rodolphe/node-spc-jeedom/node-spc-jeedom.js:94:15)
    at IncomingMessage.<anonymous> (/home/rodolphe/node-spc-jeedom/node-spc-jeedom.js:185:28)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

Discussions similaires

  1. Réponses: 0
    Dernier message: 27/11/2017, 23h21
  2. Réponses: 3
    Dernier message: 05/05/2017, 10h36
  3. Réponses: 3
    Dernier message: 01/06/2016, 20h45
  4. Erreur : TypeError: Cannot read property 'test' of undefined
    Par deathness dans le forum AngularJS
    Réponses: 1
    Dernier message: 11/05/2016, 10h42
  5. Réponses: 3
    Dernier message: 30/05/2015, 12h08

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo