-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmelcloud_exporter.py
168 lines (142 loc) · 7.31 KB
/
melcloud_exporter.py
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#!/usr/bin/env python3
# encoding: utf-8
__author__ = "Oliver Schlueter"
__license__ = "GPL"
__version__ = "1.0.0"
__email__ = "[email protected]"
__status__ = "Production"
""""
###########################################################################################################
Prometheus Exporter for Mitsubishi MelCloud Devices
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
###########################################################################################################
"""
import os
import time
import json
import requests
import datetime
from prometheus_client import start_http_server, Gauge, Info, Enum
class MelCloudMetrics:
headers = {
"Content-Type": "application/json",
"Host": "app.melcloud.com",
"Cache-Control": "no-cache"
}
def __init__(self, polling_interval_seconds, mel_cloud_user, mel_cloud_password):
self.polling_interval_seconds = polling_interval_seconds
self.mel_cloud_user = mel_cloud_user
self.mel_cloud_password = mel_cloud_password
self.data = {
"Email": self.mel_cloud_user,
"Password": self.mel_cloud_password,
"AppVersion": "1.23.4.0"
}
# Prometheus' metrics to collect
self.device_name = Info("device_name", "Device Name")
self.power = Enum('power_state', 'Power Status', ['room'], states=['on', 'off'])
self.total_energy_consumed = Gauge("total_energy_consumed", "Total Energy Consumed", ['room'])
self.wifi_signal = Gauge("wifi_signal", "Wifi Signal", ['room'])
self.room_temperature = Gauge("room_temperature", "Room Temperature", ['room'])
self.target_temperature = Gauge("target_temperature", "Target Temperature", ['room'])
self.operation_mode = Enum('operation_mode', 'Operation Mode', ['room'],
states=["heat", "dry", "cool", "fan_only", "heat_cool", "undefined"])
self.fan_speed = Gauge('fan_speed', 'Fan Speed', ['room'])
self.vane_horizontal = Gauge('vane_horizontal', 'Vane Horizontal', ['room'])
self.vane_vertical = Gauge('vane_vertical', 'Vane Vertical', ['room'])
def retrieve_mel_cloud_data(self):
error = False
timestamp = datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S)")
try:
# try to get token
url = 'https://app.melcloud.com/Mitsubishi.Wifi.Client/Login/ClientLogin'
response = requests.post(url, headers=self.headers, data=json.dumps(self.data))
out = json.loads(response.text)
if out['LoginStatus'] != 0:
print("Login not successful")
error = True
else:
token = out['LoginData']['ContextKey']
self.headers["X-MitsContextKey"] = token
except Exception as err:
print(timestamp + ": Not able to get token: " + str(err))
error = True
if not error:
try:
# try to get device data
url = 'https://app.melcloud.com/Mitsubishi.Wifi.Client/User/Listdevices'
response = requests.get(url, headers=self.headers, data=json.dumps(self.data))
out = json.loads(response.text)
devices = out[0]['Structure']['Devices']
except Exception as err:
print(timestamp + ": Not able to get device data: " + str(err))
error = True
if not error:
try:
for device in devices:
room = device['DeviceName']
self.device_name.info({"device_name": room})
print(device['Device']['Power'])
if device['Device']['Power']:
self.power.labels(room).state("on")
else:
self.power.labels(room).state("off")
self.total_energy_consumed.labels(room).set(device['Device']['CurrentEnergyConsumed'])
self.wifi_signal.labels(room).set(device['Device']['WifiSignalStrength'])
self.room_temperature.labels(room).set(device['Device']['RoomTemperature'])
self.target_temperature.labels(room).set(device['Device']['SetTemperature'])
# 1: Heating, 2: Drying, 3: Cooling, 7: Van, 8: Auto
if device['Device']['OperationMode'] == 1:
self.operation_mode.labels(room).state("heat")
if device['Device']['OperationMode'] == 2:
self.operation_mode.labels(room).state("dry")
if device['Device']['OperationMode'] == 3:
self.operation_mode.labels(room).state("cool")
if device['Device']['OperationMode'] == 7:
self.operation_mode.labels(room).state("fan_only")
if device['Device']['OperationMode'] == 8:
self.operation_mode.labels(room).state("heat_cool")
self.fan_speed.labels(room).set(device['Device']['FanSpeed'])
self.vane_horizontal.labels(room).set(device['Device']['VaneVerticalDirection'])
self.vane_vertical.labels(room).set(device['Device']['VaneHorizontalSwing'])
except Exception as err:
print(timestamp + ": Not able to get read values: " + str(err))
error = True
def run_metrics_loop(self):
while True:
self.retrieve_mel_cloud_data()
time.sleep(self.polling_interval_seconds)
def main():
"""Main entry point"""
try:
polling_interval_seconds = int(os.environ['MEL_CLOUD_PORT_INTERVAL'])
except:
polling_interval_seconds = 10
try:
port = int(os.environ['MEL_CLOUD_PORT'])
except:
port = 8020
try:
mel_cloud_user = os.environ['MEL_CLOUD_USER']
except:
mel_cloud_user = "user"
try:
mel_cloud_password = os.environ['MEL_CLOUD_PASSWORD']
except:
mel_cloud_password = "password!"
app_metrics = MelCloudMetrics(polling_interval_seconds, mel_cloud_user, mel_cloud_password)
start_http_server(port)
app_metrics.run_metrics_loop()
if __name__ == "__main__":
main()