MQTT for Multiplayer Games? I am not a Game-Developer and I do not know how they create multiplayer internet games. But I know that MQTT can be used for that. Why?
# IoT turns to IoP
MQTT is used for connecting devices. Think about using MQTT for connecting players. “Internet of Things” (IoT) will turn to „Internet of Players“ (IoP).
# A Player is like a Device?
In a multiplayer game, each player is like a device. When they join the game, it’s like they’re saying “Hello, I’m here!” to everyone else – this is known as a “birth message” in MQTT terms.
# Sharing Information Seamlessly
As players move around in the game, they keep sending updates like their location, healthy state, collected goodies, …. MQTT acts like a messenger, picking up this information and delivering it to everyone else playing.
# Handling Player Exits
What if a player leaves the game intentionally or unintentionally? MQTT has a smart feature called “last will message.” It’s like a goodbye note that tells other players someone has left the game. This way, everyone stays in the loop.
# Central Management
A central game management connected to the central MQTT broker, written in any kind of language, could be used to observe and control the game and all the players.
# Why MQTT?
1. **Real-Time Updates**: It’s fast and perfect for real-time games.
2. **Reliable**: Even if a player’s connection is shaky, MQTT makes sure messages get through.
3. **Efficient**: It doesn’t eat up much data, so players won’t lag.
4. **Simple**: It’s not complicated to set up and to use.
# Conclusion
Using MQTT in multiplayer games is like having a super-efficient mailman who ensures everyone knows what’s happening as it happens.
For Unity there is a „Unity for MQTT“ and a “GraphQL for Unity Pro” asset. Easy to use and usable with all the main build targets, including WebGL!
See the game demo I made with MQTT.. I also integrated data from WinCC Unified in the demo, with the GraphQL for Unity Pro Asset.
If you are getting errors like “Missing JToken” with the GraphQL for Unity (Pro) Asset, then open the package manager and choose “add from git url” and give this url: com.unity.nuget.newtonsoft-json
With WinCC Unified V19 we got the feature to read history values of logged tags with GraphQL 👍 I have now added this functionality to the GraphQL for Unity Pro Asset 🤝
🎥 With that done it is now also very easy to read the history of logged tags in Unity3D. See the video, there we read and visualize the history values of a tag when the application starts. And then the 3D chart gets updated with real-time values coming from a GraphQL tag subscription.
ℹ️ The GraphQL for Unity Pro Asset has a WinCC Unified interface on top of GraphQL to make the access to WinCC Unified data in Unity even more easier, you do not need to implement the GraphQL queries by your own.
👉 You can try the demo in the browser! This is possible because the asset als supports WebGL builds and because GraphQL is transported over HTTP&Websockets. Here it is. But it might happen that this link will not work anymore when you read this post.
Note: Use the PWA WebGL Template so that the application adjusts to the size of your browser window. Or adjust the settings in the generated index.html page:
In this tutorial, I will guide you through the essential steps to set up the Automation Gateway, harness the power of YAML extensions in Visual Studio Code for configuration, and connect various devices, including OPC UA, MQTT, and PLC4X devices. I will show how to integrate the values from the devices to the Gateway’s OPC UA server and how to use the MQTT interface to get the values from the devices via a MQTT client. Additionally values from the connected devices will be logged to a Influx database.
I wanted to get my Home-Automation values to SCADA, it’s a “self-made” JSON message format. I tried it with Ignition and the MQTT Module. Btw.: it’s great that they have the Makers Edition for non-commercial use at home 👍. But I don’t know why, it only got one topic and one value from my MQTT Broker, and it did not receive any updates. Don’t know what went wrong…
Anyhow, I decided to add a custom JSON format to the Automation-Gateway.com. It’s simple, just define the JSON-Path to the value and optionally to a timestamp in milliseconds since epoch or to an ISO 8601 format.
Now I can use the Automation-Gateway’s OPC UA server in any SCADA system to visualize my MQTT values…
Here is the config.yaml configuration file for the Automation-Gateway.
🤔 I thought about if it could make sense to connect to a MQTT broker and write the topic-path in a structured and connected way to a graph database. It could reflect a companies UNS with ISA structure in a graph with query possibilities.
🤝 The UNS could be enriched by adding additional meta information to the database and be linked to the MQTT nodes. Graph queries could be used to combine the enriched data with the current values of the machines…
👉 I reactivated the Neo4J Logger in the Automation-Gateway.com, and enabled MQTT for it. It creates the nodes in a neo4j graph database based on the incoming MQTT messages.
“MQTT for Unity” is a Unity Package designed to seamlessly integrate MQTT (Message Queuing Telemetry Transport) functionality into Unity projects, offering a user-friendly solution for enabling real-time communication and data exchange within Unity applications.
Tested on Windows, OSX, WebGL, UWP + HoloLens2, and Android. iOS not tested, but should work as well.
Streamlined Integration: “MQTT for Unity” provides a straightforward and hassle-free integration process, enabling developers to quickly set up MQTT communication in their Unity projects.
Real-Time Communication: Harness the power of MQTT to establish real-time communication channels within your Unity application, perfect for multiplayer games, IoT applications, and more.
Customizable Configuration: Easily configure MQTT parameters, such as broker settings, topic subscriptions, and message handling, to tailor the communication to your specific project needs.
Cross-Platform Compatibility: “MQTT for Unity” is designed to work seamlessly across various Unity-supported platforms, including Windows, OSX, WebGL, UWP + HoloLens2, and Android. iOS not tested, but should work as well.
With “MQTT for Unity,” developers can unlock the potential of MQTT communication in their Unity applications without the complexities of manual integration, making it an essential tool for creating interactive and connected experiences in Unity.
The integration of SCADA with Spark and WinCC Open Architecture offers a powerful and versatile solution that combines real-time data processing, advanced analytics, scalability, and flexibility. This combination empowers you to optimize industrial processes, make data-driven decisions, and stay ahead in a rapidly evolving technological landscape.
By utilizing my 5-year-old project that implemented a native Java manager for WinCC Open Architecture, I have enabled the integration of SCADA with Spark for the current WinCC OA Version 3.19.
Very simple example is to analyze tags and the corresponding amount of values in your SCADA system can provide valuable insights into the distribution and characteristics of the data.
res = spark.sql('SELECT tag, count(*) count FROM events GROUP BY tag ORDER by count(*) DESC')
data = res.toPandas()
plt.figure( figsize = ( 10, 6 ) )
sns.barplot( x="count", y="tag", data=data)
plt.show()
Another simple example is to calculate the moving average of 10 preceding and following values for a given data point in a time series, you can use a sliding window approach:
data = spark.sql("""
SELECT ROUND(value,2) as value,
AVG(value) OVER (PARTITION BY tag ORDER BY ts
ROWS BETWEEN 10 PRECEDING AND 10 FOLLOWING) avg
FROM events
WHERE tag = 'System1:ExampleDP_Trend2.'
ORDER BY ts DESC
LIMIT 100
""").toPandas()
data = data.reset_index().rename(columns={"index": "nr"})
sns.lineplot(data=data, x='nr', y='value', label='Value')
sns.lineplot(data=data, x='nr', y='avg', label='Average')
plt.show()
By leveraging the distributed file system, you can take advantage of Spark’s parallel processing capabilities. The distributed file system ensures that the data frame is partitioned and distributed across the nodes of the Spark cluster, enabling simultaneous processing of data in parallel. This distributed approach enhances performance and scalability, allowing for efficient handling of large volumes of real-time SCADA data.
I have achieved real-time data streaming from WinCC OA to a Spark cluster with a Websocket-Server based on the Java manager. This streaming process involves continuouslytransferring SCADA real-time data from the WinCC OA system to the Spark cluster for further processing and analysis.
Once the data is received by the Spark cluster, I store it as a data frame on the distributed file system (DFS). A data frame is a distributed collection of data organized into named columns, similar to a table in a relational database. Storing the data frame on the distributed file system ensures data persistence and allows for efficient processing and retrieval.
bulk = []
last = datetime.datetime.now()
def on_message(message):
global bulk, last, start
data = json.loads(message)
if "DpQueryConnectResult" in data:
values = data["DpQueryConnectResult"]["Values"]
for tag, value in values:
#print(tag, value)
data = {"ts": datetime.datetime.now(), "tag": tag, "value": value}
bulk.append(data)
now =datetime.datetime.now()
time = datetime.datetime.now() - last
if time.total_seconds() > 10 or len(bulk) >= 1000:
last = now
# Create a new DataFrame with the received data
new_df = spark.createDataFrame(bulk, schema)
new_df.write \
.format("csv") \
.option("header", "true") \
.mode("append") \
.save("events.csv")
bulk = []
Once the SCADA data is stored as a distributed data frame on the Spark cluster’s distributed file system, you can leverage Spark’s parallel processing capabilities to efficiently process the data in parallel.
By combining SCADA (Supervisory Control and Data Acquisition) with Spark’s powerful data processing capabilities, I have created a solution that can handle large volumes of real-time data efficiently. This enables faster and more accurate decision-making based on the insights derived from the processed data.
How to access relational databases in WinCC Unified? 👀 👉 Last night I developed a GraphQL Custom Web Control … 🌟 With that and Hasura it is possible to read and write relational data. 👉 Sources are here … not yet well documented 😎 …
Did a test with one gateway and collected 250000 😲 value changes per second(!) from 10 OPC UA servers and wrote it to 10 topics on a single Kafka Broker… Kafka was bored 😴… one and a half core of an i7 PC. The gateway had a lot of work to do, collect and bulk all the single values and then send it to Kafka … roughly 10 cores of an i7 PC.
The gateway has a GraphQL and MQTT interface where you can read and write OPC UA values. On an internal MQTT topic the logger publishes how many values are getting in and out…