File size: 2,541 Bytes
53c9876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2252a4
53c9876
 
 
 
 
 
a2252a4
 
53c9876
a2252a4
53c9876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const mqtt = require('mqtt');
require('dotenv').config({ path: '.env.local' });

const MQTT_BROKER = process.env.MQTT_BROKER || 'mqtt://broker.hivemq.com:1883';
const MQTT_TOPIC = 'sensors/water-quality';

const sensorIds = [
  // 'SENSOR_NYC_001',
  // 'SENSOR_LON_001',
  // 'SENSOR_TKY_001',
  // 'SENSOR_SYD_001',
  // 'SENSOR_PAR_001',
  // 'SENSOR_MUM_001',
  // 'SENSOR_SAO_001',
  // 'SENSOR_CAI_001',
  // 'SENSOR_SFO_001',
  'SENSOR_PUN_001'
];

function generateReading(sensorId) {
  return {
    sensorId,
    timestamp: new Date().toISOString(),
    pH: (6.8 + Math.random() * 1.5).toFixed(2),
    turbidity: (3.3+Math.random() * 1.5).toFixed(2),
    temperature: (15 + Math.random() * 15).toFixed(2),
    hardness: (467+Math.random() * 1.5).toFixed(2),
  };
}

function startSimulator() {
  console.log('🚀 Starting MQTT Sensor Simulator...');
  console.log(`📡 Broker: ${MQTT_BROKER}`);
  console.log(`📢 Topic: ${MQTT_TOPIC}`);
  
  const client = mqtt.connect(MQTT_BROKER, {
    clientId: `sensor_simulator_${Math.random().toString(16).substr(2, 8)}`,
    clean: true,
  });
  
  client.on('connect', () => {
    console.log('✓ Connected to MQTT broker\n');
    
    // Send initial readings for all sensors
    sensorIds.forEach((sensorId, index) => {
      setTimeout(() => {
        const reading = generateReading(sensorId);
        const topic = `${MQTT_TOPIC}/${sensorId}`;
        client.publish(topic, JSON.stringify(reading));
        console.log(`📤 ${sensorId}: pH=${reading.pH}, temp=${reading.temperature}°C`);
      }, index * 1000);
    });
    
    // Send random readings at random intervals
    setInterval(() => {
      const randomSensor = sensorIds[Math.floor(Math.random() * sensorIds.length)];
      const reading = generateReading(randomSensor);
      const topic = `${MQTT_TOPIC}/${randomSensor}`;
      
      client.publish(topic, JSON.stringify(reading));
      console.log(`📤 ${randomSensor}: pH=${reading.pH}, temp=${reading.temperature}°C`);
    }, 5000 + Math.random() * 2000); // Random interval between 5-15 seconds
  });
  
  client.on('error', (error) => {
    console.error('❌ MQTT error:', error);
  });
  
  client.on('offline', () => {
    console.log('⚠️  MQTT client offline');
  });
  
  client.on('reconnect', () => {
    console.log('↻ Reconnecting to MQTT broker...');
  });
  
  // Graceful shutdown
  process.on('SIGINT', () => {
    console.log('\n⚠️  Shutting down simulator...');
    client.end();
    process.exit(0);
  });
}

startSimulator();