В момента ресурсът е наличен само на английски

Problem with messages

There are some problems which apears when you want to parse messages from the server. Some of them are easy to solve, others need a little bit more attention. In practice people use format called JSON.

  • #1031
  • 01 Jan 2019

We send and receive messages without any problems. But what if we want to do something with this message? For example we want to wait for a message "play" or "light up" and to turn on our LED Strip,

How to do that?

The first way is to compare the message with specific word.

if msg.payload == "play"

But what will happend if we send "Play" or "PLAY", or "plaY"? It will not catch it. Why? Because it is CaseSensitive, this means that if we compare with lowercase it must be lowercase. We can solve this by modifying the message and make all of it's letters in lowecase.

if msg.payload.lower() == "play"

And if we send only one word it's OK. But in common case there are more than one word. In our case we want to make a game. And in this game we want to have more than one player. So every of the players must send his name, the control which he wants to play and eventually some other things like stats, ratings etc. And you can send it like a simple string for example : 

client.publish("game","UserName Right Rating")

Then the subscriber program have to parse it by " "(space), store it in some structure and go trough all the elements and do some stuffs with them. And we are fine with this. But what happens when the user is new and he doesn't have any Rating or just the user sends an empty string, or put some extra spaces between words. Then the parsing of the arguments will be ruined. 
Because аll of the mess around receiving and parsing messages people has made an specific Format called JSON.

Курсове и занятия включващи този Урок

Този Урок е използван в следните курсове и занятия.

Image for Perfect STEM course. Module 2 - 1D Games with Led strip.
  • 19
  • 0:00
  • 37
Image for Communication and Format of messages
  • 2
  • 0
  • 2
  • 3d_rotation 0