欢迎图片

Wiki source code of 01 Lua Functions

Last modified by Devin Chen on 2025/11/26 18:12

Show last authors
1 = **1 Interface description** =
2
3 == **Data type definition** ==
4
5 |=**Type**|=**Description**
6 |=nil|Null
7 |=boolean|Boolean (the value is true or false)
8 |=number|Integer or floating point (signed or unsigned)
9 |=string|String
10 |=table|Table
11 |=function|Functions
12
13 == **Built-in function library clipping** ==
14
15 Full features supported: coroutine/debug/ math/ package/ string/ table/ utf8
16
17 //Some features supported (available in []):** **os[clock/ date/ difftime/ time]//
18
19 //Not supported: io/ file//
20
21 == **Return value description** ==
22
23 The function return type multi means multiple return values (at least 2), usually:
24
25 //1st: nil//
26
27 //2nd: the error message//
28
29 (((
30 == **Function parameter description** ==
31 )))
32
33 Suppose a function prototype is defined:
34
35 {{code language="LUA"}}
36 student(string name, number age[, number class])
37
38 Function:
39
40 Register a student
41
42 Parameters:
43
44 name: student name
45
46 age: student age
47
48 [class=1]: Student class
49
50 Return:
51
52 Succeed: true
53
54 Failed: multi
55 {{/code}}
56
57 **Explanation**
58
59 1. string name indicates that the first parameter name is a string
60 1. number age indicates that the second parameter age is numeric
61 1. [, number class] indicates that the third parameter class is a numeric value, and it is optional. Specify the default class in class 1 in the parameter description.
62 1. **Any parameter in the [] is considered to be an optional parameter, and may not be transmitted when called. The default value will be given in the parameter description.**
63
64 **Call example**
65
66 |(((
67 //print(student("foo", 18)) //~-~- foo, 18 years old, assigned to class 1 by default
68
69 //print(student("bar", 19, 2))// ~-~-bar, 19 years old, assigned to class 2
70
71 //print(student("bar", 18)) //~-~-bar, 18 years old, assigned to class 1 by default
72
73 //local stat, err = student("bar", 18)// ~-~- Call again, use //err// to capture error messages
74
75 //print(stat, err)//
76 )))
77
78 **Output results**
79
80 |(((
81 //true//
82
83 //true//
84
85 //nil student bar registered//
86
87 //nil student bar registered//
88 )))
89
90 **Comment**
91
92 1. From the print result, the first line and the second line are successfully called and returns true; the third line fails the call, the error message is translated as: the bar student has been registered, and there is indeed an error in the code.
93 1. The fourth line of code uses two variables to receive the return value. The call failed, the first variable stat is nil, and the second variable err stores the error message. Then print it out using print, which is the output of the third line. This example shows how to capture and view the error message.
94
95 == **Modification of print function** ==
96
97 For the convenience of remote development, the print data is sent to the front end (web page) by means of network transmission, and the user can see the result of the debug output, because it consumes certain data and occupies the bandwidth of the server (or occupies server resources). So the following restrictions are made.
98
99 1. **Interval limit: **When debugging, transfer once every 2~~3 seconds;
100 1. **Data limit: **The transfer data cannot be larger than 1.5KB in a single transmission, otherwise the extra part will be ignored;
101 1. **Transmission limit: **The data transmission will be stopped automatically after the debugging windows is not closed normally. Only when it is in the debugging window and the switch is on, there is data transmission;
102
103 Users should pay attention to avoid printing a lot of useless information, should minimize the debug output
104
105 In addition, please refer to the front-end documentation for how to use view debugging.
106
107 (((
108 = **2 Address operation** =
109 )))
110
111 |=16-bit data formal|=HLword|=32-bit data formal|=HLword|= 64-bit data formal|=HLword
112 |12(Default)|0|1234(Default)|0|(((
113 12345678(Default)
114 )))|(((
115 0
116 )))
117 |21|6|(((
118 3412(High and low word conversion)
119 )))|2|(((
120 34127856  (High and low word conversion)
121 )))|2
122 | | |2143|3|(((
123 21436587
124 )))|3
125 | | |4321|6|(((
126 87654321
127 )))|6
128 | | | | |(((
129 78563412
130 )))|7
131 | | | | |(((
132 56781234
133 )))|8
134 | | | | |(((
135 65872143
136 )))|9
137 | | | | |(((
138 43218765
139 )))|10
140
141 Table 2-1
142
143 (% class="box infomessage" %)
144 (((
145 **✎Note: **If HLword enters any other value, it will be treated as invalid.
146 )))
147
148 == **addr_getshort(string addr[, number type, number hlword])** ==
149
150 **Function:** Read 16-bit signed decimal address
151
152 **Parameters:**
153
154 //addr//: address
155
156 //num//: value
157
158 [type = 0] not read through  1: read through
159
160 [hlword = 0]  Don't convert,See Form 2.1
161
162 **Return:**
163
164 Succeed: Single word signed decimal value
165
166 Failed: multi
167
168 (((
169 == **addr_setshort(string addr, number num[, number type, number hlword])** ==
170 )))
171
172 **Function:** Write 16-bit signed decimal address
173
174 **Parameters:**
175
176 //addr//: address
177
178 //num//: value
179
180 [type = 0]not read through  1: read through
181
182 [hlword = 0]  Don't convert,See Form 2.1
183
184 **Return:**
185
186 Succeed: true
187
188 Failed: multi
189
190 (((
191 == **addr_getword(string addr[, number type, number hlword])** ==
192 )))
193
194 **Function:** Read 16-bit unsigned decimal address
195
196 **Parameters:**
197
198 //addr//: address
199
200 [type = 0]not read through 1: read through
201
202 [hlword = 0]  Don't convert,See Form 2.1
203
204 **Return:**
205
206 Succeed: Single word unsigned decimal value
207
208 Failed: multi
209
210 (((
211 == **addr_setword(string addr, number num[, number type, number hlword])** ==
212 )))
213
214 **Function:**Write 16-bit unsigned decimal address
215
216 **Parameters:**
217
218 //addr//: address
219
220 //num//: value
221
222 [type = 0]not read through 1: read through
223
224 [hlword = 0]  Don't convert,See Form 2.1
225
226 **Return:**
227
228 Succeed: true
229
230 Failed: multi
231
232 (((
233 == **addr_getint(string addr[, number type, number hlword])** ==
234 )))
235
236 **Function:** Read 32-bit signed decimal address
237
238 **Parameters:**
239
240 //addr//: address
241
242 [type = 0]not read through 1: read through
243
244 [hlword = 0]  Don't convert,See Form 2.1
245
246 **Return:**
247
248 Succeed: Double word signed decimal value
249
250 Failed: multi
251
252 (((
253 == **addr_setint(string addr, number num[, number type, number hlword])** ==
254 )))
255
256 **Function:** Write 32-bit signed decimal address
257
258 **Parameters:**
259
260 //addr//: address
261
262 //num//: value
263
264 [type = 0]not read through 1: read through
265
266 [hlword = 0]  Don't convert,See Form 2.1
267
268 **Return:**
269
270 Succeed: true
271
272 Failed: multi
273
274 (((
275 == **addr_getdword(string addr[, number type, number hlword])** ==
276 )))
277
278 **Function:** Read 32-bit unsigned decimal address
279
280 **Parameters:**
281
282 //addr//: address
283
284 [type = 0]not read through 1: read through
285
286 [hlword = 0]  Don't convert,See Form 2.1
287
288 **Return:**
289
290 Succeed: Double word unsigned decimal value
291
292 Failed: multi
293
294 (((
295 == **addr_setdword(string addr, number num[, number type, number hlword])** ==
296 )))
297
298 **Function:** Write 32-bit unsigned decimal address
299
300 **Parameters:**
301
302 //addr//: address
303
304 //num//: value
305
306 [type = 0]not read through 1: read through
307
308 [hlword = 0]  Don't convert,See Form 2.1
309
310 **Return:**
311
312 Succeed: true
313
314 Failed: multi
315
316 (((
317 == **addr_getbit(string addr[, number type])** ==
318 )))
319
320 **Function:** Read a bit of the register address
321
322 **Parameters:**
323
324 //addr//: address
325
326 [type = 0]not read through 1: read through
327
328 [hlword = 0]  Don't convert,See Form 2.1
329
330 **Return:**
331
332 Succeed: Bit address value
333
334 Failed: multi
335
336 (((
337 == **addr_setbit(string addr, number num[, number type])** ==
338 )))
339
340 **Function:** Write a bit of the register address
341
342 **Parameters:**
343
344 //addr//: address
345
346 //num//: value
347
348 [type = 0]not read through 1: read through
349
350 [hlword = 0]  Don't convert,See Form 2.1
351
352 **Return:**
353
354 Succeed: true
355
356 Failed: multi
357
358 (((
359 == **addr_getfloat(string addr[, number type, number hlword])** ==
360 )))
361
362 **Function:** Read 32-bit floating address
363
364 **Parameters:**
365
366 //addr//: address
367
368 [type = 0]not read through 1: read through
369
370 [hlword = 0]  Don't convert,See Form 2.1
371
372 **Return:**
373
374 Succeed: 32-bit floating point value
375
376 Failed: multi
377
378 (((
379 == **addr_setfloat(string addr, number num[, number type, number hlword])** ==
380 )))
381
382 **Function:** Write 32-bit floating address
383
384 **Parameters:**
385
386 //addr//: address
387
388 //num//: value
389
390 [type = 0]not read through 1: read through
391
392 [hlword = 0]  Don't convert,See Form 2.1
393
394 **Return:**
395
396 Succeed: true
397
398 Failed: multi
399
400 (((
401 == **addr_getdouble(string addr[, number type, number hlword])** ==
402 )))
403
404 **Function:** Read 64-bit floating address
405
406 **Parameters:**
407
408 //addr//: address
409
410 [type = 0]not read through 1: read through
411
412 [hlword = 0]  Don't convert,See Form 2.1
413
414 **Return:**
415
416 Succeed: 64-bit floating point value
417
418 Failed: multi
419
420 (((
421 == **addr_setdouble(string addr, number num[, number type, number hlword])** ==
422 )))
423
424 **Function:** Write 64-bit floating address
425
426 **Parameters:**
427
428 addr: address
429
430 num: value
431
432 [type = 0]not read through //1//: read through
433
434 [hlword = 0]  Don't convert,See Form 2.1
435
436 **Return:**
437
438 Succeed: true
439
440 Failed: multi
441
442 (((
443 == **addr_getstring(string addr, number length[, number type, number hlbyte])** ==
444 )))
445
446 **Function:** Read the specified length string from address
447
448 **Parameters:**
449
450 //addr//: address
451
452 //length//: length
453
454 [type = 0]not read through 1: read through
455
456 [hlbyte = 0] Don't convert,3:High and low byte conversion, 4:GBK, 5:GBK And the first byte is the length
457
458 **Return:**
459
460 Succeed: specified length string
461
462 Failed: multi
463
464 (((
465 == **addr_setstring(string addr, string str[, number type, number hlbyte])** ==
466 )))
467
468 **Function:** Write the specified length string to address
469
470 **Parameters:**
471
472 //addr//: address
473
474 //str//: string
475
476 [type = 0]not read through 1: read through
477
478 [hlbyte = 0] Don't convert,3:High and low byte conversion, 4:GBK, 5:GBK And the first byte is the length
479
480 **Return:**
481
482 Succeed: true
483
484 Failed: multi
485
486 (((
487 == **addr_bmov(string dst, string src, number length)** ==
488 )))
489
490 **Function:** Copy data from source address to destination address
491
492 **Parameters:**
493
494 //dst//: destination address
495
496 //src//: source address
497
498 //length//: length
499
500 **Return:**
501
502 Succeed: true
503
504 **Failed: multi**
505
506 (((
507 == **addr_fill(string addr, number num, number length)** ==
508 )))
509
510 **Function:** Write the same value to consecutive addresses
511
512 **Parameters:**
513
514 //addr//: address
515
516 //num//: value
517
518 //length//:continuous length
519
520 **Return:**
521
522 Succeed: true
523
524 Failed: multi
525
526 (((
527 == **addr_newnoaddr(string addr, number offset)** ==
528 )))
529
530 **Function:** Offset address value relative to //addr//
531
532 **Parameters:**
533
534 //addr//: address
535
536 //offset//: offset value
537
538 **Return:**
539
540 Succeed: New address after offset
541
542 Failed: multi
543
544 (((
545 == **addr_newstataddr(string addr, number offset)** ==
546 )))
547
548 **Function:** Offset station number relative to //addr //station number
549
550 **Parameters:**
551
552 //addr//: address
553
554 //offset//: offset value
555
556 **Return:**
557
558 Succeed: New station number after offset
559
560 Failed: multi
561
562 == **addr_gethex64(string addr[, number type, number hlword])** ==
563
564 **Function:** Read 64-bit hexadecimal numbers
565
566 **Parameters:**
567
568 //addr//: address
569
570 [type = 0]not read through 1: read through
571
572 [hlword = 0]  Don't convert,See Form 2.1
573
574 **Return:**
575
576 Succeed: 64-bit floating-point values
577
578 Failed: multi
579
580 == **addr_sethex64(string addr, number num[, number type, number hlword])** ==
581
582 **Function:** Write 64-bit hexadecimal addresses
583
584 **Parameters:**
585
586 //addr//: address
587
588 [type = 0]not write through 1: write through
589
590 [hlword = 0]  Don't convert,See Form 2.1
591
592 **Return:**
593
594 Succeed: true
595
596 Failed: multi
597
598 (((
599 = **3 Serial port operation** =
600 )))
601
602 Operations on the serial port such as read, write, etc. must use ':' for full mode calls, ie operations on an open serial object.
603
604 **Serial port name and mode**
605
606 The serial port configured in the communication configuration window cannot be configured again using the script. RS232 and RS458 (or RS422) can be used simultaneously, but RS422 and RS485 are mutually exclusive.For example, when the communication port is configured with COM1-485, the script can only open COM1-232, but not COM1-485/422. Similarly, when the communication port is configured with COM2-485, the script can only open COM2-232, but not COM2-485.
607
608 Attempting to use a script to open a serial port in an unsupported mode will result in an error directly, as below.
609
610 |(((
611 {{code language="LUA"}}
612 local setup = {
613
614 name = "COM2",
615
616 mode = 422, -- COM2 does not support RS422
617
618 ...
619
620 }
621
622 serial.open(setup)
623 {{/code}}
624 )))
625
626 **Data bit:**
627
628 1. When the data bit is 7, the maximum value of data transmission is 127 (0x7F), and non-ASCII characters will be truncated, resulting in data errors and garbled characters.
629 1. When the data bit is 8, the maximum value of data transmission is 255 (0xFF), which supports the transmission of any character.
630
631 (((
632 == **serial.open(table setup)** ==
633 )))
634
635 **Function:** Enable one serial port
636
637 **Parameters:**
638
639 //Setup// is a Lua table; it needs to contain the following fields
640
641 //String setup.name//,// //serial port name, such as: COM1/COM2 (requires uppercase)
642
643 //number setup.mode//, mode: RS232/RS485/RS422
644
645 //number setup.baud_rate//, such as 115200
646
647 //number setup.stop_bit//, stop bit: 1 or 2
648
649 //number setup.data_len//, data bit: 7 or 8
650
651 //string setup.check_bit//, check bit: NONE/ODD/EVEN/SPACE
652
653 //number [setup.wait_timeout=300]//, waiting timeout
654
655 //number [setup.recv_timeout=50]//, receive wait timeout
656
657 //number [setup.flow_control=0]//, Flow control method, 0:XON/XOFF, 2:DSR/ER
658
659 Supported baud rate
660
661 1200/2400/4800/9600/14400/19200/38400/43000/57600/76800/115200/128000/230400/256000/460800/961000
662
663 **Return:**
664
665 Succeed: serial object
666
667 Failed: multi
668
669 (((
670 == **serial.close(serial obj)** ==
671 )))
672
673 **Function:** Disable the serial port
674
675 **Parameters: **//Obj //is the object returned by serial.open
676
677 **Return:**
678
679 Succeed: true
680
681 Failed: multi
682
683 (((
684 == **serial:read(number bytes[, number timeout])** ==
685 )))
686
687 **Function:** Read the specified byte length serial port data
688
689 **Parameters:**
690
691 //bytes//: number of bytes
692
693 //[timeout=50]//: timeout for reading, in milliseconds
694
695 **Return:**
696
697 Succeed: true
698
699 Failed: multi
700
701 (((
702 == **serial:write(string data)** ==
703 )))
704
705 **Function:** Write the specified byte length to serial port data
706
707 **Parameters: **
708
709 //data//: serial port data
710
711 **Return:**
712
713 Succeed: true
714
715 Failed: multi
716
717 (((
718 == **serial:flush([number flag])** ==
719 )))
720
721 **Function:** Clear the serial port buffer
722
723 **Parameters:**
724
725 //[flag=2]// clear option: 0: read, 1: write, 2: read-write
726
727 **Return:**
728
729 Succeed: true
730
731 Failed: multi
732
733 (((
734 == **serial:close()** ==
735 )))
736
737 **Function:** Close the serial port object
738
739 **Parameters:** None
740
741 **Return:**
742
743 Succeed: true
744
745 Failed: multi
746
747 (((
748 = **4 MQTT operation** =
749 )))
750
751 Operations on MQTT such as connect, subscribe, etc. must use ':' for full mode calls, that is, operate on a created MQTT object.
752
753 Both MQTT subscriptions and publications are asynchronous implementations that require the user to implement a callback function.
754
755 **QoS value:**
756
757 * 0: Only push messages once, messages may be lost or duplicated. It can be used for environmental sensor data, it doesn't matter if lose a record, because there will be a second push message soon. This method is mainly used for normal APP push, but if the user smart device is not connected when the message is pushed, the message will be discarded, and the smart device will not be received when it is networked again.
758 * 1: The message is delivered at least once, but the message may be delivered repeatedly.
759 * 2: The message was delivered exactly once. This level can be used in a billing system. In a billing system, repeated or missing messages can lead to incorrect results. This highest quality message push service can also be used for instant messaging APP pushes, ensuring that users only receive messages once.
760
761 **Retain flag:**
762
763 0: not reserved;
764
765 1: reserved
766
767 (((
768 == **mqtt.create(string serverurl, string clientid[, int useDomain])** ==
769 )))
770
771 **Function:** Create an MQTT object
772
773 **Parameters:**
774
775 //serverurl //Server url
776
777 Format: "//protocol:~/~/host:port//"
778
779 //protocol//: tcp/ssl
780
781 //host//: Host name/IP
782
783 //port//: such as 1883
784
785 //clientid//: Client ID
786
787 //int useDomain: //0: convert to IP for connection, 1: use domain name for connection.
788
789 **Return:**
790
791 Succeed: MQTT object
792
793 Failed: multi
794
795 (((
796 == **mqtt.close(mqtt obj)** ==
797 )))
798
799 **Function:** Close the specified MQTT object (if the connected server will be disconnected automatically)
800
801 **Parameters: **//Obj //is the objeced returned by mqtt.create
802
803 **Return:**
804
805 Succeed: true
806
807 Failed: multi
808
809 (((
810 == **mqtt:connect(table conn[, table lwt, table cart])** ==
811 )))
812
813 **Function:**Establish a connection to the server
814
815 **Parameters:**
816
817 //conn //is a Lua table and needs to contain the following fields
818
819 * //string conn.username//, user name
820 * //string conn.password//, password
821 * //number [conn.netway=0]//, networking method, if set error number will use Ethernet method
822 ** 0: Ethernet
823 ** 1: WIFI
824 ** 2: 4G
825 ** 3: 2G
826 * //number [conn.keepalive=60]//, keep connected heartbeat interval, in seconds
827 * //number [conn.cleansession=1]//, empty the session as described below:
828
829 This function is used to control the behavior when connecting and disconnecting, and the client and server will retain the session information. This information is used to guarantee "at least once" and "accurately once" delivery, as well as the subject of the client subscription, the user can choose to keep or ignore the session message, set as follows:
830
831 * 1 (Empty): If a session exists and is 1, the previous session messages on the client and server are emptied.
832 * 0 (reserved): Conversely, both the client and the server use the previous session. If the previous session does not exist, start a new session.
833
834 //lwt// (Last Will and Testament) is a Lua table and needs to contain the following fields
835
836 * //string lwt.topic//, topic
837 * //string lwt.message//, message
838 * //number [lwt.qos=0]//, qos value
839 * //number [lwt.retain=0]//, retain flag
840
841 **Return:**
842
843 Succeed: true
844
845 Failed: multi
846
847 (((
848 == **mqtt:disconnect([number timeout])** ==
849 )))
850
851 **Function:** Disconnect from the MQTT server
852
853 **Parameters: **//[timeout=10000] //Disconnect waiting timeout, in milliseconds
854
855 **Return:**
856
857 Succeed: true
858
859 Failed: multi
860
861 (((
862 == **mqtt:isconnected()** ==
863 )))
864
865 **Function:** Test whether or not a client is currently connected to the MQTT server
866
867 **Parameters:** None
868
869 **Return:**
870
871 Succeed: true ~-~-Connected
872
873 Failed: false ~-~- Unconnected and other unknowns
874
875 (((
876 == **mqtt:subscribe(string topic, number qos)** ==
877 )))
878
879 **Function: **Subscribe to the topic (before the subscription, the user must first call the connect method to connect to the server)
880
881 **Parameters:**
882
883 //topic//, topic name
884
885 //qos//, quality of service
886
887 **Return:**
888
889 Succeed: true
890
891 Failed: multi
892
893 (((
894 == **mqtt:unsubscribe(string topic)** ==
895 )))
896
897 **Function:** Unsubscribe topic
898
899 **Parameters:**
900
901 //topic//, topic name
902
903 **Return:**
904
905 Succeed: true
906
907 Failed: multi
908
909 (((
910 == **mqtt:publish(string topic, string message, number qos, number retain[, number timeout])** ==
911 )))
912
913 **Function:** Publish message
914
915 **Parameters:**
916
917 //topic//, topic name
918
919 //message//, message
920
921 //qos//, quality of service
922
923 //retain//, retain flag
924
925 //[timeout=1000]//, waiting for response timeout, in milliseconds (only valid when qos is greater than 0)
926
927 **Return:**
928
929 Succeed: true
930
931 Failed: multi
932
933 (((
934 == **mqtt:close()** ==
935 )))
936
937 **Function:** Close the mqtt object (the connection to the server will be automatically disconnected)
938
939 **Parameters:** None
940
941 **Return:**
942
943 Succeed: true
944
945 Failed: multi
946
947 (((
948 == **mqtt:on(string method, function callback)** ==
949 )))
950
951 **Function:** Register event callback function
952
953 **Parameters:**
954
955 //method//, It can be message/arrived/offline, these 3 types of events
956
957 //callback//, It is a callback function that needs to pass in a function
958
959 **1.**"message" will call this function after receiving the message
960
961 //Callback// prototype~:// function (string topic, string message)//
962
963 Parameter:
964
965 * //Topic//, topic name
966 * //Message//, content
967
968 **2."arrived" is published by publish, this function will be called after the publication arrives**
969
970 //Callback// prototype~:// function ()//
971
972 Parameter: None
973
974 **3.This function will be called after the "offline" connection is lost**
975
976 //Callback// prototype~:// function (string cause)//
977
978 Parameter:
979
980 //cause//, reason for loss of connection
981
982 **Return:**
983
984 Succeed: true
985
986 Failed: multi
987
988 (((
989 == **mqtt:setup_cfg()** ==
990 )))
991
992 **Function:** Cloud mode interface, to obtain MQTT information configured by the cloud platform
993
994 **Parameters:** None
995
996 **Return:**
997
998 //serverurl, clientid, conn, lwt, cart //(5 returns, respectively, server address, client ID, connection table, last word table, certificate table)
999
1000 //conn// is the first parameter of the mqtt:connect method, which is fixed to table. If not configured, the information in the table is an empty string
1001
1002 //LWT// Last Words configuration is not yet open for setting, //lw//t is fixed to nil
1003
1004 If ssl is not enabled, //cart// is nil, otherwise //cart// is table
1005
1006 (((
1007 = **5 JSON operation** =
1008 )))
1009
1010 Lua only has a table data structure, so all arrays and key-value objects of json will be returned as a table.
1011
1012 (((
1013 == **json.encode( lua_object )** ==
1014 )))
1015
1016 **Function: **Convert lua data type to json string
1017
1018 **Parameters: **Lua data type (including boolean, number, string, table)
1019
1020 **Return:** Json format string
1021
1022 (((
1023 == **json.decode(string json_string)** ==
1024 )))
1025
1026 **Function:** Convert json string to lua data type
1027
1028 **Parameters: **//json_string//, string of json data structure
1029
1030 **Return: **Lua data type
1031
1032 (((
1033 == **json.null** ==
1034 )))
1035
1036 **Function:**
1037
1038 This method is used when assembling json data, which is equivalent to null in json. If the user directly uses json.null() to return the address of the function, it must be valid with the use of encode.
1039
1040 **Parameters:** None
1041
1042 **Return: **None
1043
1044 = **6 Cloud mode** =
1045
1046 The cloud interface is only used in cloud mode, and V-NET mode is not available.
1047
1048 (((
1049 == **bns_get_alldata()** ==
1050 )))
1051
1052 **Function:** Obtain all monitoring points (point table) data configured by the end user
1053
1054 **✎Note: **Assuming there are timing scripts A and B with a period of 1 second, if this function is called in script A, the data will not be obtained if called in script B
1055
1056 **Parameters:** None
1057
1058 **Return:**
1059
1060 Succeed: table two-dimensional array, the structure is as follows
1061
1062 Each item is a monitoring point, which contains 5 attributes:
1063
1064 (1 ID, 2 status, 3 tag name, 4 value, 5 custom)
1065
1066 The status contains 3 enumerated values (0: offline, 1: online, 2: timeout)
1067
1068 If there is no custom configuration, return an empty table, otherwise, return with "field name/field content"
1069
1070 **For example:**
1071
1072 {{code language="LUA"}}
1073 {
1074
1075 [1]= {[1]=1234, [2]=1, [3]='temp', [4]='23.5', [5]={"fruit"="apple"}},
1076
1077 [2]= {[1]=1235, [2]=1, [3]='humi', [4]='67', [5]={"fruit"="pear"}},
1078
1079 ...
1080
1081 [n]= {[1]=xxxx, [2]=x, [3]='xxxx', [4]='xx.x', [5]={}},
1082
1083 }
1084
1085 Failed: table empty table
1086 {{/code}}
1087
1088 (((
1089 == **bns_get_config(string from)** ==
1090 )))
1091
1092 **Function:** Obtain custom configuration parameters with the specified from type
1093
1094 **parameter:**
1095
1096 from type, there are the following two categories, the string must be all lowercase
1097
1098 'user': terminal parameters, that is, custom parameters configured by the user
1099
1100 'bind': binding parameters, which are custom parameters that need to be input
1101
1102 when the user binds V-BOX
1103
1104 **Return:**
1105
1106 Succeed: table field name/field content table in organization form
1107
1108 Failed~:// table// empty table
1109
1110 (((
1111 == **bns_get_data(string name, string data)** ==
1112 )))
1113
1114 **Function:**write data to the name of the monitoring point
1115
1116 **parameter:**
1117
1118 //name //The name of the monitoring point
1119
1120 //data// the data to be written
1121
1122 **Return:**
1123
1124 Succede: //string  // value before the monitoring point is written
1125
1126 Failed: nil
1127
1128 (((
1129 == **bns_get_data(string name)** ==
1130 )))
1131
1132 **Function:**
1133
1134 Read the data of the monitoring point name
1135
1136 **parameter:**
1137
1138 //name  // The name of the monitoring point
1139
1140 **Return:**
1141
1142 Succeed: string, table 2 results: the value of the monitoring point, custom content
1143
1144 Failed: nil
1145
1146 (((
1147 == **bns_get_datadesc()** ==
1148 )))
1149
1150 **Function: **Obtain all configured communication ports and monitoring point information
1151
1152 **Parameters:** None
1153
1154 **Return:**
1155
1156 Succeed: table three-dimensional array, the structure is as follows
1157
1158 Each item is a communication port, which contains 3 attributes (1 monitoring point array, 2 ID, 3 name)
1159
1160 The monitoring point array contains 4 attributes (1 ID, 2 name, 3 read and write attributes, 4 types)
1161
1162 Read and write attributes (1: read only, 2: write only, 3: read and write)
1163
1164 Type (1: switch, 2: number, 3: string)
1165
1166 **For example:**
1167
1168 {{code language="LUA"}}
1169 {
1170
1171 [1]={--The first communication port
1172
1173 [1]={--monitoring point array of the first communication port
1174
1175 [1]={[1]=11,[2]='data1',[3]=3,[4]=2},
1176
1177 [2]={[1]=12,[2]='data2',[3]=3,[4]=2},
1178
1179 ...
1180
1181 [n]={[1]=xx,[2]='datan',[3]=x,[4]=x},--n monitoring points
1182
1183 },
1184
1185 [2]=14, --ID
1186
1187 [3]='Modbus TCP' --n monitoring points
1188
1189 },
1190
1191 [2]={--The second communication port
1192
1193 [1]={},--The monitoring point of the second communication port is not configured and is empty
1194
1195 [2]=15, --ID
1196
1197 [3]='WECON' --communication protocol name
1198
1199 },
1200
1201 ...n communication ports and so on
1202
1203 }
1204 {{/code}}
1205
1206 Failed~:// table// empty table
1207
1208 (((
1209 == **bns_get_machineinfo()** ==
1210 )))
1211
1212 **Function:** get machine information
1213
1214 **Parameters:** None
1215
1216 **Return:**
1217
1218 Succeed: 3 string type results (model, machine code, software version)
1219
1220 Failed: nil
1221
1222 (((
1223 == **bns_get_groupdata(string name)** ==
1224 )))
1225
1226 **Function:** Get all monitoring point data under the specified group name
1227
1228 **parameter:**
1229
1230 //Name  // group name
1231
1232 **Return:**
1233
1234 Succeed: //table// two-dimensional array, the structure is consistent with section 6.1
1235
1236 Failed: //table// empty table
1237
1238 (((
1239 == **bns_get_groupdesc()** ==
1240 )))
1241
1242 **Function:** Get all group information
1243
1244 **Parameters:** None
1245
1246 **Return:**
1247
1248 Succeed: //table// two-dimensional array, the structure is as follows
1249
1250 Each item represents a group, which contains 3 attributes (1 collection type, 2 name, 3 cycles)
1251
1252 Acquisition type (0: change acquisition, 1: word trigger, 2: no trigger, 3: trigger by time and conditions, 4: reset after trigger, 5: not reset after trigger)
1253
1254 Some collection types do not have a period, the period is -1
1255
1256 Failed: //table  // empty table
1257
1258 (((
1259 == **bns_get_onecache(string msg)** ==
1260 )))
1261
1262 **Function:** Save a message to the cache file, which can be stored after power failure. Store up to 2000 items, delete the old and save the new in a rolling manner when it is full.
1263
1264 **Parameters: **//msg// String
1265
1266 **Return:**
1267
1268 Succeed: true
1269
1270 Failed: nil
1271
1272 (((
1273 == **bns_get_allcache()** ==
1274 )))
1275
1276 **Function:** Get all the cached content (once the internal cache file will be emptied)
1277
1278 **Parameters:** None
1279
1280 **Return:**
1281
1282 Succeed: //table// one-dimensional array
1283
1284 **For example:**
1285
1286 {{code language="LUA"}}
1287 {
1288
1289 [1]="This is the oldest message", - the first is the oldest message
1290
1291 [2]="This is a test",
1292
1293 ...
1294
1295 [n]="This is the latest message", - the last is the latest message
1296
1297 }
1298 {{/code}}
1299
1300 Failede: nil
1301
1302 (((
1303 = **7 HTTP operation** =
1304 )))
1305
1306 Network communication includes Http request interface, this document does not provide interface description, please refer to the online document for how to use it.
1307
1308 (((
1309 == **http request** ==
1310 )))
1311
1312 [[http:~~/~~/w3.impa.br/~~~~diego/software/luasocket/http.html#request>>url:http://w3.impa.br/~~diego/software/luasocket/http.html#request]]
1313
1314 == **https request** ==
1315
1316 **For example:**
1317
1318 {{code language="LUA"}}
1319 local json = require("json")
1320
1321 local https = require("https")
1322
1323 functions https_demo.main()
1324
1325 local url = "https://XXXXXXXXXXXXXXXXXXXXXXXXXX"
1326
1327 local body = {}
1328
1329 body["XXXXXX"] = "XXXXX"
1330
1331 body["XXXXXXX"] = "XXXXXXXXXXX"
1332
1333 local bodyJson = json.encode(body)
1334
1335 local header = {}
1336
1337 header["content-type"] = "application/json"
1338
1339 local result_table, code, headers, status = https.request(url,
1340
1341 bodyJson)
1342
1343 if code == 200 then
1344
1345 print("https suc")
1346
1347 return true
1348
1349 else
1350
1351 print("https fail")
1352
1353 return nil
1354
1355 end
1356
1357 end
1358 {{/code}}
1359
1360 (((
1361
1362 )))
1363
1364 (((
1365 = **8 General Functions** =
1366 )))
1367
1368 (((
1369 == **send_sms_ira(string number, string message)** ==
1370 )))
1371
1372 **Function:** Use IRA character set to send English text messages
1373
1374 **Parameters:**
1375
1376 //number: //number (up to 32 characters, the excess will be discarded)
1377
1378 //message~:// SMS content (up to 160 English characters, including special symbols, the part exceeding 160 characters will be discarded, and no characters in other languages should appear in the content)
1379
1380 **Return:**
1381
1382 Succeed: SMS corresponding id, used to get whether the SMS was sent successfully
1383
1384 Failed: multi
1385
1386 (((
1387 == **send_sms_ucs2(string number, string message)** ==
1388 )))
1389
1390 **Function:**
1391
1392 Use UCS2 character set to send SMS in Chinese and other languages, such as Korean, Japanese, etc.
1393
1394 **Parameters:**
1395
1396 //number: //number (up to 32 characters, the excess will be discarded)
1397
1398 //message~:// SMS content (Only 70 Chinese characters at most, the part exceeding the length will be discarded)
1399
1400 **Return:**
1401
1402 Succeed: SMS corresponding id, used to get whether the SMS was sent successfully
1403
1404 Failed: multi
1405
1406 (((
1407 == **sms_get_state(number id)** ==
1408 )))
1409
1410 **Function:** Get the status of the SMS
1411
1412 **parameter:**
1413
1414 //id~:// SMS corresponding id
1415
1416 **Return:**
1417
1418 Succeed: SMS status (1: not sent, 2: sent successfully, 3: failed to send)
1419
1420 Failed: multi
1421
1422 (((
1423 == **jwt_encode(table head, table payload, string aud, number iat, number exp, string key, int jwttype)** ==
1424 )))
1425
1426 **Function:** Convert data to JWT format
1427
1428 **parameter:**
1429
1430 //aud: //project name
1431
1432 //iat: //The valid period start timestamp of the JWT data format
1433
1434 //exp~:// the expiration time stamp of the JWT data format
1435
1436 //head~:// head information table
1437
1438 key: key in JSON format
1439
1440 value: value in JSON format
1441
1442 type:value type, 0:string,1:integer,2:number,3:boolean
1443
1444 {
1445
1446 {key="test1",value="test1",type="0"}
1447
1448 }
1449
1450 payload: payload information table
1451
1452 The format is consistent with the header information table
1453
1454 {
1455
1456 {key="test",value="test",type="0"}
1457
1458 }
1459
1460 //jwttype: //encryption type
1461
1462 0:RS256 1:RS384 2:RS512
1463
1464 3: PS256 4: PS384 5: PS512
1465
1466 6:HS256 7:HS384 8:HS512
1467
1468 9:ES256 10:ES384 11:ES512
1469
1470 //key~:// the private key required for encryption
1471
1472 **For example:**
1473
1474 {{code language="LUA"}}
1475 function jwt.main()
1476
1477 local PRIVATE_KEY = [[-- Please enter the secret key--]]
1478
1479 local JWTType=0
1480
1481 local payload = {{key="test1",value="test1",type="0"},
1482
1483 {key="test",value="123122131",type="1"}}
1484
1485 local head = {{ key="name",value="data",type="0"},
1486
1487 {key="test2",value="test2",type="0"}}
1488
1489 local aud = "project"
1490
1491 local iat = 123122131
1492
1493 local exp1 = 123122331
1494
1495 local en = jwt_encode(head,payload,aud,iat,exp1,PRIVATE_KEY,JWTType);
1496
1497 print(en)
1498
1499 End
1500 {{/code}}
1501
1502 (((
1503 == **convertohex(number type, number value)** ==
1504 )))
1505
1506 **Function:** Convert data into hexadecimal data
1507
1508 **parameter:**
1509
1510 //type~:// incoming data type 0:word 1:dword 2:float
1511
1512 //value~:// the data to be converted
1513
1514 **Return:**
1515
1516 Succeed: the converted hexadecimal data
1517
1518 Failed: multi
1519
1520 == **crc.init(table prarm)** ==
1521
1522 **Function:** Initialize the CRC
1523
1524 **Parameters:**
1525
1526 prarm is a Lua table and needs to contain the following fields.
1527
1528 * string prarm name, see table 9-1 for details of the parameter model name When this parameter is passed in, the default table parameters are used and the poly,init,xorout,refin,and refout passed in are invalid.
1529 * number prarm.width: the width, i.e. the number of CRC bits.
1530 * number [prarm.poly]: short for the generated item in hexadecimal. For example, CRC-32 is 0x04C11DB7, ignoring the highest bit "1", i.e., the complete generation item is 0x104C11DB7.
1531 * number [prarm.init]: the initialization preset value of the register (crc) at the beginning of the algorithm in hexadecimal.
1532 * number [prarm.xorout]: the final CRC value obtained after heterodyning the calculation result with this parameter.
1533 * number [prarm.refin]: whether each byte of the data to be measured is inverted by bit, true or false.
1534 * number [prarm.refout]: after the calculation or before the heterodyning output, whether the whole data is inverted by bit, true or false.
1535
1536 **Return:**
1537
1538 Success: crc object
1539
1540 Failure: multi, error code
1541
1542 (((
1543 |=Parameter model name|=poly|=init|=xorout|=refin|=refout
1544 |crc8|0x07|0x00|0x00|false|false
1545 |crc8_cdma2000|0x9B|0xFF|0x00|false|false
1546 |crc8_darc|0x39|0x00|0x00|true|true
1547 |crc8_dvb_s2|0xD5|0x00|0x00|false|false
1548 |crc8_ebu|0x1D|0xFF|0x00|true|true
1549 |crc8_i_code|0x1D|0xFD|0x00|false|false
1550 |crc8_itu|0x07|0x00|0x55|false|false
1551 |crc8_maxim|0x31|0x00|0x00|true|true
1552 |crc8_rohc|0x07|0xFF|0x00|true|true
1553 |crc8_wcdma|0x9B|0x00|0x00|true|true
1554 |crc8_sae_j1850|0x1D|0xFF|0xFF|false|false
1555 |crc8_opensafety|0x2F|0x00|0x00|false|false
1556 |crc16_tms37157|0x1021|0x3791|0x0000|true|true
1557 |crc16_a|0x1021|0x6363|0x0000|true|true
1558 |crc16_riello|0x1021|0x554D|0x0000|true|true
1559 |crc16_ccitt_false|0x1021|0xFFFF|0x0000|false|false
1560 |crc16_arc|0x8005|0x0000|0x0000|true|true
1561 |crc16_arc_ccitt|0x1021|0x1D0F|0x0000|false|false
1562 |crc16_buypass|0x8005|0x0000|0x0000|false|false
1563 |crc16_cdma2000|0xC867|0xFFFF|0x0000|false|false
1564 |crc16_dds110|0x8005|0x800D|0x0000|false|false
1565 |crc16_dect_r|0x0589|0x0000|0x0001|false|false
1566 |crc16_dect_x|0x0589|0x0000|0x0000|false|false
1567 |crc16_dnp|0x3D65|0x0000|0xFFFF|true|true
1568 |crc16_en_13757|0x3D65|0x0000|0xFFFF|false|false
1569 |crc16_genibus|0x1021|0xFFFF|0xFFFF|false|false
1570 |crc16_maxim|0x8005|0x0000|0xFFFF|true|true
1571 |crc16_mcrf4xx|0x1021|0xFFFF|0x0000|true|true
1572 |crc16_t10_dif|0x8BB7|0x0000|0x0000|false|false
1573 |crc16_teledisk|0xA097|0x0000|0x0000|false|false
1574 |crc16_usb|0x8005|0xFFFF|0xFFFF|true|true
1575 |crc16_kermit|0x1021|0x0000|0x0000|true|true
1576
1577 (% class="wikigeneratedid" %)
1578 Table 9-1
1579
1580 == **crc:calc(string crcValue)** ==
1581
1582 **Function:** Calculate CRC result
1583
1584 **Parameter:**
1585
1586 crcValue: the value to be calculated
1587
1588 **Return:**
1589
1590 Succeed: calculated result
1591
1592 Failed: multi, error code
1593 )))
1594
1595 **For example:**
1596
1597 {{code language="LUA"}}
1598 function crcTest.main()
1599
1600 local param = {
1601
1602 name = '',
1603
1604 width = 64,
1605
1606 poly = 0x42F0E1EBA9EA3693,
1607
1608 init = 0xFFFFFFFFFFFFFFFF,
1609
1610 xorout = 0xFFFFFFFFFFFFFFFF,
1611
1612 refin = 1,
1613
1614 refout = 1
1615
1616 }
1617
1618 crc64,err = crc.init(param)
1619
1620 if not crc64 then
1621
1622 print("Crc init failed:", err)
1623 else
1624
1625 crcvalue = crc64:calc("123456789")
1626
1627 print(string.format("crc64 calc :0X%16X", crcvalue))
1628
1629 end
1630
1631 end
1632 {{/code}}
1633
1634 = **9 Special function for V-NET** =
1635
1636 == **normal_get_alldata()** ==
1637
1638 **Function: **Obtain the data of all the monitoring points
1639
1640 **Parameter: None**
1641
1642 **Return:**
1643
1644 Succeed: table two-dimensional arrays, as follows:
1645
1646 * Each item is a monitoring point and contains 4 attributes:
1647 ** 1: ID
1648 ** 2: status
1649 ** 3: tag name
1650 ** 4: value
1651 * Status contains 3 enumerated values
1652 ** 0: offline
1653 ** 1: online
1654 ** 2: timeout
1655 * Customization returns an empty table if there is no configuration, otherwise returns "field name/field content"
1656
1657 **For example:**
1658
1659 {{code language="LUA"}}
1660 {
1661
1662 [1]= {[1]=1234, [2]=1, [3]='temp', [4]='23.5'},
1663
1664 [2]= {[1]=1235, [2]=1, [3]='humi', [4]='67'},
1665
1666 ...
1667
1668 [n]= {[1]=xxxx, [2]=x, [3]='xxxx', [4]='xx.x'},
1669
1670 }
1671
1672 Failed: table, empty table
1673 {{/code}}
1674
1675 == **normal_setdata_byname(string name, string data)** ==
1676
1677 **Function:** Write data to the monitoring point name
1678
1679 **Parameter:**
1680
1681 name: the name of monitoring point
1682
1683 data: the data to be written
1684
1685 **Return:**
1686
1687 Succeed: string: The value of the monitor point before it is written
1688
1689 Failed: nil
1690
1691 == **normal_getdata_byname(string name)** ==
1692
1693 **Function:** Read the data of the monitoring point name
1694
1695 **Parameter:**
1696
1697 name: the name of monitoring point
1698
1699 **Return:**
1700
1701 Succeed: string
1702
1703 Failed: nil
1704
1705 = **10 Message summary algorithm** =
1706
1707 == **hmac(string hash_func, string key, string message)** ==
1708
1709 **Function:** HMAC calculate
1710
1711 **Function name**
1712
1713 hash_func:
1714
1715 * [md5, sha1, sha224, sha256, sha384, sha512]
1716 * [sha512_224, sha512_256, sha3_224, sha3_256]
1717 * [sha3_384, sha3_512]
1718
1719 **Parameter:**
1720
1721 key: the key
1722
1723 message: message content
1724
1725 **Return:**
1726
1727 Succeed: string, calculation result
1728
1729 Failed: nil
1730
1731 **For example:**
1732
1733 {{code language="LUA"}}
1734 local sha = require"sha2"
1735
1736 function hmac_test.main()
1737
1738 local hmac = sha.hmac
1739
1740 print(hmac(sha.sha1,
1741
1742 "your key", "your message"))
1743
1744 end
1745 {{/code}}
1746
1747 == **sha(string message)** ==
1748
1749 **Function:** SHA calculate
1750
1751 **Function name:**
1752
1753 sha:
1754
1755 * sha1, sha224, sha256, sha384, sha512]
1756 * [sha512_224, sha512_256, sha3_224, sha3_256]
1757 * [sha3_384, sha3_512]
1758
1759 **Parameter:**
1760
1761 key: the key
1762
1763 message: message content
1764
1765 **Return:**
1766
1767 Succeed: string, calculation result
1768
1769 Failed: nil
1770
1771 For example:
1772
1773 {{code language="LUA"}}
1774 local sha = require"sha2"
1775
1776 function sha_test.main()
1777
1778 local sha256 = sha.sha256
1779
1780 print(sha256("your message"))
1781
1782 end
1783 {{/code}}
1784
1785 = **11 MySQL database operation** =
1786
1787 {{info}}
1788 Note: E series V-box with E02 firmware doesn't support
1789 {{/info}}
1790
1791 == **luaMySql.init(string sourcename, string username, string password, string host, number port, string character)** ==
1792
1793 **Function:** Configure database connection parameters
1794
1795 **Parameters:**
1796
1797 sourcename: Database name
1798
1799 username: Connection username
1800
1801 password: Connection password
1802
1803 host: Connection host name
1804
1805 port: Connection host port
1806
1807 character: Character set used for the connection
1808
1809 **Returns:**
1810
1811 Success: true
1812
1813 Failure: multi
1814
1815 == **luaMySql.exec(string statement)** ==
1816
1817 **Function:** Execute the given SQL statement (no result set required, e.g., insert, delete, update)
1818
1819 **Parameters:**
1820
1821 statement: The given SQL statement
1822
1823 **Returns:**
1824
1825 Success: status (Returns the number of rows affected by the SQL statement execution)
1826
1827 Failure: nil, errorString
1828
1829 == **luaMySql.execWithResult(string statement)** ==
1830
1831 **Function:** Execute the given SQL statement (result set required, e.g., query)
1832
1833 **Parameters:**
1834
1835 statement: The given SQL statement
1836
1837 **Returns:**
1838
1839 Success: table (Returns the result set)
1840
1841 Failure: nil, errorString
1842
1843
1844 **Example:**
1845
1846 **{{code language="lua"}}mysql = require "mysqlclient"
1847
1848 function DataInitRight()
1849 local dbName = "db_lua1"
1850 local user = "root"
1851 local pwd = "123456"
1852 local host = "192.168.56.186"
1853 local port = 3306
1854 local character = "UTF8"
1855 mysql.init(dbName, user, pwd, host, port, character)
1856 end
1857
1858 function ExecFunc()
1859 status, errorString = mysql.exec("delete from tb_lua1 where mykey = 10;")
1860 if nil == status then
1861 print("ExecFunc() error:", errorString)
1862 return -1
1863 else
1864 print("the number of rows affected by the command:", status)
1865 end
1866 return 0
1867 end
1868
1869 function ExecWithResultFunc()
1870 status, errorString = mysql.execWithResult("select * from tb_lua1;")
1871 if nil == status then
1872 print("ExecWithResultFunc() error:", errorString)
1873 return -1
1874 else
1875 print("ExecWithResultFunc() success: status type =", type(status))
1876 print("ExecWithResultFunc() success: status len =", #status)
1877
1878 local num = #status
1879 local i = 1
1880 if num > 0 then
1881 for i = 1, num, 1 do
1882 local var = string.format("select result[%d] :mykey = %d, value = %s",
1883 i, status[i].mykey, status[i].value)
1884 print(var)
1885 end
1886 end
1887 print("---------------")
1888 end
1889 return 0
1890 end
1891
1892 function luaMysql_apiTest.main()
1893 print("script running ...")
1894 DataInitRight()
1895
1896 -- use exec demo
1897 if ExecFunc() < 0 then
1898 return
1899 end
1900
1901 -- use execWithResult demo
1902 if ExecWithResultFunc() < 0 then
1903 return
1904 end
1905
1906 print("script running success")
1907 end{{/code}}**