Class: SDN::MQTTBridge
- Inherits:
-
Object
- Object
- SDN::MQTTBridge
- Defined in:
- lib/sdn/mqtt_bridge.rb
Constant Summary collapse
- WAIT_TIME =
0.25
- BROADCAST_WAIT =
5.0
Instance Attribute Summary collapse
-
#groups ⇒ Object
readonly
Returns the value of attribute groups.
-
#motors ⇒ Object
readonly
Returns the value of attribute motors.
Instance Method Summary collapse
- #add_group(addr) ⇒ Object
- #enqueue(message, queue = :command) ⇒ Object
-
#initialize(mqtt_uri, port, device_id: "somfy", base_topic: "homie") ⇒ MQTTBridge
constructor
A new instance of MQTTBridge.
- #publish(topic, value) ⇒ Object
- #publish_basic_attributes ⇒ Object
- #publish_motor(addr) ⇒ Object
- #subscribe(topic) ⇒ Object
Constructor Details
#initialize(mqtt_uri, port, device_id: "somfy", base_topic: "homie") ⇒ MQTTBridge
Returns a new instance of MQTTBridge.
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
# File 'lib/sdn/mqtt_bridge.rb', line 126 def initialize(mqtt_uri, port, device_id: "somfy", base_topic: "homie") @base_topic = "#{base_topic}/#{device_id}" @mqtt = MQTT::Client.new(mqtt_uri) @mqtt.set_will("#{@base_topic}/$state", "lost", true) @mqtt.connect @motors = {} @groups = {} @mutex = Mutex.new @cond = ConditionVariable.new @command_queue = [] @request_queue = [] @response_pending = false @broadcast_pending = false publish_basic_attributes uri = URI.parse(port) if uri.scheme == "tcp" require 'socket' @sdn = TCPSocket.new(uri.host, uri.port) elsif uri.scheme == "telnet" || uri.scheme == "rfc2217" require 'net/telnet/rfc2217' @sdn = Net::Telnet::RFC2217.new('Host' => uri.host, 'Port' => uri.port || 23, 'baud' => 4800, 'parity' => Net::Telnet::RFC2217::ODD) else require 'serialport' @sdn = SerialPort.open(port, "baud" => 4800, "parity" => SerialPort::ODD) end read_thread = Thread.new do buffer = "" loop do begin , bytes_read = SDN::Message.parse(buffer.bytes) unless begin buffer.concat(@sdn.read_nonblock(64 * 1024)) next rescue IO::WaitReadable wait = buffer.empty? ? nil : WAIT_TIME if @sdn.wait_readable(wait).nil? # timed out; just discard everything puts "timed out reading; discarding buffer: #{buffer.unpack('H*').first}" buffer = "" end end next end # discard how much we read buffer = buffer[bytes_read..-1] src = SDN::Message.print_address(.src) # ignore the UAI Plus and ourselves if src != '7F.7F.7F' && !SDN::Message::is_group_address?(.src) && !(motor = @motors[src.gsub('.', '')]) motor = publish_motor(src.gsub('.', '')) puts "found new motor #{src}" end puts "read #{.inspect}" follow_ups = [] case when SDN::Message::PostNodeLabel if (motor.publish(:label, .label)) publish("#{motor.addr}/$name", .label) end when SDN::Message::PostMotorPosition motor.publish(:positionpercent, .position_percent) motor.publish(:positionpulses, .position_pulses) motor.publish(:ip, .ip) motor.group_objects.each do |group| positions = group.motors.map(&:positionpercent) position = nil # calculate an average, but only if we know a position for # every shade if !positions.include?(:nil) && !positions.include?(nil) position = positions.inject(&:+) / positions.length end group.publish(:positionpercent, position) end when SDN::Message::PostMotorStatus if .state == :running || motor.state == :running follow_ups << SDN::Message::GetMotorStatus.new(.src) end # this will do one more position request after it stopped follow_ups << SDN::Message::GetMotorPosition.new(.src) motor.publish(:state, .state) motor.publish(:last_direction, .last_direction) motor.publish(:last_action_source, .last_action_source) motor.publish(:last_action_cause, .last_action_cause) motor.group_objects.each do |group| states = group.motors.map(&:state).uniq state = states.length == 1 ? states.first : 'mixed' group.publish(:state, state) end when SDN::Message::PostMotorLimits motor.publish(:uplimit, .up_limit) motor.publish(:downlimit, .down_limit) when SDN::Message::PostMotorDirection motor.publish(:direction, .direction) when SDN::Message::PostMotorRollingSpeed motor.publish(:upspeed, .up_speed) motor.publish(:downspeed, .down_speed) motor.publish(:slowspeed, .slow_speed) when SDN::Message::PostMotorIP motor.publish(:"ip#{.ip}pulses", .position_pulses) motor.publish(:"ip#{.ip}percent", .position_percent) when SDN::Message::PostGroupAddr motor.add_group(.group_index, .group_address) end @mutex.synchronize do signal = @response_pending || !follow_ups.empty? @response_pending = @broadcast_pending @request_queue.concat(follow_ups) @cond.signal if signal end rescue EOFError puts "EOF reading" exit 2 rescue SDN::MalformedMessage => e puts "ignoring malformed message: #{e}" unless e.to_s =~ /issing data/ rescue => e puts "got garbage: #{e}; #{e.backtrace}" end end end write_thread = Thread.new do begin loop do = nil @mutex.synchronize do # got woken up early by another command getting queued; spin if @response_pending while @response_pending remaining_wait = @response_pending - Time.now.to_f if remaining_wait < 0 puts "timed out waiting on response" @response_pending = nil @broadcast_pending = nil else @cond.wait(@mutex, remaining_wait) end end else sleep 0.1 end = @command_queue.shift unless = @request_queue.shift if @response_pending = Time.now.to_f + WAIT_TIME if .dest == [0xff, 0xff, 0xff] @broadcast_pending = Time.now.to_f + BROADCAST_WAIT end end end # spin until there is a message @cond.wait(@mutex) unless end next unless puts "writing #{.inspect}" @sdn.write(.serialize) @sdn.flush end rescue => e puts "failure writing: #{e}" exit 1 end end @mqtt.get do |topic, value| puts "got #{value.inspect} at #{topic}" if topic == "#{@base_topic}/discovery/discover/set" && value == "true" # trigger discovery @mutex.synchronize do @request_queue.push(SDN::Message::GetNodeAddr.new) @cond.signal end elsif (match = topic.match(%r{^#{Regexp.escape(@base_topic)}/(?<addr>\h{6})/(?<property>label|down|up|stop|positionpulses|positionpercent|ip|wink|reset|(?<speed_type>upspeed|downspeed|slowspeed)|uplimit|downlimit|direction|ip(?<ip>\d+)(?<ip_type>pulses|percent)|groups)/set$})) addr = SDN::Message.parse_address(match[:addr]) property = match[:property] # not homie compliant; allows linking the positionpercent property # directly to an OpenHAB rollershutter channel if property == 'positionpercent' && value =~ /^(?:UP|DOWN|STOP)$/i property = value.downcase value = "true" end motor = @motors[SDN::Message.print_address(addr).gsub('.', '')] is_group = SDN::Message.is_group_address?(addr) follow_up = SDN::Message::GetMotorStatus.new(addr) = case property when 'label' follow_up = SDN::Message::GetNodeLabel.new(addr) SDN::Message::SetNodeLabel.new(addr, value) unless is_group when 'stop' SDN::Message::Stop.new(addr) if value == "true" when 'up', 'down' SDN::Message::MoveTo.new(addr, "#{property}_limit".to_sym) if value == "true" when 'wink' SDN::Message::Wink.new(addr) if value == "true" when 'reset' next unless SDN::Message::SetFactoryDefault::RESET.keys.include?(value.to_sym) SDN::Message::SetFactoryDefault.new(addr, value.to_sym) when 'positionpulses', 'positionpercent', 'ip' SDN::Message::MoveTo.new(addr, property.sub('position', 'position_').to_sym, value.to_i) when 'direction' next if is_group follow_up = SDN::Message::GetMotorDirection.new(addr) next unless %w{standard reversed}.include?(value) SDN::Message::SetMotorDirection.new(addr, value.to_sym) when 'uplimit', 'downlimit' next if is_group if %w{delete current_position jog_ms jog_pulses}.include?(value) type = value.to_sym value = 10 else type = :specified_position end target = property == 'uplimit' ? :up : :down follow_up = SDN::Message::GetMotorLimits.new(addr) SDN::Message::SetMotorLimits.new(addr, type, target, value.to_i) when /^ip\d(?:pulses|percent)$/ next if is_group ip = match[:ip].to_i next unless (1..16).include?(ip) follow_up = SDN::Message::GetMotorIP.new(addr, ip) type = if value == 'delete' :delete elsif value == 'current_position' :current_position elsif match[:ip_type] == 'pulses' :position_pulses else :position_percent end SDN::Message::SetMotorIP.new(addr, type, ip, value.to_i) when 'upspeed', 'downspeed', 'slowspeed' next if is_group next unless motor follow_up = SDN::Message::GetMotorRollingSpeed.new(addr) = SDN::Message::SetMotorRollingSpeed.new(addr, up_speed: motor.up_speed, down_speed: motor.down_speed, slow_speed: motor.slow_speed) .send(:"#{property.sub('speed', '')}_speed=", value.to_i) when 'groups' next if is_group next unless motor = motor.set_groups(value) @mutex.synchronize do .each { |m| @command_queue.push(m) } @cond.signal end nil end if @mutex.synchronize do @command_queue.push() @request_queue.push(follow_up) unless @request_queue.include?(follow_up) @cond.signal end end end end end |
Instance Attribute Details
#groups ⇒ Object (readonly)
Returns the value of attribute groups.
124 125 126 |
# File 'lib/sdn/mqtt_bridge.rb', line 124 def groups @groups end |
#motors ⇒ Object (readonly)
Returns the value of attribute motors.
124 125 126 |
# File 'lib/sdn/mqtt_bridge.rb', line 124 def motors @motors end |
Instance Method Details
#add_group(addr) ⇒ Object
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 |
# File 'lib/sdn/mqtt_bridge.rb', line 601 def add_group(addr) addr = addr.gsub('.', '') return if @groups.key?(addr) publish("#{addr}/$name", addr) publish("#{addr}/$type", "Shade Group") publish("#{addr}/$properties", "down,up,stop,positionpulses,positionpercent,ip,wink,reset") publish("#{addr}/down/$name", "Move in down direction") publish("#{addr}/down/$datatype", "boolean") publish("#{addr}/down/$settable", "true") publish("#{addr}/down/$retained", "false") publish("#{addr}/up/$name", "Move in up direction") publish("#{addr}/up/$datatype", "boolean") publish("#{addr}/up/$settable", "true") publish("#{addr}/up/$retained", "false") publish("#{addr}/stop/$name", "Cancel adjustments") publish("#{addr}/stop/$datatype", "boolean") publish("#{addr}/stop/$settable", "true") publish("#{addr}/stop/$retained", "false") publish("#{addr}/positionpulses/$name", "Position from up limit (in pulses)") publish("#{addr}/positionpulses/$datatype", "integer") publish("#{addr}/positionpulses/$format", "0:65535") publish("#{addr}/positionpulses/$unit", "pulses") publish("#{addr}/positionpulses/$settable", "true") publish("#{addr}/positionpercent/$name", "Position (in %)") publish("#{addr}/positionpercent/$datatype", "integer") publish("#{addr}/positionpercent/$format", "0:100") publish("#{addr}/positionpercent/$unit", "%") publish("#{addr}/positionpercent/$settable", "true") publish("#{addr}/ip/$name", "Intermediate Position") publish("#{addr}/ip/$datatype", "integer") publish("#{addr}/ip/$format", "1:16") publish("#{addr}/ip/$settable", "true") publish("#{addr}/wink/$name", "Feedback") publish("#{addr}/wink/$datatype", "boolean") publish("#{addr}/wink/$settable", "true") publish("#{addr}/wink/$retained", "false") publish("#{addr}/state/$name", "State of the motors; only set if all motors are in the same state") publish("#{addr}/state/$datatype", "enum") publish("#{addr}/state/$format", SDN::Message::PostMotorStatus::STATE.keys.join(',')) @groups[addr] = Group.new(self, addr) publish("$nodes", (["discovery"] + @motors.keys.sort + @groups.to_a).join(",")) end |
#enqueue(message, queue = :command) ⇒ Object
410 411 412 413 414 415 416 417 418 |
# File 'lib/sdn/mqtt_bridge.rb', line 410 def enqueue(, queue = :command) @mutex.synchronize do queue = instance_variable_get(:"#{@queue}_queue") unless queue.include?() queue.push() @cond.signal end end end |
#publish(topic, value) ⇒ Object
402 403 404 |
# File 'lib/sdn/mqtt_bridge.rb', line 402 def publish(topic, value) @mqtt.publish("#{@base_topic}/#{topic}", value, true) end |
#publish_basic_attributes ⇒ Object
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 |
# File 'lib/sdn/mqtt_bridge.rb', line 420 def publish_basic_attributes publish("$homie", "v4.0.0") publish("$name", "Somfy SDN Network") publish("$state", "init") publish("$nodes", "discovery") publish("discovery/$name", "Discovery Node") publish("discovery/$type", "sdn") publish("discovery/$properties", "discover") publish("discovery/discover/$name", "Trigger Motor Discovery") publish("discovery/discover/$datatype", "boolean") publish("discovery/discover/$settable", "true") publish("discovery/discover/$retained", "false") subscribe("discovery/discover/set") subscribe("+/label/set") subscribe("+/down/set") subscribe("+/up/set") subscribe("+/stop/set") subscribe("+/positionpulses/set") subscribe("+/positionpercent/set") subscribe("+/ip/set") subscribe("+/wink/set") subscribe("+/reset/set") subscribe("+/direction/set") subscribe("+/upspeed/set") subscribe("+/downspeed/set") subscribe("+/slowspeed/set") subscribe("+/uplimit/set") subscribe("+/downlimit/set") subscribe("+/groups/set") (1..16).each do |ip| subscribe("+/ip#{ip}pulses/set") subscribe("+/ip#{ip}percent/set") end publish("$state", "ready") end |
#publish_motor(addr) ⇒ Object
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 |
# File 'lib/sdn/mqtt_bridge.rb', line 460 def publish_motor(addr) publish("#{addr}/$name", addr) publish("#{addr}/$type", "Sonesse 30 Motor") publish("#{addr}/$properties", "label,down,up,stop,positionpulses,positionpercent,ip,wink,reset,state,last_direction,last_action_source,last_action_cause,uplimit,downlimit,direction,upspeed,downspeed,slowspeed,#{(1..16).map { |ip| "ip#{ip}pulses,ip#{ip}percent" }.join(',')},groups") publish("#{addr}/label/$name", "Node label") publish("#{addr}/label/$datatype", "string") publish("#{addr}/label/$settable", "true") publish("#{addr}/down/$name", "Move in down direction") publish("#{addr}/down/$datatype", "boolean") publish("#{addr}/down/$settable", "true") publish("#{addr}/down/$retained", "false") publish("#{addr}/up/$name", "Move in up direction") publish("#{addr}/up/$datatype", "boolean") publish("#{addr}/up/$settable", "true") publish("#{addr}/up/$retained", "false") publish("#{addr}/stop/$name", "Cancel adjustments") publish("#{addr}/stop/$datatype", "boolean") publish("#{addr}/stop/$settable", "true") publish("#{addr}/stop/$retained", "false") publish("#{addr}/positionpulses/$name", "Position from up limit (in pulses)") publish("#{addr}/positionpulses/$datatype", "integer") publish("#{addr}/positionpulses/$format", "0:65535") publish("#{addr}/positionpulses/$unit", "pulses") publish("#{addr}/positionpulses/$settable", "true") publish("#{addr}/positionpercent/$name", "Position (in %)") publish("#{addr}/positionpercent/$datatype", "integer") publish("#{addr}/positionpercent/$format", "0:100") publish("#{addr}/positionpercent/$unit", "%") publish("#{addr}/positionpercent/$settable", "true") publish("#{addr}/ip/$name", "Intermediate Position") publish("#{addr}/ip/$datatype", "integer") publish("#{addr}/ip/$format", "1:16") publish("#{addr}/ip/$settable", "true") publish("#{addr}/wink/$name", "Feedback") publish("#{addr}/wink/$datatype", "boolean") publish("#{addr}/wink/$settable", "true") publish("#{addr}/wink/$retained", "false") publish("#{addr}/reset/$name", "Recall factory settings") publish("#{addr}/reset/$datatype", "enum") publish("#{addr}/reset/$format", SDN::Message::SetFactoryDefault::RESET.keys.join(',')) publish("#{addr}/reset/$settable", "true") publish("#{addr}/reset/$retained", "false") publish("#{addr}/state/$name", "State of the motor") publish("#{addr}/state/$datatype", "enum") publish("#{addr}/state/$format", SDN::Message::PostMotorStatus::STATE.keys.join(',')) publish("#{addr}/last_direction/$name", "Direction of last motion") publish("#{addr}/last_direction/$datatype", "enum") publish("#{addr}/last_direction/$format", SDN::Message::PostMotorStatus::DIRECTION.keys.join(',')) publish("#{addr}/last_action_source/$name", "Source of last action") publish("#{addr}/last_action_source/$datatype", "enum") publish("#{addr}/last_action_source/$format", SDN::Message::PostMotorStatus::SOURCE.keys.join(',')) publish("#{addr}/last_action_cause/$name", "Cause of last action") publish("#{addr}/last_action_cause/$datatype", "enum") publish("#{addr}/last_action_cause/$format", SDN::Message::PostMotorStatus::CAUSE.keys.join(',')) publish("#{addr}/uplimit/$name", "Up limit (always = 0)") publish("#{addr}/uplimit/$datatype", "integer") publish("#{addr}/uplimit/$format", "0:65535") publish("#{addr}/uplimit/$unit", "pulses") publish("#{addr}/uplimit/$settable", "true") publish("#{addr}/downlimit/$name", "Down limit") publish("#{addr}/downlimit/$datatype", "integer") publish("#{addr}/downlimit/$format", "0:65535") publish("#{addr}/downlimit/$unit", "pulses") publish("#{addr}/downlimit/$settable", "true") publish("#{addr}/direction/$name", "Motor rotation direction") publish("#{addr}/direction/$datatype", "enum") publish("#{addr}/direction/$format", "standard,reversed") publish("#{addr}/direction/$settable", "true") publish("#{addr}/upspeed/$name", "Up speed") publish("#{addr}/upspeed/$datatype", "integer") publish("#{addr}/upspeed/$format", "6:28") publish("#{addr}/upspeed/$unit", "RPM") publish("#{addr}/upspeed/$settable", "true") publish("#{addr}/downspeed/$name", "Down speed, always = Up speed") publish("#{addr}/downspeed/$datatype", "integer") publish("#{addr}/downspeed/$format", "6:28") publish("#{addr}/downspeed/$unit", "RPM") publish("#{addr}/downspeed/$settable", "true") publish("#{addr}/slowspeed/$name", "Slow speed") publish("#{addr}/slowspeed/$datatype", "integer") publish("#{addr}/slowspeed/$format", "6:28") publish("#{addr}/slowspeed/$unit", "RPM") publish("#{addr}/slowspeed/$settable", "true") publish("#{addr}/groups/$name", "Group Memberships") publish("#{addr}/groups/$datatype", "string") publish("#{addr}/groups/$settable", "true") (1..16).each do |ip| publish("#{addr}/ip#{ip}pulses/$name", "Intermediate Position #{ip}") publish("#{addr}/ip#{ip}pulses/$datatype", "integer") publish("#{addr}/ip#{ip}pulses/$format", "0:65535") publish("#{addr}/ip#{ip}pulses/$unit", "pulses") publish("#{addr}/ip#{ip}pulses/$settable", "true") publish("#{addr}/ip#{ip}percent/$name", "Intermediate Position #{ip}") publish("#{addr}/ip#{ip}percent/$datatype", "integer") publish("#{addr}/ip#{ip}percent/$format", "0:100") publish("#{addr}/ip#{ip}percent/$unit", "%") publish("#{addr}/ip#{ip}percent/$settable", "true") end motor = Motor.new(self, addr) @motors[addr] = motor publish("$nodes", (["discovery"] + @motors.keys.sort + @groups.keys.sort.to_a).join(",")) sdn_addr = SDN::Message.parse_address(addr) @mutex.synchronize do @request_queue.push(SDN::Message::GetNodeLabel.new(sdn_addr)) @request_queue.push(SDN::Message::GetMotorStatus.new(sdn_addr)) @request_queue.push(SDN::Message::GetMotorLimits.new(sdn_addr)) @request_queue.push(SDN::Message::GetMotorDirection.new(sdn_addr)) @request_queue.push(SDN::Message::GetMotorRollingSpeed.new(sdn_addr)) (1..16).each { |ip| @request_queue.push(SDN::Message::GetMotorIP.new(sdn_addr, ip)) } (0...16).each { |g| @request_queue.push(SDN::Message::GetGroupAddr.new(sdn_addr, g)) } @cond.signal end motor end |
#subscribe(topic) ⇒ Object
406 407 408 |
# File 'lib/sdn/mqtt_bridge.rb', line 406 def subscribe(topic) @mqtt.subscribe("#{@base_topic}/#{topic}") end |