SmartApp is generating multiple copies of the same child Device, why?

Okay, trying to learn a bit about childDevices and I’m getting there. I’ve figured out how to create a childDevice, but unfortunately when I install the app on my phone it ends up generating two copies of the same device. Same device ID.

Worse, when I run the app it seems to generate another occasionally. I now have four copies of the device.

Here’s the command I’m using to generate the childDevice:

def newTrigger = addChildDevice("sirhcb", "Momentary Button Tile", app.id+"/gnsh", null, [name:buttonLabel.value, label:buttonLabel.value])

This is the initialize() procedure, which should only run when it’s installed, updated, right?

Do I need to somehow check if the childDevice already exists before generating it? How would I do this?

Do I need to somehow remove the childDevice before recalling initialize() when the app is updated?

you might want to consider checking for the existence of the child device first before executing that addChildDevice().

initialize(){
    settings.devices.each {deviceId ->
        try {
            def existingDevice = getChildDevice(deviceId)
            if(!existingDevice) {
                def childDevice = addChildDevice("smartthings", "Device Name", deviceId, null, [name: "Device.${deviceId}", label: device.name, completedSetup: true])
            }
        } catch (e) {
            log.error "Error creating device: ${e}"
        }
    }
}

Examples taken from here:
http://docs.smartthings.com/en/latest/cloud-and-lan-connected-device-types-developers-guide/building-cloud-connected-device-types/building-the-service-manager.html#handling-adds-changes-deletes

That’s… I’m trying to play with this, but it isn’t helping a lot. I might be missing something here.

In the line:

settings.devices.each {deviceId ->

Do I use the device ID that I’m creating or do I type in exactly “deviceId”? Same question for the line:

def existingDevice = getChildDevice(deviceId)

Well I fiddled around with things a bit… because I’m only generating one childDevice and I know what the device ID is, I just hard coded that in, so I did this:

def DeviceID = app.id+"/gnsh"
log.debug "did = ${DeviceID}"
def existingDevice = getChildDevice(DeviceID)
log.debug "EXD = ${existingDevice}"
if(!existingDevice) {
            def newTrigger = addChildDevice("sirhcb", "Momentary Button Tile", app.id+"/gnsh", null, [name:buttonLabel.value, label:buttonLabel.value])
}

Seems like it should work, but I’m still getting four devices when I install my app. For what it’s worth, it works great in the simulator. Only generates one device.