Created
May 27, 2014 20:55
-
-
Save thinkAmi/f3c10705e73cfaecd168 to your computer and use it in GitHub Desktop.
Ruby + serialport + Sinatra で、シリアルCOMポートから受信したデータを表示するサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra' | |
require 'sinatra/reloader' | |
require 'nkf' | |
require 'win32ole' | |
require 'serialport' | |
def list_com_port | |
locator = WIN32OLE.new("WbemScripting.SWbemLocator") | |
services = locator.ConnectServer() | |
result = {} | |
services.ExecQuery("SELECT * FROM Win32_SerialPort").each do |item| | |
# 取得したitem.Nameはそのままでは文字化けするため、UTF-8にする | |
result[item.DeviceID] = to_utf8(item.Name) | |
end | |
result | |
end | |
def to_utf8(str) | |
str ? NKF.nkf('-w', str) : "" | |
end | |
def recieve(port_name) | |
result = [] | |
# close()のことを考えないよう、open()を使うようにしてみた | |
SerialPort.open(port_name, | |
baud: 9600, | |
data_bits: 8, | |
stop_bits: 1, | |
parrity: SerialPort::NONE) do |sp| | |
# 操作する時間も考えて、とりあえず5秒待つ | |
sleep 5 | |
# 指定しなかったり、"0"だと常に待ち続けてしまうので、 | |
# とりあえず"5000"ミリ秒待っても来ない場合はタイムアウトにしとく | |
sp.read_timeout = 5000 | |
loop do | |
begin | |
# 読み込んだデータには末尾に改行と空白が入っているので、それらを落とす | |
r = sp.readline.chomp.strip | |
p r | |
result << r | |
# readline()は最後まで来るとEOFを返すので、それで通信終了とみなす | |
rescue EOFError | |
break | |
end | |
end | |
end | |
result | |
end | |
get '/' do | |
@com_list = list_com_port | |
p @com_list | |
erb :index | |
end | |
post '/' do | |
com = params[:comport] | |
com_list = list_com_port | |
return unless com_list.has_key?(com) | |
@recieves = recieve(com) | |
erb :list | |
end | |
__END__ | |
@@index | |
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<title>Sample</title> | |
<meta charset="urf-8"> | |
</head> | |
<body> | |
<form method="post" action=""> | |
<select name="comport"> | |
<% @com_list.each do |id, name| %> | |
<option value="<%= id %>"><%= name %></option> | |
<% end %> | |
</select> | |
<input type="submit" value="受信" /> | |
</form> | |
</body> | |
</html> | |
@@list | |
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<title>Sample - results</title> | |
<meta charset="urf-8"> | |
</head> | |
<body> | |
<% @recieves.each do |item| %> | |
<p><%= item %></p> | |
<% end %> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source 'https://rubygems.org' | |
gem 'sinatra' | |
gem 'sinatra-contrib' | |
gem 'thin' | |
gem 'serialport' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment