Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. ioBroker Allgemein
    4. Socket Io Verbindungsprobleme

    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

    Socket Io Verbindungsprobleme

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

      Hey Leute,
      ich steh auf´m Schlauch 😞

      Ich will eine Angular App schreiben in der ich mir die Werte mit dem Socket Io Adapter abgreife um anzuzeigen und zu bearbeiten.

      Dazu habe ich mir einen Service geschrieben der sich später um die Verbindung kümmern soll.
      Bei meinem lokalen Express Socket Io Server funktioniert das auch bestens.

      import { Injectable } from '@angular/core';
      import { io } from 'socket.io-client';
      
      import { environment } from "./../environments/environment";
      
      @Injectable({
        providedIn: 'root'
      })
      export class SocketioService {
      
        public socket: any;
        constructor() {   }
        setupSocketConnection() {
          this.socket = io('http://192.168.2.100:8084');
      
          this.socket.on('connect', (data: string) => {
            console.log("Connect", data);
          });
      
          this.socket.on('connect_error', (data: string) => {
            console.log("Connect Error", data);
          });
      
          this.socket.on('*', (data: string) => {
            console.log("On *", data);
          });
      
          this.socket.on('.STATE', (data: string) => {
            console.log("On my Broadcast", data);
          });
      
        }
      
        sendMessage() {
          console.log("Sende eine Nachricht");
      
          this.socket.emit('getHistory', 'smartmeter.0.1-0:16_7_0__255.value');
        }
      
      }
      

      Wenn ich mich zu dem Socket Io Server von meinem Io Broker verbinden will bekomme ich aber keine Verbindung aufgebaut. Er schmeißt mir immer folgende Fehlermeldung welche mir nochs sagt:

      Connect Error Error: server error
          at Socket.onPacket (socket.js:381)
          at XHR.<anonymous> (socket.js:196)
          at XHR.push.cpc2.Emitter.emit (index.js:145)
          at XHR.onPacket (transport.js:103)
          at callback (polling.js:101)
          at Array.forEach (<anonymous>)
          at XHR.onData (polling.js:105)
          at Request.<anonymous> (polling-xhr.js:94)
          at Request.push.cpc2.Emitter.emit (index.js:145)
          at Request.onData (polling-xhr.js:235)
      

      Wenn ich das einfach Beispiel von dem Socket Io Adapter bei mir laufen lasse, bekomme ich in der Konsole Nachrichten gelogt.
      https://github.com/ioBroker/ioBroker.socketio/tree/master/example

      Hat jemand eine Idee?

      Gruß

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

        @j-h Was sagt die Netzwerk Ansicht oder die Konsole? Gibt es irgendwelche Fehlermeldungen oder Requests, die nicht funktionieren?

        P.S.: ich habe auch eine Angular 9 Applikation als meine Vis erstellt. Funktioniert, allerdings läuft der Webserver auf derselben IP Adresse wie ioBroker (nicht derselbe Port natürlich). Zudem verwende ich Port 8082, aber das ist eigentlich nicht sauber, 8084 sollte schon der richtige.

        1 Reply Last reply Reply Quote 0
        • j h
          j h last edited by j h

          Ne, da steht eigentlich nichts drin außer der Log den ich beim Error Event ausgebe.

          Unterschiedlicher Host sollte nicht das Problem sein, da das Testprojekt von dem Adapter ja funktioniert.

          Baust du die Verbindung auch einfach mit: io('http://192.168.2.100:8084');
          auf?

          Kannst du mir deine Quellen eventuell mal zur Verfügung stellen wenn es für dich okay ist?

          Funktioniert das gut für dich? Das Lesen und Ändern von Werten?
          Oder kannst du es nicht empfehlen?

          j h UncleSam 2 Replies Last reply Reply Quote 0
          • j h
            j h @j h last edited by

            Ich bekomme ja jetzt auch noch die Fehlermeldung das die Versionen von Client und Server nicht kompatibel sind.

            Gibt es von dem Adapter noch keine Version die Version 3 von Socket IO einsetzt?

            Connect Error Error: It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client
            
            UncleSam 1 Reply Last reply Reply Quote 0
            • UncleSam
              UncleSam Developer @j h last edited by UncleSam

              @j-h Mein Service, den ich für den Zugriff auf socket.io verwende, sieht wie folgt aus:

              import { Injectable } from '@angular/core';
              import { Socket } from 'ngx-socket-io';
              import { environment } from 'src/environments/environment';
              import { Observable, concat, Subject, ReplaySubject, BehaviorSubject } from 'rxjs';
              import { IoBrokerState } from './io-broker';
              import { map, filter, tap, share, debounceTime, pairwise, startWith } from 'rxjs/operators';
              
              interface StateChange<T> {
                name: string;
                state: IoBrokerState<T>;
              }
              
              type StateCounters = {[name: string]: number};
              
              @Injectable({
                providedIn: 'root'
              })
              export class SocketioService {
              
                private waitConnected = new ReplaySubject<any>();
                private stateChanges: Observable<StateChange<any>>;
                private subscribedStates = new BehaviorSubject<StateCounters>({});
                private stateSubjects: { [name: string]: ReplaySubject<IoBrokerState<any>>; } = {};
              
                constructor(private socket: Socket) {
                  this.socket.on('connect', () => this.waitConnected.complete());
              
                  this.stateChanges = new Observable<StateChange<any>>(observer => {
                    this.socket.on('stateChange', (name: string, state: IoBrokerState<any>) => {
                      observer.next({ name, state });
                    });
                    return () => {
                      this.socket.removeListener('stateChange');
                   };
                  }).pipe(
                    share()
                  );
              
                  concat(
                    this.waitConnected,
                    this.subscribedStates
                  ).pipe(
                    map(s => s as StateCounters),
                    debounceTime(10),
                    startWith({} as StateCounters), // ensure pairwise() below has a starting value
                    pairwise()
                  ).subscribe(
                    ([prev, current]) => {
                      const newNames: string[] = [];
                      for (const name in current) {
                        if (current.hasOwnProperty(name) && !prev.hasOwnProperty(name)) {
                          newNames.push(name);
                        }
                      }
                      if (newNames.length > 0) {
                        // console.log('subscribe', newNames);
                        this.socket.emit('subscribe', newNames);
              
                        this.socket.emit(
                          'getStates',
                          newNames,
                          (_: any, data: { [stateName: string]: IoBrokerState<any> }) => {
                            for (const name in data) {
                              if (data.hasOwnProperty(name) && this.stateSubjects[name] && !!data[name]) {
                                this.stateSubjects[name].next(data[name]);
                              }
                            }
                          });
                      }
              
                      const oldNames: string[] = [];
                      for (const name in prev) {
                        if (prev.hasOwnProperty(name) && !current.hasOwnProperty(name)) {
                          oldNames.push(name);
                        }
                      }
                      if (oldNames.length > 0) {
                        // console.log('unsubscribe', oldNames);
                        this.socket.emit('unsubscribe', oldNames);
                      }
                    }
                  );
                }
              
                observeState<T>(name: string): Observable<IoBrokerState<T>> {
                  if (!this.stateSubjects[name]) {
                    this.stateSubjects[name] = new ReplaySubject<IoBrokerState<T>>(1);
              
                    this.stateChanges.pipe(
                      filter(change => change.name === name && change.state.ack),
                      map(state => state.state)
                    ).subscribe(this.stateSubjects[name]);
                  }
              
                  if (!this.subscribedStates.value.hasOwnProperty(name)) {
                    const newValue = {...this.subscribedStates.value};
                    newValue[name] = 1;
                    this.subscribedStates.next(newValue);
                  } else {
                    this.subscribedStates.value[name]++; // don't emit again (we don't care about number changes)
                  }
              
                  return new Observable<IoBrokerState<T>>(
                    observer => {
                      const subscription = this.stateSubjects[name].subscribe(observer);
                      return () => {
                        subscription.unsubscribe();
                        this.subscribedStates.value[name]--;
                        if (this.subscribedStates.value[name] === 0) {
                          const newValue = {...this.subscribedStates.value};
                          delete newValue[name];
                          this.subscribedStates.next(newValue);
                        }
                      };
                    }
                  );
                }
              
                setState(name: string, value: any) {
                  this.socket.emit('setState', name, value);
                }
              }
              

              Dafür verwende ich "ngx-socket-io": "^3.0.1"

              Zu erwähnen wäre noch, dass ich ein absoluter Fan von RxJS bin und deswegen alle Subscribes als Observable implementiert sind. Ich finde den Ansatz wunderschön, da es mir dann in einer Komponente solchen Code ermöglicht (der Nimmt den Wert von drei Datenpunkten und errechnet daraus das Icon für meinen Landroid):

              combineLatest([
                    this.socketService.observeState<boolean>(this.deviceName + '.mower.batteryCharging'),
                    this.socketService.observeState<number>(this.deviceName + '.mower.error'),
                    this.socketService.observeState<number>(this.deviceName + '.mower.status')
                  ]).pipe(
                    map(([charging, error, status]) => {
                      if (error.val > 0) {
                        return '_attention';
                      }
                      if (charging.val) {
                        return '_charging';
                      }
                      switch (status.val) {
                        case 2: // Start sequence
                        case 3: // Leaving home
                        case 4: // Follow wire
                        case 5: // Searching home
                        case 6: // Searching wire
                        case 7: // Mowing
                        case 30: // Going home
                        case 31: // Zone training
                        case 32: // Border Cut
                        case 33: // Searching zone
                          return '_active';
                        case 8: // Lifted
                        case 9: // Trapped
                        case 10: // Blade blocked
                          return '_attention';
                        case 34: // Pause
                          return '_paused';
                        default:
                          return '';
                      }
                    }),
                    map(ext => `${this.iconBaseUrl}scene_robo_lawnmower${ext}.svg`)
                  );
              
              1 Reply Last reply Reply Quote 0
              • UncleSam
                UncleSam Developer @j h last edited by

                @j-h sagte in Socket Io Verbindungsprobleme:

                Funktioniert das gut für dich? Das Lesen und Ändern von Werten?
                Oder kannst du es nicht empfehlen?

                Diese Fragen habe ich dir noch nicht beantwortet. Ich glaube ein Video sagt mehr als tausend Worte: https://www.youtube.com/watch?v=LxDPfeqv20c
                Man beachte das Einschalten des Lichtes am Schluss: es ist absolut instantan - und das, obschon das noch über einen ioBroker Master an einen Slave geht, der es dann per USB an DMX weitergeben muss.

                j h 1 Reply Last reply Reply Quote 0
                • j h
                  j h @UncleSam last edited by

                  Sehr sehr cool! Genau so hab ich mir das vorgestellt.
                  Dann ist man auch etwas freier als mit den anderen vis Frameworks.

                  Das ngx-socket Io probiere ich morgen direkt aus! Danke schonmal für den Tipp!

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

                    @j-h Bitte, bitte 🙂 . Ich will nicht den ganzen Code meiner Vis veröffentlichen, aber wenn du weitere Fragen hast, einfach nachfragen - ich werde so gut wie möglich antworten.

                    j h 1 Reply Last reply Reply Quote 0
                    • j h
                      j h @UncleSam last edited by j h

                      @unclesam

                      Ich habe soeben meine erste Nachricht erhalten 👍
                      Ich werde dich auf dem Laufenden halten

                      Vielen Danke & Gruß

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

                      Support us

                      ioBroker
                      Community Adapters
                      Donate
                      FAQ Cloud / IOT
                      HowTo: Node.js-Update
                      HowTo: Backup/Restore
                      Downloads
                      BLOG

                      727
                      Online

                      31.9k
                      Users

                      80.1k
                      Topics

                      1.3m
                      Posts

                      socket io
                      2
                      9
                      713
                      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