Loxone Intercom Gen2 - Webschnittstelle um Bild/Video rauszubekommen

Einklappen
X
 
  • Zeit
  • Anzeigen
Alles löschen
neue Beiträge
  • Laubi
    Smart Home'r
    • 01.01.2022
    • 36

    #91
    Zitat von Laubi
    Ich bin soooooo glücklich.... Details folgen, aber ich habs! WebRTC Stream ist möglich, danke KI. Gebt mir 3 Tage ich sag euch das video läuft. Ich habs gesehen. Danke geliebtes GLM .... Harte Session aber Gute Session....
    Ok das ganze in usable code zu bringen war einfacher als gedacht. Ich hab dank KI einen kleinen Container gebaut. Eigentlich ist das ganz normales webrtc.

    Ich präsentiere für das Video (noch ohne Ton): https://github.com/markuslaube/loxone-intercom2

    Das wichtigste, ich lach mich immer noch weg: ich glaubte immer das ist nicht Standard-Konform weil Firefox es im Browser nicht anzeigt, doch macht er wenn man mal in irgendein VPN wechselt. Der Traffic bleibt aber lokal. DNS Rebind Schutz war bei mir das was Debuggung schwer gemacht hat. Dieser schhhh... wechselt auf die "dyndns-namen" der loxone Cloud auch wenn man gar keine Loxone-Cloud nutzt. Steht dann halt die Lokale IP wieder drin, was in halbwegs normalen Netzen als Angriff gewertet wird....

    und eine weitere Version im gleichen repo, die das Rebind Problem jetzt umgeht.

    Viel Spaß und Grüße
    Markus
    Zuletzt geändert von Laubi; 06.09.2026, 19:21.

    Kommentar

    • Laubi
      Smart Home'r
      • 01.01.2022
      • 36

      #92
      Audio Biderektional mittels Sip geht auch, Lösung demnächst ebenfalls auf Github

      Kommentar

      • MarkusCosi
        LoxBus Spammer
        • 28.09.2023
        • 411

        #93
        spannend! aktuell versuche ich noch die Intercom in Unifi Protect zu bekommen. Auf einer Synology im Container Manager versuche ich dafür ein Container Project mit den 3 Images: loxone-intercom-bridge:amd64, ptarmiganlabs/rtsp-to-onvif:latest, alexxit/go2rtc:latest... In Protect bekam ich bereits den live stream (Loxone IntercomV2 → WebRTC → bridge → MediaMTX RTSP → go2rtc → UniFi). Aber so ganz stabil läuft das leider noch nicht... FFmpeg zeigt massive H264 decoding corruption: "P sub_mb_type ... out of range", "error while decoding MB ...", "mb_type ... in P slice too large", "out of range intra chroma pred mode"...


        Code:
        services:
          go2rtc:
            image: alexxit/go2rtc:latest
            container_name: go2rtc
            restart: unless-stopped
            ports:
              - "1984:1984"
              - "8554:8554"
            volumes:
              - ./go2rtc:/config
            networks:
              - intercom
        
          loxone-bridge:
            build:
              context: ./rtc-bridge
              args:
                TARGETARCH: amd64
            image: loxone-intercom-bridge:amd64
            container_name: loxone-bridge
            restart: unless-stopped
            environment:
              LOXONE_MINISERVER_IP: "192.168.1.X"
              LOXONE_MINISERVER_USER: "myUser"
              LOXONE_MINISERVER_PASS: "myPW"
              LOXONE_RTSP_HOST: "loxone-bridge"
              LOXONE_RTSP_PORT: "8554"
              LOXONE_STREAM_NAME: "loxone_intercom"
              GO2RTC_API_URL: "https://go2rtc:1984"
              LOXONE_GO2RTC_RECONCILE_SECONDS: "20"
              LOXONE_LOG_LEVEL: "INFO"
            networks:
              - intercom
            depends_on:
              - go2rtc
        
          rtsp-to-onvif:
             image: ptarmiganlabs/rtsp-to-onvif:latest
             container_name: rtsp-to-onvif
             network_mode: host
             cap_add:
               - NET_ADMIN
             volumes:
               - ./config.yaml:/onvif.yaml
             restart: unless-stopped
             healthcheck:
               test: ["CMD-SHELL", "curl -sf https://192.168.1.Y:8081/onvif/device_service || exit 1"]
               interval: 30s
               timeout: 5s
               retries: 3
               start_period: 10s
        
        networks:
          intercom:
            driver: bridge
        mit dem Config.yaml:

        Code:
        onvif:
          - name: LoxoneIntercom
            dev: ovs_eth0
            target:
              hostname: 192.168.1.Z (SYNOLOGY IP)
              ports:
                rtsp: 8554
                snapshot: 1984
            highQuality:
              rtsp: /loxone_intercom
              snapshot: /
              width: 1280
              height: 720
              framerate: 30
              bitrate: 250
              quality: 4
            ports:
              server: 8081
              rtsp: 9554
              snapshot: 8282
            uuid: SomeID
            mac: SomeMAC

        Kommentar


        • Laubi
          Laubi kommentierte
          Kommentar bearbeiten
          nimm die rtc-directbridge ohne ssl weniger last intensiv. Ich befürchte die SSL Variante überlebt die CPU nicht. Außerdem sparst Du die auth ok ist jetzt nicht toll aber nachdem ohne wss/https eh ohne auth geht warum jetzt mit auth auf wss/https . ....

        • MarkusCosi
          MarkusCosi kommentierte
          Kommentar bearbeiten
          Danke für den Hinweis. Ich nutze jetzt die directbridge... ich kämpfe aber noch immer.. Die Framerate bzw. Zeitachse der Streams scheint ein Problem zu sein. Bekomme nur frozen still images..

        • Laubi
          Laubi kommentierte
          Kommentar bearbeiten
          mhh Spannend, bei mir jetzt stabil. Ich vermute das ssl war gar kein Thema, meine Problem lagen davor im Devolo Powelan für die Klingel... Bin gespannt an was Deine probleme am ende liegen.
      • Laubi
        Smart Home'r
        • 01.01.2022
        • 36

        #94
        so und die Klingel ruft jetzt auch auf SIP-Device an und stellt Audio Biderektional durch. Wünsche Vorschläge nehme ich gerne an. Code Review von erfahrenen Menschen natürlich auch gern gesehen!

        Unofficial Loxone Intercom Gen.2 integrations. Contribute to markuslaube/loxone-intercom2 development by creating an account on GitHub.

        Kommentar


        • Laubi
          Laubi kommentierte
          Kommentar bearbeiten
          Getestet:
          => Anruf auf SIP-Client wenn es klingelt (2-way-Audio)
          => LiveBild auf DECT-Telefon wenn es klingelt
          => 2-Way-Audio bei anruf der Nebenstelle
      • MarkusCosi
        LoxBus Spammer
        • 28.09.2023
        • 411

        #95
        Code:
        services:
          go2rtc:
            image: alexxit/go2rtc:latest
            container_name: go2rtc
            restart: unless-stopped
            ports:
              - "1984:1984"
              - "8554:8554"
            volumes:
              - ./go2rtc:/config
            networks:
              - intercom
        
          loxone-bridge:
            build:
              context: ./rtc-directbridge
              args: 
                TARGETARCH: amd64
            image: loxone-intercom-directbridge:amd64
            container_name: loxone-directbridge
            restart: unless-stopped
            environment:
              LOXONE_INTERCOM_IP: "192.168.1.Y"
              LOXONE_RTSP_HOST: "loxone-directbridge"
              LOXONE_RTSP_PORT: "8554"
              LOXONE_STREAM_NAME: "loxone_intercom"
              GO2RTC_API_URL: "https://go2rtc:1984"
              LOXONE_GO2RTC_RECONCILE_SECONDS: "20"
              LOXONE_LOG_LEVEL: "INFO"
            networks:
              - intercom
            depends_on:
              - go2rtc
        
          rtsp-to-onvif:
             image: ptarmiganlabs/rtsp-to-onvif:latest
             container_name: rtsp-to-onvif
             network_mode: host
             cap_add:
               - NET_ADMIN
             volumes:
               - ./config.yaml:/onvif.yaml
             restart: unless-stopped
             healthcheck:
               test: ["CMD-SHELL", "curl -sf https://192.168.1.X:8081/onvif/device_service || exit 1"]
               interval: 30s
               timeout: 5s
               retries: 3
               start_period: 10s
        
        networks:
          intercom:
            driver: bridge
        ...ich bekomme keinen stabilen Video-Stream. Im go2rtc Webinterface preview sieht man einen still-frame, der Zeitleisten-Cursor startet rechts, dann geht er schnell nach links. Nur dann kann ich kurz einen stream per play abspielen, bis das ende der Zeitleiste wieder erreicht ist. Dann wieder ein still frame. Ähnlich wenn ich per VLC open network die rtps streams anschaue: still frame only. Das Bild aktualisiert sich nur beim neu öffnen. Wenn ich Unifi Protect hinzuziehe, sehe ich dort auch nur einen still frame, und die anderen "clients" können den Stream gar nicht mehr öffnen.

        nach einigem debugging mit ChatGPT:

        "I think we’ve isolated the problem in rtc-directbridge.

        The Loxone WebRTC/H.264 acquisition itself works correctly:
        • Loxone video is received.
        • H.264 depacketization produces valid video frames.
        • The original elementary H.264 stream reports avg_frame_rate=25/1.
        • go2rtc can receive and decode the resulting RTSP stream.
        The problem appears to be that the RTP timing information is lost between the Loxone RTP stream and the raw H.264 stream sent to FFmpeg.

        Currently the pipeline is essentially:
        Loxone RTP/H.264 → bridge.py depacketization → raw Annex-B H.264 stdout → FFmpeg → RTSP/MediaMTX → go2rtc.

        The original RTP packets have timestamps, but bridge.py does not appear to preserve those timestamps when emitting the H.264 stream. There is no PTS handling in the raw-H.264 output path.

        As a result, FFmpeg receives an elementary H.264 stream with valid video data but no presentation timestamps.
        It logs:
        Timestamps are unset
        and subsequently: Non-monotonic DTS

        The resulting RTSP stream has:
        time_base=1/90000
        r_frame_rate=90000/1
        avg_frame_rate=0/0

        rather than a meaningful 25-fps timeline. The 90-kHz time base itself is normal for RTP, but the mapping of video frames onto that clock appears to be missing/invalid.

        We also tested adding:
        -f h264 -framerate 25 -i -

        to the FFmpeg invocation. This tells FFmpeg to synthesize a 25-fps timeline, but the go2rtc preview still has the same bizarre moving/shrinking timeline. So simply declaring the nominal frame rate at the FFmpeg input does not seem to solve the underlying issue.

        One should look specifically at preserving the RTP timestamps through the H.264 depacketization/output stage.

        Ideally, the bridge should retain the RTP timestamp associated with each H.264 access unit/frame and provide FFmpeg with a monotonically increasing presentation timeline. For a 25-fps stream using the normal 90-kHz H.264 RTP clock, consecutive frames should be approximately 3600 RTP ticks apart (90000 / 25).

        I don't think the H.264 bitstream itself is broken. This looks like a timestamp/access-unit timing defect in the bridge's RTP → raw-H.264 handoff.

        It would be great if the fix could remain inside rtc-directbridge, rather than requiring downstream workarounds in go2rtc/MediaMTX."
        Zuletzt geändert von MarkusCosi; 09.09.2026, 09:23.

        Kommentar


        • Laubi
          Laubi kommentierte
          Kommentar bearbeiten
          Schau mal ob das so hilft:
          - https://github.com/markuslaube/loxon...fix/timestamps

          Behebt bei mir tatsäch ein Timeout-Problem bei der Einbindung als Generic Camera in HA, ich glaub der fix sollte gut helfen.
          Zuletzt geändert von Laubi; 09.09.2026, 13:22.

        • MarkusCosi
          MarkusCosi kommentierte
          Kommentar bearbeiten
          ja, danke, das funktioniert nun erst einmal! irgendwann kamen aber wieder die codec Fehler… reproduzieren konnte ich das aber nicht, aktuell läufts… ich beobachte das mal
      • MarkusCosi
        LoxBus Spammer
        • 28.09.2023
        • 411

        #96
        ...nun funktioniert auch Unifi Protect mit Motion Events:

        der Stack ist:Die pipeline ist damit:
        • Protect Video: [Loxone Intercom: Loxone WebRTC/H.264] → [Synology/Docker host: rtc-directbridge → FFmpeg (-use_wallclock_as_timestamps 1, -c copy) → go2rtc / RTSP → rtsp-to-onvif] → [Unifi UDM Pro: UniFi Protect (Discover 3rd-Party Cameras / Adopt: admin/admin)]
        • Protect Motion Events: ([Loxone Intercom: Loxone Intercom Gen2 TOF motion] → [Loxone Miniserver: Motion event → Loxone Virtual Output → HTTP Post to webhook] / [alternativ: Unifi Protect Alarm Manager (webhook)]) → [Synology: rtsp-to-onvif Events] → [Unifi UDM Pro: UniFi Protect event recording → X s motion event → recording with pre/post-event buffer]
        Die Motion Events für Protect werden für die virtuelle ONVIF Kamera Instanz bequem per webhook getriggert, z.B. von einer anderen Kamera oder von der Intercom selbst. Ziel ist die virtuelle Kamera IP die per DHCP vom onvif container kommt. Es funktioniert dann auch Recording Modus: Events Only in den Einstellungen der adoptierten virtuellen Intercom in Protect.

        Trigger ONVIF = Protect Events
        • curl -s -X POST -H 'Content-Type: application/json' -d '{"motion":true}' https://<virtCamIP>:8081/webhook (Event start)
        • curl -s -X POST -H 'Content-Type: application/json' -d '{"motion":false}' https://<virtCamIP>:8081/webhook (Event end)
        • curl -X POST https://<virtCamIP>:8081/webhook/10 oder /30 für 10s oder 30s Event.
        Toggle Logging, i.e. via docker logs -f rtsp-to-onvif from docker host SSH in terminal
        • curl -X POST https://<virtCamIP>:8081/webhook/log/on
        • curl -X POST https://<virtCamIP>:8081/webhook/log/off

        compose.yaml:
        Code:
        services:
          go2rtc:
            image: alexxit/go2rtc:latest
            container_name: go2rtc
            restart: unless-stopped
            ports:
              - "1984:1984"
              - "8554:8554"
            volumes:
              - ./go2rtc:/config
            networks:
              - intercom
        
          loxone-bridge:
            build:
              context: ./rtc-directbridge
              args:
                TARGETARCH: amd64
            image: loxone-intercom-directbridge:amd64
            container_name: loxone-directbridge
            restart: unless-stopped
            environment:
              LOXONE_INTERCOM_IP: "192.#.#.#" (←IP Intercom)
              LOXONE_RTSP_HOST: "loxone-directbridge"
              LOXONE_RTSP_PORT: "8554"
              LOXONE_STREAM_NAME: "loxone_intercom"
              GO2RTC_API_URL: "https://go2rtc:1984"
              LOXONE_GO2RTC_RECONCILE_SECONDS: "20"
              LOXONE_LOG_LEVEL: "INFO"
            networks:
              - intercom
            depends_on:
              - go2rtc
        
          rtsp-to-onvif:
            build:
              context: ./rtsp-to-onvif-main
            image: loxone-rtsp-to-onvif:amd64
            container_name: rtsp-to-onvif
            network_mode: host
            cap_add:
              - NET_ADMIN
            volumes:
              - ./config.yaml:/onvif.yaml
            restart: unless-stopped
            healthcheck:
              test: ["CMD-SHELL", "curl -sf https://192.#.#.#:8081/onvif/device_service || exit 1"] (← IP assigned to camera)
              interval: 30s
              timeout: 5s
              retries: 3
              start_period: 10s
        
        networks:
          intercom:
            driver: bridge
        config.yaml:
        Code:
        onvif:
          - name: LoxoneIntercom
            dev: ovs_eth0
            target:
              hostname: 192.#.#.# (← IP of docker host)
              ports:
                rtsp: 8554
                snapshot: 1984
            highQuality:
              rtsp: /loxone_intercom
              snapshot: /api/frame.jpeg?src=loxone_intercom
              width: 1280
              height: 720
              framerate: 30
              bitrate: 250
              quality: 4
            ports:
              server: 8081
              rtsp: 9554
              snapshot: 8282
            uuid: SOMEGENERATEDUUID
            mac: SOMEGENERATEDMAC
        onvif-server.js:
        Code:
        const soap = require('soap');
        const http = require('http');
        const dgram = require('dgram');
        const xml2js = require('xml2js');
        const { v1: uuidV1 } = require('uuid');
        const url = require('url');
        const fs = require('fs');
        
        const { getIp4FromMac } = require('./net-tools')
        const EventsProxy = require('./events-proxy');
        
        Date.prototype.stdTimezoneOffset = function () {
            let jan = new Date(this.getFullYear(), 0, 1);
            let jul = new Date(this.getFullYear(), 6, 1);
            return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
        }
        
        Date.prototype.isDstObserved = function () {
            return this.getTimezoneOffset() < this.stdTimezoneOffset();
        }
        
        module.exports = class OnvifServer {
            constructor(logger, config) {
                this.config = config;
                this.logger = logger;
            this.eventsProxy = new EventsProxy(logger, config);
        
                this.config.hostname = getIp4FromMac(logger, this.config.mac);
                if (!this.config.hostname)
                    return -1;
        
                this.videoSource = {
                    attributes: {
                        token: 'video_src_token'
                    },
                    Framerate: this.config.highQuality.framerate,
                    Resolution: { Width: this.config.highQuality.width, Height: this.config.highQuality.height }
                };
        
                this.profiles = [
                    {
                        Name: 'MainStream',
                        attributes: {
                            token: 'main_stream'
                        },
                        VideoSourceConfiguration: {
                            Name: 'VideoSource',
                            UseCount: 2,
                            attributes: {
                                token: 'video_src_config_token'
                            },
                            SourceToken: 'video_src_token',
                            Bounds: { attributes: { x: 0, y: 0, width: this.config.highQuality.width, height: this.config.highQuality.height } }
                        },
                        VideoEncoderConfiguration: {
                            attributes: {
                                token: 'encoder_hq_config_token'
                            },
                            Name: 'CardinalHqCameraConfiguration',
                            UseCount: 1,
                            Encoding: 'H264',
                            Resolution: {
                                Width: this.config.highQuality.width,
                                Height: this.config.highQuality.height
                            },
                            Quality: this.config.highQuality.quality,
                            RateControl: {
                                FrameRateLimit: this.config.highQuality.framerate,
                                EncodingInterval: 1,
                                BitrateLimit: this.config.highQuality.bitrate
                            },
                            H264: {
                                GovLength: this.config.highQuality.framerate,
                                H264Profile: 'Main'
                            },
                            SessionTimeout: 'PT1000S'
                        }
                    }
                ];
        
                if (this.config.lowQuality) {
                    this.profiles.push(
                        {
                            Name: 'SubStream',
                            attributes: {
                                token: 'sub_stream'
                            },
                            VideoSourceConfiguration: {
                                Name: 'VideoSource',
                                UseCount: 2,
                                attributes: {
                                    token: 'video_src_config_token'
                                },
                                SourceToken: 'video_src_token',
                                Bounds: { attributes: { x: 0, y: 0, width: this.config.highQuality.width, height: this.config.highQuality.height } }
                            },
                            VideoEncoderConfiguration: {
                                attributes: {
                                    token: 'encoder_lq_config_token'
                                },
                                Name: 'CardinalLqCameraConfiguration',
                                UseCount: 1,
                                Encoding: 'H264',
                                Resolution: {
                                    Width: this.config.lowQuality.width,
                                    Height: this.config.lowQuality.height
                                },
                                Quality: this.config.lowQuality.quality,
                                RateControl: {
                                    FrameRateLimit: this.config.lowQuality.framerate,
                                    EncodingInterval: 1,
                                    BitrateLimit: this.config.lowQuality.bitrate
                                },
                                H264: {
                                    GovLength: this.config.lowQuality.framerate,
                                    H264Profile: 'Main'
                                },
                                SessionTimeout: 'PT1000S'
                            }
                        }
                    );
                }
        
                this.onvif = {
                    DeviceService: {
                        Device: {
                            GetSystemDateAndTime: (args) => {
                                let now = new Date();
        
                                let offset = now.getTimezoneOffset();
                                let abs_offset = Math.abs(offset);
                                let hrs_offset = Math.floor(abs_offset / 60);
                                let mins_offset = (abs_offset % 60);
                                let tz = 'UTC' + (offset < 0 ? '-' : '+') + hrs_offset + (mins_offset === 0 ? '' : ':' + mins_offset);
        
                                return {
                                    SystemDateAndTime: {
                                        DateTimeType: 'NTP',
                                        DaylightSavings: now.isDstObserved(),
                                        TimeZone: {
                                            TZ: tz
                                        },
                                        UTCDateTime: {
                                            Time: { Hour: now.getUTCHours(), Minute: now.getUTCMinutes(), Second: now.getUTCSeconds() },
                                            Date: { Year: now.getUTCFullYear(), Month: now.getUTCMonth() + 1, Day: now.getUTCDate() }
                                        },
                                        LocalDateTime: {
                                            Time: { Hour: now.getHours(), Minute: now.getMinutes(), Second: now.getSeconds() },
                                            Date: { Year: now.getFullYear(), Month: now.getMonth() + 1, Day: now.getDate() }
                                        },
                                        Extension: {}
                                    }
                                };
                            },
        
                            GetCapabilities: (args) => {
                                let response = {
                                    Capabilities: {}
                                };
        
                                if (args.Category === undefined || args.Category == 'All' || args.Category == 'Device') {
                                    response.Capabilities['Device'] = {
                                        XAddr: `https://${this.config.hostname}:${this.config.ports.server}/onvif/device_service`,
                                        Network: {
                                            IPFilter: false,
                                            ZeroConfiguration: false,
                                            IPVersion6: false,
                                            DynDNS: false,
                                            Extension: {
                                                Dot11Configuration: false,
                                                Extension: {}
                                            }
                                        },
                                        System: {
                                            DiscoveryResolve: false,
                                            DiscoveryBye: false,
                                            RemoteDiscovery: false,
                                            SystemBackup: false,
                                            SystemLogging: false,
                                            FirmwareUpgrade: false,
                                            SupportedVersions: {
                                                Major: 2,
                                                Minor: 5
                                            },
                                            Extension: {
                                                HttpFirmwareUpgrade: false,
                                                HttpSystemBackup: false,
                                                HttpSystemLogging: false,
                                                HttpSupportInformation: false,
                                                Extension: {}
                                            }
                                        },
                                        IO: {
                                            InputConnectors: 0,
                                            RelayOutputs: 1,
                                            Extension: {
                                                Auxiliary: false,
                                                AuxiliaryCommands: '',
                                                Extension: {}
                                            }
                                        },
                                        Security: {
                                            'TLS1.1': false,
                                            'TLS1.2': false,
                                            OnboardKeyGeneration: false,
                                            AccessPolicyConfig: false,
                                            'X.509Token': false,
                                            SAMLToken: false,
                                            KerberosToken: false,
                                            RELToken: false,
                                            Extension: {
                                                'TLS1.0': false,
                                                Extension: {
                                                    Dot1X: false,
                                                    RemoteUserHandling: false
                                                }
                                            }
                                        },
                                        Extension: {}
                                    };
                                }
                                if (args.Category === undefined || args.Category == 'All' || args.Category == 'Media') {
                                    response.Capabilities['Media'] = {
                                        XAddr: `https://${this.config.hostname}:${this.config.ports.server}/onvif/media_service`,
                                        StreamingCapabilities: {
                                            RTPMulticast: false,
                                            RTP_TCP: true,
                                            RTP_RTSP_TCP: true,
                                            Extension: {}
                                        },
                                        Extension: {
                                            ProfileCapabilities: {
                                                MaximumNumberOfProfiles: this.profiles.length
                                            }
                                        }
                                    }
                                }
                    if (args.Category === undefined || args.Category == 'All' || args.Category == 'Events') {
                        response.Capabilities['Events'] = {
                                XAddr: `https://${this.config.hostname}:${this.config.ports.server}/onvif/Events`,
                                WSSubscriptionPolicySupport: false,
                                WSPullPointSupport: true,
                                WSPausableSubscriptionManagerInterfaceSupport: false
                            };
                    }
        
                                return response;
                            },
        
                            GetServices: (args) => {
                                return {
                                    Service: [
                                        {
                                            Namespace: 'https://www.onvif.org/ver10/device/wsdl',
                                            XAddr: `https://${this.config.hostname}:${this.config.ports.server}/onvif/device_service`,
                                            Version: {
                                                Major: 2,
                                                Minor: 5,
                                            }
                                        },
                                        {
                                            Namespace: 'https://www.onvif.org/ver10/media/wsdl',
                                            XAddr: `https://${this.config.hostname}:${this.config.ports.server}/onvif/media_service`,
                                            Version: {
                                                Major: 2,
                                                Minor: 5,
                                            }
                                        },
                        {
                                    Namespace: 'https://www.onvif.org/ver10/events/wsdl',
                            XAddr: `https://${this.config.hostname}:${this.config.ports.server}/onvif/Events`,
                                Version: {
                                    Major: 2,
                                        Minor: 5
                                      }
                                }
                                    ]
                                };
                            },
        
                            GetDeviceInformation: (args) => {
                                return {
                                    Manufacturer: 'rtsp-2-onvif',
                                    Model: `${this.config.name}`,
                                    FirmwareVersion: '1.0.0',
                                    SerialNumber: `${this.config.name.replace(' ', '_')}-0000`,
                                    HardwareId: `${this.config.name.replace(' ', '_')}-1001`
                                };
                            }
        
                        }
                    },
        
                    MediaService: {
                        Media: {
                            GetProfiles: (args) => {
                                return {
                                    Profiles: this.profiles
                                };
                            },
        
                            GetVideoSources: (args) => {
                                return {
                                    VideoSources: [
                                        this.videoSource
                                    ]
                                };
                            },
        
                            GetSnapshotUri: (args) => {
                                let uri = `https://${this.config.hostname}:${this.config.ports.server}/snapshot.png`;
                                if (args.ProfileToken == 'sub_stream' && this.config.lowQuality && this.config.lowQuality.snapshot)
                                    uri = `https://${this.config.hostname}:${this.config.ports.snapshot}${this.config.lowQuality.snapshot}`;
                                else if (this.config.highQuality.snapshot)
                                    uri = `https://${this.config.hostname}:${this.config.ports.snapshot}${this.config.highQuality.snapshot}`;
        
                                return {
                                    MediaUri: {
                                        Uri: uri,
                                        InvalidAfterConnect: false,
                                        InvalidAfterReboot: false,
                                        Timeout: 'PT30S'
                                    }
                                };
                            },
        
                            GetStreamUri: (args) => {
                                let path = this.config.highQuality.rtsp;
                                if (args.ProfileToken == 'sub_stream' && this.config.lowQuality)
                                    path = this.config.lowQuality.rtsp;
        
                                return {
                                    MediaUri: {
                                        Uri: `rtsp://${this.config.hostname}:${this.config.ports.rtsp}${path}`,
                                        InvalidAfterConnect: false,
                                        InvalidAfterReboot: false,
                                        Timeout: 'PT30S'
                                    }
                                };
                            }
                        }
                    }
                };
            }
        
            listen(request, response) {
                let action = url.parse(request.url, true).pathname;
                if (action == '/snapshot.png') {
                    let image = fs.readFileSync('./resources/snapshot.png');
                    response.writeHead(200, { 'Content-Type': 'image/png' });
                    response.end(image, 'binary');
            } else if (this.eventsProxy.matches(action)) {
                    this.eventsProxy.handle(request, response).catch(err => {
                    this.logger.error(
                        `SERVER: ${this.config.name} - EventsProxy error: ${err.stack || err}`
                    );
                    if (!response.writableEnded) {
                        response.writeHead(500, { 'Content-Type': 'text/plain' });
                        response.end('Events service error\n');
                    }
                });
                } else {
                    response.writeHead(404, { 'Content-Type': 'text/plain' });
                    response.write('404 Not Found\n');
                    response.end();
                }
            }
        
            startHttpServer() {
                this.logger.info(`SERVER: ${this.config.name} - HTTP listening on ${this.config.hostname}:${this.config.ports.server}`);
        
                this.server = http.createServer((req, res) => this.listen(req, res));
                this.server.listen(this.config.ports.server, this.config.hostname);
        
                this.deviceService = soap.listen(this.server, {
                    path: '/onvif/device_service',
                    services: this.onvif,
                    xml: fs.readFileSync('./wsdl/device_service.wsdl', 'utf8'),
                    forceSoap12Headers: true
                });
              
        
                this.mediaService = soap.listen(this.server, {
                    path: '/onvif/media_service',
                    services: this.onvif,
                    xml: fs.readFileSync('./wsdl/media_service.wsdl', 'utf8'),
                    forceSoap12Headers: true
                });
                
            }
        
            enableDebugOutput() {
                this.deviceService.log = function(type, data, req){
                    console.debug(`SERVER: ${data}`);
                    //there is no logger in this context
                };
                this.mediaService.log = function(type, data, req){
                    console.debug(`SERVER: ${data}`);
                    //there is no logger in this context
                };
                // this.deviceService.on('request', (request, methodName) => {
                //     this.logger.debug(`SERVER: ${this.config.name} - DeviceService: ${methodName}`);
                // });
        
                // this.mediaService.on('request', (request, methodName) => {
                //     this.logger.debug(`SERVER: ${this.config.name} -  MediaService: ${methodName}`);
                // });
            }
        
            startDiscovery() {
                this.discoveryMessageNo = 0;
                this.discoverySocket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
        
                this.discoverySocket.on('message', (message, remote) => {
        
                    this.logger.debug(`SERVER: ${this.config.name} - Discovery request from ${remote.address}:${remote.port}`);
        
                    xml2js.parseString(message.toString(), { tagNameProcessors: [xml2js['processors'].stripPrefix] }, (err, result) => {
                        let probeUuid = result['Envelope']['Header'][0]['MessageID'][0];
                        let probeType = '';
                        try {
                            probeType = result['Envelope']['Body'][0]['Probe'][0]['Types'][0];
                        } catch (err) {
                            probeType = '';
                        }
        
                        if (typeof probeType === 'object')
                            probeType = probeType._;
        
                        if (probeType === '' || probeType.indexOf('NetworkVideoTransmitter') > -1) {
                            let response =
                                `<?xml version="1.0" encoding="UTF-8"?>
                                <SOAP-ENV:Envelope xmlns:SOAP-ENV="https://www.w3.org/2003/05/soap-envelope" xmlns:wsa="https://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:d="https://schemas.xmlsoap.org/ws/2005/04/discovery" xmlns:dn="https://www.onvif.org/ver10/network/wsdl">
                                    <SOAP-ENV:Header>
                                        <wsa:MessageID>uuid:${uuidV1()}</wsa:MessageID>
                                        <wsa:RelatesTo>${probeUuid}</wsa:RelatesTo>
                                        <wsa:To SOAP-ENV:mustUnderstand="true">https://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
                                        <wsa:Action SOAP-ENV:mustUnderstand="true">https://schemas.xmlsoap.org/ws/2005/04/discovery/ProbeMatches</wsa:Action>
                                        <d:AppSequence SOAP-ENV:mustUnderstand="true" MessageNumber="${this.discoveryMessageNo}" InstanceId="1234567890"/>
                                    </SOAP-ENV:Header>
                                    <SOAP-ENV:Body>
                                        <d:ProbeMatches>
                                            <d:ProbeMatch>
                                                <wsa:EndpointReference>
                                                    <wsa:Address>urn:uuid:${this.config.uuid}</wsa:Address>
                                                </wsa:EndpointReference>
                                                <d:Types>dn:NetworkVideoTransmitter</d:Types>
                                                <d:Scopes>
                                                    onvif://www.onvif.org/type/video_encoder
                                                    onvif://www.onvif.org/type/ptz
                                                    onvif://www.onvif.org/hardware/onvif
                                                    onvif://www.onvif.org/name/${this.config.name}
                                                    onvif://www.onvif.org/location/
                                                </d:Scopes>
                                                <d:XAddrs>https://${this.config.hostname}:${this.config.ports.server}/onvif/device_service</d:XAddrs>
                                                <d:MetadataVersion>1</d:MetadataVersion>
                                            </d:ProbeMatch>
                                        </d:ProbeMatches>
                                    </SOAP-ENV:Body>
                                </SOAP-ENV:Envelope>`;
        
                            this.discoveryMessageNo++;
                            let responseBuffer = Buffer.from(response);
                            return dgram.createSocket('udp4').send(responseBuffer, 0, responseBuffer.length, remote.port, remote.address);
                        }
                    });
                });
        
                this.discoverySocket.bind(3702, () => {
                    return this.discoverySocket.addMembership('239.255.255.250', this.config.hostname);
                });
            }
        
            getHostname() {
                return this.config.hostname;
            }
        };
        events-proxy.js:
        Code:
        const crypto = require('crypto');
        
        const MAX_SUBSCRIPTIONS = 32;
        const TTL = 3600_000;
        
        module.exports = class EventsProxy {
            constructor(logger, config) {
                this.logger = logger;
                this.config = config;
        
                this.subscriptions = new Map();
        
                // Ptarmigan's logger has trace/debug/info/error, but no warn().
                // Fall back to debug() for compatibility with Ptarmigan.
                this.logWarn = typeof logger.warn === 'function'
                    ? logger.warn.bind(logger)
                    : logger.debug.bind(logger);
        
                // EventsProxy logging is intentionally quiet by default.
                // Enable temporarily with POST /webhook/log/on
                // Disable again with POST /webhook/log/off
                this.loggingEnabled = false;
        
                // Used by /webhook/10 and /webhook/30.
                // A new timed motion extends the existing motion instead of
                // creating multiple independent false events.
                this.motionTimer = null;
        
                const timer = setInterval(() => this.cleanup(), 60_000);
                if (timer.unref)
                    timer.unref();
            }
        
            matches(path) {
                return path === '/onvif/Events'
                    || path === '/onvif/events_service'
                    || path.startsWith('/onvif/subscription/')
                    || path === '/webhook'
                    || path.startsWith('/webhook/');
            }
        
            log(message) {
                if (this.loggingEnabled)
                    this.logger.info(message);
            }
        
            debug(message) {
                if (this.loggingEnabled)
                    this.logger.debug(message);
            }
        
            async handle(req, res) {
                const path = req.url.split('?')[0];
        
                if (path === '/webhook' || path.startsWith('/webhook/'))
                    return this.webhook(req, res);
        
                const body = await this.readBody(req);
                const operation = this.operation(body);
        
                this.log(
                    `EVENTS: ${this.config.name} - ${req.method} ${path} -> ${operation || 'unknown'}`
                );
        
                if (path === '/onvif/Events' || path === '/onvif/events_service') {
                    if (req.method !== 'POST') {
                        res.writeHead(405, { Allow: 'POST' });
                        return res.end('POST required');
                    }
        
                    return this.eventsRequest(req, res, body, operation);
                }
        
                if (path.startsWith('/onvif/subscription/')) {
                    const id = path.slice('/onvif/subscription/'.length);
                    const sub = this.subscriptions.get(id);
        
                    if (!sub) {
                        this.logWarn(
                            `EVENTS: ${this.config.name} - unknown subscription ${id}`
                        );
                        res.writeHead(404);
                        return res.end('Subscription not found');
                    }
        
                    return this.subscriptionRequest(req, res, sub, body, operation);
                }
        
                res.writeHead(404);
                res.end('Not found');
            }
        
            operation(body) {
                const operations = [
                    'CreatePullPointSubscription',
                    'GetEventProperties',
                    'GetServiceCapabilities',
                    'PullMessages',
                    'Renew',
                    'Unsubscribe'
                ];
        
                for (const op of operations) {
                    const re = new RegExp(`<[^>]*${op}\\b`, 'i');
        
                    if (re.test(body))
                        return op;
                }
        
                return null;
            }
        
            async eventsRequest(req, res, body, operation) {
                switch (operation) {
                    case 'CreatePullPointSubscription':
                        return this.subscribe(res);
        
                    case 'GetEventProperties':
                        return this.getEventProperties(res);
        
                    case 'GetServiceCapabilities':
                        return this.getServiceCapabilities(res);
        
                    default:
                        this.logWarn(
                            `EVENTS: ${this.config.name} - unsupported Events operation: ${operation || 'unknown'}`
                        );
        
                        return this.fault(
                            res,
                            `unsupported Events operation: ${operation || 'unknown'}`
                        );
                }
            }
        
            async subscriptionRequest(req, res, sub, body, operation) {
                switch (operation) {
                    case 'PullMessages':
                        return this.pull(req, res, sub, body);
        
                    case 'Renew':
                        sub.expires = Date.now() + TTL;
        
                        this.log(
                            `EVENTS: ${this.config.name} - renew ${sub.id}`
                        );
        
                        return this.soap(
                            res,
                            `<tev:RenewResponse>
                                <tev:TerminationTime>${new Date(sub.expires).toISOString()}</tev:TerminationTime>
                            </tev:RenewResponse>`
                        );
        
                    case 'Unsubscribe':
                        this.subscriptions.delete(sub.id);
        
                        this.log(
                            `EVENTS: ${this.config.name} - unsubscribe ${sub.id}`
                        );
        
                        return this.soap(res, '<wsnt:UnsubscribeResponse/>');
        
                    default:
                        this.logWarn(
                            `EVENTS: ${this.config.name} - unsupported subscription operation: ${operation || 'unknown'}`
                        );
        
                        return this.fault(
                            res,
                            `unsupported subscription operation: ${operation || 'unknown'}`
                        );
                }
            }
        
            async webhook(req, res) {
                if (req.method !== 'POST') {
                    res.writeHead(405, { Allow: 'POST' });
                    return res.end('POST required');
                }
        
                const path = req.url.split('?')[0];
        
                /*
                 * Logging control.
                 *
                 * POST /webhook/log/on
                 * POST /webhook/log/off
                 *
                 * These are deliberately handled before reading/parsing a body.
                 */
                if (path === '/webhook/log/on' || path === '/webhook/log/off') {
                    this.loggingEnabled = path === '/webhook/log/on';
        
                    this.logger.info(
                        `EVENTS: ${this.config.name} - diagnostic logging ${this.loggingEnabled ? 'enabled' : 'disabled'}`
                    );
        
                    res.writeHead(200, { 'Content-Type': 'application/json' });
        
                    return res.end(JSON.stringify({
                        ok: true,
                        logging: this.loggingEnabled
                    }));
                }
        
                let mode = 'true';
        
                if (path === '/webhook/false') {
                    mode = 'false';
                } else if (path === '/webhook/10') {
                    mode = '10';
                } else if (path === '/webhook/30') {
                    mode = '30';
                }
        
                const body = await this.readBody(req);
        
                /*
                 * Normal /webhook behavior:
                 *
                 *   {"motion":true}
                 *   {"motion":false}
                 *
                 * If no valid boolean is supplied, preserve the original
                 * backwards-compatible default of motion=true.
                 */
                let motion = mode !== 'false';
        
                if (mode === 'true') {
                    try {
                        const json = JSON.parse(body);
        
                        if (typeof json.motion === 'boolean')
                            motion = json.motion;
                    } catch (e) {
                        // Default to motion=true for backwards compatibility.
                    }
                }
        
                /*
                 * Explicit false always cancels a pending timed motion.
                 */
                if (mode === 'false' || (mode === 'true' && motion === false)) {
                    this.cancelMotionTimer();
                }
        
                /*
                 * Timed modes:
                 *
                 * /webhook/10
                 * /webhook/30
                 *
                 * Start motion immediately and schedule its end.
                 *
                 * IMPORTANT:
                 * A subsequent timed webhook does NOT create another independent
                 * false event. It extends the current motion by restarting the
                 * timer. This gives us debounce/extension behavior.
                 */
                if (mode === '10' || mode === '30') {
                    motion = true;
        
                    const delay = mode === '10'
                        ? 10_000
                        : 30_000;
        
                    this.scheduleMotionEnd(delay);
                }
        
                const event = {
                    time: new Date().toISOString(),
                    topic: 'tns1:VideoSource/CellMotionDetector/Motion',
                    motion
                };
        
                this.emitEvent(event);
        
                this.log(
                    `EVENTS: ${this.config.name} - webhook motion=${motion} mode=${mode}`
                );
        
                res.writeHead(200, {
                    'Content-Type': 'application/json'
                });
        
                res.end(JSON.stringify({
                    ok: true,
                    event: 'motion',
                    motion,
                    mode,
                    delayedFalse: mode === '10' || mode === '30',
                    delaySeconds:
                        mode === '10' ? 10 :
                        mode === '30' ? 30 :
                        null,
                    logging: this.loggingEnabled,
                    subscriptions: this.subscriptions.size
                }));
            }
        
            scheduleMotionEnd(delay) {
                this.cancelMotionTimer();
        
                this.motionTimer = setTimeout(() => {
                    this.motionTimer = null;
        
                    this.emitEvent({
                        time: new Date().toISOString(),
                        topic: 'tns1:VideoSource/CellMotionDetector/Motion',
                        motion: false
                    });
        
                    this.log(
                        `EVENTS: ${this.config.name} - timed motion ended`
                    );
                }, delay);
        
                if (this.motionTimer.unref)
                    this.motionTimer.unref();
            }
        
            cancelMotionTimer() {
                if (this.motionTimer) {
                    clearTimeout(this.motionTimer);
                    this.motionTimer = null;
                }
            }
        
            emitEvent(event) {
                let delivered = 0;
                let queued = 0;
        
                for (const sub of this.subscriptions.values()) {
                    if (sub.waiter) {
                        const waiter = sub.waiter;
        
                        sub.waiter = null;
                        clearTimeout(waiter.timer);
        
                        delivered++;
        
                        this.pullResponse(
                            waiter.res,
                            sub,
                            [event]
                        );
                    } else {
                        sub.events.push(event);
        
                        if (sub.events.length > 32)
                            sub.events.shift();
        
                        queued++;
                    }
                }
        
                this.log(
                    `EVENTS: ${this.config.name} - event motion=${event.motion} ` +
                    `(delivered=${delivered}, queued=${queued}, subscriptions=${this.subscriptions.size})`
                );
            }
        
            subscribe(res) {
                if (this.subscriptions.size >= MAX_SUBSCRIPTIONS)
                    return this.fault(res, 'subscription limit reached');
        
                const id = crypto.randomUUID();
                const expires = Date.now() + TTL;
        
                const url =
                    `https://${this.config.hostname}:${this.config.ports.server}` +
                    `/onvif/subscription/${id}`;
        
                const sub = {
                    id,
                    created: Date.now(),
                    expires,
                    events: [],
                    waiter: null
                };
        
                this.subscriptions.set(id, sub);
        
                this.log(
                    `EVENTS: ${this.config.name} - subscription ${id} created -> ${url}`
                );
        
                return this.soap(res, `
        <tev:CreatePullPointSubscriptionResponse>
          <tev:SubscriptionReference>
            <wsa:Address>${url}</wsa:Address>
          </tev:SubscriptionReference>
          <wsnt:CurrentTime>${new Date().toISOString()}</wsnt:CurrentTime>
          <wsnt:TerminationTime>${new Date(expires).toISOString()}</wsnt:TerminationTime>
        </tev:CreatePullPointSubscriptionResponse>`);
            }
        
            getEventProperties(res) {
                this.log(
                    `EVENTS: ${this.config.name} - GetEventProperties`
                );
        
                return this.soap(res, `
        <tev:GetEventPropertiesResponse>
          <tev:TopicNamespaceLocation>
            https://www.onvif.org/onvif/ver10/topics/topicns.xml
          </tev:TopicNamespaceLocation>
        
          <tev:MessageContentFilterDialect>
            https://www.onvif.org/ver10/tev/messageContentFilter/ItemFilter
          </tev:MessageContentFilterDialect>
        
          <tev:MessageContentSchemaLocation>
            https://www.onvif.org/ver10/schema/onvif.xsd
          </tev:MessageContentSchemaLocation>
        
          <tev:TopicExpressionDialect>
            https://www.onvif.org/ver10/tev/topicExpression/ConcreteSet
          </tev:TopicExpressionDialect>
        
          <tev:TopicSet>
            <tns1:VideoSource>
              <tns1:CellMotionDetector>
                <tns1:Motion>
                  <tt:MessageDescription IsProperty="true">
                    <tt:Source>
                      <tt:SimpleItemDescription
                        Name="VideoSourceConfigurationToken"
                        Type="tt:ReferenceToken"/>
                    </tt:Source>
                    <tt:Data>
                      <tt:SimpleItemDescription
                        Name="IsMotion"
                        Type="xsd:boolean"/>
                    </tt:Data>
                  </tt:MessageDescription>
                </tns1:Motion>
              </tns1:CellMotionDetector>
            </tns1:VideoSource>
          </tev:TopicSet>
        </tev:GetEventPropertiesResponse>`);
            }
        
            getServiceCapabilities(res) {
                this.log(
                    `EVENTS: ${this.config.name} - GetServiceCapabilities`
                );
        
                return this.soap(res, `
        <tev:GetServiceCapabilitiesResponse>
          <tev:Capabilities
            WSSubscriptionPolicySupport="false"
            WSPullPointSupport="true"
            WSPausableSubscriptionManagerInterfaceSupport="false"/>
        </tev:GetServiceCapabilitiesResponse>`);
            }
        
            async pull(req, res, sub, body) {
                const limit = this.limit(body);
                const timeoutSeconds = Math.min(
                    this.timeout(body),
                    120
                );
        
                this.log(
                    `EVENTS: ${this.config.name} - PullMessages ${sub.id} ` +
                    `(timeout=${timeoutSeconds}s, limit=${limit}, queued=${sub.events.length})`
                );
        
                if (sub.events.length) {
                    const events = sub.events.splice(0, limit);
        
                    this.log(
                        `EVENTS: ${this.config.name} - PullMessages ${sub.id} -> ${events.length} queued event(s)`
                    );
        
                    return this.pullResponse(
                        res,
                        sub,
                        events
                    );
                }
        
                const timeout = timeoutSeconds * 1000;
        
                const waiter = {
                    res,
                    timer: setTimeout(() => {
                        if (sub.waiter === waiter) {
                            sub.waiter = null;
        
                            this.log(
                                `EVENTS: ${this.config.name} - PullMessages ${sub.id} -> timeout`
                            );
        
                            this.pullResponse(
                                res,
                                sub,
                                []
                            );
                        }
                    }, timeout)
                };
        
                sub.waiter = waiter;
        
                req.on('close', () => {
                    if (sub.waiter === waiter) {
                        sub.waiter = null;
                        clearTimeout(waiter.timer);
        
                        this.log(
                            `EVENTS: ${this.config.name} - PullMessages ${sub.id} -> client closed`
                        );
                    }
                });
            }
        
            pullResponse(res, sub, events) {
                if (res.writableEnded)
                    return;
        
                const notifications = events.map(e => `
        <wsnt:NotificationMessage>
          <wsnt:Topic
            Dialect="https://www.onvif.org/ver10/tev/topicExpression/ConcreteSet">
            ${e.topic}
          </wsnt:Topic>
          <wsnt:Message>
            <tt:Message
              UtcTime="${e.time}"
              PropertyOperation="Changed">
              <tt:Source>
                <tt:SimpleItem
                  Name="VideoSourceConfigurationToken"
                  Value="video_src_token"/>
              </tt:Source>
              <tt:Data>
                <tt:SimpleItem
                  Name="IsMotion"
                  Value="${e.motion ? 'true' : 'false'}"/>
              </tt:Data>
            </tt:Message>
          </wsnt:Message>
        </wsnt:NotificationMessage>`).join('');
        
                this.soap(res, `
        <tev:PullMessagesResponse>
          <tev:CurrentTime>${new Date().toISOString()}</tev:CurrentTime>
          <tev:TerminationTime>${new Date(sub.expires).toISOString()}</tev:TerminationTime>
          ${notifications}
        </tev:PullMessagesResponse>`);
            }
        
            readBody(req) {
                return new Promise((resolve, reject) => {
                    let body = '';
        
                    req.on('data', chunk => {
                        body += chunk;
                    });
        
                    req.on('end', () => resolve(body));
                    req.on('error', reject);
                });
            }
        
            timeout(body) {
                const m = body.match(
                    /<[^>]*Timeout[^>]*>PT([\d.]+)S/i
                );
        
                return m
                    ? parseFloat(m[1])
                    : 10;
            }
        
            limit(body) {
                const m = body.match(
                    /<[^>]*MessageLimit[^>]*>(\d+)/i
                );
        
                return Math.max(
                    1,
                    Math.min(
                        m ? parseInt(m[1], 10) : 1,
                        32
                    )
                );
            }
        
            soap(res, body) {
                const xml = `<?xml version="1.0" encoding="UTF-8"?>
        <s:Envelope
          xmlns:s="https://www.w3.org/2003/05/soap-envelope"
          xmlns:wsa="https://www.w3.org/2005/08/addressing"
          xmlns:wsnt="https://docs.oasis-open.org/wsn/b-2"
          xmlns:tev="https://www.onvif.org/ver10/events/wsdl"
          xmlns:tt="https://www.onvif.org/ver10/schema"
          xmlns:tns1="https://www.onvif.org/ver10/topics"
          xmlns:xsd="https://www.w3.org/2001/XMLSchema">
          <s:Body>${body}</s:Body>
        </s:Envelope>`;
        
                res.writeHead(200, {
                    'Content-Type': 'application/soap+xml; charset=utf-8',
                    'Content-Length': Buffer.byteLength(xml)
                });
        
                res.end(xml);
            }
        
            fault(res, text) {
                this.soap(res, `
        <s:Fault>
          <s:Code>
            <s:Value>s:Sender</s:Value>
          </s:Code>
          <s:Reason>
            <s:Text>${text}</s:Text>
          </s:Reason>
        </s:Fault>`);
            }
        
            cleanup() {
                const now = Date.now();
        
                for (const [id, sub] of this.subscriptions) {
                    if (sub.expires < now) {
                        if (sub.waiter) {
                            clearTimeout(sub.waiter.timer);
        
                            if (!sub.waiter.res.writableEnded)
                                this.pullResponse(
                                    sub.waiter.res,
                                    sub,
                                    []
                                );
                        }
        
                        this.subscriptions.delete(id);
        
                        this.log(
                            `EVENTS: ${this.config.name} - expired subscription ${id}`
                        );
                    }
                }
            }
        };
        Zuletzt geändert von MarkusCosi; 11.09.2026, 09:35.

        Kommentar

      • MarkusCosi
        LoxBus Spammer
        • 28.09.2023
        • 411

        #97
        ..gibt eigentlich schon etwas Neues hinsichtlich Audio? Planst du in der Bridge auch die Ton-Spur mit abzugreifen?

        Kommentar

        • MarkusCosi
          LoxBus Spammer
          • 28.09.2023
          • 411

          #98
          ...ich fürchte das letzte Intercom Update (17.03.11.05. Dabei: "BG-T5818 Intercom Gen2 WebRTC TPD support" / "Video and audio handling improved") von Loxone hat alles kaputt gemacht? Im webinterface von go2rtc sehe ich "streams: wrong response on DESCRIBE".
          Zuletzt geändert von MarkusCosi; In den letzten 2 Wochen.

          Kommentar

          • halbleiter
            Azubi
            • 17.11.2025
            • 9

            #99
            Hier mal meine html/javascript Version, die ich mit V16 am Laufen habe. Vielleicht kann die mal jemand mit V17 testen.
            HTML:
            Code:
            <!DOCTYPE html>
            <html>
             <head>
              <meta charset="utf-8">
              <title>LoxView 13</title>
              <style>
               body { font-family: monospace; padding: 20px; }
               video { border: 1px solid #888; background: #000; display: block; margin-bottom: 10px; }
               audio { display: block; margin-bottom: 20px; }
               button { padding: 10px 20px; font-size: 14px; cursor: pointer; margin-right: 10px; }
              </style>
             </head>
            
             <body>
              <h1>LoxView 13</h1>
              <div>
               <video id="stream" width="960" height="540" autoplay playsinline>Your browser does not support video</video>
               <audio id="sound" autoplay></audio>
             </div>
              <div>
               <button id="startButton">Start</button>
               <button id="talkButton" disabled>Talk</button>
               <button id="hangupButton" disabled>Auflegen</button>
              </div>
              <script src="loxview13.js"></script>
             </body>
            </html>
            JS:
            Code:
            ​const loxIntercom = 'https://192.168.0.13';
            let rpcPeer;
            let videoPeerCon;
            let audioPeerCon;
            var micStream = null;
            let audioCtx;
            
            /* jsonRpc client/server */
            
            class JsonRpcWebSocketPeer {
             constructor(url, protocol) {
              this.url = url;
              this.protocol = protocol;
              this.ws = null;
              this.idCounter = 1;
              this.pendingRequests = new Map(); // Für ausgehende Anfragen
              this.exposedMethods = new Map();  // Für eingehende RPC-Methoden (Server-Funktion)
             }
            
             expose(method, callback) {
              this.exposedMethods.set(method, callback);
             }
            
             connect() {
              return new Promise((resolve, reject) => {
               this.ws = new WebSocket(this.url, this.protocol);
               this.ws.onopen = () => {
                console.log('Verbunden');
                resolve();
               };
               this.ws.onerror = (error) => {
                reject(error);
               };
               this.ws.onmessage = async (event) => {
                try {
                 const message = JSON.parse(event.data);
                 if ('result' in message || 'error' in message) {
                  this._handleResponse(message);
                 }
                 else if ('method' in message) {
                  await this._handleIncomingCall(message);
                 }
                } catch (err) {
                 console.error('Fehler beim Verarbeiten der Nachricht:', err);
                }
               };
              });
             }
            
             _handleResponse(response) {
              const id = response.id;
              if (this.pendingRequests.has(id)) {
               const { resolveRequest, rejectRequest } = this.pendingRequests.get(id);
               this.pendingRequests.delete(id);
               if (response.error) {
                rejectRequest(new Error(`RPC Error [${response.error.code}]: ${response.error.message}`));
               } else {
                resolveRequest(response.result);
               }
              }
             }
            
             async _handleIncomingCall(request) {
              const { method, params, id } = request;
              const isNotification = id === undefined || id === null;
              if (!this.exposedMethods.has(method)) {
               if (!isNotification) {
                this._sendError(id, -32601, `Methode '${method}' nicht gefunden`);
               }
               return;
              }
              try {
               const handler = this.exposedMethods.get(method);
               const result = await handler(params);
               if (!isNotification) {
                this.ws.send(JSON.stringify({
                 jsonrpc: '2.0',
                 result: result,
                 id: id
                }));
               }
              } catch (err) {
               if (!isNotification) {
                this._sendError(id, -32603, err.message || 'Interner Fehler');
               }
              }
             }
            
             _sendError(id, code, message) {
              this.ws.send(JSON.stringify({
               jsonrpc: '2.0',
               error: { code, message },
               id: id
              }));
             }
            
             call(method, params = []) {
              return new Promise((resolveRequest, rejectRequest) => {
               if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                return rejectRequest(new Error('Nicht verbunden.'));
               }
               const id = this.idCounter++;
               const payload = {
                jsonrpc: '2.0',
                method: method,
                params: params,
                id: id
               };
               this.pendingRequests.set(id, { resolveRequest, rejectRequest });
               this.ws.send(JSON.stringify(payload));
              });
             }
            
             disconnect() {
              if (this.ws) {
               this.ws.close(1000, 'Verbindung durch Client beendet');
              }
             }
            }
            
            
            /* webRTC handling -----------------------------*/
            
            async function onIceCandidate(event) {
             try {
              if (event.candidate == null)
               await rpcPeer.call('iceGatheringFinished',);
              else
               await rpcPeer.call('addIceCandidate', [event.candidate.candidate, 0]);
             } catch (error) {
              console.log(error);
             }
            }
            
            function onRemoteStream(event) {
             console.log('Track empfangen:', event.track.kind);
             if (event.track.kind === 'video') {
              stream.srcObject = event.streams[0];
              talkButton.disabled = false;
              hangupButton.disabled = false;
             } else if (event.track.kind === 'audio') {
              sound.srcObject = event.streams[0];
              sound.muted = true;
              sound.play().catch(e => console.log(e));
              if (!audioCtx)
               audioCtx = new (window.AudioContext || window.webkitAudioContext)();
              const source = audioCtx.createMediaStreamSource(event.streams[0]);
              const gainNode = audioCtx.createGain();
              gainNode.gain.value = 30.0;
              const compressor = audioCtx.createDynamicsCompressor();
              compressor.threshold.value = -24;
              compressor.knee.value = 30;
              compressor.ratio.value = 12;
              compressor.attack.value = 0.003;
              compressor.release.value = 0.25;  
              source.connect(gainNode);
              gainNode.connect(compressor);
              compressor.connect(audioCtx.destination);
             }
            }
            
            
            async function videoCreateOffer(event) {
             try {
              const sessionDescription = await videoPeerCon.createOffer();
              await videoPeerCon.setLocalDescription(sessionDescription);
              const result = await rpcPeer.call('call', [sessionDescription, 'new', false, 0]);
              await videoPeerCon.setRemoteDescription(new RTCSessionDescription(result.data));
             } catch (error) {
              console.log(error);
             }
            }
            
            async function audioCreateOffer(event) {
             try {
              const sessionDescription = await audioPeerCon.createOffer();
              await audioPeerCon.setLocalDescription(sessionDescription);
              const result = await rpcPeer.call('call', [sessionDescription, 'add_audio', true, 0]);
              await audioPeerCon.setRemoteDescription(new RTCSessionDescription(result.data));
             } catch (error) {
              console.log(error);
             }
            }
            
            async function addIceCandidate(params) {
             try {
              const candidate = new RTCIceCandidate({
               candidate: params[0],
               sdpMLineIndex: params[1],
               sdpMid: params[2]
              });
              try { await videoPeerCon.addIceCandidate(candidate); } catch (e) {}
              try { await audioPeerCon.addIceCandidate(candidate); } catch (e) {}
             } catch (error) {
              console.log(error);
             }
            }
            
            async function setupAudioTransceiver() {
             micStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
             const audioTracks = micStream.getAudioTracks();
             if (audioTracks.length > 0) {
              const transceiver = audioPeerCon.addTransceiver(audioTracks[0], {
               direction: 'sendrecv',
               streams: [micStream]
              });
              const capabilities = RTCRtpSender.getCapabilities('audio');
              if (capabilities && capabilities.codecs) {
               let codecs = [...capabilities.codecs];
               codecs.sort((a, b) => {
                if (a.mimeType.toLowerCase() === 'audio/pcma') return -1;
                if (b.mimeType.toLowerCase() === 'audio/pcma') return 1;
                return 0;
               });
               transceiver.setCodecPreferences(codecs);
              }
             }
            }
            
            async function start() {
             rpcPeer.expose('addIceCandidate', addIceCandidate)
             try {
              await rpcPeer.connect();
              videoPeerCon = new RTCPeerConnection();
              videoPeerCon.onicecandidate = onIceCandidate;
              videoPeerCon.ontrack = onRemoteStream;
              videoPeerCon.onnegotiationneeded = videoCreateOffer;
              videoPeerCon.addTransceiver('video', {'direction':'recvonly'});
             } catch (error) {
              console.log(error);
             }
            }
            
            async function talk() {
             rpcPeer.expose('addIceCandidate', addIceCandidate)
             try {
              audioPeerCon = new RTCPeerConnection();
              audioPeerCon.onicecandidate = onIceCandidate;
              audioPeerCon.ontrack = onRemoteStream;
              audioPeerCon.onnegotiationneeded = audioCreateOffer;
              await setupAudioTransceiver();
             } catch (error) {
              console.log(error);
             }
            }
            
            async function hangup() {
             try {
              await rpcPeer.call('hangup',);
              await rpcPeer.disconnect();
              if (micStream) {
               micStream.getTracks().forEach(track=> track.stop());
               micStream = null;
              }
              if (videoPeerCon) {
               videoPeerCon.close();
               videoPeerCon = null;
              }
              if (audioPeerCon) {
               audioPeerCon.close();
               audioPeerCon = null;
              }
              stream.srcObject = null;
              sound.srcObject = null;
              startButton.disabled = false;
              talkButton.disabled = true;
              hangupButton.disabled = true;
             } catch (error) {
              console.log(error);
             }
            }
            
            rpcPeer = new JsonRpcWebSocketPeer(loxIntercom, 'webrtc-signaling');
            startButton.addEventListener('click', start);
            talkButton.addEventListener('click', talk);
            hangupButton.addEventListener('click', hangup);
            ​

            Kommentar

            Lädt...