How do you feel about this article? Help us to provide better content for you.
Thank you! Your feedback has been received.
There was a problem submitting your feedback, please try again later.
What do you think of this article?
This project turns the air quality data of the AQ sensor kit into an experience of light and sound, with Part I providing an introductory overview, now the next step was to transport the data stream into PURE DATA and also to trigger sounds based on the input.
Using the MQTT Broker
As the original client provides MQTT data, the least invasive approach was to just use the existing MQTT server. In order to get the air quality data, the client just has to subscribe to the data stream. The only problem is that PURE DATA does not allow using MQTT and only can provide a TCP server which allows to receive and send data. So how can this be hooked up?
Providing an interface in PURE DATA
In order to exchange data with other components or programs, PURE DATA provides a netreceive object, which in this case listens on TCP port 3000 for messages. Whenever a message arrives, it is transferred to the node on the bottom left. In the object below, the incoming data is parsed and from there sent to the nodes called temp, hum, etc. From there the data can be used in the pure data sound patch. The nodes with a preceding "s" are send nodes, nodes with a preceding "r" are receive nodes. In order to debug messages, the "r tcpSend" node on the top is created, which could be tested with the textbox above the "s tcpSend" node. Debugging is easy that way.
PYTHON to the rescue
Using Python, it is easy to translate the incoming MQTT data and communicate with the socket provided by PURE DATA. A small python program will do. Whenever a message is received, it is parsed and sent to the socket provided by PURE DATA.
The code to parse the incoming MQTT data is pretty simple:
def onMsg(client, data, msg):
global socketConnected
if(not socketConnected):
return
data = json.loads(msg.payload.decode("utf-8"))
try:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((addr,port))
if("thv" in data):
s.send(("temp "+str(data["thv"]["temperature"])+";").encode())
s.send(("hum "+str(data["thv"]["humidity"])+";").encode())
if("co2" in data):
s.send(("co "+str(data["co2"]["co2"])+";").encode())
if("pm" in data):
s.send(("pOne "+str(data["pm"]["pm1.0"])+";").encode())
s.send(("pTwo "+str(data["pm"]["pm2.5"])+";").encode())
s.send(("pThree "+str(data["pm"]["pm4.0"])+";").encode())
except socket.error:
s = None
socketConnected = False
except:
pass
Tested - and yes, it works. PURE DATA receives the data which is provided by the air quality kit. The next step is to create a patch in PURE DATA in order to experiment with the sounds.