1

Dependencies:   ESP8266

main.cpp

Committer:
nikitoslav
Date:
2018-07-07
Revision:
4:e584e034f9e1
Parent:
3:24f12bc2b76d

File content as of revision 4:e584e034f9e1:

#include "mbed.h"
#include <string>
#include <sstream>
#include <vector>
#include "ESP8266.h"

int localOutPort = 49100;
int localInPort = 49101;

char IP[16]; //IP of client app
bool wasHandshake = false; //was handshake with client or not

Serial console(USBTX,USBRX);
ESP8266 wifi(PF_7,PF_6,localOutPort,localInPort);

const char* ap = "Clapeyron_Industries";
const char* passPhrase = "06737184";

Thread listeningThread;

void onReceive(void);
void processReceivedData(string&, char*, int);
std::vector<std::string> split(const std::string&, char);

//сначала запускается AP, надо подключиться прямо к точке RobotClapeyronAP (пароль passpass123),
//либо начать общение, либо передать данные о подключении робота к другой AP: имя, пароль
int main() {
    console.baud(9600);
    if (wifi.startup(3) && wifi.setupAP()) {
        console.printf("AP set up\n");
        console.printf("Your IP is: %s\n",wifi.getIPAddress());
    }
    else
        console.printf("Can not set up AP\n");
    listeningThread.start(onReceive);
}

void onReceive(void) {
    const int maxSize = 100;
    
    char buffer[100];
    string buf = "";
    int port;
    int bytes;
    while(1) {
        buf = "";
        bytes = wifi.recv(&buffer,maxSize,IP,&port);
        if (bytes != -1) {
            console.printf("Bytes received: %d; from %s:%d\n",bytes,IP,port);
            for(int i = 0; i < bytes; i++) {
                buf += buffer[i];
            }
            console.printf("Data: %s\n",buf);
            processReceivedData(buf,IP,port);
        }
    }
}

void processReceivedData(string& data, char* IP, int port) {
    if (port == localOutPort) { //TODO проверка того, что разговариваем с клиентом
        std::vector<std::string> splittedStream = split(data, '?');
        if (splittedStream.size() > 1) {
            std::vector<std::string> splittedMessage = split(splittedStream[1],'|'); //TODO цикл по splittedStream от второго (1) до предпоследнего (size-2)
            if (splittedMessage.size()>0)
  /*-->*/   if (splittedMessage[0] == "HiRobotClapeyronImAClient") {
                wasHandshake = true; //TODO говорим, что с этим клиентом поздоровались (сейчас вообще как будто один клиент может быть)
                string msg = "?HiClientImARobotClapeyron|hardvers|0.1?";
                wifi.send(msg.c_str(),msg.length(),IP,localInPort);
            } else if (wasHandshake) //TODO проверка того, что работаем с поздоровавшимся клиентом
  /*-->*/   if ((splittedMessage[0] == "ConnectToTheAP") && (splittedMessage.size() >= 3)) { //TODO проверка формата сообщения не полная, разумеется
                if (wifi.disconnect() && wifi.connect(splittedMessage[1].c_str(),splittedMessage[2].c_str())) {
                        string msg = "?ConnectedToTheAP|"+splittedMessage[1]+"|IP|"+wifi.getIPAddress()+"?";
                        console.printf(msg.c_str()); //Debug
                        wifi.send(msg.c_str(),msg.length(),IP,localInPort);
                    } else {
                        string msg = "?CanNotConnectToTheAP|"+splittedMessage[1]+"?";
                        console.printf(msg.c_str()); //Debug
                        wifi.send(msg.c_str(),msg.length(),IP,localInPort);
                    } /*else
    -->     if () {}*/
            }
        }
    }
}

std::vector<std::string> split(const std::string &s, char delim) {
  std::stringstream ss(s);
  std::string item;
  std::vector<std::string> elems;
  while (std::getline(ss, item, delim)) {
    elems.push_back(item);
    // elems.push_back(std::move(item)); // if C++11
  }
  return elems;
}