Wiki source code of Lua Script

Version 3.2 by xingzhi lin on 2025/09/24 10:26

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