Class: PicOpc::Client

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

Instance Method Summary collapse

Constructor Details

#initialize(opc_server_name, options = {}) ⇒ Client

Returns a new instance of Client.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/picopc/picopc.rb', line 34

def initialize(opc_server_name, options = {}) 
  begin
    @opc_automation = OPC_Automation_1.new
    @opc_automation.Connect opc_server_name, 'localhost'
    @groups = @opc_automation.OPCGroups
    @group = @groups.add 'picopc_group'
    @opc_items = @group.OPCItems
    @items = {}
    @handle = 1
    if options[:cache]
      @source = OPCDataSource::OPCCache
    else
      @source = OPCDataSource::OPCDevice
    end
    @prefix = options[:prefix].to_s || ''
  rescue Exception => e
    PicOpcException[ei, 'Connecting to: ' + opc_server_name] # wrap all exceptions in this type
  end
end

Instance Method Details

#[](name) ⇒ Object



93
94
95
# File 'lib/picopc/picopc.rb', line 93

def [](name)
  read name
end

#[]=(name, value) ⇒ Object



97
98
99
# File 'lib/picopc/picopc.rb', line 97

def []=(name, value)
  write name, value
end

#add_item(name) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/picopc/picopc.rb', line 63

def add_item(name)
  if not @items.key? name
    @items[name] = @opc_items.AddItem(@prefix + name, @handle)
    @handle += 1
  end
  @items[name]
end

#cleanupObject



54
55
56
57
58
59
60
61
# File 'lib/picopc/picopc.rb', line 54

def cleanup
  begin
    @groups.RemoveAll
    @opc_automation.Disconnect
  rescue Exception => e
    PicOpcException[e] # wrap all exceptions in this type
  end
end

#read(name) ⇒ Object



72
73
74
75
76
77
78
79
80
81
# File 'lib/picopc/picopc.rb', line 72

def read(name)
  begin
    item = add_item name
    return_value = WIN32OLE_VARIANT.new 0, WIN32OLE::VARIANT::VT_VARIANT|WIN32OLE::VARIANT::VT_BYREF
    item.read @source, return_value
    return_value.value
  rescue Exception => e
    PicOpcException[e, 'Reading tag: ' + name] # wrap all exceptions in this type
  end
end

#tag(name, reference) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/picopc/picopc.rb', line 101

def tag(name, reference) 
  # Get a handle to the singleton class of obj
  metaclass = class << self; self; end

  metaclass.send :define_method, name do
    read reference
  end

  metaclass.send :define_method, (name.to_s + '=').to_sym do |value|
    write reference, value
  end
end

#write(name, value) ⇒ Object



84
85
86
87
88
89
90
91
# File 'lib/picopc/picopc.rb', line 84

def write(name, value)
  begin
    item = add_item name
    item.write value
  rescue Exception => e
    PicOpcException[e, 'Writing tag: %s with value %s' % [name.to_s, value.to_s]] # wrap all exceptions in this type
  end
end