SDDC的Windows初體驗-QT篇

靈感桌面發表於2022-04-28

前言

如果熟悉愛智和看過我之前文章的朋友見到這篇文章一定會有很大疑問,SDDC 作為智慧裝置發現控制協議,怎麼會用在 windows 上?

這一切還是源自於我巨大的腦洞,因為這段在搞 Windows 開發,突發奇想能不能把電腦也接入到愛智上,於是就把嵌入式裝置使用的 SDDC 協議移植到了 Windows 上,本文就介紹下基於 QT 移植的 libsddc 庫,其實我還移植到了 VS2022 上了,這個之後再介紹吧。

軟硬體選擇

這裡使用 windows 開發,除了電腦也不需要其他額外的硬體了。

軟體的話,使用的是 QT 5.9.0 版本,官網下載太慢了,推薦大家下載這個清華大學開源映象站的資源:https://mirrors.tuna.tsinghua.edu.cn/qt/archive/qt/5.9/5.9.0/qt-opensource-windows-x86-5.9.0.exe

在這裡插入圖片描述

程式碼獲取與解析

程式碼可以從我的 gitee 倉庫直接獲取:

https://gitee.com/inspiration-desktop/windows-libsddc.git

開啟 libsddc 專案如下:

在這裡插入圖片描述

其中 SDDC 相關程式碼都已基於 windows環境進行相容修改,具體修改內容可以全域性搜尋 __WINDOWS__ 巨集來檢視,其中主要的差異是 windows 和嵌入式系統的 socket 相關實現上,還有就是多執行緒,QT本身就支援 pthread ,這個給移植帶來了很大的便利,不像 VS 為了支援 pthread 還需要一頓折騰,對於VS的移植之後的文章再介紹吧。

main.cpp 程式碼解析,主要內容是獲取uuid作為裝置唯一標識(其實還是我沒找到合適的獲取 windows MAC 地址的介面...);

#include "mainwindow.h"
#include <QApplication>
#include "sddc_message_example.h"
#include "sddc.h"
#include "test_thread.h"
#include "cJSON.h"
#include <QUuid>
#include <QFile>
#include <iostream>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    
    // 啟動視覺化視窗,暫時用不到
    //MainWindow w;
    
    //w.show();

    char * uuid_str;
    char buffer[128];
    QString uuidstr;
    QUuid uuid;

    // 獲取uuid作為裝置唯一標識
    QFile file("uuid.txt");
    if(file.exists()){
        std::cout << "file exist\n";
        if(!file.open(QIODevice::ReadWrite)){
            std::cout << "open file failed\n";
        }else{
            //讀取檔案
            //判斷檔案是否已經讀到末尾了
             while(!file.atEnd()){
                //讀取資料
                memset(buffer,0,sizeof(buffer));
                qint64 length = file.readLine(buffer,128);
                if(length != -1){
                    uuid_str = (char*)&buffer;
                    std::cout << "read success\n";
                }
            }
            file.close();
        }
    }else{
        if(!file.open(QIODevice::ReadWrite)){
            std::cout << "open file failed\n";
        }else{
            uuid = QUuid::createUuid();
            uuidstr = uuid.toString();

            uuid_str = (char *)uuidstr.remove("{").remove("}").remove("-").toStdString().data();
            memset(buffer,0,sizeof(buffer));
            memcpy(buffer,uuid_str,strlen(uuid_str));
            uuid_str = buffer;

            std::cout << uuid_str << std::endl;
            qint64 length = -1;
            length = file.write(uuid_str);

            if(length == -1){
                std::cout << "write file failed\n";
            }else{
                std::cout << "write file success\n";
            }

            file.close();
        }
    }

    std::cout << uuid_str << std::endl;

    // 啟動一個新執行緒進行其他業務處理
	//test_thread *thread1 = new test_thread();
	//thread1->start();

    // 啟動 SDDC 協議
    sddc_main(uuid_str);
    a.exec();

    return 0;
}

效果

點選左下角的綠色三角執行程式;

在這裡插入圖片描述

可以在愛智裝置搜尋中發現對應裝置並新增;

在這裡插入圖片描述
在這裡插入圖片描述

相關文章