-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataProcessing.py
More file actions
239 lines (185 loc) · 7.32 KB
/
dataProcessing.py
File metadata and controls
239 lines (185 loc) · 7.32 KB
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
from __future__ import print_function
from os.path import split
import swagger_client, requests, openpyxl, math, schedule, sys, logging
from pathlib import Path
from swagger_client.rest import ApiException
from requests.auth import HTTPBasicAuth
from influxdb import InfluxDBClient
from datetime import datetime
# -------------------------------- Saving data from the xlsx file to a Dict ----------------------------------
# Function to read the data given from the xlsx file
def readXlsx(dir, fileName):
# Setting the path to the xlsx file:
xlsx_file = Path(dir, fileName)
# Read the Excel File
wb_obj = openpyxl.load_workbook(xlsx_file)
# Read the Active Sheet from the Excel file
sheet = wb_obj.active
# Max rows
# print(("Number of rows: %d") % (sheet.max_row))
accessPoints = {}
i = 0
for row in sheet.iter_rows(max_col=7, values_only=True):
if (i != 0):
id = row[0]
apData = {
'location' : row[1],
'name' : row[2],
'latitude' : row[3],
'longitude' : row[4],
'responsible' : row[5],
'building' : row[6]
}
accessPoints[id] = apData
i+=1
return accessPoints
# ------------------------------------------- Functions ------------------------------------------------------
# Function to get the API access token (expires each hour)
def getAPIAccessToken(logger):
# Getting the access token
url = 'https://wso2-gw.ua.pt/token?grant_type=client_credentials&state=123&scope=openid'
header = {'Content-Type': 'application/x-www-form-urlencoded'}
x = requests.post(url,headers=header,auth=HTTPBasicAuth('XXXXXXXX','XXXXXXXX'))
resp = x.json()
# Configure OAuth2 access token for authorization
swagger_client.configuration.access_token = resp["access_token"]
print("token: "+str(swagger_client.configuration.access_token))
logger.info("token: "+str(swagger_client.configuration.access_token))
# create an instance of the API class
api_instance = swagger_client.DefaultApi()
return api_instance
# Function to create the database
def createDB():
client = InfluxDBClient("localhost", 8086, str(sys.argv[1]), str(sys.argv[2]), "WiFiMonitor")
client.create_database("WiFiMonitor")
client.get_list_database()
client.switch_database("WiFiMonitor")
return client
# Function to get access points Info
def getAccessPoints(client, numReq, api_instance):
apInfo = []
numReq = numReq * 100;
api_response = api_instance.access_point_get(first_result=numReq)
# Get the first index
firstIndex = int(api_response.first)
# Get the last index
lastIndex = int(api_response.last)
# Get the access points list
resp = api_response.access_points
stackSize = lastIndex - firstIndex
for i in range(0, stackSize + 1):
apInfo.append(int(resp[i].id))
apInfo.append(resp[i].name)
keys = xlsxData.keys()
# Get the building by the id
if(apInfo[0] in keys):
building = xlsxData[apInfo[0]].get('building')
# If a new access point is turned on
else:
id = int(resp[i].id)
newRequest = api_instance.access_point_id_get(id)
splits = newRequest.name.split('-')
apData = {
'location' : newRequest.location,
'name' : newRequest.name,
'latitude' : None,
'longitude' : None,
'responsible' : None,
'building' : splits[0]
}
# Save new access point data into the dict
xlsxData[id] = apData
building = splits[0]
# Write the new access point data into the xlsx file
writeXlsx('.', 'PrimeCore.xlsx', id, apData)
apInfo.append(building)
apInfo.append(int(resp[i].client_count))
apInfo.append(int(resp[i].client_count_2_4_g_hz))
apInfo.append(int(resp[i].client_count_5_g_hz))
# Write on database
writeAccessPointsOnDB(client, apInfo)
# Clearing the list of access points Info
apInfo.clear()
# Function to write the new access point data into the xlsx file
def writeXlsx(dir, fileName, id, apData):
# Setting the path to the xlsx file:
xlsx_file = Path(dir, fileName)
# Read the Excel File
wb_obj = openpyxl.load_workbook(xlsx_file)
# Read the Active Sheet from the Excel file
sheet = wb_obj.active
maxRows = sheet.max_row
col = sheet["A" + str(maxRows+1)]
col.value = id
list = []
for key in apData.keys():
list.append(key)
cols = ["B","C","D","E","F","G"]
for i in range(0, len(cols)):
col = sheet[cols[i] + str(maxRows+1)]
col.value = apData.get(list[i])
wb_obj.save("./PrimeCore.xlsx")
# Function to write the access points Info on the database
def writeAccessPointsOnDB(client, info):
# Data to send to the database
json_payload = []
#
# Note: tags -> metadata about the measurement
# fields -> a measurement that changes over time
#
data = {
"measurement" : "clientsCount",
"time" : datetime.now(),
"tags" : {
"id" : info[0],
"name" : info[1],
"building" : info[2]
},
"fields" : {
"clientsCount" : info[3],
"clientsCount2_4Ghz" : info[4],
"clientsCount5Ghz" : info[5]
}
}
# Send data to the API
json_payload.append(data)
client.write_points(json_payload)
# Function to call the API to get the access points
def apiGetAccessPoint(client, logger):
api_instance = getAPIAccessToken(logger)
print("Calling Access Points")
logger.info("Calling Access Points")
if api_instance.access_point_count_get().count != None:
# To get the total number of working access points
apsCount = int(api_instance.access_point_count_get().count)
# Defining the number os API requests needed
numberReq = math.ceil(apsCount / 100)
for index in range (0, numberReq):
# Calling function to get the access points info
getAccessPoints(client, index, api_instance)
# ------------------------------------------ Main Function ---------------------------------------------------
if __name__ == "__main__":
# Data given from the xlsx file
xlsxData = readXlsx('.', 'PrimeCore.xlsx')
# Creating the log file for the service
logging.basicConfig(filename='/var/log/dataProcessing.log', level=logging.INFO)
logger = logging.getLogger("DATA PROCESSING")
# Creating the database
client = createDB()
# Getting the initial information about the access points
try:
apiGetAccessPoint(client, logger)
except Exception as e:
print("Access Point Exception: " +str(e))
logger.error("Access Point Exception: " +str(e))
# Calling the API to get the access points every 15 minutes
try:
schedule.every(15).minutes.do(apiGetAccessPoint, client, logger)
except Exception as e:
print("Access Point Exception: " +str(e))
logger.error("Access Point Exception: " +str(e))
while True:
try:
schedule.run_pending()
except ApiException as e:
logger.error("Exception: %s\n" % e)