I'm following the latest Kamailio and Asterisk Realtime guide to offload registrations from my FreePBX / Asterisk setup and possibly load balance down the road. I'm running Kamailio 4.4.5 and Asterisk 11.6-cert15.  I realize FreePBX isn't realtime and will work around  that with a database view, etc.

I was excited to see Kamailio will handle multiple devices registering to the same device/extension and placing / receiving calls works. I did run into an issue when any device unregisters Kamailio always forwards the register with expires 0 to Asterisk. To workaround this I modified the route[REGFWD] and added the if($hdr(Expires)==$null) chunk of code. I wanted to use caller->count, but ran into stale contact records with expires set to deleted. I then tried enumerating the contacts, but don't understand why ulc(caller->expires) is 10 when kamctl ul show shows expires deleted. The code below works, but I was hoping for an explanation of the expires = 10 or if there was a better way to handle this scenario.

Additionally I enabled presence (WITH_PRESENCE) but Kamailio responds 489 bad event for subscribe requests from devices registered to it. I was hoping it would proxy these to Asterisk for BLF support. If somebody could point me in the right direction it would be appreciated.

# Forward REGISTER to Asterisk
route[REGFWD] {
        if(!is_method("REGISTER"))
        {
                return;
        }

        if($hdr(Expires)==$null)
        {
                reg_fetch_contacts("location", "$sel(contact.uri)", "caller");

                $var(i) = 0;
                $var(j) = 0;
                while($var(i) < $(ulc(caller=>count)))
                {
                        if($(ulc(caller=>expires)[$var(i)])!=10)
                        {
                                $var(j) = $var(j) + 1;
                        }

                        $var(i) = $var(i) + 1;
                }

                if($var(j)>=1)
                {
                        return;
                }
        }

        $var(rip) = $sel(cfg_get.asterisk.bindip);
        $uac_req(method)="REGISTER";
        $uac_req(ruri)="sip:" + $var(rip) + ":" + $sel(cfg_get.asterisk.bindport);
        $uac_req(furi)="sip:" + $au + "@" + $var(rip);
        $uac_req(turi)="sip:" + $au + "@" + $var(rip);
        $uac_req(hdrs)="Contact: <sip:" + $au + "@"
                                + $sel(cfg_get.kamailio.bindip)
                                + ":" + $sel(cfg_get.kamailio.bindport) + ">\r\n";
        if($sel(contact.expires) != $null)
                $uac_req(hdrs)= $uac_req(hdrs) + "Expires: " + $sel(contact.expires) + "\r\n";
        else
                $uac_req(hdrs)= $uac_req(hdrs) + "Expires: " + $hdr(Expires) + "\r\n";
        uac_req_send();
}

Thanks,
Ryan