-
Notifications
You must be signed in to change notification settings - Fork 1
/
gsheet2udmi.py
executable file
·275 lines (236 loc) · 9.58 KB
/
gsheet2udmi.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
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pyfiglet import Figlet
import argparse
from sys import argv, exit
import os
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
import numpy as np
from string import Template
import ssl
import udmi
import datetime
ssl._create_default_https_context = ssl._create_unverified_context
__author__ = "Francesco Anselmo"
__copyright__ = "Copyright 2021, Francesco Anselmo"
__credits__ = ["Francesco Anselmo"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Francesco Anselmo"
__email__ = "[email protected]"
__status__ = "Dev"
SCOPES = ["https://spreadsheets.google.com/feeds",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive"]
def show_title():
"""Show the program title
"""
f1 = Figlet(font='standard')
print(f1.renderText('gsheet2UDMI'))
class gsheet2UDMI:
def __init__(self,
spreadsheet_id,
sheet,
credentials_file_path,
gateway
):
self.spreadsheet_id = spreadsheet_id
self.sheet = sheet
self.creds = credentials_file_path
self.gateway = gateway
self.site_name = ""
self.devices = []
def _process_device_row(self, row, outputfolder):
# if an asset name has been assigned
if row['asset_name'] != "":
self.devices.append(row['asset_name'])
timestamp = datetime.datetime.utcnow()
x = row['x']
y = row['y']
if x == "": x = 0
if y == "": y = 0
system = {
"location": {
"site": "%s" % self.site_name,
"position": {
"x": float(x),
"y": float(y),
}
},
"physical_tag": {
"asset": {
"guid": "uuid://%s" % row['asset_guid'],
"site": "%s" % self.site_name,
"name": "%s" % row['asset_name']
}
}
}
cloud = {
"is_gateway": False
}
gateway = {
"gateway_id" : self.gateway
}
pointset = {
"points": {
}
}
if row['dbo_pointnames'] != "":
pointset = {
"points": {point:{} for point in row['dbo_pointnames'].split()}
}
# metadata = udmi.MetaData(timestamp, system, pointset=pointset, cloud=cloud)
metadata = udmi.MetaData(timestamp, system, pointset=pointset, gateway = gateway)
udmi_string = metadata.as_udmi()
print(row['asset_name'],)
# create device folder
device_folder_name = os.path.join(outputfolder, "devices", row['asset_name'])
# print(device_folder_name)
if not os.path.exists(device_folder_name):
os.mkdir(device_folder_name)
# save metadata.json file into device folder
metadata_file_name = os.path.join(device_folder_name, "metadata.json")
# print(metadata_file_name)
if not os.path.exists(metadata_file_name):
f = open(metadata_file_name, "w")
#print(udmi_string)
f.write(udmi_string)
f.close()
def _process_gateway_row(self, row, worksheet, outputfolder):
# find the gateway that has the same name as the connector and create UDMI metadata file
if row['connector_name'] == worksheet:
timestamp = datetime.datetime.utcnow()
system = {
"location": {
"site": "%s" % self.site_name,
"section": "%s" % row['space_name'],
"position": {
"x": float(row['x']),
"y": float(row['y']),
}
},
"physical_tag": {
"asset": {
"guid": "uuid://%s" % row['asset_guid'],
"site": "%s" % self.site_name,
"name": "%s" % row['asset_name']
}
}
}
cloud = {
"auth_type": "RS256",
"is_gateway": True
}
gateway = {
"proxy_ids": [device for device in self.devices]
}
pointset = {
"points": {
}
}
if row['dbo_pointnames'] != "":
pointset = {
"points": {point:{} for point in row['dbo_pointnames'].split()}
}
metadata = udmi.MetaData(timestamp, system, gateway=gateway, pointset=pointset, cloud=cloud)
# metadata = udmi.MetaData(timestamp, system, gateway=gateway, pointset=pointset)
udmi_string = metadata.as_udmi()
print(row['connector_name'], row['asset_name'])
#print(udmi_string)
# create gateway folder
device_folder_name = os.path.join(outputfolder, "devices", row['asset_name'])
# print(device_folder_name)
if not os.path.exists(device_folder_name):
os.mkdir(device_folder_name)
# save metadata.json file into device folder
metadata_file_name = os.path.join(device_folder_name, "metadata.json")
# print(metadata_file_name)
if not os.path.exists(metadata_file_name):
f = open(metadata_file_name, "w")
#print(udmi_string)
f.write(udmi_string)
f.close()
def convert_to_UDMI_sitemodel(self, outputfolder, cloudregion, registryid):
creds = ServiceAccountCredentials.from_json_keyfile_name(self.creds, SCOPES)
client = gspread.authorize(creds)
sh = client.open_by_key(self.spreadsheet_id)
project_wks = sh.worksheet("project")
gateways_wks = sh.worksheet("gateways")
devices_wks = sh.worksheet(self.sheet)
# process project
p_data = project_wks.get_all_values()
p_headers = p_data.pop(0)
p_df = pd.DataFrame(p_data, columns=p_headers)
self.site_name = p_df.iloc[0]['project_name']
print("Site name:", self.site_name)
# create cloud_iot_config.json file
cic_filename = os.path.join(outputfolder, "cloud_iot_config.json")
if not os.path.exists(cic_filename):
f = open(cic_filename, "w")
config = """{
"cloud_region": "%s",
"site_name": "%s",
"registry_id": "%s"
}""" % (cloudregion, self.site_name, registryid)
f.write(config)
f.close()
# process devices
d_data = devices_wks.get_all_values()
d_headers = d_data.pop(0)
d_df = pd.DataFrame(d_data, columns=d_headers)
d_df.apply(self._process_device_row, outputfolder = outputfolder, axis=1)
#print(self.devices)
# process gateways
gw_data = gateways_wks.get_all_values()
gw_headers = gw_data.pop(0)
gw_df = pd.DataFrame(gw_data, columns=gw_headers)
gw_df.apply(self._process_gateway_row, worksheet = self.sheet, outputfolder = outputfolder, axis=1)
def main():
show_title()
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true", default=False, help="increase the verbosity level")
parser.add_argument("-s", "--gsheetid", default="", help="google spreadsheet ID with devices")
parser.add_argument("-w", "--worksheet", default="Sheet1", help="google spreadsheet worksheet")
parser.add_argument("-g", "--gateway", default="", help="gateway device (optional)")
parser.add_argument("-j", "--credsfile", default=False, help="credential json file")
parser.add_argument("-c", "--cloudregion", default="europe-west1", help="GCP region")
parser.add_argument("-r", "--registryid", default="iot-registry", help="GCP Cloud IoT Registry")
parser.add_argument("-o", "--output", default="udmi_site_model", help="output folder for the generated UDMI site model")
args = parser.parse_args()
SPREADSHEET_ID = args.gsheetid
WORKSHEET = args.worksheet
GATEWAY = args.gateway
CREDENTIAL_FILE_PATH = args.credsfile
OUTFOLDER = args.output
CLOUDREGION = args.cloudregion
REGISTRY_ID = args.registryid
if args.verbose:
print("Program arguments:")
print(args)
print()
if SPREADSHEET_ID == '':
print('Convert a Google Sheet building matrix worksheet to a UDMI site model')
print()
print('Please provide an Google Sheet ID')
print('Invoke %s -h for further information\n' % argv[0])
exit(1)
else:
if not WORKSHEET:
WORKSHEET = 'Sheet1'
if not OUTFOLDER:
OUTFOLDER = 'udmi_site_model'
pwd = os.getcwd()
OUTFOLDER = os.path.join(pwd,OUTFOLDER)
print('Output UDMI Site model folder: %s' % OUTFOLDER)
if not os.path.exists(OUTFOLDER):
os.mkdir(OUTFOLDER)
if not os.path.exists(os.path.join(OUTFOLDER,"devices")):
os.mkdir(os.path.join(OUTFOLDER,"devices"))
inputfile = gsheet2UDMI(SPREADSHEET_ID, WORKSHEET, CREDENTIAL_FILE_PATH, GATEWAY)
inputfile.convert_to_UDMI_sitemodel(OUTFOLDER, CLOUDREGION, REGISTRY_ID)
if __name__ == "__main__":
main()