NodeMCU boilerplate – add network_message module

During article with ESP and relay we created functions to decode incoming packet and validate messages. I think they should be in boilerplate because we will use them frequently.
Lets add them 🙂

New file is network_message.lua:

local network_message = {}
network_message.validateMessage = function(json)                
    if json == nil or json['protocol'] ~= PROTOCOL or type(json['targets']) ~= 'table' then
        return false

     isTarget = false
     for k,v in pairs(json['targets']) do
        if v == NODE_ID or v == 'ALL' then isTarget = true end

    return isTarget
network_message.decodeMessage = function(message)        
    ok, json = pcall(cjson.decode, message)
    if not ok or not network_message.validateMessage(json) then
        json = nil
    return json

network_message.prepareMessage = function()
    data = {}
    data.protocol = PROTOCOL
    data.node = NODE_ID
    data.chip_id = node.chipid()
    data.event = ''
    data.response = ''
    data.targets = {'ALL'}

    return data
return network_message    

This is giving us two functions, one to decode packet into message and second to prepare message to send.

As for validation see that from now when you specify targets as ALL, all nodes will try to execute event.
Final change is to add

PROTOCOL = "iot:1"

to parameters.


Version 0.2.0 is on GitHub, ready to be downloaded.
There are two samples with functions usage.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s