'''
IoT-Schicht 1
- Publishd mqtt-basierte Daten (simulierter Prozess)

letzte Änderung: 16.11.2026
* Timestamp + mongoDB-TimeSeries-Collection
    ts == time.time()

Doku:
https://pypi.org/project/paho-mqtt/#description
'''

import time

import paho.mqtt.client as mqtt
import numpy as np
import json
# --------------------------------------------------------------
# Parameterblock
mq_host = "127.0.0.1"        # lokaler PC
# mq_host = "172.18.45.150"    # Labor-Server
mq_topic = "test_172"   # letzte IP-Adr-Nr

# --------------------------------------------------------------


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))


# __main__ ======================================================
client = mqtt.Client()
client.on_connect = on_connect

client.connect(mq_host, 1883, 60)

client.loop_start()

# Generieren von simulierten Daten -----------
cnt = 0
while True:
    time.sleep(1)
    cnt += 10
    # python-dict beschreibt den Daten-Block (payload)
    PL = {"ts": time.time(),     # unix-Zeit
        "cnt": cnt,
        "v1": np.random.normal(), 
        "v2":np.cos(cnt/10)*2, 
        "v3": np.cos(cnt/20)*200
        }
    # Umwandeln in ein json-Objekt
    jPL = json.dumps(PL)
    # versenden (publish)
    client.publish(topic=mq_topic, payload = jPL )
    print(PL)