Subversion Repositories HomeAutomation

Rev

Rev 2137 | Details | Compare with Previous | Last modification | View Log | SVN | RSS feed

Rev Author Line No. Line
979 linlun 1
#!/usr/bin/python
825 migan 2
 
819 migan 3
# Written by Mattias Runge 2008-05-13
4
 
5
import os
6
import sys
7
import getopt
8
 
852 migan 9
moddir = sys.path[0] + "/../../EmbeddedSoftware/AVR/module"
10
localmoddir = os.getcwd() + "/modules"
819 migan 11
 
12
def getModules():
13
	modules = []
14
	for fileName in os.listdir(moddir):
887 migan 15
		if fileName[0] != '.' and fileName != "template":
819 migan 16
			modules.append(fileName)
17
 
2006 linlun 18
	return sorted(modules, key=str.lower)
819 migan 19
 
20
 
21
def getLocalModules():
22
	modules = []
23
	for fileName in os.listdir(localmoddir):
24
		if fileName[0] != '.':
25
			modules.append(fileName)
26
 
2006 linlun 27
	return sorted(modules, key=str.lower)
819 migan 28
 
29
 
30
def parseModuleIdFromFile(moduleName, fileName):
31
	config_inc = open(fileName, 'r') 
32
	config_inc_lines = config_inc.readlines()
33
	config_inc.close()
1572 linlun 34
	takenIds = []
819 migan 35
	for line in config_inc_lines:
36
		line = line.strip("\n").strip(" ")
827 migan 37
 
819 migan 38
		if line.find(moduleName + "_ID") != -1:
39
			parts = line.split("=")
1572 linlun 40
			if parts[1].strip(" ") != -1 and parts[1].strip(" ") != "<ID>":
41
				takenIds.append(int(parts[1].strip(" "), 16))
2003 linlun 42
				print "Found id: "+parts[1].strip(" ")+" in file: "+fileName+" for module: "+moduleName
2127 linlun 43
 
1572 linlun 44
	return takenIds
819 migan 45
 
46
 
1572 linlun 47
def getModuleIdsFromFile(moduleName):
819 migan 48
	takenIds = []
1572 linlun 49
	for applicationName in os.listdir("../"):	
819 migan 50
		if applicationName[0] != '.' and os.path.exists("../" + applicationName + "/config.inc"):
2127 linlun 51
			takenIds += parseModuleIdFromFile(moduleName, "../" + applicationName + "/config.inc")
1572 linlun 52
	return takenIds
53
 
2006 linlun 54
def parseAllModuleIdFromFile(fileName, foundModules):
55
	index = 0
2003 linlun 56
	modules = getModules()
57
	config_inc = open(fileName, 'r') 
58
	config_inc_lines = config_inc.readlines()
59
	config_inc.close()
2006 linlun 60
	parts = fileName.split("/")
61
	node = parts[1]
2003 linlun 62
	for line in config_inc_lines:
63
		line = line.strip("\n").strip(" ")
64
 
65
		if line.find("_ID") != -1:
66
			parts = line.split("=")
67
			if (parts[0][:-3] in modules):
68
				if parts[1].strip(" ") != -1 and parts[1].strip(" ") != "<ID>":
2006 linlun 69
					if (foundModules == 0):
70
						print "\tModule: "+parts[0][:-3]+"\t"+parts[1].strip(" ")
71
					else:
72
						foundModules.append(parts[0][:-3]+"$"+node+"$"+parts[1].strip(" ")) 
73
 
74
	return foundModules
2137 linlun 75
 
76
def parseHwIdFromFile(fileName):
77
	index = 0
78
	config_inc = open(fileName, 'r') 
79
	config_inc_lines = config_inc.readlines()
80
	config_inc.close()
81
	parts = fileName.split("/")
82
	node = parts[1]
83
	for line in config_inc_lines:
84
		line = line.strip("\n").strip(" ")
85
 
86
		if line.find("NODE_HW_ID=") == 0:
87
			parts = line.split("=")
88
			return parts[1]
89
	return ""
2003 linlun 90
 
91
def getAllModuleIdsFromFile():
2006 linlun 92
	foundModules = []
2003 linlun 93
	for applicationName in os.listdir("../"):	
94
		if applicationName[0] != '.' and os.path.exists("../" + applicationName + "/config.inc"):
2006 linlun 95
			parseAllModuleIdFromFile("../" + applicationName + "/config.inc", foundModules)
96
 
97
	foundModulesSorted = sorted(foundModules, key=str.lower)
98
	lastModule = ""
99
	for x in foundModulesSorted:
100
		splitted = x.split("$")
101
		if (lastModule != splitted[0]):
102
			lastModule = splitted[0]
103
			print lastModule
104
		print "%20s :" % splitted[1],
105
		print splitted[2]
106
 
107
def getAllNodesFromFile():
108
	files = sorted(os.listdir("../"), key=str.lower)
109
	for applicationName in files:	
110
		if applicationName[0] != '.' and os.path.exists("../" + applicationName + "/config.inc"):
2137 linlun 111
			if applicationName[0] != '.' and os.path.exists("../" + applicationName + "/bios.inc"):
112
				hwid = parseHwIdFromFile("../" + applicationName + "/bios.inc")
113
			print "Found node: "+applicationName+ "\n With hwId: "+hwid
2006 linlun 114
			parseAllModuleIdFromFile("../" + applicationName + "/config.inc", 0)
819 migan 115
 
1572 linlun 116
def getFreeModuleId(takenIds):
819 migan 117
	if len(takenIds) == 0:
1572 linlun 118
		return 1
819 migan 119
	takenIds.sort()
120
	lastId = 0
121
 
122
	for takenId in takenIds:
2127 linlun 123
		if ((takenId != lastId+1) & (takenId != lastId)):
1572 linlun 124
			return lastId+1
827 migan 125
		lastId = takenId
819 migan 126
 
1572 linlun 127
	return lastId+1
2127 linlun 128
 
819 migan 129
 
130
def compileMainFile():
131
	print "Compiling new main.c..."
132
	main_c_template = open('src/main.c.template', 'r') 
133
	main_c_template_lines = main_c_template.readlines()
134
	main_c_template.close()
135
 
136
	modules = getLocalModules()
137
 
138
	main_c = open('src/main.c', 'w') 
139
 
140
	for main_c_template_line in main_c_template_lines:
141
		pos_include = main_c_template_line.find('%INCLUDE')
142
		pos_init = main_c_template_line.find('%INIT')
143
		pos_process = main_c_template_line.find('%PROCESS')
144
		pos_list = main_c_template_line.find('%LIST')
145
		pos_handlemsg = main_c_template_line.find('%HANDLEMSG')
146
 
147
		if pos_include != -1:
148
			for moduleName in modules:
822 migan 149
				main_c.write(main_c_template_line[:pos_include] + "#include \"../modules/" + moduleName + "/" + moduleName + ".h\"\n")
819 migan 150
		elif pos_init != -1:
151
			for moduleName in modules:
839 migan 152
				main_c.write(main_c_template_line[:pos_init] + moduleName + "_Init();\n")
819 migan 153
		elif pos_process != -1:
154
			for moduleName in modules:
839 migan 155
				main_c.write(main_c_template_line[:pos_process] + moduleName + "_Process();\n")
819 migan 156
		elif pos_list != -1:
157
			count = 1
158
			for moduleName in modules:
839 migan 159
				main_c.write(main_c_template_line[:pos_list] + moduleName + "_List(" + str(count) + ");\n")
819 migan 160
				count += 1
161
		elif pos_handlemsg != -1:
162
			for moduleName in modules:
839 migan 163
				main_c.write(main_c_template_line[:pos_handlemsg] + moduleName + "_HandleMessage(&rxMsg);\n")
819 migan 164
		else:
165
			main_c.write(main_c_template_line)
166
 
167
	main_c.close()
168
 
169
	print "Creation of main.c complete"
170
 
171
def readConfigSection(fileName, sectionName):
172
	fileInstance = open(fileName, 'r')
173
	lines = fileInstance.readlines()
174
	fileInstance.close()
175
 
176
	sectionLines = []
177
 
178
	inSection = False
179
 
180
	for line in lines:
181
		if not inSection:
1727 cougar 182
			if line.find("## Section " + sectionName + " --") != -1:
819 migan 183
				inSection = True
184
				sectionLines.append(line.strip("\n"))
185
		else:
1727 cougar 186
			if line.find("## End section " + sectionName + " --") != -1:
819 migan 187
				inSection = False
188
 
189
			sectionLines.append(line.strip("\n"))
190
 
191
	return sectionLines
192
 
193
 
194
def updateConfigFile():
2228 linlun 195
	print "Updating config.inc...\n"
819 migan 196
	modules = getLocalModules()
197
	moduleSections = {}
198
	applicationSection = []
1574 linlun 199
	moduleName="none"
819 migan 200
	if not os.path.exists("config.inc"):
201
		applicationSection = readConfigSection("src/config.inc.template", "application")
202
 
203
		for moduleName in modules:
204
			moduleSections[moduleName] = readConfigSection(localmoddir + "/" + moduleName + "/config.inc.template", moduleName)
205
	else:
206
		applicationSection = readConfigSection("config.inc", "application")
2228 linlun 207
		print "\tModules used:"
819 migan 208
		for moduleName in modules:
209
			moduleSections[moduleName] = readConfigSection("config.inc", moduleName)
2228 linlun 210
			print "\t\t"+moduleName
819 migan 211
			if len(moduleSections[moduleName]) <= 1:
212
				moduleSections[moduleName] = readConfigSection(localmoddir + "/" + moduleName + "/config.inc.template", moduleName)
213
 
214
	timers = 0
1125 linlun 215
	pcints = 0
2228 linlun 216
	print ""
819 migan 217
	for moduleName, moduleSection in moduleSections.iteritems():
218
		c = 0
219
		for line in moduleSection:
1259 runge 220
			if len(line) > 0:
221
				if line[0] != '#':
222
					if line.find("<ID>") != -1:
2228 linlun 223
						moduleIds = getModuleIdsFromFile(moduleName)
1572 linlun 224
						new_ID = getFreeModuleId(moduleIds)
2127 linlun 225
						print "\nNew module id set to: "+hex(new_ID)+"\n"
1572 linlun 226
						moduleIds.append(new_ID)
227
						line = line.replace("<ID>", hex(new_ID))
1259 runge 228
					elif line.find("<TIMER>") != -1:
229
						line = line[:line.find("=")+1] + hex(timers) + " /* <TIMER> -- DO NOT REMOVE THIS COMMENT -- */"
230
						timers += 1
231
					elif line.find("<PCINT>") != -1:
232
						line = line[:line.find("=")+1] + hex(pcints) + " /* <PCINT> -- DO NOT REMOVE THIS COMMENT -- */"
233
						pcints += 1
234
 
235
			moduleSection[c] = line;
236
			c += 1
237
 
238
	c = 0
239
	for line in applicationSection:
240
		if len(line) > 0:
1258 runge 241
			if line[0] != '#':
1259 runge 242
				if line.find("<TIMER>") != -1:
1258 runge 243
					line = line[:line.find("=")+1] + hex(timers) + " /* <TIMER> -- DO NOT REMOVE THIS COMMENT -- */"
244
					timers += 1
1259 runge 245
				elif line.find("TIMER_NUM_TIMERS=") != -1:
246
					line = "TIMER_NUM_TIMERS=" + hex(timers)
247
				elif line.find("NUMBER_OF_MODULES=") != -1:
248
					line = "NUMBER_OF_MODULES=" + hex(len(modules))
1258 runge 249
				elif line.find("<PCINT>") != -1:
250
					line = line[:line.find("=")+1] + hex(pcints) + " /* <PCINT> -- DO NOT REMOVE THIS COMMENT -- */"
251
					pcints += 1
1259 runge 252
				elif line.find("PCINT_NUM_PCINTS=") != -1:
253
					line = "PCINT_NUM_PCINTS=" + hex(pcints)
819 migan 254
		applicationSection[c] = line;
255
		c += 1
256
 
257
	config_inc = open('config.inc', 'w')
258
 
259
	for line in applicationSection:
260
		config_inc.write(line + "\n")
261
 
262
	for moduleName, moduleSection in moduleSections.iteritems():
263
		for line in moduleSection:
264
			config_inc.write(line + "\n")
265
 
266
	config_inc.close()
267
 
268
	print "Update of config.inc complete"
269
 
270
 
271
def compileSourcesFile():
272
	print "Compiling sources.inc..."
273
 
274
	uniqueSet = []
1983 linlun 275
	uniqueSet2 = []
1991 linlun 276
	if os.path.isfile("src/libraries.list.template"):
277
		libraries_list_template = open('src/libraries.list.template', 'r')
278
		libraries_list_template_lines = libraries_list_template.readlines()
279
		libraries_list_template.close()
819 migan 280
 
281
	sources_list_template = open('src/sources.list.template', 'r')
282
	sources_list_template_lines = sources_list_template.readlines()
283
	sources_list_template.close()
1991 linlun 284
	if os.path.isfile("src/libraries.list.template"):
285
		for libraries_list_template_line in libraries_list_template_lines:
286
			line =libraries_list_template_line.strip("\n").strip(" ")
287
			if len(line) > 0:
288
				if line[0] != '#':
289
					uniqueSet2.append(line)
819 migan 290
 
291
	for sources_list_template_line in sources_list_template_lines:
847 migan 292
		line = sources_list_template_line.strip("\n").strip(" ")
293
		if len(line) > 0:
294
			if line[0] != '#':
295
				uniqueSet.append(line)
819 migan 296
 
297
	modules = getLocalModules()
298
 
299
	for moduleName in modules:
300
		sources_list = open(localmoddir + "/" + moduleName + "/sources.list", 'r')
301
		sources_list_lines = sources_list.readlines()
302
		sources_list.close()
303
 
1993 linlun 304
		if os.path.isfile(localmoddir + "/" + moduleName + "/libraries.list"):
305
			libraries_list = open(localmoddir + "/" + moduleName + "/libraries.list", 'r')
306
			libraries_list_lines = libraries_list.readlines()
307
			libraries_list.close()
308
 
309
			for libraries_list_line in libraries_list_lines:
310
				line = libraries_list_line.strip("\n").strip(" ")
311
				if len(line) > 0:
312
					if line[0] != '#':
313
						uniqueSet2.append("../../../module/" + moduleName + line)
819 migan 314
		for sources_list_line in sources_list_lines:
847 migan 315
			line = sources_list_line.strip("\n").strip(" ")
316
			if len(line) > 0:
317
				if line[0] != '#':
318
					uniqueSet.append(line)
319
 
819 migan 320
 
321
	sourcesString = "SOURCES = "
322
 
323
	#FIXME: Make uniqueSet actually unique
324
 
325
	for line in uniqueSet:
326
		sourcesString += line + " "
1983 linlun 327
	sourcesString += "\n"
328
	sourcesString += "LDLIBS = "
1993 linlun 329
	for line in uniqueSet2:
330
		sourcesString += line + " "
819 migan 331
	sources_inc = open('sources.inc', 'w')
332
	sources_inc.write(sourcesString.strip(" ") + "\n")
333
	sources_inc.close()
334
 
335
	print "Creation of sources.inc complete"
336
 
337
def regenerateModules():
338
	print "Regenerating modules..."
836 migan 339
	print ""
819 migan 340
	compileSourcesFile()
836 migan 341
	print ""
819 migan 342
	compileMainFile()
836 migan 343
	print ""
819 migan 344
	updateConfigFile()
836 migan 345
	print ""
819 migan 346
	print "Regenerating modules complete"
836 migan 347
	print ""
819 migan 348
 
2003 linlun 349
def listUsedModules():
350
	print "Listing modules..."
351
	print ""
352
	getAllModuleIdsFromFile()
353
	print ""
354
	print "Listing modules complete"
355
	print ""
2006 linlun 356
 
357
def listUsedNodes():
358
	print "Listing nodes..."
359
	print ""
360
	getAllNodesFromFile()
361
	print ""
362
	print "Listing nodes complete"
363
	print ""
819 migan 364
 
365
def addModule(moduleName):
366
	print "Trying to add module " + moduleName
367
 
368
	try:
1935 arune 369
		# the following creates symlinks to <path to modulemanager>/../../EmbeddedSoftware/AVR/module
370
		# and <path to modulemanager> is an absolute path which makes the symlink similar to this:
371
		# act_dimmer230 -> /home/arune/Documents/HomeAutomation/PcSoftware/scripts/../../EmbeddedSoftware/AVR/module/act_dimmer230
372
		#os.symlink(moddir + "/" + moduleName, localmoddir + "/" + moduleName)
373
		# instead symlink to relative path instead
374
		os.symlink("../../../module/" + moduleName, localmoddir + "/" + moduleName)
820 migan 375
		print "Added module successfully"
819 migan 376
	except OSError, (errno, strerror):
377
		if errno == 17:
378
			print "A link, file or directory named " + moduleName + " is already present in the modules directory, not linking"
379
		else:
380
			raise
381
 
382
	print ""
383
 
384
	regenerateModules()
385
 
386
 
824 migan 387
def delModule(moduleName):
388
	print "Trying to remove module " + moduleName
389
 
390
	try:
391
		os.unlink(localmoddir + "/" + moduleName)
392
		print "Removed module successfully"
393
	except OSError, (errno, strerror):
394
		if errno == 2:
395
			print "No such " + moduleName + " present in the modules directory, not unlinking"
396
		else:
397
			raise
398
 
399
	print ""
400
 
401
	regenerateModules()
402
 
852 migan 403
def createFile(moduleName, templateFileName, moduleFileName):
404
	print "Creating " + moduleName + "/" + templateFileName + "..."
405
	template_file = open(moddir + "/template/" + templateFileName, 'r')
406
	lines = template_file.readlines()
407
	template_file.close()
824 migan 408
 
852 migan 409
	module_file = open(moddir + "/" + moduleName + "/" + moduleFileName, 'w')
410
 
411
	for line in lines:
412
		line = line.replace("<template>", moduleName)
413
		line = line.replace("<TEMPLATE>", moduleName.upper())
414
 
415
		module_file.write(line)
416
 
417
	module_file.close()
418
 
419
def newModule(moduleName):
420
	print "Creating " + moddir + "/" + moduleName + " directory..."
421
	os.mkdir(moddir + "/" + moduleName + "/")
422
 
423
	createFile(moduleName, "config.inc.template", "config.inc.template")
424
	createFile(moduleName, "sources.list", "sources.list")
425
	createFile(moduleName, "template.h", moduleName + ".h")
426
	createFile(moduleName, "template.c", moduleName + ".c")
1106 linlun 427
	createFile(moduleName, "template_eeprom.h", moduleName + "_eeprom.h")
852 migan 428
 
819 migan 429
def usage():
836 migan 430
	print "Syntax: ./ModuleManager [options]"
819 migan 431
	print "Options:"
836 migan 432
	print "  --help               Print this help"
433
	print "  --regenerate         Regenarate modules and files"
434
	print "  --list               List avalible and installed modules"
435
	print "  --add=<module name>  Adds a module to the application"
436
	print "  --del=<module name>  Removes a module from the application"
852 migan 437
	print "  --new=<module name>  Creates a new module from the module template"
2003 linlun 438
	print "  --modules            Lists all used modules in your personal folder"
2006 linlun 439
	print "  --nodes              Lists all nodes in your personal folder"
819 migan 440
	print ""
441
 
442
 
443
def main():
444
	try:
2006 linlun 445
		opts, args = getopt.getopt(sys.argv[1:], "hlrcmn", ["help", "list", "modules", "nodes", "regenerate", "add=", "del=", "new="])
819 migan 446
	except getopt.GetoptError, err:
447
		# print help information and exit:
448
		print str(err) # will print something like "option -a not recognized"
449
		usage()
450
		sys.exit(2)
825 migan 451
 
452
	if len(sys.argv) == 1:
453
		usage()
454
		sys.exit()
455
 
819 migan 456
	for o, a in opts:
885 migan 457
		if o in ("-c"):
836 migan 458
			modules = getModules()
824 migan 459
 
885 migan 460
			for module in modules:
461
				print module
462
 
463
		elif o in ("-l", "--list"):
464
			modules = getModules()
836 migan 465
			print "Available modules"
466
			print "================="
467
			for module in modules:
468
				print module
469
 
885 migan 470
 
471
			if os.path.exists(localmoddir):
472
				print ""
836 migan 473
 
885 migan 474
				modules = getLocalModules()
836 migan 475
 
885 migan 476
				print "Modules used in this application"
477
				print "================================"
478
				for module in modules:
479
					print module
480
 
819 migan 481
		elif o in ("-h", "--help"):
482
			usage()
483
			sys.exit()
824 migan 484
 
819 migan 485
		elif o in ("-r", "--regenerate"):
486
			regenerateModules()
824 migan 487
 
2003 linlun 488
		elif o in ("-m", "--modules"):
489
			listUsedModules()
2006 linlun 490
 
491
		elif o in ("-n", "--nodes"):
492
			listUsedNodes()
2003 linlun 493
 
819 migan 494
		elif o in ("--add"):
495
			if len(a) == 0:
496
				print "No modulename specified"
497
				usage()
498
				sys.exit()
499
 
500
			if a not in getModules():
501
				print a + " is not a recognized module name"
502
				sys.exit()
503
 
504
			addModule(a)
824 migan 505
 
506
		elif o in ("--del"):
507
			if len(a) == 0:
508
				print "No modulename specified"
509
				usage()
510
				sys.exit()
511
 
512
			if a not in getModules():
513
				print a + " is not a recognized module name"
514
				sys.exit()
515
 
516
			delModule(a)
517
 
852 migan 518
		elif o in ("--new"):
519
			if len(a) == 0:
520
				print "No modulename specified"
521
				usage()
522
				sys.exit()
523
 
524
			if a in getModules():
525
				print a + " already exists"
526
				sys.exit()
527
 
528
			newModule(a)
529
 
819 migan 530
		else:
531
			assert False, "unhandled option"
532
 
533
 
534
if __name__ == "__main__":
535
	main()
536