How to Send Data to a Device

TWedge V2

Solution: TWedge provides the function WriteToDevice () for this purpose. WriteToDevice () accepts two parameters:

  • The first one specifies the data which should be sent to the device.
  • The second parameter specifies the timeout (in milliseconds) for this operation.

The following example sends two lines of text: The first line prompts the device for accepting the username, the second line sends the username. Each line is terminated by a newline character (\n line feed):

WriteToDevice ("user\n", 1000);
WriteToDevice ("sysadmin\n", 1000);

TWedge V3

Solution: For this purpose TWedge provides the Javascript member function WriteData (). This function exists in two variants with different parameters.:

  • Integer WriteData (Array arrData, Integer nTimeout)
  • Integer WriteData (String sData, Integer nTimeout, String sEncoding = "Latin1")

The following example sends data one time as binary array and one time as string. Inside of a string you can encode a line feed with the escape sequence \n:

var arrSend = [0x48, 0x65, 0x6c, 0x6c, 0x6f]; 
hConn.WriteData (arrSend, 200);
hConn.WriteData ("Hello\n", 1000);
hConn is the actual connection object.

Why Are All Commands Ignored by the Device?

Solution: When using the function WriteToDevice () (or WriteData ()) to send device configuration or initialization commands, please check if a newline or carriage return character is required. This is especially important if the device uses a protocol like TELNET. A newline character is specified by \n.

The following example sends the text "user" followed by a newline to the device:

// TWedge 2:
WriteToDevice ("user\n", 1000);

// TWedge 3:
hConn.WriteData ("user\n", 1000);

Here is a list of common escape sequences:

  • \' Single quotation mark.
  • \" Double quotation mark. Use this escape sequence if you need to specify a " as part of a string.
  • \\ A single backslash character.
  • \b Backspace.
  • \n New-line (line-feed).
  • \r Carriage return. \r in combination with \n is used in DOS systems as sequence for a carriage return and new line. Most likely \n can be used instead.
  • \t Horizontal tab.
  • \f Form feed (for printers).

USB Device Loses Connection When Not Used for a While

Problem: My USB Device (Virtual COM Port) loses connection when not used for a while.

Power management is a common cause of USB-connected device issues. To save power, Windows automatically shuts down the power to USB ports. This may cause problems with auxiliary devices and leads to a connection loss if you don't use the device for a while.

Workaround: Here are some measures, which you can try step by step until the problem disappears:

a) Prevent Windows from Turning Off USB Devices

  1. Open Device Manager by typing device manager in the Start 🡒 Search panel.
  2. In the Device Manager expand the Universal Serial Bus controllers branch, double-click the USB Root Hub device and choose the Power Management tab.
  3. Turn off "Allow the computer to turn off this device to save power" by unchecking the box.
  4. Click the OK button

b) Motherboard: If your BIOS has a setting 'Deep Sleep Control', then disable it.

c) Turn off the "hybrid sleep option" (if available):

  • In Control Panel go to Power Options 🡒 Change plan settings 🡒 Change advanced power settings 🡒 Sleep 🡒 "Allow hybrid sleep" and turn it OFF.

d) Turn off "USB selective suspend" (if available):

  • In Control Panel go to Power options -> Change plan settings 🡒 Change advanced power settings 🡒 USB settings 🡒 "Selective suspend" and disable it.
Especially for virtual COM ports TWedge offers a monitoring option to detect connection losses and automatically reconnect to the device (see TWedge interface options). You can also try these monitoring options.

Keyboard Wedge Does Not Work If Twedge Runs as Service

Problem: Services are running as a separate process without having a user session attached, so Windows can't identify where to send the key strokes.

Solution: You can try if the option “Allow service to interact with desktop” makes a difference but usually you can't use the keystroke simulation if TWedge runs as service.
Workaround: Write to a CSV file (see action templates). The file name could be based on the actual date so you get a new file each day (needs a small modification in the Script).
CSV files can be opened in Excel as well.

Where Can I Find a Detailed User Manual of TWedge?

  • You can open the manual installed along with TWedge with the Help menu in TWedge (F1).
  • You also find a download for the manual in the documentation section of the TWedge download page.
  • The script reference can be opened with [Script Reference] button at the bottom of the script editor (CTRL-E).

SHIFT Key Not Applied to SendKeyStrokes

Problem: You try to send a SHIFT Key (or any other modifier) while reading data from a HID device, but it is not applied to your key strokes.

Solution: Apply a delay before you send some key strokes – see sample code below:

SetDelayCharacter ("#");
SetDelayTime (200);
if ( !SendKeyStrokes ("#{SHIFT+F7}"))
  NotifyWarning("Ignoring keystrokes sent to TWedge. Please set focus to the target application.");
Special instructions must be observed for HID devices – see user manual B.1.5 Send Keystrokes + B.1 USB HID Device.

How Can I Append a Carriage Return to my Data?

You have to modify the script in the OnData or processData event code. Carriage Return can be added via the escape sequence \r (Carriage Return) or \n (Line Feed). In Javascript string concatenation is done with the + operator.

Menu (V2) Configuration - Script Editor - Edit Code: OnData

Menu (V3) Device - Configure - Advanced - Script Editor - Edit Code: onData

Change the following code line and add the + "\n" as shown below:

// V2 (OnData function):
SendKeyStrokes(DATA.replace (/\x00/g, " ") + "\n");

// V3 (processData function):
SendKeyStrokes (sData.replace(/\x00/g, " ") + "{ENTER}")

See the FAQ above for a list of common escape sequences.

JavaScript Commands for Common Operations (processData)

Menu (TWedge V3) Device - Configure - Advanced - Script Editor - Edit Code in "processData"

Remove Carrige Return / Line Feed
sData = sData.replace(/\x0D\x0A/g, "");  // remove CR/LF
Remove leading whitespace
sData = sData.replace(/^\s+/, "");       // trim leading whitespace
Replace characters (via Hex Code)
sData = sData.replace(/\x2E/g, ",");     // replace . => ,
Remove character sequences
sData = sData.replace(/ d/, "");         // remove " d"
Parse a single value from a CSV sequence
// sample data: 200,    177.50,mm   ,01
if (sData.indexOf(',') > 0)
{
  sData = sData.split(',');
  sData = sData[1];  // take 2nd value
  sData = sData.replace(/^\s+/, "");       // trim leading whitespace
}
// result will be 177.50
Parse a numeric value from a fixed data format.
// extract weight from scale data format: [STX] 13400 kg S Gross[CR]
var myRegexp = /^[\x02]\s(\d{1,5})\skg S Gross[\r\n]/;
var match = myRegexp.exec(sData);
if (match && match.length >= 2)
  Print("Weight: " + match[1]); // first group value
else
  Print("Weight does not match data format: [STX] nnnnn kg S Gross[CR]");
Add a time delay
function onHotkey ()
{
  Print("onHotkey!");
  hInstance.Sleep (300); // wait 0.3 secs
  ...
}

How Can I Convert a Decimal (Float) to Integer?

My device sends 123.4 but I need only 123

Modify the script in the OnData event code (Ctrl - E). Replace the code lines with the following:

TWedge V2

var myData = Math.round(DATA).toFixed();
SendKeyStrokes(myData);

TWedge V3

var myData = DataToString(data);
myData = Math.round(myData).toFixed();
SendKeyStrokes(myData);

This code will perform rounding. If you don't need rounding, replace the Math.round with Math.floor.

My balance sends grams but I need kilograms

Change your OnData event code to the following:

TWedge V2

var myData = (parseInt(DATA)/1000).toFixed(3);
SendKeyStrokes(myData);

TWedge V3

var myData = DataToString(data);
myData = (parseInt(myData)/1000).toFixed(3);
SendKeyStrokes(myData);

How to Read Data in a Loop Without Using StartListen?

Given the case you want to access a specific COM port from two scripts, but you can only open it from one script at a time. Therefore, you cannot use StartListen() because this will occupy the port all the time while the script (data collection) is active.

Below we show you how to open the port, read data, and then close the port so that the other script can access it.

  hConn2.Open(funcOnConnectionLost2);

  var arr2Data = null;
  retries2 = 60; // wait maximum 1 minute for data (60 * 1000 ms)
  while (retries2-- > 0)
  {
    try
    {
      Print ("Waiting for data from " + hConn2.Port);
      
      var currData = hConn2.ReadData(100, 1000); // try to read max 100 Bytes in 1 sec
     
      if (arr2Data == null)
        arr2Data = currData; // first data packet
      else
        arr2Data.concat(currData); // subsequent data packet -> append
    }
    catch (err)
    {
      // stop when we have data already (no data packet after successful read) 
      if (arr2Data != null)
        break;
    }
  }

  processData2 (arr2Data);
    
  if (hConn2.IsOpen)
    closeConnection2();    

How to Use a Second Hot Key In TWedge?

You can create another hot key as follows:

  1. Open the Javascript Edtior (CTRL-E)
  2. Copy the existing hot key function (at the end of the script) and rename it to onHotKey2
  3. function onHotkey2 ()
    {
      Print("onHotkey2! ");
    }
    
  4. Register the onHotkey2 function for a specific hot key (e.g., F8) at the beginning of the script (after the generated script block):
  5. hInstance.RegisterHotkey("F8", onHotkey2); 
    
  6. By pressing F8, the second, newly added function should be called.

COM Ports on Citrix/Terminal Server

Problem: TWedge connects to the server, not to the client

Solution: You need to assign (or route) the COM port on the client to a virtual COM port on the server. This is called COM port redirection.

Error Message "Access Is Denied" When Starting TWedge

Problem: When you start TWedge you receive the message "Can't save file 'C:\ProgramData\TEC-IT\TWedge\3.5\twedge.bcopt' Access is denied."

Solution: Verify the permissions on the TWedge directory and the bcopt file for the user account where you see the problem.

C:\ProgramData\TEC-IT\TWedge\3.5

The BCOPT file stores the window settings of TWedge. The starting user account of TWedge must have read/write permissions to this file.

How Can I Setup TWedge 3 to Run As Service

For manual configuration, follow the instructions in the user manual Appendix D: Run TWedge as Service

For scripting these configuration steps (e.g. as part of a custom setup), follow the guide below:

Specify the TWG file that should be automatically opened by the service during startup:

  1. Navigate to the following file:
    C:\ProgramData\TEC-IT\TWedge\3.6\twedge.bcopt
  2. Edit or overwrite this file with your presets.
  3. Enter the full path to the TWG configuration file in the designated XML node:
    <ServiceConfigFile>>C:/Project/MyTWedgeConfig.twg</ServiceConfigFile>
  4. After making changes to this file, if the service is already running, it must be restarted. This can be done using the following commands:
    net stop "TEC-IT TWedge"
    net start "TEC-IT TWedge"

To configure the service to start automatically when the system boots, execute the following command:

sc config "TEC-IT TWedge" start=auto

It's possible to configure the service to allow interaction with the Desktop, although this functionality cannot be guaranteed. Use the following command:

sc config "TEC-IT TWedge" type=interact type=own

All commands must be executed with Admin permissions, e.g. via Admin console.

How to Install TWedge 2.x as Windows Service?

We recommend upgrading to TWedge V3 which already includes a system service. If that is not possible, you can proceed as described below.
  1. Install the Windows Resource Toolkit. You can download it from Microsoft's Website.
  2. Open the Command Line (Start -> Run -> “cmd”), go to the installation directory of the Windows Resource Toolkit and enter the following command:
    Instsrv TWedge "C:\Program Files (x86)\Windows Resource Kits\Tools\srvany.exe".
    Command Line: Installation of Windows Resource Toolkit
  3. Open the registry editor (Start -> Run -> “regedit”) and look for the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\TWedge.
    Registry Editor: TWedge Registry Key
  4. Now add a "Parameters" key with a value called "Application". It contains the path to the executable of TWedge (default: C:\Program Files (x86)\TEC-IT\TWedge2\Bin\TWedge.exe C:\TWedge.twi). The twedge.twi file opens TWedge with the predefined settings!
  5. Registry Editor: Add new key Parameters
  6. Open the properties of the new TWedge service which you can find in the Control Panel -> Administrative Tools -> Services.
  7. Go to the “Log On” tab and make assure that the checkbox “Allow service to Interact with desktop” is activated.
    Services:  TWedge Properties
  8. Run the TWedge service.