This is the multi-page printable view of this section. Click here to print...

Return to the regular view of this page

As of 2025-07-24

Miscellaneous

Miscellaneous items
Manuals for other products and services

1 - TWELITE PAL/CUE/ARIA Script

Python script for processing data from devices such as TWELITE SENSE PAL
The TWELITE PAL Script is a sample script to interpret and log data from TWELITE SENSE PAL (Sensor PAL), TWELITE CUE (acceleration and magnetic sensors), and TWELITE ARIA (temperature/humidity and magnetic sensors).

1.1 - How to Use

How to use the TWELITE PAL Script
Instructions for using TWELITE PAL with MONOSTICK.

Preparing Your PC

  1. Extract the downloaded archive to an easy-to-find folder (for example, C:).

  2. Download and install Anaconda suitable for your PC environment from the following webpage.
    https://www.anaconda.com/download/
    If you do not want to install Anaconda, refer to “If Not Installing Anaconda”.

  3. Open Anaconda Prompt and run the following command to install pyserial. (On Windows, open Anaconda Prompt from the Start menu → Anaconda3.)

    
    
    pip install pyserial

If Not Installing Anaconda

The installation steps below are an example for Windows OS. Please refer to the documentation of each library and install the necessary software and libraries.

  1. Download and install the latest version of Python from the following page.
    https://www.python.org/downloads/

    At that time, make sure to check the box surrounded by the frame in the figure below
    or add Python’s installation directory to your PATH.

  2. Open Command Prompt and enter the following command to install pyserial.

    
    
    pip install pyserial

Preparing TWELITE PAL

  1. Connect SENSE PAL to BLUE PAL/RED PAL.
  2. Insert a coin cell battery (CR2032) into the battery holder of BLUE PAL/RED PAL.

Preparing MONOSTICK

  1. Rewrite the MONOSTICK application (App_PAL-Parent-xxx-MONOSTICK.bin).
  2. Reset MONOSTICK or reconnect it to the USB port.

Running the Script

If the COM port of MONOSTICK is COM6, run the following command in Anaconda Prompt to output data as shown below. (It cannot be started if Teraterm is connected.)


cd C:\PAL_Script
python PAL_Script.py -t COM6
*** MONOWIRELESS App_PAL_Viewer 1.1.0 ***
  *** Open COM6 ***
ArriveTime : 2021/03/05 09:43:28.880
LogicalID : 1
EndDeviceSID : 10B6465
RouterSID : No Relay
LQI : 180 (-35.50 [dBm])

To exit the script, press Ctrl+C in Anaconda Prompt.

Script Arguments

You can use the following arguments when running the script.

Argument: -h

Function: Display a list of command line arguments
Example: python PAL_Script.py -h

Argument: -t

Function: Specify the port name used by MONOSTICK
Setting: MONOSTICK port name
Default: COM3 on Windows, /dev/ttyUSB0 on Linux, etc.
Example: python PAL_Script.py -t COM6

Argument: -b

Function: Specify the baud rate of the port used by MONOSTICK
Setting: MONOSTICK baud rate
Default: 115200
Example: python PAL_Script.py -t COM6 -b 115200

Argument: -l

Function: Output log in CSV format
Example: python PAL_Script.py -t COM6 -l
Note: A CSV file will be generated in the same directory.
The file name will be AppPAL_SerialNumber_PAL_YYYYMMDD.csv

The CSV file columns are explained in the table below.

HeaderDescriptionUnit
LogicalIDLogical Device ID of the end device-
EndDeviceSIDSerial number of the end device-
LQILQI-
PowerPower supply voltagemV
ADC*VoltagemV
HALLICMagnetic sensor state-
TemperatureTemperature
HumidityHumidity%
IlluminanceIlluminanceLux

AccelerationX
AccelerationY
AccelerationZ

Accelerationg

1.2 - Source Files

Source files for the TWELITE PAL Script

Operating Environment

Operation has been confirmed in the following environment.

  • Windows 10 Build 1809
    • Python 3.6.4
      • pyserial 3.4

1.2.1 - PAL_Script.py

Execution script for TWELITE PAL Script
This script initializes and runs the code that reads data from MONOSTICK and outputs the interpreted data to standard output.

How to Read Data

The example below checks whether data has been received from MONOSTICK and, if so, passes it to the Main() function.

from apppal import AppPAL

...

def mainloop(PAL):
	# Check if the user-defined Main function can be imported.
	try:
		from Main_user import Main
	except:
		mainflag = False
	else:
		mainflag = True

	# Check whether data is available
	if PAL.ReadSensorData():
		if mainflag:
			# If Main was imported, pass the PAL object to Main()
			Main(PAL)
		else:
			# If Main was not imported, display the data on the console.
			PAL.ShowSensorData()

...

if __name__ == '__main__':
...

	try:
		PAL = AppPAL(port=options.target, baud=options.baud, tout=0.05, sformat=options.format, autolog=bEnableLog, err=bEnableErrMsg, stdinput=options.stdinp, Logfilename=options.file)
	except:
		print("Cannot open \"AppPAL\" class...")
		exit(1)

	while True:
		try:
			mainloop(PAL)
		except KeyboardInterrupt:
			break

	del PAL

First, create an AppPAL object. Since serial port settings are configured at instantiation, pass them as arguments.

PPAL = AppPAL(port=options.target, baud=options.baud, tout=0.05, sformat=options.format, autolog=bEnableLog, err=bEnableErrMsg, stdinput=options.stdinp, Logfilename=options.file)

Next, in the mainloop(), call ReadSensorData() to check whether serial data has arrived. If it returns True, pass the interpreted result to Main().

def mainloop(PAL):
	# Check if the user-defined Main function can be imported.
	try:
		from Main_user import Main
	except:
		mainflag = False
	else:
		mainflag = True

	# Check whether data is available
	if PAL.ReadSensorData():
		if mainflag:
			# If Main was imported, pass the PAL object to Main()
			Main(PAL)
		else:
			# If Main was not imported, display the data on the console.
			PAL.ShowSensorData()

For details on the dictionary structure received, refer to this section.

1.2.2 - Main_user.py

This code describes the processing performed after reading data in the TWELITE PAL Script
This code contains the main processing performed after reading data. Here, it outputs the interpreted data to the console when data is received.
# Write the desired processing inside this function
def Main(PAL=None):
	# Check if the passed variable is an instance of AppPAL
	if isinstance(PAL, AppPAL):
		sns_data = PAL.GetDataDict()

		# Reception time
		print('Receive Time: ', end='')
		if isinstance(sns_data['ArriveTime'], datetime.datetime):
			print(sns_data['ArriveTime'].strftime('%Y/%m/%d %H:%M:%S') + '.%03d'%(sns_data['ArriveTime'].microsecond/1000))
		else:
			print(sns_data['ArriveTime'])

		# Logical Device ID
		print('Logical ID: 0x%02X'%sns_data['LogicalID'])
		# Serial Number
		print('Serial ID: 0x' + sns_data['EndDeviceSID'])
		# Power Voltage
		print('Power: %d mV' % sns_data['Power'])

		# Check the sensor name
		sname  = PAL.GetSensorName()

		# If the sensor name is PAL, output model name such as PAL/ARIA/CUE
		if sname == 'PAL':
			pid = PAL.GetPALName()
			print('Sensor: ' + pid )
		else:
			print('Sensor: ' + sname )

		# Analog sensor mode (App_Tag)
		if sname == 'Analog':
			print('ADC1: %d mV'%sns_data['ADC1'])
			print('ADC2: %d mV'%sns_data['ADC2'])
		else:
			# Hall IC
			if 'HALLIC' in sns_data.keys():
				print('HALLIC: %d'%sns_data['HALLIC'])

			# Temperature
			if 'Temperature' in sns_data.keys():
				print('Temperature: %.02f degC'%sns_data['Temperature'])

			# Humidity
			if 'Humidity' in sns_data.keys():
				print('Humidity: %.02f %%'%sns_data['Humidity'])

			# Illuminance
			if 'Illuminance' in sns_data.keys():
				print('Illuminance: %f lux'%sns_data['Illuminance'])

			# Pressure
			if 'Pressure' in sns_data.keys():
				print('Pressure: %f hPa'%sns_data['Pressure'])

			# Acceleration
			if 'AccelerationX' in sns_data.keys():
				print('X: ', end='')
				print(sns_data['AccelerationX'])
				print('Y: ', end='')
				print(sns_data['AccelerationY'])
				print('Z: ', end='')
				print(sns_data['AccelerationZ'])

			# Gyroscope
			if 'Roll' in sns_data.keys():
				print('Roll: ', end='')
				print(sns_data['Roll'])
				print('Pitch: ', end='')
				print(sns_data['Pitch'])
				print('Yaw: ', end='')
				print(sns_data['Yaw'])

			# Color sensor
			if 'Red' in sns_data.keys():
				print('Red: ', end='')
				print(sns_data['Red'])
				print('Green: ', end='')
				print(sns_data['Green'])
				print('Blue: ', end='')
				print(sns_data['Blue'])
				print('IR: ', end='')
				print(sns_data['IR'])


		print()

1.2.3 - MNLib

Part of the TWELITE PAL Script responsible for reading and interpreting serial data
This folder contains the part of the TWELITE PAL Script responsible for reading and interpreting serial data.

1.2.3.1 - apppal.py

Class that interprets the read byte sequence and stores it in a dictionary object

Class AppPAL

This class inherits from AppBase, interprets the received payload, converts it into usable data, and stores it in a dictionary object.

Parameters for Definition

Parameters with default values are optional.

NameTypeDefaultDescription
portstringNone

Name of the serial port to open

e.g., COM3, /dev/ttyUSB0

baudint115200Baud rate
toutfloat0.1Timeout duration (in seconds) for serial communication
sformatstringAsciiThis value is fixed to Ascii
autologbooleanFalseIf True, automatically logs interpreted payload to a CSV file
errbooleanFalseIf True, outputs error messages

ReadSensorData()

This method reads the payload and interprets it according to the TWELITE PAL parent format.

Parameters

None

Return Value

If data is successfully read: True If data could not be read: False

The keys stored in the dictionary object are as follows.

KeyTypeDescription
ArriveTimedatetimeTime the payload was received
LogicalIDintLogical device ID of the end device
EndDeviceSIDintSerial number of the end device
RouterSIDint

Serial number of the first repeater to receive the packet

(0x80000000 if the parent directly receives the packet)

LQIintLink quality of received signal
SequenceNumberint

Sequence number incremented with each transmission

Starts from 1, rolls over to 0 after 65535

SensorintSensor type (fixed at 0x80)
PALIDintPAL board ID
PALVersionintPAL board version
HALLICintState of the Hall IC
TemperaturefloatTemperature (degC)
HumidityfloatHumidity (%)
IlluminanceintIlluminance (lux)
AccelerationXlist,floatAcceleration on X-axis (g)
AccelerationYlist,floatAcceleration on Y-axis (g)
AccelerationZlist,floatAcceleration on Z-axis (g)
SamplingFrequencyintSampling frequency of acceleration
EventIDlist,intCause of event and event ID
WakeupFactorlist,intData on wakeup factors, etc.

OutputCSV()

Outputs the dictionary object to a CSV file.

Parameters

None

Return Value

None

1.2.3.2 - appbase.py

Base class for serial data interpretation

class AppBase

This code provides a base class implementing common functions required for all TWELITE APPS. It includes operations such as opening and closing the serial port, reading serial data, and writing to log files.
The derived class apppal.py interprets the received byte sequence, stores the data in a dictionary object, and returns it to the main function.

GetDataDict()

Interprets the payload and returns a dictionary object containing the data.

Parameters

None

Return Value

TypeDescription
DictDictionary object containing the interpreted payload data

1.2.3.3 - mwSerial.py

Class for managing serial port operations

Class MWSerial

This class manages serial port operations such as reading and writing.

Parameters for Definition

Initial values are set and do not need to be specified.

NameTypeDefaultDescription
portstringNone

Name of the serial port to open

e.g., COM3, /dev/ttyUSB0

baudint115200Baud rate
timeoutfloat0.1Timeout duration for serial communication (in seconds)
parityintserial.PARITY_NONESpecify parity
stopint1Stop bit
byteint8Data bit length
rtsctsint0Set to 1 to enable RTS and CTS
dsrdtrint0Set to 1 to enable DSR and DTR
modestringAsciiThis value is fixed to Ascii

SerialSelect

Searches for serial ports connected to the PC and prompts the user to select one.

If only one port is available, it is automatically selected.
If no ports are found, None is returned.
If a port name is passed as an argument, that port will be used.

Parameters

NameTypeDefaultDescription
portnamestringNone

Name of the serial port to open (e.g., COM3, /dev/ttyUSB0)

Leave unspecified for automatic selection.

Return Value

None

1.2.3.4 - parseFmt.py parseFmt_*.py

TWELITE serial format parser

class FmtBase

The base class for format parsers, defining common procedures. Subclasses such as FmtAscii (ASCII format) and FmtBinary (binary format) inherit from this.

Format parsers are designed for serial input. For ASCII format, interpretation is done per line; for binary format, it is done byte by byte. Once the input sequence satisfies the defined header, footer, and checksum, the parsing is considered complete and the content excluding the header and footer (the payload) is stored.

process(c)

Interprets the input string. After interpretation, if is_complete() returns true, the interpretation succeeded and the payload can be obtained via get_payload(). Since subsequent process() calls may invalidate the payload, it should be retrieved immediately after completion.

To interpret another sequence, call process() again.

Parameters

ParameterDescription
cThe input sequence to interpret. Supports both single-byte and sequence-level inputs. For single-byte input: int (ASCII code), str, bytes, or list of length 1. For sequence-level input: list, str, or bytes representing a complete sequence. Sequences that are incomplete or contain multiple series cannot be processed.

Return Value

None

is_comp()

Called after process() to indicate whether format interpretation is complete. If true, the payload can be retrieved using get_payload() or get_payload_in_str().

Parameters

None

Return Value

ValueDescription
trueInterpretation succeeded. Payload is available.
falseInterpretation failed or is incomplete.

get_payload()

Returns the payload.

Parameters

None

Return Value

Returns the payload portion excluding header and footer as a list of bytes.

reinit()

Explicitly resets the internal state.

Parameters

None

Return Value

None

Other methods

Several internal-use methods are defined. Please refer to the source code for details.

Code Examples

Sequence-level Interpretation

Interprets a str sequence a and stores the payload in pay. For example, pay will contain [ 0x78, 0x80, 0x01, ... , 0x00 ].

import parseFmt_Ascii

fmta=parseFmt_Ascii.FmtAscii()
a = ':7880010F0F0380030002800200DF'
pay = []

fmta.process(a)

if fmta.is_comp():
    pay = fmta.get_payload()

Byte-by-byte Interpretation

For binary sequence b, parsing is performed one byte at a time using the process() method. When the end byte 0x04 is input, parsing completes and the payload is stored in pay.

import parseFmt_Binary

fmtb=parseFmt_Binary.FmtBinary()
b = [0xA5, 0x5A, 0x80, 0x05, 0x78, 0x00, 0x11, 0x22, 0x33, 0x78, 0x04]
pay = []

for x in b:
  fmtb.process(x)

  if fmtb.is_comp():
    pay = fmtb.get_payload()
    break

2 - TWE Programmer

A TWELITE flashing and terminal tool for Windows

TWE Programmer is a utility for flashing firmware to TWELITE series wireless microcontrollers and connecting to the terminal.

Installation

Download TWE-Programmer.exe from our website and copy it to any location.

Operating Environment

Developed and tested under the following environment:

VersionOS.NET
v3.8.1Windows 10 Pro 1809v4.0.30319

Dependencies

FTDI Driver

You may need to install the FTDI serial converter IC driver used in TWELITE R and MONOSTICK.

Launch

Launch TWEProgrammer.exe by double-clicking it, like any standard application.

Example screen after startup

Example screen after startup

Flashing Firmware

Selecting the COM Port

Select the COM port connected to TWELITE R or MONOSTICK with a TWELITE module.

If TWELITE is properly recognized, the serial number printed on its surface will be displayed.

Selecting the Firmware

Press the button to select a file or drag a .bin file to load and begin firmware flashing. If a previously selected file still exists, you can press the “(Re)Write” button to reflash it.

Example screen during flashing

Example screen during flashing

If “Connect to Terminal” is checked, TWELITE will be automatically reset and the terminal screen will be displayed.

Example screen after flashing

Example screen after flashing

Options

Slow Write (Safe Mode)

Applies safer settings. Usually not needed.

Verify

Verifies the data after flashing.

Connecting to the Terminal

Baud Rate Configuration

The baud rate can be changed from the “Terminal” section. The setting uses 8N1 format.

Connecting the Terminal

To use only the terminal without flashing, check “Connect to Terminal” and press “Reset TWELITE”.

Disconnecting the Terminal

Click “Disconnect Terminal” or press Alt+I.

Shortcuts

FunctionKey CombinationRemarks
Disconnect TerminalAlt+IOr the “Disconnect Terminal” button
Connect Terminal (normal)Alt+NConnect without reset
Connect Terminal (reset)Alt+RConnect with reset
Hardware ResetAlt+R
Send +++Alt+POr the + + + button.
Used to enter interactive mode
Change Terminal Display ColorAlt+GOnly when connected
Clear Terminal DisplayAlt+LOr the clear button
Copy Display ContentsAlt+COr the copy button
Paste from ClipboardAlt+V
Open Firmware FileCtrl+Alt+ODisabled while connected to terminal
Reflash FirmwareCtrl+Alt+W
Erase FirmwareCtrl+Alt+EDisabled while connected to terminal
Change Terminal Rendering ModeCtrl+Alt+DSwitch to double-buffer mode.
Cursor hidden, may cause rendering issues
Exit TWE ProgrammerCtrl+Alt+X

The following escape sequences are also supported:

FunctionKey Combination
Move cursor up one lineESC[A]
Move cursor to beginning of lineESC[G]
Move cursor to home positionESC[H
Clear screenESC[2J
CR / Move cursor to beginning of line\r

Logging

To log terminal input and output, check “Save Terminal Log” before connecting.

A log file named twelog.log will be saved in append mode in the same folder as TWE-Programmer.exe.

To obtain multiple logs simultaneously, install TWE-Programmer.exe in separate folders.

Input/Output Format

The following format is used for saving:

CharacterDescription
Printable ASCII characters (excluding backslash \)excluding backslash \
Backslash \ (0x5C)converted to \\
Othersrepresented in hexadecimal

Input from PC to TWELITE is enclosed in escape sequences to distinguish it from TWELITE’s output.

  • Input start: ESC[7m]
  • Input end: ESC[0m]

Settings

Several settings can be configured via command-line options at startup.

ParameterDescription
-vEnable verify
-cDisable auto-connect after startup
-sEnable slow write (safe mode)
-DEnable double buffer
Reduces flickering but hides cursor and imposes limitations
-g [num]
--color [num]
Specify text color (0 for none)
0: Pink/Wine
1: Orange/Black
2: Green/Black
3: Black/White
4: White/Wine
5: Wine/Yellow
6: White/Blue
[file]Specify firmware file to load

You can create a program shortcut and add command-line options via its properties.

Example of the Properties dialog

Example of the Properties dialog

Error Output

If an error occurs during flashing, the screen will turn pink as shown below. Check the connection and press “(Re)Write”.

Example of flashing failure

Example of flashing failure

Errors also occur if another software is using the COM port. Close the software using the port, then press “Recheck Connection”.

Example of connection failure

Example of connection failure