Wiki source code of 2 Script

Version 86.1 by Devin Chen on 2025/06/06 13:57

Show last authors
1 = **1 General Script Demo** =
2
3 == **1.1 Address Operation** ==
4
5 (((
6 Write/Read data from address A to B**. **For example:transfer D2 to D0
7 )))
8
9 (% style="text-align:center" %)
10 [[image:1624245865976-320.png||height="182" width="1000" class="img-thumbnail"]]
11
12 Depend on diffferent format of data.V-Box use different script functions.
13 for example. addr_setshort(addr,num) Function: Write 16-bit signed decimal address
14 addr_getshort(addr) Function:Read 16-bit signed decimal address
15 addr_getword(string addr)Function: Read 16-bit unsigned decimal address
16 More script function are in the second section of [[“V-BOX Script Interface Manual”>>doc:V-BOX.V-Net.Manual.04 Lua Script.01 Lua Functions.WebHome]]
17
18 == **1.2 Arithmetic** ==
19
20 (% style="text-align:center" %)
21 [[image:1624249623612-177.png||height="337" width="400" class="img-thumbnail"]]
22
23 == **1.3 Set 100 to D0~-~-D19** ==
24
25 (% style="text-align:center" %)
26 [[image:1624249693457-742.png||height="135" width="400" class="img-thumbnail"]]
27
28 == **1.4 Short message** ==
29
30 The following demo shows that when the alarm condition is reached: temp1 > 5 & temp2 >10 & temp3 < 20(lasts more than 5 seconds) , then send an "alarm trigger" sms.
31
32 When the alarm condition is released,then send an  "alarm release" sms. Script is as below:
33
34 {{code language="lua"}}
35 function sms.main()
36 ------send condition------
37 local temp1 = addr_getword("@Temperature1")
38 local temp2 = addr_getword("@Temperature2")
39 local temp3 = addr_getword("@Temperature3")
40 local timer = addr_getword("@Timer")
41 local tag = addr_getbit("@Tag")
42 ------lasting time------
43 if temp1 > 5 and temp2 > 10 and temp3 < 20 then
44 timer = timer + 1
45 addr_setword("@Timer",timer)
46 else
47 timer = 0
48 addr_setword("@Timer",timer)
49 end
50 ------send sms & output Y0------
51 if timer > 5 then
52 if tag == 0 then
53 send_sms_ira("19859254700","alarm trigger")
54 addr_setbit("@Tag",1)
55 end
56 elseif tag == 1 then
57 send_sms_ira("19859254700","alarm release")
58 addr_setbit("@Tag",0)
59 end
60 end
61 {{/code}}
62
63 == **1.5 Telegram notification** ==
64
65 This example shows how to use the Bot API to send message into Telegram group or channel. When monitoring bit "@HDX" changes, it will trigger and send the message. Please replace with your own Token and chat id.
66
67 As for How to get the botToken and chatID, please check the following videos:
68
69 [[https:~~/~~/www.youtube.com/watch?v=zh6yYlnjX7k>>https://www.youtube.com/watch?v=zh6yYlnjX7k]]
70
71 [[https:~~/~~/www.youtube.com/watch?v=Pj8mwuMZZvg>>https://www.youtube.com/watch?v=Pj8mwuMZZvg]]
72
73
74 If when you follow the second video to get chatID and there is a display like the following, you can change "getUpdates" to "deleteWebhook" to solve in website.
75
76
77 (% style="text-align:center" %)
78 [[image:6Z7mdnm13p.png]]
79
80
81 (% style="text-align:center" %)
82 [[image:WjE1P2yxIA.png]]
83
84 After deleting Webhook, you can change to "getUpdates" and continue to follow the second video. 
85
86
87 (% style="text-align:center" %)
88 [[image:zl6CJlwhER.png]]
89
90 (% class="box infomessage" %)
91 (((
92 Note: Bots added to Groups or Channels need to be provided with administrator rights.
93 )))
94
95 === 1.Permissions ===
96
97 Bots added to Groups or Channels need to be provided with administrator rights. For example "joe" is bot I created.
98
99
100 (% style="text-align:center" %)
101 [[image:3GS3dP01Wx.png]]
102
103 (% style="text-align:center" %)
104 [[image:eEyv361VZs.png]]
105
106
107 === 2.URL check ===
108
109 You can use the URL to test the status of a group or channel.
110
111 url = "https:~/~/api.telegram.org/bot"..telegramBotToken.."/sendMessage?text="..message.."&chat_id="..telegramChatID
112
113 (% style="text-align:center" %)
114 [[image:telegram URL.png]]
115
116 === 3.Script ===
117
118 {{code language="Lua"}}
119 local tempBit = 0
120 local tempWord = 0
121
122 local botToken = "5504549693:AAEy6a5G-sOF3CINONxMNABeYnoS4ABVlfg"
123 local chatID = "-641959124"--The chat id from Channel or Group
124
125 local https = require("https")
126 local json = require("json")
127
128 -- Send http.get request and return response result
129 function getHttpsUrl(url)
130 local body = {}
131 local bodyJson = json.encode(body)
132 local header = {}
133 header["content-type"] = "application/json"
134 local result_table, code, headers, status = https.request(url, bodyJson)
135 print("code:"..code)
136 if code~= 200 then
137 return
138 else
139 return body
140 end
141 end
142
143 function sendAlarm(telegramBotToken, message, telegramChatID)
144 local url = "https://api.telegram.org/bot"..telegramBotToken.."/sendMessage?text="..message.."&chat_id="..telegramChatID
145 --local url = 'http://v-box.net'
146 --local url = 'https://www.google.com/'
147 print("Get the link:"..url)
148 getHttpsUrl(url)
149 end
150
151
152 function AlarmNotificate.main()
153 local bitValue = addr_getbit("@HDX");
154 local message = ''
155 print("b=="..bitValue)
156 if bitValue == 1 and bitValue ~= tempBit then
157 message = 'Alarm triggered, the monitoring point test value is '.. bitValue
158 sendAlarm(botToken, message, chatID)
159 print("Notification pushed of triggering alarm,"..bitValue)
160 elseif bitValue == 0 and bitValue ~= tempBit then
161 message = 'Alarm dismissed, the monitoring point test value is '.. bitValue
162 sendAlarm(botToken, message, chatID)
163 print("Notification pushed of dismissing alarm,"..bitValue)
164 end
165 tempBit = bitValue----Prevent monitoring values from continuous being sent to the platform
166
167 local wordValue = addr_getword("@HDW10")
168 print("w=="..wordValue)
169 --dosomething
170 if wordValue >= 100 and wordValue ~= tempWord and tempWord <= 100 then
171 message = 'Word alarm triggered, the word value is '.. wordValue
172 sendAlarm(botToken, message, chatID)
173 print("Notification pushed of triggering alarm,"..wordValue)
174 elseif wordValue < 100 and wordValue ~= tempWord and tempWord >= 100 then
175 message = 'Word alarm dismissed, the word value is '.. wordValue
176 sendAlarm(botToken, message, chatID)
177 print("Notification pushed of dismissing alarm,"..wordValue)
178 end
179 tempWord = wordValue----Prevent monitoring values from continuous being sent to the platform
180 end
181 {{/code}}
182
183 [[image:1715678008611-743.png]]
184
185 (% class="box infomessage" %)
186 (((
187 Note: The name of script must be the same as the main function.
188 )))
189
190 == **1.6 LINE Notify(Not available)** ==
191
192 {{info}}
193 The following scripts are no longer available because the related API service has been discontinued.
194 {{/info}}
195
196 This example shows how to use the LINE Notify to send message into LINE group. When monitoring bit "@test" changes, it will trigger and send the message. Please replace with your own Token.
197
198 {{code language="lua"}}
199 local tempBit = 0
200 local tempWord = 0
201
202 local LineToken = "08XCpubkOdwGdGgRTXF0x8umiyrALtoM0v6lBFUV6PC"
203
204 local https = require("https")
205 local json = require("json")
206 local ltn12 = require("ltn12")
207
208 -- Send http.get request and return response result
209 function getHttpsUrl(url,header,reqbody)
210 local body = {}
211 local bodyJson = json.encode(body)
212 local result_table, code, headers, status = https.request{
213 method = "POST",
214 url = url,
215 source = ltn12.source.string(reqbody),
216 headers = header,
217 sink = ltn12.sink.table(body)
218 }
219 print("code:"..code)
220 if code~= 200 then
221 return
222 else
223 return body
224 end
225 end
226
227 function getMessageUrl(lineMessage)
228 local url = "https://notify-api.line.me/api/notify"
229 local reqMess = "message="..lineMessage
230 local headers =
231 {
232 ["Authorization"] = "Bearer "..LineToken,
233 ["Content-Type"] = "application/x-www-form-urlencoded",
234 ["Content-Length"] = #reqMess
235 }
236
237 print("Get the link:"..url)
238 getHttpsUrl(url, headers, reqMess)
239 end
240
241
242 function linenotify.main()
243 local bitValue = addr_getbit("@test");
244 local message = ''
245 print("b=="..bitValue)
246 if bitValue == 1 and bitValue ~= tempBit then
247 message = 'Alarm V-Box triggered, the output is '.. bitValue
248 getMessageUrl(message)
249 print("Notification pushed of triggering alarm,"..bitValue)
250 elseif bitValue == 0 and bitValue ~= tempBit then
251 message = 'Alarm V-Box dismissed, the output is '.. bitValue
252 getMessageUrl(message)
253 print("Notification pushed of dismissing alarm,"..bitValue)
254 end
255 tempBit = bitValue----Prevent monitoring values from continuous being sent to the platform
256
257 local wordValue = addr_getword("@t2")
258 print("w=="..wordValue)
259 --dosomething
260 if wordValue >= 100 and wordValue ~= tempWord and tempWord <= 100 then
261 message = 'Alarm V-Box triggered, the temperature is '.. wordValue
262 getMessageUrl(message)
263 print("Notification pushed of triggering alarm,"..wordValue)
264 elseif wordValue < 100 and wordValue ~= tempWord and tempWord >= 100 then
265 message = 'Alarm V-Box dismissed, the temperature is '.. wordValue
266 getMessageUrl(message)
267 print("Notification pushed of dismissing alarm,"..wordValue)
268 end
269 tempWord = wordValue----Prevent monitoring values from continuous being sent to the platform
270 end
271 {{/code}}
272
273 == **1.7 Twilio WhatsApp Messaging** ==
274
275 This example shows how to use the Twilio API to send WhatsApp message to private number. When monitoring bit "@testBit" changes, it will trigger and send the message. Please replace with your own SID, Token, twilioPhoneNumber and receiverPhoneNumber.
276
277 About how to register the Twilio API, please check the following video:
278
279 [[https:~~/~~/www.youtube.com/watch?v=Id4lKichauU>>https://www.youtube.com/watch?v=Id4lKichauU]]
280
281 {{code language="Lua"}}
282 local tempBit = 0
283 local tempWord = 0
284
285 local https = require("https")
286 local json = require("json")
287 local ltn12 = require("ltn12")
288
289 local SID = 'AC1703bd710ffa98006d2bcc0b********'
290 local Token = 'd3c11897623c39e538b20263ec19****'
291
292 local twilioPhoneNumber = '+14155238886'
293 local receiverPhoneNumber = '+8615880018277'
294
295 local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
296 function encodingBase64(data)
297 return ((data:gsub('.', function(x)
298 local r,b='',x:byte()
299 for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
300 return r;
301 end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
302 if (#x < 6) then return '' end
303 local c=0
304 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
305 return b:sub(c+1,c+1)
306 end)..({ '', '==', '=' })[#data%3+1])
307 end
308
309 function encodeUrl(str)
310 str = string.gsub(str, "([^%w%.%- ])", function(c)
311 return string.format("%%%02X", string.byte(c)) end)
312 return string.gsub(str, " ", "+")
313 end
314
315
316
317
318 function requestBodySplice(message, sender, receiver)
319 local reqBody = ''
320 local encodeMess = encodeUrl(message)
321 local encodeSend = encodeUrl(sender)
322 local encodeRece = encodeUrl(receiver)
323 --reqBody = "Body=Hello%20Wecon2&From=whatsapp%3A%2B14155238886&To=whatsapp%3A%2B8615880018277"
324 reqBody = string.format("Body=%s&From=whatsapp:%s&To=whatsapp:%s", encodeMess, encodeSend, encodeRece)
325 print(reqBody)
326 return reqBody
327 end
328
329
330 -- Send http.get request and return response result
331 function getHttpsUrl(url,header,reqbody)
332 local body = {}
333 local bodyJson = json.encode(body)
334 local result_table, code, headers, status = https.request{
335 method = "POST",
336 url = url,
337 source = ltn12.source.string(reqbody),
338 headers = header,
339 sink = ltn12.sink.table(body)
340 }
341 print("code:"..code)
342 if code~= 200 then
343 return
344 else
345 return body
346 end
347 end
348
349 function getMessageUrl(whatsAppMessage)
350 local auth = SID..':'..Token
351 local url = "https://api.twilio.com/2010-04-01/Accounts/"..SID.."/Messages"
352 --local reqMess = "message="..twilioMessage
353 local reqMess = requestBodySplice(whatsAppMessage, twilioPhoneNumber, receiverPhoneNumber)
354 local headers =
355 {
356 ["Authorization"] = "Basic "..encodingBase64(auth),
357 ["Content-Type"] = "application/x-www-form-urlencoded",
358 ["Content-Length"] = #reqMess
359 }
360
361 print("Get the link:"..url)
362 getHttpsUrl(url, headers, reqMess)
363 end
364
365
366
367 function Twilio.main()
368 --dosomething
369 --local auth = SID..':'..Token
370 --print(requestBodySplice("HelloWorld", twilioPhoneNumber, receiverPhoneNumber))
371 --print(encodingBase64(auth))
372 local bitValue = addr_getbit("@testBit");
373 local message = ''
374 print("b=="..bitValue)
375 if bitValue == 1 and bitValue ~= tempBit then
376 message = 'Alarm V-Box triggered, the output is '.. bitValue
377 getMessageUrl(message)
378 print("Notification pushed of triggering alarm,"..bitValue)
379 elseif bitValue == 0 and bitValue ~= tempBit then
380 message = 'Alarm V-Box dismissed, the output is '.. bitValue
381 getMessageUrl(message)
382 print("Notification pushed of dismissing alarm,"..bitValue)
383 end
384 tempBit = bitValue----Prevent monitoring values from continuous being sent to the platform
385
386 local wordValue = addr_getword("@testWord")
387 print("w=="..wordValue)
388 --dosomething
389 if wordValue >= 100 and wordValue ~= tempWord and tempWord <= 100 then
390 message = 'Alarm V-Box triggered, the temperature is '.. wordValue
391 getMessageUrl(message)
392 print("Notification pushed of triggering alarm,"..wordValue)
393 elseif wordValue < 100 and wordValue ~= tempWord and tempWord >= 100 then
394 message = 'Alarm V-Box dismissed, the temperature is '.. wordValue
395 getMessageUrl(message)
396 print("Notification pushed of dismissing alarm,"..wordValue)
397 end
398 tempWord = wordValue----Prevent monitoring values from continuous being sent to the platform
399 end
400 {{/code}}
401
402 == **1.8 HTTP response body** ==
403
404 This example use [[https:~~/~~/www.weatherapi.com/>>https://www.weatherapi.com/]] as example, to show how to parse value from HTTP response body. When we input the city name into address "@HDW5050":
405
406 (% style="text-align:center" %)
407 [[image:InputHTTPparameter.png]]
408
409 Then the response body would be like as following:
410
411 {{code language="json"}}
412 {
413 "location": {
414 "name": "Madrid",
415 "region": "Madrid",
416 "country": "Spain",
417 "lat": 40.4,
418 "lon": -3.68,
419 "tz_id": "Europe/Madrid",
420 "localtime_epoch": 1669022636,
421 "localtime": "2022-11-21 10:23"
422 },
423 "current": {
424 "last_updated_epoch": 1669022100,
425 "last_updated": "2022-11-21 10:15",
426 "temp_c": 13.0,
427 "temp_f": 55.4,
428 "is_day": 1,
429 "condition": {
430 "text": "Partly cloudy",
431 "icon": "//cdn.weatherapi.com/weather/64x64/day/116.png",
432 "code": 1003
433 },
434 "wind_mph": 11.9,
435 "wind_kph": 19.1,
436 "wind_degree": 210,
437 "wind_dir": "SSW",
438 "pressure_mb": 1015.0,
439 "pressure_in": 29.97,
440 "precip_mm": 0.0,
441 "precip_in": 0.0,
442 "humidity": 88,
443 "cloud": 75,
444 "feelslike_c": 10.8,
445 "feelslike_f": 51.4,
446 "vis_km": 10.0,
447 "vis_miles": 6.0,
448 "uv": 3.0,
449 "gust_mph": 22.1,
450 "gust_kph": 35.6
451 }
452 }
453 {{/code}}
454
455 (% class="wikigeneratedid" %)
456 So we decode json into lua object to assign the value into addresses HDW6060(temperature), HDW7070(humidity), the code example like follows:
457
458 {{code language="lua"}}
459 local APIkey = '70faaecf926b4341b1974006221711'
460
461
462 local http = require("socket.http")
463 local json = require("json")
464
465 -- Send http.get request and return response result
466 function getHttpsUrl(url)
467 local result_table, code, headers, status = http.request(url)
468 print("code:"..code)
469 if code~= 200 then
470 return
471 else
472 return result_table
473 end
474 end
475
476 function sendAPI(key, city)
477 local url = "http://api.weatherapi.com/v1/current.json?key="..key.."&q="..city.."&aqi=no"
478 --local url = 'http://v-box.net'
479 --local url = 'https://www.google.com/'
480 --http://api.weatherapi.com/v1/current.json?key=70faaecf926b4341b1974006221711&q=Barcelona&aqi=no
481 print("Get the link:"..url)
482 local body = getHttpsUrl(url)
483 --print(body)
484 local jsonBody = json.decode(body)
485 --print(jsonBody["current"]["temp_c"])
486 --print(type(jsonBody["current"]["temp_c"]))
487 --print(type(jsonBody["current"]["humidity"]))
488 addr_setfloat("@HDW6060", jsonBody["current"]["temp_c"])
489 addr_setword("@HDW7070", jsonBody["current"]["humidity"])
490 end
491
492
493 function Weather.main()
494 local cityName = addr_getstring("@HDW5050",6)
495 print("cityName: "..cityName)
496 sendAPI(APIkey, cityName)
497 end
498 {{/code}}
499
500 == **1.9 High-Low Byte Switch** ==
501
502 The following example is converting the floating number from order 1234 to order 3412, and formating output the number with 2 decimal point. About which high-low word order corresponding to which value, please refer to the [[Address Operation Table>>doc:V-BOX.V-Net.Manual.04 Lua Script.01 Lua Functions.WebHome||anchor="H2Addressoperation"]].
503
504 {{code language="lua"}}
505 function highLowByteSwitch(floatNumber)
506 addr_setfloat("@W_0#HDW23036",floatNumber,0,2)
507 local newFloat = addr_getfloat("@W_0#HDW23036")
508 local formattedFloat = string.format("%.2f",newFloat)
509 print("The formatted float value is the : "..formattedFloat)
510 return formattedFloat
511 end
512 {{/code}}
513
514 == **1.10 Read 64bits Unsigned Value** ==
515
516 In our built-in function library doesn't have the function for reading 64-bit unsigned format value, so the following function is for solve this. But if the number is greater 2^53, the precision will be lost. So the final result will be a little bit different from the original value.
517
518 == **1.11 Bit-Activated Timer with Reset and Data Output** ==
519
520 This script implements a timer that increments while enabled (by a control bit) until reaching a threshold (5s), then resets the timer, disables itself, and sets an output data value.
521
522 (% style="text-align:center" %)
523 [[image:1749188641322-409.png]]
524
525 (% style="text-align:center" %)
526 [[image:1749189179543-849.png||height="300" width="571"]]
527
528 {{code language="lua"}}
529 function timer.main()
530 -- Read current state of control bit and timer value
531 local a = addr_getbit("@Bit") -- Get status of control bit (0 or 1)
532 local b = addr_getword("@Timer") -- Get current timer value (word/integer)
533
534 -- Increment phase: When activated and timer < threshold
535 if a == 1 and b < 5 then
536 b = b + 1 -- Increment timer value
537 addr_setword("@Timer", b) -- Update timer memory
538 print(b) -- Output current timer value (debug)
539 end
540
541 -- Reset phase: When timer reaches threshold
542 if b >= 5 then
543 addr_setword("@Timer", 0) -- Reset timer to 0
544 addr_setbit("@Bit", 0) -- Deactivate control bit
545 addr_setword("@Data", 10) -- Set output data to fixed value (10)
546 end
547 end
548 {{/code}}
549
550 = **2 Third part server** =
551
552 V-Box have two mode.One is for V-Net,User need to use WECON server to store data.We call this V-NET platform.
553
554 (% class="mark" %)1.Europe server:eu.v-box.net
555
556 (% class="mark" %)2.Asean server:asean.v-box.net
557
558 Second is for OpenCloud mode.It means V-Box data will transfer to third part server and do not want to store data to WECON server.We call OpenCloud paltform
559
560 OpenCloud platform is used in configuring the script.Then V-Box can connect with third part server.
561
562 Both mode can support script  to connect with third part server.the difference:
563
564 (% class="mark" %)1.If you want to store in WECON server ,please use V-NET.
565
566 (% class="mark" %)2.If your server requires SSL certificate to log in,please use OpenCloud.Because only OpenCloud platform can support to upload certificate
567
568 {{info}}
569 **✎Note: **Before program the script of MQTT, please make sure the server(MQTT broker) can be connected through MQTT Client tool.
570 {{/info}}
571
572 (% class="wikigeneratedid" %)
573 Tool link: **[[MQTT.fx>>http://mqttfx.jensd.de/index.php/download]]**
574
575 == **2.1 Test server(General Example)** ==
576
577 The following example is trying to publish to the topic "testtopic/test/no1/7890", and subscribe the topic "testtopic/test/no1/123456".
578
579 And the JSON message is like follows:
580
581 {{code language="JSON"}}
582 {
583 "timestamp": 1631152760,
584 "messageId": 1,
585 "event": "test_data",
586 "mfrs": "HMI/box",
587 "data":
588 {
589 "id" : 1436217747670454274,
590 "waterlevel" : 48,
591 "temperture" : 23
592 }
593 }
594 {{/code}}
595
596 {{code language="lua"}}
597 --MQTT configuration table
598 local MQTT_CFG={}
599 --if there is no need the username and password, please put them as ""
600 MQTT_CFG.username = "weconsupport"
601 MQTT_CFG.password = "123456"
602 MQTT_CFG.netway = 0
603 MQTT_CFG.keepalive = 60
604 MQTT_CFG.cleansession = 1
605 --TCP URL
606 MQTT_URL = "tcp://mq.tongxinmao.com:1883"
607 --Client ID
608 MQTT_CLIENT_ID = "V-BOXH-AG"
609
610 --Generate UUID
611 function uuid()
612 local seed = {'e','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}
613 local tb = {}
614 for i=1, 32 do
615 table.insert(tb, seed[math.random(1,16)])
616 end
617 local sid=table.concat(tb)
618 return string.format('%s',
619 string.sub(sid,1,32)
620 )
621 end
622
623
624 --Topic name to subscribed
625 local SUBSCRIBE_TOPIC = 'testtopic/test/no1/123456'
626
627 --Topic name to be published
628 local PUBLISH_TOPIC = 'testtopic/test/no1/7890'
629
630
631 --real time
632 local LAST_TIME = 0
633
634
635 --initialize mqtt
636 function mqtt_init()
637 print(string.format("mqtt init mqtt_url:%s mqtt_clientid:%s", MQTT_URL, MQTT_CLIENT_ID))
638 if g_mq then
639 mqtt.close(g_mq) --Close mqtt object
640 end
641 g_mq, err = mqtt.create(MQTT_URL, MQTT_CLIENT_ID) -- create mqtt object,and declare it as a global variable
642 if g_mq then
643 g_mq:on("message", mqtt_msg_callback) -- Register a callback for receiving messages
644 g_mq:on("offline", mqtt_msg_offline) -- Register a callback for offline
645 print("mqtt init success")
646 else
647 print("mqtt init failed:", err)
648 end
649 end
650
651 -- connect to mqtt
652 function mqtt_connect()
653 print("mqtt connecting...")
654 local stat, err = g_mq:connect(MQTT_CFG)
655 if stat == nil then
656 print("mqtt connect failed:", err)
657 return
658 else
659 print("mqtt connected")
660 end
661 g_mq:subscribe(SUBSCRIBE_TOPIC, 0)
662 end
663
664 --Offline callback function
665 function mqtt_msg_offline(cause)
666 print("mqtt offline, cause:", cause)
667 end
668
669 -- Received message callback function
670 function mqtt_msg_callback(topic, msg)
671 print("topic:", topic)
672 print("msg:", msg)
673 local objMsg = json.decode(msg)
674 local water = objMsg.data.waterlevel
675 local temp = objMsg.data.temperature
676 addr_setword("@HDW20",water)
677 addr_setword("@HDW10",temp)
678 end
679
680 --Send data (data upload to platform and encapsulate it with custom functions)
681 function send_data()
682 local pub_data = {
683 timestamp = os.time(),
684 messageId = 1,
685 event = 'test_data',
686 mfrs = 'V-Box',
687 data = {
688 id = uuid(),
689 waterlevel = addr_getword("@HDW10"),
690 temperature = addr_getword("@HDW20")
691 }
692 }
693 return g_mq:publish(PUBLISH_TOPIC, json.encode(pub_data), 0, 0)
694 end
695
696
697 --main function fixed timed execution
698 function MQTT.main()
699 --dosomething
700 print(os.date("%Y-%m-%d %H:%M %S", os.time()) .. " main start")
701 --determine the mqtt object whether exist
702 if g_mq then
703 --determine the mqtt object whether has been connected or not
704 if g_mq:isconnected() then
705 send_data()
706 else
707 --if exceed 5 sec not connect, reconnect once
708 if os.time() - LAST_TIME > 5 then
709 LAST_TIME = os.time()
710 --reinitial the mqtt object
711 mqtt_init()
712 --connect to mqtt or reconnect
713 mqtt_connect()
714 end
715 end
716 else
717 --mqtt object does not exist so create new one
718 mqtt_init()
719 end
720 print(os.date("%Y-%m-%d %H:%M %S", os.time()) .. " main end")
721 end
722 {{/code}}
723
724 == **2.2 Customer server:grouprobotinfo.com** ==
725
726 This demo does not use SSL certification. Script is as below
727
728 Demo1:
729
730 {{code language="lua"}}
731 -- Meta class
732 --main
733 function mq.main()
734 if not mq.m then
735 local err = ""
736
737 mq.m, err = mqtt.create("tcp://grouprobotinfo.com:1883", "ClienID") -- create connection
738 if mq.m then
739 mq.config = {
740 username = "",-- ID
741 password = "",-- password
742 netway = 1, -- Ethernet connection, WIFI=1
743 -- keepalive = 100, -- Optional, set the connection heartbeat interval for 100 seconds.
744 -- cleansession = 0, -- Optional, keep session
745 }
746 mq.m:on("message", function(topic, msg) -- Register for receiving message callbacks
747 local str = string.format("%s:%s", topic, msg)
748 -- print("mqtt msg:", str) -- Print out the received topics and content
749 end)
750 mq.m:on("offline", function (cause) -- Register for lost connection callbacks
751 -- addr_setstring("@xxx", "cause"..(cause or " got nil"))
752 end)
753 mq.m:on("arrived", function() -- Registration for sending messages to callbacks
754 print("msg arrived")
755 end)
756 else
757 print("mqtt create failed:", err) -- Create object failed
758 end
759 else
760 if mq.m:isconnected() then -- If online, post a message
761 local phaseStatus ="unknow"
762 if addr_getbit("@Standby")== 1 then
763 phaseStatus = "Standby"
764 elseif addr_getbit("@Pre-Freeze")==1 then
765 phaseStatus= "Pre-Freeze"
766 elseif addr_getbit("@Prepare")==1 then
767 phaseStatus ="Prepare"
768 elseif addr_getbit("@Primary Dry")==1 then
769 phaseStatus = "Primary dry"
770 elseif addr_getbit("@Secondary Dry")==1 then
771 phaseStatus = "Secondary Dry"
772 end
773 --print(addr_getbit("@Primary Dry"))
774 -------------------------------------------------------------------------------------------------------------------------
775 local activating ="unknow"
776 if addr_getbit("@Compressor")==1 then
777 activating = ",".."Compressor"
778 end
779 if addr_getbit("@Silicone Pump")==1 then
780 activating = activating..",".."Silicone Pump"
781 end
782 if addr_getbit("@Vacuum Pump")==1 then
783 activating = activating..",".."Vacuum Pump"
784 end
785 if addr_getbit("@Root Pump")==1 then
786 activating = activating..",".."Root Pump"
787 end
788 if addr_getbit("@Heater")==1 then
789 activating = activating..",".."Heater"
790 end
791 if addr_getbit("@Valve Silicone")==1 then
792 activating = activating..",".."Valve Silicone"
793 end
794 if addr_getbit("@Valve Ice Condenser")==1 then
795 activating = activating..",".."Valve Ice Condenser"
796 end
797 if addr_getbit("@Valve Vacuum Pump")==1 then
798 activating = activating..",".."Valve Vacuum Pump"
799 end
800 local pr_activating =string.sub(activating,2)
801 -- print(pr_activating)
802 local status_text ="unknow"
803 if addr_getbit("@Status Run")==1 then
804 status_text = "RUNNING"
805 else
806 status_text = "STOP"
807 end
808 -------------------------------------------------------------------------------------------------------------------------
809 local js = {type="status",
810 mc_name ="FD300",
811 status=status_text,
812 elapsed_time={
813 hour=addr_getword("@Elapsed Time (Hour)"),
814 min=addr_getword("@Elapsed Time (Minute)"),
815 sec=addr_getword("@Elapsed Time (Second)")
816 },
817 phase = phaseStatus,
818 step = addr_getword("@Step"),
819 activating_output = pr_activating,
820 sv=addr_getshort("@SV Silicone")/10,
821 pv=addr_getshort("@PV Silicone")/10,
822 product1=addr_getshort("@Product 1")/10,
823
824 product2=addr_getshort("@Product 2")/10,
825 product3=addr_getshort("@Product 3")/10,
826 product4=addr_getshort("@Product 4")/10,
827 ice1=addr_getshort("@Ice condenser 1")/10,
828 ice2=addr_getshort("@Ice condenser 2")/10,
829 vacuum=addr_getfloat("@Vacuum")
830 }
831 local jsAlarm = { HPC = addr_getbit("@B_25395#W0.00"),
832 ODPC = addr_getbit("@B_25395#W0.01"),
833 MTPC=addr_getbit("@B_25395#W0.02"),
834 HTT = addr_getbit("@B_25395#W1.03"),
835 CPC = addr_getbit("@B_25395#W0.08"),
836 CPSP =addr_getbit("@B_25395#W1.00"),
837 CPVP =addr_getbit("@B_25395#W0.10"),
838 CPRP =addr_getbit("@B_25395#W0.11"),
839 HP =addr_getbit("@B_25395#W1.01"),
840 PP= addr_getbit("@B_25395#W1.02"),
841 PO=addr_getbit("@B_25395#W0.07"),
842 FSE=addr_getbit("@B_25395#W2.04"),
843 AVVSVV=addr_getbit("@B_25395#W1.12"),
844 ICHT=addr_getbit("@B_25395#W3.06")
845 }
846 -- ("@B_25395#CIO1.02")
847 mq.m:publish("mqtt-v-box-epsilon-fd300", json.encode(js) , 0, 0)
848 mq.m:publish("mqtt-v-box-epsilon-alarm-fd300", json.encode(jsAlarm) , 0, 0)
849 else
850 local stat, err = mq.m:connect(mq.config) -- connection
851 if stat == nil then --Determine whether to connect
852 print("mqtt connect failed:", err)
853 return -- Connection failed, return directly
854 end
855 mq.m:subscribe("mqtt-v-box-epsilon", 0)-- Subscribe to topics
856
857 end
858 -- mq.m:unsubscribe("stc/test")
859 -- mq.m:disconnect() -- close matt
860 -- mq.m:close() -- close clase
861 end
862 end
863 {{/code}}
864
865 == **2.3 Azure platform** ==
866
867 In this demo,V-Box connects with Azure by SSL certification.
868
869 Video link: [[https:~~/~~/youtu.be/cdI6rIQcpMY?list=PL_Bpnb2RgaksCic9HCcVAZhU9sYwCRKzW>>https://youtu.be/cdI6rIQcpMY?list=PL_Bpnb2RgaksCic9HCcVAZhU9sYwCRKzW]]
870
871 Tool Download link: [[https:~~/~~/wecon-disk.oss-ap-southeast-1.aliyuncs.com/Download/WIKI/V-BOX/Demo/Azure/Azure%20tool.zip>>https://wecon-disk.oss-ap-southeast-1.aliyuncs.com/Download/WIKI/V-BOX/Demo/Azure/Azure%20tool.zip]]
872
873 Script is as below
874
875 {{code language="lua"}}
876 --https://support.huaweicloud.com/qs-IoT/iot_05_0005.html  mqtt.fx monitor to connect azure iot
877 sprint = print
878
879 --Get custom configuration parameters (vbox custom information)
880 --local CUSTOM = bns_get_config("bind")
881 --local DS_ID = CUSTOM.DSID or "60a71ccbbbe12002c08f3a1a_WECON"
882
883
884
885 --Cloud mode interface to obtain the MQTT information configured by the cloud platform: (5 returns, namely the server address, client ID, connection table, last word table, certificate table)
886 local MQTT_URL, MQTT_CLIENTID, MQTT_CFG, MQTT_LWT, MQTT_CART = mqtt.setup_cfg()
887
888 --MQTT_CFG.username = '60a71ccbbbe12002c08f3a1a_WECON'
889 --MQTT_CFG.password='wecon123'
890 --MQTT_CLIENTID = '60a71ccbbbe12002c08f3a1a_WECON_0_0_2021052110usernxame:60a71ccbbbe12002c08f3a1a_WECONpassword:a0a951581855aa8e0262129da6cf1b43f2c0ecfac4fa56117fc5a20c90be169a'
891
892 --publish to topics
893 local pub_RE_TOPIC = string.format('devices/wecon_02/messages/events/')
894 --Subscribe topics
895 local Subscribe_RE_TOPIC1 = string.format('devices/wecon_02/messages/devicebound/#')
896
897 --variable
898 local last_time = 0
899
900
901
902 --Timing main function
903 function Azure.main()
904
905    sprint(os.date("%Y-%m-%d %H:%M %S", os.time()) .. " Azureiot.main start")
906    if g_mq then
907         if g_mq:isconnected() then
908             send_Data()
909         else
910             if os.time() - last_time > 20 then
911                 last_time = os.time()
912                 mymqtt_connect()
913             end
914         end
915     else
916         mymqtt_init()
917     end
918     sprint(os.date("%Y-%m-%d %H:%M %S", os.time()) .. " Azureiot.main end")
919 end
920
921 -- Initialize MQTT
922 function mymqtt_init()
923     sprint(string.format("mqtt init mqtt_url:%s mqtt_clientid:%s", MQTT_URL, MQTT_CLIENTID))
924     g_mq, err = mqtt.create(MQTT_URL, MQTT_CLIENTID) -- Create the object and declare it as a global variable
925     if g_mq then
926         g_mq:on("message", mymqtt_msg_callback) -- Register to receive message callbacks
927         sprint("mqtt init success")
928     else
929         sprint("mqtt init failed:", err)
930     end
931 end
932
933 -- Connect to MQTT server
934 function mymqtt_connect()
935     sprint("mqtt connecting...")
936     local stat, err = g_mq:connect(MQTT_CFG,MQTT_LWT, MQTT_CART)
937     if stat == nil then
938         sprint("mqtt connect failed:", err)
939         return
940     else
941         sprint("mqtt connected")
942     end
943     g_mq:subscribe(Subscribe_RE_TOPIC1, 0) 
944 end
945
946 -- Receive MQTT message callback function
947 function mymqtt_msg_callback(topic, msg)
948     print("topic:",topic)
949     print("revdata:",msg)
950    -- local revData = json.decode(msg)
951  --  if topic == Subscribe_RE_TOPIC1 then --Process topic information subscribed from the cloud
952 -- if string.match(topic,Subscribe_RE_TOPIC1) then
953      --   print("topi11:",topic)
954        setValue(revData)
955    -- end
956 end
957
958 --Process the received data
959 --function setValue(revData)
960    -- if revData ~=nil then 
961  --       for i,v in pairs(revData) do
962   --          print("Data received:",i,v)
963   --      end
964    -- end
965 --end
966
967 --Get real-time data
968 function getData()
969     local jdata = {}
970     local addr = bns_get_alldata()
971     print(json.encode(addr))
972     for i,v in pairs(addr) do
973         if v[2] == 1 then
974            jdata[v[3]] = v[4]
975         end
976     end
977     return jdata
978 end 
979
980
981
982 --send data
983 function send_Data()
984     local pub_data = {100
985      --   services={{
986
987             --serviceId ='Temperature',
988            -- properties={
989                -- value = 55
990            -- },
991        -- }}
992 }
993 sprint(json.encode(pub_data))
994 print("..........",pub_RE_TOPIC)
995     return g_mq:publish(pub_RE_TOPIC, json.encode(pub_data), 0, 0)
996 end
997 {{/code}}
998
999 == **2.4 Huawei platform** ==
1000
1001 {{info}}
1002 **✎Note**:**Huawei IOT DA function is only in China area.If you want this function,you need to use chinese mobile to register**
1003 {{/info}}
1004
1005 1.Register a account: [[https:~~/~~/www.huaweicloud.com/intl/en-us/s/JUlPVERNJQ>>https://www.huaweicloud.com/intl/en-us/s/JUlPVERNJQ]]
1006
1007 2.log in the Huawei IOTDA
1008
1009 [[https:~~/~~/console.huaweicloud.com/iotdm/?region=cn-north-4&locale=en-us#/dm-portal/home>>https://console.huaweicloud.com/iotdm/?region=cn-north-4&locale=en-us#/dm-portal/home]]
1010
1011 3.Create product
1012
1013 (% style="text-align:center" %)
1014 [[image:1624433478954-859.png||height="497" width="1100" class="img-thumbnail"]]
1015
1016 4.Product name,manufacturer,device type and industry,set according to your own needs.
1017
1018 Protocol: MQTT
1019
1020 Data Type: JSON
1021
1022 After finishing configuration,please click "OK"
1023
1024 (% style="text-align:center" %)
1025 [[image:1624433531968-337.png||height="568" width="700" class="img-thumbnail"]]
1026
1027 5.Device
1028
1029 After product register,continue to configure "individual register".Click "Device"~-~->"individual register"
1030
1031 (% style="text-align:center" %)
1032 [[image:1624434757597-117.png||class="img-thumbnail"]]
1033
1034 **Notes for registering device:**
1035
1036 Product: Previous product registration.
1037
1038 Node ID, Device Name: set according to your own needs.
1039
1040 Secret: need to be configured, will be used when connecting later
1041
1042 After configuration, click OK to generate a device ID and password, which will be used for device access later.
1043
1044 (% style="text-align:center" %)
1045 [[image:1624436421499-613.png||height="499" width="700" class="img-thumbnail"]]
1046
1047 (% style="text-align:center" %)
1048 [[image:1624437798012-126.png||height="366" width="500" class="img-thumbnail"]]
1049
1050 6. Connection authentication (use MQTT.fx tool to access the IoT platform)
1051
1052 (1)Open mqttClientIdGenerator tool Java(TM) Platform SE binary
1053
1054 **[[Download>>https://wecon-disk.oss-ap-southeast-1.aliyuncs.com/Download/WIKI/V-BOX/Demo/Huawei/mqttClientIdGenerator-19.2.0.zip]]**
1055
1056 (% style="text-align:center" %)
1057 [[image:1624437573798-815.png||height="351" width="700" class="img-thumbnail"]]
1058
1059 (2)Fill in the device ID and secret (deviceid and secret generated when registering the device) to generate connection message
1060
1061 Client ID, user name, password
1062
1063 (% style="text-align:center" %)
1064 [[image:1624437756866-251.png||height="405" width="700" class="img-thumbnail"]]
1065
1066 (3) Download certificate file"North-Beijing4"
1067
1068 [[https:~~/~~/support.huaweicloud.com/en-us/devg-iothub/iot_02_1004.html>>https://support.huaweicloud.com/en-us/devg-iothub/iot_02_1004.html]]
1069
1070 (% style="text-align:center" %)
1071 [[image:1624438225398-363.png||height="403" width="800" class="img-thumbnail"]]
1072
1073 (% style="text-align:center" %)
1074 [[image:1624438260025-610.png||height="408" width="700" class="img-thumbnail"]]
1075
1076 7.Run MQTTfx tool to connect with Huawei
1077
1078 Download link: [[http:~~/~~/mqttfx.jensd.de/index.php/download>>url:http://mqttfx.jensd.de/index.php/download]]
1079
1080 (1)Click on the setting ICON
1081
1082 (% style="text-align:center" %)
1083 [[image:1624438821280-974.png||height="198" width="500" class="img-thumbnail"]]
1084
1085 (2)Fill in IIOT MQTT device access address, and configure authentication parameters.
1086 First: It is the server and port connected to Huawei IOT, which can be viewed through the overview of the interface.
1087
1088 (% style="text-align:center" %)
1089 [[image:1624439086268-985.png||class="img-thumbnail"]]
1090
1091 Domain name:iot-mqtts.cn-north-4.myhuaweicloud.com
1092
1093 Port: 8883
1094
1095 Client ID: check step 6
1096
1097 (% style="text-align:center" %)
1098 [[image:1624439672168-492.png||height="458" width="600" class="img-thumbnail"]]
1099
1100 (3)Upload SSL certificate file,check step 6
1101
1102 Select folder java~-~->DigiCertGlobalRootCA.crt.pem and click OK or apply button
1103
1104 (% style="text-align:center" %)
1105 [[image:1624439912938-659.png||height="458" width="600" class="img-thumbnail"]]
1106
1107 (4)Connect and test publish and subscribe
1108
1109 (% style="text-align:center" %)
1110 [[image:1624440014872-688.png||height="232" width="700" class="img-thumbnail"]]
1111
1112 (% style="text-align:center" %)
1113 [[image:1624440026937-386.png||height="215" width="700" class="img-thumbnail"]]
1114
1115 Huawei publish topic format: $oc/devices/{device_id}/sys/properties/report
1116
1117 (% style="text-align:center" %)
1118 [[image:1624440404119-815.png||class="img-thumbnail"]]
1119
1120 Huawei subscribe topic format: **$oc/devices/{device_id}/sys/commands/#**
1121
1122 (% style="text-align:center" %)
1123 [[image:1624447157493-672.png||class="img-thumbnail"]]
1124
1125 (% style="text-align:center" %)
1126 [[image:1624447209982-715.png||class="img-thumbnail"]]
1127
1128 (5).How to configure to view the received data format intuitively, multiple products (Huawei) are required to configure the model. The specific steps are as follows:
1129 ①Select the corresponding product from Huawei products to view
1130
1131 (% style="text-align:center" %)
1132 [[image:1624440647663-632.png||class="img-thumbnail"]]
1133
1134 ②Custom model: used to display the service ID name of the configuration report.
1135
1136 (% style="text-align:center" %)
1137 [[image:1624440793982-974.png||height="410" width="700" class="img-thumbnail"]]
1138
1139 (% style="text-align:center" %)
1140 [[image:1624440883015-105.png||height="370" width="600" class="img-thumbnail"]]
1141
1142 ③Add property, ID of monitoring point, and data format:
1143
1144 (% style="text-align:center" %)
1145 [[image:1624441052296-108.png||height="477" width="600" class="img-thumbnail"]]
1146
1147 ④After the configuration is complete, check the received data on the device
1148
1149 (% style="text-align:center" %)
1150 [[image:1624441186851-536.png||height="434" width="700" class="img-thumbnail"]]
1151
1152 === Huawei by SSL certification. ===
1153
1154 1.Create a project access for Huawei IOT
1155
1156 2.configure MQTT configuration
1157
1158 (% style="text-align:center" %)
1159 [[image:1624506363847-661.png||height="507" width="1000" class="img-thumbnail"]]
1160
1161 3.Create a script with the demo as below.
1162
1163 Script is as below
1164
1165 (% class="box infomessage" %)
1166 (((
1167 (% class="box infomessage" %)
1168 (((
1169 ~-~- mqtt.fx simulated access to Huawei Cloud IoT platform refer to 2.4
1170 sprint = print
1171
1172 ~-~-Get custom configuration parameters (gateway customization information)
1173 local CUSTOM = bns_get_config("bind")
1174 local DS_ID = CUSTOM.DSID or "5dfa0700df1ae506179afb9c_wecon"
1175
1176
1177 ~-~-OpenCloud mode interface, obtain MQTT information configured on cloud platform: (5 returned, respectively server address, client ID, connection table, last word table, certificate table)
1178 local MQTT_URL, MQTT_CLIENTID, MQTT_CFG, MQTT_LWT, MQTT_CART = mqtt.setup_cfg()
1179
1180 MQTT_CFG.username =DS_ID
1181 MQTT_CFG.password='d030d92338fcc18cd10fabb3003a4a0f6620fa6822cd3c23b1d9bc790200c6e7'
1182 MQTT_CLIENTID = '5dfa0700df1ae506179afb9c_wecon_0_0_2019121819'
1183
1184 ~-~-publish topic format:$oc/devices/{device id}/sys/properties/report
1185
1186 local pub_RE_TOPIC = string.format('$oc/devices/60a71ccbbbe12002c08f3a1a_WECON/sys/properties/report')
1187
1188 ~-~-variate
1189 local last_time = 0
1190
1191
1192 ~-~-Timing principal function
1193 function hwyiot.main()
1194
1195 sprint(os.date("%Y-%m-%d %H:%M %S", os.time()) .. " hwyiot.main start")
1196 if g_mq then
1197 if g_mq:isconnected() then
1198 send_Data()
1199 else
1200 if os.time() - last_time > 20 then
1201 last_time = os.time()
1202 mymqtt_connect()
1203 end
1204 end
1205 else
1206 mymqtt_init()
1207 end
1208 sprint(os.date("%Y-%m-%d %H:%M %S", os.time()) .. " hwyiot.main end")
1209 end
1210
1211 ~-~- initializationMQTT
1212 function mymqtt_init()
1213 sprint(string.format("mqtt init mqtt_url:%s mqtt_clientid:%s", MQTT_URL, MQTT_CLIENTID))
1214 g_mq, err = mqtt.create(MQTT_URL, MQTT_CLIENTID) ~-~- Create the object and declare it as a global variable
1215 if g_mq then
1216 g_mq:on("message", mymqtt_msg_callback) ~-~- Register to receive message callbacks
1217 sprint("mqtt init success")
1218 else
1219 sprint("mqtt init failed:", err)
1220 end
1221 end
1222
1223 ~-~- Connect to the MQTT server
1224 function mymqtt_connect()
1225 sprint("mqtt connecting...")
1226 local stat, err = g_mq:connect(MQTT_CFG,MQTT_LWT, MQTT_CART)
1227 if stat == nil then
1228 sprint("mqtt connect failed:", err)
1229 return
1230 else
1231 sprint("mqtt connected")
1232 end
1233
1234 ~-~-subscribe topic format:$oc/devices/{device_id}/sys/commands/#
1235
1236 g_mq:subscribe('$oc/devices/60a71ccbbbe12002c08f3a1a_WECON/sys/commands/#', 0) 
1237 end
1238
1239 ~-~- Receive the message callback function
1240 function mymqtt_msg_callback(topic, msg)
1241 sprint("recv data!")
1242 sprint("topic:msg", topic,msg)
1243 print(msg)
1244 local revData = json.decode(msg)
1245 \\end
1246
1247 ~-~-Send data
1248 function send_Data()
1249 local pub_data = {
1250 msgType = 'deviceReq',
1251 data = ~{~{
1252 serviceId ='Battery',
1253 serviceData={
1254 batteryLevel = 55
1255 }
1256 }}
1257 }
1258 return g_mq:publish(pub_RE_TOPIC, json.encode(pub_data), 0, 0)
1259 end
1260 )))
1261 )))
1262
1263 4.Download project access into V-Box to test in debug page
1264
1265 (% style="text-align:center" %)
1266 [[image:1624506710354-406.png||height="658" width="1000" class="img-thumbnail"]]
1267
1268 (% style="text-align:center" %)
1269 [[image:1624506666650-161.png||height="547" width="1000" class="img-thumbnail"]]
1270
1271 == **2.6 AWS platform** ==
1272
1273 === **Log in AWS** ===
1274
1275 Login aws account and click“Connect an IoT device”
1276
1277 [[image:image-20220709165402-1.png]]
1278
1279 [[image:image-20220709165402-2.png]]
1280
1281
1282 === **Create policy** ===
1283
1284 Click “Secure”~-~-->“Policies”~-~-->“Create policy”~-~-->Click “Create”
1285
1286 [[image:image-20220709165402-3.png]]
1287
1288 Name the policy~-~-->Click “JSON”~-~-->Copy the following content~-~-->Click “Create”
1289
1290 [[image:image-20220709165402-5.png]]
1291
1292 [[image:image-20220709165402-4.png]]
1293
1294 {{code language="java"}}
1295 {
1296   "Version": "2012-10-17",
1297   "Statement": [
1298     {
1299       "Effect": "Allow",
1300       "Action": [
1301         "iot:Connect",
1302         "iot:Publish",
1303         "iot:Subscribe",
1304         "iot:Receive",
1305         "greengrass:Discover"
1306       ],
1307       "Resource": "*"
1308     }
1309   ]
1310 }
1311 {{/code}}
1312
1313 === **Create things** ===
1314
1315 Click “Manage”~-~-->“Things”~-~-->“Create things”~-~-->“Create single thing”
1316
1317 [[image:image-20220709165402-6.png]]
1318
1319 [[image:image-20220709165402-7.png]]
1320
1321 Name the thing~-~-->Click “Next”
1322
1323 [[image:image-20220709165402-8.png]]
1324
1325 Select the way to create certificate
1326
1327 [[image:image-20220709165402-9.png]]
1328
1329 Select policy
1330
1331 [[image:image-20220709165402-10.png]]
1332
1333 [[image:image-20220709165402-11.png]]
1334
1335
1336 === **MQTT.fx tool** ===
1337
1338 Click “View Setting” to get the “Broker Adress”
1339
1340 [[image:image-20220709165402-13.png]]
1341
1342 [[image:image-20220709165402-12.png]]
1343
1344 Create one connection in MQTT.fx tool, set broker port as 8883.
1345
1346 [[image:image-20220709165402-14.png]]
1347
1348 Upload the CA File, Client Certificate File, Client Key File
1349
1350 [[image:image-20220709165402-15.png]]
1351
1352 Publish message to topic “TEST”
1353
1354 [[image:image-20220709165402-17.png]]
1355
1356 Click”Test”~-~-->”MQTT test client”~-~-->”Subscrible to a topic”, to get message publish from MQTT.fx tool.
1357
1358 [[image:image-20220709173500-1.png]]
1359
1360 And we can also send message form AWS platform to MQTT.fx tool.
1361
1362 [[image:image-20220709165402-18.png]]
1363
1364 === **CloudTool** ===
1365
1366 Copy the same setting in MQTT.fx to MQTT configuration
1367
1368 [[image:image-20220709165402-19.png]]
1369
1370 Add a lua script and copy the lua demo into it.
1371
1372 [[image:image-20220709165402-20.png]]
1373
1374 {{info}}
1375 **✎Note:** Before using the following demo script, please make sure the V-Box firmware is newer than 22110701
1376 {{/info}}
1377
1378 {{code language="lua"}}
1379 sprint = print
1380
1381 --Cloud mode interface to obtain the MQTT information configured by the cloud platform: (5 returns, namely the server address, client ID, connection table, last word table, certificate table)
1382
1383 local MQTT_URL, MQTT_CLIENTID, MQTT_CFG, MQTT_LWT, MQTT_CART = mqtt.setup_cfg()
1384
1385 --publish to topics
1386
1387 local pub_RE_TOPIC = string.format('TEST')
1388
1389 --Subscribe topics
1390
1391 local Subscribe_RE_TOPIC1 = string.format('TEST')
1392
1393 --variable
1394
1395 local last_time = 0
1396
1397 --Timing main function
1398
1399 function aws.main()
1400
1401 sprint(os.date("%Y-%m-%d %H:%M %S", os.time()) .. " aws.main start")
1402
1403 if g_mq then
1404
1405 if g_mq:isconnected() then
1406
1407 send_Data()
1408
1409 else
1410
1411 if os.time() - last_time > 5 then
1412
1413 last_time = os.time()
1414
1415 mymqtt_connect()
1416
1417 end
1418
1419 end
1420
1421 else
1422
1423 mymqtt_init()
1424
1425 end
1426
1427 sprint(os.date("%Y-%m-%d %H:%M %S", os.time()) .. " aws.main end")
1428
1429 end
1430
1431
1432
1433 -- Initialize MQTT
1434
1435 function mymqtt_init()
1436
1437 sprint(string.format("mqtt init mqtt_url:%s mqtt_clientid:%s", MQTT_URL, MQTT_CLIENTID))
1438
1439 g_mq, err = mqtt.create(MQTT_URL, MQTT_CLIENTID, 1) -- Create the object and declare it as a global variable, 1 means using the domain to connect
1440
1441 if g_mq then
1442
1443 g_mq:on("message", mymqtt_msg_callback) -- Register to receive message callbacks
1444
1445 sprint("mqtt init success")
1446
1447 else
1448
1449 sprint("mqtt init failed:", err)
1450
1451 end
1452
1453 end
1454
1455 -- Connect to MQTT server
1456
1457 function mymqtt_connect()
1458
1459 sprint("mqtt connecting...")
1460
1461 local stat, err = g_mq:connect(MQTT_CFG,MQTT_LWT, MQTT_CART)
1462
1463 if stat == nil then
1464
1465 sprint("mqtt connect failed:", err)
1466
1467 return
1468
1469 else
1470
1471 sprint("mqtt connected")
1472
1473 end
1474
1475 g_mq:subscribe(Subscribe_RE_TOPIC1, 0)
1476
1477 end
1478
1479 -- Receive MQTT message callback function
1480
1481 function mymqtt_msg_callback(topic, msg)
1482
1483 print("topic:",topic)
1484
1485 print("revdata:",msg)
1486
1487 local revData = json.decode(msg)
1488
1489 print (revData)
1490
1491 if topic == Subscribe_RE_TOPIC1 then --Process topic information subscribed from the cloud
1492
1493 if string.match(topic,Subscribe_RE_TOPIC1) then
1494
1495 --if revData ~= nil then
1496
1497 for k,v in pairs (revData) do
1498
1499 print("printing revdata after kv here")
1500
1501 print (k,v)
1502
1503 end
1504
1505 print ("current state is",fanstate)
1506
1507 --end
1508
1509 end
1510
1511 end
1512
1513 end
1514
1515
1516
1517 --Get real-time data
1518
1519 function getData()
1520
1521 local jdata = {}
1522
1523 local addr = bns_get_alldata()
1524
1525 print(json.encode(addr))
1526
1527 for i,v in pairs(addr) do
1528
1529 if v[2] == 1 then
1530
1531 jdata[v[3]] = v[4]
1532
1533 end
1534
1535 end
1536
1537 return jdata
1538
1539 end
1540
1541 --send data
1542
1543 function send_Data()
1544
1545 local pub_data =
1546 {
1547 123
1548 }
1549
1550 sprint(json.encode(pub_data))
1551
1552 print("..........",pub_RE_TOPIC)
1553
1554 return g_mq:publish(pub_RE_TOPIC, json.encode(pub_data), 0, 0)
1555
1556 end
1557 {{/code}}
1558
1559 Get message in AWS
1560
1561 [[image:image-20220709165402-21.png]]
1562
1563 == **2.7 Mysql** ==
1564
1565 In this demo you can use Mysql import the data to the terminal device through the V-box or save the data to the any Mysql database by the V-box.
1566
1567 (% class="wikigeneratedid" id="H1.InstallMysql" %)
1568 **1.Install Mysql**
1569
1570 version
1571
1572 (% style="text-align:center" %)
1573 [[image:Mysql的软件版本.png]]
1574
1575 (% class="wikigeneratedid" id="H2.InstallNavicat" %)
1576 **2.Install Navicat**
1577
1578 (% class="wikigeneratedid" %)
1579 version
1580
1581 (% style="text-align:center" %)
1582 [[image:navicat 版本.png]]
1583
1584
1585 Connecting to Mysql with navicat.
1586
1587 (% style="text-align:center" %)
1588 [[image:连接到mysql.png]]
1589
1590 (% class="wikigeneratedid" id="H3.Createdatabase" %)
1591 **3.Create database**
1592
1593 Character set should be choose utf8mb3/utf8mb4 and Collation choose utf8mb3_danish_ci/utf8mb4_danish_ci.
1594
1595 (% style="text-align:center" %)
1596 [[image:创建数据库.png]]
1597
1598 (% class="wikigeneratedid" id="H4.Createdatatable" %)
1599 **4.Create data table**
1600
1601 Create a table, enter the fields you need.
1602
1603 (% style="text-align:center" %)
1604 [[image:创建表1.png]]
1605
1606
1607 Save, enter table name.
1608
1609 (% style="text-align:center" %)
1610 [[image:创建表2.png]]
1611
1612 (% class="wikigeneratedid" id="H5.InputTableData" %)
1613 **5.Input Table Data**
1614
1615 (% style="text-align:center" %)
1616 [[image:输入或者导入数据.png]]
1617
1618 (% class="wikigeneratedid" id="H6.Script" %)
1619 **6.Script**
1620
1621 **luaMySql.init(string sourcename, string username, string password, string host, number port, string character)**
1622
1623 **Function:** Configure database connection parameters
1624
1625 **Parameter:**
1626
1627 sourcename: the name of database
1628
1629 username: the username of the connection
1630
1631 password: the password of the connection
1632
1633 host: the host name of the connection
1634
1635 port: the host port of the connection
1636
1637 character: the character set of the connection
1638
1639 **Return:**
1640
1641 Succeed: string
1642
1643 Failed: multi
1644
1645 **luaMySql.exec(string statement)**
1646
1647 **Function:** Execute the given SQL statement without returning the result set (add, delete, change)
1648
1649 **Parameter:**
1650
1651 statement: the given SQL statement
1652
1653 **Return:**
1654
1655 Succeed: status: returns the number of rows affected by SQL statement execution.
1656
1657 Failed: nil, errorString
1658
1659 **luaMySql.execWithResult(string statement)**
1660
1661 **Function:** Execute the given SQL statement returning the result set (check)
1662
1663 **Parameter:**
1664
1665 statement: the given SQL statement
1666
1667 **Return:**
1668
1669 Succeed: table: returns the result set
1670
1671 Failed: nil, errorString
1672
1673 **For example:**
1674
1675
1676 {{code language="LUA"}}
1677 -- Assuming the "mysqlclient" library is properly installed and available
1678 mysql = require("mysqlclient")
1679
1680 function DataInitRight()
1681 local dbName = "excel"
1682 local user = "root"
1683 local pwd = "XXXXX"
1684 local host = "192.168.39.146"
1685 local port = 3306
1686 local character = "utf8mb3"
1687
1688 mysql.init(dbName, user, pwd, host, port, character)
1689 end
1690
1691 function ExecFunc()
1692 status, errorString = mysql.exec("delete from student where Name = 'XXX';") --Delete statement, column name = table element
1693 if nil == status then
1694 print("ExecFunc() error:", errorString)
1695 return -1
1696 else
1697 print("the number of rows affected by the command:", status)
1698 end
1699 return 0
1700 end
1701
1702
1703 function ExecWithResultFunc()
1704 status, errorString = mysql.execWithResult("select * from student;")
1705 if nil == status then
1706 print("ExecWithResultFunc() error:", errorString)
1707 return -1
1708 else
1709 print("ExecWithResultFunc() success : status type = ", type(status))
1710 print("ExecWithResultFunc() success : status len = ", #status)
1711 local num = #status
1712 local i = 1
1713 if num > 0 then
1714 for i = 1, num, 1 do
1715 local var = string.format("select result[%d] :Num = %d,Name = %s,Age = %d", i, status[i].Num, status[i].Name,status[i].Age) --Iterate through the data in the table, noting whether the elements are strings or numbers
1716 print(var)
1717 end
1718 end
1719 print("---------------")
1720 end
1721 return 0
1722 end
1723
1724 function MySQL.main()
1725 print("script running ...")
1726 DataInitRight()
1727
1728 -- use exec demo
1729 if ExecFunc() < 0 then
1730 return
1731 end
1732
1733 -- use execWithResult demo
1734 if ExecWithResultFunc() < 0 then
1735 return
1736 end
1737
1738 print("script running success")
1739 end
1740 {{/code}}
1741
1742 (% class="wikigeneratedid" id="H7.Debug" %)
1743 **7.Debug**
1744
1745 (% style="text-align:center" %)
1746 [[image:调试结果.png]]
1747
1748 (% class="wikigeneratedid" id="H8.Problem" %)
1749 8.Problem
1750
1751 During our debugging process it may there are some problems about Mysql, such as
1752
1753 * MySQL: Host  192.168.XXX.XXX  is not allowed to connect.
1754 * MySQL: Host  192.168.XXX.XXX  is blocked because of many connection errors.
1755 * MySQL: SSL connection error: unknown error number.
1756 * (((
1757 1449-The user specified as a definer(‘mysql.infoschema‘@localhost‘) does not exist.
1758 )))
1759
1760 This type of problem has nothing to do with scripts or devices, it is a Mysql configuration issue. If you have any of these problems, please look for a solution online.
1761
1762 {{info}}
1763 ✎Note: If you want to use CMD to access Mysql, you need to add the bin file to the environment variable, please check online for details of the operation.
1764 {{/info}}