欢迎图片

Wiki source code of Lua Script

Last modified by Devin Chen on 2025/11/10 16:04

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