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'],
|
|
|
|
client_id=f'manager{id}',
|
|
|
|
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,
|
|
|
|
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)
|
|
|
|
print("Updating info...\n")
|
|
|
|
self.moisture = message.value['moisture']
|
|
|
|
self.temp = message.value['temperature']
|
|
|
|
|
|
|
|
dataMessage = {
|
|
|
|
'id' : self.id,
|
|
|
|
'moisture' : self.moisture,
|
|
|
|
'temp' : self.temp,
|
|
|
|
'valveStatus': str(self.valveStatus),
|
|
|
|
'heaterStatus': str(self.heaterStatus),
|
|
|
|
'isAutoOn' : self.isAutoOn
|
|
|
|
}
|
|
|
|
|
|
|
|
self.dataPublisher.send('data', dataMessage)
|
|
|
|
|
|
|
|
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()
|