-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathesphomeYAMLGenerator.go
1198 lines (1053 loc) · 52.4 KB
/
esphomeYAMLGenerator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// cocoaGenerator ,ModBus 协议自动生成宝具,解放双手,得空摸鱼🐟!
// Powered By Luckykeeper <[email protected] | https://luckykeeper.site> 2022/11/27
package main
import (
"bufio"
"database/sql"
"fmt"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"path"
"strconv"
"strings"
"time"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/canvas"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/driver/desktop"
"fyne.io/fyne/v2/layout"
"fyne.io/fyne/v2/theme"
"fyne.io/fyne/v2/widget"
"github.com/flopp/go-findfont"
_ "github.com/mattn/go-sqlite3"
"github.com/xuri/excelize/v2"
"github.com/xuthus5/BaiduTranslate"
)
// 显示中文
// 设置环境变量 通过go-findfont 寻找simkai.ttf 字体
func init() {
fontPaths := findfont.List()
for _, path := range fontPaths {
if strings.Contains(path, "simkai.ttf") {
fmt.Println(path)
os.Setenv("FYNE_FONT", path) // 设置环境变量 // 取消环境变量 os.Unsetenv("FYNE_FONT")
break
}
}
}
var (
Content *fyne.Container
ContentTitle *widget.Label
ContentTitleBox *fyne.Container
contentBox *fyne.Container
RunTime = 0
LayoutChanged = false
sql_initialize_table = `CREATE TABLE cocoa (platform TEXT PRIMARY KEY NOT NULL,appid TEXT NOT NULL,secret TEXT NOT NULL);`
)
func main() {
// 先初始化数据库
if exists, _ := PathExists("./cocoaGenerator.db"); exists {
log.Println("数据库存在")
} else {
log.Println("创建数据库!")
db, _ := sql.Open("sqlite3", "./cocoaGenerator.db")
defer db.Close()
db.Exec(sql_initialize_table) //初始化
}
// App 基本信息
a := app.NewWithID("cocoagenerator.luckykeeper.site")
logo, _ := fyne.LoadResourceFromPath("cocoa.ico")
a.SetIcon(logo)
makeTray(a)
logLifecycle(a)
w := a.NewWindow("esphomeYAMLGenerator, A software to generate ESPHome YAML File | Powered by Luckykeeper | Build 20221127 | Ver 1.0.0")
w.SetMainMenu(makeMenu(a, w))
// 左侧菜单
menu := container.NewVBox(
widget.NewButtonWithIcon("Welcome esphomeYAMLGenerator!",
theme.HomeIcon(),
welcomeScreen),
widget.NewButtonWithIcon("翻译 API 设定",
theme.SettingsIcon(),
translateAPISetting),
widget.NewButtonWithIcon("来生成一下 YAML 文件吧~",
theme.DocumentPrintIcon(),
database),
widget.NewButtonWithIcon("奏了奏了~",
theme.LogoutIcon(),
func() { fyne.App.Quit(a) }),
)
left := container.New(layout.NewHBoxLayout(), menu, widget.NewSeparator())
go func() {
for {
time.Sleep(time.Millisecond * 500)
if RunTime == 0 {
ContentTitle = widget.NewLabel("雷猴哇~<( ̄︶ ̄)↗[GO!]")
ContentTitleBox = container.New(layout.NewVBoxLayout(), ContentTitle, widget.NewSeparator())
addImageIcon := canvas.NewImageFromFile("./img/cocoa.png")
addImageIcon.FillMode = canvas.ImageFillContain
addImageIcon.SetMinSize(fyne.NewSize(500, 500))
Content = container.NewCenter(container.NewVBox(
widget.NewLabelWithStyle("↑心爱酱可爱捏", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}),
widget.NewLabelWithStyle("Welcome to esphomeYAMLGenerator, A software to generate ESPHome YAML File", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}),
container.NewHBox(
widget.NewHyperlink("Powered By Luckykeeper", parseURL("https://luckykeeper.site/")),
widget.NewLabel("-"),
widget.NewHyperlink("Github", parseURL("https://github.com/luckykeeper/")),
widget.NewLabel("-"),
widget.NewHyperlink("Blog", parseURL("https://luckykeeper.site/")),
widget.NewLabel("-"),
widget.NewHyperlink("来找心爱酱玩~", parseURL("https://github.com/luckykeeper/LOVE69_renpy_remaster")),
),
))
Content = container.New(layout.NewVBoxLayout(), addImageIcon, Content)
}
contentBox = container.New(layout.NewBorderLayout(ContentTitleBox, nil, nil, nil), ContentTitleBox, Content)
if RunTime == 0 || LayoutChanged {
contentBox.Refresh()
RunTime = 1
LayoutChanged = false
}
// 显示主界面,分别:适应宽度,左侧菜单,分割线,右侧内容
w.SetContent(container.New(layout.NewBorderLayout(nil, nil, left, nil), left, contentBox))
}
}()
// 设置窗口大小
w.Resize(fyne.NewSize(1280, 720))
w.SetFixedSize(true)
// 润!
w.ShowAndRun()
}
// 欢迎界面
func welcomeScreen() {
ContentTitle = widget.NewLabel("雷猴哇~<( ̄︶ ̄)↗[GO!]")
ContentTitleBox = container.New(layout.NewVBoxLayout(), ContentTitle, widget.NewSeparator())
addImageIcon := canvas.NewImageFromFile("./img/cocoa.png")
addImageIcon.FillMode = canvas.ImageFillContain
addImageIcon.SetMinSize(fyne.NewSize(500, 500))
Content = container.NewCenter(container.NewVBox(
widget.NewLabelWithStyle("↑心爱酱可爱捏", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}),
widget.NewLabelWithStyle("Welcome to esphomeYAMLGenerator, A software to generate ESPHome YAML File", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}),
container.NewHBox(
widget.NewHyperlink("Powered By Luckykeeper", parseURL("https://luckykeeper.site/")),
widget.NewLabel("-"),
widget.NewHyperlink("Github", parseURL("https://github.com/luckykeeper/")),
widget.NewLabel("-"),
widget.NewHyperlink("Blog", parseURL("https://luckykeeper.site/")),
widget.NewLabel("-"),
widget.NewHyperlink("来找心爱酱玩~", parseURL("https://github.com/luckykeeper/LOVE69_renpy_remaster")),
),
))
Content = container.New(layout.NewVBoxLayout(), addImageIcon, Content)
contentBox = container.New(layout.NewBorderLayout(ContentTitleBox, nil, nil, nil), ContentTitleBox, Content)
LayoutChanged = true
}
// 翻译 API 设置界面
func translateAPISetting() {
baiduDataExists, baiduAppID, baiduSecret := DataExists("baidu")
ContentTitle = widget.NewLabel("在这里设置翻译 API !ヾ(≧▽≦*)o")
ContentTitleBox = container.New(layout.NewVBoxLayout(), ContentTitle, widget.NewSeparator())
// 添加图片小技巧:container 套 container ,注意 layout.NewVBoxLayout (或者 HBox )的时候会按照组件最小大小来排列
// 下面带字的会自动计算最小大小,但是你加的图片不会,所以你需要手动给它一个大小,不然就会被压成一个 1x1 的像素点(乐)
addImageIcon := canvas.NewImageFromFile("./img/yuuka.jpg")
addImageIcon.FillMode = canvas.ImageFillContain
addImageIcon.SetMinSize(fyne.NewSize(464, 329.6))
inputBaiduAppID := widget.NewEntry()
inputBaiduAppID.SetPlaceHolder("在这里填写APPID")
if baiduDataExists {
inputBaiduAppID.SetPlaceHolder(baiduAppID)
}
inputBaiduAppSecret := widget.NewEntry()
inputBaiduAppSecret.SetPlaceHolder("在这里填写Secret")
if baiduDataExists {
inputBaiduAppSecret.SetPlaceHolder(baiduSecret)
}
NoneInputBaiduErrorCode := widget.NewEntry()
explainInputBaiduAppID := widget.NewLabel("百度翻译API APPID:")
explainInputBaiduSecret := widget.NewLabel("百度翻译API Secret:")
explainInputBaiduErrorCode := widget.NewLabel("下面的输入框显示API测试结果")
baiduAppIDBox := container.New(layout.NewGridLayout(2), explainInputBaiduAppID, inputBaiduAppID)
baiduAppSecretBox := container.New(layout.NewGridLayout(2), explainInputBaiduSecret, inputBaiduAppSecret)
Content = container.NewCenter(
container.NewVBox(
widget.NewLabelWithStyle("在下面设置翻译API,目前支持百度翻译API", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}),
baiduAppIDBox,
baiduAppSecretBox,
container.NewVBox(
widget.NewButton("填好之后戳这里保存~(请勿重复点击)",
func() { saveTranslateAPISetting("baidu", inputBaiduAppID.Text, inputBaiduAppSecret.Text) },
),
container.NewVBox(
widget.NewButton("然后在这里测试API",
func() {
errorCode := testBaiduAPI()
if errorCode != "" {
NoneInputBaiduErrorCode.SetPlaceHolder(errorCode)
NoneInputBaiduErrorCode.Refresh()
}
},
)),
explainInputBaiduErrorCode, NoneInputBaiduErrorCode,
),
container.NewHBox(
widget.NewHyperlink("申请API", parseURL("https://api.fanyi.baidu.com/product/11")),
widget.NewLabel("-"),
widget.NewHyperlink("可用额度查询", parseURL("https://api.fanyi.baidu.com/api/trans/product/desktop")),
widget.NewLabel("-"),
widget.NewHyperlink("错误码说明", parseURL("https://api.fanyi.baidu.com/doc/21"))),
))
Content = container.New(layout.NewVBoxLayout(), addImageIcon, Content)
contentBox = container.New(layout.NewBorderLayout(ContentTitleBox, nil, nil, nil), ContentTitleBox, Content)
LayoutChanged = true
}
// 保存翻译平台 API 参数到数据库
func saveTranslateAPISetting(platform, appid, secret string) {
baiduDataExists, _, _ := DataExists("baidu")
db, _ := sql.Open("sqlite3", "./cocoaGenerator.db")
defer db.Close()
if baiduDataExists {
db.Exec("UPDATE cocoa SET appid='" + appid + "',secret='" + secret + "' WHERE platform='" + platform + "';")
} else if !baiduDataExists {
db.Exec("insert into cocoa (platform, appid,secret) values ('" + platform + "','" + appid + "','" + secret + "');")
}
}
// 判断翻译平台 API 参数是否存在
func DataExists(platform string) (result bool, appid, secret string) {
db, _ := sql.Open("sqlite3", "./cocoaGenerator.db")
defer db.Close()
querySql := "select appid,secret from cocoa where platform='" + platform + "';"
var data, data1 string
queryResult := db.QueryRow(querySql).Scan(&data, &data1)
if queryResult == sql.ErrNoRows {
result = false
appid = "nil"
secret = "nil"
return
} else { // 之前设置过相关参数
result = true
appid = data
secret = data1
return
}
}
// 测试百度翻译 API
func testBaiduAPI() (errorCode string) {
db, _ := sql.Open("sqlite3", "./cocoaGenerator.db")
defer db.Close()
queryBaiduAccountSql := "select appid,secret from cocoa where platform='baidu';"
var baiduAppID, baiduSecret string
queryResult := db.QueryRow(queryBaiduAccountSql).Scan(&baiduAppID, &baiduSecret)
if queryResult == sql.ErrNoRows {
return "请先填写上方参数"
} else { // 数据库存在参数
bi := BaiduTranslate.BaiduInfo{AppID: baiduAppID, Salt: BaiduTranslate.Salt(12), SecretKey: baiduSecret, From: "auto", To: "en"}
bi.Text = "你好"
// log.Println(bi.Translate())
if bi.Translate() == "Hello" {
return "百度翻译API测试成功!可正常生成YAML文件!"
} else {
return bi.Translate()
}
}
}
// 判断文件是否存在
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// 库存界面
func database() {
ContentTitle = widget.NewLabel("来这里生成YAML文件吧o(*≧▽≦)ツ┏━┓")
ContentTitleBox = container.New(layout.NewVBoxLayout(), ContentTitle, widget.NewSeparator())
addImageIcon := canvas.NewImageFromFile("./img/hoshino.jpg")
addImageIcon.FillMode = canvas.ImageFillContain
addImageIcon.SetMinSize(fyne.NewSize(259.33, 366.67))
Content = container.NewCenter(container.NewVBox(
widget.NewLabelWithStyle("先到device文件夹填写上位机设备模板【对应的IDF和Arduino框架文件应存在】", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}),
widget.NewLabelWithStyle("再去modbus文件夹填写上位机及从站参数,最后使用下面的生成功能吧", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}),
widget.NewLabelWithStyle("执行生成前务必保存并关闭相关Excel文件,生成完成后到generate文件夹找生成文件", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}),
widget.NewLabelWithStyle("【注意目前仅支持ESPHome+ModBus设备】", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}),
widget.NewLabelWithStyle("【使用生成功能会清空generate文件夹下的全部文件,请务必注意备份】", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}),
container.NewHBox(
widget.NewButtonWithIcon("生成arduino框架YAML文件(调试环境使用)",
theme.DocumentIcon(),
// generateArduino,
func() {
cleanGenerate()
generateArduino()
},
),
widget.NewButtonWithIcon("生成esp-idf框架YAML文件(生产环境使用)",
theme.DocumentIcon(),
// generateESPIDF,
func() {
cleanGenerate()
generateESPIDF()
},
),
widget.NewButtonWithIcon("同时生成两种框架的YAML文件",
theme.DocumentIcon(),
// generateAll,
func() {
cleanGenerate()
generateArduino()
generateESPIDF()
},
),
)))
Content = container.New(layout.NewVBoxLayout(), addImageIcon, Content)
contentBox = container.New(layout.NewBorderLayout(ContentTitleBox, nil, nil, nil), ContentTitleBox, Content)
LayoutChanged = true
}
// 生成ardiuno框架YAML文件
func generateArduino() {
// cleanGenerate()
// 寻找有效上位机及从站配置文件
dir, _ := ioutil.ReadDir("./modbus")
for _, file := range dir {
configFileName := file.Name()
configFileNameAll := path.Base(configFileName)
if ext := path.Ext(configFileName); ext == ".xlsx" {
if configFileNameAll == "ModBus_Template.xlsx" {
log.Println("检测到模板文件,跳过!")
} else {
// 在这里处理检测到的文件
log.Println("待处理文件全名:", configFileNameAll)
// 读取上位机设置参数
deviceTemplate, deviceName, apiPassword, otaPassword, wifiSSID, wifiPassword, staticIP,
netGateway, netmask, dnsServer, fallbackSSID, fallbackPassword, esphomeWebPort, esphomeWebUser, esphomeWebPassword := readPLCconfig(configFileNameAll)
// 调试:输出读取到的上位机设置参数
// log.Println("设备模板:", deviceTemplate)
// log.Println("设备名称:", deviceName)
// log.Println("api密码:", apiPassword)
// log.Println("ota密码:", otaPassword)
// log.Println("wifi名称:", wifiSSID)
// log.Println("wifi密码:", wifiPassword)
// log.Println("固定IP地址:", staticIP)
// log.Println("网关地址:", netGateway)
// log.Println("子网掩码:", netmask)
// log.Println("DNS服务器:", dnsServer)
// log.Println("回退WiFi名称:", fallbackSSID)
// log.Println("回退WiFi密码:", fallbackPassword)
// log.Println("web 端口:", esphomeWebPort)
// log.Println("web 用户:", esphomeWebUser)
// log.Println("web 密码:", esphomeWebPassword)
log.Println("____________")
// 读取并处理上位机设置模板(ardiuno框架)
// 读取并复制(创建)目标文件
destYAMLFile := "./generate/" + deviceName + "_arduino.yaml"
copy("./device/arduino/"+deviceTemplate+".txt", destYAMLFile, 64)
// 替换关键词,完成上位机设置
tempbuffer, _ := ioutil.ReadFile(destYAMLFile)
templateContent := string(tempbuffer)
//替换写入上位机配置参数
tempContent := strings.Replace(templateContent, "cocoaGenerator", deviceName, -1)
tempContent = strings.Replace(tempContent, "cocoaApiPassword", apiPassword, -1)
tempContent = strings.Replace(tempContent, "cocoaOtaPassword", otaPassword, -1)
tempContent = strings.Replace(tempContent, "cocoaWifiName", wifiSSID, -1)
tempContent = strings.Replace(tempContent, "cocoaWifiPassword", wifiPassword, -1)
tempContent = strings.Replace(tempContent, "cocoaDeviceIp", staticIP, -1)
tempContent = strings.Replace(tempContent, "cocoaDeviceGateway", netGateway, -1)
tempContent = strings.Replace(tempContent, "cocoaDeviceNetmask", netmask, -1)
tempContent = strings.Replace(tempContent, "cocoaDeviceDns", dnsServer, -1)
tempContent = strings.Replace(tempContent, "CocoaFallback", fallbackSSID, -1)
tempContent = strings.Replace(tempContent, "CocoaEsp32!", fallbackPassword, -1)
tempContent = strings.Replace(tempContent, "cocoaWebPort", esphomeWebPort, -1)
tempContent = strings.Replace(tempContent, "cocoawebUser", esphomeWebUser, -1)
tempContent = strings.Replace(tempContent, "cocoawebPassword", esphomeWebPassword, -1)
//重新写回
ioutil.WriteFile(destYAMLFile, []byte(tempContent), 0)
// —————— 上位机数据处理完成,下面开始处理从站数据 ——————
// Step1:采集从站配置数据并写入 sqlite
// Step2:生成 modbus_controller
// Step3:按照 modbus_controller 顺序生成 sensor
// Step4: 按照 modbus_controller 顺序生成 binary_sensor
// 需要进行地址去重,这里把数据写入 sqlite 后借用 sql 语句完成此工作
// Step1:采集从站配置数据并写入 sqlite
// 为了后续排序处理方便,统一将十六进制的从站地址转换成十进制处理
sql_drop_modbus_tables := `DROP TABLE modbus;`
sql_initialize_modbus_tables := `CREATE TABLE modbus (sensorType TEXT NOT NULL,modbusAddress TEXT NOT NULL,modbusName TEXT NOT NULL,
functionCode TEXT NOT NULL,registerName TEXT NOT NULL,registerAddress TEXT NOT NULL,registerCount TEXT NOT NULL,unit TEXT,
dataType TEXT,accuracy TEXT,haClass TEXT,multiply TEXT,invert TEXT);`
db, _ := sql.Open("sqlite3", "./cocoaGenerator.db")
defer db.Close()
db.Exec(sql_drop_modbus_tables)
db.Exec(sql_initialize_modbus_tables)
// 依次读取各行从站配置数据
modbusConfigExcel, _ := excelize.OpenFile("./modbus/" + configFileNameAll)
for line := 5; line >= 2; line++ {
sensorType, _ := modbusConfigExcel.GetCellValue("从站设置", "B"+strconv.Itoa(line)) // 传感器类型
modbusAddress, _ := modbusConfigExcel.GetCellValue("从站设置", "C"+strconv.Itoa(line)) // 从站地址
// 当从站地址是十六进制时,需要转十进制存储
if strings.Contains(modbusAddress, "0x") {
modbusAddressInt64, _ := strconv.ParseUint(modbusAddress[2:], 16, 32)
modbusAddress = fmt.Sprintf("%d", modbusAddressInt64)
}
modbusName, _ := modbusConfigExcel.GetCellValue("从站设置", "D"+strconv.Itoa(line)) // 从站名称
functionCode, _ := modbusConfigExcel.GetCellValue("从站设置", "E"+strconv.Itoa(line)) // 功能码
registerName, _ := modbusConfigExcel.GetCellValue("从站设置", "F"+strconv.Itoa(line)) // 寄存器数据名称
registerAddress, _ := modbusConfigExcel.GetCellValue("从站设置", "G"+strconv.Itoa(line)) // 寄存器地址
registerCount, _ := modbusConfigExcel.GetCellValue("从站设置", "H"+strconv.Itoa(line)) // 寄存器个数
unit, _ := modbusConfigExcel.GetCellValue("从站设置", "I"+strconv.Itoa(line)) // 单位
dataType, _ := modbusConfigExcel.GetCellValue("从站设置", "J"+strconv.Itoa(line)) // 数据类型
accuracy, _ := modbusConfigExcel.GetCellValue("从站设置", "K"+strconv.Itoa(line)) // 数据精度
haClass, _ := modbusConfigExcel.GetCellValue("从站设置", "L"+strconv.Itoa(line)) // ha类别
multiply, _ := modbusConfigExcel.GetCellValue("从站设置", "M"+strconv.Itoa(line)) // 变比
invert, _ := modbusConfigExcel.GetCellValue("从站设置", "N"+strconv.Itoa(line)) // 反转
if sensorType == "" {
line = 0
} else {
// // 调试:输出读取到的从站配置参数
// log.Println("传感器类型:", sensorType)
// log.Println("从站地址:", modbusAddress)
// log.Println("从站名称:", modbusName)
// log.Println("功能码:", functionCode)
// log.Println("寄存器数据名称:", registerName)
// log.Println("寄存器地址:", registerAddress)
// log.Println("寄存器个数:", registerCount)
// log.Println("单位:", unit)
// log.Println("数据类型:", dataType)
// log.Println("数据精度:", accuracy)
// log.Println("ha类别:", haClass)
// log.Println("变比:", multiply)
// log.Println("反转:", invert)
// log.Println("____________")
// 写入数据库
sql_writeTo_modbus_table := "insert into modbus (sensorType, modbusAddress,modbusName,functionCode," +
"registerName,registerAddress,registerCount,unit,dataType,accuracy,haClass,multiply," +
"invert) values ('" + sensorType + "','" + modbusAddress + "','" + modbusName + "','" + functionCode + "','" + registerName + "','" +
registerAddress + "','" + registerCount + "','" + unit + "','" + dataType + "','" + accuracy + "','" +
haClass + "','" + multiply + "','" + invert + "');"
// log.Println("sqlWrite:", sql_writeTo_modbus_table)
db.Exec(sql_writeTo_modbus_table)
}
}
log.Println("Step1完成!")
// 以上, Step1 完成
// Step2:生成 modbus_controller
// ardiuno 框架的 modbus_controller 示例如下
// modbus_controller:
// # 01 康耐德温湿度传感器
// - id: ${device_name}_modbus_controller_01
// modbus_id: ${device_name}_modbus
// address: 0x01
// command_throttle: 200ms
// setup_priority: -10
// update_interval: 10s
// 选取去重并按照 ASCII 升序排序的从站地址
queryControllerAddressAndItsNameSql := "SELECT DISTINCT modbusAddress,modbusName FROM modbus ORDER BY modbusAddress;"
addControllerFile, _ := os.OpenFile(destYAMLFile, os.O_APPEND, os.ModePerm)
defer addControllerFile.Close()
addControllerFileWriter := bufio.NewWriter(addControllerFile)
addControllerFileWriter.WriteString("\n")
addControllerFileWriter.WriteString("modbus_controller:\n")
rows, _ := db.Query(queryControllerAddressAndItsNameSql)
// 批量生成 modbus_controller
for rows.Next() {
var modbusAddress string
var modbusName string
rows.Scan(&modbusAddress, &modbusName)
addControllerFileWriter.WriteString(" # " + modbusAddress + " " + modbusName + "\n")
addControllerFileWriter.WriteString(" - id: ${device_name}_modbus_controller_" + modbusAddress + "\n")
addControllerFileWriter.WriteString(" modbus_id: ${device_name}_modbus\n")
addControllerFileWriter.WriteString(" address: " + modbusAddress + "\n")
addControllerFileWriter.WriteString(" command_throttle: 200ms\n")
addControllerFileWriter.WriteString(" setup_priority: -10\n")
addControllerFileWriter.WriteString(" update_interval: 10s\n")
addControllerFileWriter.WriteString("\n")
}
addControllerFileWriter.Flush()
log.Println("Step2完成!")
// 以上, Step2 完成
// Step3:按照 modbus_controller 顺序生成 sensor
// sensor 模板如下:
// sensor:
// - platform: modbus_controller
// modbus_controller_id: ${device_name}_modbus_controller_01
// id: ${device_name}_modbus_01_temp
// name: "Node 3# Temperature"
// address: 0x0258
// register_count: 2
// unit_of_measurement: "°C"
// register_type: holding
// value_type: FP32_R
// accuracy_decimals: 1
// device_class: temperature
// filters:
// - multiply: 0.1
addControllerFileWriter.WriteString("sensor:\n")
queryControllerAddressSql := "SELECT DISTINCT modbusAddress FROM modbus ORDER BY modbusAddress;"
rows1, _ := db.Query(queryControllerAddressSql)
// 按照地址生成 modbus_controller
for rows1.Next() {
var modbusAddress string
rows1.Scan(&modbusAddress)
// log.Println("modbusAddress:", modbusAddress)
getModbusDetailByModbusAddressAndSensorType := "SELECT functionCode,registerName,registerAddress,registerCount,unit,dataType,accuracy,haClass,multiply,invert FROM modbus WHERE modbusAddress='" + modbusAddress + "' AND sensorType='sensor';"
detailSensorRows, _ := db.Query(getModbusDetailByModbusAddressAndSensorType)
for detailSensorRows.Next() {
var functionCode, registerName, registerAddress, registerCount, unit, dataType, accuracy, haClass, multiply, invert string
detailSensorRows.Scan(&functionCode, ®isterName, ®isterAddress, ®isterCount, &unit, &dataType, &accuracy, &haClass, &multiply, &invert)
var baiduAppID, baiduSecret string
queryBaiduAccountSql := "select appid,secret from cocoa where platform='baidu';"
db.QueryRow(queryBaiduAccountSql).Scan(&baiduAppID, &baiduSecret)
bi := BaiduTranslate.BaiduInfo{AppID: baiduAppID, Salt: BaiduTranslate.Salt(12), SecretKey: baiduSecret, From: "auto", To: "en"}
bi.Text = registerName
translateRawStr := bi.Translate()
translateStrWithoutSpace := strings.Replace(translateRawStr, " ", "_", -1)
translateStrWithoutSpace = strings.Replace(translateStrWithoutSpace, "#", "", -1)
translateStrWithoutSpace = strings.Replace(translateStrWithoutSpace, "__", "_", -1)
translateStrWithoutSpace = strings.Replace(translateStrWithoutSpace, "-", "_", -1)
// log.Println("registerName:", registerName)
// log.Println("translateRawStr:", translateRawStr)
// log.Println("translateStrWithoutSpace:", translateStrWithoutSpace)
addControllerFileWriter.WriteString("\n # " + registerName + "\n")
addControllerFileWriter.WriteString(" - platform: modbus_controller\n")
addControllerFileWriter.WriteString(" modbus_controller_id: ${device_name}_modbus_controller_" + modbusAddress + "\n")
addControllerFileWriter.WriteString(" id: ${device_name}_modbus_" + modbusAddress + "_" + translateStrWithoutSpace + "\n")
addControllerFileWriter.WriteString(" name: \"" + translateRawStr + "\"\n")
addControllerFileWriter.WriteString(" address: " + registerAddress + "\n")
addControllerFileWriter.WriteString(" register_count: " + registerCount + "\n")
if unit != "" {
addControllerFileWriter.WriteString(" unit_of_measurement: \"" + unit + "\"\n")
}
addControllerFileWriter.WriteString(" register_type: " + functionCode + "\n")
if dataType != "" {
addControllerFileWriter.WriteString(" value_type: " + dataType + "\n")
}
if accuracy != "" {
addControllerFileWriter.WriteString(" accuracy_decimals: " + accuracy + "\n")
}
if haClass != "" {
addControllerFileWriter.WriteString(" device_class: " + haClass + "\n")
}
// filters -> 针对 Sensor 和 binary_senor 通用判断语句(注意两个是不可能同时出现的)
if multiply != "" || invert != "" {
addControllerFileWriter.WriteString(" filters:\n")
addControllerFileWriter.WriteString(" - ")
if multiply != "" {
addControllerFileWriter.WriteString("multiply: " + multiply + "\n")
} else if invert != "" {
addControllerFileWriter.WriteString("invert\n")
}
}
}
}
addControllerFileWriter.Flush()
log.Println("Step3完成!")
// Step4: 按照 modbus_controller 顺序生成 binary_sensor
// 以下是 binary_sensor 示例
// # 1#低压传感器失效
// - platform: modbus_controller
// modbus_controller_id: ${device_name}_modbus_controller_01
// id: ${device_name}_01_low_pressure_sensor_failure
// name: "1# low pressure sensor failure"
// register_type: holding
// address: 0x0551
// device_class: problem
addControllerFileWriter.WriteString("\nbinary_sensor:\n")
rows2, _ := db.Query(queryControllerAddressSql)
// 按照地址生成 modbus_controller
for rows2.Next() {
var modbusAddress string
rows2.Scan(&modbusAddress)
// log.Println("modbusAddress:", modbusAddress)
queryModbusBinarySensor := "SELECT functionCode,registerName,registerAddress,registerCount,unit,dataType,accuracy,haClass,multiply,invert FROM modbus WHERE modbusAddress='" + modbusAddress + "' AND sensorType='binary_sensor';"
detailBinarySensorRows, _ := db.Query(queryModbusBinarySensor)
for detailBinarySensorRows.Next() {
var functionCode, registerName, registerAddress, registerCount, unit, dataType, accuracy, haClass, multiply, invert string
detailBinarySensorRows.Scan(&functionCode, ®isterName, ®isterAddress, ®isterCount, &unit, &dataType, &accuracy, &haClass, &multiply, &invert)
var baiduAppID, baiduSecret string
queryBaiduAccountSql := "select appid,secret from cocoa where platform='baidu';"
db.QueryRow(queryBaiduAccountSql).Scan(&baiduAppID, &baiduSecret)
bi := BaiduTranslate.BaiduInfo{AppID: baiduAppID, Salt: BaiduTranslate.Salt(12), SecretKey: baiduSecret, From: "auto", To: "en"}
bi.Text = registerName
translateRawStr := bi.Translate()
translateStrWithoutSpace := strings.Replace(translateRawStr, " ", "_", -1)
translateStrWithoutSpace = strings.Replace(translateStrWithoutSpace, "#", "", -1)
translateStrWithoutSpace = strings.Replace(translateStrWithoutSpace, "__", "_", -1)
// log.Println("registerName:", registerName)
// log.Println("translateRawStr:", translateRawStr)
// log.Println("translateStrWithoutSpace:", translateStrWithoutSpace)
addControllerFileWriter.WriteString("\n # " + registerName + "\n")
addControllerFileWriter.WriteString(" - platform: modbus_controller\n")
addControllerFileWriter.WriteString(" modbus_controller_id: ${device_name}_modbus_controller_" + modbusAddress + "\n")
addControllerFileWriter.WriteString(" id: ${device_name}_modbus_" + modbusAddress + "_" + translateStrWithoutSpace + "\n")
addControllerFileWriter.WriteString(" name: \"" + translateRawStr + "\"\n")
addControllerFileWriter.WriteString(" register_type: " + functionCode + "\n")
addControllerFileWriter.WriteString(" address: " + registerAddress + "\n")
if haClass != "" {
addControllerFileWriter.WriteString(" device_class: " + haClass + "\n")
}
// filters -> 针对 Sensor 和 binary_senor 通用判断语句(注意两个是不可能同时出现的)
if multiply != "" || invert != "" {
addControllerFileWriter.WriteString(" filters:\n")
addControllerFileWriter.WriteString(" - ")
if multiply != "" {
addControllerFileWriter.WriteString("multiply: " + multiply + "\n")
} else if invert != "" {
addControllerFileWriter.WriteString("invert\n")
}
}
}
}
addControllerFileWriter.Flush()
log.Println("Step4完成!")
log.Println(destYAMLFile, "->生成完成")
}
}
}
}
// 生成ESP-IDF框架YAML文件
// 考虑到单独使用一种功能的情况,虽然两种生成方法类似但是没有单独提出来
func generateESPIDF() {
// cleanGenerate()
// 寻找有效上位机及从站配置文件
dir, _ := ioutil.ReadDir("./modbus")
for _, file := range dir {
configFileName := file.Name()
configFileNameAll := path.Base(configFileName)
if ext := path.Ext(configFileName); ext == ".xlsx" {
if configFileNameAll == "ModBus_Template.xlsx" {
log.Println("检测到模板文件,跳过!")
} else {
// 在这里处理检测到的文件
log.Println("待处理文件全名:", configFileNameAll)
// 读取上位机设置参数
deviceTemplate, deviceName, apiPassword, otaPassword, wifiSSID, wifiPassword, staticIP,
netGateway, netmask, dnsServer, fallbackSSID, fallbackPassword, esphomeWebPort, esphomeWebUser, esphomeWebPassword := readPLCconfig(configFileNameAll)
// 调试:输出读取到的上位机设置参数
// log.Println("设备模板:", deviceTemplate)
// log.Println("设备名称:", deviceName)
// log.Println("api密码:", apiPassword)
// log.Println("ota密码:", otaPassword)
// log.Println("wifi名称:", wifiSSID)
// log.Println("wifi密码:", wifiPassword)
// log.Println("固定IP地址:", staticIP)
// log.Println("网关地址:", netGateway)
// log.Println("子网掩码:", netmask)
// log.Println("DNS服务器:", dnsServer)
// log.Println("回退WiFi名称:", fallbackSSID)
// log.Println("回退WiFi密码:", fallbackPassword)
// log.Println("web 端口:", esphomeWebPort)
// log.Println("web 用户:", esphomeWebUser)
// log.Println("web 密码:", esphomeWebPassword)
log.Println("____________")
// 读取并处理上位机设置模板(ardiuno框架)[说明:先按照ardiuno框架生成,再转换为IDF]
// 读取并复制(创建)目标文件
destYAMLFile := "./generate/" + deviceName + "_espidf.yaml"
copy("./device/esp-idf/"+deviceTemplate+".txt", destYAMLFile, 64)
// 替换关键词,完成上位机设置
tempbuffer, _ := ioutil.ReadFile(destYAMLFile)
templateContent := string(tempbuffer)
//替换写入上位机配置参数
tempContent := strings.Replace(templateContent, "cocoaGenerator", deviceName, -1)
tempContent = strings.Replace(tempContent, "cocoaApiPassword", apiPassword, -1)
tempContent = strings.Replace(tempContent, "cocoaOtaPassword", otaPassword, -1)
tempContent = strings.Replace(tempContent, "cocoaWifiName", wifiSSID, -1)
tempContent = strings.Replace(tempContent, "cocoaWifiPassword", wifiPassword, -1)
tempContent = strings.Replace(tempContent, "cocoaDeviceIp", staticIP, -1)
tempContent = strings.Replace(tempContent, "cocoaDeviceGateway", netGateway, -1)
tempContent = strings.Replace(tempContent, "cocoaDeviceNetmask", netmask, -1)
tempContent = strings.Replace(tempContent, "cocoaDeviceDns", dnsServer, -1)
tempContent = strings.Replace(tempContent, "CocoaFallback", fallbackSSID, -1)
tempContent = strings.Replace(tempContent, "CocoaEsp32!", fallbackPassword, -1)
tempContent = strings.Replace(tempContent, "cocoaWebPort", esphomeWebPort, -1)
tempContent = strings.Replace(tempContent, "cocoawebUser", esphomeWebUser, -1)
tempContent = strings.Replace(tempContent, "cocoawebPassword", esphomeWebPassword, -1)
//重新写回
ioutil.WriteFile(destYAMLFile, []byte(tempContent), 0)
// —————— 上位机数据处理完成,下面开始处理从站数据 ——————
// Step1:采集从站配置数据并写入 sqlite
// Step2:生成 modbus_controller
// Step3:按照 modbus_controller 顺序生成 sensor
// Step4: 按照 modbus_controller 顺序生成 binary_sensor
// 需要进行地址去重,这里把数据写入 sqlite 后借用 sql 语句完成此工作
// Step1:采集从站配置数据并写入 sqlite
// 为了后续排序处理方便,统一将十六进制的从站地址转换成十进制处理
sql_drop_modbus_tables := `DROP TABLE modbus;`
sql_initialize_modbus_tables := `CREATE TABLE modbus (sensorType TEXT NOT NULL,modbusAddress TEXT NOT NULL,modbusName TEXT NOT NULL,
functionCode TEXT NOT NULL,registerName TEXT NOT NULL,registerAddress TEXT NOT NULL,registerCount TEXT NOT NULL,unit TEXT,
dataType TEXT,accuracy TEXT,haClass TEXT,multiply TEXT,invert TEXT);`
db, _ := sql.Open("sqlite3", "./cocoaGenerator.db")
defer db.Close()
db.Exec(sql_drop_modbus_tables)
db.Exec(sql_initialize_modbus_tables)
// 依次读取各行从站配置数据
modbusConfigExcel, _ := excelize.OpenFile("./modbus/" + configFileNameAll)
for line := 5; line >= 2; line++ {
sensorType, _ := modbusConfigExcel.GetCellValue("从站设置", "B"+strconv.Itoa(line)) // 传感器类型
modbusAddress, _ := modbusConfigExcel.GetCellValue("从站设置", "C"+strconv.Itoa(line)) // 从站地址
// 当从站地址是十六进制时,需要转十进制存储
if strings.Contains(modbusAddress, "0x") {
modbusAddressInt64, _ := strconv.ParseUint(modbusAddress[2:], 16, 32)
modbusAddress = fmt.Sprintf("%d", modbusAddressInt64)
}
modbusName, _ := modbusConfigExcel.GetCellValue("从站设置", "D"+strconv.Itoa(line)) // 从站名称
functionCode, _ := modbusConfigExcel.GetCellValue("从站设置", "E"+strconv.Itoa(line)) // 功能码
registerName, _ := modbusConfigExcel.GetCellValue("从站设置", "F"+strconv.Itoa(line)) // 寄存器数据名称
registerAddress, _ := modbusConfigExcel.GetCellValue("从站设置", "G"+strconv.Itoa(line)) // 寄存器地址
registerCount, _ := modbusConfigExcel.GetCellValue("从站设置", "H"+strconv.Itoa(line)) // 寄存器个数
unit, _ := modbusConfigExcel.GetCellValue("从站设置", "I"+strconv.Itoa(line)) // 单位
dataType, _ := modbusConfigExcel.GetCellValue("从站设置", "J"+strconv.Itoa(line)) // 数据类型
accuracy, _ := modbusConfigExcel.GetCellValue("从站设置", "K"+strconv.Itoa(line)) // 数据精度
haClass, _ := modbusConfigExcel.GetCellValue("从站设置", "L"+strconv.Itoa(line)) // ha类别
multiply, _ := modbusConfigExcel.GetCellValue("从站设置", "M"+strconv.Itoa(line)) // 变比
invert, _ := modbusConfigExcel.GetCellValue("从站设置", "N"+strconv.Itoa(line)) // 反转
if sensorType == "" {
line = 0
} else {
// // 调试:输出读取到的从站配置参数
// log.Println("传感器类型:", sensorType)
// log.Println("从站地址:", modbusAddress)
// log.Println("从站名称:", modbusName)
// log.Println("功能码:", functionCode)
// log.Println("寄存器数据名称:", registerName)
// log.Println("寄存器地址:", registerAddress)
// log.Println("寄存器个数:", registerCount)
// log.Println("单位:", unit)
// log.Println("数据类型:", dataType)
// log.Println("数据精度:", accuracy)
// log.Println("ha类别:", haClass)
// log.Println("变比:", multiply)
// log.Println("反转:", invert)
// log.Println("____________")
// 写入数据库
sql_writeTo_modbus_table := "insert into modbus (sensorType, modbusAddress,modbusName,functionCode," +
"registerName,registerAddress,registerCount,unit,dataType,accuracy,haClass,multiply," +
"invert) values ('" + sensorType + "','" + modbusAddress + "','" + modbusName + "','" + functionCode + "','" + registerName + "','" +
registerAddress + "','" + registerCount + "','" + unit + "','" + dataType + "','" + accuracy + "','" +
haClass + "','" + multiply + "','" + invert + "');"
// log.Println("sqlWrite:", sql_writeTo_modbus_table)
db.Exec(sql_writeTo_modbus_table)
}
}
log.Println("Step1完成!")
// 以上, Step1 完成
// Step2:生成 modbus_controller
// ardiuno 框架的 modbus_controller 示例如下
// modbus_controller:
// # 01 康耐德温湿度传感器
// - id: ${device_name}_modbus_controller_01
// modbus_id: ${device_name}_modbus
// address: 0x01
// command_throttle: 200ms
// setup_priority: -10
// update_interval: 10s
// 选取去重并按照 ASCII 升序排序的从站地址
queryControllerAddressAndItsNameSql := "SELECT DISTINCT modbusAddress,modbusName FROM modbus ORDER BY modbusAddress;"
addControllerFile, _ := os.OpenFile(destYAMLFile, os.O_APPEND, os.ModePerm)
defer addControllerFile.Close()
addControllerFileWriter := bufio.NewWriter(addControllerFile)
addControllerFileWriter.WriteString("\n")
addControllerFileWriter.WriteString("modbus_controller:\n")
rows, _ := db.Query(queryControllerAddressAndItsNameSql)
// 批量生成 modbus_controller
for rows.Next() {
var modbusAddress string
var modbusName string
rows.Scan(&modbusAddress, &modbusName)
addControllerFileWriter.WriteString(" # " + modbusAddress + " " + modbusName + "\n")
addControllerFileWriter.WriteString(" - id: ${device_name}_modbus_controller_" + modbusAddress + "\n")
addControllerFileWriter.WriteString(" modbus_id: ${device_name}_modbus\n")
addControllerFileWriter.WriteString(" address: " + modbusAddress + "\n")
addControllerFileWriter.WriteString(" command_throttle: 200ms\n")
addControllerFileWriter.WriteString(" setup_priority: -10\n")
addControllerFileWriter.WriteString(" update_interval: 10s\n")
addControllerFileWriter.WriteString("\n")
}
addControllerFileWriter.Flush()
log.Println("Step2完成!")
// 以上, Step2 完成
// Step3:按照 modbus_controller 顺序生成 sensor
// sensor 模板如下:
// sensor:
// - platform: modbus_controller
// modbus_controller_id: ${device_name}_modbus_controller_01
// id: ${device_name}_modbus_01_temp
// name: "Node 3# Temperature"
// address: 0x0258
// register_count: 2
// unit_of_measurement: "°C"
// register_type: holding
// value_type: FP32_R
// accuracy_decimals: 1
// device_class: temperature
// filters:
// - multiply: 0.1
addControllerFileWriter.WriteString("sensor:\n")
queryControllerAddressSql := "SELECT DISTINCT modbusAddress FROM modbus ORDER BY modbusAddress;"
rows1, _ := db.Query(queryControllerAddressSql)
// 按照地址生成 modbus_controller
for rows1.Next() {
var modbusAddress string
rows1.Scan(&modbusAddress)
// log.Println("modbusAddress:", modbusAddress)
getModbusDetailByModbusAddressAndSensorType := "SELECT functionCode,registerName,registerAddress,registerCount,unit,dataType,accuracy,haClass,multiply,invert FROM modbus WHERE modbusAddress='" + modbusAddress + "' AND sensorType='sensor';"
detailSensorRows, _ := db.Query(getModbusDetailByModbusAddressAndSensorType)
for detailSensorRows.Next() {
var functionCode, registerName, registerAddress, registerCount, unit, dataType, accuracy, haClass, multiply, invert string
detailSensorRows.Scan(&functionCode, ®isterName, ®isterAddress, ®isterCount, &unit, &dataType, &accuracy, &haClass, &multiply, &invert)
var baiduAppID, baiduSecret string
queryBaiduAccountSql := "select appid,secret from cocoa where platform='baidu';"
db.QueryRow(queryBaiduAccountSql).Scan(&baiduAppID, &baiduSecret)
bi := BaiduTranslate.BaiduInfo{AppID: baiduAppID, Salt: BaiduTranslate.Salt(12), SecretKey: baiduSecret, From: "auto", To: "en"}
bi.Text = registerName
translateRawStr := bi.Translate()
translateStrWithoutSpace := strings.Replace(translateRawStr, " ", "_", -1)
translateStrWithoutSpace = strings.Replace(translateStrWithoutSpace, "#", "", -1)
translateStrWithoutSpace = strings.Replace(translateStrWithoutSpace, "__", "_", -1)
// log.Println("registerName:", registerName)
// log.Println("translateRawStr:", translateRawStr)
// log.Println("translateStrWithoutSpace:", translateStrWithoutSpace)
addControllerFileWriter.WriteString("\n # " + registerName + "\n")
addControllerFileWriter.WriteString(" - platform: modbus_controller\n")
addControllerFileWriter.WriteString(" modbus_controller_id: ${device_name}_modbus_controller_" + modbusAddress + "\n")
addControllerFileWriter.WriteString(" id: ${device_name}_modbus_" + modbusAddress + "_" + translateStrWithoutSpace + "\n")
addControllerFileWriter.WriteString(" name: \"" + translateRawStr + "\"\n")
addControllerFileWriter.WriteString(" address: " + registerAddress + "\n")
addControllerFileWriter.WriteString(" register_count: " + registerCount + "\n")
if unit != "" {
addControllerFileWriter.WriteString(" unit_of_measurement: \"" + unit + "\"\n")
}
addControllerFileWriter.WriteString(" register_type: " + functionCode + "\n")
if dataType != "" {
addControllerFileWriter.WriteString(" value_type: " + dataType + "\n")
}
if accuracy != "" {
addControllerFileWriter.WriteString(" accuracy_decimals: " + accuracy + "\n")
}
if haClass != "" {
addControllerFileWriter.WriteString(" device_class: " + haClass + "\n")
}
// filters -> 针对 Sensor 和 binary_senor 通用判断语句(注意两个是不可能同时出现的)
if multiply != "" || invert != "" {
addControllerFileWriter.WriteString(" filters:\n")
addControllerFileWriter.WriteString(" - ")
if multiply != "" {
addControllerFileWriter.WriteString("multiply: " + multiply + "\n")
} else if invert != "" {
addControllerFileWriter.WriteString("invert\n")
}
}
}
}
addControllerFileWriter.Flush()
log.Println("Step3完成!")
// Step4: 按照 modbus_controller 顺序生成 binary_sensor
// 以下是 binary_sensor 示例
// # 1#低压传感器失效
// - platform: modbus_controller
// modbus_controller_id: ${device_name}_modbus_controller_01
// id: ${device_name}_01_low_pressure_sensor_failure
// name: "1# low pressure sensor failure"
// register_type: holding
// address: 0x0551
// device_class: problem
addControllerFileWriter.WriteString("\nbinary_sensor:\n")
rows2, _ := db.Query(queryControllerAddressSql)
// 按照地址生成 modbus_controller
for rows2.Next() {
var modbusAddress string
rows2.Scan(&modbusAddress)
// log.Println("modbusAddress:", modbusAddress)
queryModbusBinarySensor := "SELECT functionCode,registerName,registerAddress,registerCount,unit,dataType,accuracy,haClass,multiply,invert FROM modbus WHERE modbusAddress='" + modbusAddress + "' AND sensorType='binary_sensor';"
detailBinarySensorRows, _ := db.Query(queryModbusBinarySensor)
for detailBinarySensorRows.Next() {
var functionCode, registerName, registerAddress, registerCount, unit, dataType, accuracy, haClass, multiply, invert string
detailBinarySensorRows.Scan(&functionCode, ®isterName, ®isterAddress, ®isterCount, &unit, &dataType, &accuracy, &haClass, &multiply, &invert)
var baiduAppID, baiduSecret string
queryBaiduAccountSql := "select appid,secret from cocoa where platform='baidu';"
db.QueryRow(queryBaiduAccountSql).Scan(&baiduAppID, &baiduSecret)
bi := BaiduTranslate.BaiduInfo{AppID: baiduAppID, Salt: BaiduTranslate.Salt(12), SecretKey: baiduSecret, From: "auto", To: "en"}
bi.Text = registerName
translateRawStr := bi.Translate()
translateStrWithoutSpace := strings.Replace(translateRawStr, " ", "_", -1)
translateStrWithoutSpace = strings.Replace(translateStrWithoutSpace, "#", "", -1)
translateStrWithoutSpace = strings.Replace(translateStrWithoutSpace, "__", "_", -1)
translateStrWithoutSpace = strings.Replace(translateStrWithoutSpace, "-", "_", -1)