欢迎图片

Wiki source code of Lua Script

Version 5.1 by xingzhi lin on 2025/09/24 10:41

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