Skip to content

Snippet: Retrofitting IP addressing via bindings

Justin Parker edited this page Nov 22, 2022 · 5 revisions

Many older recipes don't allow for dynamic IP addressing. Instead they only have a param_IPAddress parameter.

This snippet shows how the recipe can be easily converted.

Near the top of the recipe:

# ...existing ...

param_IPAddress = LocalEvent({ 'schema': { 'type': 'string', 'hint': '(overrides IP Address binding)' }})

DEFAULT_PORT = 10000

param_Port = LocalEvent({ 'schema': { 'type': 'integer', 'hint': '(default %s)' % DEFAULT_PORT }})

# ...

local_event_IPAddress = LocalEvent({ 'schema': { 'type': 'string' }})

def remote_event_IPAddress(ipAddr):
  if is_blank(param_IPAddress) and local_event_IPAddress.getArg() != ipAddr:
      local_event_IPAddress.emit(ipAddr)
      dest = '%s:%s' % (ipAddr, param_Port or DEFAULT_PORT)
      console.info('IP address updated! Will connect to TCP %s' % dest)
      tcp.setDest(dest)

Wherever main is called:

  if is_blank(param_IPAddress):
    ipAddr = local_event_IPAddress.getArg()
  else:
    ipAddr = param_IPAddress
    local_event_IPAddress.emit(ipAddr)
    
  if is_blank(ipAddr):
    console.warn('No IP address configured or from binding; nothing to do or will wait.')
  else:
    dest = '%s:%s' % (ipAddr, param_Port or DEFAULT_PORT)
    console.info('Will connect to TCP %s' % dest)
    tcp.setDest(dest)

Change to suit!