Operating Environment
Operation has been confirmed in the following environment.
- Windows 10 Build 1809
- Python 3.6.4
- pyserial 3.4
- Python 3.6.4
This is the multi-page printable view of this section. Click here to print...
Operation has been confirmed in the following environment.
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.
# 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()
Class AppPAL
This class inherits from AppBase, interprets the received payload, converts it into usable data, and stores it in a dictionary object.
Parameters with default values are optional.
Name | Type | Default | Description |
---|---|---|---|
port | string | None | Name of the serial port to open e.g., COM3, /dev/ttyUSB0 |
baud | int | 115200 | Baud rate |
tout | float | 0.1 | Timeout duration (in seconds) for serial communication |
sformat | string | Ascii | This value is fixed to Ascii |
autolog | boolean | False | If True, automatically logs interpreted payload to a CSV file |
err | boolean | False | If True, outputs error messages |
ReadSensorData()
This method reads the payload and interprets it according to the TWELITE PAL parent format.
None
If data is successfully read: True
If data could not be read: False
The keys stored in the dictionary object are as follows.
Key | Type | Description |
---|---|---|
ArriveTime | datetime | Time the payload was received |
LogicalID | int | Logical device ID of the end device |
EndDeviceSID | int | Serial number of the end device |
RouterSID | int | Serial number of the first repeater to receive the packet (0x80000000 if the parent directly receives the packet) |
LQI | int | Link quality of received signal |
SequenceNumber | int | Sequence number incremented with each transmission Starts from 1, rolls over to 0 after 65535 |
Sensor | int | Sensor type (fixed at 0x80) |
PALID | int | PAL board ID |
PALVersion | int | PAL board version |
HALLIC | int | State of the Hall IC |
Temperature | float | Temperature (degC) |
Humidity | float | Humidity (%) |
Illuminance | int | Illuminance (lux) |
AccelerationX | list,float | Acceleration on X-axis (g) |
AccelerationY | list,float | Acceleration on Y-axis (g) |
AccelerationZ | list,float | Acceleration on Z-axis (g) |
SamplingFrequency | int | Sampling frequency of acceleration |
EventID | list,int | Cause of event and event ID |
WakeupFactor | list,int | Data on wakeup factors, etc. |
OutputCSV()
Outputs the dictionary object to a CSV file.
None
None
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.
None
Type | Description |
---|---|
Dict | Dictionary object containing the interpreted payload data |
Class MWSerial
This class manages serial port operations such as reading and writing.
Initial values are set and do not need to be specified.
Name | Type | Default | Description |
---|---|---|---|
port | string | None | Name of the serial port to open e.g., COM3, /dev/ttyUSB0 |
baud | int | 115200 | Baud rate |
timeout | float | 0.1 | Timeout duration for serial communication (in seconds) |
parity | int | serial.PARITY_NONE | Specify parity |
stop | int | 1 | Stop bit |
byte | int | 8 | Data bit length |
rtscts | int | 0 | Set to 1 to enable RTS and CTS |
dsrdtr | int | 0 | Set to 1 to enable DSR and DTR |
mode | string | Ascii | This value is fixed to Ascii |
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.
Name | Type | Default | Description |
---|---|---|---|
portname | string | None | Name of the serial port to open (e.g., COM3, /dev/ttyUSB0) Leave unspecified for automatic selection. |
None
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.
Parameter | Description |
---|---|
c | The 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. |
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()
.
process()
may initialize or overwrite the internal payload storage, copy the data immediately.None
Value | Description |
---|---|
true | Interpretation succeeded. Payload is available. |
false | Interpretation failed or is incomplete. |
get_payload()
Returns the payload.
None
Returns the payload portion excluding header and footer as a list of bytes.
reinit()
Explicitly resets the internal state.
None
None
Several internal-use methods are defined. Please refer to the source code for details.
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