Skip to content

Instantly share code, notes, and snippets.

@shortjared
Last active December 21, 2015 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shortjared/6385557 to your computer and use it in GitHub Desktop.
Save shortjared/6385557 to your computer and use it in GitHub Desktop.
A simple example of continuously reading from a serial based device and using websockets to send data to all registered clients on the server.
# coding: utf-8
require 'sinatra'
require 'sinatra-websocket'
require 'serialport'
set :server, 'thin'
set :sockets, []
## Setup to read from your device via serial port
ser = SerialPort.new("/dev/your_device", 9600, 8, 1, SerialPort::NONE)
## Starts countously reading from Serial Port and sending data to all connected clients
count = 0
rns = Array.new()
EM.defer do
while true do
response = ser.readline("\r")
response.chomp!
rns << response.to_i
count += 1
if count == 500
count = 0
res=Hash[rns.group_by {|x| x}.map {|k,v| [k,v.count]}]
rns.clear
settings.sockets.each{|s| s.send(res.to_s) }
end
end
end
## On first request, send erb template, then we just manage sockets
get '/' do
if !request.websocket?
erb :index
else
request.websocket do |ws|
ws.onopen do
settings.sockets << ws
end
ws.onclose do
settings.sockets.delete(ws)
end
end
end
end
__END__
@@ index
<html>
<body>
<h1 class="text-align:center">Serial Data from Source</h1>
<div id="data"></div>
</body>
<script type="text/javascript">
window.onload = function(){
(function(){
var show = function(el){
return function(msg){ el.innerHTML = msg + '<br />' + el.innerHTML; }
}(document.getElementById('data'));
var ws = new WebSocket('ws://' + window.location.host + window.location.pathname);
ws.onmessage = function(m) { show(m.data); };
})();
}
</script>
</html>
void setup() {
// initialize the serial communication:
Serial.begin(9600);
// send the value of analog input 0 (electronic noise)
randomSeed(analogRead(A0));
}
void loop() {
//Send a random integer from 1 to 10 to serial port
Serial.println(random(1,11));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment