# ohos_coap **Repository Path**: openharmony-tpc/ohos_coap ## Basic Information - **Project Name**: ohos_coap - **Description**: ohos_coap是基于libcoap v4.3.1版本,封装napi接口,给上层ts提供coap通信能力的三方库 - **Primary Language**: Unknown - **License**: BSD-3-Clause - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 9 - **Forks**: 20 - **Created**: 2023-04-03 - **Last Updated**: 2026-10-04 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 🚨 **重要提示 | IMPORTANT** > > **⚠️ 此代码仓已归档。新地址请访问 [ohos_coap](https://gitcode.com/openharmony-tpc/ohos_coap)。| ⚠️ This repository has been archived. For the new address, please visit [ohos_coap](https://gitcode.com/openharmony-tpc/ohos_coap).** > --- > # ohos_coap ## Overview libcoap is a C implementation of Constrained Application Protocol (CoAP). It is a tool that uses CoAP. ohos_coap is a third-party library that encapsulates native APIs (NAPIs) of libcoap v4.3.1 and provides CoAP communication capabilities for upper-layer TSs. From the CoAP client, you can: - Initiate GET, POST, and PUT requests. From the CoAP server, you can: - Handle GET and POST data. It does not support the following capabilities yet: - Features other than registering GET and POST requests on the CoAP server - Sending files and media software from the CoAP client - Sending TLS/DTLS messages - Initiating DELETE requests ## How to Download You can download the library in either of the following ways: 1. Run the following command: ``` git clone https://gitee.com/openharmony-tpc/ohos_coap.git --recurse-submodules ``` 2. Click **Download** to download the library to the local host, and save the libcoap v4.3.1 code to the **libcoap/src/cpp/libcoapSource** directory. For vulnerability fixes, go to the **libcoap/src/main/cpp/thirdModule** directory and execute the **modify.sh** script to apply the patches in the directory to the libcoap source code. For details, see [Vulnerability Repair Record](https://gitee.com/openharmony-tpc/ohos_coap/blob/master/Vulnerability_Repair.md). ## How to Install ``` ohpm install @ohos/coap ``` For details about the OpenHarmony ohpm environment configuration, see [OpenHarmony HAR](https://gitee.com/openharmony-tpc/docs/blob/master/OpenHarmony_har_usage.en.md). ## Client Usage ### 1. Using a CoAP GET Request ``` // Enable the native log feature. CoapClient.setNativeLogOpen(true); // Initiate a CoAP GET request. Replace this.coapUri with the actual URL. // Each CoapClient corresponds to a CoAP request task and cannot be reused. let coapClient = new CoapClient(); let coapGet = coapClient.request(this.coapUri, CoapRequestMethod.GET, CoapRequestType.COAP_MESSAGE_CON); console.log("libcoap get test"); // Asynchronous callback of the CoAP GET request coapGet.then((data) => { if (data.code == CoapResponseCode.SUCCESS) { // success indicates that the request is successful. console.log("libcoap get:" + data.message[0]); } else { console.log("libcoap get code:" + data.code); console.log("libcoap get error message:" + data.message); } }) let coapClient = new CoapClient(); // GET request callback coapClient.requestCall(this.coapUri, CoapRequestMethod.GET, CoapRequestType.COAP_MESSAGE_CON, (data: CoapResponse) => { if (data.code == CoapResponseCode.SUCCESS) { console.log("libcoap requestCall get:" + data.message[0]); } else { console.log("libcoap requestCall get code:" + data.code); console.log("libcoap requestCall get error message:" + data.message[0]); } }); ``` ### 2. Using a CoAP PUT Request ``` // Enable the native log feature. CoapClient.setNativeLogOpen(true); let coapClient = new CoapClient(); // Set the port number. coapClient.setPort(5683); // Set the format of the transparently transmitted data. coapClient.setFormat(ContentFormat.PLAIN); // Set the data to be transparently transmitted. coapClient.setPayload("this is put test payload"); // Initiate a CoAP PUT request. Replace this.coapUri with the actual URL. // Each CoapClient corresponds to a CoAP request task and cannot be reused. let coapPut = coapClient.request(this.coapUri, CoapRequestMethod.PUT, CoapRequestType.COAP_MESSAGE_CON); console.log("libcoap put test"); // Asynchronous callback of the CoAP GET request coapPut.then((data) => { if (data.code == CoapResponseCode.SUCCESS) { // success indicates that the request is successful. console.log("libcoap put:" + data.message[0]); } else { console.log("libcoap put code:" + data.code); console.log("libcoap put error message:" + data.message); } }) ``` ## Server Usage ### Registering GET and POST Requests from the Server ``` let server = new CoapServer(); let resource = new CoapResource(); let exchange = new CoapExchange(); // Local IP address of the server. The port number is fixed. server.setAddr('125.0.10.5', '0'); // Enable the native log feature. CoapClient.setNativeLogOpen(true); // Add an ID. let resourceId = this.resource.createResource('test'); // Add resource attributes. resource.addAttributes(resourceId, 'title', 'Dynamic'); // Handle GET data. resource.registerGetHandler(resourceId, (responseId: string) => { let getQuesOptions = exchange.getRequestOptions(responseId); exchange.response(responseId, CoapResourceCode.COAP_RESPONSE_CODE_CONTENT, 'hello arkts'); }); // Handle POST data. resource.registerPostHandler(resourceId, (responseId: string) => { let postQuesOptions = exchange.getRequestOptions(responseId); let postQuesText = exchange.getRequestText(responseId); exchange.response(responseId, CoapResourceCode.COAP_RESPONSE_CODE_CONTENT, 'hello arkts'); }); // Add a resource. server.addResource(resourceId); // Start the CoAP server. server.start(); ``` ## Available Client APIs | API | Input Parameter | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | request(coapUri: string, method: CoapRequestMethod, type: CoapRequestType) | coapUri: string, method: CoapRequestMethod, type: CoapRequestTyp | Initiates a request. | | requestCall(coapUri: string, method: CoapRequestMethod, type: CoapRequestType, callback: AsyncCallback\) | coapUri: string, method: CoapRequestMethod, type: CoapRequestTyp, callback: AsyncCallback\ | Initiates a request. | | setFormat(format: ContentFormat) | format: ContentFormat | Sets the format of parameters to be transparently transmitted in a POST or PUT request. | | setPort(port: number) | port: number | Sets the port number. | | setWaitSecond(waitSecond: number) | waitSecond: number | Sets a duration that the client waits for a response. | | setObsSecond(obsSecond: number) | obsSecond: number | Sets the duration for connection observation. | | setRepeatCount(repeatCount: number) | repeatCount: number | Sets the number of retry requests on the client. | | setPayload(payload: string) | payload: string | Sets the data to be transparently transmitted by the client. | | setToken(token: Uint8Array) | token: Uint8Array | Sets a token. | | setNativeLogOpen(isOpen: boolean) | isOpen: boolean | Sets whether to enable the log feature on the native side. | | addOption(optionNum: number, value: string) | optionNum: number, value: string | Adds a custom option for the client. | | setMid(mid: number) | mid: number | Sets a custom message ID for the client. | | setPayloadBinary(payload: Uint8Array) | payload: Uint8Array | Sets the byte content to transmit transparently by the client. | | setBlockMode(mode: CoapBlockMode) | mode: CoapBlockMode | Sets the block transfer mode for the client. | For details about unit test cases, see [TEST.md](https://gitee.com/openharmony-tpc/ohos_coap/blob/master/TEST.md). ## Available Server APIs | API | Input Parameter | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------- | | start(classId: number) | classId: number | Starts the server. | | stop(classId: number) | classId: number | Stops the server. | | addResource(classId: number, resourceID: string) | resourceID: string | Adds a resource. | | setAddr(classId: number, ip: string, port: string) | ip: string, port: string | Sets the server IP address and port number. **0** means the default port.| | getStatus(classId: number) | classId: number | Obtains the server status code. | | registerGetHandler(resourceID: string, cb: Function) | resourceID: string, cb: Function | Registers a GET request handler. | | registerPostHandler(resourceID: string, cb: Function) | resourceID: string, cb: Function | Registers a POST request handler. | | addAttributes: (resourceId: string, attributesOptionOne: string, attributesOptionTwo: string) | (resourceId: string, attributesOptionOne: string, attributesOptionTwo: string) | Adds resource attributes. | | createResource: (resourceId: string) | resourceId: string | Creates a resource ID. | | destroy() | | Destroys the resource. | | response: (responseId: string, code: number, data: string) | (responseId: string, code: number, data: string) | Sends a response to the client. | | getRequestOptions: (responseId: string) | responseId: string | Obtains request options. | | getRequestText: (responseId: string) | responseId: string | Obtains the request payload. | | getSourceAddress: (responseId: string) | responseId: string | Obtains the IP address of the peer. | ## Constraints This project has been verified in the following versions: - DevEco Studio: NEXT Developer Beta1-5.0.3.331, SDK: API 12 (5.0.0.25(SP6)) - DevEco Studio: NEXT Beta1-5.0.3.806, SDK: API 12 Release (5.0.0.66) ## Directory Structure ``` |----ohos_coap | |---- entry # Sample code | |---- libcoap # Library | |---- index.ets # External APIs | |---- README.md # Readme ``` ## How to Contribute If you find any problem when using the project, submit an [issue](https://gitee.com/openharmony-tpc/ohos_coap/issues) or a [PR](https://gitee.com/openharmony-tpc/ohos_coap/pulls). ## License This project is licensed under [Apache License 2.0](https://gitee.com/openharmony-tpc/ohos_coap/blob/master/LICENSE). The dependency libcoap is licensed under [BSD 2](https://gitee.com/openharmony-tpc/ohos_coap/blob/master/LICENSE-BSD2-libcoap).