li.rudin.arduino.api.message.MessageParser Maven / Gradle / Ivy
package li.rudin.arduino.api.message;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageParser
{
/**
* Local logger
*/
private static final Logger logger = LoggerFactory.getLogger(MessageParser.class);
/**
* Parses a message from a byte array
* @param bytes
* @param length
* @return
*/
public static MessageParseResult parse(String msg)
{
byte[] bytes = msg.getBytes();
return parse(bytes, bytes.length);
}
/**
* Parses a message from a byte array
* @param bytes
* @param length
* @return
*/
public static MessageParseResult parse(byte[] bytes, int length)
{
ArrayList list = new ArrayList<>();
int cosumedBytes = 0;
logger.debug("Parsing {} bytes", length);
String str = new String(bytes, 0, length);
if (!str.contains(Message.OUTER_DELIM))
//No delims found, skip potential partial message
return new MessageParseResult(list, 0);
String[] parts = str.split("["+Message.OUTER_DELIM+"]");
logger.debug("Got {} parts", parts.length);
for (String part: parts)
{
String[] keyValue = part.split("["+Message.INNER_DELIM+"]");
if (keyValue.length > 2 || !part.contains(Message.INNER_DELIM))
{
logger.debug("invalid delimiters in part: '{}' message: '{}'", part, str);
continue;
}
Message message = null;
if (keyValue.length == 2)
message = new Message(keyValue[0], keyValue[1]);
else if (keyValue.length == 1)
message = new Message(keyValue[0], "");
logger.debug("Got message: {}", message);
cosumedBytes += part.length() + Message.OUTER_DELIM.length();
list.add(message);
}
return new MessageParseResult(list, cosumedBytes);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy