Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use timed_mutex. for all communication ordered, a simple mutex just works fine. #331

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions include/opc/ua/client/client.h
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ class UaClient
// close communication with OPC-UA server, close all threads and subscriptions
void Disconnect();

/// @brief Deal with Disconnection problem when TCP LINK DOWN.
static void test_handler(int sign);
static Common::Logger::SharedPtr Logger_bak;

/// @brief Abort server connection
// abort communication with OPC-UA server, close all threads and subcsriptions
// Like Disconnect() but without CloseSession() call, which is not possible on faulty connection anyway
Expand Down
17 changes: 17 additions & 0 deletions my_configure.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/bin/bash

export PATH=$PATH:/opt/buildroot-2017.02.5/output/host/usr/bin


./configure CC=arm-linux-gnueabihf-gcc CXX=arm-linux-gnueabihf-g++ --host=arm-linux CPPFLAGS="-I/home/jason/lib/arm-python/include -I/home/jason/lib/libxml2/build/include/libxml2 -I/home/jason/lib/libxml2/build/include -I/home/jason/lib/boost" LDFLAGS="-L/home/jason/lib/arm-python/lib -L/home/jason/lib/libxml2/build/lib -L/home/jason/lib/boost/stage/lib" --enable-static=no --prefix=/home/jason/workspace/freeopcua/output

# After configure, DO EDIT Makefile
# 1. change LIBS
# 2. change /usr/include/libxmle to you libxml2 include path, use: %s/\/usr....
# 3. then do make


# Build python ext:
# 1. export CC=arm-linux-gnueabihf-gcc
# 2. export LDSHARED="arm-linux-gnueabihf-gcc -shared"
# 3. python2 setup.py build_ext --include-dirs="/home/jason/lib/boost:/home/jason/lib/arm-python/include/python2.7:/home/jason/lib/libxml2/build/include/libxml2:/home/jason/lib/libxml2/build/include" --library-dirs="/home/jason/lib/arm-python/lib:/home/jason/lib/libxml2/build/lib:/home/jason/lib/boost/stage/lib" --libraries=boost_atomic:boost_python:python2.7
3 changes: 2 additions & 1 deletion python/examples/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import sys
sys.path.append(".")

from IPython import embed
# from IPython import embed
import opcua

class SubHandler(opcua.SubscriptionHandler):
Expand All @@ -19,6 +19,7 @@ def event(self, handle, event):
server = opcua.Server(True)
server.set_endpoint("opc.tcp://localhost:4841/freeopcua/server/")
server.set_server_name("FreeOpcUa Example Server")
server.set_uri("urn://exampleserver.freeopcua.github.io")

# start the server
server.start()
Expand Down
22 changes: 22 additions & 0 deletions python/my_build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/bin/bash
python2 setup.py clean
rm -rf build
export PATH=$PATH:/opt/buildroot-2017.02.5/output/host/usr/bin

export CC=arm-linux-gnueabihf-gcc
export LDSHARED="arm-linux-gnueabihf-gcc -shared"

sudo cp /usr/bin/g++ /usr/bin/g++.bak
sudo ln -sf /opt/buildroot-2017.02.5/output/host/usr/bin/arm-linux-gnueabihf-g++ /etc/alternatives/c++
#sudo ln -sf /opt/buildroot-2017.02.5/output/host/usr/bin/arm-linux-gnueabihf-g++ /usr/bin/g++

python2 setup.py build_ext --include-dirs="/home/jason/lib/boost:/home/jason/lib/arm-python/include/python2.7:/home/jason/lib/libxml2/build/include/libxml2:/home/jason/lib/libxml2/build/include" --library-dirs="/home/jason/lib/arm-python/lib:/home/jason/lib/libxml2/build/lib:/home/jason/lib/boost/stage/lib" --libraries="boost_atomic boost_python python2.7"

echo "======================build done==========================="
sudo ln -sf /usr/bin/g++ /etc/alternatives/c++
sudo cp /usr/bin/g++.bak /usr/bin/g++
OBJ=build/lib.linux-x86_64-2.7/opcua.so
arm-linux-gnueabihf-strip $OBJ
echo "======================cp to tftpboot======================="
cp $OBJ /tftpboot

44 changes: 36 additions & 8 deletions python/src/py_opcua_module.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,24 @@ static void DataValue_set_server_picoseconds(DataValue & self, uint16_t ps)
static void Node_SetValue(Node & self, const object & obj, VariantType vtype)
{ self.SetValue(ToVariant2(obj, vtype)); }

static Node Node_AddVariable(Node & self, const NodeId & variableId, const QualifiedName & browsename, const object & obj, VariantType vtype)
{ return self.AddVariable(variableId, browsename, ToVariant2(obj, vtype)); }

static Node Node_AddVariable(Node & self, const std::string & nodeId, const std::string & browseName, const object & obj, VariantType vtype)
{ return self.AddVariable(nodeId, browseName, ToVariant2(obj, vtype)); }

static Node Node_AddVariable(Node & self, uint32_t namespaceidx, const std::string & BrowseName, const object & obj, VariantType vtype)
{ return self.AddVariable(namespaceidx, BrowseName, ToVariant2(obj, vtype)); }

static Node Node_AddProperty(Node & self, const NodeId & propertyId, const QualifiedName & browsename, const object & obj, VariantType vtype)
{ return self.AddProperty(propertyId, browsename, ToVariant2(obj, vtype)); }

static Node Node_AddProperty(Node & self, const std::string & nodeid, const std::string & browseName, const object & obj, VariantType vtype)
{ return self.AddProperty(nodeid, browseName, ToVariant2(obj, vtype)); }

static Node Node_AddProperty(Node & self, uint32_t namespaceidx, const std::string & browseName, const object & obj, VariantType vtype)
{ return self.AddProperty(namespaceidx, browseName, ToVariant2(obj, vtype)); }

//--------------------------------------------------------------------------
// UaClient helpers
//--------------------------------------------------------------------------
Expand Down Expand Up @@ -439,8 +457,8 @@ BOOST_PYTHON_MODULE(opcua)
.def("get_attribute", &Node::GetAttribute)
.def("set_attribute", &Node::SetAttribute)
.def("get_value", &Node::GetValue)
.def("set_value", (void(Node::*)(const DataValue &) const) &Node::SetValue)
.def("set_value", (void(Node::*)(const Variant &) const) &Node::SetValue)
//.def("set_value", (void(Node::*)(const DataValue &) const) &Node::SetValue)
//.def("set_value", (void(Node::*)(const Variant &) const) &Node::SetValue)
.def("set_value", &Node_SetValue)
.def("get_properties", &Node::GetProperties)
.def("get_variables", &Node::GetVariables)
Expand All @@ -454,12 +472,22 @@ BOOST_PYTHON_MODULE(opcua)
.def("add_object", (Node(Node::*)(const NodeId &, const QualifiedName &) const) &Node::AddObject)
.def("add_object", (Node(Node::*)(const std::string &, const std::string &) const) &Node::AddObject)
.def("add_object", (Node(Node::*)(uint32_t, const std::string &) const) &Node::AddObject)
.def("add_variable", (Node(Node::*)(const NodeId &, const QualifiedName &, const Variant &) const) &Node::AddVariable)
.def("add_variable", (Node(Node::*)(const std::string &, const std::string &, const Variant &) const) &Node::AddVariable)
.def("add_variable", (Node(Node::*)(uint32_t, const std::string &, const Variant &) const) &Node::AddVariable)
.def("add_property", (Node(Node::*)(const NodeId &, const QualifiedName &, const Variant &) const) &Node::AddProperty)
.def("add_property", (Node(Node::*)(const std::string &, const std::string &, const Variant &) const) &Node::AddProperty)
.def("add_property", (Node(Node::*)(uint32_t, const std::string &, const Variant &) const) &Node::AddProperty)
//.def("add_variable", (Node(Node::*)(const NodeId &, const QualifiedName &, const Variant &) const) &Node::AddVariable)
//.def("add_variable", (Node(Node::*)(const std::string &, const std::string &, const Variant &) const) &Node::AddVariable)
//.def("add_variable", (Node(Node::*)(uint32_t, const std::string &, const Variant &) const) &Node::AddVariable)
//.def("add_property", (Node(Node::*)(const NodeId &, const QualifiedName &, const Variant &) const) &Node::AddProperty)
//.def("add_property", (Node(Node::*)(const std::string &, const std::string &, const Variant &) const) &Node::AddProperty)
//.def("add_property", (Node(Node::*)(uint32_t, const std::string &, const Variant &) const) &Node::AddProperty)

/*
* Must GIVE data type, for python is type-less
*/
.def("add_variable", (Node (*)(Node &, const NodeId &, const QualifiedName &, const object &, VariantType)) &Node_AddVariable)
.def("add_variable", (Node (*)(Node &, uint32_t, const std::string &, const object &, VariantType)) &Node_AddVariable)
.def("add_variable", (Node (*)(Node &, const std::string &, const std::string &, const object &, VariantType)) &Node_AddVariable)
.def("add_property", (Node(*)(Node &, const NodeId &, const QualifiedName &, const object &, VariantType)) &Node_AddProperty)
.def("add_property", (Node(*)(Node &, const std::string &, const std::string &, const object &, VariantType)) &Node_AddProperty)
.def("add_property", (Node(*)(Node &, uint32_t, const std::string &, const object &, VariantType)) &Node_AddProperty)
.def(str(self))
.def(repr(self))
.def(self == self)
Expand Down
72 changes: 60 additions & 12 deletions python/src/py_opcua_variant.h
Original file line number Diff line number Diff line change
Expand Up @@ -182,19 +182,42 @@ Variant ToVariant2(const object & obj, VariantType vtype)
{
case VariantType::BOOLEAN:
var = ToVector<bool>(obj);
return var;

break;

case VariantType::SBYTE:
var = ToVector<int8_t>(obj);
break;
case VariantType::INT16:
var = ToVector<int16_t>(obj);
break;
case VariantType::INT32:
var = ToVector<int32_t>(obj);
break;
case VariantType::INT64:
var = ToVector<int64_t>(obj);
break;

case VariantType::BYTE:
var = ToVector<uint8_t>(obj);
break;
case VariantType::UINT16:
var = ToVector<uint16_t>(obj);
break;
case VariantType::UINT32:
var = ToVector<uint32_t>(obj);
return var;

break;
case VariantType::UINT64:
var = ToVector<uint64_t>(obj);
break;
case VariantType::FLOAT:
var = ToVector<float>(obj);
return var;
break;
case VariantType::DOUBLE:
var = ToVector<double>(obj);
break;

default:
return ToVariant(obj);
var = ToVariant(obj);
}
}
}
Expand All @@ -205,21 +228,46 @@ Variant ToVariant2(const object & obj, VariantType vtype)
{
case VariantType::BOOLEAN:
var = extract<bool>(obj)();
return var;

break;

case VariantType::SBYTE:
var = extract<int8_t>(obj)();
break;
case VariantType::INT16:
var = extract<int16_t>(obj)();
break;
case VariantType::INT32:
var = extract<int32_t>(obj)();
break;
case VariantType::INT64:
var = extract<int64_t>(obj)();
break;

case VariantType::BYTE:
var = extract<uint8_t>(obj)();
break;
case VariantType::UINT16:
var = extract<uint16_t>(obj)();
break;
case VariantType::UINT32:
var = extract<uint32_t>(obj)();
return var;

break;
case VariantType::UINT64:
var = extract<uint64_t>(obj)();
break;
case VariantType::FLOAT:
var = extract<float>(obj)();
return var;
break;
case VariantType::DOUBLE:
var = extract<double>(obj)();
break;

default:
return ToVariant(obj);
var = ToVariant(obj);
}
}

return var;
}


Expand Down
21 changes: 15 additions & 6 deletions src/client/binary_client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,21 +83,25 @@ class RequestCallback
public:
RequestCallback(const Common::Logger::SharedPtr & logger)
: Logger(logger)
, lock(m)
{
m.lock();
}
~RequestCallback()
{
m.unlock();
}

void OnData(std::vector<char> data, ResponseHeader h)
{
//std::cout << ToHexDump(data);
Data = std::move(data);
this->header = std::move(h);
doneEvent.notify_all();
m.unlock();
}

T WaitForData(std::chrono::milliseconds msec)
{
if (doneEvent.wait_for(lock, msec) == std::cv_status::timeout)
if (m.try_lock_for(msec) == false)
{ throw std::runtime_error("Response timed out"); }

T result;
Expand All @@ -122,9 +126,7 @@ class RequestCallback
Common::Logger::SharedPtr Logger;
std::vector<char> Data;
ResponseHeader header;
std::mutex m;
std::unique_lock<std::mutex> lock;
std::condition_variable doneEvent;
std::timed_mutex m;
};

class CallbackThread
Expand Down Expand Up @@ -891,6 +893,7 @@ class BinaryClient
catch (std::exception & ex)
{
//Remove the callback on timeout
LOG_DEBUG(Logger, "binary_client | send exception: handle: {}", request.Header.RequestHandle);
std::unique_lock<std::mutex> lock(Mutex);
Callbacks.erase(request.Header.RequestHandle);
lock.unlock();
Expand Down Expand Up @@ -980,6 +983,12 @@ class BinaryClient
if (callbackIt == Callbacks.end())
{
LOG_WARN(Logger, "binary_client | no callback found for message id: {}, handle: {}", id, header.RequestHandle);
/* 2019-8-22: Changed by jason416, Do clear buffer
* Once we recieve a request alreay handled, buffer must BE CLEANED, otherwise there will be two packet laies in buffer.
* As above, if two buffer are diffrent type request, it will cause logic_error excpetion.
* SO ADD DO CLEAR buffer when wrong packet receive.
*/
messageBuffer.clear();
return;
}

Expand Down
52 changes: 52 additions & 0 deletions src/client/client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -338,22 +338,74 @@ UaClient::~UaClient()
Disconnect();//Do not leave any thread or connection running
}

/*
* Deal with SIGPIPE(broken pipe) when call Disconnect(with TCP LINK DOWN).
*/
#include <signal.h>
void UaClient::test_handler(int sign)
{
LOG_INFO(Logger_bak, "ua_client | triggered SIGPIPE signal");
}

/* Save Logger */
Common::Logger::SharedPtr UaClient::Logger_bak = 0;

void UaClient::Disconnect()
{
KeepAlive.Stop();
Logger_bak = Logger; // for static member test_handler use

if (Server.get())
{
#if 0
CloseSessionResponse response = Server->CloseSession();

LOG_INFO(Logger, "ua_client | CloseSession response is {}", ToString(response.Header.ServiceResult));

CloseSecureChannel();
Server.reset();
}
#endif
/*
* Catch exception which raised by SIGPIPE durring CloseSession(which call tcp_send).
*/
try
{
if(signal(SIGPIPE, test_handler) == SIG_ERR)
throw std::runtime_error("bind signal handler error!");

CloseSessionResponse response = Server->CloseSession();

LOG_INFO(Logger, "ua_client | CloseSession response is {}", ToString(response.Header.ServiceResult));

CloseSecureChannel();
Server.reset();
}
catch(std::exception &ex)
{
std::string temp_str(ex.what());

// if exception code is SIGPIPE, clean resources
if(temp_str.find(" Broken pipe") != std::string::npos)
{
Server.reset();
}
else // if not, throw to higher level
{
if(signal(SIGPIPE, SIG_DFL) == SIG_ERR) // recovery default signal handle
throw std::runtime_error("bind default signal handler error!");
throw;
}
}
}

if(signal(SIGPIPE, SIG_DFL) == SIG_ERR) // recovery default signal handle
throw std::runtime_error("bind default signal handler error!");

LOG_INFO(Logger, "ua_client | Disconnectd");
}


void UaClient::Abort()
{
KeepAlive.Stop();
Expand Down