Script using python

Creating a control script

Let’s modify the system so that there are two switches controlling the lamp, and also that the fan is turned on when the sensor is off. This means that the switch and sensor can’t publish directly to the same topics that the lamp and socket are listening to, we need a control script in between.

Let’s start by changing the topic of the switch. Click on the switch to see its public variables, and change the topic to “switch_1”.

Now we can duplicate the switch. This is done from the context menu of the switch in the assembly panel.

Make sure to change the position of the new switch a little bit, and change the topic to “switch_2”. Also, connect the new switch to the ports from the main socket to give it power.

The next thing we need to do is change the topic of the sensor to be “sensor”. This way we can subscribe to the “sensor” topic from our control script and switch the status of the socket (to which the fan is connected) by publishing to the “power” topic.

Now that we have all the topics configured, it’s time to create and run the control script. You can find an example script to start from below.

					import time
import paho.mqtt.client as mqtt

# Define input and output topics
inputs = {'switch_1': 'OFF', 'switch_2': 'OFF', 'sensor': 'OFF'}
outputs = {'lamp': 'OFF', 'power': 'OFF'}

def onMessage(client, userdata, message):
    # Decode value, and update the input dictionary with the new one
    inputs[message.topic] = str(message.payload.decode('utf-8'))

if __name__ == "__main__":
    # Create the MQTT client
    client = mqtt.Client('control')
    client.on_message = onMessage
    client.connect('', port=1883, keepalive=60)

    # Subscribe to all inputs
    client.subscribe([(topic, 0) for topic in inputs])

    # Endless loop
    while True:
        # ---------- Main control code goes here ----------
        # Update the outputs by looking at the new input data
        if inputs['switch_1'] != inputs['switch_2']:
            outputs['lamp'] = 'ON'
            outputs['lamp'] = 'OFF'
        if inputs['sensor'] == 'OFF':
            outputs['power'] = 'ON'
            outputs['power'] = 'OFF'

        # Publish outputs
        for out_topic, message in outputs.items():
            client.publish(out_topic, message)

        # Sleep


Before running the script you will need to have python installed, and run the following command in the terminal:

					 py -m pip install paho-mqtt

After installing paho-mqtt, you can start running the script.

Now that the script is running, start the emulation in Simumatik again. Both switches should now be controlling the lamp, and the fan should stop when the sensor detects a product.