Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. Skripten / Logik
    4. JavaScript
    5. Node.js Script in iobroker integrieren

    NEWS

    • 15. 05. Wartungsarbeiten am ioBroker Forum

    • Monatsrückblick - April 2025

    • Minor js-controller 7.0.7 Update in latest repo

    Node.js Script in iobroker integrieren

    This topic has been deleted. Only users with topic management privileges can see it.
    • UncleSam
      UncleSam Developer @rettroo last edited by

      @rettroo Du hast das Skript nicht genau so übernommen sondern noch Anpassungen gemacht. Kannst du bitte deine Version des Skriptes hier posten - sonst muss ich raten.

      Und wenn wir schon beim Raten sind: dir fehlen Anführungszeichen.

      R 1 Reply Last reply Reply Quote 0
      • R
        rettroo @UncleSam last edited by

        @unclesam

        const DigestFetch = require('digest-fetch');
        const net = require('net');
        const fs = require('fs');
        const path = require('path');
        const md5 = require('md5');
        const mqtt = require('mqtt');
        
        /**
         * Class to abstract a dahua doorbell.
         *
         * On instantiation it automatically connects with the doorbell, logs in and
         * subscribes to all events.
         *
         * When an event is received, it forwards it to the MQTT broker so other systems
         * can received those events. This behavior is very generic, users need to listen
         * to those MQTT messages and create their own integrations using something like
         * node-red for instance.
         *
         * In time this could be used to create a more user-friendly integration in home assistant,
         * but a doorbell is a complicated device and I don't know enough yet to decide how such
         * integration would look.
         */
        
        class DahuaVTO {
          deviceType;
          serialNumber;
        
          /**
           * {Number} requestId
           *
           * Our Request / Response ID that must be in all requests and initated by us.
           * This number auto-increments every time we send a message. Once we've logged in, every
           * response contains the request id of which it's a response of, se it could be used to
           * match responses with requests.
           *
           * I haven't bothered to do so because ,for what I saw, we only care about response order
           * for the initial setup, and we do that on request at a time.
           *
           * If we ever make requests in parallel and we need to associate response to each request,
           * we could use this. For not, it's just an auto-incremental number.
           * */
        
          requestId = 0;
        
          // Session ID will be returned after successful login
          /**
           * {Number} sessionId
           *
           * When we try to log in on the doorbell we get a sessionId. From that point on every message
           * we send over the socket needs to have include the sessionID for the doorbell to recognize us.
           */
          sessionId = 0;
        
          // Will be set after the login, but we initialize to 60s because it's a reasonable default
          /**
           * {Number} keepAliveInterval
           *
           * The number of seconds we have to space our keepAlive messages so the doorbell doesn't close
           * the connection.
           */
          keepAliveInterval = 60;
        
          /**
           * The ID returned by the `setInterval` call.
           * We keep a reference in case we want to cancel it (maybe in case of failure?)
           */
          _keepAliveTimer;
        
          /**
           * TCP socket to communicate with the doorbell external unit.
           */
          doorbellSocket;
        
          /**
           * MQTT client to publish (and maybe receive) messages.
           */
          mqttClient;
        
          constructor() {
            this.dahua_host = 10.0.0.11;
            this.dahua_username = admin;
            this.dahua_password = admin123;
            this.mqtt_broker_host = 10.0.0.10;
            this.mqtt_broker_port = 1883;
            this.mqtt_broker_username = ;
            this.mqtt_broker_password = ;
            this.mqtt_broker_topic_prefix = ;
            this.digestClient = new DigestFetch(
              this.dahua_username,
              this.dahua_password
            );
        
            this.getDeviceDetails().then(({ deviceType, serialNumber }) => {
              this.deviceType = deviceType;
              this.serialNumber = serialNumber;
              this.start();
            });
          }
        
          /**
           * Starts the app by:
           *    - Opening a TCP socket to the doorbell
           *    - Connecting to the MQTT broker
           *    - Authenticating with the doorbell and subscribing to events.
           */
          start() {
            this.setupDoorbellSocket();
            this.setupMQTT();
            this.initLogin();
          }
        
          /**
           * Makes a request to the doorbell using digest auth to retrieve the device's information.
           *
           * The information is returned in plain text (not JSON) that we have to parse.
           * For now I think we only care about device type and serial number, which can be
           * used to disambiguate in case we have more than one doorbell.
           */
          async getDeviceDetails() {
            return this.digestClient
              .fetch(
                `http://${this.dahua_host}/cgi-bin/magicBox.cgi?action=getSystemInfo`
              )
              .then((r) => r.text())
              .then((text) => {
                const deviceDetails = text
                  .trim()
                  .split('\n')
                  .reduce((obj, str) => {
                    const [key, val] = str.split('=');
                    obj[key] = val.trim();
                    return obj;
                  }, {});
                return deviceDetails;
              });
          }
        
          /**
           * Saves a snapshot of the doorbells image into the given directory (defaults to /tmp/).
           *
           * By default the file is named with a simple timestamp of the current time (YYYY-MM-DD-H-M-S.jpg)
           *
           */
          saveSnapshot(p = '/tmp/') {
            let now = new Date();
            let dateStr = `${now.getFullYear()}-${
              now.getMonth() + 1
            }-${now.getDate()}-${now.getHours()}-${now.getMinutes()}-${now.getSeconds()}`;
            let destination = path.join(p, `DoorBell_${dateStr}.jpg`);
            this.digestClient
              .fetch(`http://${this.dahua_host}/cgi-bin/snapshot.cgi`)
              .then((r) => {
                return r.buffer();
              })
              .then((buf) => {
                fs.writeFile(destination, buf, 'binary', function (err) {
                  if (err) {
                    console.error('Error saving snapshot to disk', err);
                  } else {
                    console.info('Snapshot saved');
                  }
                });
              });
          }
        
          /**
           * Creates the TCP socket connection with the doorbell on port 5000.
           *
           * Setups the listener for when we receive data over that socket
           *
           * Also setups other listeners for logging purposes mostly.
           *
           * If something goes wrong, we close everything and try to start over again.
           */
          setupDoorbellSocket() {
            let socket = new net.Socket({ readable: true, writable: true });
            socket.on('end', function () {
              console.log('Doorbell socket ended');
            });
            socket.on('close', function () {
              console.log('Doorbell socket closed');
              clearInterval(this._keepAliveTimer);
            });
            socket.on('data', this.receive.bind(this));
            socket.on('error', function (e) {
              console.error('Doorbell socket error', e);
              this.doorbellSocket.destroy(); // destroy the socket
              this.mqttClient.end(true); // End the mqtt connection right away.
              clearInterval(this._keepAliveTimer); // Stop sending keepalive requests
              this.start(); // Start over again.
            });
            this.doorbellSocket = socket.connect({ port: 5000, host: this.dahua_host });
          }
        
          /**
           * Configure an initialize the MQTT client.
           *
           * It configures the "Last Will and Testament" (LWT), which is the message send to MQTT
           * if this client gets disconnected in an ungraceful way (e.g. a fatal error).
           *
           * It also adds listeners that right now are only used for logging.
           */
          setupMQTT() {
            this.mqttClient = mqtt.connect({
              host: this.mqtt_broker_host,
              port: this.mqtt_broker_port,
              username: this.mqtt_broker_username,
              password: this.mqtt_broker_password,
              will: {
                topic: `${this.mqtt_broker_topic_prefix}/lwt`,
                payload: 'connected',
                qos: 1,
              },
            });
            this.mqttClient.on('disconnect', function (packet) {
              console.log('MQTTDisconnect', packet);
            });
            this.mqttClient.on('message', function (topic, message, packet) {
              console.log('MQTTMessage', { topic, message, packet });
            });
          }
        
          /**
           * Publishes to MQTT an event with the given name and payload.
           * @param {string} name
           * @param {object} payload
           */
          publishToMQTT(name, payload) {
            let message = JSON.stringify(payload);
            this.mqttClient.publish(
              `${this.mqtt_broker_topic_prefix}/${name}/Event`,
              message
            );
          }
        
          /**
           * Sends a message with the given data to the doorbell's outside unit using the TCP socket.
           * @param {string} data
           *
           * This is a fairly low level way of communication, so let's dive in.
           *
           * We write binary to the socket, so we have to use buffers.
           *
           * The first 32 bytes of the message are the header.
           * After the header we concat the actual message, which is a JSON string.
           * The header has some bits that are fixed and others that are the length of the message that will
           * come after.
           *
           * I didn't reverse-engineered this myself but it works. Take it as gospel as I did.
           */
          send(data) {
            let json = JSON.stringify(data);
            let buf = Buffer.alloc(32);
            let offset = buf.writeUInt32BE(0x20000000);
            offset = buf.writeUInt32BE(0x44484950, offset);
            offset = buf.writeDoubleBE(0, offset);
            offset = buf.writeUInt32LE(json.length, offset);
            offset = buf.writeUInt32LE(0, offset);
            offset = buf.writeUInt32LE(json.length, offset);
            offset = buf.writeUInt32LE(0, offset);
            buf = Buffer.concat([buf, Buffer.from(json)]);
            this.requestId += 1;
            this.doorbellSocket.write(buf);
          }
        
          /**
           * Handles received messages from the TCP socket.
           * @param {Buffer} buf
           *
           * The received messages are binary. Once discarded the first 32 bytes (the header),
           * the rest of the message is parsed as as a JSON string.
           *
           * The header contains the length of the received response in bytes 16..20 and the expected
           * length of the response in bytes 24..28 in case we need it, but I haven't found a
           * reason to. Perhaps responses might be sent in several chunks? So far it doesn't seem to be
           * the case.
           *
           * Since we always make requests in the exact same order, we know the first two responses are
           * for the authentication.
           * Subsequent responses can be either events or keepalive responses.
           */
          receive(buf) {
            let str = buf.slice(32).toString();
            let obj = JSON.parse(str);
            if (this.requestId === 1) {
              this.handleFirstLoginPayload(obj);
            } else if (this.requestId === 2) {
              this.handleSecondLoginPayload(obj);
            } else if (obj.method === 'client.notifyEventStream') {
              this.handleEvents(obj.params.eventList);
            } else {
              this.handleGenericPayload(obj);
            }
          }
        
          /**
           * Sends the initial login request.
           * Note that does not include any password.
           * The response to this request will be negative but that is expected, it will contain the
           * necessary information to login.
           */
          initLogin() {
            this.send({
              id: 10000,
              magic: '0x1234',
              method: 'global.login',
              params: {
                clientType: '',
                ipAddr: '(null)',
                loginType: 'Direct',
                password: '',
                userName: this.dahua_username,
              },
              session: 0,
            });
          }
        
          /**
           * Handles the response to the initial login request.
           *
           * The response contains a session ID, a realm and a random, which in combination with
           * the username and the password are used to generate an MD5 password that is used
           * for logging in.
           *
           * @param {object} payload
           */
          handleFirstLoginPayload({ session, params: { random, realm } }) {
            this.sessionId = session;
            let randomHash = this.genMD5Hash(random, realm);
            this.send({
              id: 10000, // I assume this ID a high number just because we have to send something.
              magic: '0x1234', // No idea what this is
              method: 'global.login',
              session: this.sessionId,
              params: {
                userName: this.dahua_username,
                password: randomHash,
                clientType: '',
                ipAddr: '(null)',
                loginType: 'Direct',
                authorityType: 'Default',
              },
            });
          }
        
          /**
           * Handles the response to the second (and last) response to login request.
           *
           * If successful, any subsequent message that includes the session id will be accepted for
           * as long as the socket is not closed.
           *
           * To prevent the socket from closing we send a keepalive message every so often.
           *
           * Also now that we're authenticated we subscribe to all events fired by the doorbell.
           */
          handleSecondLoginPayload(obj) {
            if (obj.result) {
              console.info('Logging to Dahua Doorbell successful');
              this.keepAliveInterval = obj.params.keepAliveInterval - 5;
              this.attachEventManager();
              this.keepConnectionAlive();
            } else {
              console.error('Failed to login. Response was: ', obj);
            }
          }
        
          /**
           * Handles any response not handled by any other method. I believe only keepalive responses
           * will end up here, but added some logging just in case.
           *
           * For now keepalive events are published to MQTT, but I don't see a good reason for that.
           */
          handleGenericPayload(obj) {
            if (
              obj.result === true &&
              obj.params &&
              Object.hasOwnProperty.call(obj.params, 'timeout')
            ) {
              console.info('Publish KeepAlive event');
              this.publishToMQTT('keepAlive', {
                deviceType: this.deviceType,
                serialNumber: this.serialNumber,
              });
            } else {
              console.error(
                'handleGenericPayload# Cannot handle received payload',
                obj
              );
            }
          }
        
          /**
           * Generates a MD5 digest of the username, password, realms and random to send as
           * password when logging in.
           * @param {*} random
           * @param {*} realm
           */
          genMD5Hash(random, realm) {
            const base_credentials = `${this.dahua_username}:${realm}:${this.dahua_password}`;
            const pwddb_hash = md5(base_credentials).toUpperCase();
            const base_pass = `${this.dahua_username}:${random}:${pwddb_hash}`;
            return md5(base_pass).toUpperCase();
          }
        
          /**
           * Sends the message to subscribe to all dorbell events.
           */
          attachEventManager() {
            this.send({
              id: this.requestId,
              magic: '0x1234',
              method: 'eventManager.attach',
              params: {
                codes: ['All'],
              },
              session: this.sessionId,
            });
          }
        
          /**
           * Handles the events sent by the doorbell.
           *
           * It just publishes those events along with some information of the device firing them
           * to MQTT
           */
          handleEvents(events) {
            events.forEach((event) => {
              console.info(`Publish event ${event.Code} to MQTT`);
              this.publishToMQTT(event.Code, {
                Action: event.eventAction,
                Data: event.Data,
                deviceType: this.deviceType,
                serialNumber: this.serialNumber,
              });
            });
          }
        
          /**
           * Sets up a function to be called periodically to keep the socket open by sending
           * keepalive messages.
           * @param {Number} delay (in seconds)
           */
          keepConnectionAlive(delay) {
            this._keepAliveTimer = setInterval(() => {
              let keepAlivePayload = {
                method: 'global.keepAlive',
                magic: '0x1234',
                params: {
                  timeout: delay,
                  active: true,
                },
                id: this.requestId,
                session: this.sessionId,
              };
        
              this.send(keepAlivePayload);
            }, this.keepAliveInterval * 1000);
          }
        
          /**
           * Remotely triggers the relay 1 (e.g. to open an electric gate).
           *
           * In my VTO 2202 F this also triggers the voice announcing the the door has been opened.
           */
          openDoor() {
            return this.digestClient
              .fetch(
                `http://${this.dahua_host}/cgi-bin/accessControl.cgi?action=openDoor&channel=1&UserID=101&Type=Remote`
              )
              .then((r) => {
                if (r.ok) {
                  console.info('Door relay triggered');
                } else {
                  console.error('Error triggering the door relay', e);
                }
              })
              .catch(e => console.error('Connection error triggering the door relay'));
          }
        
          // requestMissedCallsLog() {
          //   this.send({
          //     id: this.requestId,
          //     magic: '0x1234',
          //     method: 'RecordFinder.factory.create',
          //     params: {
          //       name: 'VideoTalkMissedLog',
          //     },
          //     session: this.sessionId,
          //   });
          // }
        
          // requestMissedCallsLog2(findToken) {
          //   this.send({
          //     id: this.requestId,
          //     magic: '0x1234',
          //     method: 'RecordFinder.startFind',
          //     object: findToken,
          //     params: { condition: null },
          //     session: this.sessionId,
          //   });
          // }
        
          // requestMissedCallsLog3(findToken) {
          //   this.send({
          //     id: this.requestId,
          //     magic: '0x1234',
          //     method: 'RecordFinder.doFind',
          //     object: findToken,
          //     params: { count: 3 }, // Number of calls to show
          //     session: this.sessionId,
          //   });
          // }
        };
        
        exports.default = DahuaVTO;
        
        new DahuaVTO();
        
        UncleSam 1 Reply Last reply Reply Quote 0
        • UncleSam
          UncleSam Developer @rettroo last edited by UncleSam

          @rettroo sagte in Node.js Script in iobroker integrieren:

          this.dahua_host = 10.0.0.11;
          this.dahua_username = admin;
          this.dahua_password = admin123;
          this.mqtt_broker_host = 10.0.0.10;
          

          Wie ich gesagt habe: dir fehlen Anführungszeichen. Strings müssen immer mit Anführungszeichen geschrieben werden. zB: this.dahua_host = "10.0.0.11"; Und leere Strings natürlich auch!

          R 1 Reply Last reply Reply Quote 0
          • R
            rettroo @UncleSam last edited by

            @unclesam

            Danke für deine Hilfe. Habe die variablen nun in "" gesetzt. Jetzt bekomme ich folgenden Fehler:

            javascript.0	2021-01-27 13:30:19.894	error	(954) at Script.runInContext (vm.js:130:18)
            javascript.0	2021-01-27 13:30:19.894	error	(954) at script.js.Dahua:517:1
            javascript.0	2021-01-27 13:30:19.894	error	(954) at new DahuaVTO (script.js.Dahua:88:26)
            javascript.0	2021-01-27 13:30:19.894	error	(954) TypeError: DigestFetch is not a constructor
            javascript.0	2021-01-27 13:30:19.894	error	(954) ^
            javascript.0	2021-01-27 13:30:19.894	error	(954) this.digestClient = new DigestFetch(
            javascript.0	2021-01-27 13:30:19.894	error	(954) script.js.Dahua: script.js.Dahua:88
            javascript.0	2021-01-27 13:30:19.893	error	(954) at Script.runInContext (vm.js:130:18)
            javascript.0	2021-01-27 13:30:19.893	error	(954) at script.js.Dahua:5:13
            javascript.0	2021-01-27 13:30:19.893	error	(954) at require (/opt/iobroker/node_modules/iobroker.javascript/lib/sandbox.js:389:36)
            javascript.0	2021-01-27 13:30:19.892	error	(954) at require (internal/modules/cjs/helpers.js:74:18)
            javascript.0	2021-01-27 13:30:19.892	error	(954) at Module.require (internal/modules/cjs/loader.js:903:19)
            javascript.0	2021-01-27 13:30:19.892	error	(954) script.js.Dahua: Error: Cannot find module '/opt/iobroker/node_modules/iobroker.javascript/lib/../../md5'
            javascript.0	2021-01-27 13:30:19.891	error	(954) at Script.runInContext (vm.js:130:18)
            javascript.0	2021-01-27 13:30:19.891	error	(954) at script.js.Dahua:1:21
            javascript.0	2021-01-27 13:30:19.891	error	(954) at require (/opt/iobroker/node_modules/iobroker.javascript/lib/sandbox.js:389:36)
            javascript.0	2021-01-27 13:30:19.891	error	(954) at require (internal/modules/cjs/helpers.js:74:18)
            javascript.0	2021-01-27 13:30:19.891	error	(954) at Module.require (internal/modules/cjs/loader.js:903:19)
            javascript.0	2021-01-27 13:30:19.891	error	(954) script.js.Dahua: Error: Cannot find module '/opt/iobroker/node_modules/iobroker.javascript/lib/../../digest-fetch'
            javascript.0	2021-01-27 13:30:19.883	info	(954) Start javascript script.js.Dahua
            
            UncleSam 1 Reply Last reply Reply Quote 0
            • UncleSam
              UncleSam Developer @rettroo last edited by

              @rettroo Hast du denn digest-fetch bei den benötigten Node Modulen im JavaScript Adapter angegeben?

              R 1 Reply Last reply Reply Quote 0
              • R
                rettroo @UncleSam last edited by

                @unclesam
                ist das so korrekt?
                01d92ec4-06fa-4d12-ac41-0ffbf11bc1ac-image.png

                Ich komme der Sache näher, zumindest war MQTT schon kurz verbunden. nun geht aber die javascript Instanz auf Rot kurz nach dem Start des Scriptes.

                
                host.debian	2021-01-27 14:43:01.777	info	Restart adapter system.adapter.javascript.0 because enabled
                host.debian	2021-01-27 14:43:01.777	error	instance system.adapter.javascript.0 terminated with code 1 (JS_CONTROLLER_STOPPED)
                host.debian	2021-01-27 14:43:01.776	error	Caught by controller[0]: at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
                host.debian	2021-01-27 14:43:01.776	error	Caught by controller[0]: at Socket.Readable.push (_stream_readable.js:214:10)
                host.debian	2021-01-27 14:43:01.776	error	Caught by controller[0]: at readableAddChunk (_stream_readable.js:273:9)
                host.debian	2021-01-27 14:43:01.776	error	Caught by controller[0]: at addChunk (_stream_readable.js:298:12)
                host.debian	2021-01-27 14:43:01.776	error	Caught by controller[0]: at Socket.EventEmitter.emit (domain.js:483:12)
                host.debian	2021-01-27 14:43:01.776	error	Caught by controller[0]: at Socket.emit (events.js:314:20)
                host.debian	2021-01-27 14:43:01.776	error	Caught by controller[0]: at DahuaVTO.receive (script.js.Dahua:288:12)
                host.debian	2021-01-27 14:43:01.776	error	Caught by controller[0]: at DahuaVTO.handleSecondLoginPayload (script.js.Dahua:358:15)
                host.debian	2021-01-27 14:43:01.775	error	Caught by controller[0]: TypeError: console.info is not a function
                mqtt.0	2021-01-27 14:43:01.772	info	(9477) Client [mqttjs_d9328b8b] connection closed: closed
                javascript.0	2021-01-27 14:43:01.751	error	(9509) at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
                javascript.0	2021-01-27 14:43:01.751	error	(9509) at Socket.Readable.push (_stream_readable.js:214:10)
                javascript.0	2021-01-27 14:43:01.751	error	(9509) at readableAddChunk (_stream_readable.js:273:9)
                javascript.0	2021-01-27 14:43:01.751	error	(9509) at addChunk (_stream_readable.js:298:12)
                javascript.0	2021-01-27 14:43:01.751	error	(9509) at Socket.EventEmitter.emit (domain.js:483:12)
                javascript.0	2021-01-27 14:43:01.751	error	(9509) at Socket.emit (events.js:314:20)
                javascript.0	2021-01-27 14:43:01.751	error	(9509) at DahuaVTO.receive (script.js.Dahua:288:12)
                javascript.0	2021-01-27 14:43:01.751	error	(9509) at DahuaVTO.handleSecondLoginPayload (script.js.Dahua:358:15)
                javascript.0	2021-01-27 14:43:01.750	error	(9509) script.js.Dahua: TypeError: console.info is not a function
                mqtt.0	2021-01-27 14:43:01.717	info	(9477) Client [mqttjs_d9328b8b] connected with secret 1611754981716_9127
                javascript.0	2021-01-27 14:43:01.610	info	(9509) script.js.Dahua: registered 0 subscriptions and 0 schedules
                javascript.0	2021-01-27 14:43:01.554	info	(9509) Start javascript script.js.Dahua
                javascript.0	2021-01-27 14:43:01.554	info	(9509) script.js.Test: registered 1 subscription and 0 schedules
                javascript.0	2021-01-27 14:43:01.552	info	(9509) Start javascript script.js.Test
                javascript.0	2021-01-27 14:43:01.551	info	(9509) script.js.Feueralarm: registered 1 subscription and 0 schedules
                javascript.0	2021-01-27 14:43:01.550	info	(9509) Start javascript script.js.Feueralarm
                javascript.0	2021-01-27 14:43:01.548	info	(9509) script.js.Magic: registered 5 subscriptions and 0 schedules
                javascript.0	2021-01-27 14:43:01.547	info	(9509) Start javascript script.js.Magic
                javascript.0	2021-01-27 14:43:01.546	info	(9509) script.js.Licht_WZ: registered 3 subscriptions and 0 schedules
                javascript.0	2021-01-27 14:43:01.540	info	(9509) Start javascript script.js.Licht_WZ
                javascript.0	2021-01-27 14:43:01.540	info	(9509) script.js.BWM: registered 1 subscription and 0 schedules
                javascript.0	2021-01-27 14:43:01.523	info	(9509) Start javascript script.js.BWM
                javascript.0	2021-01-27 14:43:01.419	info	(9509) received all states
                javascript.0	2021-01-27 14:43:01.395	info	(9509) received all objects
                javascript.0	2021-01-27 14:43:00.835	info	(9509) requesting all objects
                javascript.0	2021-01-27 14:43:00.834	info	(9509) requesting all states
                javascript.0	2021-01-27 14:43:00.782	info	(9509) starting. Version 4.8.4 in /opt/iobroker/node_modules/iobroker.javascript, node: v12.19.0, js-controller: 3.1.6
                host.debian	2021-01-27 14:42:59.455	info	instance system.adapter.javascript.0 started with pid 9509
                host.debian	2021-01-27 14:42:29.445	info	Restart adapter system.adapter.javascript.0 because enabled
                host.debian	2021-01-27 14:42:29.445	error	instance system.adapter.javascript.0 terminated with code 1 (JS_CONTROLLER_STOPPED)
                host.debian	2021-01-27 14:42:29.445	error	Caught by controller[0]: at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
                host.debian	2021-01-27 14:42:29.445	error	Caught by controller[0]: at Socket.Readable.push (_stream_readable.js:214:10)
                host.debian	2021-01-27 14:42:29.444	error	Caught by controller[0]: at readableAddChunk (_stream_readable.js:273:9)
                host.debian	2021-01-27 14:42:29.444	error	Caught by controller[0]: at addChunk (_stream_readable.js:298:12)
                host.debian	2021-01-27 14:42:29.444	error	Caught by controller[0]: at Socket.EventEmitter.emit (domain.js:483:12)
                host.debian	2021-01-27 14:42:29.444	error	Caught by controller[0]: at Socket.emit (events.js:314:20)
                host.debian	2021-01-27 14:42:29.444	error	Caught by controller[0]: at DahuaVTO.receive (script.js.Dahua:288:12)
                host.debian	2021-01-27 14:42:29.444	error	Caught by controller[0]: at DahuaVTO.handleSecondLoginPayload (script.js.Dahua:358:15)
                host.debian	2021-01-27 14:42:29.442	error	Caught by controller[0]: TypeError: console.info is not a function
                mqtt.0	2021-01-27 14:42:29.442	info	(9477) Client [mqttjs_d19a512b] connection closed: Error: read ECONNRESET
                mqtt.0	2021-01-27 14:42:29.378	info	(9477) Client [mqttjs_d19a512b] connected with secret 1611754949376_714
                javascript.0	2021-01-27 14:42:29.410	error	(9494) at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
                javascript.0	2021-01-27 14:42:29.410	error	(9494) at Socket.Readable.push (_stream_readable.js:214:10)
                javascript.0	2021-01-27 14:42:29.410	error	(9494) at readableAddChunk (_stream_readable.js:273:9)
                javascript.0	2021-01-27 14:42:29.410	error	(9494) at addChunk (_stream_readable.js:298:12)
                javascript.0	2021-01-27 14:42:29.409	error	(9494) at Socket.EventEmitter.emit (domain.js:483:12)
                javascript.0	2021-01-27 14:42:29.409	error	(9494) at Socket.emit (events.js:314:20)
                javascript.0	2021-01-27 14:42:29.409	error	(9494) at DahuaVTO.receive (script.js.Dahua:288:12)
                javascript.0	2021-01-27 14:42:29.409	error	(9494) at DahuaVTO.handleSecondLoginPayload (script.js.Dahua:358:15)
                javascript.0	2021-01-27 14:42:29.407	error	(9494) script.js.Dahua: TypeError: console.info is not a function
                javascript.0	2021-01-27 14:42:29.270	info	(9494) script.js.Dahua: registered 0 subscriptions and 0 schedules
                javascript.0	2021-01-27 14:42:29.206	info	(9494) Start javascript script.js.Dahua
                
                UncleSam 1 Reply Last reply Reply Quote 0
                • UncleSam
                  UncleSam Developer @rettroo last edited by

                  @rettroo Jawohl, alles richtig. Das einzige was du wohl noch anpassen musst: alles was console.<irgendwas>()ist musst du umschreiben nach log(). Denn Konsolen-Logging gibt es keines im JavaScript Adapter.

                  R 1 Reply Last reply Reply Quote 0
                  • R
                    rettroo @UncleSam last edited by rettroo

                    @unclesam
                    Danke, das Script läuft!

                    1 Reply Last reply Reply Quote 0
                    • R
                      rettroo last edited by

                      Ich benötige hier bitte noch Unterstützung. Ich bekomme in MQTT folgenden String

                      {"Data":{"CardNo":"b01xx636","CardType":null,"LocaleTime":"2021-01-28 15:47:08","Method":1,"Name":"OpenDoor","Password":"","ReaderID":"1","RecNo":96,"SnapURL":"","Status":1,"Type":"Entry","UTC":1611848828,"UserID":"2"},"deviceType":"VTO4202F","serialNumber":"6K0xxxxxxx20A0"}
                      

                      Ich benötige in dem Fall nur die User ID in 0_userdata.0.DahuaUserID

                      R 1 Reply Last reply Reply Quote 0
                      • R
                        rettroo @rettroo last edited by rettroo

                        @UncleSam
                        Ich habe mir nun was zusammengebastelt.
                        Der Datenpunkt "serialNumber" wird geschrieben, der "UserID" nicht. Wie gebe ich den richtig an, da er ja nochmal in "Data" verschachtelt ist.

                        on({id: "mqtt.0.DahuaVTO.AccessControl.Event", change: "any"}, function (obj) { ParseCommand(obj); });
                         
                        function ParseCommand(obj) {
                         
                          let value = obj.state.val;
                        
                          let serialNumber = "";
                          let UserID = "";
                         
                           
                          try { 
                            obj = JSON.parse(value);
                          
                            serialNumber = obj.serialNumber;
                            UserID = obj.UserID;
                           
                            setState('0_userdata.0.serialNumber', (serialNumber));
                            setState('0_userdata.0.UserID', (UserID));
                            
                          } catch (e) {
                            return;
                          }
                        }
                        

                        Sonst sauber programmiert?

                        UncleSam 1 Reply Last reply Reply Quote 0
                        • UncleSam
                          UncleSam Developer @rettroo last edited by

                          @rettroo sagte in Node.js Script in iobroker integrieren:

                          Wie gebe ich den richtig an, da er ja nochmal in "Data" verschachtelt ist.

                          Einfach mit einem Punkt dazwischen: obj.Data.UserID

                          R 1 Reply Last reply Reply Quote 1
                          • pseudoreal
                            pseudoreal last edited by

                            könntest Du bitte eine Anleitung für "Dummies" erstellen? Was genau muss zu erst installiert werden? Danke

                            R 1 Reply Last reply Reply Quote 0
                            • R
                              rettroo @pseudoreal last edited by

                              @pseudoreal
                              Hi, kann ich machen sobald ich alles fertig habe. Die Dahua hängt zur Zeit auch noch nicht an der Tür sondern in meinem Büro 😉

                              pseudoreal 1 Reply Last reply Reply Quote 1
                              • R
                                rettroo @UncleSam last edited by

                                Hi @unclesam,

                                das Script hat soweit schon ganz gut funktioniert, nun startet es aber nicht mehr und ich bekomme folgenden Fehler.
                                Was hat es mit dem MD5 auf sich?

                                
                                host.debian	2021-03-10 14:02:45.431	info	instance system.adapter.javascript.0 started with pid 2673
                                host.debian	2021-03-10 14:02:15.418	info	Restart adapter system.adapter.javascript.0 because enabled
                                host.debian	2021-03-10 14:02:15.418	error	instance system.adapter.javascript.0 terminated with code 1 (JS_CONTROLLER_STOPPED)
                                host.debian	2021-03-10 14:02:15.418	error	Caught by controller[0]: at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
                                host.debian	2021-03-10 14:02:15.418	error	Caught by controller[0]: at Socket.Readable.push (_stream_readable.js:214:10)
                                host.debian	2021-03-10 14:02:15.418	error	Caught by controller[0]: at readableAddChunk (_stream_readable.js:273:9)
                                host.debian	2021-03-10 14:02:15.418	error	Caught by controller[0]: at addChunk (_stream_readable.js:298:12)
                                host.debian	2021-03-10 14:02:15.418	error	Caught by controller[0]: at Socket.EventEmitter.emit (domain.js:483:12)
                                host.debian	2021-03-10 14:02:15.417	error	Caught by controller[0]: at Socket.emit (events.js:314:20)
                                host.debian	2021-03-10 14:02:15.417	error	Caught by controller[0]: at DahuaVTO.receive (script.js.DAHUA.Dahua_Script:287:12)
                                host.debian	2021-03-10 14:02:15.417	error	Caught by controller[0]: at DahuaVTO.handleFirstLoginPayload (script.js.DAHUA.Dahua_Script:330:27)
                                host.debian	2021-03-10 14:02:15.417	error	Caught by controller[0]: at DahuaVTO.genMD5Hash (script.js.DAHUA.Dahua_Script:401:24)
                                host.debian	2021-03-10 14:02:15.417	error	Caught by controller[0]: TypeError: md5 is not a function
                                mqtt.0	2021-03-10 14:02:15.400	info	(1533) Client [mqttjs_09066ccf] connection closed: closed
                                javascript.0	2021-03-10 14:02:15.386	error	(2658) at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
                                javascript.0	2021-03-10 14:02:15.385	error	(2658) at Socket.Readable.push (_stream_readable.js:214:10)
                                javascript.0	2021-03-10 14:02:15.385	error	(2658) at readableAddChunk (_stream_readable.js:273:9)
                                javascript.0	2021-03-10 14:02:15.385	error	(2658) at addChunk (_stream_readable.js:298:12)
                                javascript.0	2021-03-10 14:02:15.385	error	(2658) at Socket.EventEmitter.emit (domain.js:483:12)
                                javascript.0	2021-03-10 14:02:15.385	error	(2658) at Socket.emit (events.js:314:20)
                                javascript.0	2021-03-10 14:02:15.385	error	(2658) at DahuaVTO.receive (script.js.DAHUA.Dahua_Script:286:12)
                                javascript.0	2021-03-10 14:02:15.385	error	(2658) at DahuaVTO.handleFirstLoginPayload (script.js.DAHUA.Dahua_Script:329:27)
                                javascript.0	2021-03-10 14:02:15.385	error	(2658) at DahuaVTO.genMD5Hash (script.js.DAHUA.Dahua_Script:400:24)
                                javascript.0	2021-03-10 14:02:15.385	error	(2658) script.js.DAHUA.Dahua_Script: TypeError: md5 is not a function
                                mqtt.0	2021-03-10 14:02:15.356	info	(1533) Client [mqttjs_09066ccf] connected with secret 1615381335356_7933
                                javascript.0	2021-03-10 14:02:15.292	info	(2658) script.js.DAHUA.Dahua_Script: registered 0 subscriptions and 0 schedules
                                javascript.0	2021-03-10 14:02:15.246	error	(2658) at Script.runInContext (vm.js:130:18)
                                javascript.0	2021-03-10 14:02:15.246	error	(2658) at script.js.DAHUA.Dahua_Script:518:3
                                javascript.0	2021-03-10 14:02:15.246	error	(2658) at script.js.DAHUA.Dahua_Script:5:13
                                javascript.0	2021-03-10 14:02:15.245	error	(2658) at require (/opt/iobroker/node_modules/iobroker.javascript/lib/sandbox.js:397:36)
                                javascript.0	2021-03-10 14:02:15.245	error	(2658) at require (internal/modules/cjs/helpers.js:74:18)
                                javascript.0	2021-03-10 14:02:15.245	error	(2658) at Module.require (internal/modules/cjs/loader.js:903:19)
                                javascript.0	2021-03-10 14:02:15.245	error	(2658) script.js.DAHUA.Dahua_Script: Error: Cannot find module '/opt/iobroker/node_modules/iobroker.javascript/lib/../../md5'
                                
                                UncleSam 1 Reply Last reply Reply Quote 0
                                • UncleSam
                                  UncleSam Developer @rettroo last edited by

                                  @rettroo Hast du das md5 Modul installiert?

                                  const md5 = require('md5');

                                  Sollte eigentlich schief gehen, wenn du md5 nicht installiert hast, was ich etwas komisch finde. Hast du das etwa aus dem Skript gelöscht?

                                  1 Reply Last reply Reply Quote 0
                                  • pseudoreal
                                    pseudoreal @rettroo last edited by

                                    @rettroo
                                    also ich habe jetzt den MQTT server installiert. Das Script in Javascript erstellt und alle Instanzen gestartet. Ich bekomme den Fehler:
                                    (20360) FetchError: request to https://192.168.178.10:443/cgi-bin/magicBox.cgi?action=getSystemInfo failed, reason: unable to verify the first certificate

                                    Unter Instanzen ist jedoch MQTT gelb und auch im Script sebst sind mir einige Zeilen als Fehler unterstrichen - zB const DigestFetch = require('digest-fetch');
                                    md5 und digest-fetch sind aber in der JavaScript instanz aktiviert.

                                    UncleSam R 2 Replies Last reply Reply Quote 0
                                    • UncleSam
                                      UncleSam Developer @pseudoreal last edited by

                                      @pseudoreal sagte in Node.js Script in iobroker integrieren:

                                      request to https://192.168.178.10:443/cgi-bin/magicBox.cgi?action=getSystemInfo failed, reason: unable to verify the first certificate

                                      Da steht ja die Fehlermeldung. Du machst HTTPS und das Zertifikat ist ungültig. Muss es denn HTTPS sein? Wie du die Zertifikatsüberprüfung ausschaltest, kann ich dir leider auch nicht sagen (ich kenne digest-fetch nicht).

                                      1 Reply Last reply Reply Quote 0
                                      • R
                                        rettroo @pseudoreal last edited by

                                        @pseudoreal

                                        Hi,

                                        wie von @UncleSam angemerkt würde ich das "s" mal weglassen also "http://

                                        MQTT sollte erst grün werden wenn sich das Script mit Dahua verbindet

                                        pseudoreal 1 Reply Last reply Reply Quote 0
                                        • pseudoreal
                                          pseudoreal @rettroo last edited by

                                          @rettroo @UncleSam
                                          ok, ich habe das https weggelassen uns nun klappt die Verbindung und ich sehe auch im Script log, wenn sich jemand bewegt (VideoEvent) oder jemand klingelt (Invite).

                                          Jetzt fehlt mir nur noch die Information wie ich diese in iobroker weiterverarbeite, damit mir zB eine WhatsApp geschickt wird. Habe hier schon gesucht, aber leider nichts gefunden - wahrscheinlich falsche Suchbegriffe. Habt ihr irgendwo ein gutes Tutorial, wie man nun mit den Werten in MQTT weiterarbeitet?

                                          UncleSam 1 Reply Last reply Reply Quote 0
                                          • UncleSam
                                            UncleSam Developer @pseudoreal last edited by

                                            @pseudoreal sagte in Node.js Script in iobroker integrieren:

                                            Jetzt fehlt mir nur noch die Information wie ich diese in iobroker weiterverarbeite, damit mir zB eine WhatsApp geschickt wird. Habe hier schon gesucht, aber leider nichts gefunden - wahrscheinlich falsche Suchbegriffe. Habt ihr irgendwo ein gutes Tutorial, wie man nun mit den Werten in MQTT weiterarbeitet?

                                            @pseudoreal Du füllst Datenpunkte ab und schreibst Skripte, Blocklys oder machst Rules. Das hat dann nichts mehr mit deinem Skript zu tun sondern ist ganz gewöhnliches Skripting in ioBroker.

                                            pseudoreal 1 Reply Last reply Reply Quote 0
                                            • First post
                                              Last post

                                            Support us

                                            ioBroker
                                            Community Adapters
                                            Donate

                                            879
                                            Online

                                            31.6k
                                            Users

                                            79.4k
                                            Topics

                                            1.3m
                                            Posts

                                            7
                                            33
                                            4597
                                            Loading More Posts
                                            • Oldest to Newest
                                            • Newest to Oldest
                                            • Most Votes
                                            Reply
                                            • Reply as topic
                                            Log in to reply
                                            Community
                                            Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen
                                            The ioBroker Community 2014-2023
                                            logo