plc_stream_demo.rb
1#!/usr/bin/env ruby
2
3require 'didkit'
4require 'json'
5require 'skyfall'
6
7# $ gem install skyfall didkit
8
9class PLCMessage
10 attr_reader :seq, :type, :op
11
12 def initialize(data)
13 @json = JSON.parse(data)
14
15 @seq = @json['seq']
16 @type = @json['type'].to_sym
17 return if @type != :sequenced_op
18
19 @op = DIDKit::PLCOperation.new(@json)
20 end
21end
22
23class PLCStream < Skyfall::Stream
24 def initialize
25 super('plc.directory')
26 end
27
28 def handle_message(msg)
29 if @handlers[:message]
30 @handlers[:message].call(PLCMessage.new(msg.data))
31 end
32 end
33
34 def build_websocket_url
35 @root_url + "/export/stream"
36 end
37end
38
39plc = PLCStream.new
40plc.on_connecting { |u| puts "Connecting to #{u}..." }
41plc.on_connect { puts "Connected ✓" }
42plc.on_disconnect { puts "Disconnected." }
43plc.on_error { |e| puts "Error: #{e.class} #{e.message}" }
44
45plc.on_message do |msg|
46 puts "#{msg.seq} [#{msg.op.created_at}]: #{msg.op.did} -> #{msg.op.handles.first} (@ #{msg.op.pds_host})"
47end
48
49plc.connect