55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
|
|
import redis
|
|
import time
|
|
import random
|
|
import json
|
|
|
|
# Connect to Redis
|
|
# This assumes Redis is running on localhost:6379
|
|
try:
|
|
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
|
|
r.ping()
|
|
print("Successfully connected to Redis.")
|
|
except redis.exceptions.ConnectionError as e:
|
|
print(f"Could not connect to Redis: {e}")
|
|
exit(1)
|
|
|
|
# The channel to publish data to
|
|
REDIS_CHANNEL = "energy_data"
|
|
|
|
def generate_mock_data():
|
|
"""Generates a single mock data point for a random sensor."""
|
|
sensor_id = f"sensor_{random.randint(1, 10)}"
|
|
# Simulate energy consumption in kWh
|
|
energy_value = round(random.uniform(0.5, 5.0) + (random.random() * 5 * (1 if random.random() > 0.9 else 0)), 4)
|
|
|
|
return {
|
|
"sensorId": sensor_id,
|
|
"timestamp": int(time.time()),
|
|
"value": energy_value,
|
|
"unit": "kWh"
|
|
}
|
|
|
|
def main():
|
|
"""Main loop to generate and publish data."""
|
|
print(f"Starting data simulation. Publishing to Redis channel: '{REDIS_CHANNEL}'")
|
|
while True:
|
|
try:
|
|
data = generate_mock_data()
|
|
payload = json.dumps(data)
|
|
|
|
r.publish(REDIS_CHANNEL, payload)
|
|
print(f"Published: {payload}")
|
|
|
|
# Wait for a random interval before sending the next data point
|
|
time.sleep(random.uniform(1, 3))
|
|
except KeyboardInterrupt:
|
|
print("Stopping data simulation.")
|
|
break
|
|
except Exception as e:
|
|
print(f"An error occurred: {e}")
|
|
time.sleep(5)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|