Cucumber/GreenhouseDetector/detector.py

49 lines
1.4 KiB
Python
Raw Normal View History

2024-10-29 16:07:02 +04:00
from random import random
from turtledemo.penrose import start
from kafka import KafkaProducer, KafkaConsumer
import kafka
import socket
from json import dumps, loads
import time
import random as rnd
class Detector:
def __init__(self, id, moistureThresholdUpper, moistureThresholdLower, tempThresholdUpper, tempThresholdLower):
self.id = id
self.moistureThresholdUpper = moistureThresholdUpper
self.moistureThresholdLower = moistureThresholdLower
self.tempThresholdUpper = tempThresholdUpper
self.tempThresholdLower = tempThresholdLower
self.moisture = 0
self.temp = 0
self.producer = KafkaProducer(
bootstrap_servers=['localhost:9092'],
client_id=f'detector{self.id}',
value_serializer=lambda v: dumps(v).encode('utf-8')
)
def sendData(self):
message = {'id' : self.id,
'moisture': self.moisture,
'temperature' : self.temp }
2024-10-29 17:31:47 +04:00
self.producer.send('dataDetectors', message)
2024-10-29 16:07:02 +04:00
def cycle(self):
self.moisture += rnd.random() / 100
self.temp += (rnd.random() - 0.5) / 100
2024-10-29 17:31:47 +04:00
detector1 = Detector(1, 0.6, 0.2, 40, 20)
detector2 = Detector(2, 0.7, 0.3, 40, 20)
detector3 = Detector(3, 0.9, 0.6, 40, 20)
detectors = [detector1, detector2, detector3]
2024-10-29 16:07:02 +04:00
while True:
2024-10-29 17:31:47 +04:00
for detector in detectors:
detector.cycle()
detector.sendData()
2024-10-29 16:07:02 +04:00
time.sleep(1)