api_client.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. require 'json'
  2. require 'net/http'
  3. require 'net/http/post/multipart'
  4. require 'uri'
  5. class ApiClient
  6. def initialize(host, base_id)
  7. @host = host
  8. @current_id = Integer(base_id)
  9. end
  10. def generate_id
  11. id = @current_id
  12. @current_id += 1
  13. id
  14. end
  15. def request(type, path, req_body = nil)
  16. uri = URI("http://#{@host}#{path}")
  17. Net::HTTP.start(uri.host, uri.port) do |http|
  18. req_type = Net::HTTP.const_get(type)
  19. req = req_type.new(uri)
  20. if req_body
  21. req['Content-Type'] = 'application/json'
  22. req.body = req_body
  23. end
  24. res = http.request(req)
  25. res.value
  26. body = res.body
  27. if res['content-type'].downcase == 'application/json'
  28. body = JSON.parse(body)
  29. end
  30. body
  31. end
  32. end
  33. def upload_json(path, file)
  34. `curl -s "http://#{@host}#{path}" -X POST -F 'f=@settings.json'`
  35. end
  36. def get(path)
  37. request(:Get, path)
  38. end
  39. def put(path, body)
  40. request(:Put, path, body)
  41. end
  42. def post(path, body)
  43. request(:Post, path, body)
  44. end
  45. def get_state(params = {})
  46. get("/gateways/#{params[:id]}/#{params[:type]}/#{params[:group_id]}")
  47. end
  48. def patch_state(state, params = {})
  49. put("/gateways/#{params[:id]}/#{params[:type]}/#{params[:group_id]}", state.to_json)
  50. end
  51. end