Class: SpsMqttBridge

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

Instance Method Summary collapse

Constructor Details

#initialize(mqtt: {address: 'mqtt', port: '1883'}, sps: {host: 'sps', address: host, port: '59000'}, sps2: {address: 'sps', port: '59000'}) ⇒ SpsMqttBridge

Returns a new instance of SpsMqttBridge.



15
16
17
18
19
# File 'lib/sps_mqtt_bridge.rb', line 15

def initialize(mqtt: {address: 'mqtt', port: '1883'}, 
   sps:{host: 'sps', address: host, port: '59000'}, 
               sps2:{address: 'sps', port: '59000'})
  @mqtt, @sps, @sps2 = mqtt, sps, sps2
end

Instance Method Details

#mqtt_to_sps(topic: '#') ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/sps_mqtt_bridge.rb', line 21

def mqtt_to_sps(topic: '#')

  MQTT::Client.connect(@mqtt[:address], @mqtt[:port]) do |client|

    client.get(topic) do |t, message|
      SPSPub.notice [t, message].join(': '), 
                              address: @sps[:address], port: @sps[:port]
    end
  end
end

#sps_to_http(topic: '#', url: '', timeout: 5, http_auth: ["user", "password"]) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/sps_mqtt_bridge.rb', line 54

def sps_to_http(topic: '#', url: '', timeout: 5, \
                                           http_auth: ["user", "password"])

  sps = SPSSub.new(host: @sps[:address], port: @sps[:port])

  sps.subscribe(topic: topic) do |message,t|
 
    begin
      
      Timeout::timeout(timeout){

        ipaddr = url[/https?:\/\/([^\/]+)/,1]
        ip_address = block_given? ? yield(ipaddr) || ipaddr : ipaddr
        full_url = url.sub(/(https?:\/\/)([^\/]+)/,'\1' + ip_address).\
                                    sub('$topic', t).sub('$msg', message)

        buffer = open(full_url, read_timeout: timeout,\
                    http_basic_authentication: http_auth).read

      }
    rescue Timeout::Error => e
      
      puts 'connection timed out'
      
    rescue OpenURI::HTTPError => e
      
      puts '400 bad request'
      
    end

  end
end

#sps_to_mqtt(topic: '#') ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/sps_mqtt_bridge.rb', line 32

def sps_to_mqtt(topic: '#')

  SPSSub.new(host: @sps[:address], port: @sps[:port]).\
                                       subscribe(topic: topic) do |message,t|

    MQTT::Client.connect(@mqtt[:address], @mqtt[:port]) do |client|
      client.publish(t, message)
    end

  end
end

#sps_to_sps(topic: '#') ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/sps_mqtt_bridge.rb', line 44

def sps_to_sps(topic: '#')

  SPSSub.new(host: @sps[:address], port: @sps[:port]).\
                                       subscribe(topic: topic) do |message,t|

    SPSPub.notice [t, message].join(': '), 
                                 address: @sps2[:address], port: @sps2[:port]
  end
end