Skip to content

Commit 2cf3f58

Browse files
authored
Update lambda_magic.rst (#4187)
Add some fixes in example code to make it more robust: - Prevent from buffer overflow - Add check on valid character
1 parent bc5c886 commit 2cf3f58

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

cookbook/lambda_magic.rst

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,17 +128,24 @@ With this you can use automations or lambda to set switch or sensor states.
128128
129129
if (readch > 0) {
130130
switch (readch) {
131-
case '\n': // Ignore new-lines
132-
break;
133-
case '\r': // Return on CR
131+
case '\n':
132+
case '\r': // Return on CR or newline
133+
buffer[pos] = 0; // Just to be sure, set last character 0
134134
rpos = pos;
135135
pos = 0; // Reset position index ready for next time
136136
return rpos;
137137
default:
138-
if (pos < len-1) {
138+
if ((pos < len-1) && ( readch < 127 )) { // Filter on <127 to make sure it is a character
139139
buffer[pos++] = readch;
140140
buffer[pos] = 0;
141141
}
142+
else
143+
{
144+
buffer[pos] = 0; // Just to be sure, set last character 0
145+
rpos = pos;
146+
pos = 0; // Reset position index ready for next time
147+
return rpos;
148+
}
142149
}
143150
}
144151
// No end of line has been found, so return -1.

0 commit comments

Comments
 (0)