Tyzen9 Solutions

SimHub MQTT

A brief explanation on how to prepare SimHub with SHWotever's MQTT Publisher

Overview

Having MQTT data published by SimHub can be a very powerful tool for people like me that leverage Home Assistant for in home automation. And this can be useful when racing to control the lighting environment and notifying others with indicators as to how much longer your current race will last, and if you should not be disturbed.

Thankfully, SHWotever has provided a SimHub MQTT plugin they will provide everything you need. However, getting this plugin up and running is not very clear and I hope to demystify that here.

The SHWotever SimHub MQTT plugin must be compiled before it can be used as a SimHub plugin.

You might not need to compile this...

Simen Asphaug has created an incredible fork of the SimHub MQTT plugin called SimHub-MQTT-Publisher. This has .dll's already compiled and provides some simple configuration out of the box that can save you some time and headaches.

That said, you will still need to configure Home Assistant to consume to JSON sent via MQTT. You can find some hints on this at the bottom of this guide.

Compiling Prerequisites

So if you still want compile a version from source for yourself, this is what you will need to do to get started.

1. Install VSCode (accepting the defaults is fine)

2. Install the Build Tools for Visual Studio (recommended, no full IDE)

At the time of writing, this was located near the bottom of the Microsoft page under the "Tools For Visual Studio" section

simhub_msbuildtools.png

3. Run this command in Powershell to set the MSBuild.exe path (verify the installation path and adjust this command as needed)

[System.Environment]::SetEnvironmentVariable("PATH", "$env:PATH;C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\MSBuild\Current\Bin", "User")
C:\workspace>msbuild -version
MSBuild version 18.5.4+cb4e32d21 for .NET Framework
18.5.4.18101

4. Validate your NuGet.config

<?xml version="1.0"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
</configuration>

5. Install the latest version of SimHub (accepting the defaults is fine)

If you have not already, please consider purchasing a license. It is not very expensive, and it will help support this AMAZING sim racing add-on.

6. Run this command in powershell to set the SimHub install path (verify the installation path and adjust this command as needed)

[System.Environment]::SetEnvironmentVariable("SIMHUB_INSTALL_PATH", "C:\Program Files (x86)\SimHub\", "User")

7. Install Git for Windows (accepting the defaults is fine)

8. Clone the SHWotever SimHub MQTT plugin repository

git clone https://github.com/SHWotever/SimHub-MQTT-Publisher.git

Let's Get to Building

Now that you have all the prerequisites installed, lets get to the build process. This will build the SimHub MQTT plugin and load it into the SimHub on the machine you are building on.

1. Stop SimHub by right-clicking on the tray icon, and clicking Exit SimHub

2. Open a new VSCode window

3. Click on the SimHubMQTTPublisher.sln file.

4. Open a new Terminal

5. Compile the Solution

msbuild SimHub.MQTTPublisher.sln /t:restore
msbuild SimHub.MQTTPublisher.sln /p:Configuration=Release

Did it Work?

When you open SimHub, you should be greeted with a screen indicating that the new MQTT plugin has been found:

simhub_mqtt_plugin.png

Configure the Plugin

Click Additional Plugins on the left, and enter the connection information for your MQTT server.

simhub_mqtt_settings.png

Do not enter a port number in the MQTT Server field, this plug-in assumes you are using port 1883

If this is not your sim racing PC, then you need to copy the compiled files to the SimHub running on that system. You can find MQTTnet.dll and SimHub.MQTTPublisher.dll in the bin\release directory in Visual Studio, or in the directory where you cloned SimHub MQTT plugin. Restart that SimHub instance and you should see the plug-in detection popup.

Look for MQTT traffic

Next, lets make sure that the MQTT traffic is making it to your MQTT server. The easiest way to do this is with MQTT Explorer

1. Install MQTT Explorer

2. Configure MQTT Explorer

mqtt_explorer_config.png

3. Check for SimHub MQTT messages

mqtt_explorer_simhub.png

Congratulations, if you made it to this point the SimHub MQTT plugin is working as expected!

Custom Data

OK, you have MQTT working, but how do you customize the data that is being sent? For me I want to know when there is an active session, laps remaining, the type of active session, and surprisingly by default these are not being sent. Back in MQTT Explorer (above) you can have a look at the values to see what is being sent by default:

{
  "time": 1778184170285,
  "userId": "55f4a41a-0f78-4e37-b385-9db792aa5826",
  "carState": {
    "SpeedKmh": 0,
    "Rpms": 300,
    "Brake": 100,
    "Throttle": 0,
    "Clutch": 100,
    "Gear": "N",
    "CarCoordinates": [
      0,
      0,
      0
    ],
    "CurrentLapTime": 0,
    "CarModel": "Mazda MX-5 Cup",
    "CarClass": "",
    "EngineIgnitionOn": true,
    "EngineStarted": true
  },
  "flagData": {
    "Flag_Name": "",
    "Flag_Black": 0,
    "Flag_Blue": 0,
    "Flag_Checkered": 0,
    "Flag_Yellow": 0,
    "Flag_Green": 0,
    "Flag_White": 0,
    "Flag_Orange": 0
  }
}

Back in SimHum, click on Available Properties, this will list all the available data points that can be sent via MQTT.
Back in Visual Studio, the payload in configured in the Payload folder, let's try and make some changes.

  1. Create a new SessionInformation.cs object in the Payload folder
using GameReaderCommon;

namespace SimHub.MQTTPublisher.Payload
{
    public class SessionInformation
    {
        public SessionInformation(GameData data)
        {
            this.CompletedLaps = data.NewData.CompletedLaps;
            this.RemainingLaps = data.NewData.RemainingLaps;
            this.TotalLaps = data.NewData.TotalLaps;
        }

        public int CompletedLaps { get; set; }
        public double RemainingLaps { get; set; }
        public int TotalLaps { get; set; }
    }
}
  1. Added sessionInfo to the PayloadRoot object in PayloadRoot.cs
       public PayloadRoot(GameData data, SimHubMQTTPublisherPluginUserSettings userSettings)
        {
            time = DateTimeOffset.Now.ToUnixTimeMilliseconds();
            carState = new Car(data);
            userId = userSettings.UserId.ToString();
            flagData = new FlagInformation(data);
            sessionInfo = new SessionInformation(data);
        }
  1. Edit the project file to include these new SessionInformation object
    <Compile Include="Payload\Car.cs" />
    <Compile Include="Payload\SessionInformation.cs" />
  1. Lets recompile
msbuild SimHub.MQTTPublisher.sln /t:"restore;Build" /p:Configuration=Release

  1. Test the changes
{
  "time": 1778185827059,
  "userId": "55f4a41a-0f78-4e37-b385-9db792aa5826",
  "carState": {
    "SpeedKmh": 0,
    "Rpms": 300,
    "Brake": 100,
    "Throttle": 0,
    "Clutch": 100,
    "Gear": "N",
    "CarCoordinates": [
      0,
      0,
      0
    ],
    "CurrentLapTime": 0,
    "CarModel": "Mazda MX-5 Cup",
    "CarClass": "",
    "EngineIgnitionOn": true,
    "EngineStarted": true
  },
  "flagData": {
    "Flag_Name": "",
    "Flag_Black": 0,
    "Flag_Blue": 0,
    "Flag_Checkered": 0,
    "Flag_Yellow": 0,
    "Flag_Green": 0,
    "Flag_White": 0,
    "Flag_Orange": 0
  },
  "sessionInfo": {
    "CompletedLaps": 0,
    "RemainingLaps": 0,
    "TotalLaps": 0
  }
}

Check it out!! We see our new SessionInfo in the JSON

Home Assistant

This assumes you are seeing the JSON sent to your MQTT server connected to Home Assistant.

Ok, the hard part is done. Either you have built your own version of the SimHub MQTT Plugin, or you are using the Simen Asphaug's SimHub-MQTT-Publisher - both are sending JSON on MQTT to Home Assistant.

Next all you need to do is add some mqtt: sensors to your configuration.yaml. Below is an subset of the sensors that I have created:

mqtt:
  sensor:
    # -------------------------------------------------------------------------
    # Car State
    # -------------------------------------------------------------------------
    - name: "SimHub Speed"
      unique_id: simhub_speed
      state_topic: "simhub"
      expire_after: 5
      value_template: "{{ value_json.carState.SpeedMph }}"
      unit_of_measurement: "mph"
      icon: mdi:speedometer

    - name: "SimHub RPM"
      unique_id: simhub_rpm
      state_topic: "simhub"
      expire_after: 5
      value_template: "{{ value_json.carState.Rpms }}"
      unit_of_measurement: "rpm"
      icon: mdi:gauge

    - name: "SimHub Brake"
      unique_id: simhub_brake
      state_topic: "simhub"
      expire_after: 5
      value_template: "{{ value_json.carState.Brake }}"
      unit_of_measurement: "%"
      icon: mdi:car-brake-alert

    - name: "SimHub Throttle"
      unique_id: simhub_throttle
      state_topic: "simhub"
      expire_after: 5
      value_template: "{{ value_json.carState.Throttle }}"
      unit_of_measurement: "%"
      icon: mdi:gauge

    - name: "SimHub Clutch"
      unique_id: simhub_clutch
      state_topic: "simhub"
      expire_after: 5
      value_template: "{{ value_json.carState.Clutch }}"
      unit_of_measurement: "%"
      icon: mdi:car-cog

I am using expire after: 5 so that these sensors become unavailable after 5 seconds of not receiving new MQTT messages. This is how I know that there is no current racing taking place

Once these have been added to your configuration.yaml in Home Assistant, restart your Home Assistance instance. After the restart is complete, and there are no errors, navigate to Dev tools -> State and you can look for your new simhub sensors:

ha_states_simhib.png

Finally, here is a simple automation that turns some lights off when a race is taking place:

automation:
  # ---------------------------------------------------------------------------
  # When SimHub starts publishing (player name becomes available), turn off
  # lights and switches for the sim racing environment
  # ---------------------------------------------------------------------------
  - alias: SimHub - Sim Session Started
    id: simhub_sim_session_started
    description: "When SimHub begins publishing, turn off lights and switches."
    mode: single
    triggers:
      - trigger: state
        entity_id: sensor.simhub_player_name
        from: "unavailable"
    actions:
      - action: light.turn_off
        target:
          entity_id:
            - light.dimmer_raceroom
            - light.wled_raceroom

  # ---------------------------------------------------------------------------
  # When SimHub stops publishing (player name goes unavailable), wait 5 minutes
  # then restore the office ceiling light
  # ---------------------------------------------------------------------------
  - alias: SimHub - Sim Session Ended
    id: simhub_sim_session_ended
    description: "When SimHub stops publishing, restore office ceiling light after 5 minutes."
    mode: single
    triggers:
      - trigger: state
        entity_id: sensor.simhub_player_name
        to: "unavailable"
        for:
          minutes: 5
    actions:
      - action: light.turn_on
        target:
          entity_id:
            - light.dimmer_raceroom
            - light.wled_raceroom