Might not be worth it if you’ve got a working solution, but if you need to parse out all values, you can actually do it all in one lambda in a single parse, loop over each split/delimiter, and publish the new values to the relevant sensor.
My example below does something a bit similar (but you’d need to adjust). It does a “double split” of the string. First it splits on ‘,’ and then it splits again on ‘M’ or ‘m’.
- platform: template
name: "test String Splits"
id: test_string_split
icon: mdi:format-text-rotation-none
update_interval: never
#x is like "1M-10,2M-700,3M-100,4M-10,3M70,8M170"
on_raw_value:
then:
- lambda: |-
ESP_LOGD("custom", "text sensor received new value");
std::string item;
std::size_t start = 0, end; // Initialize "start" variable to 0
// Loop until no ',' character is found in "x"
while ((end = x.find(",", start)) != std::string::npos)
{
// Extract substring from "x" starting at "start" and ending at "end"
item = x.substr(start, end - start);
// Split item by "M" to get motor number and movement amount
std::size_t motor_number_pos = item.find_first_of("Mm");
std::string motor_number_str = item.substr(0, motor_number_pos);
std::string movement_amount_str = item.substr(motor_number_pos + 1);
// If motor number and movement amount are not empty, process them
if (!motor_number_str.empty() && !movement_amount_str.empty())
{
int motor_number = std::stoi(motor_number_str);
int movement_amount = std::stoi(movement_amount_str);
ESP_LOGD("custom", "Motor Number: %d, Movement Amount: %d", motor_number, movement_amount);
// Publish movement amount to corresponding template based on motor number
switch (motor_number)
{
case 1: id(m1_last_movement_amount).publish_state(movement_amount); break;
case 2: id(m2_last_movement_amount).publish_state(movement_amount); break;
case 3: id(m3_last_movement_amount).publish_state(movement_amount); break;
case 4: id(m4_last_movement_amount).publish_state(movement_amount); break;
case 5: id(m5_last_movement_amount).publish_state(movement_amount); break;
case 6: id(m6_last_movement_amount).publish_state(movement_amount); break;
case 7: id(m7_last_movement_amount).publish_state(movement_amount); break;
case 8: id(m8_last_movement_amount).publish_state(movement_amount); break;
default: break;
}
}
// Set "start" to position after ',' character found
start = end + 1;
}