Subversion Repositories HomeAutomation

Rev

Rev 2127 | Go to most recent revision | 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():
195
	print "Updating config.inc..."
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")
207
 
208
		for moduleName in modules:
209
			moduleSections[moduleName] = readConfigSection("config.inc", moduleName)
210
 
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
1572 linlun 216
 
217
	moduleIds = getModuleIdsFromFile(moduleName)
218
 
819 migan 219
	for moduleName, moduleSection in moduleSections.iteritems():
220
		c = 0
221
		for line in moduleSection:
1259 runge 222
			if len(line) > 0:
223
				if line[0] != '#':
224
					if line.find("<ID>") != -1:
1572 linlun 225
						new_ID = getFreeModuleId(moduleIds)
2127 linlun 226
						print "\nNew module id set to: "+hex(new_ID)+"\n"
1572 linlun 227
						moduleIds.append(new_ID)
228
						line = line.replace("<ID>", hex(new_ID))
1259 runge 229
					elif line.find("<TIMER>") != -1:
230
						line = line[:line.find("=")+1] + hex(timers) + " /* <TIMER> -- DO NOT REMOVE THIS COMMENT -- */"
231
						timers += 1
232
					elif line.find("<PCINT>") != -1:
233
						line = line[:line.find("=")+1] + hex(pcints) + " /* <PCINT> -- DO NOT REMOVE THIS COMMENT -- */"
234
						pcints += 1
235
 
236
			moduleSection[c] = line;
237
			c += 1
238
 
239
	c = 0
240
	for line in applicationSection:
241
		if len(line) > 0:
1258 runge 242
			if line[0] != '#':
1259 runge 243
				if line.find("<TIMER>") != -1:
1258 runge 244
					line = line[:line.find("=")+1] + hex(timers) + " /* <TIMER> -- DO NOT REMOVE THIS COMMENT -- */"
245
					timers += 1
1259 runge 246
				elif line.find("TIMER_NUM_TIMERS=") != -1:
247
					line = "TIMER_NUM_TIMERS=" + hex(timers)
248
				elif line.find("NUMBER_OF_MODULES=") != -1:
249
					line = "NUMBER_OF_MODULES=" + hex(len(modules))
1258 runge 250
				elif line.find("<PCINT>") != -1:
251
					line = line[:line.find("=")+1] + hex(pcints) + " /* <PCINT> -- DO NOT REMOVE THIS COMMENT -- */"
252
					pcints += 1
1259 runge 253
				elif line.find("PCINT_NUM_PCINTS=") != -1:
254
					line = "PCINT_NUM_PCINTS=" + hex(pcints)
819 migan 255
		applicationSection[c] = line;
256
		c += 1
257
 
258
	config_inc = open('config.inc', 'w')
259
 
260
	for line in applicationSection:
261
		config_inc.write(line + "\n")
262
 
263
	for moduleName, moduleSection in moduleSections.iteritems():
264
		for line in moduleSection:
265
			config_inc.write(line + "\n")
266
 
267
	config_inc.close()
268
 
269
	print "Update of config.inc complete"
270
 
271
 
272
def compileSourcesFile():
273
	print "Compiling sources.inc..."
274
 
275
	uniqueSet = []
1983 linlun 276
	uniqueSet2 = []
1991 linlun 277
	if os.path.isfile("src/libraries.list.template"):
278
		libraries_list_template = open('src/libraries.list.template', 'r')
279
		libraries_list_template_lines = libraries_list_template.readlines()
280
		libraries_list_template.close()
819 migan 281
 
282
	sources_list_template = open('src/sources.list.template', 'r')
283
	sources_list_template_lines = sources_list_template.readlines()
284
	sources_list_template.close()
1991 linlun 285
	if os.path.isfile("src/libraries.list.template"):
286
		for libraries_list_template_line in libraries_list_template_lines:
287
			line =libraries_list_template_line.strip("\n").strip(" ")
288
			if len(line) > 0:
289
				if line[0] != '#':
290
					uniqueSet2.append(line)
819 migan 291
 
292
	for sources_list_template_line in sources_list_template_lines:
847 migan 293
		line = sources_list_template_line.strip("\n").strip(" ")
294
		if len(line) > 0:
295
			if line[0] != '#':
296
				uniqueSet.append(line)
819 migan 297
 
298
	modules = getLocalModules()
299
 
300
	for moduleName in modules:
301
		sources_list = open(localmoddir + "/" + moduleName + "/sources.list", 'r')
302
		sources_list_lines = sources_list.readlines()
303
		sources_list.close()
304
 
1993 linlun 305
		if os.path.isfile(localmoddir + "/" + moduleName + "/libraries.list"):
306
			libraries_list = open(localmoddir + "/" + moduleName + "/libraries.list", 'r')
307
			libraries_list_lines = libraries_list.readlines()
308
			libraries_list.close()
309
 
310
			for libraries_list_line in libraries_list_lines:
311
				line = libraries_list_line.strip("\n").strip(" ")
312
				if len(line) > 0:
313
					if line[0] != '#':
314
						uniqueSet2.append("../../../module/" + moduleName + line)
819 migan 315
		for sources_list_line in sources_list_lines:
847 migan 316
			line = sources_list_line.strip("\n").strip(" ")
317
			if len(line) > 0:
318
				if line[0] != '#':
319
					uniqueSet.append(line)
320
 
819 migan 321
 
322
	sourcesString = "SOURCES = "
323
 
324
	#FIXME: Make uniqueSet actually unique
325
 
326
	for line in uniqueSet:
327
		sourcesString += line + " "
1983 linlun 328
	sourcesString += "\n"
329
	sourcesString += "LDLIBS = "
1993 linlun 330
	for line in uniqueSet2:
331
		sourcesString += line + " "
819 migan 332
	sources_inc = open('sources.inc', 'w')
333
	sources_inc.write(sourcesString.strip(" ") + "\n")
334
	sources_inc.close()
335
 
336
	print "Creation of sources.inc complete"
337
 
338
def regenerateModules():
339
	print "Regenerating modules..."
836 migan 340
	print ""
819 migan 341
	compileSourcesFile()
836 migan 342
	print ""
819 migan 343
	compileMainFile()
836 migan 344
	print ""
819 migan 345
	updateConfigFile()
836 migan 346
	print ""
819 migan 347
	print "Regenerating modules complete"
836 migan 348
	print ""
819 migan 349
 
2003 linlun 350
def listUsedModules():
351
	print "Listing modules..."
352
	print ""
353
	getAllModuleIdsFromFile()
354
	print ""
355
	print "Listing modules complete"
356
	print ""
2006 linlun 357
 
358
def listUsedNodes():
359
	print "Listing nodes..."
360
	print ""
361
	getAllNodesFromFile()
362
	print ""
363
	print "Listing nodes complete"
364
	print ""
819 migan 365
 
366
def addModule(moduleName):
367
	print "Trying to add module " + moduleName
368
 
369
	try:
1935 arune 370
		# the following creates symlinks to <path to modulemanager>/../../EmbeddedSoftware/AVR/module
371
		# and <path to modulemanager> is an absolute path which makes the symlink similar to this:
372
		# act_dimmer230 -> /home/arune/Documents/HomeAutomation/PcSoftware/scripts/../../EmbeddedSoftware/AVR/module/act_dimmer230
373
		#os.symlink(moddir + "/" + moduleName, localmoddir + "/" + moduleName)
374
		# instead symlink to relative path instead
375
		os.symlink("../../../module/" + moduleName, localmoddir + "/" + moduleName)
820 migan 376
		print "Added module successfully"
819 migan 377
	except OSError, (errno, strerror):
378
		if errno == 17:
379
			print "A link, file or directory named " + moduleName + " is already present in the modules directory, not linking"
380
		else:
381
			raise
382
 
383
	print ""
384
 
385
	regenerateModules()
386
 
387
 
824 migan 388
def delModule(moduleName):
389
	print "Trying to remove module " + moduleName
390
 
391
	try:
392
		os.unlink(localmoddir + "/" + moduleName)
393
		print "Removed module successfully"
394
	except OSError, (errno, strerror):
395
		if errno == 2:
396
			print "No such " + moduleName + " present in the modules directory, not unlinking"
397
		else:
398
			raise
399
 
400
	print ""
401
 
402
	regenerateModules()
403
 
852 migan 404
def createFile(moduleName, templateFileName, moduleFileName):
405
	print "Creating " + moduleName + "/" + templateFileName + "..."
406
	template_file = open(moddir + "/template/" + templateFileName, 'r')
407
	lines = template_file.readlines()
408
	template_file.close()
824 migan 409
 
852 migan 410
	module_file = open(moddir + "/" + moduleName + "/" + moduleFileName, 'w')
411
 
412
	for line in lines:
413
		line = line.replace("<template>", moduleName)
414
		line = line.replace("<TEMPLATE>", moduleName.upper())
415
 
416
		module_file.write(line)
417
 
418
	module_file.close()
419
 
420
def newModule(moduleName):
421
	print "Creating " + moddir + "/" + moduleName + " directory..."
422
	os.mkdir(moddir + "/" + moduleName + "/")
423
 
424
	createFile(moduleName, "config.inc.template", "config.inc.template")
425
	createFile(moduleName, "sources.list", "sources.list")
426
	createFile(moduleName, "template.h", moduleName + ".h")
427
	createFile(moduleName, "template.c", moduleName + ".c")
1106 linlun 428
	createFile(moduleName, "template_eeprom.h", moduleName + "_eeprom.h")
852 migan 429
 
819 migan 430
def usage():
836 migan 431
	print "Syntax: ./ModuleManager [options]"
819 migan 432
	print "Options:"
836 migan 433
	print "  --help               Print this help"
434
	print "  --regenerate         Regenarate modules and files"
435
	print "  --list               List avalible and installed modules"
436
	print "  --add=<module name>  Adds a module to the application"
437
	print "  --del=<module name>  Removes a module from the application"
852 migan 438
	print "  --new=<module name>  Creates a new module from the module template"
2003 linlun 439
	print "  --modules            Lists all used modules in your personal folder"
2006 linlun 440
	print "  --nodes              Lists all nodes in your personal folder"
819 migan 441
	print ""
442
 
443
 
444
def main():
445
	try:
2006 linlun 446
		opts, args = getopt.getopt(sys.argv[1:], "hlrcmn", ["help", "list", "modules", "nodes", "regenerate", "add=", "del=", "new="])
819 migan 447
	except getopt.GetoptError, err:
448
		# print help information and exit:
449
		print str(err) # will print something like "option -a not recognized"
450
		usage()
451
		sys.exit(2)
825 migan 452
 
453
	if len(sys.argv) == 1:
454
		usage()
455
		sys.exit()
456
 
819 migan 457
	for o, a in opts:
885 migan 458
		if o in ("-c"):
836 migan 459
			modules = getModules()
824 migan 460
 
885 migan 461
			for module in modules:
462
				print module
463
 
464
		elif o in ("-l", "--list"):
465
			modules = getModules()
836 migan 466
			print "Available modules"
467
			print "================="
468
			for module in modules:
469
				print module
470
 
885 migan 471
 
472
			if os.path.exists(localmoddir):
473
				print ""
836 migan 474
 
885 migan 475
				modules = getLocalModules()
836 migan 476
 
885 migan 477
				print "Modules used in this application"
478
				print "================================"
479
				for module in modules:
480
					print module
481
 
819 migan 482
		elif o in ("-h", "--help"):
483
			usage()
484
			sys.exit()
824 migan 485
 
819 migan 486
		elif o in ("-r", "--regenerate"):
487
			regenerateModules()
824 migan 488
 
2003 linlun 489
		elif o in ("-m", "--modules"):
490
			listUsedModules()
2006 linlun 491
 
492
		elif o in ("-n", "--nodes"):
493
			listUsedNodes()
2003 linlun 494
 
819 migan 495
		elif o in ("--add"):
496
			if len(a) == 0:
497
				print "No modulename specified"
498
				usage()
499
				sys.exit()
500
 
501
			if a not in getModules():
502
				print a + " is not a recognized module name"
503
				sys.exit()
504
 
505
			addModule(a)
824 migan 506
 
507
		elif o in ("--del"):
508
			if len(a) == 0:
509
				print "No modulename specified"
510
				usage()
511
				sys.exit()
512
 
513
			if a not in getModules():
514
				print a + " is not a recognized module name"
515
				sys.exit()
516
 
517
			delModule(a)
518
 
852 migan 519
		elif o in ("--new"):
520
			if len(a) == 0:
521
				print "No modulename specified"
522
				usage()
523
				sys.exit()
524
 
525
			if a in getModules():
526
				print a + " already exists"
527
				sys.exit()
528
 
529
			newModule(a)
530
 
819 migan 531
		else:
532
			assert False, "unhandled option"
533
 
534
 
535
if __name__ == "__main__":
536
	main()
537