You are getting into the overall problem of occupancy detection. There are no easy answers. Some solutions are:
- Light detection. IR or visible light detectors are put under the track in various places. Either some ambient illumination is assumed, or IR LEDs are put overhead. Rolling stock on the track is detected by the shadow it casts.
This has the advantage of working with any rolling stock without modification, but is susceptible to noise, changes in ambient illumination, and has problems with steady state levelling. Accumulated dirt is a never-ending problem. It also only measures occupancy at specific points.
- Current sensing. This measures the current draw from different sections of track. Some friends of mine are into model railroading, and I designed them a advanced DCC current sensor. It worked so well that I even made a product out of it.
Advantages are that it senses whole sections of track regardless of where the rolling stock is. Problems are that unpowered cars aren't sensed unless you put deliberate resistors across wheel sets. 10 kΩ is sufficient for the OC1.
- Magnetic sensing. This is probably the least popular from what I can tell.
It doesn't have the problem of adjusting to the ambient level as light detection does, but not all cars have a sufficiently large magnetic signature. It also requires more circuitry at each point, and is point-based like the light method.
All these methods as usually employed only tell you something is there, not what is there. The most common method I've seen to know what is where is to track it in clever software. As long as the software initially knows what's where, it can track it as it moves between sensed segments or points. There is a module in JMRI that already does this, and I've seen it work.
You could theoretically have each locomotive pulse a magnet with a unique ID, then detect that with the Hall sensors. However, if I wanted to do that I'd probably use IR pointing down with sensors below the track. That makes both the transmission and detection circuitry simpler.
With good software tracking, you only need occasional identification. I'd look into a combination of the two to keep track of where things are.