edouard@3364: from __future__ import print_function edouard@3364: from __future__ import absolute_import edouard@3364: edouard@3364: import csv edouard@3364: edouard@3364: from opcua import Client edouard@3364: from opcua import ua edouard@3364: edouard@3364: import wx edouard@3370: from wx.lib.agw.hypertreelist import HyperTreeList as TreeListCtrl edouard@3364: import wx.dataview as dv edouard@3364: edouard@3364: edouard@3364: UA_IEC_types = dict( edouard@3364: # pyopcua | IEC61131| C type | sz | open62541 enum | open62541 edouard@3364: Boolean = ("BOOL" , "uint8_t" , "X", "UA_TYPES_BOOLEAN", "UA_Boolean"), edouard@3364: SByte = ("SINT" , "int8_t" , "B", "UA_TYPES_SBYTE" , "UA_SByte" ), edouard@3364: Byte = ("USINT", "uint8_t" , "B", "UA_TYPES_BYTE" , "UA_Byte" ), edouard@3364: Int16 = ("INT" , "int16_t" , "W", "UA_TYPES_INT16" , "UA_Int16" ), edouard@3364: UInt16 = ("UINT" , "uint16_t", "W", "UA_TYPES_UINT16" , "UA_UInt16" ), edouard@3364: Int32 = ("DINT" , "uint32_t", "D", "UA_TYPES_INT32" , "UA_Int32" ), edouard@3364: UInt32 = ("UDINT", "int32_t" , "D", "UA_TYPES_UINT32" , "UA_UInt32" ), edouard@3364: Int64 = ("LINT" , "int64_t" , "L", "UA_TYPES_INT64" , "UA_Int64" ), edouard@3364: UInt64 = ("ULINT", "uint64_t", "L", "UA_TYPES_UINT64" , "UA_UInt64" ), edouard@3364: Float = ("REAL" , "float" , "D", "UA_TYPES_FLOAT" , "UA_Float" ), edouard@3364: Double = ("LREAL", "double" , "L", "UA_TYPES_DOUBLE" , "UA_Double" ), edouard@3364: ) edouard@3364: edouard@3364: UA_NODE_ID_types = { edouard@3365: "int" : ("UA_NODEID_NUMERIC", "{}" ), edouard@3365: "str" : ("UA_NODEID_STRING" , '"{}"'), edouard@3406: "UUID" : ("UA_NODEID_UUID" , '"{}"'), edouard@3364: } edouard@3364: edouard@3364: lstcolnames = [ "Name", "NSIdx", "IdType", "Id", "Type", "IEC"] edouard@3364: lstcolwidths = [ 100, 50, 100, 100, 100, 50] edouard@3364: lstcoltypess = [ str, int, str, str, str, int] edouard@3364: edouard@3364: directions = ["input", "output"] edouard@3364: edouard@3370: class OPCUASubListModel(dv.PyDataViewIndexListModel): edouard@3364: def __init__(self, data, log): edouard@3370: dv.PyDataViewIndexListModel.__init__(self, len(data)) edouard@3364: self.data = data edouard@3364: self.log = log edouard@3364: edouard@3364: def GetColumnType(self, col): edouard@3364: return "string" edouard@3364: edouard@3364: def GetValueByRow(self, row, col): edouard@3364: return str(self.data[row][col]) edouard@3364: edouard@3364: # This method is called when the user edits a data item in the view. edouard@3364: def SetValueByRow(self, value, row, col): edouard@3364: expectedtype = lstcoltypess[col] edouard@3364: edouard@3364: try: edouard@3364: v = expectedtype(value) edouard@3364: except ValueError: edouard@3364: self.log("String {} is invalid for type {}\n".format(value,expectedtype.__name__)) edouard@3364: return False edouard@3364: edouard@3364: if col == lstcolnames.index("IdType") and v not in UA_NODE_ID_types: edouard@3364: self.log("{} is invalid for IdType\n".format(value)) edouard@3364: return False edouard@3364: edouard@3364: self.data[row][col] = v edouard@3364: return True edouard@3364: edouard@3364: # Report how many columns this model provides data for. edouard@3364: def GetColumnCount(self): edouard@3364: return len(lstcolnames) edouard@3364: edouard@3364: # Report the number of rows in the model edouard@3364: def GetCount(self): edouard@3364: #self.log.write('GetCount') edouard@3364: return len(self.data) edouard@3364: edouard@3364: # Called to check if non-standard attributes should be used in the edouard@3364: # cell at (row, col) edouard@3364: def GetAttrByRow(self, row, col, attr): edouard@3364: if col == 5: edouard@3364: attr.SetColour('blue') edouard@3364: attr.SetBold(True) edouard@3364: return True edouard@3364: return False edouard@3364: edouard@3364: edouard@3364: def DeleteRows(self, rows): edouard@3364: # make a copy since we'll be sorting(mutating) the list edouard@3364: # use reverse order so the indexes don't change as we remove items edouard@3364: rows = sorted(rows, reverse=True) edouard@3364: edouard@3364: for row in rows: edouard@3364: # remove it from our data structure edouard@3364: del self.data[row] edouard@3364: # notify the view(s) using this model that it has been removed edouard@3364: self.RowDeleted(row) edouard@3364: edouard@3364: edouard@3364: def AddRow(self, value): edouard@3378: if self.data.append(value): edouard@3378: # notify views edouard@3378: self.RowAppended() edouard@3364: edouard@3364: def ResetData(self): edouard@3364: self.Reset(len(self.data)) edouard@3364: edouard@3364: OPCUAClientDndMagicWord = "text/beremiz-opcuaclient" edouard@3364: edouard@3364: class NodeDropTarget(wx.DropTarget): edouard@3364: edouard@3364: def __init__(self, parent): edouard@3364: data = wx.CustomDataObject(OPCUAClientDndMagicWord) edouard@3364: wx.DropTarget.__init__(self, data) edouard@3364: self.ParentWindow = parent edouard@3364: edouard@3364: def OnDrop(self, x, y): edouard@3364: self.ParentWindow.OnNodeDnD() edouard@3364: return True edouard@3364: edouard@3364: class OPCUASubListPanel(wx.Panel): edouard@3364: def __init__(self, parent, log, model, direction): edouard@3364: self.log = log edouard@3364: wx.Panel.__init__(self, parent, -1) edouard@3364: edouard@3364: self.dvc = dv.DataViewCtrl(self, edouard@3364: style=wx.BORDER_THEME edouard@3364: | dv.DV_ROW_LINES edouard@3364: | dv.DV_HORIZ_RULES edouard@3364: | dv.DV_VERT_RULES edouard@3364: | dv.DV_MULTIPLE edouard@3364: ) edouard@3364: edouard@3364: self.model = model edouard@3364: edouard@3364: self.dvc.AssociateModel(self.model) edouard@3364: edouard@3364: for idx,(colname,width) in enumerate(zip(lstcolnames,lstcolwidths)): edouard@3364: self.dvc.AppendTextColumn(colname, idx, width=width, mode=dv.DATAVIEW_CELL_EDITABLE) edouard@3364: edouard@3364: DropTarget = NodeDropTarget(self) edouard@3364: self.dvc.SetDropTarget(DropTarget) edouard@3364: edouard@3364: self.Sizer = wx.BoxSizer(wx.VERTICAL) edouard@3364: edouard@3364: self.direction = direction edouard@3364: titlestr = direction + " variables" edouard@3364: edouard@3364: title = wx.StaticText(self, label = titlestr) edouard@3364: edouard@3364: delbt = wx.Button(self, label="Delete Row(s)") edouard@3364: self.Bind(wx.EVT_BUTTON, self.OnDeleteRows, delbt) edouard@3364: edouard@3364: topsizer = wx.BoxSizer(wx.HORIZONTAL) edouard@3364: topsizer.Add(title, 1, wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, 5) edouard@3364: topsizer.Add(delbt, 0, wx.LEFT|wx.RIGHT, 5) edouard@3364: self.Sizer.Add(topsizer, 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5) edouard@3364: self.Sizer.Add(self.dvc, 1, wx.EXPAND) edouard@3364: edouard@3364: edouard@3364: edouard@3364: def OnDeleteRows(self, evt): edouard@3364: items = self.dvc.GetSelections() edouard@3364: rows = [self.model.GetRow(item) for item in items] edouard@3364: self.model.DeleteRows(rows) edouard@3364: edouard@3364: edouard@3364: def OnNodeDnD(self): edouard@3364: # Have to find OPC-UA client extension panel from here edouard@3364: # in order to avoid keeping reference (otherwise __del__ isn't called) edouard@3364: # splitter. panel. splitter edouard@3364: ClientPanel = self.GetParent().GetParent().GetParent() edouard@3364: nodes = ClientPanel.GetSelectedNodes() edouard@3364: for node in nodes: edouard@3364: cname = node.get_node_class().name edouard@3377: dname = node.get_display_name().Text edouard@3364: if cname != "Variable": edouard@3364: self.log("Node {} ignored (not a variable)".format(dname)) edouard@3364: continue edouard@3364: edouard@3364: tname = node.get_data_type_as_variant_type().name edouard@3364: if tname not in UA_IEC_types: edouard@3364: self.log("Node {} ignored (unsupported type)".format(dname)) edouard@3364: continue edouard@3364: edouard@3364: access = node.get_access_level() edouard@3364: if {"input":ua.AccessLevel.CurrentRead, edouard@3364: "output":ua.AccessLevel.CurrentWrite}[self.direction] not in access: edouard@3364: self.log("Node {} ignored because of insuficient access rights".format(dname)) edouard@3364: continue edouard@3364: edouard@3364: nsid = node.nodeid.NamespaceIndex edouard@3364: nid = node.nodeid.Identifier edouard@3364: nid_type = type(nid).__name__ edouard@3364: iecid = nid edouard@3364: edouard@3364: value = [dname, edouard@3364: nsid, edouard@3364: nid_type, edouard@3364: nid, edouard@3364: tname, edouard@3364: iecid] edouard@3364: self.model.AddRow(value) edouard@3364: edouard@3364: edouard@3364: edouard@3364: il = None edouard@3364: fldridx = None edouard@3364: fldropenidx = None edouard@3364: fileidx = None edouard@3364: smileidx = None edouard@3364: isz = (16,16) edouard@3364: edouard@3364: treecolnames = [ "Name", "Class", "NSIdx", "Id"] edouard@3364: treecolwidths = [ 250, 100, 50, 200] edouard@3364: edouard@3364: edouard@3364: def prepare_image_list(): edouard@3364: global il, fldridx, fldropenidx, fileidx, smileidx edouard@3364: edouard@3364: if il is not None: edouard@3364: return edouard@3364: edouard@3364: il = wx.ImageList(isz[0], isz[1]) edouard@3364: fldridx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, isz)) edouard@3364: fldropenidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, isz)) edouard@3364: fileidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, isz)) edouard@3364: smileidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_ADD_BOOKMARK, wx.ART_OTHER, isz)) edouard@3364: edouard@3364: edouard@3364: class OPCUAClientPanel(wx.SplitterWindow): edouard@3364: def __init__(self, parent, modeldata, log, uri_getter): edouard@3364: self.log = log edouard@3364: wx.SplitterWindow.__init__(self, parent, -1) edouard@3364: edouard@3364: self.ordered_nodes = [] edouard@3364: edouard@3364: self.inout_panel = wx.Panel(self) edouard@3364: self.inout_sizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=0) edouard@3364: self.inout_sizer.AddGrowableCol(0) edouard@3364: self.inout_sizer.AddGrowableRow(1) edouard@3364: edouard@3364: self.client = None edouard@3364: self.uri_getter = uri_getter edouard@3364: edouard@3364: self.connect_button = wx.ToggleButton(self.inout_panel, -1, "Browse Server") edouard@3364: edouard@3364: self.selected_splitter = wx.SplitterWindow(self.inout_panel, style=wx.SUNKEN_BORDER | wx.SP_3D) edouard@3364: edouard@3364: self.selected_datas = modeldata edouard@3364: self.selected_models = { direction:OPCUASubListModel(self.selected_datas[direction], log) for direction in directions } edouard@3364: self.selected_lists = { direction:OPCUASubListPanel( edouard@3364: self.selected_splitter, log, edouard@3364: self.selected_models[direction], direction) edouard@3364: for direction in directions } edouard@3364: edouard@3364: self.selected_splitter.SplitHorizontally(*[self.selected_lists[direction] for direction in directions]+[300]) edouard@3364: edouard@3364: self.inout_sizer.Add(self.connect_button, flag=wx.GROW) edouard@3364: self.inout_sizer.Add(self.selected_splitter, flag=wx.GROW) edouard@3364: self.inout_sizer.Layout() edouard@3364: self.inout_panel.SetAutoLayout(True) edouard@3364: self.inout_panel.SetSizer(self.inout_sizer) edouard@3364: edouard@3364: self.Initialize(self.inout_panel) edouard@3364: edouard@3364: self.Bind(wx.EVT_TOGGLEBUTTON, self.OnConnectButton, self.connect_button) edouard@3364: edouard@3364: def OnClose(self): edouard@3364: if self.client is not None: edouard@3364: self.client.disconnect() edouard@3364: self.client = None edouard@3364: edouard@3364: def __del__(self): edouard@3364: self.OnClose() edouard@3364: edouard@3364: def OnConnectButton(self, event): edouard@3364: if self.connect_button.GetValue(): edouard@3364: edouard@3364: self.tree_panel = wx.Panel(self) edouard@3364: self.tree_sizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=0) edouard@3364: self.tree_sizer.AddGrowableCol(0) edouard@3364: self.tree_sizer.AddGrowableRow(0) edouard@3364: edouard@3370: self.tree = TreeListCtrl(self.tree_panel, -1, style=0, agwStyle= edouard@3370: wx.TR_DEFAULT_STYLE edouard@3370: | wx.TR_MULTIPLE edouard@3370: | wx.TR_FULL_ROW_HIGHLIGHT edouard@3364: ) edouard@3364: edouard@3364: prepare_image_list() edouard@3364: self.tree.SetImageList(il) edouard@3364: edouard@3364: for idx,(colname, width) in enumerate(zip(treecolnames, treecolwidths)): edouard@3364: self.tree.AddColumn(colname) edouard@3364: self.tree.SetColumnWidth(idx, width) edouard@3364: edouard@3364: self.tree.SetMainColumn(0) edouard@3364: edouard@3364: self.client = Client(self.uri_getter()) edouard@3364: self.client.connect() edouard@3364: self.client.load_type_definitions() # load definition of server specific structures/extension objects edouard@3364: rootnode = self.client.get_root_node() edouard@3364: edouard@3364: rootitem = self.AddNodeItem(self.tree.AddRoot, rootnode) edouard@3364: edouard@3364: # Populate first level so that root can be expanded edouard@3364: self.CreateSubItems(rootitem) edouard@3364: edouard@3364: self.tree.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnExpand) edouard@3364: edouard@3364: self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnTreeNodeSelection) edouard@3364: self.tree.Bind(wx.EVT_TREE_BEGIN_DRAG, self.OnTreeBeginDrag) edouard@3364: edouard@3364: self.tree.Expand(rootitem) edouard@3364: edouard@3364: hint = wx.StaticText(self, label = "Drag'n'drop desired variables from tree to Input or Output list") edouard@3364: edouard@3364: self.tree_sizer.Add(self.tree, flag=wx.GROW) edouard@3364: self.tree_sizer.Add(hint, flag=wx.GROW) edouard@3364: self.tree_sizer.Layout() edouard@3364: self.tree_panel.SetAutoLayout(True) edouard@3364: self.tree_panel.SetSizer(self.tree_sizer) edouard@3364: edouard@3364: self.SplitVertically(self.tree_panel, self.inout_panel, 500) edouard@3364: else: edouard@3364: self.client.disconnect() edouard@3364: self.client = None edouard@3364: self.Unsplit(self.tree_panel) edouard@3364: self.tree_panel.Destroy() edouard@3364: edouard@3364: edouard@3364: def CreateSubItems(self, item): edouard@3364: node, browsed = self.tree.GetPyData(item) edouard@3364: if not browsed: edouard@3364: for subnode in node.get_children(): edouard@3364: self.AddNodeItem(lambda n: self.tree.AppendItem(item, n), subnode) edouard@3364: self.tree.SetPyData(item,(node, True)) edouard@3364: edouard@3364: def AddNodeItem(self, item_creation_func, node): edouard@3364: nsid = node.nodeid.NamespaceIndex edouard@3364: nid = node.nodeid.Identifier edouard@3367: dname = node.get_display_name().Text edouard@3364: cname = node.get_node_class().name edouard@3364: edouard@3364: item = item_creation_func(dname) edouard@3364: edouard@3364: if cname == "Variable": edouard@3364: access = node.get_access_level() edouard@3364: normalidx = fileidx edouard@3364: r = ua.AccessLevel.CurrentRead in access edouard@3364: w = ua.AccessLevel.CurrentWrite in access edouard@3364: if r and w: edouard@3364: ext = "RW" edouard@3364: elif r: edouard@3364: ext = "RO" edouard@3364: elif w: edouard@3364: ext = "WO" # not sure this one exist edouard@3364: else: edouard@3364: ext = "no access" # not sure this one exist edouard@3364: cname = "Var "+node.get_data_type_as_variant_type().name+" (" + ext + ")" edouard@3364: else: edouard@3364: normalidx = fldridx edouard@3364: edouard@3364: self.tree.SetPyData(item,(node, False)) edouard@3364: self.tree.SetItemText(item, cname, 1) edouard@3364: self.tree.SetItemText(item, str(nsid), 2) edouard@3364: self.tree.SetItemText(item, type(nid).__name__+": "+str(nid), 3) edouard@3364: self.tree.SetItemImage(item, normalidx, which = wx.TreeItemIcon_Normal) edouard@3364: self.tree.SetItemImage(item, fldropenidx, which = wx.TreeItemIcon_Expanded) edouard@3364: edouard@3364: return item edouard@3364: edouard@3364: def OnExpand(self, evt): edouard@3364: for item in evt.GetItem().GetChildren(): edouard@3364: self.CreateSubItems(item) edouard@3364: edouard@3364: # def OnActivate(self, evt): edouard@3364: # item = evt.GetItem() edouard@3364: # node, browsed = self.tree.GetPyData(item) edouard@3364: edouard@3364: def OnTreeNodeSelection(self, event): edouard@3364: items = self.tree.GetSelections() edouard@3364: items_pydata = [self.tree.GetPyData(item) for item in items] edouard@3364: edouard@3364: nodes = [node for node, _unused in items_pydata] edouard@3364: edouard@3364: # append new nodes to ordered list edouard@3364: for node in nodes: edouard@3364: if node not in self.ordered_nodes: edouard@3364: self.ordered_nodes.append(node) edouard@3364: edouard@3364: # filter out vanished items edouard@3364: self.ordered_nodes = [ edouard@3364: node edouard@3364: for node in self.ordered_nodes edouard@3364: if node in nodes] edouard@3364: edouard@3364: def GetSelectedNodes(self): edouard@3364: return self.ordered_nodes edouard@3364: edouard@3364: def OnTreeBeginDrag(self, event): edouard@3364: """ edouard@3364: Called when a drag is started in tree edouard@3364: @param event: wx.TreeEvent edouard@3364: """ edouard@3364: if self.ordered_nodes: edouard@3364: # Just send a recognizable mime-type, drop destination edouard@3364: # will get python data from parent edouard@3364: data = wx.CustomDataObject(OPCUAClientDndMagicWord) edouard@3364: dragSource = wx.DropSource(self) edouard@3364: dragSource.SetData(data) edouard@3364: dragSource.DoDragDrop() edouard@3364: edouard@3364: def Reset(self): edouard@3364: for direction in directions: edouard@3364: self.selected_models[direction].ResetData() edouard@3364: edouard@3364: edouard@3378: class OPCUAClientList(list): edouard@3378: def __init__(self, log = lambda m:None): edouard@3378: super(OPCUAClientList, self).__init__(self) edouard@3378: self.log = log edouard@3378: edouard@3378: def append(self, value): edouard@3378: v = dict(zip(lstcolnames, value)) edouard@3378: edouard@3378: if type(v["IEC"]) != int: edouard@3378: if len(self) == 0: edouard@3378: v["IEC"] = 0 edouard@3378: else: edouard@3378: iecnums = set(zip(*self)[lstcolnames.index("IEC")]) edouard@3378: greatest = max(iecnums) edouard@3378: holes = set(range(greatest)) - iecnums edouard@3378: v["IEC"] = min(holes) if holes else greatest+1 edouard@3378: edouard@3378: if v["IdType"] not in UA_NODE_ID_types: edouard@3378: self.log("Unknown IdType\n".format(value)) edouard@3378: return False edouard@3378: edouard@3378: try: edouard@3378: for t,n in zip(lstcoltypess, lstcolnames): edouard@3378: v[n] = t(v[n]) edouard@3378: except ValueError: edouard@3378: self.log("Variable {} (Id={}) has invalid type\n".format(v["Name"],v["Id"])) edouard@3378: return False edouard@3378: edouard@3378: if len(self)>0 and v["Id"] in zip(*self)[lstcolnames.index("Id")]: edouard@3378: self.log("Variable {} (Id={}) already in list\n".format(v["Name"],v["Id"])) edouard@3378: return False edouard@3378: edouard@3378: list.append(self, [v[n] for n in lstcolnames]) edouard@3378: edouard@3378: return True edouard@3378: edouard@3364: class OPCUAClientModel(dict): edouard@3378: def __init__(self, log = lambda m:None): edouard@3378: super(OPCUAClientModel, self).__init__() edouard@3364: for direction in directions: edouard@3378: self[direction] = OPCUAClientList(log) edouard@3364: edouard@3364: def LoadCSV(self,path): edouard@3364: with open(path, 'rb') as csvfile: edouard@3364: reader = csv.reader(csvfile, delimiter=',', quotechar='"') edouard@3364: buf = {direction:[] for direction, _model in self.iteritems()} edouard@3378: for direction, model in self.iteritems(): edouard@3378: self[direction][:] = [] edouard@3364: for row in reader: edouard@3364: direction = row[0] edouard@3378: self[direction].append(row[1:]) edouard@3364: edouard@3364: def SaveCSV(self,path): edouard@3364: with open(path, 'wb') as csvfile: edouard@3364: for direction, data in self.iteritems(): edouard@3364: writer = csv.writer(csvfile, delimiter=',', edouard@3364: quotechar='"', quoting=csv.QUOTE_MINIMAL) edouard@3364: for row in data: edouard@3364: writer.writerow([direction] + row) edouard@3364: edouard@3364: def GenerateC(self, path, locstr, server_uri): edouard@3364: template = """/* code generated by beremiz OPC-UA extension */ edouard@3364: edouard@3364: #include edouard@3364: #include edouard@3364: #include edouard@3364: edouard@3407: static UA_Client *client; edouard@3364: edouard@3364: #define DECL_VAR(ua_type, C_type, c_loc_name) \\ edouard@3407: static UA_Variant c_loc_name##_variant; \\ edouard@3407: static C_type c_loc_name##_buf = 0; \\ edouard@3364: C_type *c_loc_name = &c_loc_name##_buf; edouard@3364: edouard@3364: %(decl)s edouard@3364: edouard@3364: void __cleanup_%(locstr)s(void) edouard@3364: { edouard@3364: UA_Client_disconnect(client); edouard@3364: UA_Client_delete(client); edouard@3364: } edouard@3364: edouard@3364: edouard@3406: #define INIT_READ_VARIANT(ua_type, c_loc_name) \\ edouard@3392: UA_Variant_init(&c_loc_name##_variant); edouard@3392: edouard@3392: #define INIT_WRITE_VARIANT(ua_type, ua_type_enum, c_loc_name) \\ edouard@3392: UA_Variant_setScalar(&c_loc_name##_variant, (ua_type*)c_loc_name, &UA_TYPES[ua_type_enum]); edouard@3364: edouard@3364: int __init_%(locstr)s(int argc,char **argv) edouard@3364: { edouard@3364: UA_StatusCode retval; edouard@3364: client = UA_Client_new(); edouard@3364: UA_ClientConfig_setDefault(UA_Client_getConfig(client)); edouard@3364: %(init)s edouard@3364: edouard@3364: /* Connect to server */ edouard@3364: retval = UA_Client_connect(client, "%(uri)s"); edouard@3364: if(retval != UA_STATUSCODE_GOOD) { edouard@3364: UA_Client_delete(client); edouard@3364: return EXIT_FAILURE; edouard@3364: } edouard@3364: } edouard@3364: edouard@3392: #define READ_VALUE(ua_type, ua_type_enum, c_loc_name, ua_nodeid_type, ua_nsidx, ua_node_id) \\ edouard@3392: retval = UA_Client_readValueAttribute( \\ edouard@3392: client, ua_nodeid_type(ua_nsidx, ua_node_id), &c_loc_name##_variant); \\ edouard@3392: if(retval == UA_STATUSCODE_GOOD && UA_Variant_isScalar(&c_loc_name##_variant) && \\ edouard@3392: c_loc_name##_variant.type == &UA_TYPES[ua_type_enum]) { \\ edouard@3392: c_loc_name##_buf = *(ua_type*)c_loc_name##_variant.data; \\ edouard@3392: UA_Variant_clear(&c_loc_name##_variant); /* Unalloc requiered on each read ! */ \\ edouard@3364: } edouard@3364: edouard@3364: void __retrieve_%(locstr)s(void) edouard@3364: { edouard@3364: UA_StatusCode retval; edouard@3364: %(retrieve)s edouard@3364: } edouard@3364: edouard@3392: #define WRITE_VALUE(ua_type, c_loc_name, ua_nodeid_type, ua_nsidx, ua_node_id) \\ edouard@3392: UA_Client_writeValueAttribute( \\ edouard@3392: client, ua_nodeid_type(ua_nsidx, ua_node_id), &c_loc_name##_variant); edouard@3364: edouard@3364: void __publish_%(locstr)s(void) edouard@3364: { edouard@3364: %(publish)s edouard@3364: } edouard@3364: edouard@3364: """ edouard@3364: edouard@3364: formatdict = dict( edouard@3364: locstr = locstr, edouard@3364: uri = server_uri, edouard@3364: decl = "", edouard@3364: cleanup = "", edouard@3364: init = "", edouard@3364: retrieve = "", edouard@3364: publish = "" edouard@3364: ) edouard@3364: for direction, data in self.iteritems(): edouard@3364: iec_direction_prefix = {"input": "__I", "output": "__Q"}[direction] edouard@3364: for row in data: edouard@3365: name, ua_nsidx, ua_nodeid_type, _ua_node_id, ua_type, iec_number = row edouard@3364: iec_type, C_type, iec_size_prefix, ua_type_enum, ua_type = UA_IEC_types[ua_type] edouard@3364: c_loc_name = iec_direction_prefix + iec_size_prefix + locstr + "_" + str(iec_number) edouard@3365: ua_nodeid_type, id_formating = UA_NODE_ID_types[ua_nodeid_type] edouard@3365: ua_node_id = id_formating.format(_ua_node_id) edouard@3364: edouard@3364: formatdict["decl"] += """ edouard@3364: DECL_VAR({ua_type}, {C_type}, {c_loc_name})""".format(**locals()) edouard@3392: edouard@3392: if direction == "input": edouard@3392: formatdict["init"] +=""" edouard@3392: INIT_READ_VARIANT({ua_type}, {c_loc_name})""".format(**locals()) edouard@3392: formatdict["retrieve"] += """ edouard@3364: READ_VALUE({ua_type}, {ua_type_enum}, {c_loc_name}, {ua_nodeid_type}, {ua_nsidx}, {ua_node_id})""".format(**locals()) edouard@3392: edouard@3392: if direction == "output": edouard@3392: formatdict["init"] +=""" edouard@3392: INIT_WRITE_VARIANT({ua_type}, {ua_type_enum}, {c_loc_name})""".format(**locals()) edouard@3392: formatdict["publish"] += """ edouard@3392: WRITE_VALUE({ua_type}, {c_loc_name}, {ua_nodeid_type}, {ua_nsidx}, {ua_node_id})""".format(**locals()) edouard@3364: edouard@3364: Ccode = template%formatdict edouard@3364: edouard@3364: return Ccode edouard@3364: edouard@3364: if __name__ == "__main__": edouard@3364: edouard@3364: import wx.lib.mixins.inspection as wit edouard@3364: import sys,os edouard@3364: edouard@3364: app = wit.InspectableApp() edouard@3364: edouard@3364: frame = wx.Frame(None, -1, "OPCUA Client Test App", size=(800,600)) edouard@3364: edouard@3364: uri = sys.argv[1] if len(sys.argv)>1 else "opc.tcp://localhost:4840" edouard@3364: edouard@3364: test_panel = wx.Panel(frame) edouard@3364: test_sizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=0) edouard@3364: test_sizer.AddGrowableCol(0) edouard@3364: test_sizer.AddGrowableRow(0) edouard@3364: edouard@3378: modeldata = OPCUAClientModel(print) edouard@3364: edouard@3364: opcuatestpanel = OPCUAClientPanel(test_panel, modeldata, print, lambda:uri) edouard@3364: edouard@3364: def OnGenerate(evt): edouard@3364: dlg = wx.FileDialog( edouard@3364: frame, message="Generate file as ...", defaultDir=os.getcwd(), edouard@3364: defaultFile="", edouard@3364: wildcard="C (*.c)|*.c", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT edouard@3364: ) edouard@3364: edouard@3364: if dlg.ShowModal() == wx.ID_OK: edouard@3364: path = dlg.GetPath() edouard@3364: Ccode = """ edouard@3364: /* edouard@3364: In case open62541 was built just aside beremiz, you can build this test with: edouard@3364: gcc %s -o %s \\ edouard@3364: -I ../../open62541/plugins/include/ \\ edouard@3364: -I ../../open62541/build/src_generated/ \\ edouard@3364: -I ../../open62541/include/ \\ edouard@3364: -I ../../open62541/arch/ ../../open62541/build/bin/libopen62541.a edouard@3364: */ edouard@3364: edouard@3364: """%(path, path[:-2]) + modeldata.GenerateC(path, "test", uri) + """ edouard@3364: edouard@3364: int main(int argc, char *argv[]) { edouard@3364: edouard@3364: __init_test(arc,argv); edouard@3364: edouard@3364: __retrieve_test(); edouard@3364: edouard@3364: __publish_test(); edouard@3364: edouard@3364: __cleanup_test(); edouard@3364: edouard@3364: return EXIT_SUCCESS; edouard@3364: } edouard@3364: """ edouard@3364: edouard@3364: with open(path, 'wb') as Cfile: edouard@3364: Cfile.write(Ccode) edouard@3364: edouard@3364: edouard@3364: dlg.Destroy() edouard@3364: edouard@3364: def OnLoad(evt): edouard@3364: dlg = wx.FileDialog( edouard@3364: frame, message="Choose a file", edouard@3364: defaultDir=os.getcwd(), edouard@3364: defaultFile="", edouard@3364: wildcard="CSV (*.csv)|*.csv", edouard@3364: style=wx.FD_OPEN | wx.FD_CHANGE_DIR | wx.FD_FILE_MUST_EXIST ) edouard@3364: edouard@3364: if dlg.ShowModal() == wx.ID_OK: edouard@3364: path = dlg.GetPath() edouard@3364: modeldata.LoadCSV(path) edouard@3364: opcuatestpanel.Reset() edouard@3364: edouard@3364: dlg.Destroy() edouard@3364: edouard@3364: def OnSave(evt): edouard@3364: dlg = wx.FileDialog( edouard@3364: frame, message="Save file as ...", defaultDir=os.getcwd(), edouard@3364: defaultFile="", edouard@3364: wildcard="CSV (*.csv)|*.csv", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT edouard@3364: ) edouard@3364: edouard@3364: if dlg.ShowModal() == wx.ID_OK: edouard@3364: path = dlg.GetPath() edouard@3364: modeldata.SaveCSV(path) edouard@3364: edouard@3364: dlg.Destroy() edouard@3364: edouard@3364: test_sizer.Add(opcuatestpanel, flag=wx.GROW) edouard@3364: edouard@3364: testbt_sizer = wx.BoxSizer(wx.HORIZONTAL) edouard@3364: edouard@3364: loadbt = wx.Button(test_panel, label="Load") edouard@3364: test_panel.Bind(wx.EVT_BUTTON, OnLoad, loadbt) edouard@3364: edouard@3364: savebt = wx.Button(test_panel, label="Save") edouard@3364: test_panel.Bind(wx.EVT_BUTTON, OnSave, savebt) edouard@3364: edouard@3364: genbt = wx.Button(test_panel, label="Generate") edouard@3364: test_panel.Bind(wx.EVT_BUTTON, OnGenerate, genbt) edouard@3364: edouard@3364: testbt_sizer.Add(loadbt, 0, wx.LEFT|wx.RIGHT, 5) edouard@3364: testbt_sizer.Add(savebt, 0, wx.LEFT|wx.RIGHT, 5) edouard@3364: testbt_sizer.Add(genbt, 0, wx.LEFT|wx.RIGHT, 5) edouard@3364: edouard@3364: test_sizer.Add(testbt_sizer, flag=wx.GROW) edouard@3364: test_sizer.Layout() edouard@3364: test_panel.SetAutoLayout(True) edouard@3364: test_panel.SetSizer(test_sizer) edouard@3364: edouard@3364: def OnClose(evt): edouard@3364: opcuatestpanel.OnClose() edouard@3364: evt.Skip() edouard@3364: edouard@3364: frame.Bind(wx.EVT_CLOSE, OnClose) edouard@3364: edouard@3364: frame.Show() edouard@3364: edouard@3364: app.MainLoop() edouard@3364: