OpenHarmony 3.1 Beta 樣例:使用分散式菜單創建點餐神器
- 2022 年 4 月 18 日
- 筆記
- OpenHarmony, 關鍵技術解讀, 應用開發, 開發板
(以下內容來自開發者分享,不代表 OpenHarmony 項目群工作委員會觀點)

劉麗紅
隨著社會的進步與發展,科技手段的推陳出新,餐飲行業也在尋求新的突破與變革,手機掃描二維碼點餐系統已經成為餐飲行業的未來趨勢,發展空間巨大;掃碼點餐,是「互聯網+餐飲」潮流的產物,可以有效地為餐廳節省人力成本,提高顧客點餐用餐效率,節省顧客時間,提高餐廳翻台率。
但是,一些老年人也在面對掃碼點餐時犯了難;還有些消費者不願意使用掃碼點餐,是擔心個人資訊泄露等安全問題。
如此,我們設計了一款分散式菜單應用,不需要個人去關注公眾號或下載小程式,服務員會提供幾個點單的平板,連接店鋪網路,區域網內通訊,這樣大家點單、查看訂單詳情等都不受網路限制。先上效果:
潤和 HiSpark Taurus AI Camera(Hi3516d)
潤和大禹系列 HH-SCDAYU200 開發板
如上動圖:可由一人拉起點單平板上的點單應用,大家可同時點單,點擊菜品圖片進入菜品詳情頁面,選擇口味後確認,就是一次點單完成,並自動返回到菜單首頁;此時可看到下方購物車數量和總額的變化,點擊下方”點好了” 可進入訂單詳細,並通過分散式資料庫讓其他人也查看訂單詳情,從訂單詳情返回到點單頁後,可再進行疊加點單。
下面是 Demo 的開發說明。
一、開發說明
基於 OpenAtom OpenHarmony(以下簡稱「OpenHarmony」) 3.1 beta 版本,並結合方舟開發框架(ArkUI)、分散式組網、分散式資料庫等特性,使用 eTS 語言開發的一款分散式菜單應用;主要體現了 OpenHarmony 分散式資料庫特性,根據設計師提供的 UX ,首先就要考慮分散式資料庫應該要怎麼設計,需要包含哪些元素;其次 demo 是沒有後台服務端,結合 ArkUI 框架,需要思考多個頁面間數據怎麼傳遞。
Demo 主要包含菜單首頁、菜單詳情頁和訂單詳情頁,以及加入菜單分散式資料庫和結算訂單分散式資料庫。三個頁面都需要訂單列表數據,因為目前 ArkUI 框架在 app.ets 定義數據,其他頁面不能直接引用,所以通過 router.push 的方法,帶上 param 的參數,將數據在頁面間進行傳遞。
兩個分散式資料庫,一個是訂單列表數據,訂單列表需要根據 UX 提供的設計圖,來確認資料庫中的元素,本 Demo 中的訂單頁面數據資訊其他包括菜品的資訊(圖片、名稱、份數、辣度等)以及點單人的資訊(圖片、名稱和點單的數量);另一個是將下單成功通知所有人。
Demo 也還有很多待完善的點,比如:點擊加/減的圖標進行菜單的加減、一鍵清空訂單、以及 Demo 是否有更好的方案來達到更好的點單體驗等等,期待更多的讀者們來完善。
程式碼結構如下圖:
├─entry │ └─src │ └─main │ │ config.json // 應用配置文件 │ │ │ ├─ets │ │ └─MainAbility │ │ │ app.ets // 應用程式主入口 │ │ │ │ │ ├─model │ │ │ CommonLog.ets // 日誌類 │ │ │ MenuData.ets // 初始化菜單數據類 │ │ │ MenuListDistributedData.ets // 加入菜單分散式資料庫 │ │ │ RemoteDeviceManager.ets // 分散式拉起設備管理類 │ │ │ SubmitData.ets // 結算訂單分散式資料庫 │ │ │ │ │ └─pages │ │ detailedPage.ets // 菜品詳細頁面 │ │ index.ets // 首頁 │ │ menuAccount.ets // 訂單詳情頁面 │ │ │ └─resources │ ├─base │ │ ├─element │ │ │ string.json │ │ │ │ │ ├─graphic │ │ ├─layout │ │ ├─media // 存放媒體資源 │ │ │ icon.png │ │ │ icon_add.png │ │ │ icon_back.png │ │ │ icon_cart.png
二、頁面編寫
2.1 點單首頁
效果圖如上,可以分為四部分:
1)頂部頁標籤
@Component
struct PageInfo {
build() {
Flex() {
Text('點單頁')
.fontSize('36lpx')
}
.padding({ left: '48lpx', top: '28lpx' })
.width('100%')
.height('10%')
.backgroundColor('#FFFFFF')
}
}
2)用戶資訊
• 主要用到 Flex 容器 Image 和 Text 組件;
• 用戶名稱和頭像圖標,根據設備序列號不同,可展示不同的名稱和圖標;
• 點擊右上角分享的小圖標,可分散式拉起區域網內的另一台設備。
@Component
struct MemberInfo {
@Consume userImg: Resource
@Consume userName: string
aboutToAppear() {
// 根據設備序列號不同,展示不同的名稱和圖標
CommonLog.info('==serial===' + deviceInfo.serial);
if (deviceInfo.serial == '150100384754463452061bba4c3d670b') {
this.userImg = $r("app.media.icon_user")
this.userName = 'Sunny'
}
else {
this.userImg = $r("app.media.icon_user_another")
this.userName = 'Jenny'
}
}
build() {
Flex({ direction: FlexDirection.Column }) {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
Image(this.userImg)
.width('96lpx')
.height('96lpx')
.margin({ right: '18lpx' })
Text(this.userName)
.fontSize('36lpx')
.fontWeight(FontWeight.Bold)
.flexGrow(1)
Image($r("app.media.icon_share"))
.width('64lpx')
.height('64lpx')
}
// 打開分散式設備列表
.onClick(() => {
this.DeviceDialog.open()
})
.layoutWeight(1)
.padding({ left: '48lpx', right: '48lpx' })
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
Column() {
Text('124')
.fontSize('40lpx')
.margin({ bottom: '24lpx' })
Text('積分')
.fontSize('22lpx')
.opacity(0.4)
}
.flexGrow(1)
Column() {
Text('0')
.fontSize('40lpx')
.margin({ bottom: '24lpx' })
Text('優惠劵')
.fontSize('22lpx')
.opacity(0.4)
}
.flexGrow(1)
Column() {
Image($r("app.media.icon_member"))
.width('48lpx')
.height('48lpx')
.margin({ bottom: '24lpx' })
Text('會員碼')
.fontSize('22lpx')
.fontColor('#000000')
.opacity(0.4)
}
.flexGrow(1)
}
.layoutWeight(1)
}
.width('93%')
.height('25%')
.borderRadius('16lpx')
.backgroundColor('#FFFFFF')
.margin({ top: '24lpx', bottom: '32lpx' })
}
}
3)列表展示
• 主要用到 Flex 容器和 Scroll 容器 Image 和 Text 組件;
• 從首頁點擊列表進入菜品詳細頁面,點菜成功後會自動返回首頁,此時列表需要動態更新菜品的數量。
@Component
struct MenuHome {
private specialty: any[]
private winterNew: any[]
private classic: any[]
private soup: any[]
private menuItems: MenuData[]
private titleList = ['招牌菜', '冬季新品', '下飯菜', '湯品']
@State name: string = '招牌菜'
build() {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Start }) {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceAround }) {
ForEach(this.titleList, item => {
Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
Text(item)
.fontSize('24lpx')
}
.padding({ left: '24lpx' })
.backgroundColor(this.name == item ? '#1A006A3A' : '#FFFFFF')
.height('160lpx')
.onClick(() => {
this.name = item
if (this.name == '招牌菜') {
this.menuItems = initializeOnStartup(this.specialty);
}
else if (this.name == '冬季新品') {
this.menuItems = initializeOnStartup(this.winterNew);
}
else if (this.name == '下飯菜') {
this.menuItems = initializeOnStartup(this.classic);
}
else if (this.name == '湯品') {
this.menuItems = initializeOnStartup(this.soup);
}
})
}, item => item)
}
.width('20%')
.backgroundColor('#FFFFFF')
Flex({ direction: FlexDirection.Column }) {
Text(this.name)
.fontSize('32lpx')
.fontWeight(FontWeight.Bold)
.opacity(0.4)
.height('8%')
Scroll() {
Column() {
List() {
ForEach(this.menuItems, item => {
ListItem() {
MenuListItem({ menuItem: item })
}
}, item => item.id.toString())
}
}
}
.height('92%')
}
.margin({ left: '10lpx' })
.width('75%')
}
.height('50%')
}
}
4)底部總額
• 主要用到 Flex 容器和 Stack 容器 Image 和 Text 組件;
• 從首頁點擊列表進入菜品詳細頁面,點菜成功後會自動返回首頁,更新訂單數量和總額;
• 點擊底部總額框,將訂單列表加入分散式資料庫,@entry 模擬監聽資料庫變化,拉起訂單列表詳情頁面。
@Component struct TotalInfo { @Consume TotalMenu: any[]; private total: number = 0; private amount: number = 0; private remoteData: MenuListData aboutToAppear() { for (var index = 0; index < this.TotalMenu.length; index++) { this.total = this.total + this.TotalMenu[index].price * this.TotalMenu[index].quantity this.amount = this.amount + this.TotalMenu[index].quantity } } build() { Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) { Stack({ alignContent: Alignment.Center }) { Image($r("app.media.icon_cart")) .width('96lpx') .height('96lpx') .margin({ left: '22lpx' }) Text(this.amount.toString()) .backgroundColor('#F84747') .borderRadius('30plx') .fontSize('24plx') .textAlign(TextAlign.Center) .fontColor('#FFFFFF') .width('50lpx') .height('50lpx') .margin({ left: '100lpx', bottom: '85lpx' }) } .width('150lpx') .height('150lpx') Text('¥') .fontSize('22lpx') .fontColor('#006A3A') .margin({ left: '22lpx' }) Text(this.total.toString()) .fontSize('40lpx') .fontColor('#006A3A') .flexGrow(1) Text('點好了') .height('100%') .width('35%') .fontColor('#FFFFFF') .backgroundColor('#F84747') .textAlign(TextAlign.Center) } // 將總的訂單數據,加入分散式資料庫 .onClick(() => { this.remoteData.putData("menu_list", this.TotalMenu) }) .width('100%') .height('10%') .backgroundColor('#FFFFFF') } }
2.2 菜品詳情頁
效果圖如上,可以分為三部分:
1)頂部頁標籤
@Component
struct PageInfo {
build() {
Flex() {
Text('點單頁')
.fontSize('36lpx')
}
.padding({ left: '48lpx', top: '28lpx' })
.width('100%')
.height('10%')
.backgroundColor('#FFFFFF')
}
}
2)菜單詳情
• 主要用到 Flex 容器 Image 和 Text 組件 Button 組件;
• 辣度可以選擇。
@Component
struct detailInfo {
private menuItem
private spicyList = ['正常辣', '加辣', '少辣']
@State spicy: string = '正常辣'
private TotalMenu: any[]
private index = 0
private userName: string
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
Flex({ direction: FlexDirection.Row }) {
Button()
.backgroundColor('#006A3A ')
.width('8lpx')
.height('48lpx')
.margin({ right: '12lpx' })
Text('辣度')
}
.margin({ left: '44lpx', top: '48lpx', bottom: '32lpx' })
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceEvenly }) {
ForEach(this.spicyList, item => {
Button(item)
.fontSize('28lpx')
.height('60lpx')
.width('156lpx')
.borderRadius('12lpx')
.backgroundColor(this.spicy == item ? '#006A3A' : '#0D000000')
.fontColor(this.spicy == item ? '#FFFFFF' : '#000000')
.onClick(() => {
this.spicy = item
})
}, item => item)
}
}
.margin({ top: '56lpx' })
.width('92%')
.height('50%')
.borderRadius('16lpx')
.backgroundColor('#FFFFFF')
}
}
}
3)點擊按鈕
• 點擊選好了,需要判斷該菜品是否已經在總訂單裡面,並判斷是哪一個用戶添加,根據判斷,做出相應的增加。
Button('選好了') .fontSize('36lpx') .width('80%') .height('7%') .backgroundColor('#F84747') .onClick(() => { for (this.index = 0; this.index < this.TotalMenu.length; this.index++) { if (this.TotalMenu[this.index].name == this.menuItem.name && this.TotalMenu[this.index].spicy == this.spicy) { this.TotalMenu[this.index].quantity = this.TotalMenu[this.index].quantity + 1; if (this.userName == 'Sunny') { this.TotalMenu[this.index].userNumber = this.TotalMenu[this.index].userNumber + 1; } else if (this.userName == 'Jenny') { this.TotalMenu[this.index].anotherUserNumber = this.TotalMenu[this.index].anotherUserNumber + 1; } break; } } // 菜名不一樣,辣度不一樣,都需要重新push到列表裡面 if (this.index == this.TotalMenu.length) { this.menuItem.spicy = this.spicy; this.menuItem.quantity = 1; //根據不用的用戶名稱, if (this.userName == 'Sunny') { this.menuItem.userNumber = 1; } else if (this.userName == 'Jenny') { this.menuItem.anotherUserNumber = 1; } this.TotalMenu.push(this.menuItem); } router.push({ uri: 'pages/index', params: { menuItem: this.menuItem, TotalMenu: this.TotalMenu } }) }) .margin({ top: '10%' })
2.3 訂單詳情頁
效果如上,可以分為三部分:
1)訂單列表
• 主要用到 Flex 容器 Image 和 Text 組件 Button 組件;
• 展示不同用戶加入菜單數量。
@Component
struct TotalItem {
private totalMenu: MenuData
build() {
Flex({ direction: FlexDirection.Column }) {
Flex({ direction: FlexDirection.Row, alignContent: FlexAlign.Start, justifyContent: FlexAlign.Start }) {
if (this.totalMenu.userNumber > 0) {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
Image(this.totalMenu.userImg)
.width('96lpx')
.height('96lpx')
Text(this.totalMenu.userName)
.fontSize('36lpx')
.fontWeight(FontWeight.Bold)
.margin({ left: '12lpx' })
.flexGrow(1)
Text(this.totalMenu.userNumber.toString())
.fontSize('32lpx')
.margin({ right: '11plx' })
}
.height('150lpx')
}
if (this.totalMenu.anotherUserNumber > 0) {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
Image(this.totalMenu.anotherUserImg)
.width('96lpx')
.height('96lpx')
Text(this.totalMenu.anotherUserName)
.fontSize('36lpx')
.fontWeight(FontWeight.Bold)
.margin({ left: '12lpx' })
.flexGrow(1)
Text(this.totalMenu.anotherUserNumber.toString())
.fontSize('32lpx')
.margin({ right: '11plx' })
}
.height('150lpx')
}
}
.margin({ top: '12lpx' })
.borderRadius('16lpx')
.padding({ left: '3%', right: '3%', top: '2%' })
.backgroundColor('#FFFFFF')
}
}
2)下單按鈕
• 點擊下單,將”submitOk” 加入分散式資料庫,監聽資料庫變化後,彈出自定義對話框。
@Component
struct SubmitList {
private remoteData: SubmitData
private SubmitOK: any[] = [
{
submit: "submitOk"
}
];
build() {
Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('下單')
.fontSize('36lpx')
.fontColor('#FFFFFF')
}
.width('100%')
.height('10%')
.backgroundColor('#F84747')
.onClick(() => {
this.remoteData.putData("submit", this.SubmitOK)
})
.margin({ top: '5%' })
}
}
3)自定義彈框
• 通過 @CustomDialog 裝飾器來創建自定義彈窗,使用方式可參考 自定義彈窗;
• 規則彈窗效果如下,彈窗組成由一個 Image 和兩個 Text 豎向排列組成;
• 在 build()下使用 Flex 容器來包裹,組件程式碼如下:
@CustomDialog
struct SubmitDialog {
private controller: CustomDialogController
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
Flex({ justifyContent: FlexAlign.Center }) {
Image($r("app.media.icon_success"))
.width('100lpx')
.height('80lpx')
}
.flexGrow(1)
Text('下單成功')
.fontSize('36lpx')
.fontColor('#000000')
.flexGrow(1)
Text('*溫馨提示:菜品具體售賣情況請以店面實際情況為準哦~')
.fontSize('22lpx')
.opacity(0.6)
.fontColor('#000000')
.padding({ left: '10lpx', right: '10lpx' })
}
.height('300lpx')
.width('100%')
.padding({ top: '50lpx', bottom: '20lpx' })
}
}
• 在 @entry 模組創建 CustomDialogController 對象並傳入彈窗所需參數,設置點擊允許點擊遮障層退出,通過 open() 方法,顯示彈窗。
SubmitDialog: CustomDialogController = new CustomDialogController({
builder: SubmitDialog(),
autoCancel: true
})
aboutToAppear() {
this.remoteData.createManager(() => {
let self = this
var data;
if (JSON.stringify(self.remoteData.dataItem).length > 0) {
data = self.remoteData.dataItem;
CommonLog.info("======submit==" + data[0].submit);
if (data[0].submit == "submitOk") {
this.SubmitDialog.open()
}
}
}, "com.distributed.order", "submit")
}
三、分散式數據管理
OpenHarmony 技術特性包括分散式數據管理、分散式任務調度等;分散式數據管理基於分散式軟匯流排的能力,實現應用程式數據和用戶數據的分散式管理。用戶數據不再與單一物理設備綁定,業務邏輯與數據存儲分離,跨設備的數據處理如同本地數據處理一樣方便快捷,讓開發者能夠輕鬆實現全場景、多設備下的數據存儲、共享和訪問,為打造一致、流暢的用戶體驗創造了基礎條件。
3.1 開發步驟
分散式數據管理要求兩個或多個設備在同一網路。開發步驟:
1)導入模組
import distributedData from '@ohos.data.distributedData';
2)創建一個 KVManager 對象實例,用於管理資料庫對象;注意 bundleName 需要修改為自己的包名。
let kvManager;
try {
const kvManagerConfig = {
bundleName : 'com.distributed.order',
userInfo : {
userId : '0',
userType : distributedData.UserType.SAME_USER_ID
}
}
distributedData.createKVManager(kvManagerConfig, function (err, manager) {
if (err) {
console.log("createKVManager err: " + JSON.stringify(err));
return;
}
console.log("createKVManager success")
kvManager = manager
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
3)通過指定 Options 和 storeId,創建並獲取 KVStore 資料庫,如下是參數說明;需要先通過 createKVManager 構建一個 KVManager 實例。
let kvStore;
let kvManager;
try {
const options = {
createIfMissing : true,
encrypt : false,
backup : false,
autoSync : true,
kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
securityLevel : distributedData.SecurityLevel.S2,
};
kvManager.getKVStore('storeId', options, function (err, store) {
if (err) {
console.log("getKVStore err: " + JSON.stringify(err));
return;
}
console.log("getKVStore success");
kvStore = store
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
4)KVStore 資料庫實例, KVStore.put 提供增加數據的方法,如下是參數說明。
let kvStore;
try {
kvStore.put(key, value, function (err,data) {
if (err != undefined) {
console.log("put err: " + JSON.stringify(err))
return;
}
console.log("put success");
});
}catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
5) KVStore 資料庫實例,KVStore.on 訂閱指定類型的數據變更通知;一般監聽遠端設備變化,再進行相應操作達到分散式數據共享的效果。
let kvStore;
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(data));
});
6)具體開發請參考分散式數據管理:
3.2 應用示例
本項目通過 storeId (資料庫唯一標識符)值不同,創建了兩個數據管理類,分別是 MenuListData 類和 SubmitData 類,即 Demo 中的 MenuListDistributedData.ets SubmitData.ets 文件。
1)MenuListData 是將完整訂單添加到分散式資料庫,當監聽到資料庫變化時,獲取完整訂單列表,並通過 router.push 介面將數據傳遞到訂單詳情頁面展示。
• 創建一個 MenuListData 類
private remoteData: MenuListData = new MenuListData()
• 定義一個訂單列表集合,集合中的元素包括菜單資訊和點單用戶資訊;點菜後就根據菜品名稱和辣度的不同,對訂單數據集合進行修改或增加。
TotalMenu: any[] = [
{
"imgSrc": "", // 菜品圖片
"name": "", // 菜品名稱
"remarks": "", // 菜品備註
"price": 0, // 菜品價格
"quantity": 0, // 菜品數量
"spicy": "", //辣度
"userImg": ,
"userName": "",
"userNumber": 0,
"anotherUserImg": "",
"anotherUserName": "",
"anotherUserNumber": 0,
}];
• 將訂單數據加入到分散式資料庫
this.remoteData.putData("menu_list", this.TotalMenu)
• 監聽資料庫變化,獲取數據,並將數據傳遞到 menuAccount 訂單詳情頁面;
this.remoteData.createManager(() => { let self = this var data if (JSON.stringify(self.remoteData.dataItem).length > 0) { data = self.remoteData.dataItem var list = [] for (var i = 0; i < data.length; i++) { list[i] = data[i] } router.push({ uri: 'pages/menuAccount', params: { TotalMenu: list } }) } })
2)SubmitData 在訂單結算時點擊下單,將 submitOK 集合添加到資料庫,表示下單完成,監聽到資料庫變化,各設備彈出下單成功提示框;
• 創建一個 SubmitData 類
private remoteData: SubmitData = new SubmitData();
• 定義一個 SubmitOK 集合,這裡用集合主要是為了處理數據方便
private SubmitOK: any[] = [
{
submit: "submitOk"
}
]
• 添加 SubmitOK 集合到資料庫中
this.remoteData.putData("submit", this.SubmitOK)
• 監聽到資料庫變化,獲取數據並比較是 submitOK 後,彈出提示框,告知所有人下單成功。
this.remoteData.createManager(() => {
let self = this
var data
if (JSON.stringify(self.remoteData.dataItem).length > 0) {
data = self.remoteData.dataItem
if (data[0].submit == "submitOk") {
this.SubmitDialog.open()
}
}
})
更完整的分散式資料庫的使用,請參考 Demo。
四、項目下載和導入
項目地址://gitee.com/openharmony-sig/knowledge_demo_temp/tree/master/FA/Shopping/DistributedOrder
1)git 下載
git clone //gitee.com/openharmony-sig/knowledge_demo_temp.git
2)項目導入
打開 DevEco Studio,點擊 File->Open->下載路徑/FA/Shopping/DistributedOrder
3)硬體約束
需要下載對應開發板鏡像(//gitee.com/openharmony/docs/blob/master/zh-cn/release-notes/OpenHarmony-v3.1-beta.md)進行燒錄;如下圖:
五、分享與共建
豐富多樣的 OpenHarmony 開發樣例離不開廣大合作夥伴和開發者的貢獻,如果你開發出了更好的 OpenHarmony 開發樣例,並願意分享給廣大開發者學習,請 Fork 並 Pull Request 到如下倉庫,共建 OpenHarmony 開發樣例。
若您不清楚如何提交程式碼到倉庫,請參考程式碼貢獻教程,我們等著你的 Pull Request。(//gitee.com/openharmony-sig/knowledge_demo_smart_home/blob/master/dev/docs/contribute/README.md)。