Example of reading in local file and parsing it?

So a while back I was working on a generic MQTT client app/driver that could create child devices on the hubitat hub for MQTT subscriptions. I got busy, so set it to the side, but pulled it out and was looking at it tonight.

What I did was have it load a CSV file that had the MQTT info in it - one child device per line (format is: mqtt path, child device type, name). Side note, it wouldn't have to be CSV, could be JSON or something else. I just stuck to what I know. :slight_smile:

Is there a better/worse way to read in a file like a CSV and parse it? I did below (no laughing), which works, but seems really clunky?

    byte[] filebytes = downloadHubFile(mqttFileName)
    if(filebytes) {
        //convert the bytes to a string
        str1 = new String(filebytes);
        
        String[] str2;
        String[] str3;

        //Split the string blob back into rows        
        str2 = str1.split('\n');
       
        //Parse each row and split apart the comma separated values
        for( String values : str2 ) {
            log.debug "str2: " + values;
            str3 = values.split(',');
            log.debug "subs: " + str3[0];
            log.debug "type: " + str3[1];
            log.debug "name: " + str3[2];

            // MQTT Subscribe
		    mqttDriver.subscribe(str3[0])
		    pauseExecution(100)
        }
    }
    ```

The last example on this page that uses splitEachLine() is pretty slick.

2 Likes

Thanks, that is easier than how I did it brute force.

I did work out a quick json version, too, but I was trying to make it "simpler" for non-programmers to make the list, thus the original thought of leaving it CSV. Anyway, I'll think on it.

json example that worked for me:

{
    byte[] dBytes = downloadHubFile(strFileName)
    listJson = new JsonSlurper().parseText(new String(dBytes))
    listJson.each{ key, value ->
        log.debug "key: " + key
        log.debug "value.mqtt: " + value.mqtt
        log.debug "value.type: " + value.type
        log.debug "value.name: " + value.name        
    }
}

2 Likes

Good tip. That is a lot nicer than my old way.

This worked:

    // CSV File
    byte[] csvBytes = downloadHubFile(strCSVFileName)
    str1 = new String(csvBytes);
    str1.splitEachLine(',') { items ->
        log.debug "csv mqtt: ${items[0]},  type: ${items[1]}, name: ${items[2]}"  
    }   
2 Likes

I know its just a debug line but you could make that a single line all in one quoted string like this:

        log.debug "mqtt: ${items[0]},  type: ${items[1]}, name: ${items[2]}"

Less stuff flying down the log and possibly easier to read that way.

3 Likes

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.