Aduino - MSSQL

#include <ESP8266WiFi.h> #include <WiFiClient.h> #include "sqlard.h" const char* ssid = "xx"; const char* password = "xx"; static byte Gateway_IPAddr[] = { 127,0,0,1 }; WiFiClient client; SQLard MSSQL(Gateway_IPAddr, 1433, &client);

SQLard kısımda sürekli hata alıyorum. Sebebi ne olabilir?

test:10:42: error: no matching function for call to 'SQLard::SQLard(byte [4], int, WiFiClient&)' 10 | SQLard MSSQL(Gateway_IPAddr, 1433, &client);
 
Merhaba,
Yukarıdaki örneklerle insert yaptırıyorum. İnsert ü değiştirip select sorgusu çalıştırıyorum. Fakat deserializeJson failed = empty input hatası alıyorum. Ethernet modülü kullandım projede. Neden bu hatayı alırım yardımcı olabilecek var mı?


#include <ArduinoJson.h>
#include <sqlard.h>
#include <Ethernet.h>



uint8_t Ethernet_MacAddr[6] = { 0x74,0x69,0x69,0x2D,0x30,0x31 }; /* MAC ADRESİ */
static byte Server_IPAddr[] = { 192, 168, 10, 89 };
static byte Static_IPAddr[] = { 192,168,10,170 };
static byte Gateway_IPAddr[] = { 192,168,10,168 };
static byte Subnet_Mask[] = { 255,255,255,0 };
EthernetClient client;

int d = 0;
int kk_flag = 0;
char c;


unsigned long asyncDelay = 0; // Maksimum alabileceği rakam : 4,294,967,295
int delayLength = 10000;

SQLard MSSQL(Server_IPAddr, 1984, &client);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
while (!Serial);
Ethernet.begin(Ethernet_MacAddr, Static_IPAddr, Gateway_IPAddr, Gateway_IPAddr, Subnet_Mask);


}

void loop() {
recvWithStartEndMarkers();

if (millis() > asyncDelay + delayLength) {
if (asyncDelay > (4294967295 - delayLength)) {
asyncDelay = (4294967295 - asyncDelay) + (delayLength - (4294967295 - asyncDelay));
} else {
asyncDelay += delayLength;
}
Sending_To_database();
}
delay(2000);
}


void Sending_To_database() //CONNECTING WITH MS SQL
{
Serial.println("Login to the server");
if (MSSQL.connect()) // Check if the connection with the Data Base is correct
{
Serial.println("Registration ok");

// The database, the login name, the PW, and a "Sender" name are passed
MSSQL.setCredentials(L"ardunio", L"sa", L"Prosoft5656", L"Mustafa"); // For login to the Data Base
Serial.println("MSSQL-Login");
MSSQL.login(); // Now we are able to send querie

// String tarihs = "09.06.22";
// String saats = "14.42";
// float nem = 70.22;
// float temp = 28.50;


char newName [102];
// sprintf(newName, "INSERT INTO dbo.TestB (Tarih,Saat,Nem,Sicaklik) VALUES('%s','%s','%d.%02d','%d.%02d')", tarihs.c_str(), saats.c_str(), int(nem), int(round(nem * 100)) % 100, int(temp), int(round(temp * 100)) % 100);
// sprintf(newName, "INSERT INTO [dbo].[test]([data]) VALUES('EMRAH OZTEN')");
sprintf(newName, "SELECT TOP 10 * FROM EMRAHEV");
wchar_t fileName[102];
int i;
for (i = 0; i < 102; i++)
{
fileName = newName;
}
for (i = 0 ; i < 102 ; i++)
Serial.write(fileName);
Serial.println("");

MSSQL.executeNonQuery(fileName); // Databese'e queryi gönder.
Serial.println("Done");

if (!client) {
Serial.println("disconnecting.");
client.stop();
}

}
else
{
Serial.println("Login error");
}
}

void recvWithStartEndMarkers() { // Databaseden gelen verileri ayrıştırma işlemi yapılır.
String data_from_display = "";

while (client.available() > 0) {
c = client.read();
Serial.print(c);

if ( c == '[') {
kk_flag = 1;
}

if (kk_flag == 1) {
data_from_display += c;
}

if ( c == ']') {
kk_flag = 0;
}

}
Serial.println(data_from_display);
Serial.println(utf8ascii(data_from_display));

String input = data_from_display;

DynamicJsonDocument doc(1536);

DeserializationError error = deserializeJson(doc, utf8ascii(data_from_display));

if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}

for (JsonObject item : doc.as<JsonArray>()) {

int ID1 = item["ID"]; // 29, 28, 27, 26, 25, 24, 23, 22, 21, 20
const char* Tarih1 = item["Tarih"]; // "09.06.22", "09.06.22", "09.06.22", "09.06.22", "09.06.22", ...
const char* Saat1 = item["Saat"]; // "14.42", "14.42", "14.42", "14.42", "14.42", "14.42", "14.42", ...
const char* Nem1 = item["Nem"]; // "70.22", "70.22", "70.22", "70.22", "70.22", "70.22", "70.22", ...
const char* Sicaklik1 = item["Sicaklik"]; // "28.50", "28.50", "28.50", "28.50", "28.50", "28.50", ...

Serial.println("ID: " + String(ID1));
Serial.println("Tarih: " + String(Tarih1));
Serial.println("Saat: " + String(Saat1));
Serial.println("Nem: " + String(Nem1));
Serial.println("Sıcaklık: " + String(Sicaklik1));

}


Serial.println(input.length());

}

// ****** UTF8-Decoder: convert UTF8-string to extended ASCII *******
static byte c1; // Last character buffer

// Convert a single Character from UTF8 to Extended ASCII
// Return "0" if a byte has to be ignored
byte utf8ascii(byte ascii) {
if ( ascii < 128 ) // Standard ASCII-set 0..0x7F handling
{ c1 = 0;
return ( ascii );
}

// get previous input
byte last = c1; // get last char
c1 = ascii; // remember actual character

switch (last) // conversion depending on first UTF8-character
{ case 0xC2: return (ascii); break;
case 0xC3: return (ascii | 0xC0); break;
case 0x82: if (ascii == 0xAC) return (0x80); // special case Euro-symbol
}

return (0); // otherwise: return zero, if character has to be ignored
}

// convert String object from UTF8 String to Extended ASCII
String utf8ascii(String s)
{
String r = "";
char c;
for (int i = 0; i < s.length(); i++)
{
c = utf8ascii(s.charAt(i));
if (c != 0) r += c;
}
return r;
}

// In Place conversion UTF8-string to Extended ASCII (ASCII is shorter!)
void utf8ascii(char* s)
{
int k = 0;
char c;
for (int i = 0; i < strlen(s); i++)
{
c = utf8ascii(s);
if (c != 0)
s[k++] = c;
}
s[k] = 0;
}
 
Selamlar arkadaşlar!
Paylaştığınız `arduino-mssql` kütüphanenin yazarıyım, internette gezinirken konunuza rast geldim ve size ufak bir bilgilendirme yapmak istedim.

`arduino-mssql` kütüphanesi konseptin kanıtı (proof-of-concept) olarak yaptığım bir çalışmaydı, kısa süre önce kütüphanenin halefi olarak `tdslite` adlı yeni bir kütüphaneyi yayınladım. MSSQL'e bağlanmak için bu yeni kütüphaneyi kullanabilirsiniz. Kütüphaneyi Arduino Library Manager veya Platform IO Registry'da `tdslite` olarak aratarak bulabilirsiniz. Alternatif olarak, GitHub reposunda yayınlanan sürümlerden "zip" halini indirerek de kullanabilirsiniz.

Yeni kütüphane platform bağımsız bir yapıda olduğundan Arduino dışında bir çok board'da (örn. ESP, STM) da kullanabilirsiniz. Başlangıç örneği olarak https://github.com/mustafakemalgilo...les/arduino/03-select-rows/03-select-rows.ino bu örneği incelemenizi öneririm.

https://github.com/mustafakemalgilor/tdslite

Sağlıcakla kalın,
Mustafa
 
Son düzenleme:
Teşekkürler Mustafa Kemal Gilor.
 
Selamlar arkadaşlar!
Paylaştığınız `arduino-mssql` kütüphanenin yazarıyım, internette gezinirken konunuza rast geldim ve size ufak bir bilgilendirme yapmak istedim.

`arduino-mssql` kütüphanesi konseptin kanıtı (proof-of-concept) olarak yaptığım bir çalışmaydı, kısa süre önce kütüphanenin halefi olarak `tdslite` adlı yeni bir kütüphaneyi yayınladım. MSSQL'e bağlanmak için bu yeni kütüphaneyi kullanabilirsiniz. Kütüphaneyi Arduino Library Manager veya Platform IO Registry'da `tdslite` olarak aratarak bulabilirsiniz. Alternatif olarak, GitHub reposunda yayınlanan sürümlerden "zip" halini indirerek de kullanabilirsiniz.

Yeni kütüphane platform bağımsız bir yapıda olduğundan Arduino dışında bir çok board'da (örn. ESP, STM) da kullanabilirsiniz. Başlangıç örneği olarak https://github.com/mustafakemalgilo...les/arduino/03-select-rows/03-select-rows.ino bu örneği incelemenizi öneririm.

https://github.com/mustafakemalgilor/tdslite

Sağlıcakla kalın,
Mustafa

Merhaba,

Öncelikle kütüphane için teşekkür ederim :)
Açıklamada belirtmişsiniz ama tekrar sormak istediğim bir şey var. WiFi ile erişimi deneme şansınız hiç oldu mu? Ben denediğimde EthernetClient yerine WiFiClient yazdım. WiFi başlattıktan sonra ilgili bağlantı parametlerini girip bağlanmayı denediğimde aşağıdaki hatayı alıyorum.

User exception (panic/abort/assert)
17:13:51.835 -> --------------- CUT HERE FOR EXCEPTION DECODER ---------------
17:13:51.835 ->
17:13:51.835 -> Panic src/tdslite-net/base/network_io_base.hpp:178 uint32_t tdsl::net::network_io_base<Implementation>::do_receive_tds_pdu() [with Implementation = tdsl::net:: Assertion '!(!(0)) && "Invalid tds message length!"' failed.
17:13:51.835 ->
 
Son düzenleme:
Merhaba,

Öncelikle kütüphane için teşekkür ederim :)
Açıklamada belirtmişsiniz ama tekrar sormak istediğim bir şey var. WiFi ile erişimi deneme şansınız hiç oldu mu? Ben denediğimde EthernetClient yerine WiFiClient yazdım. WiFi başlattıktan sonra ilgili bağlantı parametlerini girip bağlanmayı denediğimde aşağıdaki hatayı alıyorum.

User exception (panic/abort/assert)
17:13:51.835 -> --------------- CUT HERE FOR EXCEPTION DECODER ---------------
17:13:51.835 ->
17:13:51.835 -> Panic src/tdslite-net/base/network_io_base.hpp:178 uint32_t tdsl::net::network_io_base<Implementation>::do_receive_tds_pdu() [with Implementation = tdsl::net:: Assertion '!(!(0)) && "Invalid tds message length!"' failed.
17:13:51.835 ->
Merhabalar, rica ederim :)

Evet, ESP-32S ve ESP8266 ile test etme fırsatım oldu, test için buradaki sketch'i kullanıyorum. Paylaştığınız hata mesajı aşağıdaki doğrulamanın tetiklenmesinden kaynaklanıyor:
if (length < sizeof(detail::tds_header) || length > k_max_length)

referans
... yani, gelen TDS mesajı ya standartta belirtilenden daha büyük (32767), veya olabilecek en küçük TDS mesajından daha küçük. Kullandığınız kodu ek olarak paylaşırsanız daha net yorum yapabilirim. Bir de imkanınız varsa, SQL server üzerinden Wireshark ile alacağınız bir pcap dosyası da problemin nereden kaynaklandığını anlayabilmek adına faydalı olacaktır. Wireshark ile paket toplarken diğer trafiği hariç tutmak için filtre kısmına "tds" yazabilirsiniz.

1681930209967.png
 
Merhabalar, rica ederim :)

Evet, ESP-32S ve ESP8266 ile test etme fırsatım oldu, test için buradaki sketch'i kullanıyorum. Paylaştığınız hata mesajı aşağıdaki doğrulamanın tetiklenmesinden kaynaklanıyor:
if (length < sizeof(detail::tds_header) || length > k_max_length)

referans
... yani, gelen TDS mesajı ya standartta belirtilenden daha büyük (32767), veya olabilecek en küçük TDS mesajından daha küçük. Kullandığınız kodu ek olarak paylaşırsanız daha net yorum yapabilirim. Bir de imkanınız varsa, SQL server üzerinden Wireshark ile alacağınız bir pcap dosyası da problemin nereden kaynaklandığını anlayabilmek adına faydalı olacaktır. Wireshark ile paket toplarken diğer trafiği hariç tutmak için filtre kısmına "tds" yazabilirsiniz.

Ekli dosyayı görüntüle 97493
#include <ESP8266WiFi.h> #include <WiFiClient.h> #include <tdslite.h> WiFiClient client; #define SKETCH_ENABLE_SERIAL_OUTPUT const char* ssid = "XXX"; const char* password = "XXX"; #if defined SKETCH_ENABLE_SERIAL_OUTPUT #define SERIAL_PRINTF_PROGMEM(FMTPM, ...) \ char buf [64] = {}; \ snprintf_P(buf, sizeof(buf), FMTPM, ##__VA_ARGS__); \ Serial.print(buf); #define SERIAL_PRINTF(FMTSTR, ...) \ [&]() { \ /* Save format string into program */ \ /* memory to save flash space */ \ static const char __fmtpm [] PROGMEM = FMTSTR; \ SERIAL_PRINTF_PROGMEM(__fmtpm, ##__VA_ARGS__) \ }() #define SERIAL_PRINTLNF_PROGMEM(FMTPM, ...) \ SERIAL_PRINTF_PROGMEM(FMTPM, ##__VA_ARGS__) \ Serial.println(""); \ Serial.flush() #define SERIAL_PRINTLNF(FMTSTR, ...) \ SERIAL_PRINTF(FMTSTR, ##__VA_ARGS__); \ Serial.println(""); \ Serial.flush() #define SERIAL_PRINT_U16_AS_MB(U16SPAN) \ [](tdsl::u16char_view v) { \ for (const auto ch : v) { \ Serial.print(static_cast<char>(ch)); \ } \ }(U16SPAN) #else #define SERIAL_PRINTF_PROGMEM(FMTPM, ...) #define SERIAL_PRINTF(FMTSTR, ...) #define SERIAL_PRINTLNF_PROGMEM(FMTPM, ...) #define SERIAL_PRINTLNF(FMTSTR, ...) #define SERIAL_PRINT_U16_AS_MB(U16SPAN) #endif tdsl::uint8_t net_buf [768] = {}; tdsl::arduino_driver<WiFiClient> driver{net_buf}; void setup() { Serial.begin(115200); delay(1000); ConnectWiFi(); delay(1000); SetupCon(); } void loop() { #ifdef SKETCH_ENABLE_SERIAL_OUTPUT Serial.begin(112500); while (!Serial); #endif } void ConnectWiFi() { int connAttempts = 0; Serial.println(); Serial.println(WiFi.macAddress()); Serial.print("Bağlanılıyor: "); Serial.print(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { if (connAttempts > 30) { Serial.println("\nWi-Fi ağına bağlanılamadı"); return; } delay(1000); Serial.print("."); connAttempts++; } Serial.println("\nWiFi baglanildi…"); Serial.print("IP Adresi: "); Serial.println(WiFi.localIP()); } void SetupCon() { #ifdef SKETCH_ENABLE_SERIAL_OUTPUT Serial.begin(112500); while (!Serial); #endif decltype(driver)::progmem_connection_parameters params; params.server_name = TDSL_PMEMSTR("111.111.111.111"); params.port = 14333; params.user_name = TDSL_PMEMSTR("XX"); params.password = TDSL_PMEMSTR("XX"); params.client_name = TDSL_PMEMSTR("Erdem"); params.app_name = TDSL_PMEMSTR("Arduino"); params.db_name = TDSL_PMEMSTR("XXX"); params.packet_size = {512}; SERIAL_PRINTLNF("Bağlanmaya çalışıyor"); auto result = driver.connect(params); if (not(decltype(driver)::e_driver_error_code::success == result)) { SERIAL_PRINTLNF("Error: Database connection failed!"); // Database connection failed. while (true) { delay(1000); } } }

Arduino konusunda pek tecrübeli değilim. Sizin verdiğiniz örnekteki komutları kopyaladım aslında. Sadece Ethernet yerine wificlient kullandım ancak henüz select aşamasına gelmeden yani connect olmaya çalışırken bu hatayı alıyorum. Çalıştığım yerde bir db üzerine select atmaya çalıştığım için oraya WireShark kuramıyorum maalesef.
 
Merhaba,
tdsl::uint8_t net_buf [768] = {}; satırını -> tdsl::uint8_t net_buf [4096] = {}; olarak
params.packet_size = {512}; satırını ise -> params.packet_size = {2048}; olarak

değiştirerek tekrardan deneyebilir misin?
 
Merhaba,
tdsl::uint8_t net_buf [768] = {}; satırını -> tdsl::uint8_t net_buf [4096] = {}; olarak
params.packet_size = {512}; satırını ise -> params.packet_size = {2048}; olarak

değiştirerek tekrardan deneyebilir misin?
Yine aynı hatayı verdi. Sonrasında burada verdiğiniz skecthi denedim. Bu sefer aşağıdaki hatayı alıp yine connect olamadım. Bağlantı için kullandığım user ve password doğru olduğundan eminim çünkü MSSQL ile denediğimde anında connect olabiliyorum. Atladığım bir şey mi var anlam veremedim.

Sizi de meşgul etmiyorumdur umarım :)

attempting to connect to x.x.x.x:14333, 9 retries remaining ...
... connection attempt failed (0) ...

CSS:
#if defined ESP8266
#include <ESP8266WiFi.h>
#elif defined ESP32
#include <WiFi.h>
#include <esp_task_wdt.h>
#else
#error "Architecture unrecognized by this code."
#endif

#define SKETCH_TDSL_NETBUF_SIZE 512 * 16
#define SKETCH_TDSL_PACKET_SIZE 2048

#define SERIAL_PRINTF(FMTSTR, ...)                                                                 \
    [&]() {                                                                                        \
        static_assert(sizeof(FMTSTR) <= 255, "Format string cannot be greater than 255");          \
        /* Save format string into program */                                                      \
        /* memory to save flash space */                                                           \
        static const char __fmtpm [] PROGMEM = FMTSTR;                                             \
        char buf [128]                       = {};                                                 \
        snprintf_P(buf, sizeof(buf), __fmtpm, ##__VA_ARGS__);                                      \
        Serial.print(buf);                                                                         \
    }()

#define SERIAL_PRINTLNF(FMTSTR, ...)                                                               \
    SERIAL_PRINTF(FMTSTR, ##__VA_ARGS__);                                                          \
    Serial.println("")

#define SERIAL_PRINT_U16_AS_MB(U16SPAN)                                                            \
    [](tdsl::u16char_view v) {                                                                     \
        for (const auto ch : v) {                                                                  \
            Serial.print(static_cast<char>(ch));                                                   \
        }                                                                                          \
    }(U16SPAN)

#define TDSL_DEBUG_PRINT(FMTSTR, ...)       SERIAL_PRINTF(FMTSTR, ##__VA_ARGS__)
#define TDSL_DEBUG_PRINTLN(FMTSTR, ...)     SERIAL_PRINTLNF(FMTSTR, ##__VA_ARGS__)
#define TDSL_DEBUG_PRINT_U16_AS_MB(U16SPAN) SERIAL_PRINT_U16_AS_MB(U16SPAN)

#ifndef SKETCH_NO_TDSLITE

#include <tdslite.h>

// --------------------------------------------------------------------------------

static void info_callback(void *, const tdsl::tds_info_token & token) noexcept {
    SERIAL_PRINTF("%c: [%d/%d/%d@%d] --> ", (token.is_info() ? 'I' : 'E'), token.number,
                  token.state, token.class_, token.line_number);
    SERIAL_PRINT_U16_AS_MB(token.msgtext);
    SERIAL_PRINTLNF("");
}

// --------------------------------------------------------------------------------

static void row_callback(void * u, const tdsl::tds_colmetadata_token & colmd,
                         const tdsl::tdsl_row & row) {
    // Feed the dog so he won't bite us

#if defined ESP8266
    ESP.wdtFeed();
#elif defined ESP32
    esp_task_wdt_reset();
#endif

    SERIAL_PRINTF("row: ");

    // TODO: implement a visitor for this?
    for (const auto & field : row) {
        SERIAL_PRINTF("%d\t", field.as<tdsl::uint32_t>());
    }
    SERIAL_PRINTLNF("");
}

// The network buffer
tdsl::uint8_t net_buf [SKETCH_TDSL_NETBUF_SIZE] = {};
tdsl::arduino_driver<WiFiClient> driver{net_buf};

// --------------------------------------------------------------------------------

void tdslite_database_init() noexcept {
    SERIAL_PRINTLNF("... init database begin...");  
}

// --------------------------------------------------------------------------------

bool tdslite_setup() noexcept {
    SERIAL_PRINTLNF("... init tdslite ...");
    decltype(driver)::connection_parameters params;
    params.server_name = "123.123.123.123";
    params.port        = 14333;
    params.user_name   = "xx";
    params.password    = "xxx";
    params.client_name = "arduino mega";
    params.app_name    = "sketch";
    params.db_name     = "xxxx";
    params.packet_size = {SKETCH_TDSL_PACKET_SIZE};
    driver.set_info_callback(&info_callback, nullptr);
    auto cr = driver.connect(params);
    if (not(decltype(driver)::e_driver_error_code::success == cr)) {
        SERIAL_PRINTLNF("... tdslite init failed, connection failed %d ...",
                        static_cast<tdsl::uint32_t>(cr));
        return false;
    }

    tdslite_database_init();
    SERIAL_PRINTLNF("... init tdslite end...");
    return true;
}

// --------------------------------------------------------------------------------

inline void tdslite_loop() noexcept {
     
}

#else

inline void tdslite_loop() {}

inline void initDatabase() {}

#endif

// --------------------------------------------------------------------------------

inline bool init_serial() {
    Serial.begin(112500);
    while (!Serial)
        ;
    return true;
}

// --------------------------------------------------------------------------------

inline bool wifi_setup() {
    SERIAL_PRINTLNF("... wifi setup ...");
    const char * ssid     = "xyz";
    const char * password = "xyz";
    WiFi.mode(WIFI_STA); // Optional
    WiFi.begin(ssid, password);
    while (not(WiFi.status() == WL_CONNECTED)) {
        SERIAL_PRINTLNF("... waiting for WiFi connection ...");
        delay(1000);
    };
    SERIAL_PRINTLNF("Connected to the WiFi network `%s`, IP address is: %s", ssid,
                    WiFi.localIP().toString().c_str());
    return true;
}

// --------------------------------------------------------------------------------

void setup() {
    bool r = {false};
    r      = init_serial();
    r      = r && wifi_setup();
    r      = r && tdslite_setup();
    if (not r) {
        SERIAL_PRINTLNF("... setup failed ...");
        for (;;) {
            delay(1000);
        }
    }
    SERIAL_PRINTLNF("--- setup finished ---");
}

// --------------------------------------------------------------------------------

void loop() {
}
 
Yine aynı hatayı verdi. Sonrasında burada verdiğiniz skecthi denedim. Bu sefer aşağıdaki hatayı alıp yine connect olamadım. Bağlantı için kullandığım user ve password doğru olduğundan eminim çünkü MSSQL ile denediğimde anında connect olabiliyorum. Atladığım bir şey mi var anlam veremedim.

Sizi de meşgul etmiyorumdur umarım :)

attempting to connect to x.x.x.x:14333, 9 retries remaining ...
... connection attempt failed (0) ...

CSS:
#if defined ESP8266
#include <ESP8266WiFi.h>
#elif defined ESP32
#include <WiFi.h>
#include <esp_task_wdt.h>
#else
#error "Architecture unrecognized by this code."
#endif

#define SKETCH_TDSL_NETBUF_SIZE 512 * 16
#define SKETCH_TDSL_PACKET_SIZE 2048

#define SERIAL_PRINTF(FMTSTR, ...)                                                                 \
    [&]() {                                                                                        \
        static_assert(sizeof(FMTSTR) <= 255, "Format string cannot be greater than 255");          \
        /* Save format string into program */                                                      \
        /* memory to save flash space */                                                           \
        static const char __fmtpm [] PROGMEM = FMTSTR;                                             \
        char buf [128]                       = {};                                                 \
        snprintf_P(buf, sizeof(buf), __fmtpm, ##__VA_ARGS__);                                      \
        Serial.print(buf);                                                                         \
    }()

#define SERIAL_PRINTLNF(FMTSTR, ...)                                                               \
    SERIAL_PRINTF(FMTSTR, ##__VA_ARGS__);                                                          \
    Serial.println("")

#define SERIAL_PRINT_U16_AS_MB(U16SPAN)                                                            \
    [](tdsl::u16char_view v) {                                                                     \
        for (const auto ch : v) {                                                                  \
            Serial.print(static_cast<char>(ch));                                                   \
        }                                                                                          \
    }(U16SPAN)

#define TDSL_DEBUG_PRINT(FMTSTR, ...)       SERIAL_PRINTF(FMTSTR, ##__VA_ARGS__)
#define TDSL_DEBUG_PRINTLN(FMTSTR, ...)     SERIAL_PRINTLNF(FMTSTR, ##__VA_ARGS__)
#define TDSL_DEBUG_PRINT_U16_AS_MB(U16SPAN) SERIAL_PRINT_U16_AS_MB(U16SPAN)

#ifndef SKETCH_NO_TDSLITE

#include <tdslite.h>

// --------------------------------------------------------------------------------

static void info_callback(void *, const tdsl::tds_info_token & token) noexcept {
    SERIAL_PRINTF("%c: [%d/%d/%d@%d] --> ", (token.is_info() ? 'I' : 'E'), token.number,
                  token.state, token.class_, token.line_number);
    SERIAL_PRINT_U16_AS_MB(token.msgtext);
    SERIAL_PRINTLNF("");
}

// --------------------------------------------------------------------------------

static void row_callback(void * u, const tdsl::tds_colmetadata_token & colmd,
                         const tdsl::tdsl_row & row) {
    // Feed the dog so he won't bite us

#if defined ESP8266
    ESP.wdtFeed();
#elif defined ESP32
    esp_task_wdt_reset();
#endif

    SERIAL_PRINTF("row: ");

    // TODO: implement a visitor for this?
    for (const auto & field : row) {
        SERIAL_PRINTF("%d\t", field.as<tdsl::uint32_t>());
    }
    SERIAL_PRINTLNF("");
}

// The network buffer
tdsl::uint8_t net_buf [SKETCH_TDSL_NETBUF_SIZE] = {};
tdsl::arduino_driver<WiFiClient> driver{net_buf};

// --------------------------------------------------------------------------------

void tdslite_database_init() noexcept {
    SERIAL_PRINTLNF("... init database begin..."); 
}

// --------------------------------------------------------------------------------

bool tdslite_setup() noexcept {
    SERIAL_PRINTLNF("... init tdslite ...");
    decltype(driver)::connection_parameters params;
    params.server_name = "123.123.123.123";
    params.port        = 14333;
    params.user_name   = "xx";
    params.password    = "xxx";
    params.client_name = "arduino mega";
    params.app_name    = "sketch";
    params.db_name     = "xxxx";
    params.packet_size = {SKETCH_TDSL_PACKET_SIZE};
    driver.set_info_callback(&info_callback, nullptr);
    auto cr = driver.connect(params);
    if (not(decltype(driver)::e_driver_error_code::success == cr)) {
        SERIAL_PRINTLNF("... tdslite init failed, connection failed %d ...",
                        static_cast<tdsl::uint32_t>(cr));
        return false;
    }

    tdslite_database_init();
    SERIAL_PRINTLNF("... init tdslite end...");
    return true;
}

// --------------------------------------------------------------------------------

inline void tdslite_loop() noexcept {
    
}

#else

inline void tdslite_loop() {}

inline void initDatabase() {}

#endif

// --------------------------------------------------------------------------------

inline bool init_serial() {
    Serial.begin(112500);
    while (!Serial)
        ;
    return true;
}

// --------------------------------------------------------------------------------

inline bool wifi_setup() {
    SERIAL_PRINTLNF("... wifi setup ...");
    const char * ssid     = "xyz";
    const char * password = "xyz";
    WiFi.mode(WIFI_STA); // Optional
    WiFi.begin(ssid, password);
    while (not(WiFi.status() == WL_CONNECTED)) {
        SERIAL_PRINTLNF("... waiting for WiFi connection ...");
        delay(1000);
    };
    SERIAL_PRINTLNF("Connected to the WiFi network `%s`, IP address is: %s", ssid,
                    WiFi.localIP().toString().c_str());
    return true;
}

// --------------------------------------------------------------------------------

void setup() {
    bool r = {false};
    r      = init_serial();
    r      = r && wifi_setup();
    r      = r && tdslite_setup();
    if (not r) {
        SERIAL_PRINTLNF("... setup failed ...");
        for (;;) {
            delay(1000);
        }
    }
    SERIAL_PRINTLNF("--- setup finished ---");
}

// --------------------------------------------------------------------------------

void loop() {
}
params.port = 14333; bu değeri params.port = 1433; şeklinde güncellerseniz muhtemelen çalışacaktır.
 

Forum istatistikleri

Konular
128,198
Mesajlar
915,774
Kullanıcılar
449,979
Son üye
schule48

Yeni konular

Çevrimiçi üyeler

Geri
Üst