2024-10-28 14:47:20 +04:00
|
|
|
from kafka import KafkaProducer, KafkaConsumer
|
|
|
|
import kafka
|
|
|
|
import socket
|
2024-10-28 19:43:13 +04:00
|
|
|
from json import dumps, loads
|
|
|
|
import time
|
2024-10-29 17:31:47 +04:00
|
|
|
from enum import Enum
|
2024-10-28 14:47:20 +04:00
|
|
|
|
2024-10-29 17:31:47 +04:00
|
|
|
class Status(Enum):
|
|
|
|
UNKNOWN = -1
|
|
|
|
OFF = 0
|
|
|
|
ON = 1
|
|
|
|
|
|
|
|
class Manager:
|
|
|
|
def __init__(self, id : int, moisture : float = 0, temp : float = 20, valveStatus : Status = Status.UNKNOWN, heaterStatus : Status = Status.UNKNOWN, isAutoOn : bool = False):
|
|
|
|
self.id = id
|
|
|
|
self.moisture = moisture
|
|
|
|
self.temp = temp
|
|
|
|
self.valveStatus = valveStatus
|
|
|
|
self.heaterStatus = heaterStatus
|
|
|
|
self.isAutoOn = isAutoOn
|
|
|
|
|
|
|
|
self.dataPublisher = KafkaProducer(
|
|
|
|
bootstrap_servers=['localhost:9092'],
|
2024-10-29 17:51:20 +04:00
|
|
|
client_id=f'manager{id}_producer',
|
2024-10-29 17:31:47 +04:00
|
|
|
value_serializer=lambda v: dumps(v).encode('utf-8')
|
|
|
|
)
|
|
|
|
|
|
|
|
self.detectorConsumer = KafkaConsumer(
|
|
|
|
'dataDetectors',
|
|
|
|
bootstrap_servers=['localhost:9092'],
|
|
|
|
auto_offset_reset='earliest',
|
|
|
|
enable_auto_commit=True,
|
2024-10-29 17:51:20 +04:00
|
|
|
consumer_timeout_ms = 1000,
|
2024-10-29 17:31:47 +04:00
|
|
|
group_id=f'manager{id}',
|
|
|
|
value_deserializer=lambda x: loads(x.decode('utf-8'))
|
|
|
|
)
|
|
|
|
|
|
|
|
def update(self):
|
|
|
|
for message in self.detectorConsumer:
|
|
|
|
if message.value['id'] == self.id:
|
|
|
|
print(f"Manager {self.id} received message: ")
|
|
|
|
print(message.value)
|
|
|
|
self.moisture = message.value['moisture']
|
|
|
|
self.temp = message.value['temperature']
|
2024-10-29 17:51:20 +04:00
|
|
|
print("Updating info...\n")
|
2024-10-29 17:31:47 +04:00
|
|
|
|
2024-10-29 17:51:20 +04:00
|
|
|
self.sendData()
|
|
|
|
|
|
|
|
def sendData(self):
|
|
|
|
print("sending data...")
|
|
|
|
message = {
|
|
|
|
'id': self.id,
|
|
|
|
'moisture': self.moisture,
|
|
|
|
'temp': self.temp,
|
2024-10-29 17:31:47 +04:00
|
|
|
'valveStatus': str(self.valveStatus),
|
|
|
|
'heaterStatus': str(self.heaterStatus),
|
2024-10-29 17:51:20 +04:00
|
|
|
'isAutoOn': self.isAutoOn
|
2024-10-29 17:31:47 +04:00
|
|
|
}
|
|
|
|
|
2024-10-29 17:51:20 +04:00
|
|
|
print(message)
|
|
|
|
self.dataPublisher.send('data', message)
|
2024-10-29 17:31:47 +04:00
|
|
|
|
|
|
|
manager1 = Manager(id = 1)
|
|
|
|
|
|
|
|
managers = [manager1]
|
2024-10-28 14:47:20 +04:00
|
|
|
|
2024-10-28 19:43:13 +04:00
|
|
|
while True:
|
2024-10-29 17:31:47 +04:00
|
|
|
time.sleep(1)
|
|
|
|
for manager in managers:
|
|
|
|
manager.update()
|