Switch to desktop version  
Validating Wifi or internet connection - Printable Version

+- Ewon Technical Forum (https://techforum.ewon.biz)
+-- Forum: Development (https://techforum.ewon.biz/forum-50.html)
+--- Forum: Java (https://techforum.ewon.biz/forum-53.html)
+--- Thread: Validating Wifi or internet connection (/thread-2801.html)



Validating Wifi or internet connection - james.taylor@malonegroup.com - 09-10-2025

I have written a MQTT project for my Ewon Flexy 205, which appears to connect to my broker successfully, however i an gelling LOTS of messages in my error log

Time                        | Event  | Description                           | Originator                
09/10/2025 13:40:12 | 38003 | mqtt-Cannot start connection | jvmasync
09/10/2025 13:40:12 | 38004 | mqtt-Connect failed               | jvmasync

these are repeated alot and eventually, my Ewon reboots its self  (has just done it while writing this  )

Time                        | Event   | Description                                                                                | Originator    
09/10/2025 09:32:27 | -22602 | System Booting, FWR: 14.9s4 (14.9), SN: 2210-0019-24 [EF0000]  | elog


Sorry but i'm going pasting my class here in the hope someone can identify what is my issue:

I recognise i have some loops in here that repeatedly try and connect to the broker in my void "EstablishConnection"

When the " mqtt-Cannot start connection" messages appear, i dont have any entries in the log for "EstablishConnection: Retrying connection..." which leads me to believe that its not my code generating the errors, but something within 
the "com.ewon.ewonitf.MqttClient" library


Now, is there any way i can use the SysControlBlock to check if my internet connection is established before i do any kind of connection to my broker?


Thanks in advance.

Code:
import java.util.ArrayList;
import com.ewon.ewonitf.MqttMessage;
import com.ewon.ewonitf.EWException;
import com.ewon.ewonitf.IOManager;
//import com.ewon.ewonitf.MqttClient;
import com.ewon.ewonitf.SysControlBlock;

/**
* MQTT_Thread
*
* Handles MQTT communication for an Ewon device.
* Periodically reads tag values, detects changes, and publishes data as JSON.
*/
public class MQTT_Thread implements Runnable {

    private Thread thread = null;
    private MQTTConfig config;
    private boolean enable;
    private String eWonSN = "";
    private String commentPrefix = "********** ";
    private String commentSuffix = " **********";
   
    //  int mqtt_STATE_EXISTS = 0;
    //  int mqtt_STATE_HAS_SEM = 1;
    //  int mqtt_STATE_HAS_LOCK = 2;
      final int mqtt_STATE_LOOP_STARTED = 3;
    //  int mqtt_STATE_DISCONNECTED = 4;
      final int mqtt_STATE_CONNECTED = 5;
     
    /**
     * Start the MQTT thread if enabled in configuration.
     */
    public void start() throws Exception {
        // Read the configuration file
        config = new MQTTConfig();
       
        if (config.isValid()) {
            enable = config.enable();
           
            // Store the JSON
        try { IOManager.writeTag("Config_MQTT_Text", config.toString()); }
        catch (Exception e) { System.out.println("Error Writing JSON To Tag: " + e.getLocalizedMessage()); }
            
            if (enable) {
                WriteComment("Creating MQTT Thread");
                // Create a new thread if enabled
                if (thread == null) {
                    thread = new Thread(this);
                    thread.start();
                }
            } else { WriteComment("MQTT Threads Disabled in Configuration"); }
        } else { WriteComment("MQTT JSON Not Valid"); }
    }

    /**
     * Main loop for reading and publishing MQTT data.
     */   
    public void run() {
        try {
            
            WriteHeading("JAVA Started");
            
            // Create the System Control Block
            SysControlBlock Sys = new SysControlBlock(SysControlBlock.INF);
            // Save the Serial Number
            eWonSN = Sys.getItem("SerNum");
           
            String topicPath = config.topicPath() + eWonSN;
            int defaultTime = config.defaultTime();
            int sleepTime = config.sleepTime();
            int QOS = config.QOS();
            String tagGroup = config.tagGroup();
            ArrayList topics = config.topics();
           
            WriteHeading("MQTT Publush Settings");
            WriteComment("MQTT Publush Settings: Topic: " + topicPath, true);
            WriteComment("MQTT Publush Settings: Sleep Time: " + sleepTime + "ms", true);
            WriteComment("MQTT Publush Settings: Sample Time: " + defaultTime + "s", true);
            WriteComment("MQTT Publush Settings: QOS: " + QOS , true);
            WriteComment("MQTT Publush Settings: tagGroup: " + tagGroup, true);
            WriteHeading("MQTT Publush Settings");
           
            // MQTT Connected Status
            boolean connected = false;
           
            // Create MQTT Client Object
            MQTTClient Mqtt_c = null;
    
            // Establish a new connection
            while (!connected) {
                // Establish a new connection
                Mqtt_c = EstablishConnection(Mqtt_c);
                connected = isClientConnected(Mqtt_c);
            }
           
            // Check a valid client exists
            if (Mqtt_c != null ) {
                // Are we connected?
                connected = isClientConnected(Mqtt_c);  
          
                // Subscribe to all configured topics
                for (int i = 0; i < topics.size(); ++i) {
                    WriteComment("MQTT: Subscribing to " + topics.get(i).toString());
                    Mqtt_c.subscribe(topics.get(i).toString(), 0);
                    WriteComment("MQTT: Subscription getStatus: " + Mqtt_c.getStatus());               
                }
    
                // Define variables
                int elapsedTime = 0;
                boolean valuesChanged = true; // Monitor changes in value
                String ewonTag = "";
    
                // Convert default time to milliseconds
                defaultTime = defaultTime * 1000;
    
                // Create new Tags Handler
                EwonTags myTags = new EwonTags();
    
                // Generate a list from the configured tag group
                ArrayList tagList = myTags.GetGroupTags(tagGroup);
    
                // Default the Array to 1000 Tags to allow adding/removing during runtime
                float[][] values = new float[1000][3];
    
                WriteHeading("MQTT Publish: Starting Tag monitoring Loop");
    
                // Main loop to read tag values
                while (true) {   
                    // Get the connected Status
                    connected = isClientConnected(Mqtt_c);
                   
                    // Loop until we can connect
                    while (!connected) {
                        // Establish a new connection
                        Mqtt_c = EstablishConnection(Mqtt_c);
                        connected = isClientConnected(Mqtt_c);  
                    }
                    
                    // Record current time in milliseconds (Epoch)
                    long epoch = System.currentTimeMillis();
    
                    try {
                        // Get the number of tags
                        int tagCount = tagList.size();
    
                        for (int i = 0; i < tagCount; i++) {
                            if (i < tagCount) {
                                // Update previous value
                                values[i][1] = values[i][0];
                                ewonTag = (String) tagList.get(i);
    
                                try {
                                    // Skip if tag previously had an error
                                    if (values[i][2] != -1) {
                                        // Read current tag value
                                        values[i][0] = com.ewon.ewonitf.IOManager.readTagAsFloat(ewonTag);
                                        values[i][2] = 0; // Error = False
    
                                        // Detect change
                                        if (values[i][0] != values[i][1]) { valuesChanged = true; }
                                    }
                                } catch (Exception ex) {
                                    handleError(ex, "Error with Tag: \"" + ewonTag + "\" msg:");
                                    values[i][0] = 0;
                                    values[i][1] = 0;
                                    values[i][2] = -1; // Set Reading Error = True
                                }
                            } else {
                                // Reset unused values
                                values[i][0] = 0;
                                values[i][1] = 0;
                                values[i][2] = -1;
                            }
                        }
    
                        // If time or values changed, publish messages
                        if ((elapsedTime >= (defaultTime - sleepTime)) || valuesChanged) {
    
                            // For each tag, publish message
                            for (int i = 0; i < tagCount; i++) {
                                if (values[i][2] == 0) { // Read OK
                                    ewonTag = (String) tagList.get(i);
                                    String topic = topicPath;
    
                                    // Build JSON payload
                                    JSONObject payload = new JSONObject();
                                    payload.put("time", String.valueOf(epoch));
                                    payload.put("id", ewonTag);
                                    payload.put("pv", String.valueOf(values[i][0]));
                                        
                                    try {
                                        
                                        // Get the connected Status
                                        connected = isClientConnected(Mqtt_c);
                                        if (connected) {
                                            // Publish new message (no retain)
                                            Mqtt_c.publish(new MqttMessage(topic, payload.toString()), QOS, false);
                                            WriteComment("MQTT : value published: " + payload);
                                        } else { WriteComment("MQTT : value NOT published: Mqtt_c.GetStatus: " + Mqtt_c.getStatus()); }
                                    }
                                    catch (EWException ex) { handleError(ex, "EWException in loop:"); }
                                    catch (Exception ex) { handleError(ex, "Exception in loop:"); }
                                   
                                }
                                // Reset error flag
                                values[i][2] = 0;
                            }
    
                            // Rebuild the tag list in case tags have changed dynamically
                            tagList = myTags.GetGroupTags(tagGroup);
                        }
    
                        // Reset timer if needed
                        if (elapsedTime >= (defaultTime - sleepTime)) { elapsedTime = 0; }
    
                    } catch (Exception ex) { handleError(ex, "Error in loop:");}
    
                    // Calculate when to run again
                    long deltaTime = sleepTime - (System.currentTimeMillis() - epoch);
                    deltaTime = Math.max(deltaTime, 1000); // Prevent negative sleep times
    
                    // Add asleep between checking values
                    try { Thread.sleep(deltaTime); }
                    catch (InterruptedException e) { e.printStackTrace();}               
                   
                    // Reset changed flag
                    valuesChanged = false;
                    elapsedTime += deltaTime;
                }               
            }
        } catch (Exception ex) { handleError(ex, "Error occurred:"); }       
    }
   
    /**
     * Handle a Throwable Error with a comment
     * @param ex
     * @param comment
     */
    public void handleError(Throwable ex, String error) {
        if (error != null && !error.equals("")) { WriteError(error + ' ' + ex.getLocalizedMessage());}
        ex.printStackTrace(System.err); // ensures it prints to stderr
    }
   
    /**
     * Handle a Throwable Error
     * @param ex
     */
    public void handleError(Throwable ex) {
        handleError(ex, null);
    }
   
    /**
     * Establish new connection
     * @param existingClient the current MQTT client, may be null
     * @return a connected MQTTClient instance, or null if connection fails
     */
    public MQTTClient EstablishConnection(MQTTClient existingClient) {

        int maxRetries = 50; // Limit the number of retries
        int retryDelayMs = 5000; // Set a reconnection delay
       
        boolean connected = false;
        MQTTClient client = existingClient;

        // Read configuration parameters
        String brokerHost = config.brokerHost();
        String brokerPort = config.brokerPort();
        String brokerUsername = config.brokerUsername();
        String brokerPassword = config.brokerPassword();
        String brokerLog = config.brokerLog();
        boolean brokerUseCert = config.brokerUseCert();

        try {
            if (client == null) {

                WriteHeading("EstablishConnection: Initilise Connection");
                WriteComment("Broker Settings: JAVA Script Starting", true);
                WriteComment("Broker Settings: ClientID: " + eWonSN + " (Ewon Serial Number)", true);
                WriteComment("Broker Settings: Host: " + brokerHost + ", Port: " + brokerPort, true);
                if (brokerUsername != null && !brokerUsername.equals("")) {
                    WriteComment("Broker Settings: Username: " + brokerUsername, true);
                    WriteComment("Broker Settings: Password: " + brokerPassword, true);
                }
                WriteComment("Broker Settings: Logging: " + brokerLog, true);     
                WriteComment("Broker Settings: Use Certificates: " + brokerUseCert, true);               

                // Create MQTT Client Object
                client = new MQTTClient(eWonSN, brokerHost);

                // Set Broker Port and options
                client.setOption("port", brokerPort);

                // Set the Username and Password if provided
                if (brokerUsername != null && !brokerUsername.equals("")) {
                    client.setOption("Username", brokerUsername);
                    client.setOption("Password", brokerPassword);
                }

                // Set the logging value
                client.setOption("log", brokerLog);

                // Assign the Certificates to the device
                try {
                    WriteComment("Broker Settings: Loading Certificates:", true);
                    client.setOption("cafile", "/usr/isrgrootx1.pem");
                    if (brokerUseCert) {
                        client.setOption("certfile", "/usr/plc.cert.pem");
                        client.setOption("keyfile", "/usr/plc.key.pem");
                    }
                } catch (Exception ex) { handleError(ex, "Error occurred:"); }
               
                WriteHeading("EstablishConnection: Client Configured");               
            }

            // Check if client is connected
            connected = isClientConnected(client);
           
            for (int attempt = 1; attempt <= maxRetries; attempt++) {
            //while (!connected) {
                // Attempt to connect
                WriteComment("EstablishConnection: Attempting to Connect...");
                client.connect();
    
                int status = client.getStatus();
                connected = isClientConnected(client);               
                if (connected) {
                    WriteComment("Mqtt_c.GetStatus: " + status);
                    WriteComment("EstablishConnection: Connected to: " + brokerHost + ":" + brokerPort);
                    WriteHeading("EstablishConnection: Client Connected");
                    return client; // success
                } else {
                    WriteComment("EstablishConnection: Retrying connection...");
                    try {
                        Thread.sleep(retryDelayMs);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        WriteError("EstablishConnection: Thread interupted");
                        break; // stop retrying if thread interrupted
                    }
                }
            }
           
            WriteError("Failed to connect after " + maxRetries + " attempts");
            return client; // success
        }
        catch (EWException ex) { handleError(ex, "EstablishConnection: EWException:"); }
        catch (Exception ex) { handleError(ex, "EstablishConnection: Exception:"); }
       
        return null; // failed connection
    }

    /**
     * Establish new connection
     * @param existingClient the current MQTT client, may be null
     * @return a connected MQTTClient instance, or null if connection fails
     */
    public boolean isClientConnected(MQTTClient existingClient) {
        int status = 0;
        boolean connected = false;
        try {
            if (existingClient != null ) {
                // Get the connected Status
                status = existingClient.getStatus();
                connected =(status == mqtt_STATE_CONNECTED || status == mqtt_STATE_LOOP_STARTED);
            }
        }
        catch (EWException ex) { handleError(ex, "isClientConnected: EWException:"); }
        return connected;
    }
   
    /**
     * Write a comment to the Log
     * @param comment
     * @param includePrefix
     */
    public void WriteComment(String comment, boolean includePrefix) {        
        if (includePrefix) { comment = commentPrefix + comment;}
        System.out.println(comment);
    }
   
    /**
     * Write a comment to the Log
     * @param comment
     */
    public void WriteComment(String comment) {
        WriteComment(comment, false);
    }
   
    /**
     * Write a Heading to the Log
     * @param comment
     */
    public void WriteHeading(String comment) {
        System.out.println(commentPrefix + comment + commentSuffix);
    }
   
   
    /**
     * Write an error to the Log
     * @param error
     */
    public void WriteError(String error) {
        System.out.println(error);
    }
}



RE: Validating Wifi or internet connection - simon - 09-10-2025

Hi,

My recommendation is to change the code so that you start the MQTT connection (and throw the possible errors - but do nothing with that) whathever is the state of your Ewon (connected or not to internet).
The MQTT engine of the Ewon is handling the reconnection automatically.

Then you just check if you are connected or not via the MQTT status for sending the data.


RE: Validating Wifi or internet connection - james.taylor@malonegroup.com - 10-10-2025

(09-10-2025, 05:56 PM)simon Wrote: Hi,

My recommendation is to change the code so that you start the MQTT connection (and throw the possible errors - but do nothing with that) whathever is the state of your Ewon (connected or not to internet).
The MQTT engine of the Ewon is handling the reconnection automatically.

Then you just check if you are connected or not via the MQTT status for sending the data.

Thanks for the response, i shall try that, 
Rather than re creating a connection, i shall wait until the connection is re established.

I have since added a log to the code to see when it reboots:
Logging: timestamp: 1760026007393 09 October 2025 16:06:47
Logging: timestamp: 1760026035180 09 October 2025 16:07:15
Logging: timestamp: 1760043853334 09 October 2025 21:04:13
Logging: timestamp: 1760071561318 10 October 2025 04:46:01
Logging: timestamp: 1760072790460 10 October 2025 05:06:30
Logging: timestamp: 1760081535757 10 October 2025 07:32:16
Logging: timestamp: 1760081609168 10 October 2025 07:33:29
Logging: timestamp: 1760081771740 10 October 2025 07:36:12
Logging: timestamp: 1760081794459 10 October 2025 07:36:34
Logging: timestamp: 1760084253869 10 October 2025 08:17:34
Logging: timestamp: 1760087168340 10 October 2025 09:06:08
Logging: timestamp: 1760087316425 10 October 2025 09:08:36
Logging: timestamp: 1760087408103 10 October 2025 09:10:08
Logging: timestamp: 1760087503146 10 October 2025 09:11:43
Logging: timestamp: 1760087654727 10 October 2025 09:14:15
Logging: timestamp: 1760087747207 10 October 2025 09:15:47
Logging: timestamp: 1760089636588 10 October 2025 09:47:17
Logging: timestamp: 1760092182735 10 October 2025 10:29:43
Logging: timestamp: 1760094369963 10 October 2025 11:06:10
Logging: timestamp: 1760094462642 10 October 2025 11:07:43

Doesn't seem to have any particular pattern to it, but still annoying.

Ill try the reconnection change and see how it goes.

Thanks