print "Current project."
proj = projects.primary

PROJECT = r"C:\CoDeSys-Projects\Script-Test.project"

# clean up any open project:
if projects.primary:
   projects.primary.close()
print("--- CleanUp finished. ---")

# create a new project
proj = projects.create(PROJECT)
print("--- Project created. ---")

# add PLC
proj.add("CODESYS Control RTE V3",4096,"0000 0002","3.5.5.40")
print("--- PLC Device Insert. ---")
		 
# Create the IO
 
for dev in proj.get_children():
   if dev.is_device:
      f = open("C:\Users\RO\Desktop\Import.txt", "r")
      for line in f:
         tok = line.split(' ')
         if "(Master)" in tok[1]:
            dev.add(tok[0], DeviceID(64, "0000 0001", "3.5.5.0"))
            subnodes = dev.get_children()
            master = subnodes[len(subnodes) - 1]
         elif "(Slave)" in tok[1]:
            master.add(tok[0], DeviceID(65, "51D_0201001000000001", "3.5.4.0"))
            # subnodes = master.get_children()
            #coupler = subnodes.ilist
         elif "(IO)" in tok[1]:
			objects = master.find('EH-IOCA', True) # Recursive search
			assert(objects and len(objects) == 1, "no object or more than one object with the name EH_IOCA")
			subnodes = objects[0].get_children() # Get all children

	    # Scenario 1: Plug all
	 i = 1
	 for node in subnodes:
		name = "%s %d" % (tok[0], i) # Create name with index
		node.plug(name, 68, "51D_00000001_16 Digital Input_16 Digital Input","0")
		i += 1

	    # Scenario 2: Plug only the first one
	 #if len(subnodes) > 0:
            #subnodes[0].plug(tok[0], 68, "51D_00000001_16 Digital Input_16 Digital Input","0")	


# Save project
proj.save()
			
# Script finished
print("--- Script finished. ---")

