sanitycheck: Improve handling of duplicate devices

Some devices have multiple serial ports, which show as duplicates in the
hardware map. This doesn't work well when using --generate-hardware-map
to regenerate an existing map. E.g. nrf5340pdk_nrf5340_cpuapp by default
prints to the 3rd of 3 devices. If it shows up on /dev/ttyACM0,
/dev/ttyACM1, and /dev/ttyACM2, printout will come on /dev/ttyACM2.
nrf9160dk_nrf9160 also provides 3 devices, but prints to the 1st.

This patch sorts the devices by the serial port and matches multiple
duplicate entries one-to-one to retain the ordering. This way, the
correct device can be given the platform name and the others can be kept
as "unknown" so that --device-testing understands correctly
1) that there is only one device (not 3)
2) where the serial output will come.

Signed-off-by: Øyvind Rønningstad <oyvind.ronningstad@nordicsemi.no>
diff --git a/scripts/sanity_chk/sanitylib.py b/scripts/sanity_chk/sanitylib.py
index a344470..798964f 100644
--- a/scripts/sanity_chk/sanitylib.py
+++ b/scripts/sanity_chk/sanitylib.py
@@ -3450,14 +3450,17 @@
         if os.path.exists(hwm_file):
             with open(hwm_file, 'r') as yaml_file:
                 hwm = yaml.load(yaml_file, Loader=yaml.FullLoader)
+                hwm.sort(key=lambda x: x['serial'] or '')
+
                 # disconnect everything
                 for h in hwm:
                     h['connected'] = False
                     h['serial'] = None
 
+                self.detected.sort(key=lambda x: x['serial'] or '')
                 for d in self.detected:
                     for h in hwm:
-                        if d['id'] == h['id'] and d['product'] == h['product']:
+                        if d['id'] == h['id'] and d['product'] == h['product'] and not h['connected'] and not d.get('match', False):
                             h['connected'] = True
                             h['serial'] = d['serial']
                             d['match'] = True