Arduino:覆盖Print类问题

时间:2017-05-27 17:30:51

标签: c++ arduino nodemcu arduino-esp8266

我正在尝试创建一个库,用于重定向打印到Print类的数据。遗憾的是,我被误读为

  

错误:无法声明变量' diagData'是抽象类型' PrintToString'

     

注意:因为以下虚拟函数在' PrintToString'

中是纯粹的      

注意:virtual size_t PrintToString :: write(uint8_t)

我尝试了几种不同的方法,但没有运气。 (来自互联网)

链接

打印课程:github.com/ Print.hPrint.cpp

我的代码

PrintToString.h

#ifndef PRINT_TO_STRING_H

    #define PRINT_TO_STRING_H

    #include <Arduino.h>


    class PrintToString : public Print
    {
        private:
            String* data;

        public:
            PrintToString();
            ~PrintToString();

            String* results();
            void clear();

            size_t write(uint8_t) = 0;
            size_t write(const uint8_t* buffer, size_t size);
    };

#endif

PrintToString.cpp

#include "PrintToString.h"



PrintToString::PrintToString()
{
    data = new String();
}

PrintToString::~PrintToString()
{
    delete data;
    data = NULL;
}


String* PrintToString::results()
{
    return data;
}

void PrintToString::clear()
{
    delete data;
    data = new String();
}


size_t PrintToString::write(const uint8_t* buffer, size_t size)
{
    size_t n = 0;

    while (size--)
    {
        if (data->concat(*buffer++))
            n++;
        else
            break;
    }

    return n;
}

TestSketch.ino(我遗漏了所有常量的内容)

#include <ESP8266WiFi.h>
#include <PrintToString.h>

const char*    WIFI_SSID
const char*    WIFI_PASS

const char*    API_HOST
const uint16_t API_PORT
const uint16_t LOCAL_UDP_PORT

WiFiUDP UDPClint;
PrintToString diagData;
uint64_t packetNumber = 0;

void setup()
{
    WiFi.begin(WIFI_SSID, WIFI_PASS);
    UDPClint.begin(LOCAL_UDP_PORT);

    while (WiFi.status() != WL_CONNECTED)
        delay(500);

    WiFi.printDiag(diagData);
    sendStringPacket(diagData.result());
    diagData.clear();
}

void loop()
{
    delay(1000);
}

void sendStringPacket(String payload)
{
    UDPClint.beginPacket(API_HOST, API_PORT);


    uint64_t thisPNumber = packetNumber++;
    String thisPNumberStr;

    while (thisPNumber > 0)
    {
        uint8_t digit = thisPNumber % 10;
        thisPNumberStr.concat(digit);

        thisPNumber /= 10;
    }

    UDPClint.write(';');

    for (uint64_t i = 0; i < payload.length(); i++)
        UDPClint.write(payload.charAt(i));

    UDPClint.endPacket();
}

1 个答案:

答案 0 :(得分:1)

这是因为这个类在这里有一个pure virtual function

  

size_t write(uint8_t)= 0;

无法实例化具有纯虚函数的类。因此,方法write(uint8_t)必须以某种方式在您的代码中实现。

编辑:请考虑将sendStringPacket()中使用的代码用于write(uint8_t)。您可以在不使用sendStringPacket(diagData.result());语句的情况下重定向输出。