parse an API link message as a server in C (Arduino IDE)

亡梦爱人 提交于 2019-12-11 16:34:30

问题


I am using Arduino IDE to program my micro-controller which has a built-in Wi-Fi chip (ESP8266 NodeMCU) , it connects to my internet router and then has a specific IP (as like 192.168.1.5).

So I want to send commands (and data) by a message which added to the link, then the link becomes as : 192.168.1.5/?A=data1&B=data2.

When link above is launched from a device within LAN, then I can get the message in a String variable, here I have now a message which contains "?A=data1&B=data2".

So the question is: How I can obtain A and B contents at separate variables?

Second easier question: How to convert contents to a Boolean, int or float variables?


回答1:


The algorithm would look like this. This example only print the tokens, but you should be able to modify it to handle the keys, the values and the exception cases.

#include <stdio.h>
#include <malloc.h>
#include <string.h>

#define MESSAGE_TOKENS ("=&?")

int main()
{
    char *msg = "?A=data1&B=data2";
    char *msg_dup = strdup(msg);
    char *tok = strtok(msg_dup, MESSAGE_TOKENS);

    while (tok != NULL)
    {
        char delim = msg[tok - msg_dup - 1];

        switch(delim)
        {
            case '?':
            case '&':
                printf("key=%s\n", tok);
                break;
            case '=':
                printf("val=%s\n", tok);
                break;
            default:
                break;
        }

        tok = strtok(NULL, MESSAGE_TOKENS);
    }

    free(msg_dup);
}

As for data types, you can use methods of the ctype.h header file (link). For example, you can verify if a string is a number by iterating through all characters of the string and verifying that all chars are numbers (the isnumber() method).



来源:https://stackoverflow.com/questions/49121119/parse-an-api-link-message-as-a-server-in-c-arduino-ide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!