Class: DiPS::DiPSClient

Inherits:
Object
  • Object
show all
Defined in:
lib/dipsclient.rb

Instance Method Summary collapse

Constructor Details

#initialize(serverUrl) ⇒ DiPSClient

Returns a new instance of DiPSClient.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/dipsclient.rb', line 11

def initialize serverUrl
	$dipsSubscriptions = Hash.new
	@clientId = SecureRandom.uuid
	@diPSservice = "#{serverUrl}/?clientid=#{@clientId}" #We send the clientid to the server
	@ws = WebSocket::Client::Simple.connect @diPSservice, {
						  :proxy => {
						    :origin  => 'http://console.org',
						    :headers => {'User-Agent' => 'ruby'}
						  }
						}
	#Process check if we have a scubscription for that event
	#if so, launch the proper callback
	@ws.on :message do |msg|
		begin
			#Parse the message as an object
			event = JSON.parse(msg.data)
			 eName = event["EventName"]
			if !$dipsSubscriptions[eName].nil?
				$dipsSubscriptions[eName].call(event["PayLoad"])
			end				
		rescue Exception => e
			#p e
		end			
	end

	@ws.on :open do
 		#do nothing
	end

	@ws.on :close do |e|
 		#do nothing		 
	end

	@ws.on :error do |e|
	  p e
	end
end

Instance Method Details

#DisconnectObject



49
50
51
# File 'lib/dipsclient.rb', line 49

def Disconnect
	@ws.close
end

#Publish(eventName, eventParameter) ⇒ Object

publish and event and send some parameter to the subscribers



82
83
84
85
86
87
88
# File 'lib/dipsclient.rb', line 82

def Publish eventName, eventParameter
	#create the event
	parameter = JSON.generate(eventParameter)
	event = { "EventName" => eventName , "ClientId" => @clientId, "MessageType" => "publish", "EventParameter" => parameter	}
	#send the event
	@ws.send JSON.generate(event)
end

#Subscribe(eventName, &callback) ⇒ Object

Subscribe to some event, a callback is executed when the event occurs



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/dipsclient.rb', line 54

def Subscribe eventName, &callback
	if $dipsSubscriptions[eventName].nil?
		$dipsSubscriptions[eventName] = callback	
		#send the subscription to the server
		event = { "EventName" => eventName , "ClientId" => @clientId, "MessageType" => "subscribe" }
		msg = JSON.generate(event)

		#send the event
		@ws.send msg
	else
		raise "You can only have one subscription to an event"
	end
end

#Unsubscribe(eventName) ⇒ Object

unscubscribe from some event



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/dipsclient.rb', line 69

def Unsubscribe eventName
	if !$dipsSubscriptions[eventName].nil?
		$dipsSubscriptions.delete(eventName)
		#send the unsubscription to the server
		event = { "EventName" => eventName , "ClientId" => @clientId, "MessageType" => "unsubscribe" }
		#send the event
		@ws.send JSON.generate(event)
	else
		raise "You are not subscribed to that event"
	end
end