diff options
Diffstat (limited to 'mobile_src/NFC')
75 files changed, 9119 insertions, 0 deletions
diff --git a/mobile_src/NFC/CMakeLists.txt b/mobile_src/NFC/CMakeLists.txt new file mode 100755 index 0000000..64c3a72 --- /dev/null +++ b/mobile_src/NFC/CMakeLists.txt @@ -0,0 +1,75 @@ +SET(TARGET_NAME ${nfc_target}) +SET(DESTINATION_NAME ${nfc_dest}) +SET(TARGET_IMPL_NAME ${nfc_impl}) + +IF(ENABLE_OPTIONAL_NFC) +PKG_CHECK_MODULES(platform_pkgs_nfc REQUIRED capi-network-nfc) + +INCLUDE_DIRECTORIES( + ${TOP}/Common + ${platform_pkgs_nfc_INCLUDE_DIRS} +) + +SET(CMAKE_INSTALL_RPATH +${CMAKE_INSTALL_RPATH} +${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + JSNFCManager.cpp + JSNFCAdapter.cpp + JSNFCTag.cpp + JSNdefMessage.cpp + JSNdefRecord.cpp + JSNdefRecordText.cpp + JSNdefRecordURI.cpp + JSNdefRecordMedia.cpp + JSNFCTarget.cpp + NFCConverter.cpp + EventNFCChangedPrivateData.cpp + NFCStaticController.cpp + NFCAsyncCallbackManager.cpp + NFCListenerManager.cpp + ResponseDispatcher.cpp + NFCFactory.cpp + INFCAdapter.cpp + INFCTag.cpp + TagFilter.cpp + INFCTarget.cpp + NFCDefaultAdapter.cpp + NFCAdapter.cpp + NFCTag.cpp + NdefMessage.cpp + NdefRecord.cpp + NdefRecordText.cpp + NdefRecordURI.cpp + NdefRecordMedia.cpp + NFCTarget.cpp + NFCUtil.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} + ${platform_pkgs_nfc_LIBRARIES} +) + +SET(SRCS + plugin_config.cpp + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +ENDIF(ENABLE_OPTIONAL_NFC) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/nfc + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) diff --git a/mobile_src/NFC/EventNFC.h b/mobile_src/NFC/EventNFC.h new file mode 100755 index 0000000..c2ce9c6 --- /dev/null +++ b/mobile_src/NFC/EventNFC.h @@ -0,0 +1,58 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_API_NFC_EVENT_NFC_H_ +#define WRTPLUGINS_API_NFC_EVENT_NFC_H_ + +#include <Commons/IEvent.h> + +namespace DeviceAPI { +namespace NFC { + +template <class templateClass> +class EventNFCTemplate : public WrtDeviceApis::Commons::IEvent<templateClass> +{ +protected: + bool result; + std::string errorName; + std::string errorMessage; +public: + void setResult(const bool value) {result = value;} + bool getResult() const {return result;} + void setError(const std::string &error) { errorName= error;} + void setErrorMessage(const std::string &message) { errorMessage= message;} + std::string getError() {return errorName;} + std::string getErrorMessage() {return errorMessage;} + EventNFCTemplate() :result(true), errorName(""), errorMessage("") { } +}; + +template <class templateEventClass> +class EventNFCPtrs +{ +private: + DPL::SharedPtr<templateEventClass> eventPtr; + void * thisPtr; +public: + DPL::SharedPtr<templateEventClass> getEventPtrs() const {return eventPtr;} + void *getThisPtr() {return thisPtr;} + EventNFCPtrs(const DPL::SharedPtr<templateEventClass> &event, void *myPtr) : eventPtr(event), thisPtr(myPtr) {} +}; + +} // NFC +} // DeviceAPI + +#endif //WRTPLUGINS_API_NFC_EVENT_NFC_H_
\ No newline at end of file diff --git a/mobile_src/NFC/EventNFCChanged.h b/mobile_src/NFC/EventNFCChanged.h new file mode 100755 index 0000000..61a894a --- /dev/null +++ b/mobile_src/NFC/EventNFCChanged.h @@ -0,0 +1,70 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_API_NFC_EVENT_NFC_CHANGED_H_ +#define WRTPLUGINS_API_NFC_EVENT_NFC_CHANGED_H_ + +#include <vector> +#include <dpl/shared_ptr.h> +#include <Commons/ListenerEvent.h> +#include <Commons/ListenerEventEmitter.h> +#include "EventNFC.h" + +namespace DeviceAPI { +namespace NFC { +enum EventNFCType { + NFC_TAG_TYPE, + NFC_TARGET_TYPE +}; +enum EventNFCStatus { + NFC_ATTATCHED, + NFC_DETATCHED +}; + +class EventNFCChanged : public WrtDeviceApis::Commons::ListenerEvent<EventNFCChanged> +{ +private: + void *m_props; + EventNFCType m_type; + EventNFCStatus m_status; +public: + void *getNFCProperties() { return m_props; } + void setNFCProperties(void *props) { m_props = props; } + EventNFCType getNFCType() const {return m_type;} + void setNFCType(const EventNFCType type) {m_type = type;} + EventNFCStatus getNFCStatus() const {return m_status;} + void setNFCStatus(const EventNFCStatus type) {m_status = type;} + EventNFCChanged() {} +}; +class EventNFCChangedSetPowered : public EventNFCTemplate<EventNFCChangedSetPowered> +{ +private: + bool powerState; +public: + bool getState() {return powerState;} + EventNFCChangedSetPowered(bool state): powerState(state) { } +}; + + +typedef DPL::SharedPtr<EventNFCChanged> EventNFCChangedPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter<EventNFCChanged> EventNFCChangedEmitter; +typedef DPL::SharedPtr<EventNFCChangedEmitter> EventNFCChangedEmitterPtr; +typedef DPL::SharedPtr<EventNFCChangedSetPowered> EventNFCChangedSetPoweredPtr; +} // NFC +} // DeviceAPI + +#endif //WRTPLUGINS_API_NFC_EVENT_NFC_CHANGED_H_
\ No newline at end of file diff --git a/mobile_src/NFC/EventNFCChangedPrivateData.cpp b/mobile_src/NFC/EventNFCChangedPrivateData.cpp new file mode 100755 index 0000000..f6a1012 --- /dev/null +++ b/mobile_src/NFC/EventNFCChangedPrivateData.cpp @@ -0,0 +1,43 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 "EventNFCChangedPrivateData.h" + +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace NFC { +EventNFCChangedPrivateData::EventNFCChangedPrivateData( + const JSCallbackManagerPtr& callbackManager, + const JSCallbackManagerPtr& detachedCallbackManager) : + m_callbackManager(callbackManager), + m_detachedCallbackManager(detachedCallbackManager) +{ +} + +JSCallbackManagerPtr EventNFCChangedPrivateData::getCallbackManager() const +{ + return m_callbackManager; +} + +JSCallbackManagerPtr EventNFCChangedPrivateData::getDetachedCallbackManager() +const +{ + return m_detachedCallbackManager; +} +} +} diff --git a/mobile_src/NFC/EventNFCChangedPrivateData.h b/mobile_src/NFC/EventNFCChangedPrivateData.h new file mode 100755 index 0000000..ba01254 --- /dev/null +++ b/mobile_src/NFC/EventNFCChangedPrivateData.h @@ -0,0 +1,47 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 TIZEN_NFC_EVENTNFCCHANGEDPRIVATE_H_ +#define TIZEN_NFC_EVENTNFCCHANGEDPRIVATE_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include <Security.h> + +namespace DeviceAPI { +namespace NFC { +class EventNFCChangedPrivateData : public WrtDeviceApis::Commons::IEventPrivateData, + public DeviceAPI::Common::SecurityAccessor +{ + public: + EventNFCChangedPrivateData(const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& callbackManager, + const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr& detachedCallbackManager); + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getCallbackManager() const; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getDetachedCallbackManager() const; + + private: + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_callbackManager; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_detachedCallbackManager; +}; + +typedef DPL::SharedPtr<EventNFCChangedPrivateData> EventNFCChangedPrivateDataPtr; +} +} + +#endif //TIZEN_NFC_EVENTNFCCHANGEDPRIVATE_H_
\ No newline at end of file diff --git a/mobile_src/NFC/EventTagAction.h b/mobile_src/NFC/EventTagAction.h new file mode 100755 index 0000000..bab0153 --- /dev/null +++ b/mobile_src/NFC/EventTagAction.h @@ -0,0 +1,95 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_API_NFC_EVENT_TAG_ACTION_H_ +#define WRTPLUGINS_API_NFC_EVENT_TAG_ACTION_H_ + +#include <vector> +#include "EventNFC.h" +#include <dpl/shared_ptr.h> +#include <nfc.h> + +namespace DeviceAPI { +namespace NFC { + +template <class templateClass> +class EventTagAction : public EventNFCTemplate<templateClass> +{ +protected: + void *messageHandle; + void setNdefMessageHandle(void *handle) { messageHandle = handle; } + void *getNdefMessageHandle() { return messageHandle; } +public: + EventTagAction() : messageHandle(NULL) { } +}; + +class EventTagActionRead : public EventNFCTemplate<EventTagActionRead> +{ +public: + void setReadNdefResult(std::vector<unsigned char> &result) {rawData = result;} + std::vector<unsigned char> getReadNdefResult() {return rawData;} + EventTagActionRead(){ } +private: + std::vector<unsigned char> rawData; + +}; + +class EventTagActionWrite : public EventTagAction<EventTagActionWrite> +{ +public: + ~EventTagActionWrite() { + if (messageHandle) + nfc_ndef_message_destroy((nfc_ndef_message_h)messageHandle); + } + void writeNdef(void *handle) {setNdefMessageHandle(handle);} + void *getNdefForWriting() {return getNdefMessageHandle();} + EventTagActionWrite(){ } +}; + +class EventTagActionTransceive : public EventNFCTemplate<EventTagActionTransceive> +{ +private: + std::vector<unsigned char> transceiveBuffer; +public: + void setTransceiveBuffer(const std::vector<unsigned char> &data) {transceiveBuffer = data;} + std::vector<unsigned char> getTransceiveBuffer() const {return transceiveBuffer;} + int getTransceiveBufferSize() const {return transceiveBuffer.size();} + void transceive(const std::vector<unsigned char> &data) {setTransceiveBuffer(data);} + EventTagActionTransceive() { } +}; + +class EventTagActionFormat : public EventNFCTemplate<EventTagActionFormat> +{ +private: + std::vector<unsigned char> m_key; + +public: + void format(const std::vector<unsigned char> &key) {m_key = key;} + std::vector<unsigned char> getKey() {return m_key;} + int getKeySize() const {return m_key.size();} + EventTagActionFormat() { } +}; + +typedef DPL::SharedPtr<EventTagActionRead> EventTagActionReadPtr; +typedef DPL::SharedPtr<EventTagActionWrite> EventTagActionWritePtr; +typedef DPL::SharedPtr<EventTagActionTransceive> EventTagActionTransceivePtr; +typedef DPL::SharedPtr<EventTagActionFormat> EventTagActionFormatPtr; +} // NFC +} // DeviceAPI + +#endif //WRTPLUGINS_API_NFC_EVENT_TAG_ACTION_H_ diff --git a/mobile_src/NFC/EventTargetAction.h b/mobile_src/NFC/EventTargetAction.h new file mode 100755 index 0000000..38dfed5 --- /dev/null +++ b/mobile_src/NFC/EventTargetAction.h @@ -0,0 +1,66 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_API_NFC_EVENT_TARGET_ACTION_H_ +#define WRTPLUGINS_API_NFC_EVENT_TARGET_ACTION_H_ + +#include <vector> +#include <dpl/shared_ptr.h> +#include <Commons/ListenerEvent.h> +#include <Commons/ListenerEventEmitter.h> +#include "EventNFC.h" +#include <nfc.h> + +namespace DeviceAPI { +namespace NFC { + +class EventTargetActionReceive : public WrtDeviceApis::Commons::ListenerEvent<EventTargetActionReceive> +{ + +public: + void setReadNdefResult(std::vector<unsigned char> &ndefResult) {rawData = ndefResult;} + std::vector<unsigned char> getReadNdefResult() {return rawData;} + EventTargetActionReceive(){ } +private: + std::vector<unsigned char> rawData; + +}; + +class EventTargetActionSend : public EventNFCTemplate<EventTargetActionSend> +{ +public: + ~EventTargetActionSend() { + if (message) + nfc_ndef_message_destroy((nfc_ndef_message_h)message); + } + void *getMessageForSending() {return message;} + EventTargetActionSend(void *handle) :message(handle){ } +private: + void *message; +}; + +typedef DPL::SharedPtr<EventTargetActionReceive> EventTargetActionReceivePtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter<EventTargetActionReceive> EventTargetActionReceiveEmitter; +typedef DPL::SharedPtr<EventTargetActionReceiveEmitter> EventTargetActionReceiveEmitterPtr; + +typedef DPL::SharedPtr<EventTargetActionSend> EventTargetActionSendPtr; + +} // NFC +} // DeviceAPI + +#endif //WRTPLUGINS_API_NFC_EVENT_TARGET_ACTION_H_ diff --git a/mobile_src/NFC/INFCAdapter.cpp b/mobile_src/NFC/INFCAdapter.cpp new file mode 100755 index 0000000..a961f18 --- /dev/null +++ b/mobile_src/NFC/INFCAdapter.cpp @@ -0,0 +1,34 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 "INFCAdapter.h" + +namespace DeviceAPI { +namespace NFC { + +using namespace WrtDeviceApis::Commons; + +INFCAdapter::INFCAdapter() : + EventNFCSetPoweredRequestReceiver(ThreadEnum::NFC_THREAD) { +} + +INFCAdapter::~INFCAdapter() { +} + +} +} diff --git a/mobile_src/NFC/INFCAdapter.h b/mobile_src/NFC/INFCAdapter.h new file mode 100755 index 0000000..ac223a2 --- /dev/null +++ b/mobile_src/NFC/INFCAdapter.h @@ -0,0 +1,56 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _ABSTRACT_LAYER_INFCADAPTER_H_ +#define _ABSTRACT_LAYER_INFCADAPTER_H_ + +#include <dpl/shared_ptr.h> +#include <vector> +#include <Commons/ThreadPool.h> +#include "EventNFCChanged.h" +#include "TagFilter.h" + +namespace DeviceAPI { +namespace NFC { + +typedef WrtDeviceApis::Commons::EventRequestReceiver<EventNFCChangedSetPowered> EventNFCSetPoweredRequestReceiver; + +class INFCAdapter : + public EventNFCSetPoweredRequestReceiver +{ + public: + + virtual ~INFCAdapter(); + virtual int setTagListener(const EventNFCChangedEmitterPtr& emitter, const TagFilterPtr& filter) = 0; + virtual void unsetTagListener() = 0; + virtual int setPeerListener(const EventNFCChangedEmitterPtr& emitter) = 0; + virtual void unsetPeerListener() = 0; + virtual void *getCachedMessage() = 0; + virtual bool getPowerState() = 0; + virtual void setPowered(const EventNFCChangedSetPoweredPtr& event) = 0; +protected: + INFCAdapter(); + virtual void OnRequestReceived(const EventNFCChangedSetPoweredPtr& event) = 0; +}; + +typedef DPL::SharedPtr<INFCAdapter> INFCAdapterPtr; + +} +} + +#endif /* _ABSTRACT_LAYER_INFCADAPTER_H_ */ diff --git a/mobile_src/NFC/INFCTag.cpp b/mobile_src/NFC/INFCTag.cpp new file mode 100755 index 0000000..39a2052 --- /dev/null +++ b/mobile_src/NFC/INFCTag.cpp @@ -0,0 +1,37 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 "INFCTag.h"
+
+namespace DeviceAPI {
+namespace NFC {
+
+using namespace WrtDeviceApis::Commons;
+
+INFCTag::INFCTag() :
+ EventRequestReceiver<EventTagActionRead>(ThreadEnum::NFC_THREAD),
+ EventRequestReceiver<EventTagActionWrite>(ThreadEnum::NFC_THREAD),
+ EventRequestReceiver<EventTagActionTransceive>(ThreadEnum::NFC_THREAD),
+ EventRequestReceiver<EventTagActionFormat>(ThreadEnum::NFC_THREAD){
+}
+
+INFCTag::~INFCTag() {
+}
+
+}
+}
diff --git a/mobile_src/NFC/INFCTag.h b/mobile_src/NFC/INFCTag.h new file mode 100755 index 0000000..302aa2a --- /dev/null +++ b/mobile_src/NFC/INFCTag.h @@ -0,0 +1,86 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _ABSTRACT_LAYER_NFCTAG_H_ +#define _ABSTRACT_LAYER_NFCTAG_H_ + +#include <dpl/shared_ptr.h> +#include <vector> +#include <Commons/ThreadPool.h> +#include "EventTagAction.h" +#include "NFCTagProperties.h" + +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace NFC { + + enum nfcTagType { + NFC_TAGTYPE_GENERIC_PICC = 0x00, + NFC_TAGTYPE_ISO14443_A_PICC = 0x01, + NFC_TAGTYPE_ISO14443_4A_PICC = 0x02, + NFC_TAGTYPE_ISO14443_3A_PICC = 0x03, + NFC_TAGTYPE_MIFARE_MINI_PICC = 0x04, + NFC_TAGTYPE_MIFARE_1K_PICC = 0x05, + NFC_TAGTYPE_MIFARE_4K_PICC = 0x06, + NFC_TAGTYPE_MIFARE_ULTRA_PICC = 0x07, + NFC_TAGTYPE_MIFARE_DESFIRE_PICC = 0x08, + NFC_TAGTYPE_ISO14443_B_PICC = 0x09, + NFC_TAGTYPE_ISO14443_4B_PICC = 0x0a, + NFC_TAGTYPE_ISO14443_BPRIME_PICC = 0x0b, + NFC_TAGTYPE_FELICA_PICC = 0x0c, + NFC_TAGTYPE_JEWEL_PICC = 0x0d, + NFC_TAGTYPE_ISO15693_PICC = 0x0e, + NFC_TAGTYPE_UNKNOWN_TARGET = 0xff + }; + +class INFCTag : + public EventRequestReceiver<EventTagActionRead>, + public EventRequestReceiver<EventTagActionWrite>, + public EventRequestReceiver<EventTagActionTransceive>, + public EventRequestReceiver<EventTagActionFormat> +{ + public: + + + virtual ~INFCTag(); + virtual bool isConnected() = 0; + virtual nfcTagType getTagType() = 0; + virtual bool isNDEFSupport() = 0; + virtual long getNdefSize() = 0; + virtual std::vector<NFCTagProperties> getProperties() = 0; + virtual void readNdef(const EventTagActionReadPtr& event) = 0; + virtual void writeNdef(const EventTagActionWritePtr& event) = 0; + virtual void transceive(const EventTagActionTransceivePtr& event) = 0; + virtual void format(const EventTagActionFormatPtr& event) = 0; + protected: + INFCTag(); + virtual void OnRequestReceived(const EventTagActionReadPtr& event) = 0; + virtual void OnRequestReceived(const EventTagActionWritePtr& event) = 0; + virtual void OnRequestReceived(const EventTagActionTransceivePtr& event) = 0; + virtual void OnRequestReceived(const EventTagActionFormatPtr& event) = 0; + +}; + +typedef DPL::SharedPtr<INFCTag> INFCTagPtr; + +} +} + +#endif /* _ABSTRACT_LAYER_NFCTAG_H_ */ diff --git a/mobile_src/NFC/INFCTarget.cpp b/mobile_src/NFC/INFCTarget.cpp new file mode 100755 index 0000000..43d0e95 --- /dev/null +++ b/mobile_src/NFC/INFCTarget.cpp @@ -0,0 +1,33 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 "INFCTarget.h"
+
+namespace DeviceAPI {
+namespace NFC {
+
+using namespace WrtDeviceApis::Commons;
+
+INFCTarget::INFCTarget() : EventRequestReceiver<EventTargetActionSend>(ThreadEnum::NFC_THREAD) {
+}
+
+INFCTarget::~INFCTarget() {
+}
+
+}
+}
diff --git a/mobile_src/NFC/INFCTarget.h b/mobile_src/NFC/INFCTarget.h new file mode 100755 index 0000000..2c6feef --- /dev/null +++ b/mobile_src/NFC/INFCTarget.h @@ -0,0 +1,53 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _ABSTRACT_LAYER_NFCTARGET_H_ +#define _ABSTRACT_LAYER_NFCTARGET_H_ + +#include <dpl/shared_ptr.h> +#include <vector> +#include "EventTargetAction.h" + +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace NFC { + + +class INFCTarget : public EventRequestReceiver<EventTargetActionSend> +{ + public: + + + virtual ~INFCTarget(); + virtual bool isConnected() = 0; + virtual void setReceiveNDEFListener(const EventTargetActionReceiveEmitterPtr& event) = 0; + virtual void unsetReceiveNDEFListener() = 0; + virtual void sendNDEF(const EventTargetActionSendPtr& event) = 0; + protected: + INFCTarget(); + virtual void OnRequestReceived(const EventTargetActionSendPtr& event) = 0; +}; + +typedef DPL::SharedPtr<INFCTarget> INFCTargetPtr; + +} +} + +#endif /* _ABSTRACT_LAYER_NFCTARGET_H_ */ diff --git a/mobile_src/NFC/INdefMessage.h b/mobile_src/NFC/INdefMessage.h new file mode 100755 index 0000000..e607e01 --- /dev/null +++ b/mobile_src/NFC/INdefMessage.h @@ -0,0 +1,50 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _ABSTRACT_LAYER_INDEFMESSAGE_H_ +#define _ABSTRACT_LAYER_INDEFMESSAGE_H_ + +#include <dpl/shared_ptr.h> +#include <vector> +#include <PropertyBag.h> +#include "NdefRecordProperties.h" + +namespace DeviceAPI { +namespace NFC { + +class INdefMessage +{ + public: + + INdefMessage() {} + virtual ~INdefMessage() {} + virtual std::vector<unsigned char> toByte(std::vector<void *> &ndefRcords)= 0; + virtual void *makeNdefMessageHandle(std::vector<void *> &ndefRcords) = 0; + virtual std::vector<NdefRecordData> toNDEFRecords(const std::vector<unsigned char> &rawdata) = 0; + virtual std::vector<NdefRecordData> toNDEFRecords(void *message) = 0; + + Common::PropertyBag mLocalProperty; +}; + +typedef DPL::SharedPtr<INdefMessage> INdefMessagePtr; + +} +} + +#endif /* _ABSTRACT_LAYER_INDEFMESSAGE_H_ */ diff --git a/mobile_src/NFC/INdefRecord.h b/mobile_src/NFC/INdefRecord.h new file mode 100755 index 0000000..4c93269 --- /dev/null +++ b/mobile_src/NFC/INdefRecord.h @@ -0,0 +1,52 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _ABSTRACT_LAYER_INDEFRECORD_H_ +#define _ABSTRACT_LAYER_INDEFRECORD_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/Exception.h> +#include "NdefRecordProperties.h" + + +namespace DeviceAPI { +namespace NFC { +using namespace WrtDeviceApis::Commons; + +class INdefRecord +{ + public: + INdefRecord() {} + virtual ~INdefRecord() {} + virtual NdefRecordData getNDEFRecordData() = 0; + virtual void *getHandle() = 0; + virtual std::string getText() {ThrowMsg(NotFoundException, "Not Found text attribute");} + virtual std::string getLanguageCode() {ThrowMsg(NotFoundException, "Not Found languageCode attribute");} + virtual nfcTextEncodeUTF getEncoding() {ThrowMsg(NotFoundException, "Not Found encoding attribute");} + virtual std::string getUri( ) {ThrowMsg(NotFoundException, "Not Found uri attribute");} + virtual std::string getMimeType() {ThrowMsg(NotFoundException, "Not Found mimeType attribute");} + +}; + +typedef DPL::SharedPtr<INdefRecord> INdefRecordPtr; + +} +} + +#endif /* _ABSTRACT_LAYER_INDEFRECORD_H_ */ diff --git a/mobile_src/NFC/JSNFCAdapter.cpp b/mobile_src/NFC/JSNFCAdapter.cpp new file mode 100755 index 0000000..8f4cf70 --- /dev/null +++ b/mobile_src/NFC/JSNFCAdapter.cpp @@ -0,0 +1,470 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <string> +#include <CommonsJavaScript/Validator.h> +#include <Commons/Exception.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include <CommonsJavaScript/Utils.h> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <GlobalContextManager.h> +#include <ArgumentValidator.h> +#include <JSUtil.h> +#include <PlatformException.h> + +#include "JSNFCManager.h" +#include "JSNFCAdapter.h" +#include "JSNdefMessage.h" +#include "JSNdefRecord.h" +#include "NFCConverter.h" +#include "NFCStaticController.h" +#include "EventNFCChangedPrivateData.h" +#include "NFCAsyncCallbackManager.h" +#include "NFCListenerManager.h" +#include "NFCFactory.h" +#include "EventNFCChanged.h" +#include "plugin_config_impl.h" +#include <Logger.h> + +using namespace std; + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define TIZEN_NFCADAPTER_ATTRIBUTENAME "NFCAdapter" +#define TIZEN_NFCADAPTER_POWERED "powered" + +namespace DeviceAPI { +namespace NFC { + + JSClassDefinition JSNFCAdapter::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_NFCADAPTER_ATTRIBUTENAME, + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSNFCAdapter::m_property[] = +{ + //NFCAdapterProperties + {TIZEN_NFCADAPTER_POWERED, getProperty, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSNFCAdapter::m_function[] = { + {"setTagListener", JSNFCAdapter::setTagListener, kJSPropertyAttributeNone }, + {"unsetTagListener", JSNFCAdapter::unsetTagListener, kJSPropertyAttributeNone}, + {"setPeerListener", JSNFCAdapter::setPeerListener, kJSPropertyAttributeNone }, + {"unsetPeerListener", JSNFCAdapter::unsetPeerListener, kJSPropertyAttributeNone}, + {"getCachedMessage", JSNFCAdapter::getCachedMessage, kJSPropertyAttributeNone}, + {"setPowered", JSNFCAdapter::setPowered, kJSPropertyAttributeNone }, + { 0, 0, 0} +}; + +JSClassRef JSNFCAdapter::m_jsClassRef = JSClassCreate(JSNFCAdapter::getClassInfo()); + +void JSNFCAdapter::initialize(JSContextRef context, JSObjectRef object) +{ + LoggerD("entered. Nothing to do"); +} + +void JSNFCAdapter::finalize(JSObjectRef object) +{ + NFCAdapterPrivObject* priv = + static_cast<NFCAdapterPrivObject*>(JSObjectGetPrivate(object)); + delete priv; + JSObjectSetPrivate(object, NULL); +} + +JSObjectRef JSNFCAdapter::createJSObject(JSContextRef context, NFCManagerPrivObject *nfcManagerPriv) { + LoggerD("entered"); + + INFCAdapterPtr nfcAdapter(NFCFactory::getInstance().createNFCAdapterObject()); + NFCAdapterPrivObject *priv = new NFCAdapterPrivObject(context, nfcAdapter); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NFCTag object"); + } + + priv->copyAceCheckAccessFunction(nfcManagerPriv); + return JSObjectMake(context, getClassRef(), priv); +} + +const JSClassRef JSNFCAdapter::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNFCAdapter::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSNFCAdapter::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + + Try { + NFCConverter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCADAPTER_POWERED)) { + NFCAdapterPrivObject* privateObject = static_cast<NFCAdapterPrivObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + LoggerE("private object is null"); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + INFCAdapterPtr nfcAdapter(privateObject->getObject()); + return convert.toJSValueRef(nfcAdapter->getPowerState()); + } + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (UnsupportedException) { + LoggerE("UnsupportedException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCAdapter::setTagListener (JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + LoggerD("JSNFCAdapter::setTagListener Enter"); + + NFCAdapterPrivObject* privateObject = static_cast<NFCAdapterPrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_TAG_FUNCS); + + Try { + ArgumentValidator validator(context, argumentCount, arguments); + NFCChangedCallback callbacks; + NFCConverter nfcConverter(context); + if (validator.toObject(0)) + callbacks = nfcConverter.toNFCChangedCallback(arguments[0]); + + std::vector<std::string> filterValue = validator.toStringVector(1, true); + + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, callbacks.onattach, NULL, true, true); + JSCallbackManagerPtr detachedCallbackManager = JSCallbackManager::createObject(global_context, callbacks.ondetach, NULL); + TagFilterPtr tagFilter(new TagFilter()); + for (unsigned int i=0; i<filterValue.size(); i++) { + nfcTagType filter = nfcConverter.toNfcTagType(filterValue.at(i)); + + tagFilter->addTagTypeValue(filter); + LoggerD("tag_types.at(i): " << filterValue.at(i)); + } + + INFCAdapterPtr nfcAdapter(privateObject->getObject()); + + EventNFCChangedPrivateDataPtr privateData( + new EventNFCChangedPrivateData(callbackManager, + detachedCallbackManager) + ); + privateData->copyAceCheckAccessFunction(privateObject); + + EventNFCChangedEmitterPtr emitter(new EventNFCChangedEmitter); + emitter->setListener(&NFCStaticController::getInstance()); + emitter->setEventPrivateData(DPL::StaticPointerCast<EventNFCChanged::PrivateDataType>(privateData)); + + if (nfcAdapter->setTagListener(emitter, tagFilter) != 0) + Throw(WrtDeviceApis::Commons::UnknownException); + + NFCListenerCancellerPtr canceller = NFCListenerCancellerPtr(new NFCListenerCanceller(global_context, thisObject, static_cast<long>(ID_NFCADAPTER_TAG_LISTENER))); + IListenerItemPtr listenerItem = DPL::StaticPointerCast<IListenerItem>(canceller); + NFCListenerManagerSingleton::Instance().registerListener(listenerItem, global_context); + + return JSValueMakeUndefined(context); + } Catch (BasePlatformException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + return JSWebAPIErrorFactory::postException(context, exception, _rethrown_exception); + } Catch (ConversionException) { + LoggerE("JSNFCAdapter::setTagListener : ConversionException"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available"); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSNFCAdapter::setPeerListener (JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + LoggerD("JSNFCAdapter::setPeerListener Enter"); + + NFCAdapterPrivObject* privateObject = static_cast<NFCAdapterPrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_P2P_FUNCS); + + Try { + ArgumentValidator validator(context, argumentCount, arguments); + + NFCConverter nfcConverter(context); + NFCChangedCallback callbacks; + + if (validator.toObject(0)) + callbacks = nfcConverter.toNFCChangedCallback(arguments[0]); + + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, callbacks.onattach, NULL, true, true); + JSCallbackManagerPtr detachedCallbackManager = JSCallbackManager::createObject(global_context, callbacks.ondetach, NULL); + + INFCAdapterPtr nfcAdapter(privateObject->getObject()); + + EventNFCChangedPrivateDataPtr privateData( + new EventNFCChangedPrivateData(callbackManager, + detachedCallbackManager) + ); + + privateData->copyAceCheckAccessFunction(privateObject); + EventNFCChangedEmitterPtr emitter(new EventNFCChangedEmitter); + emitter->setListener(&NFCStaticController::getInstance()); + emitter->setEventPrivateData(DPL::StaticPointerCast<EventNFCChanged::PrivateDataType>(privateData)); + + if (nfcAdapter->setPeerListener(emitter) != 0) + Throw(WrtDeviceApis::Commons::UnknownException); + + NFCListenerCancellerPtr canceller = NFCListenerCancellerPtr(new NFCListenerCanceller(global_context, thisObject, static_cast<long>(ID_NFCADAPTER_PEER_LISTENER))); + IListenerItemPtr listenerItem = DPL::StaticPointerCast<IListenerItem>(canceller); + NFCListenerManagerSingleton::Instance().registerListener(listenerItem, global_context); + + return JSValueMakeUndefined(context); + } Catch (BasePlatformException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + return JSWebAPIErrorFactory::postException(context, exception, _rethrown_exception); + } Catch (ConversionException) { + LoggerE("JSNFCAdapter::setPeerListener : ConversionException"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available"); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} +JSValueRef JSNFCAdapter::unsetTagListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { + LoggerD("JSNFCAdapter::unsetNFCTagListener Enter"); + + NFCAdapterPrivObject* privateObject = static_cast<NFCAdapterPrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_TAG_FUNCS); + + Try { + INFCAdapterPtr nfcAdapter(privateObject->getObject()); + + nfcAdapter->unsetTagListener(); + + NFCListenerCancellerPtr canceller = NFCListenerCancellerPtr(new NFCListenerCanceller(privateObject->getContext(), thisObject, static_cast<long>(ID_NFCADAPTER_TAG_LISTENER))); + IListenerItemPtr listenerItem = DPL::StaticPointerCast<IListenerItem>(canceller); + NFCListenerManagerSingleton::Instance().unregisterListener(listenerItem); + + return JSValueMakeUndefined(context); + } Catch (NullPointerException) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available"); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSNFCAdapter::unsetPeerListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { + LoggerD("JSNFCAdapter::unsetPeerListener Enter"); + + NFCAdapterPrivObject* privateObject = static_cast<NFCAdapterPrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_P2P_FUNCS); + Try { + INFCAdapterPtr nfcAdapter( privateObject->getObject()); + + nfcAdapter->unsetPeerListener(); + + NFCListenerCancellerPtr canceller = NFCListenerCancellerPtr(new NFCListenerCanceller(privateObject->getContext(), thisObject, static_cast<long>(ID_NFCADAPTER_PEER_LISTENER))); + IListenerItemPtr listenerItem = DPL::StaticPointerCast<IListenerItem>(canceller); + NFCListenerManagerSingleton::Instance().unregisterListener(listenerItem); + + return JSValueMakeUndefined(context); + } Catch (NullPointerException) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available"); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSNFCAdapter::getCachedMessage (JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + LoggerD("JSNFCAdapter::getCachedMessage Enter"); + + NFCAdapterPrivObject* privateObject = static_cast<NFCAdapterPrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_COMMON_FUNCS); + + Try { + INFCAdapterPtr nfcAdapter(privateObject->getObject()); + void *cachedMessage = nfcAdapter->getCachedMessage(); + if (cachedMessage != NULL) { + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + return JSNdefMessage::createJSObject(global_context, cachedMessage); + } + return JSValueMakeNull(context); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available"); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSNFCAdapter::setPowered (JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + LoggerD("Enter"); + + NFCAdapterPrivObject* privateObject = static_cast<NFCAdapterPrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_ADMIN_FUNCS); + + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, NULL, NULL, true, true); + + Try { + ArgumentValidator validator(context, argumentCount, arguments); + + // state + bool state = validator.toBool(0); + // successCallback + if (validator.toFunction(1, true)) + callbackManager->setOnSuccess(arguments[1]); + // errorCallback + if (validator.toFunction(2, true)) + callbackManager->setOnError(arguments[2]); + + EventNFCChangedSetPoweredPtr event(new EventNFCChangedSetPowered(state)); + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManager) ); + event->setForAsynchronousCall(&NFCStaticController::getInstance()); + callbackManager->setObject(thisObject); + INFCAdapterPtr nfcAdapter(privateObject->getObject()); + nfcAdapter->setPowered(event); + NFCAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, global_context); + return JSValueMakeUndefined(context); + } Catch (BasePlatformException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + return JSWebAPIErrorFactory::postException(context, exception, _rethrown_exception); + } Catch (ConversionException) { + LoggerE("ConversionException"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available")); + return JSValueMakeUndefined(context); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException: " << _rethrown_exception.GetMessage()); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error")); + return JSValueMakeUndefined(context); +} + + +} +} diff --git a/mobile_src/NFC/JSNFCAdapter.h b/mobile_src/NFC/JSNFCAdapter.h new file mode 100755 index 0000000..bf71a72 --- /dev/null +++ b/mobile_src/NFC/JSNFCAdapter.h @@ -0,0 +1,126 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _JS_TIZEN_NFCADAPTER_H_ +#define _JS_TIZEN_NFCADAPTER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <Security.h> +#include "INFCAdapter.h" +#include "JSNFCManager.h" + +namespace DeviceAPI { +namespace NFC { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<INFCAdapterPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> NFCAdapterPrivObjectBase; +class NFCAdapterPrivObject : + public DeviceAPI::Common::SecurityAccessor, + public NFCAdapterPrivObjectBase +{ +public: + NFCAdapterPrivObject(JSContextRef context, INFCAdapterPtr adapter) : + DeviceAPI::Common::SecurityAccessor(), + NFCAdapterPrivObjectBase(context, adapter) + { + } + + virtual ~ NFCAdapterPrivObject() + { + } +}; + +class JSNFCAdapter +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, NFCManagerPrivObject *nfcManagerPriv); +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters for properties + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static JSValueRef setTagListener(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetTagListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef setPeerListener(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetPeerListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef getCachedMessage(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setPowered(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +} +} + +#endif /* _JS_TIZEN_NFCADAPTER_H_ */ diff --git a/mobile_src/NFC/JSNFCManager.cpp b/mobile_src/NFC/JSNFCManager.cpp new file mode 100755 index 0000000..1264ed0 --- /dev/null +++ b/mobile_src/NFC/JSNFCManager.cpp @@ -0,0 +1,260 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <Commons/Exception.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <GlobalContextManager.h> +#include <ArgumentValidator.h> +#include <PlatformException.h> + +#include "JSNFCManager.h" +#include "JSNFCAdapter.h" +#include "NFCConverter.h" +#include "NFCFactory.h" +#include "plugin_config_impl.h" +#include "NFCDefaultAdapter.h" +#include <Logger.h> + +using namespace std; + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define TIZEN_NFCMANAGER_ATTRIBUTENAME "NFCManager" + +#define TIZEN_NFCMANAGER_TNF_EMPTY "NFC_RECORD_TNF_EMPTY" +#define TIZEN_NFCMANAGER_TNF_WELL_KNOWN "NFC_RECORD_TNF_WELL_KNOWN" +#define TIZEN_NFCMANAGER_TNF_MIME_MEDIA "NFC_RECORD_TNF_MIME_MEDIA" +#define TIZEN_NFCMANAGER_TNF_URI "NFC_RECORD_TNF_URI" +#define TIZEN_NFCMANAGER_TNF_EXTERNAL_RTD "NFC_RECORD_TNF_EXTERNAL_RTD" +#define TIZEN_NFCMANAGER_TNF_UNKNOWN "NFC_RECORD_TNF_UNKNOWN" +#define TIZEN_NFCMANAGER_TNF_UNCHANGED "NFC_RECORD_TNF_UNCHANGED" + +namespace DeviceAPI { +namespace NFC { + + JSClassDefinition JSNFCManager::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_NFCMANAGER_ATTRIBUTENAME, + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSNFCManager::m_property[] = +{ + //NFCManagerProperties + {TIZEN_NFCMANAGER_TNF_EMPTY, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN_NFCMANAGER_TNF_WELL_KNOWN, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN_NFCMANAGER_TNF_MIME_MEDIA, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN_NFCMANAGER_TNF_URI, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN_NFCMANAGER_TNF_EXTERNAL_RTD, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN_NFCMANAGER_TNF_UNKNOWN, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN_NFCMANAGER_TNF_UNCHANGED, getProperty, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSNFCManager::m_function[] = { + {"getDefaultAdapter", JSNFCManager::getDefaultAdapter, kJSPropertyAttributeNone }, + {"setExclusiveMode", JSNFCManager::setExclusiveMode, kJSPropertyAttributeNone }, + { 0, 0, 0} +}; + +JSClassRef JSNFCManager::m_jsClassRef = JSClassCreate(JSNFCManager::getClassInfo()); + +void JSNFCManager::initialize(JSContextRef context, JSObjectRef object) +{ + LoggerD("entered"); + NFCManagerPrivObject* priv = static_cast<NFCManagerPrivObject*>(JSObjectGetPrivate(object)); + if (!priv) { + Try { + priv = new NFCManagerPrivObject(context); + if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) { + LoggerE("Object can't store private data."); + delete priv; + } + } Catch (UnsupportedException) { + LoggerE("UnsupportedException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + } +} + +void JSNFCManager::finalize(JSObjectRef object) +{ + LoggerD( "entered" ); + NFCManagerPrivObject *priv = static_cast<NFCManagerPrivObject*>(JSObjectGetPrivate(object)); + if (priv) { + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting NFC Manager object"); + delete priv; + } +} + + +const JSClassRef JSNFCManager::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNFCManager::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSNFCManager::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + + Try { + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCMANAGER_TNF_EMPTY)) { + return convert.toJSValueRef(NFC_TNF_EMPTY); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCMANAGER_TNF_WELL_KNOWN)) { + return convert.toJSValueRef(NFC_TNF_WELL_KNOWN); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCMANAGER_TNF_MIME_MEDIA)) { + return convert.toJSValueRef(NFC_TNF_MIME_MEDIA); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCMANAGER_TNF_URI)) { + return convert.toJSValueRef(NFC_TNF_URI); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCMANAGER_TNF_EXTERNAL_RTD)) { + return convert.toJSValueRef(NFC_TNF_EXTERNAL_RTD); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCMANAGER_TNF_UNKNOWN)) { + return convert.toJSValueRef(NFC_TNF_UNKNOWN); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCMANAGER_TNF_UNCHANGED)) { + return convert.toJSValueRef(NFC_TNF_UNCHANGED); + } + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (UnsupportedException) { + LoggerE("UnsupportedException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCManager::getDefaultAdapter (JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + LoggerD("Enter"); + + Try { + NFCManagerPrivObject* privateObject = static_cast<NFCManagerPrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("private object is null"); + ThrowMsg(UnsupportedException, "private object is null"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_COMMON_FUNCS); + + return JSNFCAdapter::createJSObject(GlobalContextManager::getInstance()->getGlobalContext(context), privateObject); + } Catch (UnsupportedException) { + LoggerE("UnsupportedException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, "Not Supported"); + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (InvalidArgumentException) { + LoggerE("InvalidArgumentException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Invalid Values"); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available"); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSNFCManager::setExclusiveMode (JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception) { + LoggerD("Enter"); + + Try { + NFCManagerPrivObject* privateObject = static_cast<NFCManagerPrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("private object is null"); + throw TypeMismatchException("private object is null"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_COMMON_FUNCS); + + ArgumentValidator validator(context, argumentCount, arguments); + // mode + bool mode = validator.toBool(0); + LoggerD("mode : " << mode); + + NFCDefaultAdapterSingleton::Instance().setExclusiveMode(mode); + return JSValueMakeUndefined(context); + } Catch (BasePlatformException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + return JSWebAPIErrorFactory::postException(context, exception, _rethrown_exception); + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +} +} diff --git a/mobile_src/NFC/JSNFCManager.h b/mobile_src/NFC/JSNFCManager.h new file mode 100755 index 0000000..c5082b3 --- /dev/null +++ b/mobile_src/NFC/JSNFCManager.h @@ -0,0 +1,107 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _JS_TIZEN_NFCMANAGER_H_ +#define _JS_TIZEN_NFCMANAGER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <Security.h> +#include "INFCAdapter.h" + +namespace DeviceAPI { +namespace NFC { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<void, WrtDeviceApis::CommonsJavaScript::NoOwnership> NFCManagerPrivObjectBase; +class NFCManagerPrivObject : + public DeviceAPI::Common::SecurityAccessor, + public NFCManagerPrivObjectBase +{ +public: + NFCManagerPrivObject(JSContextRef context) : + DeviceAPI::Common::SecurityAccessor(), + NFCManagerPrivObjectBase(context) + { + } + + virtual ~NFCManagerPrivObject() + { + } +}; + +class JSNFCManager +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters for properties + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + + static JSValueRef getDefaultAdapter(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setExclusiveMode(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef* exception); + +}; + +} +} + +#endif /* _JS_TIZEN_NFCMANAGER_H_ */ diff --git a/mobile_src/NFC/JSNFCTag.cpp b/mobile_src/NFC/JSNFCTag.cpp new file mode 100755 index 0000000..128eae6 --- /dev/null +++ b/mobile_src/NFC/JSNFCTag.cpp @@ -0,0 +1,420 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed 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 <CommonsJavaScript/Validator.h> +#include <Commons/Exception.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include <CommonsJavaScript/Utils.h> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <ArgumentValidator.h> +#include <GlobalContextManager.h> +#include <PlatformException.h> + +#include "JSNFCTag.h" +#include "JSNdefMessage.h" +#include "JSNFCManager.h" +#include "NFCConverter.h" +#include "ResponseDispatcher.h" +#include "NFCFactory.h" +#include "EventTagAction.h" +#include "NFCAsyncCallbackManager.h" +#include "plugin_config_impl.h" +#include <Logger.h> + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + + +#define TIZEN_NFCTAG_ATTRIBUTENAME "NFCTag" + +#define TIZEN_NFCTAG_TYPE "type" +#define TIZEN_NFCTAG_ISSUPPORTEDNDEF "isSupportedNDEF" +#define TIZEN_NFCTAG_NDEFSIZE "ndefSize" +#define TIZEN_NFCTAG_PROPERTIES "properties" +#define TIZEN_NFCTAG_ISCONNECTED "isConnected" + +namespace DeviceAPI { +namespace NFC { + + JSClassDefinition JSNFCTag::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_NFCTAG_ATTRIBUTENAME, + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSNFCTag::m_property[] = +{ + //NFCTagProperties + { TIZEN_NFCTAG_TYPE, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_NFCTAG_ISSUPPORTEDNDEF, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_NFCTAG_NDEFSIZE, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_NFCTAG_PROPERTIES, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_NFCTAG_ISCONNECTED, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSNFCTag::m_function[] = { + {"readNDEF", JSNFCTag::readNDEF, kJSPropertyAttributeNone}, + {"writeNDEF", JSNFCTag::writeNDEF, kJSPropertyAttributeNone}, + {"transceive", JSNFCTag::transceive, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +JSClassRef JSNFCTag::m_jsClassRef = JSClassCreate(JSNFCTag::getClassInfo()); + +JSObjectRef JSNFCTag::createJSObject(JSContextRef context, void *tagHandle, EventNFCChangedPrivateDataPtr eventNFCChangedPriv) { + LoggerD("entered"); + + INFCTagPtr nfcTag = NFCFactory::getInstance().createNFCTagObject(tagHandle); + + NFCTagPrivObject *priv = new NFCTagPrivObject(context, nfcTag); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NFCTag object"); + } + + priv->copyAceCheckAccessFunction(eventNFCChangedPriv.Get()); + return JSObjectMake(context, getClassRef(), priv); +} + +void JSNFCTag::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSNFCTag::finalize(JSObjectRef object) +{ + LoggerD( "entered" ); + NFCTagPrivObject *priv = static_cast<NFCTagPrivObject*>( JSObjectGetPrivate( object ) ) ; + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting NFCTag object"); + delete priv; +} + + +const JSClassRef JSNFCTag::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNFCTag::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSNFCTag::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + + Try { + NFCTagPrivObject* privateObject = static_cast<NFCTagPrivObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + INFCTagPtr nfcTag(privateObject->getObject()); + NFCConverter convert(context); + + LoggerD("propertyName : " << convert.toString(propertyName)); + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCTAG_TYPE)) { + return convert.toJSValueRef(convert.toNfcTagTypeString(nfcTag->getTagType())); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCTAG_ISSUPPORTEDNDEF)) { + return convert.toJSValueRef(nfcTag->isNDEFSupport()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCTAG_NDEFSIZE)) { + return convert.toJSValueRefLong(nfcTag->getNdefSize()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCTAG_PROPERTIES)) { + LoggerD("get Properties"); + return convert.toJSValueRef(nfcTag->getProperties()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCTAG_ISCONNECTED)) { + return convert.toJSValueRef(nfcTag->isConnected()); + } + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + +bool JSNFCTag::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSNFCTag::readNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("Entered "); + + NFCTagPrivObject* privateObject = static_cast<NFCTagPrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_TAG_FUNCS); + + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, NULL, NULL, true, true); + + Try { + ArgumentValidator validator(context, argumentCount, arguments); + + // successCallback + if (validator.toFunction(0)) + callbackManager->setOnSuccess(arguments[0]); + // errorCallback + if (validator.toFunction(1, true)) + callbackManager->setOnError(arguments[1]); + + EventTagActionReadPtr event(new EventTagActionRead()); + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + callbackManager->setObject(thisObject); + INFCTagPtr nfcTag(privateObject->getObject()); + nfcTag->readNdef(event); + NFCAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, global_context); + return JSValueMakeUndefined(context); + } Catch (BasePlatformException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + return JSWebAPIErrorFactory::postException(context, exception, _rethrown_exception); + } Catch (ConversionException) { + LoggerE("readNDEF : ConversionException"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (UnsupportedException) { + LoggerE("UnsupportedException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, "Not Support NDEF"); + } Catch (InvalidArgumentException) { + LoggerE("readNDEF InvalidArgumentException"); + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Invalid Values")); + return JSValueMakeUndefined(context); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available")); + return JSValueMakeUndefined(context); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error")); + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCTag::writeNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("Entered "); + + NFCTagPrivObject* privateObject = static_cast<NFCTagPrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_TAG_FUNCS); + + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, NULL, NULL, true, true); + Try { + ArgumentValidator validator(context, argumentCount, arguments); + + // ndefMessage + JSObjectRef ndefMessageObj = validator.toObject(0, JSNdefMessage::getClassRef(), false); + // successCallback + if (validator.toFunction(1, true)) + callbackManager->setOnSuccess(arguments[1]); + // errorCallback + if (validator.toFunction(2, true)) + callbackManager->setOnError(arguments[2]); + + EventTagActionWritePtr event(new EventTagActionWrite()); + void *messageHandle = NULL; + try { + NdefMessagePrivObject* ndefMessagePrivateObj = static_cast<NdefMessagePrivObject*>(JSObjectGetPrivate(ndefMessageObj)); + if (!ndefMessagePrivateObj) { + LogError("NDEF Message Private object is not set."); + ThrowMsg(ConversionException, "Private object is not set"); + } + INdefMessagePtr ndefMessage(ndefMessagePrivateObj->getObject()); + JSValueRef recordsValue = (ndefMessage->mLocalProperty).getProperty(global_context, TIZEN_NDEFMESSAGE_RECORDS); + NFCConverter convert(global_context); + std::vector<void *> records = convert.toVectorOfRecordHandles(recordsValue); + messageHandle = ndefMessage->makeNdefMessageHandle(records); + } catch (WrtDeviceApis::Commons::Exception& err) { + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + ThrowMsg(InvalidArgumentException, "Invalid NDEF Message"); + } + if (messageHandle == NULL) + ThrowMsg(InvalidArgumentException, "Invalid NDEF Message"); + + event->writeNdef(messageHandle); + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManager)); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + callbackManager->setObject(thisObject); + INFCTagPtr nfcTag(privateObject->getObject()); + nfcTag->writeNdef(event); + NFCAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, global_context); + return JSValueMakeUndefined(context); + } Catch (BasePlatformException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + return JSWebAPIErrorFactory::postException(context, exception, _rethrown_exception); + } Catch (ConversionException) { + LoggerE("writeNDEF : ConversionException"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (UnsupportedException) { + LoggerE("UnsupportedException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, "Not Support NDEF"); + } Catch (InvalidArgumentException) { + LoggerE("writeNDEF InvalidArgumentException"); + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, _rethrown_exception.GetMessage())); + return JSValueMakeUndefined(context); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available")); + return JSValueMakeUndefined(context); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error")); + return JSValueMakeUndefined(context); +} + +JSValueRef JSNFCTag::transceive(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("Entered "); + + NFCTagPrivObject* privateObject = static_cast<NFCTagPrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_TAG_FUNCS); + + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, NULL, NULL, true, true); + Try { + ArgumentValidator validator(context, argumentCount, arguments); + + // ndefMessage + JSObjectRef dataObj = validator.toArrayObject(0); + + // successCallback + if (validator.toFunction(1)) + callbackManager->setOnSuccess(arguments[1]); + // errorCallback + if (validator.toFunction(2, true)) + callbackManager->setOnError(arguments[2]); + + EventTagActionTransceivePtr event(new EventTagActionTransceive()); + std::vector<unsigned char> data; + if (dataObj) { + NFCConverter convert(context); + data= convert.toVectorOfOctets(arguments[0]); + } + event->transceive(data); + event->setPrivateData( DPL::StaticPointerCast<IEventPrivateData>(callbackManager) ); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + callbackManager->setObject(thisObject); + INFCTagPtr nfcTag(privateObject->getObject()); + nfcTag->transceive(event); + NFCAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, global_context); + return JSValueMakeUndefined(context); + } Catch (BasePlatformException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + return JSWebAPIErrorFactory::postException(context, exception, _rethrown_exception); + } Catch (ConversionException) { + LoggerE("transceive : ConversionException"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (InvalidArgumentException) { + LoggerE("transceive InvalidArgumentException"); + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Invalid Values")); + return JSValueMakeUndefined(context); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available")); + return JSValueMakeUndefined(context); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error")); + return JSValueMakeUndefined(context); +} + + +} +} diff --git a/mobile_src/NFC/JSNFCTag.h b/mobile_src/NFC/JSNFCTag.h new file mode 100755 index 0000000..393693a --- /dev/null +++ b/mobile_src/NFC/JSNFCTag.h @@ -0,0 +1,131 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _JS_TIZEN_NFCTAG_H_ +#define _JS_TIZEN_NFCTAG_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <Security.h> +#include "INFCTag.h" +#include "EventNFCChangedPrivateData.h" + + +namespace DeviceAPI { +namespace NFC { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<INFCTagPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> NFCTagPrivObjectBase; +class NFCTagPrivObject : + public DeviceAPI::Common::SecurityAccessor, + public NFCTagPrivObjectBase +{ +public: + NFCTagPrivObject(JSContextRef context, INFCTagPtr nfcTag) : + DeviceAPI::Common::SecurityAccessor(), + NFCTagPrivObjectBase(context, nfcTag) + { + } + + virtual ~NFCTagPrivObject() + { + } +}; + +class JSNFCTag +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, void *tagHandle, EventNFCChangedPrivateDataPtr eventNFCChangedPriv); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters for properties + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + static JSValueRef readNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef writeNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef transceive(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + +}; + +} +} + +#endif /* _JS_TIZEN_NFCTAG_H_ */ diff --git a/mobile_src/NFC/JSNFCTarget.cpp b/mobile_src/NFC/JSNFCTarget.cpp new file mode 100755 index 0000000..b00b6c4 --- /dev/null +++ b/mobile_src/NFC/JSNFCTarget.cpp @@ -0,0 +1,358 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <CommonsJavaScript/Validator.h> +#include <Commons/Exception.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include <CommonsJavaScript/Utils.h> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <ArgumentValidator.h> +#include <GlobalContextManager.h> +#include <PlatformException.h> + +#include "JSNFCTarget.h" +#include "JSNFCManager.h" +#include "JSNdefMessage.h" +#include "NFCConverter.h" +#include "ResponseDispatcher.h" +#include "NFCAsyncCallbackManager.h" +#include "NFCListenerManager.h" +#include "NFCFactory.h" +#include "EventTargetAction.h" +#include "plugin_config_impl.h" +#include <Logger.h> + + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + + +#define TIZEN_NFCTARGET_ATTRIBUTENAME "NFCTarget" + +#define TIZEN_NFCTARGET_ISCONNECTED "isConnected" + +namespace DeviceAPI { +namespace NFC { + + JSClassDefinition JSNFCTarget::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_NFCTARGET_ATTRIBUTENAME, + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSNFCTarget::m_property[] = +{ + //NFCTargetProperties + { TIZEN_NFCTARGET_ISCONNECTED, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSNFCTarget::m_function[] = { + {"setReceiveNDEFListener", JSNFCTarget::setReceiveNDEFListener, kJSPropertyAttributeNone}, + {"unsetReceiveNDEFListener", JSNFCTarget::unsetReceiveNDEFListener, kJSPropertyAttributeNone}, + {"sendNDEF", JSNFCTarget::sendNDEF, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +JSClassRef JSNFCTarget::m_jsClassRef = JSClassCreate(JSNFCTarget::getClassInfo()); + +JSObjectRef JSNFCTarget::createJSObject(JSContextRef context, void *tagHandle, EventNFCChangedPrivateDataPtr eventNFCChangedPriv) { + LoggerD("entered"); + + INFCTargetPtr nfcTarget = NFCFactory::getInstance().createNFCTargetObject(tagHandle); + + NFCTargetPrivObject *priv = new NFCTargetPrivObject(context, nfcTarget); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NFCTarget object"); + } + + priv->copyAceCheckAccessFunction(eventNFCChangedPriv.Get()); + return JSObjectMake(context, getClassRef(), priv); +} + +void JSNFCTarget::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSNFCTarget::finalize(JSObjectRef object) +{ + LoggerD( "entered" ); + NFCTargetPrivObject *priv = static_cast<NFCTargetPrivObject*>( JSObjectGetPrivate( object ) ) ; + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting timezone object"); + delete priv; +} + + +const JSClassRef JSNFCTarget::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNFCTarget::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSNFCTarget::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + + Try { + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NFCTARGET_ISCONNECTED)) { + NFCTargetPrivObject* privateObject = static_cast<NFCTargetPrivObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + INFCTargetPtr nfcTarget(privateObject->getObject()); + NFCConverter convert(context); + return convert.toJSValueRef(nfcTarget->isConnected()); + } + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + +bool JSNFCTarget::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSNFCTarget::setReceiveNDEFListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("Entered "); + + NFCTargetPrivObject* privateObject = static_cast<NFCTargetPrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_P2P_FUNCS); + + Try { + ArgumentValidator validator(context, argumentCount, arguments); + JSValueRef onSuccessForCbm = NULL; + // NDEFMessageReadCallback + if (validator.toFunction(0)) + onSuccessForCbm = arguments[0]; + + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, onSuccessForCbm, NULL, true, true); + + EventTargetActionReceiveEmitterPtr emitter(new EventTargetActionReceiveEmitter); + emitter->setListener(&NFCResponseDispatcher::getInstance()); + emitter->setEventPrivateData(DPL::StaticPointerCast<EventTargetActionReceive::PrivateDataType>(callbackManager)); + INFCTargetPtr nfcTarget(privateObject->getObject()); + nfcTarget->setReceiveNDEFListener(emitter); + + NFCListenerCancellerPtr canceller = NFCListenerCancellerPtr(new NFCListenerCanceller(global_context, thisObject, static_cast<long>(ID_NFCPEER_RECEIVENDEF_LISTENER))); + IListenerItemPtr listenerItem = DPL::StaticPointerCast<IListenerItem>(canceller); + NFCListenerManagerSingleton::Instance().registerListener(listenerItem, global_context); + + return JSValueMakeUndefined(context); + } Catch (BasePlatformException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + return JSWebAPIErrorFactory::postException(context, exception, _rethrown_exception); + } Catch (ConversionException) { + LoggerE("setReceiveNDEFListener : ConversionException"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available"); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSNFCTarget::unsetReceiveNDEFListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("Entered "); + Try { + NFCTargetPrivObject* privateObject = static_cast<NFCTargetPrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_P2P_FUNCS); + + INFCTargetPtr nfcTarget(privateObject->getObject()); + nfcTarget->unsetReceiveNDEFListener(); + + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + NFCListenerCancellerPtr canceller = NFCListenerCancellerPtr(new NFCListenerCanceller(global_context, thisObject, static_cast<long>(ID_NFCPEER_RECEIVENDEF_LISTENER))); + IListenerItemPtr listenerItem = DPL::StaticPointerCast<IListenerItem>(canceller); + NFCListenerManagerSingleton::Instance().unregisterListener(listenerItem); + + return JSValueMakeUndefined(context); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available"); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSNFCTarget::sendNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("Entered "); + + NFCTargetPrivObject* privateObject = static_cast<NFCTargetPrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TIZEN_CHECK_ACCESS(context, exception, privateObject, + NFC_FUNCTION_API_P2P_FUNCS); + + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(global_context, NULL, NULL, true, true); + Try { + ArgumentValidator validator(context, argumentCount, arguments); + + // ndefMessage + JSObjectRef ndefMessageObj = validator.toObject(0, JSNdefMessage::getClassRef()); + // successCallback + if (validator.toFunction(1, true)) + callbackManager->setOnSuccess(arguments[1]); + // errorCallback + if (validator.toFunction(2, true)) + callbackManager->setOnError(arguments[2]); + + void *messageHandle = NULL; + try { + NdefMessagePrivObject* ndefMessagePrivateObj = static_cast<NdefMessagePrivObject*>(JSObjectGetPrivate(ndefMessageObj)); + if (!ndefMessagePrivateObj) { + LogError("NDEF Message Private object is not set."); + ThrowMsg(ConversionException, "Private object is not set"); + } + INdefMessagePtr ndefMessage(ndefMessagePrivateObj->getObject()); + JSValueRef recordsValue = (ndefMessage->mLocalProperty).getProperty(global_context, TIZEN_NDEFMESSAGE_RECORDS); + NFCConverter convert(global_context); + std::vector<void *> records = convert.toVectorOfRecordHandles(recordsValue); + messageHandle = ndefMessage->makeNdefMessageHandle(records); + } catch (WrtDeviceApis::Commons::Exception& err) { + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + ThrowMsg(InvalidArgumentException, "Invalid NDEF Message"); + } + if (messageHandle == NULL) + ThrowMsg(InvalidArgumentException, "Invalid NDEF Message"); + + EventTargetActionSendPtr event(new EventTargetActionSend(messageHandle)); + callbackManager->setObject(thisObject); + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManager)); + event->setForAsynchronousCall(&NFCResponseDispatcher::getInstance()); + INFCTargetPtr nfcTarget(privateObject->getObject()); + nfcTarget->sendNDEF(event); + NFCAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, global_context); + return JSValueMakeUndefined(context); + } Catch (BasePlatformException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + return JSWebAPIErrorFactory::postException(context, exception, _rethrown_exception); + } Catch (ConversionException) { + LoggerE("sendNDEF : ConversionException"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (InvalidArgumentException) { + LoggerE("sendNDEF InvalidArgumentException"); + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, _rethrown_exception.GetMessage())); + return JSValueMakeUndefined(context); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "Service Not Available")); + return JSValueMakeUndefined(context); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + callbackManager->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error")); + return JSValueMakeUndefined(context); +} + +} +} diff --git a/mobile_src/NFC/JSNFCTarget.h b/mobile_src/NFC/JSNFCTarget.h new file mode 100755 index 0000000..7f3d17d --- /dev/null +++ b/mobile_src/NFC/JSNFCTarget.h @@ -0,0 +1,129 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _JS_TIZEN_NFCTARGET_H_ +#define _JS_TIZEN_NFCTARGET_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <Security.h> +#include "EventNFCChangedPrivateData.h" +#include "INFCTarget.h" + +namespace DeviceAPI { +namespace NFC { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<INFCTargetPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> NFCTargetPrivObjectBase; +class NFCTargetPrivObject : + public DeviceAPI::Common::SecurityAccessor, + public NFCTargetPrivObjectBase +{ +public: + NFCTargetPrivObject(JSContextRef context, INFCTargetPtr nfcTarget) : + DeviceAPI::Common::SecurityAccessor(), + NFCTargetPrivObjectBase(context, nfcTarget) + { + } + + virtual ~NFCTargetPrivObject() + { + } +}; + +class JSNFCTarget +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, void *tagHandle, EventNFCChangedPrivateDataPtr eventNFCChangedPriv); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * Getters and setters for properties + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + static JSValueRef setReceiveNDEFListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetReceiveNDEFListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef sendNDEF(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +} +} + +#endif /* _JS_TIZEN_NFCTARGET_H_ */ diff --git a/mobile_src/NFC/JSNdefMessage.cpp b/mobile_src/NFC/JSNdefMessage.cpp new file mode 100755 index 0000000..9020dd0 --- /dev/null +++ b/mobile_src/NFC/JSNdefMessage.cpp @@ -0,0 +1,390 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 "JSNdefMessage.h" +#include "JSNdefRecord.h" +#include "JSNdefRecordText.h" +#include "JSNdefRecordURI.h" +#include "JSNdefRecordMedia.h" +#include "NFCConverter.h" +#include <GlobalContextManager.h> +#include <ArgumentValidator.h> +#include <Commons/Exception.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSUtils.h> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <PlatformException.h> + +#include "NFCFactory.h" +#include <Logger.h> + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace NFC { + + JSClassDefinition JSNdefMessage::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_NDEFMESSAGE_ATTRIBUTENAME, + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSNdefMessage::m_property[] = +{ + //NdefMessageProperties + { TIZEN_NDEFMESSAGE_RECORDCOUNT, getProperty, + NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_NDEFMESSAGE_RECORDS, getProperty, + setProperty, kJSPropertyAttributeNone}, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSNdefMessage::m_function[] = { + {"toByte", JSNdefMessage::toByte, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +JSClassRef JSNdefMessage::m_jsClassRef = JSClassCreate(JSNdefMessage::getClassInfo()); + +JSObjectRef JSNdefMessage::createJSObject(JSContextRef context, void *messageHandle) { + LoggerD("entered"); + + INdefMessagePtr ndefMessage = NFCFactory::getInstance().createNDEFMessageObject(); + std::vector<NdefRecordData> records = ndefMessage->toNDEFRecords(messageHandle); + JSValueRef recordArray = NULL; + if (records.size() > 0) { + JSValueRef valueArray[records.size()]; + NFCConverter convert(context); + for (std::size_t i = 0; i < records.size(); ++i) { + valueArray[i] = convert.toJSValueRef(records[i]); + } + recordArray = JSCreateArrayObject(context, records.size(), valueArray); + } else + recordArray = JSCreateArrayObject(context, 0, NULL); + return createJSObject(context, ndefMessage, recordArray); +} + +/* +JSObjectRef JSNdefMessage::createJSObject(JSContextRef context, std::vector<void *> ndefRcords) { + LoggerD("entered"); + + INdefMessagePtr ndefMessage = NFCFactory::getInstance().createNDEFMessageObject(ndefRcords); + return createJSObject(context, ndefMessage); +}*/ + +JSObjectRef JSNdefMessage::createJSObject(JSContextRef context, std::vector<unsigned char> rawdata) { + LoggerD("entered"); + + INdefMessagePtr ndefMessage = NFCFactory::getInstance().createNDEFMessageObject(); + NFCConverter convert(context); + std::vector<NdefRecordData> records = ndefMessage->toNDEFRecords(rawdata); + JSValueRef recordArray = NULL; + if (records.size() > 0) { + JSValueRef valueArray[records.size()]; + NFCConverter convert(context); + for (std::size_t i = 0; i < records.size(); ++i) { + valueArray[i] = convert.toJSValueRef(records[i]); + } + recordArray = JSCreateArrayObject(context, records.size(), valueArray); + } else + recordArray = JSCreateArrayObject(context, 0, NULL); + return createJSObject(context, ndefMessage, recordArray); +} + +JSObjectRef JSNdefMessage::createJSObject(JSContextRef context, INdefMessagePtr message, JSValueRef recordArray) { + LoggerD("entered"); + + if ((message->mLocalProperty).setArrayProperty(context, TIZEN_NDEFMESSAGE_RECORDS, recordArray) == false) + LoggerE("Can't set property"); + + NdefMessagePrivObject *priv = new NdefMessagePrivObject(context, message); + JSObjectRef obj = JSObjectMake(context, getClassRef(), priv); + return obj; +} +void JSNdefMessage::initialize(JSContextRef context, JSObjectRef object) +{ + LoggerD("entered"); +} + +void JSNdefMessage::finalize(JSObjectRef object) +{ + LoggerD( "entered" ); + NdefMessagePrivObject *priv = static_cast<NdefMessagePrivObject*>(JSObjectGetPrivate(object)); + if (priv) { + INdefMessagePtr ndefMessage(priv->getObject()); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting NdefMessage object"); + delete priv; + } +} + + +const JSClassRef JSNdefMessage::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNdefMessage::getClassInfo() +{ + return &m_classInfo; +} + +JSObjectRef JSNdefMessage::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + LoggerD("entered"); + + ArgumentValidator validator(ctx, argumentCount, arguments); + JSObjectRef objArg = NULL; + try { + if (argumentCount > 0) + objArg = validator.toArrayObject(0); + } catch(...) { + LoggerE("First parameter is not an array"); + } + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(ctx); + + JSObjectRef result = NULL; + Try { + if (objArg != NULL) { + NFCConverter convert(global_context); + unsigned int arrayLen = JSGetArrayLength(ctx, objArg); + if (arrayLen > 0) { + bool isRecordArray = false; + bool isByteArray = false; + JSValueRef valueArray[arrayLen]; + + for (unsigned int i = 0; i < arrayLen; ++i) { + valueArray[i] = JSGetArrayElement(ctx, objArg, i); + bool bNdefRecord = convert.isNdefRecord(valueArray[i]); + LoggerD("isNdefRecord : " << bNdefRecord); + if (bNdefRecord) + isRecordArray = true; + else + isByteArray = true; + if (isRecordArray && isByteArray) + break; + } + if (!isRecordArray && isByteArray) { + result = createJSObject(global_context, convert.toVectorOfOctets(arguments[0])); + } else { + INdefMessagePtr ndefMessage = NFCFactory::getInstance().createNDEFMessageObject(); + JSValueRef recordArray = JSCreateArrayObject(global_context, arrayLen, valueArray); + result = createJSObject(global_context, ndefMessage, recordArray); + } + } + } + } Catch(WrtDeviceApis::Commons::Exception) { + LoggerE(_rethrown_exception.GetClassName() << ": " << _rethrown_exception.GetMessage()); + } Catch(BasePlatformException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + } + + if (result == NULL) + result = createJSObject(global_context); + + if (result) { + JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor"); + JSObjectSetProperty(global_context, result, ctorName, constructor, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + JSStringRelease(ctorName); + } + return result; + +} + +JSValueRef JSNdefMessage::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + + Try { + NdefMessagePrivObject* privateObject = static_cast<NdefMessagePrivObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + INdefMessagePtr ndefMessage(privateObject->getObject()); + + NFCConverter convert(context); + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + JSValueRef recordsValue = (ndefMessage->mLocalProperty).getProperty(global_context, TIZEN_NDEFMESSAGE_RECORDS); + + LoggerD("propertyName : " << convert.toString(propertyName)); + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFMESSAGE_RECORDCOUNT)) { + if (JSValueIsNull(global_context, recordsValue) || JSValueIsUndefined(global_context, recordsValue)) { + ThrowMsg(ConversionException, + "NdefRecordArray is JS null or JS undefined."); + } + + if (!JSIsArrayValue(global_context, recordsValue)) { + ThrowMsg(ConversionException, "Argument is not an JS array."); + } + + JSObjectRef obj = convert.toJSObjectRef(recordsValue); + + if (!obj) { + LoggerE("Object is null"); + ThrowMsg(ConversionException, "Object is null"); + } + long count = 0; + for (std::size_t i = 0; i < JSGetArrayLength(global_context, obj); ++i) { + JSValueRef element = JSGetArrayElement(global_context, obj, i); + if (convert.isNdefRecord(element)) + count++; + } + return convert.toJSValueRefLong(count); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFMESSAGE_RECORDS)) { + return recordsValue; + } + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + +bool JSNdefMessage::setProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + LoggerD("Enter"); + + Try { + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFMESSAGE_RECORDS)) { + NdefMessagePrivObject* privateObject = static_cast<NdefMessagePrivObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + NFCConverter convert(context); + + if (JSValueIsNull(context, value) || JSValueIsUndefined(context, value) || !JSIsArrayValue(context, value)) { + LoggerE("value is invald."); + ThrowMsg(ConversionException, "value is invald."); + } + INdefMessagePtr ndefMessage(privateObject->getObject()); + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + + JSObjectRef obj = convert.toJSObjectRef(value); + + if (!obj) { + LoggerE("Object is null"); + ThrowMsg(ConversionException, "Object is null"); + } + unsigned int arrayLen = JSGetArrayLength(global_context, obj); + JSValueRef valueArray[arrayLen]; + for (std::size_t i = 0; i < arrayLen; ++i) { + JSValueRef element = JSGetArrayElement(global_context, obj, i); + valueArray[i] = element; + } + JSValueRef recordsArray = JSCreateArrayObject(global_context, arrayLen, valueArray); + return (ndefMessage->mLocalProperty).setArrayProperty(global_context, TIZEN_NDEFMESSAGE_RECORDS, recordsArray); + } + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (InvalidArgumentException) { + LoggerE("InvalidArgumentException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return false; + +} + +JSValueRef JSNdefMessage::toByte(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("Entered "); + Try { + NdefMessagePrivObject* privateObject = static_cast<NdefMessagePrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + INdefMessagePtr ndefMessage(privateObject->getObject()); + NFCConverter convert(context); + + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(context); + std::vector<void *> records; + try { + JSValueRef recordsValue = (ndefMessage->mLocalProperty).getProperty(global_context, TIZEN_NDEFMESSAGE_RECORDS); + records = convert.toVectorOfRecordHandles(recordsValue); + } catch (WrtDeviceApis::Commons::Exception& err) { + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + ThrowMsg(InvalidArgumentException, "Invalid NDEF Message"); + } + return convert.toJSValueRef(ndefMessage->toByte(records)); + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(InvalidArgumentException) { + LoggerE("InvalidArgumentException: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } +} + +} +} diff --git a/mobile_src/NFC/JSNdefMessage.h b/mobile_src/NFC/JSNdefMessage.h new file mode 100755 index 0000000..5062d60 --- /dev/null +++ b/mobile_src/NFC/JSNdefMessage.h @@ -0,0 +1,100 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _JS_TIZEN_NDEFMESSAGE_H_ +#define _JS_TIZEN_NDEFMESSAGE_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "INdefMessage.h" + +#define TIZEN_NDEFMESSAGE_ATTRIBUTENAME "NDEFMessage" +#define TIZEN_NDEFMESSAGE_RECORDCOUNT "recordCount" +#define TIZEN_NDEFMESSAGE_RECORDS "records" + +namespace DeviceAPI { +namespace NFC { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<INdefMessagePtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> NdefMessagePrivObject; + +class JSNdefMessage +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, void *messageHandle = NULL); + static JSObjectRef createJSObject(JSContextRef context, INdefMessagePtr message, JSValueRef recordArray); + static JSObjectRef createJSObject(JSContextRef context, std::vector<unsigned char> rawdata); + + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + + /** + * Getters and setters for properties + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + static bool setProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + static JSValueRef toByte(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +} +} + +#endif /* _JS_TIZEN_NDEFMESSAGE_H_ */ diff --git a/mobile_src/NFC/JSNdefRecord.cpp b/mobile_src/NFC/JSNdefRecord.cpp new file mode 100755 index 0000000..3a1abde --- /dev/null +++ b/mobile_src/NFC/JSNdefRecord.cpp @@ -0,0 +1,225 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <memory> +#include <string> +#include <CommonsJavaScript/JSUtils.h> + +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <ArgumentValidator.h> +#include <GlobalContextManager.h> +#include <PlatformException.h> +#include "NFCFactory.h" + +#include "JSNdefRecord.h" +#include "NFCConverter.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define TIZEN_NDEFRECORD_TNF "tnf" +#define TIZEN_NDEFRECORD_TYPE "type" +#define TIZEN_NDEFRECORD_ID "id" +#define TIZEN_NDEFRECORD_PAYLOAD "payload" + +JSClassDefinition JSNdefRecord::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "NDEFRecord", + 0, + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSNdefRecord::m_property[] = +{ + {TIZEN_NDEFRECORD_TNF, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN_NDEFRECORD_TYPE, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN_NDEFRECORD_ID, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN_NDEFRECORD_PAYLOAD, getProperty, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSNdefRecord::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNdefRecord::getClassInfo() { + return &m_classInfo; +} + +JSClassRef JSNdefRecord::m_jsClassRef = JSClassCreate(JSNdefRecord::getClassInfo()); + + +JSObjectRef JSNdefRecord::createJSObject(JSContextRef context) { + LoggerD("Entered"); + return createJSObject(context, NFCFactory::getInstance().createNDEFRecordObject()); + +} + +JSObjectRef JSNdefRecord::createJSObject(JSContextRef context, const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload, bool isValid) { + return createJSObject(context, NFCFactory::getInstance().createNDEFRecordObject(ndefRecordProperties, payload, isValid)); +} + +JSObjectRef JSNdefRecord::createJSObject(JSContextRef context, std::vector<unsigned char> rawdata) { + return createJSObject(context, NFCFactory::getInstance().createNDEFRecordObject(rawdata)); +} + +JSObjectRef JSNdefRecord::createJSObject(JSContextRef context, INdefRecordPtr ndefRecord) { + NdefRecordPrivObject *priv = new NdefRecordPrivObject(context, ndefRecord); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new a NdefRecord object"); + } + + JSObjectRef obj = JSObjectMake(context, getClassRef(), priv); + return obj; +} + +void JSNdefRecord::initialize(JSContextRef context, JSObjectRef object) { + LoggerD("entered"); +} + +void JSNdefRecord::finalize(JSObjectRef object) { + LoggerD("Entered"); + NdefRecordPrivObject* priv = static_cast<NdefRecordPrivObject*>(JSObjectGetPrivate(object)); + if (priv) { + INdefRecordPtr ndefRecord = priv->getObject(); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting ndefrecord object"); + delete priv; + } else + LoggerD("priv null"); +} + +JSObjectRef JSNdefRecord::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + LoggerD("entered"); + + JSObjectRef result = NULL; + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(ctx); + Try { + ArgumentValidator validator(ctx, argumentCount, arguments); + NFCConverter convert(ctx); + + if (argumentCount == 0) { + throw TypeMismatchException("Argument count is 0."); + } else if (argumentCount < 3) { + if (!JSIsArrayValue(ctx, arguments[0])) + throw TypeMismatchException("Raw data is not array."); + else + result = createJSObject(global_context, convert.toVectorOfOctets(arguments[0])); + } else { + NdefRecordProperties prop; + bool isValid = true; + prop.tnf = static_cast<short>(validator.toNumber(0)); + if (!JSIsArrayValue(ctx, arguments[1])) + isValid = false; + else + prop.typeName = convert.toVectorOfOctets(arguments[1]); + std::vector<unsigned char> payload; + if (!JSIsArrayValue(ctx, arguments[2])) + isValid = false; + else + payload = convert.toVectorOfOctets(arguments[2]); + if ((argumentCount > 3) && JSIsArrayValue(ctx, arguments[3])) + prop.id = convert.toVectorOfOctets(arguments[3]); + result = createJSObject(global_context, prop, payload, isValid); + } + } Catch (BasePlatformException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + } Catch(ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (InvalidArgumentException) { + LoggerE("InvalidArgumentException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + if (result == NULL) + result = createJSObject(global_context); + + JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor"); + JSObjectSetProperty(global_context, result, ctorName, constructor, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + JSStringRelease(ctorName); + return result; +} + +JSValueRef JSNdefRecord::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) { + LoggerD("Enter"); + + Try { + NFCConverter convert(context); + NdefRecordPrivObject *priv = static_cast<NdefRecordPrivObject*>(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object not set."); + } + INdefRecordPtr ndefRecord = priv->getObject(); + NdefRecordData recordData = ndefRecord->getNDEFRecordData(); + LoggerD("propertyName : " << convert.toString(propertyName)); + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFRECORD_TNF)) + return convert.toJSValueRef(recordData.properties.tnf); + else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFRECORD_TYPE)) + return convert.toJSValueRef(recordData.properties.typeName); + else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFRECORD_ID)) + return convert.toJSValueRef(recordData.properties.id); + else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFRECORD_PAYLOAD)) + return convert.toJSValueRef(recordData.payload); + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + +} //NFC +} //DeviceAPI + diff --git a/mobile_src/NFC/JSNdefRecord.h b/mobile_src/NFC/JSNdefRecord.h new file mode 100755 index 0000000..a78a47b --- /dev/null +++ b/mobile_src/NFC/JSNdefRecord.h @@ -0,0 +1,83 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_TIZEN_JS_NDEFRECORD_H_ +#define WRTPLUGINS_TIZEN_JS_NDEFRECORD_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "INdefRecord.h" + +namespace DeviceAPI { +namespace NFC { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<INdefRecordPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> NdefRecordPrivObject; + +class JSNdefRecord +{ +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context); + static JSObjectRef createJSObject(JSContextRef context, + const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload, bool isValid = true); + static JSObjectRef createJSObject(JSContextRef context, + std::vector<unsigned char> rawdata); + static JSObjectRef createJSObject(JSContextRef context, INdefRecordPtr ndefRecord); + + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + +}; + +} //NFC +} //DeviceAPI + +#endif + diff --git a/mobile_src/NFC/JSNdefRecordMedia.cpp b/mobile_src/NFC/JSNdefRecordMedia.cpp new file mode 100755 index 0000000..6bfcc5b --- /dev/null +++ b/mobile_src/NFC/JSNdefRecordMedia.cpp @@ -0,0 +1,174 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <memory> +#include <string> +#include <CommonsJavaScript/JSUtils.h> + +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <ArgumentValidator.h> +#include <GlobalContextManager.h> +#include <PlatformException.h> + +#include "NFCFactory.h" +#include "JSNdefRecordMedia.h" +#include "NFCConverter.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define TIZEN_NDEFRECORD_MEDIA_MIMETYPE "mimeType" + +JSClassDefinition JSNdefRecordMedia::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "NDEFRecordMedia", + JSNdefRecord::getClassRef(), + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSNdefRecordMedia::m_property[] = +{ + {TIZEN_NDEFRECORD_MEDIA_MIMETYPE, getProperty, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSNdefRecordMedia::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNdefRecordMedia::getClassInfo() { + return &m_classInfo; +} + +JSClassRef JSNdefRecordMedia::m_jsClassRef = JSClassCreate(JSNdefRecordMedia::getClassInfo()); + +JSObjectRef JSNdefRecordMedia::createJSObject(JSContextRef context, const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload) { + return createJSObject(context, NFCFactory::getInstance().createNDEFRecordMediaObject(ndefRecordProperties, payload)); +} + +JSObjectRef JSNdefRecordMedia::createJSObject(JSContextRef context, const std::string &mimeType, std::vector<unsigned char> data, bool isValid) { + return createJSObject(context, NFCFactory::getInstance().createNDEFRecordMediaObject(mimeType, data, isValid)); +} + +JSObjectRef JSNdefRecordMedia::createJSObject(JSContextRef context, INdefRecordPtr ndefRecord) { + NdefRecordPrivObject *priv = new NdefRecordPrivObject(context, ndefRecord); + + JSObjectRef obj = JSObjectMake(context, getClassRef(), priv); + return obj; +} + +void JSNdefRecordMedia::initialize(JSContextRef context, JSObjectRef object) { + LoggerD("Entered"); +} + +void JSNdefRecordMedia::finalize(JSObjectRef object) { + LoggerD("Entered"); +} + +JSObjectRef JSNdefRecordMedia::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + LoggerD("entered"); + + std::vector<unsigned char> data; + std::string mimeType = ""; + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(ctx); + bool isValid = true; + + ArgumentValidator validator(ctx, argumentCount, arguments); + try { + mimeType = validator.toString(0); + } catch (...) { + isValid = false; + LoggerE("Can't convert mimeType"); + } + + try { + NFCConverter convert(ctx); + if (validator.toArrayObject(1)) + data = convert.toVectorOfOctets(arguments[1]); + } catch (...) { + isValid = false; + LoggerE("Can't convert data"); + } + + + JSObjectRef result = createJSObject(global_context, mimeType, data, isValid); + + JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor"); + JSObjectSetProperty(global_context, result, ctorName, constructor, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + JSStringRelease(ctorName); + return result; + +} + +JSValueRef JSNdefRecordMedia::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) { + LoggerD("Enter"); + + Try { + NFCConverter convert(context); + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFRECORD_MEDIA_MIMETYPE)) { + NdefRecordPrivObject *priv = static_cast<NdefRecordPrivObject*>(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object not set."); + } + INdefRecordPtr ndefRecord = priv->getObject(); + return convert.toJSValueRef(ndefRecord->getMimeType()); + } + + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + + +} //NFC +} //DeviceAPI + diff --git a/mobile_src/NFC/JSNdefRecordMedia.h b/mobile_src/NFC/JSNdefRecordMedia.h new file mode 100755 index 0000000..070be2c --- /dev/null +++ b/mobile_src/NFC/JSNdefRecordMedia.h @@ -0,0 +1,78 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_TIZEN_JS_NDEFRECORD_MEDIA_H_ +#define WRTPLUGINS_TIZEN_JS_NDEFRECORD_MEDIA_H_ + +#include "JSNdefRecord.h" + +namespace DeviceAPI { +namespace NFC { + +class JSNdefRecordMedia +{ +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, + const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload); + + static JSObjectRef createJSObject(JSContextRef context, + const std::string &mimeType, std::vector<unsigned char> data, bool isValid = true); + static JSObjectRef createJSObject(JSContextRef context, INdefRecordPtr ndefRecord); + + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + +}; + +} //NFC +} //DeviceAPI + +#endif + diff --git a/mobile_src/NFC/JSNdefRecordText.cpp b/mobile_src/NFC/JSNdefRecordText.cpp new file mode 100755 index 0000000..bd78ed8 --- /dev/null +++ b/mobile_src/NFC/JSNdefRecordText.cpp @@ -0,0 +1,196 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <memory> +#include <string> +#include <CommonsJavaScript/JSUtils.h> + +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <ArgumentValidator.h> +#include <GlobalContextManager.h> +#include <PlatformException.h> + +#include "NFCFactory.h" +#include "JSNdefRecordText.h" +#include "NFCConverter.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define TIZEN_NDEFRECORD_TEXT_TEXT "text" +#define TIZEN_NDEFRECORD_TEXT_LANGCODE "languageCode" +#define TIZEN_NDEFRECORD_TEXT_ENCODING "encoding" + +JSClassDefinition JSNdefRecordText::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "NDEFRecordText", + JSNdefRecord::getClassRef(), + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSNdefRecordText::m_property[] = +{ + {TIZEN_NDEFRECORD_TEXT_TEXT, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN_NDEFRECORD_TEXT_LANGCODE, getProperty, NULL, kJSPropertyAttributeReadOnly}, + {TIZEN_NDEFRECORD_TEXT_ENCODING, getProperty, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSNdefRecordText::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNdefRecordText::getClassInfo() { + return &m_classInfo; +} + +JSClassRef JSNdefRecordText::m_jsClassRef = JSClassCreate(JSNdefRecordText::getClassInfo()); + +JSObjectRef JSNdefRecordText::createJSObject(JSContextRef context, const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload) { + return createJSObject(context, NFCFactory::getInstance().createNDEFRecordTextObject(ndefRecordProperties, payload)); +} + +JSObjectRef JSNdefRecordText::createJSObject(JSContextRef context, const std::string &text, const std::string &langCode, const nfcTextEncodeUTF encodeType, bool isValid) { + return createJSObject(context, NFCFactory::getInstance().createNDEFRecordTextObject(text, langCode, encodeType, isValid)); +} + +JSObjectRef JSNdefRecordText::createJSObject(JSContextRef context, INdefRecordPtr ndefRecord) { + NdefRecordPrivObject *priv = new NdefRecordPrivObject(context, ndefRecord); + + JSObjectRef obj = JSObjectMake(context, getClassRef(), priv); + return obj; +} + +void JSNdefRecordText::initialize(JSContextRef context, JSObjectRef object) { + LoggerD("entered"); +} + +void JSNdefRecordText::finalize(JSObjectRef object) { + LoggerD("Entered"); +} + +JSObjectRef JSNdefRecordText::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + LoggerD("entered"); + + ArgumentValidator validator(ctx, argumentCount, arguments); + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(ctx); + + bool isValid = true; + + NFCConverter convert(ctx); + nfcTextEncodeUTF encodeType = NFC_TEXT_ENCODE_UTF_8; + + std::string text = ""; + std::string languageCode = ""; + std::string encoding = ""; + + try { + text = validator.toString(0); + } catch (...) { + isValid = false; + LoggerE("Can't convert text"); + } + + try { + languageCode = validator.toString(1); + } catch (...) { + isValid = false; + LoggerE("Can't convert languageCode"); + } + + try { + encoding = validator.toString(2, true); + } catch (...) { + encoding = ""; + LoggerE("Can't convert encoding"); + } + + if (encoding != "") + encodeType = convert.toNfcTextEncodeUTF(encoding); + + JSObjectRef result = createJSObject(global_context, text, languageCode, encodeType, isValid); + JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor"); + JSObjectSetProperty(global_context, result, ctorName, constructor, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + JSStringRelease(ctorName); + + return result; +} +JSValueRef JSNdefRecordText::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) { + LoggerD("Enter"); + + Try { + NFCConverter convert(context); + NdefRecordPrivObject *priv = static_cast<NdefRecordPrivObject*>(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object not set."); + } + INdefRecordPtr ndefRecord = priv->getObject(); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFRECORD_TEXT_TEXT)) { + return convert.toJSValueRef(ndefRecord->getText()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFRECORD_TEXT_LANGCODE)) { + return convert.toJSValueRef(ndefRecord->getLanguageCode()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFRECORD_TEXT_ENCODING)) { + nfcTextEncodeUTF encodeType = ndefRecord->getEncoding(); + return convert.toJSValueRef(convert.toNfcTextEncodeUTFString(encodeType)); + } + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::NotFoundException) { + LoggerE("NotFoundException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + +} //NFC +} //DeviceAPI + diff --git a/mobile_src/NFC/JSNdefRecordText.h b/mobile_src/NFC/JSNdefRecordText.h new file mode 100755 index 0000000..09fdb8a --- /dev/null +++ b/mobile_src/NFC/JSNdefRecordText.h @@ -0,0 +1,78 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_TIZEN_JS_NDEFRECORD_TEXT_H_ +#define WRTPLUGINS_TIZEN_JS_NDEFRECORD_TEXT_H_ + +#include "JSNdefRecord.h" + +namespace DeviceAPI { +namespace NFC { + +class JSNdefRecordText +{ +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, + const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload); + + static JSObjectRef createJSObject(JSContextRef context, const std::string &text, + const std::string &langCode, const nfcTextEncodeUTF encodeType, bool isValid = true); + static JSObjectRef createJSObject(JSContextRef context, INdefRecordPtr ndefRecord); + + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + +}; + +} //NFC +} //DeviceAPI + +#endif + diff --git a/mobile_src/NFC/JSNdefRecordURI.cpp b/mobile_src/NFC/JSNdefRecordURI.cpp new file mode 100755 index 0000000..052a342 --- /dev/null +++ b/mobile_src/NFC/JSNdefRecordURI.cpp @@ -0,0 +1,162 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <memory> +#include <string> +#include <CommonsJavaScript/JSUtils.h> + +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <ArgumentValidator.h> +#include <GlobalContextManager.h> +#include <PlatformException.h> + +#include "NFCFactory.h" +#include "NFCConverter.h" +#include "JSNdefRecordURI.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define TIZEN_NDEFRECORD_URI_URI "uri" + +JSClassDefinition JSNdefRecordURI::m_classInfo = +{ + 0, + kJSClassAttributeNone, + "NDEFRecordURI", + JSNdefRecord::getClassRef(), + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSNdefRecordURI::m_property[] = +{ + {TIZEN_NDEFRECORD_URI_URI, getProperty, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSNdefRecordURI::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSNdefRecordURI::getClassInfo() { + return &m_classInfo; +} + +JSClassRef JSNdefRecordURI::m_jsClassRef = JSClassCreate(JSNdefRecordURI::getClassInfo()); + +void JSNdefRecordURI::initialize(JSContextRef context, JSObjectRef object) { + LoggerD("entered"); +} + +void JSNdefRecordURI::finalize(JSObjectRef object) { + LoggerD("Entered"); +} + +JSObjectRef JSNdefRecordURI::createJSObject(JSContextRef context, const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload) { + return createJSObject(context, NFCFactory::getInstance().createNDEFRecordUriObject(ndefRecordProperties, payload)); +} + +JSObjectRef JSNdefRecordURI::createJSObject(JSContextRef context, const std::string &uri, bool isValid) { + return createJSObject(context, NFCFactory::getInstance().createNDEFRecordUriObject(uri, isValid)); +} + +JSObjectRef JSNdefRecordURI::createJSObject(JSContextRef context, INdefRecordPtr ndefRecord) { + NdefRecordPrivObject *priv = new NdefRecordPrivObject(context, ndefRecord); + + JSObjectRef obj = JSObjectMake(context, getClassRef(), priv); + return obj; +} + +JSObjectRef JSNdefRecordURI::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + LoggerD("entered"); + + ArgumentValidator validator(ctx, argumentCount, arguments); + JSContextRef global_context = GlobalContextManager::getInstance()->getGlobalContext(ctx); + bool isValid = true; + std::string uri = ""; + + try { + uri = validator.toString(0); + } catch (...) { + isValid = false; + LoggerE("Can't convert text"); + } + JSObjectRef result = createJSObject(global_context, uri, isValid); + + JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor"); + JSObjectSetProperty(global_context, result, ctorName, constructor, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + JSStringRelease(ctorName); + return result; +} +JSValueRef JSNdefRecordURI::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) { + LoggerD("Enter"); + + Try { + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_NDEFRECORD_URI_URI)) { + NdefRecordPrivObject *priv = static_cast<NdefRecordPrivObject*>(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(NullPointerException, "Private object not set."); + } + INdefRecordPtr ndefRecord = priv->getObject(); + NFCConverter convert(context); + return convert.toJSValueRef(ndefRecord->getUri()); + } + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownExceptionException: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("PlatformException: " << _rethrown_exception.GetMessage()); + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::NotFoundException) { + LoggerE("NotFoundException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + + +} //NFC +} //DeviceAPI + diff --git a/mobile_src/NFC/JSNdefRecordURI.h b/mobile_src/NFC/JSNdefRecordURI.h new file mode 100755 index 0000000..6d233da --- /dev/null +++ b/mobile_src/NFC/JSNdefRecordURI.h @@ -0,0 +1,78 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_TIZEN_JS_NDEFRECORD_URI_H_ +#define WRTPLUGINS_TIZEN_JS_NDEFRECORD_URI_H_ + +#include "JSNdefRecord.h" + +namespace DeviceAPI { +namespace NFC { + +class JSNdefRecordURI +{ +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, + const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload); + + static JSObjectRef createJSObject(JSContextRef context, const std::string &uri, bool isValid = true); + + static JSObjectRef createJSObject(JSContextRef context, INdefRecordPtr ndefRecord); + + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + +}; + +} //NFC +} //DeviceAPI + +#endif + diff --git a/mobile_src/NFC/NFCAdapter.cpp b/mobile_src/NFC/NFCAdapter.cpp new file mode 100755 index 0000000..f66839e --- /dev/null +++ b/mobile_src/NFC/NFCAdapter.cpp @@ -0,0 +1,214 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <dpl/scoped_ptr.h> +#include <Commons/Exception.h> +#include <nfc.h> +#include <JSWebAPIErrorFactory.h> +#include "NFCDefaultAdapter.h" +#include "NFCAdapter.h" +#include "NFCUtil.h" +#include <Logger.h> + + +namespace DeviceAPI { +namespace NFC { + +NFCAdapter::NFCAdapter() { + LoggerD("NFCAdapter"); + if (!NFCDefaultAdapterSingleton::Instance().isSupported()) + ThrowMsg(UnsupportedException, "Not Support"); + + m_NFCTagEmitterPtr.Reset(); + m_NFCTargetEmitterPtr.Reset(); + m_tagFilter.Reset(); + m_EventNFCChangedSetPoweredPtr.Reset(); +} + +NFCAdapter::~NFCAdapter() { + LoggerD("Enter"); + try { + unsetTagListener(); + unsetPeerListener(); + } catch(...) { + LoggerE("ignore exception"); + } + m_EventNFCChangedSetPoweredPtr.Reset(); +} + +int NFCAdapter::setTagListener(const EventNFCChangedEmitterPtr& emitter, const TagFilterPtr& filter) { + LoggerD(" NFCAdapter::setTagListener Entered"); + if (!getPowerState()) + ThrowMsg(PlatformException, "NFC is OFF."); + if (m_NFCTagEmitterPtr.Get() != NULL) + ThrowMsg(PlatformException, "It has already set Tag Listener"); + + m_NFCTagEmitterPtr = emitter; + m_tagFilter = filter; + + return NFCDefaultAdapterSingleton::Instance().setTagListener(this); +} + +int NFCAdapter::setPeerListener(const EventNFCChangedEmitterPtr& emitter) { + LoggerD(" NFCAdapter::setPeerListener Entered"); + if (!getPowerState()) + ThrowMsg(PlatformException, "NFC is OFF."); + if (m_NFCTargetEmitterPtr.Get() != NULL) + ThrowMsg(PlatformException, "It has already set Peer Listener"); + + m_NFCTargetEmitterPtr = emitter; + return NFCDefaultAdapterSingleton::Instance().setPeerListener(this); +} +void NFCAdapter::unsetTagListener() { + LoggerD(" NFCAdapter::unsetTagListener Entered"); + if (!getPowerState()) + ThrowMsg(PlatformException, "NFC is OFF."); + m_NFCTagEmitterPtr.Reset(); + m_tagFilter.Reset(); + NFCDefaultAdapterSingleton::Instance().unsetTagListener(this); +} + +void NFCAdapter::unsetPeerListener() { + LoggerD(" NFCAdapter::unsetPeerListener Entered"); + if (!getPowerState()) + ThrowMsg(PlatformException, "NFC is OFF."); + m_NFCTargetEmitterPtr.Reset(); + NFCDefaultAdapterSingleton::Instance().unsetPeerListener(this); +} + +void NFCAdapter::NFCTagHasDetected(void *props) +{ + if (m_NFCTagEmitterPtr.Get() != NULL) { + if ((props != NULL) && (m_tagFilter->getFilterSize() > 0)) { + nfc_tag_type_e tagType = NFC_UNKNOWN_TARGET; + + if (nfc_tag_get_type((nfc_tag_h)props, &tagType) == NFC_ERROR_NONE) { + LoggerD("NFCAdapter::NFCTagHasDetected Tag real type : " << tagType); + int cnt; + for (cnt = 0; cnt < m_tagFilter->getFilterSize(); cnt++) { + NFCUtil util; + if (util.convertTonfcTagType(static_cast<unsigned short>(tagType)) == m_tagFilter->getFilterValue(cnt)) + break; + } + if (cnt == m_tagFilter->getFilterSize()) { + LoggerD("Filter doesn't have this tag type "); + return; + } + } else { + LoggerD("It can't get real nfc tag type"); + int cnt; + for (cnt = 0; cnt < m_tagFilter->getFilterSize(); cnt++) { + if (NFC_TAGTYPE_GENERIC_PICC == m_tagFilter->getFilterValue(cnt)) + break; + } + + if (cnt == m_tagFilter->getFilterSize()) { + LoggerD("Filter doesn't have this tag type "); + return; + } + + } + } + EventNFCChangedPtr event(new EventNFCChanged()); + if (props == NULL) + event->setNFCStatus(NFC_DETATCHED); + else + event->setNFCStatus(NFC_ATTATCHED); + + event->setNFCProperties(props); + event->setNFCType(NFC_TAG_TYPE); + LoggerD("emit event with nfc tag info"); + m_NFCTagEmitterPtr->emit(event); + } +} + +void NFCAdapter::NFCTargetHasDetected(void *props) +{ + if (m_NFCTargetEmitterPtr.Get() != NULL) { + EventNFCChangedPtr event(new EventNFCChanged()); + if (props == NULL) + event->setNFCStatus(NFC_DETATCHED); + else + event->setNFCStatus(NFC_ATTATCHED); + event->setNFCProperties(props); + event->setNFCType(NFC_TARGET_TYPE); + LoggerD("emit event with nfc target info"); + m_NFCTargetEmitterPtr->emit(event); + } +} + +void *NFCAdapter::getCachedMessage() { + return NFCDefaultAdapterSingleton::Instance().getCachedMessage(); +} + +bool NFCAdapter::getPowerState() { + return NFCDefaultAdapterSingleton::Instance().getPowerState(); +} + +void NFCAdapter::setPowered(const EventNFCChangedSetPoweredPtr& event) { + LoggerD("Enter"); + EventRequestReceiver<EventNFCChangedSetPowered>::PostRequest(event); +} + +void NFCAdapter::OnRequestReceived(const EventNFCChangedSetPoweredPtr& event) { + if (getPowerState() == event->getState()) { + event->setResult(true); + return; + } + if (m_EventNFCChangedSetPoweredPtr.Get() !=NULL) { + event->setResult(false); + event->setError(DeviceAPI::Common::JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR); + event->setErrorMessage("Progressing Identical Operation"); + return; + } + + event->switchToManualAnswer(); + m_EventNFCChangedSetPoweredPtr = event; + Try { + NFCDefaultAdapterSingleton::Instance().setPowered(event->getState(), this); + return; + } Catch(PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + event->setResult(false); + event->setError(DeviceAPI::Common::JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR); + event->setErrorMessage("Progressing Identical Operation"); + EventRequestReceiver<EventNFCChangedSetPowered>::ManualAnswer(event); + } Catch(WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + setPoweredManualAnswer(NFC_ERROR_OPERATION_FAILED); + } +} + +void NFCAdapter::setPoweredManualAnswer(int error) { + if (m_EventNFCChangedSetPoweredPtr.Get() != NULL) { + EventNFCChangedSetPoweredPtr event = m_EventNFCChangedSetPoweredPtr; + m_EventNFCChangedSetPoweredPtr.Reset(); + + if (error == NFC_ERROR_NONE) { + event->setResult(true); + } else { + NFCUtil util; + event->setResult(false); + event->setError(util.getNFCErrorString(error)); + event->setErrorMessage(util.getNFCErrorMessage(error)); + } + EventRequestReceiver<EventNFCChangedSetPowered>::ManualAnswer(event); + } +} + +} +} diff --git a/mobile_src/NFC/NFCAdapter.h b/mobile_src/NFC/NFCAdapter.h new file mode 100755 index 0000000..e9b48b9 --- /dev/null +++ b/mobile_src/NFC/NFCAdapter.h @@ -0,0 +1,73 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NFCADAPTER_H_ +#define _NFCADAPTER_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/Emitters.h> + +#include "INFCAdapter.h" +#include "NFCFactory.h" +#include "EventNFCChanged.h" + + + +namespace DeviceAPI { +namespace NFC { +class NFCAdapter : public INFCAdapter +{ + friend class NFCFactory; + public: + NFCAdapter(); + virtual ~NFCAdapter(); + +public: + /** + * watchNFCTag + */ + virtual int setTagListener(const EventNFCChangedEmitterPtr& emitter, const TagFilterPtr& filter); + virtual int setPeerListener(const EventNFCChangedEmitterPtr& emitter); + /** + * clearWatch + */ + virtual void unsetTagListener(); + virtual void unsetPeerListener(); + + void NFCTagHasDetected(void *props); + void NFCTargetHasDetected(void *props); + + virtual void *getCachedMessage(); + + virtual bool getPowerState(); + virtual void setPowered(const EventNFCChangedSetPoweredPtr& event); + void setPoweredManualAnswer(int error); +private: + EventNFCChangedEmitterPtr m_NFCTagEmitterPtr; + EventNFCChangedEmitterPtr m_NFCTargetEmitterPtr; + EventNFCChangedSetPoweredPtr m_EventNFCChangedSetPoweredPtr; + TagFilterPtr m_tagFilter; + protected: + virtual void OnRequestReceived(const EventNFCChangedSetPoweredPtr& event); +}; + +} +} + +#endif /* _NFCADAPTER_H_ */ diff --git a/mobile_src/NFC/NFCAsyncCallbackManager.cpp b/mobile_src/NFC/NFCAsyncCallbackManager.cpp new file mode 100755 index 0000000..4508c50 --- /dev/null +++ b/mobile_src/NFC/NFCAsyncCallbackManager.cpp @@ -0,0 +1,30 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 "NFCAsyncCallbackManager.h" +#include <dpl/singleton_impl.h> + + + +IMPLEMENT_SINGLETON(DeviceAPI::NFC::NFCAsyncCallbackManager) + +namespace DeviceAPI { +namespace NFC { + +} // NFC +} // DeviceAPI diff --git a/mobile_src/NFC/NFCAsyncCallbackManager.h b/mobile_src/NFC/NFCAsyncCallbackManager.h new file mode 100644 index 0000000..06da039 --- /dev/null +++ b/mobile_src/NFC/NFCAsyncCallbackManager.h @@ -0,0 +1,46 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _TIZEN_NFC_ASYNC_CALLBACK_MANAGER_H_ +#define _TIZEN_NFC_ASYNC_CALLBACK_MANAGER_H_ + +#include <dpl/singleton.h> +#include <AsyncCallbackManager.h> + +namespace DeviceAPI { +namespace NFC { + +class NFCAsyncCallbackManager : public DeviceAPI::Common::AsyncCallbackManager +{ +public: + NFCAsyncCallbackManager() + { + } + + virtual ~NFCAsyncCallbackManager() + { + } + + friend class DPL::Singleton<NFCAsyncCallbackManager>; +}; + +typedef DPL::Singleton<NFCAsyncCallbackManager> NFCAsyncCallbackManagerSingleton; + +} // NFC +} // DeviceAPI + +#endif // _TIZEN_NFC_ASYNC_CALLBACK_MANAGER_H_
\ No newline at end of file diff --git a/mobile_src/NFC/NFCChangedCallback.h b/mobile_src/NFC/NFCChangedCallback.h new file mode 100755 index 0000000..71d8cba --- /dev/null +++ b/mobile_src/NFC/NFCChangedCallback.h @@ -0,0 +1,39 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 TIZEN_NFC_NFCCHANGEDCALLBACK_H_ +#define TIZEN_NFC_NFCCHANGEDCALLBACK_H_ + +#include <JavaScriptCore/JavaScript.h> + +namespace DeviceAPI { +namespace NFC { +struct NFCChangedCallback +{ + JSValueRef onattach; + JSValueRef ondetach; + + NFCChangedCallback() : + onattach(NULL), + ondetach(NULL) + { + } +}; +} +} + +#endif diff --git a/mobile_src/NFC/NFCConverter.cpp b/mobile_src/NFC/NFCConverter.cpp new file mode 100755 index 0000000..7d93350 --- /dev/null +++ b/mobile_src/NFC/NFCConverter.cpp @@ -0,0 +1,380 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <CommonsJavaScript/JSUtils.h> +#include <JSUtil.h> +#include "NFCFactory.h" +#include "NFCConverter.h" +#include "JSNdefRecord.h" +#include "JSNdefRecordText.h" +#include "JSNdefRecordURI.h" +#include "JSNdefRecordMedia.h" +#include "JSNdefMessage.h" +#include <Logger.h> + +using namespace std; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis; + + +#define NFC_FILTER_ATTRIBUTE_TAG_TYPES "tagTypes" + +#define NFC_CHANGED_CALLBACK_ONATTATCH "onattach" +#define NFC_CHANGED_CALLBACK_ONDETACH "ondetach" + +namespace DeviceAPI { +namespace NFC { + +vector<std::string> NFCConverter::m_allowedTagFilterProperties; + +NFCConverter::NFCConverter(JSContextRef context) : Converter(context) +{ + LoggerD("entered"); + static bool init = initializeAllowedProperties(); + (void) init; +} + +NFCConverter::~NFCConverter() +{ + LoggerD("entered"); +} + +TagFilterPtr NFCConverter::toNFCTagFilter(JSValueRef jsValue) +{ + LoggerD("entered"); + if (JSValueIsNull(m_context, jsValue) || + JSValueIsUndefined(m_context, jsValue)) { + return TagFilterPtr(); //empty filter + } + TagFilterPtr filter(new TagFilter()); + + if (!JSValueIsUndefined(m_context, jsValue)) { + vector<std::string> filter_values(toVectorOfStrings(jsValue)); + + LoggerD("NFCConverter, start setting filter values, tag_types.size() : " << filter_values.size()); + for (unsigned int i=0; i<filter_values.size(); i++) { + nfcTagType filterValue = toNfcTagType(filter_values.at(i)); + + filter->addTagTypeValue(filterValue); + LoggerD("NFCConverter, tag_types.at(i): " << filter_values.at(i)); + } + } + LoggerD("NFCConverter, filter size == " << filter->getFilterSize()); + + return filter; +} + + +nfcTagType NFCConverter::toNfcTagType(std::string typeString) { + if (typeString == "GENERIC_TARGET") + return NFC_TAGTYPE_GENERIC_PICC; + else if (typeString == "ISO14443_A") + return NFC_TAGTYPE_ISO14443_A_PICC; + else if (typeString == "ISO14443_4A") + return NFC_TAGTYPE_ISO14443_4A_PICC; + else if (typeString == "ISO14443_3A") + return NFC_TAGTYPE_ISO14443_3A_PICC; + else if (typeString == "MIFARE_MINI") + return NFC_TAGTYPE_MIFARE_MINI_PICC; + else if (typeString == "MIFARE_1K") + return NFC_TAGTYPE_MIFARE_1K_PICC; + else if (typeString == "MIFARE_4K") + return NFC_TAGTYPE_MIFARE_4K_PICC; + else if (typeString == "MIFARE_ULTRA") + return NFC_TAGTYPE_MIFARE_ULTRA_PICC; + else if (typeString == "MIFARE_DESFIRE") + return NFC_TAGTYPE_MIFARE_DESFIRE_PICC; + else if (typeString == "ISO14443_B") + return NFC_TAGTYPE_ISO14443_B_PICC; + else if (typeString == "ISO14443_4B") + return NFC_TAGTYPE_ISO14443_4B_PICC; + else if (typeString == "ISO14443_BPRIME") + return NFC_TAGTYPE_ISO14443_BPRIME_PICC; + else if (typeString == "FELICA") + return NFC_TAGTYPE_FELICA_PICC; + else if (typeString == "JEWEL") + return NFC_TAGTYPE_JEWEL_PICC; + else if (typeString == "ISO15693") + return NFC_TAGTYPE_ISO15693_PICC; + else if (typeString == "UNKNOWN_TARGET") + return NFC_TAGTYPE_UNKNOWN_TARGET; + else + ThrowMsg(Commons::ConversionException, "No Match Tag Type"); +} + +std::string NFCConverter::toNfcTagTypeString(nfcTagType type) { + switch (type) { + case NFC_TAGTYPE_GENERIC_PICC: + return "GENERIC_TARGET"; + break; + case NFC_TAGTYPE_ISO14443_A_PICC: + return "ISO14443_A"; + break; + case NFC_TAGTYPE_ISO14443_4A_PICC: + return "ISO14443_4A"; + break; + case NFC_TAGTYPE_ISO14443_3A_PICC: + return "ISO14443_3A"; + break; + case NFC_TAGTYPE_MIFARE_MINI_PICC: + return "MIFARE_MINI"; + break; + case NFC_TAGTYPE_MIFARE_1K_PICC: + return "MIFARE_1K"; + break; + case NFC_TAGTYPE_MIFARE_4K_PICC: + return "MIFARE_4K"; + break; + case NFC_TAGTYPE_MIFARE_ULTRA_PICC: + return "MIFARE_ULTRA"; + break; + case NFC_TAGTYPE_MIFARE_DESFIRE_PICC: + return "MIFARE_DESFIRE"; + break; + case NFC_TAGTYPE_ISO14443_B_PICC: + return "ISO14443_B"; + break; + case NFC_TAGTYPE_ISO14443_4B_PICC: + return "ISO14443_4B"; + break; + case NFC_TAGTYPE_ISO14443_BPRIME_PICC: + return "ISO14443_BPRIME"; + break; + case NFC_TAGTYPE_FELICA_PICC: + return "FELICA"; + break; + case NFC_TAGTYPE_JEWEL_PICC: + return "JEWEL"; + break; + case NFC_TAGTYPE_ISO15693_PICC: + return "ISO15693"; + break; + case NFC_TAGTYPE_UNKNOWN_TARGET: + default: + return "UNKNOWN_TARGET"; + break; + } +} + +nfcTextEncodeUTF NFCConverter::toNfcTextEncodeUTF(std::string encodeString) { + if (encodeString == "UTF16") + return NFC_TEXT_ENCODE_UTF_16; + else + return NFC_TEXT_ENCODE_UTF_8; + +} + +std::string NFCConverter::toNfcTextEncodeUTFString(nfcTextEncodeUTF encode) { + switch(encode) { + case NFC_TEXT_ENCODE_UTF_16: + return "UTF16"; + break; + case NFC_TEXT_ENCODE_UTF_8: + default: + return "UTF8"; + break; + } +} + +bool NFCConverter::initializeAllowedProperties() +{ + LoggerD("entered"); + //NFC Filter properties + m_allowedTagFilterProperties.push_back(NFC_FILTER_ATTRIBUTE_TAG_TYPES); + return true; +} + +JSValueRef NFCConverter::toJSValueRef(const std::vector<unsigned char>& arg) { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(Commons::UnknownException, "Could not create js array object"); + } + + for (std::size_t i = 0; i < arg.size(); ++i) { + JSValueRef tmpVal = JSValueMakeNumber(m_context, arg[i]); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(Commons::UnknownException, "Could not insert value into js array"); + } + } + + return jsResult; +} + +JSValueRef NFCConverter::toJSValueRef(NdefRecordData arg) { + if (arg.properties.tnf == NFC_TNF_MIME_MEDIA) + return JSNdefRecordMedia::createJSObject(m_context, arg.properties, arg.payload); + if (arg.properties.tnf == NFC_TNF_WELL_KNOWN) { + if (arg.properties.typeName.size() > 0) { + if (arg.properties.typeName[0] == 0x54) + return JSNdefRecordText::createJSObject(m_context, arg.properties, arg.payload); + if (arg.properties.typeName[0] == 0x55) + return JSNdefRecordURI::createJSObject(m_context, arg.properties, arg.payload); + } + } + return JSNdefRecord::createJSObject(m_context, arg.properties, arg.payload); +} + +JSValueRef NFCConverter::toJSValueRef(std::vector<NFCTagProperties> props) { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not create js array object"); + } + + for (std::size_t i = 0; i < props.size(); ++i) { + JSValueRef tmpVal = toJSValueRef(props[i].value); + if (!JSSetArrayElementInArrayList(m_context, jsResult, props[i].key.c_str(), tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + return jsResult; +} + +std::vector<unsigned char> NFCConverter::toVectorOfOctets(const JSValueRef& arg) { + return Common::JSUtil::JSArrayToType_<unsigned char>(m_context, arg, Common::JSUtil::JSValueToOctet); +} + +bool NFCConverter::isNdefRecord(const JSValueRef& arg) { + LoggerD("Entered"); + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg)) { + LoggerD("Object is Null or Undefied"); + return false; + } + if (JSValueIsObjectOfClass(m_context, arg, JSNdefRecord::getClassRef()) + || JSValueIsObjectOfClass(m_context, arg, JSNdefRecordText::getClassRef()) + || JSValueIsObjectOfClass(m_context, arg, JSNdefRecordURI::getClassRef()) + || JSValueIsObjectOfClass(m_context, arg, JSNdefRecordMedia::getClassRef())) + return true; + + return false; +} + +std::vector<void *> NFCConverter::toVectorOfRecordHandles(const JSValueRef& arg) { + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg)) { + ThrowMsg(Commons::ConversionException, + "NdefRecordArray is JS null or JS undefined."); + } + + if (!JSIsArrayValue(m_context, arg)) { + ThrowMsg(Commons::ConversionException, "Argument is not an JS array."); + } + + JSObjectRef obj = toJSObjectRef(arg); + + if (!obj) { + LoggerE("Object is null"); + ThrowMsg(Commons::ConversionException, "Object is null"); + } + + return toVectorOfRecordHandles(obj); +} + +std::vector<void *> NFCConverter::toVectorOfRecordHandles(const JSObjectRef& obj) { + std::vector<void *> result; + for (std::size_t i = 0; i < JSGetArrayLength(m_context, obj); ++i) { + JSValueRef element = JSGetArrayElement(m_context, obj, i); + try { + if (isNdefRecord(element)) + result.push_back(getRecordHandle(element)); + else + ThrowMsg(Commons::ConversionException, "JS array has items those are not NDEFRecord."); + } catch (const WrtDeviceApis::Commons::Exception& err) { + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + for (std::size_t j = 0; j < result.size(); ++j) { + if (result[j]) + nfc_ndef_record_destroy((nfc_ndef_record_h)result[j]); + } + ThrowMsg(Commons::ConversionException, "JS array has items those are not NDEFRecords or invalid records."); + } + } + return result; +} + +std::string NFCConverter::toRecordClassName(NdefRecordData arg) { + if (arg.properties.tnf == NFC_TNF_MIME_MEDIA) + return JSNdefRecordMedia::getClassInfo()->className; + if (arg.properties.tnf == NFC_TNF_WELL_KNOWN) { + if (arg.properties.typeName.size() > 0) { + if (arg.properties.typeName[0] == 0x54) + return JSNdefRecordText::getClassInfo()->className; + if (arg.properties.typeName[0] == 0x55) + return JSNdefRecordURI::getClassInfo()->className; + } + } + return JSNdefRecord::getClassInfo()->className; +} + +void *NFCConverter::getRecordHandle(const JSValueRef& arg) { + LoggerD("Entered"); + if (!isNdefRecord(arg)) { + ThrowMsg(Commons::ConversionException, + "Not record value"); + } + JSObjectRef obj = toJSObjectRef(arg); + + if (!obj) { + LoggerE("Object is null"); + ThrowMsg(Commons::ConversionException, "Object is null"); + } + NdefRecordPrivObject* privateObject = static_cast<NdefRecordPrivObject*>(JSObjectGetPrivate(obj)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(Commons::ConversionException, "Private object not set"); + } + + INdefRecordPtr record = privateObject->getObject(); + void *handle = record->getHandle(); + if (handle == NULL) + ThrowMsg(Commons::ConversionException, "Invalid Handle"); + return handle; +} + +NFCChangedCallback NFCConverter::toNFCChangedCallback(const JSValueRef& arg) { + LoggerD("Entered"); + JSObjectRef object = toJSObjectRef(arg); + + NFCChangedCallback result; + Validator validator(m_context); + + result.onattach= JSUtils::getJSPropertyOrUndefined( + m_context, object, NFC_CHANGED_CALLBACK_ONATTATCH + ); + if (!validator.isNullOrUndefined(result.onattach) && + !validator.isCallback(result.onattach)) { + ThrowMsg(Commons::ConversionException, "Not a valid callback."); + } + + result.ondetach= JSUtils::getJSPropertyOrUndefined( + m_context, object, NFC_CHANGED_CALLBACK_ONDETACH + ); + if (!validator.isNullOrUndefined(result.ondetach) && + !validator.isCallback(result.ondetach)) { + ThrowMsg(Commons::ConversionException, "Not a valid callback."); + } + + if (validator.isNullOrUndefined(result.onattach) && validator.isNullOrUndefined(result.ondetach)) + ThrowMsg(Commons::ConversionException, "Not a valid callback."); + + return result; +} + +} +} diff --git a/mobile_src/NFC/NFCConverter.h b/mobile_src/NFC/NFCConverter.h new file mode 100755 index 0000000..15d68f2 --- /dev/null +++ b/mobile_src/NFC/NFCConverter.h @@ -0,0 +1,69 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _JS_TIZEN_NFC_CONVERTER_H_ +#define _JS_TIZEN_NFC_CONVERTER_H_ + +#include <vector> +#include <string> +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/Converter.h> +#include "TagFilter.h" +#include "NdefRecordProperties.h" +#include "NFCTagProperties.h" +#include "INdefRecord.h" +#include "INdefMessage.h" +#include "EventNFCChanged.h" +#include "NFCChangedCallback.h" + +namespace DeviceAPI { +namespace NFC { + + +class NFCConverter : public WrtDeviceApis::CommonsJavaScript::Converter +{ + public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; + public: + explicit NFCConverter(JSContextRef context); + virtual ~NFCConverter(); + TagFilterPtr toNFCTagFilter(JSValueRef jsValue); + nfcTagType toNfcTagType(std::string typeString); + std::string toNfcTagTypeString(nfcTagType type); + nfcTextEncodeUTF toNfcTextEncodeUTF(std::string encodeString); + std::string toNfcTextEncodeUTFString(nfcTextEncodeUTF encode); + JSValueRef toJSValueRef(const std::vector<unsigned char>& arg); + JSValueRef toJSValueRef(std::vector<NFCTagProperties> props); + JSValueRef toJSValueRef(NdefRecordData arg); + bool isNdefRecord(const JSValueRef& arg); + std::vector<unsigned char> toVectorOfOctets(const JSValueRef& arg); + std::vector<void *> toVectorOfRecordHandles(const JSValueRef& arg); + std::vector<void *> toVectorOfRecordHandles(const JSObjectRef& obj); + std::string toRecordClassName(NdefRecordData arg); + void *getRecordHandle(const JSValueRef& arg); + NFCChangedCallback toNFCChangedCallback(const JSValueRef& arg); + private: + bool initializeAllowedProperties(); + static std::vector<std::string> m_allowedTagFilterProperties; +}; + +} +} + +#endif /* _JS_TIZEN_NFC_CONVERTER_H_ */ diff --git a/mobile_src/NFC/NFCDefaultAdapter.cpp b/mobile_src/NFC/NFCDefaultAdapter.cpp new file mode 100755 index 0000000..ce1f4df --- /dev/null +++ b/mobile_src/NFC/NFCDefaultAdapter.cpp @@ -0,0 +1,343 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <dpl/singleton.h> +#include <dpl/scoped_ptr.h> +#include <dpl/singleton_impl.h> +#include <Commons/Exception.h> +#include <nfc.h> +#include "NFCDefaultAdapter.h" +#include "NFCUtil.h" +#include <Logger.h> + + +IMPLEMENT_SINGLETON(DeviceAPI::NFC::NFCDefaultAdapter) + +namespace DeviceAPI { +namespace NFC { + +namespace +{ + static void TagDetectedCallback(nfc_discovered_type_e type, nfc_tag_h tag, void *data) { + LoggerD("Callback TagDetectedCallback."); + + if (data) { + if (NFC_DISCOVERED_TYPE_ATTACHED == type) { + (static_cast<NFCDefaultAdapter*>(data))->NFCTagHasDetected((void *)tag); + } else { + (static_cast<NFCDefaultAdapter*>(data))->NFCTagHasDetected(NULL); + } + } else { + LoggerE("Callback private data is NULL."); + } + + } + + static void TargetDetectedCallback(nfc_discovered_type_e type, nfc_p2p_target_h target, void *data) { + LoggerD("Callback TargetDetectedCallback."); + + if (data) { + if (NFC_DISCOVERED_TYPE_ATTACHED == type) { + (static_cast<NFCDefaultAdapter*>(data))->NFCTargetHasDetected((void *)target); + } else { + (static_cast<NFCDefaultAdapter*>(data))->NFCTargetHasDetected(NULL); + } + } else { + LoggerE("Callback private data is NULL."); + } + + } + + static void NFCSetActivationCompletedCallback(nfc_error_e error, void *user_data) { + LoggerD("Callback NFCSetActivationCompletedCallback."); + NFCDefaultAdapterSingleton::Instance().setPoweredManualAnswer(error); + } + +}//private namespace + +NFCDefaultAdapter::NFCDefaultAdapter() + :m_initialized(false) { + LoggerD("NFC Enter"); + + m_NFCTagListeners.clear(); + m_NFCTargetListeners.clear(); + m_poweredAdapter = NULL; +} + +NFCDefaultAdapter::~NFCDefaultAdapter() { + LoggerD("Enter"); + deinitialze(); +} + +void NFCDefaultAdapter::setExclusiveMode(bool mode) { + LoggerD("Enter"); + LoggerD("initilized:" << m_initialized); + if (!getPowerState()) + return; + if (!m_initialized) { + + if (initialize() != NFC_ERROR_NONE) { + ThrowMsg(UnknownException, "Could not initialize NFC."); + } + } + bool bEnabled = !mode; + LoggerD("system handeler enable?" << bEnabled); + // If exclusive mode is true, system handler has to be disabled. + if (nfc_manager_set_system_handler_enable(bEnabled) != NFC_ERROR_NONE) + ThrowMsg(UnknownException, "Failed to set exclusive mode."); + LoggerD("End"); +} + +bool NFCDefaultAdapter::isSupported() { + return nfc_manager_is_supported(); +} + +void NFCDefaultAdapter::deinitialze() { + LoggerD("Enter"); + int result = -1; + + m_NFCTagListeners.clear(); + m_NFCTargetListeners.clear(); + m_poweredAdapter = NULL; + + nfc_manager_unset_tag_discovered_cb(); + nfc_manager_unset_p2p_target_discovered_cb(); + + unsetExclusiveMode(); + + if(m_initialized == true) + { + result = nfc_manager_deinitialize (); + if (result !=NFC_ERROR_NONE) { + LoggerI("failed to deinitialize nfc"); + } + } + m_initialized = false; + + LoggerD("destroy nfc"); +} + +void NFCDefaultAdapter::unsetExclusiveMode() { + LoggerD("entered"); + if (getPowerState() && m_initialized) + if (nfc_manager_set_system_handler_enable(true) != NFC_ERROR_NONE) + LoggerD("failed to unset exclusive mode"); +} + +int NFCDefaultAdapter::setTagListener(NFCAdapter * adapter) { + LoggerD(" NFCDefaultAdapter::setTagListener Entered"); + int result = -1; + + m_NFCTagListeners.push_back(adapter); + + if (!m_initialized) { + if (initialize() != NFC_ERROR_NONE) { + m_NFCTagListeners.clear(); + ThrowMsg(PlatformException, "Could not initialize NFC."); + } + + } + + nfc_tag_h currentTag = NULL; + if ((nfc_manager_get_connected_tag(¤tTag) == NFC_ERROR_NONE) && currentTag) + adapter->NFCTagHasDetected((void *)currentTag); + + if (m_NFCTagListeners.size() > 1) + return 0; + + nfc_manager_set_tag_filter(NFC_TAG_FILTER_ALL_ENABLE); + result = nfc_manager_set_tag_discovered_cb (TagDetectedCallback, this); + + NFCUtil util; + if (result != NFC_ERROR_NONE) { + m_NFCTagListeners.pop_back(); + util.throwNFCException(result, "failed to set callback of nfc_manager_set_tag_discovered_cb"); + } + + LoggerI("NFCDefaultAdapter::setTagListener : result << " << result); + return result; +} + +int NFCDefaultAdapter::setPeerListener(NFCAdapter *adapter) { + LoggerD(" NFCDefaultAdapter::setPeerListener Entered"); + int result = -1; + + m_NFCTargetListeners.push_back(adapter); + + if (!m_initialized) { + if (initialize() != NFC_ERROR_NONE) { + m_NFCTargetListeners.clear(); + ThrowMsg(PlatformException, "Could not initialize NFC."); + } + } + + nfc_p2p_target_h currentTarget = NULL; + if ((nfc_manager_get_connected_target(¤tTarget) == NFC_ERROR_NONE) && currentTarget) + adapter->NFCTargetHasDetected((void *)currentTarget); + + if (m_NFCTargetListeners.size() > 1) + return 0; + + result = nfc_manager_set_p2p_target_discovered_cb (TargetDetectedCallback, this); + + NFCUtil Util; + if (result != NFC_ERROR_NONE) { + m_NFCTargetListeners.pop_back(); + Util.throwNFCException(result, "failed to set callback of nfc_manager_set_p2p_target_discovered_cb"); + } + + LoggerI("NFCDefaultAdapter::setPeerListener : result << " << result); + return result; +} + +void NFCDefaultAdapter::unsetTagListener(NFCAdapter * adapter) { + LoggerD(" NFCDefaultAdapter::unsetTagListener Entered"); + + if (!m_initialized) { + m_NFCTagListeners.clear(); + return; + } + + std::vector<NFCAdapter *>::iterator it; + for (it = m_NFCTagListeners.begin(); it != m_NFCTagListeners.end(); ++it) { + if (*it == adapter) { + m_NFCTagListeners.erase(it); + LoggerD("emitter is removed. (" << m_NFCTagListeners.size() << ")"); + break; + } + } + + if (m_NFCTagListeners.empty()) + nfc_manager_unset_tag_discovered_cb (); +} + +void NFCDefaultAdapter::unsetPeerListener(NFCAdapter * adapter) { + LoggerD(" NFCDefaultAdapter::unsetPeerListener Entered"); + + if (!m_initialized) { + m_NFCTargetListeners.clear(); + return; + } + + std::vector<NFCAdapter *>::iterator it; + for (it = m_NFCTargetListeners.begin(); it != m_NFCTargetListeners.end(); ++it) { + if (*it == adapter) { + m_NFCTargetListeners.erase(it); + LoggerD("emitter is removed. (" << m_NFCTargetListeners.size() << ")"); + break; + } + } + + if (m_NFCTargetListeners.empty()) + nfc_manager_unset_p2p_target_discovered_cb(); + +} + +void NFCDefaultAdapter::NFCTagHasDetected(void *props) +{ + LoggerD("NFCDefaultAdapter::NFCTagHasDetected Enter type"); + + std::vector<NFCAdapter *>::iterator it; + for (it = m_NFCTagListeners.begin(); it != m_NFCTagListeners.end(); ++it) { + (*it)->NFCTagHasDetected(props); + } +} + +void NFCDefaultAdapter::NFCTargetHasDetected(void *props) +{ + std::vector<NFCAdapter *>::iterator it; + for (it = m_NFCTargetListeners.begin(); it != m_NFCTargetListeners.end(); ++it) { + (*it)->NFCTargetHasDetected(props); + } +} + +int NFCDefaultAdapter::initialize() { + LoggerD("NFCDefaultAdapter::initialize Entered"); + + int result = nfc_manager_initialize_sync(); + if (result != NFC_ERROR_NONE) { + LoggerE("Could not initialize NFC."); + m_initialized = false; + } else { + m_initialized = true; + } + return result; +} + +void *NFCDefaultAdapter::getCachedMessage() { + LoggerD("Entered"); + nfc_ndef_message_h messageHandle = NULL; + int result = nfc_manager_get_cached_message(&messageHandle); + if ((result == NFC_ERROR_INVALID_NDEF_MESSAGE) || (result == NFC_ERROR_NO_NDEF_MESSAGE)) { + if (messageHandle) + nfc_ndef_message_destroy(messageHandle); + + return NULL; + } + + NFCUtil util; + if (result != NFC_ERROR_NONE) { + util.throwNFCException(result, "Can't get cached message"); + } + return (void *)(messageHandle); +} + +bool NFCDefaultAdapter::getPowerState() { + return nfc_manager_is_activated(); +} + +void NFCDefaultAdapter::setPowered(const bool state, NFCAdapter * poweredAdapter) { + LoggerD("Enter"); + try { + if (m_poweredAdapter != NULL) { + ThrowMsg(PlatformException, "Progressing Identical Operation"); + return; + } else if (getPowerState() == state) { + poweredAdapter->setPoweredManualAnswer(NFC_ERROR_NONE); + return; + } + + int result = NFC_ERROR_NONE; + if (!m_initialized) + result = initialize(); + + if (result == NFC_ERROR_NONE) { + m_poweredAdapter = poweredAdapter; + result = nfc_manager_set_activation(state, NFCSetActivationCompletedCallback, NULL); + } + + if (result != NFC_ERROR_NONE) { + poweredAdapter->setPoweredManualAnswer(result); + m_poweredAdapter = NULL; + } + } catch (const WrtDeviceApis::Commons::Exception& ex) { + LoggerE("Exception: " << ex.GetMessage()); + poweredAdapter->setPoweredManualAnswer(NFC_ERROR_OPERATION_FAILED); + m_poweredAdapter = NULL; + } +} + +void NFCDefaultAdapter::setPoweredManualAnswer(int error) { + if (m_poweredAdapter != NULL) { + m_poweredAdapter->setPoweredManualAnswer(error); + m_poweredAdapter = NULL; + } +} + + +} +} diff --git a/mobile_src/NFC/NFCDefaultAdapter.h b/mobile_src/NFC/NFCDefaultAdapter.h new file mode 100755 index 0000000..8e0f746 --- /dev/null +++ b/mobile_src/NFC/NFCDefaultAdapter.h @@ -0,0 +1,87 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NFCDEFAULTADAPTER_H_ +#define _NFCDEFAULTADAPTER_H_ + +#include <vector> +#include <dpl/shared_ptr.h> +#include <dpl/singleton.h> +#include <Commons/Emitters.h> + +#include "EventNFCChanged.h" +#include "NFCAdapter.h" + + +namespace DeviceAPI { +namespace NFC { +class NFCDefaultAdapter +{ + public: + NFCDefaultAdapter(); + virtual ~NFCDefaultAdapter(); + +public: + /** + * watchNFCTag + */ + int setTagListener(NFCAdapter* adapter); + int setPeerListener(NFCAdapter * adapter); + /** + * clearWatch + */ + void unsetTagListener(NFCAdapter * adapter); + void unsetPeerListener(NFCAdapter * adapter); + + void NFCTagHasDetected(void *props); + void NFCTargetHasDetected(void *props); + + void *getCachedMessage(); + + bool getPowerState(); + void setPowered(const bool state, NFCAdapter * adapter); + void setPoweredManualAnswer(int error); + + + void setExclusiveMode(bool mode); + void unsetExclusiveMode(); + bool isSupported(); + void deinitialze(); + /** + * Initialize NFC. + */ + int initialize(); + +private: + + std::vector<NFCAdapter *> m_NFCTagListeners; + std::vector<NFCAdapter *> m_NFCTargetListeners; + + NFCAdapter * m_poweredAdapter; + bool m_initialized; + + friend class DPL::Singleton<NFCDefaultAdapter>; + +}; +typedef DPL::Singleton<NFCDefaultAdapter> NFCDefaultAdapterSingleton; + +} +} + +#endif /* _NFCDEFAULTADAPTER_H_ */ diff --git a/mobile_src/NFC/NFCFactory.cpp b/mobile_src/NFC/NFCFactory.cpp new file mode 100755 index 0000000..cc85435 --- /dev/null +++ b/mobile_src/NFC/NFCFactory.cpp @@ -0,0 +1,91 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 "NFCFactory.h" + +#include "NFCAdapter.h" +#include "NdefMessage.h" +#include "NdefRecord.h" +#include "NdefRecordMedia.h" +#include "NdefRecordText.h" +#include "NdefRecordURI.h" +#include "NFCTag.h" +#include "NFCTarget.h" + +namespace DeviceAPI { +namespace NFC { + +INFCAdapterPtr NFCFactory::createNFCAdapterObject() { + return INFCAdapterPtr( new NFCAdapter() ); +} + +INdefMessagePtr NFCFactory::createNDEFMessageObject() { + return INdefMessagePtr( new NdefMessage() ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordObject() { + return INdefRecordPtr( new NdefRecord() ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordObject(std::vector<unsigned char> data) { + return INdefRecordPtr( new NdefRecord(data) ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordObject(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload, bool isValid) { + return INdefRecordPtr( new NdefRecord(ndefRecordProperties, payload, isValid) ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordTextObject(const std::string &text, const std::string &langCode, const nfcTextEncodeUTF encodeType, bool isValid) { + return INdefRecordPtr( new NdefRecordText(text, langCode, encodeType, isValid) ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordTextObject(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload) { + return INdefRecordPtr( new NdefRecordText(ndefRecordProperties, payload) ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordUriObject(const std::string &uri, bool isValid) { + return INdefRecordPtr( new NdefRecordUri(uri, isValid) ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordUriObject(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload) { + return INdefRecordPtr( new NdefRecordUri(ndefRecordProperties, payload) ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordMediaObject(const std::string &mimeType, const std::vector<unsigned char> data, bool isValid) { + return INdefRecordPtr( new NdefRecordMedia(mimeType, data, isValid) ); +} + +INdefRecordPtr NFCFactory::createNDEFRecordMediaObject(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload) { + return INdefRecordPtr( new NdefRecordMedia(ndefRecordProperties, payload) ); +} + +INFCTagPtr NFCFactory::createNFCTagObject(void *tagHandle) { + return INFCTagPtr( new NFCTag(tagHandle)); +} + +INFCTargetPtr NFCFactory::createNFCTargetObject(void *targetHandle) { + return INFCTargetPtr( new NFCTarget(targetHandle)); +} + +NFCFactory& NFCFactory::getInstance() { + static NFCFactory theInstance; + return theInstance; +} + +} +} diff --git a/mobile_src/NFC/NFCFactory.h b/mobile_src/NFC/NFCFactory.h new file mode 100755 index 0000000..b536ff4 --- /dev/null +++ b/mobile_src/NFC/NFCFactory.h @@ -0,0 +1,62 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_API_NFCFACTORY_H_ +#define WRTPLUGINS_API_NFCFACTORY_H_ + +#include <dpl/noncopyable.h> +#include "INFCAdapter.h" +#include "INdefMessage.h" +#include "INdefRecord.h" +#include "INFCTag.h" +#include "INFCTarget.h" + +namespace DeviceAPI { +namespace NFC { + +class NFCFactory : DPL::Noncopyable +{ +private: + /** + * Private constructor to provide singleton + */ + NFCFactory(){;} +public: + INFCAdapterPtr createNFCAdapterObject(); + INdefMessagePtr createNDEFMessageObject(); + INdefRecordPtr createNDEFRecordObject(); + INdefRecordPtr createNDEFRecordObject(std::vector<unsigned char> data); + INdefRecordPtr createNDEFRecordObject(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload, bool isValid = true); + INdefRecordPtr createNDEFRecordTextObject(const std::string &text, const std::string &langCode, const nfcTextEncodeUTF encodeType, bool isValid = true); + INdefRecordPtr createNDEFRecordTextObject(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload); + INdefRecordPtr createNDEFRecordUriObject(const std::string &uri, bool isValid = true); + INdefRecordPtr createNDEFRecordUriObject(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload); + INdefRecordPtr createNDEFRecordMediaObject(const std::string &mimeType, const std::vector<unsigned char> data, bool isValid = true); + INdefRecordPtr createNDEFRecordMediaObject(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload); + INFCTagPtr createNFCTagObject(void *tagHandle); + INFCTargetPtr createNFCTargetObject(void *targetHandle); + + static NFCFactory& getInstance(); + +}; + +} +} + +#endif //WRTPLUGINS_API_NFCFACTORY_H_ + diff --git a/mobile_src/NFC/NFCListenerManager.cpp b/mobile_src/NFC/NFCListenerManager.cpp new file mode 100755 index 0000000..45dc0a9 --- /dev/null +++ b/mobile_src/NFC/NFCListenerManager.cpp @@ -0,0 +1,29 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 "NFCListenerManager.h" +#include <dpl/singleton_impl.h> + + +IMPLEMENT_SINGLETON(DeviceAPI::NFC::NFCListenerManager) + +namespace DeviceAPI { +namespace NFC { + +} // NFC +} // DeviceAPI diff --git a/mobile_src/NFC/NFCListenerManager.h b/mobile_src/NFC/NFCListenerManager.h new file mode 100644 index 0000000..628df15 --- /dev/null +++ b/mobile_src/NFC/NFCListenerManager.h @@ -0,0 +1,113 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _TIZEN_NFC_LISTENER_MANAGER_H_ +#define _TIZEN_NFC_LISTENER_MANAGER_H_ + +#include <map> +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <dpl/singleton.h> +#include <IListenerManager.h> +#include "JSNFCAdapter.h" +#include "JSNFCTarget.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +enum NFCListenerWatchID { + ID_NFCADAPTER_TAG_LISTENER = 1, + ID_NFCADAPTER_PEER_LISTENER, + ID_NFCPEER_RECEIVENDEF_LISTENER, +}; + +class NFCListenerManager : public DeviceAPI::Common::IListenerController +{ +public: + NFCListenerManager() + { + } + + virtual ~NFCListenerManager() + { + } + +}; +typedef DPL::Singleton<NFCListenerManager> NFCListenerManagerSingleton; + +class NFCListenerCanceller : public DeviceAPI::Common::IListenerItem +{ +public: + NFCListenerCanceller(JSContextRef context, JSObjectRef object, long watchId) : + DeviceAPI::Common::IListenerItem(context, object, watchId) + { + } + + virtual ~NFCListenerCanceller() + { + } + + virtual void cancelListener() + { + LoggerD("context : " << m_context); + LoggerD("object : " << m_object); + switch(m_watchId) { + case ID_NFCPEER_RECEIVENDEF_LISTENER: + { + NFCTargetPrivObject* privateObject = static_cast<NFCTargetPrivObject*>(JSObjectGetPrivate(m_object)); + if (NULL == privateObject) { + LoggerW("Object has no privateObject"); + return; + } + + INFCTargetPtr nfcTarget(privateObject->getObject()); + nfcTarget->unsetReceiveNDEFListener(); + break; + } + case ID_NFCADAPTER_TAG_LISTENER: + case ID_NFCADAPTER_PEER_LISTENER: + { + NFCAdapterPrivObject* privateObject = static_cast<NFCAdapterPrivObject*>(JSObjectGetPrivate(m_object)); + if (NULL == privateObject) { + LoggerE("Object has no privateObject"); + return; + } + Try { + INFCAdapterPtr nfcAdapter( privateObject->getObject()); + if (ID_NFCADAPTER_TAG_LISTENER == m_watchId) + nfcAdapter->unsetTagListener(); + else + nfcAdapter->unsetPeerListener(); + } Catch(WrtDeviceApis::Commons::Exception) { + LoggerE("Error on platform : " << _rethrown_exception.GetMessage()); + } + break; + } + + default: + LoggerE("Wrong ID"); + } + } +}; +typedef DPL::SharedPtr<NFCListenerCanceller> NFCListenerCancellerPtr; + +} // NFC +} // DeviceAPI + +#endif // _TIZEN_NFC_LISTENER_MANAGER_H_
\ No newline at end of file diff --git a/mobile_src/NFC/NFCStaticController.cpp b/mobile_src/NFC/NFCStaticController.cpp new file mode 100755 index 0000000..38c6d98 --- /dev/null +++ b/mobile_src/NFC/NFCStaticController.cpp @@ -0,0 +1,136 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <dpl/shared_ptr.h> + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <Commons/IEvent.h> +#include <JSWebAPIErrorFactory.h> + +#include "NFCStaticController.h" +#include "EventNFCChangedPrivateData.h" +#include "JSNFCTag.h" +#include "JSNFCTarget.h" +#include "NFCConverter.h" +#include "NFCAsyncCallbackManager.h" +#include <Logger.h> + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace NFC { + +NFCStaticController& NFCStaticController::getInstance() { + static NFCStaticController controller; + return controller; +} + +NFCStaticController::NFCStaticController() : + EventNFCChangedListener(ThreadEnum::NULL_THREAD), + setPoweredAnswerReceiver(ThreadEnum::NULL_THREAD) { +} + +void NFCStaticController::onAnswerReceived(const EventNFCChangedPtr& event) { + LoggerD("onAnswerReceived Enter"); + + EventNFCChangedPrivateDataPtr privateData = + DPL::DynamicPointerCast<EventNFCChangedPrivateData>(event->getPrivateData()); + + void *nfcProp = event->getNFCProperties(); + + Try { + /** + *When received answer from platform, create an NFCTag JSObject and then call success function. + */ + if (nfcProp != NULL) { + JSObjectRef nfcObj; + JSCallbackManagerPtr callbackManager = privateData->getCallbackManager(); + JSContextRef context = callbackManager->getContext(); + + if (event->getNFCType() == NFC_TAG_TYPE) + nfcObj = JSNFCTag::createJSObject(context, nfcProp, privateData); + else + nfcObj = JSNFCTarget::createJSObject(context, nfcProp, privateData); + LoggerD("callOnSuccess"); + callbackManager->callOnSuccess(static_cast<JSValueRef>(nfcObj)); + } else { + JSCallbackManagerPtr detachedCallbackManager = privateData->getDetachedCallbackManager(); + + detachedCallbackManager->callOnSuccess(); + } + } Catch (ConversionException) { + LoggerE("Conversion exception while processing EventNFCChanged"); + } Catch (PlatformException) { + LoggerE("PlatformException:Platform can't create NFCTag" << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException:Platform can't create NFCTag" << _rethrown_exception.GetMessage()); + } Catch (NullPointerException) { + LoggerE("NullPointer exception while processing EventNFCChanged"); + } + +} + +void NFCStaticController::OnAnswerReceived(const EventNFCChangedSetPoweredPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + + Try { + if (!cbm) { + LoggerD("no callback manager"); + return; + } + NFCAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(cbm); + if (event->getResult()) { + LoggerD("result success"); + cbm->callOnSuccess(); + return; + } + LoggerD("result fail"); + std::string error = event->getError(); + std::string errorMessage = event->getErrorMessage(); + JSValueRef errorObject; + if (error != "") { + if (errorMessage != "") + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, errorMessage); + else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, error); + } else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } Catch (PlatformException) { + LoggerE("PlatformException" << _rethrown_exception.GetMessage()); + JSValueRef errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR,"Service Not Available"); + cbm->callOnError(errorObject); + } Catch (WrtDeviceApis::Commons::UnknownException) { + LoggerE("UnknownException" << _rethrown_exception.GetMessage()); + JSValueRef errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } Catch (Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + JSValueRef errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } +} + +} // NFC +} // DeviceAPI diff --git a/mobile_src/NFC/NFCStaticController.h b/mobile_src/NFC/NFCStaticController.h new file mode 100755 index 0000000..e7749a9 --- /dev/null +++ b/mobile_src/NFC/NFCStaticController.h @@ -0,0 +1,52 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_TIZEN_NFC_STATIC_CONTROLLER_H_ +#define WRTPLUGINS_TIZEN_NFC_STATIC_CONTROLLER_H_ + +#include <Commons/EventListener.h> +#include <Commons/EventReceiver.h> +#include"EventNFCChanged.h" + +namespace DeviceAPI { +namespace NFC { +using namespace WrtDeviceApis::Commons; +typedef EventListener<EventNFCChanged> EventNFCChangedListener; +typedef EventAnswerReceiver<EventNFCChangedSetPowered> setPoweredAnswerReceiver; + +class NFCStaticController : + public EventNFCChangedListener, + public setPoweredAnswerReceiver +{ +public: + static NFCStaticController& getInstance(); + + void onAnswerReceived(const EventNFCChangedPtr& event); + void OnAnswerReceived(const EventNFCChangedSetPoweredPtr &event); + +protected: + NFCStaticController(); +}; + + +} // NFC +} // DeviceAPI + +#endif /* WRTPLUGINS_TIZEN_NFC_STATIC_CONTROLLER_H_ */ + diff --git a/mobile_src/NFC/NFCTag.cpp b/mobile_src/NFC/NFCTag.cpp new file mode 100755 index 0000000..289684c --- /dev/null +++ b/mobile_src/NFC/NFCTag.cpp @@ -0,0 +1,440 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <Commons/Exception.h> +#include <JSWebAPIErrorFactory.h> + +#include "NFCTag.h" +#include "NFCUtil.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +namespace +{ + /** + * Callback method called by platform as interval time. + * @param event_type Platform magnetic evet type + * @param event Platform sensor event data + * @param this_ User data pointer. + */ + static bool TagInformationCallback(const char *key, const unsigned char *value, int value_size, void *user_data) { + LoggerD("Callback TagInformationCallback."); + if (user_data) { + NFCUtil util; + std::vector<unsigned char> tagInfo = util.toVector(value, (unsigned int)value_size); + (static_cast<NFCTag*>(user_data))->makeTagProperties(key, tagInfo); + return TRUE; + } + LoggerD("Error! TagInformationCallback is Null."); + return false; + } + + static void TagReadCallback(nfc_error_e result , nfc_ndef_message_h message , void * data) { + LoggerD("Callback TagReadCallback."); + if (data) { + NFCTag *tagPtr = (NFCTag *)((EventNFCPtrs<EventTagActionRead> *)data)->getThisPtr(); + if (tagPtr) { + EventTagActionReadPtr event = ((EventNFCPtrs<EventTagActionRead> *)data)->getEventPtrs(); + LoggerD("message handler :" << message); + + unsigned char *rawdata = NULL; + unsigned int size; + if (nfc_ndef_message_get_rawdata(message, &rawdata, &size) != NFC_ERROR_NONE) { + LoggerE("Can't get record's rawdata"); + if (rawdata) + free(rawdata); + return; + } + + NFCUtil util; + std::vector<unsigned char> readData = util.toVector(rawdata, size); + if (rawdata) + free(rawdata); + tagPtr->readNdefManualAnswer((int)result, readData, event); + } + + } else { + LoggerD("Error! TagReadCallback is Null."); + } + } + + static void TagWriteCallback(nfc_error_e result, void *data) { + LoggerD("Callback TagWriteCallback."); + if (data) { + ((NFCTag *)data)->writeNdefManualAnswer((int)result); + } else { + LoggerD("Error! TagWriteCallback is Null."); + } + } + + static void TagTransceiveCallback(nfc_error_e result, unsigned char *buffer, int buffer_size, void *data) { + LoggerD("Callback TagTransceiveCallback."); + if (data) { + NFCUtil util; + std::vector<unsigned char> responseData = util.toVector(buffer, (unsigned int)buffer_size) ; + ((NFCTag *)data)->transceiveManualAnswer((int)result, responseData); + } else { + LoggerD("Error! TagTransceiveCallback is Null."); + } + } + + static void TagFormatCallback(nfc_error_e result, void *data) { + LoggerD("Callback TagFormatCallback."); + if (data) { + ((NFCTag *)data)->formatManualAnswer((int)result); + } else { + LoggerD("Error! TagFormatCallback is Null."); + } + } +}//private namespace + +NFCTag::NFCTag(void *tagHandle) +{ + LoggerD("entered"); + + handle = (nfc_tag_h)tagHandle; + + m_EventTagActionWritePtr.Reset(); + m_EventTagActionTransceivePtr.Reset(); + m_EventTagActionFormatPtr.Reset(); +} + +NFCTag::~NFCTag() +{ + LoggerD("entered"); + handle = NULL; +} + +bool NFCTag::isConnected() { + nfc_tag_h curHandle = NULL; + if (nfc_manager_get_connected_tag(&curHandle) == NFC_ERROR_NONE) { + if (curHandle == handle) + return true; + } + return false; +} + +nfcTagType NFCTag::getTagType() { + nfc_tag_type_e type = NFC_UNKNOWN_TARGET; + int result = nfc_tag_get_type(handle, &type); + + NFCUtil util; + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't get tag Type"); + + return util.convertTonfcTagType(type); +} + +bool NFCTag::isNDEFSupport() { + bool isNDEF = FALSE; + int result = nfc_tag_is_support_ndef(handle, &isNDEF); + + NFCUtil util; + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't get if Ndef is supported"); + + return isNDEF; +} +long NFCTag::getNdefSize(){ + unsigned int ndefSize = 0; + int result = nfc_tag_get_ndef_size(handle, &ndefSize); + + NFCUtil util; + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't get Ndef size"); + + return static_cast<long>(ndefSize); +} +std::vector<NFCTagProperties> NFCTag::getProperties() { + LoggerD("Enter"); + props.clear(); + int result = nfc_tag_foreach_information(handle, TagInformationCallback, this); + + NFCUtil util; + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't get Ndef Properties"); + + return props; +} + +void NFCTag::makeTagProperties(const char *key, std::vector<unsigned char> &value) { + NFCTagProperties newProp; + newProp.key = key; + newProp.value = value; + props.push_back(newProp); +} + +void NFCTag::readNdef(const EventTagActionReadPtr& event) { + LoggerD("Enter"); + if (!isNDEFSupport()) + ThrowMsg(WrtDeviceApis::Commons::UnsupportedException, "Not Support NDEF"); + + EventRequestReceiver<EventTagActionRead>::PostRequest(event); +} + +void NFCTag::writeNdef(const EventTagActionWritePtr& event) { + LoggerD("Enter"); + if (!isNDEFSupport()) + ThrowMsg(WrtDeviceApis::Commons::UnsupportedException, "Not Support NDEF"); + + if (m_EventTagActionWritePtr.Get() != NULL) + EventTagActionWrites.push_back(event); + else + EventRequestReceiver<EventTagActionWrite>::PostRequest(event); + + return; +} + +void NFCTag::transceive(const EventTagActionTransceivePtr& event) { + LoggerD("Enter"); + + if (m_EventTagActionTransceivePtr.Get() != NULL) + EventTagActionTransceives.push_back(event); + else + EventRequestReceiver<EventTagActionTransceive>::PostRequest(event); +} + +void NFCTag::format(const EventTagActionFormatPtr& event) { + LoggerD("Enter"); + EventRequestReceiver<EventTagActionFormat>::PostRequest(event); +} + +void NFCTag::readNdefManualAnswer(int result, std::vector<unsigned char> &data, const EventTagActionReadPtr &event) +{ + LoggerD("Enter"); + if ((nfc_error_e)result == NFC_ERROR_NONE) { + event->setResult(TRUE); + event->setReadNdefResult(data); + } else { + NFCUtil util; + event->setResult(FALSE); + event->setError(util.getNFCErrorString(result)); + event->setErrorMessage(util.getNFCErrorMessage(result)); + } + EventRequestReceiver<EventTagActionRead>::ManualAnswer(event); + + std::vector<TagReadDataPtr>::iterator it; + for (it = EventTagActionsReads.begin(); it != EventTagActionsReads.end(); ++it) { + if ((*it)->getEventPtrs() == event) { + EventTagActionsReads.erase(it); + LoggerD("event is removed. (" << EventTagActionsReads.size() << ")"); + break; + } + } +} + +void NFCTag::writeNdefManualAnswer(int result) +{ + LoggerD("Enter"); + if (m_EventTagActionWritePtr.Get() != NULL) { + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagActionWritePtr->setResult(TRUE); + } else { + NFCUtil util; + m_EventTagActionWritePtr->setResult(FALSE); + m_EventTagActionWritePtr->setError(util.getNFCErrorString(result)); + m_EventTagActionWritePtr->setErrorMessage(util.getNFCErrorMessage(result)); + } + EventRequestReceiver<EventTagActionWrite>::ManualAnswer(m_EventTagActionWritePtr); + + m_EventTagActionWritePtr.Reset(); + if (EventTagActionWrites.size() > 0) { + EventTagActionWritePtr event = EventTagActionWrites.front(); + EventTagActionWrites.erase(EventTagActionWrites.begin()); + LoggerD("EventTagActionWrites is removed. (" << EventTagActionWrites.size() << ")"); + EventRequestReceiver<EventTagActionWrite>::PostRequest(event); + } + } +} + +void NFCTag::transceiveManualAnswer(int result , std::vector<unsigned char> &data) +{ + LoggerD("Enter"); + if (m_EventTagActionTransceivePtr.Get() != NULL) { + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagActionTransceivePtr->setResult(TRUE); + m_EventTagActionTransceivePtr->setTransceiveBuffer(data); + } else { + NFCUtil util; + m_EventTagActionTransceivePtr->setResult(FALSE); + m_EventTagActionTransceivePtr->setError(util.getNFCErrorString(result)); + m_EventTagActionTransceivePtr->setErrorMessage(util.getNFCErrorMessage(result)); + } + EventRequestReceiver<EventTagActionTransceive>::ManualAnswer(m_EventTagActionTransceivePtr); + + m_EventTagActionTransceivePtr.Reset(); + if (EventTagActionTransceives.size() > 0) { + EventTagActionTransceivePtr event = EventTagActionTransceives.front(); + EventTagActionTransceives.erase(EventTagActionTransceives.begin()); + LoggerD("EventTagActionWrites is removed. (" << EventTagActionTransceives.size() << ")"); + EventRequestReceiver<EventTagActionTransceive>::PostRequest(event); + } + } +} + +void NFCTag::formatManualAnswer(int result) +{ + LoggerD("Enter"); + if (m_EventTagActionFormatPtr.Get() != NULL) { + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTagActionFormatPtr->setResult(TRUE); + } else { + NFCUtil util; + m_EventTagActionFormatPtr->setResult(FALSE); + m_EventTagActionFormatPtr->setError(util.getNFCErrorString(result)); + m_EventTagActionFormatPtr->setErrorMessage(util.getNFCErrorMessage(result)); + } + EventRequestReceiver<EventTagActionFormat>::ManualAnswer(m_EventTagActionFormatPtr); + m_EventTagActionFormatPtr.Reset(); + } +} + +void NFCTag::OnRequestReceived(const EventTagActionReadPtr& event) { + LoggerD("Enter"); + + try { + event->switchToManualAnswer(); + + TagReadDataPtr data( new EventNFCPtrs<EventTagActionRead>(event, this)); + EventTagActionsReads.push_back(data); + int result = nfc_tag_read_ndef(handle, TagReadCallback, data.Get()); + + NFCUtil util; + std::string error = util.getNFCErrorString(result); + if (error != "") { + event->setResult(false); + event->setError(error); + event->setErrorMessage(util.getNFCErrorMessage(result)); + EventRequestReceiver<EventTagActionRead>::ManualAnswer(event); + + std::vector<TagReadDataPtr>::iterator it; + for (it = EventTagActionsReads.begin(); it != EventTagActionsReads.end(); ++it) { + if ((*it)->getEventPtrs() == event) { + EventTagActionsReads.erase(it); + LoggerD("event is removed. (" << EventTagActionsReads.size() << ")"); + break; + } + } + } + } + catch (const WrtDeviceApis::Commons::Exception& ex) { + LoggerE("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver<EventTagActionRead>::ManualAnswer(event); + } + +} + +void NFCTag::OnRequestReceived(const EventTagActionWritePtr& event) { + try { + event->switchToManualAnswer(); + + m_EventTagActionWritePtr = event; + + int result = nfc_tag_write_ndef(handle, (nfc_ndef_message_h)event->getNdefForWriting(),TagWriteCallback, this); + + NFCUtil util; + std::string error = util.getNFCErrorString(result); + if (error != "") { + writeNdefManualAnswer(result); + } + } + catch (const WrtDeviceApis::Commons::Exception& ex) { + LoggerE("Exception: " << ex.GetMessage()); + + if (event != m_EventTagActionWritePtr) + m_EventTagActionWritePtr = event; + writeNdefManualAnswer(NFC_ERROR_OPERATION_FAILED); + } +} + +void NFCTag::OnRequestReceived(const EventTagActionTransceivePtr& event) { + NFCUtil util; + try { + event->switchToManualAnswer(); + + m_EventTagActionTransceivePtr = event; + + unsigned char *buffer = util.toCharPtr(event->getTransceiveBuffer()); + int result = nfc_tag_transceive(handle, buffer, event->getTransceiveBufferSize(), TagTransceiveCallback, this); + + if (buffer) + free(buffer); + + std::string error = util.getNFCErrorString(result); + if (error != "") { + std::vector<unsigned char> emptyData; + transceiveManualAnswer(result, emptyData); + } + } + catch (const WrtDeviceApis::Commons::Exception& ex) { + LoggerE("Exception: " << ex.GetMessage()); + + std::vector<unsigned char> emptyData; + transceiveManualAnswer(NFC_ERROR_OPERATION_FAILED, emptyData); + } + +} + +void NFCTag::OnRequestReceived(const EventTagActionFormatPtr& event) { + + try { + event->switchToManualAnswer(); + + if (m_EventTagActionFormatPtr.Get() != NULL) { + event->setResult(false); + event->setError(DeviceAPI::Common::JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR); + event->setErrorMessage("Progressing Identical Operation"); + EventRequestReceiver<EventTagActionFormat>::ManualAnswer(event); + return; + } + m_EventTagActionFormatPtr = event; + + NFCUtil util; + LoggerD("key size :" << event->getKeySize()); + + unsigned char *key = util.toCharPtr(event->getKey()); + int result = nfc_tag_format_ndef(handle, key, event->getKeySize(), TagFormatCallback, this); + + if (key) + free(key); + + std::string error = util.getNFCErrorString(result); + if (error != "") { + event->setResult(false); + event->setError(error); + event->setErrorMessage(util.getNFCErrorMessage(result)); + EventRequestReceiver<EventTagActionFormat>::ManualAnswer(event); + m_EventTagActionFormatPtr.Reset(); + } + } + catch (const WrtDeviceApis::Commons::Exception& ex) { + LoggerE("Exception: " << ex.GetMessage()); + event->setResult(false); + + EventRequestReceiver<EventTagActionFormat>::ManualAnswer(event); + m_EventTagActionFormatPtr.Reset(); + } + +} + + +} +} diff --git a/mobile_src/NFC/NFCTag.h b/mobile_src/NFC/NFCTag.h new file mode 100755 index 0000000..b3cb970 --- /dev/null +++ b/mobile_src/NFC/NFCTag.h @@ -0,0 +1,77 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NFCTAG_H_ +#define _NFCTAG_H_ + +#include "INFCTag.h" +#include <nfc.h> + + + +namespace DeviceAPI { +namespace NFC { +typedef DPL::SharedPtr<EventNFCPtrs<EventTagActionRead>> TagReadDataPtr; + +class NFCTag : public INFCTag +{ + friend class NFCFactory; + public: + NFCTag(void *tagHandle); + virtual ~NFCTag(); + + virtual bool isConnected(); + virtual nfcTagType getTagType(); + virtual bool isNDEFSupport(); + virtual long getNdefSize(); + virtual std::vector<NFCTagProperties> getProperties(); + virtual void readNdef(const EventTagActionReadPtr& event); + virtual void writeNdef(const EventTagActionWritePtr& event); + virtual void transceive(const EventTagActionTransceivePtr& event); + virtual void format(const EventTagActionFormatPtr& event); + + void readNdefManualAnswer(int result , std::vector<unsigned char> &data, const EventTagActionReadPtr &event); + void writeNdefManualAnswer(int result ); + void transceiveManualAnswer(int result , std::vector<unsigned char> &data); + void formatManualAnswer(int result); + + void makeTagProperties(const char *key, std::vector<unsigned char> &value); + private: + EventTagActionWritePtr m_EventTagActionWritePtr; + EventTagActionTransceivePtr m_EventTagActionTransceivePtr; + EventTagActionFormatPtr m_EventTagActionFormatPtr; + + std::vector<TagReadDataPtr> EventTagActionsReads; + std::vector<EventTagActionWritePtr> EventTagActionWrites; + std::vector<EventTagActionTransceivePtr> EventTagActionTransceives; + + protected: + nfc_tag_h handle; + std::vector<NFCTagProperties> props; + virtual void OnRequestReceived(const EventTagActionReadPtr& event); + virtual void OnRequestReceived(const EventTagActionWritePtr& event); + virtual void OnRequestReceived(const EventTagActionTransceivePtr& event); + virtual void OnRequestReceived(const EventTagActionFormatPtr& event); +}; + + +} +} + +#endif /* _NFCTAG_H_ */ diff --git a/mobile_src/NFC/NFCTagProperties.h b/mobile_src/NFC/NFCTagProperties.h new file mode 100755 index 0000000..b6e2ed3 --- /dev/null +++ b/mobile_src/NFC/NFCTagProperties.h @@ -0,0 +1,46 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_API_NFC_NFCTAG_PROPERTIES_H_ +#define WRTPLUGINS_API_NFC_NFCTAG_PROPERTIES_H_ + +#include <dpl/shared_ptr.h> +#include <vector> +#include <string> + +namespace DeviceAPI { +namespace NFC { + +struct NFCTagProperties +{ + std::string key ; + std::vector<unsigned char> value ; + NFCTagProperties() + : key("") + { + } +}; + + +typedef DPL::SharedPtr<NFCTagProperties> NFCTagPropertiesPtr; + +} // NFC +} // DeviceAPI + +#endif //WRTPLUGINS_API_NFC_NFCTAG_PROPERTIES_H_
\ No newline at end of file diff --git a/mobile_src/NFC/NFCTarget.cpp b/mobile_src/NFC/NFCTarget.cpp new file mode 100755 index 0000000..b449dfd --- /dev/null +++ b/mobile_src/NFC/NFCTarget.cpp @@ -0,0 +1,192 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <Commons/Exception.h> +#include "NFCTarget.h" +#include "NFCUtil.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +using namespace WrtDeviceApis; + +namespace +{ + /** + * Callback method called by platform as interval time. + * @param event_type Platform magnetic evet type + * @param event Platform sensor event data + * @param this_ User data pointer. + */ + static void TargetReceivedCallback(nfc_p2p_target_h target, nfc_ndef_message_h message, void *user_data) { + LoggerD("Callback TargetReceivedCallback."); + if (user_data) { + unsigned char *rawdata = NULL; + unsigned int size; + if (nfc_ndef_message_get_rawdata(message, &rawdata, &size) != NFC_ERROR_NONE) { + LoggerE("Can't get rawdata of message"); + if (rawdata) + free(rawdata); + return; + } + + NFCUtil util; + std::vector<unsigned char> receiveData = util.toVector(rawdata, size); + if (rawdata) + free(rawdata); + ((NFCTarget *)user_data)->receiveNdef(receiveData); + } else { + LoggerD("Error! TargetReceivedCallback is Null."); + } + } + + static void TargetSentCallback(nfc_error_e result, void *user_data) { + LoggerD("Callback TargetSentCallback."); + if (user_data) { + ((NFCTarget *)user_data)->sendNDEFManualAnswer((unsigned int)result); + + } else { + LoggerD("Error! TargetSentCallback is Null."); + } + } +}//private namespace + +NFCTarget::NFCTarget(void *targetHandle) +{ + LoggerD("entered"); + + if (targetHandle == NULL) + ThrowMsg(Commons::UnknownException, "Target Handler is Null Pointer."); + + handle = (nfc_p2p_target_h)targetHandle; + LoggerD("handle:"<<targetHandle); + m_isSetReceiveListenter = false; + m_EventTargetActionSendPtr.Reset(); +} + +NFCTarget::~NFCTarget() +{ + LoggerD("entered"); + handle = NULL; +} + +bool NFCTarget::isConnected() { + nfc_p2p_target_h curHandle = NULL; + if (nfc_manager_get_connected_target(&curHandle) == NFC_ERROR_NONE) { + if (curHandle == handle) + return true; + } + return false; +} + +void NFCTarget::setReceiveNDEFListener(const EventTargetActionReceiveEmitterPtr& event) { + LoggerD("Enter"); + if (m_isSetReceiveListenter == true) + ThrowMsg(Commons::AlreadyInUseException, "Already set Listener"); + + m_emitter = event; + m_isSetReceiveListenter = true; + + int result = nfc_p2p_set_data_received_cb(handle, TargetReceivedCallback, this); + + NFCUtil util; + if (result != NFC_ERROR_NONE) { + m_isSetReceiveListenter = false; + util.throwNFCException(result, "Can't set Receive Ndef Listener"); + } +} + +void NFCTarget::receiveNdef(std::vector<unsigned char>&messageData) { + LoggerD("Enter"); + if ((m_isSetReceiveListenter == true) && (m_emitter.Get() != NULL)) { + EventTargetActionReceivePtr event(new EventTargetActionReceive()); + event->setReadNdefResult(messageData); + m_emitter->emit(event); + } +} + +void NFCTarget::unsetReceiveNDEFListener() { + LoggerD("Enter"); + if (m_isSetReceiveListenter == true) { + nfc_p2p_unset_data_received_cb(handle); + LoggerD("Success to unset Listener"); + } else { + LoggerD("No set Listener"); + } + m_isSetReceiveListenter = false; +} + +void NFCTarget::sendNDEF(const EventTargetActionSendPtr& event) { + LoggerD("Enter"); + + if (m_EventTargetActionSendPtr.Get() != NULL) + m_EventTargetActionSends.push_back(event); + else + EventRequestReceiver<EventTargetActionSend>::PostRequest(event); + + return; +} + +void NFCTarget::sendNDEFManualAnswer(unsigned int result) { + LoggerD("Enter"); + if (m_EventTargetActionSendPtr.Get() != NULL) { + if ((nfc_error_e)result == NFC_ERROR_NONE) { + m_EventTargetActionSendPtr->setResult(TRUE); + } else { + NFCUtil util; + m_EventTargetActionSendPtr->setResult(FALSE); + m_EventTargetActionSendPtr->setError(util.getNFCErrorString(result)); + m_EventTargetActionSendPtr->setErrorMessage(util.getNFCErrorMessage(result)); + } + EventRequestReceiver<EventTargetActionSend>::ManualAnswer(m_EventTargetActionSendPtr); + + m_EventTargetActionSendPtr.Reset(); + + if (m_EventTargetActionSends.size() > 0) { + EventTargetActionSendPtr event = m_EventTargetActionSends.front(); + m_EventTargetActionSends.erase(m_EventTargetActionSends.begin()); + LoggerD("m_EventTargetActionSends is removed. (" << m_EventTargetActionSends.size() << ")"); + EventRequestReceiver<EventTargetActionSend>::PostRequest(event); + } + } +} + +void NFCTarget::OnRequestReceived(const EventTargetActionSendPtr& event) { + LoggerD("Enter"); + try { + event->switchToManualAnswer(); + m_EventTargetActionSendPtr = event; + + nfc_ndef_message_h message = (nfc_ndef_message_h)event->getMessageForSending(); + int result = nfc_p2p_send(handle, message, TargetSentCallback, this); + + NFCUtil util; + std::string error = util.getNFCErrorString(result); + if (error != "") { + sendNDEFManualAnswer(result); + } + } catch (const Commons::Exception& ex) { + LoggerE("Exception: " << ex.GetMessage()); + if (event != m_EventTargetActionSendPtr) + m_EventTargetActionSendPtr = event; + sendNDEFManualAnswer(NFC_ERROR_OPERATION_FAILED); + } +} + +} +} diff --git a/mobile_src/NFC/NFCTarget.h b/mobile_src/NFC/NFCTarget.h new file mode 100755 index 0000000..b9a3a11 --- /dev/null +++ b/mobile_src/NFC/NFCTarget.h @@ -0,0 +1,57 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NFCTARGET_H_ +#define _NFCTARGET_H_ + +#include "INFCTarget.h" +#include <nfc.h> + + + +namespace DeviceAPI { +namespace NFC { + +class NFCTarget : public INFCTarget +{ + friend class NFCFactory; + public: + NFCTarget(void *tagHandle); + virtual ~NFCTarget(); + + virtual bool isConnected(); + virtual void setReceiveNDEFListener(const EventTargetActionReceiveEmitterPtr& event); + void receiveNdef(std::vector<unsigned char>&messageData); + virtual void unsetReceiveNDEFListener(); + virtual void sendNDEF(const EventTargetActionSendPtr& event); + void sendNDEFManualAnswer(unsigned int result); + protected: + nfc_p2p_target_h handle; + EventTargetActionReceiveEmitterPtr m_emitter; + bool m_isSetReceiveListenter; + EventTargetActionSendPtr m_EventTargetActionSendPtr; + std::vector<EventTargetActionSendPtr> m_EventTargetActionSends; + virtual void OnRequestReceived(const EventTargetActionSendPtr& event); +}; + + +} +} + +#endif /* _NFCTARGET_H_ */ diff --git a/mobile_src/NFC/NFCUtil.cpp b/mobile_src/NFC/NFCUtil.cpp new file mode 100755 index 0000000..a92cb0a --- /dev/null +++ b/mobile_src/NFC/NFCUtil.cpp @@ -0,0 +1,293 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <Commons/Exception.h> +#include <nfc.h> +#include <JSWebAPIErrorFactory.h> +#include "NFCUtil.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +std::vector<unsigned char> NFCUtil::toVector(const unsigned char *ch, const unsigned int size) { + std::vector<unsigned char> vec; + if (ch && (size > 0)) { + unsigned int i; + + for (i = 0; i < size; i++) + vec.push_back(ch[i]); + + LoggerD("result:" << byteToString(ch, size)); + } else + LoggerD("result: NULL"); + return vec; +} + +unsigned char *NFCUtil::toCharPtr(std::vector<unsigned char> vec) { + if (vec.size() > 0) { + unsigned char * chr = (unsigned char *) malloc(vec.size() * sizeof(unsigned char)); + for (int i = 0; i < static_cast<int>(vec.size()); i++) + chr[i] = vec.at(i); + + return chr; + } + + return NULL; +} + +char *NFCUtil::byteToString(std::vector<unsigned char> *buffer){ + static char localbuffer[256]; + memset(localbuffer, 0, 256); + if (buffer->size() > 0) { + unsigned char *charBuf = toCharPtr(*buffer); + if (charBuf) { + if (buffer->size() > 255) { + memcpy(localbuffer, charBuf, 255); + LoggerD("size is " << buffer->size() << ". Too Big! It will copy some of data(255 bytes)"); + } else + memcpy(localbuffer, charBuf, buffer->size()); + + free(charBuf); + } else + LoggerD("Size is 0"); + } else + LoggerD("Size is 0"); + return localbuffer; +} + +char *NFCUtil::byteToString(const unsigned char* buffer, const int size){ + if (size > 255) + LoggerD("size is " << size << ". Too Big! It will copy some of data(255 bytes)"); + + static char localbuffer[256]; + memset(localbuffer, 0, 256); + if ((size > 0) && buffer) + memcpy(localbuffer, buffer, size > 255 ? 255 : size); + else + LoggerD("Size is 0"); + return localbuffer; +} + +nfcTagType NFCUtil::convertTonfcTagType(const unsigned short type) { + switch (static_cast<nfc_tag_type_e>(type)) { + case NFC_GENERIC_PICC: + return NFC_TAGTYPE_GENERIC_PICC; + case NFC_ISO14443_A_PICC: + return NFC_TAGTYPE_ISO14443_A_PICC; + case NFC_ISO14443_4A_PICC: + return NFC_TAGTYPE_ISO14443_4A_PICC; + case NFC_ISO14443_3A_PICC: + return NFC_TAGTYPE_ISO14443_3A_PICC; + case NFC_MIFARE_MINI_PICC: + return NFC_TAGTYPE_MIFARE_MINI_PICC; + case NFC_MIFARE_1K_PICC: + return NFC_TAGTYPE_MIFARE_1K_PICC; + case NFC_MIFARE_4K_PICC: + return NFC_TAGTYPE_MIFARE_4K_PICC; + case NFC_MIFARE_ULTRA_PICC: + return NFC_TAGTYPE_MIFARE_ULTRA_PICC; + case NFC_MIFARE_DESFIRE_PICC: + return NFC_TAGTYPE_MIFARE_DESFIRE_PICC; + case NFC_ISO14443_B_PICC: + return NFC_TAGTYPE_ISO14443_B_PICC; + case NFC_ISO14443_4B_PICC: + return NFC_TAGTYPE_ISO14443_4B_PICC; + case NFC_ISO14443_BPRIME_PICC: + return NFC_TAGTYPE_ISO14443_BPRIME_PICC; + case NFC_FELICA_PICC: + return NFC_TAGTYPE_FELICA_PICC; + case NFC_JEWEL_PICC: + return NFC_TAGTYPE_JEWEL_PICC; + case NFC_ISO15693_PICC: + return NFC_TAGTYPE_ISO15693_PICC; + case NFC_UNKNOWN_TARGET: + default : + return NFC_TAGTYPE_UNKNOWN_TARGET; + } +} + +void *NFCUtil::makeNDEFRecord(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload) { + LoggerD("entered"); + + if ((ndefRecordProperties.tnf < 0) || (ndefRecordProperties.tnf > 6)) + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "Not Supported tnf"); + + nfc_ndef_record_h handle = NULL; + + unsigned char *recordPayload = toCharPtr(payload); + unsigned int payloadSize = payload.size(); + unsigned char *typeName = toCharPtr(ndefRecordProperties.typeName); + int typeSize = (static_cast<int>(ndefRecordProperties.typeName.size()) > 255) ? 255 : static_cast<int>(ndefRecordProperties.typeName.size()); + unsigned char *id = toCharPtr(ndefRecordProperties.id); + int idSize = (static_cast<int>(ndefRecordProperties.id.size()) > 255) ? 255 : static_cast<int>(ndefRecordProperties.id.size()); + + int result = nfc_ndef_record_create(&handle, static_cast<nfc_record_tnf_e>(ndefRecordProperties.tnf), typeName, typeSize, + id, idSize, recordPayload, payloadSize) ; + + if (recordPayload) + free(recordPayload); + if (typeName) + free(typeName); + if (id) + free(id); + + if (result != NFC_ERROR_NONE) { + if (handle) + nfc_ndef_record_destroy(handle); + throwNFCException(result, " Can't create Ndef Record"); + } else if (!handle) + ThrowMsg(PlatformException, " Can't create Ndef Record"); + return (void *)handle; + +} + +NdefRecordData NFCUtil::getNDEFRecordData(void *handle) { + if (!handle) + ThrowMsg(PlatformException, "Invalid NDEFRecord"); + + nfc_ndef_record_h recordHandle = static_cast<nfc_ndef_record_h>(handle); + + NdefRecordData recordData; + + nfc_record_tnf_e tnf; + unsigned char *typeName = NULL, *id = NULL, *payload = NULL; + int typeSize = 0, idSize = 0; + unsigned int payloadSize = 0; + + int result = nfc_ndef_record_get_tnf(recordHandle, &tnf); + throwNFCException(result, "Can't get record's tnf"); + + result = nfc_ndef_record_get_type(recordHandle, &typeName, &typeSize); + throwNFCException(result, "Can't get record's type"); + + result = nfc_ndef_record_get_id(recordHandle, &id, &idSize); + throwNFCException(result, "Can't get record's id"); + + result = nfc_ndef_record_get_payload(recordHandle, &payload, &payloadSize); + throwNFCException(result, "Can't get record's payload"); + + LoggerD("tnf : " <<tnf); + LoggerD("typeName : " << byteToString(typeName, typeSize)); + LoggerD("payload : " << byteToString(payload, payloadSize)); + + recordData.properties.tnf = static_cast<short>(tnf); + recordData.properties.typeName = toVector(typeName, (unsigned int)typeSize); + recordData.properties.id = toVector(id, (unsigned int)idSize); + recordData.payload = toVector(payload, payloadSize); + + return recordData; +} + +std::string NFCUtil::getNFCErrorString(const int errorCode) { + LoggerD ("Errorcode : " << errorCode); + switch(errorCode) { + case NFC_ERROR_NONE: + case NFC_ERROR_ALREADY_ACTIVATED: + case NFC_ERROR_ALREADY_DEACTIVATED: + return ""; + case NFC_ERROR_INVALID_PARAMETER: + case NFC_ERROR_INVALID_NDEF_MESSAGE: + case NFC_ERROR_INVALID_RECORD_TYPE: + return DeviceAPI::Common::JSWebAPIErrorFactory::INVALID_VALUES_ERROR; + case NFC_ERROR_NO_DEVICE: + case NFC_ERROR_OUT_OF_MEMORY: + case NFC_ERROR_OPERATION_FAILED: + case NFC_ERROR_DEVICE_BUSY: + return DeviceAPI::Common::JSWebAPIErrorFactory::UNKNOWN_ERROR; + case NFC_ERROR_NOT_ACTIVATED: + return DeviceAPI::Common::JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR; + case NFC_ERROR_NOT_SUPPORTED: + return DeviceAPI::Common::JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR; + case NFC_ERROR_TIMED_OUT: + return DeviceAPI::Common::JSWebAPIErrorFactory::TIMEOUT_ERROR; + } + return DeviceAPI::Common::JSWebAPIErrorFactory::UNKNOWN_ERROR; +} + +std::string NFCUtil::getNFCErrorMessage(const int errorCode) { + LoggerD ("Errorcode : " << errorCode); + switch(errorCode) { + case NFC_ERROR_NONE: + case NFC_ERROR_ALREADY_ACTIVATED: + case NFC_ERROR_ALREADY_DEACTIVATED: + return ""; + case NFC_ERROR_INVALID_PARAMETER: + return "Invalid Parameter"; + case NFC_ERROR_INVALID_NDEF_MESSAGE: + return "Invalid NDEF Message"; + case NFC_ERROR_INVALID_RECORD_TYPE: + return "Invalid Record Type"; + case NFC_ERROR_NO_DEVICE: + return "No Device"; + case NFC_ERROR_OUT_OF_MEMORY: + return "Out Of Memory"; + case NFC_ERROR_NOT_SUPPORTED: + return "NFC Not Supported"; + case NFC_ERROR_OPERATION_FAILED: + return "Operation Failed"; + case NFC_ERROR_DEVICE_BUSY: + return "Device Busy"; + case NFC_ERROR_NOT_ACTIVATED: + return "NFC Not Activated"; + case NFC_ERROR_TIMED_OUT: + return "Time Out"; + case NFC_ERROR_READ_ONLY_NDEF: + return "Read Only NDEF"; + case NFC_ERROR_NO_SPACE_ON_NDEF: + return "No Space On NDEF"; + case NFC_ERROR_NO_NDEF_MESSAGE: + return "No NDEF Message"; + case NFC_ERROR_NOT_NDEF_FORMAT: + return "Not NDEF Format"; + case NFC_ERROR_SECURITY_RESTRICTED: + return "Security Restricted"; + } + return "UnknownError"; +} + +void NFCUtil::throwNFCException(const int errorCode, const std::string &message) { + LoggerD ("Errorcode : " << static_cast<unsigned int>(errorCode)); + + switch(errorCode) { + case NFC_ERROR_NONE: + return; + case NFC_ERROR_INVALID_PARAMETER: + case NFC_ERROR_INVALID_NDEF_MESSAGE: + case NFC_ERROR_INVALID_RECORD_TYPE: + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, message); + break; + case NFC_ERROR_NOT_ACTIVATED: + ThrowMsg(WrtDeviceApis::Commons::PlatformException, message); + break; + case NFC_ERROR_SECURITY_RESTRICTED: + ThrowMsg(WrtDeviceApis::Commons::SecurityException, message); + break; + case NFC_ERROR_NOT_SUPPORTED: + case NFC_ERROR_OPERATION_FAILED: + case NFC_ERROR_DEVICE_BUSY: + case NFC_ERROR_NO_DEVICE: + case NFC_ERROR_TIMED_OUT: + case NFC_ERROR_OUT_OF_MEMORY: + default: + ThrowMsg(WrtDeviceApis::Commons::UnknownException, message); + break; + } +} + +} +} diff --git a/mobile_src/NFC/NFCUtil.h b/mobile_src/NFC/NFCUtil.h new file mode 100755 index 0000000..60b2551 --- /dev/null +++ b/mobile_src/NFC/NFCUtil.h @@ -0,0 +1,53 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NFCUTIL_H_ +#define _NFCUTIL_H_ + +#include <vector> +#include "NdefRecordProperties.h" +#include "EventNFCChanged.h" +#include "INFCTag.h" + + +namespace DeviceAPI { +namespace NFC { + +class NFCUtil +{ + + public: + NFCUtil() {} + virtual ~NFCUtil() {} + std::vector<unsigned char> toVector(const unsigned char *ch, const unsigned int size); + unsigned char *toCharPtr(std::vector<unsigned char> vec) ; + char *byteToString(const unsigned char* buffer, const int size); + char *byteToString(std::vector<unsigned char> *buffer); + nfcTagType convertTonfcTagType(const unsigned short type); + NdefRecordData getNDEFRecordData(void *handle); + std::string getNFCErrorString(const int errorCode); + std::string getNFCErrorMessage(const int errorCode); + void throwNFCException(const int errorCode, const std::string &message); + void *makeNDEFRecord(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload); +}; + +} +} + +#endif /* _NFCUTIL_H_ */ diff --git a/mobile_src/NFC/NdefMessage.cpp b/mobile_src/NFC/NdefMessage.cpp new file mode 100755 index 0000000..d7bb0eb --- /dev/null +++ b/mobile_src/NFC/NdefMessage.cpp @@ -0,0 +1,168 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <Commons/Exception.h> +#include "NdefMessage.h" +#include "NFCUtil.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +using namespace WrtDeviceApis::Commons; + +NdefMessage::NdefMessage() +{ + LoggerD("entered"); +} + +NdefMessage::~NdefMessage() +{ + LoggerD("entered"); +} + +void *NdefMessage::makeNdefMessageHandle(std::vector<void *> &ndefRcords) { + NFCUtil util; + if (ndefRcords.size() == 0) + return NULL; + + nfc_ndef_message_h message = NULL; + int result = nfc_ndef_message_create(&message); + + if (result != NFC_ERROR_NONE) { + LoggerE(util.getNFCErrorMessage(result)); + if (message) + nfc_ndef_message_destroy(message); + util.throwNFCException(result, "Can't create Ndef Message"); + } else if (!message) { + LoggerE("No Message Handle"); + ThrowMsg(PlatformException, "Can't create Ndef Message"); + } + + for (int i = 0 ; i < static_cast<int>(ndefRcords.size()); i++) { + if ((message == NULL) && (ndefRcords[i] != NULL)) + nfc_ndef_record_destroy((nfc_ndef_record_h)ndefRcords[i]); + result = nfc_ndef_message_append_record(message, (nfc_ndef_record_h)ndefRcords[i]); + + if (result != NFC_ERROR_NONE) { + LoggerE(i << " record can't be inserted. " << ndefRcords[i] << " : " << message); + if (message) + nfc_ndef_message_destroy(message); + message = NULL; + } + } + + return (void *)message; +} + +std::vector<unsigned char> NdefMessage::toByte(std::vector<void *> &ndefRcords) { + NFCUtil util; + if (ndefRcords.size() == 0) + return util.toVector(NULL, 0); + + nfc_ndef_message_h message = (nfc_ndef_message_h)makeNdefMessageHandle(ndefRcords); + if (message == NULL) + ThrowMsg(ConversionException, "Invalid NDEF Message"); + unsigned char *rawdata = NULL; + unsigned int size = 0; + int result = nfc_ndef_message_get_rawdata(message, &rawdata, &size); + + std::vector<unsigned char> byteData = util.toVector(rawdata, size); + + if (message) + nfc_ndef_message_destroy(message); + if (rawdata) + free(rawdata); + + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't get serial bytes of NDEF message"); + + return byteData; +} + +std::vector<NdefRecordData> NdefMessage::toNDEFRecords(const std::vector<unsigned char> &rawdata) { + LoggerD("entered"); + NFCUtil util; + unsigned char *messageRawdata = util.toCharPtr(rawdata); + nfc_ndef_message_h message = NULL; + + try { + int result = nfc_ndef_message_create_from_rawdata(&message, messageRawdata, rawdata.size()); + if (messageRawdata) + free(messageRawdata); + + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't create Ndef Message"); + else if (!message) + ThrowMsg(PlatformException, "Can't create Ndef Message"); + } catch (const WrtDeviceApis::Commons::Exception& err) { + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + } + + return toNDEFRecords((void *)message); +} + +std::vector<NdefRecordData> NdefMessage::toNDEFRecords(void *message) { + LoggerD("entered"); + NFCUtil util; + std::vector<NdefRecordData> records; + + if (message == NULL) + return records; + + try { + int count = 0; + int result = nfc_ndef_message_get_record_count((nfc_ndef_message_h)message, &count); + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't get a record count of message"); + for (int i=0; i<count; i++) { + NdefRecordData record; + try { + record = _getNDEFRecord((nfc_ndef_message_h)message, i); + } catch(const WrtDeviceApis::Commons::Exception& err) { + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + } + records.push_back(record); + } + } catch (const WrtDeviceApis::Commons::Exception& err) { + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + } + + + if (message) + nfc_ndef_message_destroy((nfc_ndef_message_h)message); + message = NULL; + + return records; +} + + +NdefRecordData NdefMessage::_getNDEFRecord(nfc_ndef_message_h handle, const long index) { + nfc_ndef_record_h recordHandle; + int result = nfc_ndef_message_get_record(handle, static_cast<int>(index), &recordHandle); + + NFCUtil util; + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't get Ndef Record"); + + NdefRecordData recordData; + + return util.getNDEFRecordData(recordHandle); +} + +} +} diff --git a/mobile_src/NFC/NdefMessage.h b/mobile_src/NFC/NdefMessage.h new file mode 100755 index 0000000..765e4c2 --- /dev/null +++ b/mobile_src/NFC/NdefMessage.h @@ -0,0 +1,49 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NDEFMESSAGE_H_ +#define _NDEFMESSAGE_H_ + +#include "INdefMessage.h" +#include <nfc.h> + + + +namespace DeviceAPI { +namespace NFC { + +class NdefMessage : public INdefMessage +{ + friend class NFCFactory; + public: + NdefMessage(); + virtual ~NdefMessage(); + + virtual std::vector<unsigned char> toByte(std::vector<void *> &ndefRcords); + virtual void *makeNdefMessageHandle(std::vector<void *> &ndefRcords); + virtual std::vector<NdefRecordData> toNDEFRecords(const std::vector<unsigned char> &rawdata); + virtual std::vector<NdefRecordData> toNDEFRecords(void *message); + private: + NdefRecordData _getNDEFRecord(nfc_ndef_message_h handle, const long index); +}; + +} +} + +#endif /* _NDEFMESSAGE_H_ */ diff --git a/mobile_src/NFC/NdefRecord.cpp b/mobile_src/NFC/NdefRecord.cpp new file mode 100755 index 0000000..dbc3a03 --- /dev/null +++ b/mobile_src/NFC/NdefRecord.cpp @@ -0,0 +1,105 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 "NdefRecord.h" +#include "NFCUtil.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +using namespace WrtDeviceApis::Commons; + +NdefRecord::NdefRecord() : validStatus(INVALID_STATE) {} + +NdefRecord::NdefRecord(std::vector<unsigned char> data) : validStatus(UNKNOWN_STATE) +{ + LoggerD("entered"); + + nfc_ndef_message_h messageHandle = NULL; + + NFCUtil util; + unsigned char *rawdata = util.toCharPtr(data); + try { + int result = nfc_ndef_message_create_from_rawdata(&messageHandle, rawdata, data.size()); + + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't create Ndef Message from data"); + else if (!messageHandle) + ThrowMsg(PlatformException, "Can't create Ndef Message from data"); + + int count = 0; + result = nfc_ndef_message_get_record_count(messageHandle, &count); + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't get record count"); + + nfc_ndef_record_h recordHandle = NULL; + result = nfc_ndef_message_get_record(messageHandle, 0, &recordHandle); + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't get Ndef Record"); + + ndefRecordData = util.getNDEFRecordData((void *)recordHandle); + validStatus = VALID_STATE; + } catch (const WrtDeviceApis::Commons::Exception& err) { + validStatus = INVALID_STATE; + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + } + + if (messageHandle) + nfc_ndef_message_destroy(messageHandle); + messageHandle = NULL; + + if (rawdata) + free(rawdata); + rawdata = NULL; +} + +NdefRecord::NdefRecord(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload, bool isValid) : validStatus(UNKNOWN_STATE) +{ + LoggerD("entered"); + + ndefRecordData.properties = ndefRecordProperties; + ndefRecordData.payload = payload; + + if (!isValid) + validStatus = INVALID_STATE; +} + +NdefRecord::~NdefRecord() +{ + LoggerD("entered"); +} + +void *NdefRecord::getHandle() { + if (validStatus == INVALID_STATE) + return NULL; + NFCUtil util; + + void *handle = NULL; + try { + handle = util.makeNDEFRecord(ndefRecordData.properties, ndefRecordData.payload); + validStatus = VALID_STATE; + } catch (const WrtDeviceApis::Commons::Exception& err) { + validStatus = INVALID_STATE; + handle = NULL; + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + } + return handle; +} + +} +} diff --git a/mobile_src/NFC/NdefRecord.h b/mobile_src/NFC/NdefRecord.h new file mode 100755 index 0000000..c1c93f1 --- /dev/null +++ b/mobile_src/NFC/NdefRecord.h @@ -0,0 +1,51 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NDEFRECORD_H_ +#define _NDEFRECORD_H_ + +#include <vector> +#include <nfc.h> +#include "INdefRecord.h" +#include "NFCFactory.h" + +namespace DeviceAPI { +namespace NFC { + +class NdefRecord : public INdefRecord +{ + friend class NFCFactory; + public: + NdefRecord(); + NdefRecord(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload, bool isValid = true); + NdefRecord(std::vector<unsigned char> data); + virtual ~NdefRecord(); + virtual void *getHandle(); + virtual NdefRecordData getNDEFRecordData() {return ndefRecordData;} + + protected: + NdefRecordData ndefRecordData; + ndefStatus validStatus; + +}; + +} +} + +#endif /* _NDEFRECORD_H_ */ diff --git a/mobile_src/NFC/NdefRecordMedia.cpp b/mobile_src/NFC/NdefRecordMedia.cpp new file mode 100755 index 0000000..b9d4ee0 --- /dev/null +++ b/mobile_src/NFC/NdefRecordMedia.cpp @@ -0,0 +1,101 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <Commons/Exception.h> +#include "NdefRecordMedia.h" +#include "NFCUtil.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +using namespace WrtDeviceApis::Commons; + +NdefRecordMedia::NdefRecordMedia(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload) +{ + LoggerD("entered"); + + ndefRecordData.properties = ndefRecordProperties; + ndefRecordData.payload = payload; + + NFCUtil util; + nfc_ndef_record_h handle = NULL; + char *mime = NULL; + try { + handle = (nfc_ndef_record_h)util.makeNDEFRecord(ndefRecordProperties, payload); + + int result = nfc_ndef_record_get_mime_type(handle, &mime); + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, " Can't get mime type"); + else if (!mime) + mimeType = ""; + else + mimeType = mime; + validStatus = VALID_STATE; + } catch (const WrtDeviceApis::Commons::Exception& err) { + validStatus = INVALID_STATE; + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + } + + if (mime) + free(mime); + mime = NULL; + + if (handle) + nfc_ndef_record_destroy(handle); +} + +NdefRecordMedia::NdefRecordMedia(const std::string &mimeType, const std::vector<unsigned char> data, bool isValid) +{ + LoggerD("entered"); + + this->mimeType = mimeType; + + if (!isValid) { + validStatus = INVALID_STATE; + return; + } + + NFCUtil util; + nfc_ndef_record_h handle = NULL; + unsigned char *mimeData = util.toCharPtr(data); + try { + int result = nfc_ndef_record_create_mime(&handle, mimeType.c_str(), mimeData, static_cast<int>(data.size())); + + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't create Ndef Mime Record"); + + ndefRecordData = util.getNDEFRecordData(handle); + validStatus = VALID_STATE; + } catch (const WrtDeviceApis::Commons::Exception& err) { + validStatus = INVALID_STATE; + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + } + + if (mimeData) + free(mimeData); + if (handle) + nfc_ndef_record_destroy(handle); +} + +NdefRecordMedia::~NdefRecordMedia() +{ + LoggerD("entered"); +} + +} +} diff --git a/mobile_src/NFC/NdefRecordMedia.h b/mobile_src/NFC/NdefRecordMedia.h new file mode 100755 index 0000000..2e4e468 --- /dev/null +++ b/mobile_src/NFC/NdefRecordMedia.h @@ -0,0 +1,45 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NDEFRECORDMEDIA_H_ +#define _NDEFRECORDMEDIA_H_ + +#include "NdefRecord.h" +#include <string> + + +namespace DeviceAPI { +namespace NFC { + +class NdefRecordMedia : public NdefRecord +{ + friend class NFCFactory; + public: + NdefRecordMedia(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload); + NdefRecordMedia(const std::string &mimeType, const std::vector<unsigned char> data, bool isValid = true); + virtual ~NdefRecordMedia(); + virtual std::string getMimeType() {return mimeType;} + protected: + std::string mimeType; +}; + +} +} + +#endif /* _NDEFRECORDMEDIA_H_ */ diff --git a/mobile_src/NFC/NdefRecordProperties.h b/mobile_src/NFC/NdefRecordProperties.h new file mode 100755 index 0000000..2021617 --- /dev/null +++ b/mobile_src/NFC/NdefRecordProperties.h @@ -0,0 +1,73 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_API_NFC_NDEFRECORD_PROPERTIES_H_ +#define WRTPLUGINS_API_NFC_NDEFRECORD_PROPERTIES_H_ + +#include <dpl/shared_ptr.h> +#include <vector> + +namespace DeviceAPI { +namespace NFC { + +enum nfcTNF { + NFC_TNF_EMPTY = 0, + NFC_TNF_WELL_KNOWN = 1, + NFC_TNF_MIME_MEDIA = 2, + NFC_TNF_URI = 3, + NFC_TNF_EXTERNAL_RTD = 4, + NFC_TNF_UNKNOWN = 5, + NFC_TNF_UNCHANGED = 6 +}; + +enum nfcTextEncodeUTF { + NFC_TEXT_ENCODE_UTF_8 = 0, + NFC_TEXT_ENCODE_UTF_16 = 1 +}; + +enum ndefStatus { + UNKNOWN_STATE, + VALID_STATE, + INVALID_STATE +}; + +struct NdefRecordProperties +{ + short tnf; + std::vector<unsigned char> typeName ; + std::vector<unsigned char> id ; + NdefRecordProperties() + : tnf(NFC_TNF_UNKNOWN) + { + } +}; + +struct NdefRecordData +{ + NdefRecordProperties properties; + std::vector<unsigned char> payload; + NdefRecordData() {} +}; + +//typedef DPL::SharedPtr<NdefRecordProperties> NdefRecordPropertiesPtr; + +} // NFC +} // DeviceAPI + +#endif //WRTPLUGINS_API_NFC_NDEFRECORD_PROPERTIES_H_
\ No newline at end of file diff --git a/mobile_src/NFC/NdefRecordText.cpp b/mobile_src/NFC/NdefRecordText.cpp new file mode 100755 index 0000000..b000e08 --- /dev/null +++ b/mobile_src/NFC/NdefRecordText.cpp @@ -0,0 +1,138 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <Commons/Exception.h> +#include "NdefRecordText.h" +#include "NFCUtil.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +using namespace WrtDeviceApis::Commons; + +NdefRecordText::NdefRecordText(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload) +{ + LoggerD("entered"); + + ndefRecordData.properties = ndefRecordProperties; + ndefRecordData.payload = payload; + + NFCUtil util; + nfc_ndef_record_h handle = NULL; + char *recordText = NULL; + char *recordLang = NULL; + try { + handle = (nfc_ndef_record_h)util.makeNDEFRecord(ndefRecordProperties, payload); + + int result = nfc_ndef_record_get_text(handle, &recordText); + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, " Can't get text"); + else if (!recordText) + text = ""; + else + text = std::string(recordText); + + result = nfc_ndef_record_get_langcode(handle, &recordLang); + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, " Can't get languageCode"); + else if (!recordLang) + languageCode = ""; + else + languageCode = std::string(recordLang); + + nfc_encode_type_e type = NFC_ENCODE_UTF_8; + result = nfc_ndef_record_get_encode_type(handle, &type); + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, " Can't get encoding"); + + encoding = _convertToNfcEncodeType(type); + validStatus = VALID_STATE; + } catch (const WrtDeviceApis::Commons::Exception& err) { + validStatus = INVALID_STATE; + encoding = NFC_TEXT_ENCODE_UTF_8; + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + } + + if (recordText) + free(recordText); + + if (recordLang) + free(recordLang); + + if (handle) + nfc_ndef_record_destroy(handle); +} + +NdefRecordText::NdefRecordText(const std::string &text, const std::string &langCode, const nfcTextEncodeUTF encodeType, bool isValid) +{ + LoggerD("entered"); + this->text = text; + languageCode = langCode; + encoding = encodeType; + + if (!isValid) { + validStatus = INVALID_STATE; + return; + } + + nfc_ndef_record_h handle = NULL; + try { + int result = nfc_ndef_record_create_text(&handle, text.c_str(), langCode.c_str(), _convertToEncodeType(encodeType)); + + NFCUtil util; + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, "Can't create Ndef Text Record"); + + ndefRecordData = util.getNDEFRecordData(handle); + validStatus = VALID_STATE; + } catch (const WrtDeviceApis::Commons::Exception& err) { + validStatus = INVALID_STATE; + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + } + if (handle) + nfc_ndef_record_destroy(handle); +} + +NdefRecordText::~NdefRecordText() +{ + LoggerD("entered"); + +} + +nfc_encode_type_e NdefRecordText::_convertToEncodeType(const nfcTextEncodeUTF &type) { + switch(type) { + case NFC_TEXT_ENCODE_UTF_16: + return NFC_ENCODE_UTF_16; + case NFC_TEXT_ENCODE_UTF_8: + return NFC_ENCODE_UTF_8; + } +} + +nfcTextEncodeUTF NdefRecordText::_convertToNfcEncodeType(const nfc_encode_type_e type) { + switch(type) { + case NFC_ENCODE_UTF_16: + return NFC_TEXT_ENCODE_UTF_16; + case NFC_ENCODE_UTF_8: + default: + return NFC_TEXT_ENCODE_UTF_8; + } +} + + +} +} diff --git a/mobile_src/NFC/NdefRecordText.h b/mobile_src/NFC/NdefRecordText.h new file mode 100755 index 0000000..70b1612 --- /dev/null +++ b/mobile_src/NFC/NdefRecordText.h @@ -0,0 +1,50 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NDEFRECORDTEXT_H_ +#define _NDEFRECORDTEXT_H_ + +#include "NdefRecord.h" + +namespace DeviceAPI { +namespace NFC { + +class NdefRecordText : public NdefRecord +{ + friend class NFCFactory; + public: + NdefRecordText(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload); + NdefRecordText(const std::string &text, const std::string &langCode, const nfcTextEncodeUTF encodeType, bool isValid=true); + virtual ~NdefRecordText(); + virtual std::string getText() {return text;} + virtual std::string getLanguageCode() {return languageCode;} + virtual nfcTextEncodeUTF getEncoding() {return encoding;} + private: + std::string text; + std::string languageCode; + nfcTextEncodeUTF encoding; + + nfc_encode_type_e _convertToEncodeType(const nfcTextEncodeUTF &type); + nfcTextEncodeUTF _convertToNfcEncodeType(const nfc_encode_type_e type); +}; + +} +} + +#endif /* _NDEFRECORDTEXT_H_ */ diff --git a/mobile_src/NFC/NdefRecordURI.cpp b/mobile_src/NFC/NdefRecordURI.cpp new file mode 100755 index 0000000..9f45a66 --- /dev/null +++ b/mobile_src/NFC/NdefRecordURI.cpp @@ -0,0 +1,96 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <Commons/Exception.h> +#include "NdefRecordURI.h" +#include "NFCUtil.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace NFC { + +using namespace WrtDeviceApis::Commons; + +NdefRecordUri::NdefRecordUri(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload) +{ + LoggerD("entered"); + + ndefRecordData.properties = ndefRecordProperties; + ndefRecordData.payload = payload; + + NFCUtil util; + nfc_ndef_record_h handle = NULL; + char *recordUri = NULL; + try { + handle = (nfc_ndef_record_h)util.makeNDEFRecord(ndefRecordProperties, payload); + + int result = nfc_ndef_record_get_uri(handle, &recordUri); + if (result != NFC_ERROR_NONE) + util.throwNFCException(result, " Can't get uri"); + else if (!recordUri) + uri = ""; + else + uri = std::string(recordUri); + + validStatus = VALID_STATE; + } catch (const WrtDeviceApis::Commons::Exception& err) { + validStatus = INVALID_STATE; + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + } + if (recordUri) + free(recordUri); + + if (handle) + nfc_ndef_record_destroy(handle); +} + +NdefRecordUri::NdefRecordUri(const std::string &uri, bool isValid) +{ + LoggerD("entered"); + + this->uri = uri; + + if (!isValid) { + validStatus = INVALID_STATE; + return; + } + + nfc_ndef_record_h handle = NULL; + try { + int result = nfc_ndef_record_create_uri(&handle, uri.c_str()); + + NFCUtil util; + if (result != NFC_ERROR_NONE) { + util.throwNFCException(result, "Can't create Ndef Uri Record"); + } + ndefRecordData = util.getNDEFRecordData(handle); + validStatus = VALID_STATE; + } catch (const WrtDeviceApis::Commons::Exception& err) { + validStatus = INVALID_STATE; + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + } + if (handle) + nfc_ndef_record_destroy(handle); +} + +NdefRecordUri::~NdefRecordUri() +{ + LoggerD("entered"); +} + +} +} diff --git a/mobile_src/NFC/NdefRecordURI.h b/mobile_src/NFC/NdefRecordURI.h new file mode 100755 index 0000000..1e062db --- /dev/null +++ b/mobile_src/NFC/NdefRecordURI.h @@ -0,0 +1,47 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NDEFRECORDURI_H_ +#define _NDEFRECORDURI_H_ + +#include "NdefRecord.h" + + + +namespace DeviceAPI { +namespace NFC { + + +class NdefRecordUri : public NdefRecord +{ + friend class NFCFactory; + public: + NdefRecordUri(const NdefRecordProperties &ndefRecordProperties, std::vector<unsigned char> payload); + NdefRecordUri(const std::string &uri, bool isValid = true); + virtual ~NdefRecordUri(); + virtual std::string getUri( ) {return uri;} + private: + std::string uri; + +}; + +} +} + +#endif /* _NDEFRECORDURI_H_ */ diff --git a/mobile_src/NFC/ResponseDispatcher.cpp b/mobile_src/NFC/ResponseDispatcher.cpp new file mode 100755 index 0000000..f89e30c --- /dev/null +++ b/mobile_src/NFC/ResponseDispatcher.cpp @@ -0,0 +1,262 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <vector> +#include <CommonsJavaScript/JSCallbackManager.h> +#include <JSWebAPIErrorFactory.h> +#include "ResponseDispatcher.h" +#include "NFCConverter.h" +#include "JSNdefMessage.h" +#include "NFCAsyncCallbackManager.h" +#include <Logger.h> + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +namespace DeviceAPI { +namespace NFC { + +NFCResponseDispatcher& NFCResponseDispatcher::getInstance() +{ + static NFCResponseDispatcher instance; + return instance; +} + +NFCResponseDispatcher::NFCResponseDispatcher() : + readNDEFAnswerReceiver(ThreadEnum::NULL_THREAD), + writeNDEFAnswerReceiver(ThreadEnum::NULL_THREAD), + transceiveAnswerReceiver(ThreadEnum::NULL_THREAD), + formatAnswerReceiver(ThreadEnum::NULL_THREAD), + TargetSendNdefAnswerReceiver(ThreadEnum::NULL_THREAD), + TargetReceiveNdefListener(ThreadEnum::NULL_THREAD) +{ + LoggerD("entered"); +} + +NFCResponseDispatcher::~NFCResponseDispatcher() +{ + LoggerD("entered"); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagActionReadPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + + Try { + if (!cbm) { + LoggerD("no callback manager"); + return; + } + NFCAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(cbm); + + if (event->getResult()) { + LoggerD("result success"); + cbm->callOnSuccess(JSNdefMessage::createJSObject(cbm->getContext(), event->getReadNdefResult())); + return; + } + LoggerD("result fail"); + + std::string error = event->getError(); + std::string errorMessage = event->getErrorMessage(); + JSValueRef errorObject; + if (error != "") { + if (errorMessage != "") + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, errorMessage); + else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, error); + } else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + + cbm->callOnError(errorObject); + } Catch (PlatformException) { + LoggerE("Platform can't create NdefMessage" << _rethrown_exception.GetMessage()); + JSValueRef errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } Catch (Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + JSValueRef errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagActionWritePtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + + if (!cbm) { + LoggerD("no callback manager"); + return; + } + NFCAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(cbm); + + if (event->getResult()) { + LoggerD("result success"); + cbm->callOnSuccess(); + return; + } + LoggerD("result fail"); + + std::string error = event->getError(); + std::string errorMessage = event->getErrorMessage(); + JSValueRef errorObject; + if (error != "") { + if (errorMessage != "") + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, errorMessage); + else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, error); + } else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + + cbm->callOnError(errorObject); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagActionTransceivePtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + + Try { + if (!cbm) { + LoggerD("no callback manager"); + return; + } + NFCAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(cbm); + + JSContextRef context = cbm->getContext(); + + if (event->getResult()) { + NFCConverter convert(context); + LoggerD("result success"); + cbm->callOnSuccess(convert.toJSValueRef(event->getTransceiveBuffer())); + return; + } + LoggerD("result fail"); + + std::string error = event->getError(); + std::string errorMessage = event->getErrorMessage(); + JSValueRef errorObject; + if (error != "") { + if (errorMessage != "") + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, errorMessage); + else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, error); + } else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + + cbm->callOnError(errorObject); + } Catch (ConversionException) { + LoggerE("Conversion exception while processing EventTagActionTransceive"); + JSValueRef errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } Catch (Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + JSValueRef errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + cbm->callOnError(errorObject); + } +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTagActionFormatPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + + if (!cbm) { + LoggerD("no callback manager"); + return; + } + NFCAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(cbm); + + if (event->getResult()) { + LoggerD("result success"); + cbm->callOnSuccess(); + return; + } + LoggerD("result fail"); + + std::string error = event->getError(); + std::string errorMessage = event->getErrorMessage(); + JSValueRef errorObject; + if (error != "") { + if (errorMessage != "") + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, errorMessage); + else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, error); + } else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + + cbm->callOnError(errorObject); +} + +void NFCResponseDispatcher::OnAnswerReceived(const EventTargetActionSendPtr &event) +{ + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + + if (!cbm) { + LoggerD("no callback manager"); + return; + } + NFCAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(cbm); + + if (event->getResult()) { + LoggerD("result success"); + cbm->callOnSuccess(); + return; + } + LoggerD("result fail"); + + std::string error = event->getError(); + std::string errorMessage = event->getErrorMessage(); + JSValueRef errorObject; + if (error != "") { + if (errorMessage != "") + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, errorMessage); + else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), error, error); + } else + errorObject = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"Unknown Error"); + + cbm->callOnError(errorObject); +} + +void NFCResponseDispatcher::onAnswerReceived(const EventTargetActionReceivePtr &event) +{ + LoggerD("onAnswerReceived Enter"); + JSCallbackManagerPtr cbm = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + + Try { + if (!cbm) { + LoggerD("no callback manager"); + return; + } + + JSContextRef context = cbm->getContext(); + + LoggerD("result success"); + cbm->callOnSuccess(JSNdefMessage::createJSObject(context, event->getReadNdefResult())); + } Catch (PlatformException) { + LoggerE("Platform can't create NdefMessage" << _rethrown_exception.GetMessage()); + } Catch (Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } +} + +} +} diff --git a/mobile_src/NFC/ResponseDispatcher.h b/mobile_src/NFC/ResponseDispatcher.h new file mode 100755 index 0000000..9f9ff6d --- /dev/null +++ b/mobile_src/NFC/ResponseDispatcher.h @@ -0,0 +1,65 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 WRTPLUGINS_TIZEN_NFC_RESPONSEDISPATCHER_H_ +#define WRTPLUGINS_TIZEN_NFC_RESPONSEDISPATCHER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <Commons/EventReceiver.h> +#include <Commons/EventListener.h> +#include "EventTagAction.h" +#include "EventTargetAction.h" + +using namespace WrtDeviceApis::Commons; +namespace DeviceAPI { +namespace NFC { + +typedef EventAnswerReceiver<EventTagActionRead> readNDEFAnswerReceiver; +typedef EventAnswerReceiver<EventTagActionWrite> writeNDEFAnswerReceiver; +typedef EventAnswerReceiver<EventTagActionTransceive> transceiveAnswerReceiver; +typedef EventAnswerReceiver<EventTagActionFormat> formatAnswerReceiver; +typedef EventAnswerReceiver<EventTargetActionSend> TargetSendNdefAnswerReceiver; +typedef EventListener<EventTargetActionReceive> TargetReceiveNdefListener; + +class NFCResponseDispatcher : + public readNDEFAnswerReceiver, + public writeNDEFAnswerReceiver, + public transceiveAnswerReceiver, + public formatAnswerReceiver, + public TargetSendNdefAnswerReceiver, + public TargetReceiveNdefListener + +{ +public: + static NFCResponseDispatcher& getInstance(); +private: + NFCResponseDispatcher(); + virtual ~NFCResponseDispatcher(); +protected: + void OnAnswerReceived(const EventTagActionReadPtr &event); + void OnAnswerReceived(const EventTagActionWritePtr &event); + void OnAnswerReceived(const EventTagActionTransceivePtr &event); + void OnAnswerReceived(const EventTagActionFormatPtr &event); + void OnAnswerReceived(const EventTargetActionSendPtr &event); + void onAnswerReceived(const EventTargetActionReceivePtr &event); +}; + +} +} + +#endif
\ No newline at end of file diff --git a/mobile_src/NFC/TagFilter.cpp b/mobile_src/NFC/TagFilter.cpp new file mode 100755 index 0000000..e204d2b --- /dev/null +++ b/mobile_src/NFC/TagFilter.cpp @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 "TagFilter.h" + +namespace DeviceAPI { +namespace NFC { + +TagFilter::TagFilter() +{ +} + +TagFilter::~TagFilter() +{ +} + +void TagFilter::addTagTypeValue(nfcTagType type){ + m_tagList.push_back(type); +} + +nfcTagType TagFilter::getFilterValue(int index){ + if (index >=0 && index < (int)m_tagList.size()) + return m_tagList.at(index); + else + return NFC_TAGTYPE_UNKNOWN_TARGET; +} + +int TagFilter::getFilterSize(){ + return m_tagList.size(); +} + +} +} diff --git a/mobile_src/NFC/TagFilter.h b/mobile_src/NFC/TagFilter.h new file mode 100755 index 0000000..f325274 --- /dev/null +++ b/mobile_src/NFC/TagFilter.h @@ -0,0 +1,52 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _TIZEN_NFC_TAG_FILTER_H_ +#define _TIZEN_NFC_TAG_FILTER_H_ + +#include <map> +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> +#include <JavaScriptCore/JavaScript.h> + +#include "INFCTag.h" + +namespace DeviceAPI { +namespace NFC { + +class TagFilter +{ + public: + + typedef std::vector<nfcTagType> TagList; + + explicit TagFilter(); + virtual ~TagFilter(); + + void addTagTypeValue(nfcTagType type); + int getFilterSize(); + nfcTagType getFilterValue(int index); + private: + TagList m_tagList; +}; + +typedef DPL::SharedPtr<TagFilter> TagFilterPtr; + +} +} +#endif //_TIZEN_NFC_TAG_FILTER_H_
\ No newline at end of file diff --git a/mobile_src/NFC/config.xml b/mobile_src/NFC/config.xml new file mode 100755 index 0000000..a06d606 --- /dev/null +++ b/mobile_src/NFC/config.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-nfc.so</library-name> + <feature-install-uri>nfc.install.uri</feature-install-uri> + + <api-feature> + <name>http://tizen.org/privilege/nfc.common</name> + <device-capability>nfc.common</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/nfc.tag</name> + <device-capability>nfc.tag</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/nfc.p2p</name> + <device-capability>nfc.p2p</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/nfc.admin</name> + <device-capability>nfc.admin</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/nfc.cardemulation</name> + <device-capability>nfc.cardemulation</device-capability> + </api-feature> +</plugin-properties> + diff --git a/mobile_src/NFC/plugin_config.cpp b/mobile_src/NFC/plugin_config.cpp new file mode 100755 index 0000000..fda5f11 --- /dev/null +++ b/mobile_src/NFC/plugin_config.cpp @@ -0,0 +1,174 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <map> +#include <utility> +#include <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <Commons/Exception.h> +#include "plugin_config.h" + +#define NFC_FEATURE_API_COMMON "http://tizen.org/privilege/nfc.common" +#define NFC_FEATURE_API_ADMIN "http://tizen.org/privilege/nfc.admin" +#define NFC_FEATURE_API_TAG "http://tizen.org/privilege/nfc.tag" +#define NFC_FEATURE_API_P2P "http://tizen.org/privilege/nfc.p2p" +#define NFC_FEATURE_API_CARDEMULATION "http://tizen.org/privilege/nfc.cardemulation" + +#define NFC_DEVICE_CAP_COMMON "nfc.common" +#define NFC_DEVICE_CAP_ADMIN "nfc.admin" +#define NFC_DEVICE_CAP_TAG "nfc.tag" +#define NFC_DEVICE_CAP_P2P "nfc.p2p" +#define NFC_DEVICE_CAP_CARDEMULATION "nfc.cardemulation" + +namespace DeviceAPI { +namespace NFC { + +static WrtDeviceApis::Commons::FunctionMapping createNFCFunctions(); + +static WrtDeviceApis::Commons::FunctionMapping NFCFunctions = + createNFCFunctions(); + +DEFINE_FUNCTION_GETTER(NFC, NFCFunctions); + +static WrtDeviceApis::Commons::FunctionMapping createNFCFunctions() +{ + using namespace WrtDeviceApis::Commons; + + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_NFC_COMMON, NFC_DEVICE_CAP_COMMON); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_NFC_ADMIN, NFC_DEVICE_CAP_ADMIN); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_NFC_TAG, NFC_DEVICE_CAP_TAG); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_NFC_P2P, NFC_DEVICE_CAP_P2P); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_NFC_CARDEMULATION, NFC_DEVICE_CAP_CARDEMULATION); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_NFC_COMMON); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_NFC_COMMON, DEVICE_CAP_NFC_COMMON); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_NFC_ADMIN); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_NFC_ADMIN, DEVICE_CAP_NFC_ADMIN); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_NFC_TAG); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_NFC_TAG, DEVICE_CAP_NFC_TAG); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_NFC_P2P); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_NFC_P2P, DEVICE_CAP_NFC_P2P); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_NFC_CARDEMULATION); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_NFC_CARDEMULATION, DEVICE_CAP_NFC_CARDEMULATION); + + /** + * API features + */ + ACE_CREATE_FEATURE(FEATURE_COMMON, NFC_FEATURE_API_COMMON); + ACE_CREATE_FEATURE(FEATURE_ADMIN, NFC_FEATURE_API_ADMIN); + ACE_CREATE_FEATURE(FEATURE_TAG, NFC_FEATURE_API_TAG); + ACE_CREATE_FEATURE(FEATURE_P2P, NFC_FEATURE_API_P2P); + ACE_CREATE_FEATURE(FEATURE_CARDEMULATION, NFC_FEATURE_API_CARDEMULATION); + + ACE_CREATE_FEATURE_LIST(NFC_FEATURES_NFC_COMMON); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_COMMON, FEATURE_COMMON); + + ACE_CREATE_FEATURE_LIST(NFC_FEATURES_NFC_ADMIN); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_ADMIN, FEATURE_ADMIN); + + ACE_CREATE_FEATURE_LIST(NFC_FEATURES_NFC_TAG); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_TAG, FEATURE_TAG); + + ACE_CREATE_FEATURE_LIST(NFC_FEATURES_NFC_P2P); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_P2P, FEATURE_P2P); + + ACE_CREATE_FEATURE_LIST(NFC_FEATURES_NFC_CARDEMULATION); + ACE_ADD_API_FEATURE(NFC_FEATURES_NFC_CARDEMULATION, FEATURE_CARDEMULATION); + + /** + * Functions + */ + FunctionMapping NFCFunctions; + + AceFunction nfcCommonFuncs = ACE_CREATE_FUNCTION( + FUNCTION_NFC_COMMON_FUNCTIONS, + NFC_FUNCTION_API_COMMON_FUNCS, + NFC_FEATURES_NFC_COMMON, + DEVICE_LIST_NFC_COMMON); + + NFCFunctions.insert(std::make_pair( + NFC_FUNCTION_API_COMMON_FUNCS, + nfcCommonFuncs)); + + AceFunction nfcAdminFuncs = ACE_CREATE_FUNCTION( + FUNCTION_NFC_ADMIN_FUNCTIONS, + NFC_FUNCTION_API_ADMIN_FUNCS, + NFC_FEATURES_NFC_ADMIN, + DEVICE_LIST_NFC_ADMIN); + + NFCFunctions.insert(std::make_pair( + NFC_FUNCTION_API_ADMIN_FUNCS, + nfcAdminFuncs)); + + AceFunction nfcTagFuncs = ACE_CREATE_FUNCTION( + FUNCTION_NFC_TAG_FUNCTIONS, + NFC_FUNCTION_API_TAG_FUNCS, + NFC_FEATURES_NFC_TAG, + DEVICE_LIST_NFC_TAG); + + NFCFunctions.insert(std::make_pair( + NFC_FUNCTION_API_TAG_FUNCS, + nfcTagFuncs)); + + AceFunction nfcP2PFuncs = ACE_CREATE_FUNCTION( + FUNCTION_NFC_P2P_FUNCTIONS, + NFC_FUNCTION_API_P2P_FUNCS, + NFC_FEATURES_NFC_P2P, + DEVICE_LIST_NFC_P2P); + + NFCFunctions.insert(std::make_pair( + NFC_FUNCTION_API_P2P_FUNCS, + nfcP2PFuncs)); + + AceFunction nfcCardEmulationFuncs = ACE_CREATE_FUNCTION( + FUNCTION_NFC_CARDEMULATION_FUNCTIONS, + NFC_FUNCTION_API_CARDEMULATION_FUNCS, + NFC_FEATURES_NFC_CARDEMULATION, + DEVICE_LIST_NFC_CARDEMULATION); + + NFCFunctions.insert(std::make_pair( + NFC_FUNCTION_API_CARDEMULATION_FUNCS, + nfcCardEmulationFuncs)); + + + return NFCFunctions; +} + +} // namespace NFC +} // namespace DeviceAPI + +#undef NFC_FEATURE_API_COMMON +#undef NFC_FEATURE_API_ADMIN +#undef NFC_FEATURE_API_TAG +#undef NFC_FEATURE_API_P2P +#undef NFC_FEATURE_API_CARDEMULATION +#undef NFC_DEVICE_CAP_COMMON +#undef NFC_DEVICE_CAP_ADMIN +#undef NFC_DEVICE_CAP_TAG +#undef NFC_DEVICE_CAP_P2P +#undef NFC_DEVICE_CAP_CARDEMULATION diff --git a/mobile_src/NFC/plugin_config.h b/mobile_src/NFC/plugin_config.h new file mode 100755 index 0000000..5388f9d --- /dev/null +++ b/mobile_src/NFC/plugin_config.h @@ -0,0 +1,38 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NFC_PLUGIN_CONFIG_H_ +#define _NFC_PLUGIN_CONFIG_H_ + +#include <Commons/FunctionDeclaration.h> +#include "plugin_config_impl.h" + +namespace DeviceAPI { +namespace NFC { + + +DECLARE_FUNCTION_GETTER(NFC); + +#define NFC_CHECK_ACCESS(functionName) \ + aceCheckAccess<AceFunctionGetter, DefaultArgsVerifier<> >( \ + getNFCFunctionData, \ + functionName) +} +} + +#endif // _NFC_PLUGIN_CONFIG_H_ diff --git a/mobile_src/NFC/plugin_config_impl.h b/mobile_src/NFC/plugin_config_impl.h new file mode 100755 index 0000000..1d8f572 --- /dev/null +++ b/mobile_src/NFC/plugin_config_impl.h @@ -0,0 +1,29 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 _NFC_PLUGIN_CONFIG_IMPL_H_ +#define _NFC_PLUGIN_CONFIG_IMPL_H_ + +#define NFC_FUNCTION_API_COMMON_FUNCS "NFCCommonFunctions" +#define NFC_FUNCTION_API_ADMIN_FUNCS "NFCAdminFunctions" +#define NFC_FUNCTION_API_TAG_FUNCS "NFCTagFunctions" +#define NFC_FUNCTION_API_P2P_FUNCS "NFCP2PFunctions" +#define NFC_FUNCTION_API_CARDEMULATION_FUNCS "NFCCardEmulationFunctions" + + +#endif // _NFC_PLUGIN_CONFIG_IMPL_H_
\ No newline at end of file diff --git a/mobile_src/NFC/plugin_initializer.cpp b/mobile_src/NFC/plugin_initializer.cpp new file mode 100755 index 0000000..e352c84 --- /dev/null +++ b/mobile_src/NFC/plugin_initializer.cpp @@ -0,0 +1,154 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed 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 <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <GlobalContextManager.h> +#include "JSNFCManager.h" +#include "JSNdefMessage.h" +#include "JSNdefRecord.h" +#include "JSNdefRecordText.h" +#include "JSNdefRecordURI.h" +#include "JSNdefRecordMedia.h" +#include "NFCAsyncCallbackManager.h" +#include "NFCListenerManager.h" +#include "NFCDefaultAdapter.h" +#include "plugin_config.h" +#include <Security.h> +#include <JSStringRefWrapper.h> +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace NFC { + +AceSecurityStatus nfcAceCheckAccessFunction(const char* functionName) +{ + return NFC_CHECK_ACCESS(functionName); +} + +DEFINE_GLOBAL_SECURITY_ACCESSOR(gSecurityAccessor); +DEFINE_SECURITY_ACCESSOR_SETTER(AceCheckerNfcSetter, NFCManagerPrivObject, gSecurityAccessor); +DEFINE_JSOBJECT_SECURITY_ACCESSOR_SETTER(AceCheckerNfcConstructorSetter, gSecurityAccessor); + +class_definition_options_t ClassOptions = +{ + JS_CLASS, + CREATE_INSTANCE, + ALWAYS_NOTICE, + USE_OVERLAYED, //ignored + AceCheckerNfcSetter, + NULL +}; + + +class_definition_options_t ConstructorClassOptions = +{ + JS_INTERFACE, + CREATE_INSTANCE, + ALWAYS_NOTICE, + USE_OVERLAYED, //ignored + AceCheckerNfcConstructorSetter, // JSWidget::acquireGlobalContext, + NULL, + NULL +}; + +void on_widget_start_callback(int widgetId) +{ + LoggerD("[TIZEN\\NFC ] on_widget_start_callback (" << widgetId << ")"); + Try + { + WrtAccessSingleton::Instance().initialize(widgetId); + } + Catch(Commons::Exception) + { + LoggerE("WrtAccess initialization failed"); + } + INITAILIZE_GLOBAL_SECURITY_ACCESSOR(gSecurityAccessor, nfcAceCheckAccessFunction); +} + +void on_widget_stop_callback(int widgetId) +{ + LoggerD("[TIZEN\\NFC ] on_widget_stop_callback (" << widgetId << ")"); + Try + { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } + Catch(Commons::Exception) + { + LoggerE("WrtAccess deinitialization failed"); + } + FINALIZE_GLOBAL_SECURITY_ACCESSOR(gSecurityAccessor); +} + +void on_frame_load_callback(const void *context) +{ + LoggerD("[Tizen\\NFC] on_frame_load_callback (" << context << ")"); + GlobalContextManager::getInstance()->addGlobalContext(static_cast<JSContextRef>(context)); +} + +void on_frame_unload_callback(const void *context) +{ + LoggerD("[Tizen\\NFC] on_frame_unload_callback (" << context << ")"); + GlobalContextManager::getInstance()->removeGlobalContext(static_cast<JSContextRef>(context)); + DeviceAPI::NFC::NFCAsyncCallbackManagerSingleton::Instance().unregisterContext(static_cast<JSContextRef>(context)); + DeviceAPI::NFC::NFCListenerManagerSingleton::Instance().unregisterContext(static_cast<JSContextRef>(context)); + DeviceAPI::NFC::NFCDefaultAdapterSingleton::Instance().unsetExclusiveMode(); +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) +PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) +PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, + "nfc", + (js_class_template_getter)JSNFCManager::getClassRef, + &ClassOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN, + "NDEFMessage", + (js_class_template_getter)JSNdefMessage::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(JSNdefMessage::constructor), + &ConstructorClassOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN, + "NDEFRecord", + (js_class_template_getter)JSNdefRecord::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(JSNdefRecord::constructor), + &ConstructorClassOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN, + "NDEFRecordText", + (js_class_template_getter)JSNdefRecordText::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(JSNdefRecordText::constructor), + &ConstructorClassOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN, + "NDEFRecordURI", + (js_class_template_getter)JSNdefRecordURI::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(JSNdefRecordURI::constructor), + &ConstructorClassOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN, + "NDEFRecordMedia", + (js_class_template_getter)JSNdefRecordMedia::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(JSNdefRecordMedia::constructor), + &ConstructorClassOptions) +PLUGIN_CLASS_MAP_END + +} // NFC +} // DeviceAPI |