first commit
This commit is contained in:
44
collector.py
Normal file
44
collector.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import os
|
||||
import django
|
||||
import time
|
||||
from pymodbus.client import ModbusTcpClient
|
||||
|
||||
# Setup Environment Django
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
|
||||
django.setup()
|
||||
|
||||
from dashboard.models import KwhReadings
|
||||
|
||||
# Sesuaikan dengan IP ESP32 Anda
|
||||
ESP32_IP = '192.168.1.100'
|
||||
PORT = 502
|
||||
|
||||
def fetch_data():
|
||||
client = ModbusTcpClient(ESP32_IP, port=PORT)
|
||||
if client.connect():
|
||||
# Membaca 4 register dari ESP32
|
||||
result = client.read_holding_registers(address=0, count=4, slave=1)
|
||||
if not result.isError():
|
||||
v = result.registers[0] / 10.0
|
||||
i = result.registers[1] / 100.0
|
||||
p = result.registers[2] / 1000.0
|
||||
kwh = result.registers[3] / 10.0
|
||||
|
||||
KwhReadings.objects.create(
|
||||
voltage=v,
|
||||
current=i,
|
||||
active_power=p,
|
||||
total_energy=kwh
|
||||
)
|
||||
print(f"[BERHASIL SIMPAN] V: {v}V | I: {i}A | P: {p}kW | Energy: {kwh}kWh")
|
||||
else:
|
||||
print("[ERROR] Gagal membaca register Modbus")
|
||||
client.close()
|
||||
else:
|
||||
print(f"[ERROR] Tidak dapat terhubung ke ESP32 di IP: {ESP32_IP}")
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Menjalankan Modbus Collector...")
|
||||
while True:
|
||||
fetch_data()
|
||||
time.sleep(5)
|
||||
Reference in New Issue
Block a user