如何使用rails从webhook与IoT设备进行通信

时间:2018-02-23 10:06:58

标签: ruby ruby-on-rails-5 eventmachine google-home

我正在使用物联网设备学习Google Home Integration。我有IoT设备,它只响应TCP ​​/ WS协议来获取/更新设备中的东西。我在rails应用程序中运行webhook。 Rails Web服务可以从谷歌助手获取请求并回复。现在要填写从谷歌助手收到的请求,我必须向设备发出TCP / WS请求。我正在设备中运行客户端Web套接字程序来获取请求。服务器Web套接字程序在服务器端。 my problem(相同)是如何使用网络套接字将谷歌助手收到的请求转发到设备并获取设备响应并转发给谷歌助手。

以下是样本控制器代码。

class WebhookController < ApplicationController
  def create
    value = params[:result][:parameters][:value].first
    action = params[:result][:parameters]['action'].first
    /*
       Here I have to access the following web socket connection and send the request and need to get response back and update to google assistant.
    */
    res = { 'speech' => "temperature #{value} successfully changed.", 'displayText' => 'success' }
    render json: res
  end
end

示例Web套接字服务器,它已与设备中运行的客户端连接。

require 'em-websocket'

EM.run {
  EM::WebSocket.run(:host => "0.0.0.0", :port => 8080) do |ws|
    ws.onopen { |handshake|
      puts "WebSocket connection open"
      ws.send "Hello Client, you connected to #{handshake.path}"
    }

    ws.onclose { puts "Connection closed" }

    ws.onmessage { |msg|
      puts "Recieved message: #{msg}"
      ws.send msg
      /*
           Here It should get msg from controller and forward to the client and get response from client and send to server controller.
      */
    }

  end
}

0 个答案:

没有答案