欢迎图片

Wiki source code of Lua Script

Version 8.1 by xingzhi lin on 2025/10/31 11:07

Show last authors
1 = Reference =
2
3 Before using the Lua script function, you should understand the basic grammar, and master how to use the script.
4
5 For the description of Lua syntax and functions, please refer to [[Lua Reference Manual>>url:http://www.lua.org/manual/5.3/]].
6
7 == Common function ==
8
9 Here is a list of commonly used functions to facilitate quick search
10
11 * basic Basic functions: English
12 * string String processing: English
13 * table Table processing: English
14 * math Mathematical calculation: English
15
16 == Built-In library ==
17
18 Removed the Lua built-in functions (Including libraries), the details are as follows
19
20 * Completely remove: debug
21 * Partial removal:
22
23 |=io|=os|=basic
24 |io.close|os.clock|--dofile--
25 |--io.flush--|os.date|--loadfile--
26 |--io.input--|os.difftime|
27 |--io.lines--|--os.execute--|
28 |io.open|--os.exit--|
29 |--io.output--|--os.getenv--|
30 |--io.popen--|os.remove|
31 |--io.read--|os.rename|
32 |--io.stderr--|--os.setlocale--|
33 |--io.stdin--|os.time|
34 |--io.stdout--|--os.tmpname--|
35 |--io.tmpfile--| |
36 |io.type| |
37 |--io.write--| |
38
39 (% class="box infomessage" %)
40 (((
41 **✎Note:** The io/os library cannot write to the internal Flash
42 )))
43
44 = Lua extension =
45
46 On the basis of Lua, combined with the characteristics of HMI, some functional expansions have been made to assist in completing some more complex business requirements
47
48 == General class ==
49
50 |=(% style="width: 264px;" %)Function|=(% style="width: 318px;" %)Overview|=(% style="width: 123px;" %)i/HMI+ series|=(% style="width: 122px;" %)ie series|=(% style="width: 101px;" %)ig series|=(% style="width: 103px;" %)HMI V2.0
51 |(% style="width:264px" %)1.1 Basic Functions|(% style="width:318px" %)Address Read&Write, screen operations, etc.|(% style="width:123px" %)√|(% style="width:122px" %)√|(% style="width:101px" %)√|(% style="width:103px" %)√
52 |(% style="width:264px" %)1.2 Lua Object Operation|(% style="width:318px" %)Object status and property control|(% style="width:123px" %)√|(% style="width:122px" %)√|(% style="width:101px" %)√|(% style="width:103px" %)√
53 |(% style="width:264px" %)1.3 Timer|(% style="width:318px" %)Cycle execution function|(% style="width:123px" %)×|(% style="width:122px" %)√|(% style="width:101px" %)√|(% style="width:103px" %)√
54 |(% style="width:264px" %)1.4 Trigger|(% style="width:318px" %)Trigger execution function|(% style="width:123px" %)×|(% style="width:122px" %)√|(% style="width:101px" %)√|(% style="width:103px" %)√
55 |(% style="width:264px" %)1.5 Flash Read&Write|(% style="width:318px" %)Custom files Read&Write|(% style="width:123px" %)×|(% style="width:122px" %)√|(% style="width:101px" %)√|(% style="width:103px" %)√
56 |(% style="width:264px" %)1.6 Other functions|(% style="width:318px" %)-|(% style="width:123px" %)√|(% style="width:122px" %)√|(% style="width:101px" %)√|(% style="width:103px" %)√
57 |(% style="width:264px" %)4.2 LuaSqlite|(% style="width:318px" %)Lua sqlite database operation|(% style="width:123px" %)√|(% style="width:122px" %)√|(% style="width:101px" %)√|(% style="width:103px" %)√
58
59 == Custom object class ==
60
61 Realize the drawing and display of charts through **custom parts + functions**
62
63
64 |=Function|=Overview|=i/HMI+ series|=ie series|=ig series|=HMI V2.0
65 |2.1 Table Drawing|-|×|√|√|√
66 |2.2 Curve Drawing|-|×|√|√|√
67
68 == Network communication ==
69
70 |=Function|=Overview|=i/HMI+ series|=ie series|=ig series|=HMI V2.0
71 |3.1 MQTT|MQTT Client|×|×|√|√
72 |3.2 Cloud Interface|Get the data of tags from Cloud Function|×|×|√|√
73 |3.3 json|Conversion between json string and lua data|×|×|√|√
74 |3.4 wlan|WLAN configuration|×|×|√|√
75 |3.5 ftpserver|Relevant functions for FTP server|×|×|√|√
76 |3.6 sim|SIM card information|×|×|√|√
77 |3.7 sms|Relevant functions for SIM card sending SMS|×|×|√|√
78 |4.1 LuaSocket|Network modules programming|√|√|√|√
79
80 = Debug =
81
82 At present, it can only be debugged by the printing function print. There are two situations for debugging.
83
84 |=Category|=Overview|=i/HMI+ series|=ie series|=ig series|=HMI V2.0
85 |Simulation debugging|View the print information through the black window created by the simulation operation|√|√|√|√
86 |HMI debugging|Create a small independent window at the top of the screen to view the print information|×|√|√|√
87
88 (% class="wikigeneratedid" id="HHowtouseHMIdebugging" %)
89 **How to use HMI debugging**
90
91 * Open the debug window, add the print_debug(1) in falling script to new Lua object
92 * Close the debug window, add the print_debug(0) in falling script to new Lua object
93
94 (% class="box infomessage" %)
95 (((
96 **✎Note:**
97
98 * When using HMI debugging, if the printing is too frequent and the quantity is large, it may cause the screen to stuck or freeze
99 * If you have completed the debugging phase of development, you can close the debugging window to reduce the performance consumption of HMI debugging
100 )))
101
102 = Coding environment =
103
104 Like the Lua standard, the encoding environment of the simulator and the HMI is unified with the encoding of UTF8, including the definition and processing of strings
105
106 If you need to print strings in Chinese or other languages into the debugging window, please use we_u8ta for transcoding output
107
108 = Appendix: editor shortcut hotkeys =
109
110 |=Modifier Key|=Function Key|=Function
111 |Ctrl|A|Select all
112 |Ctrl|B|Insert bit address
113 |Ctrl|C|Copy
114 |Ctrl|D|Copy cursor line
115 |Ctrl|E|When the cursor is inside (outside) a pair of brackets, the cursor switches position inside (outside)
116 |Shift+Ctrl|E|When the cursor is inside (outside) a pair of brackets, select the text inside (outside) the brackets
117 |Ctrl|F|Find
118 |Ctrl|H|Replace
119 |Ctrl|L|Delete cursor line
120 |Shift+Ctrl|L|Lowercase the selected content
121 |Ctrl|S|Save
122 |Ctrl|T|Swap the cursor line and the previous line position
123 |Shift+Ctrl|U|Uppercase the selected content
124 |Ctrl|V|Paste
125 |Ctrl|W|Insert word address
126 |Ctrl|X|Cut
127 |Ctrl|Y|Redo
128 |Ctrl|Z|Undo
129 |None|Arrow key up ↑|Move cursor up
130 |Shift|Arrow key up ↑|Up area selection
131 |Shift+Alt|Arrow key up ↑|Up vertical area selection
132 |Ctrl|Arrow keys up ↑|Window slide up
133 |Shift+Ctrl|Arrow key up ↑|Move selected line up
134 |None|Arrow key down ↓|Move cursor down
135 |Shift|Arrow key down ↓|Down area selection
136 |Shift+Alt|Arrow key down ↓|Down vertical area selection
137 |Ctrl|Arrow key down ↓|Window down
138 |Shift+Ctrl|Arrow key down ↓|Move selected line down
139 |None|Left arrow key ←|Move cursor to the left
140 |Shift|Left arrow key ←|Select a symbol to the left
141 |Shift+Alt|Left Arrow ←|Select a symbol to the left
142 |Ctrl|Left Arrow ←|Cursor cross over a word to the left
143 |Shift+Ctrl|Left Arrow ←|Select a word to the left
144 |None|Right arrow key →|Move the cursor to the right
145 |Shift|Right arrow key →|Select a symbol to the right
146 |Shift+Alt|Right Arrow →|Select a symbol to the right
147 |Ctrl|Right Arrow →|Cursor cross over a word to the right
148 |Shift+Ctrl|Right Arrow →|Select a word to the right
149 |Ctrl|Numeric keyboard plus +|Zoom in the display
150 |Ctrl|Numeric keyboard minus-|Zoom out the display
151 |Ctrl|Slash'?/'|Select content comment
152 |None|Tab|Indent 4 spaces
153 |Shift|Tab|Reduce 4 spaces
154 |None|Home|Move the cursor to the beginning of the line
155 |Shift|Home|Select the cursor position to the beginning of the line
156 |None|End|Move the cursor to the end of the line
157 |Shift|End|Select the cursor position to the end of the line
158 |None|PageUp|The cursor moves up one page according to the size of the window
159 |Shift|PageUp|Select the cursor position to the previous page
160 |None|PageDown|The cursor moves down one page according to the size of the window
161 |Shift|PageDown|Select the cursor position to the next page
162 |None|Insert|Switch input mode
163 | | |The following delete operation
164 |None|Delete|Delete one symbol backward
165 |Ctrl|Backspace|Delete the content of the word range to the left of the cursor
166 |Ctrl|Delete|Delete the content of the word range to the right of the cursor
167 |Ctrl+Shift|Backspace|Delete all content to the left of the cursor
168 |Ctrl+Shift|Delete|Delete all content to the right of the cursor
169 | | |The following paragraph operations, span: paragraph length
170 |Ctrl|[|Move cursor up
171 |Ctrl+Shift|[|Move cursor up and select area
172 |Ctrl|]|Move cursor down
173 |Ctrl+Shift|]|Move cursor down and select area
174
175 = Basic function =
176
177 == Address class ==
178
179 How to read or write address
180
181 |=Function|=Description
182 |[[we_bas_getshort/addr_getshort>>doc:||anchor="Hwe_bas_getshort"]]|Read single-word(16bits) signed Decimal
183 |[[we_bas_setshort/addr_setshort>>||anchor="Hwe_bas_setshort"]]|Write single-word(16bits) signed Decimal
184 |[[we_bas_getword/addr_getword>>||anchor="Hwe_bas_getword" ancord="Hwe_bas_getword"]]|Read single-word(16bits) unsigned Decimal
185 |[[we_bas_setword/addr_setword>>||anchor="Hwe_bas_setword" ancord="Hwe_bas_setword"]]|Write single-word(16bits) unsigned Decimal
186 |[[we_bas_getint/addr_getint>>||anchor="Hwe_bas_getint"]]|Read double-word(32bits) signed Decimal
187 |[[we_bas_setint/addr_setint>>||anchor="Hwe_bas_getint"]]|Write double-word(32bits) signed Decimal
188 |[[we_bas_getdword/addr_getdword>>||anchor="Hwe_bas_getint" ancwor="Hwe_bas_getdword"]]|Read double-word(32bits) unsigned Decimal
189 |[[we_bas_setdword/addr_setdword>>||anchor="Hwe_bas_setdword" ancwor="Hwe_bas_setdword"]]|Write double-word(32bits) unsigned Decimal
190 |[[we_bas_getfloat/addr_getfloat>>||anchor="Hwe_bas_getfloat" ancloa="Hwe_bas_getfloat"]]|Read 32bits Floating
191 |[[we_bas_setfloat/addr_setfloat>>||anchor="Hwe_bas_setfloat" ancloa="Hwe_bas_setfloat"]]|Write 32bits Floating
192 |[[we_bas_getdouble/addr_getdouble>>||anchor="Hwe_bas_getdouble" ancoub="Hwe_bas_getdouble"]]|Read 64bits Floating
193 |[[we_bas_setdouble/addr_setdouble>>||anchor="Hwe_bas_setdouble" ancoub="Hwe_bas_setdouble"]]|Write 64bits Floating
194 |[[we_bas_getbit/addr_getbit>>||anchor="Hwe_bas_getbit"]]|Read one bit
195 |[[we_bas_setbit/addr_setbit>>||anchor="Hwe_bas_setbit"]]|Write one bit
196 |[[we_bas_getstring/addr_getstring>>||anchor="Hwe_bas_setbit" anctri="Hwe_bas_getstring"]]|Read string
197 |[[we_bas_setstring/addr_setstring>>||anchor="Hwe_bas_setbit" anctri="Hwe_bas_setstring"]]|Write string
198 |[[we_bas_bmov/addr_bmov>>||anchor="Hwe_bas_bmov"]]|Continuous address copy
199 |[[we_bas_fill/addr_fill>>||anchor="Hwe_bas_fill"]]|Consecutive address assignment
200 |[[we_bas_newnoaddr/addr_newnoaddr>>||anchor="Hwe_bas_newnoaddr" ancoad="Hwe_bas_newnoaddr"]]|External address offset
201 |[[we_bas_newstataddr/addr_newstataddr>>||anchor="Hwe_bas_newstataddr" anctat="Hwe_bas_newstataddr"]]|External station number offset
202 |[[we_bas_getdatas>>||anchor="Hwe_bas_getdatas" ancoad="Hwe_bas_newnoaddr"]]|continous read address
203 |[[we_bas_setdatas>>||anchor="Hwe_bas_setdatas" anctat="Hwe_bas_newstataddr"]]|continous write address
204
205 == Path class ==
206
207 Usage Notice
208
209 |=Function|=Description
210 |[[we_bas_getscriptpath>>||anchor="Hwe_bas_getscriptpath"]](HMI)|Get project script path
211 |[[we_bas_getcustompath>>||anchor="Hwe_bas_getcustompath"]](HMI)|Get the available internal flash path
212 |[[we_bas_getusbpath>>||anchor="Hwe_bas_getusbpath"]](HMI)|Detect USB
213 |[[we_bas_getsdpath>>||anchor="Hwe_bas_getsdpath"]](HMI)|Detect SD card
214 |[[we_bas_file_exist>>||anchor="Hwe_bas_file_exist"]](HMI)|Does the file exist
215 |[[we_bas_path_exist>>||anchor="Hwe_bas_path_exist"]](HMI)|Does the folder exist
216
217 == Screen class ==
218
219 |=Function|=Description
220 |[[we_bas_jumpscreen>>||anchor="Hwe_bas_jumpscreen"]](HMI)|Main screen jump
221 |[[we_bas_popscreen>>||anchor="Hwe_bas_popscreen"]](HMI)|Pop up sub-screen
222 |[[we_bas_closescreen>>||anchor="Hwe_bas_closescreen"]](HMI)|Close sub-screen
223
224 == Others ==
225
226 |=Function|=Description
227 |[[we_bas_beep>>||anchor="Hwe_bas_beep"]]|Beep
228 |[[we_bas_gettickcount>>||anchor="Hwe_bas_gettickcount"]]|Get milliseconds that have passed since the operating system was started
229 |[[we_bas_sleep>>||anchor="Hwe_bas_sleep"]]|Sleep
230 |[[we_atu8>>||anchor="Hwe_atu8"]]|Character set conversion, windows to utf8
231 |[[we_u8ta>>||anchor="Hwe_u8ta"]]|Character set conversion, utf8 to windows
232 |[[we_bas_getmachineinfo>>||anchor="Hwe_bas_getmachineinfo"]]|Get HMI machine information
233
234 = Address class =
235
236 (% class="wikigeneratedid" id="HHowtoreadorwriteaddress" %)
237 **How to read or write address**
238
239 Let HDW0 store a 32-bit integer value, the macro instruction reads/writes the address like following:
240
241 {{code language="Basic"}}
242 @W_HDW0 = 1 'Write 1 to address HDW0
243 Dim a as integer
244 a = @W_HDW0 'Read address HDW0 to variable a
245 {{/code}}
246
247 How to do in Lua:
248
249 {{code language="Lua"}}
250 -- The following is the wrong way to write
251 -- Mistake 1: Attempt to assign a value to a string
252 "@W_HDW0" = 1 -- The address here is a string, and an error will be reported when compiling the project
253 -- Mistake 2: Attempt to assign a value to a variable
254 W_HDW0 = 1 -- The address here is a variable, so the assignment will not be written to the real address
255
256 -- The following is the correct way to write
257 we_bas_setint("@W_HDW0", 1) - write 1 to the address HDW0
258 local a = we_bas_getint("@W_HDW0") - read address HDW0 to variable a
259 {{/code}}
260
261 * Same point: The address is expressed in the same form, but Lua needs to be enclosed in double quotation marks. The address read and write functions, its address parameters are the same as VB, or use the combination key ctrl+W in the editor to insert the word address, ctrl+BInsert bit address
262 * Different point: In Lua, you need to **call the interface function** to complete the operation address, there is no **equal sign assignment** method like macro instruction
263
264 You can find all the interface functions available for reading /writing address operations from this list>>path:#listaddress]]
265
266 == [[we_bas_getshort>>||anchor="HAddressclass"]] ==
267
268 Prototype: we_bas_getshort(address [, type])
269
270 Function: Read single-word(16bits) signed Decimal
271
272 Parameters:
273
274 * address(string):address
275 * type(number):type, type=1 is for read-through
276
277 Return:
278
279 * Success: Single word signed decimal value
280 * Failure: nil
281
282 Example:
283
284 {{code language="Lua"}}
285 print(we_bas_getshort("@W_HDW0"))
286 {{/code}}
287
288 == [[we_bas_setshort>>||anchor="HAddressclass"]] ==
289
290 Prototype: we_bas_setshort(address, value [, type])
291
292 Function: Write single-word(16bits) signed Decimal
293
294 Parameters:
295
296 * address(string):address
297 * value(number):value
298 * type(number):type,type=1 is for write-through
299
300 Return:
301
302 * Success: true
303 * Failure: nil
304
305 Example:
306
307 {{code language="Lua"}}
308 we_bas_setshort("@W_HDW0", 123)
309 {{/code}}
310
311 == [[we_bas_getword>>||anchor="HAddressclass"]] ==
312
313 Prototype: we_bas_getword(address [, type])
314
315 Function: Read single-word(16bits) unsigned Decimal
316
317 Parameters:
318
319 * address(string):address
320 * type(number):type,type=1 is for read-through
321
322 Return:
323
324 * Success: single-word(16bits) unsigned Decimal value
325 * Failure: nil
326
327 Example:
328
329 {{code language="Lua"}}
330 print(we_bas_getword("@W_HDW0"))
331 {{/code}}
332
333 == [[we_bas_setword>>||anchor="HAddressclass"]] ==
334
335 Prototype: we_bas_setword(address, value [, type])
336
337 Function: Write single-word(16bits) unsigned Decimal
338
339 Parameters:
340
341 * address(string):address
342 * value(number):value
343 * type(number):type,type = 1 is for write-through
344
345 Return:
346
347 * Success: true
348 * Failure: nil
349
350 Example:
351
352 {{code language="Lua"}}
353 we_bas_setword("@W_HDW0", 123)
354 {{/code}}
355
356 == [[we_bas_getint>>||anchor="HAddressclass"]] ==
357
358 Prototype: we_bas_getint(address [, type])
359
360 Function: Read double-word(32bits) signed Decimal
361
362 Parameters:
363
364 * address(string):address
365 * type(number):type,type=1 is for read-through
366
367 Return:
368
369 * Success: Read double-word(32bits) signed Decimal value
370 * Failure: nil
371
372 Example:
373
374 {{code language="Lua"}}
375 print(we_bas_getint("@W_HDW0"))
376 {{/code}}
377
378 == [[we_bas_setint>>||anchor="HAddressclass"]] ==
379
380 Prototype: we_bas_setint(address, value [, type])
381
382 Function: Write double-word(32bits) signed Decimal
383
384 Parameters:
385
386 * address(string):address
387 * value(number):value
388 * type(number):type,type=1 is for write-through
389
390 Return:
391
392 * Success: true
393 * Failure: nil
394
395 Example:
396
397 {{code language="Lua"}}
398 we_bas_setint("@W_HDW0", -111)
399 {{/code}}
400
401 == [[we_bas_getdword>>||anchor="HAddressclass"]] ==
402
403 Prototype: we_bas_getdword(address [, type])
404
405 Function: Read double-word(32bits) unsigned Decimal
406
407 Parameters:
408
409 * address(string):address
410 * type(number):type,type=1 is for read-through
411
412 Return:
413
414 * Success: Read double-word(32bits) unsigned Decimal value
415 * Failure: nil
416
417 Example:
418
419 {{code language="Lua"}}
420 print(we_bas_getdword("@W_HDW0"))
421 {{/code}}
422
423 == [[we_bas_setdword>>||anchor="HAddressclass"]] ==
424
425 Prototype: we_bas_setdword(address, value [, type])
426
427 Function: Write double-word(32bits) unsigned Decimal
428
429 Parameters:
430
431 * address(string):address
432 * value(number):value
433 * type(number):type,type=1为write-through
434
435 Return:
436
437 * Success: true
438 * Failure: nil
439
440 Example:
441
442 {{code language="Lua"}}
443 we_bas_setdword("@W_HDW0", 12345678)
444 {{/code}}
445
446 == [[we_bas_getfloat>>||anchor="HAddressclass"]] ==
447
448 Prototype: we_bas_getfloat(address [, type])
449
450 Function: Read 32bits Floating
451
452 Parameters:
453
454 * address(string):address
455 * type(number):type,type=1 is for read-through
456
457 Return:
458
459 * Success: 32bits Floating value
460 * Failure: nil
461
462 Example:
463
464 {{code language="Lua"}}
465 print(we_bas_getfloat("@W_HDW0"))
466 {{/code}}
467
468 == [[we_bas_setfloat>>||anchor="HAddressclass"]] ==
469
470 Prototype: we_bas_setfloat(address, value [, type])
471
472 Function: Write 32bits Floating
473
474 Parameters:
475
476 * address(string):address
477 * value(number):value
478 * type(number):type,type=1 is for write-through
479
480 Return:
481
482 * Success: true
483 * Failure: nil
484
485 Example:
486
487 {{code language="Lua"}}
488 we_bas_setfloat("@W_HDW0", 123.456)
489 {{/code}}
490
491 == [[we_bas_getdouble>>||anchor="HAddressclass"]] ==
492
493 Prototype: we_bas_getdouble(address [, type])
494
495 Function: Read 64bits Floating
496
497 Parameters:
498
499 * address(string):address
500 * type(number):type,type=1is for read-through
501
502 Return:
503
504 * Success: Read 64bits Floating value
505 * Failure: nil
506
507 Example:
508
509 {{code language="Lua"}}
510 print(we_bas_getdouble("@W_HDW0"))
511 {{/code}}
512
513 == [[we_bas_setdouble>>||anchor="HAddressclass"]] ==
514
515 Prototype: we_bas_setdouble(address, value [, type])
516
517 Function: Write 64bits Floating
518
519 Parameters:
520
521 * address(string):address
522 * value(number):value
523 * type(number):type,type=1为write-through
524
525 Return:
526
527 * Success: true
528 * Failure: nil
529
530 Example:
531
532 {{code language="Lua"}}
533 we_bas_setdouble("@W_HDW0", 1.23456)
534 {{/code}}
535
536 == [[we_bas_getbit>>||anchor="HAddressclass"]] ==
537
538 Prototype: we_bas_getbit(address [, type])
539
540 Function: Read one bit
541
542 Parameters:
543
544 * address(string):address
545 * type(number):type,type=1is for read-through
546
547 Return:
548
549 * Success: Single-word signed decimal value
550 * Failure: nil
551
552 Example:
553
554 {{code language="Lua"}}
555 print(we_bas_getbit("@B_HDX0.0"))
556 {{/code}}
557
558 == [[we_bas_setbit>>||anchor="HAddressclass"]] ==
559
560 Prototype: we_bas_setbit(address, value [, type])
561
562 Function: Write one bit
563
564 Parameters:
565
566 * address(string):address
567 * value(number):value,value=0 is off,value=1 is on
568 * type(number):type,type=1 is for write-through
569
570 Return:
571
572 * Success: true
573 * Failure: nil
574
575 Example:
576
577 {{code language="Lua"}}
578 we_bas_setbit("@B_HDX0.0", 1)
579 {{/code}}
580
581 == [[we_bas_getstring>>||anchor="HAddressclass"]] ==
582
583 Prototype: we_bas_getstring(address, len [, type, element4, element5, element6])
584
585 Function: Read string
586
587 Parameters:
588
589 * address(string):address
590 * len(number):length,Unit: byte
591 * type(number):type,type=1 is write-through
592 * element4:element
593
594 |=(% style="width: 203px;" %)Value|=(% style="width: 967px;" %)Describe
595 |(% style="width:203px" %)0|(% style="width:967px" %)Default
596 |(% style="width:203px" %)1|(% style="width:967px" %)Forced prohibition of the use of the high-order function
597 |(% style="width:203px" %)2|(% style="width:967px" %)Enable high and low character swapping
598 |(% style="width:203px" %)3|(% style="width:967px" %)Enable high and low byte swapping
599 |(% style="width:203px" %)4|(% style="width:967px" %)Gbk text, normal setting
600 |(% style="width:203px" %)5|(% style="width:967px" %)Gbk text, the first byte is the string length
601 |(% style="width:203px" %)6|(% style="width:967px" %)Endian-reversed type1: 12345678 -> 87654321
602 |(% style="width:203px" %)7|(% style="width:967px" %)Endian-reversed type2: 12345678 -> 78563412
603 |(% style="width:203px" %)8|(% style="width:967px" %)Endian-reversed type3: 12345678 -> 56781234
604 |(% style="width:203px" %)9|(% style="width:967px" %)Endian-reversed type4: 12345678 -> 65872143
605 |(% style="width:203px" %)10|(% style="width:967px" %)Endian-reversed type5: 12345678 -> 43218765
606 |(% style="width:203px" %)11|(% style="width:967px" %)Characters are stored in one word
607 |(% style="width:203px" %)12|(% style="width:967px" %)Unicode text
608
609 * element5:element
610
611 |=(% style="width: 203px;" %)Value|=(% style="width: 967px;" %)Describe
612 |(% style="width:203px" %)0|(% style="width:967px" %)Default
613 |(% style="width:203px" %)4|(% style="width:967px" %)Gbk text, normal setting
614 |(% style="width:203px" %)5|(% style="width:967px" %)Gbk text, the first byte is the string length
615 |(% style="width:203px" %)12|(% style="width:967px" %)Unicode text
616
617 * element6:element
618
619 |=(% style="width: 203px;" %)Value|=(% style="width: 967px;" %)Describe
620 |(% style="width:203px" %)0|(% style="width:967px" %)Default
621 |(% style="width:203px" %)11|(% style="width:967px" %)Characters are stored in one word
622
623 Return:
624
625 * Success: the designated length of the string
626 * Failure: nil
627
628 Example:
629
630 {{code language="Lua"}}
631 print(we_bas_getstring("@W_HDW0", 10,0,0,0,0))
632 {{/code}}
633
634 == [[we_bas_setstring>>||anchor="HAddressclass"]] ==
635
636 Prototype: we_bas_setstring(address, str [, len, type, element4, element5, element6])
637
638 Function: Write string
639
640 Parameters:
641
642 * address(string):address
643 * str(string):string
644 * len(number):length, if not set, it will be the bytes of the string
645 * element4:element
646
647 |=(% style="width: 203px;" %)Value|=(% style="width: 967px;" %)Describe
648 |(% style="width:203px" %)0|(% style="width:967px" %)Default
649 |(% style="width:203px" %)1|(% style="width:967px" %)Forced prohibition of the use of the high-order function
650 |(% style="width:203px" %)2|(% style="width:967px" %)Enable high and low character swapping
651 |(% style="width:203px" %)3|(% style="width:967px" %)Enable high and low byte swapping
652 |(% style="width:203px" %)4|(% style="width:967px" %)Gbk text, normal setting
653 |(% style="width:203px" %)5|(% style="width:967px" %)Gbk text, the first byte is the string length
654 |(% style="width:203px" %)6|(% style="width:967px" %)Endian-reversed type1: 12345678 -> 87654321
655 |(% style="width:203px" %)7|(% style="width:967px" %)Endian-reversed type2: 12345678 -> 78563412
656 |(% style="width:203px" %)8|(% style="width:967px" %)Endian-reversed type3: 12345678 -> 56781234
657 |(% style="width:203px" %)9|(% style="width:967px" %)Endian-reversed type4: 12345678 -> 65872143
658 |(% style="width:203px" %)10|(% style="width:967px" %)Endian-reversed type5: 12345678 -> 43218765
659 |(% style="width:203px" %)11|(% style="width:967px" %)Characters are stored in one word
660 |(% style="width:203px" %)12|(% style="width:967px" %)Unicode text
661
662 * element5:element
663
664 |=(% style="width: 203px;" %)Value|=(% style="width: 967px;" %)Describe
665 |(% style="width:203px" %)0|(% style="width:967px" %)Default
666 |(% style="width:203px" %)4|(% style="width:967px" %)Gbk text, normal setting
667 |(% style="width:203px" %)5|(% style="width:967px" %)Gbk text, the first byte is the string length
668 |(% style="width:203px" %)12|(% style="width:967px" %)Unicode text
669
670 * element6:element
671
672 |=(% style="width: 203px;" %)Value|=(% style="width: 967px;" %)Describe
673 |(% style="width:203px" %)0|(% style="width:967px" %)Default
674 |(% style="width:203px" %)11|(% style="width:967px" %)Characters are stored in one word
675
676 Return:
677
678 * Success: true
679 * Failure: nil
680
681 Example:
682
683 {{code language="Lua"}}
684 local str = "Hello"
685 we_bas_setstring("@W_HDW0", str, 10, 0, 0, 0, 0)
686 {{/code}}
687
688 == [[we_bas_bmov>>||anchor="HAddressclass"]] ==
689
690 Prototype: we_bas_bmov(dstAddress, srcAddress, len[, type])
691
692 Function: Copy data of the designated length from the source address to the target address
693
694 Parameters:
695
696 * dstAddress(string): Target address
697 * srcAddress(string): Source address
698 * len(number): designated length
699 * type(number): read-write type, if type=1, it means write through
700
701 Return:
702
703 * Success: true
704 * Failure: nil
705
706 Example:
707
708 {{code language="Lua"}}
709 we_bas_bmov("@W_HDW100", "@W_HDW0", 10)
710 {{/code}}
711
712 == [[we_bas_fill>>||anchor="HAddressclass"]] ==
713
714 Prototype: we_bas_fill(address, value, len)
715
716 Function: Assign the same value to continuous addresses
717
718 Parameters:
719
720 * address(string):address
721 * value(number):value
722 * len(number):continuous length(Unit:word)
723
724 Return:
725
726 * Success: true
727 * Failure: nil
728
729 Example:
730
731 {{code language="Lua"}}
732 we_bas_fill("@W_HDW0", 0, 10)
733 {{/code}}
734
735 == [[we_bas_newnoaddr>>||anchor="HAddressclass"]] ==
736
737 Prototype: we_bas_newnoaddr(address, len)
738
739 Function: External address offset
740
741 Parameters:
742
743 * address(string):address
744 * len(number):length
745
746 Return:
747
748 * Success: offset address(string)
749 * Failure: nil
750
751 Example:
752
753 {{code language="Lua"}}
754 local x0 = "@W_X0"
755 for i=1, 10 do
756 -- address offset x1 ~ x10
757 local x_i = we_bas_newnoaddr(x0, i)
758 -- todo
759 end
760 {{/code}}
761
762 == [[we_bas_newstataddr>>||anchor="HAddressclass"]] ==
763
764 Prototype: we_bas_newstataddr(address, len)
765
766 Function: External station number offset
767
768 Parameters:
769
770 * address(string):address
771 * len(number):length
772
773 Return:
774
775 * Success: offset address(string)
776 * Failure: nil
777
778 Example:
779
780 {{code language="Lua"}}
781 -- The address 10 of station No.1 is offset by 2 station numbers
782 local a = we_bas_newstataddr("@W_1:10", 2)
783 -- Write 20 to address 10 of station No.3
784 we_bas_setword(a, 20)
785 {{/code}}
786
787
788
789 == [[we_bas_getdatas>>||anchor="HAddressclass"]] ==
790
791 Prototype: we_bas_getdatas(address,quantity,type[,rwtype,hilorever])
792
793 Function: Read continous address
794
795 (% class="wikigeneratedid" %)
796 **Data type table**
797
798 |=Value|=Description
799 |0|16-bit signed decimal
800 |1|16-bit unsigned decimal
801 |2|32-bit signed decimal
802 |3|32-bit unsigned decimal
803 |4|32-bit floating point number
804 |5|64-bit floating point number
805 |6|bit
806
807 Parameters:
808
809 * address(string): address
810 * quantity(number): number
811 * type(number): data type, please refer to the data type table above
812 * rwtype(number): Read values directly from the device.  When type=1,  read values directly from the device.
813 * hilorever (number): high and low words. When type=1, high words are in front.
814
815 Return:
816
817 * Success: Return data table
818 * Failure: nil
819
820 Example:
821
822 {{code language="lua"}}
823 a = we_bas_getdatas("@W_HDW0",10,0) --Take @W_HDW0 as the start address, read ten consecutive words in a signed decimal.
824 for i,v in pairs(a)
825 print(i,v)
826 end
827 b = we_bas_getdatas("@B_HDX10.0",10,6) --Take B_HDX10.0 as the starting address and read ten consecutive bits.
828 for i,v in pairs(b)
829 print(i,v)
830 end
831 {{/code}}
832
833 == [[we_bas_setdatas>>||anchor="HAddressclass"]] ==
834
835 Prototype: we_bas_setdatas(address,data,quantity,type[,rwtype,hilorever])
836
837 Function: Read continous address
838
839 Parameters:
840
841 * address(string): address
842 * quantity(number): Data table name
843 * type(number): data type, please refer to the following data type table
844 * rwtype(number): Read-write type, if set type=1,  enable write through.
845 * hilorever (number): high and low words. When type=1, high words are in front.
846
847 **Data type table**
848
849 |=Value|=Description
850 |0|16-bit signed decimal
851 |1|16-bit unsigned decimal
852 |2|32-bit signed decimal
853 |3|32-bit unsigned decimal
854 |4|32-bit floating point number
855 |5|64-bit floating point number
856 |6|bit
857
858 Return:
859
860 * Success: 1
861 * Failure: nil
862
863 Example:
864
865 {{code language="lua"}}
866 tlb = {1,2,3,4,5,6,7,8,9,10}
867 we_bas_setdatas("@W_HDW0","tlb",10,0) --Take @W_HDW0 as the start address, write ten consecutive words.
868 tlbbit = {1,0,1,0,0,1,1,0,1,1}
869 we_bas_getdatas("@B_HDX10.0","tlbbit",10,0) --Take B_HDX10.0 as the starting address and read ten consecutive bits.
870 {{/code}}
871
872 = Path class =
873
874 (% class="wikigeneratedid" id="HUsageNotice" %)
875 **Usage Notice**
876
877 Before using this type of interface,you need to understand the structure of the File System inside the HMI.
878
879 == [[we_bas_getscriptpath>>||anchor="HPathclass"]](HMI) ==
880
881 Prototype: we_bas_getscriptpath()
882
883 Function: Get project script path
884
885 Parameters: None
886
887 Return:
888
889 * Success: The path of script(string)
890 * Failure: nil
891
892 Example:
893
894 {{code language="Lua"}}
895 local path = we_bas_getscriptpath()
896 if path then
897 -- todo
898 end
899 {{/code}}
900
901 == [[we_bas_getcustompath>>||anchor="HPathclass"]](HMI) ==
902
903 Prototype: we_bas_getcustompath()
904
905 Function: Get the available internal flash path
906
907 Parameters:None
908
909 Return:
910
911 * Success: Internal Flash path(string)
912 * Failure: nil
913
914 Example:
915
916 {{code language="Lua"}}
917 local path = we_bas_getcustompath()
918 if path then
919 -- todo
920 end
921 {{/code}}
922
923 == [[we_bas_getusbpath>>||anchor="HPathclass"]](HMI) ==
924
925 Prototype: we_bas_getusbpath()
926
927 Function: Detect USB, if detected, Return USB path (premise: support U disk Function)
928
929 Parameters: None
930
931 Return:
932
933 * Success: The path of USB
934 * Failure: nil
935
936 Example:
937
938 {{code language="Lua"}}
939 local path = we_bas_getusbpath()
940 if path then
941 print("udisk found")
942 -- todo
943 else
944 print("udisk not found")
945 end
946 {{/code}}
947
948 == [[we_bas_getsdpath>>||anchor="HPathclass"]](HMI) ==
949
950 Prototype: we_bas_getsdpath()
951
952 Function: Detect SD card, if detected, return SD card path (premise: support SD card Function)
953
954 Parameters: None
955
956 Return:
957
958 * Success: The path of SD card
959 * Failure: nil
960
961 Example:
962
963 {{code language="Lua"}}
964 local path = we_bas_getsdpath()
965 if path then
966 print("sd found")
967 -- todo
968 else
969 print("sd not found")
970 end
971 {{/code}}
972
973 == [[we_bas_file_exist>>||anchor="HPathclass"]](HMI) ==
974
975 Prototype: we_bas_file_exist(filepath)
976
977 Function: Does the file exist
978
979 Parameters:
980
981 * filepath(string):File path
982
983 Return:
984
985 * Success: true ~-~-exist
986 * Failure: false ~-~-not exist or error
987
988 Example:
989
990 {{code language="Lua"}}
991 -- Judge whether there is a file 123.txt in the root directory of the U disk
992 print(we_bas_file_exist("udisk:123.txt"))
993 {{/code}}
994
995 == [[we_bas_path_exist>>||anchor="HPathclass"]](HMI) ==
996
997 Prototype: we_bas_path_exist(dirpath)
998
999 Function: Does the folder exist
1000
1001 Parameters:
1002
1003 * dirpath(string): Folder path
1004
1005 Return:
1006
1007 * Success: true ~-~-exist
1008 * Failure: false ~-~-not exist or error
1009
1010 Example:
1011
1012 {{code language="Lua"}}
1013 -- Judge whether there is a folder dir in the root directory of the U disk
1014 print(we_bas_path_exist("udisk:dir"))
1015 {{/code}}
1016
1017 = Screen class =
1018
1019 == [[we_bas_jumpscreen>>||anchor="HScreenclass"]](HMI) ==
1020
1021 Prototype: we_bas_jumpscreen(screenid)
1022
1023 Function: Main screen jump
1024
1025 Parameters:
1026
1027 * screenid(number): Main screen No.
1028
1029 Return:
1030
1031 * Success: true
1032 * Failure: false
1033
1034 Example:
1035
1036 {{code language="Lua"}}
1037 -- Jump to Screen 0
1038 we_bas_jumpscreen(0)
1039 {{/code}}
1040
1041 {{info}}
1042 **✎Note: **Do not recommend to use this function in poll script, otherwise frequent calls may cause the HMI get stuck.
1043 {{/info}}
1044
1045 == [[we_bas_popscreen>>||anchor="HScreenclass"]](HMI) ==
1046
1047 Prototype: we_bas_popscreen(subscreenid, x, y)
1048
1049 Function: Pop up a sub-screen, if a built-in screen like keyboard pops up, the screen cannot be used
1050
1051 Parameters:
1052
1053 * subscreenid(number): Sub-screen No.
1054 * x(number):The X coordinate of upper left corner of the screen
1055 * y(number):The Y coordinate of upper left corner of the screen
1056
1057 Return:
1058
1059 * Success: true
1060 * Failure: false
1061
1062 Example:
1063
1064 {{code language="Lua"}}
1065 -- Pop up a sub-screen, coordinates (100, 100)
1066 we_bas_popscreen(100, 100, 100)
1067 {{/code}}
1068
1069 {{info}}
1070 **✎Note: **Do not recommend to use this function in poll script, otherwise frequent calls may cause the HMI get stuck.
1071 {{/info}}
1072
1073 == [[we_bas_closescreen>>||anchor="HScreenclass"]](HMI) ==
1074
1075 Prototype: we_bas_closescreen(subscreenid)
1076
1077 Function: Close sub-screen
1078
1079 Parameters:
1080
1081 * subscreenid(number): Sub-screen No.
1082
1083 Return:
1084
1085 * Success: true
1086 * Failure: false
1087
1088 Example:
1089
1090 {{code language="Lua"}}
1091 -- Close sub-screen 100
1092 we_bas_closescreen(100)
1093 {{/code}}
1094
1095 {{info}}
1096 **✎Note: **Do not recommend to use this function in poll script, otherwise frequent calls may cause the HMI get stuck.
1097 {{/info}}
1098
1099 = Others =
1100
1101 == [[we_bas_gettickcount>>||anchor="HOthers"]] ==
1102
1103 Prototype: we_bas_gettickcount()
1104
1105 Function: Get milliseconds that have passed since the operating system was started
1106
1107 Parameters: None
1108
1109 Return: Time
1110
1111 Example:
1112
1113 {{code language="Lua"}}
1114 print(we_bas_gettickcount())
1115 {{/code}}
1116
1117 == [[we_bas_sleep>>||anchor="HOthers"]] ==
1118
1119 Prototype: we_bas_sleep(millisecond)
1120
1121 Function: Sleep,**would block the running of the script**
1122
1123 Parameters:
1124
1125 * millisecond(number): Sleep milliseconds
1126
1127 Return: None;
1128
1129 Example:
1130
1131 {{code language="Lua"}}
1132 we_bas_sleep()
1133 {{/code}}
1134
1135 == [[we_bas_beep>>||anchor="HOthers"]] ==
1136
1137 Prototype: we_bas_beep()
1138
1139 Function: Beep
1140
1141 Parameters: None
1142
1143 Return: None
1144
1145 Example:
1146
1147 {{code language="Lua"}}
1148 we_bas_beep()
1149 {{/code}}
1150
1151 == [[we_atu8>>||anchor="HOthers"]] ==
1152
1153 Prototype: we_atu8(str)
1154
1155 Function: Character set conversion, windows to utf8
1156
1157 Note: Only effective for the simulator, no conversion in the real HMI
1158
1159 Parameters:
1160
1161 * str(string): string of windows character set
1162
1163 Return:
1164
1165 * Success: string of utf8 character set
1166 * Failure: nil
1167
1168 Example:[[Reference>>path:../input/General.odt/1.6lfs.html#func2]]
1169
1170 == [[we_u8ta>>||anchor="HOthers"]] ==
1171
1172 Prototype: we_u8ta(str)
1173
1174 Function: Character set conversion, utf8 to windows
1175
1176 Note: Only effective for the simulator, no conversion in the real HMI
1177
1178 Parameters:
1179
1180 * str(string): string of utf8 character set
1181
1182 Return:
1183
1184 * Success: string of windows character set
1185 * Failure: nil
1186
1187 Example:[[Reference>>path:../input/General.odt/1.6lfs.html#func2]]
1188
1189 == [[we_bas_getmachineinfo>>||anchor="HOthers"]] ==
1190
1191 Prototype: we_bas_getmachineinfo()
1192
1193 Function: Get HMI machine information
1194
1195 Parameters: None
1196
1197 Return:
1198
1199 * Success: Model, Machine code, Image list
1200 * Failure: nil
1201
1202 Example:
1203
1204 {{code language="Lua"}}
1205 local sBoardType, sMachineID, sImageList = we_bas_getmachineinfo()
1206 local sSendData = ""
1207
1208 sSendData = sBoardType .. "\n" .. sMachineID .. "\n" .. sImageList
1209 print(sSendData)
1210 {{/code}}
1211
1212 = Lua object operation =
1213
1214 (% class="wikigeneratedid" id="HDescription" %)
1215 **Description**
1216
1217 The library is mainly added for **Lua Object **, used to control various states of Lua Object
1218
1219 The prefix name of the library is: **we_part_xxx**
1220
1221 (% class="box infomessage" %)
1222 (((
1223 (% class="wikigeneratedid" id="H270ENote:" %)
1224 **✎Note:**
1225
1226 * Do not use the functions of this type of interface for other types of components, may get unexpected results
1227 * The state of Lua object will be cleared after leaving the screen, and no state will be retained or recorded
1228 )))
1229
1230 |=Function|=Description
1231 |[[we_part_setstate>>||anchor="Hwe_part_setstate"]](HMI)|Set the state of the object
1232 |[[we_part_getstate>>||anchor="Hwe_part_getstate"]](HMI)|Get the state value of the object
1233 |[[we_part_settchenable>>||anchor="Hwe_part_settchenable"]](HMI)|Set object allowed to click
1234 |[[we_part_settchunable>>||anchor="Hwe_part_settchunable"]](HMI)|Set object not allowed to click
1235 |[[we_part_gettchstate>>||anchor="Hwe_part_gettchstate"]](HMI)|Get whether the object is allowed to be clicked
1236 |[[we_part_sethidestate>>||anchor="Hwe_part_sethidestate"]](HMI)|Set object hidden value
1237 |[[we_part_gethidestate>>||anchor="Hwe_part_gethidestate"]](HMI)|Get object hidden value
1238 |[[we_part_clickdown>>||anchor="Hwe_part_clickdown"]](HMI)|Send a click and press message to the specified object, and execute the press script
1239 |[[we_part_clickup>>||anchor="Hwe_part_clickup"]](HMI)|Send a click~-~- up message to the specified part and execute the pop~-~- up script
1240 |[[we_part_setcurrc>>||anchor="Hwe_part_setcurrc"]](HMI)|Set current outline information of object
1241 |[[we_part_getcurrc>>||anchor="Hwe_part_getcurrc"]](HMI)|Get current outline information of object
1242 |[[we_part_getoriginalrc>>||anchor="Hwe_part_getoriginalrc"]](HMI)|Get the original outline information of the object
1243
1244 == [[we_part_setstate>>||anchor="HLuaobjectoperation"]](HMI) ==
1245
1246 Prototype: we_part_setstate(partname, value)
1247
1248 Function: Set the status of object
1249
1250 Parameter:
1251
1252 * partname(string): object name
1253 * value(number): the status value of the object
1254
1255 Return:
1256
1257 * Success: true
1258 * Failure: false
1259
1260 Example:
1261
1262 {{code language="Lua"}}
1263 -- Set the state of part 0_Lua_0 to 1
1264 we_part_setstate("0_Lua_0", 1)
1265 {{/code}}
1266
1267 == [[we_part_getstate>>||anchor="HLuaobjectoperation"]](HMI) ==
1268
1269 Prototype: we_part_getstate(partname)
1270
1271 Function: Get the status value of the object
1272
1273 Parameter:
1274
1275 * partname(string): object name
1276
1277 Return:
1278
1279 * Success: Status value (number)
1280 * Failure: nil
1281
1282 Example:
1283
1284 {{code language="Lua"}}
1285 print(we_part_getstate("0_Lua_0"))
1286 {{/code}}
1287
1288 == [[we_part_settchenable>>||anchor="HLuaobjectoperation"]](HMI) ==
1289
1290 Prototype: we_part_settchenable(partname)
1291
1292 Function: Set the object allowed to click
1293
1294 Parameter:
1295
1296 * partname(string): object name
1297
1298 Return:
1299
1300 * Success: true
1301 * Failure: false
1302
1303 Example:
1304
1305 {{code language="Lua"}}
1306 print(we_part_settchenable("0_Lua_0"))
1307 {{/code}}
1308
1309 == [[we_part_settchunable>>||anchor="HLuaobjectoperation"]](HMI) ==
1310
1311 Prototype: we_part_settchunable(partname)
1312
1313 Function: Set object not allowed to click
1314
1315 Parameter:
1316
1317 * partname(string): object name
1318
1319 Return:
1320
1321 * Success: true
1322 * Failure: false
1323
1324 Example:
1325
1326 {{code language="Lua"}}
1327 print(we_part_settchunable("0_Lua_0"))
1328 {{/code}}
1329
1330 == [[we_part_gettchstate>>||anchor="HLuaobjectoperation"]](HMI) ==
1331
1332 Prototype: we_part_gettchstate(partname)
1333
1334 Function: Get whether the object is allowed to be clicked
1335
1336 Parameter:
1337
1338 * partname(string): object name
1339
1340 Return:
1341
1342 * Success: true allowed to click, false not allowed to click
1343 * Failure: nil
1344
1345 Example:
1346
1347 {{code language="Lua"}}
1348 print(we_part_gettchstate("0_Lua_0"))
1349 {{/code}}
1350
1351 == [[we_part_sethidestate>>||anchor="HLuaobjectoperation"]](HMI) ==
1352
1353 Prototype: we_part_sethidestate(partname, value)
1354
1355 Function: set the hidden value of the object
1356
1357 Parameter:
1358
1359 * partname(string): object name
1360 * value(number): set value
1361 0: No special processing is performed, according to the Hide function controlled by the object’s control address
1362 1: Display and not be affected by the Hide function of the object's control address
1363 2: Hidden and not affected by the Hide function of the object's control address
1364
1365 Return:
1366
1367 * Success: true
1368 * Failure: false
1369
1370 Example:
1371
1372 {{code language="Lua"}}
1373 -- hide
1374 we_part_sethidestate("0_Lua_0", 2)
1375 {{/code}}
1376
1377 == [[we_part_gethidestate>>||anchor="HLuaobjectoperation"]](HMI) ==
1378
1379 Prototype: we_part_gethidestate(partname)
1380
1381 Function: Get the hidden value of the object
1382
1383 Parameter:
1384
1385 * partname(string): object name
1386
1387 Return:
1388
1389 * Success: true object is hidden, false object is displayed
1390 * Failure: nil
1391
1392 == [[we_part_clickdown>>||anchor="HLuaobjectoperation"]](HMI) ==
1393
1394 Prototype: we_part_clickdown(partname)
1395
1396 Function: Send a click~-~- down message to the specified component, and execute the click~-~- down script
1397
1398 Parameter:
1399
1400 * partname(string): object name
1401
1402 Return:
1403
1404 * Success: true
1405 * Failure: false
1406
1407 == [[we_part_clickup>>||anchor="HLuaobjectoperation"]](HMI) ==
1408
1409 Prototype: we_part_clickup(partname)
1410
1411 Function: Send a click~-~- up message to the specified component, and execute the click~-~- up script
1412
1413 Parameter:
1414
1415 * partname(string): object name
1416
1417 Return:
1418
1419 * Success: true
1420 * Failure: false
1421
1422 == [[we_part_setcurrc>>||anchor="HLuaobjectoperation"]](HMI) ==
1423
1424 Prototype: we_part_setcurrc(partname, left, top, right, bottom)
1425
1426 Function: Set the current contour info of the object
1427
1428 Parameter:
1429
1430 * partname(string): object name
1431 * left(number): coordinate value of the left side of the object
1432 * top(number): coordinate value of the left side of the object
1433 * right(number): coordinate value of the right side of the object
1434 * bottom(number): coordinate value of the bottom of the object
1435
1436 Return:
1437
1438 * Success: true
1439 * Failure: false
1440
1441 Example:
1442
1443 {{code language="Lua"}}
1444 -- Move the object to the upper left corner, and the size is 100x100
1445 we_part_setcurrc("0_Lua_0", 0, 0, 100, 100)
1446 {{/code}}
1447
1448 == [[we_part_getcurrc>>||anchor="HLuaobjectoperation"]](HMI) ==
1449
1450 Prototype: we_part_getcurrc(partname)
1451
1452 Function: Get the current contour info of the object
1453
1454 Parameter:
1455
1456 * partname(string): object name
1457
1458 Return:
1459
1460 * Success: left, top, right, bottom (number), four values
1461 * Failure: nil
1462
1463 Example:
1464
1465 {{code language="Lua"}}
1466 local left, top, right, bottom = we_part_getcurrc("0_Lua_0")
1467 print(left, top, right, bottom)
1468 {{/code}}
1469
1470 == [[we_part_getoriginalrc>>||anchor="HLuaobjectoperation"]](HMI) ==
1471
1472 Prototype: we_part_getoriginalrc(partname)
1473
1474 Function: Get the original contour info of the object
1475
1476 Parameter:
1477
1478 * partname(string): object name
1479
1480 Return:
1481
1482 * Success: left, top, right, bottom (number), four values
1483 * Failure: nil
1484
1485 Example:
1486
1487 {{code language="Lua"}}
1488 local left, top, right, bottom = we_part_getoriginalrc("0_Lua_0")
1489 print(left, top, right, bottom)
1490 {{/code}}
1491
1492 = Timer =
1493
1494 (% class="wikigeneratedid" id="HDescription" %)
1495 **Description**
1496
1497 The timer function is similar to the timing script of the Macro, which has the effect of timing execution. The difference is that Macro executes one script, while Lua executes one function.
1498
1499 The name of the library is: **timer**
1500
1501 (% class="wikigeneratedid" id="HFeatures" %)
1502 **Features**
1503
1504 * Trigger execution when timing arrives
1505 * Dynamic switching enable, can disable or enable during operation
1506 * The timing interval is variable, and the interval value can be modified during operation
1507
1508 (% class="wikigeneratedid" id="H270ENote:-1" %)
1509 **✎Note:**
1510
1511 * If multiple timers are registered in one screen, they will be executed out of order, and timing arrives will be executed first
1512 * The function registered by the timer cannot be written in an endless loop, otherwise it will be stuck in all operations, including the execution of screen polling **we//scr//poll_x**
1513
1514 (% class="wikigeneratedid" id="HList-1" %)
1515 List
1516
1517
1518 |=Function|=Description
1519 |[[timer.create>>||anchor="Htimer.create"]]|Create timer
1520 |[[timer.set_status>>||anchor="Htimer.set_status"]]|Enable timer
1521 |[[timer.get_status>>||anchor="Htimer.get_status"]]|Get timer status
1522 |[[timer.set_interval>>||anchor="Htimer.set_interval"]]|Modify timer interval value
1523 |[[timer.get_interval>>||anchor="Htimer.get_interval"]]|Get timer interval value
1524 |[[timer.get_func>>||anchor="Htimer.get_func"]]|Get the function associated with the timer
1525
1526 (% class="wikigeneratedid" id="HParameterRequirements:" %)
1527 **Parameter Requirements:**
1528
1529 The value range of **screen number** in the function parameters is:
1530
1531 * -1: Global background
1532 * [0,99999]: the corresponding screen number
1533
1534 The **ID** in the function parameters must be unique in every screen, and also unique in the global, but each screen is independent of each other. For example, a timer with ID=[1,2,3] is created on screen 0, screen 1 can also have a timer with ID=[1,2,3], and the global background can also have ID=[1,2, 3] these timers are independent and unique
1535
1536 == [[timer.create>>||anchor="HTimer"]] ==
1537
1538 Prototype: timer.create(screenid, id, interval, f)
1539
1540 Function: Create a timer, execute the registered function when the timer arrives, and automatically start to run after it is created by default
1541
1542 Parameter:
1543
1544 * screenid(number): screen number
1545 * id(number): ID
1546 * interval(number): interval
1547 * f(function): registered execution function
1548
1549 Return:
1550
1551 * Success: true
1552 * Failure: nil
1553
1554 Example:
1555
1556 {{code language="Lua"}}
1557 -- Method 1: On screen 0, create a timer with ID=1 and an interval of 1000ms
1558 timer.create(0, 1, 1000, function() print("Hello world") end)
1559
1560 -- Method 2: Write the function first, then register it
1561 function callback() print("Timer called") end
1562 -- Similarly, in screen 0, pay attention to ID=2 at this time, it cannot be repeated, and the function name can be used directly for the registration function
1563 timer.create(0, 2, 1000, callback)
1564
1565 -- Create a timer for global execution, which should follow the unique ID
1566 timer.create(-- 1, 1, 1000, function() print("This is global timer test.") end)
1567 {{/code}}
1568
1569 == [[timer.set_status>>||anchor="HTimer"]] ==
1570
1571 Prototype: timer.set_status(screenid, id, value)
1572
1573 Function: enable timer
1574
1575 Parameter:
1576
1577 * screenid(number): screen number
1578 * id(number): ID
1579 * value(number): value, 0: off, 1: on
1580
1581 Return:
1582
1583 * Success: true
1584 * Failure: nil
1585
1586 Example:
1587
1588 {{code language="Lua"}}
1589 -- Turn off the timer
1590 timer.set_status(0, 1, 0)
1591 -- Turn on the timer
1592 timer.set_status(0, 1, 1)
1593 {{/code}}
1594
1595 == [[timer.get_status>>||anchor="HTimer"]] ==
1596
1597 Prototype: timer.get_status(screenid, id)
1598
1599 Function: Get timer status
1600
1601 Parameter:
1602
1603 * screenid(number): screen number
1604 * id(number): ID
1605
1606 Return:
1607
1608 * Success: 0: off, 1: on (number)
1609 * Failure: nil
1610
1611 Example:
1612
1613 {{code language="Lua"}}
1614 -- Get the status of the timer
1615 local status = timer.get_status(0, 1)
1616 print(status)
1617 {{/code}}
1618
1619 (% id="Htimer.set_interval" %)
1620 == [[timer.set_interval>>||anchor="HTimer"]] ==
1621
1622 Prototype: timer.set_interval(screenid, id, num)
1623
1624 Function: modify the interval value of the timer
1625
1626 Parameter:
1627
1628 * screenid(number): screen number
1629 * id(number): ID
1630 * num(number): value, unit: ms
1631
1632 Return:
1633
1634 * Success: true
1635 * Failure: nil
1636
1637 Example:
1638
1639 {{code language="Lua"}}
1640 -- Change the interval value of screen 0, ID=1 to 2000ms
1641 timer.set_interval(0, 1, 2000)
1642 {{/code}}
1643
1644 == [[timer.get_interval>>||anchor="HTimer"]] ==
1645
1646 Prototype: timer.get_interval(screenid, id)
1647
1648 Function: Get the interval value of the timer
1649
1650 Parameter:
1651
1652 * screenid(number): screen number
1653 * id(number): ID
1654
1655 Return:
1656
1657 * Success: Interval value (number)
1658 * Failure: nil
1659
1660 Example:
1661
1662 {{code language="Lua"}}
1663 local val = timer.get_interval(0, 1)
1664 print(val)
1665 {{/code}}
1666
1667 == [[timer.get_func>>||anchor="HTimer"]] ==
1668
1669 Prototype: timer.get_func(screenid, id)
1670
1671 Function: Get the execution function associated with the timer
1672
1673 Parameter:
1674
1675 * screenid(number): screen number
1676 * id(number): ID
1677
1678 Return:
1679
1680 * Success: function
1681 * Failure: nil
1682
1683 Example:
1684
1685 {{code language="Lua"}}
1686 local f = timer.get_func(0, 1)
1687 -- Print function address
1688 print(f)
1689 -- or execute function
1690 f()
1691 {{/code}}
1692
1693 = Trigger =
1694
1695 (% class="wikigeneratedid" id="HDescription-2" %)
1696 **Description**
1697
1698 The trigger function is similar to the trigger script of Macro, which has the effect of triggering execution. The difference is that Macro executes a script, while Lua executes a function.
1699
1700 The name of the library is: **trigger**
1701 \\Support 5 trigger types:
1702
1703 1. TRUE: trigger.type_true
1704 1. FALSE: trigger.type_false
1705 1. Bit change: trigger.type_change
1706 1. Rising edge: trigger.type_raise
1707 1. Falling edge: trigger.type_fall
1708
1709 (% class="wikigeneratedid" id="HFeatures-1" %)
1710 **Features**
1711
1712 * Bit address condition triggers execution
1713 * Dynamic switching enable, which can enable or disable during operation
1714 * Variable trigger conditions, trigger conditions can be modified during operation
1715
1716 (% class="wikigeneratedid" id="H270ENote:-1" %)
1717 **✎Note:**
1718
1719 * If multiple triggers are registered in one screen, the address monitoring will be executed out of order
1720 * The function registered by the trigger cannot be written in an endless loop, otherwise it will be stuck in all operations, including the execution of screen polling **we//scr//poll_x**
1721
1722 |=Function|=Description
1723 |[[trigger.create>>||anchor="Htrigger.create"]]|Create Trigger
1724 |[[trigger.set_status>>||anchor="Htrigger.set_status"]]|Enable trigger
1725 |[[trigger.get_status>>||anchor="Htrigger.get_status"]]|Get trigger status
1726 |[[trigger.set_type>>||anchor="Htrigger.set_type"]]|Modify the trigger type of the trigger
1727 |[[trigger.get_type>>||anchor="Htrigger.get_type"]]|Get the trigger type of the trigger
1728 |[[trigger.get_func>>||anchor="Htrigger.get_func"]]|Get the execution function associated with the trigger
1729
1730 (% class="wikigeneratedid" id="HParameterRequirements:-1" %)
1731 **Parameter Requirements:**
1732
1733 The value range of **screen number** in the function parameters is:
1734
1735 * -1: Global background
1736 * [0,99999]: the corresponding screen number
1737
1738 The **ID** in the function parameters must be unique in every screen, and also unique in the global, but each screen is independent of each other. For example, a trigger with ID=[1,2,3] is created on screen 0, screen 1 can also have a trigger with ID=[1,2,3], and the global background can also have ID=[1,2, 3] , these triggers are independent and unique
1739
1740 == [[trigger.create>>||anchor="HTrigger"]] ==
1741
1742 Prototype: trigger.create(screenid, id, triggertype, address, f)
1743
1744 Function: Create a trigger, execute the registered function when the trigger condition is met, and automatically start monitoring after it is created by default
1745
1746 Parameter:
1747
1748 * screenid(number): screen number
1749 * id(number): ID
1750 * triggertype(number): trigger condition type
1751 * address(string): the bit address to be monitored and triggered
1752 * f(function): registered execution function
1753
1754 Return:
1755
1756 * Success: true
1757 * Failure: nil
1758
1759 Example:
1760
1761 {{code language="Lua"}}
1762 -- Method 1: On screen 0, create a trigger with ID=1, type TRUE, and address HDX0.0
1763 trigger.create(0, 1, trigger.type_true, "@B_HDX0.0", function() print("Hello world") end)
1764
1765 -- Method 2: Write the function first, then register
1766 function callback() print("trigger called") end
1767 -- Similarly, in screen 0, pay attention to ID=2 at this time, it cannot be repeated, and the function name can be used directly for the registration function
1768 trigger.create(0, 2, trigger.type_true, "@B_HDX0.1", callback)
1769
1770 -- Create a global execution bit change trigger, which should follow the unique ID
1771 trigger.create(-- 1, 1, trigger.type_change, "@B_HDX0.2", function() print("This is global trigger test.") end)
1772 {{/code}}
1773
1774 == [[trigger.set_status>>||anchor="HTrigger"]] ==
1775
1776 Prototype: trigger.set_status(screenid, id, value)
1777
1778 Function: Enable trigger
1779
1780 Parameter:
1781
1782 * screenid(number): screen number
1783 * id(number): ID
1784 * value(number): value, 0: off, 1: on
1785
1786 Return:
1787
1788 * Success: true
1789 * Failure: nil
1790
1791 Example:
1792
1793 {{code language="Lua"}}
1794 -- Enable the trigger
1795 trigger.set_status(0, 1, 0)
1796 -- Disable the trigger
1797 trigger.set_status(0, 1, 1)
1798 {{/code}}
1799
1800 == [[trigger.get_status>>||anchor="HTrigger"]] ==
1801
1802 Prototype: trigger.get_status(screenid, id)
1803
1804 Function: Get trigger status
1805
1806 Parameter:
1807
1808 * screenid(number): screen number
1809 * id(number): ID
1810
1811 Return:
1812
1813 * Success: 0: off, 1: on(number)
1814 * Failure: nil
1815
1816 Example:
1817
1818 {{code language="Lua"}}
1819 -- Get the status of the trigger
1820 local status = trigger.get_status(0, 1)
1821 print(status)
1822 {{/code}}
1823
1824 == [[trigger.set_type>>||anchor="HTrigger"]] ==
1825
1826 Prototype: trigger.set_type(screenid, id, num)
1827
1828 Function: modify the trigger type of the trigger
1829
1830 Parameter:
1831
1832 * screenid(number): screen number
1833 * id(number): ID
1834 * num(number): type value
1835
1836 Return:
1837
1838 * Success: true
1839 * Failure: nil
1840
1841 Example:
1842
1843 {{code language="Lua"}}
1844 -- Change the trigger type of screen 0, ID=1 to false
1845 trigger.set_type(0, 1, trigger.type_false)
1846 {{/code}}
1847
1848 == [[trigger.get_type>>||anchor="HTrigger"]] ==
1849
1850 Prototype: trigger.get_type(screenid, id)
1851
1852 Function: Get the trigger type of the trigger
1853
1854 Parameter:
1855
1856 * screenid(number): screen number
1857 * id(number): ID
1858
1859 Return:
1860
1861 * Success: trigger type value (number)
1862 * Failure: nil
1863
1864 Example:
1865
1866 {{code language="Lua"}}
1867 local val = trigger.get_type(0, 1)
1868 print(val)
1869 {{/code}}
1870
1871 == [[trigger.get_func>>||anchor="HTrigger"]] ==
1872
1873 Prototype: trigger.get_func(screenid, id)
1874
1875 Function: Get the execution function associated with the trigger
1876
1877 Parameter:
1878
1879 * screenid(number): screen number
1880 * id(number): ID
1881
1882 Return:
1883
1884 * Success: function
1885 * Failure: nil
1886
1887 Example:
1888
1889 {{code language="Lua"}}
1890 local f = trigger.get_func(0, 1)
1891 -- Print function address
1892 print(f)
1893 -- or execute function
1894 f()
1895 {{/code}}
1896
1897 = Flash Read&Write =
1898
1899 (% class="wikigeneratedid" id="HDescription-3" %)
1900 **Description**
1901
1902 Lua's io/os library doesn’t support operating the internal Flash of the HMI. There is another interface for Flash that can implement common operations for files and folders.
1903
1904 The name of the library is: **flash**
1905
1906 The path format of the system is drive letter: location, and the available drive letters have the following 4 types:
1907
1908 * User directory: "user:"
1909 * User script: "script:"
1910 * U Disk: "udisk:"
1911 * SD card: "sdcard:"
1912
1913 The following shows how to express the path:
1914
1915 * Example 1: If a file named 1.txt exists in the root directory of the U disk, the path expression is: udisk:1.txt
1916 * Example 2: If a folder named dir exists in the root directory of the U disk, the path expression is: udisk:dir
1917
1918 (% class="wikigeneratedid" id="H270ENote:-2" %)
1919 **✎Note:**
1920
1921 * In order to prolong the service life, there is a limited control for writing, and only 1M is allowed to be written within 1 minute. If it exceeds, an error message will be prompted
1922 * The storage space is limited. This part of the space for reading and writing in Lua is shared with Data recording, Historical data and other functions. If the recording data is full, it may be impossible to use Lua scripts to write files, and vice versa
1923
1924 |=Function|=Description
1925 |[[flash.file_write>>||anchor="Hflash.file_write"]]|Write file
1926 |[[flash.file_copy>>||anchor="Hflash.file_copy"]]|Copy file
1927 |[[flash.file_rename>>||anchor="Hflash.file_rename"]]|Rename file
1928 |[[flash.file_remove>>||anchor="Hflash.file_remove"]]|Delete file
1929 |[[flash.file_filter>>||anchor="Hflash.file_filter"]]|Traverse folders
1930 |[[flash.dir_make>>||anchor="Hflash.dir_make"]]|Recursively create folders
1931 |[[flash.dir_remove>>||anchor="Hflash.dir_remove"]]|Recursively delete folders
1932 |[[flash.file_u8ta>>||anchor="Hflash.file_u8ta"]]|File character set conversion, UTF8 to gb2312
1933 |[[flash.file_atu8>>||anchor="Hflash.file_atu8"]]|File character set conversion, gb2312 to UTF8
1934 |[[flash.file_save>>https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#Hflash.file_save]]|Save files immediately
1935
1936 == [[flash.file_write>>||anchor="HFlashRead26Write"]] ==
1937
1938 Prototype: flash.file_write(filepath, mode, data)
1939
1940 Function: Write data to a file, and you can write a file to the internal Flash through this interface
1941
1942 Parameter:
1943
1944 * filepath(string): file path
1945 * mode(string): open mode, it can be non~-~- r mode,
1946 * data(string): the data to be written
1947
1948 Return:
1949
1950 * Success: true
1951 * Failure: nil
1952
1953 Example: "w" is written once and "a" is written multiple times.
1954
1955 {{code language="Lua"}}
1956 -- Write to internal Flash
1957 flash.file_write("user:demo.txt", "w", "Hello world")
1958 flash.file_write("user:demo.txt", "a", "Hello world")
1959 -- Write to U disk
1960 flash.file_wrtie("udisk:export.txt", "w", "This is a demo file")
1961 flash.file_wrtie("udisk:export.txt", "a", "This is a demo file")
1962 {{/code}}
1963
1964 == [[flash.file_copy>>||anchor="HFlashRead26Write"]] ==
1965
1966 Prototype: flash.file_copy(srcpath, dstpath, failifexists)
1967
1968 Function: Copy files, you can copy files from the peripheral to the internal Flash through this interface, and can also be used to export
1969
1970 Parameter:
1971
1972 * srcpath(string): source file path
1973 * dstpath(string): target file path
1974 * failifexists(boolean): whether it fails if the target file already exists
1975 ** true if the target file exists, copy fails
1976 ** false If the target file exists, overwrite copy
1977
1978 Return:
1979
1980 * Success: true
1981 * Failure: nil
1982
1983 Example:
1984
1985 {{code language="Lua"}}
1986 -- Assuming that the U disk has a demo.txt file, copy it to the HMI and perform an overwrite copy
1987 flash.file_copy("udisk:demo.txt", "user:demo.txt", false)
1988 -- The following is the export
1989 flash.file_copy("user:demo.txt", "udisk:demo2.txt", true)
1990 {{/code}}
1991
1992 == [[flash.file_rename>>||anchor="HFlashRead26Write"]] ==
1993
1994 Prototype: flash.file_rename(oldname, newname)
1995
1996 Function: Rename file
1997
1998 Parameter:
1999
2000 * oldname(string): old file name path
2001 * newname(string): new file name path
2002
2003 Return:
2004
2005 * Success: true
2006 * Failure: false
2007
2008 Example:
2009
2010 {{code}}
2011 flash.file_rename("udisk:old.txt", "udisk:new.txt")
2012 {{/code}}
2013
2014 == [[flash.file_remove>>||anchor="HFlashRead26Write"]] ==
2015
2016 Prototype: flash.file_remove(filepath)
2017
2018 Function: delete files
2019
2020 Parameter:
2021
2022 * filepath(string): file name path
2023
2024 Return:
2025
2026 * Success: true
2027 * Failure: false
2028
2029 Example:
2030
2031 {{code language="Lua"}}
2032 flash.file_remove("udisk:new.txt")
2033 {{/code}}
2034
2035 == [[flash.file_filter>>||anchor="HFlashRead26Write"]] ==
2036
2037 Prototype: flash.file_filter(dirpath, format)
2038
2039 Function: traverse folders and return all file names that conform to the file format
2040
2041 Parameter:
2042
2043 * dirpath(string): folder path
2044 * format(string): file format
2045
2046 Return:
2047
2048 * Success: an array of file names (table)
2049 * Failure: nil
2050
2051 Example:
2052
2053 {{code language="Lua"}}
2054 -- Assume that the root directory of the U disk has the following files
2055 -- 123.txt|sheet.csv|demo.txt|zzz.txt|myword.doc
2056 -- Execute to get all files in txt format
2057 local data = flash.file_filter("udisk:", "*.txt")
2058 if data and type(data) == "table" then
2059 for i,v in ipairs(data) do
2060 print(i, v)
2061 end
2062 end
2063 {{/code}}
2064
2065 {{{Output:
2066 }}}
2067
2068 {{code language="Lua"}}
2069 1 123.txt
2070 2 demo.txt
2071 3 zzz.txt
2072 {{/code}}
2073
2074 == [[flash.dir_make>>||anchor="HFlashRead26Write"]] ==
2075
2076 Prototype: flash.dir_make(dirpath)
2077
2078 Function: Recursively create folders
2079
2080 Parameter:
2081
2082 * dirpath(string): folder path
2083
2084 Return:
2085
2086 * Success: true
2087 * Failure: false
2088
2089 Example:
2090
2091 {{code language="Lua"}}
2092 flash.dir_make("udisk:dir1/dir2/dir3")
2093 {{/code}}
2094
2095 == [[flash.dir_remove>>||anchor="HFlashRead26Write"]] ==
2096
2097 Prototype: flash.dir_remove(dirpath)
2098
2099 Function: delete folders recursively, **including files in the folder**
2100
2101 Parameter:
2102
2103 * dirpath(string): folder path
2104
2105 Return:
2106
2107 * Success: true
2108 * Failure: false
2109
2110 Example:
2111
2112 {{code language="Lua"}}
2113 -- Assuming that there are dir1/dir2/dir3, three-- level folders in the U disk, specify dir1 to clear all
2114 flash.dir_remove("udisk:dir1")
2115 {{/code}}
2116
2117 == [[flash.file_u8ta>>||anchor="HFlashRead26Write"]] ==
2118
2119 **Prototype:** flash.file_u8ta(u8file, gbfile)
2120
2121 **Function:** File character set conversion, UTF8 to GB2312
2122
2123 **Parameter:**
2124
2125 * u8file(string): utf8 file to convert
2126 * gbfile(string): Save gb2312 file of converted data (**Only files in a Udisk or sd card supported)**
2127
2128 **Return:**
2129
2130 * = 0:Succeed
2131 * =-1:Function parameter error
2132 * =-2:File path error
2133 * =-3:Failed to read utf8 file data
2134 * =-4:utf8 file data exception
2135 * =-5:Insufficient space
2136 * =-6:Data conversion failure
2137 * =-7:Failed to write the GB2312 file
2138
2139 **Example:**
2140
2141 {{code language="LUA"}}
2142 --Convert utF8 files in the Udisk to GB2312 and save the files in the Udisk
2143 flash.file_u8ta("udisk:utf8.txt", "udisk:new_gb2312.txt")
2144 {{/code}}
2145
2146 == [[flash.file_atu8>>||anchor="HFlashRead26Write"]] ==
2147
2148 **Prototype:** flash.file_atu8(gbfile, u8file)
2149
2150 **Function:** File character set conversion, UTF8 to GB2312
2151
2152 **Parameter:**
2153
2154 * u8file(string): gb2312 file to convert
2155 * gbfile(string): Save utf8 file of converted data (**Only files in a Udisk or sd card supported)**
2156
2157 **Return:**
2158
2159 * = 0:Succeed
2160 * =-1:Function parameter error
2161 * =-2:File path error
2162 * =-3:Failed to read gb2312 file data
2163 * =-4:utf8 file data exception
2164 * =-5:Insufficient space
2165 * =-6:Data conversion failure
2166 * =-7:Failed to write the utf8 file
2167
2168 **Example:**
2169
2170 {{code language="LUA"}}
2171 --Convert GB2312 files in the Udisk to utF8 and save the files in the Udisk
2172 flash.file_atu8("udisk:gb2312.txt", "udisk:new_u8.txt")
2173 {{/code}}
2174
2175 == [[flash.file_save>>https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#HFlashRead26Write]] ==
2176
2177 **Prototype:** flash.file_save(filePath)
2178
2179 **Function:** File saved immediately.
2180
2181 **Parameter:**
2182
2183 * filePath(string): File name that needs to save immediately.
2184
2185 **Return:**
2186
2187 * = 0:Succeed
2188
2189 **Example:**
2190
2191 {{code language="LUA"}}
2192 flash.file_save("udisk:111.txt")
2193 {{/code}}
2194
2195 = Other functions =
2196
2197 (% class="wikigeneratedid" id="HDescription-1" %)
2198 **Description**
2199
2200 The library provides operations for folder traversal, creation, and deletion
2201
2202 The name of the library is: **lfs**
2203
2204 (% class="wikigeneratedid" id="HList-4" %)
2205 List
2206
2207 |=Function|=Description
2208 |[[lfs.attributes>>||anchor="Hlfs.attributes"]]|Get properties
2209 |[[lfs.dir>>||anchor="Hlfs.dir"]]|Traverse folders
2210 |[[lfs.mkdir>>||anchor="Hlfs.mkdir"]]|Create folder
2211 |[[lfs.rmdir>>||anchor="Hlfs.rmdir"]]|Delete folder
2212
2213 == [[lfs.attributes>>||anchor="HOtherfunctions"]] ==
2214
2215 Prototype: lfs.attributes(filepath [, aname])
2216
2217 Function: Get properties and return a table with file properties corresponding to the file path. If the second parameter is given, only the value of the naming property will be returned
2218
2219 Parameter:
2220
2221 * filepath(string): file path
2222 * aname(string): file attribute
2223
2224 Return:
2225
2226 * Success: table
2227 * Failure: nil
2228
2229 Example:
2230
2231 {{code language="Lua"}}
2232 -- Judge whether the format of the specified file is a text file
2233 local filemode = lfs.attributes("udisk:123.txt", "mode")
2234 if filemode == "file" then
2235 print("udisk:123.txt is a normal txt file")
2236 end
2237 {{/code}}
2238
2239 == [[lfs.dir>>||anchor="HOtherfunctions"]] ==
2240
2241 Prototype: lfs.dir(dirpath)
2242
2243 Function: traverse the folder, this is an iterator function, need to use the for statement
2244
2245 Note: This interface function is planned to be deprecated in the future, it is recommended to use the [[flash.file_filter>>||anchor="Hflash.file_filter"]] function
2246
2247 Parameter:
2248
2249 * dirpath(string): folder path
2250
2251 Return:
2252
2253 * Success: file name (string)
2254 * Failure: nil
2255
2256 Example:
2257
2258 {{code language="Lua"}}
2259 -- Example of traversing folders
2260 local mydir = "udisk:"
2261 for fn in lfs.dir(mydir) do
2262 if fn ~= "." and fn ~= ".." then
2263 local filepath = mydir .. fn
2264 local attr = lfs.attributes(filepath)
2265 -- The simulator window needs the windows character set to display Chinese
2266 -- Print the full file path and its file properties
2267 print(we_u8ta(filepath), attr.mode)
2268 end
2269 end
2270 {{/code}}
2271
2272 == [[lfs.mkdir>>||anchor="HOtherfunctions"]] ==
2273
2274 Prototype: lfs.mkdir(dirpath)
2275
2276 Function: Create a folder (recursion is not supported)
2277
2278 Notice: This interface function is planned to be deprecated in the future, it is recommended to use the [[flash.dir_make>>||anchor="Hflash.dir_make"]] function
2279
2280 Parameter:
2281
2282 * dirpath(string): folder path
2283
2284 Return:
2285
2286 * Success: true
2287 * Failure: nil
2288
2289 Example:
2290
2291 {{code language="Lua"}}
2292 -- Create the parent folder first, then create the sub folders
2293 if lfs.mkdir("udisk:mydir") then
2294 lfs.mkdir("udisk:mydir/subdir")
2295 end
2296 {{/code}}
2297
2298 == [[lfs.rmdir>>||anchor="HOtherfunctions"]] ==
2299
2300 Prototype: lfs.rmdir(dirpath)
2301
2302 Function: Delete folder (recursion is not supported)
2303
2304 Note: This interface function is planned to be deprecated in the future. It is recommended to use the [[flash.dir_remove>>||anchor="Hflash.dir_remove"]] function
2305
2306 Parameter:
2307
2308 * dirpath(string): folder path
2309
2310 Return:
2311
2312 * Success: true
2313 * Failure: nil
2314
2315 Example:
2316
2317 {{code language="Lua"}}
2318 -- Remove the sub folder first, then remove the parent folder
2319 if lfs.rmdir("udisk:mydir/subdir") then
2320 lfs.rmdir("udisk:mydir")
2321 end
2322 {{/code}}
2323
2324 (% id="HTableDrawing28Experimental29" %)
2325 = Table drawing =
2326
2327 (% id="HDescription-2" %)
2328 Description
2329
2330 The name of the library is: cus_table
2331
2332 The following interface example assumes that there is a object named 0_CST_0 on screen 0
2333
2334 {{info}}
2335 (% id="H270ENote:-3" %)
2336 ✎Note:
2337
2338 * The appearance of the table style cannot be modified currently
2339 * It is currently an experimental function. If there is any modification in the future, please read the interface documentation carefully
2340 * The status of the parts will be cleared after leaving the screen, and no status will be retained or recorded
2341 {{/info}}
2342
2343 (% id="HList-5" %)
2344 List
2345
2346 |=Function|=Description
2347 |[[cus_table.set_cell>>||anchor="Hcus_table.set_cell"]](HMI)|Set the number of rows and columns of the table
2348 |[[cus_table.set_head>>||anchor="Hcus_table.set_head"]](HMI)|Set table header text
2349 |[[cus_table.set_mode>>||anchor="Hcus_table.set_mode"]](HMI)|Set display mode
2350 |[[cus_table.page_up>>||anchor="Hcus_table.page_up"]](HMI)|Execute page up
2351 |[[cus_table.page_down>>||anchor="Hcus_table.page_down"]](HMI)|Execute page down
2352 |[[cus_table.get_index>>||anchor="Hcus_table.get_index"]](HMI)|Get the currently selected index
2353 |[[cus_table.get_page>>||anchor="Hcus_table.get_page"]](HMI)|Get the current page and the total number of pages
2354 |[[cus_table.refresh>>||anchor="Hcus_table.refresh"]](HMI)|Refresh object
2355 |[[cus_table.reset>>||anchor="Hcus_table.reset"]](HMI)|Reset object
2356 |[[Example>>||anchor="HExample"]]|
2357
2358 (% id="Hcus_table.set_cell" %)
2359 == [[cus_table.set_cell>>||anchor="HTableDrawing28Experimental29"]](HMI) ==
2360
2361 Prototype: cus_table.set_cell(part, row, col[, ratio])
2362
2363 Function: Set the number of rows and columns of the table
2364
2365 * part(string): object name
2366 * row(number): number of rows
2367 * col(number): number of columns
2368 * ratio(string): optional parameter (default equal width), the ratio of column width
2369
2370 Return:
2371
2372 * Success: true
2373 * Failure: nil, error message
2374
2375 Example:
2376
2377 {{code language="Lua"}}
2378 --  Set the table with 20 rows and 6 columns. The width of the first column is twice times than that of the second column, and the second, third, fourth, fifth, and sixth columns are equal in width
2379 cus_table.set_cell("0_CST_0", 20, 6, "2:1:1:1:1:1")
2380 {{/code}}
2381
2382 (% id="Hcus_table.set_head" %)
2383 == [[cus_table.set_head>>||anchor="HTableDrawing28Experimental29"]](HMI) ==
2384
2385 Prototype: custable.sethead(part, head)
2386
2387 Function: set header text
2388
2389 * part(string): object name
2390 * head(table): array, head[1] position represents column 1, and so on
2391
2392 Return:
2393
2394 * Success: true
2395 * Failure: nil, error message
2396
2397 Example:
2398
2399 {{code language="Lua"}}
2400 -- Set the header text of these 6 columns
2401 local head = {
2402 [1] = "c1",
2403 [2] = "c2",
2404 [3] = "c3",
2405 [4] = "c4",
2406 [5] = "c5",
2407 [6] = "c6",
2408 }
2409 cus_table.set_head("0_CST_0", head)
2410 {{/code}}
2411
2412 (% id="Hcus_table.set_mode" %)
2413 == [[cus_table.set_mode>>||anchor="HTableDrawing28Experimental29"]](HMI) ==
2414
2415 Prototype: cus_table.set_mode(part, mode)
2416
2417 Function: Set the display mode, you can display in ascending or descending order, the default is ascending order
2418
2419 * part(string): object name
2420 * mode(number): 0 ascending order, 1 descending order
2421
2422 Return:
2423
2424 * Success: true
2425 * Failure: nil, error message
2426
2427 Example:
2428
2429 {{code language="Lua"}}
2430 --  Set to display in descending order
2431 cus_table.set_mode("0_CST_0", 1)
2432 {{/code}}
2433
2434 (% id="Hcus_table.page_up" %)
2435 == [[cus_table.page_up>>||anchor="HTableDrawing28Experimental29"]](HMI) ==
2436
2437 Prototype: cus_table.page_up(part)
2438
2439 Function: execute page up
2440
2441 * part(string): object name
2442
2443 Return:
2444
2445 * Success:
2446 ** true turn page up successfully
2447 ** false has reached the top page
2448 * Failure: nil, error message
2449
2450 Example:
2451
2452 {{code language="Lua"}}
2453 cus_table.page_up("0_CST_0")
2454 {{/code}}
2455
2456 (% id="Hcus_table.page_down" %)
2457 == [[cus_table.page_down>>||anchor="HTableDrawing28Experimental29"]](HMI) ==
2458
2459 Prototype: cus_table.page_down(part)
2460
2461 Function: Execute page down
2462
2463 * part(string): object name
2464
2465 Return:
2466
2467 * Success:
2468 ** true turn page down successfully
2469 ** false to the bottom page
2470 * Failure: nil, error message
2471
2472 Example:
2473
2474 {{code language="Lua"}}
2475 cus_table.page_down("0_CST_0")
2476 {{/code}}
2477
2478 (% id="Hcus_table.get_index" %)
2479 == [[cus_table.get_index>>||anchor="HTableDrawing28Experimental29"]](HMI) ==
2480
2481 Prototype: cus_table.get_index(part)
2482
2483 Function: Get the currently selected index
2484
2485 * part(string): object name
2486
2487 Return:
2488
2489 * Success: Index (number)
2490 * Failure: nil, error message
2491
2492 Example:
2493
2494 {{code language="Lua"}}
2495 print(cus_table.get_index("0_CST_0"))
2496 {{/code}}
2497
2498 (% id="Hcus_table.get_page" %)
2499 == [[cus_table.get_page>>||anchor="HTableDrawing28Experimental29"]](HMI) ==
2500
2501 Prototype: cus_table.get_page(part)
2502
2503 Function: Get the current page and the total number of pages
2504
2505 * part(string): object name
2506
2507 Return:
2508
2509 * Success: current page (number), total page number (number)
2510 * Failure: nil, error message
2511
2512 Example:
2513
2514 {{code language="Lua"}}
2515 print(cus_table.get_page("0_CST_0"))
2516 {{/code}}
2517
2518 (% id="Hcus_table.refresh" %)
2519 == [[cus_table.refresh>>||anchor="HTableDrawing28Experimental29"]](HMI) ==
2520
2521 Prototype: cus_table.refresh(part, data)
2522
2523 Function: Refresh the object, after performing page turning and modifying the data source, you need to call this function once to refresh the object display
2524
2525 * part(string): object name
2526 * data(table): data source, two~-~- dimensional array, data[1][1] position represents the content of the first row and the first column
2527
2528 Return:
2529
2530 * Success: true
2531 * Failure: nil, error message
2532
2533 Example:
2534
2535 {{code language="Lua"}}
2536 local t = {
2537 [1] = {1,2,3,4,5,6}, -- Row 1
2538 [2] = {2,3,4,5,6,7}, -- Row 2
2539 [3] = {3,4,5,6,7,8},
2540 }
2541 cus_table.refresh("0_CST_0", t)
2542 {{/code}}
2543
2544 (% id="Hcus_table.reset" %)
2545 == [[cus_table.reset>>||anchor="HTableDrawing28Experimental29"]](HMI) ==
2546
2547 Prototype: cus_table.reset(part)
2548
2549 Function: reset object, clear all settings
2550
2551 * part(string): object name
2552
2553 Return:
2554
2555 * Success: true
2556 * Failure: nil, error message
2557
2558 Example:
2559
2560 {{code language="Lua"}}
2561 cus_table.reset("0_CST_0")
2562 {{/code}}
2563
2564 == [[Example>>||anchor="HTableDrawing28Experimental29"]] ==
2565
2566 Use Lua object, add table_test() in the press script, compile and run to see the effect
2567
2568 {{code language="Lua"}}
2569 function table_test()
2570 local head = {
2571 [1] = "order",
2572 [2] = "c2",
2573 [3] = "c3",
2574 [4] = "c4",
2575 [5] = "c5",
2576 [6] = "c6",
2577 }
2578 local t = {
2579 [1] = {1,2,3,4,5,6}, -- The first row, the table has 6 columns, so all need 6 data
2580 [2] = {2,3,4,5,6,7},
2581 [3] = {3,4,5,6,7,8},
2582 }
2583 local part = "0_CST_0"
2584 cus_table.set_cell(part, 10, 6, "2:1:1:1:1:1")
2585 cus_table.set_head(part, head)
2586 cus_table.refresh(part, t)
2587 print(cus_table.get_index(part))
2588 print(cus_table.get_page(part))
2589 end
2590 {{/code}}
2591
2592 (% id="HCurveDrawing28Experimental29" %)
2593 = Curve drawing =
2594
2595 (% id="HDescription" %)
2596 Description
2597
2598 The name of the library is: cus_curve
2599
2600 {{code language="lua"}}
2601 local style = {
2602 color = 0xff0000, -- color [0,0xffffff]: red
2603 linetype = 0, -- Line type [0,3]: 0 solid line, 1 dotted line, 2 short dotted line, 3 long dotted line
2604 width = 1, -- line width [1,9]
2605 visible = 1,-- visible attribute [0,1]: 0 invisible, 1 visible
2606 }
2607 {{/code}}
2608
2609 The following interface example assumes that there is a object named 0_CST_0 on screen 0
2610
2611 {{info}}
2612 (% id="H270ENote:-4" %)
2613 ✎Note:
2614
2615 * It is currently an experimental function. If there is any modification in the future, please read the interface documentation carefully
2616 * The status of the object will be cleared after leaving the screen, and no status will be retained or recorded
2617 * It is able to draw up to 5 curves, 5 X-axis reference lines, and 5 Y-Axis reference lines at the same time
2618 {{/info}}
2619
2620 (% id="HList" %)
2621 List
2622
2623 |=Function|=Description
2624 |[[cus_curve.init>>||anchor="Hcus_curve.init"]](HMI)|Set the number of x and y major scale divisions
2625 |[[cus_curve.set_range>>||anchor="Hcus_curve.set_range"]](HMI)|Set the range of the specified axis
2626 |[[cus_curve.get_range>>||anchor="Hcus_curve.get_range"]](HMI)|Get the range of the specified axis
2627 |[[cus_curve.set_scale>>||anchor="Hcus_curve.set_scale"]](HMI)|Set the major scale style of the specified axis
2628 |[[cus_curve.get_scale>>||anchor="Hcus_curve.get_scale"]](HMI)|Get the major scale style of the specified axis
2629 |[[cus_curve.set_grid>>||anchor="Hcus_curve.set_grid"]](HMI)|Set the main grid style of the specified axis
2630 |[[cus_curve.get_grid>>||anchor="Hcus_curve.get_grid"]](HMI)|Get the main grid style of the specified axis
2631 |[[cus_curve.set_line>>||anchor="Hcus_curve.set_line"]](HMI)|Set the point and style of the curve
2632 |[[cus_curve.get_line>>||anchor="Hcus_curve.get_line"]](HMI)|Get the point and style of the curve
2633 |[[cus_curve.set_visible>>||anchor="Hcus_curve.set_visible"]](HMI)|Set the visibility of the curve
2634 |[[cus_curve.get_visible>>||anchor="Hcus_curve.get_visible"]](HMI)|Get the visibility of the curve
2635 |[[cus_curve.set_refer>>||anchor="Hcus_curve.set_refer"]](HMI)|Set a reference line
2636 |[[cus_curve.set_cursor>>||anchor="Hcus_curve.set_cursor"]](HMI)|Set the display of the click event cursor
2637 |[[cus_curve.draw_line>>||anchor="Hcus_curve.draw_line"]](HMI)|Draw a curve
2638 |[[cus_curve.refresh>>||anchor="Hcus_curve.refresh"]](HMI)|Refresh object
2639 |[[cus_curve.reset>>||anchor="Hcus_curve.reset"]](HMI)|Reset object
2640 |[[cus_curve.set_slider>>||anchor="Hcus_curve.set_slider"]]|Set the slider
2641 |Example|
2642
2643 (% id="Hcus_curve.init" %)
2644 == [[cus_curve.init>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2645
2646 Prototype: cus_curve.init(part, x, y)
2647
2648 Function: Set the number of x and y major scale divisions
2649
2650 * part(string): part name
2651 * x(number): The number of major scale on the x~-~- axis [1, 10]
2652 * y(number): the number of major scale on the y~-~- axis [1, 10]
2653
2654 Return:
2655
2656 * Success: true
2657 * Failure: nil, error message
2658
2659 Example:
2660
2661 {{code language="Lua"}}
2662 --  Set 3x3 major scale
2663 cus_curve.init("0_CST_0", 3, 3)
2664 {{/code}}
2665
2666 (% id="Hcus_curve.set_range" %)
2667 == [[cus_curve.set_range>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2668
2669 Prototype: cus_curve.set_range(part, axis, min, max)
2670
2671 Function: Set the range of the specified axis
2672
2673 * part(string): object name
2674 * axis(string): specify the axis, x or y
2675 * min(number): minimum value
2676 * max(number): maximum value
2677
2678 Return:
2679
2680 * Success: true
2681 * Failure: nil, error message
2682
2683 Example:
2684
2685 {{code language="Lua"}}
2686 --  Set the x-- axis range [1,4]
2687 cus_curve.set_range("0_CST_0", "x", 1, 4)
2688 --  Set the y-- axis range [1,4]
2689 cus_curve.set_range("0_CST_0", "y", 1, 4)
2690 {{/code}}
2691
2692 (% id="Hcus_curve.get_range" %)
2693 == [[cus_curve.get_range>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2694
2695 Prototype: cus_curve.get_range(part, axis)
2696
2697 Function: Get the range of the specified axis
2698
2699 * part(string): object name
2700 * axis(string): specify the axis, x or y
2701
2702 Return:
2703
2704 * Success: minimum (number), maximum (number)
2705 * Failure: nil, error message
2706
2707 Example:
2708
2709 {{code language="Lua"}}
2710 local xmin, xmax = cus_curve.get_range("0_CST_0", "x")
2711 print(xmin, xmax)
2712 {{/code}}
2713
2714 (% id="Hcus_curve.set_scale" %)
2715 == [[cus_curve.set_scale>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2716
2717 Prototype: cus_curve.set_scale(part, axis, style)
2718
2719 Function: Set the major scale style of the specified axis
2720
2721 * part(string): object name
2722 * axis(string): specify the axis, x or y
2723 * style(table): style sheet, [[format>>path:#linestyle]]
2724
2725 Return:
2726
2727 * Success: true
2728 * Failure: nil, error message
2729
2730 Example:
2731
2732 {{code language="Lua"}}
2733 local style = {
2734 color = 0x000000,
2735 linetype = 0,
2736 width = 1,
2737 visible = 1,
2738 }
2739 cus_curve.set_scale("0_CST_0", "x", style)
2740 cus_curve.set_scale("0_CST_0", "y", style)
2741 {{/code}}
2742
2743 (% id="Hcus_curve.get_scale" %)
2744 == [[cus_curve.get_scale>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2745
2746 Prototype: cus_curve.get_scale(part, axis)
2747
2748 Function: Get the major scale style of the specified axis
2749
2750 * part(string): object name
2751 * axis(string): specify the axis, x or y
2752
2753 Return:
2754
2755 * Success: style sheet (table)
2756 * Failure: nil, error message
2757
2758 Example:
2759
2760 {{code language="Lua"}}
2761 local x_scale_style = cus_curve.get_scale("0_CST_0", "x")
2762 {{/code}}
2763
2764 (% id="Hcus_curve.set_grid" %)
2765 == [[cus_curve.set_grid>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2766
2767 Prototype: cus_curve.set_grid(part, axis, style)
2768
2769 Function: Set the main grid style of the specified axis
2770
2771 * part(string): object name
2772 * axis(string): specify the axis, x or y
2773 * style(table): style sheet, [[format>>path:#linestyle]]
2774
2775 Return:
2776
2777 * Success: true
2778 * Failure: nil, error message
2779
2780 Example:
2781
2782 {{code language="Lua"}}
2783 local gridStyle = {
2784 color = 0xcccccc,
2785 linetype = 2,
2786 width = 1,
2787 visible = 1,
2788 }
2789 cus_curve.set_grid("0_CST_0", "x", gridStyle)
2790 cus_curve.set_grid("0_CST_0", "y", gridStyle)
2791 {{/code}}
2792
2793 (% id="Hcus_curve.get_grid" %)
2794 == [[cus_curve.get_grid>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2795
2796 Prototype: cus_curve.get_grid(part, axis)
2797
2798 Function: Get the main grid style of the specified axis
2799
2800 * part(string): object name
2801 * axis(string): specify the axis, x or y
2802
2803 Return:
2804
2805 * Success: style sheet (table)
2806 * Failure: nil, error message
2807
2808 Example:
2809
2810 {{code language="Lua"}}
2811 local x_grid_style = cus_curve.get_grid("0_CST_0", "x")
2812 {{/code}}
2813
2814 (% id="Hcus_curve.set_line" %)
2815 == [[cus_curve.set_line>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2816
2817 Prototype: cus_curve.set_line(part, id, num, style)
2818
2819 Function: Set the number of points and style of the curve
2820
2821 * part(string): object name
2822 * id(number): curve ID
2823 * num(number): The number of points that can be [0, 1000] for each curve
2824 * style(table): style sheet, see the beginning of this section for the format
2825
2826 Return:
2827
2828 * Success: true
2829 * Failure: nil, error message
2830
2831 Example:
2832
2833 {{code language="Lua"}}
2834 local line1Style = {
2835 color = 0x00868b,
2836 linetype = 0,
2837 width = 1,
2838 visible = 1,
2839 }
2840 -- Set the properties of line 1
2841 cus_curve.set_line("0_CST_0", 1, 4, line1Style)
2842 {{/code}}
2843
2844 (% id="Hcus_curve.get_line" %)
2845 == [[cus_curve.get_line>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2846
2847 Prototype: cus_curve.get_line(part, id)
2848
2849 Function: Get the number of points and style of the curve
2850
2851 * part(string): object name
2852 * id(number): curve ID
2853
2854 Return:
2855
2856 * Success: points (number), style sheet (table)
2857 * Failure: nil, error message
2858
2859 Example:
2860
2861 {{code language="Lua"}}
2862 local num, style = cus_curve.get_line("0_CST_0", 1)
2863 {{/code}}
2864
2865 (% id="Hcus_curve.set_visible" %)
2866 == [[cus_curve.set_visible>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2867
2868 Prototype: cus_curve.set_visible(part, id, visible)
2869
2870 Function: Set the visibility of the curve
2871
2872 * part(string): object name
2873 * id(number): curve ID
2874 * visible(number):[[visibility>>path:#linestyle]]
2875
2876 Return:
2877
2878 * Success: true
2879 * Failure: nil, error message
2880
2881 Example:
2882
2883 {{code language="Lua"}}
2884 --  Hide curve 1
2885 cus_curve.set_visible("0_CST_0", 1, 0)
2886 {{/code}}
2887
2888 (% id="Hcus_curve.get_visible" %)
2889 == [[cus_curve.get_visible>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2890
2891 Prototype: cus_curve.get_visible(part, id)
2892
2893 Function: Get the visibility of the curve
2894
2895 * part(string): object name
2896 * id(number): curve ID
2897
2898 Return:
2899
2900 * Success: visibility (number)
2901 * Failure: nil, error message
2902
2903 Example:
2904
2905 {{code language="Lua"}}
2906 local visable = cus_curve.get_visible("0_CST_0", 1)
2907 {{/code}}
2908
2909 (% id="Hcus_curve.set_refer" %)
2910 == [[cus_curve.set_refer>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2911
2912 Prototype: cus_curve.set_refer(part, axis, id, num, style)
2913
2914 Function: Set a reference line
2915
2916 * part(string): object name
2917 * axis(string): specify the axis, x or y
2918 * id(number): reference line ID
2919 * num(number): the value of the reference line
2920 * style(table): style sheet
2921
2922 Return:
2923
2924 * Success: true
2925 * Failure: nil, error message
2926
2927 Example:
2928
2929 {{code language="Lua"}}
2930 local referStyle = {
2931 color = 0x00468b,
2932 linetype = 0,
2933 width = 1,
2934 visible = 1,
2935 }
2936 -- Set a reference line perpendicular to the x axis and x=1.5
2937 cus_curve.set_refer("0_CST_0", "x", 1, 1.5, referStyle)
2938 {{/code}}
2939
2940 (% id="Hcus_curve.set_cursor" %)
2941 == [[cus_curve.set_cursor>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2942
2943 Prototype: cus_curve.set_cursor(part, mode, style)
2944
2945 Function: Set the display of the click event cursor
2946
2947 * part(string): object name
2948 * mode(number): display mode, 0 integer value, 1 floating value
2949 * style(table): style sheet, see the beginning of this section for the format
2950
2951 Return:
2952
2953 * Success: true
2954 * Failure: nil, error message
2955
2956 Example:
2957
2958 {{code language="Lua"}}
2959 local cursorStyle = {
2960 color = 0xff0000, -- color
2961 linetype = 2, -- line type
2962 width = 1, -- line width
2963 visible = 1, -- visible or not
2964 }
2965 cus_curve.set_cursor("0_CST_0", 0, cursorStyle)
2966 {{/code}}
2967
2968 (% id="Hcus_curve.draw_line" %)
2969 == [[cus_curve.draw_line>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2970
2971 Prototype: cus_curve.draw_line(part, id, data)
2972
2973 Function: Draw a curve and connect all the coordinates into a line in the increasing order of the array
2974
2975 * part(string): object name
2976 * id(number): curve ID
2977 * data(table): a one~-~- dimensional data table, odd~-~- numbered index represents x, even~-~- numbered index represents y, such as:
2978 (data[1], data[2]) represents the first coordinate (x1, y1),
2979 (data[3], data[4]) represents the second coordinate (x2, y2),
2980
2981 Return:
2982
2983 * Success: true
2984 * Failure: nil, error message
2985
2986 Example:
2987
2988 {{code language="Lua"}}
2989 local xy = {1, 3, 2, 1, 3, 4, 4, 1}
2990 cus_curve.draw_line("0_CST_0", 1, xy)
2991 {{/code}}
2992
2993 (% id="Hcus_curve.refresh" %)
2994 == [[cus_curve.refresh>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
2995
2996 Prototype: cus_curve.refresh(part)
2997
2998 Function: Refresh the object, call this interface after setting the scale, grid, label and line drawing to refresh the curve object and display it
2999
3000 * part(string): object name
3001
3002 Return:
3003
3004 * Success: true
3005 * Failure: nil, error message
3006
3007 Example:
3008
3009 {{code language="Lua"}}
3010 cus_curve.refresh("0_CST_0")
3011 {{/code}}
3012
3013 (% id="Hcus_curve.reset" %)
3014 == [[cus_curve.reset>>||anchor="HCurveDrawing28Experimental29"]](HMI) ==
3015
3016 Prototype: cus_curve.reset(part)
3017
3018 Function: reset object, clear all settings
3019
3020 * part(string): object name
3021
3022 Return:
3023
3024 * Success: true
3025 * Failure: nil, error message
3026
3027 Example:
3028
3029 {{code language="Lua"}}
3030 cus_curve.reset("0_CST_0")
3031 {{/code}}
3032
3033 == [[cus_curve.set_slider>>||anchor="HCurveDrawing28Experimental29"]] ==
3034
3035 Prototype: cus_curve.set_slider(part [, config] )
3036
3037 Function: Set curve slider and display the data selected by the slider.
3038
3039 * part(string): object name
3040 * config(table): Slider configuration option
3041
3042 Note:
3043
3044 {{code language="lua"}}
3045 --@1、Slider style configuration (the following are the default values of all parameters, select the specified configuration as needed):
3046 local config = {
3047 sliderType = 0, -- type[0,1], 0: x axis index, 1:y axis index
3048 format = {
3049 0, -- Label data format (Data format to be retained) [0,6]
3050 1, -- Channel 1 data format (Data format to be retained) [0,6]
3051 2, -- Channel 2 data format (Data format to be retained) [0,6]
3052 2, -- Channel 3 data format (Data format to be retained) [0,6]
3053 2, -- Channel 4 data format (Data format to be retained) [0,6]
3054 5 -- Channel 5 data format (Data format to be retained) [0,6]
3055 },
3056 func = sliderCallback, -- Handle the label data callback function
3057 lineColor = 0xff0000, -- slider color,[0x000000,0xffffff]
3058 lineType = 0, -- slider type,[0,3]
3059 lineWidth = 3, -- slider width,[0,10]
3060 fontSize = 15, -- text font size,[5,512]
3061 bgColor = 0xff7f00, -- background color,[0x0000,0xffffff]
3062 bgOpacity = 50 -- Background transparency,[0,100]
3063 }
3064
3065 -- @2、note:Callback function parameters format is as follows (the following are the default values, change them as needed):
3066 --srcData = {
3067 -- title = {name = "index = ", data = "7.00000"}
3068 -- label[5] = {
3069 -- {name = "Channel 1 : ", data = "3.00000"},
3070 -- {name = "Channel 2 : ", data = "4.00000"},
3071 -- {name = "Channel 3 : ", data = "5.00000"},
3072 -- {name = "Channel 4 : ", data = "6.00000"},
3073 -- {name = "Channel 5 : ", data = "7.00000"},
3074 -- }
3075 --}
3076 -- Example of callback function usage: (srcData is given internally as a parameter, and you need to pay attention to the format when processing the data)
3077 local function sliderCallback(srcData)
3078
3079 dstData = {}
3080 dstData.title = srcData.title
3081 dstData.label = srcData.label
3082 -- Change label title
3083 dstData.title.name = "date = "
3084 -- dstData.title.data = string.format("%f", tonumber(srcData.title.data))
3085 -- Change data
3086 dstData.label[1].name = "Temperature: "
3087 dstData.label[1].data = srcData.label[1].data.."(x10 ℃)"
3088 dstData.label[2].name = "humidity: "
3089 dstData.label[2].data = srcData.label[2].data.."(x10 %)"
3090 dstData.label[3].name = "luminous intensity: "
3091 dstData.label[3].data = srcData.label[3].data.."(x100 cd/㎡)"
3092 dstData.label[4].name = "wind power: "
3093 dstData.label[4].data = srcData.label[4].data.."(grade)"
3094 dstData.label[5].name = "PM2.5 : "
3095 dstData.label[5].data = srcData.label[5].data.."( x10)"
3096
3097 return dstData
3098 end
3099 {{/code}}
3100
3101 Example (For details, see Example 2):
3102
3103 {{code language="lua"}}
3104 -- Called as the default configuration
3105 cus_curve.set_slider(partName)
3106 {{/code}}
3107
3108 == [[Example>>||anchor="HCurveDrawing28Experimental29"]] ==
3109
3110 (% class="wikigeneratedid" id="Hexample1" %)
3111 **example 1**
3112
3113 Use Lua object, add curve_test() in the falling script, compile and run to see the effect
3114
3115 {{code language="Lua"}}
3116 function curve_test()
3117 local style = {
3118 color = 0x000000,
3119 linetype = 0,
3120 width = 1,
3121 visible = 1,
3122 }
3123 local gridStyle = {
3124 color = 0xcccccc,
3125 linetype = 2,
3126 width = 1,
3127 visible = 1,
3128 }
3129 local line1Style = {
3130 color = 0x00868b,
3131 linetype = 0,
3132 width = 1,
3133 visible = 1,
3134 }
3135 local referStyle = {
3136 color = 0x00468b,
3137 linetype = 0,
3138 width = 1,
3139 visible = 1,
3140 }
3141 local cursorStyle = {
3142 color = 0xff0000,
3143 linetype = 2,
3144 width = 1,
3145 visible = 1,
3146 }
3147 local xy = {1, 3, 2, 1, 3, 4, 4, 1}
3148 local part = "0_CST_0"
3149 cus_curve.init(part, 3, 3)
3150 cus_curve.set_range(part, "x", 1, 4)
3151 cus_curve.set_range(part, "y", 1, 4)
3152 cus_curve.set_scale(part, "x", style)
3153 cus_curve.set_scale(part, "y", style)
3154 cus_curve.set_grid(part, "x", gridStyle)
3155 cus_curve.set_grid(part, "y", gridStyle)
3156 cus_curve.set_line(part, 1, 4, line1Style)
3157 -- cus_curve.set_visible(part, 1, 0)
3158 cus_curve.set_refer(part, "x", 1, 1.5, referStyle)
3159 cus_curve.set_cursor(part, 0, cursorStyle)
3160 cus_curve.draw_line(part, 1, xy)
3161 cus_curve.refresh(part)
3162
3163 print(cus_curve.get_range(part, "x"))
3164 print(cus_curve.get_scale(part, "x"))
3165 print(cus_curve.get_grid(part, "x"))
3166 print(cus_curve.get_label(part, "x"))
3167 print(cus_curve.get_line(part, 1))
3168 print(cus_curve.get_visible(part, 1))
3169 end
3170 {{/code}}
3171
3172 (% class="wikigeneratedid" id="Hexample2" %)
3173 **example 2**
3174
3175 Use the Lua widget, add sldierRun() to the press script or init script, and compile.
3176
3177 {{code language="lua"}}
3178 --1、 Curve object configuration
3179 local c_axisX = "x"
3180 local c_axisY = "y"
3181 local config = {
3182 partName = "2_CST_0", -- object name
3183 scaleX = 6, -- The number of x-axis scales
3184 scaleY = 6, -- The number of y-axis scales
3185 minValueX = 1, -- Minimum value of x-axis
3186 maxValueX = 7, -- Maximum value of x-axis
3187 minValueY = 0, -- Minimum value of x-axis
3188 maxValueY = 6, -- Maximum value of y-axis
3189 }
3190
3191 -- Obtain style configuration
3192 local function getStyle(color,linetype,width,visible)
3193
3194 -- This is a uniform style sheet for curves, used to control the display of curves
3195 local style = {
3196 color = 0xff0000, -- color[0,0xffffff]: red
3197 linetype = 0, -- line style[0,3]:0 full line,1 Dotted dashed line,2 short dashed line,3 long dashed line
3198 width = 1, -- line width[1,9]
3199 visible = 1, -- visual property[0,1]:0 invisible, 1 visible,
3200 }
3201
3202 if color~=nil then style.color = color end
3203 if linetype~=nil then style.linetype = linetype end
3204 if width~= nil then style.width = width end
3205 if visible~=nil then style.visible = visible end
3206
3207 return style
3208 end
3209
3210 --2、Initialize the table
3211 local function initCurva()
3212 -- Initialize the numbers of X and Y scales
3213 cus_curve.init(config.partName, config.scaleX, config.scaleY);
3214
3215 -- Initialize the data ranges of X and Y scales
3216 cus_curve.set_range(config.partName, c_axisX, config.minValueX, config.maxValueX);
3217 cus_curve.set_range(config.partName, c_axisY, config.minValueY, config.maxValueY);
3218
3219 -- Initialize the styles of X and Y scales
3220 cus_curve.set_scale(config.partName, c_axisX, getStyle(0x000000))
3221 cus_curve.set_scale(config.partName, c_axisY, getStyle(0x000000))
3222
3223 -- Initializing the grid
3224 cus_curve.set_grid(config.partName, c_axisX, getStyle(0x000000,1))
3225 cus_curve.set_grid(config.partName, c_axisY, getStyle(0x000000,1))
3226
3227 -- Initialize the number of curve points and styles
3228 cus_curve.set_line(config.partName, 1, 1000, getStyle(0x000000))
3229 cus_curve.set_line(config.partName, 2, 1000, getStyle(0xff0000))
3230 cus_curve.set_line(config.partName, 3, 1000, getStyle(0x00ff00))
3231 cus_curve.set_line(config.partName, 4, 1000, getStyle(0x000ff0))
3232 cus_curve.set_line(config.partName, 5, 1000, getStyle(0xaaff00))
3233
3234 -- Set curve visibility
3235 cus_curve.set_visible(config.partName, 1, 1)
3236
3237 -- Draw curve
3238 local line1 = { 1,3.7, 2,3.9, 3,4.0, 4,3.9, 5,3.9, 6,3.8, 7,3.6}
3239 local line2 = {1,4.5, 2,5.0, 3,5.3, 4,4.9, 5,5.2, 6,4.8, 7,5.0}
3240 local line3 = {1,3.12, 2,3.00, 3,2.85, 4,2.96, 5,2.68, 6,2.70, 7,3.00}
3241 local line4 = {1,1, 2,1, 3,2, 4,1, 5,2, 6,1, 7,2}
3242 local line5 = {1,2.5, 2,2.4, 3,2.5, 4,2.3, 5,2.6, 6,2.5, 7,2.6}
3243 cus_curve.draw_line(config.partName, 1, line1)
3244 cus_curve.draw_line(config.partName, 2, line2)
3245 cus_curve.draw_line(config.partName, 3, line3)
3246 cus_curve.draw_line(config.partName, 4, line4)
3247 cus_curve.draw_line(config.partName, 5, line5)
3248
3249 -- Refresh to display
3250 cus_curve.refresh(config.partName)
3251 end
3252
3253 --3、Create a callback function
3254 local function sliderCallback(srcData)
3255
3256 dstData = {}
3257 dstData.title = srcData.title
3258 dstData.label = srcData.label
3259 -- Change the label title
3260 dstData.title.name = "date = "
3261 -- dstData.title.data = string.format("%f", tonumber(srcData.title.data))
3262 -- Change the data
3263 dstData.label[1].name = "Temperature: "
3264 dstData.label[1].data = srcData.label[1].data.."(x10 ℃)"
3265 dstData.label[2].name = "Huminity: "
3266 dstData.label[2].data = srcData.label[2].data.."(x10 %)"
3267 dstData.label[3].name = "luminous intensity: "
3268 dstData.label[3].data = srcData.label[3].data.."(x100 cd/㎡)"
3269 dstData.label[4].name = "wind power: "
3270 dstData.label[4].data = srcData.label[4].data.."(grade)"
3271 dstData.label[5].name = "PM2.5 : "
3272 dstData.label[5].data = srcData.label[5].data.."( x10)"
3273
3274 return dstData
3275 end
3276
3277 --4、set slider
3278 local function setSlider()
3279
3280 -- Fill in the parameters as needed
3281 local sliderCfg = {
3282 sliderType = 0, -- type[0,1], 0: x axis index, 1:y axis index
3283 format = {
3284 0, -- Label data format (Data format to be retained) [0,6]
3285 1, -- Channel 1 data format (Data format to be retained) [0,6]
3286 2, -- Channel 2 data format (Data format to be retained) [0,6]
3287 2, -- Channel 3 data format (Data format to be retained) [0,6]
3288 2, -- Channel 4 data format (Data format to be retained) [0,6]
3289 5 -- Channel 5 data format (Data format to be retained)[0,6]
3290 },
3291 func = sliderCallback, -- Handle the label data callback function
3292 lineColor = 0xff0000, -- slider color,[0x000000,0xffffff]
3293 lineType = 0, -- slider type,[0,3]
3294 lineWidth = 3, -- slider width, [0,10]
3295 fontSize = 15, -- text font size,[5,512]
3296 bgColor = 0xff7f00, -- background color,[0x0000,0xffffff]
3297 bgOpacity = 50 -- background transparency,[0,100]
3298 }
3299
3300 -- create a slider
3301 cus_curve.set_slider(config.partName,sliderCfg)
3302 end
3303
3304 -- Run the function
3305 function sldierRun()
3306 -- Initializing the table
3307 initCurva()
3308
3309 -- Set the slider
3310 setSlider()
3311 end
3312 {{/code}}
3313
3314 = MQTT =
3315
3316 (% class="wikigeneratedid" id="HDescription-7" %)
3317 **Description**
3318
3319 The library provides the MQTT client function, which can let HMI connect to the MQTT server
3320
3321 The name of the library is: **mqtt**
3322
3323 (% class="wikigeneratedid" id="HSafetyAuthentication" %)
3324 **Safety Authentication**
3325
3326 Only supports the method of username/password authentication
3327
3328 (% class="box infomessage" id="H270ENote:-5" %)
3329 (((
3330 **✎Note:** This library cannot be run on the simulator, please debug and run on HMI
3331
3332 Only ig series can support this library.
3333 )))
3334
3335 |=Function|=Description
3336 |[[mqtt.setup_cfg>>||anchor="Hmqtt.setup_cfg"]]|Get the configuration information of mqtt from the HMI
3337 |[[mqtt.create>>||anchor="Hmqtt.create"]]|Create object of mqtt client
3338 |[[mqtt.close>>||anchor="Hmqtt.close"]]|Close object of mqtt client
3339 |[[mqtt:connect>>||anchor="Hmqtt:connect"]]|Establish connection with the server
3340 |[[mqtt:disconnect>>||anchor="Hmqtt:disconnect"]]|Disconnect from server
3341 |[[mqtt:isconnected>>||anchor="Hmqtt:isconnected"]]|Whether connect to the server
3342 |[[mqtt:close>>||anchor="Hmqtt:close"]]|Close the mqtt client object
3343 |[[mqtt:subscribe>>||anchor="Hmqtt:subscribe"]]|Subscribe topic
3344 |[[mqtt:unsubscribe>>||anchor="Hmqtt:unsubscribe"]]|Unsubscribe topic
3345 |[[mqtt:publish>>||anchor="Hmqtt:publish"]]|Publish message
3346 |[[mqtt:on>>||anchor="Hmqtt:on"]]|Register message callback function
3347 |Example 1|Standard usage example of mqtt library
3348 |Example 2|How to easily get configuration parameters
3349
3350 == [[mqtt.setup_cfg>>||anchor="HMQTT"]] ==
3351
3352 Prototype: mqtt.setup_cfg()
3353
3354 Function: Get the user MQTT parameters configured in the “Cloud" in the record settings
3355
3356 Parameters: None
3357
3358 Return:
3359
3360 * Success: 4 results
3361 Server address (string)
3362 Client ID (string)
3363 Connection (table)
3364 Will message (table)
3365 * Failure: nil
3366
3367 Example: [[Example 2>>path:https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#HExample2]]
3368
3369 {{code language="Lua"}}
3370 local serverurl, clientid, conn, lwt = mqtt.setup_cfg()
3371 print(serverurl, clientid, conn, lwt)
3372 {{/code}}
3373
3374 == [[mqtt.create>>||anchor="HMQTT"]] ==
3375
3376 Prototype: mqtt.create(serverurl, clientid)
3377
3378 Function: Create mqtt client object
3379
3380 Parameter:
3381
3382 * serverurl(string): server address, format: "protocol:~/~/host:port"
3383 protocol: tcp
3384 host: Hostname/IP address
3385 port: such as 1883
3386 * clientid(string): client ID
3387
3388 Return:
3389
3390 * Success: mqtt object (mqtt)
3391 * Failure: nil, err
3392
3393 Example: [[Example 1>>https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#HExample1]]
3394
3395 {{code language="Lua"}}
3396 -- 1. Use Get method
3397 local serverurl, clientid, conn, lwt = mqtt.setup_cfg()
3398 local obj, err = mqtt.create(serverurl, clientid)
3399 if obj then
3400 print("mqtt create ok")
3401 else
3402 print("mqtt create:", err)
3403 end
3404
3405 -- 2. Use the designated IP method, if 192.168.1.123 is an mqtt server then
3406 local obj2 = mqtt.create("tcp://192.168.1.123:1883", "demo123")
3407 {{/code}}
3408
3409 == [[mqtt.close>>||anchor="HMQTT"]] ==
3410
3411 Prototype: mqtt.close(obj)
3412
3413 Function: close the mqtt client object
3414
3415 Parameter:
3416
3417 * obj(mqtt): obj is the object created and returned by mqtt.create
3418
3419 Return:
3420
3421 * Success: true
3422 * Failure: nil
3423
3424 Example:
3425
3426 {{code language="Lua"}}
3427 local obj2 = mqtt.create("tcp://192.168.1.123:1883", "demo123")
3428 if obj2 then
3429 print(mqtt.close(obj2))
3430 end
3431 {{/code}}
3432
3433 == [[mqtt:connect>>||anchor="HMQTT"]] ==
3434
3435 Prototype: mqtt:connect(conn[, lwt])
3436
3437 Function: establish connection with the server
3438
3439 Parameter:
3440
3441 * conn(table): table, require the following fields
3442 conn.username(string): username
3443 conn.password(string): password
3444 conn.keepalive(number): Keep-Alive Interval, unit: second, default 60 seconds
3445 conn.cleansession(number): Clean Session, default 1
3446 This function is used to control the behavior when connecting & disconnecting. Both client and server retain session information. This information is used to ensure arrived "at least once" and "accurately once" , and includes the topic subscribed by the client. You can choose to reserve or ignore the session message. The settings are as follows:
3447 1 (Clean): If the session exists previously and is 1, then all messages from session on the client and server are cleaned.
3448 0 (Reserved): Conversely, both the client and the server use the previous session. If the previous session does not exist, start a new session.
3449 * lwt(table): Will message, also called Last Will and Testament, require the following fields
3450 lwt.topic(string): Topic
3451 lwt.message(string): Message body
3452 lwt.qos(number): QoS value, default 0
3453 lwt.retain(number): Reserved flag bit, default 0
3454
3455 Return:
3456
3457 * Success: true
3458 * Failure: nil, err
3459
3460 Example: [[Example 1>>https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#HExample1]]
3461
3462 == [[mqtt:disconnect>>||anchor="HMQTT"]] ==
3463
3464 Prototype: mqtt:disconnect([timeout])
3465
3466 Function: Disconnect from the server
3467
3468 Parameter:
3469
3470 -timeout(number): Connection Timeout, unit: milliseconds, the default is 10000 milliseconds
3471
3472 Return:
3473
3474 * Success: true
3475 * Failure: nil
3476
3477 Example: [[Example 1>>https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#HExample1]]
3478
3479 == [[mqtt:isconnected>>||anchor="HMQTT"]] ==
3480
3481 Prototype: mqtt:isconnected()
3482
3483 Function: Whether connect to the server
3484
3485 Parameters: None
3486
3487 Return:
3488
3489 * Success: true Connected
3490 * Failure: false Not connected, other unknown situations also return false
3491
3492 Example: [[Example 1>>https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#HExample1]]
3493
3494 == [[mqtt:close>>||anchor="HMQTT"]] ==
3495
3496 Prototype: mqtt:close()
3497
3498 Function: Close the object of mqtt client (If it is connected to the server and not manually disconnected, it will be automatically disconnected)
3499
3500 Parameters: None
3501
3502 Return:
3503
3504 * Success: true
3505 * Failure: nil, err
3506
3507 Example: [[Example 1>>https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#HExample1]]
3508
3509 == [[mqtt:subscribe>>||anchor="HMQTT"]] ==
3510
3511 Prototype: mqtt:subscribe(topic, qos)
3512
3513 Function: Subscribe topic
3514
3515 Parameter:
3516
3517 * topic(string): Topic name
3518 * qos(number): QoS value
3519
3520 Return:
3521
3522 * Success: true
3523 * Failure: nil, err
3524
3525 Example: [[Example 1>>https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#HExample1]]
3526
3527 == [[mqtt:unsubscribe>>||anchor="HMQTT"]] ==
3528
3529 Prototype: mqtt:unsubscribe(topic)
3530
3531 Function: Unsubscribed topic
3532
3533 Parameter:
3534
3535 * topic(string): Topic name
3536
3537 Return:
3538
3539 * Success: true
3540 * Failure: nil, err
3541
3542 Example: [[Example 1>>https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#HExample1]]
3543
3544 == [[mqtt:publish>>||anchor="HMQTT"]] ==
3545
3546 Prototype: mqtt:publish(topic, message, qos, retain[, timeout])
3547
3548 Function: Publish message
3549
3550 Parameter:
3551
3552 * topic(string): Topic name
3553 * message(string): Message body
3554 * qos(number): QoS value
3555 * retain(number): Reserved flag
3556 * timeout(number): Waiting Timeout of publish response, unit: milliseconds (only works when QoS > 0)
3557
3558 Return:
3559
3560 * Success: true
3561 * Failure: nil, err
3562
3563 Example: [[Example 1>>https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#HExample1]]
3564
3565 == [[mqtt:on>>||anchor="HMQTT"]] ==
3566
3567 Prototype: mqtt:on(method, callback)
3568
3569 Function: Register message callback function
3570
3571 Parameter:
3572
3573 * method(string): Totally 3 types of events (Message/Arrived/Offline)
3574
3575 1.message: This function will be called when a message is received
3576
3577 * Function prototype: function(string topic, string message)
3578 * Parameters:
3579 ** topic Topic name
3580 message Message content
3581
3582 2.arrived: This function will be called after the publication is arrived
3583
3584 * Function prototype: function()
3585 * Parameters: None
3586
3587 3.offline: This function will be called after the connection is lost
3588
3589 * Function prototype: function(string cause)
3590 * Function:
3591 ** cause Reason of loss connection
3592 * callback(function): callback function, call this function once after the event is triggered
3593
3594 Return:
3595
3596 * Success: true
3597 * Failure: nil, err
3598
3599 Example: [[Example 1>>https://docs.we-con.com.cn/bin/view/PIStudio/09%20Lua%20Editor/Lua%20Script/#HExample1]]
3600
3601 == Example 1 ==
3602
3603 Effect: Demonstrate that the mqtt client sends and receives print data spontaneously
3604
3605 The operation steps are as follows:
3606
3607 1. Create a new file named mqdemo.lua, and copy the following code to the file
3608 1. Modify the configuration parameters in the function mqtt.create and the variable local config in the script
3609 1. Place a Lua object on screen No.0, and fill in mqtt_test() in the falling type script
3610 1. Compile and click object, let the object execute the function mqtt_test(), observe the debug console
3611
3612 {{code language="Lua"}}
3613 mqdemo_limits = 11
3614 local obj
3615 local config = {
3616 username = "admin",-- account
3617 password = "password",-- password
3618 keepalive = 100, -- set the Keepalive Interval to 100 seconds
3619 cleansession = 0, -- keep the session
3620 }
3621 -- mqtt execution
3622 function mqtt_loop()
3623 if not obj then
3624 local err
3625 -- Create an object, please replace it with the IP address of the server you want to connect to
3626 obj, err = mqtt.create("tcp://192.168.40.226:1883", "clientid")
3627 if obj then
3628 -- Register callback for receiving message
3629 obj:on("message",
3630 function(topic, msg)
3631 print("mqtt msg:", string.format("%s:%s", topic, msg))
3632 end
3633 )
3634 -- Register callback for lost connection
3635 obj:on("offline", function(cause) print("mqtt offline:", cause) end)
3636 -- Register callback for sending message
3637 obj:on("arrived", function() print("msg arrived") end)
3638 else
3639 print("mqtt create err:", err)
3640 end
3641 else
3642 if obj:isconnected() then
3643 obj:publish("tomyself", "send message to my self", 0, 0)
3644 else
3645 -- Connect
3646 local stat, err = obj:connect(config)
3647 if stat == nil then
3648 -- Connection failed
3649 print("mqtt connect err:", err)
3650 else
3651 -- Subscribe topic after the connection is successful
3652 obj:subscribe("tomyself", 0)
3653 end
3654 end
3655 -- The following comment lines are only used as interface demonstration usage, know how to call
3656 -- obj:unsubscribe("tohmi") - Unsubscribe
3657 -- obj:disconnect() - disconnect
3658 -- obj:close() - close
3659 end
3660 end
3661
3662 function mqtt_test()
3663 -- Create a timer on screen No.0
3664 timer.create(0, 0, 1000, mqtt_loop)
3665 end
3666 {{/code}}
3667
3668 == Example 2 ==
3669
3670 Goal: Learn to use the interface function to get configuration parameters
3671
3672 Effect: Demonstrate that mqtt client sends and receives print data spontaneously, same as example 1
3673
3674 The operation steps are as follows:
3675
3676 1. Confirm that the User MQTT parameters are configured in the “Cloud"
3677 1. Create a new file named mqdemo.lua, copy the following code to the file
3678 1. Modify the configuration parameters in the function mqtt.create and the variable local config in the script
3679 1. Place a Lua object on screen No.0, and fill in mqtt_test() in the falling type script
3680 1. Compile and click object, let it execute the function mqtt_test(), observe the debug output
3681
3682 {{code language="Lua"}}
3683 mqdemo_limits = 11
3684 local obj
3685
3686 -- mqtt execution
3687 function mqtt_loop()
3688 if not obj then
3689 local err
3690 -- Create an object, the parameters are taken from global variables
3691 obj, err = mqtt.create(URL, CLIENDID)
3692 if obj then
3693 -- Register callback for receiving message
3694 obj:on("message",
3695 function(topic, msg)
3696 print("mqtt msg:")
3697 print(string.format("topic: %s\\n msg: %s\\n", topic, msg))
3698 end
3699 )
3700 -- Register callback for lost connection
3701 obj:on("offline", function(cause) print("mqtt offline:", cause) end)
3702 -- Register callback for sending message
3703 obj:on("arrived", function() print("msg arrived") end)
3704 else
3705 print("mqtt create err:", err)
3706 end
3707 else
3708 if obj:isconnected() then
3709 obj:publish("tomyself", "send message to my self", 0, 0)
3710 else
3711 -- Connection, parameters are taken from global variables
3712 local stat, err = obj:connect(CONN, LWT)
3713 if stat == nil then
3714 -- Connection failed
3715 print("mqtt connect err:", err)
3716 else
3717 -- Subscribe topic after the connection is successful
3718 obj:subscribe("tomyself", 0)
3719 end
3720 end
3721 -- The following comment lines are only used as interface demonstration usage, know how to call
3722 -- obj:unsubscribe("tohmi") - Unsubscribe
3723 -- obj:disconnect() - disconnect
3724 -- obj:close() - close
3725 end
3726 end
3727
3728 function mqtt_test()
3729 -- Get parameters from the configuration and set them as global variables
3730 URL, CLIENDID, CONN, LWT = mqtt.setup_cfg()
3731 -- Create a timer on screen No.0
3732 timer.create(0, 0, 1000, mqtt_loop)
3733 end
3734 {{/code}}
3735
3736 = Cloud interface =
3737
3738 (% class="wikigeneratedid" id="HDescription-8" %)
3739 **Description**
3740
3741 The library provides the function of getting data collected by "Cloud".
3742
3743 In the configuration interface of the "Cloud", there is a checkbox for the tags for upload selection. If you make the following selections:
3744
3745 1. Check upload to Cloud: the real-time data, Data records, and Alarm record of the tags will be pushed to the Cloud.
3746 1. Check upload to User MQTT: the real-time data, Data records, and Alarm record of the tags will all be transmitted through the lua callback function, and the user can upload these data to the third-party server.
3747
3748 That is, the choice of the upload selection of the data, can only choose one from two.
3749
3750 **For example, if you choose upload to Cloud, all interfaces of this library can be considered invalid and cannot be used.**
3751
3752 The name of the library is: **cloud**, some of which are callback functions
3753
3754 (% class="box infomessage" id="H270ENote:-6" %)
3755 (((
3756 **✎Note:** This library cannot be run on the simulator, please debug and run on HMI.
3757 )))
3758
3759 == Data type table ==
3760
3761 |=Value|=Description
3762 |100|16-bit binary
3763 |101|16-bit octal
3764 |102|16-bit hexadecimal
3765 |103|16-bit BCD
3766 |104|16-bit signed decimal
3767 |105|16-bit unsigned decimal
3768 |200|32-bit binary
3769 |201|32-bit octal
3770 |202|32-bit hexadecimal
3771 |203|32-bit BCD
3772 |204|32-bit signed decimal
3773 |205|32-bit unsigned decimal
3774 |206|32-bit (single precision) floating
3775 |400|64-bit binary
3776 |401|64-bit octal
3777 |402|64-bit hexadecimal
3778 |403|64-bit BCD
3779 |404|64-bit signed decimal
3780 |405|64-bit unsigned decimal
3781 |406|64-bit (double precision) floating
3782 |1000|String format
3783
3784 == Function table ==
3785
3786 |=Function|=Description
3787 |[[cloud.get_history_def>>||anchor="Hcloud.get_history_def"]](HMI)|Get the configuration of Data record from HMI
3788 |[[cloud_history_data>>||anchor="Hcloud_history_data"]](HMI)|Data recording callback function
3789 |[[cloud.get_alarm_def>>||anchor="Hcloud.get_alarm_def"]](HMI)|Get the configuration of the alarm record on the configuration software
3790 |[[cloud_alarm_data>>||anchor="Hcloud_alarm_data"]](HMI)|Callback function of alarm record
3791 |[[cloud.get_groupdesc/bns_get_groupdesc>>||anchor="Hcloud.get_groupdesc"]]|Get the configurations of all groups (Only valid in "OpenCloud mode")
3792 |[[cloud.get_datadesc/bns_get_datadesc>>||anchor="Hcloud.get_datadesc"]]|Get the configurations of all collection points (Only valid in "OpenCloud mode")
3793 |[[cloud.get_groupdata/bns_get_groupdata>>||anchor="Hcloud.get_groupdata"]]|Get the collection point information of one group (Only valid in "OpenCloud mode")
3794 |[[cloud.set_data/bns_set_data>>||anchor="Hcloud.set_data"]]|Set a collection point (Only valid in "OpenCloud mode")
3795 |[[cloud.get_data/bns_get_data>>||anchor="Hcloud.get_data"]]|Get the data of a collection point(Only valid in "OpenCloud mode")
3796 |[[cloud.get_alldata/bns_get_alldata>>||anchor="Hcloud.get_alldata"]]|Get all the collection points that meet the conditions (Only valid in "OpenCloud mode")
3797 |[[cloud.set_onecache/bns_set_onecache>>||anchor="Hcloud.set_onecache"]]|Save a piece of data to the cache (Only valid in "OpenCloud mode")
3798 |[[cloud.get_allcache/bns_get_allcache>>||anchor="Hcloud.get_allcache"]]|Get data from the cache (Only valid in "OpenCloud mode")
3799
3800 == [[cloud.get_history_def>>||anchor="HFunctiontable"]](HMI) ==
3801
3802 Prototype: cloud.get_//history_//def()
3803
3804 Function: Get the configuration of Data record from HMI, only get channels with the Cloud checked
3805
3806 Parameters: None
3807
3808 Return:
3809
3810 * Success: three-dimensional array (table)
3811 * Failure: nil
3812
3813 Example:
3814
3815 {{code language="Lua"}}
3816 function get_history_config()
3817 local data = cloud.get_history_def()
3818 if data == nil then return end
3819 for i,m in ipairs(data) do
3820 print(i, m[1], m[2], m[3], m[4], m[5], m[6], m[7])
3821 -- [1] The group ID of the tag
3822 -- [2] The group name of the tag
3823 -- [3] Collection ID of the tag
3824 -- [4] The channel name of the tag
3825 -- [5] The address of the tag
3826 -- [6] The data format of the tag, see the beginning of this section
3827 -- [7] Data length of the tag
3828 end
3829 end
3830 {{/code}}
3831
3832 == [[cloud_history_data>>||anchor="HFunctiontable"]](HMI) ==
3833
3834 Prototype: cloud_//history_//data(gid, ts, data)
3835
3836 Function: Data Record collection callback function, when the collection conditions are met, the collection is triggered and this interface function is called
3837
3838 Parameter:
3839
3840 * gid(number): group ID
3841 * ts(string): time format string, for example: "2021-03-01 14:35:38"
3842 * data(table): two-dimensional array, collected data
3843 The first layer is the number of data
3844 The second layer is the specific information of the data
3845
3846 Return: None
3847
3848 Example:
3849
3850 {{code language="Lua"}}
3851 function cloud_history_data(gid, t, tb)
3852 if tb == nil then return end
3853 print("group id=", gid)
3854 print("collect time=", t)
3855 for i,v in pairs(tb) do
3856 -- i represents the i-th tag, v is the second layer table, which contains the specific information of the data
3857 print(i, v[1], v[2], v[3])
3858 -- [1] Tag ID
3859 -- [2] Current value
3860 -- [3] Tag status, 1 success, 0 failure
3861 end
3862 end
3863 {{/code}}
3864
3865 == **[[cloud.get_alarm_def>>||anchor="HFunctiontable"]]**(HMI)[[||anchor="HFunctiontable"]] ==
3866
3867 Prototype: cloud.get_//alarm_//def()
3868
3869 Function: Get the configuration of the Alarm record from HMI, only get channels with the Cloud checked
3870
3871 Parameters: None
3872
3873 Return:
3874
3875 * Success: two-dimensional array (table)
3876 * Failure: nil
3877
3878 Example:
3879
3880 {{code language="Lua"}}
3881 function get_alarm_config()
3882 local data = cloud.get_alarm_def()
3883 if data == nil then return end
3884 for i,m in ipairs(data) do
3885 print(i, m[1], m[2], m[3], m[4], m[5])
3886 -- [1] Tag ID
3887 -- [2] Alarm type, 0 bit, 1 word
3888 -- [3] Alarm address, for example: "HDX100.0" or "HDW19"
3889 -- [4] Alarm condition, for example: "On" or "100≤X≤300"
3890 -- [5] Alarm text
3891 end
3892 end
3893 {{/code}}
3894
3895 == [[**cloud_//alarm_//data**>>||anchor="HFunctiontable"]](HMI)[[||anchor="HFunctiontable"]] ==
3896
3897 Prototype: cloud_//alarm_//data(data)
3898
3899 Function: Alarm data callback function, call this interface function when an alarm occurs
3900
3901 Parameter:
3902
3903 * data(table): two-dimensional array, Alarm data
3904 The first level is the number of Alarm
3905 The second layer is the specific information of the Alarm
3906
3907 Return: None
3908
3909 Example:
3910
3911 {{code language="Lua"}}
3912 function cloud_alarm_data(tb)
3913 if tb == nil then return end
3914 for i,v in pairs(tb) do
3915 -- i means the i-th Alarm, v is the second layer table, which contains the specific information of the alarm
3916 print(i, v[1], v[2], v[3], v[4])
3917 -- [1] Tag ID
3918 -- [2] Current value
3919 -- [3] Tag status, 1 success, 0 failure
3920 -- [4] String time, for example: "2021-03-01 14:35:38"
3921 end
3922 end
3923 {{/code}}
3924
3925 == [[**cloud.get_groupdesc**>>||anchor="HFunctiontable"]] ==
3926
3927 Prototype: cloud.//get_groupdesc()//
3928
3929 Function: Get the configurations of all groups.
3930
3931 Parameter: None
3932
3933 Return:
3934
3935 * (((
3936 Success: table two-dimensional array
3937
3938 {
3939
3940 [1] = {[1] = Trigger type, [2] = Group name, [3] = Cycle},
3941
3942 ...
3943
3944 [n] = {[1] = xx, [2] = xx, [3] = xx},
3945
3946 }
3947 Trigger type:
3948
3949 0: Change triggered
3950
3951 1: Word triggered
3952
3953 2: No trigger (sampling by time)
3954
3955 3: Bit triggers record (sampling by time)
3956
3957 4: Bit triggers a record and resets
3958
3959 5:Bit triggers a record and does not reset
3960
3961 Cycle: Some tags type have no cycle (Unit: ms),then the cycle is -1.
3962 )))
3963 * Failure: table empty
3964
3965 Example:
3966
3967 {{code language="LUA"}}
3968 local tableGroupDef = cloud.get_groupdesc()
3969 local sSenddData = ""
3970
3971 for i, j in pairs(tableGroupDef) do
3972 local sData = ""
3973 for k, v in pairs(j) do
3974 sData = sData .. v
3975 sData = sData .. " "
3976 end
3977 sSenddData = sSenddData .. sData .. "\n"
3978 end
3979 print(sSenddData)
3980 {{/code}}
3981
3982 == [[**cloud.get_datadesc**>>||anchor="HFunctiontable"]] ==
3983
3984 Prototype: cloud.//get_datadesc()//
3985
3986 Function: Get the configurations of all collection points
3987
3988 Parameter: None
3989
3990 Return:
3991
3992 * (((
3993 Success: table three-dimensional array
3994
3995 {
3996
3997 [1]={~-~-~-~-~-~-First group
3998
3999 [1]={~-~-~-~-~-~-The tag array of first group
4000
4001 ?[1] = {[1] = Collection pointID, [2] = Collection point name, [3] = Read-write property, [4] = Type},
4002
4003 ...
4004
4005 [n] = {[1] = xx, [2] =xx [3] = xx, [4] = xx}
4006
4007 },
4008
4009 [2] = Group ID,
4010
4011 [3] = Group name
4012
4013 },
4014
4015 ......n groups and so on
4016
4017 }
4018
4019 Read-write property: 0: read-only, 1: write-only, 2: read and write
4020
4021 Type: 1: switch, 2: numerical, 3: strings
4022 )))
4023 * Failure: table empty
4024
4025 Example:
4026
4027 {{code language="LUA"}}
4028 local tablePointDef = cloud.get_datadesc()
4029 local sSendData = ""
4030
4031 for i, j in pairs(tablePointDef) do
4032 local sData = ""
4033 for x, y in pairs(j) do
4034 if type(y) == "table" then
4035 for k, v in pairs(y) do
4036 for a, b in pairs(v) do
4037 sData = sData .. b
4038 sData = sData .. ","
4039 end
4040 sData = sData .. " "
4041 end
4042 else
4043 sData = sData .. y
4044 sData = sData .. " "
4045 end
4046 end
4047 sSendData = sSendData .. sData .. "\n"
4048 end
4049 print(sSendData)
4050 {{/code}}
4051
4052 == [[**cloud.get_groupdata**>>||anchor="HFunctiontable"]] ==
4053
4054 Prototype: cloud.//get_groupdata(name)//
4055
4056 Function: Get the collection point information of one group
4057
4058 Parameter:
4059
4060 * name: group name
4061
4062 Return:
4063
4064 * (((
4065 Success: table two-dimensional array
4066
4067 {
4068
4069 [1]= {[1]=Collection point ID, [2]=status, [3]=Collect pointion name, [4]=Numeric value, [5]={Cunstom content}},
4070
4071 ...
4072
4073 [n] = {[1] = xx, [2] = xx, [3] = xx, [4] = xx, [5] = {xx}}
4074
4075 }
4076
4077 Status: 0: Online, -1: Write-only, -2: Offline,
4078 )))
4079 * Failure: table empty
4080
4081 Example:
4082
4083 {{code language="LUA"}}
4084 local sGroup = cloud.get_groupdata("Group 3")
4085 local sSendData = ""
4086
4087 for i, j in pairs(sGroup) do
4088 local sData = ""
4089 for k, v in pairs(j) do
4090 if type(v) == "table" then
4091 sData = sData .. "Custom:{"
4092 for x, y in pairs(v) do
4093 sData = sData .. x
4094 sData = sData .. ":"
4095 sData = sData .. y
4096 sData = sData .. ","
4097 end
4098 sData = sData .. "}"
4099 sData = sData .. " "
4100 else
4101 sData = sData .. v
4102 sData = sData .. " "
4103 end
4104 end
4105 sSendData = sSendData .. sData .. "\n"
4106 end
4107 print(sSendData)
4108 {{/code}}
4109
4110 == [[**cloud.set_data**>>||anchor="HFunctiontable"]] ==
4111
4112 Prototype: cloud.s//et_data(name, data)//
4113
4114 Function: Set a collection point
4115
4116 Parameter:
4117
4118 * name: collection point name
4119 * data: value (only be string)
4120
4121 Return:
4122
4123 * (((
4124 Success: The set value
4125 )))
4126 * Failure: nil
4127
4128 Example:
4129
4130 {{code language="LUA"}}
4131 local sValue = cloud.set_data("Channel 1", "100")
4132 local sSendData = ""
4133
4134 sSendData = sSendData .. "Set channel 1 Value : " .. sValue
4135 print(sSendData)
4136 {{/code}}
4137
4138 == [[**cloud.get_data**>>||anchor="HFunctiontable"]] ==
4139
4140 Prototype: cloud.g//et_data(name)//
4141
4142 Function: Get the configurations of a collection point
4143
4144 Parameter:
4145
4146 * name: collection point name
4147
4148 Return:
4149
4150 * (((
4151 Success: The value of collection point, the custom content of collection point
4152 )))
4153 * Failure: nil
4154
4155 Example:
4156
4157 {{code language="LUA"}}
4158 local sValue, tableCustome = cloud.get_data("Channel 1")
4159 local sSendData = ""
4160
4161 sSendData = sSendData .. sValue .. "\n"
4162 for i, j in pairs(tableCustome) do
4163 sSendData = sSendData .. i .. j .. "\n"
4164 end
4165 print(sSendData)
4166 {{/code}}
4167
4168 == [[**cloud.get_alldata**>>||anchor="HFunctiontable"]] ==
4169
4170 Prototype: cloud.//get_alldata()//
4171
4172 Function: Get all the collection points that meet the conditions
4173
4174 Parameter: None
4175
4176 Return:
4177
4178 * (((
4179 Success: table two-dimensional array
4180
4181 {
4182
4183 [1]= {[1]=Collection point ID, [2]=status, [3]=Collect pointion name, [4]=Numeric value, [5]={Cunstom content}},
4184
4185 ...
4186
4187 [n] = {[1] = xx, [2] = xx, [3] = xx, [4] = xx, [5] = {xx}}
4188
4189 }
4190
4191 Status: 0: Online, -1: Write-only, -2: Offline,
4192 )))
4193 * Failure: table empty
4194
4195 Example:
4196
4197 {{code language="LUA"}}
4198 local tablePointsData = cloud.get_alldata()
4199 local sSendData = ""
4200
4201 for i, j in pairs(tablePointsData) do
4202 local sData = ""
4203 for k, v in pairs(j) do
4204 if type(v) == "table" then
4205 sData = sData .. "Custom:{"
4206 for x, y in pairs(v) do
4207 sData = sData .. x
4208 sData = sData .. ":"
4209 sData = sData .. y
4210 sData = sData .. ","
4211 end
4212 sData = sData .. "}"
4213 sData = sData .. " "
4214 else
4215 sData = sData .. v
4216 sData = sData .. " "
4217 end
4218 end
4219 sSendData = sSendData .. sData .. "\n"
4220 end
4221 print(sSendData)
4222 {{/code}}
4223
4224 == [[**cloud.set_onecache**>>||anchor="HFunctiontable"]] ==
4225
4226 Prototype: cloud.set//_onecache(data)//
4227
4228 Function: Save a piece of data to the cache (30 seconds to write cached data to flash)
4229
4230 Parameter:
4231
4232 * data: the data to the cache
4233
4234 Return:
4235
4236 * (((
4237 Success: TRUE
4238 )))
4239 * Failure: nil
4240
4241 Example:
4242
4243 {{code language="LUA"}}
4244 local sSaveData = we_bas_getstring("@W_HDW5000", 10)
4245 local sSendData = ""
4246
4247 cloud.set_onecache(sSaveData)
4248 sSendData = sSendData .. "Save Data : " .. sSaveData
4249 print(sSendData)
4250 {{/code}}
4251
4252 == [[**cloud.get_allcache**>>||anchor="HFunctiontable"]] ==
4253
4254 Prototype: cloud.//get_allcache()//
4255
4256 Function: Getdata from the cache (The cache data and flash data will be cleared after fetching))
4257
4258 Parameter: None
4259
4260 Return:
4261
4262 * (((
4263 Success: table two-dimensional array
4264
4265 {
4266
4267 [1]="This is the oldest message", ~-~-~-~-~-~- The first one is the oldest message
4268
4269 ......
4270
4271 [n]="This is the latest message", ~-~-~-~-~-~- The last one is the latest message
4272
4273 }
4274 )))
4275 * Failure: nil
4276
4277 Example:
4278
4279 {{code language="LUA"}}
4280 local tableCacheDatas = cloud.get_allcache()
4281 local sSendData = ""
4282
4283 if nil == tableCacheDatas then
4284 return
4285 end
4286 for k, v in pairs(tableCacheDatas) do
4287 sSendData = sSendData .. v .. "\n"
4288 end
4289 print(sSendData)
4290 {{/code}}
4291
4292 = json =
4293
4294 (% class="wikigeneratedid" id="HDescription-9" %)
4295 **Description**
4296
4297 The library provides the conversion function from json string data to lua table data
4298
4299 The name of the library is: **json**
4300
4301 |=Function|=Description
4302 |[[json.encode>>||anchor="Hjson.encode"]]|Lua data type to json string
4303 |[[json.decode>>||anchor="Hjson.decode"]]|json string to lua data type
4304 |[[json.null>>||anchor="Hjson.null"]]|null
4305 |[[Example>>path:http://13.229.109.52:8080/wiki/pistudio/view/Helps/10.Lua/#HExample-2]]|
4306
4307 == [[json.encode>>||anchor="Hjson"]] ==
4308
4309 Prototype: json.encode(object)
4310
4311 Function: convert lua data type to json string
4312
4313 Parameter:
4314
4315 * object(boolean, number, string, table): lua data
4316
4317 Return:
4318
4319 * Success: json format string (string)
4320 * Failure: nil
4321
4322 == [[json.decode>>||anchor="Hjson"]] ==
4323
4324 Prototype: json.decode(json_string)
4325
4326 Function: json string to lua data type
4327
4328 Parameter:
4329
4330 * json_string(string): string on json data structure
4331
4332 Return:
4333
4334 * Success: lua data type
4335 * Failure: nil
4336
4337 == [[json.null>>||anchor="Hjson"]] ==
4338
4339 Prototype: json.null()
4340
4341 Function: This function is used when encapsulating json data, which is equivalent to null in json. If you use json.null() directly, it will directly return the address of the function, please use it with encode function together
4342
4343 Parameters: None
4344
4345 Return: None
4346
4347 == Example ==
4348
4349 {{code language="Lua"}}
4350 local json = require("json")
4351 local js_string = json.encode({1, 2,'fred', {username ='foo', password=json.null}})
4352 print("json encode:", js_string) -- convert to json data
4353 local data = json.decode(js_string) -- converted to script data type
4354 if type(data) =='table' then
4355 print("json decode:")
4356 for k,v in pairs(data) do
4357 print(k,v)
4358 end
4359 end
4360 {{/code}}
4361
4362 Output:
4363
4364 {{code language="Lua"}}
4365 json encode: [1,2,"fred",{"username":"foo","password":null}]
4366 json decode:
4367 1 1
4368 2 2
4369 3 fred
4370 4 table: 05B30068
4371 {{/code}}
4372
4373 = WLAN =
4374
4375 The library provides WLAN configuration function.
4376
4377 The name of the library is: **hmiwifi**
4378
4379 **List**
4380
4381 |=Function|=Description
4382 |[[hmiwifi.open>>||anchor="Hhmiwifi.open"]]|Enable
4383 |[[hmiwifi.close>>||anchor="Hhmiwifi.close"]]|Disable
4384 |[[hmiwifi.config>>||anchor="Hhmiwifi.config"]]|Configure
4385
4386 == [[hmiwifi.open>>||anchor="HWLAN"]] ==
4387
4388 Prototype: hmiwif.open()
4389
4390 Function: Enable wifi function
4391
4392 Parameters: None
4393
4394 Return:
4395
4396 * Success: ture
4397 * Failure: nil, err
4398
4399 == [[hmiwifi.close>>||anchor="HWLAN"]] ==
4400
4401 Prototype: hmiwif.close()
4402
4403 Function: Disnable wifi function
4404
4405 Parameters: None
4406
4407 Return:
4408
4409 * Success: ture
4410 * Failure: nil, err
4411
4412 == [[hmiwifi.config>>||anchor="HWLAN"]] ==
4413
4414 Prototype: hmiwif.close(ssid, passwd)
4415
4416 Function: Configure wifi
4417
4418 Parameters:
4419
4420 * ssid(string) hotspot name format: length 1~~32 bytes
4421 * passwd(streing) hotspot password format: length is 0 or greater 8
4422
4423 Return:
4424
4425 * Success: ture
4426 * Failure: nil, err
4427
4428 == Example ==
4429
4430 {{code language="LUA"}}
4431 local ret,err = hmiwifi.open()
4432 if ret then
4433 print("Wlan open ok")
4434 else
4435 print("Wlan open :", err)
4436 end
4437
4438 local ret,err = hmiwifi.config("aaa","12345678")
4439 if ret then
4440 print("Wlan config ok")
4441 else
4442 print("Wlan config:", err)
4443 End
4444
4445 //open hotspot
4446 local ret,err = hmiwifi.config("aaa","")
4447 if ret then
4448 print("Wlan config ok")
4449 else
4450 print("Wlan config:", err)
4451 end
4452
4453 local ret,err = hmiwifi.close()
4454 if ret then
4455 print("Wlan close ok")
4456 else
4457 print("Wlan close :", err)
4458 end
4459 {{/code}}
4460
4461 (% class="wikigeneratedid" %)
4462 Output:
4463
4464 {{code language="LUA"}}
4465 Wlan open ok
4466 Wlan config ok
4467 Wlan config ok
4468 Wlan close ok
4469 {{/code}}
4470
4471 = FtpServer =
4472
4473 The library provides the FtpServer password change function.
4474
4475 Library name: ftpserver
4476
4477 |=Function|=Fearture
4478 |[[ftpserver.changePsd>>||anchor="Hftpserver.changePsd(oldPsd,newPsd)"]]|Change the server password
4479
4480 == [[ftpserver.changePsd(oldPsd,newPsd)>>||anchor="HFtpServer"]] ==
4481
4482 Prototype: ftpserver.changePsd(oldPsd,newPsd)
4483
4484 Function: change the server password
4485
4486 Parameters:
4487
4488 * oldPsd(string) old password  format: length in 1 to 32 bytes
4489 * newPsd(string) new password  format: Only letters, numbers, and underscores are allowed,and the length must be 6 to 8 bits.
4490
4491 Return:
4492
4493 * Success: true
4494 * Failure: nil,err
4495
4496 == Example ==
4497
4498 {{code language="lua"}}
4499 local ret,err =ftpserver.changePsd("123456","888888")
4500 if ret then
4501 print("change_Password ok")
4502 else
4503 print("change_Password:", err)
4504 end
4505 {{/code}}
4506
4507 Output:
4508
4509 (% class="box" %)
4510 (((
4511 change_Password ok
4512 )))
4513
4514 = SIM =
4515
4516 (% class="wikigeneratedid" id="HInstruction" %)
4517 **Instruction:**
4518
4519 This library provides SIM card configuration information.
4520
4521 The name of the library is: **sim**.
4522
4523 {{info}}
4524 **✎Note: **Need to wait for about 15s after HMI powered on, this module can only run normally after the sim starts.
4525 {{/info}}
4526
4527 |=Function|=Description
4528 |[[sim.getCCID>>doc:||anchor="Hsim.getCCID"]]|Get CCID
4529 |[[sim.getIMEI>>doc:||anchor="Hsim.getIMEI"]]|Get IMEI
4530
4531 == [[sim.getCCID>>doc:||anchor="HSIM"]] ==
4532
4533 Prototype: sim.getCCID()
4534
4535 Function: Get CCID string
4536
4537 Parameters:
4538
4539 * None
4540
4541 Returns:
4542
4543 * Success: CCID string
4544 * Failure: nil
4545
4546 == [[sim.getIMEI>>doc:||anchor="HSIM"]] ==
4547
4548 Prototype: sim.getIMEI()
4549
4550 Function: Get IMEI string
4551
4552 Parameters:
4553
4554 * None
4555
4556 Returns:
4557
4558 * Success: IMEI string
4559 * Failure: nil
4560
4561 Example:
4562
4563 {{code language="LUA"}}
4564 local CCID = sim.getCCID();
4565 local IMEI = sim.getIMEI();
4566 if CCID then
4567 print("CCID = ",CCID)
4568 we_bas_setstring("@W_HDW0",CCID,256)
4569 end
4570 if IMEI then
4571 print("IMEI = ",IMEI)
4572 we_bas_setstring("@W_HDW500",IMEI,256)
4573 end
4574 {{/code}}
4575
4576 Output:
4577
4578 {{code language="LUA"}}
4579 CCID = 89860321482093086463
4580 IMEI = 866340051749169
4581 {{/code}}
4582
4583 = SMS =
4584
4585 **Instruction:**
4586
4587 This library provides relevant functions for sending SMS.
4588
4589 The name of the library is: **sms**.
4590
4591 {{info}}
4592 **✎Note: **
4593
4594 * Need to wait for about 15s after HMI powered on, this module only run normally after the sim starts.
4595 * Call the sending SMS interface, it will not be sent immediately, the program will only send when the polling time is about 2s.
4596 * Each mobile phone number is corresponding to one message ID in the same method of sending SMS. User can use the message ID to confirm that the set SMS of the current mobile phone number is successfully sent before sending the next new message, otherwise the new SMS will overwrite the old SMS.
4597 * It supports up to set to send to 20 mobile phone numbers at the same time, **if one mobile phone number uses two different SMS sending methods, it is equivalent to occupying two mobile phone numbers.**
4598 * To use this module function, need to declare its namespace first like following:
4599 {{/info}}
4600
4601 {{code language="lua"}}
4602 local sms = require("sms") -- Load SMS module
4603 {{/code}}
4604
4605 |=(% style="width: 255px;" %)Function|=(% style="width: 759px;" %)Description
4606 |(% style="width:255px" %)[[sms.send_sms_ira>>||anchor="Hsms.send_sms_ira"]]|(% style="width:759px" %)Send English SMS using the IRA character set
4607 |(% style="width:255px" %)[[sms.send_sms_ucs2>>doc:||anchor="Hsms.send_sms_ucs2"]]|(% style="width:759px" %)Send other languages' SMS using the UCS2 character set, such as Chinese, Japanese, Korean, etc.
4608 |(% style="width:255px" %)[[sms.sms_get_state>>doc:||anchor="Hsms.sms_get_state"]]|(% style="width:759px" %)Obtain corresponding SMS status
4609
4610 == [[sms.send_sms_ira>>doc:||anchor="HSMS"]] ==
4611
4612 Prototype: sms.send_sms_ira(number, message)
4613
4614 Function: Send English SMS using the IRA character set
4615
4616 Parameter:
4617
4618 * number(string): number(Only 32 characters at most, the exceed character will be discarded)
4619 * message(string): SMS content(Only 160 English characters at most, including special sign, the exceed character will be discarded, do not use characters from other languages in the content)
4620
4621 Return
4622
4623 * Success: Message id, is used for obtain corresponding SMS status
4624 * Failure: nil
4625
4626 Example:
4627
4628 {{code language="lua"}}
4629 local sms = require("sms") -- Load SMS module
4630 local num = we_bas_getstring("@W_HDW0",20)
4631 local msg = we_bas_getstring("@W_HDW1000",256)
4632 local id = sms.send_sms_ira(num,msg)--Sending SMS as IRA format
4633 --print("id:", id)
4634 we_bas_setword("@W_HDW202",id)--Save message id into HMI internal register
4635 {{/code}}
4636
4637 == [[sms.send_sms_ucs2>>doc:||anchor="HSMS"]] ==
4638
4639 Prototype: sms.send_sms_ucs2(number, message)
4640
4641 Function: Send other languages' SMS using the UCS2 character set, such as Chinese, Japanese, Korean, etc.
4642
4643 Parameter:
4644
4645 * number(string): number(Only 32 characters at most, the exceed character will be discarded)
4646 * message(string): SMS content(Only 70 characters for other languages at most, the exceed character will be discarded)
4647
4648 Return
4649
4650 * Success: Message id, is used for obtain corresponding SMS status
4651 * Failure: nil
4652
4653 Example:
4654
4655 {{code language="lua"}}
4656 local sms = require("sms") -- Load SMS module
4657 local num = we_bas_getstring("@W_HDW0",20)
4658 local msg = we_bas_getstring("@W_HDW1000",256)
4659 local id = sms.send_sms_ucs2(num,msg)--Sending SMS as UCS2 format
4660 --print("id:", id)
4661 we_bas_setword("@W_HDW202",id)--Save message id into HMI internal register
4662 {{/code}}
4663
4664 == [[sms.sms_get_state>>doc:||anchor="HSMS"]] ==
4665
4666 Prototype: sms.sms_get_state(id)
4667
4668 Function: Obtain corresponding SMS status
4669
4670 Parameter:
4671
4672 * id(number): Message id returned from function sms.send_sms_ira or sms.send_sms_ucs2
4673
4674 Return:
4675
4676 * Success: SMS status(1: Not sent, 2: Successfully sent, 3: Failed to send)
4677 * Failure: nil
4678
4679 Example:
4680
4681 {{code language="lua"}}
4682 local sms = require("sms") -- Load SMS module
4683 local id = we_bas_getword("@W_HDW202")--Get message id
4684 local state = sms.sms_get_state(id)--Obtain SMS sending status according to message id
4685 --print("state:", state)
4686 we_bas_setword("@W_HDW200",state)
4687 {{/code}}
4688
4689 = LuaSocket =
4690
4691 It is the network programming module of Lua, and can be used for secondary development according to requirements.
4692
4693 It include the following contents:
4694
4695 1. socket: Network basic module: basic parameter and baisic fuction
4696 1. [[dns>>||anchor="Hdnsmodule"]]: DNS module
4697 1. [[TCP:>>||anchor="HTCPmodule"]] TCP protocol object
4698 1. [[UDP>>||anchor="HUDPmodule"]]: UDP protocol object
4699 1. [[ftp:>>||anchor="HFTPmodule"]] ftp protocal API: Used for file transfer. This module only supports FTP client API, and does not support server API.
4700 1. [[http>>||anchor="Hhttpmodule"]]: http protocol API
4701 1. [[https:>>||anchor="Hhttpsmodule"]] https protocol API
4702 1. [[smtp: >>||anchor="HSMTPmodule"]]smtp protocol API: Used for third-party email services
4703 1. [[Other auxiliary modules>>||anchor="HAuxiliaryModule"]]: It is the extented function of module including ltn12 auxiliary module and mime auxiliary module.
4704 1. [[Appendix>>||anchor="HAppendix"]]: ftp parameter list
4705
4706 (% class="wikigeneratedid" id="H270ENote:-1" %)
4707 **✎Note:**
4708
4709 {{code language="LUA"}}
4710 local socket = require("socket") -- Load the socket module and everything it needs
4711 local http = require("socket.http") -- Load the http module and everything it needs
4712 local smtp = require("socket.smtp") -- Load the smtp module and everything it needs
4713 local ftp = require("socket.ftp") -- Load the ftp module and everything it needs
4714 {{/code}}
4715
4716 = Modules =
4717
4718 == Socket module parameter ==
4719
4720
4721 |=Parameter|=Description|=Value|=Type
4722 |_DATAGRAMSIZE|Call the default datagram size used to send and receive usage|8192|number
4723 |_SETSIZE|The maximum number of sockets that the select function can process|64|number
4724 |_SOCKETINVALID|invalid socket system operation value|4294967295|number
4725 |_VERSION|luasocket version|“LuaSocket 3.0-rc1”|string
4726 |BLOCKSIZE|socket receiving block size|2048|number
4727
4728 == Socket basic function ==
4729
4730
4731 |=Function|=Features
4732 |[[socket.bind()>>||anchor="Hsocket.bind2829"]]|Bind IP address and port, and return a TCP server object to the server
4733 |[[socket.connect4()>>||anchor="Hsocket.connect42829"]]|Connect the object to the IP address and port and create a TCP object.(IPV4)
4734 |[[socket.connect6()>>||anchor="Hsocket.connect62829"]]|Connect the object to the IP address and port and create a TCP object.(IPV6)
4735 |[[socket.gettime()>>||anchor="Hsocket.gettime2829"]]|Return the system time. Unit: scond.
4736 |[[socket.newtry()>>||anchor="Hsocket.newtry2829"]]|Create and return a function that throws an exception
4737 |[[socket.protect()>>||anchor="Hsocket.protect2829"]]|Convert the throw exception function to a safety function
4738 |[[socket.select()>>||anchor="Hsocket.select2829"]]|Wait for multiple sockets to change state
4739 |[[socket.sink()>>||anchor="Hsocket.sink2829"]]|Create an LTN12 sink from a stream socket object.
4740 |[[socket.sleep()>>||anchor="Hsocket.sleep2829"]]|Dormancy
4741 |[[socket.source()>>||anchor="Hsocket.source2829"]]|Create an LTN12 source from a stream socket object
4742 |[[socket.tcp()>>||anchor="Hsocket.tcp2829"]]|Create and return a Tcp object
4743 |[[socket.udp()>>||anchor="Hsocket.udp2829"]]|Creates an empty (disconnected) UDP object
4744
4745 == dns module ==
4746
4747 **✎Note:**
4748
4749 * DNS resolution in HMI is not supported due to internal changes in HMI. Therefore, only offline simulation is supported.
4750 * dns is a part of data socket basic module. To use the contents of this module, you need to quote the followings.
4751
4752 {{code language="LUA"}}
4753 local socket = require("socket") -- References the socket basic module
4754 local dns = socket.dns -- Get DNS module content
4755 {{/code}}
4756
4757 |=Function|=Features
4758 |[[dns.toip()>>||anchor="Hdns.toip2829"]]|Transfer from host name to IPv4 address
4759 |[[dns.getaddrinfo()>>||anchor="Hdns.getaddrinfo2829"]]|Transfer from host name to address
4760 |[[dns.tohostname()>>||anchor="Hdns.tohostname2829"]]|Transfer from IPv4 address to host name
4761 |[[dns.getnameinfo()>>||anchor="Hdns.getnameinfo2829"]]|Given an address (hostname or IP address) and port, and  returns all the information provided by the DNS resolver
4762 |[[dns.gethostname()>>||anchor="Hdns.gethostname2829"]]|Returns the standard hostname of the machine as a string
4763
4764 == TCP module ==
4765
4766 This module is a part of socket. It is the object created by socket.tcp() 、socket.tcp4() 、socket.tcp6().
4767
4768 This module divides Tcp objects into three types of objects: masterTcp、clientTcp、serverTcp.
4769
4770 Different Tcp objects have corresponding methods.
4771
4772 * masterTcp: close
4773 * clientTcp: send, receive, getsockname, getpeername, settimeout and close
4774 * serverTcp: accept, getsockname, setoption, settimeout and close
4775
4776 |=Function|=Features
4777 |[[tcp:bind()>>||anchor="Htcp:bind2829"]]|Bind the object to the address and port of the localhost
4778 |[[tcp:connect()>>||anchor="Htcp:connect2829"]]|Attempt to connect the primary object to the remote host
4779 |[[tcp:listen()>>||anchor="Htcp:listen2829"]]|Socket lisntening
4780 |[[tcp:accept()>>||anchor="Htcp:accept2829"]]|Wait for a remote connection and return the server object representing the link
4781 |[[tcp:send()>>||anchor="Htcp:send2829"]]|Send data
4782 |[[tcp:receive()>>||anchor="Htcp:receive2829"]]|Reads data from client object according to the specified read mode.
4783 |[[tcp:close()>>||anchor="Htcp:close2829"]]|Close a TCP object
4784 |[[tcp:getoption()>>||anchor="Htcp:getoption2829"]]|Gets the options for the TCP object
4785 |[[tcp:getpeername()>>||anchor="Htcp:getpeername2829"]]|Return information about the remote end of the connected client object
4786 |[[tcp:getsockname>>||anchor="Htcp:getsockname"]]|Return information about the local address associated with the object
4787 |[[tcp:getstats()>>||anchor="Htcp:getstats2829"]]|Return accounting information about a socket that can be used to limit bandwidth
4788 |[[tcp:gettimeout()>>||anchor="Htcp:gettimeout2829"]]|Get timeout
4789 |[[tcp:setoption()>>||anchor="Htcp:setoption2829"]]|Set the options for the TCP object
4790 |[[tcp:setstats()>>||anchor="Htcp:setstats2829"]]|Reset accounting information on sockets (useful for bandwidth limit)
4791 |[[tcp:settimeout()>>||anchor="Htcp:settimeout2829"]]|Change the timeout value of tcp object
4792 |[[tcp:shutdown()>>||anchor="Htcp:shutdown2829"]]|Disable some full-duplex connections.
4793 |[[tcp:getfamily()>>||anchor="Htcp:getfamily2829"]]|Get the TCP protocol family
4794 |[[tcp:setpeername()>>||anchor="Htcp:setpeername2829"]]|Change the main object to connect to remote host
4795 |[[tcp:setsockname()>>||anchor="Htcp:setsockname"]]|Change the address and port number of the object binding
4796
4797 == UDP module ==
4798
4799 This module is a part of socket. It is the object created by socket.udp(), socket.udp4(), socket.udp6().
4800
4801 This module divides UDP objects into twotypes: connect and connected. The difference is whether remote ports and addresses are bound to the generated object. Please refer to the following table.
4802
4803
4804 |=Function|=Features
4805 |[[udp:send()>>||anchor="Hudp:send2829"]]|Sends datagrams to connected UDP objects
4806 |[[udp:sendto()>>||anchor="Hudp:sendto2829"]]|Sends a datagram to the specified IP address and port number.
4807 |[[udp:receive()>>||anchor="Hudp:receive2829"]]|Receives datagrams from UDP objects
4808 |[[udp:receivefrom()>>||anchor="Hudp:receivefrom2829"]]|Receives datagrams and addresses and ports from UDP objects
4809 |[[udp:close()>>||anchor="Hudp:close2829"]]|Close udp object
4810 |[[udp:gettimeout()>>||anchor="Hudp:gettimeout2829"]]|Get timeout value
4811 |[[udp:settimeout()>>||anchor="Hudp:settimeout2829"]]|Change timeout value of udp object
4812 |[[udp:getoption()>>||anchor="Hudp:getoption2829"]]|Gets the option value from the UDP object
4813 |[[udp:getpeername()>>||anchor="Hudp:getpeername2829"]]|Search information about the peer associated with the connected UDP object
4814 |[[udp:getsockname()>>||anchor="Hudp:getsockname2829"]]|Return information about the local address associated with the object
4815 |[[udp:setoption()>>||anchor="Hudp:setoption2829"]]|Set the options for the UDP object
4816 |[[udp:setpeername()>>||anchor="Hudp:setpeername2829"]]|Change the remote information of UDP object
4817 |[[udp:setsockname()>>||anchor="Hudp:setsockname2829"]]|Bind UDP object to local address
4818 |[[udp:getfamily()>>||anchor="Hudp:getfamily2829"]]|Return a tcp protocol family
4819
4820 == FTP module ==
4821
4822 * This is submodule of socket. To use the contents of this module, you need to quote the followings.
4823
4824 {{{local ftp = require("socket.ftp")
4825 }}}
4826
4827 For details about FTP commands, see "appendix".
4828
4829
4830 |=Parameter|=Type|=Value|=Description
4831 |ftp.USER|string|"ftp"|Anonymous user by default
4832 |ftp.PASSWORD|string|"anonymous@anonymous.org"|This is the default anonymous password, and used when no password is provided in the URL
4833 |ftp.TIMEOUT|number|60|Set the timeout of all I/O operations. Unit: second
4834
4835 |=Function |=Features
4836 |[[ftp.command()>>||anchor="Hftp.command2829"]]|Send ftp command
4837 |[[ftp.genericform()>>||anchor="Hftp.genericform2829"]]|Request parameter conversion, the simple URL request mode convert to a general table parameter form
4838 |[[ftp.put()>>||anchor="Hftp.put2829"]]|Upload data
4839 |[[ftp.get()>>||anchor="Hftp.get2829"]]|Get data
4840
4841 == http module ==
4842
4843 This is submodule of socket. To use the contents of this module, you need to quote the followings.
4844
4845 {{{local http = require("socket.http")
4846 }}}
4847
4848
4849 |=Parameter|=Type|=Value|=Description
4850 |http.TIMEOUT|number|60|Time out unit: second
4851
4852 |=Function |=Features
4853 |[[http.request()>>||anchor="Hhttp.request2829"]]|HTTP request function
4854 |[[http genericform()>>||anchor="Hhttp genericform2829"]]|Convert a simple URL to a generic table parameter
4855
4856 == https module ==
4857
4858 This is submodule of socket. To use the contents of this module, you need to quote the followings.
4859
4860 {{{local https = require("socket.https")
4861 }}}
4862
4863
4864 |=Function |=Features
4865 |[[https.request()>>||anchor="Hhttps.request2829"]]|HTTP request function
4866
4867 == SMTP module ==
4868
4869 This is submodule of socket. To use the contents of this module, you need to quote the followings.
4870
4871 {{{local smtp = require("socket.smtp")
4872 }}}
4873
4874
4875 |=Parameter|=Type|=Value|=Description
4876 |smtp.TIMEOUT|number|60|Connection timeout period
4877 |smtp.SERVER|string|“localhost”|Default server used for sending E-mail
4878 |smtp.DOMAIN|string|“localhost”|Domain used to access the server
4879 |smtp.POST|number|25|Default port for connecting
4880 |smtp.ZONE|string|"-0000"|default time zone
4881
4882 |=Function |=Features
4883 |[[smtp.message()>>||anchor="Hsmtp.message2829"]]|Generate mail format messages
4884 |[[smtp.send()>>||anchor="Hsmtp.send2829"]]|Send email
4885
4886 == Auxiliary Module ==
4887
4888 === LTN12 module ===
4889
4890 This is auxiliary Module of socket. To use the contents of this module, you need to quote the followings.
4891
4892 {{{local LTN12 = require("socket.ltn12")
4893 }}}
4894
4895 **filter**
4896
4897 |=Function |=Features
4898 |[[LTN12.filter.chain()>>||anchor="HLTN12.filter.chain2829"]]|Generates a filter that connects a series of filters
4899 |[[LTN12.filter.cycle()>>||anchor="HLTN12.filter.cycle2829"]]|Generate a high-level filter consisting of low-level filter loops
4900
4901 (((
4902 **pump (Data pump)**
4903 )))
4904
4905 |=Function |=Features
4906 |[[LTN12.pump.all()>>||anchor="HLTN12.pump.all2829"]]|Extract all data from one source to one sink.
4907 |[[LTN12.pump.step()>>||anchor="HLTN12.pump.step2829"]]|Extract a chunk of data from the source to the acceptor
4908
4909 **sink (acceptor)**
4910
4911 |=Function |=Features
4912 |[[LTN12.sink.chain()>>||anchor="HLTN12.sink.chain2829"]]|Create a new sink that transmit data through a filter before sending it to the given sink.
4913 |[[LTN12.sink.error()>>||anchor="HLTN12.sink.error2829"]]|Create and return a new sink that aborts the transmission with an error message
4914 |[[LTN12.sink.file()>>||anchor="HLTN12.sink.file2829"]]|Create a sink that send data to file
4915 |[[LTN12.sink.null()>>||anchor="HLTN12.sink.null2829"]]|Returns a sink that ignores all data received
4916 |[[LTN12.sink.simplify()>>||anchor="HLTN12.sink.simplify2829"]]|Given a selected sink, create and return a simple sink
4917 |[[LTN12.sink.table()>>||anchor="HLTN12.sink.table2829"]]|Create a sink that stores all the blocks in a table.
4918
4919 (((
4920 **source**
4921 )))
4922
4923 |=Function |=Features
4924 |[[LTN12.source.cat()>>||anchor="HLTN12.source.cat2829"]]|Create a new source that generates concatenations of data generated by multiple sources
4925 |[[LTN12.source.chain()>>||anchor="HLTN12.source.chain2829"]]|Create a new source that transmit data through a filter before returning it.
4926 |[[LTN12.source.empty()>>||anchor="HLTN12.source.empty2829"]]|Create and return a new source
4927 |[[LTN12.source.error()>>||anchor="HLTN12.source.error2829"]]|Create and return a source that aborts the transfer and display an error message.
4928 |[[LTN12.source.file()>>||anchor="HLTN12.source.file2829"]]|Create a source to connect file contents.
4929 |[[LTN12.source.simplify()>>||anchor="HLTN12.source.simplify2829"]]|Given a source, create and return a simple source.
4930 |[[LTN12.source.string()>>||anchor="HLTN12.source.string2829"]]|Creates and returns a source that generates string content
4931 |[[LTN12.source.table()>>||anchor="HLTN12.source.table2829"]]|Create and return a table data source
4932
4933 === MIME module ===
4934
4935 This is auxiliary Module of socket. To use the contents of this module, you need to quote the followings.
4936
4937 {{{local mime = require("socket.mime")}}}
4938
4939
4940 |=Function |=Features
4941 |[[mime.decode()>>||anchor="Hmime.decode2829"]]|Return a filter used to decode data from the given transmission content encoding
4942 |[[mime.encode()>>||anchor="Hmime.encode2829"]]|Returns a filter that encodes data based on the given transmission content encoding.
4943 |[[mime.normalize()>>||anchor="Hmime.normalize2829"]]|Return a filter that converts the most common end-of-line tags to a specific given tag
4944 |[[mime.stuff()>>||anchor="Hmime.stuff2829"]]|Create and return a filter that performs SMTP message filling.
4945 |[[mime.wrap()>>||anchor="Hmime.wrap2829"]]|Return a filter that divides data into several lines.
4946 |[[mime.b64()>>||anchor="Hmime.b642829"]]|Create a low-level filter to perform end-of-line tag translation
4947 |[[mime.dot()>>||anchor="Hmime.dot2829"]]|Create a low-level filter that performs SMTP filling and enables the transmission of messages containing the sequence "crlf.crLF".
4948 |[[mime.eol()>>||anchor="Hmime.eol2829"]]|Create a low-level filter to perform end-of-line tag translation
4949 |[[mime.qp()>>||anchor="Hmime.qp2829"]]|Create a low-level filter to perform Quoted-Printable decoding
4950 |[[mime.qpwrp()>>||anchor="Hmime.qpwrp2829"]]|Create a low-level filter that divides Quoted-Printable text into several rows.
4951 |[[mime.unb64()>>||anchor="Hmime.unb642829"]]|Create a low-level filter to perform Base64 decoding
4952 |[[mime.unqp()>>||anchor="Hmime.unqp2829"]]|Create a low-level filter that delete quoted-printable transfer content encoding from data
4953 |[[mime.wrp()>>||anchor="Hmime.wrp2829"]]|Create a low-level filter that uses CRLF tags to split text into several lines.
4954
4955 = Socket basic function =
4956
4957 == [[socket.bind()>>||anchor="HSocketbasicfunction"]] ==
4958
4959 **Prototype:** socket.bind(address, port [, backlog])
4960
4961 **Function: **A shortcut function that encapsulates tcp's bind, accept, and listen calling processes. Creates and returns a TCP server object bound to a local address and port.
4962
4963 **Parameters: **
4964
4965 * address — local address
4966 * port — Port
4967 * backlog — Specifies the number of client connections that can be queued for service. If the queue is full and another client tries to connect, the connection will be rejected. (This parameter is optional. The default value is 32)
4968
4969 **Return: **
4970
4971 * Success: return tcp server object
4972 * Failure: return nil and error
4973
4974 **Example**
4975
4976 {{code language="LUA"}}
4977 local socket = require("socket")
4978
4979 local ip = "192.168.88.246"
4980 local port = 8899
4981
4982 local fd_server = socket.bind(ip,port)
4983 print(fd_server,type(fd_server))
4984 --Output:tcp{server}: 06F5ED60 userdata
4985 {{/code}}
4986
4987 == [[socket.connect4()>>||anchor="HSocketbasicfunction"]] ==
4988
4989 **Prototype: **socket.connect4(address, port [, locaddr] [, locport] )
4990
4991 **Function:** This function is a shortcut that creates and returns a TCP client object connected to the remote (ipv4) address of a given port.
4992
4993 **Parameters: **
4994
4995 * address(string) : Remote server address
4996 * port(number) : Remote server port
4997 * locaddr(string) : Local address
4998 * locport(number) : Local port
4999
5000 **Return: **
5001
5002 * Success: return tcp client object
5003 * Failure: nil, error
5004
5005 **Example**
5006
5007 {{code language="LUA"}}
5008 local socket = require("socket")
5009 local ip = "192.168.88.246"
5010 local port = "9966"
5011 local locIp = "192.168.88.246"
5012 local locPort = "8888"
5013
5014 local fd_client = socket.connect4(ip,port,locIp,locPort)
5015 print(fd_client,type(fd_client))
5016 --Output: tcp{client}: 07F627D8 userdata
5017 {{/code}}
5018
5019 == [[socket.connect6()>>||anchor="HSocketbasicfunction"]] ==
5020
5021 **Prototype: **socket.connect6(address, port [, locaddr] [, locport])
5022
5023 **Function:** This function is a shortcut that creates and returns a TCP client object connected to the remote (ipv6) address of a given port.
5024
5025 **Parameters: **
5026
5027 * address(string) : Remote server address
5028 * port(number) : Remote server port
5029 * locaddr(string) : Local address
5030 * locport(number) : Local port
5031
5032 **Return: **
5033
5034 * Success: return tcp client object
5035 * Failure: nil, error
5036
5037 **Example**
5038
5039 {{code language="LUA"}}
5040 local socket = require("socket")
5041 local ip = "192.168.88.246"
5042 local port = "9966"
5043 local locIp = "192.168.88.246"
5044 local locPort = "8888"
5045
5046 local fd_client = socket.connect6(ip,port,locIp,locPort) -- This parameter is used when the server address is ipv6
5047 print(fd_client,type(fd_client))
5048
5049 --Output (test results in IPv4 addresses): nil nil
5050 {{/code}}
5051
5052 == [[socket.gettime()>>||anchor="HSocketbasicfunction"]] ==
5053
5054 **Prototype: **socket.gettime()
5055
5056 **Function:** Get the system time in seconds, from January 1970.
5057
5058 **Parameters: None**
5059
5060 **Return: **
5061
5062 * systemtime(number): system time: second
5063
5064 **Example**
5065
5066 {{code language="LUA"}}
5067 local socket = require("socket")
5068
5069 local t1 = socket.gettime() -- Get the current time
5070 socket.sleep(5) -- Sleep for 5 seconds
5071 local t2 = socket.gettime() -- Get2 the current time 2
5072
5073 print("t1 =",t1) -- Print time 1
5074 print("t2 =",t2) -- Print time 2
5075 print("t2-t1=",t2-t1) -- Print time difference
5076 --Output:
5077 -- t1 = 1636878024.5057
5078 -- t2 = 1636878029.5201
5079 -- t2-t1= 5.0144500732422
5080 {{/code}}
5081
5082 == [[socket.newtry()>>||anchor="HSocketbasicfunction"]] ==
5083
5084 **Prototype: **socket.newtry(finalizer)
5085
5086 **Function:** Creates and returns a try function that allows the exception to be cleaned up before it is thrown.
5087
5088 **Parameters: **
5089
5090 * finalizer(function): Finalizer is a function that will be called before newtry throws an exception.
5091
5092 **Return: **
5093
5094 * Returns a newtry function that throws an exception block
5095
5096 **Note:**
5097
5098 * This function is usually used with the socket.protect() function; Try throws an exception and Protect catches it.
5099
5100 **Example**
5101
5102 {{code language="LUA"}}
5103 local socket = require("socket")
5104
5105 foo = socket.protect(function()
5106 print("--------------")
5107 local c = socket.try(socket.connect("192.168.88.241", 9090))
5108 print(c,type(c))
5109 -- create a try function that closes 'c' on error
5110 local try = socket.newtry(function() c:close() end)-- Call the TCP object closure function if an exception occurs
5111 -- do everything reassured c will be closed
5112 try(c:send("hello there?\r\n")) -- formal call c of try:send()
5113 local answer = try(c:receive()) -- formal call c of try:receive()
5114
5115 print(answer)
5116 try(c:send("good bye\r\n"))
5117 c:close()formal call c of try
5118 end)
5119 foo()
5120 -- Analysis:Functions or more important blocks of code that may have exceptions are called in the form of try, and protection functions are called before exceptions occur.
5121 Prevent major problems caused by exceptions.
5122 {{/code}}
5123
5124 == [[socket.protect()>>||anchor="HSocketbasicfunction"]] ==
5125
5126 **Prototype: **socket.protect(func)
5127
5128 **Function:** Convert the throw exception function to safety function. This function only catches exceptions thrown by the try and newtry functions, and would not catch normal Lua errors.
5129
5130 **Parameters: **
5131
5132 * func(function): Is a function that calls try (or Assert or error) to throw an exception.
5133
5134 **Return: **
5135
5136 * Returns a equivalent func function that no longer throws an exception when a try call fails but returns nil and an error.
5137
5138 **Example**
5139
5140 {{code language="LUA"}}
5141 local socket = require("socket")
5142
5143 foo = socket.protect(function()
5144 print("--------------")
5145 local c = socket.try(socket.connect("192.168.88.241", 9090))
5146 print(c,type(c))
5147 -- create a try function that closes 'c' on error
5148 local try = socket.newtry(function() c:close() end)-- Call the TCP object closure function if an exception occurs
5149 -- do everything reassured c will be closed
5150 try(c:send("hello there?\r\n")) -- formal call c of try:send()
5151 local answer = try(c:receive()) -- formal call c of try:receive()
5152
5153 print(answer)
5154 try(c:send("good bye\r\n"))
5155 c:close()
5156 end)
5157 foo()
5158 {{/code}}
5159
5160 == [[socket.select()>>||anchor="HSocketbasicfunction"]] ==
5161
5162 **Prototype: **socket.select(recvt, sendt [, timeout])
5163
5164 **Function:** Wait for multiple sockets to change status.
5165
5166 **Parameters: **
5167
5168 * recvt(arrary):An array with sockets that tests readable characters.
5169 * send(arrary):sendt array. Monitor the sockets of sendt array to see if they can be written immediately.
5170 * timeout(bunber):Timeout period,nil or a negative number is an indefinite timeout.
5171
5172 **Return: **
5173
5174 * Returns a equivalent func function that no longer throws an exception when a try call fails but returns nil and an error.
5175
5176 **Note:**
5177
5178 * Select could monitor a limited number of sockets, as defined by the constant socket._setsize. By default, this number could be as high as 1024 or as low as 64, depending on the system. You could usually change it when compiling. Calling select with a large number of sockets, an error would occur.
5179 * Call select using the server socket in the receive parameter before calling accept does not guarantee that accept will return immediately. Using the settimeout method or accept may cause block forever.
5180 * If a closed socket is passed to select, it will be ignored.
5181 * Use select with non-socket objects: Any objects that implement getfd and dirty could be used with select. This allows objects from other libraries to be used in the loops of socket.select-driven.
5182
5183 **Example**
5184
5185 {{code language="LUA"}}
5186 -- Implement timeout waits
5187 function timeoutWait()
5188 local tabFd = {}
5189 table.insert(tabFd,fdServer) -- Add the server socket to the Select socket monitoring table
5190 for i,v in pairs(tabClient) do -- Loop traversal client
5191 table.insert(tabFd,tabClient[i].fd) -- Add the client socket to the Select socket monitoring table
5192 end
5193 socket.select(tabFd) -- select monitor socket.If the socket does not receive a connection, it remains blocked
5194 end
5195 {{/code}}
5196
5197 == [[socket.sink()>>||anchor="HSocketbasicfunction"]] ==
5198
5199 **Prototype: **socket.sink(mode, socket)
5200
5201 **Function:** Create an LTN12 sink from a stream socket object.
5202
5203 **Parameters: **
5204
5205 * mode —— Receiver mode
5206 * socket —— A stream socket object used to receive data
5207
5208 **Return: **
5209
5210 * Return an LTN12 receiver
5211
5212 **Note:**
5213
5214 LTN12 receiver mode:
5215
5216 * "http-chunked": After using chunked transmission encoding, send data through socket, and close socket when completed.
5217 * "close-when-done": Send all received data through socket, and then close the socket.
5218 * "keep-open": Send all received data through socket, Leave it open when it is done.
5219
5220 == [[socket.sleep()>>||anchor="HSocketbasicfunction"]] ==
5221
5222 **Prototype: **sleep(s)
5223
5224 **Function:** Sleep s seconds
5225
5226 **Parameters: **
5227
5228 * n(number):The number of seconds to sleep
5229
5230 **Return: None**
5231
5232 **Example**
5233
5234 {{code language="LUA"}}
5235 local socket = require("socket") print("start . . .")
5236 local time1 = socket.gettime() socket.sleep(5)
5237 -- Print the difference between the two acquisition times after sleeping for 5 seconds
5238 print("socket time=",socket.gettime() - time1)
5239 --Output:
5240 -- start . . . -- socket time= 5.0082302093506
5241 {{/code}}
5242
5243 == [[socket.source()>>||anchor="HSocketbasicfunction"]] ==
5244
5245 **Prototype: **socket.source(mode, socket [, length])
5246
5247 **Function:** Create LTN12 source from stream socket object.
5248
5249 **Parameters: **
5250
5251 * mode(string):The mode of source
5252 * socket(userdata):A stream socket object used to receive data.
5253 * ength(number):Length
5254
5255 **Return: **
5256
5257 * Return a created LTN12 source
5258
5259 **Note:**
5260
5261 LTN12 source mode. The following options are available.
5262
5263 * "http-chunked": Receives data from the socket, and remove the chunked transmission encoding before returning data.
5264 * "by-length": Receives a fixed number of bytes from the socket. This mode requires additional parameter lengths.
5265 * "until-closed": Receives data from the socket until the other end closes the connection.
5266
5267 == [[socket.tcp()>>||anchor="HSocketbasicfunction"]] ==
5268
5269 **Prototype: **socket.tcp()、socket.tcp4()、socket.tcp6()
5270
5271 **Function:** Create and return a Tcp main object.
5272
5273 **Parameters: **None
5274
5275 **Return: **
5276
5277 * Success: Return a tcp object
5278 * Failure: nil, error
5279
5280 **Note:**
5281
5282 * The difference between socket.tcp4() and socket.tcp6() is whether the selected IP is ipv4 or ipv6.
5283 * Socket. TCP divides objects into three types: main object, client object and server object. Socket.tcp creates the main object. The main object could be converted to a server object through the listen method (after calling bind), or it could be converted to a clientobject through the connect method. The only method supported by the main object is the close method.
5284 * To choose IPv4 or IPv6 during the calling of bind or connection, it isdepending on the address family obtained from the parser.
5285 * If the internal socket object is invalid before choosing IPv4 or IPv6, setoption will fail.
5286
5287 **Example:**
5288
5289 {{code language="LUA"}}
5290 local socket = require("socket")
5291 local tcp = socket.tcp()
5292 print("tcp=",tcp,type(tcp)) -- Obtain TCP objects. For details about how to use TCP objects, see TCP Module
5293 --------------------------------------------
5294 --Output:
5295 -- tcp= tcp{master}: 0B3074F8 userdata
5296 {{/code}}
5297
5298 == [[socket.udp()>>||anchor="HSocketbasicfunction"]] ==
5299
5300 **Prototype: **socket.udp()、socket.udp4()、socket.udp6()
5301
5302 **Function:** Create an empty (disconnected) udp object.
5303
5304 **Parameters: **None
5305
5306 **Return: **
5307
5308 * Success: Return a new disconnected udp object.
5309 * Failure: nil, error
5310
5311 **Note:**
5312
5313 * The difference between socket.tcp4() and socket.tcp6() is whether the selected IP is ipv4 or ipv6.
5314 * To choose IPv4 or IPv6 during the calling of udp:sendto, udp:setpeeername or udp:sockname, it is depending on the address family obtained from the parser.
5315 * If the internal socket object is invalid before choosing IPv4 or IPv6, udp: setoption will fail.
5316
5317 **Example:**
5318
5319 {{code language="LUA"}}
5320 local socket = require("socket")
5321 local udp = socket.udp()
5322 print("udp=",udp,type(udp)) -- Obtain udp objects. For details about how to use udp objects, see udp Module
5323 --------------------------------------------
5324 --Ouptput
5325 -- udp= udp{unconnected}: 0B808B98 userdata
5326 {{/code}}
5327
5328 = dns module =
5329
5330 == [[dns.toip()>>||anchor="Hdnsmodule"]] ==
5331
5332 **Prototype: **dns.toip(address)
5333
5334 **Function:** Convert from hostname to IPv4 address
5335
5336 **Parameters: **
5337
5338 * address(string): Address. It could be an IP name or a host name.
5339
5340 **Return: **
5341
5342 Success: .
5343
5344 * address(string): IP address
5345 * info(table): address information table
5346
5347 Failure: return nil and error
5348
5349 **Example:**
5350
5351 {{code language="LUA"}}
5352 local socket = require("socket")
5353 local dns = socket.dns
5354 local hostname = dns.gethostname()
5355 local ip,msg = dns.toip(hostname)
5356 if ip then
5357 print("ip=",ip)
5358 else
5359 print(msg)
5360 end
5361
5362
5363 --Output
5364 -- ip= 192.168.33.149
5365 {{/code}}
5366
5367 == [[dns.getaddrinfo()>>||anchor="Hdnsmodule"]] ==
5368
5369 **Prototype: **dns.getaddrinfo(address)
5370
5371 **Function:** Convert from hostname to address
5372
5373 **Parameters: **
5374
5375 * address(string): Address. It could be an IP name or a host name.
5376
5377 **Return: **
5378
5379 * Success: info(table): address information table
5380 * Failure: return nil and error
5381
5382 **Example:**
5383
5384 {{code language="LUA"}}
5385 local socket = require("socket")
5386 local dns = socket.dns
5387 local host = dns.gethostname()
5388 local addrinfo = dns.getaddrinfo(host)
5389 for i,v in pairs(addrinfo) do
5390 print(i,v,"--------------")
5391 for i2,v2 in pairs(v) do
5392 print(i2,v2)
5393 end
5394 end
5395
5396 --Output:
5397 -- 1 table: 0AB71660 --------------
5398 -- addr fe80::9930:10db:5b7f:1249%4
5399 -- family inet6
5400 -- 2 table: 0AB715C0 --------------
5401 -- addr 192.168.33.149
5402 -- family inet
5403 {{/code}}
5404
5405 == [[dns.tohostname()>>||anchor="Hdnsmodule"]] ==
5406
5407 **Prototype: **dns.tohostname(address)
5408
5409 **Function:** Convert from IP4v address to hostname
5410
5411 **Parameters: **
5412
5413 * address(string): Address. It could be an IP name or a host name.
5414
5415 **Return: **
5416
5417 * Success: Return a host name string and an address information table
5418 * Failure: return nil and error
5419
5420 **Example:**
5421
5422 {{code language="LUA"}}
5423 local host = dns.gethostname()
5424 local ip = dns.toip(host)
5425 local hostname,msg = dns.tohostname(ip)
5426 if hostname then
5427 print("hostname=",hostname)
5428 else
5429 print(msg)
5430 end
5431
5432 --Output:
5433 -- hostname= DESKTOP-LB0DAGV
5434 {{/code}}
5435
5436 == [[dns.getnameinfo()>>||anchor="Hdnsmodule"]] ==
5437
5438 **Prototype: **dns.getnameinfo(address, port)
5439
5440 **Function:** Given address (host name or IP address) and port, and return all the information provided by dns parser.
5441
5442 **Parameters: **
5443
5444 * address(string): Address. It could be an IP name or a host name.
5445 * port(number): Service port number
5446
5447 **Return: **
5448
5449 * Success: Return an address information table and port informantion string
5450 * Failure: return nil and error
5451
5452 **Example:**
5453
5454 {{code language="LUA"}}
5455 local socket = require("socket")
5456 local json = require("json")
5457
5458 local host = "DESKTOP-P46LTTK"
5459 local port = 21
5460 local hostinfo,servinfo=socket.dns.getnameinfo(host, port)
5461 print("hostinfo =",json.encode(hostinfo))
5462 print("portinfo =",servinfo)
5463
5464 --Output:
5465 -- hostinfo = ["DESKTOP-P46LTTK","DESKTOP-P46LTTK"]
5466 -- portinfo = ftp
5467 {{/code}}
5468
5469 == [[dns.gethostname()>>||anchor="Hdnsmodule"]] ==
5470
5471 **Prototype: **dns.gethostname()
5472
5473 **Function:** Return the standard hostname of the machine as a string
5474
5475 **Parameters: **None
5476
5477 **Return: **
5478
5479 * Success: Return the standard hostname of the machine as a string
5480 * Failure: return nil and error
5481
5482 **Example:**
5483
5484 {{code language="LUA"}}
5485 local socket = require("socket")
5486 print("host name =",socket.dns.gethostname())
5487 --Output:
5488 -- host name = DESKTOP-P46LTTK
5489 {{/code}}
5490
5491 = TCP module =
5492
5493 == [[tcp:bind()>>||anchor="HTCPmodule"]] ==
5494
5495 **Prototype: **master:bind(address, port)
5496
5497 **Function: **Bind the object to the address and port of local host.
5498
5499 **Parameters: **
5500
5501 * address(string):IP address or host name
5502 * port(number):port number
5503
5504 **Return: **
5505
5506 * Success: Return 1.
5507 * Failure: return nil and error.
5508
5509 **Note:**
5510
5511 * If the address is "*", the system binds all local interfaces with the INADDR_ANYc constant or IN6ADDR_ANY_INIT.
5512 * If the port is 0, the system automatically selects a temporary port.
5513 * The socket.bind function is a shortcut to create a server socket.
5514
5515 == [[tcp:connect()>>||anchor="HTCPmodule"]] ==
5516
5517 **Prototype: **master:connect(address, port)
5518
5519 **Function: **Attempt to connect the primary object to the remote host.
5520
5521 **Parameters: **
5522
5523 * address(string):IP address or host name
5524 * port(number):port number
5525
5526 **Return: **
5527
5528 * Success: Return 1.
5529 * Failure: return nil and error.
5530
5531 **Note:**
5532
5533 * Convert main object to client object after using the connect function.
5534 * The socket.connect function is available and is a shortcut to create a client socket.
5535 * Starting with LuaSocket 2.0, the settimeout method woudl affect the action of connect, causing it to return an error in the case of a timeout. If this happens, you could still use the socket in the Sendt table to call socket.select. AFfter the connection, the socket will be writable.
5536 * Starting with LuaSocket 3.0, hostname resolution depends on whether a socket is created by socket.tcp, socket.tcp4, or socket.tcp6. Try the addresses from the appropriate series (or both) according to the order returned by the parser until the first success or the last failure. If timeout is set to zero, only the first address is tried.
5537
5538 == [[tcp:listen()>>||anchor="HTCPmodule"]] ==
5539
5540 **Prototype: **master:listen(backlog)
5541
5542 **Function: **Listening socket, convert the specified master to server object.
5543
5544 **Parameters: **
5545
5546 * backlog(number):Specify the number of client connections that can be queued for service. If the queue is full and another client tries to connect, the connection will be rejected.
5547
5548 **Return: **
5549
5550 * Success: Return 1.
5551 * Failure: return nil and error.
5552
5553 == [[tcp:accept()>>||anchor="HTCPmodule"]] ==
5554
5555 **Prototype: **server:accept( )
5556
5557 **Function: **Wait for a remote connection and return the server object representing the connection.
5558
5559 **Parameters: **None
5560
5561 **Return: **
5562
5563 * Success: Return a client object.
5564 * Failure: return nil and error. (If the timeout condition is met, return nil and error string "timeout")
5565
5566 **Note:**
5567
5568 * Call select using the server socket in the receive parameter before calling accept does not guarantee that accept will return immediately. Using the settimeout method or accept may cause block forever until another client appears.
5569
5570 == [[tcp:send()>>||anchor="HTCPmodule"]] ==
5571
5572 **Prototype: **client:send(data [, i [, j]])
5573
5574 **Function: **Send data.
5575
5576 **Parameters: **
5577
5578 * data(string): The string to be sent
5579 * i,j(number): The parameter fucntion is like string.sub. You could select a substring to send.
5580
5581 **Return: **
5582
5583 * Success: Return the index of the last byte in the sent [i,j]. If i is 1 or does not exist, then it is the actual total
5584 * Failure: return nil and error.
5585
5586 **Note:**
5587
5588 * The output is not buffered. For small strings, it is better to connect them in Lua and send the result in one call rather than calling the method multiple times.
5589
5590 == [[tcp:receive()>>||anchor="HTCPmodule"]] ==
5591
5592 **Prototype: **client:receive([pattern [, prefix]])
5593
5594 **Function: **Read data from client object according to the specified read mode. The mode follows the Lua file I/O format, and the performance differences between all modes could be ignored.
5595
5596 **Parameters: **
5597
5598 * pattern(string): 
5599 ** '*a': Read from socket until the connection is closed. End-of-line translation is not performed.
5600 ** '*l': Read a line of text from socket. The line is ends with the LF character (ASCII 10), and  optionally preceded by the CR character (ASCII 13). CR and LF characters are not included in the returned line. In fact, the mode ignores all CR characters. This is the default mode.
5601 ** number: Read the specified number of bytes from socket.
5602 * prefix(string): Prefix is an optional string, and connect to the beginning of any received data before returning.
5603
5604 **Return: **
5605
5606 * Success: Return the received data.
5607 * Failure: return nil and error.
5608
5609 == [[tcp:close()>>||anchor="HTCPmodule"]] ==
5610
5611 **Prototype: **
5612
5613 * master:close()
5614 * clien:close()
5615 * server:close()
5616
5617 **Function: **Close a TCP object
5618
5619 **Parameters: **None
5620
5621 **Return: **None
5622
5623 **Note:**
5624
5625 * It is important to close all the sockets when not needed. Because in many systems, every socket uses a file descriptor. This is a limited system resource. However, the garbage collection object is automatically closed before being destroyed.
5626
5627 == [[tcp:getoption()>>||anchor="HTCPmodule"]] ==
5628
5629 **Prototype: **
5630
5631 * client:getoption(option)
5632 * server:getoption(option)
5633
5634 **Function: **Get the options of TCP object. Option is a string with option name.
5635
5636 **Parameters: **
5637
5638 * option(string): Option is a string with option name. ("keepalive", "linger", "reuseaddr", "tcp-nodelay")
5639
5640 **Return: **
5641
5642 * Success: Return option value.
5643 * Failure: return nil and error.
5644
5645 == [[tcp:getpeername()>>||anchor="HTCPmodule"]] ==
5646
5647 **Prototype: **client:getpeername()
5648
5649 **Function: **Return remote information of the connected client object.
5650
5651 **Parameters: **None
5652
5653 **Return: **
5654
5655 * return a string, including the IP address of the peer, the port number used by the peer to connect and a string with series ("inet" or "inet6"). If an error occurs, return nil.
5656
5657 == [[tcp:getsockname()>>||anchor="HTCPmodule"]] ==
5658
5659 **Prototype: **
5660
5661 * master:getsockname()
5662 * client:getsockname()
5663 * server:getsockname()
5664
5665 **Function: **Return information about the local address associated with the object.
5666
5667 **Parameters: **None
5668
5669 **Return: **
5670
5671 * Success: Return a string with local IP address, a number with local port and a string with a series "inet" or "inet6".
5672 * Failure: return nil and error.
5673
5674 == [[tcp:getstats()>>||anchor="HTCPmodule"]] ==
5675
5676 **Prototype: **
5677
5678 * master:getstats()
5679 * client:getstats()
5680 * server:getstats()
5681
5682 **Function: **Return accounting information about socket. It could be used to limit bandwidth.
5683
5684 **Parameters: **None
5685
5686 **Return: **
5687
5688 * Success: Return the number of the bytes received, he number of the bytes sent and the time of socket object. (Unit: second)
5689 * Failure: return nil and error.
5690
5691 == [[tcp:gettimeout()>>||anchor="HTCPmodule"]] ==
5692
5693 **Prototype: **
5694
5695 * master:settimeout*value [, mode])
5696 * client:settimeout(value [, mode])server:settimeout(value [, mode])
5697
5698 **Function: **Change the timeout value of tcp object.
5699
5700 **Parameters: **
5701
5702 * value(number): The amount of time to wait is specified as the value parameter in seconds. nil and negative value allow operations to block indefinitely.
5703 * mod(string):timeout mode
5704
5705 **Return: **None
5706
5707 **Note:**
5708
5709 1. By default, all the I/O operations are blocked. That is, any call to the method send, receive and accept will indefinitely block until the operation is complete. The method settimeout define a limit on the amount of time that n I/O method can block. When timeout is set and after a specified amount of time, the affected method aborts and fails with an error code.
5710 1. There are two timeout modes:
5711
5712 * 'B': block timeout. It specifies the maximum time limit that the operating system can block LuaSocket while waiting for any single I/O operation to complete. This is the default mode.
5713 * 't' : total timeout. It specifies the maximum time limit that LuaSocket can block Lua scripts before the call returns
5714
5715 (% start="3" %)
5716 1. Although the timeout value in LuaSocket has millisecond precision, large blocks can cause I/O functions not to respect timeout values due to the time the library takes to transfer blocks to and from the OS and to and from the Lua interpreter. Also, function that accept host names and perform automatic name resolution might be blocked by the resolver for longer than the specified timeout value.
5717
5718 == [[tcp:setoption()>>||anchor="HTCPmodule"]] ==
5719
5720 **Prototype: **
5721
5722 * client:setoption(option [, value])
5723 * server:setoption(option [, value])
5724
5725 **Function: **Set the option of TCP object. Only low-level or time-critical applications require options. If you are sure that you need it, you should only modify one option.
5726
5727 **Parameters: **
5728
5729 * option(string): option name
5730 * valu(number): option value
5731
5732 **Return: **
5733
5734 * Success: Return 1.
5735 * Failure: return nil and error.
5736
5737 **Note:**
5738
5739 * 'keepalive': Set this option to true to transmit messages regularly on the connected socket. If the connection fails to respond to these messages, then it is considered disconnected and the process using the socket is notified.
5740 * 'linbger': Controls the action taken when unsent data is queued on the socket and the action taken when it is closed. The value is a table of numeric entries with a Boolean entry "on" and a time interval "timeout" (in seconds). If the "on" field is set to true, the system blocks the process on a shutdown attempt until it can transfer data or until the "timeout" passes. If "on" is false and a shutdown is issued, the system will process it in a way that allows the process to continue as soon as possible. It is not recommended to set it to anything value other than 0.
5741 Shut down. I do not recommend that you set it to anything other than zero
5742 * 'reuseaddr': Set this option indicates that the rule used to validate the address provided in the binding call should allow the reuse of the local address.
5743 * 'tcp-nodelay': Set this option to true would disable the Nagle algorithm for connection.
5744 * 'tcp-keepidle': Only applicable to the value of TCP_KEEPIDLE Linux. (Unit: second)
5745 * 'tcp-keepcnt': Only applicable to the value of TCP_KEEPCNT Linux.
5746 * 'tcp-keepintv1': Only applicable to the value of TCP_KEEPINTVL Linux.
5747 * 'ipv6-v6only': Set this option to true would restrict the inET6 socket to only sending and receiving IPv6 packets.
5748
5749 == [[tcp:setstats()>>||anchor="HTCPmodule"]] ==
5750
5751 **Prototype: **
5752
5753 * master:setstats(received, sent, age)
5754 * client:setstats(received, sent, age)
5755 * server:setstats(received, sent, age)
5756
5757 **Function: **Reset accounting information on sockets. It is useful for bandwidth limiting.
5758
5759 **Parameters: **
5760
5761 * received: Received is a number with the number of new received bytes
5762 * shend: Sent is a number with the number of new Sent bytes.
5763 * age: Age is the new Age in seconds.
5764
5765 **Return: **
5766
5767 * Success: Return 1.
5768 * Failure: return nil
5769
5770 == [[tcp:settimeout()>>||anchor="HTCPmodule"]] ==
5771
5772 **Prototype:**
5773
5774 * master:settimeout*value [, mode])
5775 * client:settimeout(value [, mode])server:settimeout(value [, mode])
5776
5777 **Function: **Change the timeout value of tcp object.
5778
5779 **Parameters: **
5780
5781 * value(number):The amount of time to wait. nil and negative value are indefinite block. (Unit: second)
5782 * mod(string):timeout mode
5783
5784 **Return: **None
5785
5786 **Note:**
5787
5788 1. By default, all the I/O operations are blocked. That is, any call to the method send, receive and accept will indefinitely block until the operation is complete. The method settimeout define a limit on the amount of time that n I/O method can block. When timeout is set and after a specified amount of time, the affected method aborts and fails with an error code.
5789 1. There are two timeout modes:
5790
5791 * 'B': block timeout. It specifies the maximum time limit that the operating system can block LuaSocket while waiting for any single I/O operation to complete. This is the default mode.
5792 * 't' : total timeout. It specifies the maximum time limit that LuaSocket can block Lua scripts before the call returns
5793
5794 1. Although the timeout value in LuaSocket has millisecond precision
5795
5796 == [[tcp:shutdown()>>||anchor="HTCPmodule"]] ==
5797
5798 **Prototype: **client:shutdown(mode)
5799
5800 **Function: **Disable some full-duplex connections
5801
5802 **Parameters: **
5803
5804 * mode: Close connection mode
5805 ** "both": Close send and receive connection (default mode)
5806 ** "send": Close send connection
5807 ** "receive": Close receive connection
5808
5809 **Return: **
5810
5811 * Success: Return 1.
5812 * Failure: Return nil and error.
5813
5814 == [[tcp:getfamily()>>||anchor="HTCPmodule"]] ==
5815
5816 **Prototype: **
5817
5818 * master:getfamily()
5819 * client:getfamily()
5820 * server:getfamily()
5821
5822 **Function: **Obtain tcp protocol family
5823
5824 **Parameters: **None
5825
5826 **Return: **
5827
5828 * Return a protocol family string
5829
5830 == [[tcp:setpeername()>>||anchor="HTCPmodule"]] ==
5831
5832 **Prototype: **client:setpeername(address, port)
5833
5834 **Function: **Change the host object to connect to a remote host.
5835
5836 **Parameters: **
5837
5838 * address(string): IP address or host name
5839 * port(number): port number
5840
5841 **Return: **
5842
5843 * Success: Return 1.
5844 * Failure: Return nil and error.
5845
5846 == [[tcp:setsockname>>||anchor="HTCPmodule"]] ==
5847
5848 **Prototype: **server:setsockname(address, port)
5849
5850 **Function: **Change the address and port number of the objectified binding.
5851
5852 **Parameters: **
5853
5854 * address(string): IP address or host name
5855 * port(number): port number
5856
5857 **Return: **
5858
5859 * Success: Return 1.
5860 * Failure: Return nil and error.
5861
5862 = UDP module =
5863
5864 == [[udp:send()>>||anchor="HUDPmodule"]] ==
5865
5866 **Prototype: **connected:send(datagram)
5867
5868 **Function: **Sends datagrams to connected udp objects.
5869
5870 **Parameters: **
5871
5872 * datagram(string): Datagram is a string with the datagram contents
5873
5874 **Return: **
5875
5876 * Success: Returns the number of bytes sent.
5877 * Failure: return nil and error.
5878
5879 **Note:**
5880
5881 * (((
5882 The maximum datagram size for UDP is 64K minus IP layer overhead. However datagrams larger than the link layer packet size will be fragmented, which may deteriorate performance and reliability.
5883 )))
5884 * (((
5885 In UDP, the send method never blocks and the only way it can fail is if the underlying transport layer refuses to send a message to the specified address (i.e. no interface accepts the address).
5886 )))
5887 * (((
5888 If the destination does not exist, the packet is discarded and no error is returned.
5889 )))
5890
5891 == [[udp:sendto()>>||anchor="HUDPmodule"]] ==
5892
5893 **Prototype: **unconnected:sendto(datagram, ip, port)
5894
5895 **Function: **Sends datagrams to connected udp objects.
5896
5897 **Parameters: **
5898
5899 * datagram(string): Datagram is a string with the datagram contents
5900 * ip(string): Destination IP.  Host names are not allowed due to performance.
5901 * port(number): Destination port
5902
5903 **Return: **
5904
5905 * Success: Returns 1.
5906 * Failure: return nil and error.
5907
5908 **Note:**
5909
5910 * (((
5911 The maximum datagram size for UDP is 64K minus IP layer overhead. However datagrams larger than the link layer packet size will be fragmented, which may deteriorate performance and reliability.
5912 )))
5913 * (((
5914 In UDP, the send method never blocks and the only way it can fail is if the underlying transport layer refuses to send a message to the specified address (i.e. no interface accepts the address).
5915 )))
5916
5917 == [[udp:receive()>>||anchor="HUDPmodule"]] ==
5918
5919 **Prototype:**
5920
5921 * connected:receive([size])
5922 * unconnected:receive([size])
5923
5924 **Function: **Receives a datagram from the UDP object. If the UDP object is connected, only datagrams coming from the peer are accepted. Otherwise, the returned datagram can come from any host.
5925
5926 **Parameters: **
5927
5928 * size(number): Specifies the maximum size of the datagram to be retrieved
5929
5930 **Return: **
5931
5932 * Success: Returns the datagram received.
5933 * Failure: return nil and error.
5934
5935 **Note:**
5936
5937 * (((
5938 If there are more than size bytes available in the datagram, the excess bytes are discarded. If there are less then size bytes available in the current datagram, the available bytes are returned. If size is omitted, the compile-time constant ##socket._DATAGRAMSIZE## is used (it defaults to 8192 bytes). Larger sizes will cause a temporary buffer to be allocated for the operation.
5939 )))
5940
5941 == [[udp:receivefrom()>>||anchor="HUDPmodule"]] ==
5942
5943 **Prototype:** unconnected:receivefrom([size])
5944
5945 **Function: **It works exactly as the receive method, except it returns the IP address and port as extra return values, and is therefore slightly less efficient.
5946
5947 **Parameters: **
5948
5949 * size(number): Specifies the maximum size of the datagram to be retrieved
5950
5951 **Return: **
5952
5953 * dgram(string):received data
5954 * adderss(string):IP address
5955 * port(number):Port
5956
5957 == [[udp:close()>>||anchor="HUDPmodule"]] ==
5958
5959 **Prototype: **
5960
5961 * connected:close()
5962 * unconnected:close()
5963
5964 **Function: **Closes a UDP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the ##close## method) are allowed on a closed socket.
5965
5966 **Parameters: **None
5967
5968 **Return: **None
5969
5970 **Note:**
5971
5972 * (((
5973 It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.
5974 )))
5975
5976 == [[udp:gettimeout()>>||anchor="HUDPmodule"]] ==
5977
5978 **Prototype: **
5979
5980 * connected:settimeout( )
5981 * unconnected:settimeout( )
5982
5983 **Function: **Obtains the current timeout value.
5984
5985 **Parameters: **None
5986
5987 **Return: **
5988
5989 * Returns the current timeout value.
5990
5991 == [[udp:settimeout()>>||anchor="HUDPmodule"]] ==
5992
5993 **Prototype: **
5994
5995 * connected:settimeout(value)
5996 * unconnected:settimeout(value)
5997
5998 **Function: **Change the timeout value of UDP object.
5999
6000 **Parameters:**
6001
6002 * value(number): The amount of time to wait is specified as the value parameter in seconds. nil and negative value allow operations to block indefinitely.
6003
6004 **Return: **
6005
6006 * Returns 1
6007
6008 **Note:**
6009
6010 * (((
6011 By default, the operations of receive and receiveform are blocked.
6012 )))
6013 * (((
6014 In UDP, the send and sendto methods never block (the datagram is just passed to the OS and the call returns immediately). Therefore, the settimeout method has no effect on them.
6015 )))
6016
6017 == [[udp:getoption()>>||anchor="HUDPmodule"]] ==
6018
6019 **Prototype: **
6020
6021 * connected:getoption()
6022 * unconnected:getoption (optionName)
6023
6024 **Function: **Gets an option value from the UDP object
6025
6026 **Parameters:**
6027
6028 * optionName: option name.
6029
6030 **Return: **
6031
6032 * Success: Returns the option value.
6033 * Failure: Returns nil and error.
6034
6035 **Note:**
6036
6037 Option names are as follows:
6038
6039 * 'dontroute': Indicates that outgoing messages should bypass standard routing facilities.
6040 * 'broadcast': Requests permission to send broadcast datagrams on sockets.
6041 * 'reuseaddr': Rules that represent the validation of addresses provided in a bind() call should allow the reuse of local addresses.
6042 * 'reuseport': If multiple processes have set 'reusePort' before binding the port, they are allowed to double bind completely.
6043 * 'ip-multicast-loop': Specifies whether a copy of an outgoing multicast datagram is sent to the sending host as long as it is a member of a multicast group.
6044 * 'ipv6-v6only': Specifies whether inet6 sockets are restricted to sending and receiving only IPv6 packets.
6045 * 'ip-multicast-if': Sets the interface for sending multicast datagrams.
6046 * 'ip-multicast-ttl': Sets the lifetime in the IP header for outgoing multicast datagrams.
6047 * 'ip-add-membership': Added to the specified multicast group.
6048 * 'ip-drop-membership': Leaves the specified multicast group.
6049
6050 == [[udp:getpeername()>>||anchor="HUDPmodule"]] ==
6051
6052 **Prototype: **
6053
6054 * connected:getpeername()
6055 * unconnected:getpeername()
6056
6057 **Function: **Retrieves information about the peer associated with a connected UDP object.
6058
6059 **Parameters: **None
6060
6061 **Return: **
6062
6063 * Success: Returns a string with the IP address of the peer, the port number that peer is using for the connection, and a string with the family ("inet4" or "inet6").
6064 * Failure: return nil and error.
6065
6066 **Note:**
6067
6068 * It makes no sense to call this method on unconnected objects.
6069
6070 == [[udp:getsockname()>>||anchor="HUDPmodule"]] ==
6071
6072 **Prototype: **
6073
6074 * connected:getsockname()
6075 * unconnected:getsockname()
6076
6077 **Function: **Returns the local address information associated to the object.
6078
6079 **Parameters: **None
6080
6081 **Return: **
6082
6083 * Success: Returns a string with local IP address, a number with the local port, and a string with the family ("inet4" or "inet6").
6084 * Failure: return nil and error.
6085
6086 **Note:**
6087
6088 * UDP sockets are not bound to any address until the setsockname or the sendto method is called for the first time (in which case it is bound to an ephemeral port and the wild-card address).
6089
6090 == [[udp:setoption()>>||anchor="HUDPmodule"]] ==
6091
6092 **Prototype: **
6093
6094 * connected:setoption(option [, value])
6095 * unconnected:setoption(option [, value])
6096
6097 **Function: **Sets options for the UDP object.
6098
6099 **Parameters: **
6100
6101 * option(string): Option name
6102 * value: Option value and it depends on the option being set.
6103
6104 **Return: **
6105
6106 * Success: Returns 1
6107 * Failure: return nil and error.
6108
6109 **Note:**
6110
6111 Options are only needed by low-level or time-critical applications. You should only modify an option if you are sure you need it.
6112
6113 Option name are as follows:
6114
6115 * 'dontroute': Indicates that outgoing messages should bypass the standard routing facilities. Receives a boolean value.
6116 * 'broadcast': Requests permission to send broadcast datagrams on the socket. Receives a boolean value.
6117 * 'reuseaddr': Indicates that the rules used in validating addresses supplied in a ##bind()## call should allow reuse of local addresses. Receives a boolean value.
6118 * 'reuseport': Allows completely duplicate bindings by multiple processes if they all set '##reuseport##' before binding the port. Receives a boolean value.
6119 * 'ip-multicast-loop': Specifies whether or not a copy of an outgoing multicast datagram is delivered to the sending host as long as it is a member of the multicast group. Receives a boolean value.
6120 * 'ipv6-v6only': Specifies whether to restrict ##inet6## sockets to sending and receiving only IPv6 packets. Receive a boolean value.
6121 * 'ip-multicast-if': Sets the interface over which outgoing multicast datagrams are sent. Receives an IP address.
6122 * 'ip-multicast-ttl': Sets the Time To Live in the IP header for outgoing multicast datagrams. Receives a number.
6123 * 'ip-add-membership': Joins the multicast group specified. Receives a table with fields multiaddr and interface, each containing an IP address.
6124 * 'ip-drop-membership': Leaves the multicast group specified. Receives a table with fields multiaddr and interface, each containing an IP address.
6125
6126 == [[udp:setpeername()>>||anchor="HUDPmodule"]] ==
6127
6128 **Prototype: **
6129
6130 * connected:setpeername('*')
6131 * unconnected:setpeername(address, port)
6132
6133 **Function: **Changes the peer of a UDP object.
6134
6135 **Parameters:**
6136
6137 * "* "(string): If address is '##*##' and the object is connected, the peer association is removed and the object becomes an unconnected object again.
6138 * address(string), port(number) —— address could be IP address or hostname. Port is the port number.
6139
6140 **Return: **
6141
6142 * Success: Returns 1.
6143 * Failure: Returns nil and error.
6144
6145 **Note:**
6146
6147 * This method converts an unconnected UDP object into a connected UDP object or vice versa.
6148 * For connected objects, the outgoing datagrams will be sent to the specified peer, and datagrams received from other peers will be discarded by the OS. The connected UDP objects must use the sand and receive methods instead of sendto and receiveform.
6149 * Since the address of the peer does not have to be passed to and from the OS, the use of connected UDP objects is recommended when the same peer is used for several transmissions and can result in up to 30% performance gains.
6150 * Starting with LuaSocket 3.0, the host name resolution depends on whether the socket was created by socket.udp and socket.udp6. Addresses from the appropriate family are tried in succession until the first success or until the last failure.
6151
6152 == [[udp:setsockname()>>||anchor="HUDPmodule"]] ==
6153
6154 **Prototype: **unconnected:setsockname(address, port)
6155
6156 **Function: **Binds the UDP object to a local address.
6157
6158 **Parameters:**
6159
6160 * address(string): Bind address. The address can be an IP address or a host name. If address is '*', the system will bind to all local interfaces using the constant INADDR_ANY.
6161 * port(number): Port number. It the port is 0, the system chooses an ephemeral port.
6162
6163 **Return: **
6164
6165 * Success: Returns 1.
6166 * Failure: Returns nil and error.
6167
6168 **Note:**
6169
6170 * This method could only be called before any datagram is sent through the UDP object, and only once. Otherwise, the system automatically binds the object to all local interfaces and chooses an ephemeral port as soon as the first datagram is sent. After the local address is set, either automatically by the system or explicitly by socketname, it cannot be changed.
6171
6172 == [[udp:getfamily()>>||anchor="HUDPmodule"]] ==
6173
6174 **Prototype: **
6175
6176 * connect:getfamily
6177 * unconnect:getfamily
6178
6179 **Function: **Returns a TCP family
6180
6181 **Parameters: **None
6182
6183 **Return: **
6184
6185 * Success: Returns a protocol family string
6186 * Failure: Returns nil and error.
6187
6188 = ftp module =
6189
6190 == [[ftp.command()>>||anchor="HFTPmodule"]] ==
6191
6192 **Prototype: **ftp.command(cmdt)
6193
6194 **Function: **Send ** **ftp command
6195
6196 **Parameters:**
6197
6198 * (((
6199 cmdt(table):ftp command list
6200
6201 {
6202
6203 host = string, ~-~- address
6204
6205 command = string, ~-~- ftp command
6206
6207 port = number, ~-~- port
6208
6209 user = string, ~-~- username
6210
6211 password = string or table , ~-~- password
6212
6213 argument = string or table, ~-~- upload parameter
6214
6215 check = function, ~-~- Check function
6216
6217 create = function, ~-~- Create a connection function
6218
6219 }
6220 )))
6221
6222 **Return: **
6223
6224 * Success: Returns 1.
6225 * Failure: Returns nil and error.
6226
6227 **Note:**
6228
6229 * This function only sends commands and does not receive data. To receive data, you need to create another channel.
6230
6231 **Example**
6232
6233 {{code language="LUA"}}
6234 -- 1. Introduce modules
6235 -- local ftp = require("socket.ftp")
6236 -- local LTN12 = require("ltn12")
6237
6238 -- 2. Send command
6239 local tabRecv = {} -- Create a table to receive data
6240 local state,err = ftp.command({
6241 host = "192.168.50.225", -- Set ftp server address to "192.168.50.225"
6242 port = 21, -- Set ftp server port to 21
6243 -- user = ftp.USER, -- The password is set to the default anonymous account, so it can be omitted
6244 -- password = ftp.PASSWORD,
6245 command = "DELE", -- Set to send ftp command "DELE". For details about the command, see the appendix
6246 argument = "/test.png", -- Set the Delete command parameter "/test.png", (delete "/test.png" file)
6247 sink = LTN12.sink.table(tabRecv) -- Configure the receiver
6248 })
6249 -- 3. Print result
6250 if state and err==nil then
6251 print("dele '/test.png' success ! ")
6252 else
6253 print("faild !",err)
6254 end
6255 {{/code}}
6256
6257 == [[ftp.genericform()>>||anchor="HFTPmodule"]] ==
6258
6259 **Prototype: **ftp.genericform(u, b)
6260
6261 **Function: **Request parameter conversion. The simple URL request mode convert to a general table table parameter form.
6262
6263 **Parameters:**
6264
6265 * u(string): The requested URL field
6266 * b(string): The requested body field
6267
6268 **Return: **
6269
6270 * General request table parameter
6271
6272 **Example**
6273
6274 {{code language="LUA"}}
6275 local ftp = require("socket.ftp")
6276 local json = require("json")
6277
6278 local server_ip = "192.168.50.225"
6279 local server_file1 = "/chenGH/ftpput.txt"
6280
6281 local url = "ftp://"..server_ip..server_file1
6282
6283 local t = assert(ftp.genericform(url))
6284 print(type(t),json.encode(t))
6285 --------------------------------------------------------------------------------Output:
6286 -- table {"path":"/chenGH/ftpput.txt","scheme":"ftp","host":"192.168.50.225","authority":
6287 --"192.168.50.225"}
6288 {{/code}}
6289
6290 == [[ftp.put()>>||anchor="HFTPmodule"]] ==
6291
6292 **Prototype 1: **ftp.**put(** url, content **)**
6293
6294 **Function: **Upload url data
6295
6296 **Parameters:**
6297
6298 * url: Resource identification locator
6299 * content: Data to be uploaded
6300
6301 **Return: **
6302
6303 * Success: Return 1.
6304 * Failure: Return nil and error.
6305
6306 **Prototype 2: **
6307
6308 ftp.**put{**
6309 host = //string//,
6310 source = //LTN12 sink//,
6311 argument //or// path = //string//,
6312 [user = //string//,]
6313 [password = //string//]
6314 [command = //string//,]
6315 [port = //number//,]
6316 [type = //string//,]
6317 [step = //LTN12 pump step//,]
6318 [create = //function//]
6319 **}**
6320
6321 **Function: **Data upload is controlled by fields
6322
6323 **Parameters:**
6324
6325 * host: houstname, IP address (Required parameters)
6326 * source: LTN12 object (Required parameters)
6327 * argument or path: Upload parameter/request path (Required parameters)
6328 * user: username
6329 * password: password
6330 * command: Used to send data. Defaults to ##stor##.
6331 * port: Used for the control connection. Defaults to 21
6332 * type: The transfer mode. Can take values "##i##" or "##a##" (Binary or ASCII). The default value is the server default value.
6333 * step: Used to tranmist data from the server to the sink. Defaults to the LTN12 pump.step function.
6334 * create: An optional function to be used instead of socket.tcp when the communications socket is created.
6335
6336 **Return: **
6337
6338 * Success: Return 1.
6339 * Failure: Return nil and error.
6340
6341 **Example**
6342
6343 {{code language="LUA"}}
6344 local ftp = require("socket.ftp")
6345 local ltn12 = require("ltn12")
6346
6347 local server_ip = "192.168.50.225"
6348 -- Create a file if the file does not exist, overwrites the original data if the file exists,
6349 and reports an error if the folder does not exist
6350 local server_file1 = "/chenGH/ftpput.txt"
6351 local server_file2 = "/chenGH/ftpput.dll"
6352
6353 -- ftp.put Data push format 1, simple mode, push simple data
6354 local url = "ftp://"..server_ip..server_file1
6355 local ret,msg = ftp.put(url,"hello server ! this is put data !")
6356 if ret then
6357 print("put data success !")
6358 else
6359 print(msg)
6360 end
6361
6362 -- ftp.put Data push format 2, You can configure parameters to push complex data or files
6363 local put_param = {} -- Creatt a parameter table
6364 put_param.host = server_ip
6365 put_param.path = server_file2
6366 put_param.source = ltn12.source.file(io.open("user:ftpTest.dll","rb"),"connot open file !")
6367 local ret = assert(ftp.put(put_param))
6368 if ret then
6369 print("put data success ! ")
6370 end
6371 {{/code}}
6372
6373 == [[ftp.get()>>||anchor="HFTPmodule"]] ==
6374
6375 **Prototype 1: **ftp.**get(** url, content **)**
6376
6377 **Function: **Download the contents of a URL and returns it as a string.
6378
6379 **Parameters:**
6380
6381 * 【string】 url —— url resource identifier
6382
6383 **Return: **
6384
6385 * Success: Return the string content that the url points to.
6386 * Failure: Return nil and error.
6387
6388 **Note:**
6389
6390 * The cached string size cannot exceed 1 MB. If the string size exceeds 1 MB, data processing is performed throuhg LTN2.
6391
6392 **Prototype 2: **
6393
6394 ftp.**get{**
6395 host = //string//,
6396 sink = //LTN12 sink//,
6397 argument //or// path = //string//,
6398 [user = //string//,]
6399 [password = //string//]
6400 [command = //string//,]
6401 [port = //number//,]
6402 [type = //string//,]
6403 [step = //LTN12 pump step//,]
6404 [create = //function//]
6405 **}**
6406
6407 **Function: **Download is controlled by parameter fields.
6408
6409 **Parameters:**
6410
6411 * host: houstname, IP address
6412 * source: LTN12 object
6413 * argument or path: Request parameter/request path
6414 * user: username. Default to "ftp".
6415 * password: password. Default to "anonymous@anonymous.org".
6416 * command: Used to get ftp command of data. Defaults to retr.
6417 * port: Used for the control connection. Defaults to 21.
6418 * type: The transfer mode. Can take values "i" or "a". The default value is the server default value.
6419 * step: Used to tranmist data from the server to the sink. Defaults to the LTN12 pump.step()
6420 * create: An optional function to be used instead of socket.tcp when the communications socket is created.
6421
6422 **Return: **
6423
6424 * Success: Return 1.
6425 * Failure: Return nil and error.
6426
6427 **Note:**
6428
6429 * If the size of the retrieved file exceeds the size of the cache (1M), the receiver (prototype 2) is used to block the data or the retrieved data will fail.
6430 * The IO module of Lua is required to use the file receiver. Currently, the IO module of Hmi is not open, so files exceeding 1M cannot be obtained temporarily.
6431
6432 **Example**
6433
6434 {{code language="LUA"}}
6435 local ftp = require("socket.ftp")
6436 local ltn12 = require("ltn12")
6437
6438 local server_ip = "192.168.50.225" -- server address
6439 local server_port = "21" -- default to 21,If there is special, it can be changed.
6440 local server_user = "ftp" -- server name, default to "ftp"
6441 -- server passpword, default to "anonymous@anonymous.org"
6442 local server_password = "anonymous@anonymous.org"
6443 local server_file1 = "/chenGH/ftpTest.txt" -- Server destination file(File 1 you want to download)
6444 local server_file2 = "/chenGH/ftpTest.dll" -- Server destination file(File 2 you want to download)
6445
6446
6447 -- ftp.get get format 1,Enter the URL of the file directly
6448 -- Note: The size of the file cannot exceed the buffer size (1M), and exceeding will result in acquisition failure.
6449 local ftpUrl = "ftp://"..server_ip..server_file1
6450 local data,msg = ftp.get(ftpUrl)
6451 if not data then
6452 print("ftp_get",msg)
6453 return nil
6454 else
6455 print(data)
6456 assert(flash.file_write("user:ftpTest.txt", "w+", data)) -- Create a local ftptest.txt file and write data to it
6457 end
6458
6459 -- ftp.get format 2,configure ftp.get paramter
6460 local dataTab = {}
6461 local getRequest = {}
6462 getRequest.host = server_ip
6463 getRequest.path = server_file2
6464 -- io operation temporarily blocks I/O file operations in HMI. Therefore, files that exceed 1 MB cannot be written.
6465 getRequest.sink = ltn12.sink.file(io.open("user:ftpTest.dll", "wb"))
6466 assert(ftp.get(getRequest))
6467 {{/code}}
6468
6469 = http module =
6470
6471 == [[http.request()>>||anchor="Hhttpmodule"]] ==
6472
6473 **Prototype 1: **http.request(url [, body])
6474
6475 **Function: **http request function
6476
6477 **Parameters:**
6478
6479 * url(string): Website address, uniform resource locator.
6480 * body: The requested data body
6481
6482 **Return: **
6483
6484 * The simple form returns the response body as a string, followed by a response status code, a response header, and a response status line.
6485
6486 **Example**
6487
6488 {{code language="LUA"}}
6489 -- 1. Introduce modules
6490 local http = require("socket.http")
6491 local json = require("json")
6492
6493 -- 2. Constant and variable definitions
6494 local weather_url = "http://t.weather.itboy.net/api/weather/city"
6495 local city_code = "101010100" -- Beijing
6496
6497 -- 3. Get weather information
6498 local url = weather_url.."/"..city_code
6499 print(url)
6500 str_weatherInfo = http.request(url)
6501 -- print(str_weatherInfo)
6502 tab_weatherInfo = json.decode(str_weatherInfo) -- Convert the weather information in JSON format to a table
6503 print("wendu =",tab_weatherInfo["data"]["wendu"]) -- Get the temperature information in the table
6504 ----------------------------------------------------Output:
6505 --http://t.weather.itboy.net/api/weather/city/101010100
6506 --wendu = 7
6507 {{/code}}
6508
6509 **Prototype 2: **http.**request{**
6510 url = //string//,
6511 [sink = //LTN12 sink//,]
6512 [method = //string//,]
6513 [headers = //header-table//,]
6514 [source = //LTN12 source//],
6515 [step = //LTN12 pump step//,]
6516 [proxy = //string//,]
6517 [redirect = //boolean//,]
6518 [create = //function//]
6519 **}**
6520
6521 **Function: **http request function
6522
6523 **Parameters:**
6524
6525 * url: website address, uniform resource locator. (required parameter)
6526 * sink: LTN12 reveiver (optional parameter)
6527 * method: http request method, default to "get". (optional parameter)
6528 * headers: Any other HTTP headers sent with the request. (optional parameter)
6529 * source: //simple// LTN12 source to provide the request body. If there is a body, you need to provide an appropriate "content-length" request header field, or the function will attempt to send the body as "chunked" (something few servers support). Defaults to the empty source. (optional parameter)
6530 * step: Used to tranmist data from the server to the sink. Defaults to the LTN12 pump.step function. (optional parameter)
6531 * proXY: The URL of the proxy server to use. The default is no proxy. (optional parameter)
6532 * tredirect: Set to false to prevent this feature from automatically following 301 or 302 server redirection messages. (optional parameter)
6533 * create: An optional function to be used instead of socket.tcp when the communications socket is created.(optional parameter)
6534
6535 **Return: **
6536
6537 * Success: Return 1, and stores the data to the receiver.
6538 * Failure: Return nil and error.
6539
6540 **Example**
6541
6542 {{code language="LUA"}}
6543 -- 1. Introduce modules
6544 local http = require("socket.http")
6545 local json = require("json")
6546 local LTN12= require("ltn12")
6547
6548 -- 2. Constant and variable definitions
6549 local weather_url = "http://t.weather.itboy.net/api/weather/city"
6550 local city_code = "101010100" -- Beijing
6551 local tabWeatherInfo = {}
6552
6553 -- 3. Get weather information
6554 local url = weather_url.."/"..city_code
6555 print(url)
6556
6557 local tabRequest = {}
6558 tabRequest.url = url
6559 tabRequest.sink = LTN12.sink.table(tabWeatherInfo)
6560
6561 status,str_weatherInfo = http.request(tabRequest)
6562 print(type(tabWeatherInfo[1]))
6563 print("str_weatherInfo =",tabWeatherInfo[1])
6564
6565 -- Convert the weather information in JSON format to a table. Since the LTN12.sink.table receiver is used to receive,
6566 the accepted result is present in the tabWeatherInfo table.The receive occurs only once, and it is stored at the tabWeatherInfo[1].
6567 local tab_weatherInfo = json.decode(tabWeatherInfo[1])
6568 print("wendu =",tab_weatherInfo["data"]["wendu"]) -- Get the temperature information in the table.
6569 {{/code}}
6570
6571 == [[http.genericform()>>||anchor="Hhttpmodule"]] ==
6572
6573 **Prototype : **http.genericform(u, b)
6574
6575 **Function: **Convert a simple URL to a generic table parameter
6576
6577 **Parameters:**
6578
6579 * u(string):The URL field that http requested
6580 * b(string):The body field that http requested
6581
6582 **Return: **
6583
6584 * Generic table parameter
6585
6586 **Example**
6587
6588 {{code language="LUA"}}
6589 -- 1. Introduce modules
6590 local http = require("socket.http")
6591
6592 -- 2. Constant and variable definitions
6593 local url = "http://t.weather.itboy.net/api/weather/city/101010100"
6594
6595 ta = http.genericform(url)
6596 print(type(ta))
6597 print("ta.utl =",ta.url)
6598 print("ta.sink =",ta.sink)
6599 print("ta.method =",ta.method)
6600 print("ta.heards =",ta.heards)
6601 print("ta.source =",ta.source)
6602 print("ta.step =",ta.step)
6603 print("ta.proxy =",ta.proxy)
6604 print("ta.redirect=",ta.redirect)
6605 print("ta.create =",ta.create)
6606 ------------------------------Output:
6607 --table
6608 --ta.utl = http://t.weather.itboy.net/api/weather/city/101010100
6609 --ta.sink = function: 060405E0
6610 --ta.method = nil
6611 --ta.heards = nil
6612 --ta.source = nil
6613 --ta.step = nil
6614 --ta.proxy = nil
6615 --ta.redirect= nil
6616 --ta.create = nil
6617 {{/code}}
6618
6619 = https module =
6620
6621 == [[https.request()>>||anchor="Hhttpsmodule"]] ==
6622
6623 **Prototype 1: **https.request(url [, body])
6624
6625 **Function: **https request fucntion
6626
6627 **Parameters:**
6628
6629 * url(string): Website address, uniform resource locator.
6630 * body: The requested data body
6631
6632 **Return: **
6633
6634 |=Return value position|=Meaning
6635 |1|The returned data result
6636 |2|The access result code. 200 indicates that the connection is successful
6637 |3|The returned response header line
6638 |4|The returned response status
6639
6640 **~ Example**
6641
6642 {{code language="LUA"}}
6643 -- 1. Declare modules
6644 local https = require("socket.https")
6645 local LTN12= require("ltn12")
6646
6647 function test()
6648 print_debug(1)
6649 print("wait request . . . ")
6650 local res, code, headers, status = https.request{
6651 url = "https://www.we-con.com.cn/"
6652 }
6653
6654 print("res=",res)--The returned data result
6655 print("code=",code)--The access result code. 200 indicates that the connection is successful
6656 for i,v in pairs(headers) do --The returned response header line
6657 print("i,v=",i,v)
6658 end
6659 print("state=",status)--The returned response status
6660
6661 we_bas_setstring("@W_HDW4600", status)
6662 end
6663 {{/code}}
6664
6665 **Prototype 2: ** http.**request{**url = //string//,
6666 [sink = //LTN12 sink//,]
6667 [method = //string//,]
6668 [headers = //header-table//,]
6669 [source = //LTN12 source//],
6670 [step = //LTN12 pump step//,]
6671 [proxy = //string//,]
6672 [redirect = //boolean//,]
6673 [create = //function//]
6674 **}**
6675
6676 **Function: **https request fucntion
6677
6678 **Parameters:**
6679
6680 * url ~-~- web address, uniform resource locator [mandatory parameter
6681 * sink ~-~- LTN12 receiver [optional parameter
6682 * method ~-~- the HTTP request method, default is "GET" [optional parameter
6683 * headers ~-~- any other HTTP headers sent with the request; [optional] [optional
6684 * source ~-~- A simple LTN12 source that provides the body of the request. If there is a body, the appropriate "content length" request header field needs to be provided, otherwise the function will attempt to send the body as a "chunk" (rarely supported by servers). Default is empty source; [optional parameter
6685 * step ~-~- Used to move the data, default is LTN12.pump.step function. [optional parameters]
6686 * proXY ~-~- the URL of the proxy server to use. Default is no proxy; [optional parameter
6687 * redirect ~-~- set to false to prevent the function from automatically following 301 or 302 server redirect messages; [optional parameter
6688 * create ~-~- optional function to use when creating communication sockets instead of socket.tcp. [optional parameter
6689
6690 **Return: **
6691
6692 |=Return value position|=Meaning
6693 |1|The returned data result
6694 |2|The access result code. 200 indicates that the connection is successful
6695 |3|The returned response header line
6696 |4|The returned response status
6697
6698 **~ Example**
6699
6700 {{code language="LUA"}}
6701 -- 1、Declare modules
6702 local http = require("socket.https")
6703 local json = require("json")
6704 local LTN12= require("ltn12")
6705
6706 -- Case 2
6707 function test2()
6708 print_debug(1)
6709 local url="https://open.ys7.com/api/lapp/device/info?accessToken=at.dunwhxt2azk02hcn7phqygsybbw0wv6p&deviceSerial=427734168"
6710 local Result = {}
6711
6712 local tabRequest = {}
6713 tabRequest.url = url
6714 tabRequest.method = "POST"
6715 tabRequest.sink = LTN12.sink.table(Result)
6716
6717 print("wait request . . . ")
6718 local res, code, headers, status = https.request(tabRequest)
6719
6720 print("Result =",table.concat(Result))--Returned data results
6721 print("res",res)--Returned response result
6722 print("code =", code)--Returned status code, 200 is OK
6723 for i,v in pairs(headers) do --Returned response message header
6724 print(i,v)
6725 end
6726 print("status=",status)--Returned response status
6727 end
6728 --Case 3
6729 function test3()
6730 print_debug(1)
6731 print("wait request . . . ")
6732 local Result = {}
6733
6734 local res, code, headers, status = https.request{
6735 url = "https://open.ys7.com/api/lapp/device/info?accessToken=at.dunwhxt2azk02hcn7phqygsybbw0wv6p&deviceSerial=427734168",
6736 method = "POST",
6737 sink = LTN12.sink.table(Result),
6738 }
6739
6740 print("Result =",table.concat(Result))--Returned data results
6741 print("res",res)--Returned response result
6742 print("code=",code)--Returned status code, 200 is OK
6743 for i,v in pairs(headers) do --Returned response message header
6744 print("i,v=",i,v)
6745 end
6746 print("state=",status)--Returned response status
6747 end
6748 {{/code}}
6749
6750 = SMTP module =
6751
6752 == [[smtp.message()>>||anchor="HSMTPmodule"]] ==
6753
6754 **Prototype: **smtp.message(mesgt)
6755
6756 **Function: **Generate mail format messages
6757
6758 **Parameters: **
6759
6760 * mesgt(table): Message format
6761
6762 {{code language="LUA"}}
6763 -- Message format:
6764 mesgt = {
6765 headers = header-table, -- message header
6766 body = LTN12 source or string or multipart-mesgt -- message text
6767 }
6768
6769 multipart-mesgt = {
6770 [preamble = string,] -- preface
6771 [1] = mesgt, -- text content 1
6772 [2] = mesgt, -- text content 2
6773 ...
6774 [n] = mesgt, -- text content n
6775 [epilogue = string,] -- Conclusion
6776 }
6777 {{/code}}
6778
6779 **Return: **
6780
6781 * Returns a mail message source used to send messages
6782
6783 {{code language="LUA"}}
6784 source = smtp.message
6785 {
6786 headers = -- mail header
6787 {
6788 -- Note: smtp.send ignores headers
6789 from = "chenGH <chen__GH@163.com>", -- sender
6790 to = "chenGH <chengh@we-con.com.cn>", -- recipient
6791 cc = "<3388545257@qq.com>", -- cc
6792 subject = "Test the mail sending function of the LUa SMTP module!" -- title
6793 },
6794 body = -- mail content
6795 {
6796 preamble = "Thanks for participating in the Lua SMTP mail test!", -- preface
6797 [1] = -- text 1(text)
6798 {
6799 -- The first part has no header, which means it is plain text, encoded in ASCII.
6800 -- mime.eol is an underlying function, and used to normalize trailing line break marks
6801 body = mime.eol(0, [[
6802 Lines in the message body should always end in CRLF (carriage return line feed)
6803 The Smtp module does not process the message content。 The execution process is as follows
6804 A: Package the message content via smtp.message
6805 B: Package the message content via smtp.send and send the message.(Contains attachment data fill sections)
6806 ]])
6807 },
6808 [2] = -- text 2 (picture)
6809 {
6810 -- Part two: The title describes the content as a png image.
6811 -- Transfer content based on base64 encoding format
6812 -- Note: Nothing happens until the message is actually sent, and the data is assembled just after it is sent.
6813 headers =
6814 {
6815 -- Declare the type and name of the content of the second part of the message(type:image/png,name:image.png")
6816 ["content-type"] = 'image/png; name="image.png"',
6817 ["content-disposition"] = 'attachment; filename="image.png"', -- content description
6818 ["content-description"] = 'a beautiful image', -- mail description
6819 ["content-transfer-encoding"] = "BASE64" -- Mail encoding format
6820 },
6821 body = LTN12.source.chain( -- Data source connection
6822 LTN12.source.file(io.open("user:smtp.png","rb")), -- Open a file as the data source
6823 LTN12.filter.chain( -- Encoding format is base64
6824 mime.encode("base64"),
6825 mime.wrap()
6826 ))
6827 },
6828 epilogue = "This might also show up, but after the attachments" -- Conclusion
6829 }
6830 }
6831 {{/code}}
6832
6833 == [[smtp.send()>>||anchor="HSMTPmodule"]] ==
6834
6835 **Prototype : **smtp.**send{**
6836 from = //string//,
6837 rcpt = //string// or //string-table//,
6838 source = //LTN12 source//,
6839 [user = //string//,]
6840 [password = //string//,]
6841 [server = //string//,]
6842 [port = //number//,]
6843 [domain = //string//,]
6844 [step = //LTN12 pump step//,]
6845 [create = //function//]
6846 **}**
6847
6848 **Function: **send email
6849
6850 **Parameters:**
6851
6852 * from: sender
6853 * rcpt: recipient list
6854 * source: message source. The message after packaging
6855 * user: account. It is for mailbox authentication
6856 * password: password. It is for mailbox authenticatio. (base64 format)
6857 * server: smtp server address. e.g., the server of 163 mail is smtp.163.com; the server of QQ mail is smtp.qq.com.
6858 * port: smtp server port, default to 25. 163 Mailbox smtp port is 25, qq mailbox smtp server port number is 587/465.
6859 * domain: domain information. Default to "localhost".
6860 * step: Used to pass data from the source to the server. Defaults to the LTN12 ##pump.step## function.
6861 * create: Used to create socket connection. Default to socket.tcp().
6862
6863 **Return: **
6864
6865 * Success: Return 1.
6866 * Failure: Return nil and error.
6867
6868 **Note:**
6869
6870 1. SMTP servers can be very picky with the format of e-mail addresses. To be safe, use only addresses of the form "##<fulano@example.com>##" in the from and rcpt arguments of the send function. In headers, e-mail addresses can take whatever form you like.
6871 1. Only recipients specified in the rcpt list will receive a copy of the message. Each recipient of an SMTP mail message receives a copy of the message body along with the headers, and nothing more. The headers //are// part of the message and should be produced by the LTN12 source function. The rcpt list is //not// part of the message and will not be sent to anyone.
6872
6873 * To: Contains the address(es) of the primary recipient(s) of the message.
6874 * Cc: Contains the addresses of others who are to receive the message, though the content of the message may not be directed at them (where the "Cc" means "Carbon Copy" in the sense of making a copy on a typewriter using carbon paper).
6875 * Bcc: Contains addresses of recipients of the message whose addresses are not to be revealed to other recipients of the message (where the "Bcc" means "Blind Carbon Copy")
6876
6877 (% start="3" %)
6878 1. (((
6879 The LuaSocket send function does not care or interpret the headers you send, but it gives you full control over what is sent and to whom it is sent:
6880 )))
6881
6882 * If someone is to receive the message, the e-mail address //has// to be in the recipient list. This is the only parameter that controls who gets a copy of the message.
6883 * If there are multiple recipients, none of them will automatically know that someone else got that message. That is, the default behavior is similar to the ##Bcc## field of popular e-mail clients;
6884 * It is up to you to add the To header with the list of primary recipients so that other recipients can see it.
6885 * It is also up to you to add the Cc header with the list of additional recipients so that everyone else sees it.
6886 * Adding a header Bcc is nonsense, unless it is empty. Otherwise, everyone receiving the message will see it and that is exactly what you //don't// want to happen.
6887
6888 **Example**
6889
6890 {{code language="LUA"}}
6891 local smtp = require("socket.smtp")
6892 local LTN12= require("ltn12")
6893 local mime = require("mime")
6894 from = "<chen__GH@163.com>" -- sender(Angle brackets must be added or some errors may occur)
6895 rcpt = { -- send list(Angle brackets must be added or some errors may occur)
6896 "<chengh@we-con.com.cn>",
6897 "<1125920709@qq.com>",
6898 "<3388545257@qq.com>"
6899 }
6900
6901 -- Create a sending source that is divided into two parts, one for plain text and the other for the PNG image。
6902 source = smtp.message
6903 {
6904 headers = -- mail header
6905 {
6906 -- Note: smtp.send ignores headers
6907 from = "chenGH <chen__GH@163.com>", -- sender
6908 to = "chenGH <chengh@we-con.com.cn>", -- recipient
6909 cc = "<3388545257@qq.com>", -- CC
6910 subject = "Test the mail sending function of the LUa SMTP module!!" -- title
6911 },
6912 body = -- mail text
6913 {
6914 preamble = "Thanks for participating in the Lua SMTP mail test!", -- preface
6915 [1] = -- text 1(plain text)
6916 {
6917 -- The first part has no header, which means it is plain text, encoded in ASCII.
6918 -- mime.eol is an underlying function, and used to normalize trailing line break marks
6919 body = mime.eol(0, [[
6920 Lines in the message body should always end in CRLF (carriage return line feed)
6921 The Smtp module does not process the message content。 The execution process is as follows
6922                  A: Package the message content via smtp.message
6923                  B: Package the message content via smtp.send and send the message.(Contains attachment data fill sections)
6924 ]])
6925 },
6926 [2] = -- text 2 (picture)
6927 {
6928 -- Part two: The title describes the content as a png image.
6929            -- Transfer content based on base64 encoding format
6930            -- Note: Nothing happens until the message is actually sent, and the data is assembled just after it is sent.
6931 headers =
6932 {
6933 -- Declare the type and name of the content of the second part of the message(type:image/png,name:image.png")
6934 ["content-type"] = 'image/png; name="image.png"',
6935 -- content description
6936 ["content-disposition"] = 'attachment; filename="image.png"',
6937 -- mail description
6938 ["content-description"] = 'a beautiful image',
6939 -- Message encoding format
6940 ["content-transfer-encoding"] = "BASE64"
6941 },
6942 body = LTN12.source.chain( -- Data source connection
6943 LTN12.source.file(io.open("user:smtp.png","rb")), -- Open a file as the data source
6944 LTN12.filter.chain(
6945 mime.encode("base64"), -- Encoding format is base64
6946 mime.wrap()
6947 ))
6948 },
6949 epilogue = "This might also show up, but after the attachments" -- Conclusion
6950 }
6951 }
6952
6953 -- send email
6954 r, e = assert(smtp.send{
6955 from = from, -- mail sender
6956 rcpt = rcpt, -- Mail receiving list
6957 -- smtp server. e.g.,qq mail is smtp.qq.com; enterprise mail is smtp.qiye.com。
6958 server = "smtp.163.com",
6959 user = "chen__GH@163.com", -- account
6960 password = "HUCOYKAUIKLSGZFJ", -- password(the password after conversion to base64)
6961
6962
6963 -- smtp server port,You need to look it up yourself;qq mailbox open 587/465, 163 mailbox port 25
6964 --(25 is the smtp default port)
6965 -- port = 587,
6966 source = source, -- message source } )
6967 print("end success!! ")
6968 {{/code}}
6969
6970 = LTN12 module =
6971
6972 == [[LTN12.filter.chain()>>||anchor="HLTN12module"]] ==
6973
6974 **Prototype : **ltn12.filter.chain(filter1, filter2 [, ... filterN])
6975
6976 **Function: **Generates a set of connected filters, and the nesting of filters can be arbitrary
6977
6978 **Parameters:**
6979
6980 * filter1 to filter N are simple filters
6981
6982 **Return: **
6983
6984 * Returns the connected filter
6985
6986 == [[LTN12.filter.cycle()>>||anchor="HLTN12module"]] ==
6987
6988 **Prototype : **ltn12.filter.cycle(low [, ctx, extra])
6989
6990 **Function: **Returns a high-level filter that cycles though a low-level filter by passing it each chunk and updating a context between calls.
6991
6992 **Parameters:**
6993
6994 * low:The low-level filter to be cycled.
6995 * ctx:The initial context.
6996 * extra:Any extra argument the low-level filter might take.
6997
6998 **Return: **
6999
7000 * Returns the high-level filter.
7001
7002 == [[LTN12.pump.all()>>||anchor="HLTN12module"]] ==
7003
7004 **Prototype : **ltn12.pump.all(source, sink)
7005
7006 **Function: **Pumps all  data from a source to a sink##.##
7007
7008 **Parameters:**
7009
7010 * source:data source
7011 * sink:sink
7012
7013 **Return: **
7014
7015 * Success: Return true.
7016 * Failure: Return false and error.
7017
7018 == [[LTN12.pump.step()>>||anchor="HLTN12module"]] ==
7019
7020 **Prototype : **ltn12.pump.step(source, sink)
7021
7022 **Function: **Pumps  a large chunk of data from the source to the sink.
7023
7024 **Parameters:**
7025
7026 * source:source
7027 * sink:sink
7028
7029 **Return: **
7030
7031 * Success: Return true.
7032 * Failure: Return false and error.
7033
7034 == [[LTN12.sink.chain()>>||anchor="HLTN12module"]] ==
7035
7036 **Prototype : **ltn12.sink.chain(filter, sink)
7037
7038 **Function: **Creates a new sink that passes data through a filter before sending it to a given sink.
7039
7040 **Parameters:**
7041
7042 * source: filter
7043 * sink: sink
7044
7045 **Return: **
7046
7047 * Return the created sink.
7048
7049 == [[LTN12.sink.error()>>||anchor="HLTN12module"]] ==
7050
7051 **Prototype : **ltn12.sink.chain(filter, sink)
7052
7053 **Function: **Creates a new sink that passes data through a filter before sending it to a given sink.
7054
7055 **Parameters:**
7056
7057 * filter:filter
7058 * sink:sink
7059
7060 **Return: **
7061
7062 * Returns the new sink that was created.
7063
7064 == [[LTN12.sink.file()>>||anchor="HLTN12module"]] ==
7065
7066 **Prototype : **ltn12.sink.file(handle, message)
7067
7068 **Function: **Create a sink that sends data to a file
7069
7070 **Parameters:**
7071
7072 * handle: file handle
7073 * message: If ##handle## is ##**nil**##, ##message## should give the reason for failure
7074
7075 **Return: **
7076
7077 * Returns the new sink that was created.
7078
7079 **Note:**
7080
7081 * The function returns a sink that sends all data to the given handleThe fu and closes the file when done, or a sink that aborts the transmission with the error message.
7082 * This function is used with io.open(): ltn12.sink.file(io.open("copy.png", "wb"))
7083
7084 == [[LTN12.sink.null()>>||anchor="HLTN12module"]] ==
7085
7086 **Prototype : **ltn12.sink.null()
7087
7088 **Function: **Returns a sink that ignores all data it receives.
7089
7090 **Parameters: **None
7091
7092 **Return: **
7093
7094 * Returns the new sink that was created.
7095
7096 == [[LTN12.sink.simplify()>>||anchor="HLTN12module"]] ==
7097
7098 **Prototype : **ltn12.sink.simplify(sink)
7099
7100 **Function: **Creates and returns a simple sink given a fancy sink.
7101
7102 **Parameters:**
7103
7104 * sink:sink
7105
7106 **Return: **
7107
7108 * Returns the new sink that was created.
7109
7110 == [[LTN12.sink.table()>>||anchor="HLTN12module"]] ==
7111
7112 **Prototype : **ltn12.sink.table([table])
7113
7114 **Function: **Creates a sink that stores all chunks in a table. The chunks can later be efficiently concatenated into a single string.
7115
7116 **Parameters:**
7117
7118 * table: Used to hold the chunks. If it is nil, the function creates its own table.
7119
7120 **Return: **
7121
7122 * Returns the sink and the table used to store the chunks.
7123
7124 == [[LTN12.source.cat()>>||anchor="HLTN12module"]] ==
7125
7126 **Prototype : **ltn12.source.cat(source1 [, source2, ..., sourceN])
7127
7128 **Function: **Creates a new source that produces the concatenation of the data produced by a number of sources.
7129
7130 **Parameters:**
7131
7132 * source 1 to source n are the original sources.
7133
7134 **Return: **
7135
7136 * Returns the new source created.
7137
7138 == [[LTN12.source.chain()>>||anchor="HLTN12module"]] ==
7139
7140 **Prototype : **ltn12.source.chain(source, filter)
7141
7142 **Function: **Creates a new source that passes data through a filter before returning it.
7143
7144 **Parameters:**
7145
7146 * source: original source
7147 * filter: filter
7148
7149 **Return: **
7150
7151 * Returns the new source created.
7152
7153 == [[LTN12.source.empty()>>||anchor="HLTN12module"]] ==
7154
7155 **Prototype : **ltn12.source.empty()
7156
7157 **Function: **Creates and return a new source.
7158
7159 **Parameters: **None
7160
7161 **Return: **
7162
7163 * Returns the new source created.
7164
7165 == [[LTN12.source.error()>>||anchor="HLTN12module"]] ==
7166
7167 **Prototype : **ltn12.source.**error(message**)
7168
7169 **Function: **Creates and returns a source that aborts transmission with the error message.
7170
7171 **Parameters:**
7172
7173 * message: error message
7174
7175 **Return: **
7176
7177 * Returns the new source created.
7178
7179 == [[LTN12.source.file()>>||anchor="HLTN12module"]] ==
7180
7181 **Prototype : **ltn12.source.file(handle, message)
7182
7183 **Function: **Creates a source that produces the contents of a file.
7184
7185 **Parameters:**
7186
7187 * handle: file handle
7188 * message: If ##handle## is ##**nil**##, ##message## should give the reason for failure
7189
7190 **Return: **
7191
7192 * Returns the new source created.
7193
7194 **Note:**
7195
7196 * The function returns a source that reads chunks of data from given handle and returns it to the user, closing the file when done, or a source that aborts the transmission with the error message.
7197
7198 == [[LTN12.source.simplify()>>||anchor="HLTN12module"]] ==
7199
7200 **Prototype : **ltn12.source.simplify(source)
7201
7202 **Function: **Given a source, create and return a simple source.
7203
7204 **Parameters:**
7205
7206 * source: the given initial source
7207
7208 **Return: **
7209
7210 * Returns the new source created.
7211
7212 == [[LTN12.source.string()>>||anchor="HLTN12module"]] ==
7213
7214 **Prototype : **ltn12.source.string(string)
7215
7216 **Function: **Creates and returns a source that produces the contents of a string, chunk by chunk.
7217
7218 **Parameters:**
7219
7220 * string: string source
7221
7222 **Return: **
7223
7224 * Returns the new source created.
7225
7226 == [[LTN12.source.table()>>||anchor="HLTN12module"]] ==
7227
7228 **Prototype : **ltn12.source.table(table)
7229
7230 **Function: **Creates and returns a source that produces the numerically-indexed values of a ##table## successively beginning at 1. The source returns nil (end-of-stream) whenever a nil value is produced by the current index, which proceeds forward regardless.
7231
7232 **Parameters:**
7233
7234 * table: table data
7235
7236 **Return: **
7237
7238 * Returns the new source created.
7239
7240 = MIME module =
7241
7242 == [[mime.decode()>>||anchor="HMIMEmodule"]] ==
7243
7244 **Prototype : **
7245
7246 * mime.decode("base64")
7247 * mime.decode("quoted-printable")
7248
7249 **Function: **Returns a filter that decodes data from a given transfer content encoding.
7250
7251 **Parameters:**
7252
7253 * The two encoding formats above.
7254
7255 **Return: **
7256
7257 * Returns decoder filter.
7258
7259 == [[mime.encode()>>||anchor="HMIMEmodule"]] ==
7260
7261 **Prototype : **
7262
7263 * mime.encode("base64")
7264 * mime.encode("quoted-printable" [, mode])
7265
7266 **Function: **Returns a filter that encodes data according to a given transfer content encoding.
7267
7268 **Parameters:**
7269
7270 * mode(string): User can specify whether the data is textual or binary, by passing the mode strings "text" or "binary". Mode defaults to "text".
7271
7272 **Return: **
7273
7274 * Returns code filter.
7275
7276 **Note:**
7277
7278 * Although both transfer content encodings specify a limit for the line length, the encoding filters do not break text into lines (for added flexibility). Below is a filter that converts binary data to the Base64 transfer content encoding and breaks it into lines of the correct size.
7279
7280 == [[mime.normalize()>>||anchor="HMIMEmodule"]] ==
7281
7282 **Prototype : **mime.normalize([marker])
7283
7284 **Function: **Converts most common end-of-line markers to a specific given marker.
7285
7286 **Parameters:**
7287
7288 * marker(string):  The new marker. It defaults to CRLF. This is the standard end-of-line tag defined by MIME standards.
7289
7290 **Return: **
7291
7292 * returns a filter that performs the conversion
7293
7294 == [[mime.stuff()>>||anchor="HMIMEmodule"]] ==
7295
7296 **Prototype : **mime.stuff()
7297
7298 **Function: **Creates and returns a filter that performs stuffing of SMTP messages.
7299
7300 **Parameters**: None
7301
7302 **Return: **
7303
7304 * Returns a filter that performs stuffing of SMTP messages.
7305
7306 **Note: **
7307
7308 * The smtp.send function uses this filter automatically. You don't need to chain it with your source, or apply it to your message body.
7309
7310 == [[mime.wrap()>>||anchor="HMIMEmodule"]] ==
7311
7312 **Prototype : **
7313
7314 * mime.wrap("text" [, length])
7315 * mime.wrap("base64")
7316 * mime.wrap("quoted-printable")
7317
7318 **Function: **Returns a filter that breaks data into lines.
7319
7320 **Parameters**:
7321
7322 * length(number):
7323
7324 **Return: **
7325
7326 * Returns a filter that performs stuffing of SMTP messages.
7327
7328 **Note: **
7329
7330 * The smtp.send function uses this filter automatically. You don't need to chain it with your source, or apply it to your message body.
7331
7332 == [[mime.b64()>>||anchor="HMIMEmodule"]] ==
7333
7334 **Prototype : ** A, B = mime.b64(C [, D])
7335
7336 **Function: **Low-level filter to perform Base64 encoding.
7337
7338 **Parameters**:
7339
7340 * C: String that needs to be encoded.
7341 * D: String 2 that needs to be encoded.
7342
7343 **Return: **
7344
7345 * ##A## is the encoded version of the largest prefix of ##C..D## that can be encoded unambiguously. B has the remaining bytes of ##C..D##, //before// encoding. If ##D## is ##**nil**##, ##A## is padded with the encoding of the remaining bytes of ##C##.
7346
7347 **Note: **
7348
7349 * The simplest use of this function is to encode a string into it's Base64 transfer content encoding. Notice the extra parenthesis around the call to ##mime.b64 ##to discard the second return value.
7350
7351 **Example**
7352
7353 {{code language="LUA"}}
7354 print((mime.b64("diego:password")))
7355 --> ZGllZ286cGFzc3dvcmQ=
7356 {{/code}}
7357
7358 == [[mime.dot()>>||anchor="HMIMEmodule"]] ==
7359
7360 **Prototype : **A, n = mime.dot(m [, B])
7361
7362 **Function: **Low-level filter to perform SMTP stuffing and enable transmission of messages containing the sequence "CRLF.CRLF".
7363
7364 **Parameters**:
7365
7366 * m: The data fast value used to determine whether the text concatenation belongs to the same block.
7367 * B: Data that needs to be populated.
7368
7369 **Return: **
7370
7371 * ##A## is the stuffed version of ##B##. '##n##' gives the number of characters from the sequence CRLF seen in the end of ##B##. '##m##' should tell the same, but for the previous chunk.
7372
7373 **Note: **
7374
7375 * The message body is defined to begin with an implicit CRLF. Therefore, to stuff a message correctly, the first ##m## should have the value 2.
7376
7377 **Example**
7378
7379 {{code language="LUA"}}
7380 print((string.gsub(mime.dot(2, ".\r\nStuffing the message.\r\n.\r\n."), "\r\n", "\\n")))
7381 --> ..\nStuffing the message.\n..\n..
7382 {{/code}}
7383
7384 == [[mime.eol()>>||anchor="HMIMEmodule"]] ==
7385
7386 **Prototype : **A, B = mime.eol(C [, D, marker])
7387
7388 **Function: **Low-level filter to perform end-of-line marker translation.
7389
7390 **Parameters**:
7391
7392 * C: C is the ASCII value of the last character of the previous chunk, if it was a candidate for line break, or 0 otherwise.
7393 * D: D Is the block data that needs to be translated
7394 * marker: the new end-of-line marker and defaults to CRLF.
7395
7396 **Return: **
7397
7398 * ##A:T##he translated version of ##D##.
7399 * ##B## is the same as ##C##, but for the current chunk.
7400
7401 **Example**
7402
7403 {{code language="LUA"}}
7404 -- translates the end-of-line marker to UNIX
7405 unix = mime.eol(0, dos, "\n")
7406 {{/code}}
7407
7408 == [[mime.qp()>>||anchor="HMIMEmodule"]] ==
7409
7410 **Prototype : **A, B = mime.qp(C [, D, marker])
7411
7412 **Function: **Low-level filter to perform Quoted-Printable encoding.
7413
7414 **Parameters**:
7415
7416 * ##A## is the encoded version of the largest prefix of ##C..D## that can be encoded unambiguously. ##B## has the remaining bytes of ##C..D##, //before// encoding. If ##D## is ##**nil**##, ##A## is padded with the encoding of the remaining bytes of ##C##. Throughout encoding, occurrences of CRLF are replaced by the ##marker##, which itself defaults to CRLF.
7417
7418 **Return: None**
7419
7420 **Note: **
7421
7422 * The simplest use of this function is to encode a string into it's Quoted-Printable transfer content encoding. Notice the extra parenthesis around the call to ##mime.qp##, to discard the second return value.
7423
7424 == [[mime.qpwrp()>>||anchor="HMIMEmodule"]] ==
7425
7426 **Prototype : **A, m = mime.qpwrp(n [, B, length])
7427
7428 **Function: **Low-level filter to break Quoted-Printable text into lines.
7429
7430 **Parameters**:
7431
7432 * n: The number of bytes remaining in the first line
7433 * B: Data block
7434 * length: The length of the line, defaults to 76.
7435
7436 **Return: **
7437
7438 * ##A:## a copy of ##B.##
7439 * ##m: ##Returns the number of bytes left in the last line of ##A##.
7440
7441 **Note: **
7442
7443 * Besides breaking text into lines, this function makes sure the line breaks don't fall in the middle of an escaped character combination. Also, this function only breaks lines that are bigger than ##length## bytes.
7444
7445 == [[mime.unb64()>>||anchor="HMIMEmodule"]] ==
7446
7447 **Prototype : **A, B = mime.unb64(C [, D])
7448
7449 **Function: **Low-level filter to perform Base64 decoding.
7450
7451 **Parameters**:
7452
7453 * C: Data block 1
7454 * D: Data block 2
7455
7456 **Return: **
7457
7458 * ##A## is the decoded version of the largest prefix of ##C..D## that can be decoded unambiguously. ##B## has the remaining bytes of ##C..D##, //before// decoding. If ##D## is ##**nil**##, ##A## is the empty string and ##B## returns whatever couldn't be decoded.
7459
7460 **Note: **
7461
7462 * The simplest use of this function is to decode a string from it's Base64 transfer content encoding. Notice the extra parenthesis around the call to ##mime.unqp##, to discard the second return value.
7463
7464 **Example**
7465
7466 {{code language="LUA"}}
7467 print((mime.unb64("ZGllZ286cGFzc3dvcmQ=")))
7468 --> diego:password
7469 {{/code}}
7470
7471 == [[mime.unqp()>>||anchor="HMIMEmodule"]] ==
7472
7473 **Prototype : **A, B = mime.unqp(C [, D])
7474
7475 **Function: **Low-level filter to remove the Quoted-Printable transfer content encoding from data.
7476
7477 **Parameters**:
7478
7479 * C: Code block 1
7480 * D: Code block 2
7481
7482 **Return: **
7483
7484 * ##A## is the decoded version of the largest prefix of ##C..D## that can be decoded unambiguously. ##B## has the remaining bytes of ##C..D##, //before// decoding. If ##D## is ##**nil**##, ##A## is augmented with the encoding of the remaining bytes of ##C##.
7485
7486 **Note: **
7487
7488 * The simplest use of this function is to decode a string from it's Quoted-Printable transfer content encoding. Notice the extra parenthesis around the call to ##mime.unqp##, to discard the second return value.
7489
7490 **Example**
7491
7492 {{code language="LUA"}}
7493 print((mime.qp("ma=E7=E3=")))
7494 --> ma??
7495 {{/code}}
7496
7497 == [[mime.wrp()>>||anchor="HMIMEmodule"]] ==
7498
7499 **Prototype : **A, m = mime.wrp(n [, B, length])
7500
7501 **Function: **Create a low-level filter that uses CRLF tags to split text into several lines.
7502
7503 **Parameters**:
7504
7505 * n: The number of bytes remaining in the first line
7506 * B: Code block 2
7507 * length: The length of the line, defaults to 76.
7508
7509 **Return: **
7510
7511 * ##A## is a copy of ##B##, broken into lines of at most ##length## bytes (defaults to 76). '##n##' should tell how many bytes are left for the first line of ##B## and '##m##' returns the number of bytes left in the last line of ##A##.
7512
7513 **Note: **
7514
7515 * This function only breaks lines that are bigger than ##length## bytes. The resulting line length does not include the CRLF marker.
7516
7517 = Appendix =
7518
7519 == ftp command list ==
7520
7521 **Access commands**
7522
7523 |=Command|=Format|=Instruction
7524 |USER|USER|Specifies the login user name for authentication.
7525 |PASS|PASS|Specifies the user password, which must be followed by the login user name command
7526 |REIN|REIN|Reinitialize the user information. This command terminates the transfer of the current USER and the data being transferred, and then resets all parameters and enables the control connection so that the USER command occurs again on the client.
7527 |QUIT|QUIT|Disable the connection to the server
7528
7529 **Mode setting command**
7530
7531 |=Command|=Format|=Instruction
7532 |PASV|PASV|This command tells the FTP server to listen on the specified data port and passively accept requests from clients. If no mode is specified, the FTP server uses PASV mode by default.
7533 |PORT|PORT|This command tells the FTP server that the port number monitored by the client is address, and enables the FTP server to connect to the client in active mode.
7534 |TYPE|TYPE|This command specifies the data type to be transferred: ASCII and BINARY.
7535 |MODE|MODE|The command specifies the transmission mode. S denotes stream, B denotes block, and C denotes compression.
7536
7537 **File manegement command**
7538
7539 |=Command|=Format|=Instruction
7540 |CWD|CWD|Change the working directory; This command allows users to work in different directories or data sets without changing their login information. Directory is usually a directory name or a collection of files related to the system.
7541 |PWD|PDW|Returns the current working directory.
7542 |MKD|MKD|Creates a new directory in the specified path. Directory is a string for a specific directory.
7543 |CDUP|CDUP|Returns to the upper-layer directory.
7544 |RMD|RMD|Deletes a specified directory. Directory is a string representing a specific directory.
7545 |LIST|LIST|Returns a list of subdirectories and files under the specified path. Name is the path. If the path is omitted, the list of files in the current path is returned.
7546 |NLST|NLST|Returns a list of directories under the specified path. If the path is omitted, the current directory is returned.
7547 |RNFR|RNFR|Renames the file, and the next command in this command specifies the new file name with RNTO.
7548 |RNTO|RNTO|This command works with the RNFR command to rename a file.
7549 |DELE|DELE|Used to delete files in the specified path.
7550
7551 **File tranfer command**
7552
7553 |=Command|=Format|=Instruction
7554 |RETR|RETR|Downloads the file in the specified path
7555 |STOR|STOR|Uploads a specified file and stores it in the specified location. If the file already exists, the original file will be overwritten. If the file does not exist, a new file will be created.
7556 |SYST|SYST|Returns to the operating system used by the server
7557
7558 == ftp common response code ==
7559
7560 |=(((
7561 Response Code
7562 )))|=Meaning
7563 |110|Restart the token repl. In this case the text is deterministic, it must be MARK yyyy=mmmm. YYYY is the user process data flow marker and MMMM is the server marker.
7564 |120|Service is ready in N minutes
7565 |125|Data connection open, ready for transfer
7566 |150|The file is in good condition and will open a data connection
7567 |200|Command successful
7568 |202|Command not executed
7569 |211|System status or system help response
7570 |212|Directory status reply
7571 |213|File status reply
7572 |214|Help message Reply
7573 |215|System type reply
7574 |220|Service is ready
7575 |221|The service closes the control connection and can log out
7576 |225|Data connection open, no transfer in progress
7577 |226|Closed data connection. Requested file operation succeeded
7578 |227|In passive mode
7579 |230|User logged in
7580 |250|Requested file action completed
7581 |257|Create pathname
7582 |331|Correct user name, password required
7583 |332|Account information is required for login
7584 |350|The requested file operation requires further command
7585 |421|Unable to provide service, close control connection
7586 |425|Unable to open data link
7587 |426|Close the connection and terminate the transmission
7588 |450|Unavailable file
7589 |451|Requested action aborted: local error
7590 |452|Requested action not performed: Insufficient system storage space
7591 |500|Invalid command
7592 |501|syntax error
7593 |502|The command was not executed
7594 |503|Command order error
7595 |504|Invalid command parameter
7596 |530|Not logged in
7597 |532|Account information is required to store files
7598 |550|Requested action not performed
7599 |551|Request action aborted: unknown page type
7600 |552|Requested file action aborted: storage allocation overflowed
7601 |553|Requested action not performed: filename is invalid
7602
7603 = LuaSqlite module =
7604
7605 **Introduction**
7606
7607 * Luasqlite is a third-party library of Lua that provides lua operations on sqLite databases.
7608 * Luasqlite is a built-in module that can be used without reference. Module name is luasql_sqlite3.
7609 * It is roughly divided into three parts: SQLite environment Settings, database file operations, database file cursor operations.
7610 * Since sqLite's extensive read and write operations shorten Flash life, database files can only be created on Udisk or SD cards.
7611
7612 **Get sqlite environment**
7613
7614 {{{env = luasql_sqlite3.sqlite3()
7615 }}}
7616
7617 **sqlite environment operation**
7618
7619 {{code language="LUA"}}
7620 -- sqlite environment
7621 env = luasql_sqlite3.sqlite3()
7622 {{/code}}
7623
7624 == **db file operation** ==
7625
7626 {{code language="LUA"}}
7627 ​​​-- Get objects in database files
7628
7629 env = luasql_sqlite3.sqlite3()-- Initialize the environment before obtaining the db file object
7630
7631 db = env:connect("udisk:test.db")-- Connect a db file
7632 {{/code}}
7633
7634 |=Function|=Introduction
7635 |[[db:close()>>||anchor="Hdb:close2829"]]|Close the database file
7636 |[[db:escape()>>||anchor="Hdb:escape2829"]]|Escape encoding of string data
7637 |[[db:execute()>>||anchor="Hdb:execute2829"]]|Execute the sql statement
7638 |[[db:commit()>>||anchor="Hdb:commit2829"]]|Commit the data to the database
7639 |[[db:rollback()>>||anchor="Hdb:rollback2829"]]|Roll back operations on the database before committing
7640 |[[db:setautocommit()>>||anchor="Hdb:setautocommit2829"]]|Set the automatic submission function
7641 |[[db:getlastautoid()>>||anchor="Hdb:getlastautoid2829"]]|Get the total number of data records for the current database +1
7642
7643 == **Cursor operation** ==
7644
7645 {{code language="LUA"}}
7646 -- Get cursor object
7647 env = luasql_sqlite3.sqlite3() -- Initialize the environment before obtaining the db file object
7648 db = env:connect("udisk:test.db") -- Connect a db file
7649
7650 cursor = db:execute([[select * from students]])
7651 {{/code}}
7652
7653 |=Function|=Introduction
7654 |[[cursor:close()>>||anchor="Hcursor:close2829"]]|Close the cursor
7655 |[[cursor:getcolnames()>>||anchor="Hcursor:getcolnames2829"]]|Get the name of the header
7656 |[[cursor:getcoltypes()>>||anchor="Hcursor:getcoltypes2829"]]|Get the type of the header
7657 |[[cursor:fetch()>>||anchor="Hcursor:fetch2829"]]|Similar to iterators, facilitate row nodes
7658
7659 = LuaSecure =
7660
7661 **Description**
7662
7663 This module provides common data verification algorithm function.
7664
7665 The name of the library is: secure, crc
7666
7667 **List**
7668
7669 |**Function**|**Features**
7670 |[[secure.md5string>>path:mk:@MSITStore:D:\WV%20Studio20230801\HmiHelp.chm::/leviⅡ/6/6.4/4.3LuaSecure.html#func1]]|Verify the string with md5 algorithm
7671 |[[secure.md5file>>path:mk:@MSITStore:D:\WV%20Studio20230801\HmiHelp.chm::/leviⅡ/6/6.4/4.3LuaSecure.html#func2]]|Verify the file with md5 algorithm
7672 |[[secure.sha>>path:mk:@MSITStore:D:\WV%20Studio20230801\HmiHelp.chm::/leviⅡ/6/6.4/4.3LuaSecure.html#func3]]|Verify the string with sha algorithm
7673 |[[secure.checksum>>path:mk:@MSITStore:D:\WV%20Studio20230801\HmiHelp.chm::/leviⅡ/6/6.4/4.3LuaSecure.html#func4]]|verify string with 8-bit checksum algorithm
7674 |[[secure.xor>>path:mk:@MSITStore:D:\WV%20Studio20230801\HmiHelp.chm::/leviⅡ/6/6.4/4.3LuaSecure.html#func5]]|verify string with 8-bit XOR checksum algorithm
7675 |[[crc.init>>path:mk:@MSITStore:D:\WV%20Studio20230801\HmiHelp.chm::/leviⅡ/6/6.4/4.3LuaSecure.html#func6]]|Initialization of luacrc checksum algorithm
7676 |[[crc.calc>>path:mk:@MSITStore:D:\WV%20Studio20230801\HmiHelp.chm::/leviⅡ/6/6.4/4.3LuaSecure.html#func7]]|Verify the string with crc algorithm
7677
7678 === **secure.md5string** ===
7679
7680 Prototype: md5string (data)
7681
7682 Function: Verify the string with md5 algorithm
7683
7684 Parameter:
7685
7686 * data (string): Data
7687
7688 Return:
7689
7690 * Success: Return 32-bit md5 encrypted data
7691 * Failure: nil
7692
7693 Example:
7694
7695 {{code}}
7696 print (secure.md5string ("test"))
7697 {{/code}}
7698
7699 **✎Note: When using MD5 encryption, the letters in the string to be encrypted need to be case-sensitive, but the contents of the ciphertext need not be case-sensitive.**
7700
7701 === **secure.md5file** ===
7702
7703 Prototype: md5file (path)
7704
7705 Function: Verify the file with md5 algorithm
7706
7707 Parameter:
7708
7709 * Path (string): File path
7710
7711 Return:
7712
7713 * Success: Return 32-bit file encrypted data
7714 * Failure: nil
7715
7716 Example:
7717
7718 {{code}}
7719 print(secure.md5file("udisk:test.txt"))
7720 {{/code}}
7721
7722 === **secure.sha** ===
7723
7724 Prototype: sha (data, length)
7725
7726 * data (string): Data
7727
7728 Function: Encrypt strings with sha algorithm
7729
7730 Parameter:
7731
7732 * Length (number): Output data length
7733 * Supported length: 160,256,384,512 (only these 4 fixed lengths are supported, and cannot be customized)
7734
7735 Return:
7736
7737 * Success: Corresponding length sha encrypted data
7738 * Failure: nil
7739
7740 Example:
7741
7742 {{code}}
7743 print (secure.sha ("test", 160))
7744 {{/code}}
7745
7746 === **secure.checksum** ===
7747
7748 Prototype: checksum (data, length)
7749
7750 Function: 16-bit checksum algorithm for string
7751
7752 Parameter:
7753
7754 * data (string): Data
7755 * Length (number): Data length
7756
7757 Return:
7758
7759 * Success: Return 16-bit checksum encrypted data
7760 * Failure: nil
7761
7762 Example:
7763
7764 {{code}}
7765 print (secure.checksum ("test", 4))
7766 {{/code}}
7767
7768 === **secure.xor** ===
7769
7770 Prototype: xor (data, length)
7771
7772 Function: 16-bit XOR checksum algorithm for string
7773
7774 Parameter:
7775
7776 * data (string): Data
7777 * Length (number): Data length
7778
7779 Return:
7780
7781 * Success: Return 16-bit xor encrypted data
7782 * Failure: nil
7783
7784 Example:
7785
7786 {{code}}
7787 print (secure.xor ("test", 4))
7788 {{/code}}
7789
7790 === **crc.init** ===
7791
7792 Prototype: crc.init (parameter)
7793
7794 Function: Initialize crc check algorithm
7795
7796 Parameter:
7797
7798 * parameter (table): Parameter list, the required parameters are as follows:
7799 ** name (string): Parameter model name (Example: crc8, crc16_arc, crc32, etc.)
7800 ** width (number): Width, that is, the number of CRC bits.
7801 ** poly (number) (Hexadecimal): Abbreviations for generated items, expressed in hexadecimal.
7802 ** init (number) (Hexadecimal): This is the initialization preset value of the register (crc) when the algorithm starts, which is expressed in hexadecimal.
7803 ** xorout (number) (Hexadecimal): The final CRC value is obtained after the calculation result is exclusive or with this parameter.
7804 ** refin (number): Whether each byte of the data under test is inverted bitwise. 1 is true and 0 is false.
7805 ** refout (number): Whether the whole data is inverted bitwise after calculation and before XOR output, 1 is true and 0 is false.
7806
7807 Return:
7808
7809 * Success: crc object
7810 * Failure: nil
7811
7812 === **crc.calc** ===
7813
7814 Prototype: crc.calc (lcrc, data)
7815
7816 Function: Calculate the results after crc , which should be used in conjunction with crc.init.
7817
7818 Parameter:
7819
7820 * lcrc: crc object
7821 * data (string): Data
7822
7823 Return:
7824
7825 * Success: Return crc encrypted data
7826 * Failure: nil
7827
7828 Example:
7829
7830 {{code}}
7831 local crc = require("crc")local parameter={name="crc32",width=32,poly=0x04C11DB7,init=FFFFFFFF,xorout=FFFFFFFF,refin=1,refout=1}
7832 lcrc = crc.init(parameter)if lcrc ~= nil
7833 result,err= lcrc.calc(lcrc,"123456789")print(result)
7834
7835 {{/code}}
7836
7837 **Appendix**
7838
7839 Some common crc initialization parameters and their output results.
7840
7841 |**Algorithm**|**Poly**|**Init**|**XorOut**|**RefIn**|**RefOut**|**Input**|**Result**
7842 |crc8|0x07|0x00|0x00|false|false|123456789|0xF4
7843 |crc16_arc|0x8005|0x0000|0x0000|true|true|123456789|0xBB3D
7844 |crc32|0x04C11DB7|0xFFFFFFF|0xFFFFFFF|true|true|123456789|0xCBF43926
7845
7846 = LuaUserSecure =
7847
7848 == user_secure.usersecure_getInfo ==
7849
7850 **Prototype : **user_secure.usersecure_getInfo()
7851
7852 **Function: **Get all user information
7853
7854 **Return: **
7855
7856 * Success: User data table
7857 * Failure: Returns nil
7858
7859 **Example**
7860
7861 {{code language="LUA"}}
7862 secure = user_secure.usersecure_getInfo()
7863 for index,j in pairs(secure) do
7864 for msg,value in pairs(j) do
7865 if "permission" == msg then
7866 print("index",index,"msg",msg,"value",table.concat(value,','))
7867 else
7868 print("index",index,"msg",msg,"value",value)
7869 end
7870
7871 end
7872 end
7873
7874 {{/code}}
7875
7876 == user_secure.usersecure_addInfo ==
7877
7878 **Prototype : **user_secure.usersecure_addInfo(username, password, supassword, desc, hide, permission)
7879
7880 **Function: **Add user information
7881
7882 **Parameters**:
7883
7884 * username(string): New username (16 characters)
7885 * password(string): Password (8 characters)
7886 * supassword(string): Confirm password (8 characters)
7887 * desc(string): Description (10 characters)
7888 * hide(bool): Controls hiding; true: hide if insufficient permissions
7889 * permission(table): Permissions; 1 for granted permissions, 0 for no permissions
7890
7891 **Return: **
7892
7893 * Success: Return 0
7894 * Failure: Returns nil
7895
7896 **Example**
7897
7898 {{code language="LUA"}}
7899 tab = {0,1,1,1,1,1,1,1,1,1,1,1}
7900 user_secure.usersecure_addInfo("user1","123","123","user1",false,"tab")
7901 {{/code}}
7902
7903 == user_secure.usersecure_deleteInfo ==
7904
7905
7906 **Prototype : **user_secure.usersecure_deleteInfo(username)
7907
7908 **Function: **Delete user information
7909
7910 **Parameters**:
7911
7912 * username
7913
7914 **Return: **
7915
7916 * Failure: Returns nil
7917
7918 **Example**
7919
7920 {{code language="LUA"}}
7921 ret, msg = user_secure.usersecure_deleteInfo("user1")
7922 {{/code}}
7923
7924 == user_secure.usersecure_updatepermission ==
7925
7926
7927 **Prototype : **user_secure.usersecure_updatepermission(username, permission)
7928
7929 **Function: **Modify permissions
7930
7931 **Parameters**:
7932
7933 * username
7934 * permission(table): Permissions; 1 for granted permissions, 0 for no permissions
7935
7936 **Return: **
7937
7938 * Failure: Returns nil
7939
7940 **Example**
7941
7942 {{code language="LUA"}}
7943 tab = {0,1,1,1,1,1,1,1,1,1,1,1}
7944 ret, msg =user_secure.usersecure_updatepermission("user1","tab")
7945 {{/code}}
7946
7947 == user_secure.usersecure_login ==
7948
7949 **Prototype : **user_secure.usersecure_login(username,pwd)
7950
7951 **Function: **User login
7952
7953 **Parameters**:
7954
7955 * username
7956 * pwd: password
7957
7958 **Return: **
7959
7960 * Failure: Returns nil
7961
7962 **Example**
7963
7964 {{code language="LUA"}}
7965 ret, msg = user_secure.usersecure_login("user1", "123")
7966 {{/code}}
7967
7968
7969 == user_secure.usersecure_logout ==
7970
7971 == user_secure.usersecure_updatepwd ==
7972
7973 = LuaChart =
7974
7975 == chart.setAlarmBtnSpacing ==
7976
7977 **Prototype : **user_secure.usersecure_getInfo()
7978
7979 **Function: **Connect to a DB file.(If the file does not exist)
7980
7981 **Parameters**:
7982
7983 * dbFilePath (string): Full path to the DB file to connect to (create)
7984
7985 **Return: **
7986
7987 * Success: database object
7988 * Failure: Returns nil and error.
7989
7990 **Example**
7991
7992 {{code language="LUA"}}
7993 sql = require "Luasqlite" -- Introducing the lua libraries  
7994 env = sql.sqlite3() -- Get the environment class
7995 {{/code}}
7996
7997 == chart.setAlarmBtnScale ==
7998
7999 == chart.setFormulaBtnSpacing ==
8000
8001 == chart.setFormulaBtnScale ==
8002
8003 == chart.setBarChartBtnSpacing ==
8004
8005 == chart.setBarChartBtnScale ==
8006
8007 = Environment operation =
8008
8009 (% class="wikigeneratedid" id="HGetsqliteenvironment" %)
8010 **Get sqlite environment**
8011
8012 {{code language="LUA"}}
8013 sql = require "Luasqlite" -- Introducing the lua libraries  
8014 env = sql.sqlite3() -- Get the environment class
8015 {{/code}}
8016
8017 == env:connect() ==
8018
8019 **Prototype : **env:connect(dbFilePath)
8020
8021 **Function: **Connect to a DB file.(If the file does not exist)
8022
8023 **Parameters**:
8024
8025 * dbFilePath (string): Full path to the DB file to connect to (create)
8026
8027 **Return: **
8028
8029 * Success: database object
8030 * Failure: Returns nil and error.
8031
8032 **Example**
8033
8034 {{code language="LUA"}}
8035 env = luasql_sqlite3.sqlite3()-- Get the environment class
8036 db = env:connect("udisk:test.db") -- Connect to a DB file
8037 db:close()-- Close the db Connection
8038 env:close()-- Close the database environment
8039 {{/code}}
8040
8041 == env:close() ==
8042
8043 **Prototype : **env:close()
8044
8045 **Function: **Close the environment
8046
8047 **Parameters**: None
8048
8049 **Return: **None
8050
8051 **Example**
8052
8053 {{code language="LUA"}}
8054 env = luasql_sqlite3.sqlite3()-- Get the environment class
8055 db = env:connect("udisk:test.db") -- Connect to a DB file
8056 db:close()-- Close the db Connection
8057 env:close()-- Close the database environment
8058 {{/code}}
8059
8060 = db file operation =
8061
8062 == [[db:close()>>||anchor="Hdbfileoperation"]] ==
8063
8064 **Prototype : **db:close()
8065
8066 **Function: **Close connection
8067
8068 **Parameters**: None
8069
8070 **Return: **None
8071
8072 **Example**
8073
8074 {{code language="LUA"}}
8075 env = luasql_sqlite3.sqlite3()-- Get the environment class
8076 db = env:connect("udisk:test.db") -- Connect to a DB file
8077 db:close()-- Close the db Connection
8078 env:close()-- Close the database environment
8079 {{/code}}
8080
8081 == [[db:escape()>>||anchor="Hdbfileoperation"]] ==
8082
8083 **Prototype : **db:escape(szValue)
8084
8085 **Function: **Connect to a DB file.(If the file does not exist)
8086
8087 **Parameters**:
8088
8089 * szValue(string): The string that needs to be encoded
8090
8091 **Return: **
8092
8093 * string: Converted string
8094
8095 **Example**
8096
8097 {{code language="LUA"}}
8098 local env = luasql_sqlite3.sqlite3() -- Get the environment class
8099 local db = env:connect("udisk:test.db") -- Connect to a DB file
8100
8101 strSql=db:escape("INSERT INTO student values(1,'lili')")
8102
8103 db:close() -- Close the db Connection
8104 env:close() -- Close the database environment
8105 -- printout: INSERT INTO student values(1,"lili")
8106 {{/code}}
8107
8108 == [[db:execute()>>||anchor="Hdbfileoperation"]] ==
8109
8110 **Prototype : **db:execute(sql)
8111
8112 **Function: **execute a SQL statement
8113
8114 **Parameters**:
8115
8116 * SQL statement executed
8117
8118 **Return: **It depends on the type of SQL
8119
8120 * If the information is retrieved from a database, the return value is a user-defined data object. (Extracted target data)
8121 * If the statement is a non-fetch data type, return a status to verify that whether the SQL statement was successfully executed
8122
8123 **Example**
8124
8125 {{code language="LUA"}}
8126 local env = luasql_sqlite3.sqlite3() -- Get the environment class
8127 local db = env:connect("udisk:test.db") -- Connect to a DB file.
8128
8129 local status=db:execute("CREATE TABLE students('id' TEXT,'name' TEXT)") -- Create a table "student"
8130 status=db:execute("INSERT INTO students values('1','AA')") -- Insert information  1 AA
8131 status=db:execute("INSERT INTO students values('2','BB')") -- Insert information  2 BB
8132 status=db:execute("INSERT INTO students values('3','CC')") -- Insert information  3 CC
8133 status=db:execute([[UPDATE students SET name = 'DD' WHERE id = '3']]) -- Update information 
8134 status=db:execute([[DELETE FROM students WHERE id='2']]) -- Delete statement
8135 local cursor=db:execute("SELECT * FROM students") --Query the database
8136
8137 local row = cursor:fetch({},"a")
8138 while row do
8139 print(row.id,row.name)
8140 row = cursor:fetch({},"a")
8141 end
8142 cursor:close()
8143 db:close()
8144 env:close()
8145 ----------Output----------:
8146 {{/code}}
8147
8148 == [[db:commit()>>||anchor="Hdbfileoperation"]] ==
8149
8150 **Prototype : **db:commit()
8151
8152 **Function: **Commit data to the database (executing the execture () function simply stores the data into memory, automatically commit by default (can be set))
8153
8154 **Parameters**: None
8155
8156 **Return:** None
8157
8158 **Example**
8159
8160 {{code language="LUA"}}
8161 local env = luasql_sqlite3.sqlite3() -- Get the environment class
8162 local db = env:connect("udisk:test.db") -- Connect a db file
8163
8164 local status=db:execute("CREATE TABLE students('id' TEXT,'name' TEXT)") -- Create a table "student"
8165 status=assert(db:setautocommit(false)) -- Set non-auto commit
8166 status=assert(db:execute("INSERT INTO students values('4','AA')")) -- Insert information 4 AA
8167 status=assert(db:execute("INSERT INTO students values('5','BB')")) -- Insert information 5 BB
8168 status=assert(db:execute("INSERT INTO students values('6','CC')")) -- Insert information 6 CC
8169
8170 --statue=assert(db:commit()) -- Manually commit the database
8171 --while 1 do
8172 --At this point, cut out and view the database content, you will find that the data is not commited to the database
8173 --Put the commit() function in front of the dead loop and re-verify that the data has been updated into the database
8174 --end
8175 statue=assert(db:commit()) -- Manually commit the database
8176
8177 db:close()
8178 {{/code}}
8179
8180 == [[db:rollback()>>||anchor="Hdbfileoperation"]] ==
8181
8182 **Prototype : **db:rollback()
8183
8184 **Function: **Roll back operations on the database until before commit
8185
8186 **Parameters**: None
8187
8188 **Return:** None
8189
8190 **Exmaple:**
8191
8192 {{code language="LUA"}}
8193 local env = luasql_sqlite3.sqlite3() -- Get the environment class
8194 local db = env:connect("udisk:test.db") -- Connect a db file
8195
8196 local status=db:execute("CREATE TABLE students('id' TEXT,'name' TEXT)") -- Create a table "student" 
8197 local status=assert(db:setautocommit(false)) -- Manually commit the database
8198 status=assert(db:execute("INSERT INTO students values('7','AA')")) -- Insert information 7 AA
8199 statue=assert(db:commit()) -- Commit
8200 status=assert(db:execute("INSERT INTO students values('8','BB')")) -- Insert information 8 BB
8201 statue=assert(db:rollback()) -- Rollback
8202 status=assert(db:execute("INSERT INTO students values('9','CC')")) -- Insert information 9 CC
8203 statue=assert(db:commit()) -- Commit
8204
8205 db:close()
8206 env:close()
8207 ------------------------------------------------------------
8208 -- Only 7 and 9 are inserted in the final result because after 8 we roll back the operation to before commit.
8209 {{/code}}
8210
8211 == [[db:setautocommit()>>||anchor="Hdbfileoperation"]] ==
8212
8213 **Prototype : **db:setautocommit( flag )
8214
8215 **Function: **Set the automatic commit function
8216
8217 **Parameters**:
8218
8219 * flag(boolean) : Whether to set auto-commit
8220 ** true —— auto-commit
8221 ** false —— Commit mannully
8222
8223 **Return:** None
8224
8225 **Exmaple:**
8226
8227 {{code language="LUA"}}
8228 env = luasql_sqlite3.sqlite3() -- Get the environment class
8229 db = env:connect("udisk:test.db") -- Connect a db file
8230
8231 status=assert(db:setautocommit(false)) -- Set non-auto commit
8232 status=assert(db:execute("INSERT INTO students values('10','AA')")) -- Insert information 10 AA
8233 statue=assert(db:commit()) -- Commit
8234 status=assert(db:execute("INSERT INTO students values('11','BB')")) -- Insert information 11 BB
8235 statue=assert(db:rollback()) -- Rollback
8236
8237 status=assert(db:setautocommit(true)) -- Set non-auto commit
8238 status=assert(db:execute("INSERT INTO students values('12','CC')")) -- Insert information 12 CC
8239 statue=assert(db:rollback()) -- Rollback
8240 statue=assert(db:commit()) -- Commit
8241
8242 cursor:close()
8243 db:close()
8244 env:close()
8245 ------------------------------------------
8246 --By comparing the two rollbacks and combining the information actually written to the database (11 is not written to the database, 12 is written to the database)
8247 --You can see that setting automatic commit as it literally means, commits to the database after the SQL statement is executed.
8248 --(ps: The flash of embedded machine has a life limit. To increase the service life, the operation frequency of flash should be reduced as much as possible)
8249 {{/code}}
8250
8251 == [[db:getlastautoid()>>||anchor="Hdbfileoperation"]] ==
8252
8253 **Prototype : **db:getlastautoid()
8254
8255 **Function: **Gets the total number of data records for the current database
8256
8257 **Parameters**: None
8258
8259 **Return:** Total number of data records (number)
8260
8261 **Exmaple:**
8262
8263 {{code language="LUA"}}
8264 local env = luasql_sqlite3.sqlite3() -- Get the environment class
8265 local db = env:connect("udisk:test.db") -- Connect a db file
8266
8267 local status=db:execute("CREATE TABLE students('id' TEXT,'name' TEXT)") -- Create a table "student" 
8268 status=assert(db:execute("INSERT INTO students values('1','AA')")) -- Insert information 1 AA
8269 status=assert(db:execute("INSERT INTO students values('2','BB')")) -- Insert information 2 BB
8270 status=assert(db:execute("INSERT INTO students values('3','CC')")) -- Insert information 3 CC
8271 status=assert(db:getlastautoid())
8272 print(type(status),status) -- number 4.0
8273
8274 db:close()
8275 env:close()
8276 {{/code}}
8277
8278 = Cursor operation =
8279
8280 == [[cursor:close()>>||anchor="HCursoroperation"]] ==
8281
8282 **Prototype : **cursor:close()
8283
8284 **Function: **Close the cursor
8285
8286 **Parameters**: None
8287
8288 **Return:** None
8289
8290 **Exmaple: **
8291
8292 {{{cursor:close()
8293 }}}
8294
8295 == [[cursor:getcolnames()>>||anchor="HCursoroperation"]] ==
8296
8297 **Prototype : **cursor:getcolnames()
8298
8299 **Function: **Gets the name of the header
8300
8301 **Parameters**: None
8302
8303 **Return:** Header (table): the database table header
8304
8305 **Exmaple: **
8306
8307 {{code language="LUA"}}
8308 local env = luasql_sqlite3.sqlite3() -- Get the environment class
8309 local db = env:connect("udisk:test.db") -- Connect a db file
8310
8311 local status=db:execute("CREATE TABLE students('id' TEXT,'name' TEXT)")
8312 local cursor,errorString = db:execute([[select * from students]])
8313 local colNmaes=cursor:getcolnames()
8314 for i,v in ipairs(colNmaes) do
8315 print(v)
8316 end
8317
8318 cursor:close()
8319 db:close()
8320 env:close()
8321 --------------Output
8322 --id
8323 --name
8324 {{/code}}
8325
8326 == [[cursor:getcoltypes()>>||anchor="HCursoroperation"]] ==
8327
8328 **Prototype : **cursor:getcoltypes()
8329
8330 **Function: **Gets the type of the header
8331
8332 **Parameters**: None
8333
8334 **Return:**
8335
8336 * headerType(table): Returns a table containing header type information
8337
8338 **Exmaple: **
8339
8340 {{code language="LUA"}}
8341 local env = luasql_sqlite3.sqlite3() --Get the environment class
8342 local db = env:connect("udisk:test.db") --Connect a db file
8343
8344 local status=db:execute("CREATE TABLE students('id' TEXT,'name' TEXT)")
8345 status=db:execute("INSERT INTO students values('1','AA')") --Insert information 1 AA
8346 status=db:execute("INSERT INTO students values('2','BB')") --Insert information 2 BB
8347 status=db:execute("INSERT INTO students values('3','CC')") --Insert information 3 CC
8348 local cursor,errorString = assert(db:execute([[select * from students]]))
8349
8350 local colTypes = cursor:getcoltypes()
8351 for i,v in ipairs(colTypes) do
8352 print(i,v)
8353 end
8354
8355 cursor:close()
8356 db:close()
8357 env:close()
8358 ----------Output
8359 --1 TEXT
8360 --2 TEXT
8361 {{/code}}
8362
8363 == [[cursor:fetch()>>||anchor="HCursoroperation"]] ==
8364
8365 **Prototype : **cursor:fetch(tab, opt)
8366
8367 **Function: **Facilitate row nodes (Similar to iterators)
8368
8369 **Parameters**:
8370
8371 * tab(table) : Row node
8372 * (((
8373 opt(string):
8374
8375 "n" —— The index of the table is the header of the table, column id
8376
8377 "a" —— The index of the table is the header of the table, column value
8378 )))
8379
8380 **Return:**
8381
8382 * row(table) :  Get the extracted data
8383
8384 **Exmaple:**
8385
8386 {{code language="LUA"}}
8387 local env = luasql_sqlite3.sqlite3() -- Get the environment class
8388 local db = env:connect("udisk:test.db") -- Connect a db file
8389
8390 local status = db:execute("CREATE TABLE students('id' TEXT,'name' TEXT)")
8391 status = assert(db:execute([[INSERT INTO students values('1','AA')]]))
8392 status = assert(db:execute([[INSERT INTO students values('2','BB')]]))
8393 status = assert(db:execute([[INSERT INTO students values('3','CC')]]))
8394
8395 local cursor = assert(db:execute([[select * from students]]))
8396
8397 local row = cursor:fetch({},"a")
8398 print(string.format("id = %s name = %s ",row.id,row.name)) -- Index by table header name
8399
8400 row = cursor:fetch({},"n")
8401 print(string.format("id = %s name = %s ",row[1], row[2])) -- Index by numerical number
8402
8403
8404 cursor:close()
8405 db:close()
8406 env:close()
8407 ----------Output:
8408 --id = 1 , name = AA
8409 --id = 2 , name = BB
8410 {{/code}}
8411
8412 = TTS =
8413
8414 **Description**
8415
8416 The library name is: TTS
8417
8418 (% class="box infomessage" %)
8419 (((
8420 Note: When using this function, please check whether the OS version is greater than 2.2.45.20241029
8421 )))
8422
8423 |=Function|=Description
8424 |(((
8425 [[TTS.play>>doc:||anchor="HTTS.play"]]
8426 )))|(((
8427 Plays the specified sound; sets the number of times it is played.
8428 )))
8429 |(((
8430 [[TTS.textToSpeech>>doc:||anchor="HTTS.textToSpeech"]]
8431 )))|(((
8432 Converts text to voice and plays it; sets the number of times it is played
8433 )))
8434 |(((
8435 [[TTS.setVolume>>doc:||anchor="HTTS.setVolume"]]
8436 )))|(((
8437 Sets volume
8438 )))
8439 |(((
8440 [[TTS.pause>>doc:||anchor="HTTS.pause"]]
8441 )))|(((
8442 Pauses playback
8443 )))
8444 |(((
8445 [[TTS.resume>>doc:||anchor="HTTS.pause"]]
8446 )))|(((
8447 Continues playback
8448 )))
8449 |(((
8450 [[TTS.stop>>doc:||anchor="HTTS.stop"]]
8451 )))|(((
8452 Cancels the currently playing audio
8453 )))
8454
8455 == [[TTS.play>>doc:||anchor="HTTS"]] ==
8456
8457 Prototype: TTS.play(SoundName,PlayCount)
8458
8459 Function: Play the voice with the specified id; text to voice
8460
8461 SoundNane(string): sound name
8462
8463 PlayCount(number): number of plays
8464
8465 Return:
8466
8467 * Success: true
8468 * Failure: false
8469
8470 Example:
8471
8472 {{code language="Lua"}}
8473 -- Play the sound named "sound 1" once.
8474
8475 TTS.play("sound 1",1)
8476
8477 -- Play the sound named "sound 2" three times.
8478
8479 TTS.play("sound 2",3)
8480 {{/code}}
8481
8482 == [[TTS.textToSpeech>>doc:||anchor="HTTS"]] ==
8483
8484 Prototype: TTS.textToSpeech(Text,Priority,PlayCount)
8485
8486 Function: Text to voice
8487
8488 Text(string): Text content
8489
8490 Priority(number): Play priority
8491
8492 PlayCount(number): Play count
8493
8494 Return:
8495
8496 * Success: true
8497 * Failure: false
8498
8499 Example:
8500
8501 {{code language="Lua"}}
8502 -- Convert "Hello World!" to a voice file, set the sound priority, and play it once
8503 TTS.textToSpeech("Hello World!", 10, 1)
8504 {{/code}}
8505
8506 == [[TTS.setVolume>>doc:||anchor="HTTS"]] ==
8507
8508 Prototype: TTS.setVolume(Volume)
8509
8510 Function: Set volume
8511
8512 Volume (number): Volume value (0~~100)
8513
8514 Return:
8515
8516 * Success: true
8517 * Failure: false
8518
8519 Example:
8520
8521 {{code language="Lua"}}
8522 -- Set 50 volume
8523 TTS.setVolume(50)
8524 {{/code}}
8525
8526 == [[TTS.pause>>doc:||anchor="HTTS"]] ==
8527
8528 Prototype: TTS.pause()
8529
8530 Function: Pause playback
8531
8532 Return:
8533
8534 * Success: true
8535 * Failure: false
8536
8537 Example:
8538
8539 {{code language="Lua"}}
8540 --Pause playback
8541 TTS.pause()
8542 {{/code}}
8543
8544 == [[TTS.resume>>doc:||anchor="HTTS"]] ==
8545
8546 Prototype: TTS.resume()
8547
8548 Function: Continue playing
8549
8550 Return:
8551
8552 * Success: true
8553 * Failure: false
8554
8555 Example:
8556
8557 {{code language="Lua"}}
8558 --Continue playing
8559 TTS.resume()
8560 {{/code}}
8561
8562 == [[TTS.stop>>doc:||anchor="HTTS"]] ==
8563
8564 Prototype: TTS.stop()
8565
8566 Function: Cancel the currently playing audio, and do not continue to play
8567
8568 Return:
8569
8570 * Success: true
8571 * Failure: false
8572
8573 Example:
8574
8575 {{code language="Lua"}}
8576 --Stop playing
8577 TTS.stop()
8578 {{/code}}