這些元件所需的相關引數包括:版本號(1到40)、LMQH的四種糾錯級別(分別表示資料丟失容忍度為7%、15%、25%和30%)和編碼方案(可以是數字、字母數字、八位或漢字)。
定義介面
將二維碼的元件型別轉換為 Motoko 的型別:
public type Version = { #Version : Nat };
public type ErrorCorrection = { #L; #M; #Q; #H };
public type Mode = { #Alphanumeric; #EightBit; #Kanji; #Numeric };
public type Matrix = { #Matrix : [[Bool]] };
我們可以使用這些型別,在 Motoko 中定義一個函式來生成二維碼:
/**
* Encodes the input text according to the QR code specification or
* returns null if the input text is invalid for the given mode.
*/
public func encode(
version : Version, // Version number.
level : ErrorCorrection, // Error correction level.
mode : Mode, // Encoding scheme.
input : Text // Input text.
) : async ?Matrix { .. };
將以上程式碼封裝在 Motoko actor 宣告中定義介面。
實現
我把實現程式碼放到了 GitHub 上,總共2000多行程式碼,需要十幾個模組支援。可以 git 下來後在 Visual Studio 中開啟,Visual Studio 上有一個可以高亮 Motoko 語法的外掛,比較方便。
$ git clone https://github.com/enzoh/qr
$ code qr
這個二維碼服務在很大程度上依賴於 Motoko 的標準程式碼庫。之前我一直不感冒,用了才知道, Motoko 已經足夠成熟了,並且功能強大。Motoko的 API 和 Rust 與 SML 提供的很相似,所以如果你很熟悉這些語言,那用 Motoko 的時候基本不需要查閱任何的文件。雖然文件網站仍在開發中,然而,透過直接在 Visual Studio 中開啟標準庫,始終可以找到最新的詳細資訊。
$ code $HOME/.cache/dfinity/versions/$DFX_VERSION/stdlib
演示
啟動本地網際網路計算機節點:
$ dfx start
在另一個視窗中執行以下命令
$ dfx build
$ dfx canister install --all
$ dfx canister call demo encode \
$ '(variant{Version=2}, variant{M}, variant{Alphanumeric}, "HTTPS://SDK.DFINITY.ORG")' \
$ | sed 's/[(")]//g' \
$ | sed 's/#/█/g'
結果就輸出來了:
教你用Dfinity實現一個開放式二維碼服務
免責聲明:
- 本文版權歸原作者所有,僅代表作者本人觀點,不代表鏈報觀點或立場。
- 如發現文章、圖片等侵權行爲,侵權責任將由作者本人承擔。
- 鏈報僅提供相關項目信息,不構成任何投資建議。