欢迎图片

Wiki source code of Lua Script

Version 3.3 by xingzhi lin on 2025/09/24 10:38

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