Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • EKS/Python/MQTT-Queue-Template
  • h.brand/MQTT-Test-Alert
2 results
Show changes
Commits on Source (3)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Read trend data from file recorded with mqtt-recorder.
Copyright 2022 GSI Helmholtzzentrum für Schwerionenforschung GmbH
Dr. Holger Brand, EEL, Planckstraße 1, 64291 Darmstadt, Germany
eMail: H.Brand@gsi.de
Web: https://www.gsi.de/work/forschung/experimentelektronik/kontrollsysteme
Published under EUPL.
"""
import datetime
import json
import matplotlib.pyplot as plt
import numpy as np
# Opening record definition JSON file
with open('Topics-bool.json',) as fObj:
topics_bool = json.load(fObj)['topics']
# print(topics_bool)
csv_data_type_bool = np.dtype(
[
('Topic', np.compat.unicode, 100),
('Payload', np.bool_),
('QoS', np.int8),
('Retain', np.int8),
('Time', np.float64),
('dt', np.float64)
]
)
csv_data_bool = np.genfromtxt("Topics-Record.csv", dtype=csv_data_type_bool, delimiter=",")
t_zero_bool = csv_data_bool['Time'][0]
with open('Topics-float64.json',) as fObj:
topics_float = json.load(fObj)['topics']
# print(topics_float)
csv_data_type_float = np.dtype(
[
('Topic', np.compat.unicode, 100),
('Payload', np.float64),
('QoS', np.int8), ('Retain', np.int8),
('Time', np.float64),
('dt', np.float64)
]
)
csv_data_float = np.genfromtxt("Topics-Record.csv", dtype=csv_data_type_float, delimiter=",")
t_zero_float = csv_data_float['Time'][0]
t_zero = min(t_zero_bool, t_zero_float)
fig = plt.figure(figsize=(10, 5))
sub1 = fig.add_subplot(2, 1, 1)
sub2 = fig.add_subplot(2, 1, 2)
sub1.set_title('MQTT Recorded Analog Data (t0=' + datetime.datetime.utcfromtimestamp(t_zero).strftime("%d.%m.%y %H:%M:%S") + ')')
sub1.set_xlabel('Time / s')
sub1.set_ylabel('Value / V')
sub2.set_title('MQTT Recorded Digital Data (t0=' + datetime.datetime.utcfromtimestamp(t_zero).strftime("%d.%m.%y %H:%M:%S") + ')')
sub2.set_xlabel('Time / s')
sub2.set_ylabel('Value')
for topic in topics_float:
# print('Topic:', topic)
data_float = csv_data_float[csv_data_float['Topic'] == topic]
data_f = data_float['Payload']
t_f = (data_float['Time'] - t_zero)
# print(t_f, data_f)
sub1.plot(t_f, data_f, label=topic)
for topic in topics_bool:
# print('Topic:', topic)
data_bool = csv_data_bool[csv_data_bool['Topic'] == topic]
data_b = data_bool['Payload']
t_b = (data_bool['Time'] - t_zero)
# print(t_b, data_b)
sub2.step(t_b, data_b, where='post', label=topic)
sub2.plot(t_b, data_b, 'o')
sub1.legend(loc='upper left')
sub2.legend(loc='upper left')
plt.tight_layout()
plt.show()
{
"topics": [
"Test/Test_AI_0",
"Test/Test_AI_1",
"Test/Test_AI_2",
"Test/Test_AI_3",
"Test/Test_AI_4",
"Test/Test_AI_5",
"Test/Test_AI_6",
"Test/Test_AI_7",
"Test/Test_DI_0",
"Test/Test_DI_1",
"Test/Test_DI_2",
"Test/Test_DI_3",
"Test/Test_DO_0",
"Test/Test_DO_1",
"Test/Test_DO_2",
"Test/Test_DO_3"
]
}
\ No newline at end of file
mqtt-recorder --host localhost --mode record --file Topics-Record.csv --topics Topics.json
\ No newline at end of file
This diff is collapsed.
{
"topics": [
"Test/Test_DI_0",
"Test/Test_DI_1",
"Test/Test_DI_2",
"Test/Test_DI_3",
"Test/Test_DO_0",
"Test/Test_DO_1",
"Test/Test_DO_2",
"Test/Test_DO_3"
]
}
\ No newline at end of file
{
"topics": [
"Test/Test_AI_2",
"Test/Test_AI_3",
"Test/Test_AI_4",
"Test/Test_AI_5",
"Test/Test_AI_6",
"Test/Test_AI_7"
]
}
\ No newline at end of file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A template to be used as starting point for new MQTT projects.
MQTT project publishing some values and monitoring alerts published by InfluxDB.
Copyright 2022 GSI Helmholtzzentrum für Schwerionenforschung GmbH
Dr. Holger Brand, EEL, Planckstraße 1, 64291 Darmstadt, Germany
......@@ -16,6 +16,7 @@ Acknowledgements
"""
import datetime
import json
import os
import platform
import queue
......@@ -25,17 +26,31 @@ import threading
import time
import paho.mqtt.client as mqtt
broker = "localhost"
broker = 'localhost'
hostname = platform.node()
client_name = hostname + "_" + re.split(".py", os.path.basename(__file__))[0]
date_time = re.split(" ", str(datetime.datetime.now()))
# client_name = hostname + '_' + re.split('.py', os.path.basename(__file__))[0]
client_name = 'TestAlert'
date_time = re.split(' ', str(datetime.datetime.now()))
client_id = client_name # + "_" + date_time[0] + "_" + date_time[1]
topic_command = client_id + "/Command"
topic_status = client_id + "/Status"
topic_command = client_id + '/Command'
topic_status = client_id + '/Status'
topic_t_single = client_id + '/TMonitor' + '/t_single'
topic_t_array = client_id + '/TMonitor' + '/t_array'
topic_t_0 = client_id + '/TMonitor' + '/t_0'
topic_t_1 = client_id + '/TMonitor' + '/t_1'
topic_t_2 = client_id + '/TMonitor' + '/t_2'
t_t = list(range(0, 101, 1))
q = queue.Queue()
def rotate(le, k):
"""Rotate list elements by k."""
return le[k:] + le[:k]
def on_log(client, userdata, level, buf):
"""Log buffer if callback is assigned."""
print("log: " + buf)
......@@ -101,10 +116,22 @@ def publish_all(client):
"""Publish all topics."""
rc, mid = client.publish(client_id, "connected")
print("Publishing: 'connected' returned rc =", rc, "mid = ", mid)
rc, mid = client.publish(topic_status, 0)
print("Publishing: '", topic_status, "' returned rc =", rc, "mid = ", mid)
rc, mid = client.publish(topic_command, "Write your command here.")
print("Publishing: '", topic_command, "' returned rc =", rc, "mid = ", mid)
rc, mid = client.publish(topic_status, 0)
print("Publishing: '", topic_status, "' returned rc =", rc, "mid = ", mid)
t_index = (len(t_t) // 2) % len(t_t)
rc, mid = client.publish(topic_t_single, t_t[t_index])
print("Publishing: '", topic_t_single, "' returned rc =", rc, "mid = ", mid)
rc, mid = client.publish(topic_t_0, t_t[t_index + 0])
print("Publishing: '", topic_t_0, "' returned rc =", rc, "mid = ", mid)
rc, mid = client.publish(topic_t_1, t_t[t_index + 1])
print("Publishing: '", topic_t_1, "' returned rc =", rc, "mid = ", mid)
rc, mid = client.publish(topic_t_2, t_t[t_index + 2])
print("Publishing: '", topic_t_2, "' returned rc =", rc, "mid = ", mid)
rc, mid = client.publish(topic_t_array, json.dumps(t_t[t_index:t_index + 3]))
print("Publishing: '", topic_t_array, "' returned rc =", rc, "mid = ", mid)
rotate(t_t, 1)
pass
......@@ -146,6 +173,13 @@ def command_processor():
def periodic_processor(client, ii):
"""Perform periodic actions."""
client.publish(topic_status, ii)
t_index = (len(t_t) // 2) % len(t_t) + ii
client.publish(topic_t_single, t_t[t_index])
client.publish(topic_t_0, t_t[t_index + 0])
client.publish(topic_t_1, t_t[t_index + 1])
client.publish(topic_t_2, t_t[t_index + 2])
client.publish(topic_t_array, json.dumps(t_t[t_index:t_index + 3]))
rotate(t_t, 1)
pass
......
MQTT-Queue-Template
MQTT-Test-Alert
===================
- MQTT-Queue-Template.py is a template to be used as starting point for new MQTT projects.
- MQTT-Recorder contains an example utilizing the MQTT-Recorder to log selected messages and plot historical data.
- MQTT project publishing some values and monitoring alerts published by InfluxDB.
- Project was derived from MQTT-Queue-Template.
Copyright 2022 GSI Helmholtzzentrum für Schwerionenforschung GmbH
Dr. Holger Brand, EEL, Planckstraße 1, 64291 Darmstadt, Germany
......@@ -16,10 +16,6 @@ Refer to import statements.
Known issues
------------
- Supported data types, all converted to float:
- boolean {false/true}
- integer and
- float, only.
Copyright 2022 GSI Helmholtzzentrum für Schwerionenforschung GmbH
Dr. Holger Brand, EEL, Planckstraße 1, 64291 Darmstadt, Germany
......@@ -34,5 +30,5 @@ Acknowledgements
Revision History
----------------
Revision 1.0.0.0 - 13.05.2022 H.Brand@gsi.de
- Initial commit.
\ No newline at end of file
Revision 1.0.0.0 - 09.06.2022 H.Brand@gsi.de
- Forked from https://git.gsi.de/EE-LV/Python/MQTT-Queue-Template.
\ No newline at end of file
%% Cell type:code id:3eeeb84b-0713-44a3-bc74-2dd761b57d71 tags:
``` python
import paho.mqtt.publish as publish
publish.single("testtopic/single", "Huhu", hostname="localhost")
```
%% Cell type:code id:776d79ac-c4a1-43f9-ae24-c28b6ca8db62 tags:
``` python
msgs = [{'topic':"testtopic/multiple 1", 'payload':"multiple 1"},
("testtopic/multiple 2", "multiple 2", 0, False)]
publish.multiple(msgs, hostname="BNT-Raspi")
```
%% Cell type:code id:915f1622-af45-4aec-aeff-f751bfe7853b tags:
``` python
import paho.mqtt.subscribe as subscribe
msg = subscribe.simple("testtopic/single", hostname="BNT-Raspi")
print("%s %s" % (msg.topic, msg.payload))
```
%% Cell type:code id:0211aa4b-68c7-46ad-8c2d-c52bdaeef48c tags:
``` python
import paho.mqtt.client as mqtt
client_name="HB-Test"
host_name="BNT-Raspi"
client =mqtt.Client(client_name)
client.connect(host_name)
client.publish("house/light","OFF")
```
%% Cell type:code id:b9d0f17f-c225-4d77-aacb-fc85c9c3c047 tags:
``` python
import paho.mqtt.client as mqtt #import the client1
import time
############
def on_message(client, userdata, message):
print("message received " ,str(message.payload.decode("utf-8")))
print("message topic=",message.topic)
print("message qos=",message.qos)
print("message retain flag=",message.retain)
########################################
broker_address="localhost"
#broker_address="iot.eclipse.org"
print("creating new instance")
client = mqtt.Client("P1") #create new instance
client.on_message=on_message #attach function to callback
print("connecting to broker")
client.connect(broker_address) #connect to broker
client.loop_start() #start the loop
print("Subscribing to topic","+/PollingTime")
client.subscribe("+/PollingTime")
#print("Publishing message to topic","house/bulbs/bulb1")
#client.publish("house/bulbs/bulb1","OFF")
time.sleep(60) # wait
client.loop_stop() #stop the loop
print("Program stopped.")
```
%% Output
creating new instance
connecting to broker
Subscribing to topic +/PollingTime
message received 2.234
message topic= Test/PollingTime
message qos= 0
message retain flag= 0
message received 3.234
message topic= Test/PollingTime
message qos= 0
message retain flag= 0
Program stopped.
%% Cell type:code id:df2e1182-d52c-43f9-b45d-87ea38ec7c65 tags:
``` python
```