You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by ms...@apache.org on 2019/06/28 12:20:21 UTC
[plc4x] branch feature/s7-cpp updated: first stand with dll and all
necessary lib of boost
This is an automated email from the ASF dual-hosted git repository.
msommer pushed a commit to branch feature/s7-cpp
in repository https://gitbox.apache.org/repos/asf/plc4x.git
The following commit(s) were added to refs/heads/feature/s7-cpp by this push:
new 9779dc0 first stand with dll and all necessary lib of boost
9779dc0 is described below
commit 9779dc07d1e361e99ce57081d0e06517512ac43b
Author: Markus Sommer <ms...@apache.org>
AuthorDate: Fri Jun 28 14:20:06 2019 +0200
first stand with dll and all necessary lib of boost
---
.../cpp/org/apache/plc4x/cpp/PlcConnection.cpp | 82 ++++
.../main/cpp/org/apache/plc4x/cpp/PlcConnection.h | 169 +++++++
.../cpp/org/apache/plc4x/cpp/PlcDriverManager.cpp | 175 +++++++
.../cpp/org/apache/plc4x/cpp/PlcDriverManager.h | 71 +++
plc4cpp/drivers/CMakeLists.txt | 20 +
plc4cpp/drivers/s7/CMakeLists.txt | 46 ++
.../cpp/org/apache/plc4x/cpp/s7/S7PlcDriver.cpp | 93 ++++
.../main/cpp/org/apache/plc4x/cpp/s7/S7PlcDriver.h | 87 ++++
.../plc4x/cpp/s7/connection/S7PlcConnection.cpp | 133 ++++++
.../plc4x/cpp/s7/connection/S7PlcConnection.h | 149 ++++++
.../cpp/org/apache/plc4x/cpp/s7/dllexports.cpp | 18 +
.../main/cpp/org/apache/plc4x/cpp/s7/dllexports.h | 16 +
plc4cpp/examples/hello-world-plc4x/CMakeLists.txt | 37 ++
.../plc4x/cpp/examples/helloplc4x/helloPlc4x.cpp | 122 +++++
plc4cpp/protocols/driver-bases/base/CMakeLists.txt | 2 +-
.../plc4x/cpp/base/connection/BoostConnection.cpp | 504 +++++++++++++++++++++
.../plc4x/cpp/base/connection/BoostConnection.h | 120 +++++
.../cpp/base/messages/items/BaseDefaultFieldItem.h | 2 +-
18 files changed, 1844 insertions(+), 2 deletions(-)
diff --git a/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcConnection.cpp b/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcConnection.cpp
new file mode 100644
index 0000000..1c9380f
--- /dev/null
+++ b/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcConnection.cpp
@@ -0,0 +1,82 @@
+/*
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+ */
+
+#include "PlcConnection.h"
+#include "Logger.h"
+
+org.apache.plc4x.java.api
+
+namespace org
+{
+ namespace apache
+ {
+ namespace plc4x
+ {
+ namespace cpp
+ {
+ namespace api
+ {
+
+ PlcConnection::PlcConnection() :
+ _bOpen(false),
+ _pSendBuffer(NULL),
+ _pRecvBuffer(NULL),
+ _iSendBufferSize(0),
+ _iRecvBufferSize(0),
+ {
+ setSendBufferSize(DEFAULT_BUFFER_SIZE);
+ setRecvBufferSize(DEFAULT_BUFFER_SIZE);
+ _strErrorMessage = "";
+ }
+
+ PlcConnection::~PlcConnection()
+ {
+ if (_pSendBuffer != NULL) delete[] _pSendBuffer;
+ if (_pRecvBuffer != NULL) delete[] _pRecvBuffer;
+ }
+
+ PlcField PlcConnection::prepareField(String fieldQuery) throws PlcInvalidFieldException
+ {
+ BOOST_THROW_EXCEPTION(PlcRuntimeException("Parse method is not implemented for this connection / driver"));
+ }
+
+ void PlcConnection::setSendBufferSize(int iBufferSize)
+ {
+ if (iBlockSize != _iSendBufferSize)
+ {
+ _iSendBufferSize = iBlockSize;
+ if (_pSendBuffer != NULL) delete[] _pSendBuffer;
+ _pSendBuffer = new unsigned char[_iBlockSizeSend];
+ }
+ }
+
+ void PlcConnection::setRecvBufferSize(int iBufferSize)
+ {
+ if (iBlockSize != _iRecvBufferSize)
+ {
+ _iRecvBufferSize = iBufferSize;
+ if (_pRecvBuffer != NULL) delete[] _pRecvBuffer;
+ _pRecvBuffer = new unsigned char[_iBlockSizeReceive];
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcConnection.h b/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcConnection.h
new file mode 100644
index 0000000..26d6c79
--- /dev/null
+++ b/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcConnection.h
@@ -0,0 +1,169 @@
+/*
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+ */
+#ifndef _PLC_CONNECTION
+#define _PLC_CONNECTION
+
+#include <org/apache/plc4x/cpp/api/metadata/PlcConnectionMetadata.h>
+#include <org/apache/plc4x/cpp/api/messages/PlcReadRequest.h>
+#include <org/apache/plc4x/cpp/api/messages/PlcWriteRequest.h>
+#include <org/apache/plc4x/cpp/api/messages/PlcSubscriptionRequest.h>
+#include <org/apache/plc4x/cpp/api/messages/PlcUnsubscriptionRequest.h>
+
+#include <org/apache/plc4x/cpp/utils/logger/DatDmp.h>
+
+#include <boost/signals2.hpp>
+#include <memory>
+
+#define DEFAULT_BUFFER_SIZE 16384
+
+namespace org
+{
+ namespace apache
+ {
+ namespace plc4x
+ {
+ namespace cpp
+ {
+ namespace api
+ {
+ using namespace org::apache::plc4x::cpp::api::metadata;
+ using namespace org::apache::plc4x::cpp::api::messages;
+ using namespace org::apache::plc4x::cpp::utils;
+
+ /**
+ * Interface defining the most basic methods a PLC4X connection should support.
+ * This generally handles the connection establishment itself and the parsing of
+ * field address strings to the platform dependent PlcField instances.
+ */
+ class Message
+ {
+ public:
+ vector<char> vecBuffer;
+ };
+
+ typedef shared_ptr<Message> type_shpMessage;
+
+ typedef boost::signals2::signal<void(type_shpMessage)> type_sigConMessage;
+ typedef boost::signals2::signal<void(std::exception&)> type_sigConEventException;
+
+
+ class PlcConnection
+ {
+ public:
+
+ PlcConnection();
+ ~PlcConnection();
+
+
+ /**
+ * Establishes the connection to the remote PLC.
+ * @throws PlcConnectionException if the connection attempt failed
+ */
+ virtual void connect() = 0;
+
+ /**
+ * Indicates if the connection is established to a remote PLC.
+ * @return {@code true} if connected, {@code false} otherwise
+ */
+
+ inline bool isConnected() const { return _bConnected; }
+
+ /**
+ * Closes the connection to the remote PLC.
+ * @throws Exception if shutting down the connection failed
+ */
+ virtual void close() = 0;
+
+ /**
+ * Parse a fieldQuery for the given connection type.
+ *
+ * @throws PlcRuntimeException If the string cannot be parsed
+ */
+ PlcField prepareField(std::string fieldQuery);
+
+ /**
+ * Provides connection metadata.
+ */
+ virtual PlcConnectionMetadata* getMetadata() = 0;
+
+ /**
+ * Execute a ping query against a remote device to check the availability of the connection.
+ *
+ * @return CompletableFuture that is completed successfully (Void) or unsuccessfully with an PlcException.
+ */
+ virtual void ping() = 0;
+
+ /**
+ * Obtain read request builder.
+ * @throws PlcUnsupportedOperationException if the connection does not support reading
+ */
+ virtual PlcReadRequest::Builder* readRequestBuilder() = 0;
+
+ /**
+ * Obtain write request builder.
+ * @throws PlcUnsupportedOperationException if the connection does not support writing
+ */
+ //virtual Builder* writeRequestBuilder() = 0;
+
+ /**
+ * Obtain subscription request builder.
+ * @throws PlcUnsupportedOperationException if the connection does not support subscription
+ */
+ //virtual Builder* subscriptionRequestBuilder() = 0;
+
+ /**
+ * Obtain unsubscription request builder.
+ * @throws PlcUnsupportedOperationException if the connection does not support subscription
+ */
+ //virtual Builder* unsubscriptionRequestBuilder() = 0;
+
+
+ virtual bool send(unsigned char* pBytesToSend, int iNumBytesToSend) = 0;
+
+ inline int getSendBufferSize() const { return _iSendBufferSize; }
+ void setSendBufferSize(int iBufferSize);
+
+ inline int getRecvBufferSize() const { return _iRecvBufferSize; }
+ void setRecvBufferSize(int iBlockSize);
+
+ protected:
+
+ virtual void onReceive(const boost::system::error_code& errorCode, std::size_t szRecvBytes) = 0;
+
+ protected:
+ bool _bConnected;
+ unsigned char* _pSendBuffer;
+ int _iSendBufferSize;
+ unsigned char* _pRecvBuffer;
+ int _iRecvBufferSize;
+ std::string _strErrorMessage;
+
+ boost::mutex _mtxComLock;
+ boost::condition_variable _condComHandler;
+
+ DatDmp _dump;
+
+ };
+ }
+ }
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcDriverManager.cpp b/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcDriverManager.cpp
new file mode 100644
index 0000000..5c3506a
--- /dev/null
+++ b/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcDriverManager.cpp
@@ -0,0 +1,175 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+#include "PlcDriverManager.h"
+#include <windows.h>
+#include <boost/filesystem.hpp>
+#include <boost/regex.hpp>
+#include <iostream>
+
+namespace fs = boost::filesystem;
+
+namespace org
+{
+ namespace apache
+ {
+ namespace plc4x
+ {
+ namespace cpp
+ {
+ PlcDriverManager::PlcDriverManager()
+ {
+ findDrivers();
+ }
+
+ PlcDriverManager::~PlcDriverManager()
+ {
+ }
+
+ /**
+ * Connects to a PLC using the given plc connection string.
+ *
+ * @param url plc connection string.
+ * @return PlcConnection object.
+ * @throws PlcConnectionException an exception if the connection attempt failed.
+ */
+ PlcConnection* PlcDriverManager::getConnection(std::string url)
+ {
+ PlcDriver* pPlcDriver = NULL;
+ PlcConnection* pPlcConnection = NULL;
+
+ pPlcDriver = getDriver(url);
+ if (pPlcDriver != NULL)
+ {
+ pPlcConnection = pPlcDriver->connect(url);
+ }
+
+ return pPlcConnection;
+ }
+
+ /**
+ * Connects to a PLC using the given plc connection string using given authentication credentials.
+ *
+ * @param url plc connection string.
+ * @param authentication authentication credentials.
+ * @return PlcConnection object.
+ * @throws PlcConnectionException an exception if the connection attempt failed.
+ **/
+ PlcConnection* PlcDriverManager::getConnection(std::string url, PlcAuthentication& authentication)
+ {
+ PlcDriver* pPlcDriver = NULL;
+ PlcConnection* pPlcConnection = NULL;
+
+ pPlcDriver = getDriver(url);
+ if (pPlcDriver != NULL)
+ {
+ pPlcConnection = pPlcDriver->connect(url, authentication);
+ }
+
+ return pPlcConnection;
+ }
+
+ PlcDriver* PlcDriverManager::getDriver(std::string url)
+ {
+ PlcDriver* pPlcDriver = NULL;
+ std::string strProtocol = "";
+
+ try
+ {
+ boost::regex exFilter(REGEX_PROTOCOL.c_str());
+ boost::smatch what;
+
+ if (boost::regex_search(url, what, exFilter))
+ {
+ if (what.size() > 1)
+ {
+ strProtocol = what[1].str();
+ pPlcDriver = _mapDrivers[strProtocol];
+ }
+ }
+
+ if (pPlcDriver == NULL)
+ {
+ BOOST_THROW_EXCEPTION(PlcConnectionException("Unable to find driver for protocol '" + strProtocol + "'"));
+ }
+ }
+ catch (std::exception& ex)
+ {
+ BOOST_THROW_EXCEPTION(PlcConnectionException("Invalid plc4; connection string '" + url + "'", ex));
+ }
+
+ return pPlcDriver;
+ }
+
+ void PlcDriverManager::findDrivers()
+ {
+ typedef PlcDriver* (*pfCreatePlcDriver)();
+ pfCreatePlcDriver CreatePlcDriver;
+
+ boost::regex exFilter(PLC_DRIVER_TEMPLATE);
+ boost::smatch what;
+
+ for (fs::recursive_directory_iterator itDirFiles("../.."); itDirFiles != fs::recursive_directory_iterator(); itDirFiles++)
+ {
+ if (boost::filesystem::is_regular_file(*itDirFiles))
+ {
+ std::string strFilename = itDirFiles->path().filename().string();
+
+ if (boost::regex_search(strFilename, what, exFilter))
+ {
+ std::string strDriverName = what[1].str();
+
+ try
+ {
+ //TODO: Only implemented for Windows
+ HINSTANCE hdll = NULL;
+ hdll = LoadLibrary((itDirFiles->path().string().c_str()));
+ if (hdll != NULL)
+ {
+ CreatePlcDriver = (pfCreatePlcDriver)GetProcAddress(hdll, PLC_CREATE_DRIVER_INSTANCE.c_str());
+ if (CreatePlcDriver != NULL)
+ {
+ PlcDriver* pPlcDriver = NULL;
+
+ pPlcDriver = CreatePlcDriver();
+ if (pPlcDriver != NULL)
+ {
+ _mapDrivers.insert(std::pair<std::string, PlcDriver*>(pPlcDriver->getProtocolCode(), pPlcDriver));
+ }
+ }
+ }
+ }
+ catch (...)
+ {
+ }
+ }
+ }
+ }
+
+ if (_mapDrivers.size() == 0)
+ {
+ BOOST_THROW_EXCEPTION(PlcConnectionException("Unable to find drivers"));
+ }
+
+ return;
+ }
+ }
+ }
+ }
+}
diff --git a/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcDriverManager.h b/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcDriverManager.h
new file mode 100644
index 0000000..227310f
--- /dev/null
+++ b/plc4cpp/api/src/main/cpp/org/apache/plc4x/cpp/PlcDriverManager.h
@@ -0,0 +1,71 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+#ifndef _PLC_DRIVER_MANAGER
+#define _PLC_DRIVER_MANAGER
+#include <vector>
+#include <map>
+#include <string>
+#include <iostream>
+#include "./api/PlcConnection.h"
+#include "./spi/PlcDriver.h"
+#include "./api/exceptions/PlcConnectionException.h"
+
+using namespace org::apache::plc4x::cpp::api::exceptions;
+using namespace org::apache::plc4x::cpp::spi;
+
+namespace org
+{
+ namespace apache
+ {
+ namespace plc4x
+ {
+ namespace cpp
+ {
+ class PlcDriverManager
+ {
+
+ public:
+ PlcDriverManager();
+
+ ~PlcDriverManager();
+
+ PlcConnection* getConnection(std::string url);
+ PlcConnection* getConnection(std::string url, PlcAuthentication& authentication);
+
+ protected:
+
+ private:
+ std::map<std::string, PlcDriver*> _mapDrivers;
+ PlcDriver* getDriver(std::string url);
+
+ void findDrivers();
+
+ const std::string PLC_DRIVER_TEMPLATE = "plc4cpp-driver-(.*)(.dll|.so)";
+ const std::string PLC_CREATE_DRIVER_INSTANCE = "_CreatePlcDriverInstance";
+ const std::string REGEX_PROTOCOL = "^(?<proto>.*)://";
+
+
+ };
+ }
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/plc4cpp/drivers/CMakeLists.txt b/plc4cpp/drivers/CMakeLists.txt
new file mode 100644
index 0000000..4c3bf2b
--- /dev/null
+++ b/plc4cpp/drivers/CMakeLists.txt
@@ -0,0 +1,20 @@
+#[[
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+]]
+
+add_subdirectory(s7)
diff --git a/plc4cpp/drivers/s7/CMakeLists.txt b/plc4cpp/drivers/s7/CMakeLists.txt
new file mode 100644
index 0000000..5f4727f
--- /dev/null
+++ b/plc4cpp/drivers/s7/CMakeLists.txt
@@ -0,0 +1,46 @@
+#[[
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+]]
+
+cmake_minimum_required(VERSION 3.7)
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+set(CMAKE_CXX_EXTENSIONS OFF)
+
+add_library(plc4cpp-driver-s7 SHARED
+ src/main/cpp/org/apache/plc4x/cpp/s7/dllexports.cpp
+ src/main/cpp/org/apache/plc4x/cpp/s7/S7PlcDriver.cpp
+ src/main/cpp/org/apache/plc4x/cpp/s7/connection/S7PlcConnection.cpp
+ )
+#[[
+ Import the headers for boost and the plc4cpp-api module
+]]
+target_include_directories (plc4cpp-driver-s7 PUBLIC ${Boost_INCLUDE_DIRS})
+target_include_directories (plc4cpp-driver-s7 PUBLIC ../../api/src/main/cpp)
+target_include_directories (plc4cpp-driver-s7 PUBLIC ../../protocols/driver-bases/base/src/main/cpp)
+target_include_directories (plc4cpp-driver-s7 PUBLIC ../../protocols/s7/src/main/cpp)
+target_include_directories (plc4cpp-driver-s7 PUBLIC ../../utils/logger/src/main/cpp)
+target_include_directories (plc4cpp-driver-s7 PUBLIC ../../utils/systemconfig/src/main/cpp)
+
+TARGET_LINK_LIBRARIES (plc4cpp-driver-s7
+ ${Boost_LIBRARIES}
+ plc4cpp-utils-logger
+ plc4cpp-api
+ plc4cpp-protocols-driver-base-base
+ plc4cpp-utils-systemconfig
+ )
\ No newline at end of file
diff --git a/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/S7PlcDriver.cpp b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/S7PlcDriver.cpp
new file mode 100644
index 0000000..e1a8f57
--- /dev/null
+++ b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/S7PlcDriver.cpp
@@ -0,0 +1,93 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+#include "S7PlcDriver.h"
+#include "connection/S7PlcConnection.h"
+#include <org/apache/plc4x/cpp/api/exceptions/PlcConnectionException.h>
+#include <boost/regex.hpp>
+
+using namespace std;
+using namespace org::apache::plc4x::cpp::api::exceptions;
+
+namespace org
+{
+ namespace apache
+ {
+ namespace plc4x
+ {
+ namespace cpp
+ {
+ namespace s7
+ {
+ string S7PlcDriver::getProtocolCode()
+ {
+ return std::string("s7");
+ }
+
+
+ string S7PlcDriver::getProtocolName() {
+ return "Siemens S7 (Basic)";
+ }
+
+ PlcConnection* S7PlcDriver::connect(std::string url)
+ {
+ boost::regex exFilter(S7_URI_PATTERN.c_str());
+ boost::smatch what;
+
+ std::string strHost = "";
+ int iRack = -1;
+ int iSlot = -1;
+ std::string strParams = "";
+ S7PlcConnection* pS7PlcConnection = NULL;
+
+ try
+ {
+ if (!boost::regex_search(url, what, exFilter))
+ {
+ BOOST_THROW_EXCEPTION(PlcConnectionException("Connection url doesn't match the format 's7://{host|ip}/{rack}/{slot}'"));
+ }
+
+ strHost = what[1].str(); // Host
+ iRack = std::stoi(what[2].str()); // Rack
+ iSlot = std::stoi(what[3].str()); // Slot
+ strParams = what[4].str(); // Params
+
+ // Resolve from Hostname to implements PlcConnection
+ pS7PlcConnection = new S7PlcConnection(strHost, iRack, iSlot, strParams);
+ }
+ catch (exception ex)
+ {
+ BOOST_THROW_EXCEPTION(PlcConnectionException("Error connecting to host", ex));
+ }
+
+ return pS7PlcConnection;
+ }
+
+
+ PlcConnection* S7PlcDriver::connect(std::string url, PlcAuthentication authentication)
+ {
+ BOOST_THROW_EXCEPTION(PlcConnectionException("Basic S7 connections don't support authentication."));
+ }
+
+
+ }
+ }
+ }
+ }
+}
diff --git a/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/S7PlcDriver.h b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/S7PlcDriver.h
new file mode 100644
index 0000000..53950a9
--- /dev/null
+++ b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/S7PlcDriver.h
@@ -0,0 +1,87 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+#ifndef _S7_PLC_DRIVER
+#define _S7_PLC_DRIVER
+
+#include <org/apache/plc4x/cpp/spi/PlcDriver.h>
+#include <org/apache/plc4x/cpp/api/authentication/PlcAuthentication.h>
+#include <string>
+
+using namespace org::apache::plc4x::cpp::spi;
+
+namespace org
+{
+ namespace apache
+ {
+ namespace plc4x
+ {
+ namespace cpp
+ {
+ namespace s7
+ {
+ /**
+ * Interface defining the most basic methods a PLC4X connection should support.
+ * This generally handles the connection establishment itself and the parsing of
+ * field address strings to the platform dependent PlcField instances.
+ */
+ class S7PlcDriver : public PlcDriver
+ {
+
+ public:
+ /**
+ * @return code of the implemented protocol. This is usually a lot shorter than the String returned by @seeĀ #getProtocolName().
+ */
+ virtual std::string getProtocolCode();
+
+ /**
+ * @return name of the implemented protocol.
+ */
+ virtual std::string getProtocolName();
+
+ /**
+ * Connects to a PLC using the given plc connection string.
+ * @param url plc connection string.
+ * @return PlcConnection object.
+ * @throws PlcConnectionException an exception if the connection attempt failed.
+ */
+ virtual PlcConnection* connect(std::string url);
+
+ /**
+ * Connects to a PLC using the given plc connection string using given authentication credentials.
+ * @param url plc connection string.
+ * @param authentication authentication credentials.
+ * @return PlcConnection object.
+ * @throws PlcConnectionException an exception if the connection attempt failed.
+ */
+ virtual PlcConnection* connect(std::string url, PlcAuthentication authentication);
+
+ private:
+
+ const std::string S7_URI_PATTERN="s7://(?<host>.*)/(?<rack>\\d{1,4})/(?<slot>\\d{1,4})(?<params>\\?.*)?";
+
+ };
+ }
+ }
+ }
+ }
+}
+
+#endif
+
diff --git a/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/connection/S7PlcConnection.cpp b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/connection/S7PlcConnection.cpp
new file mode 100644
index 0000000..b13dd11
--- /dev/null
+++ b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/connection/S7PlcConnection.cpp
@@ -0,0 +1,133 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+#include "S7PlcConnection.h"
+#include <boost/algorithm/string.hpp>
+#include <boost/lexical_cast.hpp>
+
+
+namespace org
+{
+ namespace apache
+ {
+ namespace plc4x
+ {
+ namespace cpp
+ {
+ namespace s7
+ {
+ S7PlcConnection::S7PlcConnection()
+ {
+ _lCloseDeviceTimeoutMS = CONF.getLong("plc4x.s7connection.close.device,timeout", 1000);
+ };
+
+ S7PlcConnection::~S7PlcConnection()
+ {
+
+ };
+
+ S7PlcConnection::S7PlcConnection(std::string strHost, int iRack, int iSlot, string strParams)
+ {
+ setIPAddress(strHost);
+ setPort(_ISO_ON_TCP_PORT);
+
+ _iRack = iRack;
+ _iSlot = iSlot;
+
+ short sCurParamPduSize = 1024;
+ short sCurParamMaxAmqCaller = 8;
+ short sCurParamMaxAmqCallee = 8;
+ S7ControllerType curParamControllerType = S7ControllerType::ANY;
+
+ if (strParams.length() > 0)
+ {
+ vector<string> vecParams;
+ boost::split(vecParams, strParams, boost::is_any_of("&"), boost::token_compress_on);
+ for (vector<string>::iterator itParams= vecParams.begin(); itParams < vecParams.end(); itParams++)
+ {
+ vector<string> vecParamElements;
+ boost::split(vecParamElements, *itParams, boost::is_any_of("="), boost::token_compress_on);
+ string strParamName = vecParamElements[0];
+ if (vecParamElements.size() == 2)
+ {
+ string strParamValue = vecParamElements[1];
+ boost::algorithm::to_lower(strParamValue);
+
+ if (strParamValue == "pdu-size")
+ {
+ sCurParamPduSize = boost::lexical_cast<short>(strParamValue);
+ }
+ else if (strParamValue == "max-amq-caller")
+ {
+ sCurParamMaxAmqCaller = boost::lexical_cast<short>(strParamValue);
+ }
+ else if (strParamValue == "max-amq-callee")
+ {
+ sCurParamMaxAmqCallee = boost::lexical_cast<short>(strParamValue);
+ }
+ else if (strParamValue == "controller-type")
+ {
+ S7ControllerTypeMap s7ControllerTypeMap;
+ curParamControllerType = s7ControllerTypeMap[strParamValue];
+ }
+ else
+ {
+ string strMessage = "Unknown parameter " + strParamName + " with value " + strParamValue;
+ LOG_DEBUG(strMessage);
+ }
+ }
+ else {
+ string strMessage = "Unknown no-value parameter " + strParamName;
+ LOG_DEBUG(strMessage);
+ }
+ }
+ }
+
+ // It seems that the LOGO devices are a little picky about the pdu-size.
+ // Instead of handling this out, they just hang up without any error message.
+ // So in case of a LOGO controller, set this to a known working value.
+ if (curParamControllerType == S7ControllerType::LOGO && sCurParamPduSize == 1024)
+ {
+ sCurParamPduSize = 480;
+ }
+
+ // IsoTP uses pre defined sizes. Find the smallest box,
+ // that would be able to contain the requested pdu size.
+ _sParamPduSize = sCurParamPduSize;
+ _sParamMaxAmqCaller = sCurParamMaxAmqCaller;
+ _sParamMaxAmqCallee = sCurParamMaxAmqCallee;
+ paramControllerType = curParamControllerType;
+
+ string strMessage = "Setting up S7cConnection with: host-name " + strHost +
+ " rack " + std::to_string(_iRack) + " slot " + std::to_string(_iSlot) +
+ " pdu-size " + std::to_string(_sParamPduSize) + " slot " + std::to_string(_iSlot) +
+ " max-amq-caller " + std::to_string(_sParamMaxAmqCaller) +
+ " max-amq-callee " + std::to_string(_sParamMaxAmqCallee);
+ LOG_INFO(strMessage);
+
+ return;
+ }
+
+
+
+ }
+ }
+ }
+ }
+}
diff --git a/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/connection/S7PlcConnection.h b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/connection/S7PlcConnection.h
new file mode 100644
index 0000000..856251b
--- /dev/null
+++ b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/connection/S7PlcConnection.h
@@ -0,0 +1,149 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+#ifndef _S7_PLC_CONNECTION
+#define _S7_PLC_CONNECTION
+
+#include <org/apache/plc4x/cpp/api/metadata/PlcConnectionMetadata.h>
+#include <org/apache/plc4x/cpp/api/messages/PlcReadRequest.h>
+#include <org/apache/plc4x/cpp/api/messages/PlcWriteRequest.h>
+#include <org/apache/plc4x/cpp/api/messages/PlcSubscriptionRequest.h>
+#include <org/apache/plc4x/cpp/api/messages/PlcUnsubscriptionRequest.h>
+#include <org/apache/plc4x/cpp/base/connection/BoostConnection.h>
+#include <org/apache/plc4x/cpp/base/connection/ChannelFactory.h>
+#include <org/apache/plc4x/cpp/s7/types/S7ControllerType.h>
+#include <org/apache/plc4x/cpp/utils/logger/BLogger.h>
+#include <org/apache/plc4x/cpp/utils/systemconfig/SystemConfiguration.h>
+
+
+/**
+ * Class implementing the Connection handling for Siemens S7.
+ * The adressing of Values in S7 works as follows:
+ * <p>
+ * For adressing values from Datablocks the following syntax is used:
+ * <pre>
+ * DATA_BLOCKS/{blockNumer}/{byteOffset}
+ * </pre>
+ * <p>
+ * For adressing data from other memory segments like I/O, Markers, ...
+ * <pre>
+ * {memory area}/{byte offset}
+ * or
+ * {memory area}/{byte offset}/{bit offset}
+ * </pre>
+ * where the {bit-offset} is optional.
+ * All Available Memory Areas for this mode are defined in the {@link MemoryArea} enum.
+ */
+
+namespace org
+{
+ namespace apache
+ {
+ namespace plc4x
+ {
+ namespace cpp
+ {
+ namespace s7
+ {
+
+ using namespace org::apache::plc4x::cpp::api::metadata;
+ using namespace org::apache::plc4x::cpp::api::messages;
+ using namespace org::apache::plc4x::cpp::api;
+ using namespace org::apache::plc4x::cpp::base::connection;
+ using namespace org::apache::plc4x::cpp::s7::types;
+ using namespace org::apache::plc4x::cpp::utils;
+
+ /**
+ * Interface defining the most basic methods a PLC4X connection should support.
+ * This generally handles the connection establishment itself and the parsing of
+ * field address strings to the platform dependent PlcField instances.
+ */
+ class S7PlcConnection : public BoostConnection
+ {
+ public:
+
+ S7PlcConnection();
+ S7PlcConnection(std::string strHost, int iRack, int iSlot, string strParams);
+
+ ~S7PlcConnection();
+
+ void connect() {};
+
+ /**
+ * Provides connection metadata.
+ */
+ PlcConnectionMetadata* getMetadata() { return NULL; };
+
+ /**
+ * Obtain read request builder.
+ * @throws PlcUnsupportedOperationException if the connection does not support reading
+ * Todo: implement pendant for java Builder pattern
+ */
+ PlcReadRequest::Builder* readRequestBuilder() { return NULL; };
+
+ /**
+ * Obtain write request builder.
+ * @throws PlcUnsupportedOperationException if the connection does not support writing
+ * Todo: implement pendant for java Builder pattern (PlcWriteRequest.Builder)
+ */
+ PlcWriteRequest* writeRequestBuilder() { return NULL; };
+
+ /**
+ * Obtain subscription request builder.
+ * @throws PlcUnsupportedOperationException if the connection does not support subscription
+ * Todo: implement pendant for java Builder pattern (PlcSubscriptionRequest.Builder)
+ */
+ PlcSubscriptionRequest* subscriptionRequestBuilder() { return NULL; };
+
+ /**
+ * Obtain unsubscription request builder.
+ * @throws PlcUnsupportedOperationException if the connection does not support subscription
+ * Todo: implement pendant for java Builder pattern (PlcSubscriptionRequest.Builder)
+
+ */
+ PlcUnsubscriptionRequest* unsubscriptionRequestBuilder() { return NULL; };
+
+ void ping() {};
+
+ bool send(unsigned char* pBytesToSend, int iNumBytesToSend) { return true;};
+
+ void onReceive(const boost::system::error_code& errorCode, std::size_t szRecvBytes) {};
+
+ private:
+
+ const int _ISO_ON_TCP_PORT = 102;
+
+ SystemConfiguration CONF;
+
+ int _iRack;
+ int _iSlot;
+
+ short _sParamPduSize;
+ short _sParamMaxAmqCaller;
+ short _sParamMaxAmqCallee;
+ S7ControllerType paramControllerType;
+
+ };
+ }
+ }
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/dllexports.cpp b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/dllexports.cpp
new file mode 100644
index 0000000..1037feb
--- /dev/null
+++ b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/dllexports.cpp
@@ -0,0 +1,18 @@
+//-------- DllMain.cpp --------//
+#define __dll__
+#include "DllExports.h"
+#include "S7PlcDriver.h"
+#include <windows.h>
+
+using namespace org::apache::plc4x::cpp::s7;
+using namespace org::apache::plc4x::cpp::spi;
+
+int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void*)
+{
+ return 1;
+}
+
+_declspec(dllexport) PlcDriver* _CreatePlcDriverInstance()
+{
+ return new S7PlcDriver;
+}
\ No newline at end of file
diff --git a/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/dllexports.h b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/dllexports.h
new file mode 100644
index 0000000..a1de274
--- /dev/null
+++ b/plc4cpp/drivers/s7/src/main/cpp/org/apache/plc4x/cpp/s7/dllexports.h
@@ -0,0 +1,16 @@
+//-------- DllExports.h --------//
+#ifndef _DLLEXPORTS_H
+#define _DLLEXPORTS_H
+
+#include <org/apache/plc4x/cpp/spi/PlcDriver.h>
+
+/*#ifdef __dll__
+#define IMPEXP __declspec(dllexport)
+#else
+#define IMPEXP __declspec(dllimport)
+#endif // __dll__*/
+
+extern "C" __declspec(dllexport) org::apache::plc4x::cpp::spi::PlcDriver* _CreatePlcDriverInstance();
+
+
+#endif // DLLEXPORTS_H
\ No newline at end of file
diff --git a/plc4cpp/examples/hello-world-plc4x/CMakeLists.txt b/plc4cpp/examples/hello-world-plc4x/CMakeLists.txt
new file mode 100644
index 0000000..6e79849
--- /dev/null
+++ b/plc4cpp/examples/hello-world-plc4x/CMakeLists.txt
@@ -0,0 +1,37 @@
+#[[
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+]]
+
+cmake_minimum_required(VERSION 3.7)
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+set(CMAKE_CXX_EXTENSIONS OFF)
+
+add_executable(helloplc4x
+ src/main/cpp/org/apache/plc4x/cpp/examples/helloplc4x/helloplc4x.cpp)
+
+#[[
+ Import the headers for boost and the plc4cpp-api module
+]]
+
+TARGET_LINK_LIBRARIES (helloplc4x ${Boost_LIBRARIES} plc4cpp-driver-s7 plc4cpp-utils-logger plc4cpp-api)
+
+target_include_directories (helloplc4x PUBLIC ${Boost_INCLUDE_DIRS})
+target_include_directories (helloplc4x PUBLIC ../../api/src/main/cpp)
+target_include_directories (helloplc4x PUBLIC ../../utils/logger/src/main/cpp)
+
diff --git a/plc4cpp/examples/hello-world-plc4x/src/main/cpp/org/apache/plc4x/cpp/examples/helloplc4x/helloPlc4x.cpp b/plc4cpp/examples/hello-world-plc4x/src/main/cpp/org/apache/plc4x/cpp/examples/helloplc4x/helloPlc4x.cpp
new file mode 100644
index 0000000..0ad98bc
--- /dev/null
+++ b/plc4cpp/examples/hello-world-plc4x/src/main/cpp/org/apache/plc4x/cpp/examples/helloplc4x/helloPlc4x.cpp
@@ -0,0 +1,122 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+//package org.apache.plc4x.java.examples.helloplc4x;
+#include <iostream>
+
+#include <org/apache/plc4x/cpp/PlcDriverManager.h>
+#include <org/apache/plc4x/cpp/api/PlcConnection.h>
+#include <org/apache/plc4x/cpp/api/messages/PlcReadRequest.h>
+#include <org/apache/plc4x/cpp/api/messages/PlcReadResponse.h>
+#include <org/apache/plc4x/cpp/api/types/PlcResponseCode.h>
+#include <org/apache/plc4x/cpp/utils/logger/BLogger.h>
+
+using namespace std;
+using namespace org::apache::plc4x::cpp;
+
+/**
+ * Example code do demonstrate using PLC4X.
+ *
+ * @param args ignored.
+ */
+int main(int argc, char *argv[])
+{
+ /* CliOptions options = CliOptions.fromArgs(args);
+ if (options == null) {
+ CliOptions.printHelp();
+ // Could not parse.
+ System.exit(1);
+ }*/
+
+ cout << "test";
+
+ // Establish a connection to the plc using the url provided as first argument
+ try
+ {
+ PlcDriverManager plcDriverManager;
+ //options.getConnectionString()
+ PlcConnection* plcConnection = plcDriverManager.getConnection("s7://192.168.167.210/0/1");
+
+ // Check if this connection support reading of data.
+ /*if (!plcConnection.getMetadata().canRead()) {
+ logger.error("This connection doesn't support reading.");
+ return;
+ }*/
+
+ // Create a new read request:
+ // - Give the single item requested the alias name "value"
+ /*PlcReadRequest::Builder builder = plcConnection.readRequestBuilder();
+ for (int i = 0; i < options.getFieldAddress().length; i++) {
+ builder.addItem("value-" + i, options.getFieldAddress()[i]);
+ }
+ PlcReadRequest readRequest = builder.build();*/
+
+ //////////////////////////////////////////////////////////
+ // Read synchronously ...
+ // NOTICE: the ".get()" immediately lets this thread pause until
+ // the response is processed and available.*/
+ LOG_INFO("Synchronous request ...");
+ /*PlcReadResponse syncResponse = readRequest.execute().get();
+ // Simply iterating over the field names returned in the response.
+ printResponse(syncResponse);
+
+ //////////////////////////////////////////////////////////
+ // Read asynchronously ...
+ // Register a callback executed as soon as a response arrives.
+ logger.info("Asynchronous request ...");
+ CompletableFuture<? extends PlcReadResponse> asyncResponse = readRequest.execute();
+ asyncResponse.whenComplete((readResponse, throwable) -> {
+ if (readResponse != null) {
+ printResponse(readResponse);
+ } else {
+ logger.error("An error occurred: " + throwable.getMessage(), throwable);
+ }
+ }*/
+ }
+ catch (...)
+ {
+
+ }
+
+ return 0;
+}
+
+/*private static void printResponse(PlcReadResponse response) {
+ for (String fieldName : response.getFieldNames()) {
+ if(response.getResponseCode(fieldName) == PlcResponseCode.OK) {
+ int numValues = response.getNumberOfValues(fieldName);
+ // If it's just one element, output just one single line.
+ if(numValues == 1) {
+ logger.info("Value[" + fieldName + "]: " + response.getObject(fieldName));
+ }
+ // If it's more than one element, output each in a single row.
+ else {
+ logger.info("Value[" + fieldName + "]:");
+ for(int i = 0; i < numValues; i++) {
+ logger.info(" - " + response.getObject(fieldName, i));
+ }
+ }
+ }
+ // Something went wrong, to output an error message instead.
+ else {
+ logger.error("Error[" + fieldName + "]: " + response.getResponseCode(fieldName).name());
+ }
+ }
+}*/
+
+
diff --git a/plc4cpp/protocols/driver-bases/base/CMakeLists.txt b/plc4cpp/protocols/driver-bases/base/CMakeLists.txt
index 2abfea7..310ca0d 100644
--- a/plc4cpp/protocols/driver-bases/base/CMakeLists.txt
+++ b/plc4cpp/protocols/driver-bases/base/CMakeLists.txt
@@ -24,7 +24,7 @@ set(CMAKE_CXX_EXTENSIONS OFF)
add_library(plc4cpp-protocols-driver-base-base
src/main/cpp/org/apache/plc4x/cpp/base/connection/AbstractPlcConnection.cpp
- #src/main/cpp/org/apache/plc4x/cpp/base/connection/BoostConnection.cpp
+ src/main/cpp/org/apache/plc4x/cpp/base/connection/BoostConnection.cpp
src/main/cpp/org/apache/plc4x/cpp/base/connection/ChannelFactory.cpp
src/main/cpp/org/apache/plc4x/cpp/base/connection/DefaultPlcFieldHandler.cpp
src/main/cpp/org/apache/plc4x/cpp/base/connection/PlcFieldHandler.cpp
diff --git a/plc4cpp/protocols/driver-bases/base/src/main/cpp/org/apache/plc4x/cpp/base/connection/BoostConnection.cpp b/plc4cpp/protocols/driver-bases/base/src/main/cpp/org/apache/plc4x/cpp/base/connection/BoostConnection.cpp
new file mode 100644
index 0000000..9c06cc2
--- /dev/null
+++ b/plc4cpp/protocols/driver-bases/base/src/main/cpp/org/apache/plc4x/cpp/base/connection/BoostConnection.cpp
@@ -0,0 +1,504 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+#include "BoostConnection.h"
+#include <org/apache/plc4x/cpp/api/exceptions/PlcConnectionException.h>
+#include <org/apache/plc4x/cpp/utils/logger/DbgTrace.h>
+#include <org/apache/plc4x/cpp/utils/logger/BLogger.h>
+#include <org/apache/plc4x/cpp/utils/logger/ExLog.h>
+#include <boost/lexical_cast.hpp>
+#include <boost/format.hpp>
+
+#define CON_DEFAULT_IPADDRESS "127.0.0.1"
+#define CON_DEFAULT_PORT_ 0
+#define CON_DEFAULT_TIMEOUT 2000 // Milliseconds
+
+namespace org
+{
+ namespace apache
+ {
+ namespace plc4x
+ {
+ namespace cpp
+ {
+ namespace base
+ {
+ namespace connection
+ {
+
+ using namespace boost;
+ using namespace boost::signals2;
+ using namespace org::apache::plc4x::cpp::utils;
+ using namespace org::apache::plc4x::cpp::api::exceptions;
+
+ BoostConnection::BoostConnection() :
+ _pSocket(NULL),
+ _pWorker(NULL),
+ _pReceiveDispatcher_Thread(NULL),
+ _isReceiving(false),
+ _pClientThread(NULL),
+ _uiConnectionTimeout(CON_DEFAULT_TIMEOUT)
+ {
+ }
+
+ BoostConnection::~BoostConnection()
+ {
+ if (_pSocket != NULL)
+ {
+ try
+ {
+ this->close();
+ }
+ catch (std::exception& ex)
+ {
+ ExLog(1, ex, "BoostConnection::~BoostConnection() failed");
+ }
+ }
+ }
+
+ void BoostConnection::setIPAddress(string strIPAddress)
+ {
+ if (strIPAddress != _strIPAddress)
+ {
+ if (_bConnected)
+ {
+ _strErrorMessage = "Attempt to change the IP-Address " + strIPAddress + "of an already open connection";
+ BOOST_THROW_EXCEPTION(PlcConnectionException(_strErrorMessage));
+ }
+ else
+ {
+ try
+ {
+ if ((strIPAddress.length() >= 7) && (strIPAddress != _strIPAddress))
+ {
+ _strIPAddress = strIPAddress;
+ resolveEndpoint();
+
+ ip::tcp::endpoint ep(ip::address::from_string(strIPAddress), _usPort);
+ _endpoint = ep;
+ }
+ }
+ catch (std::exception& ex)
+ {
+ BOOST_THROW_EXCEPTION(ExLog(1, ex, "BoostConnection::setIP_Address(string strIP_Address) failed"));
+ }
+ }
+ }
+ }
+
+ void BoostConnection::setPort(unsigned short usPort)
+ {
+ if (_usPort != usPort)
+ {
+ if (_bConnected)
+ {
+ BOOST_THROW_EXCEPTION(PlcConnectionException("Attempt to change the port of an already open communication"));
+ }
+ else
+ {
+ try
+ {
+ _usPort = usPort;
+ resolveEndpoint();
+
+ ip::tcp::endpoint ep(ip::address::from_string(_strIPAddress), _usPort);
+ _endpoint = ep;
+ }
+ catch (std::exception& ex)
+ {
+ BOOST_THROW_EXCEPTION(ExLog(1, ex, "BoostConnection::setPort(unsigned short port) failed"));
+ }
+ }
+ }
+ }
+
+ void BoostConnection::setEndpoint(tcp::endpoint endpoint)
+ {
+ if (endpoint != _endpoint)
+ {
+ if (_bConnected)
+ {
+ _strErrorMessage = "Attempt to change the endpoint of an already open communication";
+ _strErrorMessage = _strErrorMessage + "Setting Endpoint " + endpoint.address().to_string() + ":" + boost::lexical_cast<string>((unsigned int)endpoint.port()) + " for BoostConnection object failed";
+ BOOST_THROW_EXCEPTION(PlcConnectionException(_strErrorMessage));
+ }
+ else
+ {
+ try
+ {
+ _endpoint = endpoint;
+ resolveEndpoint();
+ }
+ catch (std::exception& ex)
+ {
+ BOOST_THROW_EXCEPTION(ExLog(1, ex, "BoostConnection::setEndpoint(tcp::endpoint endpoint) failed"));
+ }
+ }
+ }
+ }
+
+ /**---------------------------------------------------------------------
+ * Service Callback receive TCP Packets
+ *---------------------------------------------------------------------*/
+ void BoostConnection::dispatchReceive()
+ {
+ _strErrorMessage = "Attempt to use BoostConnection::dispatchReceive of BoostConnection";
+ LOG_INFO(_strErrorMessage); DEBUG_TRACE1("%s\n", _strErrorMessage.c_str());
+ BOOST_THROW_EXCEPTION(PlcConnectionException(_strErrorMessage));
+ }
+
+ /**---------------------------------------------------------------------
+ Connect TCP Socket
+ *---------------------------------------------------------------------*/
+ void BoostConnection::connect()
+ {
+ try
+ {
+
+ resolveEndpoint();
+
+ _endpoint = *_iterEndPoint;
+
+ BoostConnection::close();
+
+ _io_service.reset();
+
+ if (_pSocket == NULL) _pSocket = new tcp::socket(_io_service);
+
+ _pSocket->async_connect(_endpoint, boost::bind(&BoostConnection::onConnect, this, asio::placeholders::error, _iterEndPoint));
+
+ _pWorker = new io_service::work(_io_service);
+ _pClientThread = new boost::thread(boost::bind(&asio::io_service::run, &_io_service));
+
+ boost::mutex::scoped_lock lock(_mtxComLock);
+ _condComHandler.timed_wait(lock, boost::posix_time::milliseconds(_uiConnectionTimeout));
+
+ LOG_BOOL("Open BoostCommunication", _bConnected);
+
+ if (_bConnected)
+ {
+ _pReceiveDispatcher_Thread = new boost::thread(boost::bind(&BoostConnection::dispatchReceive, this));
+ }
+ else
+ {
+ BOOST_THROW_EXCEPTION(PlcConnectionException("Timeout while opening BoostConnection"));
+ }
+
+ }
+ catch (std::exception& ex)
+ {
+ BoostConnection::close();
+
+ BOOST_THROW_EXCEPTION(ExLog(1, ex, "BoostConnection::connect() failed"));
+ }
+ }
+
+ /**---------------------------------------------------------------------
+ Close TCP Socket
+ *---------------------------------------------------------------------*/
+ void BoostConnection::close()
+ {
+
+ try
+ {
+ _bConnected = false;
+
+ if ((_pClientThread != NULL) && (boost::this_thread::get_id() != _pClientThread->get_id()))
+ {
+ if (_pSocket != NULL)
+ {
+ _io_service.post(boost::bind(&asio::ip::tcp::socket::close, _pSocket));
+ }
+ _io_service.post(boost::bind(&io_service::stop, &_io_service));
+
+ }
+ else
+ {
+ if (_pSocket != NULL)
+ {
+ _pSocket->close();
+ }
+ _io_service.stop();
+ }
+
+ clearRessources();
+
+ }
+ catch (std::exception& ex)
+ {
+ clearRessources();
+
+ _bConnected = false;
+
+ BOOST_THROW_EXCEPTION(ExLog(1, ex, "BoostConnection::close() failed"));
+ }
+
+ return;
+ }
+
+ /**---------------------------------------------------------------------
+ Send Bytes via TCP Socket
+ *---------------------------------------------------------------------*/
+ bool BoostConnection::send(unsigned char* pBytesToSend, int iBytesToSend)
+ {
+ bool bSuccess = false;
+
+ boost::lock_guard<boost::mutex> lock(_mutexSend);
+
+ if (_bConnected)
+ {
+ try
+ {
+ _pSocket->async_send(asio::buffer(pBytesToSend, iBytesToSend),
+ boost::bind(&BoostConnection::onSend, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)
+ );
+
+ _dump.setLeadingNewLine(true);
+ std::string strTelegram = "\nBoostConnection TCP Telegram Send" + _dump.Show(pBytesToSend, iBytesToSend, " ** ");
+ LOG_TRACE(strTelegram.c_str()); DEBUG_TRACE1("%s", strTelegram.c_str());
+
+ bSuccess = true;
+ }
+ catch (std::exception& ex)
+ {
+ bSuccess = false;
+ BOOST_THROW_EXCEPTION(ExLog(1, ex, "BoostConnection::send() failed"));
+ }
+ }
+ return bSuccess;
+ }
+
+
+ void BoostConnection::ping()
+ {
+ try
+ {
+ /*(Socket s = new Socket())
+ s.connect(address, PING_TIMEOUT_MS);
+ // TODO keep the address for a (timely) next request???
+ s.setReuseAddress(true);*/
+ }
+ catch (std::exception ex)
+ {
+ BOOST_THROW_EXCEPTION(ExLog(1, ex, "Unable to ping remote host"));
+ }
+ }
+ /**---------------------------------------------------------------------
+ Free Ressources
+ *---------------------------------------------------------------------*/
+ void BoostConnection::clearRessources()
+ {
+ try
+ {
+
+ _io_service.reset();
+
+ if (_pReceiveDispatcher_Thread != NULL)
+ {
+ if (boost::this_thread::get_id() != _pReceiveDispatcher_Thread->get_id())
+ {
+ _pReceiveDispatcher_Thread->interrupt();
+ _pReceiveDispatcher_Thread->join();
+ delete _pReceiveDispatcher_Thread; _pReceiveDispatcher_Thread = NULL;
+ }
+ }
+
+ if (_pClientThread != NULL)
+ {
+ if (boost::this_thread::get_id() != _pClientThread->get_id())
+ {
+ _pClientThread->interrupt();
+ _pClientThread->join();
+ delete _pClientThread; _pClientThread = NULL;
+ }
+ }
+
+ if (_pWorker != NULL)
+ {
+ delete _pWorker; _pWorker = NULL;
+ }
+
+ if (_pSocket != NULL)
+ {
+ delete _pSocket; _pSocket = NULL;
+ }
+
+ }
+ catch (std::exception&)
+ {
+
+ }
+
+ return;
+ }
+
+ /**---------------------------------------------------------------------
+ Recieve next TCP Packets
+ *---------------------------------------------------------------------*/
+ void BoostConnection::continueReceive()
+ {
+ _pSocket->async_receive(
+ asio::buffer(_pRecvBuffer, _iRecvBufferSize),
+ bind(&BoostConnection::onReceive, this, asio::placeholders::error, asio::placeholders::bytes_transferred)
+ );
+ }
+
+ /**---------------------------------------------------------------------
+ Convert endpoint to String
+ *---------------------------------------------------------------------*/
+ string BoostConnection::endPointToString(tcp::endpoint ep)
+ {
+ return string(ep.address().to_string() + ":" + boost::lexical_cast<std::string>((unsigned short)ep.port()));
+ }
+
+ /**---------------------------------------------------------------------
+ Service Callback for Async-Send Result by OnSend
+ *---------------------------------------------------------------------*/
+ void BoostConnection::onSend(const system::error_code& errorCode, std::size_t bytes_transferred)
+ {
+ if (errorCode != system::errc::success)
+ {
+ int iErrCode = errorCode.value();
+ if (iErrCode != NO_ERROR)
+ {
+ // WSAECONNRESET = 10054, WSAECONNABORTED = 10053, EPIPE, ECONNABORTED indicates "broken Connection"
+ if (iErrCode == WSAECONNRESET || iErrCode == WSAECONNABORTED || iErrCode == EPIPE)
+ {
+ BoostConnection::close();
+ }
+
+ std::stringstream stm;
+ stm << boost::format("BoostConnection Send Error %i: %s") % iErrCode % errorCode.message();
+ _strErrorMessage = stm.str();
+ LOG_TRACE(_strErrorMessage.c_str()); DEBUG_TRACE1("%s", _strErrorMessage.c_str());
+ // TODO: Signal
+ }
+ }
+ }
+
+ /**---------------------------------------------------------------------
+ Service Callback , Receive Data via TCP
+ *---------------------------------------------------------------------*/
+ void BoostConnection::onReceive(const system::error_code& errorCode, std::size_t bytes_transferred)
+ {
+ DEBUG_TRACE0("BoostConnection::onReceive() called\n");
+ if (errorCode != system::errc::success && errorCode.value() != ENOENT)
+ {
+ int iErrCode = errorCode.value();
+ if (iErrCode != NO_ERROR)
+ {
+ // WSAECONNRESET = 10054, WSAECONNABORTED = 10053, EPIPE, ECONNABORTED indicates "broken Connection"
+ if (iErrCode == WSAECONNRESET || iErrCode == WSAECONNABORTED || iErrCode == EPIPE)
+ {
+ BoostConnection::close();
+ }
+
+ std::stringstream stm;
+ stm << boost::format("BoostConnection Receive Error %i: %s") % iErrCode % errorCode.message();
+ _strErrorMessage = stm.str();
+ LOG_TRACE(_strErrorMessage.c_str()); DEBUG_TRACE1("%s", _strErrorMessage.c_str());
+ // TODO: Signal
+ }
+ }
+ }
+
+ /**---------------------------------------------------------------------
+ Resolve Endpoint
+ *---------------------------------------------------------------------*/
+ void BoostConnection::resolveEndpoint()
+ {
+ try
+ {
+ tcp::resolver Resolver(_io_service);
+ tcp::resolver::query EndpointQuery(_strIPAddress, std::to_string(_usPort));
+ _iterEndPoint = Resolver.resolve(EndpointQuery);
+ }
+ catch (std::exception& ex)
+ {
+ BOOST_THROW_EXCEPTION(ExLog(1, ex, "BoostConnection::resolveEndpoint() failed"));
+ }
+ }
+
+ /**---------------------------------------------------------------------
+ Service Callback open Connection Result
+ *---------------------------------------------------------------------*/
+ void BoostConnection::onConnect(const system::error_code& errorCode, tcp::resolver::iterator endpointIterator)
+ {
+
+ // Setzen des IsOpen auf true oder false
+ _bConnected = errorCode == system::errc::success;
+
+ ++endpointIterator;
+
+ if (!_bConnected && endpointIterator != tcp::resolver::iterator()) // connection failed, ..
+ {
+ try
+ {
+ // .. try the next endpoint in the list.
+ _pSocket->close();
+ _endpoint = *endpointIterator;
+ _pSocket->async_connect(_endpoint, boost::bind(&BoostConnection::onConnect, this, asio::placeholders::error, endpointIterator));
+ }
+ catch (std::exception& ex)
+ {
+ ExLog(1, ex, "BoostConnection::onConnect() Handler failed");
+ }
+ }
+ else if (errorCode == system::errc::success)
+ {
+ bool bServiceStopped = _io_service.stopped();
+
+ try
+ {
+ _pSocket->async_receive(
+ asio::buffer(_pRecvBuffer, _iRecvBufferSize),
+ bind(&BoostConnection::onReceive, this, asio::placeholders::error, asio::placeholders::bytes_transferred)
+ );
+
+ }
+ catch (std::exception& ex)
+ {
+ ExLog(1, ex, "BoostConnection::onConnect() async_receive failed");
+ }
+
+ if (bServiceStopped)
+ {
+ LOG_INFO("Restarting Client Thread for BoostConnection OnConnect");
+
+ try
+ {
+ if (_pClientThread != NULL) delete _pClientThread;
+ _pClientThread = new boost::thread(bind(&asio::io_service::run, &_io_service));
+ }
+ catch (std::exception& ex)
+ {
+ ExLog(1, ex, "BoostConnection::onConnect() failed");
+ }
+ }
+ }
+
+ _condComHandler.notify_all();
+
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/plc4cpp/protocols/driver-bases/base/src/main/cpp/org/apache/plc4x/cpp/base/connection/BoostConnection.h b/plc4cpp/protocols/driver-bases/base/src/main/cpp/org/apache/plc4x/cpp/base/connection/BoostConnection.h
new file mode 100644
index 0000000..bafe8d3
--- /dev/null
+++ b/plc4cpp/protocols/driver-bases/base/src/main/cpp/org/apache/plc4x/cpp/base/connection/BoostConnection.h
@@ -0,0 +1,120 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+
+#ifndef _BOOST_COMMUNICATION
+#define _BOOST_COMMUNICATION
+
+#include <string>
+#include <boost/asio.hpp>
+#include <boost/thread/thread.hpp>
+#include <boost/atomic/atomic.hpp>
+#include <org/apache/plc4x/cpp/PlcConnection.h>
+
+
+namespace org
+{
+ namespace apache
+ {
+ namespace plc4x
+ {
+ namespace cpp
+ {
+ namespace base
+ {
+ namespace connection
+ {
+ using namespace boost::asio;
+ using namespace boost::asio::ip;
+ using namespace org::apache::plc4x::cpp::api;
+
+ class BoostConnection: public PlcConnection
+ {
+ public:
+
+ BoostConnection();
+
+ ~BoostConnection();
+
+ inline unsigned short getPort() { return _endpoint.port(); }
+ void setPort(unsigned short usPort);
+
+ inline string getIPAddress() { return _strIPAddress; }
+ void setIPAddress(string strIPAddress);
+
+ inline int getConnectionTimeout() { return _uiConnectionTimeout; }
+ void setConnectionTimeout(int uiConnectionTimeout) { _uiConnectionTimeout = uiConnectionTimeout; }
+
+ inline tcp::endpoint getEndpoint() { return _endpoint; }
+ void setEndpoint(tcp::endpoint endpoint);
+
+ inline bool getIsReceiving() { return _isReceiving; }
+
+ virtual void connect();
+ virtual void close();
+ virtual bool send(unsigned char* pBytesToSend, int iBytesToSend);
+
+ void ping();
+
+ protected:
+
+ void clearRessources();
+
+ void resolveEndpoint();
+
+ virtual void onConnect(const boost::system::error_code& errorCode, tcp::resolver::iterator endpointIterator);
+ virtual void onSend(const boost::system::error_code& ErrorCode, std::size_t bytes_transferred);
+ virtual void onReceive(const boost::system::error_code& ErrorCode, std::size_t bytes_transferred);
+ virtual void dispatchReceive();
+
+ virtual void continueReceive();
+
+ string endPointToString(tcp::endpoint ep);
+
+ protected:
+ io_service _io_service;
+ io_service::work* _pWorker;
+ boost::thread* _pReceiveDispatcher_Thread;
+
+ tcp::endpoint _endpoint;
+ tcp::resolver::iterator _iterEndPoint;
+ tcp::socket* _pSocket;
+ address _ipAddress;
+ string _strIPAddress;
+ unsigned short _usPort;
+ unsigned int _uiConnectionTimeout;
+ long _lCloseDeviceTimeoutMS;
+
+ boost::mutex _mutexSend;
+ boost::atomic<bool> _isReceiving;
+
+ // General Properties
+ bool _bWriteInProgress;
+ boost::thread* _pClientThread;
+
+ private:
+
+ };
+ }
+ }
+ }
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/plc4cpp/protocols/driver-bases/base/src/main/cpp/org/apache/plc4x/cpp/base/messages/items/BaseDefaultFieldItem.h b/plc4cpp/protocols/driver-bases/base/src/main/cpp/org/apache/plc4x/cpp/base/messages/items/BaseDefaultFieldItem.h
index a06da0b..ddff424 100644
--- a/plc4cpp/protocols/driver-bases/base/src/main/cpp/org/apache/plc4x/cpp/base/messages/items/BaseDefaultFieldItem.h
+++ b/plc4cpp/protocols/driver-bases/base/src/main/cpp/org/apache/plc4x/cpp/base/messages/items/BaseDefaultFieldItem.h
@@ -113,7 +113,7 @@ namespace org
protected:
//BaseDefaultFieldItem() { this._values = new array<T>(0); }
inline BaseDefaultFieldItem(T* values) { _values = values; }
- inline T getValue(int index)
+ inline T getValue(unsigned int index)
{
if ((index < 0 || (index >= _values.size())))
{