# Connecting ewon flexy 202 to serverless cluster

**URL:** <https://community.hivemq.com/t/connecting-ewon-flexy-202-to-serverless-cluster/3132>\
**Category:** HiveMQ Cloud\
**Created:** [August 26, 2024, 3:55am UTC](https://community.hivemq.com/t/connecting-ewon-flexy-202-to-serverless-cluster/3132 "2024-08-26T03:55:52Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![fahmimff](https://avatars.discourse-cdn.com/v4/letter/f/7bcc69/32.png) [@fahmimff](https://community.hivemq.com/u/fahmimff)\
**Post date:** [August 26, 2024, 3:55am UTC](https://community.hivemq.com/t/connecting-ewon-flexy-202-to-serverless-cluster/3132/1 "2024-08-26T03:55:52Z")

</div>

Hi, I’m never use ewon flexy or hivemq before this. So my company want me to run this R&D. Basically, i’m stuck at how to connect my ewon flexy202 to the serverless cluster. Can i get any guidance to solve this issue? I use the basic IDE function in my ewon but keep failing.

---

<div class="post-metadata">

**Author:** ![Diego](https://avatars.discourse-cdn.com/v4/letter/d/f04885/32.png) [@Diego](https://community.hivemq.com/u/Diego)\
**Post date:** [August 26, 2024, 4:50pm UTC](https://community.hivemq.com/t/connecting-ewon-flexy-202-to-serverless-cluster/3132/2 "2024-08-26T16:50:27Z")

</div>

Hello @fahmimff

Welcome to the HiveMQ Community! I’m not familiar with Ewon Flexy 202 device, but I can try to help you. First HiveMQ Cloud only allows secure TLS connections, you need to ensure that your device supports TLS in their MQTT client implementation.

Additionally, to establish a TLS connection to the HiveMQ Cloud (Serverless offer), you must ensure that your device/client supports and uses the TLS protocol extension called “SNI” (Server Name Indication). This TLS extension provides the server’s hostname in the “Client Hello” TLS packet.

Can you please share which step are you stuck in? Any error message while trying to connect to HiveMQ Cloud?

Kind regards,  
Diego from HiveMQ Team

---

<div class="post-metadata">

**Author:** ![fahmimff](https://avatars.discourse-cdn.com/v4/letter/f/7bcc69/32.png) [@fahmimff](https://community.hivemq.com/u/fahmimff)\
**Post date:** [August 27, 2024, 8:43am UTC](https://community.hivemq.com/t/connecting-ewon-flexy-202-to-serverless-cluster/3132/4 "2024-08-27T08:43:37Z")

</div>

Thank you for responding.  
So basically i want to send tag value from my ewon to the hivemq serverless cloud cluster. The ewon use basic IDE to make MQTT connection. Since I’m new to this, most of the script I tried, I took from the internet. The error that I always get was ‘‘MQTT connect : failed’’ and ‘‘WAN interface not yet ready’’

I’m also a bit confuse with the serverless cluster. Do i need to do the credential and include the username and passsword in my script? And if I manage to establish the connection, where can i monitor the tag value from my ewon?

---

<div class="post-metadata">

**Author:** ![Diego](https://avatars.discourse-cdn.com/v4/letter/d/f04885/32.png) [@Diego](https://community.hivemq.com/u/Diego)\
**Post date:** [August 27, 2024, 10:38am UTC](https://community.hivemq.com/t/connecting-ewon-flexy-202-to-serverless-cluster/3132/5 "2024-08-27T10:38:50Z")

</div>

@fahmimff

You’re welcome. Yes, credentials (username/password) should be included in your Basic IDE script. Could you please share the script you are using?

Kind regards,  
Diego from HiveMQ Team

---

<div class="post-metadata">

**Author:** ![fahmimff](https://avatars.discourse-cdn.com/v4/letter/f/7bcc69/32.png) [@fahmimff](https://community.hivemq.com/u/fahmimff)\
**Post date:** [August 28, 2024, 3:35am UTC](https://community.hivemq.com/t/connecting-ewon-flexy-202-to-serverless-cluster/3132/6 "2024-08-28T03:35:06Z")

</div>

This is the default basic IDE script provided in my ewon flexy 202.

//////////////setting allll here//////////////  
tagheader$ = “MY999952”  
siteid$ = “DP\_Controls” //change this  
ip$="10.17.140.130 " //change this  
Last\_ConnStatus% = 0  
//Configure MQTT Connection parameters  
ClientID$ =“DP\_Controls\_EwonFlexy202” //change this  
MQTTBrokerURL$=“[Ewon MQTT Broker](https://tools.ewonsupport.biz/mqtt/)”

MQTTPort$ =“1883”  
Topic$=“Flexy/Data1”  
TopicFTP$=siteid$+“/”+“FTP”  
Goto CONNECTMQTT  
MQTTRECEIVEMSG:  
//Executed when receiving messages from Broker  
MessageQty%=Mqtt “READ” //Return the number of pending messages  
IF (MessageQty%\>0) Then  
MsgTopic$= MQTT “MSGTOPIC”  
MsgData$ = MQTT “MSGDATA”  
// @Log(“[MQTT SCRIPT] Message '”+ MsgData$ + “’ received on topic " +MsgTopic$)  
// \<TAG\_EWON\>@ = FCNV MsgData$,20,0,”%f"  
//GOTO MQTTRECEIVEMSG  
IF (MsgTopic$=TopicFTP$) Then  
mid\_time% = INSTR 1,MsgData$,“\*”  
start\_request$ = MsgData$(1 TO mid\_time%-1)  
end\_request$ = MsgData$( mid\_time% +1TO LEN(MsgData$))  
CLS  
PRINT "START: " + start\_request$ + " END: " +end\_request$  
start\_request% = FCNV start\_request$, 40  
end\_request% = FCNV end\_request$, 40  
@send\_ftp( “Flow”,“FT-GN21”,start\_request% ,end\_request% )  
@send\_ftp( “Pressure”,“PT-GN21”,start\_request% ,end\_request% )  
@send\_ftp( “Temperature”,“TT-GN21”,start\_request% ,end\_request% )  
@send\_ftp( “Tier1”,“FQ-GN21”,start\_request% ,end\_request% )

ENDIF  
END

CONNECTMQTT:  
MQTT “OPEN”, ClientID$ , MQTTBrokerURL$  
//MQTT “SetParam”, “Username”, Username$  
//MQTT “SetParam”, “Password”, Password$  
MQTT “SETPARAM”, “PORT”, MQTTPort$  
MQTT “SETPARAM”, “KEEPALIVE”, “10”  
SETSYS PRG,“RESUMENEXT”,1 //Continue in case of error at MQTT “CONNECT”  
MQTT “CONNECT”  
//If an error is raised → Log a message  
MQTT “SUBSCRIBE”,TopicFTP$,1  
ONMQTT “GOTO MQTTRECEIVEMSG”  
ErrorReturned% = GETSYS PRG,“LSTERR”  
IF ErrorReturned% = 28 THEN  
Print “[MQTT SCRIPT] WAN interface not yet ready”  
trig@ = 0  
SETSYS PRG,“RESUMENEXT”,0  
ENDif  
ONTIMER 1, “GOTO SENDDATA”  
TSET 1,30 //publish every 1 seconds  
END  
SENDDATA:  
//Read MQTT Connection Status (5 = Connected, other values = Not connected)  
ConnStatus% = MQTT “STATUS”  
IF Last\_ConnStatus% \<\> ConnStatus% THEN  
IF ConnStatus% = 5 THEN //Connection is back online  
trig@ = 1  
Print “[MQTT SCRIPT] Flexy connected to Broker”  
ELSE  
trig@ = 0  
Print “[MQTT SCRIPT] Flexy disconnected from Broker”  
ENDIF  
Last\_ConnStatus% = ConnStatus%  
ENDIF  
//IF Connected → Publish messages  
IF ConnStatus% = 5 THEN //If connected → Publish  
SETSYS PRG,“RESUMENEXT”,1  
// MsgToPublish$ = SFMT \<TAG\_EWON\>@,20,0,“%f”  
json\_1$ = ‘{’  
json\_1$ = json\_1$ +‘“tag\_header”:"’+tagheader$+‘",’  
json\_1$ = json\_1$ +‘“site\_id”:"’+siteid$+‘",’  
json\_1$ = json\_1$ +‘“ip”:"’+ip$+‘",’  
json\_1$ = json\_1$ +‘“datetime”: "’+@GetTime$()+‘",’  
json\_1$ = json\_1$ + ‘“data”: [’

json\_1$ = json\_1$ + ‘{“tagname”:’+‘“FT-GN21”,’  
json\_1$ = json\_1$ + ‘“define”:’+‘“Flow”,’  
json\_1$ = json\_1$ + ‘“value”:"’ + STR$ Flow@ + ‘"},’  
json\_1$ = json\_1$ + ‘{“tagname”:’+‘“TT-GN21”,’  
json\_1$ = json\_1$ + ‘“define”:’+‘“Temperature”,’  
json\_1$ = json\_1$ + ‘“value”:"’ + STR$ Temperature@ + ‘"},’  
json\_1$ = json\_1$ + ‘{“tagname”:’+‘“PT-GN21”,’  
json\_1$ = json\_1$ + ‘“define”:’+‘“Pressure”,’  
json\_1$ = json\_1$ + ‘“value”:"’ + STR$ Pressure@ + ‘"},’  
json\_1$ = json\_1$ + ‘{“tagname”:’+‘“FQ-GN21”,’  
json\_1$ = json\_1$ + ‘“define”:’+‘“Tier1”,’  
json\_1$ = json\_1$ + ‘“value”:"’ + Tier1@ + ‘"}’

json\_1$ = json\_1$ + ‘]}’  
///////////////

```
  MQTT "PUBLISH", Topic$ , json_1$, 0,0
  PRINT "send data 30s!"

```

///////////////////////

ErrorReturned = GETSYS PRG,“LSTERR”  
IF ErrorReturned=28 THEN //ERROR while publishing → No connection → Better to close and open  
MQTT “CLOSE”  
GOTO CONNECTMQTT  
ENDIF  
ELSE //If not connected → Save message in file  
Print “[MQTT SCRIPT] Flexy not connected”  
ENDIF  
END  
gettime:If trig@ =1 Then  
Goto “reconnect”  
Else  
Goto “lost”  
Endif  
END  
lost:If flag@ = 0 Then  
temp$ = Time$  
//temp2$ = temp$(1 To 2) +“/” +temp$(4 To 5) +“/” +temp$(7 To 10) + " " + temp$(12 To 13) + “:”+temp$(15 To 16)+“:”+ temp$(18 To 19)  
time\_down% = GETSYS PRG, “TIMESEC”  
//time\_down$ = Time$  
Print “record time down: " +temp$ +”:" STR$time\_down%  
flag@=1  
Else  
Print “done record time”  
Endif  
END  
reconnect:temp3$ = Time$  
temp4$ = temp3$(1 To 2) +“/” +temp3$(4 To 5) +“/” +temp3$(7 To 10) + " " + temp3$(12 To 13) + “:”+temp3$(15 To 16)+“:”+ temp3$(18 To 19)  
time\_end% = GETSYS PRG, “TIMESEC”  
Print "flexy reconnect to sever ! " +STR$time\_end%  
//time\_end$ = Time$  
//time\_duration% = FNCV time\_end$, 40 - FNCV time\_down$, 40  
time\_duration% = time\_end% - time\_down%  
//time\_hour4% = time\_duration%/(3600_4)//get hour .  
time\_hour4%= time\_duration%/(60)  
duration@ = time\_duration%/(2_3600)  
count\_h@ = duration@  
start\_down@ = SFMT time\_down%, 40  
end\_down@ = SFMT time\_end%, 40  
Print "duration " + time\_hour4%  
If (count\_h@ \<2 ) Then  
Print “lost \<4”+ STR$time\_hour4%  
time\_down% = time\_down%+10  
time\_end% = time\_end% + 10

```
 @send_ftp( "Flow","FT-GN21",time_down% ,time_end% )
 @send_ftp( "Temperature","TT-GN21",time_down% ,time_end% )
 @send_ftp( "Pressure","PT-GN21",time_down% ,time_end% )
 @send_ftp( "Tier1","FQ-GN21",time_down% ,time_end% )
 
  // @send_ftp( "connect","COMMUNICATION",time_down% ,time_end% )

```

Else  
//time\_start\_s% = time\_down% -30_60  
time\_down% = time\_down%+10  
time\_start\_s% = time\_down%  
FOR i% =1 TO count\_h@  
time\_end\_c% = time\_down% + 3600_2\*i%  
//print “c1”+ STR$time\_end\_c%  
time\_end\_c1% = time\_end\_c%

```
@send_ftp( "Flow","FT-GN21",time_start_s% ,time_end_c% )
@send_ftp( "Temperature","TT-GN21",time_start_s% ,time_end_c% )
@send_ftp( "Pressure","PT-GN21",time_start_s% ,time_end_c% )
@send_ftp( "Tier1","FQ-GN21",time_start_s% ,time_end_c% )

 time_start_s% = time_end_c%
Print "FTP break file!"
NEXT i%
time_end% = time_end% + 10
@send_ftp( "Flow","FT-GN21",time_end_c% ,time_end% )
@send_ftp( "Temperature","TT-GN21",time_end_c% ,time_end% )
@send_ftp( "Pressure","PT-GN21",time_end_c% ,time_end% )
@send_ftp( "Tier1","FQ-GN21",time_end_c% ,time_end% )

  //@send_ftp( "connect","COMMUNICATION",time_down% ,time_end% )

```

Print “time\_from\_start\_end” + STR$time\_duration%  
Endif  
flag@ = 0  
END  
unction send\_ftp($tagname$,$define$,$start\_time%,$end\_time%)  
$start\_time% =$start\_time%  
start\_time\_parse$ = SFMT $start\_time%, 40  
time\_start\_ftp$ = start\_time\_parse$(1 To 2) + start\_time\_parse$(4 To 5) + start\_time\_parse$(7 To 10) + “_" + start\_time\_parse$(12 To 13) + start\_time\_parse$(15 To 16)+ start\_time\_parse$(18 To 19)  
//$end\_time% = $end\_time%  
end\_time\_parse$ = SFMT $end\_time%, 40  
time\_end\_ftp$ = end\_time\_parse$(1 To 2) + end\_time\_parse$(4 To 5) + end\_time\_parse$(7 To 10) + "_” + end\_time\_parse$(12 To 13) + end\_time\_parse$(15 To 16)+ end\_time\_parse$(18 To 19)  
Print “call ftp send” + time\_start\_ftp$ +“: :” +time\_end\_ftp$  
filename1$ = tagheader$ +“_“+siteid$+”_”+$define$+“_“+$tagname$+”_”+ time\_end\_ftp$ +“.csv”  
stringfile$=“[$dtHL$ftT$et”+time\_end\_ftp$+“$st”+time\_start\_ftp$ +“$fnirc\_”+$tagname$+“.txt$tn”+$tagname$+“]”  
//PUTFTP filename$,“[$dtHL$ftT$et”+time\_end\_ftp$+“$st”+time\_start\_ftp$ +“$fnirc\_”+$tagname$+“.txt$tn”+$tagname$+“]”  
PUTFTP filename1$,stringfile$  
TSET 3,1  
ONTIMER 3, “GOTO Delay”

Delay://PRINT " Send FTP file " + filename$+" "+stringfile$  
TSET 3,0  
END  
Hourmeter:hourmeterdword@=hourmeterdword@+1  
hourmeterd@=VAL(“hourmeterdword@”)  
hourmeter@=hourmeterd@/10  
If hourmeter@\>100000 Then  
hourmeterdword@=0  
EndIf  
E\_Trigger@ = 1  
If E\_Count1@ \< 360 Then  
E\_TimeDiff@ = 360 - E\_Count1@  
E\_TotOffset@ = E\_FlowAve@ \* E\_TimeDiff@ / 3600  
EndIf  
E\_Count1@ = 0  
E\_FlowSum@ = 0  
END

Calculate: If E\_Trigger@ = 0 Then  
E\_Count1@=0  
E\_FlowSum@=0  
E\_TotOffset@=0  
EndIf

If E\_Trigger@ = 1 Then  
E\_Count1@ = E\_Count1@ + 1  
E\_FlowSum@ = E\_FlowSum@ + Flow@  
E\_FlowAve@ = E\_FlowSum@/E\_Count1@  
EndIf  
////////////////////////////  
If Flow@ \>= 100 Then  
If Flow2@ \< 1.0 Then  
Flow2@ = Flow2@ + ((Flow@-100)/3600) + E\_TotOffset@  
Else  
Flow2@ = Flow2@ + ((Flow@-100)/3600) + E\_TotOffset@  
Tier2P@ = Tier2P@ +1.0  
Flow2@ = Flow2@ -1.0  
EndIf  
If Flow1@ \< 1.0 Then  
Flow1@ = Flow1@ + 100/3600 + E\_TotOffset@  
Else  
Flow1@ = Flow1@ + 100/3600 + E\_TotOffset@  
Tier1P@ = Tier1P@ + 1.0  
Flow1@ = Flow1@ - 1.0  
EndIf  
Else   
If Flow1@ \< 1.0 Then  
Flow1@ = Flow1@ + Flow@/3600 + E\_TotOffset@  
Else  
Flow1@ = Flow1@ + Flow@/3600 + E\_TotOffset@  
Tier1P@ = Tier1P@ + 1.0  
Flow1@ = Flow1@ - 1.0  
EndIf  
EndIf  
If E\_TotOffset@ \<\> 0 Then  
E\_TotOffset\_Last@=E\_TotOffset@  
EndIf  
E\_TotOffset@=0  
tier1\_pre@ = Tier1P@  
tier2\_pre@ = Tier2P@

PressBaseStd = 1.013 //Base pressure standard in bar  
PressBaseNorm = 1.013 //Base pressure normal in bar  
TempBaseStd = 288.15 //Base temperature standard in Kelvin  
TempBaseNorm = 273.15 //Base temperature normal in Kelvin  
Density\_N2 = 1.2506 //Density at STP for N2 gas in kg/m3  
Density\_O2 = 1.429 //Density at STP for O2 gas in kg/m3  
Density\_H2 = 0.090 //Density at STP for H2 gas in kg/m3  
Density\_Ar = 1.78 //Density at STP for Ar gas in kg/m3  
If CalibrationTrigger@ = 1 Then  
Index1@ = Index1@ + 1

```
Tier1P@ = tier1_pre@ + TotalizerOffset@

TotalizerOffset@ = 0

PressureCalc@ = CalibrationPressure@
TempCalc@ = CalibrationTemperature@

  If Index1@ > 3600 Then
    CalibrationTrigger@ = 0
  Endif

```

Else  
Index1@ = 0  
PressureCalc@ = Pressure@  
TempCalc@ = Temperature@  
EndIf

If Temperature@ \< 0 Then  
TempCalc@ = 30  
EndIf

If Pressure@ \< 0 Then  
PressureCalc@ = 8  
EndIf  
//If Flow@ \>= 0 Then  
//Volumetric Flowmeters with 4-20mA Output  
// FlowComp\_Vol\_Std@ = Flow@ \* ((Pressure@ + 1.013) / PressBaseStd) \* (TempBaseStd/(Temperature@ + 273.15))  
//Differential Pressure Flowmeters with 4-20mA output with linear flow  
//FlowComp\_Vol\_Std@ = Flow@ \* (SQRT(Pressure@ / PressBaseStd)) \* (SQRT(TempBaseStd/(Temperature@ + 273.15)))  
Else  
// FlowComp\_Vol\_Std@ = 0 //Standard cubic meter flow calculation (SCM/h)  
EndIf

// FlowComp\_Vol\_Norm@ = FlowComp\_Vol\_Std@ \* 0.947943779 //Normal cubic meter flow calculation (NCM/h)

// FlowComp\_Mass@ = FlowComp\_Vol\_Std@ \* Density\_N2 //Mass flow calculation (kg/h)

// highdigit1display@=VAL(“high\_digit1@”)

low\_digit1@=tier1\_pre@  
IF low\_digit1@\>99999 Then  
high\_digit1@=high\_digit1@+1  
Tier1P@=0  
EndIF  
Tier1@= STR$ high\_digit1@+ SFMT low\_digit1@,20,0,“%08.2f”

low\_digit2@=tier2\_pre@  
IF low\_digit2@\>99999 Then  
high\_digit2@=high\_digit2@+1  
Tier2P@=0  
EndIF

Tier2@= STR$ high\_digit2@+ SFMT low\_digit2@,20,0,“%08.2f”

END

---

<div class="post-metadata">

**Author:** ![Diego](https://avatars.discourse-cdn.com/v4/letter/d/f04885/32.png) [@Diego](https://community.hivemq.com/u/Diego)\
**Post date:** [August 28, 2024, 10:05am UTC](https://community.hivemq.com/t/connecting-ewon-flexy-202-to-serverless-cluster/3132/7 "2024-08-28T10:05:56Z")

</div>

Hello @fahmimff

I took the basic script example from this [page](https://tools.ewonsupport.biz/mqtt/) to get started and added some configurations, please follow the instructions.

1. Ensure you are using the latest Ewon Flexy 202 firmware available.

2. Download and upload it to your device the Let’s Encrypt CA certificate file that must be used with the script. Link to download: [https://letsencrypt.org/certs/isrgrootx1.pem](https://letsencrypt.org/certs/isrgrootx1.pem)

3. Edit Cluster URL, Username, and Password from the script below copy it in your Ewon Flexy BASIC IDE (Init Section), and save it.

```auto
CLS
SETSYS INF, "LOAD"
SerNum$ = GETSYS INF, "SERNUM"
SendTagValues% = 0

//###################################
//######## CONFIG ###############
//###################################

MQTTBrokerURL$ = "TYPE_YOUR_HIVEMQ_CLOUD_CLUSTER_URL"
MQTTPort$ = "8883"
TopicToPublishOn$ = "/topic/flexy/" + SerNum$ + "/data"
TopicToSubscribe$ = "/topic/flexy/" + SerNum$ + "/command"
MsgToPublish$ = "Hello From Flexy " + SerNum$

//<--Uncomment the below line if you want to send your Tag values in a json format-->
//SendTagValues% = 1

//To update Tags, you can send/publish the json {"tagname1":12.3,"tagname2":4.56}

//###################################
//######## END CONFIG ###############
//###################################

//START SCRIPT
Last_ConnStatus% = 0
//Configure MQTT Connection parameters

CONNECTMQTT:
MQTT "OPEN", SerNum$ , MQTTBrokerURL$
MQTT "SETPARAM", "PORT", MQTTPort$ 
MQTT "SETPARAM", "KEEPALIVE", "60"
MQTT "SETPARAM", "USERNAME", "TYPE_YOUR_HIVEMQ_CLOUD_USERNAME"
MQTT "SETPARAM", "PASSWORD", "TYPE_YOUR_HIVEMQ_CLOUD_PASSWORD"
MQTT "SETPARAM", "TLSVERSION", "tlsv1.2" //Firmware 14.8 Required
MQTT "SETPARAM", "PROTOCOLVERSION", "3.1.1"
MQTT "SETPARAM", "CAFILE", "/usr/isrgrootx1.pem"
MQTT "SETPARAM", "WILLTOPIC", "/willtopic"
MQTT "SETPARAM", "WILLPAYLOAD", "Flexy " + SerNum$ + " is disconnected"
MQTT "SUBSCRIBE",TopicToSubscribe$,1
//Launch the MQTT process in the background
SETSYS PRG,"RESUMENEXT",1 //Continue in case of error at MQTT "CONNECT"
MQTT "CONNECT"
//If an error is raised --> Log a message
ErrorReturned% = GETSYS PRG,"LSTERR"
IF ErrorReturned% = 28 THEN @Log("[MQTT SCRIPT] WAN interface not yet ready")
SETSYS PRG,"RESUMENEXT",0
//When receiving a message from Broker, "GOTO MQTTRECEIVEMSG"
ONMQTT "GOTO MqttRx"
ONTIMER 1, "GOTO SENDDATA"
TSET 1,5 //publish every 5 seconds
END

SENDDATA:
//Read MQTT Connection Status (5 = Connected, other values = Not connected)
ConnStatus% = MQTT "STATUS"
IF Last_ConnStatus% <> ConnStatus% THEN
  IF ConnStatus% = 5 THEN //Connection is back online
    @Log("[MQTT SCRIPT] Flexy connected to Broker")
  ELSE
    @Log("[MQTT SCRIPT] Flexy disconnected from Broker")
  ENDIF
  Last_ConnStatus% = ConnStatus%
ENDIF
//IF Connected --> Publish messages
IF ConnStatus% = 5 THEN //If connected --> Publish

  IF SendTagValues% = 1 THEN
    NB% = GETSYS PRG,"NBTAGS"
    MsgToPublish$ = "["
    FOR i% = 0 TO NB%-1
      SETSYS Tag, "load",-i%
      TagName$ = GETSYS Tag, "Name"
      TagValue$ = GETSYS Tag, "TagValue"
      IF i% = 0 THEN
        MsgToPublish$ = MsgToPublish$ + '{"tag":"' + TagName$ + '","value":"' + TagValue$ + '","time":"' + @GetTime$() + '"}'
      ELSE  
        MsgToPublish$ = MsgToPublish$ + ',{"tag":"' + TagName$ + '","value":"' + TagValue$ + '","time":"' + @GetTime$() + '"}'
      ENDIF
    NEXT i%
    MsgToPublish$ = MsgToPublish$ + "]"
  ENDIF

  MQTT "PUBLISH", TopicToPublishOn$ , MsgToPublish$, 0,0
  PRINT "[MQTT SCRIPT] Message '" + MsgToPublish$ + "' sent on topic : " + TopicToPublishOn$
ELSE //If not connected --> Save message in file
  @Log("[MQTT SCRIPT] Flexy not connected")
ENDIF
END

MqttRx:
//Executed when receiving messages from Broker
//Example : {"TestMQTT":0,"string1":"test string","ana1":12.3} to update Tags

   MessageQty%=Mqtt "READ" //Return the number of pending messages
   IF (MessageQty%>0) Then
      MsgTopic$= MQTT "MSGTOPIC"
      MsgData$ = MQTT "MSGDATA"
      Print "Subscribe Message Received:" +MsgTopic$
      Print "Message:" +MsgData$
      posJson% = 1
      
ReadJsonNext:
      JsonPart$ = @SplitString$(MsgData$,posJson%, ",")
      //PRINT JsonPart$
      posJson% = posJson%+1
      IF JsonPart$ = "" THEN GOTO ReadJsonEnd //no more data to read

      JsonPart$ = JsonPart$ + "}" // to help to detect first and middle elements end

      Pos1stQuote% = INSTR 1,JsonPart$, '"'
      Pos1stQuote% = Pos1stQuote%+1
      Pos2stQuote% = INSTR Pos1stQuote%,JsonPart$, '"'
      TagNameToWrite$ = JsonPart$(Pos1stQuote% TO Pos2stQuote%-1)
   
      Pos1stColumn% = INSTR 1,JsonPart$, ':'
      Pos1stColumn% = Pos1stColumn%+1
      Pos2stBraket% = INSTR Pos1stColumn%,JsonPart$, '}'
      TagValueToWrite$ = JsonPart$(Pos1stColumn% TO Pos2stBraket%-1)
   
      //PRINT TagNameToWrite$ + " - " + TagValueToWrite$
      IF TagValueToWrite$ >"" THEN
        //Print "valid value"
        SETSYS PRG,"RESUMENEXT",1
        SETSYS Tag, "load", TagNameToWrite$
        LastError%= GETSYS PRG,"LSTERR"
        IF LastError% = -4 THEN SETSYS PRG,"RESUMENEXT",0 : GOTO ReadJsonNext
        myType$ = GETSYS TAG, "Type"
        If myType$ = "6" THEN
           TagValueToWrite$ = JsonPart$(Pos1stColumn%+1 TO Pos2stBraket%-2) //Trim off quote marks
           //PRINT TagValueToWrite$
           SETIO TagNameToWrite$, TagValueToWrite$
        ELSE
          SETIO TagNameToWrite$, VAL TagValueToWrite$
        ENDIF
        SETSYS PRG,"RESUMENEXT",0
      ENDIF
      GOTO ReadJsonNext
ReadJsonEnd:   
      //PRINT MsgData$ + " (Topic: " + MsgTopic$ + ")"
      GOTO MQTTRx
   ENDIF
END

FUNCTION SplitString$ ($StringToParse$,$Pos%, $char$)

  $e% = 1
  $loopnbr% = 0
  $NextItem:
  $f% = INSTR $e% , $StringToParse$ , $char$
  //PRINT STR$ $f%
  //LAST ELEMENT
  IF $f% = 0 THEN 
      $B$ = $StringToParse$( $e% TO LEN $StringToParse$)
      IF $Pos% > $loopnbr% + 1 THEN $B$ = ""
      GOTO $EndOfLine       
  ENDIF
  
  $loopnbr% = $loopnbr% + 1
  $B$ = $StringToParse$( $e% TO $f%-1)
  IF $Pos% = $loopnbr% THEN GOTO $EndOfLine
  $e% = $f% + 1 //REM Init for next loop/line
  
  GOTO $NextItem
  $EndOfLine:
  $SplitString$ = $B$
ENDFN

FUNCTION Log($Msg$)
  LOGEVENT $Msg$ ,100
  PRINT $Msg$
ENDFN

FUNCTION GetTime$()
  $a$ = Time$
  $GetTime$ = $a$(7 To 10) + "-" + $a$(4 To 5) + "-" + $a$(1 To 2) + " " + $a$(12 To 13)+":"+$a$(15 To 16)+":"+$a$(18 To 19)
ENDFN

```

Kind regards,  
Diego from HiveMQ Team
