diff --git a/natlib/svcd.c b/natlib/svcd.c index b188a5c..8c5d2ff 100644 --- a/natlib/svcd.c +++ b/natlib/svcd.c @@ -2,7 +2,8 @@ #define SVCD_SYMBOLS \ - { LSTRKEY( "svcd_init"), LFUNCVAL ( svcd_init ) }, + { LSTRKEY( "svcd_init"), LFUNCVAL ( svcd_init ) }, \ + { LSTRKEY( "svcd_subscribe"), LFUNCVAL ( svcd_subscribe ) }, //If this file is defining only specific functions, or if it @@ -185,3 +186,52 @@ static int svcd_init( lua_State *L ) return 0; } + +static int svcd_subscribe(lua_State* L) +{ + if (lua_gettop(L) != 4) return luaL_error(L, "Expected (targetip, svcid, attrid, on_notify)"); + + // arg 1 is targetip, to be passed along to to libstorm_net_sendto + uint16_t svcid = luaL_checknumber(L, 2); + uint16_t attrid = luaL_checknumber(L, 3); + // arg 4 is on_notify + + lua_getglobal(L, "SVCD"); // position 5 on stack + lua_getfield(L, 5, "ivkid"); + + uint16_t ivkid = lua_tointeger(L, -1); + + uint16_t new_ivkid = ivkid + 1; + if (new_ivkid > 65535) { + new_ivkid = 0; + } + + lua_pushnumber(L, new_ivkid); + lua_setfield(L, 5, "ivkid"); + + lua_getfield(L, 5, "oursubs"); + // put value on the stack + lua_pushinteger(L, ivkid); + lua_pushvalue(L, 4); // on_notify + lua_settable(L, -3); + + lua_pushlightfunction(L, libstorm_net_sendto); + + lua_getfield(L, 5, "ncsock"); + + char msg[8] __attribute__((aligned(2))); + + // don't use the msg[0] byte + msg[1] = 1; + ((uint16_t*) msg)[1] = svcid; + ((uint16_t*) msg)[2] = attrid; + ((uint16_t*) msg)[3] = ivkid; + lua_pushlstring(L, &(msg[1]), 7); + + lua_pushvalue(L, 1); // targetip + lua_pushnumber(L, 2530); + lua_call(L, 4, 0); + + lua_pushnumber(L, ivkid); + return 1; +}