Jumat, 16 Desember 2016

Tutorial NodeMCU: GET Twitter account/settings Using REST API (ESP8266, WeMos, Lua)

Jika pada tulisan sebelumnya kita membahas tentang bagaimana melakukan posting Tweet dengan menggunakan REST API, maka pada tulisan ini kita akan melakukan pembacaan account/setting Twitter dengan menggunakan metode GET.

Untuk menjalankan script ini, anda perlu melakukan kustomisasi firmware nodemcu dengan memasukan beberapa module berikut ini:
NodeMCU custom build by frightanic.com
    branch: master
    commit: 81ec3665cb5fe68eb8596612485cc206b65659c9
    SSL: true
    modules: cjson,crypto,dht,file,gpio,http,net,node,rtctime,sntp,tmr,uart,websocket,wifi
 build     built on: 2016-12-10 10:19
 powered by Lua 5.1.4 on SDK 1.5.4.1(39cb9a32)
Dengan script sebagai berikut:

-- by Hendra Soewarno (0119067305) base on documentation
-- https://dev.twitter.com/rest/reference/get/account/settings
api_base = "https://api.twitter.com"
consumer_key = "7LzQ03LBNtFZ8OIsgq******"
consumer_secret = "xfyoGFz2fV9nOPAS4dx9sfiHz7PZEKeGOgZJqiXb98w******"
access_token = "2203290865-ClUx6zIDTmBWI3JjML5tZlfEXOhnzvKl******"
access_token_secret = "k09y3gSIQ4pEROSvLJewd7lG51YBXcLyno23m8JM******"

-- Calculate the sha1 hash for a given string.
local function sha1(str, key)
    return crypto.hmac("sha1",str,key)
end

-- Returns the current time as a Unix timestamp.
function oauth_timestamp()
   return tostring(rtctime.get() + 1) -- we want the next second
end

-- Generate nonce none for oauth
function oauth_nonce()  
   return oauth_timestamp()
end


function encode_parameter(str)
    return str:gsub('[^-%._~a-zA-Z0-9]', function(c)
        return string.format("%%%02x", c:byte()):upper()
    end)
end

function built_base_string(baseuri, method, param)
    local t = { }
    for key, val in pairs(param) do
        table.insert(t, {key = key,val = val})
    end
   
    -- Sort by key first, then value
    table.sort(t, function(a,b)
        if a.key < b.key then
            return true
        elseif a.key > b.key then
            return false
        else
            return a.val < b.val
        end
    end)

    local key_value_pairs = { }
    for _, rec in pairs(t) do      
        table.insert(key_value_pairs, rec.key .. "=" .. encode_parameter(rec.val))
    end
   
    local query_string_except_signature = table.concat(key_value_pairs, "&")

    return method .. '&' .. encode_parameter(baseuri) .. '&' .. encode_parameter(query_string_except_signature)  
end

function built_authorization_header(oauth, oauth_signature)
    local r = "Authorization: OAuth "
    local oauth_headers = { }
   
    for key, val in pairs(oauth) do
        if (string.sub(key,1,5)=="oauth") then
            table.insert(oauth_headers, key .. "=\"" .. encode_parameter(val) .. "\"")
        end           
    end

    table.insert(oauth_headers, "oauth_signature=\"" .. oauth_signature .. "\"")

    local authorization_header = table.concat(oauth_headers, ", ")

    return r .. authorization_header
end

function requestToGet(path)
    local oauth = {
        oauth_consumer_key = consumer_key,
        oauth_nonce = oauth_nonce(),
        oauth_signature_method = "HMAC-SHA1",
        oauth_token =  access_token,
        oauth_timestamp = oauth_timestamp(),
        oauth_version = "1.0"
        }

    local signature_base_string = built_base_string(api_base .. path, "GET", oauth)
    print(signature_base_string)

    local signature_key = encode_parameter(consumer_secret) .. "&" .. encode_parameter(access_token_secret)
    print(signature_key)

    local oauth_signature = crypto.toBase64(sha1(signature_base_string, signature_key))
    print(oauth_signature)

    local header = built_authorization_header(oauth, encode_parameter(oauth_signature))
    print(header)

    local url = api_base .. path
    print(url)
   
    http.get(url,
        header,
        function(code, data)
            if (code ~= 200) then
                print("Failed : HTTP error code : " .. code, data)
            else
                print("Succeed : " .. code, data)
            end
        end)
end

sntp.sync("1.id.pool.ntp.org",
    function(sec,usec,server)
        print('setting time to:', sec, usec, "from: " .. server)
        rtctime.set(sec, usec)
        requestToGet("/1.1/account/settings.json")
    end,

    function()
        print('failed!')
    end
)

Hasil Run:

Succeed : 200   {"protected":false,"screen_name":"hendrasoewarno","always_use_https":true,"use_cookie_personalization":true,"sleep_time":{"enabled":false,"end_time":null,"start_time":null},"geo_enabled":false,"language":"en","discoverable_by_email":false,"discoverable_by_mobile_phone":false,"display_sensitive_media":false,"allow_contributor_request":"all","allow_dms_from":"following","allow_dm_groups_from":"following","smart_mute":false,"translator_type":"none"}





Tidak ada komentar:

Posting Komentar