Class: I3Ipc::Protocol

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

Overview

Communication interface with i3-ipc.

Can connect to i3-ipc socket, disconnect, send and receive messages.

Usage example: protocol = Protocol.new protocol.send(7) puts protocol.receive protocol.disconnect

For i3-ipc interface details refer to https://i3wm.org/docs/ipc.html.

Defined Under Namespace

Classes: NotConnected, WrongMagicString, WrongType

Constant Summary collapse

MAGIC_STRING =

Magic string for i3-ipc protocol to ensure the integrity of messages.

'i3-ipc'

Instance Method Summary collapse

Constructor Details

#initialize(socketpath = nil) ⇒ Protocol

Returns a new instance of Protocol.



48
49
50
# File 'lib/i3ipc/protocol.rb', line 48

def initialize(socketpath = nil)
  @socketpath = socketpath ? socketpath : get_socketpath
end

Instance Method Details

#connectObject

Connects to i3-ipc server socket using Socket::UNIXSocket. Does nothing if already connected.



54
55
56
# File 'lib/i3ipc/protocol.rb', line 54

def connect
  @socket = UNIXSocket.new(@socketpath) unless @socket
end

#disconnectObject

Disconnects from i3-ipc server socket. Does nothing if not connected.



60
61
62
63
# File 'lib/i3ipc/protocol.rb', line 60

def disconnect
  @socket && @socket.close
  @socket = nil
end

#receive(type = nil) ⇒ Object

Receives message from i3-ipc server socket.

Throws:

  • NotConnected if protocol is not connected.
  • WrongMagicString if got message with not expected magic string.
  • WrongType if got message with not expected magic type.

+type+: expected type of the message.

Raises:



85
86
87
88
89
90
91
92
93
94
95
# File 'lib/i3ipc/protocol.rb', line 85

def receive(type = nil)
  check_connected
  # length of "i3-ipc" + 4 bytes length + 4 bytes type
  data = @socket.read 14
  magic, len, recv_type = unpack_header(data)

  raise WrongMagicString.new(magic) unless MAGIC_STRING.eql? magic
  type && (raise WrongType.new(type, recv_type) unless type == recv_type)

  @socket.read(len)
end

#send(type, payload = nil) ⇒ Object

Sends packed message to i3-ipc server socket.

Throws:

  • NotConnected if protocol is not connected.

+type+: type of the message. +payload+: payload of the message



72
73
74
75
# File 'lib/i3ipc/protocol.rb', line 72

def send(type, payload = nil)
  check_connected
  @socket.write(pack(type, payload))
end