-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathisyexport.py
More file actions
executable file
·196 lines (159 loc) · 6.98 KB
/
isyexport.py
File metadata and controls
executable file
·196 lines (159 loc) · 6.98 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
#!/usr/bin/env python3
import click
import errno
import os
import shutil
import utils
import yaml
import xml.etree.ElementTree as ET
from zipfile import ZipFile
from drivers.param_parser import ParamParser
ISY_CONF_FOLDER = 'CONF'
ISY_NET_FOLDER = 'NET'
DEFAULT_TIMEOUT = 4000
DEFAULT_METHOD = 'PUT'
STATE_VAR_MESSAGE = '/${var.2.<replace with stare resource ID>}'
REQUEST = '''{} /{} HTTP/1.1\r
Host: {}:{}\r
User-Agent: Mozilla/4.0\r
Connection: Close\r
Content-Type: application/x-www-form-urlencoded\r
Content-Length: 0\r
\r
'''
curResourceID = 0
@click.command()
@click.option('-c', '--config', help='Config file', type=click.File('r'),
required=True)
@click.option('-sc', '--serverConfig', help='Config file', type=click.File('r'),
required=True)
@click.option('-d', '--destination', help='Config file',
type=click.Path(writable=True), required=True)
@click.option('-o', '--output', help='Output file name', required=True)
@click.option('-i', '--input', help='Input file (existing network resources backup)',
type=click.File('r'))
@click.option('-h', '--host', help='Host running RESTRemote', required=True)
@click.option('-t', '--temp', help='Do not remote temp files', is_flag=True)
def ISYExport(config, serverconfig, destination, output, input, host, temp):
configData = yaml.safe_load(config)
configData.update(yaml.safe_load(serverconfig))
configData['host'] = host
if input:
print("Extracting existing resources from", input.name)
with ZipFile(input) as inputFile:
inputFile.extractall(destination)
global curResourceID
resources = {}
commands = {}
maxResourceID = 0
outputFileName = os.path.join(destination, ISY_CONF_FOLDER, ISY_NET_FOLDER,
'RES.CFG')
try:
with open(outputFileName, 'r') as resourceFile:
resourceTree = ET.parse(resourceFile).getroot()
for resource in resourceTree:
curResourceID = 0
for id in resource.iter('id'):
curResourceID = int(id.text)
if maxResourceID < curResourceID:
maxResourceID = curResourceID
for name in resource.iter('name'):
resources[name.text] = resource
except:
resourceTree = ET.Element('NetConfig')
print('Found', maxResourceID, 'existing resources')
curResourceID = maxResourceID + 1
print("Exporting ISY network resources from",
config.name, "to", destination)
for deviceName, deviceData in configData['devices'].items():
deviceData.update(configData['drivers'][deviceData['driver']])
paramParser = ParamParser(deviceData)
utils.flatten_commands(deviceData)
for commandName, commandData in deviceData['commands'].items():
if not commandData.get('result'):
simpleCommand = True
resourceName = deviceName + '.' + commandName
command = deviceName + '/' + commandName
if commandData.get('acceptsNumber'):
print('Create state variable for', resourceName)
resourceID = addResource(configData, resources, resourceTree,
resourceName)
commands[resourceID] = command + STATE_VAR_MESSAGE
simpleCommand = False
if 'value_set' in commandData:
for value in paramParser.value_sets[commandData['value_set']].keys():
resourceID = addResource(configData, resources,
resourceTree, resourceName + '/' + value)
commands[resourceID] = command + '/' + value
simpleCommand = False
if simpleCommand:
resourceID = addResource(configData, resources, resourceTree,
resourceName)
commands[resourceID] = command
outputFileName = os.path.join(destination, ISY_CONF_FOLDER, ISY_NET_FOLDER,
'RES.CFG')
if not os.path.exists(os.path.dirname(outputFileName)):
try:
os.makedirs(os.path.dirname(outputFileName))
except OSError as error:
if error.errno != errno.EEXIST:
raise
with ZipFile(os.path.join(destination, output), 'w') as outputFile:
with open(outputFileName, 'w') as output:
output.write(ET.tostring(resourceTree).decode())
# Add main resources file to zip
outputFile.write(outputFileName,
os.path.relpath(outputFileName, destination))
# Add RES files to zip
for resourceID in range(1, curResourceID):
command = commands.get(resourceID)
outputFileName = os.path.join(destination, ISY_CONF_FOLDER,
ISY_NET_FOLDER, str(resourceID) + '.RES')
if command:
with open(outputFileName, 'w') as output:
output.write(REQUEST.format(DEFAULT_METHOD, command,
configData['host'], configData['port']))
outputFile.write(outputFileName,
os.path.relpath(outputFileName, destination))
if not temp:
shutil.rmtree(os.path.join(destination, ISY_CONF_FOLDER))
def addResource(configData, resources, parent, resourceName):
resource = resources.get(resourceName)
if resource is None:
resource = addNewResource(parent, resourceName)
updateResource(resource, configData['host'], configData['port'],
DEFAULT_METHOD)
for id in resource.iter('id'):
return int(id.text)
return -1
def addNewResource(parent, resourceName):
global curResourceID
print('Adding new resource', resourceName)
netRule = ET.SubElement(parent, 'NetRule')
addElement(netRule, 'name', resourceName)
addElement(netRule, 'id', str(curResourceID))
addElement(netRule, 'isModified', 'false')
controlInfo = ET.SubElement(netRule, 'ControlInfo')
addElement(controlInfo, 'mode', 'C Escaped')
addElement(controlInfo, 'protocol', 'http')
addElement(controlInfo, 'timeout', str(DEFAULT_TIMEOUT))
ET.SubElement(controlInfo, 'host')
ET.SubElement(controlInfo, 'port')
ET.SubElement(controlInfo, 'method')
addElement(controlInfo, 'encodeURLs', 'false')
addElement(controlInfo, 'useSNI', 'false')
curResourceID += 1
return netRule
def updateResource(resource, host, port, method):
for element in resource.find('ControlInfo'):
if element.tag == 'host':
element.text = host
elif element.tag == 'port':
element.text = str(port)
elif element.tag == 'method':
element.text = method
def addElement(parent, name, value):
element = ET.SubElement(parent, name)
element.text = value
if __name__ == '__main__':
ISYExport()