Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. Entwicklung
    4. Funktion innerhalb der main.js aufrufen gelingt nicht

    NEWS

    • Neuer Blog: Fotos und Eindrücke aus Solingen

    • ioBroker@Smart Living Forum Solingen, 14.06. - Agenda added

    • ioBroker goes Matter ... Matter Adapter in Stable

    Funktion innerhalb der main.js aufrufen gelingt nicht

    This topic has been deleted. Only users with topic management privileges can see it.
    • R
      reutli last edited by

      Hallo Leute,

      als Youngster im Bereich Adapter-Entwicklung bin ich gerade am Verzweifeln.... 😥 😞 😥

      Ich habe unter node funktionierende Funktionen geschrieben, die ich jetzt in meinen Adapter Portieren möchte.
      Dazu habe ich die iobroker-Testumgebung aufgebaut, mit Webstorm programmiert, GIT installiert und dann mit iobroker/create-adapter v1.23.0 einen Adapter hochgezogen. Bis hierhin hat alles wunderbar geklappt.

      Jetzt wollte ich meine "Login-Funktion" ( async function login() ) innerhalb der main.js einfügen und bei der Initialisierung des Adapters aufrufen ( login(); ).
      Leider wird die Funktion aber nicht aufgerufen und alles nach dem Aufruf wird auch nicht mehr ausgeführt.

      Hier mein Code:

      'use strict';
      
      /*
       * Created with @iobroker/create-adapter v1.23.0
       */
      
      // The adapter-core module gives you access to the core ioBroker functions
      // you need to create an adapter
      const utils = require('@iobroker/adapter-core');
      
      // Load your modules here, e.g.:
      const fetch = require('node-fetch');
      const { URLSearchParams } = require('url');
      const request = require('request');
      const qs = require('querystring');
      const fs = require('fs');
      const cron = require('node-cron');
      const appKey   = 'xyz'; //do not delete or change this!
      
      class HusqvarnaMowers extends utils.Adapter {
      
      	/**
      	 * @param {Partial<ioBroker.AdapterOptions>} [options={}]
      	 */
      	constructor(options) {
      		super({
      			...options,
      			name: 'husqvarna_mowers',
      		});
      		this.on('ready', this.onReady.bind(this));
      		this.on('objectChange', this.onObjectChange.bind(this));
      		this.on('stateChange', this.onStateChange.bind(this));
      		// this.on('message', this.onMessage.bind(this));
      		this.on('unload', this.onUnload.bind(this));
      	}
      
      
      // === Login Funktion auf Husqvarna Authentifizierungs-Server ===
      
      	async function login() {
      		const params = new URLSearchParams();
      		params.set('grant_type', 'password');
      		params.set('client_id', appKey);
      		params.set('username', this.config.Username);
      		params.set('password', this.config.Passwort);
      
      		const res = await fetch('https://api.authentication.husqvarnagroup.dev/v1/oauth2/token', {
      			method: 'POST',
      			body: params
      		});
      
      		if (!res.ok) {
      			this.log.error('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
      			this.log.error('Login fehlgeschlagen! Fehler: ' + res.statusText);
      			this.log.error('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
      			this.log.error('');
      			throw new Error(res.statusText);
      		} else {
      			const ergebnis = await res.json();
      			//const jsonString = JSON.stringify(ergebnis, null, 2); //Formatierung des JSON zur Speicherung als Datei
      			//fs.writeFile('./login.json', jsonString, err => {
      			//	if (err) {
      			//		console.log('Error writing file', err)
      			//	} else {
      			//		console.log('*** Login Daten (Login.json) - Successfully wrote file ***')
      			//	}
      			this.log.info('Login erfolgreich !!! --> erhaltener TOKEN: ' + ergebnis.access_token);
      			return ergebnis.acess_token;
      		}
      
      	};
      
      // -> Ende LOGIN Funktion
      
      
      	/**
      	 * Is called when databases are connected and adapter received configuration.
      	 */
      
      	async onReady() {
      		// Initialize your adapter here
      
      		// The adapters config (in the instance object everything under the attribute "native") is accessible via
      		// this.config:
      		this.log.info('config Username: ' + this.config.Username);
      		if (this.config.Passwort !== '') {
      			this.log.info('config Passwort: wurde gesetzt');
      		}
      		else this.log.error('Passwort nicht gesetzt!!!');
      
      		login();
      
      
      
      
      		/*
      		For every state in the system there has to be also an object of type state
      		Here a simple template for a boolean variable named "testVariable"
      		Because every adapter instance uses its own unique namespace variable names can't collide with other adapters variables
      		*/
      		await this.createDevice('test');
      
      		await this.setObjectAsync('test.testVariable', {
      			type: 'state',
      			common: {
      				name: 'testVariable',
      				type: 'boolean',
      				role: 'indicator',
      				read: true,
      				write: true,
      			},
      			native: {},
      		});
      
      
      
      		// in this template all states changes inside the adapters namespace are subscribed
      		this.subscribeStates('*');
      
      		/*
      		setState examples
      		you will notice that each setState will cause the stateChange event to fire (because of above subscribeStates cmd)
      		*/
      		// the variable testVariable is set to true as command (ack=false)
      		await this.setStateAsync('testVariable', true);
      
      		// same thing, but the value is flagged "ack"
      		// ack should be always set to true if the value is received from or acknowledged from the target system
      		await this.setStateAsync('testVariable', { val: true, ack: true });
      
      		// same thing, but the state is deleted after 30s (getState will return null afterwards)
      		await this.setStateAsync('testVariable', { val: true, ack: true, expire: 30 });
      
      		// examples for the checkPassword/checkGroup functions
      		let result = await this.checkPasswordAsync('admin', 'iobroker');
      		this.log.info('check user admin pw iobroker: ' + result);
      
      		result = await this.checkGroupAsync('admin', 'admin');
      		this.log.info('check group user admin group admin: ' + result);
      
      	}
      
      	/**
      	 * Is called when adapter shuts down - callback has to be called under any circumstances!
      	 * @param {() => void} callback
      	 */
      	onUnload(callback) {
      		try {
      			this.log.info('cleaned everything up...');
      			callback();
      		} catch (e) {
      			callback();
      		}
      	}
      
      	/**
      	 * Is called if a subscribed object changes
      	 * @param {string} id
      	 * @param {ioBroker.Object | null | undefined} obj
      	 */
      	onObjectChange(id, obj) {
      		if (obj) {
      			// The object was changed
      			this.log.info(`object ${id} changed: ${JSON.stringify(obj)}`);
      		} else {
      			// The object was deleted
      			this.log.info(`object ${id} deleted`);
      		}
      	}
      
      	/**
      	 * Is called if a subscribed state changes
      	 * @param {string} id
      	 * @param {ioBroker.State | null | undefined} state
      	 */
      	onStateChange(id, state) {
      		if (state) {
      			// The state was changed
      			this.log.info(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
      		} else {
      			// The state was deleted
      			this.log.info(`state ${id} deleted`);
      		}
      	}
      
      	// /**
      	//  * Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
      	//  * Using this method requires "common.message" property to be set to true in io-package.json
      	//  * @param {ioBroker.Message} obj
      	//  */
      	// onMessage(obj) {
      	// 	if (typeof obj === 'object' && obj.message) {
      	// 		if (obj.command === 'send') {
      	// 			// e.g. send email or pushover or whatever
      	// 			this.log.info('send command');
      
      	// 			// Send response in callback if required
      	// 			if (obj.callback) this.sendTo(obj.from, obj.command, 'Message received', obj.callback);
      	// 		}
      	// 	}
      	// }
      
      
      }
      
      
      
      // @ts-ignore parent is a valid property on module
      if (module.parent) {
      	// Export the constructor in compact mode
      	/**
      	 * @param {Partial<ioBroker.AdapterOptions>} [options={}]
      	 */
      	module.exports = (options) => new HusqvarnaMowers(options);
      } else {
      	// otherwise start the instance directly
      	new HusqvarnaMowers();
      }
      

      Was mache ich denn falsch???

      Danke und Gruss

      OliverIO 1 Reply Last reply Reply Quote 0
      • OliverIO
        OliverIO @reutli last edited by

        @reutli

        this.login();

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

          @OliverIO sagte in Funktion innerhalb der main.js aufrufen gelingt nicht:

          @reutli

          this.login();

          Hallo,
          danke für die schnelle Antwort. Tut leider auch nicht er meldet im Log

          host.iMac-Micha.local	2020-04-12 18:47:14.826	error	instance system.adapter.husqvarna_mowers.0 terminated with code 1 (JS_CONTROLLER_STOPPED)
          host.iMac-Micha.local	2020-04-12 18:47:14.826	error	Caught by controller[0]: at internal/main/run_main_module.js:18:47
          host.iMac-Micha.local	2020-04-12 18:47:14.826	error	Caught by controller[0]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
          host.iMac-Micha.local	2020-04-12 18:47:14.826	error	Caught by controller[0]: at Function.Module._load (internal/modules/cjs/loader.js:901:14)
          host.iMac-Micha.local	2020-04-12 18:47:14.826	error	Caught by controller[0]: at Module.load (internal/modules/cjs/loader.js:1002:32)
          host.iMac-Micha.local	2020-04-12 18:47:14.826	error	Caught by controller[0]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
          host.iMac-Micha.local	2020-04-12 18:47:14.826	error	Caught by controller[0]: at Module._compile (internal/modules/cjs/loader.js:1122:27)
          host.iMac-Micha.local	2020-04-12 18:47:14.826	error	Caught by controller[0]: at wrapSafe (internal/modules/cjs/loader.js:1072:16)
          host.iMac-Micha.local	2020-04-12 18:47:14.826	error	Caught by controller[0]: SyntaxError: Unexpected identifier
          host.iMac-Micha.local	2020-04-12 18:47:14.825	error	Caught by controller[0]: ^^^^^
          host.iMac-Micha.local	2020-04-12 18:47:14.825	error	Caught by controller[0]: async function login() {
          host.iMac-Micha.local	2020-04-12 18:47:14.825	error	Caught by controller[0]: /usr/local/iobroker/node_modules/iobroker.husqvarna_mowers/main.js:40
          
          

          Habe ich die Funktion an der richtigen Stelle eingesetzt?

          OliverIO 1 Reply Last reply Reply Quote 0
          • OliverIO
            OliverIO @reutli last edited by

            @reutli

            das this gehört da hin wo die funktion aufgerufen wird und nicht da wo sie definiert wird.

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

              @OliverIO sagte in Funktion innerhalb der main.js aufrufen gelingt nicht:

              @reutli

              das this gehört da hin wo die funktion aufgerufen wird und nicht da wo sie definiert wird.

              Das habe ich nicht verstanden, sorry.

              Ich definiere ja an einer Stelle die Funktion und an anderer Stelle rufe ich die Funktion dann mit "this login();" auf.
              Das habe ich auch so gemacht (siehe oben).

              Hier nochmals alles, wie es jetzt implementiert ist in der main.js:

              'use strict';
              
              /*
               * Created with @iobroker/create-adapter v1.23.0
               */
              
              // The adapter-core module gives you access to the core ioBroker functions
              // you need to create an adapter
              const utils = require('@iobroker/adapter-core');
              
              // Load your modules here, e.g.:
              const fetch = require('node-fetch');
              const { URLSearchParams } = require('url');
              const request = require('request');
              const qs = require('querystring');
              const fs = require('fs');
              const cron = require('node-cron');
              const appKey   = 'bb86c50c-a149-45d3-b388-5b9729e740c6'; //do not delete or change this!
              
              class HusqvarnaMowers extends utils.Adapter {
              
              	/**
              	 * @param {Partial<ioBroker.AdapterOptions>} [options={}]
              	 */
              	constructor(options) {
              		super({
              			...options,
              			name: 'husqvarna_mowers',
              		});
              		this.on('ready', this.onReady.bind(this));
              		this.on('objectChange', this.onObjectChange.bind(this));
              		this.on('stateChange', this.onStateChange.bind(this));
              		// this.on('message', this.onMessage.bind(this));
              		this.on('unload', this.onUnload.bind(this));
              	}
              
              
              // === Login Funktion auf Husqvarna Authentifizierungs-Server ===
              
              	async function login() {
              		const params = new URLSearchParams();
              		params.set('grant_type', 'password');
              		params.set('client_id', appKey);
              		params.set('username', this.config.Username);
              		params.set('password', this.config.Passwort);
              
              		const res = await fetch('https://api.authentication.husqvarnagroup.dev/v1/oauth2/token', {
              			method: 'POST',
              			body: params
              		});
              
              		if (!res.ok) {
              			this.log.error('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
              			this.log.error('Login fehlgeschlagen! Fehler: ' + res.statusText);
              			this.log.error('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
              			this.log.error('');
              			throw new Error(res.statusText);
              		} else {
              			const ergebnis = await res.json();
              			//const jsonString = JSON.stringify(ergebnis, null, 2); //Formatierung des JSON zur Speicherung als Datei
              			//fs.writeFile('./login.json', jsonString, err => {
              			//	if (err) {
              			//		console.log('Error writing file', err)
              			//	} else {
              			//		console.log('*** Login Daten (Login.json) - Successfully wrote file ***')
              			//	}
              			this.log.info('Login erfolgreich !!! --> erhaltener TOKEN: ' + ergebnis.access_token);
              			return ergebnis.acess_token;
              		}
              
              	};
              
              // -> Ende LOGIN Funktion
              
              
              	/**
              	 * Is called when databases are connected and adapter received configuration.
              	 */
              
              	async onReady() {
              		// Initialize your adapter here
              
              		// The adapters config (in the instance object everything under the attribute "native") is accessible via
              		// this.config:
              		this.log.info('config Username: ' + this.config.Username);
              		if (this.config.Passwort !== '') {
              			this.log.info('config Passwort: wurde gesetzt');
              		}
              		else this.log.error('Passwort nicht gesetzt!!!');
              
              		this.login();
              
              
              
              
              		/*
              		For every state in the system there has to be also an object of type state
              		Here a simple template for a boolean variable named "testVariable"
              		Because every adapter instance uses its own unique namespace variable names can't collide with other adapters variables
              		*/
              		await this.createDevice('test');
              
              		await this.setObjectAsync('test.testVariable', {
              			type: 'state',
              			common: {
              				name: 'testVariable',
              				type: 'boolean',
              				role: 'indicator',
              				read: true,
              				write: true,
              			},
              			native: {},
              		});
              
              
              
              		// in this template all states changes inside the adapters namespace are subscribed
              		this.subscribeStates('*');
              
              		/*
              		setState examples
              		you will notice that each setState will cause the stateChange event to fire (because of above subscribeStates cmd)
              		*/
              		// the variable testVariable is set to true as command (ack=false)
              		await this.setStateAsync('testVariable', true);
              
              		// same thing, but the value is flagged "ack"
              		// ack should be always set to true if the value is received from or acknowledged from the target system
              		await this.setStateAsync('testVariable', { val: true, ack: true });
              
              		// same thing, but the state is deleted after 30s (getState will return null afterwards)
              		await this.setStateAsync('testVariable', { val: true, ack: true, expire: 30 });
              
              		// examples for the checkPassword/checkGroup functions
              		let result = await this.checkPasswordAsync('admin', 'iobroker');
              		this.log.info('check user admin pw iobroker: ' + result);
              
              		result = await this.checkGroupAsync('admin', 'admin');
              		this.log.info('check group user admin group admin: ' + result);
              
              	}
              
              	/**
              	 * Is called when adapter shuts down - callback has to be called under any circumstances!
              	 * @param {() => void} callback
              	 */
              	onUnload(callback) {
              		try {
              			this.log.info('cleaned everything up...');
              			callback();
              		} catch (e) {
              			callback();
              		}
              	}
              
              	/**
              	 * Is called if a subscribed object changes
              	 * @param {string} id
              	 * @param {ioBroker.Object | null | undefined} obj
              	 */
              	onObjectChange(id, obj) {
              		if (obj) {
              			// The object was changed
              			this.log.info(`object ${id} changed: ${JSON.stringify(obj)}`);
              		} else {
              			// The object was deleted
              			this.log.info(`object ${id} deleted`);
              		}
              	}
              
              	/**
              	 * Is called if a subscribed state changes
              	 * @param {string} id
              	 * @param {ioBroker.State | null | undefined} state
              	 */
              	onStateChange(id, state) {
              		if (state) {
              			// The state was changed
              			this.log.info(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
              		} else {
              			// The state was deleted
              			this.log.info(`state ${id} deleted`);
              		}
              	}
              
              	// /**
              	//  * Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
              	//  * Using this method requires "common.message" property to be set to true in io-package.json
              	//  * @param {ioBroker.Message} obj
              	//  */
              	// onMessage(obj) {
              	// 	if (typeof obj === 'object' && obj.message) {
              	// 		if (obj.command === 'send') {
              	// 			// e.g. send email or pushover or whatever
              	// 			this.log.info('send command');
              
              	// 			// Send response in callback if required
              	// 			if (obj.callback) this.sendTo(obj.from, obj.command, 'Message received', obj.callback);
              	// 		}
              	// 	}
              	// }
              
              
              }
              
              
              
              // @ts-ignore parent is a valid property on module
              if (module.parent) {
              	// Export the constructor in compact mode
              	/**
              	 * @param {Partial<ioBroker.AdapterOptions>} [options={}]
              	 */
              	module.exports = (options) => new HusqvarnaMowers(options);
              } else {
              	// otherwise start the instance directly
              	new HusqvarnaMowers();
              }
              
              Jey Cee 1 Reply Last reply Reply Quote 0
              • Jey Cee
                Jey Cee Developer @reutli last edited by

                @reutli die deklaration einer function innerhalb einer Klasse erfolgt immer ohne "function", also nur so:

                meineFunktion() {}
                

                Der Aufruf muss dann mit this erfolgen da die Funktion nur im Kontext der Klasse Aufrufbar ist.

                R 1 Reply Last reply Reply Quote 1
                • R
                  reutli @Jey Cee last edited by

                  @Jey-Cee sagte in Funktion innerhalb der main.js aufrufen gelingt nicht:

                  @reutli die deklaration einer function innerhalb einer Klasse erfolgt immer ohne "function", also nur so:

                  meineFunktion() {}
                  

                  Der Aufruf muss dann mit this erfolgen da die Funktion nur im Kontext der Klasse Aufrufbar ist.

                  Ja fasse ich es denn? Danke! Das war es. Tja wenn man keine Ahnung von JavaScript hat sollte man es lassen.... 👶 aber ich lerne dazu.

                  Jey Cee dslraser 2 Replies Last reply Reply Quote 0
                  • Jey Cee
                    Jey Cee Developer @reutli last edited by

                    @reutli sagte in Funktion innerhalb der main.js aufrufen gelingt nicht:

                    Tja wenn man keine Ahnung von JavaScript hat sollte man es lassen....

                    Achwas.. ich hab doch auch keine 😉
                    Immer schön dran bleiben dann wird das schon.

                    1 Reply Last reply Reply Quote 0
                    • dslraser
                      dslraser Forum Testing Most Active @reutli last edited by

                      @reutli
                      Vielleicht tust Du Dich mit @intruder7 zusammen, ich glaube der baut auch gerade.

                      https://forum.iobroker.net/post/409649

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

                        @dslraser : Jepp, danke, da war ich auch schon. Ich arbeite allerdings auf der neuen V3 API und meine gesehen zu haben, dass @intruder7 auf der "alten" API arbeitet, so wie sie auch in dem bereits vorhandenen Adapter integriert ist.
                        Das blickt ohnehin keiner, welche API die richtige ist. Die alte liefert deutlich mehr Daten... kann aber m.W. die Kalenderdaten nicht.

                        I 1 Reply Last reply Reply Quote 0
                        • I
                          intruder7 @reutli last edited by

                          @reutli
                          respekt.. da bist du deutlich weiter als ich. nein... ich habe tatsächlich mit der neuen API getestet da Greyhound meinte sie ist deutlich besser.Unterm Strich kann sie nur die Wochenprogramme mehr so weit ich das gesehen habe.

                          R 1 Reply Last reply Reply Quote 0
                          • V
                            Vogelbecker last edited by Vogelbecker

                            Ups, war ja schon gelöst 🙂

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

                              @intruder7 sagte in Funktion innerhalb der main.js aufrufen gelingt nicht:

                              @reutli
                              respekt.. da bist du deutlich weiter als ich. nein... ich habe tatsächlich mit der neuen API getestet da Greyhound meinte sie ist deutlich besser.Unterm Strich kann sie nur die Wochenprogramme mehr so weit ich das gesehen habe.

                              Hi,
                              na ja "weiter" bestimmt nicht ;o) aber dran.
                              Der neuen Adapter hat aber auch einiges an Nachteilen, z.B. fehlen sämtliche Infos zu Geo-Daten etc.. Btw., gibt es irgendwo eine Doku zur alten API oder hat sich Greyhound das alles aus der App 'gesnifft'?
                              Vielleicht könnten man die verschiedenen Daten aus den beiden APIs ja mergen...

                              I 1 Reply Last reply Reply Quote 0
                              • I
                                intruder7 @reutli last edited by

                                @reutli Stimmt die GeoDaten fehlen auch . Eine Docu zur alten API hab ich bisher noch nicht gefunden. Habe aber auch noch nicht aktiv danach gesucht.
                                Kannst mich ja mal auf dem laufenden halten wie du so voran kommst. oder hast du was auf Git?

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

                                  @intruder7 sagte in Funktion innerhalb der main.js aufrufen gelingt nicht:

                                  oder hast du was auf Git?

                                  Ha, die Peinlichkeit gebe ich mir erst wenn was läuft 😲

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

                                  Support us

                                  ioBroker
                                  Community Adapters
                                  Donate

                                  829
                                  Online

                                  31.7k
                                  Users

                                  79.8k
                                  Topics

                                  1.3m
                                  Posts

                                  adapterentwicklung funktion aufrufen funktion in funktion
                                  6
                                  15
                                  1171
                                  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