How to parse / route a string of characters?

yagodequay's icon

Hi, I'm having a hard time parsing / routing a 4 and 12-byte message from an inertial sensor. The sensor measures rotation and detects hits. There are two different message structures, one is a "heartbeat" and the other "sensor data".

Example of heartbeat: 02037901 (4-byte)
Example of sensor data: 010081000200014B0057000000 (12-byte)

I have two problems:

1) Any message starting with "02" is a heartbeat message, any message starting with "01" is a sensor data message. How can I distinguish between them? In other words, how can I separate heartbeat messages from data messages?

2) Sensor data message has an identifier in the 3rd and 4th bit: 0001, 0002, 0003, 0004.
This example identifies that chuck: 010081"0002"00014B0057000000
How to I route each of the four identifiers and the subsequent data? I don't care about the data preceding the identifier.

In case you are curious, this is the meaning of each byte:
Byte - Info
0 - Gesture [01] or Heartbeat [02]
1 - Gesture Type (does not matter)
2 - Sequence Number (does not matter)
3, 4 - Gesture Detected Mask (identifier)
5 - Hit Velocity
6, 7 - Wrist Angle (16-bit value)
8, 9 -Arm Vertical Angle (16-bit value)
10, 11 - Arm Horizontal Angle (16-bit value)
12 - Hit Direction

Ernest's icon

Max is not really the ideal language for this.Not knowing what else you want to do, it's difficult to advise the best solution, but generally Max is designed to handle space-delimited lists. So you might be best to explode the string and put spaces between each of the characters, using the itoa object for example, but on the other hand, regular expressions may be better if you have more specific parsing needs.

Peter Ostry's icon

Your input values through [atoi] give you ASCII numbers with spaces between. Insert an ASCII space at each space occurence and go through [itoa] to get your values as lists. You can distribute them according to list lengths and finally group them to 4-digit chunks.

Max Patch
Copy patch and select New From Clipboard in Max.

The patch below does that.

bkshepard's icon

Assuming the 2nd character is always either a 1 or 2, this will allow you to route the two types of messages.

Max Patch
Copy patch and select New From Clipboard in Max.

bkshepard's icon

I *think* this does what you want for both problems.

Max Patch
Copy patch and select New From Clipboard in Max.

yagodequay's icon

Thank you so much ERNEST, PETER OSTRY, BKSHEPARD. I ended up using a combination of [atoi] with a [route]. Definitely a bit cumbersome and it worries me how much latency this adds. Nevertheless, the code is below for future reference.

EDIT: this patch adds around 0.03 ms -- so practically nothing :)

Max Patch
Copy patch and select New From Clipboard in Max.