Wednesday, September 2, 2015

Read COM Port Dynamically by reading Windows Registry



I encounter issue when I try to develop integration between a Device and Navision by using Microsoft Communications Control, version 6.0.

This OCX tools need specific COM Port number information before opening the port. When the Device connect to USB port, system will assign COM Port number. Normally fixed COM Port number.

CRLF[1] := 13;
CommCtrl.CommPort := 8; // This is Fixed COM Port number
CommCtrl.Settings := '9600,n,8,1';
CommCtrl.InputMode := 0;    // 0 - Text mode, 1 - Binary
CommCtrl.PortOpen := TRUE;
CommCtrl.Output := <your command to Device> + CRLF;

If you have many USB Port, you plug the Device to any port you want. The problem is that every time we plug to certain port, system will assign new COM Port number. For example, you have 2 USB Port on your PC, USB port 1 will assign COM8 and USB Port 2 will assign COM9.

On this situation, we need to get COM Port number dynamically so that we have flexibility when we plug the Device in our PC regardless any USB port.

After checking further, if the Device without assigned Unique Serial Number will not have Fixed COM Port Number.

This is the work-around how to read COM Port dynamically by reading Windows Registry.

REPEAT
  CLEAR(InstanceID);
  CLEAR(PortName);
  CLEAR(DevicePortFound);

gToolsOcx.getRegKeyStringValue('SYSTEM\CurrentControlSet\services\usbser\Enum',FORMAT(I),InstanceID);
  IF (InstanceID <> '') AND (STRPOS(InstanceID,'VID_04B4&PID_E00A') > 0) THEN BEGIN
    gToolsOcx.getRegKeyStringValue('SYSTEM\CurrentControlSet\Enum\' + InstanceID + '\Device Parameters','PortName',PortName);
    IF (PortName <> '') AND (STRPOS(PortName,'COM') > 0) THEN BEGIN
      DevicePortFound := TRUE;
      PortName := COPYSTR(PortName,4);
    END;
  END;

  I += 1;
UNTIL (DevicePortFound) OR (I = 16); //Limitation of CommCtrl: COM1 to COM16


Note:
You have to find out VID (Vendor ID) and PID (Product ID) of the Device. Normally can be found on device's driver file (.inf) or by using usbdeview or usbview tool (free download) to view PID and VID number.

gToolsOcx is OCX object from LS Retail. you may use WSHShell instead to read registry.

No comments:

Post a Comment