欢迎图片

Wiki source code of Lua Script

Version 5.2 by xingzhi lin on 2025/10/31 09:57

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