MQTT Visualisierte Steuerung Sensor

Aus Xinux Wiki
Zur Navigation springen Zur Suche springen

Voraussetzungen

Neues Verzeichnis für den Steuerungsserver erstellen

  • mkdir /usr/local/control-switch
  • cd /usr/local/control-switch

Initialisiere das Node.js-Projekt

  • npm init -y

Installiere die benötigten Pakete

  • npm install mqtt express

Konfiguration des Steuerungsservers

Erstelle die Datei switch-server.js im Verzeichnis /usr/local/control-switch mit folgendem Inhalt:


const mqtt = require('mqtt');
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;

let status = {
  livingRoom: 'off',
  bedroom: 'off',
  kitchen: 'off',
  frontDoor: 'closed'
};

// MQTT connection options (without TLS for unencrypted communication)
const options = {
  port: 1883,
  host: 'mqtt.dkbi.int'
};

const client = mqtt.connect(options);

client.on('connect', () => {
  console.log('Connected to the MQTT broker');
  client.subscribe('home/+/status', (err) => {
    if (!err) {
      console.log('Subscribed to all topics');
    }
  });
});

client.on('message', (topic, message) => {
  const room = topic.split('/')[1];
  status[room] = message.toString();
  console.log(`Status of ${room}: ${status[room]}`);
});

// Route to get the status of the lights and front door
app.get('/status', (req, res) => {
  res.send(status);
});

// Route to toggle a device
app.post('/toggle/:device', (req, res) => {
  const device = req.params.device;
  const currentStatus = status[device];

  if (!currentStatus) {
    res.status(400).send({ error: 'Invalid device' });
    return;
  }

  // Toggle the status (for front door: closed/open)
  let newStatus;
  if (device === 'frontDoor') {
    newStatus = currentStatus === 'closed' ? 'open' : 'closed';
  } else {
    newStatus = currentStatus === 'on' ? 'off' : 'on';
  }
  status[device] = newStatus;

  // Send MQTT message
  const topic = `home/${device}/status`;
  client.publish(topic, newStatus, (err) => {
    if (err) {
      console.log(`Error sending message to ${device}: ${err.message}`);
      res.status(500).send({ success: false, message: 'Error sending message' });
    } else {
      console.log(`Message sent: ${device} is now ${newStatus}`);
      res.send({ success: true, message: `Device ${device} successfully toggled` });
    }
  });
});

// Serve the static directory for the web interface
app.use(express.static(path.join(__dirname)));

// Start the web server
app.listen(port, () => {
  console.log(`Control Center is running at http://localhost:${port}`);
});


Die HTML Datei index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Control Center</title>
  <style>
    .device {
      margin: 20px;
      padding: 10px;
      border-radius: 10px;
      text-align: center;
      font-size: 1.5em;
      cursor: pointer;
    }
    .on {
      background-color: yellow;
      color: black;
    }
    .off {
      background-color: gray;
      color: white;
    }
    .open {
      background-color: red;
      color: white;
    }
    .closed {
      background-color: gray;
      color: white;
    }
  </style>
  <script>
    // Fetch and display the status of devices
    function fetchStatus() {
      fetch('/status')
        .then(response => response.json())
        .then(data => {
          // Update the class and text for each device
          document.getElementById('livingRoom').className = 'device ' + (data.livingRoom === 'on' ? 'on' : 'off');
          document.getElementById('livingRoom').textContent = 'Living Room Light: ' + (data.livingRoom === 'on' ? 'On' : 'Off');

          document.getElementById('bedroom').className = 'device ' + (data.bedroom === 'on' ? 'on' : 'off');
          document.getElementById('bedroom').textContent = 'Bedroom Light: ' + (data.bedroom === 'on' ? 'On' : 'Off');

          document.getElementById('kitchen').className = 'device ' + (data.kitchen === 'on' ? 'on' : 'off');
          document.getElementById('kitchen').textContent = 'Kitchen Light: ' + (data.kitchen === 'on' ? 'On' : 'Off');

          document.getElementById('frontDoor').className = 'device ' + (data.frontDoor === 'open' ? 'open' : 'closed');
          document.getElementById('frontDoor').textContent = 'Front Door: ' + (data.frontDoor === 'open' ? 'Open' : 'Closed');
        });
    }

    // Toggle a device and update its status
    function toggleDevice(device) {
      fetch(`/toggle/${device}`, { method: 'POST' })
        .then(fetchStatus);
    }

    // Fetch status every second
    setInterval(fetchStatus, 1000);
  </script>
</head>
<body>
  <h1>Control Center</h1>
  <div id="livingRoom" class="device off" onclick="toggleDevice('livingRoom')">Living Room Light: Off</div>
  <div id="bedroom" class="device off" onclick="toggleDevice('bedroom')">Bedroom Light: Off</div>
  <div id="kitchen" class="device off" onclick="toggleDevice('kitchen')">Kitchen Light: Off</div>
  <div id="frontDoor" class="device closed" onclick="toggleDevice('frontDoor')">Front Door: Closed</div>
</body>
</html>



systemd-Unit für den Steuerungsserver erstellen

Erstelle die Datei /etc/systemd/system/control-switch.service mit folgendem Inhalt:

[Unit]
Description=Home Control Switch Server

[Service]
Type=simple
WorkingDirectory=/usr/local/control-switch
ExecStart=/usr/bin/node server.js
ExecStartPost=/bin/echo "Schalt-Server gestartet"

[Install]
WantedBy=multi-user.target

Steuerungsserver starten und beim Booten aktivieren

  • systemctl start control-switch.service
  • systemctl enable control-switch.service