-
Notifications
You must be signed in to change notification settings - Fork 1
/
MQTTtoOpsRamp
144 lines (122 loc) · 5.31 KB
/
MQTTtoOpsRamp
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
#!/usr/bin/python
# =====================================================================================================
# Author : Eric Repec ([email protected])
# Version: 0.4
# Date created: 5/1/2020
# Description: Python example to post metric from MQTT to OpsRamp Metric API V2
# =====================================================================================================
import paho.mqtt.subscribe as subscribe
import time
import json
import requests
mqtthost="<MQTT Broker Host>"
# Setup connection to OpsRamp
# OpsRamp Tenant credentials Need to protect this data
with open('OpsRampTenantCredentials.json','r') as f:
client = json.load(f)
# Define the Metric Payload for OpsRamp
# Documentation URL: https://docs.pov.opsramp.com/metric-apis/#Save_Metrics_on_a_Resource
# metric_opsramp_json = [{
# "metricName": "EnergyUsage",
# "instanceVal": "1200",
# "ts": time.mktime(time.localtime())
# }]
metric_opsramp_json = [{
"metricName": "resource.availability",
"instanceVal": "1",
"ts": "0"
},{
"metricName": "Total_Watts",
"instanceVal": "0",
"ts": "0"
},{
"metricName": "Pump_1",
"instanceVal": "0",
"ts": "0"
},{
"metricName": "Pump_2",
"instanceVal": "0",
"ts": "0"
},{
"metricName": "Pump_3",
"instanceVal": "0",
"ts": "0"
},{
"metricName": "Pump_4",
"instanceVal": "0",
"ts": "0"
},{
"metricName": "RPM_Pump_1",
"instanceVal": "0",
"ts": "0"
}]
# Build Base URIs to connect to OpsRamp API
base_uri = 'https://'+client['suffix']+'.api.pov.opsramp.com'
base_api_uri = base_uri+'/api/v2/metric/tenants/'+client['tenant_id']
#OAuth token generator
def build_access_header():
# Post OAuth2 token and build access_header for submission
headers = {"Content-Type": "application/x-www-form-urlencoded","Accept": "application/json"}
# Key and Secret are generated in the OpsRamp GUI under Setup~Integrations~Other~"Custom Integration"
data = {"grant_type": "client_credentials","client_id": client['key'],"client_secret": client['secret']}
auth_uri = base_uri+'/auth/oauth/token'
r = requests.post(auth_uri,data=data,headers=headers)
print('\nAuthentication Post Status Code: '+str(r.status_code))
if r.status_code != 200:
print('\nAuthentication Post Response: ' + str(r.content))
json = r.json()
auth = str(json["token_type"]) + " " + str(json["access_token"])
global access_header
access_header = {"Content-Type": "application/json", "Accept": "application/json","Authorization": auth}
print ("Captured Access Header %s " % access_header)
# Post metric to OpsRamp Metric API
def post_opsramp_metric():
# Create metric uri
create_metric_uri = base_api_uri+'/rtypes/'+client['rtype']+'/resources/'+client['resource_guid']+'/metrics'
print("uri:"+create_metric_uri)
# Unpack JSON object into string
json_out = json.dumps(metric_opsramp_json,indent=4)
print("\nMetic Payload: \n"+json_out)
#Post the message and wait for response status_code
r = requests.post(create_metric_uri,headers=access_header,data=json_out)
print('\nMetric Post Status Code: '+str(r.status_code))
if r.status_code != 200:
print('\nFailed Metric Post Response: ' + str(r.content))
#Else do nothing. In this example we don't care if we lose a few records
def on_message_print(client,userdata,message):
#Generate a timestamp for the data point if one is not in the data packet
ts=time.time()
print("Received %s from %s at %s" % (str(message.payload),message.topic,ts))
iot_data=json.loads(message.payload.decode('utf-8'))
print("JSON: %s" % (iot_data))
#Post information to OpsRamp
print('Send data to OpsRamp')
build_access_header()
# Addup watts from all pumps
watts=int(iot_data.get("Pump1_watts"))
watts=watts+int(iot_data.get("Pump2_watts"))
watts=watts+int(iot_data.get("Pump3_watts"))
watts=watts+int(iot_data.get("Pump4_watts"))
#Insert new values into payload JSON object
metric_opsramp_json[0]['instanceVal']=1
metric_opsramp_json[0]['ts']=time.mktime(time.localtime())
metric_opsramp_json[1]['instanceVal']=watts
metric_opsramp_json[1]['ts']=time.mktime(time.localtime())
metric_opsramp_json[2]['instanceVal']=iot_data.get("Pump1_watts")
metric_opsramp_json[2]['ts']=time.mktime(time.localtime())
metric_opsramp_json[3]['instanceVal']=iot_data.get("Pump2_watts")
metric_opsramp_json[3]['ts']=time.mktime(time.localtime())
metric_opsramp_json[4]['instanceVal']=iot_data.get("Pump3_watts")
metric_opsramp_json[4]['ts']=time.mktime(time.localtime())
metric_opsramp_json[5]['instanceVal']=iot_data.get("Pump4_watts")
metric_opsramp_json[5]['ts']=time.mktime(time.localtime())
metric_opsramp_json[6]['instanceVal']=iot_data.get("Pump1_rpm")
metric_opsramp_json[6]['ts']=time.mktime(time.localtime())
print("JSON: %s" % (metric_opsramp_json))
post_opsramp_metric()
# Subscribe to MQTT topic and forward information to on_message_print function
subscribe.callback(on_message_print, "house/pool/status",hostname=mqtthost)
# TO install
# apt-get install vim
# pip install --upgrade pip
# pip install paho.mqtt