Commit 8871c732 authored by Holger Brand's avatar Holger Brand
Browse files

Add project files after cloning origin.

parent d755675a
*.bak
.ipynb_checkpoints/*
.spyproject/*
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A template to be used as starting point for new MQTT projects.
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.
Acknowledgements
----------------
- The MQTT part is inpired by http://www.steves-internet-guide.com
"""
import datetime
import os
import platform
import queue
import re
import sys
import threading
import time
import paho.mqtt.client as mqtt
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_id = client_name # + "_" + date_time[0] + "_" + date_time[1]
topic_command = client_id + "/Command"
topic_status = client_id + "/Status"
q = queue.Queue()
def on_log(client, userdata, level, buf):
"""Log buffer if callback is assigned."""
print("log: " + buf)
pass
def on_connect(client, userdata, flags, rc):
"""
Handle broker connected callback.
Publish all topic once.
Subscribe to desired topics.
"""
if rc == 0:
client.connected_flag = True
print("Connected OK")
publish_all(client)
subscribe_all(client)
else:
print("Bad connection, returned code =", rc)
pass
def on_disconnect(client, userdata, flags, rc=0):
"""Handle broker disconnected callback."""
# client.connected_flag = False
print("Disconnected result code =" + str(rc))
pass
def on_publish(client, userdata, mid):
"""Handle publish callback."""
# print("Client published message ID =", mid)
pass
def on_message(client, userdata, msg):
"""
Handle message received callback.
Decode received message data and insert into command processor queue.
"""
topic = msg.topic
m_decode = str(msg.payload.decode("utf-8", "ignore"))
# print("Message received. Topic:", topic, "Payload:", m_decode)
q.put((topic, m_decode))
pass
def on_subscribe(client, userdata, mid, granted_qos):
"""Handle subscribed callback."""
# print("Client subscribed message ID =", mid, "with qos =", granted_qos)
pass
def on_unsubscribe(client, userdata, mid):
"""Handle unsubscribed callback."""
# print("Client unsubscribed message ID =", mid)
pass
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)
pass
def subscribe_all(client):
"""Subscribe to all topics."""
rc, mid = client.subscribe(topic_command)
print("Subscribing to: '", topic_command, "'returned rc =", rc, "mid = ", mid)
pass
def unsubscribe_all(client):
"""Unsubscribe from all topics."""
rc, mid = client.unsubscribe(topic_command)
print("Unsubscribing to: '", topic_command, "'returned rc =", rc, "mid = ", mid)
pass
def command_processor():
"""
Implement command processing here.
Get decoded message from queue and process.
Example: Handle topic 'Command'.
"""
while True:
received = q.get()
topics = re.split("/", received[0])
data = received[1]
print("Command processing:", topics[1])
if topics[1] == "Command":
print(topics[1], data)
else:
print("Received unkown:", received[0])
print("Command processing done.")
q.task_done()
pass
def periodic_processor(client, ii):
"""Perform periodic actions."""
client.publish(topic_status, ii)
pass
if __name__ == '__main__':
print(os.path.basename(__file__), "\n\
Copyright 2021 GSI Helmholtzzentrum für Schwerionenforschung GmbH\n\
Dr. Holger Brand, EEL, Planckstraße 1, 64291 Darmstadt, Germany\n\
eMail: H.Brand@gsi.de\n\
Web: https://www.gsi.de/work/forschung/experimentelektronik/kontrollsysteme\n\
Published under EUPL.")
# Insert you main code here
try:
# client = mqtt.Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")
client = mqtt.Client(client_id, clean_session=True)
client.connected_flag = False
client.will_set(client_id, "Offline", 1, False)
# bind call back function
client.on_connect = on_connect
client.on_disconnect = on_disconnect
# client.on_log=on_log
client.on_publish = on_publish
client.on_message = on_message
client.on_subscribe = on_subscribe
client.on_unsubscribe = on_unsubscribe
print("Connecting client '", client_id, " 'to broker", broker)
# turn-on the worker thread
threading.Thread(target=command_processor, daemon=True).start()
client.loop_start()
client.connect(broker, port=1883, keepalive=60, bind_address="")
while not client.connected_flag:
print("Waiting for", broker, "...")
time.sleep(1)
time.sleep(3)
print("Waiting for exception (Ctrl+c) ...")
ii = 0
while client.connected_flag:
ii += 1
periodic_processor(client, ii)
# client.publish(topic_status, ii)
time.sleep(1)
except BaseException as e:
print("Exception catched!", e)
client.connected_flag = False
finally:
unsubscribe_all(client)
q.join()
print("Publishing: 'disconnected'")
rc, mid = client.publish(client_id, "disconnected")
print("Publishing: 'disconnected' returned rc =", rc, "mid = ", mid)
print("Disonnecting from broker", broker)
client.disconnect()
time.sleep(1)
print("Stopping message loop")
client.loop_stop(force=False)
print("Script execution stopped.")
sys.exit()
#!/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
# MQTT-Queue-Template
A template to be used as starting point for new MQTT projects.
MQTT-Queue-Template
===================
- 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.
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.
Acknowledgements: Inpired by http://www.steves-internet-guide.
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://git.gsi.de/EE-LV/Python/MQTT-Queue-Template.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://git.gsi.de/EE-LV/Python/MQTT-Queue-Template/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
Dependencies
------------
Refer to import statements.
***
Known issues
------------
- Supported data types, all converted to float:
- boolean {false/true}
- integer and
- float, only.
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
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
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
Published under EUPL V. 1.1. Refer to license files on disc.
## License
For open source projects, say how it is licensed.
Acknowledgements
----------------
- The MQTT part is inpired by http://www.steves-internet-guide.com
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
Revision History
----------------
Revision 1.0.0.0 - 13.05.2022 H.Brand@gsi.de
- Initial commit.
\ No newline at end of file
#! c:\python34\python.exe
#!/usr/bin/env python
##demo code provided by Steve Cope at www.steves-internet-guide.com
##email steve@steves-internet-guide.com
##Free to use for any purpose
"""
Demonstrates callbacks- If you set the QOS to ) you will notice that the
on_publish callback isn't triggered. It also demonstrates getting
messages into main script from the on_message callback using a queue
Question Why isn't the on_subscribe callback triggered.
Answer at bottom
"""
import paho.mqtt.client as mqtt #import the client
import time
from queue import Queue
q=Queue()
messages=[]
broker="test.mosquitto.org"
broker="192.168.1.41"
#broker="localhost"
QOS=0
QOS=1 #Set to 1 or 2 and you see on publish callback
def on_connect(client, userdata, flags, rc):
client.connected_flag=True
#messages.append(m)
#print(m)
def on_message(client, userdata, message):
#global messages
m="message received " ,str(message.payload.decode("utf-8"))
q.put(m) #put messages on queue
print("message received ",m)
def on_publish (client, userdata, mid):
print("on publish callback mid "+str(mid))
def on_subscribe(client, userdata, mid, granted_QOS):
print("on_subscribe callback mid "+str(mid))
client = mqtt.Client("P1") #create new instance
client.on_connect= on_connect #attach function to callback
client.on_message=on_message #attach function to callback
client.on_publish =on_publish #attach function to callback
#client.on_subscribe =on_subscribe #attach function to callback
time.sleep(1)
print("connecting to broker")
client.connected_flag=False
client.connect(broker) #connect to broker
print("starting the loop")
client.loop_start() #start the loop
print("subscribing QOS=",QOS)
r=client.subscribe("house/bulbs/#",QOS)
while not client.connected_flag:
print("waiting for connect")
time.sleep(0.5)
for i in range(3):
print("publishing")
m="test message number =" +str(i)
client.publish("house/bulbs/bulb1",m,QOS)
time.sleep(1)
while not q.empty():
message = q.get()
print("queue: ",message)
client.disconnect()
client.loop_stop()
"""
on_subscribe callback isn't triggered because it is missing the
assignement.client.on_Subscribe =on_Subscribe
"""
#! c:\python34\python.exe
#!/usr/bin/env python
##demo code provided by Steve Cope at www.steves-internet-guide.com
##email steve@steves-internet-guide.com
##Free to use for any purpose
"""
Try connecting to a non existant broker and see what you get
Rhe script also demonstrates generating client names using two methods
a random number and time.Notice I use a prefix
"""
broker="test.mosquitto.org"
broker="192.168.1.41"
#broker="localhost"
import paho.mqtt.client as mqtt #import the client1
import time
import random
def on_log(client, userdata, level, buf):
print("log: "+buf)
def on_connect(client, userdata, flags, rc):
if rc==0:
print("connected OK")
else:
print("Bad connection Returned code=",rc)
#edit accorfingly
cname="testclient-"+str(int(time.time()))
#r=random.randrange(1,10000)
#cname="testclient" +"-"+str(r)
client = mqtt.Client(cname)#create new instance
client.on_connect=on_connect #bind call back function
client.on_log=on_log
print("Connecting to broker ",broker)
client.connect(broker) #connect to broker
client.loop_start() #Start loop
time.sleep(4)
client.loop_stop() #Stop loop
client.disconnect() # disconnect
#! c:\python34\python.exe
#!/usr/bin/env python
##demo code provided by Steve Cope at www.steves-internet-guide.com
##email steve@steves-internet-guide.com
##Free to use for any purpose
"""
Simple publish and sbscribe. See the callback script for code to get the message from the
on_message callback into the main script. Notice I use a wildcard to subscribe so I receive message
sent on multiple topics
"""
broker="test.mosquitto.org"
broker="192.168.1.41"
#broker="localhost"
import paho.mqtt.client as mqtt #import the client1
import time
def on_log(client, userdata, level, buf):
print("log: "+buf)
def on_connect(client, userdata, flags, rc):
if rc==0:
print("connected OK")
else:
print("Bad connection Returned code=",rc)
def on_disconnect(client, userdata, flags, rc=0):
print("DisConnected result code "+str(rc))
def on_message(client,userdata,msg):
topic=msg.topic
m_decode=str(msg.payload.decode("utf-8","ignore"))
print("message received",m_decode)