Weiter zum Inhalt
  • Home
  • Aktuell
  • Tags
  • 0 Ungelesen 0
  • Kategorien
  • Unreplied
  • Beliebt
  • GitHub
  • Docu
  • Hilfe
Skins
  • Hell
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dunkel
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Standard: (Kein Skin)
  • Kein Skin
Einklappen
ioBroker Logo

Community Forum

donate donate
  1. ioBroker Community Home
  2. Deutsch
  3. Skripten / Logik
  4. JavaScript
  5. Script mit "request" umbauen

NEWS

  • Neuer ioBroker-Blog online: Monatsrückblick März/April 2026
    BluefoxB
    Bluefox
    8
    1
    1.7k

  • Verwendung von KI bitte immer deutlich kennzeichnen
    HomoranH
    Homoran
    10
    1
    679

  • Monatsrückblick Januar/Februar 2026 ist online!
    BluefoxB
    Bluefox
    18
    1
    1.2k

Script mit "request" umbauen

Geplant Angeheftet Gesperrt Verschoben JavaScript
7 Beiträge 3 Kommentatoren 921 Aufrufe 5 Beobachtet
  • Älteste zuerst
  • Neuste zuerst
  • Meiste Stimmen
Antworten
  • In einem neuen Thema antworten
Anmelden zum Antworten
Dieses Thema wurde gelöscht. Nur Nutzer mit entsprechenden Rechten können es sehen.
  • Merlin123M Offline
    Merlin123M Offline
    Merlin123
    schrieb am zuletzt editiert von
    #1

    Ein ähnliches Problem gab es hier schon, aber ich kann mit der Lösung dort nichts anfangen :( Kann kein JS (bis jetzt)

    Hab folgendes Script

    const printerName = 'K1'; // Replace with your actual printer name
    const printerBaseUrl = 'http://192.168.0.252:7125'; // Replace with your actual moonraker ip
    const updateInterval = 20000; // 20 seconds
     
    // Function to make an HTTP request and return a promise
    function getPrinterStatus(url) {
        return new Promise((resolve, reject) => {
            const request = require('request');
            request(url, { json: true }, (err, res, body) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(body);
                }
            });
        });
    }
     
    // Function to get metadata for the given filename
    function getFileMetadata(filename) {
        const metadataUrl = printerBaseUrl + `/server/files/metadata?filename=${encodeURIComponent(filename)}`;
        return getPrinterStatus(metadataUrl); // Reusing the HTTP request function
    }
     
    // Function to convert seconds to HH:MM:SS
    function toHHMMSS(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const sec = Math.floor(seconds % 60);
        return [hours, minutes, sec]
            .map(v => v < 10 ? "0" + v : v)
            .join(":");
    }
     
    // Function to update the online status of the printer
    function updatePrinterOnlineStatus(isOnline) {
        const onlineStateName = `${printerName}.onlineStatus`;
        createOrUpdateState(onlineStateName, isOnline);
    }
     
    // Function to create or update ioBroker states
    function createOrUpdateState(fullStateName, value, key='') {
     
        // Check if the key contains 'duration' and format it if it does
        if (key.includes('duration')) {
            value = toHHMMSS(value);
        }
     
        // Check if the key contains 'progress' and multiply by 100 and round it if it does
        if (key.includes('progress')) {
            value = Math.round(value * 100); // Converts to percentage and rounds to the nearest integer
        }
     
        if (!existsState(fullStateName)) {
            createState(fullStateName, {
                type: typeof value,
                read: true,
                write: false,
                desc: 'Printer status value'
            }, () => {
                setState(fullStateName, value, true);
            });
        } else {
            setState(fullStateName, value, true);
        }
    }
     
    // Function to process the printer status and update the ioBroker states
    function processPrinterStatus(printerData, parentKey = '') {
        Object.keys(printerData).forEach(key => {
            const value = printerData[key];
            let fullStateName = `${printerName}`;
            if (parentKey) {
                fullStateName += `.${parentKey}`;
            }
            fullStateName += `.${key}`;
     
            if (value !== null && typeof value === 'object' && !(value instanceof Array)) {
                // It's a nested object, so we need to recurse
                processPrinterStatus(value, key);
            } else {
                // It's a value, so we create or update the state
                createOrUpdateState(fullStateName, value, key);
            }
        });
    }
     
    // Function to nullify file metadata states in ioBroker
    function nullifyFileMetadataStates() {
     
        var states = $(`*.${printerName}.file_metadata.*`/*Printer file metadata*/);
     
        states.each(function(id, i){
            setState(id, {val: null, ack: true});
        });
    }
     
    // Polling function
    function startPolling() {
        setInterval(() => {
            if (getState('sonoff.0.DVES_C38B13.POWER').val == true) getPrinterStatus(printerBaseUrl + '/printer/objects/query?display_status&print_stats&extruder&heater_bed&system_stats')
                .then(response => {
                    if (response && response.result) {
                        
                        const printStats = response.result.status.print_stats || {};
                        const filename = printStats.filename;
                        
                        // Update printer status
                        processPrinterStatus(response.result);
     
                        // If there is a filename, get and process the file metadata
                        if (filename) {
                            getFileMetadata(filename).then(metadataResponse => {
                                if (metadataResponse && metadataResponse.result) {
                                    processPrinterStatus(metadataResponse.result, 'file_metadata');
                                }
                            }).catch(error => {
                                console.error('Error fetching file metadata:', error);
                            });
                        } else {
                            // If filename is empty, nullify all file_metadata states
                            nullifyFileMetadataStates();
                        }
                        
                        updatePrinterOnlineStatus(true); // Printer is online
                    }
                })
                .catch(error => {
                    console.log('Error fetching printer status... setting Printer offline');
                    updatePrinterOnlineStatus(false); // Printer is offline
                });
        }, updateInterval);
    }
     
    // Start the polling process
    startPolling();
    
    

    Da soll das request raus.
    Hatte mit ChatGPT mein Glück versucht und den request block so ersetzt:

    // Function to make an HTTP request and return a promise
    const axios = require('axios');
    
    function getPrinterStatus(url) {
        return axios.get(url)
            .then(response => response.data)
            .catch(error => {
                throw error;
            });
    }
    

    Reicht aber anscheinend nicht...
    Was muss ich da noch umbauen?

    Beta-Tester

    Merlin123M crunchipC haus-automatisierungH 3 Antworten Letzte Antwort
    0
    • Merlin123M Merlin123

      Ein ähnliches Problem gab es hier schon, aber ich kann mit der Lösung dort nichts anfangen :( Kann kein JS (bis jetzt)

      Hab folgendes Script

      const printerName = 'K1'; // Replace with your actual printer name
      const printerBaseUrl = 'http://192.168.0.252:7125'; // Replace with your actual moonraker ip
      const updateInterval = 20000; // 20 seconds
       
      // Function to make an HTTP request and return a promise
      function getPrinterStatus(url) {
          return new Promise((resolve, reject) => {
              const request = require('request');
              request(url, { json: true }, (err, res, body) => {
                  if (err) {
                      reject(err);
                  } else {
                      resolve(body);
                  }
              });
          });
      }
       
      // Function to get metadata for the given filename
      function getFileMetadata(filename) {
          const metadataUrl = printerBaseUrl + `/server/files/metadata?filename=${encodeURIComponent(filename)}`;
          return getPrinterStatus(metadataUrl); // Reusing the HTTP request function
      }
       
      // Function to convert seconds to HH:MM:SS
      function toHHMMSS(seconds) {
          const hours = Math.floor(seconds / 3600);
          const minutes = Math.floor((seconds % 3600) / 60);
          const sec = Math.floor(seconds % 60);
          return [hours, minutes, sec]
              .map(v => v < 10 ? "0" + v : v)
              .join(":");
      }
       
      // Function to update the online status of the printer
      function updatePrinterOnlineStatus(isOnline) {
          const onlineStateName = `${printerName}.onlineStatus`;
          createOrUpdateState(onlineStateName, isOnline);
      }
       
      // Function to create or update ioBroker states
      function createOrUpdateState(fullStateName, value, key='') {
       
          // Check if the key contains 'duration' and format it if it does
          if (key.includes('duration')) {
              value = toHHMMSS(value);
          }
       
          // Check if the key contains 'progress' and multiply by 100 and round it if it does
          if (key.includes('progress')) {
              value = Math.round(value * 100); // Converts to percentage and rounds to the nearest integer
          }
       
          if (!existsState(fullStateName)) {
              createState(fullStateName, {
                  type: typeof value,
                  read: true,
                  write: false,
                  desc: 'Printer status value'
              }, () => {
                  setState(fullStateName, value, true);
              });
          } else {
              setState(fullStateName, value, true);
          }
      }
       
      // Function to process the printer status and update the ioBroker states
      function processPrinterStatus(printerData, parentKey = '') {
          Object.keys(printerData).forEach(key => {
              const value = printerData[key];
              let fullStateName = `${printerName}`;
              if (parentKey) {
                  fullStateName += `.${parentKey}`;
              }
              fullStateName += `.${key}`;
       
              if (value !== null && typeof value === 'object' && !(value instanceof Array)) {
                  // It's a nested object, so we need to recurse
                  processPrinterStatus(value, key);
              } else {
                  // It's a value, so we create or update the state
                  createOrUpdateState(fullStateName, value, key);
              }
          });
      }
       
      // Function to nullify file metadata states in ioBroker
      function nullifyFileMetadataStates() {
       
          var states = $(`*.${printerName}.file_metadata.*`/*Printer file metadata*/);
       
          states.each(function(id, i){
              setState(id, {val: null, ack: true});
          });
      }
       
      // Polling function
      function startPolling() {
          setInterval(() => {
              if (getState('sonoff.0.DVES_C38B13.POWER').val == true) getPrinterStatus(printerBaseUrl + '/printer/objects/query?display_status&print_stats&extruder&heater_bed&system_stats')
                  .then(response => {
                      if (response && response.result) {
                          
                          const printStats = response.result.status.print_stats || {};
                          const filename = printStats.filename;
                          
                          // Update printer status
                          processPrinterStatus(response.result);
       
                          // If there is a filename, get and process the file metadata
                          if (filename) {
                              getFileMetadata(filename).then(metadataResponse => {
                                  if (metadataResponse && metadataResponse.result) {
                                      processPrinterStatus(metadataResponse.result, 'file_metadata');
                                  }
                              }).catch(error => {
                                  console.error('Error fetching file metadata:', error);
                              });
                          } else {
                              // If filename is empty, nullify all file_metadata states
                              nullifyFileMetadataStates();
                          }
                          
                          updatePrinterOnlineStatus(true); // Printer is online
                      }
                  })
                  .catch(error => {
                      console.log('Error fetching printer status... setting Printer offline');
                      updatePrinterOnlineStatus(false); // Printer is offline
                  });
          }, updateInterval);
      }
       
      // Start the polling process
      startPolling();
      
      

      Da soll das request raus.
      Hatte mit ChatGPT mein Glück versucht und den request block so ersetzt:

      // Function to make an HTTP request and return a promise
      const axios = require('axios');
      
      function getPrinterStatus(url) {
          return axios.get(url)
              .then(response => response.data)
              .catch(error => {
                  throw error;
              });
      }
      

      Reicht aber anscheinend nicht...
      Was muss ich da noch umbauen?

      Merlin123M Offline
      Merlin123M Offline
      Merlin123
      schrieb am zuletzt editiert von
      #2

      @merlin123 Hab es jetzt mal anders umbauen lassen:

      const http = require('http');
      
      // Function to make an HTTP request and return a promise
      function getPrinterStatus(url) {
          return new Promise((resolve, reject) => {
              const req = http.get(url, (res) => {
                  let data = '';
      
                  // A chunk of data has been received
                  res.on('data', (chunk) => {
                      data += chunk;
                  });
      
                  // The whole response has been received
                  res.on('end', () => {
                      try {
                          const parsedData = JSON.parse(data);
                          resolve(parsedData);
                      } catch (error) {
                          reject(error);
                      }
                  });
              });
      
              // Error handling for the request
              req.on('error', (error) => {
                  reject(error);
              });
          });
      }
      

      Wirft zumindest nicht gleich nen Fehler. Mal testen, wenn ich das nächste Mal was drucke

      Beta-Tester

      Merlin123M 1 Antwort Letzte Antwort
      0
      • Merlin123M Merlin123

        @merlin123 Hab es jetzt mal anders umbauen lassen:

        const http = require('http');
        
        // Function to make an HTTP request and return a promise
        function getPrinterStatus(url) {
            return new Promise((resolve, reject) => {
                const req = http.get(url, (res) => {
                    let data = '';
        
                    // A chunk of data has been received
                    res.on('data', (chunk) => {
                        data += chunk;
                    });
        
                    // The whole response has been received
                    res.on('end', () => {
                        try {
                            const parsedData = JSON.parse(data);
                            resolve(parsedData);
                        } catch (error) {
                            reject(error);
                        }
                    });
                });
        
                // Error handling for the request
                req.on('error', (error) => {
                    reject(error);
                });
            });
        }
        

        Wirft zumindest nicht gleich nen Fehler. Mal testen, wenn ich das nächste Mal was drucke

        Merlin123M Offline
        Merlin123M Offline
        Merlin123
        schrieb am zuletzt editiert von
        #3

        War leider nix.... Wirft keinen Fehler, aber es geht leider nicht mehr :(

        Beta-Tester

        1 Antwort Letzte Antwort
        0
        • Merlin123M Merlin123

          Ein ähnliches Problem gab es hier schon, aber ich kann mit der Lösung dort nichts anfangen :( Kann kein JS (bis jetzt)

          Hab folgendes Script

          const printerName = 'K1'; // Replace with your actual printer name
          const printerBaseUrl = 'http://192.168.0.252:7125'; // Replace with your actual moonraker ip
          const updateInterval = 20000; // 20 seconds
           
          // Function to make an HTTP request and return a promise
          function getPrinterStatus(url) {
              return new Promise((resolve, reject) => {
                  const request = require('request');
                  request(url, { json: true }, (err, res, body) => {
                      if (err) {
                          reject(err);
                      } else {
                          resolve(body);
                      }
                  });
              });
          }
           
          // Function to get metadata for the given filename
          function getFileMetadata(filename) {
              const metadataUrl = printerBaseUrl + `/server/files/metadata?filename=${encodeURIComponent(filename)}`;
              return getPrinterStatus(metadataUrl); // Reusing the HTTP request function
          }
           
          // Function to convert seconds to HH:MM:SS
          function toHHMMSS(seconds) {
              const hours = Math.floor(seconds / 3600);
              const minutes = Math.floor((seconds % 3600) / 60);
              const sec = Math.floor(seconds % 60);
              return [hours, minutes, sec]
                  .map(v => v < 10 ? "0" + v : v)
                  .join(":");
          }
           
          // Function to update the online status of the printer
          function updatePrinterOnlineStatus(isOnline) {
              const onlineStateName = `${printerName}.onlineStatus`;
              createOrUpdateState(onlineStateName, isOnline);
          }
           
          // Function to create or update ioBroker states
          function createOrUpdateState(fullStateName, value, key='') {
           
              // Check if the key contains 'duration' and format it if it does
              if (key.includes('duration')) {
                  value = toHHMMSS(value);
              }
           
              // Check if the key contains 'progress' and multiply by 100 and round it if it does
              if (key.includes('progress')) {
                  value = Math.round(value * 100); // Converts to percentage and rounds to the nearest integer
              }
           
              if (!existsState(fullStateName)) {
                  createState(fullStateName, {
                      type: typeof value,
                      read: true,
                      write: false,
                      desc: 'Printer status value'
                  }, () => {
                      setState(fullStateName, value, true);
                  });
              } else {
                  setState(fullStateName, value, true);
              }
          }
           
          // Function to process the printer status and update the ioBroker states
          function processPrinterStatus(printerData, parentKey = '') {
              Object.keys(printerData).forEach(key => {
                  const value = printerData[key];
                  let fullStateName = `${printerName}`;
                  if (parentKey) {
                      fullStateName += `.${parentKey}`;
                  }
                  fullStateName += `.${key}`;
           
                  if (value !== null && typeof value === 'object' && !(value instanceof Array)) {
                      // It's a nested object, so we need to recurse
                      processPrinterStatus(value, key);
                  } else {
                      // It's a value, so we create or update the state
                      createOrUpdateState(fullStateName, value, key);
                  }
              });
          }
           
          // Function to nullify file metadata states in ioBroker
          function nullifyFileMetadataStates() {
           
              var states = $(`*.${printerName}.file_metadata.*`/*Printer file metadata*/);
           
              states.each(function(id, i){
                  setState(id, {val: null, ack: true});
              });
          }
           
          // Polling function
          function startPolling() {
              setInterval(() => {
                  if (getState('sonoff.0.DVES_C38B13.POWER').val == true) getPrinterStatus(printerBaseUrl + '/printer/objects/query?display_status&print_stats&extruder&heater_bed&system_stats')
                      .then(response => {
                          if (response && response.result) {
                              
                              const printStats = response.result.status.print_stats || {};
                              const filename = printStats.filename;
                              
                              // Update printer status
                              processPrinterStatus(response.result);
           
                              // If there is a filename, get and process the file metadata
                              if (filename) {
                                  getFileMetadata(filename).then(metadataResponse => {
                                      if (metadataResponse && metadataResponse.result) {
                                          processPrinterStatus(metadataResponse.result, 'file_metadata');
                                      }
                                  }).catch(error => {
                                      console.error('Error fetching file metadata:', error);
                                  });
                              } else {
                                  // If filename is empty, nullify all file_metadata states
                                  nullifyFileMetadataStates();
                              }
                              
                              updatePrinterOnlineStatus(true); // Printer is online
                          }
                      })
                      .catch(error => {
                          console.log('Error fetching printer status... setting Printer offline');
                          updatePrinterOnlineStatus(false); // Printer is offline
                      });
              }, updateInterval);
          }
           
          // Start the polling process
          startPolling();
          
          

          Da soll das request raus.
          Hatte mit ChatGPT mein Glück versucht und den request block so ersetzt:

          // Function to make an HTTP request and return a promise
          const axios = require('axios');
          
          function getPrinterStatus(url) {
              return axios.get(url)
                  .then(response => response.data)
                  .catch(error => {
                      throw error;
                  });
          }
          

          Reicht aber anscheinend nicht...
          Was muss ich da noch umbauen?

          crunchipC Abwesend
          crunchipC Abwesend
          crunchip
          Forum Testing Most Active Developer
          schrieb am zuletzt editiert von
          #4

          @merlin123 sagte in Script mit "request" umbauen:

          Kann kein JS

          ich auch nicht, aber denke das sollte so in etwas passen
          https://forum.iobroker.net/post/1159470

          umgestiegen von Proxmox auf Unraid

          1 Antwort Letzte Antwort
          1
          • Merlin123M Merlin123

            Ein ähnliches Problem gab es hier schon, aber ich kann mit der Lösung dort nichts anfangen :( Kann kein JS (bis jetzt)

            Hab folgendes Script

            const printerName = 'K1'; // Replace with your actual printer name
            const printerBaseUrl = 'http://192.168.0.252:7125'; // Replace with your actual moonraker ip
            const updateInterval = 20000; // 20 seconds
             
            // Function to make an HTTP request and return a promise
            function getPrinterStatus(url) {
                return new Promise((resolve, reject) => {
                    const request = require('request');
                    request(url, { json: true }, (err, res, body) => {
                        if (err) {
                            reject(err);
                        } else {
                            resolve(body);
                        }
                    });
                });
            }
             
            // Function to get metadata for the given filename
            function getFileMetadata(filename) {
                const metadataUrl = printerBaseUrl + `/server/files/metadata?filename=${encodeURIComponent(filename)}`;
                return getPrinterStatus(metadataUrl); // Reusing the HTTP request function
            }
             
            // Function to convert seconds to HH:MM:SS
            function toHHMMSS(seconds) {
                const hours = Math.floor(seconds / 3600);
                const minutes = Math.floor((seconds % 3600) / 60);
                const sec = Math.floor(seconds % 60);
                return [hours, minutes, sec]
                    .map(v => v < 10 ? "0" + v : v)
                    .join(":");
            }
             
            // Function to update the online status of the printer
            function updatePrinterOnlineStatus(isOnline) {
                const onlineStateName = `${printerName}.onlineStatus`;
                createOrUpdateState(onlineStateName, isOnline);
            }
             
            // Function to create or update ioBroker states
            function createOrUpdateState(fullStateName, value, key='') {
             
                // Check if the key contains 'duration' and format it if it does
                if (key.includes('duration')) {
                    value = toHHMMSS(value);
                }
             
                // Check if the key contains 'progress' and multiply by 100 and round it if it does
                if (key.includes('progress')) {
                    value = Math.round(value * 100); // Converts to percentage and rounds to the nearest integer
                }
             
                if (!existsState(fullStateName)) {
                    createState(fullStateName, {
                        type: typeof value,
                        read: true,
                        write: false,
                        desc: 'Printer status value'
                    }, () => {
                        setState(fullStateName, value, true);
                    });
                } else {
                    setState(fullStateName, value, true);
                }
            }
             
            // Function to process the printer status and update the ioBroker states
            function processPrinterStatus(printerData, parentKey = '') {
                Object.keys(printerData).forEach(key => {
                    const value = printerData[key];
                    let fullStateName = `${printerName}`;
                    if (parentKey) {
                        fullStateName += `.${parentKey}`;
                    }
                    fullStateName += `.${key}`;
             
                    if (value !== null && typeof value === 'object' && !(value instanceof Array)) {
                        // It's a nested object, so we need to recurse
                        processPrinterStatus(value, key);
                    } else {
                        // It's a value, so we create or update the state
                        createOrUpdateState(fullStateName, value, key);
                    }
                });
            }
             
            // Function to nullify file metadata states in ioBroker
            function nullifyFileMetadataStates() {
             
                var states = $(`*.${printerName}.file_metadata.*`/*Printer file metadata*/);
             
                states.each(function(id, i){
                    setState(id, {val: null, ack: true});
                });
            }
             
            // Polling function
            function startPolling() {
                setInterval(() => {
                    if (getState('sonoff.0.DVES_C38B13.POWER').val == true) getPrinterStatus(printerBaseUrl + '/printer/objects/query?display_status&print_stats&extruder&heater_bed&system_stats')
                        .then(response => {
                            if (response && response.result) {
                                
                                const printStats = response.result.status.print_stats || {};
                                const filename = printStats.filename;
                                
                                // Update printer status
                                processPrinterStatus(response.result);
             
                                // If there is a filename, get and process the file metadata
                                if (filename) {
                                    getFileMetadata(filename).then(metadataResponse => {
                                        if (metadataResponse && metadataResponse.result) {
                                            processPrinterStatus(metadataResponse.result, 'file_metadata');
                                        }
                                    }).catch(error => {
                                        console.error('Error fetching file metadata:', error);
                                    });
                                } else {
                                    // If filename is empty, nullify all file_metadata states
                                    nullifyFileMetadataStates();
                                }
                                
                                updatePrinterOnlineStatus(true); // Printer is online
                            }
                        })
                        .catch(error => {
                            console.log('Error fetching printer status... setting Printer offline');
                            updatePrinterOnlineStatus(false); // Printer is offline
                        });
                }, updateInterval);
            }
             
            // Start the polling process
            startPolling();
            
            

            Da soll das request raus.
            Hatte mit ChatGPT mein Glück versucht und den request block so ersetzt:

            // Function to make an HTTP request and return a promise
            const axios = require('axios');
            
            function getPrinterStatus(url) {
                return axios.get(url)
                    .then(response => response.data)
                    .catch(error => {
                        throw error;
                    });
            }
            

            Reicht aber anscheinend nicht...
            Was muss ich da noch umbauen?

            haus-automatisierungH Offline
            haus-automatisierungH Offline
            haus-automatisierung
            Developer Most Active
            schrieb am zuletzt editiert von
            #5

            @merlin123 Ungetestet, aber das wäre die Grundlage. Ginge auch mit httpGetAsync.

            const printerName = 'K1'; // Replace with your actual printer name
            const printerBaseUrl = 'http://192.168.0.252:7125'; // Replace with your actual moonraker ip
            const updateInterval = 20000; // 20 seconds
            
            // Function to make an HTTP request and return a promise
            async function getPrinterStatus(url) {
                return new Promise((resolve, reject) => {
                    httpGet(url, { timeout: 2000 }, (err, response) => {
                        if (err) {
                            reject(err);
                        } else {
                            resolve(JSON.parse(response.data));
                        }
                    });
                });
            }
            
            // Function to get metadata for the given filename
            async function getFileMetadata(filename) {
                return getPrinterStatus(`${printerBaseUrl}/server/files/metadata?filename=${encodeURIComponent(filename)}`); // Reusing the HTTP request function
            }
            
            // Function to convert seconds to HH:MM:SS
            function toHHMMSS(seconds) {
                const hours = Math.floor(seconds / 3600);
                const minutes = Math.floor((seconds % 3600) / 60);
                const sec = Math.floor(seconds % 60);
            
                return [hours, minutes, sec]
                    .map(v => v < 10 ? '0' + v : v)
                    .join(':');
            }
            
            // Function to update the online status of the printer
            function updatePrinterOnlineStatus(isOnline) {
                createOrUpdateState(`${printerName}.onlineStatus`, isOnline);
            }
            
            // Function to create or update ioBroker states
            function createOrUpdateState(fullStateName, value, key='') {
                // Check if the key contains 'duration' and format it if it does
                if (key.includes('duration')) {
                    value = toHHMMSS(value);
                }
             
                // Check if the key contains 'progress' and multiply by 100 and round it if it does
                if (key.includes('progress')) {
                    value = Math.round(value * 100); // Converts to percentage and rounds to the nearest integer
                }
             
                if (!existsState(fullStateName)) {
                    createState(fullStateName, {
                        type: typeof value,
                        read: true,
                        write: false,
                        desc: 'Printer status value'
                    }, () => {
                        setState(fullStateName, value, true);
                    });
                } else {
                    setState(fullStateName, value, true);
                }
            }
             
            // Function to process the printer status and update the ioBroker states
            function processPrinterStatus(printerData, parentKey = '') {
                Object.keys(printerData).forEach(key => {
                    const value = printerData[key];
                    let fullStateName = `${printerName}`;
                    if (parentKey) {
                        fullStateName += `.${parentKey}`;
                    }
                    fullStateName += `.${key}`;
             
                    if (value !== null && typeof value === 'object' && !(value instanceof Array)) {
                        // It's a nested object, so we need to recurse
                        processPrinterStatus(value, key);
                    } else {
                        // It's a value, so we create or update the state
                        createOrUpdateState(fullStateName, value, key);
                    }
                });
            }
             
            // Function to nullify file metadata states in ioBroker
            function nullifyFileMetadataStates() {
                const states = $(`*.${printerName}.file_metadata.*`);
             
                states.each((id, i) => {
                    setState(id, { val: null, ack: true });
                });
            }
             
            // Polling function
            function startPolling() {
                setInterval(() => {
                    if (getState('sonoff.0.DVES_C38B13.POWER').val) {
                        getPrinterStatus(`${printerBaseUrl}/printer/objects/query?display_status&print_stats&extruder&heater_bed&system_stats`)
                            .then(data => {
                                const printStats = data.status.print_stats || {};
                                const filename = printStats.filename;
            
                                // Update printer status
                                processPrinterStatus(data);
             
                                // If there is a filename, get and process the file metadata
                                if (filename) {
                                    getFileMetadata(filename)
                                        .then(data => {
                                            processPrinterStatus(data, 'file_metadata');
                                        }).catch(error => {
                                            console.error('Error fetching file metadata:', error);
                                        });
                                } else {
                                    // If filename is empty, nullify all file_metadata states
                                    nullifyFileMetadataStates();
                                }
            
                                updatePrinterOnlineStatus(true); // Printer is online
                            })
                            .catch(error => {
                                console.log('Error fetching printer status... setting Printer offline');
                                updatePrinterOnlineStatus(false); // Printer is offline
                            });
                    }
                }, updateInterval);
            }
            
            // Start the polling process
            startPolling();
            

            🧑‍🎓 Autor des beliebten ioBroker-Master-Kurses
            🎥 Tutorials rund um das Thema DIY-Smart-Home: https://haus-automatisierung.com/
            📚 Meine inoffizielle ioBroker Dokumentation

            Merlin123M 2 Antworten Letzte Antwort
            2
            • haus-automatisierungH haus-automatisierung

              @merlin123 Ungetestet, aber das wäre die Grundlage. Ginge auch mit httpGetAsync.

              const printerName = 'K1'; // Replace with your actual printer name
              const printerBaseUrl = 'http://192.168.0.252:7125'; // Replace with your actual moonraker ip
              const updateInterval = 20000; // 20 seconds
              
              // Function to make an HTTP request and return a promise
              async function getPrinterStatus(url) {
                  return new Promise((resolve, reject) => {
                      httpGet(url, { timeout: 2000 }, (err, response) => {
                          if (err) {
                              reject(err);
                          } else {
                              resolve(JSON.parse(response.data));
                          }
                      });
                  });
              }
              
              // Function to get metadata for the given filename
              async function getFileMetadata(filename) {
                  return getPrinterStatus(`${printerBaseUrl}/server/files/metadata?filename=${encodeURIComponent(filename)}`); // Reusing the HTTP request function
              }
              
              // Function to convert seconds to HH:MM:SS
              function toHHMMSS(seconds) {
                  const hours = Math.floor(seconds / 3600);
                  const minutes = Math.floor((seconds % 3600) / 60);
                  const sec = Math.floor(seconds % 60);
              
                  return [hours, minutes, sec]
                      .map(v => v < 10 ? '0' + v : v)
                      .join(':');
              }
              
              // Function to update the online status of the printer
              function updatePrinterOnlineStatus(isOnline) {
                  createOrUpdateState(`${printerName}.onlineStatus`, isOnline);
              }
              
              // Function to create or update ioBroker states
              function createOrUpdateState(fullStateName, value, key='') {
                  // Check if the key contains 'duration' and format it if it does
                  if (key.includes('duration')) {
                      value = toHHMMSS(value);
                  }
               
                  // Check if the key contains 'progress' and multiply by 100 and round it if it does
                  if (key.includes('progress')) {
                      value = Math.round(value * 100); // Converts to percentage and rounds to the nearest integer
                  }
               
                  if (!existsState(fullStateName)) {
                      createState(fullStateName, {
                          type: typeof value,
                          read: true,
                          write: false,
                          desc: 'Printer status value'
                      }, () => {
                          setState(fullStateName, value, true);
                      });
                  } else {
                      setState(fullStateName, value, true);
                  }
              }
               
              // Function to process the printer status and update the ioBroker states
              function processPrinterStatus(printerData, parentKey = '') {
                  Object.keys(printerData).forEach(key => {
                      const value = printerData[key];
                      let fullStateName = `${printerName}`;
                      if (parentKey) {
                          fullStateName += `.${parentKey}`;
                      }
                      fullStateName += `.${key}`;
               
                      if (value !== null && typeof value === 'object' && !(value instanceof Array)) {
                          // It's a nested object, so we need to recurse
                          processPrinterStatus(value, key);
                      } else {
                          // It's a value, so we create or update the state
                          createOrUpdateState(fullStateName, value, key);
                      }
                  });
              }
               
              // Function to nullify file metadata states in ioBroker
              function nullifyFileMetadataStates() {
                  const states = $(`*.${printerName}.file_metadata.*`);
               
                  states.each((id, i) => {
                      setState(id, { val: null, ack: true });
                  });
              }
               
              // Polling function
              function startPolling() {
                  setInterval(() => {
                      if (getState('sonoff.0.DVES_C38B13.POWER').val) {
                          getPrinterStatus(`${printerBaseUrl}/printer/objects/query?display_status&print_stats&extruder&heater_bed&system_stats`)
                              .then(data => {
                                  const printStats = data.status.print_stats || {};
                                  const filename = printStats.filename;
              
                                  // Update printer status
                                  processPrinterStatus(data);
               
                                  // If there is a filename, get and process the file metadata
                                  if (filename) {
                                      getFileMetadata(filename)
                                          .then(data => {
                                              processPrinterStatus(data, 'file_metadata');
                                          }).catch(error => {
                                              console.error('Error fetching file metadata:', error);
                                          });
                                  } else {
                                      // If filename is empty, nullify all file_metadata states
                                      nullifyFileMetadataStates();
                                  }
              
                                  updatePrinterOnlineStatus(true); // Printer is online
                              })
                              .catch(error => {
                                  console.log('Error fetching printer status... setting Printer offline');
                                  updatePrinterOnlineStatus(false); // Printer is offline
                              });
                      }
                  }, updateInterval);
              }
              
              // Start the polling process
              startPolling();
              
              Merlin123M Offline
              Merlin123M Offline
              Merlin123
              schrieb am zuletzt editiert von
              #6

              @haus-automatisierung Dank Dir! Werde es testen :)

              Beta-Tester

              1 Antwort Letzte Antwort
              0
              • haus-automatisierungH haus-automatisierung

                @merlin123 Ungetestet, aber das wäre die Grundlage. Ginge auch mit httpGetAsync.

                const printerName = 'K1'; // Replace with your actual printer name
                const printerBaseUrl = 'http://192.168.0.252:7125'; // Replace with your actual moonraker ip
                const updateInterval = 20000; // 20 seconds
                
                // Function to make an HTTP request and return a promise
                async function getPrinterStatus(url) {
                    return new Promise((resolve, reject) => {
                        httpGet(url, { timeout: 2000 }, (err, response) => {
                            if (err) {
                                reject(err);
                            } else {
                                resolve(JSON.parse(response.data));
                            }
                        });
                    });
                }
                
                // Function to get metadata for the given filename
                async function getFileMetadata(filename) {
                    return getPrinterStatus(`${printerBaseUrl}/server/files/metadata?filename=${encodeURIComponent(filename)}`); // Reusing the HTTP request function
                }
                
                // Function to convert seconds to HH:MM:SS
                function toHHMMSS(seconds) {
                    const hours = Math.floor(seconds / 3600);
                    const minutes = Math.floor((seconds % 3600) / 60);
                    const sec = Math.floor(seconds % 60);
                
                    return [hours, minutes, sec]
                        .map(v => v < 10 ? '0' + v : v)
                        .join(':');
                }
                
                // Function to update the online status of the printer
                function updatePrinterOnlineStatus(isOnline) {
                    createOrUpdateState(`${printerName}.onlineStatus`, isOnline);
                }
                
                // Function to create or update ioBroker states
                function createOrUpdateState(fullStateName, value, key='') {
                    // Check if the key contains 'duration' and format it if it does
                    if (key.includes('duration')) {
                        value = toHHMMSS(value);
                    }
                 
                    // Check if the key contains 'progress' and multiply by 100 and round it if it does
                    if (key.includes('progress')) {
                        value = Math.round(value * 100); // Converts to percentage and rounds to the nearest integer
                    }
                 
                    if (!existsState(fullStateName)) {
                        createState(fullStateName, {
                            type: typeof value,
                            read: true,
                            write: false,
                            desc: 'Printer status value'
                        }, () => {
                            setState(fullStateName, value, true);
                        });
                    } else {
                        setState(fullStateName, value, true);
                    }
                }
                 
                // Function to process the printer status and update the ioBroker states
                function processPrinterStatus(printerData, parentKey = '') {
                    Object.keys(printerData).forEach(key => {
                        const value = printerData[key];
                        let fullStateName = `${printerName}`;
                        if (parentKey) {
                            fullStateName += `.${parentKey}`;
                        }
                        fullStateName += `.${key}`;
                 
                        if (value !== null && typeof value === 'object' && !(value instanceof Array)) {
                            // It's a nested object, so we need to recurse
                            processPrinterStatus(value, key);
                        } else {
                            // It's a value, so we create or update the state
                            createOrUpdateState(fullStateName, value, key);
                        }
                    });
                }
                 
                // Function to nullify file metadata states in ioBroker
                function nullifyFileMetadataStates() {
                    const states = $(`*.${printerName}.file_metadata.*`);
                 
                    states.each((id, i) => {
                        setState(id, { val: null, ack: true });
                    });
                }
                 
                // Polling function
                function startPolling() {
                    setInterval(() => {
                        if (getState('sonoff.0.DVES_C38B13.POWER').val) {
                            getPrinterStatus(`${printerBaseUrl}/printer/objects/query?display_status&print_stats&extruder&heater_bed&system_stats`)
                                .then(data => {
                                    const printStats = data.status.print_stats || {};
                                    const filename = printStats.filename;
                
                                    // Update printer status
                                    processPrinterStatus(data);
                 
                                    // If there is a filename, get and process the file metadata
                                    if (filename) {
                                        getFileMetadata(filename)
                                            .then(data => {
                                                processPrinterStatus(data, 'file_metadata');
                                            }).catch(error => {
                                                console.error('Error fetching file metadata:', error);
                                            });
                                    } else {
                                        // If filename is empty, nullify all file_metadata states
                                        nullifyFileMetadataStates();
                                    }
                
                                    updatePrinterOnlineStatus(true); // Printer is online
                                })
                                .catch(error => {
                                    console.log('Error fetching printer status... setting Printer offline');
                                    updatePrinterOnlineStatus(false); // Printer is offline
                                });
                        }
                    }, updateInterval);
                }
                
                // Start the polling process
                startPolling();
                
                Merlin123M Offline
                Merlin123M Offline
                Merlin123
                schrieb am zuletzt editiert von
                #7

                @haus-automatisierung Auf den ersten Blick sieht es gut aus. Riesigen Dank! Ich schau mir das mal in Ruhe an und versuche es zu verstehen :)

                Beta-Tester

                1 Antwort Letzte Antwort
                1

                Hey! Du scheinst an dieser Unterhaltung interessiert zu sein, hast aber noch kein Konto.

                Hast du es satt, bei jedem Besuch durch die gleichen Beiträge zu scrollen? Wenn du dich für ein Konto anmeldest, kommst du immer genau dorthin zurück, wo du zuvor warst, und kannst dich über neue Antworten benachrichtigen lassen (entweder per E-Mail oder Push-Benachrichtigung). Du kannst auch Lesezeichen speichern und Beiträge positiv bewerten, um anderen Community-Mitgliedern deine Wertschätzung zu zeigen.

                Mit deinem Input könnte dieser Beitrag noch besser werden 💗

                Registrieren Anmelden
                Antworten
                • In einem neuen Thema antworten
                Anmelden zum Antworten
                • Älteste zuerst
                • Neuste zuerst
                • Meiste Stimmen


                Support us

                ioBroker
                Community Adapters
                Donate

                500

                Online

                32.9k

                Benutzer

                83.0k

                Themen

                1.3m

                Beiträge
                Community
                Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen | Einwilligungseinstellungen
                ioBroker Community 2014-2025
                logo
                • Anmelden

                • Du hast noch kein Konto? Registrieren

                • Anmelden oder registrieren, um zu suchen
                • Erster Beitrag
                  Letzter Beitrag
                0
                • Home
                • Aktuell
                • Tags
                • Ungelesen 0
                • Kategorien
                • Unreplied
                • Beliebt
                • GitHub
                • Docu
                • Hilfe