-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMqtt.cs
104 lines (93 loc) · 3.19 KB
/
Mqtt.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System;
using System.Collections;
using System.Text;
using nanoFramework.M2Mqtt;
namespace nanoFramework_Panasonic_Automation
{
internal static class Mqtt
{
private static MqttClient MqttClient;
internal static void Connect()
{
try
{
if (MqttClient != null && MqttClient.IsConnected)
{
return;
}
Disconnect();
MqttClient = new MqttClient("IP ADDRESS OF INSTANCE")
{
ProtocolVersion = MqttProtocolVersion.Version_5
};
MqttClient.Connect(Guid.NewGuid().ToString(), username: "", password: "");
}
catch
{
// do nothing
}
}
internal static void Disconnect()
{
if (MqttClient == null)
{
return;
}
try
{
MqttClient.Disconnect();
MqttClient.Dispose();
MqttClient = null;
}
catch
{
// do nothing
}
}
internal static void AnnounceTempSensorToHomeAssistant(string area)
{
try
{
MqttClient.Publish($"homeassistant/sensor/{area}Temperature/config",
Encoding.UTF8.GetBytes($"{{ \"name\": \"{area} temperature sensor\", \"device_class\": \"temperature\", \"state_topic\": \"homeassistant/sensor/{area}/state\", \"unit_of_measurement\": \"°C\", \"value_template\": \"{{{{ value_json.temperature }}}}\"}}"),
"application/json",
userProperties: null,
qosLevel: nanoFramework.M2Mqtt.Messages.MqttQoSLevel.AtMostOnce,
retain: true);
}
catch
{
// do nothing
}
}
internal static void AnnounceHumiditySensorToHomeAssistant(string area)
{
try
{
MqttClient.Publish($"homeassistant/sensor/{area}Humidity/config",
Encoding.UTF8.GetBytes($"{{ \"name\": \"{area} humidity sensor\", \"device_class\": \"humidity\", \"state_topic\": \"homeassistant/sensor/{area}/state\", \"unit_of_measurement\": \"%\", \"value_template\": \"{{{{ value_json.humidity }}}}\"}}"),
"application/json",
userProperties: null,
qosLevel: nanoFramework.M2Mqtt.Messages.MqttQoSLevel.AtMostOnce,
retain: true);
}
catch
{
// do nothing
}
}
internal static void PublishData(string area, double temp, double humidity)
{
try
{
MqttClient.Publish($"homeassistant/sensor/{area}/state",
Encoding.UTF8.GetBytes($"{{ \"temperature\": {temp}, \"humidity\": {humidity} }}"),
"application/json");
}
catch
{
// do nothing
}
}
}
}