Sample program showing how to connect GR-PEACH into Watson IoT through mbed Connector and Watson's Connector Bridge
Dependencies: AsciiFont DisplayApp GR-PEACH_video LCD_shield_config LWIPBP3595Interface_STA_for_mbed-os USBDevice
Overview
This sample program shows how to connect GR-PEACH into Watson IoT through mbed Connector and Watson's Connector Bridge. Note that this program is derived from https://github.com/ARMmbed/mbed-ethernet-sample-techcon2016.
In this program, at first, the barcode data input from camera is decoded on GR-PEACH using ZXing which is an open-source, multi-format 1D/2D barcode image processing library. Then, the decoded string is sent to Watson IoT via mbed Device Connector and Watson's Connector Bridge. At last, the delivered string is confirmed via NodeRED flow.
Required hardware
- GR-PEACH ( https://developer.mbed.org/platforms/Renesas-GR-PEACH/ )
- Audio Camera Shield ( https://developer.mbed.org/teams/Renesas/wiki/Audio_Camera-shield )
- LCD Shield ( https://developer.mbed.org/teams/Renesas/wiki/LCD-shield )
- BP3595 ( https://developer.mbed.org/components/BP3595-for-GR-PEACH/ )
- Ethernet cable and connection to the internet
Application setup
- Select the connection type. For details, please refer to the following wiki:
https://developer.mbed.org/teams/Renesas/code/mbed-os_Watson-IoT_ZXing_sample/wiki/Connection-type. - Set the client credentials. For details, please refer to the following wiki:
https://developer.mbed.org/teams/Renesas/code/mbed-os_Watson-IoT_ZXing_sample/wiki/Client-credentials. - Change Ethernet settings. For details, please refer to the following wiki:
https://developer.mbed.org/teams/Renesas/code/mbed-os_Watson-IoT_ZXing_sample/wiki/Ethernet-settings. - Change Wifi settings. For details, please refer to the following wiki:
https://developer.mbed.org/teams/Renesas/code/mbed-os_Watson-IoT_ZXing_sample/wiki/Wifi-settings.
Building this sample program
- Import this sample program onto mbed Compiler.
- Configure this sample program in accordance with Application setup.
- Compile the example on mbed Compiler and download the resultant binary file.
- Plug the Ethernet cable into GR-PEACH if you are using Ethernet mode.
- Plug the micro-USB cable into the OpenSDA port with lies on the next to the RESET button.
- Copy the binary previously downloaded to your PC to GR-PEACH to flash this sample program. When the copy is successfully completed, the board is ready to work.
- Press the RESET button on the board to run this sample program.
- For verification, please refer to the following wiki:
https://developer.mbed.org/teams/Renesas/code/mbed-os_Watson-IoT_ZXing_sample/wiki/Monitoring-the-application.
Application resources
This sample program exposes two resources listed below:
- /311/0/5850 : Trigger to toggle LED on GR-PEACH (PUT). When "1" is sent to this resource by PUT method, LED should be turned off. Otherwise, LED should be turned on.
- /888/0/7700: Decode result of barcode data input from camera (GET)
Setup of Watson IoT
- You should create Watson IoT Instance by the following procedure:
- Login IBM Bluemix from https://console.ng.bluemix.net/ and login it.
- Select Services as follows:
- Select Internet of Things" as follows:
- Press Get Started as follows:
- Configure Watson IoT Instance
- Leave unbound
- Select the Free plan, then click Create
- You should create Watson IoT Application Credentials
Once you successfully create Watson IoT Instance, you should see the following Watson IoT dashboard:
- On dashboard, launch the Connect your devices dashboard
- Click APPS
- Click Generate API Key
- Record the API Key and Authenticatoin Token. Then click Generate after adding a comment Note that these two values will be needed in the later step.
- Watson IoT NodeRED Application should be created in accordance with the following procedure:
- Go back to your Bluemix Dashboard: https://console.ng.bluemix.net
- Click Create Application
- Select Node-RED Starter
- Enter a unique App name and Click Create
- Application will Stage after a few minutes
- Application will report app is running when the staging has completed
- Watson NodeRED Application should be binded to Watson IoT instance
- You can now see the dashboard below:
- Click Connections. Then, press Connect Existing
- Click on Watson IoT Instance badge. Then, press Connect
- NodeRED application will restage. This will take a while. Please wait for Your app is running state
- You should acquire mbed Device Connector DOMAIN value
- Go to the mbed Device Connector Dashboard: https://connector.mbed.com and log in
- Select Access Key in order to create a new token
- Click CREATE NEW ACCESS KEY and enter a unique name. Then, push ADD bution
- an API token is generated. Need to save the generated string for later steps
- You should configure Watson IoT ARM mbed Connector Bridge
- Go back to the Watson IoT Dashboard and select Extensions
- Press Add Extension
- Add ARM mbed Connector
- Setup the bridge
- Enter your Connector API Token to Access Key and MBED_DOMAIN to Domain Id, respectively. Then, click Check Connection
- If the connection is successfully established, you can see Connection Established. Then, press Done
- NodeRED Flow Example should be imported
- Open NODEFLOW_GR-PEACH.txt
- Navigate to the URL that you recorded earlier for your Watson IoT NodeRED Application (i.e. http://<app name>.mybluemix.net) and Select Go to your NodeRED flow editor
- Select menu, Import and Clipboard
- Paste the entire contents of JSON code described in NODEFLOW_GR-PEACH.txt and click Import
- Watson IoT Application Node Flow should be configured
- Double-click input node and link them to your Watson IoT instance.
- Click on the edit button
- First enter arbitrary name. Then, Watson API Key and Watson Auth Token previously acquired. Finally, press Add to save
- Enter MBED_ENDPOINT_NAME in security.h as Device ID. Then, press Done to save
- Double-click output node
- Edit API Key and Device Id in the same manner as that for input node
- Click LED OFF and LED ON node and replace MBED_ENDPOINT_NAME_GOES_HERE with MBED_ENDPOINT_NAME as shown below:
- Click Deproy to deploy NodeRED application
- Invoke sample program
- Press the reset button on GR-PEACH
- The decode result of barcode data should be shown in debug window
- Also, you can toggle LED by clicking Turn LED OFF and Turn LED ON injection node
Revision 0:ad834d403a8c, committed 2016-11-24
- Comitter:
- Osamu Nakamura
- Date:
- Thu Nov 24 13:59:16 2016 +0900
- Commit message:
- Initial Commit
Changed in this revision
diff -r 000000000000 -r ad834d403a8c AsciiFont.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/AsciiFont.lib Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,1 @@ +https://developer.mbed.org/teams/Renesas/code/AsciiFont/#0d8bc371d109
diff -r 000000000000 -r ad834d403a8c DisplayApp.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/DisplayApp.lib Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,1 @@ +https://developer.mbed.org/users/dkato/code/DisplayApp/#b7ffe5216cd7
diff -r 000000000000 -r ad834d403a8c GR-PEACH_video.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/GR-PEACH_video.lib Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,1 @@ +https://developer.mbed.org/teams/Renesas/code/GR-PEACH_video/#aeefe5171463
diff -r 000000000000 -r ad834d403a8c LCD_shield_config.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/LCD_shield_config.lib Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,1 @@ +https://developer.mbed.org/users/dkato/code/LCD_shield_config/#5bc6a60b8ff5
diff -r 000000000000 -r ad834d403a8c LWIPBP3595Interface_STA_for_mbed-os.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/LWIPBP3595Interface_STA_for_mbed-os.lib Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,1 @@ +https://developer.mbed.org/users/dkato/code/LWIPBP3595Interface_STA_for_mbed-os/#590c87b7dcc2
diff -r 000000000000 -r ad834d403a8c NODEFLOW_GR-PEACH.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/NODEFLOW_GR-PEACH.txt Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,1 @@ +[{"id":"6e9a1f05.7f81","type":"ibmiot in","z":"b9758c03.a34b6","authentication":"apiKey","apiKey":"","inputType":"evt","deviceId":"MBED_ENDPOINT_NAME_GOES_HERE","applicationId":"","deviceType":"mbed-endpoint","eventType":"notify","commandType":"","format":"json","name":"barcode reader observations","service":"registered","allDevices":false,"allApplications":"","allDeviceTypes":false,"allEvents":false,"allCommands":"","allFormats":false,"qos":"0","x":430,"y":281.9440612792969,"wires":[["728ad60e.9bbce8"]]},{"id":"d5129024.164ca","type":"ibmiot out","z":"b9758c03.a34b6","authentication":"apiKey","apiKey":"","outputType":"cmd","deviceId":"MBED_ENDPOINT_NAME_GOES_HERE","deviceType":"mbed-endpoint","eventCommandType":"PUT","format":"json","data":"0","qos":"0","name":"set LED command (PUT)","service":"registered","x":911.0512084960938,"y":180.29727935791016,"wires":[]},{"id":"5f2c35f0.d739ac","type":"template","z":"b9758c03.a34b6","name":"LED ON","field":"payload","fieldType":"msg","format":"json","syntax":"mustache","template":"{ \"resourceId\":\"311/0/5850\", \"payload\":\"MA==\", \"deviceId\":\"MBED_ENDPOINT_NAME_GOES_HERE\", \"method\":\"PUT\" }","x":676.7462158203125,"y":207.48011779785156,"wires":[["d5129024.164ca"]]},{"id":"93a4ebe7.356748","type":"template","z":"b9758c03.a34b6","name":"LED OFF","field":"payload","fieldType":"msg","format":"json","syntax":"mustache","template":"{ \"resourceId\":\"311/0/5850\", \"payload\":\"MQ==\", \"deviceId\":\"MBED_ENDPOINT_NAME_GOES_HERE\", \"method\":\"PUT\" }","x":674.7817993164062,"y":154.6229705810547,"wires":[["d5129024.164ca"]]},{"id":"4a711f82.6011a","type":"debug","z":"b9758c03.a34b6","name":"","active":true,"console":"false","complete":"value","x":1155.380859375,"y":281.5078430175781,"wires":[]},{"id":"5dae42b3.312c2c","type":"inject","z":"b9758c03.a34b6","name":"Turn LED ON","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"x":409.90069580078125,"y":208.01576232910156,"wires":[["5f2c35f0.d739ac"]]},{"id":"d80b2f6b.25dfa","type":"inject","z":"b9758c03.a34b6","name":"Turn LED OFF","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"x":408.31353759765625,"y":154,"wires":[["93a4ebe7.356748"]]},{"id":"465a3acf.5bd724","type":"function","z":"b9758c03.a34b6","name":"Base64DecodeToValue","func":"var Base64 = {\n _keyStr: \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\",\n encode: function(e) {\n var t = \"\";\n var n, r, i, s, o, u, a;\n var f = 0;\n e = Base64._utf8_encode(e);\n while (f < e.length) {\n n = e.charCodeAt(f++);\n r = e.charCodeAt(f++);\n i = e.charCodeAt(f++);\n s = n >> 2;\n o = (n & 3) << 4 | r >> 4;\n u = (r & 15) << 2 | i >> 6;\n a = i & 63;\n if (isNaN(r)) {\n u = a = 64\n } else if (isNaN(i)) {\n a = 64\n }\n t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)\n }\n return t\n },\n decode: function(e) {\n var t = \"\";\n var n, r, i;\n var s, o, u, a;\n var f = 0;\n e = e.replace(/[^A-Za-z0-9+/=]/g, \"\");\n while (f < e.length) {\n s = this._keyStr.indexOf(e.charAt(f++));\n o = this._keyStr.indexOf(e.charAt(f++));\n u = this._keyStr.indexOf(e.charAt(f++));\n a = this._keyStr.indexOf(e.charAt(f++));\n n = s << 2 | o >> 4;\n r = (o & 15) << 4 | u >> 2;\n i = (u & 3) << 6 | a;\n t = t + String.fromCharCode(n);\n if (u != 64) {\n t = t + String.fromCharCode(r)\n }\n if (a != 64) {\n t = t + String.fromCharCode(i)\n }\n }\n t = Base64._utf8_decode(t);\n return t\n },\n _utf8_encode: function(e) {\n e = e.replace(/rn/g, \"n\");\n var t = \"\";\n for (var n = 0; n < e.length; n++) {\n var r = e.charCodeAt(n);\n if (r < 128) {\n t += String.fromCharCode(r)\n } else if (r > 127 && r < 2048) {\n t += String.fromCharCode(r >> 6 | 192);\n t += String.fromCharCode(r & 63 | 128)\n } else {\n t += String.fromCharCode(r >> 12 | 224);\n t += String.fromCharCode(r >> 6 & 63 | 128);\n t += String.fromCharCode(r & 63 | 128)\n }\n }\n return t\n },\n _utf8_decode: function(e) {\n var t = \"\";\n var n = 0;\n var r, c2;\n while (n < e.length) {\n r = e.charCodeAt(n);\n if (r < 128) {\n t += String.fromCharCode(r);\n n++\n } else if (r > 191 && r < 224) {\n c2 = e.charCodeAt(n + 1);\n t += String.fromCharCode((r & 31) << 6 | c2 & 63);\n n += 2\n } else {\n c2 = e.charCodeAt(n + 1);\n c3 = e.charCodeAt(n + 2);\n t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);\n n += 3\n }\n }\n return t\n }\n};\n\nvar str = Base64.decode(msg.payload.payload);\nreturn {\"value\":str};","outputs":1,"noerr":0,"x":910.8890991210938,"y":281.6666564941406,"wires":[["4a711f82.6011a"]]},{"id":"728ad60e.9bbce8","type":"switch","z":"b9758c03.a34b6","name":"Is Barcode Data?","property":"payload.path","propertyType":"msg","rules":[{"t":"eq","v":"/888/0/7700","vt":"str"}],"checkall":"true","outputs":1,"x":684.7778930664062,"y":281.6666564941406,"wires":[["465a3acf.5bd724"]]}] \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c USBDevice.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBDevice.lib Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,1 @@ +https://developer.mbed.org/users/mbed_official/code/USBDevice/#01321bd6ff89
diff -r 000000000000 -r ad834d403a8c main.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,81 @@ +/** + * @file main.cpp + * @brief mbed Endpoint Sample main + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + +// Our device type +#define MY_DEVICE_TYPE "mbed-endpoint" + +// Include security.h +#include "security.h" + +// mbed Endpoint Network +#include "mbed-connector-interface/mbedEndpointNetwork.h" + +// Logger +#include "mbed-connector-interface/Logger.h" +Serial pc(USBTX,USBRX); +Logger logger(&pc); + +// LED Resource +#include "mbed-endpoint-resources/LEDResource.h" +LEDResource led(&logger,"311","5850"); + +// ZXing Resource +#include "mbed-endpoint-resources/ZXingResource.h" +ZXingResource barcodedecode(&logger,"888","7700",true); + +// called from the Endpoint::start() below to create resources and the endpoint internals... +Connector::Options *configure_endpoint(Connector::OptionsBuilder &config) +{ + // Build the endpoint configuration parameters + logger.logging("Endpoint::main (%s): customizing endpoint configuration...",net_get_type()); + return config + // PROVISIONING: set the Provisioning Credentials (all from security.h) + .setEndpointNodename(MBED_ENDPOINT_NAME) + .setDomain(MBED_DOMAIN) + .setEndpointType(MY_DEVICE_TYPE) + .setServerCertificate((uint8_t *)SERVER_CERT,(int)sizeof(SERVER_CERT)) + .setClientCertificate((uint8_t *)CERT,(int)sizeof(CERT)) + .setClientKey((uint8_t *)KEY,(int)sizeof(KEY)) + + // Add my specific physical resources... + .addResource(&led) + .addResource(&barcodedecode,(bool)false) // on demand observation + + // finalize the configuration... + .build(); +} + +// main entry point... +int main() +{ + // set Serial + pc.baud(115200); + + // Announce + logger.logging("\r\n\r\nmbed Connector Sample Endpoint - TechCon2016 (%s)",net_get_type()); + + // we have to plumb our network first + Connector::Endpoint::plumbNetwork(); + + // starts the endpoint by finalizing its configuration (configure_endpoint() above gets called...) + Connector::Endpoint::start(); +}
diff -r 000000000000 -r ad834d403a8c mbed-endpoint-resources/LEDResource.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-endpoint-resources/LEDResource.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,62 @@ +/** + * @file LEDResource.h + * @brief mbed CoAP Endpoint LED resource supporting CoAP PUT + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __LED_RESOURCE_H__ +#define __LED_RESOURCE_H__ + +// Base class +#include "mbed-connector-interface/DynamicResource.h" + +// our LED sensor +DigitalOut __light(LED3); + +// possible LED states +#define LEDOFF "1" +#define LEDON "0" + +/** LEDResource class + */ +class LEDResource : public DynamicResource +{ + +public: + /** + Default constructor + @param logger input logger instance for this resource + @param obj_name input the LED Object name + @param res_name input the LED Resource name + @param observable input the resource is Observable (default: FALSE) + */ + LEDResource(const Logger *logger,const char *obj_name,const char *res_name,const bool observable = false) : DynamicResource(logger,obj_name,res_name,"LED",M2MBase::PUT_ALLOWED,observable) { + } + + /** + Set the value of the LED + @param string input the string containing "0" (light off) or "1" (light on) + */ + virtual void put(const string value) { + if (value.compare(string(LEDOFF)) == 0) __light = 0; + else __light = 1; + } +}; + +#endif // __LED_RESOURCE_H__
diff -r 000000000000 -r ad834d403a8c mbed-endpoint-resources/ZXingResource.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-endpoint-resources/ZXingResource.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,512 @@ +/** + * @file ZXingResource.h + * @brief mbed CoAP Endpoint Accelerometer sensor resource supporting CoAP GET + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __ZXING_RESOURCE_H__ +#define __ZXING_RESOURCE_H__ + +// Base class +#include "mbed-connector-interface/DynamicResource.h" + +#include "DisplayBace.h" +#include "ImageReaderSource.h" +#include "DisplayApp.h" +#include "AsciiFont.h" + +// forward declarations +static void *_instance = NULL; +extern "C" void _zxing_processing(const void *args); +extern "C" void _zxing_loop(void); + +#define VIDEO_CVBS (0) /* Analog Video Signal */ +#define VIDEO_CMOS_CAMERA (1) /* Digital Video Signal */ +#define VIDEO_RGB888 (1) + +/**** User Selection *********/ +/** Camera setting **/ +#define VIDEO_INPUT_METHOD (VIDEO_CMOS_CAMERA) /* Select VIDEO_CVBS or VIDEO_CMOS_CAMERA */ +#define VIDEO_INPUT_FORMAT (VIDEO_RGB888) /* Select VIDEO_RGB888 */ +#define USE_VIDEO_CH (0) /* Select 0 or 1 If selecting VIDEO_CMOS_CAMERA, should be 0.) */ +#define VIDEO_PAL (0) /* Select 0(NTSC) or 1(PAL) If selecting VIDEO_CVBS, this parameter is not referenced.) */ +/** LCD setting **/ +#define LCD_ONOFF (1) /* Select 0(without LCD) or 1(with LCD) */ +#if LCD_ONOFF +#define LCD_TYPE (0) /* Select 0(4.3inch) or 1(7.1inch) */ +#endif +/*****************************/ + +#if LCD_ONOFF +/** LCD shield config **/ +#if (LCD_TYPE == 0) + #include "LCD_shield_config_4_3inch.h" +#else + #include "LCD_shield_config_7_1inch.h" +#endif +#endif + +/** Video and Grapics (GRAPHICS_LAYER_0) parameter **/ +/* video input */ +#if USE_VIDEO_CH == (0) + #define VIDEO_INPUT_CH (DisplayBase::VIDEO_INPUT_CHANNEL_0) + #define VIDEO_INT_TYPE (DisplayBase::INT_TYPE_S0_VFIELD) +#else + #define VIDEO_INPUT_CH (DisplayBase::VIDEO_INPUT_CHANNEL_1) + #define VIDEO_INT_TYPE (DisplayBase::INT_TYPE_S1_VFIELD) +#endif + +/* NTSC or PAL */ +#if VIDEO_PAL == 0 + #define COL_SYS (DisplayBase::COL_SYS_NTSC_358) +#else + #define COL_SYS (DisplayBase::COL_SYS_PAL_443) +#endif + +/* Video input */ +#define VIDEO_FORMAT (DisplayBase::VIDEO_FORMAT_RGB888) +#define GRAPHICS_FORMAT (DisplayBase::GRAPHICS_FORMAT_RGB888) +#define WR_RD_WRSWA (DisplayBase::WR_RD_WRSWA_32BIT) + +/* The size of the video input */ +#if ((LCD_ONOFF) && (LCD_TYPE == 0)) + #define VIDEO_PIXEL_HW LCD_PIXEL_WIDTH + #define VIDEO_PIXEL_VW LCD_PIXEL_HEIGHT +#else + #define VIDEO_PIXEL_HW (640) /* VGA */ + #define VIDEO_PIXEL_VW (480) /* VGA */ +#endif + +/*! Frame buffer stride: Frame buffer stride should be set to a multiple of 32 or 128 + in accordance with the frame buffer burst transfer mode. */ +/* FRAME BUFFER Parameter GRAPHICS_LAYER_0 */ +#define FRAME_BUFFER_NUM (2u) +#define FRAME_BUFFER_BYTE_PER_PIXEL (4u) +#define FRAME_BUFFER_STRIDE (((VIDEO_PIXEL_HW * FRAME_BUFFER_BYTE_PER_PIXEL) + 31u) & ~31u) + +#if LCD_ONOFF +#define VIDEO_PIXEL_HW_STR (VIDEO_PIXEL_HW - 64) +#define VIDEO_PIXEL_VW_STR (VIDEO_PIXEL_VW - 64) +#define FRAME_BUFFER_BYTE_PER_PIXEL_STR (2u) +#define FRAME_BUFFER_STRIDE_STR (((VIDEO_PIXEL_HW_STR * FRAME_BUFFER_BYTE_PER_PIXEL_STR) + 31u) & ~31u) +#endif + +static DisplayBase Display; +static DisplayApp display_app; +static Timer decode_timer; +#if LCD_ONOFF +static DigitalOut lcd_pwon(P7_15); +static DigitalOut lcd_blon(P8_1); +static PwmOut lcd_cntrst(P8_15); +#endif + +/* 32 bytes aligned */ +static uint8_t user_frame_buffer0[FRAME_BUFFER_STRIDE * VIDEO_PIXEL_VW]__attribute((aligned(32))); +static uint8_t user_frame_buffer1[FRAME_BUFFER_STRIDE * VIDEO_PIXEL_VW]__attribute((aligned(32))); +#if LCD_ONOFF +static uint8_t user_frame_buffer_string[FRAME_BUFFER_STRIDE_STR * VIDEO_PIXEL_VW_STR]__attribute((aligned(32))); +static AsciiFont ascii_font(user_frame_buffer_string, VIDEO_PIXEL_HW_STR, VIDEO_PIXEL_VW_STR, FRAME_BUFFER_STRIDE_STR, FRAME_BUFFER_BYTE_PER_PIXEL_STR); +static bool string_draw; +#endif +static uint8_t * decode_buffer = user_frame_buffer0; +static uint8_t * FrameBufferTbl[FRAME_BUFFER_NUM] = {user_frame_buffer0, user_frame_buffer1}; +static volatile int32_t vfield_count = 0; +static int write_buff_num = 0; +static bool graphics_init_end = false; +static int decode_wait_time = 0; + +vector<Ref<Result> > results; +char ** decode_str; + +/****** cache control ******/ +static void dcache_clean(void * p_buf, uint32_t size) { + uint32_t start_addr = (uint32_t)p_buf & 0xFFFFFFE0; + uint32_t end_addr = (uint32_t)p_buf + size; + uint32_t addr; + + /* Data cache clean */ + for (addr = start_addr; addr < end_addr; addr += 0x20) { + __v7_clean_dcache_mva((void *)addr); + } +} + +static void dcache_invalid(void * p_buf, uint32_t size){ + uint32_t start_addr = (uint32_t)p_buf & 0xFFFFFFE0; + uint32_t end_addr = (uint32_t)p_buf + size; + uint32_t addr; + + /* Data cache invalid */ + for (addr = start_addr; addr < end_addr; addr += 0x20) { + __v7_inv_dcache_mva((void *)addr); + } +} + +#if LCD_ONOFF +/****** LCD ******/ +static void Init_LCD_Display(void) { + DisplayBase::graphics_error_t error; + DisplayBase::lcd_config_t lcd_config; + PinName lvds_pin[8] = { + /* data pin */ + P5_7, P5_6, P5_5, P5_4, P5_3, P5_2, P5_1, P5_0 + }; + + lcd_pwon = 0; + lcd_blon = 0; + Thread::wait(100); + lcd_pwon = 1; + lcd_blon = 1; + + Display.Graphics_Lvds_Port_Init(lvds_pin, 8); + + /* Graphics initialization process */ + lcd_config = LcdCfgTbl_LCD_shield; + error = Display.Graphics_init(&lcd_config); + if (error != DisplayBase::GRAPHICS_OK) { + printf("Line %d, error %d\n", __LINE__, error); + mbed_die(); + } + graphics_init_end = true; +} + +static void Start_LCD_Display(uint8_t * p_buf) { + DisplayBase::rect_t rect; + + rect.vs = 0; + rect.vw = VIDEO_PIXEL_VW; + rect.hs = 0; + rect.hw = VIDEO_PIXEL_HW; + Display.Graphics_Read_Setting( + DisplayBase::GRAPHICS_LAYER_0, + (void *)p_buf, + FRAME_BUFFER_STRIDE, + GRAPHICS_FORMAT, + WR_RD_WRSWA, + &rect + ); + Display.Graphics_Start(DisplayBase::GRAPHICS_LAYER_0); +} +#endif + +/****** Video ******/ +static void IntCallbackFunc_Vfield(DisplayBase::int_type_t int_type) { + /* Interrupt callback function for Vfield interruption */ + if (vfield_count > 0) { + vfield_count--; + } +} + +static void Wait_Vfield(const int32_t wait_count) { + /* Wait for the specified number of times Vsync occurs */ + vfield_count = wait_count; + while (vfield_count > 0) { + Thread::wait(1); + } +} + +static void Init_Video(void) { + DisplayBase::graphics_error_t error; + + /* Graphics initialization process */ + if (graphics_init_end == false) { + /* When not initializing LCD, this processing is needed. */ + error = Display.Graphics_init(NULL); + if (error != DisplayBase::GRAPHICS_OK) { + printf("Line %d, error %d\n", __LINE__, error); + mbed_die(); + } + graphics_init_end = true; + } + +#if VIDEO_INPUT_METHOD == VIDEO_CVBS + error = Display.Graphics_Video_init( DisplayBase::INPUT_SEL_VDEC, NULL); + if( error != DisplayBase::GRAPHICS_OK ) { + printf("Line %d, error %d\n", __LINE__, error); + mbed_die(); + } +#elif VIDEO_INPUT_METHOD == VIDEO_CMOS_CAMERA + DisplayBase::video_ext_in_config_t ext_in_config; + PinName cmos_camera_pin[11] = { + /* data pin */ + P2_7, P2_6, P2_5, P2_4, P2_3, P2_2, P2_1, P2_0, + /* control pin */ + P10_0, /* DV0_CLK */ + P1_0, /* DV0_Vsync */ + P1_1 /* DV0_Hsync */ + }; + + /* MT9V111 camera input config */ + ext_in_config.inp_format = DisplayBase::VIDEO_EXTIN_FORMAT_BT601; /* BT601 8bit YCbCr format */ + ext_in_config.inp_pxd_edge = DisplayBase::EDGE_RISING; /* Clock edge select for capturing data */ + ext_in_config.inp_vs_edge = DisplayBase::EDGE_RISING; /* Clock edge select for capturing Vsync signals */ + ext_in_config.inp_hs_edge = DisplayBase::EDGE_RISING; /* Clock edge select for capturing Hsync signals */ + ext_in_config.inp_endian_on = DisplayBase::OFF; /* External input bit endian change on/off */ + ext_in_config.inp_swap_on = DisplayBase::OFF; /* External input B/R signal swap on/off */ + ext_in_config.inp_vs_inv = DisplayBase::SIG_POL_NOT_INVERTED; /* External input DV_VSYNC inversion control */ + ext_in_config.inp_hs_inv = DisplayBase::SIG_POL_INVERTED; /* External input DV_HSYNC inversion control */ + ext_in_config.inp_f525_625 = DisplayBase::EXTIN_LINE_525; /* Number of lines for BT.656 external input */ + ext_in_config.inp_h_pos = DisplayBase::EXTIN_H_POS_CRYCBY; /* Y/Cb/Y/Cr data string start timing to Hsync reference */ + ext_in_config.cap_vs_pos = 6; /* Capture start position from Vsync */ + ext_in_config.cap_hs_pos = 150; /* Capture start position form Hsync */ +#if ((LCD_ONOFF) && (LCD_TYPE == 0)) + /* The same screen ratio as the screen ratio of the LCD. */ + ext_in_config.cap_width = 640; /* Capture width */ + ext_in_config.cap_height = 363; /* Capture height Max 468[line] + Due to CMOS(MT9V111) output signal timing and VDC5 specification */ +#else + ext_in_config.cap_width = 640; /* Capture width */ + ext_in_config.cap_height = 468; /* Capture height Max 468[line] + Due to CMOS(MT9V111) output signal timing and VDC5 specification */ +#endif + error = Display.Graphics_Video_init( DisplayBase::INPUT_SEL_EXT, &ext_in_config); + if( error != DisplayBase::GRAPHICS_OK ) { + printf("Line %d, error %d\n", __LINE__, error); + mbed_die(); + } + + /* Camera input port setting */ + error = Display.Graphics_Dvinput_Port_Init(cmos_camera_pin, 11); + if( error != DisplayBase::GRAPHICS_OK ) { + printf("Line %d, error %d\n", __LINE__, error); + mbed_die(); + } +#endif + + /* Interrupt callback function setting (Field end signal for recording function in scaler 0) */ + error = Display.Graphics_Irq_Handler_Set(VIDEO_INT_TYPE, 0, IntCallbackFunc_Vfield); + if (error != DisplayBase::GRAPHICS_OK) { + printf("Line %d, error %d\n", __LINE__, error); + mbed_die(); + } +} + +static void Start_Video(uint8_t * p_buf) { + DisplayBase::graphics_error_t error; + + /* Video capture setting (progressive form fixed) */ + error = Display.Video_Write_Setting( + VIDEO_INPUT_CH, + COL_SYS, + p_buf, + FRAME_BUFFER_STRIDE, + VIDEO_FORMAT, + WR_RD_WRSWA, + VIDEO_PIXEL_VW, + VIDEO_PIXEL_HW + ); + if (error != DisplayBase::GRAPHICS_OK) { + printf("Line %d, error %d\n", __LINE__, error); + mbed_die(); + } + + /* Video write process start */ + error = Display.Video_Start(VIDEO_INPUT_CH); + if (error != DisplayBase::GRAPHICS_OK) { + printf("Line %d, error %d\n", __LINE__, error); + mbed_die(); + } + + /* Video write process stop */ + error = Display.Video_Stop(VIDEO_INPUT_CH); + if (error != DisplayBase::GRAPHICS_OK) { + printf("Line %d, error %d\n", __LINE__, error); + mbed_die(); + } + + /* Video write process start */ + error = Display.Video_Start(VIDEO_INPUT_CH); + if (error != DisplayBase::GRAPHICS_OK) { + printf("Line %d, error %d\n", __LINE__, error); + mbed_die(); + } +} + +/** + * ZXingResource class + */ +class ZXingResource : public DynamicResource +{ +private: + Thread * m_zxing_processor; + +public: + /** + Default constructor + @param logger input logger instance for this resource + @param obj_name input the Accelerometer Object name + @param res_name input the Accelerometer Resource name + @param observable input the resource is Observable (default: FALSE) + */ + + ZXingResource(const Logger *logger,const char *obj_name,const char *res_name,const bool observable = false) : DynamicResource(logger,obj_name,res_name,"ZXing",M2MBase::GET_ALLOWED,observable) { + // init + _instance = (void *)this; + +#if LCD_ONOFF + // Initialze LCD + Init_LCD_Display(); +#endif + // Initialize Video + Init_Video(); + + // Initialize frame buffer + for (int i = 0; i < FRAME_BUFFER_NUM; i++) { + memset(FrameBufferTbl[i], 0, (FRAME_BUFFER_STRIDE * VIDEO_PIXEL_VW)); + dcache_clean(FrameBufferTbl[i], (FRAME_BUFFER_STRIDE * VIDEO_PIXEL_VW)); + } + + // Start Video + Start_Video(FrameBufferTbl[write_buff_num]); + /* Wait for first video drawing */ + Wait_Vfield(2); + +#if LCD_ONOFF + DisplayBase::rect_t rect; + + /* The layer by which the touch panel location is drawn */ + ascii_font.Erase(0x00000000); /* rrrrGBAR (r:Reserve G:Green B:Blue A:Alpha R:Red */ + dcache_clean(user_frame_buffer_string, sizeof(user_frame_buffer_string)); + rect.vs = 32; + rect.vw = VIDEO_PIXEL_VW_STR; + rect.hs = 32; + rect.hw = VIDEO_PIXEL_HW_STR; + Display.Graphics_Read_Setting( + DisplayBase::GRAPHICS_LAYER_1, + (void *)user_frame_buffer_string, + FRAME_BUFFER_STRIDE_STR, + DisplayBase::GRAPHICS_FORMAT_ARGB4444, + DisplayBase::WR_RD_WRSWA_32_16BIT, + &rect + ); + Display.Graphics_Start(DisplayBase::GRAPHICS_LAYER_1); + string_draw = false; + /* Start of LCD */ + Start_LCD_Display(FrameBufferTbl[write_buff_num]); + /* Backlight on */ + Thread::wait(200); + lcd_cntrst.write(1.0); +#endif + decode_timer.reset(); + decode_timer.start(); + + // no Thread yet + this->m_zxing_processor = NULL; + } + + /** + Get the value of the barcode data + @returns string containing the acclerometer sensor value + */ + virtual string get() { +#if 1 + if (this->m_zxing_processor == NULL) { + // create the processing thread + this->m_zxing_processor = new Thread(_zxing_processing); + } + + if (*decode_str == NULL) { + return string("0\0"); + } else { + return string(*decode_str); + } + +#endif + } +}; + +void _zxing_processing(const void *args) { + while (true) { + _zxing_loop(); + Thread::wait(5); + } +} + +void _zxing_loop(void) { + DisplayBase::graphics_error_t error; + int decode_result = -1; + +#if 1 + decode_buffer = FrameBufferTbl[write_buff_num]; + write_buff_num++; + + if (write_buff_num >= FRAME_BUFFER_NUM) { + write_buff_num = 0; + } + /* Change video buffer */ + error = Display.Video_Write_Change(VIDEO_INPUT_CH, FrameBufferTbl[write_buff_num], FRAME_BUFFER_STRIDE); + if (error != DisplayBase::GRAPHICS_OK) { + printf("Line %d, error %d\n", __LINE__, error); + mbed_die(); + } + Wait_Vfield(2); +#if LCD_ONOFF + /* Change LCD buffer */ + Display.Graphics_Read_Change(DisplayBase::GRAPHICS_LAYER_0, (void *)FrameBufferTbl[write_buff_num]); +#endif + dcache_invalid(decode_buffer, (FRAME_BUFFER_STRIDE * VIDEO_PIXEL_VW)); + /* Decode barcode image */ + if (decode_timer.read_ms() >= decode_wait_time) { + decode_timer.reset(); + decode_result = ex_decode(decode_buffer, (FRAME_BUFFER_STRIDE * VIDEO_PIXEL_VW), VIDEO_PIXEL_HW, VIDEO_PIXEL_VW, &results); + if (decode_result == 0) { + decode_str = (char **)&(results[0]->getText()->getText()); + + if (_instance != NULL) { + // observe... + ((ZXingResource *)_instance)->observe(); + } + +#if LCD_ONOFF + /* Drow string */ + ascii_font.Erase(0x00000090); /* rrrrGBAR (r:Reserve G:Green B:Blue A:Alpha R:Red */ + int rest_size = strlen(*decode_str); + int draw_idx = 0; + int draw_size; + int draw_line = 0; + + while (rest_size > 0) { + draw_size = ascii_font.DrawStr(*decode_str + draw_idx, 6, 5 + (18 * draw_line), 0x0000ffff, 2); + if (draw_size <= 0) { + break; + } + rest_size -= draw_size; + draw_idx += draw_size; + draw_line++; + } + + dcache_clean(user_frame_buffer_string, sizeof(user_frame_buffer_string)); + string_draw = true; +#endif + decode_wait_time = 500; + } else { +#if LCD_ONOFF + if (string_draw != false) { + /* Clear string */ + ascii_font.Erase(0x00000000); /* rrrrGBAR (r:Reserve G:Green B:Blue A:Alpha R:Red */ + dcache_clean(user_frame_buffer_string, sizeof(user_frame_buffer_string)); + string_draw = false; + } +#endif + decode_wait_time = 10; + } + } + display_app.SendRgb888(decode_buffer, VIDEO_PIXEL_HW, VIDEO_PIXEL_VW); +#endif +} +#endif // __ZXING_RESOURCE_H__
diff -r 000000000000 -r ad834d403a8c mbed-os.lib --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-os.lib Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,1 @@ +https://github.com/Osamu-Nakamura/mbed-os/#0ad5d4d3122cf9192596df791b129b7fe7d3e118 \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/.mbed --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/.mbed Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,1 @@ +ROOT=.
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/Authenticator.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/Authenticator.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,67 @@ +/** + * @file Authenticator.h + * @brief mbed CoAP Endpoint Device Management Authenticator class + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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 __DM_AUTHENTICATOR_H__ +#define __DM_AUTHENTICATOR_H__ + +// Logger +#include "mbed-connector-interface/Logger.h" + +class Authenticator { + public: + /** + Default constructor + @param logger input logger instance + @param secret input secret + */ + Authenticator(const Logger *logger,const void *secret = NULL); + + /** + Copy constructor + @param resource input the Authenticator that is to be deep copied + */ + Authenticator(const Authenticator &manager); + + /** + Destructor + */ + virtual ~Authenticator(); + + /** + Set the secret + @param secret input the secret + */ + virtual void setSecret(void *secret); + + /** + Authenticate + @param challenge input the challenge to authenticate with + @return true - authenciated successfully, false - otherwise + */ + virtual bool authenticate(void *challenge); + + protected: + Logger *m_logger; + void *m_secret; +}; + +#endif // __DM_AUTHENTICATOR_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/ConnectionStatusInterface.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/ConnectionStatusInterface.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,85 @@ +/** + * @file ConnectionStatusInterface.h + * @brief ConnectionStatusInterface (header) + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __CONNECTION_STATUS_INTERFACE_H__ +#define __CONNECTION_STATUS_INTERFACE_H__ + +// mbedConnectorInterface configuration +#include "mbed-connector-interface/mbedConnectorInterface.h" + +// mbed support +#if defined(MCI_USE_YOTTA) + // mbed support + #include "mbed-drivers/mbed.h" +#else + // mbed support + #include "mbed.h" +#endif + +// Connector namespace +namespace Connector { + +class ConnectionStatusInterface { + public: + // Default constructor + ConnectionStatusInterface(); + + // Copy constructor + ConnectionStatusInterface(ConnectionStatusInterface &csi); + + // Destructor + virtual ~ConnectionStatusInterface(); + + /** + Registered + */ + virtual void object_registered(void *ep,void *security,void *data = NULL); + + /** + Re-registered + */ + virtual void registration_updated(void *ep,void *security,void *data = NULL); + + /** + Beginning de-registration + */ + virtual void begin_object_unregistering(void *ep); + + /** + De-registered + */ + virtual void object_unregistered(void *ep,void *data = NULL); + + /** + Bootstrapped + */ + virtual void bootstrapped(void *ep,void *data = NULL); + + /** + Value Updated + */ + virtual void value_updated(void *ep,void *data,int type); + }; + + } // namespace Connector + + #endif // __CONNECTION_STATUS_INTERFACE_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/ConnectorEndpoint.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/ConnectorEndpoint.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,203 @@ +/** + * @file Endpoint.h + * @brief mbed CoAP Endpoint base class + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __CONNECTOR_ENDPOINT_H__ +#define __CONNECTOR_ENDPOINT_H__ + +// mbed-client support +#include "mbed-client/m2minterfacefactory.h" +#include "mbed-client/m2minterfaceobserver.h" +#include "mbed-client/m2minterface.h" +#include "mbed-client/m2mobjectinstance.h" +#include "mbed-client/m2mresource.h" +#include "mbed-client/m2mdevice.h" +#include "mbed-client/m2mfirmware.h" + +// Support for Logging/Debug output +#include "mbed-connector-interface/Logger.h" + +// Options support +#include "mbed-connector-interface/Options.h" + +// ConnectionStatusInterface support +#include "mbed-connector-interface/ConnectionStatusInterface.h" + +// ObjectInstanceManager support +#include "mbed-connector-interface/ObjectInstanceManager.h" + +// Connector namespace +namespace Connector { + +/** Endpoint class + */ +class Endpoint : public M2MInterfaceObserver { + +public: + /** + Default Constructor + */ + Endpoint(const Logger *logger,const Options *ob); + + /** + Copy Constructor + @param ob input endpoint instance to deep copy + */ + Endpoint(const Endpoint &ep); + + /** + Destructor + */ + virtual ~Endpoint(); + + /** + Build out the endpoint. + */ + void buildEndpoint(); + + /** + Plumb the lower RF network stack + @param device_manager input optional device manager (DeviceManager type) + @param canActAsRouterNode input boolean indicating whether this node can act as a router node or not. + */ + static void plumbNetwork(void *device_manager = NULL,bool canActAsRouterNode = false); + + /** + Initialize the endpoint's configuration and begin the endpoint's main even loop + */ + static void start(); + + /** + Set the ConnectionStatusInterface instance + @param csi input instance pointer to the ConnectionStatusInterface implementation to be used + */ + static void setConnectionStatusInterface(ConnectionStatusInterface *csi); + + // register the endpoint + void register_endpoint(M2MSecurity *server_instance, M2MObjectList resources); + + // re-register endpoint + void re_register_endpoint(); + + // de-register endpoint and stop scheduling + void de_register_endpoint(void); + + // mbed-client : object registered + virtual void object_registered(M2MSecurity *server_instance, const M2MServer &server); + + // mbed-client : registration updated + virtual void registration_updated(M2MSecurity *server_instance, const M2MServer &server) ; + + // mbed-client : object unregistered + virtual void object_unregistered(M2MSecurity *server_instance); + + // mbed-client : bootstrap done + virtual void bootstrap_done(M2MSecurity *server_instance); + + // mbed-client : resource value updated + virtual void value_updated(M2MBase *resource, M2MBase::BaseType type) ; + + // mbed-client : error handler + virtual void error(M2MInterface::Error error); + + // get our Options + void setOptions(Options *options); + + // get our Options + Options *getOptions(); + + // get our Endpoint Interface + M2MInterface *getEndpointInterface(); + + // get our Endpoint Security + M2MSecurity *getEndpointSecurity(); + + // get our Endpoint Object List + M2MObjectList getEndpointObjectList(); + + // configure to act as router node + void asRouterNode(bool canActAsRouterNode); + + // access the logger + Logger *logger(); + + // set the device manager + void setDeviceManager(void *device_manager); + + // get the device manager + void *getDeviceManager(void); + + // underlying network is connected (SET) + void isConnected(bool connected); + + // underlying network is connected (GET) + bool isConnected(); + + // Registered with mDC/mDS + bool isRegistered(); + + /** + Set the ConnectionStatusInterface instance + @param csi input instance pointer to the ConnectionStatusInterface implementation to be used + */ + void setConnectionStatusInterfaceImpl(ConnectionStatusInterface *csi); + + // Set ObjectInstanceManager + void setObjectInstanceManager(ObjectInstanceManager *oim); + + // Get ObjectInstanceManager + ObjectInstanceManager *getObjectInstanceManager(); + +private: + Logger *m_logger; + Options *m_options; + bool m_canActAsRouterNode; + bool m_connected; + bool m_registered; + + // mbed-client support + M2MInterface *m_endpoint_interface; + M2MSecurity *m_endpoint_security; + M2MObjectList m_endpoint_object_list; + + // Device Manager + void *m_device_manager; + + // ConnectionStatusInterface implementation + ConnectionStatusInterface *m_csi; + + // ObjectInstanceManager + ObjectInstanceManager *m_oim; + + // mbed-client methods + void createEndpointInterface(); + M2MSecurity *createEndpointInstance(); + + // DynamicResource Lookup + DynamicResource *lookupDynamicResource(M2MBase *base); + + // stop underlying observers + void stopObservations(); +}; + +} // namespace Connector + +#endif // __CONNECTOR_ENDPOINT_H__
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/DataWrapper.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/DataWrapper.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,112 @@ +/** + * @file DataWrapper.h + * @brief mbed CoAP Endpoint Data Wrapper class (header) + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __DATA_WRAPPER_H__ +#define __DATA_WRAPPER_H__ + +// mbedConnectorInterface configuration +#include "mbed-connector-interface/mbedConnectorInterface.h" + +// mbed support +#if defined(MCI_USE_YOTTA) + // mbed support + #include "mbed-drivers/mbed.h" +#else + // mbed support + #include "mbed.h" +#endif + +class DataWrapper { + public: + /** + Default constructor + @param data input the buffer to use for operations + @param data_length input the data length + */ + DataWrapper(uint8_t *data,int data_length); + + /** + Default constructor (alloc) + @param data_length input the data length (alloc) + */ + DataWrapper(int data_length); + + /** + Default copy constructor + @param data input the DataWrapper to copy + */ + DataWrapper(const DataWrapper &data); + + /** + Destructor + */ + virtual ~DataWrapper(); + + /** + Wrap the data (trivial in base class) + @param data input the data to wrap + @param data_length input the length of the data to wrap + */ + virtual void wrap(uint8_t *data,int data_length); + + /** + Unwrap the data (trivial in base class) + @param data input the data to unwrap + @param data_length input the length of the data to unwrap + */ + virtual void unwrap(uint8_t *data,int data_length); + + /** + Get the wrap/unwrap result + @return pointer to the data buffer of DataWrapper containing the wrap/unwrap result + */ + uint8_t *get() { return this->m_data; } + + /** + Get the wrap/unwrap result length + @return length of the wrap/unwrap data result + */ + int length() { return this->m_data_length; } + + /** + Reset the wrapper + */ + void reset(); + + /** + Set the new application key + @param appkey input the new appkey (encrypted) to set + @param appkey_length input the new appkey (encrypted) length + */ + virtual void setAppKey(uint8_t *appkey,int appkey_length); + + protected: + uint8_t *m_data; + + private: + bool m_alloced; + int m_data_length; + int m_data_length_max; +}; + +#endif // __DATA_WRAPPER_H__ +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/DeviceDeRegisterResource.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/DeviceDeRegisterResource.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,64 @@ +/** + * @file DeviceDeRegisterResource.h + * @brief mbed CoAP Endpoint Device DeRegister Resource + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __DEVICE_DEREGISTER_RESOURCE_H__ +#define __DEVICE_DEREGISTER_RESOURCE_H__ + +// Base class +#include "mbed-connector-interface/DynamicResource.h" + +// Device Management Responder +#include "mbed-connector-interface/DeviceManagementResponder.h" + +/** DeviceDeRegisterResource class + */ +class DeviceDeRegisterResource : public DynamicResource +{ +public: + /** + Default constructor + @param logger input logger instance for this resource + @param obj_name input the Light Object name + @param res_name input the Light Resource name + @param dm_responder input the DM responder instance + */ + DeviceDeRegisterResource(const Logger *logger,const char *obj_name,const char *res_name,const void *dm_responder,bool observable = false) : + DynamicResource(logger,obj_name,res_name,"deregistration",M2MBase::POST_ALLOWED,observable) + { + this->m_dm_responder = (DeviceManagementResponder *)dm_responder; + this->m_value = string("OK"); + } + + /** + POST handler + @param value input input value (DM authentication challenge) + */ + virtual void post(void *args) { + // perform our action + this->m_dm_responder->deregisterDevice(args); + } + +protected: + DeviceManagementResponder *m_dm_responder; +}; + +#endif // __DEVICE_DEREGISTER_RESOURCE_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/DeviceManagementResponder.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/DeviceManagementResponder.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,181 @@ +/** + * @file DeviceManagementResponder.h + * @brief mbed CoAP Endpoint Device Management Responder class + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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 __DEVICE_MANAGEMENT_RESPONDER_H__ +#define __DEVICE_MANAGEMENT_RESPONDER_H__ + +// Logger +#include "mbed-connector-interface/Logger.h" + +// Authenticator Support +#include "mbed-connector-interface/Authenticator.h" + +// invocation handler signature +typedef void (*initialize_fn)(const void *logger); +typedef bool (*manifest_fn)(const void *ep,const void *logger,const void *manifest,uint32_t manifest_length); +typedef bool (*image_set_fn)(const void *ep,const void *logger,const void *image,uint32_t image_length); +typedef bool (*responder_fn)(const void *ep,const void *logger,const void *data); + +class DeviceManagementResponder { + public: + /** + Default constructor + @param logger input logger instance + @param authenticator input authentication instance + */ + DeviceManagementResponder(const Logger *logger,const Authenticator *authenticator); + + /** + Copy constructor + @param resource input the DeviceManagementResponder that is to be deep copied + */ + DeviceManagementResponder(const DeviceManagementResponder &manager); + + /** + Destructor + */ + virtual ~DeviceManagementResponder(); + + /** + Set the Endpoint instance + @param ep input the endpoint instance pointer + */ + void setEndpoint(const void *ep); + + /** + Set our Initialize handler function + @param initialize_fn input the device initialize function pointer + */ + void setInitializeHandler(initialize_fn initialize_fn); + + /** + Set our Reboot Responder handler function + @param reboot_responder_fn input the device reboot responder function pointer + */ + void setRebootResponderHandler(responder_fn reboot_responder_fn); + + /** + Set our Reset Responder handler function + @param reset_responder_fn input the device reset responder function pointer + */ + void setResetResponderHandler(responder_fn reset_responder_fn); + + /** + Set our FOTA manifest handler function + @param fota_manifest_fn input the FOTA manifest handler function pointer + */ + void setFOTAManifestHandler(manifest_fn fota_manifest_fn); + + /** + Set our FOTA image set handler function + @param fota_image_set_fn input the FOTA image set function pointer + */ + void setFOTAImageHandler(image_set_fn fota_image_set_fn); + + /** + Set our FOTA invocation handler function + @param fota_invocation_fn input the FOTA invocation handler function pointer + */ + void setFOTAInvocationHandler(responder_fn fota_invocation_fn); + + /** + ACTION: Deregister device + @param challenge input the input authentication challenge + */ + virtual void deregisterDevice(const void *challenge); + + /** + ACTION: Reboot device + @param challenge input the input authentication challenge + */ + virtual void rebootDevice(const void *challenge); + + /** + ACTION: Reset device + @param challenge input the input authentication challenge + */ + virtual void resetDevice(const void *challenge); + + /** + Set our FOTA manifest + @param manifest input the FOTA manifest + @param manifest_length input the length of the FOTA manifest + */ + virtual void setFOTAManifest(char *manifest,uint32_t manifest_length); + + /** + Get our FOTA manifest + @return the FOTA manifest + */ + virtual char *getFOTAManifest(); + + /** + Get our FOTA manifest length + @return the FOTA manifest length + */ + virtual uint32_t getFOTAManifestLength(); + + /** + Set our FOTA image + @param fota_image input the FOTA image + @param fota_image_length input the length of the fota image + */ + virtual void setFOTAImage(void *fota_image,uint32_t fota_image_length); + + /** + Get our FOTA image + @return the FOTA image + */ + virtual void *getFOTAImage(); + + /** + Get our FOTA image length + @return the FOTA image length + */ + virtual uint32_t getFOTAImageLength(); + + /** + ACTION: Invoke FOTA (default: empty action) + @param challenge input the input authentication challenge + */ + virtual void invokeFOTA(const void *challenge); + + private: + Logger *m_logger; + Authenticator *m_authenticator; + void *m_endpoint; + char *m_manifest; + int m_manifest_length; + void *m_fota_image; + uint32_t m_fota_image_length; + + initialize_fn m_initialize_fn; + responder_fn m_reboot_responder_fn; + responder_fn m_reset_responder_fn; + manifest_fn m_fota_manifest_fn; + image_set_fn m_fota_image_set_fn; + responder_fn m_fota_invocation_fn; + + bool authenticate(const void *challenge); +}; + +#endif // __DEVICE_MANAGEMENT_RESPONDER_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/DeviceManager.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/DeviceManager.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,206 @@ +/** + * @file DeviceManager.h + * @brief mbed CoAP Endpoint Device Management class + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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 __DEVICE_MANAGER_H__ +#define __DEVICE_MANAGER_H__ + +// mbed-client support +#include "mbed-client/m2mconstants.h" +#include "mbed-client/m2mdevice.h" +#include "mbed-client/m2mfirmware.h" + +// Action Resource: Device DeRegistration +#include "mbed-connector-interface/DeviceDeRegisterResource.h" + +// LWM2M Device Info # of Device Resources we support +#define NUM_DEVICE_RESOURCES 9 + +// LWM2M Firmware Resources supported +#define NUM_FIRMWARE_RESOURCES 7 + +// LWM2M DeRegistration Object ID +#define LWM2M_DREGISTER_OBJ_ID "86" + +// LWM2M Device DeRegistration Resource ID +#define LWM2M_DEV_DEREGISTER_ID "1" + +/** DeviceManager is the endpoint management class + */ +class DeviceManager +{ + public: + // Optional Firmware Resource (indices) + typedef enum { + PackageName = 0, + PackageVersion = 1, + Update = 2, + Package = 3, + PackageURI = 4, + State = 5, + UpdateResult = 6 + } FirmwareResources; + + // Optional Device Resource (indices) + typedef enum { + Manufacturer = 0, + DeviceType = 1, + ModelNumber = 2, + SerialNumber = 3, + FirmwareVersion = 4, + HardwareVersion = 5, + SoftwareVersion = 6, + Reboot = 7, + FactoryReset = 8, + DeRegistration = 9 + } DeviceResources; + + /** + Default constructor + @param logger input logger instance + @param dm_responder input data management responder/processor + @param mfg input endpoint manufacturer + @param dev_type input the endpoint type + @param model input the model of the endpoint + @param serial input the serial of the endpoint + @param fw_vers input the current firmware version + @param hw_vers input the current hardware version + @param sw_vers input the current software version + */ + DeviceManager(const Logger *logger,const void *dm_responder=NULL,const char *mfg="ARM",const char *dev_type="mbed",const char *model="ARM" ,const char *serial="000000",const char *fw_ver="0.0.0",const char *hw_ver="0.0.0",const char *sw_ver="0.0.0"); + + /** + Copy constructor + @param resource input the DeviceManager that is to be deep copied + */ + DeviceManager(const DeviceManager &manager); + + /** + Destructor + */ + virtual ~DeviceManager(); + + /** + install the device manager into the endpoint + @param endpoint input the endpoint instance + @param config input the endpoint configuration instance + */ + void install(const void *endpoint,const void *config); + + /** + get the DeviceManagementResponder + @return the DeviceManagementResponder or NULL + */ + void *getResponder(); + + // LWM2M Device: Reboot Action Handler + void process_reboot_action(void *args); + + // LWM2M Device: Reset Action Handler + void process_reset_action(void *args); + + // LWM2M Firmware: Update + void process_firmware_update_action(void *args); + + // bind our device resources + void bind(); + + // Get a specific Firmware Resource + M2MResource *getFirmwareResource(FirmwareResources res); + + // Get a specific Device Resource + M2MResource *getDeviceResource(DeviceResources res); + + // Get the Device Object + M2MDevice *getDeviceObject(); + + // Get the Firmware Object + M2MFirmware *getFirmwareObject(); + + // Process updated values + void process(M2MBase *base, M2MBase::BaseType type); + + private: + Logger *m_logger; + void *m_endpoint; + void *m_config; + char *m_dev_type; + void *m_dm_responder; + char *m_mfg; + char *m_model; + char *m_serial; + char *m_fw_vers; + char *m_hw_vers; + char *m_sw_vers; + + // LWM2M Firmware Data + char *m_fw_manifest; + uint32_t m_fw_manifest_length; + void *m_fw_image; + uint32_t m_fw_image_length; + + // LWM2M Device Info Resources + M2MDevice *m_device; + M2MResource *m_dev_res[NUM_DEVICE_RESOURCES]; + + // LWM2M Firmware Resources + M2MFirmware *m_firmware; + M2MResource *m_fw_res[NUM_FIRMWARE_RESOURCES]; + + // DeRegistation Resource + DeviceDeRegisterResource *m_deregister_resource; + + // Memory utilities + char *saveManifest(uint8_t *value,uint32_t length); + void *saveImage(void *image,uint32_t image_length); + + // Bind our Device Resources to our Device Object + void bindDeviceResources(); + + // Bind our Firmware Resources to our Firmware Object + void bindFirmwareResources(); + + // Bind our mbed Cloud Resource + void bindMBEDCloudResources(); + + // Get the Device Reboot Resource from the Device Object + M2MResource *getDeviceRebootResource(); + + // Get the Firmware Update Resource from the Firmware Object + M2MResource *getFirmwareUpdateResource(); + + // Get the Firmware Package Resource from the Firmware Object + M2MResource *getFirmwarePackageResource(); + + // Get the Firmware Package URI Resource from the Firmware Object + M2MResource *getFirmwarePackageURIResource(); + + // Get the Firmware State Resource from the Firmware Object + M2MResource *getFirmwareStateResource(); + + // Get the Firmware UpdateResult Resource from the Firmware Object + M2MResource *getFirmwareUpdateResultResource(); + + // Get a specific resource from a given resource object + M2MResource *getResourceFromObject(M2MObject *obj,int instanceID,int resID); +}; + +#endif // __DEVICE_MANAGER_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/DynamicResource.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/DynamicResource.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,216 @@ +/** + * @file DynamicResource.h + * @brief mbed CoAP Endpoint Dynamic Resource class + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __DYNAMIC_RESOURCE_H__ +#define __DYNAMIC_RESOURCE_H__ + +// Base Class +#include "mbed-connector-interface/Resource.h" + +// DataWrapper support +#include "mbed-connector-interface/DataWrapper.h" + +/** DynamicResource class + */ +class DynamicResource : public Resource<string> +{ +public: + /** + Default constructor (char strings) + @param logger input logger instance for this resource + @param obj_name input the Object + @param name input the Resource URI/Name + @param res_type input type for the Resource + @param res_mask input the resource enablement mask (GET, PUT, etc...) + @param observable input the resource is Observable (default: FALSE) + */ + DynamicResource(const Logger *logger,const char *obj_name,const char *res_name,const char *res_type,uint8_t res_mask,const bool observable = false,const ResourceType type = STRING); + + /** + Default constructor (char strings) + @param logger input logger instance for this resource + @param obj_name input the Object + @param name input the Resource URI/Name + @param res_type input type for the Resource + @param value input initial value for the Resource + @param res_mask input the resource enablement mask (GET, PUT, etc...) + @param observable input the resource is Observable (default: FALSE) + */ + DynamicResource(const Logger *logger,const char *obj_name,const char *res_name,const char *res_type,const string value,uint8_t res_mask,const bool observable = false,const ResourceType type = STRING); + + /** + constructor with string buffer for name + @param logger input logger instance for this resource + @param obj_name input the Object + @param name input the Resource URI/Name + @param res_type input type for the Resource + @param value input initial value for the Resource + @param res_mask input the resource enablement mask (GET, PUT, etc...) + @param observable input the resource is Observable (default: FALSE) + */ + DynamicResource(const Logger *logger,const string obj_name,const string res_name,const string res_type,const string value,uint8_t res_mask,const bool observable = false,const ResourceType type = STRING); + + /** + Copy constructor + @param resource input the DynamicResource that is to be deep copied + */ + DynamicResource(const DynamicResource &resource); + + /** + Destructor + */ + virtual ~DynamicResource(); + + /** + Bind resource to endpoint + @param ep input endpoint instance pointer + */ + virtual void bind(void *ep); + + /** + Process the CoAP message + @param op input the CoAP Verb (operation) + @param type input clarification of the M2MBase instance being passed in (Object vs. ObjectInstance vs. Resource vs. ResourceInstance) + @param args input arguments (unused) + @return 0 - success, 1 - failure + */ + uint8_t process(M2MBase::Operation op,M2MBase::BaseType type,void *args = NULL); + + /** + Resource value getter (REQUIRED: must be implemented in derived class as all Binders MUST support and implement GET) + @returns string value of the resource + */ + virtual string get(); + + /** + Resource value setter (PUT) (OPTIONAL: defaulted noop if not derived. Binders MAY implement PUT if needed) + @param string value of the resource + */ + virtual void put(const string value); + + /** + Resource value setter (POST) (OPTIONAL: defaulted noop if not derived. Binders MAY implement POST if needed) + @param void * args for the post() operation + */ + virtual void post(void *args); + + /** + Resource value deleter (OPTIONAL: defaulted noop if not derived. Binders MAY implement DELETE if needed) + @param void * args for the del() operation + */ + virtual void del(void *args); + + /** + Send notification of new data + @param data input the new data to update + @returns 1 - success, 0 - failure + */ + int notify(const string data); + + /** + Determine whether this dynamic resource is observable or not + @returns true - is observable, false - otherwise + */ + bool isObservable() { return this->m_observable; } + + /** + Set the observer pointer + @param observer input the pointer to the ResourceObserver observing this resource + */ + void setObserver(void *observer); + + /** + Set the content format for responses + @param content_format short integer CoAP content-format ID + */ + void setContentFormat(uint8_t content_format); + + /** + Set the max-age for cache control of responses in a proxy cache + @param maxage short integer CoAP max-age in seconds + */ + void setMaxAge(uint8_t maxage); + + /** + Set the data wrapper + @param data_wrapper input the data wrapper instance + */ + void setDataWrapper(DataWrapper *data_wrapper) { this->m_data_wrapper = data_wrapper; } + + /** + observe the resource + */ + virtual void observe(); + + /** + get the base resource representation + */ + M2MResource *getResource(); + + /** + Process a POST message for Resources + */ + void process_resource_post(void *args); + + /** + Determine if we are connected or not + */ + bool isConnected(); + + /** + Determine if we are registered or not + */ + bool isRegistered(); + + /** + Get our Observer + */ + void *getObserver(); + +protected: + int notify(uint8_t *data,int data_length); + DataWrapper *getDataWrapper() { return this->m_data_wrapper; } + bool m_observable; + +private: + + string m_res_type; // a string description of our resource type (i.e. "Counter", etc...) + ResourceType m_type; // the core type of our resource (i.e. String, Integer, etc...) + uint8_t m_res_mask; + uint8_t m_obs_number; + DataWrapper *m_data_wrapper; + void *m_observer; + uint8_t m_maxage; + uint8_t m_content_format; + M2MResource *m_res; + void *m_ep; + +public: + // convenience method to create a string from the NSDL CoAP data buffers... + string coapDataToString(uint8_t *coap_data_ptr,int coap_data_ptr_length); + int coapDataToInteger(uint8_t *coap_data_ptr,int coap_data_ptr_length); + float coapDataToFloat(uint8_t *coap_data_ptr,int coap_data_ptr_length); + void *coapDataToOpaque(uint8_t *coap_data_ptr,int coap_data_ptr_length); +}; + +#endif // __DYNAMIC_RESOURCE_H__ +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/Location.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/Location.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,105 @@ +/** + * @file Location.h + * @brief mbed CoAP Endpoint location base class + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __LOCATION_H__ +#define __LOCATION_H__ + +// mbedConnectorInterface configuration +#include "mbed-connector-interface/mbedConnectorInterface.h" + +// mbed support +#if defined(MCI_USE_YOTTA) + // mbed support + #include "mbed-drivers/mbed.h" +#else + // mbed support + #include "mbed.h" +#endif + +// Max length of a coordinate: -XXX.YYYYYY +#define LOCATION_COORDINATE_LENGTH 12 + +// Max length of the MSL altitude (m): ZZZZZZ.Z +#define LOCATION_MSL_ALT_LENGTH 9 + +// Max length of the speed (km/h): ZZZZZZ.Z +#define LOCATION_SPEED_LENGTH 9 + +namespace Connector { + +/** Location class + */ +class Location +{ +protected: + char m_latitude[LOCATION_COORDINATE_LENGTH+1]; + char m_longitude[LOCATION_COORDINATE_LENGTH+1]; + char m_msl_altitude_m[LOCATION_MSL_ALT_LENGTH+1]; + char m_speed[LOCATION_SPEED_LENGTH+1]; + +public: + /** + Default constructor + */ + Location(); + + /** + Copy constructor + @param logger input Location instance to deep copy + */ + Location(const Location &location); + + /** + Destructor + */ + virtual ~Location(); + + /** + Update the current location (pure virtual) + */ + virtual void updateLocation() = 0; + + /** + Get latest Latitude + */ + virtual char *getLatitude(); + + /** + Get latest Longitude + */ + virtual char *getLongitude(); + + /** + Get latest MSL Altitude (m) + */ + char *getMSLAltitude(); + + /** + Get latest Speed (km/h) (pure virtual) + */ + char *getSpeed(); +}; + +}; + +#endif // __LOCATION_H__ +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/Logger.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/Logger.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,78 @@ +/** + * @file Logger.h + * @brief mbed CoAP Endpoint logging class + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __LOGGER_H__ +#define __LOGGER_H__ + +// Configuration +#include "mbed-connector-interface/mbedConnectorInterface.h" + +// Support for std args +#include <stdarg.h> + +// mbed support +#if defined(MCI_USE_YOTTA) + // mbed support + #include "mbed-drivers/mbed.h" +#else + // mbed support + #include "mbed.h" +#endif + +// logging macro +#define logging(x, ...) logIt(x"\r\n",##__VA_ARGS__) + +/** Logger class + */ +class Logger +{ +public: + /** + Default constructor + @param pc input BufferedSerial instance for debugging (if NULL, no debugging output will occur in the library) + */ + Logger(const Serial *pc); + + /** + Copy constructor + @param logger input Logger instance to deep copy + */ + Logger(const Logger &logger); + + /** + Destructor + */ + virtual ~Logger(); + + /** + Log output to the given serial console + @param format input format for the logging + @param ... input (variable arguments to display) + */ + void logIt(const char *format, ...); + +private: + Serial *m_pc; +}; + +#endif // __LOGGER_H__ +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/MinarResourceObserver.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/MinarResourceObserver.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,83 @@ +/** + * @file MinarResourceObserver.h + * @brief mbed CoAP DynamicResource Minar-based observer (header) + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __MINAR_RESOURCE_OBSERVER_H__ +#define __MINAR_RESOURCE_OBSERVER_H__ + +// mbedConnectorInterface configuration +#include "mbed-connector-interface/mbedConnectorInterface.h" + +// mbed support +#if defined(MCI_USE_YOTTA) + // mbed support + #include "mbed-drivers/mbed.h" +#else + // mbed support + #include "mbed.h" +#endif + +#if defined(MCI_MINAR_SCHEDULER) + +// Base class support +#include "mbed-connector-interface/ResourceObserver.h" + +class MinarResourceObserver : public ResourceObserver { + public: + /** + Default Constructor + @param resource input the resource to observe + @param sleep_time input the time for the observation thread to sleep (in ms) + */ + MinarResourceObserver(DynamicResource *resource,int sleep_time = DEFAULT_OBS_PERIOD); + + /** + Destructor + */ + virtual ~MinarResourceObserver(); + + /** + begin the observation + */ + virtual void beginObservation(); + + /** + stop the observation + */ + virtual void stopObservation(); + + /** + perform the observation (iteration) + */ + void perform_observation(); + + /** + halt the underlying observer mechanism + */ + virtual void halt(); + + private: + +}; + +#endif // MCI_MINAR_SCHEDULER + +#endif // __MINAR_RESOURCE_OBSERVER_H__
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/NamedPointer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/NamedPointer.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,61 @@ +/** + * @file NamedPointer.h + * @brief mbed CoAP Endpoint Device Management Named Pointer (header) + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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 __NAMED_POINTER_H__ +#define __NAMED_POINTER_H__ + +// String class +#include <string> + +class NamedPointer { +public: + // constructor + NamedPointer(string name,void *ptr,int index); + + // copy constructor + NamedPointer(const NamedPointer &np); + + // Destructor + virtual ~NamedPointer(); + + // Get the Name + string name(); + + // Get the Pointer + void *ptr(); + + // Get the associated list + void *list(); + + // Get our associated index + int index(); + +private: + string m_name; + int m_index; + void *m_ptr; + void *m_list; + + void *copyList(void *list); +}; + +#endif // __NAMED_POINTER_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/ObjectInstanceManager.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/ObjectInstanceManager.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,104 @@ +/** + * @file ObjectInstanceManager.h + * @brief mbed CoAP Endpoint Device Management Object Instance Manager (header) + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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 __OBJECT_INSTANCE_MANAGER_H__ +#define __OBJECT_INSTANCE_MANAGER_H__ + +// Logger +#include "mbed-connector-interface/Logger.h" + +// Named Pointer List +#include "mbed-connector-interface/NamedPointer.h" + +// Resources list +#include <vector> +typedef vector<NamedPointer> NamedPointerList; + +class ObjectInstanceManager { + public: + /** + Default constructor + @param logger input logger instance + @param ep input the Endpoint instance + */ + ObjectInstanceManager(const Logger *logger,const void *ep); + + /** + Copy constructor + @param resource input the ObjectInstanceManager that is to be deep copied + */ + ObjectInstanceManager(const ObjectInstanceManager &manager); + + /** + Destructor + */ + virtual ~ObjectInstanceManager(); + + /** + Create DynamicResourceInstance + @param objID input the Object ID to parent this new resource instance under + @param resID input the Resource ID for this resource + @param resName input the Resource Name + @param resType input the type of Resource (cast from Resource::ResourceType) + @param observable input whether this Resource is observable or not + */ + void *createDynamicResourceInstance(char *objID,char *resID,char *resName,int resType,bool observable); + + /** + Create StaticResourceInstance + @param objID input the Object ID to parent this new resource instance under + @param resID input the Resource ID for this resource + @param resName input the Resource Name + @param resType input the type of Resource (cast from Resource::ResourceType) + @param observable input whether this Resource is observable or not + */ + void *createStaticResourceInstance(char *objID,char *resID,char *resName,int resType,void *data,int data_length); + + /** + Get our Object List + */ + NamedPointerList getObjectList(); + + /** + Get the instance number of the just-created ResourceInstance + */ + int getLastCreatedInstanceNumber(); + + protected: + Logger *m_logger; + void *m_ep; + NamedPointerList m_object_list; + int m_instance_number; + + private: + // Generic Static and Dynamic Resource Instances/Objects + void *getOrCreateInstance(char *objID,char *resID); + NamedPointer *getOrCreateObject(char *objID); + + // Underlying lookup support + NamedPointer *getNamedPointer(const char *id,NamedPointerList *list); + + // Logger + Logger *logger(); +}; + +#endif // __OBJECT_INSTANCE_MANAGER_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/Options.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/Options.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,259 @@ +/** + * @file Options.h + * @brief mbed CoAP Options (immutable OptionsBuilder instance) class header + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __OPTIONS_H__ +#define __OPTIONS_H__ + +// Static Resources +#include "mbed-connector-interface/StaticResource.h" + +// Dynamic Resources +#include "mbed-connector-interface/DynamicResource.h" + +// include the mbed connector resource list +#include "mbed-connector-interface/mbedConnectorInterface.h" + +// include the resource observer includes here so that they are not required in main.cpp +#include "mbed-connector-interface/ThreadedResourceObserver.h" +#include "mbed-connector-interface/TickerResourceObserver.h" +#include "mbed-connector-interface/MinarResourceObserver.h" + +// Vector support +#include <vector> + +// Resources list +typedef vector<StaticResource *> StaticResourcesList; +typedef vector<DynamicResource *> DynamicResourcesList; +typedef vector<ResourceObserver *> ResourceObserversList; + +// Default CoAP Port for mbed Cloud/Connector +#define DEF_COAP_PORT 5684 + +// WiFi Security types (maps to wifi_security_t) +typedef enum { + WIFI_NONE = 0, + WIFI_WEP, + WIFI_WPA_PERSONAL, + WIFI_WPA2_PERSONAL +} WiFiAuthTypes; + +// Connection Types for CoAP +typedef enum { + COAP_TCP, + COAP_UDP, + COAP_NUM_TYPES +} CoAPConnectionTypes; + +// IP Address Types +typedef enum { + IP_ADDRESS_TYPE_IPV4, + IP_ADDRESS_TYPE_IPV6, + IP_ADDRESS_TYPE_NUM_TYPES +} IPAddressTypes; + +namespace Connector { + +/** Options class + */ +class Options +{ +public: + /** + Default constructor + */ + Options(); + + /** + Copy constructor + */ + Options(const Options &opt); + + /** + Destructor + */ + virtual ~Options(); + + /** + Get the node lifetime + */ + int getLifetime(); + + /** + Get the NSP domain + */ + string getDomain(); + + /** + Get the node name + */ + string getEndpointNodename(); + + /** + Get the node type + */ + string getEndpointType(); + + /** + Get the endpoint Connector URL + */ + char *getConnectorURL(); + + /** + Get the connector connection port from the URL + */ + uint16_t getConnectorPort(); + + /** + Get the Device Resources Object Instance + */ + void *getDeviceResourcesObject(); + + /** + Get the Firmware Resources Object Instance + */ + void *getFirmwareResourcesObject(); + + /** + Get the list of static resources + */ + StaticResourcesList *getStaticResourceList(); + + /** + Get the list of dynamic resources + */ + DynamicResourcesList *getDynamicResourceList(); + + /** + Get the WiFi SSID + */ + string getWiFiSSID(); + + /** + Get the WiFi Auth Type + */ + WiFiAuthTypes getWiFiAuthType(); + + /** + Get the WiFi Auth Key + */ + string getWiFiAuthKey(); + + /** + Get the CoAP Connection Type + */ + CoAPConnectionTypes getCoAPConnectionType(); + + /** + Get the IP Address Type + */ + IPAddressTypes getIPAddressType(); + + /** + Enable/Disable Immediate Observationing + */ + bool immedateObservationEnabled(); + + /** + Enable/Disable Observation control via GET + */ + bool enableGETObservationControl(); + + /** + Get the Server Certificate + */ + uint8_t *getServerCertificate(); + + /** + Get the Server Certificate Size (bytes) + */ + int getServerCertificateSize(); + + /** + Get the Client Certificate + */ + uint8_t *getClientCertificate(); + + /** + Get the Client Certificate Size (bytes) + */ + int getClientCertificateSize(); + + /** + Get the Client Key + */ + uint8_t *getClientKey(); + + /** + Get the Client Key Size (bytes) + */ + int getClientKeySize(); + + /** + Get Our Endpoint + */ + void *getEndpoint(); + +protected: + // mDS Resources + int m_lifetime; + string m_domain; + string m_node_name; + string m_endpoint_type; + string m_connector_url; + + // WiFi Resources + string m_wifi_ssid; + string m_wifi_auth_key; + WiFiAuthTypes m_wifi_auth_type; + + // CoAP Connection Types + CoAPConnectionTypes m_coap_connection_type; + + // IP Address Types + IPAddressTypes m_ip_address_type; + + // DTLS/TLS Resources + uint8_t *m_server_cert; + int m_server_cert_length; + uint8_t *m_client_cert; + int m_client_cert_length; + uint8_t *m_client_key; + int m_client_key_length; + + // CoAP behavior adjustments + bool m_enable_immediate_observation; + bool m_enable_get_obs_control; + + // Endpoint Resources + void *m_device_resources_object; + void *m_firmware_resources_object; + StaticResourcesList m_static_resources; + DynamicResourcesList m_dynamic_resources; + ResourceObserversList m_resource_observers; + + // Our Endpoint + void *m_endpoint; +}; + +} // namespace Connector + +#endif // __OPTIONS_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/OptionsBuilder.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/OptionsBuilder.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,217 @@ +/** + * @file OptionsBuilder.h + * @brief mbed CoAP OptionsBuilder class header + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __OPTIONS_BUILDER_H__ +#define __OPTIONS_BUILDER_H__ + +// base class support +#include "mbed-connector-interface/Options.h" + +// Connector namespace +namespace Connector { + +/** OptionsBuilder class + */ +class OptionsBuilder : Options +{ +public: + /** + Default Constructor + */ + OptionsBuilder(); + + /** + Copy Constructor + @param ob input options builder instance to deep copy + */ + OptionsBuilder(const OptionsBuilder &ob); + + /** + Destructor + */ + virtual ~OptionsBuilder(); + + /** + Set the NSDL Endpoint Lifetime + @param lifetime input the NSDL endpoint lifetime (seconds) + @return instance to ourself + */ + OptionsBuilder &setLifetime(int lifetime); + + /** + Set the NSDL Domain + @param domain input the NSDL domain to set + @return instance to ourself + */ + OptionsBuilder &setDomain(const char *domain); + + /** + Set the Endpoint Node Name + @param node_name input the node endpoint name + @return instance to ourself + */ + OptionsBuilder &setEndpointNodename(const char *node_name); + + /** + Set the NSDL Endpoint Type + @param endpoint_type input the NSDL endpoint type + @return instance to ourself + */ + OptionsBuilder &setEndpointType(const char *endpoint_type); + + /** + Set the Connector URL + @param url input the Connector URL + @return instance to ourself + */ + OptionsBuilder &setConnectorURL(const char *connector_url); + + /** + Set the LWM2M Device Resource Object Instance + @param device_resources_object input the LWM2M device resource object instance + @return instance to ourself + */ + OptionsBuilder &setDeviceResourcesObject(const void *device_resources_object); + + /** + Set the LWM2M Firmware Resource Object Instance + @param firmware_resources_object input the LWM2M firmware resource object instance + @return instance to ourself + */ + OptionsBuilder &setFirmwareResourcesObject(const void *firmware_resources_object); + + /** + Add a NSDL endpoint resource (static) + @param static_resource input the NSDL static resource + @return instance to ourself + */ + OptionsBuilder &addResource(const StaticResource *static_resource); + + /** + Add a NSDL endpoint resource (dynamic) + @param dynamic_resource input the NSDL dynamic resource + @return instance to ourself + */ + OptionsBuilder &addResource(const DynamicResource *dynamic_resource); + + /** + Add a NSDL endpoint resource (dynamic) + @param dynamic_resource input the NSDL dynamic resource + @param use_observer input if true, use an appropriate ResourceObserver to observer. if false, the underlying resource will handle it + @return instance to ourself + */ + OptionsBuilder &addResource(const DynamicResource *dynamic_resource,const bool use_observer); + + /** + Add a NSDL endpoint resource (dynamic) + @param dynamic_resource input the NSDL dynamic resource + @param sleep_time input the observation sleep time in milliseconds (for observable resource only) + @return instance to ourself + */ + OptionsBuilder &addResource(const DynamicResource *dynamic_resource,const int sleep_time); + + /** + Add a NSDL endpoint resource (dynamic) + @param dynamic_resource input the NSDL dynamic resource + @param sleep_time input the observation sleep time in milliseconds (for observable resource only) + @param use_observer input if true, use an appropriate ResourceObserver to observer. if false, the underlying resource will handle it + @return instance to ourself + */ + OptionsBuilder &addResource(const DynamicResource *dynamic_resource,const int sleep_time,const bool use_observer); + + /** + Set the WiFi SSID + @param ssid input the WiFi SSID + */ + OptionsBuilder &setWiFiSSID(char *ssid); + + /** + Set the WiFi AuthType + @param auth_type input the WiFi AuthType + */ + OptionsBuilder &setWiFiAuthType(WiFiAuthTypes auth_type); + + /** + Set the WiFi AuthKey + @param auth_key input the WiFi AuthKey + */ + OptionsBuilder &setWiFiAuthKey(char *auth_key); + + /** + Set the CoAP Connection Type + @param coap_connection_type input the CoAP Connection type + */ + OptionsBuilder &setCoAPConnectionType(CoAPConnectionTypes coap_connection_type); + + /** + Set the IP Address Type + @param ip_address_type input the IP Address type + */ + OptionsBuilder &setIPAddressType(IPAddressTypes ip_address_type); + + /** + Enable/Disable immediate observationing + @param enable input enable immediate observationing without GET + */ + OptionsBuilder &setImmedateObservationEnabled(bool enable); + + /** + Enable/Disable GET-based control of observations + @param enable input enable GET-based observation enable/disable control + */ + OptionsBuilder &setEnableGETObservationControl(bool enable); + + /** + Set the Server Certificate + @param cert input the server certificate + @param cert_size input the length of the server certificate + */ + OptionsBuilder &setServerCertificate(uint8_t *cert,int cert_size); + + /** + Set the Client Certificate + @param cert input the client certificate + @param cert_size input the length of the client certificate + */ + OptionsBuilder &setClientCertificate(uint8_t *cert,int cert_size); + + /** + Set the Client Key + @param key input the client key + @param key_size input the length of the client key + */ + OptionsBuilder &setClientKey(uint8_t *key,int key_size); + + /** + Build our our immutable self + */ + Options *build(); + + /** + Set our Endpoint instance + */ + void setEndpoint(void *endpoint); +}; + +} // namespace Connector + +#endif // __OPTIONS_BUILDER_H__
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/PassphraseAuthenticator.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/PassphraseAuthenticator.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,63 @@ +/** + * @file PassphraseAuthenticator.h + * @brief mbed CoAP Endpoint Device Management Passphrase-based Authenticator class + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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 __PASSPHRASE_AUTHENTICATOR_H__ +#define __PASSPHRASE_AUTHENTICATOR_H__ + +// Base class +#include "mbed-connector-interface/Authenticator.h" + +// string support +#include <string> + +class PassphraseAuthenticator : public Authenticator { + public: + /** + Default constructor + @param logger input logger instance + @param secret input secret (passphrase) + */ + PassphraseAuthenticator(const Logger *logger,const void *passphrase = NULL); + + /** + Copy constructor + @param resource input the BasicAuthenticator that is to be deep copied + */ + PassphraseAuthenticator(const PassphraseAuthenticator &manager); + + /** + Destructor + */ + virtual ~PassphraseAuthenticator(); + + /** + Authenticate + @param challenge input the challenge to authenticate with + @return true - authenciated successfully, false - otherwise + */ + virtual bool authenticate(void *challenge); + + private: + string coapDataToString(uint8_t *coap_data_ptr,int coap_data_ptr_length); +}; + +#endif // __PASSPHRASE_AUTHENTICATOR_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/Resource.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/Resource.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,211 @@ +/** + * @file Resource.h + * @brief mbed CoAP Endpoint Resource base class template + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __RESOURCE_H__ +#define __RESOURCE_H__ + +// logging facility +#include "mbed-connector-interface/Logger.h" + +// mbed-client support +#include "mbed-client/m2minterfacefactory.h" +#include "mbed-client/m2minterfaceobserver.h" +#include "mbed-client/m2minterface.h" +#include "mbed-client/m2mobjectinstance.h" +#include "mbed-client/m2mresource.h" +#include "mbed-client/m2mdevice.h" +#include "mbed-client/m2mfirmware.h" + +// string support +#include <string> + +/** Resource class + */ +template <typename InnerType> class Resource +{ +public: + // Available Resource Types + typedef enum { + STRING, + INTEGER, + FLOAT, + BOOLEAN, + OPAQUE, + TIME, + OBJLINK + }ResourceType; + + /** + Default constructor + @param logger input the Logger instance this Resource is a part of + @param obj_name input the Object Name + @param res_name input the Resource URI/Name + @param value input the Resource value + */ + Resource(const Logger *logger,const string obj_name,const string res_name,InnerType value) { + this->init(logger); + this->m_obj_name = obj_name; + this->m_res_name = res_name; + this->m_value = value; + this->m_implements_observation = false; + this->m_instance_number = 0; + } + + /** + Copy constructor + @param resource input the Resource that is to be deep copied + */ + Resource(const Resource<InnerType> &resource) { + this->init(resource.m_logger); + this->m_endpoint = resource.m_endpoint; + this->m_obj_name = resource.m_obj_name; + this->m_res_name = resource.m_res_name; + this->m_value = resource.m_value; + this->m_implements_observation = resource.m_implements_observation; + this->m_instance_number = resource.m_instance_number; + } + + /** + Destructor + */ + virtual ~Resource() { + } + + /** + Get the Object name + @return the name of the object + */ + string getObjName() { + return this->m_obj_name; + } + + /** + Get the Resource name + @return the name of the resource + */ + string getResName() { + return this->m_res_name; + } + + /** + Get the Full name + @return the name of the object + */ + string getFullName() { + char buf[5]; + memset(buf,0,5); + sprintf(buf,"/%d/",this->m_instance_number); + return this->m_obj_name + buf + this->m_res_name; + } + + /** + Get the resource value + @return the value of the resource + */ + InnerType getValue() { + return this->m_value; + } + + /** + Set the resource name + @param name input the resource name + */ + void setName(const string name) { + this->m_name = name; + } + + /** + Set the resource value + @param value input the resource value + */ + void setValue(const InnerType value) { + this->m_value = value; + } + + /** + Bind resource to endpoint + @param ep input pointer to the Endpoint instance + */ + virtual void bind(void *ep) = 0; + + // access the logger() + Logger *logger() { + return this->m_logger; + } + + /** + set the options + */ + void setOptions(const void *options) { + this->m_options = (void *)options; + } + + /** + set the endpoint + */ + void setEndpoint(const void *endpoint) { + this->m_endpoint = (void *)endpoint; + } + + // this resource implements its own observation handler + bool implementsObservation() { return this->m_implements_observation; } + + /** + Get our Instance Number + @return our instance number + */ + int getInstanceNumber() { return this->m_instance_number; } + + /** + Set our Instance Number + @param instance_number input our designated instance number + */ + void setInstanceNumber(int instance_number) { this->m_instance_number = instance_number; } + +protected: + // initialize internals to Resource + void init(const Logger *logger) { + this->m_logger = (Logger *)logger; + this->m_endpoint = NULL; + this->m_obj_name = ""; + this->m_res_name = ""; + this->m_value = ""; + this->m_instance_number = 0; + } + + // get our options + void *getOptions() { + return this->m_options; + } + + Logger *m_logger; + void *m_endpoint; + string m_obj_name; + string m_res_name; + InnerType m_value; + bool m_implements_observation; + void *m_options; + int m_instance_number; +}; + +#endif // __RESOURCE_H__ +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/ResourceObserver.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/ResourceObserver.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,84 @@ +/** + * @file ResourceObserver.h + * @brief mbed CoAP DynamicResource observer (header) + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __RESOURCE_OBSERVER_H__ +#define __RESOURCE_OBSERVER_H__ + +// DynamicResource +#include "mbed-connector-interface/DynamicResource.h" + +class ResourceObserver { + public: + /** + Default Constructor + @param resource input the resource to observe + @param sleep_time input the amount of time to sleep between observations + */ + ResourceObserver(DynamicResource *resource,int sleep_time); + + /** + Copy Constructor + */ + ResourceObserver(const ResourceObserver &observer); + + /** + Destructor + */ + virtual ~ResourceObserver(); + + /** + begin the observation (ABSTRACT) + */ + virtual void beginObservation() = 0; + + /** + stop the observation (ABSTRACT) + */ + virtual void stopObservation() = 0; + + /** + we are observing? + */ + bool isObserving(); + + /** + get our sleep time + */ + int getSleepTime(); + + /** + halt the underlying observer mechanism + */ + virtual void halt(); + + protected: + DynamicResource *getResource(); + void setObserving(bool observing); + Logger *logger(); + + private: + DynamicResource *m_resource; + bool m_is_observing; + int m_sleep_time; +}; + +#endif // __RESOURCE_OBSERVER_H__
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/StaticResource.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/StaticResource.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,97 @@ +/** + * @file StaticResource.h + * @brief mbed CoAP Endpoint Static Resource class + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __STATIC_RESOURCE_H__ +#define __STATIC_RESOURCE_H__ + +// Base Class +#include "mbed-connector-interface/Resource.h" + +// DataWrapper support +#include "mbed-connector-interface/DataWrapper.h" + +/** StaticResource is a static (GET only) resource with a value type pinned as a string type + */ +class StaticResource : public Resource<string> +{ +public: + /** + Default constructor + @param logger input logger instance for this resource + @param obj_name input the Object + @param res_name input the Resource URI/Name + @param value input the Resource value (a string) + */ + StaticResource(const Logger *logger,const char *obj_name,const char *res_name,const char *value); + + /** + string value constructor + @param logger input logger instance for this resource + @param obj_name input the Object + @param name input the Resource URI/Name + @param value input the Resource value (a string) + */ + StaticResource(const Logger *logger,const char *obj_name,const char *res_name,const string value); + + /** + constructor with buffer lengths + @param logger input logger instance for this resource + @param obj_name input the Object + @param name input the Resource URI/Name + #param name_length input the length of the Resource URI/Name + @param value input the Resource value (or NULL) + */ + StaticResource(const Logger *logger,const string obj_name,const string res_name,const string value); + + /** + Copy constructor + @param resource input the StaticResource that is to be deep copied + */ + StaticResource(const StaticResource &resource); + + /** + Destructor + */ + virtual ~StaticResource(); + + /** + Bind resource to endpoint + @param ep input endpoint instance pointer + */ + virtual void bind(void *ep); + + /** + Set the data wrapper + @param data_wrapper input the data wrapper instance + */ + void setDataWrapper(DataWrapper *data_wrapper) { this->m_data_wrapper = data_wrapper; } + +protected: + DataWrapper *getDataWrapper() { return this->m_data_wrapper; } + +private: + DataWrapper *m_data_wrapper; + M2MResource *m_res; +}; + +#endif // __STATIC_RESOURCE_H__ +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/ThreadedResourceObserver.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/ThreadedResourceObserver.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,84 @@ +/** + * @file ThreadedResourceObserver.h + * @brief mbed CoAP DynamicResource Thread-based observer (header) + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __THREADED_RESOURCE_OBSERVER_H__ +#define __THREADED_RESOURCE_OBSERVER_H__ + +// mbedConnectorInterface configuration +#include "mbed-connector-interface/mbedConnectorInterface.h" + +#ifdef CONNECTOR_USING_THREADS + +// mbed support +#if defined(MCI_USE_YOTTA) + // mbed support + #include "mbed-drivers/mbed.h" +#else + // mbed support + #include "mbed.h" + #include "rtos.h" +#endif + +// Base class support +#include "mbed-connector-interface/ResourceObserver.h" + +class ThreadedResourceObserver : public ResourceObserver { + public: + /** + Default Constructor + @param resource input the resource to observe + @param sleep_time input the time for the observation thread to sleep (in ms) + */ + ThreadedResourceObserver(DynamicResource *resource,int sleep_time = DEFAULT_OBS_PERIOD); + + /** + Destructor + */ + virtual ~ThreadedResourceObserver(); + + /** + begin the observation + */ + virtual void beginObservation(); + + /** + stop the observation + */ + virtual void stopObservation(); + + /** + thread task method + */ + void observation_task(); + + /** + halt the underlying observer mechanism + */ + virtual void halt(); + + private: + Thread m_observation_thread; +}; + +#endif // CONNECTOR_USING_THREADS + +#endif // __THREADED_RESOURCE_OBSERVER_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/TickerResourceObserver.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/TickerResourceObserver.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,89 @@ +/** + * @file TickerResourceObserver.h + * @brief mbed CoAP DynamicResource Ticker-based observer (header) + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __TICKER_RESOURCE_OBSERVER_H__ +#define __TICKER_RESOURCE_OBSERVER_H__ + +// mbedConnectorInterface configuration +#include "mbed-connector-interface/mbedConnectorInterface.h" + +#ifdef CONNECTOR_USING_TICKER + +// mbed support +#if defined(MCI_USE_YOTTA) + // mbed support + #include "mbed-drivers/mbed.h" +#else + // mbed support + #include "mbed.h" +#endif + +// Base class support +#include "mbed-connector-interface/ResourceObserver.h" + +class TickerResourceObserver : public ResourceObserver { + public: + /** + Default Constructor + @param resource input the resource to observe + @param timer_id input the id for our timer (can be index value of each resource that is observed...) + @param sleep_time input the time for the observation tasklet to sleep (in whole seconds...) + */ + TickerResourceObserver(DynamicResource *resource,int sleep_time = DEFAULT_OBS_PERIOD); + + /** + Copy Constructor + */ + TickerResourceObserver(const TickerResourceObserver &observer); + + /** + Destructor + */ + virtual ~TickerResourceObserver(); + + /** + begin the observation + */ + virtual void beginObservation(); + + /** + stop the observation + */ + virtual void stopObservation(); + + /** + tasklet invoke function (static) + */ + void observationNotifier(void); + + /** + halt the underlying observer mechanism + */ + virtual void halt(); + + private: + Ticker m_ticker; +}; + +#endif // CONNECTOR_USING_TICKER + +#endif // __TICKER_RESOURCE_OBSERVER_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/Utils.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/Utils.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,31 @@ +/** + * @file Utils.h + * @brief mbed CoAP Endpoint misc utils collection (header) + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __UTILS_H__ +#define __UTILS_H__ + +extern void *utils_init_endpoint(bool canActAsRouterNode); +extern void utils_configure_endpoint(void *p); +extern void utils_build_endpoint(void *p); +extern uint16_t extract_port_from_url(char *url,uint16_t default_port); + +#endif // __UTILS_H__ +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/mbedConnectorInterface.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/mbedConnectorInterface.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,97 @@ +/** + * @file mbedConnectorInterface.h + * @brief mbed Connector Inteface configuration header file + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __MBED_CONNECTOR_INTERFACE_H__ +#define __MBED_CONNECTOR_INTERFACE_H__ + +// mbed +#include "mbed.h" +#include "rtos.h" + +/************** DEFAULT CONFIGURATION PARAMETERS ************************/ + + // Network Selection Definitions + #define ETHERNET 1 + #define WIFI 2 + #define MESH_LOWPAN_ND 3 + #define MESH_THREAD 4 + + // we will use ThreadedResourceObserver + #define CONNECTOR_USING_THREADS 1 + #define MCI_LWIP_INTERFACE true + #define HAS_EXECUTE_PARAMS true + + // Default node name + #define NODE_NAME_LENGTH 128 + #define NODE_NAME "mbed-endpoint" + + // Connection URL to mbed Cloud + #if MBED_CONF_APP_NETWORK_INTERFACE == MESH_LOWPAN_ND || MBED_CONF_APP_NETWORK_INTERFACE == MESH_THREAD + // IPv6 URL Configuration + #define CONNECTOR_URL "coaps://[2607:f0d0:2601:52::20]:5684" + + // OVERRIDE (until patched in mbed-client) + #define IPV4_OVERRIDE true + #else + // IPv4 URL Configuration + #define CONNECTOR_URL "coap://api.connector.mbed.com:5684" + #endif + + // Default Endpoint Type specification + #define ENDPOINT_TYPE_LENGTH 128 + #define DEFAULT_ENDPOINT_TYPE "mbed-device" + + // Default Domain used + #define DOMAIN_LENGTH 128 + #define DEFAULT_DOMAIN "domain" + + // Main loop iteration wait time (ms) + #define MAIN_LOOP_WAIT_TIME_MS 1000 + + // mbed-client endpoint lifetime +#define REG_LIFETIME_SEC 100 // Lifetime of the endpoint in seconds + +// default observation period (ms) +#define DEFAULT_OBS_PERIOD 0 // 0 - disabled (manual invocation), otherwise "n" in ms... + +// Maximum CoAP URL length +#define MAX_CONN_URL_LENGTH 128 // Maximum Connection URL length + +// DynamicResource Configuration +#define MAX_VALUE_BUFFER_LENGTH 128 // largest "value" a dynamic resource may assume as a string + +// Logger buffer size +#define LOGGER_BUFFER_LENGTH 128 // largest single print of a given debug line + +// WiFi Configuration +#define WIFI_SSID_LENGTH 64 +#define WIFI_DEFAULT_SSID "changeme" +#define WIFI_AUTH_KEY_LENGTH 64 +#define WIFI_DEFAULT_AUTH_KEY "changeme" + +// Default context address string for mbed-client +#define CONTEXT_ADDRESS_STRING "" + +/************** DEFAULT CONFIGURATION PARAMETERS ************************/ + +#endif // __MBED_CONNECTOR_INTERFACE___ +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/mbedEndpointNetwork.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/mbedEndpointNetwork.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,48 @@ +/** + * @file mbedEndpointNetwork.h + * @brief mbed Endpoint Network header - declares underling network instance + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __MBED_ENDPOINT_NETWORK_H__ + #define __MBED_ENDPOINT_NETWORK_H__ + + // mbed-client support + #include "mbed-client/m2minterfacefactory.h" + #include "mbed-client/m2minterfaceobserver.h" + #include "mbed-client/m2minterface.h" + #include "mbed-client/m2mobjectinstance.h" + #include "mbed-client/m2mresource.h" + #include "mbed-client/m2mdevice.h" + #include "mbed-client/m2mfirmware.h" + + // mbed Connector Interface (configuration) + #include "mbed-connector-interface/mbedConnectorInterface.h" + + // Include the Connector::Endpoint + #include "mbed-connector-interface/ConnectorEndpoint.h" + + // Include the Connector::OptionsBuilder + #include "mbed-connector-interface/OptionsBuilder.h" + + // Forward declarations of public functions in mbedEndpointNetwork + #include "mbed-connector-interface/mbedEndpointNetworkImpl.h" + + #endif // __MBED_ENDPOINT_NETWORK_H__ +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/mbed-connector-interface/mbedEndpointNetworkImpl.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/mbed-connector-interface/mbedEndpointNetworkImpl.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,32 @@ +/** + * @file mbedEndpointNetworkImpl.h + * @brief mbed Endpoint Network header (impl) - forward references to public functions of mbedEndpointNetwork + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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 __MBED_ENDPOINT_NETWORK_IMPL_H__ +#define __MBED_ENDPOINT_NETWORK_IMPL_H__ + +// Forward references to public functions of mbedEndpointNetwork... +extern "C" char *net_get_type(void); +extern "C" void net_shutdown_endpoint(void); +extern "C" void net_plumb_network(void *p); +extern "C" void net_finalize_and_run_endpoint_main_loop(void *p); + +#endif // __MBED_ENDPOINT_NETWORK_IMPL_H__ \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/Authenticator.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/Authenticator.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,48 @@ +/** + * @file Authenticator.cpp + * @brief mbed CoAP Endpoint Device Management Authenticator (base) class + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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. + */ + + // Class support + #include "mbed-connector-interface/Authenticator.h" + + // constructor + Authenticator::Authenticator(const Logger *logger,const void *secret) { + this->m_logger = (Logger *)logger; + this->setSecret((void *)secret); +} + +// copy constructor +Authenticator::Authenticator(const Authenticator &authenticator) { + this->m_logger = authenticator.m_logger; + this->m_secret = authenticator.m_secret; +} + +// set secret +void Authenticator::setSecret(void *secret) { + this->m_secret = secret; +} + +// destructor +Authenticator::~Authenticator() { +} + +// authenticator +bool Authenticator::authenticate(void * /*challenge */) { return false; } \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/ConnectionStatusInterface.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/ConnectionStatusInterface.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,65 @@ +/** + * @file ConnectionStatusInterface.cpp + * @brief ConnectionStatusInterface + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + +// Class Support +#include "mbed-connector-interface/ConnectionStatusInterface.h" + +// Connector namespace +namespace Connector { + +// Default constructor +ConnectionStatusInterface::ConnectionStatusInterface() { +} + +// Copy constructor +ConnectionStatusInterface::ConnectionStatusInterface(ConnectionStatusInterface & /* csi */) { +} + +// Destructor +ConnectionStatusInterface::~ConnectionStatusInterface() { +} + +// Registered +void ConnectionStatusInterface::object_registered(void * /* ep */,void * /* security */,void * /*data */) { +} + +// Re-registered +void ConnectionStatusInterface::registration_updated(void * /* ep */,void * /* security */,void * /*data */) { +} + +// Beginning de-registration +void ConnectionStatusInterface::begin_object_unregistering(void * /* ep */) { +} + +// De-registered +void ConnectionStatusInterface::object_unregistered(void * /* ep */,void * /* data */) { +} + +// Bootstrapped +void ConnectionStatusInterface::bootstrapped(void * /* ep */,void * /* data */) { +} + +// Value Updated +void ConnectionStatusInterface::value_updated(void * /* ep */,void * /* data */,int /* type */) { +} + +} // Connector namespace \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/ConnectorEndpoint.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/ConnectorEndpoint.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,522 @@ +/** + * @file ConnectorEndpoint.cpp + * @brief mbed CoAP Endpoint base class + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + + // Lower level Network +#include "mbed-connector-interface/mbedEndpointNetwork.h" + +// ConnectorEndpoint +#include "mbed-connector-interface/ConnectorEndpoint.h" + +// Utils support +#include "mbed-connector-interface/Utils.h" + +// Device Manager support +#include "mbed-connector-interface/DeviceManager.h" + +// our endpoint instance +static Connector::Endpoint *__endpoint = NULL; + +// LWIP Network interface instance +NetworkInterface *__network_interface = NULL; + +// Connector namespace +namespace Connector { + +// STATIC: Plumb the network +void Endpoint::plumbNetwork(void *device_manager,bool canActAsRouterNode) { + // create our endpoint instance... + if (__endpoint == NULL) { + // initialize our endpoint instance + printf("Connector::Endpoint::plumbNetwork: initializing endpoint instance...\r\n"); + __endpoint = (Connector::Endpoint *)utils_init_endpoint(canActAsRouterNode); + } + + // set the device manager + if (device_manager != NULL) { + // device manager has been supplied + printf("Connector::Endpoint::plumbNetwork: setting a device manager...\r\n"); + __endpoint->setDeviceManager(device_manager); + } + else { + // no device manager supplied + printf("Connector::Endpoint::plumbNetwork: no device manager supplied (OK)\r\n"); + } + + // configure the endpoint... + printf("Connector::Endpoint::plumbNetwork: configuring endpoint...\r\n"); + utils_configure_endpoint((void *)__endpoint); + + // plumb the endpoint's network... + printf("Connector::Endpoint::plumbNetwork: plumbing network...\r\n"); + net_plumb_network((void *)__endpoint); +} + +// STATIC: Finalize the endpoint's configuration and begin the endpoint's main even loop (static, not tied into Logger) +void Endpoint::start() +{ + // build out the endpoint with its configuration... + printf("Connector::Endpoint::start: building out endpoint...\r\n"); + utils_build_endpoint((void *)__endpoint); + + // finalize the endpoint and start its main loop + printf("Endpoint::start: finalize and run the endpoint main loop..\r\n"); + net_finalize_and_run_endpoint_main_loop((void *)__endpoint); +} + +// STATIC: Set the ConnectionStatusInterface Implementation instance +void Endpoint::setConnectionStatusInterface(ConnectionStatusInterface *csi) { + if (__endpoint != NULL) { + __endpoint->setConnectionStatusInterfaceImpl(csi); + } +} + +// Constructor +Endpoint::Endpoint(const Logger *logger, const Options *options) : M2MInterfaceObserver() +{ + this->m_logger = (Logger *)logger; + this->m_options = (Options *)options; + this->m_device_manager = NULL; + this->m_connected = false; + this->m_registered = false; + this->m_csi = NULL; + this->m_oim = NULL; +} + +// Copy Constructor +Endpoint::Endpoint(const Endpoint &ep) +{ + this->m_logger = ep.m_logger; + this->m_options = ep.m_options; + this->m_endpoint_interface = ep.m_endpoint_interface; + this->m_endpoint_security = ep.m_endpoint_security; + this->m_endpoint_object_list = ep.m_endpoint_object_list; + this->m_device_manager = ep.m_device_manager; + this->m_connected = ep.m_connected; + this->m_registered = ep.m_registered; + this->m_csi = ep.m_csi; + this->m_oim = ep.m_oim; +} + +// Destructor +Endpoint::~Endpoint() { + if (this->m_endpoint_interface != NULL) + delete this->m_endpoint_interface; + if (this->m_endpoint_security != NULL) + delete this->m_endpoint_security; +} + +// set the device manager +void Endpoint::setDeviceManager(void *device_manager) { + this->m_device_manager = device_manager; +} + +// get the device manager +void *Endpoint::getDeviceManager(void) { + return this->m_device_manager; +} + +// router node behavior setting +void Endpoint::asRouterNode(bool canActAsRouterNode) { + this->m_canActAsRouterNode = canActAsRouterNode; +} + +// set our Options +void Endpoint::setOptions(Options *options) { + this->m_options = options; +} + +// get our Options +Options *Endpoint::getOptions() { + return this->m_options; +} + +// get our Server +M2MSecurity *Endpoint::getEndpointSecurity() { + return this->m_endpoint_security; +} + +// get our ObjectList +M2MObjectList Endpoint::getEndpointObjectList() { + return this->m_endpoint_object_list; +} + +// get our endpoint interface +M2MInterface *Endpoint::getEndpointInterface() { + return this->m_endpoint_interface; +} + +// mbed-client: create our interface +void Endpoint::createEndpointInterface() { + // get the CoAP listening port + uint16_t listening_port = (uint16_t)this->m_options->getConnectorPort(); + + // randomize the port if we are using certificates... + if (this->m_options->getServerCertificateSize() > 0) { + // Randomizing listening port for Certificate mode connectivity + srand(time(NULL)); + listening_port = rand() % 65535 + 12345; + } + + // DEBUG + //this->logger()->logging("Connector::Endpoint: listening port: %d",listening_port); + + // Socket protocol type: TCP or UDP + M2MInterface::BindingMode socket_protocol_type = M2MInterface::UDP; + if (this->m_options->getCoAPConnectionType() == COAP_TCP) socket_protocol_type = M2MInterface::TCP; + + // Socket address type: IPv4 or IPv6 + M2MInterface::NetworkStack socket_address_type = M2MInterface::LwIP_IPv4; + if (this->m_options->getIPAddressType() == IP_ADDRESS_TYPE_IPV6) { + // IPv6 mode for the socket addressing type... + socket_address_type = M2MInterface::LwIP_IPv6; + +#if defined (IPV4_OVERRIDE) + // OVERRIDE (until patched...) + this->logger()->logging("Connector::Endpoint: Socket Address Type: IPv4 (IPv6 OVERRIDE)"); + socket_address_type = M2MInterface::LwIP_IPv4; +#endif + } + + // DEBUG + if (socket_protocol_type == M2MInterface::TCP) this->logger()->logging("Connector::Endpoint: Socket Protocol: TCP"); + if (socket_protocol_type == M2MInterface::UDP) this->logger()->logging("Connector::Endpoint: Socket Protocol: UDP"); + if (socket_address_type == M2MInterface::LwIP_IPv4) this->logger()->logging("Connector::Endpoint: Socket Address Type: IPv4"); + if (socket_address_type == M2MInterface::LwIP_IPv6) this->logger()->logging("Connector::Endpoint: Socket Address Type: IPv6"); + + // Create the endpoint M2MInterface instance + this->m_endpoint_interface = M2MInterfaceFactory::create_interface(*this, + (char *)this->m_options->getEndpointNodename().c_str(), // endpoint name + (char *)this->m_options->getEndpointType().c_str(), // endpoint type + (int32_t)this->m_options->getLifetime(), // registration lifetime (in seconds) + listening_port, // listening port (ephemeral...) + (char *)this->m_options->getDomain().c_str(), // endpoint domain + socket_protocol_type, // Socket protocol type: UDP or TCP... + socket_address_type, // Socket addressing type: IPv4 or IPv6 + CONTEXT_ADDRESS_STRING // context address string (mbedConnectorInterface.h) + ); + + // bind LWIP network interface pointer... + if (__network_interface != NULL && this->m_endpoint_interface != NULL) { + this->logger()->logging("Connector::Endpoint: binding LWIP network instance..."); + this->m_endpoint_interface->set_platform_network_handler((void *)__network_interface); + } +} + +// mbed-client: createEndpointInstance() +M2MSecurity *Endpoint::createEndpointInstance() { + // Creates register server object with mbed device server address and other parameters + M2MSecurity *server = M2MInterfaceFactory::create_security(M2MSecurity::M2MServer); + if (server != NULL) { + const String url = this->m_options->getConnectorURL(); + server->set_resource_value(M2MSecurity::M2MServerUri, url); + server->set_resource_value(M2MSecurity::BootstrapServer, false); + server->set_resource_value(M2MSecurity::SecurityMode, M2MSecurity::Certificate); + server->set_resource_value(M2MSecurity::ServerPublicKey,this->m_options->getServerCertificate(),this->m_options->getServerCertificateSize()); + server->set_resource_value(M2MSecurity::PublicKey,this->m_options->getClientCertificate(),this->m_options->getClientCertificateSize()); + server->set_resource_value(M2MSecurity::Secretkey,this->m_options->getClientKey(),this->m_options->getClientKeySize()); + } + return server; +} + +// mbed-client: Callback from mbed client stack if any error is encountered +void Endpoint::error(M2MInterface::Error error) { + switch(error){ + case M2MInterface::AlreadyExists: + this->logger()->logging("Connector::Endpoint(ERROR): M2MInterface::AlreadyExists"); + break; + case M2MInterface::BootstrapFailed: + this->logger()->logging("Connector::Endpoint(ERROR): M2MInterface::BootstrapFailed"); + break; + case M2MInterface::InvalidParameters: + this->logger()->logging("Connector::Endpoint(ERROR): M2MInterface::InvalidParameters"); + break; + case M2MInterface::NotRegistered: + this->logger()->logging("Connector::Endpoint(ERROR): M2MInterface::NotRegistered"); + break; + case M2MInterface::Timeout: + this->logger()->logging("Connector::Endpoint(ERROR): M2MInterface::Timeout"); + break; + case M2MInterface::NetworkError: + this->logger()->logging("Connector::Endpoint(ERROR): M2MInterface::NetworkError"); + break; + case M2MInterface::ResponseParseFailed: + this->logger()->logging("Connector::Endpoint(ERROR): M2MInterface::ResponseParseFailed"); + break; + case M2MInterface::UnknownError: + this->logger()->logging("Connector::Endpoint(ERROR): M2MInterface::UnknownError"); + break; + case M2MInterface::MemoryFail: + this->logger()->logging("Connector::Endpoint(ERROR): M2MInterface::MemoryFail"); + break; + case M2MInterface::NotAllowed: + this->logger()->logging("Connector::Endpoint(ERROR): M2MInterface::NotAllowed"); + break; + default: + break; + } +} + +// register the endpoint +void Endpoint::register_endpoint(M2MSecurity *endpoint_security, M2MObjectList endpoint_objects) { + if (this->m_endpoint_interface != NULL && endpoint_security != NULL && endpoint_objects.size() > 0) { + // register endpoint + this->logger()->logging("Connector::Endpoint: registering endpoint..."); + this->m_endpoint_interface->register_object(endpoint_security, endpoint_objects); + } +} + +// re-register the endpoint +void Endpoint::re_register_endpoint() { + if (this->m_endpoint_interface != NULL) { + this->m_endpoint_interface->update_registration(this->m_endpoint_security,this->m_options->getLifetime()); + } +} + +// de-register endpoint +void Endpoint::de_register_endpoint(void) { + if (this->m_endpoint_interface != NULL) { + // de-register endpoint + this->logger()->logging("Connector::Endpoint: de-registering endpoint..."); + this->m_endpoint_interface->unregister_object(NULL); + if (this->m_csi != NULL) { + this->m_csi->begin_object_unregistering((void *)this); + } + } +} + +// object registered +void Endpoint::object_registered(M2MSecurity *security, const M2MServer &server) { + this->logger()->logging("Connector::Endpoint: endpoint registered."); + this->m_connected = true; + this->m_registered = true; + if (this->m_csi != NULL) { + this->m_csi->object_registered((void *)this,(void *)security,(void *)&server); + } +} + +// registration updated +void Endpoint::registration_updated(M2MSecurity *security, const M2MServer &server) { + this->logger()->logging("Connector::Endpoint: endpoint re-registered."); + this->m_connected = true; + this->m_registered = true; + if (this->m_csi != NULL) { + this->m_csi->registration_updated((void *)this,(void *)security,(void *)&server); + } +} + +// object unregistered +void Endpoint::object_unregistered(M2MSecurity *server) { + // DEBUG + this->logger()->logging("Connector::Endpoint: endpoint de-registered."); + + // no longer connected/registered + this->m_registered = false; + this->m_connected = false; + + // stop all observers... + this->stopObservations(); + + // invoke ConnectionHandler if we have one... + if (this->m_csi != NULL) { + this->m_csi->object_unregistered((void *)this,(void *)server); + } + + // halt the main event loop... we are done. + net_shutdown_endpoint(); +} + +// bootstrap done +void Endpoint::bootstrap_done(M2MSecurity *server) { + this->logger()->logging("Connector::Endpoint: endpoint bootstrapped."); + if (this->m_csi != NULL) { + this->m_csi->bootstrapped((void *)this,(void *)server); + } +} + +// resource value updated +void Endpoint::value_updated(M2MBase *base, M2MBase::BaseType type) { + // Lookup the resource and invoke process() on it... + DynamicResource *target_res = this->lookupDynamicResource(base); + if (target_res != NULL) { + // DEBUG + //this->logger()->logging("Value Updated (Custom Resource)"); + + // its a custom resource... + target_res->process(base->operation(),type); + } + else { + // DEBUG + //this->logger()->logging("Value Updated (Device Manager)"); + + // let DeviceManager handle it + ((DeviceManager *)this->m_device_manager)->process(base,type); + } + + // CSI + if (this->m_csi != NULL) { + this->m_csi->value_updated((void *)this,(void *)base,(int)type); + } +} + +// lookup which DynamicResource cooresponds to a given M2MBase instance... +DynamicResource *Endpoint::lookupDynamicResource(M2MBase *base) { + const DynamicResourcesList *dynamic_resources = this->m_options->getDynamicResourceList(); + for(int i=0; i<(int)dynamic_resources->size(); ++i) { + M2MBase *t = (M2MBase *)dynamic_resources->at(i)->getResource(); + if (t == base) { + return dynamic_resources->at(i); + } + } + return NULL; +} + +// build out the endpoint +void Endpoint::buildEndpoint() +{ + // initialize as an mbed-client + this->createEndpointInterface(); + + // Create our server instance + this->m_endpoint_security = this->createEndpointInstance(); + + // We now have to bind our device resources + if (this->m_device_manager != NULL) { + // DEBUG + this->logger()->logging("Connector::Endpoint::build(): plumbing the device management objects and resources..."); + + // bind the device manager + ((DeviceManager *)this->m_device_manager)->bind(); + + // push back the Device Resources Object + if (this->m_options->getDeviceResourcesObject() != NULL) { + // DEBUG + this->logger()->logging("Connector::Endpoint::build(): plumbing device resources object..."); + + // push back the device resources object + this->m_endpoint_object_list.push_back((M2MObject *)this->m_options->getDeviceResourcesObject()); + } + else { + // unable to plumb device manager + this->logger()->logging("Connector::Endpoint::build(): Unable to plumb device resources. Not installing device resource object..."); + } + + // push back the Firmware Resources Object + if (this->m_options->getFirmwareResourcesObject() != NULL) { + // DEBUG + this->logger()->logging("Connector::Endpoint::build(): plumbing firmware resources object..."); + + // push back the firmware resources object + this->m_endpoint_object_list.push_back((M2MObject *)this->m_options->getFirmwareResourcesObject()); + } + else { + // unable to plumb firmware manager + this->logger()->logging("Connector::Endpoint::build(): Unable to plumb firmware resources. Not installing firmware resource object..."); + } + } + else { + // no device manager installed + this->logger()->logging("Connector::Endpoint::build(): No device manager installed."); + } + + // Loop through Static Resources and bind each of them... + this->logger()->logging("Connector::Endpoint::build(): adding static resources..."); + const StaticResourcesList *static_resources = this->m_options->getStaticResourceList(); + for(int i=0; i<(int)static_resources->size(); ++i) { + this->logger()->logging("Connector::Endpoint::build(): binding static resource: [%s]...",static_resources->at(i)->getFullName().c_str()); + static_resources->at(i)->bind(this); + } + + // Loop through Dynamic Resources and bind each of them... + this->logger()->logging("Connector::Endpoint::build(): adding dynamic resources..."); + const DynamicResourcesList *dynamic_resources = this->m_options->getDynamicResourceList(); + for(int i=0; i<(int)dynamic_resources->size(); ++i) { + this->logger()->logging("Connector::Endpoint::build(): binding dynamic resource: [%s]...",dynamic_resources->at(i)->getFullName().c_str()); + dynamic_resources->at(i)->bind(this); + } + + // Get the ObjectList from the ObjectInstanceManager... + NamedPointerList list = this->getObjectInstanceManager()->getObjectList(); + + // DEBUG + //this->logger()->logging("Endpoint::build(): All Resources bound. Number of Objects in list: %d",list.size()); + + // add all of the object instances we have created... + for(int i=0;i<(int)list.size();++i) { + // DEBUG + //this->logger()->logging("Endpoint::build(): adding Object Instance with ObjID: %s...",list.at(i).name().c_str()); + + // push back the object instance... + this->m_endpoint_object_list.push_back((M2MObject *)(list.at(i).ptr())); + } +} + +// stop underlying observation mechanisms +void Endpoint::stopObservations() { + const DynamicResourcesList *dynamic_resources = this->m_options->getDynamicResourceList(); + for(int i=0; i<(int)dynamic_resources->size(); ++i) { + if (dynamic_resources->at(i)->isObservable() == true) { + ResourceObserver *observer = (ResourceObserver *)dynamic_resources->at(i)->getObserver(); + if (observer != NULL) { + this->logger()->logging("Connector::Endpoint::stopObservations(): stopping resource observer for: [%s]...",dynamic_resources->at(i)->getFullName().c_str()); + observer->halt(); + } + } + } +} + +// underlying network is connected (SET) +void Endpoint::isConnected(bool connected) { + this->m_connected = connected; +} + +// underlying network is connected (GET) +bool Endpoint::isConnected() { + return this->m_connected; +} + +// Registered with mDC/mDS +bool Endpoint::isRegistered() { + return this->m_registered; +} + +// Set the ConnectionStatusInterface +void Endpoint::setConnectionStatusInterfaceImpl(ConnectionStatusInterface *csi) { + this->m_csi = csi; +} + +// Set our ObjectInstanceManager +void Endpoint::setObjectInstanceManager(ObjectInstanceManager *oim) { + this->m_oim = oim; +} + +// Get our ObjectInstanceManager +ObjectInstanceManager *Endpoint::getObjectInstanceManager() { + return this->m_oim; +} + +// our logger +Logger *Endpoint::logger() +{ + return this->m_logger; +} + +} // namespace Connector
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/DataWrapper.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/DataWrapper.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,92 @@ +/** + * @file DataWrapper.cpp + * @brief mbed CoAP Endpoint Resource Data Wrapper + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + + // Class Support + #include "mbed-connector-interface/DataWrapper.h" + + // constructor + DataWrapper::DataWrapper(uint8_t *data,int data_length) { + this->m_data = data; + this->m_data_length = 0; + this->m_data_length_max = data_length; + this->m_alloced = false; + this->reset(); + } + + // constructor (alloc) + DataWrapper::DataWrapper(int data_length) { + this->m_data = (uint8_t *)malloc(data_length+1); + memset(this->m_data,0,data_length+1); + this->m_data_length = 0; + this->m_data_length_max = data_length; + this->m_alloced = true; + } + + // copy constructor + DataWrapper::DataWrapper(const DataWrapper &data) { + this->m_data = data.m_data; + this->m_data_length = data.m_data_length; + this->m_data_length_max = data.m_data_length_max; + this->m_alloced = data.m_alloced; + } + + // destructor + DataWrapper::~DataWrapper() { + if (this->m_alloced && this->m_data != NULL) free(this->m_data); + } + + // wrap + void DataWrapper::wrap(uint8_t *data,int data_length) { + this->reset(); + if (data != NULL && data_length > 0) { + int length = data_length; + if (length > this->m_data_length_max) length = this->m_data_length_max; + memcpy(this->m_data,data,length); + this->m_data_length = length; + } + } + + // unwrap + void DataWrapper::unwrap(uint8_t *data,int data_length) { + this->reset(); + if (data != NULL && data_length > 0) { + int length = data_length; + if (length > this->m_data_length_max) length = this->m_data_length_max; + memcpy(this->m_data,data,length); + this->m_data_length = length; + } + } + + // reset + void DataWrapper::reset() { + if (this->m_data != NULL && this->m_data_length_max > 0) + memset(this->m_data,0,this->m_data_length_max); + this->m_data_length = 0; + } + + // set the app key + void DataWrapper::setAppKey(uint8_t * /* appkey */,int /* appkey_length */) { + // do nothing in the base class + ; + } + +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/DeviceManagementResponder.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/DeviceManagementResponder.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,256 @@ +/** + * @file DeviceManagementResponder.cpp + * @brief mbed CoAP Endpoint Device Management Responder class + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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. + */ + + // Class support + #include "mbed-connector-interface/DeviceManagementResponder.h" + + // Endpoint support + #include "mbed-connector-interface/ConnectorEndpoint.h" + + // DeviceManager Support + #include "mbed-connector-interface/DeviceManager.h" + + // constructor + DeviceManagementResponder::DeviceManagementResponder(const Logger *logger,const Authenticator *authenticator) { + this->m_logger = (Logger *)logger; + this->m_authenticator = (Authenticator *)authenticator; + this->m_endpoint = NULL; + this->m_initialize_fn = NULL; + this->m_reboot_responder_fn = NULL; + this->m_reset_responder_fn = NULL; + this->m_fota_manifest_fn = NULL; + this->m_fota_image_set_fn = NULL; + this->m_fota_invocation_fn = NULL; + this->m_manifest = NULL; + this->m_manifest_length = 0; + this->m_fota_image = NULL; + this->m_fota_image_length = 0; +} + +// copy constructor +DeviceManagementResponder::DeviceManagementResponder(const DeviceManagementResponder &responder) { + this->m_logger = responder.m_logger; + this->m_authenticator = responder.m_authenticator; + this->m_endpoint = responder.m_endpoint; + this->m_initialize_fn = responder.m_initialize_fn; + this->m_reboot_responder_fn = responder.m_reboot_responder_fn; + this->m_reset_responder_fn = responder.m_reset_responder_fn; + this->m_fota_manifest_fn = responder.m_fota_manifest_fn; + this->m_fota_image_set_fn = responder.m_fota_image_set_fn; + this->m_fota_invocation_fn = responder.m_fota_invocation_fn; + this->m_manifest = responder.m_manifest; + this->m_manifest_length = responder.m_manifest_length; + this->m_fota_image = responder.m_fota_image; + this->m_fota_image_length = responder.m_fota_image_length; +} + +// destructor +DeviceManagementResponder::~DeviceManagementResponder() { +} + +// set the Endpoint +void DeviceManagementResponder::setEndpoint(const void *ep) { + this->m_endpoint = (void *)ep; +} + +// authenticate +bool DeviceManagementResponder::authenticate(const void *challenge) { + if (this->m_authenticator != NULL) { + return this->m_authenticator->authenticate((void *)challenge); + } + return false; +} + +// set the Initialize handler +void DeviceManagementResponder::setInitializeHandler(initialize_fn initialize_fn) { + this->m_initialize_fn = initialize_fn; + if (this->m_initialize_fn != NULL) { + (*this->m_initialize_fn)(this->m_logger); + } +} + +// set the Reboot Responder handler +void DeviceManagementResponder::setRebootResponderHandler(responder_fn reboot_responder_fn) { + this->m_reboot_responder_fn = reboot_responder_fn; +} + +// set the Reset Responder handler +void DeviceManagementResponder::setResetResponderHandler(responder_fn reset_responder_fn) { + this->m_reset_responder_fn = reset_responder_fn; +} + +// set the FOTA manifest handler +void DeviceManagementResponder::setFOTAManifestHandler(manifest_fn fota_manifest_fn) { + this->m_fota_manifest_fn = fota_manifest_fn; +} + +// set the FOTA image set handler +void DeviceManagementResponder::setFOTAImageHandler(image_set_fn fota_image_set_fn) { + this->m_fota_image_set_fn = fota_image_set_fn; +} + +// set the FOTA invocation handler +void DeviceManagementResponder::setFOTAInvocationHandler(responder_fn fota_invocation_fn) { + this->m_fota_invocation_fn = fota_invocation_fn; +} + +// set the FOTA manifest +void DeviceManagementResponder::setFOTAManifest(char *manifest,uint32_t manifest_length) { + this->m_manifest = manifest; + this->m_manifest_length = manifest_length; + if (this->m_fota_manifest_fn != NULL) { + (*this->m_fota_manifest_fn)(this->m_endpoint,this->m_logger,this->m_manifest,this->m_manifest_length); + } +} + +// get the FOTA manifest +char *DeviceManagementResponder::getFOTAManifest() { + return this->m_manifest; +} + +// get the FOTA manifest +uint32_t DeviceManagementResponder::getFOTAManifestLength() { + return this->m_manifest_length; +} + +// set the FOTA Image +void DeviceManagementResponder::setFOTAImage(void *fota_image,uint32_t fota_image_length) { + this->m_fota_image = fota_image; + this->m_fota_image_length = fota_image_length; + if (this->m_fota_image_set_fn != NULL) { + (*this->m_fota_image_set_fn)(this->m_endpoint,this->m_logger,this->m_fota_image,this->m_fota_image_length); + } +} + +// get the FOTA Image +void *DeviceManagementResponder::getFOTAImage() { + return this->m_fota_image; +} + +// get the FOTA Image Length +uint32_t DeviceManagementResponder::getFOTAImageLength() { + return this->m_fota_image_length; +} + +// ACTION: deregister device +void DeviceManagementResponder::deregisterDevice(const void *challenge) { + // check endpoint + if (this->m_endpoint != NULL) { + // authenticate + if (this->authenticate(challenge)) { + // DEBUG + this->m_logger->logging("DeviceManagementResponder(deregister): de-registering device..."); + + // act + ((Connector::Endpoint *)this->m_endpoint)->de_register_endpoint(); + } + else { + // authentication failure + this->m_logger->logging("DeviceManagementResponder(deregister): authentication failed. No action taken."); + } + } + else { + // no endpoint + this->m_logger->logging("DeviceManagementResponder(deregister): No endpoint instance. No action taken."); + } +} + +// ACTION: reboot device +void DeviceManagementResponder::rebootDevice(const void *challenge) { + // check our Reboot Responder handler pointer + if (this->m_reboot_responder_fn != NULL) { + // check endpoint + if (this->m_endpoint != NULL) { + // authenticate + if (this->authenticate(challenge)) { + // act + (*this->m_reboot_responder_fn)((const void *)this->m_endpoint,(const void *)this->m_logger,NULL); + } + else { + // authentication failure + this->m_logger->logging("DeviceManagementResponder(reboot): authentication failed. No action taken."); + } + } + else { + // no endpoint + this->m_logger->logging("DeviceManagementResponder(reboot): No endpoint instance. No action taken."); + } + } + else { + // no reset responder handler + this->m_logger->logging("DeviceManagementResponder(reboot): No reboot responder handler pointer. No action taken."); + } +} + +// ACTION: reset device +void DeviceManagementResponder::resetDevice(const void *challenge) { + // check our Reset Responder handler pointer + if (this->m_reset_responder_fn != NULL) { + // check endpoint + if (this->m_endpoint != NULL) { + // authenticate + if (this->authenticate(challenge)) { + // act + (*this->m_reset_responder_fn)((const void *)this->m_endpoint,(const void *)this->m_logger,NULL); + } + else { + // authentication failure + this->m_logger->logging("DeviceManagementResponder(reset): authentication failed. No action taken."); + } + } + else { + // no endpoint + this->m_logger->logging("DeviceManagementResponder(reset): No endpoint instance. No action taken."); + } + } + else { + // no reset responder handler + this->m_logger->logging("DeviceManagementResponder(reset): No reset responder handler pointer. No action taken."); + } +} + +// ACTION: invoke FOTA +void DeviceManagementResponder::invokeFOTA(const void *challenge) { + // check our FOTA invocation handler pointer + if (this->m_fota_invocation_fn != NULL) { + // check endpoint + if (this->m_endpoint != NULL) { + // authenticate + if (this->authenticate(challenge)) { + // act + (*this->m_fota_invocation_fn)((const void *)this->m_endpoint,(const void *)this->m_logger,this->getFOTAManifest()); + } + else { + // authentication failure + this->m_logger->logging("DeviceManagementResponder(FOTA): authentication failed. No action taken."); + } + } + else { + // no endpoint + this->m_logger->logging("DeviceManagementResponder(FOTA): No endpoint instance. No action taken."); + } + } + else { + // no FOTA invocation handler + this->m_logger->logging("DeviceManagementResponder(FOTA): No FOTA invocation handler pointer. No action taken."); + } +} \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/DeviceManager.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/DeviceManager.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,435 @@ +/** + * @file DeviceManager.cpp + * @brief mbed CoAP Endpoint Device Management class + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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. + */ + + // configuration + #include "mbed-connector-interface/mbedConnectorInterface.h" + + // BaseClass + #include "mbed-connector-interface/DeviceManager.h" + + // Endpoint Class + #include "mbed-connector-interface/ConnectorEndpoint.h" + + // Options Builder + #include "mbed-connector-interface/OptionsBuilder.h" + + // Device Management Responder + #include "mbed-connector-interface/DeviceManagementResponder.h" + +// Constructor +DeviceManager::DeviceManager(const Logger *logger,const void *dm_responder,const char *mfg,const char *dev_type,const char *model,const char *serial,const char *fw_vers,const char *hw_vers,const char *sw_vers) { + // record the data management responder if we have one + this->m_dm_responder = (void *)dm_responder; + + // save off for later + this->m_dev_type = (char *)dev_type; + this->m_logger = (Logger *)logger; + this->m_mfg = (char *)mfg; + this->m_model = (char *)model; + this->m_serial = (char *)serial; + this->m_fw_vers = (char *)fw_vers; + this->m_sw_vers = (char *)sw_vers; + this->m_hw_vers = (char *)hw_vers; + + // initialize + this->m_device = NULL; + for(int i=0;i<NUM_DEVICE_RESOURCES;++i) { + this->m_dev_res[i] = NULL; + } + for(int i=0;i<NUM_FIRMWARE_RESOURCES;++i) { + this->m_fw_res[i] = NULL; + } + this->m_deregister_resource = NULL; + this->m_endpoint = NULL; + this->m_config = NULL; + this->m_fw_manifest = NULL; + this->m_fw_manifest_length = 0; + this->m_fw_image = NULL; + this->m_fw_image_length = 0; +} + +// Copy constructor +DeviceManager::DeviceManager(const DeviceManager &manager) { + for(int i=0;i<NUM_DEVICE_RESOURCES;++i) { + this->m_dev_res[i] = manager.m_dev_res[i]; + } + for(int i=0;i<NUM_FIRMWARE_RESOURCES;++i) { + this->m_fw_res[i] = manager.m_fw_res[i]; + } + this->m_dm_responder = manager.m_dm_responder; + this->m_device = manager.m_device; + this->m_dev_type = manager.m_dev_type; + this->m_logger = manager.m_logger; + this->m_endpoint = manager.m_endpoint; + this->m_config = manager.m_config; + this->m_mfg = manager.m_mfg; + this->m_model = manager.m_model; + this->m_serial = manager.m_serial; + this->m_fw_vers = manager.m_fw_vers; + this->m_sw_vers = manager.m_sw_vers; + this->m_hw_vers = manager.m_hw_vers; + this->m_deregister_resource = manager.m_deregister_resource; + this->m_fw_manifest = this->saveManifest((uint8_t *)manager.m_fw_manifest,manager.m_fw_manifest_length); + this->m_fw_manifest_length = manager.m_fw_manifest_length; + this->m_fw_image = this->saveImage(manager.m_fw_image,manager.m_fw_image_length); + this->m_fw_image_length = manager.m_fw_image_length; +} + +// Destructor +DeviceManager::~DeviceManager() { + if (this->m_fw_manifest != NULL) { + free(this->m_fw_manifest); + } + if (this->m_fw_image != NULL) { + free(this->m_fw_image); + } + this->m_fw_manifest = NULL; + this->m_fw_manifest_length = 0; + this->m_fw_image = NULL; + this->m_fw_image_length = 0; +} + +// save the fota manifest +char *DeviceManager::saveManifest(uint8_t *manifest,uint32_t manifest_length) { + if (manifest != NULL && manifest_length > 0) { + if (this->m_fw_manifest != NULL) { + free(this->m_fw_manifest); + } + this->m_fw_manifest = (char *)malloc(manifest_length+1); + memset(this->m_fw_manifest,0,manifest_length+1); + memcpy(this->m_fw_manifest,manifest,manifest_length); + this->m_fw_manifest_length = manifest_length; + } + return this->m_fw_manifest; +} + +// save the fota image +void *DeviceManager::saveImage(void *image,uint32_t image_length) { + if (image != NULL && image_length > 0) { + if (this->m_fw_image != NULL) { + free(this->m_fw_image); + } + this->m_fw_image = (char *)malloc(image_length); + memset(this->m_fw_image,0,image_length); + memcpy(this->m_fw_image,image,image_length); + } + return this->m_fw_image; +} + +// bind the device resources +void DeviceManager::bindDeviceResources() { + // our Endpoint configuration + Connector::OptionsBuilder *cfg = (Connector::OptionsBuilder *)this->m_config; + + // establish the default base LWM2M device info resource values + this->m_device = M2MInterfaceFactory::create_device(); + if (this->m_device != NULL) { + this->m_dev_res[0] = this->m_device->create_resource(M2MDevice::Manufacturer,this->m_mfg); // Manufacturer + this->m_dev_res[1] = this->m_device->create_resource(M2MDevice::DeviceType,this->m_dev_type); // Device Type + this->m_dev_res[2] = this->m_device->create_resource(M2MDevice::ModelNumber,this->m_model); // Device Model + this->m_dev_res[3] = this->m_device->create_resource(M2MDevice::SerialNumber,this->m_serial); // Device Serial + this->m_dev_res[4] = this->m_device->create_resource(M2MDevice::FirmwareVersion,this->m_fw_vers); // Firmware Version + this->m_dev_res[5] = this->m_device->create_resource(M2MDevice::HardwareVersion,this->m_hw_vers); // Hardware Version + this->m_dev_res[6] = this->m_device->create_resource(M2MDevice::SoftwareVersion,this->m_sw_vers); // Software Version + this->m_dev_res[7] = this->getDeviceRebootResource(); // Reboot + this->m_dev_res[8] = this->m_device->create_resource(M2MDevice::FactoryReset); // Reset + + // set the callback functions for Reboot and Reset + if (this->m_dev_res[7] != NULL) { + this->m_dev_res[7]->set_operation(M2MBase::POST_ALLOWED); + this->m_dev_res[7]->set_execute_function(execute_callback(this,&DeviceManager::process_reboot_action)); + } + if (this->m_dev_res[8] != NULL) { + this->m_dev_res[8]->set_operation(M2MBase::POST_ALLOWED); + this->m_dev_res[8]->set_execute_function(execute_callback(this,&DeviceManager::process_reset_action)); + } + + // set the Device Resources Object + if (cfg != NULL) { + cfg->setDeviceResourcesObject(this->m_device); // device resources created under single device object... so just set it + } + } + else { + // unable to create the device object + this->m_logger->logging("DeviceManager::bindDeviceResources(): Unable to create Device Object!"); + } +} + +// bind the firmware resources +void DeviceManager::bindFirmwareResources() { + // our Endpoint configuration + Connector::OptionsBuilder *cfg = (Connector::OptionsBuilder *)this->m_config; + + // establish the default base LWM2M firmware info resource values + this->m_firmware = M2MInterfaceFactory::create_firmware(); + if (this->m_firmware != NULL) { + // Create our optional resources + this->m_fw_res[0] = this->m_firmware->create_resource(M2MFirmware::PackageName,""); // Package Name + this->m_fw_res[1] = this->m_firmware->create_resource(M2MFirmware::PackageVersion,""); // Package Version + + // Get the speciality resources + this->m_fw_res[2] = this->getFirmwareUpdateResource(); + this->m_fw_res[3] = this->getFirmwarePackageResource(); + this->m_fw_res[4] = this->getFirmwarePackageURIResource(); + this->m_fw_res[5] = this->getFirmwareStateResource(); + this->m_fw_res[6] = this->getFirmwareUpdateResultResource(); + + // set the callback functions for Update + if (this->m_fw_res[2] != NULL) { + this->m_fw_res[2]->set_operation(M2MBase::POST_ALLOWED); + this->m_fw_res[2]->set_execute_function(execute_callback(this,&DeviceManager::process_firmware_update_action)); + } + + // set the Firmware Resources Object + if (cfg != NULL) { + cfg->setFirmwareResourcesObject(this->m_firmware); // firmware resources created under single firmware object... so just set it + } + } + else { + // unable to create the firmware object + this->m_logger->logging("DeviceManager::bindFirmwareResources(): Unable to create Firmware Object!"); + } +} + +// bind mbed Cloud resources +void DeviceManager::bindMBEDCloudResources() { + // our Endpoint configuration + Connector::OptionsBuilder *cfg = (Connector::OptionsBuilder *)this->m_config; + + // Add mbed Cloud resources here... + + // mbed Cloud DeRegistration Resource + this->m_deregister_resource = new DeviceDeRegisterResource(this->m_logger,LWM2M_DREGISTER_OBJ_ID,LWM2M_DEV_DEREGISTER_ID,this->m_dm_responder); + if (this->m_deregister_resource != NULL) { + cfg->addResource(this->m_deregister_resource); // de-registration action resource added + } +} + +// setup the Device Manager +void DeviceManager::bind() { + // Bind our Device Resources + this->bindDeviceResources(); + + // Bind our Firmware Resources + this->bindFirmwareResources(); + + // Bind our mbed Cloud Resources + this->bindMBEDCloudResources(); +} + +// process updated values (PUT): The only updatable device management resources are: Firmware::Package, Firmware::PackageURI +void DeviceManager::process(M2MBase *base, M2MBase::BaseType type) { + // DeviceManagementResponder + DeviceManagementResponder *dmr = (DeviceManagementResponder *)this->m_dm_responder; + + // PackageURI handler + if (base == this->getFirmwareResource(PackageURI)) { + // PackageURI resource + M2MResource *res = this->getFirmwareResource(PackageURI); + + // Save off the manifest + this->saveManifest(res->value(),res->value_length()); + + // DEBUG + this->m_logger->logging("DeviceManager::process(PUT): Setting FOTA Manifest: [%s] type: %d length: %d",this->m_fw_manifest,type,this->m_fw_manifest_length); + + // Manifest Updated + dmr->setFOTAManifest(this->m_fw_manifest,this->m_fw_manifest_length); + } + + // Package handler + if (base == this->getFirmwareResource(Package)) { + // FOTA Image (direct) Updated + M2MResource *res = this->getFirmwareResource(PackageURI); + + // DEBUG + this->m_logger->logging("DeviceManager::process(PUT): Setting FOTA Image. Length=%d type: %d",res->value_length(),type); + + // FOTA Image updated + dmr->setFOTAImage(res->value(),res->value_length()); + } +} + +// Get the Device Reboot Resource from the Device Object +M2MResource *DeviceManager::getDeviceRebootResource() { + if (this->m_device != NULL) { + // Get /3/0/3 + return this->getResourceFromObject(this->m_device,0,M2MDevice::Reboot); + } + return NULL; +} + +// Get the Firmware Update Resource from the Firmware Object +M2MResource *DeviceManager::getFirmwareUpdateResource() { + if (this->m_firmware != NULL) { + // Get /5/0/2 + return this->getResourceFromObject(this->m_firmware,0,M2MFirmware::Update); + } + return NULL; +} + +// Get the Firmware Package Resource from the Firmware Object +M2MResource *DeviceManager::getFirmwarePackageResource() { + if (this->m_firmware != NULL) { + // Get /5/0/0 + return this->getResourceFromObject(this->m_firmware,0,M2MFirmware::Package); + } + return NULL; +} + +// Get the Firmware Package URI Resource from the Firmware Object +M2MResource *DeviceManager::getFirmwarePackageURIResource() { + if (this->m_firmware != NULL) { + // Get /5/0/1 + return this->getResourceFromObject(this->m_firmware,0,M2MFirmware::PackageUri); + } + return NULL; +} + +// Get the Firmware State Resource from the Firmware Object +M2MResource *DeviceManager::getFirmwareStateResource() { + if (this->m_firmware != NULL) { + // Get /5/0/3 + return this->getResourceFromObject(this->m_firmware,0,M2MFirmware::State); + } + return NULL; +} + +// Get the Firmware UpdateResult Resource from the Firmware Object +M2MResource *DeviceManager::getFirmwareUpdateResultResource() { + if (this->m_firmware != NULL) { + // Get /5/0/5 + return this->getResourceFromObject(this->m_firmware,0,M2MFirmware::UpdateResult); + } + return NULL; +} +// Get a specific resource from a resource object +M2MResource *DeviceManager::getResourceFromObject(M2MObject *obj,int instanceID,int resID) { + if (obj != NULL) { + M2MObjectInstanceList instances = obj->instances(); + if (instances.size() > 0 && instances.size() > instanceID) { + M2MObjectInstance *instance = instances[instanceID]; + if (instance != NULL) { + M2MResourceList resources = instance->resources(); + if (resources.size() > 0 && resources.size() > resID) { + M2MResource *resource = resources[resID]; + return resource; + } + } + } + } + return NULL; +} + +// Get the Device Object + M2MDevice *DeviceManager::getDeviceObject() { + return this->m_device; +} + +// Get the Firmware Object +M2MFirmware *DeviceManager::getFirmwareObject() { + return this->m_firmware; +} + +// extract a specific firmware resource +M2MResource *DeviceManager::getFirmwareResource(FirmwareResources res) { + // indexed optional resources + int index = (int)res; + if (index >= 0 && index <NUM_FIRMWARE_RESOURCES) { + return this->m_fw_res[index]; + } + return NULL; +} + +// extract a specific device resource +M2MResource *DeviceManager::getDeviceResource(DeviceResources res) { + // special case: DeRegistration + if (res == DeRegistration){ + return this->m_deregister_resource->getResource(); + } + + // indexed optional resources + int index = (int)res; + if (index >= 0 && index <NUM_DEVICE_RESOURCES) { + return this->m_dev_res[index]; + } + return NULL; +} + +// Install the device manager into the Connector Endpoint +void DeviceManager::install(const void *endpoint,const void *config) { + // record the configuration + this->m_config = (void *)config; + + // record the endpoint + this->m_endpoint = (void *)endpoint; + + // set the endpoint type + Connector::OptionsBuilder *cfg = (Connector::OptionsBuilder *)this->m_config; + if (cfg != NULL) { + // set our device type + cfg->setEndpointType(this->m_dev_type); + } + + // establish connection to our responder + if (this->m_dm_responder != NULL) { + ((DeviceManagementResponder *)this->m_dm_responder)->setEndpoint(this->m_endpoint); + } +} + +// get our device management responder +void *DeviceManager::getResponder() { + return this->m_dm_responder; +} + +// process our reboot action +void DeviceManager::process_reboot_action(void *args) { + if (this->m_dm_responder != NULL) { + ((DeviceManagementResponder *)this->m_dm_responder)->rebootDevice(args); + } + else { + // no device management responder instance + this->m_logger->logging("DeviceManager::process_reboot_action: DeviceManagementResponder is NULL. No reboot processed"); + } +} + +// process our reset action +void DeviceManager::process_reset_action(void *args) { + if (this->m_dm_responder != NULL) { + ((DeviceManagementResponder *)this->m_dm_responder)->resetDevice(args); + } + else { + // no device management responder instance + this->m_logger->logging("DeviceManager:: process_reset_action: DeviceManagementResponder is NULL. No reset processed"); + } +} + +// process our firmware update action +void DeviceManager::process_firmware_update_action(void *args) { + if (this->m_dm_responder != NULL) { + ((DeviceManagementResponder *)this->m_dm_responder)->invokeFOTA(args); + } + else { + // no device management responder instance + this->m_logger->logging("DeviceManager:: process_firmware_update_action: DeviceManagementResponder is NULL. No firmware update action processed"); + } +} \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/DynamicResource.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/DynamicResource.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,484 @@ +/** + * @file DynamicResource.cpp + * @brief mbed CoAP Endpoint Dynamic Resource class + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + +// Class support +#include "mbed-connector-interface/DynamicResource.h" + +// ResourceObserver help +#include "mbed-connector-interface/ResourceObserver.h" + +// Options enablement +#include "mbed-connector-interface/Options.h" + +// Endpoint +#include "mbed-connector-interface/ConnectorEndpoint.h" + +// GET option that can be used to Start/Stop Observations... +#define START_OBS 0 +#define STOP_OBS 1 + +// MaxAge support for each DynamicResource +#define DEFAULT_MAXAGE 60 + +// ContentFormat defaults for each DynamicResource +#define DEFAULT_CONTENT_FORMAT 0 + +// default constructor +DynamicResource::DynamicResource(const Logger *logger,const char *obj_name,const char *res_name,const char *res_type,uint8_t res_mask,const bool observable,const ResourceType type) : Resource<string>(logger,string(obj_name),string(res_name),string("")) +{ + this->m_res_type = string(res_type); + this->m_type = type; + this->m_observable = observable; + this->m_res_mask = res_mask; + this->m_obs_number = 0; + this->m_data_wrapper = NULL; + this->m_observer = NULL; + this->m_maxage = DEFAULT_MAXAGE; + this->m_content_format = DEFAULT_CONTENT_FORMAT; + this->m_ep = NULL; + this->m_res = NULL; +} + +// constructor (input initial value) +DynamicResource::DynamicResource(const Logger *logger,const char *obj_name,const char *res_name,const char *res_type,const string value,uint8_t res_mask,const bool observable,const ResourceType type) : Resource<string>(logger,string(obj_name),string(res_name),value) +{ + this->m_res_type = string(res_type); + this->m_type = type; + this->m_observable = observable; + this->m_res_mask = res_mask; + this->m_obs_number = 0; + this->m_data_wrapper = NULL; + this->m_observer = NULL; + this->m_maxage = DEFAULT_MAXAGE; + this->m_content_format = DEFAULT_CONTENT_FORMAT; + this->m_ep = NULL; + this->m_res = NULL; +} + +// constructor (strings) +DynamicResource::DynamicResource(const Logger *logger,const string obj_name,const string res_name,const string res_type,const string value,uint8_t res_mask,const bool observable,const ResourceType type) : Resource<string>(logger,obj_name,res_name,value) +{ + this->m_res_type = res_type; + this->m_type = type; + this->m_observable = observable; + this->m_res_mask = res_mask; + this->m_obs_number = 0; + this->m_data_wrapper = NULL; + this->m_observer = NULL; + this->m_maxage = DEFAULT_MAXAGE; + this->m_content_format = DEFAULT_CONTENT_FORMAT; + this->m_ep = NULL; + this->m_res = NULL; +} + +// copy constructor +DynamicResource::DynamicResource(const DynamicResource &resource) : Resource<string>((const Resource<string> &)resource) +{ + this->m_res_type = resource.m_res_type; + this->m_type = resource.m_type; + this->m_observable = resource.m_observable; + this->m_res_mask = resource.m_res_mask; + this->m_obs_number = resource.m_obs_number; + this->m_data_wrapper = resource.m_data_wrapper; + this->m_observer = resource.m_observer; + this->m_maxage = resource.m_maxage; + this->m_content_format = resource.m_content_format; + this->m_ep = resource.m_ep; + this->m_res = resource.m_res; +} + +// destructor +DynamicResource::~DynamicResource() { +} + +// bind CoAP Resource... +void DynamicResource::bind(void *ep) { + if (ep != NULL) { + // cast + Connector::Endpoint *endpoint = (Connector::Endpoint *)ep; + + // get our ObjectInstanceManager + ObjectInstanceManager *oim = endpoint->getObjectInstanceManager(); + + // Create our Resource + this->m_res = (M2MResource *)oim->createDynamicResourceInstance((char *)this->getObjName().c_str(),(char *)this->getResName().c_str(),(char *)this->m_res_type.c_str(),(int)this->m_type,this->m_observable); + if (this->m_res != NULL) { + // Record our Instance Number + this->setInstanceNumber(oim->getLastCreatedInstanceNumber()); + + // perform an initial get() to initialize our data value + this->setValue(this->get()); + + // now record the data value + if (this->getDataWrapper() != NULL) { + // wrap the data... + this->getDataWrapper()->wrap((uint8_t *)this->getValue().c_str(),(int)this->getValue().size()); + this->m_res->set_operation((M2MBase::Operation)this->m_res_mask); + this->m_res->set_value( this->getDataWrapper()->get(),(uint8_t)this->getDataWrapper()->length()); + this->logger()->logging("%s: [%s] value: [%s] bound (observable: %d)",this->m_res_type.c_str(),this->getFullName().c_str(),this->getDataWrapper()->get(),this->m_observable); + } + else { + // do not wrap the data... + this->m_res->set_operation((M2MBase::Operation)this->m_res_mask); + this->m_res->set_value((uint8_t *)this->getValue().c_str(),(uint8_t)this->getValue().size()); + this->logger()->logging("%s: [%s] value: [%s] bound (observable: %d)",this->m_res_type.c_str(),this->getFullName().c_str(),this->getValue().c_str(),this->m_observable); + } + + // set our endpoint instance + this->m_ep = (void *)ep; + + // For POST-enabled RESOURCES (only...), we must add a callback + if ((this->m_res_mask & M2MBase::POST_ALLOWED) != 0) { + // add a callback for the execute function...we will just direct through process()... + //this->logger()->logging("DynamicResource::bind(): Setting up POST execute callback function"); + this->m_res->set_execute_function(execute_callback(this, &DynamicResource::process_resource_post)); + } + } + } + else { + // no instance pointer to our endpoint + this->logger()->logging("%s: NULL endpoint instance pointer in bind() request...",this->m_res_type.c_str()); + } +} + +// get our M2MBase representation +M2MResource *DynamicResource::getResource() { + return this->m_res; +} + +// process inbound mbed-client POST message for a Resource +void DynamicResource::process_resource_post(void *args) { + // just call process() for POST and Resources... + //this->logger()->logging("DynamicResource::process_resource_post(): calling process(POST)"); + (void)this->process(M2MBase::POST_ALLOWED,this->m_res->base_type(),args); +} + +// process inbound mbed-client message +uint8_t DynamicResource::process(M2MBase::Operation op,M2MBase::BaseType type,void *args) { +#if defined (HAS_EXECUTE_PARAMS) + M2MResource::M2MExecuteParameter* param = NULL; + + // cast args if present... + if (args != NULL) { + param = (M2MResource::M2MExecuteParameter*)args; + } +#endif + // DEBUG + //this->logger()->logging("in %s::process() Operation=0x0%x Type=%x%x",this->m_res_type.c_str(),op,type); + + // PUT() check + if ((op & M2MBase::PUT_ALLOWED) != 0) { + string value = this->coapDataToString(this->m_res->value(),this->m_res->value_length()); + this->logger()->logging("%s: put(%d) [%s]=[%s] called.",this->m_res_type.c_str(),type,this->getFullName().c_str(),value.c_str()); + this->put(value.c_str()); + return 0; + } + +#if defined (HAS_EXECUTE_PARAMS) + // POST() check + if ((op & M2MBase::POST_ALLOWED) != 0) { + string value; + if (param != NULL) { + // use parameters + String object_name = param->get_argument_object_name(); + int instance_id = (int)param->get_argument_object_instance_id(); + String resource_name = param->get_argument_resource_name(); + value = this->coapDataToString(param->get_argument_value(),param->get_argument_value_length()); + this->logger()->logging("%s: post(%d) [%s/%d/%s]=[%s]) called.",this->m_res_type.c_str(),type,object_name.c_str(),instance_id,resource_name.c_str(),value.c_str()); + } + else { + // use the resource value itself + value = this->coapDataToString(this->m_res->value(),this->m_res->value_length()); + this->logger()->logging("%s: post(%d) [%s]=[%s] called.",this->m_res_type.c_str(),type,this->getFullName().c_str(),value.c_str()); + } + + // invoke + this->post(args); + return 0; + } +#else + // POST() check + if ((op & M2MBase::POST_ALLOWED) != 0) { + if (args != NULL) { + this->logger()->logging("%s: post(%d) [%s]=[%s] called.",this->m_res_type.c_str(),type,this->getFullName().c_str(),(char *)args); + this->post(args); + } + else { + string value = this->coapDataToString(this->m_res->value(),this->m_res->value_length()); + this->logger()->logging("%s: post(%d) [%s]=[%s] called.",this->m_res_type.c_str(),type,this->getFullName().c_str(),value.c_str()); + this->post((void *)value.c_str()); + } + return 0; + } +#endif + +#if defined (HAS_EXECUTE_PARAMS) + // DELETE() check + if ((op & M2MBase::DELETE_ALLOWED) != 0) { + if (param != NULL) { + // use parameters + String object_name = param->get_argument_object_name(); + int instance_id = (int)param->get_argument_object_instance_id(); + String resource_name = param->get_argument_resource_name(); + string value = this->coapDataToString(param->get_argument_value(),param->get_argument_value_length()); + this->logger()->logging("%s: delete(%d) [%s/%d/%s]=[%s]) called.",this->m_res_type.c_str(),type,object_name.c_str(),instance_id,resource_name.c_str(),value.c_str()); + } + else { + // use the resource value itself + string value = this->coapDataToString(this->m_res->value(),this->m_res->value_length()); + this->logger()->logging("%s: delete(%d) [%s]=[%s] called.",this->m_res_type.c_str(),type,this->getFullName().c_str(),value.c_str()); + } + + // invoke + this->del(args); + return 0; + } +#else + // DELETE() check + if ((op & M2MBase::DELETE_ALLOWED) != 0) { + if (args != NULL) { + this->logger()->logging("%s: delete(%d) [%s]=[%s] called.",this->m_res_type.c_str(),type,this->getFullName().c_str(),(char *)args); + this->del(args); + } + else { + string value = this->coapDataToString(this->m_res->value(),this->m_res->value_length()); + this->logger()->logging("%s: delete(%d) [%s]=[%s] called.",this->m_res_type.c_str(),type,this->getFullName().c_str(),value.c_str()); + this->del((void *)value.c_str()); + } + } +#endif + + // unknown type... + this->logger()->logging("%s: Unknown Operation (0x%x) for [%s]=[%s]... FAILED.",op,this->m_res_type.c_str(),this->getFullName().c_str(),this->m_res->value()); + return 1; +} + +// send the notification +int DynamicResource::notify(const string data) { + return this->notify((uint8_t *)data.c_str(),(int)data.length()); +} + +// send the notification +int DynamicResource::notify(uint8_t *data,int data_length) { + uint8_t *notify_data = NULL; + int notify_data_length = 0; + int status = 0; + + // convert the string from the GET to something suitable for CoAP payloads + if (this->getDataWrapper() != NULL) { + // wrap the data... + this->getDataWrapper()->wrap((uint8_t *)data,data_length); + + // announce (after wrap) + //this->logger()->logging("Notify payload [%s]...",this->getDataWrapper()->get()); + + // fill notify + notify_data_length = this->getDataWrapper()->length(); + notify_data = this->getDataWrapper()->get(); + } + else { + // announce (no wrap) + //this->logger()->logging("Notify payload [%s]...",data); + + // do not wrap the data... + notify_data_length = data_length; + notify_data = data; + } + + // update the resource + this->m_res->set_value((uint8_t *)notify_data,(uint8_t)notify_data_length); + + // return our status + return status; +} + +// default GET (does nothing) +string DynamicResource::get() +{ + // not used by default + //this->logger()->logging("DynamicResource::get() invoked (NOOP)"); + return string(""); +} + +// default PUT (does nothing) +void DynamicResource::put(const string /* value */) +{ + // not used by default + //this->logger()->logging("DynamicResource::put() invoked (NOOP)"); +} + +// default POST (does nothing) +void DynamicResource::post(void * /* args */) +{ + // not used by default + //this->logger()->logging("DynamicResource::post() invoked (NOOP)"); +} + +// default DELETE (does nothing) +void DynamicResource::del(void * /* args */) +{ + // not used by default + //this->logger()->logging("DynamicResource::del() invoked (NOOP)"); +} + +// default observe behavior +void DynamicResource::observe() { + if (this->m_observable == true && this->isRegistered() == true) { + this->notify(this->get()); + } +} + +// set the observer pointer +void DynamicResource::setObserver(void *observer) { + this->m_observer = observer; +} + +// set the content-format in responses +void DynamicResource::setContentFormat(uint8_t content_format) { + this->m_content_format = content_format; +} + +// set the max-age of responses +void DynamicResource::setMaxAge(uint8_t maxage) { + this->m_maxage = maxage; +} + +// convert the CoAP data pointer to a string type +string DynamicResource::coapDataToString(uint8_t *coap_data_ptr,int coap_data_ptr_length) +{ + if (coap_data_ptr != NULL && coap_data_ptr_length > 0) { + if (this->getDataWrapper() != NULL) { + // unwrap the data... + this->getDataWrapper()->unwrap(coap_data_ptr,coap_data_ptr_length); + char *buf = (char *)this->getDataWrapper()->get(); // assumes data is null terminated in DataWrapper... + return string(buf); + } + else { + // no unwrap of the data... + char buf[MAX_VALUE_BUFFER_LENGTH+1]; + memset(buf,0,MAX_VALUE_BUFFER_LENGTH+1); + memcpy(buf,(char *)coap_data_ptr,coap_data_ptr_length); + return string(buf); + } + } + return string(""); +} + +// convert the CoAP data pointer to an integer type +int DynamicResource::coapDataToInteger(uint8_t *coap_data_ptr,int coap_data_ptr_length) { + int value = 0; + if (coap_data_ptr != NULL && coap_data_ptr_length > 0) { + if (this->getDataWrapper() != NULL) { + // unwrap the data... + this->getDataWrapper()->unwrap(coap_data_ptr,coap_data_ptr_length); + //value = (int)this->getDataWrapper()->get(); // assumes data is null terminated in DataWrapper... + } + else { + // no unwrap of the data... + //value = (int)coap_data_ptr; + } + } + return value; +} + +// convert the CoAP data pointer to a float type +float DynamicResource::coapDataToFloat(uint8_t *coap_data_ptr,int coap_data_ptr_length) { + float value = 0.0; + if (coap_data_ptr != NULL && coap_data_ptr_length > 0) { + if (this->getDataWrapper() != NULL) { + // unwrap the data... + this->getDataWrapper()->unwrap(coap_data_ptr,coap_data_ptr_length); + //value = (float)this->getDataWrapper()->get(); // assumes data is null terminated in DataWrapper... + } + else { + // no unwrap of the data... + //value = (float)coap_data_ptr; + } + } + return value; +} + +// convert the CoAP data pointer to an opaque type +void *DynamicResource::coapDataToOpaque(uint8_t *coap_data_ptr,int coap_data_ptr_length) { + if (coap_data_ptr != NULL && coap_data_ptr_length > 0) { + if (this->getDataWrapper() != NULL) { + // unwrap the data... + this->getDataWrapper()->unwrap(coap_data_ptr,coap_data_ptr_length); + char *buf = (char *)this->getDataWrapper()->get(); // assumes data is null terminated in DataWrapper... + return (void *)buf; + } + } + return (void *)coap_data_ptr; +} + +// Determine if we are connected or not +bool DynamicResource::isConnected() { + bool is_connected = false; + + // get our Endpoint + Connector::Endpoint *ep = (Connector::Endpoint *)this->m_endpoint; + if (ep != NULL) { + is_connected = ep->isConnected(); + if (is_connected) { + //this->logger()->logging("DynamicResource::isConnected = true"); + } + else { + //this->logger()->logging("DynamicResource::isConnected = false"); + } + } + else { + this->logger()->logging("DynamicResource::isConnected = false (no endpoint)"); + } + + // return our endpoint connection state + return is_connected; +} + +// Determine if we are registered or not +bool DynamicResource::isRegistered() { + bool is_registered = false; + + if (this->isConnected() == true) { + // get our Endpoint + Connector::Endpoint *ep = (Connector::Endpoint *)this->m_endpoint; + if (ep != NULL) { + is_registered = ep->isRegistered(); + if (is_registered) { + //this->logger()->logging("DynamicResource::isRegistered = true"); + } + else { + //this->logger()->logging("DynamicResource::isRegistered = false"); + } + } + else { + this->logger()->logging("DynamicResource::isRegistered = false (no endpoint)"); + } + } + + // return our endpoint registration state + return is_registered; +} + +// get our observer +void *DynamicResource::getObserver() { + return this->m_observer; +} \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/Location.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/Location.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,69 @@ +/** + * @file Location.cpp + * @brief mbed CoAP Endpoint Location base class + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + +// Class support +#include "mbed-connector-interface/Location.h" + +namespace Connector { + +// Constructor +Location::Location() { + memset(this->m_latitude,0,LOCATION_COORDINATE_LENGTH+1); + memset(this->m_longitude,0,LOCATION_COORDINATE_LENGTH+1); + memset(this->m_msl_altitude_m,0,LOCATION_MSL_ALT_LENGTH+1); + memset(this->m_speed,0,LOCATION_SPEED_LENGTH+1); +} + +// Copy Constructor +Location::Location(const Location &location) { + memcpy(this->m_latitude,location.m_latitude,LOCATION_COORDINATE_LENGTH+1); + memcpy(this->m_longitude,location.m_longitude,LOCATION_COORDINATE_LENGTH+1); + memcpy(this->m_msl_altitude_m,location.m_msl_altitude_m,LOCATION_MSL_ALT_LENGTH+1); + memcpy(this->m_speed,location.m_speed,LOCATION_SPEED_LENGTH+1); +} + +// Destructor +Location::~Location() { +} + +// get the latitude +char *Location::getLatitude() { + return this->m_latitude; +} + +// get the longitude +char *Location::getLongitude() { + return this->m_longitude; +} + +// get the MSL Altitude +char *Location::getMSLAltitude() { + return this->m_msl_altitude_m; +} + +// get the Speed +char *Location::getSpeed() { + return this->m_speed; +} + +}; +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/Logger.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/Logger.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,64 @@ +/** + * @file Logger.cpp + * @brief mbed CoAP Endpoint logging class + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + +// Class support +#include "mbed-connector-interface/Logger.h" + +// Constructor +Logger::Logger(const Serial *pc) +{ + this->m_pc = (Serial *)pc; +} + +// Copy Constructor +Logger::Logger(const Logger &logger) +{ + this->m_pc = logger.m_pc; +} + +// Destructor +Logger::~Logger() +{ +} + +// Log the ouput to the attached serial console +void Logger::logIt(const char *format,...) +{ +#if !defined(QUIET_LOGGING) + // build the variable args into a string + va_list args; + char buffer[LOGGER_BUFFER_LENGTH+1]; + memset(buffer,0,LOGGER_BUFFER_LENGTH+1); + va_start(args, format); + vsnprintf(buffer,LOGGER_BUFFER_LENGTH,format,args); + + // clean up... + va_end(args); + + // print it... + if (this->m_pc != NULL) + this->m_pc->printf("%s",buffer); +// else +// std::printf("%s",buffer); +#endif +} +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/MinarResourceObserver.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/MinarResourceObserver.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,69 @@ +/** + * @file MinarResourceObserver.cpp + * @brief mbed CoAP DynamicResource Minar-based observer (implementation) + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + +// class support +#include "mbed-connector-interface/MinarResourceObserver.h" + +#if defined(MCI_MINAR_SCHEDULER) + + // constructor + MinarResourceObserver::MinarResourceObserver(DynamicResource *resource,int sleep_time) : ResourceObserver(resource,sleep_time) { + this->setObserving(false); + + // DEBUG + if (sleep_time > 0) { + this->logger()->log("MinarResourceObserver being used for %s (sleep_time: %d ms)",resource->getFullName().c_str(),sleep_time); + } + else { + this->logger()->log("MinarResourceObserver being used for %s",resource->getFullName().c_str()); + } + } + + // destructor + MinarResourceObserver::~MinarResourceObserver() { + this->stopObservation(); + } + + // notifier + void MinarResourceObserver::perform_observation() { + if (this->isObserving() == true && this->getResource() != NULL && this->getResource()->isConnected() == true) { + this->getResource()->observe(); + } + } + + // begin observing... + void MinarResourceObserver::beginObservation() { + this->setObserving(true); + minar::Scheduler::postCallback(this,&MinarResourceObserver::perform_observation).period(minar::milliseconds(this->getSleepTime())); + } + + // stop observing... + void MinarResourceObserver::stopObservation() { + this->setObserving(false); + } + + // halt the underlying observer mechanism + void MinarResourceObserver::halt() { + minar::Scheduler::stop(); + } + + #endif // MCI_MINAR_SCHEDULER
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/NamedPointer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/NamedPointer.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,79 @@ +/** + * @file NamedPointer.cpp + * @brief mbed CoAP Endpoint Device Management Named Pointer + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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. + */ + +// Base Class +#include "mbed-connector-interface/ObjectInstanceManager.h" + +// constructor +NamedPointer::NamedPointer(string name,void *ptr,int index) { + this->m_name = name; + this->m_ptr = ptr; + this->m_index = index; + this->m_list = (void *)new NamedPointerList(); +} + +// copy constructor +NamedPointer::NamedPointer(const NamedPointer &np) { + this->m_name = np.m_name; + this->m_ptr = np.m_ptr; + this->m_index = np.m_index; + this->m_list = this->copyList(np.m_list); +} + +// Destructor +NamedPointer::~NamedPointer() { + NamedPointerList *list = (NamedPointerList *)this->m_list; + if (list != NULL) { + delete list; + } +} + +// Get the Name +string NamedPointer::name() { + return this->m_name; +} + +// Get the Pointer +void *NamedPointer::ptr() { + return this->m_ptr; +} + +// Get the Index +int NamedPointer::index() { + return this->m_index; +} + +// Get any associated list +void *NamedPointer::list() { + return this->m_list; +} + +// Copy the list +void *NamedPointer::copyList(void *list) { + NamedPointerList *npl = new NamedPointerList(); + NamedPointerList *tmp_list = (NamedPointerList *)list; + for(int i=0;tmp_list != NULL && i<(int)tmp_list->size();++i) { + npl->push_back(tmp_list->at(i)); + } + return (void *)npl; +} + \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/ObjectInstanceManager.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/ObjectInstanceManager.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,170 @@ +/** + * @file ObjectInstanceManager.cpp + * @brief mbed CoAP Endpoint Device Management Object Instance Manager + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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. + */ + +// Class support +#include "mbed-connector-interface/ObjectInstanceManager.h" + +// mbed-client support +#include "mbed-client/m2minterfacefactory.h" +#include "mbed-client/m2minterfaceobserver.h" +#include "mbed-client/m2minterface.h" +#include "mbed-client/m2mobjectinstance.h" +#include "mbed-client/m2mresource.h" +#include "mbed-client/m2mdevice.h" +#include "mbed-client/m2mfirmware.h" + +// string support +#include <string> + + // constructor + ObjectInstanceManager::ObjectInstanceManager(const Logger *logger,const void *ep) { + this->m_logger = (Logger *)logger; + this->m_ep = (void *)ep; + this->m_object_list.clear(); + this->m_instance_number = 0; +} + +// copy constructor +ObjectInstanceManager::ObjectInstanceManager(const ObjectInstanceManager &oim) { + this->m_logger = oim.m_logger; + this->m_ep = oim.m_ep; + this->m_object_list = oim.m_object_list; + this->m_instance_number = oim.m_instance_number; +} + +// destructor +ObjectInstanceManager::~ObjectInstanceManager() { + this->m_object_list.clear(); +} + +// create a Dynamic Resource Instance +void *ObjectInstanceManager::createDynamicResourceInstance(char *objID,char *resID,char *resName,int resType,bool observable) { + void *res = NULL; + M2MObjectInstance *instance = (M2MObjectInstance *)this->getOrCreateInstance(objID,resID); + if (instance != NULL) { + // DEBUG + //this->logger()->logging("ObjectInstanceManager: Creating Dynamic Resource: ObjID:%s ResID:%s ResName:%s Type:%d Observable: %d",objID,resID,resName,resType,observable); + + // create the resource + res = (void *)instance->create_dynamic_resource(resID,resName,(M2MResourceInstance::ResourceType)resType,observable); + } + return res; +} + +// create a Static Resource Instance +void *ObjectInstanceManager::createStaticResourceInstance(char *objID,char *resID,char *resName,int resType,void *data,int data_length) { + void *res = NULL; + M2MObjectInstance *instance = (M2MObjectInstance *)this->getOrCreateInstance(objID,resID); + if (instance != NULL) { + // DEBUG + //this->logger()->logging("ObjectInstanceManager: Creating Static Resource: ObjID:%s ResID:%s ResName:%s Type:%d DataLength: %d",objID,resID,resName,resType,data_length); + + // create the resource + res = (void *)instance->create_static_resource(resID,resName,(M2MResourceInstance::ResourceType)resType,(uint8_t *)data,(uint8_t)data_length); + } + return res; +} + +// Get the instance number of the resource just created +int ObjectInstanceManager::getLastCreatedInstanceNumber() { + return this->m_instance_number; +} + +// create and/or retrieve a given instance +void *ObjectInstanceManager::getOrCreateInstance(char *objID,char *resID) { + void *instance = NULL; + NamedPointer *obj_np = this->getOrCreateObject(objID); + if (obj_np != NULL) { + NamedPointerList *list = (NamedPointerList *)obj_np->list(); + NamedPointer *inst_np = this->getNamedPointer(resID,list); + if (inst_np != NULL) { + // instance already exists... so create another one (n)... + M2MObject *obj = (M2MObject *)(obj_np->ptr()); + if (obj != NULL) { + instance = (void *)obj->create_object_instance(); + this->m_instance_number = inst_np->index()+1; + NamedPointer new_inst_np(string(resID),instance,this->m_instance_number); + list->push_back(new_inst_np); + } + } + else if (list->size() > 0) { + // 0th instance exists... parent the resource to it... + this->m_instance_number = 0; + instance = (void *)(list->at(0).ptr()); + } + else { + // no instance does not exist so create one (0).. + M2MObject *obj = (M2MObject *)(obj_np->ptr()); + if (obj != NULL) { + instance = (void *)obj->create_object_instance(); + this->m_instance_number = 0; + NamedPointer new_inst_np(string(resID),instance,this->m_instance_number); + list->push_back(new_inst_np); + } + } + } + else { + // DEBUG + this->logger()->logging("getOrCreateInstance: unable to create object instance for objID:%s",objID); + } + return instance; +} + +// create and/or retrieve a given objectID +NamedPointer *ObjectInstanceManager::getOrCreateObject(char *objID) { + NamedPointer *result = NULL; + if (objID != NULL) { + result = this->getNamedPointer(objID,&(this->m_object_list)); + } + if (result == NULL) { + void *obj = (void *)M2MInterfaceFactory::create_object(objID); + NamedPointer new_np(string(objID),obj,0); + this->m_object_list.push_back(new_np); + result = this->getNamedPointer(objID,&(this->m_object_list)); + } + return result; +} + +// get the named pointer for a given id +NamedPointer *ObjectInstanceManager::getNamedPointer(const char *id,NamedPointerList *list) { + NamedPointer *result = NULL; + bool found = false; + for(int i=0;list != NULL && i<(int)list->size() && !found;++i) { + char *tmp_id = (char *)list->at(i).name().c_str(); + if (id != NULL && tmp_id != NULL && strcmp(id,tmp_id) == 0) { + found = true; + result = &(list->at(i)); + } + } + return result; +} + +// Get our Object List +NamedPointerList ObjectInstanceManager::getObjectList() { + return this->m_object_list; +} + +// Logger +Logger *ObjectInstanceManager::logger() { + return this->m_logger; +} +
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/Options.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/Options.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,176 @@ +/** + * @file Options.cpp + * @brief mbed CoAP Options (immutable OptionsBuilder instance) class implementation + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + +// Class support +#include "mbed-connector-interface/Options.h" + +// Utils +#include "mbed-connector-interface/Utils.h" + +namespace Connector { + +// default constructor +Options::Options() +{ +} + +// copy constructor +Options::Options(const Options & /* opt */) +{ +} + +// destructors +Options::~Options() +{ +} + +// lifetime pointer +int Options::getLifetime() +{ + return this->m_lifetime; +} + +// NSP domain +string Options::getDomain() +{ + return this->m_domain; +} + +// Endpoint name +string Options::getEndpointNodename() +{ + return this->m_node_name; +} + +// Endpoint Type +string Options::getEndpointType() +{ + return this->m_endpoint_type; +} + +// Connector URL +char *Options::getConnectorURL() +{ + return (char *)this->m_connector_url.c_str(); +} + +// Connector Port +uint16_t Options::getConnectorPort() +{ + return extract_port_from_url(this->getConnectorURL(),DEF_COAP_PORT); +} + +// Device Resources Object +void *Options::getDeviceResourcesObject() +{ + return this->m_device_resources_object; +} + +// Firmware Resources Object +void *Options::getFirmwareResourcesObject() +{ + return this->m_firmware_resources_object; +} + +// Static Resources +StaticResourcesList *Options::getStaticResourceList() +{ + return &this->m_static_resources; +} + +// Dynamic Resources +DynamicResourcesList *Options::getDynamicResourceList() +{ + return &this->m_dynamic_resources; +} + +// WiFi SSID +string Options::getWiFiSSID() { + return this->m_wifi_ssid; +} + +// WiFi AuthType +WiFiAuthTypes Options::getWiFiAuthType() { + return this->m_wifi_auth_type; +} + +// WiFi AuthKey +string Options::getWiFiAuthKey() { + return this->m_wifi_auth_key; +} + +// CoAP Connection Type +CoAPConnectionTypes Options::getCoAPConnectionType() { + return this->m_coap_connection_type; +} + +// IP Address Type +IPAddressTypes Options::getIPAddressType() { + return this->m_ip_address_type; +} + +// Immediate Observationing Enabled +bool Options::immedateObservationEnabled() { + return this->m_enable_immediate_observation; +} + +// Enable/Disable Observation control via GET +bool Options::enableGETObservationControl() { + return this->m_enable_get_obs_control; +} + +// Get the Server Certificate +uint8_t *Options::getServerCertificate() { + return this->m_server_cert; +} + +// Get the Server Certificate length +int Options::getServerCertificateSize() { + return this->m_server_cert_length; +} + +// Get the Client Certificate +uint8_t *Options::getClientCertificate() { + return this->m_client_cert; +} + +// Get the Client Certificate length +int Options::getClientCertificateSize() { + return this->m_client_cert_length; +} + +// Get the Client Key +uint8_t *Options::getClientKey() { + return this->m_client_key; +} + +// Get the Client Key length +int Options::getClientKeySize() { + return this->m_client_key_length; +} + +// Get our Endpoint +void *Options::getEndpoint() { + return this->m_endpoint; +} + +} // namespace Connector
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/OptionsBuilder.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/OptionsBuilder.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,295 @@ +/** + * @file OptionsBuilder.cpp + * @brief mbed CoAP OptionsBuilder class implementation + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + +// Class support +#include "mbed-connector-interface/OptionsBuilder.h" + +// ResourceObserver support +#include "mbed-connector-interface/ThreadedResourceObserver.h" +#include "mbed-connector-interface/TickerResourceObserver.h" +#include "mbed-connector-interface/MinarResourceObserver.h" + +// Connector namespace +namespace Connector { + +// Constructor +OptionsBuilder::OptionsBuilder() +{ + this->m_endpoint = NULL; + this->m_domain = DEFAULT_DOMAIN; + this->m_endpoint_type = DEFAULT_ENDPOINT_TYPE; + this->m_node_name = NODE_NAME; + this->m_lifetime = REG_LIFETIME_SEC; + this->m_connector_url = string(CONNECTOR_URL); + this->m_server_cert = NULL; + this->m_server_cert_length = 0; + this->m_client_cert = NULL; + this->m_client_cert_length = 0; + this->m_client_key = NULL; + this->m_client_key_length = 0; + this->m_device_resources_object = NULL; + this->m_firmware_resources_object = NULL; + this->m_static_resources.clear(); + this->m_dynamic_resources.clear(); + this->m_resource_observers.clear(); +} + +// Copy Constructor +OptionsBuilder::OptionsBuilder(const OptionsBuilder &ob) : Options(ob) +{ + this->m_endpoint = ob.m_endpoint; + this->m_domain = ob.m_domain; + this->m_endpoint_type = ob.m_endpoint_type; + this->m_node_name = ob.m_node_name; + this->m_lifetime = ob.m_lifetime; + this->m_connector_url = ob.m_connector_url; + this->m_server_cert = ob.m_server_cert; + this->m_server_cert_length = ob.m_server_cert_length; + this->m_client_cert = ob.m_client_cert; + this->m_client_cert_length = ob.m_client_cert_length; + this->m_client_key = ob.m_client_key; + this->m_client_key_length= ob.m_client_key_length; + this->m_device_resources_object = ob.m_device_resources_object; + this->m_firmware_resources_object = ob.m_firmware_resources_object; + this->m_static_resources = ob.m_static_resources; + this->m_dynamic_resources = ob.m_dynamic_resources; + this->m_resource_observers = ob.m_resource_observers; + this->m_wifi_ssid = ob.m_wifi_ssid; + this->m_wifi_auth_key = ob.m_wifi_auth_key; + this->m_wifi_auth_type = ob.m_wifi_auth_type; + this->m_coap_connection_type = ob.m_coap_connection_type; + this->m_ip_address_type = ob.m_ip_address_type; + this->m_enable_immediate_observation = ob.m_enable_immediate_observation; + this->m_enable_get_obs_control = ob.m_enable_get_obs_control; + this->m_endpoint = ob.m_endpoint; +} + +// Destructor +OptionsBuilder::~OptionsBuilder() +{ + this->m_device_resources_object = NULL; + this->m_firmware_resources_object = NULL; + this->m_static_resources.clear(); + this->m_dynamic_resources.clear(); + this->m_resource_observers.clear(); +} + +// set lifetime +OptionsBuilder &OptionsBuilder::setLifetime(int lifetime) +{ + this->m_lifetime = lifetime; + return *this; +} + +// set domain +OptionsBuilder &OptionsBuilder::setDomain(const char *domain) +{ + this->m_domain = string(domain); + return *this; +} + +// set endpoint nodename +OptionsBuilder &OptionsBuilder::setEndpointNodename(const char *node_name) +{ + this->m_node_name = string(node_name); + return *this; +} + +// set lifetime +OptionsBuilder &OptionsBuilder::setEndpointType(const char *endpoint_type) +{ + this->m_endpoint_type = string(endpoint_type); + return *this; +} + +// set Connector URL +OptionsBuilder &OptionsBuilder::setConnectorURL(const char *connector_url) +{ + if (connector_url != NULL) { + this->m_connector_url = string(connector_url); + } + return *this; +} + +// add the device resources object +OptionsBuilder &OptionsBuilder::setDeviceResourcesObject(const void *device_resources_object) +{ + if (device_resources_object != NULL) { + this->m_device_resources_object = (void *)device_resources_object; + } + return *this; +} + +// add the firmware resources object +OptionsBuilder &OptionsBuilder::setFirmwareResourcesObject(const void *firmware_resources_object) +{ + if (firmware_resources_object != NULL) { + this->m_firmware_resources_object = (void *)firmware_resources_object; + } + return *this; +} + +// add static resource +OptionsBuilder &OptionsBuilder::addResource(const StaticResource *resource) +{ + if (resource != NULL) { + ((StaticResource *)resource)->setOptions(this); + this->m_static_resources.push_back((StaticResource *)resource); + } + return *this; +} + +// add dynamic resource +OptionsBuilder &OptionsBuilder::addResource(const DynamicResource *resource) +{ + // ensure that the boolean isn't mistaken by the compiler for the obs period... + return this->addResource(resource,DEFAULT_OBS_PERIOD,!(((DynamicResource *)resource)->implementsObservation())); +} + +// add dynamic resource +OptionsBuilder &OptionsBuilder::addResource(const DynamicResource *resource,const int sleep_time) +{ + // ensure that the boolean isn't mistaken by the compiler for the obs period... + return this->addResource(resource,sleep_time,!(((DynamicResource *)resource)->implementsObservation())); +} + +// add dynamic resource +OptionsBuilder &OptionsBuilder::addResource(const DynamicResource *resource,const bool use_observer) +{ + // ensure that the boolean isn't mistaken by the compiler for the obs period... + return this->addResource(resource,DEFAULT_OBS_PERIOD,use_observer); +} + +// add dynamic resource +OptionsBuilder &OptionsBuilder::addResource(const DynamicResource *resource,const int sleep_time,const bool use_observer) +{ + if (resource != NULL) { + this->m_dynamic_resources.push_back((DynamicResource *)resource); + ((DynamicResource *)resource)->setOptions(this); + ((DynamicResource *)resource)->setEndpoint((const void *)this->getEndpoint()); + if (((DynamicResource *)resource)->isObservable() == true && use_observer == true) { + // Establish the appropriate ResourceObserver +#if defined (MCI_MINAR_SCHEDULER) + // Minar-based Scheduler ResourceObserver + MinarResourceObserver *observer = new MinarResourceObserver((DynamicResource *)resource,(int)sleep_time); +#else + #ifdef CONNECTOR_USING_THREADS + // mbedOS RTOS Thread ResourceObserver + ThreadedResourceObserver *observer = new ThreadedResourceObserver((DynamicResource *)resource,(int)sleep_time); + #endif + #ifdef CONNECTOR_USING_TICKER + // mbed Ticker ResourceObserver + TickerResourceObserver *observer = new TickerResourceObserver((DynamicResource *)resource,(int)sleep_time); + #endif +#endif + // If no observer type is set in mbed-connector-interface/configuration.h (EndpointNetwork lib), then "observer" will be unresolved + this->m_resource_observers.push_back(observer); + + // immedate observation enablement option + if (this->immedateObservationEnabled()) { + observer->beginObservation(); + } + } + } + return *this; +} + +// set WiFi SSID +OptionsBuilder &OptionsBuilder::setWiFiSSID(char *ssid) +{ + this->m_wifi_ssid = string(ssid); + return *this; +} + +// set WiFi AuthType +OptionsBuilder &OptionsBuilder::setWiFiAuthType(WiFiAuthTypes auth_type) +{ + this->m_wifi_auth_type = auth_type; + return *this; +} + +// set WiFi AuthKey +OptionsBuilder &OptionsBuilder::setWiFiAuthKey(char *auth_key) +{ + this->m_wifi_auth_key = string(auth_key); + return *this; +} + +// set the CoAP Connection Type +OptionsBuilder &OptionsBuilder::setCoAPConnectionType(CoAPConnectionTypes coap_connection_type) +{ + this->m_coap_connection_type = coap_connection_type; + return *this; +} + +// set the IP Address Type +OptionsBuilder &OptionsBuilder::setIPAddressType(IPAddressTypes ip_address_type) +{ + this->m_ip_address_type = ip_address_type; + return *this; +} + +// build out our immutable self +Options *OptionsBuilder::build() +{ + return (Options *)this; +} + +// Enable/Disable immediate observationing +OptionsBuilder &OptionsBuilder::setImmedateObservationEnabled(bool enable) { + this->m_enable_immediate_observation = enable; + return *this; +} + +// Enable/Disable GET-based control of observations +OptionsBuilder &OptionsBuilder::setEnableGETObservationControl(bool enable) { + this->m_enable_get_obs_control = enable; + return *this; +} + +// set the server certificate +OptionsBuilder &OptionsBuilder::setServerCertificate(uint8_t *cert,int cert_size) { + this->m_server_cert = cert; + this->m_server_cert_length = cert_size; + return *this; +} + +// set the client certificate +OptionsBuilder &OptionsBuilder::setClientCertificate(uint8_t *cert,int cert_size) { + this->m_client_cert = cert; + this->m_client_cert_length = cert_size; + return *this; +} + +// set the client key +OptionsBuilder &OptionsBuilder::setClientKey(uint8_t *key,int key_size) { + this->m_client_key = key; + this->m_client_key_length = key_size; + return *this; +} + +// set our endpoint +void OptionsBuilder::setEndpoint(void *endpoint) { + this->m_endpoint = endpoint; +} + +} // namespace Connector
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/PassphraseAuthenticator.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/PassphraseAuthenticator.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,91 @@ +/** + * @file PassphraseAuthenticator.cpp + * @brief mbed CoAP Endpoint Device Management Passphrase-based Authenticator class + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2016 + * + * 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. + */ + +// Class support +#include "mbed-connector-interface/PassphraseAuthenticator.h" + +// demarshalling support +#include "mbed-client/m2mresource.h" + +// constructor +PassphraseAuthenticator::PassphraseAuthenticator(const Logger *logger,const void *passphrase) : Authenticator(logger,passphrase) { +} + +// copy constructor +PassphraseAuthenticator::PassphraseAuthenticator(const PassphraseAuthenticator &authenticator) : Authenticator(authenticator) { +} + +// destructor +PassphraseAuthenticator::~PassphraseAuthenticator() { +} + +// basic (trivial passphrase authentication) +bool PassphraseAuthenticator::authenticate(void *challenge) { + // use simple, trivial passphrase based comparison as the check... + char *passphrase = (char *)this->m_secret; + char *input_passphrase = NULL; + +#if defined (HAS_EXECUTE_PARAMS) + // ExecParam mbed-client: un-marshall the ExecuteParameter to get the simple string... + M2MResource::M2MExecuteParameter* param = (M2MResource::M2MExecuteParameter*)challenge; + if (param != NULL) { + // use parameters to extract the passphrase + String object_name = param->get_argument_object_name(); + // int instance_id = (int)param->get_argument_object_instance_id(); + String resource_name = param->get_argument_resource_name(); + string value = this->coapDataToString(param->get_argument_value(),param->get_argument_value_length()); + input_passphrase = (char *)value.c_str(); + } +#else + // Non-ExecParam mbed-client: use the parameter directly... + input_passphrase = (char *)challenge; +#endif + + // DEBUG + //this->m_logger->logging("Authenticator(passphrase): passphrase: [%s] challenge: [%s]",passphrase,input_passphrase); + + // parameter checks...the compare passphrases and return the result + if (passphrase != NULL && input_passphrase != NULL && strcmp(passphrase,input_passphrase) == 0) { + // DEBUG + this->m_logger->logging("Authenticator(passphrase): Passphrases MATCH. Authenticated."); + + // passphrases match + return true; + } + + // DEBUG + this->m_logger->logging("Authenticator(passphrase): Passphrases do not match"); + + // authentication failure + return false; +} + +// convenience method to get the URI from its buffer field... +string PassphraseAuthenticator::coapDataToString(uint8_t *coap_data_ptr,int coap_data_ptr_length) { + if (coap_data_ptr != NULL && coap_data_ptr_length > 0) { + char buf[MAX_VALUE_BUFFER_LENGTH+1]; + memset(buf,0,MAX_VALUE_BUFFER_LENGTH+1); + memcpy(buf,(char *)coap_data_ptr,coap_data_ptr_length); + return string(buf); + } + return string(""); +} \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/ResourceObserver.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/ResourceObserver.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,71 @@ +/** + * @file ResourceObserver.cpp + * @brief mbed CoAP DynamicResource observer (implementation) + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + + // Class support + #include "mbed-connector-interface/ResourceObserver.h" + + // constructor + ResourceObserver::ResourceObserver(DynamicResource *resource,int sleep_time) : m_is_observing(false), m_sleep_time(sleep_time) { + this->m_resource = resource; + if (resource != NULL) resource->setObserver(this); + } + + // copy constructor + ResourceObserver::ResourceObserver(const ResourceObserver &observer) { + this->m_resource = observer.m_resource; + } + + // destructor + ResourceObserver::~ResourceObserver() { + } + + // get our resource + DynamicResource *ResourceObserver::getResource() { + return this->m_resource; + } + + // we are observing? + bool ResourceObserver::isObserving() { + return this->m_is_observing; + } + + // set our observation state + void ResourceObserver::setObserving(bool observing) { + this->m_is_observing = observing; + } + + // get our sleep time + int ResourceObserver::getSleepTime() { + return this->m_sleep_time; + } + + // halt the underlying observer mechanism + void ResourceObserver::halt() { + } + + // get our logger instance + Logger *ResourceObserver::logger() { + if (this->m_resource != NULL) { + return this->m_resource->logger(); + } + return NULL; + }
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/StaticResource.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/StaticResource.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,104 @@ +/** + * @file StaticResource.h + * @brief mbed CoAP Endpoint Static Resource class + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + +// Class support +#include "mbed-connector-interface/StaticResource.h" + +// Endpoint +#include "mbed-connector-interface/ConnectorEndpoint.h" + +// Constructor +StaticResource::StaticResource(const Logger *logger,const char *obj_name,const char *res_name, const char *value) : Resource<string>(logger,string(obj_name),string(res_name),string(value)), m_data_wrapper() +{ + this->m_data_wrapper = NULL; + this->m_res = NULL; +} + +// Constructor +StaticResource::StaticResource(const Logger *logger,const char *obj_name,const char *res_name,const string value) : Resource<string>(logger,string(obj_name),string(res_name),string(value)) +{ + this->m_data_wrapper = NULL; + this->m_res = NULL; +} + +// Constructor with buffer lengths +StaticResource::StaticResource(const Logger *logger,const string obj_name,const string res_name,const string value) : Resource<string>(logger,string(obj_name),string(res_name),string(value)) +{ + this->m_data_wrapper = NULL; + this->m_res = NULL; +} + +// Copy constructor +StaticResource::StaticResource(const StaticResource &resource) : Resource<string>((const Resource<string> &)resource) +{ + this->m_data_wrapper = resource.m_data_wrapper; + this->m_res = resource.m_res; +} + +// Destructor +StaticResource::~StaticResource() { +} + +// bind CoAP Resource.. +void StaticResource::bind(void *ep) { + // Static Resources nailed to STRING type... + int type = (int)M2MResourceInstance::STRING; + + // check our Endpoint instance... + if (ep != NULL) { + // cast + Connector::Endpoint *endpoint = (Connector::Endpoint *)ep; + + // get our ObjectInstanceManager + ObjectInstanceManager *oim = endpoint->getObjectInstanceManager(); + + if (this->getDataWrapper() != NULL) { + // wrap the data... + this->getDataWrapper()->wrap((uint8_t *)this->getValue().c_str(),(int)this->getValue().size()); + + // Create our Resource + this->m_res = (M2MResource *)oim->createStaticResourceInstance((char *)this->getObjName().c_str(),(char *)this->getResName().c_str(),(char *)"StaticResource",(int)type,(void *)this->getDataWrapper()->get(),(int)this->getDataWrapper()->length()); + if (this->m_res != NULL) { + // Record our Instance Number + this->setInstanceNumber(oim->getLastCreatedInstanceNumber()); + + // DEBUG + this->logger()->logging("StaticResource: [%s] value: [%s] bound",this->getFullName().c_str(),this->getDataWrapper()->get()); + } + } + else { + // Create our Resource + this->m_res = (M2MResource *)oim->createStaticResourceInstance((char *)this->getObjName().c_str(),(char *)this->getResName().c_str(),(char *)"StaticResource",(int)type,(void *)this->getValue().c_str(),(int)this->getValue().size()); + if (this->m_res != NULL) { + // Record our Instance Number + this->setInstanceNumber(oim->getLastCreatedInstanceNumber()); + + // DEBUG + this->logger()->logging("StaticResource: [%s] value: [%s] bound",this->getFullName().c_str(),this->getValue().c_str()); + } + } + } + else { + // no instance pointer to our endpoint + this->logger()->logging("%s: NULL endpoint instance pointer in bind() request...",this->getFullName().c_str()); + } +} \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/ThreadedResourceObserver.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/ThreadedResourceObserver.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,79 @@ +/** + * @file ThreadedResourceObserver.cpp + * @brief mbed CoAP DynamicResource Thread-based observer (implementation) + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + + // Class support + #include "mbed-connector-interface/ThreadedResourceObserver.h" + + #ifdef CONNECTOR_USING_THREADS + + // constructor + ThreadedResourceObserver::ThreadedResourceObserver(DynamicResource *resource,int sleep_time) : ResourceObserver(resource,sleep_time), m_observation_thread() { + // default is not observing... + this->setObserving(false); + + // DEBUG + if (sleep_time > 0) { + this->logger()->logging("ThreadedResourceObserver being used for %s (sleep_time: %d ms)",resource->getFullName().c_str(),sleep_time); + } + else { + this->logger()->logging("ThreadedResourceObserver being used for %s",resource->getFullName().c_str()); + } + + // start the thread by invoking the thread task... + this->m_observation_thread.start(this,&ThreadedResourceObserver::observation_task); + } + + // destructor + ThreadedResourceObserver::~ThreadedResourceObserver() { + this->stopObservation(); + this->m_observation_thread.terminate(); + } + + // thread task method + void ThreadedResourceObserver::observation_task() { + while(true) { + Thread::wait(this->getSleepTime()); + if (this->isObserving() == true && this->getResource() != NULL) { + DynamicResource *res = this->getResource(); + if (res != NULL && res->isRegistered() == true) { + res->observe(); + } + } + } + } + + // begin observing... + void ThreadedResourceObserver::beginObservation() { + this->setObserving(true); + } + + // stop observing... + void ThreadedResourceObserver::stopObservation() { + this->setObserving(false); + } + + // halt the underlying observer mechanism + void ThreadedResourceObserver::halt() { + m_observation_thread.terminate(); + } + + #endif // CONNECTOR_USING_THREADS \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/TickerResourceObserver.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/TickerResourceObserver.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,72 @@ +/** + * @file TickerResourceObserver.cpp + * @brief mbed CoAP DynamicResource Ticker-based observer (implementation) + * @author Doug Anson/Chris Paola + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + + // Class support + #include "mbed-connector-interface/TickerResourceObserver.h" + + #ifdef CONNECTOR_USING_TICKER + + // constructor + TickerResourceObserver::TickerResourceObserver(DynamicResource *resource,int sleep_time) : + ResourceObserver(resource,(int)(sleep_time/1000)) { + this->setObserving(false); + + // DEBUG + if (sleep_time > 0) { + this->logger()->log("TickerResourceObserver being used for %s (sleep_time: %d ms)",resource->getFullName().c_str(),sleep_time); + } + else { + this->logger()->log("TickerResourceObserver being used for %s",resource->getFullName().c_str()); + } + } + + // destructor + TickerResourceObserver::~TickerResourceObserver() { + this->stopObservation(); + } + + // notifier + void TickerResourceObserver::observationNotifier() { + if (this->isObserving() == true && this->getResource() != NULL && this->getResource()->isRegistered() == true) { + this->getResource()->observe(); + } + } + + // begin observing... + void TickerResourceObserver::beginObservation() { + if (this->isObserving() == false) { + this->m_ticker.attach(this,&TickerResourceObserver::observationNotifier,(float)this->getSleepTime()); + this->setObserving(true); + } + } + + // begin observing... + void TickerResourceObserver::stopObservation() { + this->setObserving(false); + } + + // halt the underlying observer mechanism + void TickerResourceObserver::halt() { + this->m_ticker.detach(); + } + + #endif // CONNECTOR_USING_TICKER \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/Utils.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/Utils.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,175 @@ +/** + * @file Utils.cpp + * @brief mbed CoAP Endpoint misc utils collection + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + +// mbed Endpoint includes +#include "mbed-connector-interface/ConnectorEndpoint.h" +#include "mbed-connector-interface/OptionsBuilder.h" +#include "mbed-connector-interface/mbedEndpointNetwork.h" +#include "mbed-connector-interface/DeviceManager.h" +#include "mbed-connector-interface/ObjectInstanceManager.h" + +// External references (defined in main.cpp) +Connector::Options *configure_endpoint(Connector::OptionsBuilder &builder); +extern Logger logger; + +// Our Endpoint +Connector::Endpoint *__endpoint = NULL; + +// Our Endpoint configured Options +Connector::OptionsBuilder config; +Connector::Options *options = NULL; + +// initialize the Connector::Endpoint instance +void *utils_init_endpoint(bool canActAsRouterNode) { + // alloc Endpoint + logger.logging("Endpoint: allocating endpoint instance..."); + Connector::Endpoint *ep = new Connector::Endpoint(&logger,options); + if (ep != NULL) { + // link to config object + config.setEndpoint((void *)ep); + + // not sure if we need this anymore... + ep->asRouterNode(canActAsRouterNode); + + // Add ObjectInstanceManager + ObjectInstanceManager *oim = new ObjectInstanceManager(&logger,(void *)ep); + ep->setObjectInstanceManager(oim); + } + return (void *)ep; +} + +// further simplifies the endpoint main() configuration by removing the final initialization details of the endpoint... +void utils_configure_endpoint(void *p) +{ + // our Endpoint + Connector::Endpoint *ep = (Connector::Endpoint *)p; + + // default configuration - see mbedConnectorInterface.h for definitions... + logger.logging("Endpoint: setting defaults..."); + config.setEndpointNodename(NODE_NAME); + config.setEndpointType(DEFAULT_ENDPOINT_TYPE); + config.setLifetime(REG_LIFETIME_SEC); + + // WiFi defaults + config.setWiFiSSID((char *)WIFI_DEFAULT_SSID); // default: changeme + config.setWiFiAuthType(WIFI_NONE); // default: none + config.setWiFiAuthKey((char *)WIFI_DEFAULT_AUTH_KEY); // default: changeme + + // Default CoAP Connection Type + config.setCoAPConnectionType(COAP_UDP); // default CoAP Connection Type + + // Set the default IP Address Type +#if MBED_CONF_APP_NETWORK_INTERFACE == MESH_LOWPAN_ND || MBED_CONF_APP_NETWORK_INTERFACE == MESH_THREAD + config.setIPAddressType(IP_ADDRESS_TYPE_IPV6); // IPv6 is the default for mesh +#else + config.setIPAddressType(IP_ADDRESS_TYPE_IPV4); // IPv4 is the default for all but mesh +#endif + + // Establish default CoAP observation behavior + config.setImmedateObservationEnabled(true); + + // Establish default CoAP GET-based observation control behavior + config.setEnableGETObservationControl(false); + + // Device Manager installation + DeviceManager *device_manager = (DeviceManager *)ep->getDeviceManager(); + if (device_manager != NULL) { + logger.logging("Endpoint: installing and setting up device manager and its resources..."); + device_manager->install((void *)ep,(void *)&config); + } + else { + logger.logging("Endpoint: no device manager installed..."); + } + + // main.cpp can override or change any of the above defaults... + logger.logging("Endpoint: gathering configuration overrides..."); + options = configure_endpoint(config); + + // set our options + ep->setOptions(options); + + // DONE + logger.logging("Endpoint: endpoint configuration completed."); +} + +// build out the endpoint and its resources +void utils_build_endpoint(void *p) +{ + if (p != NULL) { + // Build the Endpoint + logger.logging("Endpoint: building endpoint and its resources..."); + Connector::Endpoint *ep = (Connector::Endpoint *)p; + ep->buildEndpoint(); + } +} + +// parse out the CoAP port number from the connection URL +uint16_t extract_port_from_url(char *url,uint16_t default_port) +{ + uint16_t port = default_port; + + if (url != NULL && strlen(url) > 0) { + char buffer[MAX_CONN_URL_LENGTH+1]; + char uri[MAX_CONN_URL_LENGTH+1]; + char path[MAX_CONN_URL_LENGTH+1]; + + // initialize the buffer + memset(buffer,0,MAX_CONN_URL_LENGTH+1); + memset(uri,0,MAX_CONN_URL_LENGTH+1); + memset(path,0,MAX_CONN_URL_LENGTH+1); + int length = strlen(url); + + // truncate if needed + if (length >MAX_CONN_URL_LENGTH) length = MAX_CONN_URL_LENGTH; + + // make a copy... + memcpy(buffer,url,length); + + // remove the forward slashes and colons + for(int i=0;i<length;++i) { + if (buffer[i] == ':') buffer[i] = ' '; + if (buffer[i] == '/') buffer[i] = ' '; + if (buffer[i] == '[') buffer[i] = ' '; + if (buffer[i] == ']') buffer[i] = ' '; + } + + // parse + sscanf(buffer,"%s%s%d",uri,path,(int *)&port); + + // IPv6 kludge until we parse it properly... + if (strcmp(uri,"coaps") == 0 && strcmp(path,"2607") == 0) { + // IPv6 in use - so nail to Connector's IPv6 address + strcpy(uri,"coap"); + strcpy(path,"2607:f0d0:2601:52::20"); + port = default_port; + + // DEBUG + logger.logging("Endpoint: Connector IPV6 uri: %s path: %s port: %d",uri,path,port); + } + } + + // DEBUG + logger.logging("Endpoint: Connector URL: %s CoAP port: %u",url,port); + + // return the port + return port; +} \ No newline at end of file
diff -r 000000000000 -r ad834d403a8c mbedConnectorInterface/source/mbedEndpointNetwork.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedConnectorInterface/source/mbedEndpointNetwork.cpp Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,252 @@ +/** + * @file mbedEndpointNetwork.cpp + * @brief mbed Connector Interface network low level functions and support (Ethernet, WiFi, Mesh (6LowPAN,Thread)) + * @author Doug Anson + * @version 1.0 + * @see + * + * Copyright (c) 2014 + * + * 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. + */ + +// Connector Endpoint +#include "mbed-connector-interface/ConnectorEndpoint.h" + +// OptionsBuilder +#include "mbed-connector-interface/OptionsBuilder.h" + +// Forward declarations of public functions in mbedEndpointNetwork +#include "mbed-connector-interface/mbedEndpointNetworkImpl.h" + +// Network Selection +#if MBED_CONF_APP_NETWORK_INTERFACE == WIFI + #define NETWORK_TYPE (char *)"WiFi" +#if 1 //bp3595 + #include "LWIPBP3595Interface.h" + LWIPBP3595Interface network; + DigitalOut usb1en(P3_8); +#else //#if 1 + #include "ESP8266Interface.h" + ESP8266Interface network(MBED_CONF_APP_WIFI_TX,MBED_CONF_APP_WIFI_RX); +#endif +#elif MBED_CONF_APP_NETWORK_INTERFACE == ETHERNET + #define NETWORK_TYPE (char *)"Ethernet" + #include "EthernetInterface.h" + EthernetInterface network; +#elif MBED_CONF_APP_NETWORK_INTERFACE == MESH_LOWPAN_ND + #define NETWORK_TYPE (char *)"6LowPAN" + #include "NanostackInterface.h" + LoWPANNDInterface network; +#elif MBED_CONF_APP_NETWORK_INTERFACE == MESH_THREAD + #define NETWORK_TYPE (char *)"Thread" + #include "NanostackInterface.h" + ThreadInterface network; +#endif + +// Logger instance +extern Logger logger; + +// endpoint instance +static void *_endpoint_instance = NULL; + +// LWIP network instance forward reference +extern NetworkInterface *__network_interface; + +// main loop cycle period +static int _main_loop_iteration_wait_ms = MAIN_LOOP_WAIT_TIME_MS; + +// endpoint shutdown indicator +static volatile bool _shutdown_endpoint = false; + +extern "C" { + +/*********************** START LOCAL FUNCTIONS **************************/ + +// start shutting downt the endpoint +void start_endpoint_shutdown(void) { + if (_shutdown_endpoint == true) { + Connector::Endpoint *ep = (Connector::Endpoint *)_endpoint_instance; + if (ep != NULL && ep->isRegistered() == true) { + logger.logging("mbedEndpointNetwork(%s): shutdown requested. De-registering the endpoint...",NETWORK_TYPE); + ep->de_register_endpoint(); + } + + // Clean up + if (ep != NULL) { + delete ep; + _endpoint_instance = NULL; + } + } + + // ready to shutdown... + logger.logging("mbedEndpointNetwork(%s): endpoint shutdown. Bye!",NETWORK_TYPE); +} + +// setup shutdown button +#if MBED_CONF_APP_SHUTDOWN_BUTTON_ENABLE == true +InterruptIn shutdown_button(MBED_CONF_APP_SHUTDOWN_PIN); +void configure_deregistration_button(void) { + logger.logging("mbedEndpointNetwork(%s): configuring de-registration button...",NETWORK_TYPE); + shutdown_button.fall(&net_shutdown_endpoint); +} +#endif + +// setup shutdown button +void setup_deregistration_button(void) { +#if MBED_CONF_APP_SHUTDOWN_BUTTON_ENABLE == true + configure_deregistration_button(); +#endif +} + +// configure main loop parameters +void configure_main_loop_params(Connector::Endpoint *endpoint) { + // set the initial shutdown state + _shutdown_endpoint = false; +} + +// perform an actvity in the main loop +void peform_main_loop_activity(void) { + // empty for now... + ; +} + +// begin the main loop for processing endpoint events +void begin_main_loop(void) +{ + // DEBUG + logger.logging("mbedEndpointNetwork(%s): endpoint main loop beginning...",NETWORK_TYPE); + + // enter our main loop (until the shutdown condition flags it...) + while(_shutdown_endpoint == false) { + Thread::wait(_main_loop_iteration_wait_ms); + peform_main_loop_activity(); + } + + // main loop has exited... start the endpoint shutdown... + logger.logging("mbedEndpointNetwork(%s): endpoint main loop exited. Starting endpoint shutdown...",NETWORK_TYPE); + start_endpoint_shutdown(); +} + +/************************ END LOCAL FUNCTIONS ***************************/ + +/*********************** START PUBLIC FUNCTIONS *************************/ + +// get the network type +char *net_get_type() { + return NETWORK_TYPE; +} + +// shutdown the endpoint +void net_shutdown_endpoint() { + _shutdown_endpoint = true; +} + +// called after the endpoint is configured... +void net_plumb_network(void *p) +{ + int connected = 0; + Connector::Endpoint *ep = NULL; + Connector::Options *options = NULL; + + // save + _endpoint_instance = p; + + // connected + if (p != NULL) { + ep = (Connector::Endpoint *)p; + options = ep->getOptions(); + } + +#if MBED_CONF_APP_NETWORK_INTERFACE == WIFI +#if 1 //BP3595 + usb1en = 1; + Thread::wait(5); + usb1en = 0; + Thread::wait(5); + connected = network.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, MBED_CONF_APP_WIFI_SECURITY); +#else //#if 1 + // map security types + nsapi_security_t security_opt = NSAPI_SECURITY_NONE; + if (options->getWiFiAuthType() == WIFI_WPA_PERSONAL) { + security_opt = NSAPI_SECURITY_WPA; + } + if (options->getWiFiAuthType() == WIFI_WPA2_PERSONAL) { + security_opt = NSAPI_SECURITY_WPA2; + } + if (options->getWiFiAuthType() == WIFI_WEP) { + security_opt = NSAPI_SECURITY_WEP; + } + + // Network Init (WIFI)... + connected = network.connect(options->getWiFiSSID().c_str(),options->getWiFiAuthKey().c_str(),security_opt); +#endif +#elif MBED_CONF_APP_NETWORK_INTERFACE == MESH_LOWPAN_ND || MBED_CONF_APP_NETWORK_INTERFACE == MESH_THREAD + // Set the IP Address type to IPV6 + ((Connector::OptionsBuilder *)options)->setIPAddressType(IP_ADDRESS_TYPE_IPV6); + + // Network Init (Mesh) + connected = network.connect(); +#else + // not used... just removes a compiler warning... + options->getConnectorURL(); + + // Network Init (Ethernet) + connected = network.connect(); +#endif + + // check the connection status.. + if (connected == 0) { + // success + __network_interface = (NetworkInterface *)&network; + if (ep != NULL) { + ep->isConnected(true); + + // Debug + logger.logging("mbedEndpointNetwork(%s): IP Address: %s",NETWORK_TYPE,network.get_ip_address()); + } + } + else { + __network_interface = NULL; + if (ep != NULL) { + ep->isConnected(false); + } + + // Debug + logger.logging("mbedEndpointNetwork(%s): CONNECTION FAILED",NETWORK_TYPE); + } +} + +// finalize and run the endpoint main loop +void net_finalize_and_run_endpoint_main_loop(void *p) +{ + // cast + Connector::Endpoint *ep = (Connector::Endpoint *)p; + + // Initialize our main loop... + configure_main_loop_params(ep); + + // setup the shutdown button (if enabled for a given platform...) + setup_deregistration_button(); + + // register the endpoint + logger.logging("mbedEndpointNetwork(%s): registering endpoint...",NETWORK_TYPE); + ep->register_endpoint(ep->getEndpointSecurity(),ep->getEndpointObjectList()); + + // Begin the endpoint's main loop + begin_main_loop(); +} + +/************************ END PUBLIC FUNCTIONS **************************/ + +}
diff -r 000000000000 -r ad834d403a8c mbed_app.json --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed_app.json Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,47 @@ +{ + "config": { + "network-interface":{ + "help": "options are ETHERNET,WIFI,MESH_LOWPAN_ND,MESH_THREAD", + "value": "ETHERNET" + }, + "wifi-ssid": { + "help": "WiFi SSID", + "value": "\"SSID\"" + }, + "wifi-password": { + "help": "WiFi Password", + "value": "\"Password\"" + }, + "wifi-security": { + "help": "Type of encryption for connection", + "value": "NSAPI_SECURITY_WPA2" + }, + "wifi-tx": { + "help": "TX pin for serial connection to external device", + "value": "D1" + }, + "wifi-rx": { + "help": "RX pin for serial connection to external device", + "value": "D0" + }, + "shutdown-button-enable": { + "help": "enable the K64F use of SWx for the deregistation/shutdown button", + "value": "true" + }, + "shutdown-pin": { + "help": "which shutdown button should be used as the deregistation/shutdown button", + "value": "USER_BUTTON0" + } + }, + "macros": ["MBEDTLS_USER_CONFIG_FILE=\"mbedtls_mbed_client_config.h\""], + "target_overrides": { + "*": { + "target.features_add": ["CLIENT", "COMMON_PAL"], + "mbed-client.reconnection-count": 3, + "mbed-client.reconnection-interval": 5 + }, + "RZ_A1H": { + "target.macros_add": ["MBEDTLS_TEST_NULL_ENTROPY", "MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES"] + } + } +}
diff -r 000000000000 -r ad834d403a8c mbed_settings.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed_settings.py Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,45 @@ +""" +mbed SDK +Copyright (c) 2016 ARM Limited + +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. +""" + +from os.path import join, abspath, dirname + +#ROOT = abspath(join(dirname(__file__), ".")) + +############################################################################## +# Build System Settings +############################################################################## +#BUILD_DIR = abspath(join(ROOT, "build")) + +# ARM +#ARM_PATH = "C:/Program Files/ARM" + +# GCC ARM +#GCC_ARM_PATH = "" + +# GCC CodeRed +#GCC_CR_PATH = "" + +# IAR +#IAR_PATH = "" + +# Goanna static analyser. Please overload it in private_settings.py +#GOANNA_PATH = "" + +#BUILD_OPTIONS = [] + +# mbed.org username +#MBED_ORG_USER = ""
diff -r 000000000000 -r ad834d403a8c mbedtls_mbed_client_config.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedtls_mbed_client_config.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,115 @@ +/* + * Minimal configuration for using mbedtls as part of mbed-client + * + * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * 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. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + + +#ifndef MBEDTLS_CUSTOM_CONFIG_H +#define MBEDTLS_CUSTOM_CONFIG_H + +/* System support */ +#define MBEDTLS_HAVE_ASM + +/* mbed TLS feature support */ +#define MBEDTLS_ECP_DP_SECP256R1_ENABLED +#define MBEDTLS_ECP_NIST_OPTIM +#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH +#define MBEDTLS_SSL_PROTO_TLS1_2 +#define MBEDTLS_SSL_PROTO_DTLS +#define MBEDTLS_SSL_DTLS_ANTI_REPLAY +#define MBEDTLS_SSL_DTLS_HELLO_VERIFY +#define MBEDTLS_SSL_EXPORT_KEYS + +/* mbed TLS modules */ +#define MBEDTLS_AES_C +#define MBEDTLS_ASN1_PARSE_C +#define MBEDTLS_ASN1_WRITE_C +#define MBEDTLS_BIGNUM_C +#define MBEDTLS_CCM_C +#define MBEDTLS_CIPHER_C +#define MBEDTLS_CTR_DRBG_C +#define MBEDTLS_ECP_C +#define MBEDTLS_ENTROPY_C +#define MBEDTLS_MD_C +#define MBEDTLS_OID_C +#define MBEDTLS_PK_C +#define MBEDTLS_PK_PARSE_C +#define MBEDTLS_SHA256_C +#define MBEDTLS_SSL_COOKIE_C +#define MBEDTLS_SSL_CLI_C +#define MBEDTLS_SSL_SRV_C +#define MBEDTLS_SSL_TLS_C + +// XXX mbedclient needs these: mbedtls_x509_crt_free, mbedtls_x509_crt_init, mbedtls_x509_crt_parse +#define MBEDTLS_X509_USE_C +#define MBEDTLS_X509_CRT_PARSE_C +// a bit wrong way to get mbedtls_ssl_conf_psk: +// XXX: this should be ifdef'd out from client too +#define MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED + +// XXX: clean these up!! +#define MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED +#define MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED +#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED +#define MBEDTLS_SHA512_C +#define MBEDTLS_ECDH_C +#define MBEDTLS_GCM_C +#define MBEDTLS_CCM_C + +#define MBEDTLS_PKCS1_V15 + +#define MBEDTLS_CIPHER_MODE_CBC +#define MBEDTLS_ECDH_C +#define MBEDTLS_ECDSA_C +#define MBEDTLS_X509_CRT_PARSE_C + +// Remove RSA, save 20KB at total +#undef MBEDTLS_RSA_C +#undef MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED + +// Remove error messages, save 10KB of ROM +#undef MBEDTLS_ERROR_C + +// Remove selftesting and save 11KB of ROM +#undef MBEDTLS_SELF_TEST + +#undef MBEDTLS_SSL_COOKIE_C + +// Reduces ROM size by 30 kB +#undef MBEDTLS_ERROR_STRERROR_DUMMY +#undef MBEDTLS_VERSION_FEATURES +#undef MBEDTLS_DEBUG_C + +// needed for parsing the certificates +#define MBEDTLS_PEM_PARSE_C +// dep of the previous +#define MBEDTLS_BASE64_C + +// reduce IO buffer to save RAM, default is 16KB +#define MBEDTLS_SSL_MAX_CONTENT_LEN 2048 + +// define to save 8KB RAM at the expense of ROM +#undef MBEDTLS_AES_ROM_TABLES + +// Save ROM and a few bytes of RAM by specifying our own ciphersuite list +#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + +#include "mbedtls/check_config.h" + +#endif /* MBEDTLS_CUSTOM_CONFIG_H */
diff -r 000000000000 -r ad834d403a8c security.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/security.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2015 ARM Limited. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * 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 __SECURITY_H__ +#define __SECURITY_H__ + +#include <inttypes.h> + +#define MBED_DOMAIN "DOMAIN" +#define MBED_ENDPOINT_NAME "ENDPOINT_NAME" + +const uint8_t SERVER_CERT[] = "-----BEGIN CERTIFICATE-----\r\n" +"-----END CERTIFICATE-----\r\n"; + +const uint8_t CERT[] = "-----BEGIN CERTIFICATE-----\r\n" +"-----END CERTIFICATE-----\r\n"; + +const uint8_t KEY[] = "-----BEGIN PRIVATE KEY-----\r\n" +"-----END PRIVATE KEY-----\r\n"; + +#endif //__SECURITY_H__ + +#error "You need to get security.h credentials from connector.mbed.com and replace the content of this security.h file"
diff -r 000000000000 -r ad834d403a8c zxing_lib/ImageReaderSource.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/ImageReaderSource.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,77 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __IMAGE_READER_SOURCE_H_ +#define __IMAGE_READER_SOURCE_H_ +/* + * Copyright 2010-2011 ZXing authors + * + * 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 "mbed.h" +#include <iostream> +#include <fstream> +#include <string> +#include <zxing/LuminanceSource.h> +#include <zxing/common/Counted.h> +#include <zxing/Binarizer.h> +#include <zxing/MultiFormatReader.h> +#include <zxing/Result.h> +#include <zxing/ReaderException.h> +#include <zxing/common/GlobalHistogramBinarizer.h> +#include <zxing/common/HybridBinarizer.h> +#include <exception> +#include <zxing/Exception.h> +#include <zxing/common/IllegalArgumentException.h> +#include <zxing/BinaryBitmap.h> +#include <zxing/DecodeHints.h> + +#include <zxing/qrcode/QRCodeReader.h> +#include <zxing/multi/qrcode/QRCodeMultiReader.h> +#include <zxing/multi/ByQuadrantReader.h> +#include <zxing/multi/MultipleBarcodeReader.h> +#include <zxing/multi/GenericMultipleBarcodeReader.h> + +using std::string; +using std::ostringstream; +using zxing::Ref; +using zxing::ArrayRef; +using zxing::LuminanceSource; + +using namespace std; +using namespace zxing; +using namespace zxing::multi; +using namespace zxing::qrcode; + + +class ImageReaderSource : public zxing::LuminanceSource { +private: + typedef LuminanceSource Super; + + const zxing::ArrayRef<char> image; + const int comps; + + char convertPixel(const char* pixel) const; + +public: + static zxing::Ref<LuminanceSource> create(char* buf, int buf_size, int width, int height); + + ImageReaderSource(zxing::ArrayRef<char> image, int width, int height, int comps); + + zxing::ArrayRef<char> getRow(int y, zxing::ArrayRef<char> row) const; + zxing::ArrayRef<char> getMatrix() const; +}; + +extern int ex_decode(uint8_t* buf, int buf_size, int width, int height, vector<Ref<Result> > * results); + + +#endif /* __IMAGE_READER_SOURCE_H_ */
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/BarcodeFormat.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/BarcodeFormat.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,60 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __BARCODE_FORMAT_H__ +#define __BARCODE_FORMAT_H__ + +/* + * BarcodeFormat.h + * zxing + * + * Copyright 2010 ZXing authors 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. + */ + +namespace zxing { + +class BarcodeFormat { +public: + // if you update the enum, update BarcodeFormat.cpp + + enum Value { + NONE, + AZTEC, + CODABAR, + CODE_39, + CODE_93, + CODE_128, + DATA_MATRIX, + EAN_8, + EAN_13, + ITF, + MAXICODE, + PDF_417, + QR_CODE, + RSS_14, + RSS_EXPANDED, + UPC_A, + UPC_E, + UPC_EAN_EXTENSION + }; + + BarcodeFormat(Value v) : value(v) {} + const Value value; + operator Value () const {return value;} + + static char const* barcodeFormatNames[]; +}; + +} + +#endif // __BARCODE_FORMAT_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/Binarizer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/Binarizer.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,50 @@ +#ifndef BINARIZER_H_ +#define BINARIZER_H_ + +/* + * Binarizer.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/LuminanceSource.h> +#include <zxing/common/BitArray.h> +#include <zxing/common/BitMatrix.h> +#include <zxing/common/Counted.h> + +namespace zxing { + +class Binarizer : public Counted { + private: + Ref<LuminanceSource> source_; + + public: + Binarizer(Ref<LuminanceSource> source); + virtual ~Binarizer(); + + virtual Ref<BitArray> getBlackRow(int y, Ref<BitArray> row) = 0; + virtual Ref<BitMatrix> getBlackMatrix() = 0; + + Ref<LuminanceSource> getLuminanceSource() const ; + virtual Ref<Binarizer> createBinarizer(Ref<LuminanceSource> source) = 0; + + int getWidth() const; + int getHeight() const; + +}; + +} +#endif /* BINARIZER_H_ */
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/BinaryBitmap.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/BinaryBitmap.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,56 @@ +#ifndef __BINARYBITMAP_H__ +#define __BINARYBITMAP_H__ + +/* + * BinaryBitmap.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/common/Counted.h> +#include <zxing/common/BitMatrix.h> +#include <zxing/common/BitArray.h> +#include <zxing/Binarizer.h> + +namespace zxing { + + class BinaryBitmap : public Counted { + private: + Ref<Binarizer> binarizer_; + + public: + BinaryBitmap(Ref<Binarizer> binarizer); + virtual ~BinaryBitmap(); + + Ref<BitArray> getBlackRow(int y, Ref<BitArray> row); + Ref<BitMatrix> getBlackMatrix(); + + Ref<LuminanceSource> getLuminanceSource() const; + + int getWidth() const; + int getHeight() const; + + bool isRotateSupported() const; + Ref<BinaryBitmap> rotateCounterClockwise(); + + bool isCropSupported() const; + Ref<BinaryBitmap> crop(int left, int top, int width, int height); + + }; + +} + +#endif /* BINARYBITMAP_H_ */
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/DecodeHints.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/DecodeHints.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,89 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __DECODEHINTS_H_ +#define __DECODEHINTS_H_ +/* + * DecodeHintType.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/BarcodeFormat.h> +#include <zxing/ResultPointCallback.h> + +namespace zxing { + +typedef unsigned int DecodeHintType; +class DecodeHints; +DecodeHints operator | (DecodeHints const&, DecodeHints const&); + +class DecodeHints { + private: + DecodeHintType hints; + Ref<ResultPointCallback> callback; + + public: + static const DecodeHintType AZTEC_HINT = 1 << BarcodeFormat::AZTEC; + static const DecodeHintType CODABAR_HINT = 1 << BarcodeFormat::CODABAR; + static const DecodeHintType CODE_39_HINT = 1 << BarcodeFormat::CODE_39; + static const DecodeHintType CODE_93_HINT = 1 << BarcodeFormat::CODE_93; + static const DecodeHintType CODE_128_HINT = 1 << BarcodeFormat::CODE_128; + static const DecodeHintType DATA_MATRIX_HINT = 1 << BarcodeFormat::DATA_MATRIX; + static const DecodeHintType EAN_8_HINT = 1 << BarcodeFormat::EAN_8; + static const DecodeHintType EAN_13_HINT = 1 << BarcodeFormat::EAN_13; + static const DecodeHintType ITF_HINT = 1 << BarcodeFormat::ITF; + static const DecodeHintType MAXICODE_HINT = 1 << BarcodeFormat::MAXICODE; + static const DecodeHintType PDF_417_HINT = 1 << BarcodeFormat::PDF_417; + static const DecodeHintType QR_CODE_HINT = 1 << BarcodeFormat::QR_CODE; + static const DecodeHintType RSS_14_HINT = 1 << BarcodeFormat::RSS_14; + static const DecodeHintType RSS_EXPANDED_HINT = 1 << BarcodeFormat::RSS_EXPANDED; + static const DecodeHintType UPC_A_HINT = 1 << BarcodeFormat::UPC_A; + static const DecodeHintType UPC_E_HINT = 1 << BarcodeFormat::UPC_E; + static const DecodeHintType UPC_EAN_EXTENSION_HINT = 1 << BarcodeFormat::UPC_EAN_EXTENSION; + +#if defined(__ICCARM__) // + static const DecodeHintType TRYHARDER_HINT = 0x80000000; +#else + static const DecodeHintType TRYHARDER_HINT = 1 << 31; +#endif // + static const DecodeHintType CHARACTER_SET = 1 << 30; + // static const DecodeHintType ALLOWED_LENGTHS = 1 << 29; + // static const DecodeHintType ASSUME_CODE_39_CHECK_DIGIT = 1 << 28; + static const DecodeHintType ASSUME_GS1 = 1 << 27; + // static const DecodeHintType NEED_RESULT_POINT_CALLBACK = 1 << 26; + + static const DecodeHints PRODUCT_HINT; + static const DecodeHints ONED_HINT; + static const DecodeHints DEFAULT_HINT; + + DecodeHints(); + DecodeHints(DecodeHintType init); + + void addFormat(BarcodeFormat toadd); + bool containsFormat(BarcodeFormat tocheck) const; + bool isEmpty() const {return (hints==0);} + void clear() {hints=0;} + void setTryHarder(bool toset); + bool getTryHarder() const; + + void setResultPointCallback(Ref<ResultPointCallback> const&); + Ref<ResultPointCallback> getResultPointCallback() const; + + friend DecodeHints operator | (DecodeHints const&, DecodeHints const&); +}; + +} + +#endif
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/Exception.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/Exception.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,51 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __EXCEPTION_H__ +#define __EXCEPTION_H__ + +/* + * Exception.h + * ZXing + * + * Copyright 2010 ZXing authors 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 <string> +#include <exception> + +namespace zxing { + +class Exception : public std::exception { +private: + char const* const message; + +public: + Exception() throw() : message(0) {} + Exception(const char* msg) throw() : message(copy(msg)) {} + Exception(Exception const& that) throw() : std::exception(that), message(copy(that.message)) {} + ~Exception() throw() { + if(message) { + deleteMessage(); + } + } + char const* what() const throw() {return message ? message : "";} + +private: + static char const* copy(char const*); + void deleteMessage(); +}; + +} + +#endif // __EXCEPTION_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/LuminanceSource.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/LuminanceSource.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,59 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __LUMINANCESOURCE_H__ +#define __LUMINANCESOURCE_H__ +/* + * LuminanceSource.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/common/Counted.h> +#include <zxing/common/Array.h> +#include <string.h> + +namespace zxing { + +class LuminanceSource : public Counted { + private: + const int width; + const int height; + + public: + LuminanceSource(int width, int height); + virtual ~LuminanceSource(); + + int getWidth() const { return width; } + int getHeight() const { return height; } + + // Callers take ownership of the returned memory and must call delete [] on it themselves. + virtual ArrayRef<char> getRow(int y, ArrayRef<char> row) const = 0; + virtual ArrayRef<char> getMatrix() const = 0; + + virtual bool isCropSupported() const; + virtual Ref<LuminanceSource> crop(int left, int top, int width, int height) const; + + virtual bool isRotateSupported() const; + + virtual Ref<LuminanceSource> invert() const; + + virtual Ref<LuminanceSource> rotateCounterClockwise() const; + + operator std::string () const; +}; + +} + +#endif /* LUMINANCESOURCE_H_ */
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/MultiFormatReader.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/MultiFormatReader.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,48 @@ +#ifndef __MULTI_FORMAT_READER_H__ +#define __MULTI_FORMAT_READER_H__ + +/* + * MultiFormatBarcodeReader.h + * ZXing + * + * Copyright 2010 ZXing authors 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 <zxing/Reader.h> +#include <zxing/common/BitArray.h> +#include <zxing/Result.h> +#include <zxing/DecodeHints.h> + +namespace zxing { + class MultiFormatReader : public Reader { + private: + Ref<Result> decodeInternal(Ref<BinaryBitmap> image); + + std::vector<Ref<Reader> > readers_; + DecodeHints hints_; + + public: + MultiFormatReader(); + + Ref<Result> decode(Ref<BinaryBitmap> image); + Ref<Result> decode(Ref<BinaryBitmap> image, DecodeHints hints); + Ref<Result> decodeWithState(Ref<BinaryBitmap> image); + void setHints(DecodeHints hints); + ~MultiFormatReader(); + }; +} + +#endif
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/Reader.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/Reader.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,40 @@ +#ifndef __READER_H__ +#define __READER_H__ + +/* + * Reader.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/BinaryBitmap.h> +#include <zxing/Result.h> +#include <zxing/DecodeHints.h> + +namespace zxing { + + class Reader : public Counted { + protected: + Reader() {} + public: + virtual Ref<Result> decode(Ref<BinaryBitmap> image); + virtual Ref<Result> decode(Ref<BinaryBitmap> image, DecodeHints hints) = 0; + virtual ~Reader(); +}; + +} + +#endif // __READER_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/ReaderException.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/ReaderException.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,37 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __READER_EXCEPTION_H__ +#define __READER_EXCEPTION_H__ + +/* + * ReaderException.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/Exception.h> + +namespace zxing { + +class ReaderException : public Exception { + public: + ReaderException() throw() {} + ReaderException(char const* msg) throw() : Exception(msg) {} + ~ReaderException() throw() {} +}; + +} + +#endif // __READER_EXCEPTION_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/Result.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/Result.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,55 @@ +#ifndef __RESULT_H__ +#define __RESULT_H__ + +/* + * Result.h + * zxing + * + * Copyright 2010 ZXing authors 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 <string> +#include <zxing/common/Array.h> +#include <zxing/common/Counted.h> +#include <zxing/common/Str.h> +#include <zxing/ResultPoint.h> +#include <zxing/BarcodeFormat.h> + +namespace zxing { + +class Result : public Counted { +private: + Ref<String> text_; + ArrayRef<char> rawBytes_; + ArrayRef< Ref<ResultPoint> > resultPoints_; + BarcodeFormat format_; + +public: + Result(Ref<String> text, + ArrayRef<char> rawBytes, + ArrayRef< Ref<ResultPoint> > resultPoints, + BarcodeFormat format); + ~Result(); + Ref<String> getText(); + ArrayRef<char> getRawBytes(); + ArrayRef< Ref<ResultPoint> > const& getResultPoints() const; + ArrayRef< Ref<ResultPoint> >& getResultPoints(); + BarcodeFormat getBarcodeFormat() const; + + friend std::ostream& operator<<(std::ostream &out, Result& result); +}; + +} +#endif // __RESULT_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/ResultPoint.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/ResultPoint.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,55 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __RESULT_POINT_H__ +#define __RESULT_POINT_H__ + +/* + * ResultPoint.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/common/Counted.h> +#include <vector> + +namespace zxing { + +class ResultPoint : public Counted { +protected: + const float posX_; + const float posY_; + +public: + ResultPoint(); + ResultPoint(float x, float y); + ResultPoint(int x, int y); + virtual ~ResultPoint(); + + virtual float getX() const; + virtual float getY() const; + + bool equals(Ref<ResultPoint> other); + + static void orderBestPatterns(std::vector<Ref<ResultPoint> > &patterns); + static float distance(Ref<ResultPoint> point1, Ref<ResultPoint> point2); + static float distance(float x1, float x2, float y1, float y2); + +private: + static float crossProductZ(Ref<ResultPoint> pointA, Ref<ResultPoint> pointB, Ref<ResultPoint> pointC); +}; + +} + +#endif // __RESULT_POINT_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/ResultPointCallback.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/ResultPointCallback.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,39 @@ +#ifndef __RESULT_POINT_CALLBACK_H__ +#define __RESULT_POINT_CALLBACK_H__ + +/* + * ResultPointCallback.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/common/Counted.h> + +namespace zxing { + +class ResultPoint; + +class ResultPointCallback : public Counted { +protected: + ResultPointCallback() {} +public: + virtual void foundPossibleResultPoint(ResultPoint const& point) = 0; + virtual ~ResultPointCallback(); +}; + +} + +#endif // __RESULT_POINT_CALLBACK_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/ZXing.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/ZXing.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,135 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +/* + * Copyright 2013 ZXing authors 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. + */ +#ifndef __ZXING_H_ +#define __ZXING_H_ + +#define ZXING_ARRAY_LEN(v) ((int)(sizeof(v)/sizeof(v[0]))) +#define ZX_LOG_DIGITS(digits) \ + ((digits == 8) ? 3 : \ + ((digits == 16) ? 4 : \ + ((digits == 32) ? 5 : \ + ((digits == 64) ? 6 : \ + ((digits == 128) ? 7 : \ + (-1)))))) + +#ifndef ZXING_DEBUG +#define ZXING_DEBUG 0 +#endif + +namespace zxing { +typedef char byte; +typedef bool boolean; +} + +#include <limits> + +#if defined(_WIN32) || defined(_WIN64) + +#include <float.h> + +namespace zxing { +inline bool isnan(float v) {return _isnan(v) != 0;} +inline bool isnan(double v) {return _isnan(v) != 0;} +inline float nan() {return std::numeric_limits<float>::quiet_NaN();} +} + +#else + +#include <cmath> + +namespace zxing { +#if defined(__ICCARM__) || defined( __CC_ARM ) // +#else // +inline bool isnan(float v) {return std::isnan(v);} +inline bool isnan(double v) {return std::isnan(v);} +#endif // +inline float nan() {return std::numeric_limits<float>::quiet_NaN();} +} +#endif + +#if ZXING_DEBUG + +#include <iostream> +#include <string> + +using std::cout; +using std::cerr; +using std::endl; +using std::flush; +using std::string; +using std::ostream; + +#if ZXING_DEBUG_TIMER + +#include <sys/time.h> + +namespace zxing { + +class DebugTimer { +public: + DebugTimer(char const* string_) : chars(string_) { + gettimeofday(&start, 0); + } + + DebugTimer(std::string const& string_) : chars(0), string(string_) { + gettimeofday(&start, 0); + } + + void mark(char const* string) { + struct timeval end; + gettimeofday(&end, 0); + int diff = + (end.tv_sec - start.tv_sec)*1000*1000+(end.tv_usec - start.tv_usec); + + cerr << diff << " " << string << '\n'; + } + + void mark(std::string string) { + mark(string.c_str()); + } + + ~DebugTimer() { + if (chars) { + mark(chars); + } else { + mark(string.c_str()); + } + } + +private: + char const* const chars; + std::string string; + struct timeval start; +}; + +} + +#define ZXING_TIME(string) DebugTimer __timer__ (string) +#define ZXING_TIME_MARK(string) __timer__.mark(string) + +#endif + +#endif // ZXING_DEBUG + +#ifndef ZXING_TIME +#define ZXING_TIME(string) (void)0 +#endif +#ifndef ZXING_TIME_MARK +#define ZXING_TIME_MARK(string) (void)0 +#endif + +#endif
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/Array.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/Array.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,170 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __ARRAY_H__ +#define __ARRAY_H__ + +/* + * Array.h + * zxing + * + * Copyright 2010 ZXing authors 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 <vector> + +#include <zxing/common/Counted.h> + +namespace zxing { + +template<typename T> class Array : public Counted { +protected: +public: + std::vector<T> values_; + Array() {} + Array(int n) : + Counted(), values_(n, T()) { + } + Array(T const* ts, int n) : + Counted(), values_(ts, ts+n) { + } + Array(T const* ts, T const* te) : + Counted(), values_(ts, te) { + } + Array(T v, int n) : + Counted(), values_(n, v) { + } + Array(std::vector<T> &v) : + Counted(), values_(v) { + } + Array(Array<T> &other) : + Counted(), values_(other.values_) { + } + Array(Array<T> *other) : + Counted(), values_(other->values_) { + } + virtual ~Array() { + } + Array<T>& operator=(const Array<T> &other) { + values_ = other.values_; + return *this; + } + Array<T>& operator=(const std::vector<T> &array) { + values_ = array; + return *this; + } + T const& operator[](int i) const { + return values_[i]; + } + T& operator[](int i) { + return values_[i]; + } + int size() const { + return values_.size(); + } + bool empty() const { + return values_.size() == 0; + } + std::vector<T> const& values() const { + return values_; + } + std::vector<T>& values() { + return values_; + } +}; + +template<typename T> class ArrayRef : public Counted { +private: +public: + Array<T> *array_; + ArrayRef() : + array_(0) { + } + explicit ArrayRef(int n) : + array_(0) { + reset(new Array<T> (n)); + } + ArrayRef(T *ts, int n) : + array_(0) { + reset(new Array<T> (ts, n)); + } + ArrayRef(Array<T> *a) : + array_(0) { + reset(a); + } + ArrayRef(const ArrayRef &other) : + Counted(), array_(0) { + reset(other.array_); + } + + template<class Y> + ArrayRef(const ArrayRef<Y> &other) : + array_(0) { + reset(static_cast<const Array<T> *>(other.array_)); + } + + ~ArrayRef() { + if (array_) { + array_->release(); + } + array_ = 0; + } + + T const& operator[](int i) const { + return (*array_)[i]; + } + + T& operator[](int i) { + return (*array_)[i]; + } + + void reset(Array<T> *a) { + if (a) { + a->retain(); + } + if (array_) { + array_->release(); + } + array_ = a; + } + void reset(const ArrayRef<T> &other) { + reset(other.array_); + } + ArrayRef<T>& operator=(const ArrayRef<T> &other) { + reset(other); + return *this; + } + ArrayRef<T>& operator=(Array<T> *a) { + reset(a); + return *this; + } + + Array<T>& operator*() const { + return *array_; + } + + Array<T>* operator->() const { + return array_; + } + + operator bool () const { + return array_ != 0; + } + bool operator ! () const { + return array_ == 0; + } +}; + +} // namespace zxing + +#endif // __ARRAY_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/BitArray.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/BitArray.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,81 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __BIT_ARRAY_H__ +#define __BIT_ARRAY_H__ + +/* + * Copyright 2010 ZXing authors. 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 <zxing/ZXing.h> +#include <zxing/common/Counted.h> +#include <zxing/common/IllegalArgumentException.h> +#include <zxing/common/Array.h> +#include <vector> +#include <limits> +#include <iostream> + +namespace zxing { + +class BitArray : public Counted { +public: + static const int bitsPerWord = std::numeric_limits<unsigned int>::digits; + +private: + int size; + ArrayRef<int> bits; + static const int logBits = ZX_LOG_DIGITS(bitsPerWord); + static const int bitsMask = (1 << logBits) - 1; + +public: + BitArray(int size); + ~BitArray(); + int getSize() const; + + bool get(int i) const { + return (bits[i >> logBits] & (1 << (i & bitsMask))) != 0; + } + + void set(int i) { + bits[i >> logBits] |= 1 << (i & bitsMask); + } + + int getNextSet(int from); + int getNextUnset(int from); + + void setBulk(int i, int newBits); + void setRange(int start, int end); + void clear(); + bool isRange(int start, int end, bool value); + std::vector<int>& getBitArray(); + + void reverse(); + + class Reverse { + private: + Ref<BitArray> array; + public: + Reverse(Ref<BitArray> array); + ~Reverse(); + }; + +private: + static int makeArraySize(int size); +}; + +std::ostream& operator << (std::ostream&, BitArray const&); + +} + +#endif // __BIT_ARRAY_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/BitMatrix.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/BitMatrix.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,94 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __BIT_MATRIX_H__ +#define __BIT_MATRIX_H__ + +/* + * BitMatrix.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/common/Counted.h> +#include <zxing/common/BitArray.h> +#include <zxing/common/Array.h> +#include <limits> +#if defined(__ICCARM__) // +#include <stddef.h> /*for size_t*/ // +#endif // + +namespace zxing { + +class BitMatrix : public Counted { +public: + static const int bitsPerWord = std::numeric_limits<unsigned int>::digits; + +private: + int width; + int height; + int rowSize; + ArrayRef<int> bits; + +#define ZX_LOG_DIGITS(digits) \ + ((digits == 8) ? 3 : \ + ((digits == 16) ? 4 : \ + ((digits == 32) ? 5 : \ + ((digits == 64) ? 6 : \ + ((digits == 128) ? 7 : \ + (-1)))))) + + static const int logBits = ZX_LOG_DIGITS(bitsPerWord); + static const int bitsMask = (1 << logBits) - 1; + +public: + BitMatrix(int dimension); + BitMatrix(int width, int height); + + ~BitMatrix(); + + bool get(int x, int y) const { + int offset = y * rowSize + (x >> logBits); + return ((((unsigned)bits[offset]) >> (x & bitsMask)) & 1) != 0; + } + + void set(int x, int y) { + int offset = y * rowSize + (x >> logBits); + bits[offset] |= 1 << (x & bitsMask); + } + + void flip(int x, int y); + void clear(); + void setRegion(int left, int top, int width, int height); + Ref<BitArray> getRow(int y, Ref<BitArray> row); + + int getWidth() const; + int getHeight() const; + + ArrayRef<int> getTopLeftOnBit() const; + ArrayRef<int> getBottomRightOnBit() const; + + friend std::ostream& operator<<(std::ostream &out, const BitMatrix &bm); + const char *description(); + +private: + inline void init(int, int); + + BitMatrix(const BitMatrix&); + BitMatrix& operator =(const BitMatrix&); +}; + +} + +#endif // __BIT_MATRIX_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/Counted.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/Counted.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,140 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __COUNTED_H__ +#define __COUNTED_H__ + +/* + * Copyright 2010 ZXing authors 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 <iostream> + +namespace zxing { + +/* base class for reference-counted objects */ +class Counted { +private: + unsigned int count_; +public: + Counted() : + count_(0) { + } + virtual ~Counted() { + } + Counted *retain() { + count_++; + return this; + } + void release() { + count_--; + if (count_ == 0) { + count_ = 0xDEADF001; + delete this; + } + } + + + /* return the current count for denugging purposes or similar */ + int count() const { + return count_; + } +}; + +/* counting reference to reference-counted objects */ +template<typename T> class Ref { +private: +public: + T *object_; + explicit Ref(T *o = 0) : + object_(0) { + reset(o); + } + Ref(const Ref &other) : + object_(0) { + reset(other.object_); + } + + template<class Y> + Ref(const Ref<Y> &other) : + object_(0) { + reset(other.object_); + } + + ~Ref() { + if (object_) { + object_->release(); + } + } + + void reset(T *o) { + if (o) { + o->retain(); + } + if (object_ != 0) { + object_->release(); + } + object_ = o; + } + Ref& operator=(const Ref &other) { + reset(other.object_); + return *this; + } + template<class Y> + Ref& operator=(const Ref<Y> &other) { + reset(other.object_); + return *this; + } + Ref& operator=(T* o) { + reset(o); + return *this; + } + template<class Y> + Ref& operator=(Y* o) { + reset(o); + return *this; + } + + T& operator*() { + return *object_; + } + T* operator->() const { + return object_; + } + operator T*() const { + return object_; + } + + bool operator==(const T* that) { + return object_ == that; + } + bool operator==(const Ref &other) const { + return object_ == other.object_ || *object_ == *(other.object_); + } + template<class Y> + bool operator==(const Ref<Y> &other) const { + return object_ == other.object_ || *object_ == *(other.object_); + } + + bool operator!=(const T* that) { + return !(*this == that); + } + + bool empty() const { + return object_ == 0; + } +}; + +} + +#endif // __COUNTED_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/DecoderResult.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/DecoderResult.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,51 @@ +#ifndef __DECODER_RESULT_H__ +#define __DECODER_RESULT_H__ + +/* + * DecoderResult.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/common/Counted.h> +#include <zxing/common/Array.h> +#include <string> +#include <zxing/common/Str.h> + +namespace zxing { + +class DecoderResult : public Counted { +private: + ArrayRef<char> rawBytes_; + Ref<String> text_; + ArrayRef< ArrayRef<char> > byteSegments_; + std::string ecLevel_; + +public: + DecoderResult(ArrayRef<char> rawBytes, + Ref<String> text, + ArrayRef< ArrayRef<char> >& byteSegments, + std::string const& ecLevel); + + DecoderResult(ArrayRef<char> rawBytes, Ref<String> text); + + ArrayRef<char> getRawBytes(); + Ref<String> getText(); +}; + +} + +#endif // __DECODER_RESULT_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/GlobalHistogramBinarizer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/GlobalHistogramBinarizer.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,48 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __GLOBALHISTOGRAMBINARIZER_H__ +#define __GLOBALHISTOGRAMBINARIZER_H__ +/* + * GlobalHistogramBinarizer.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/Binarizer.h> +#include <zxing/common/BitArray.h> +#include <zxing/common/BitMatrix.h> +#include <zxing/common/Array.h> + +namespace zxing { + +class GlobalHistogramBinarizer : public Binarizer { +private: + ArrayRef<char> luminances; + ArrayRef<int> buckets; +public: + GlobalHistogramBinarizer(Ref<LuminanceSource> source); + virtual ~GlobalHistogramBinarizer(); + + virtual Ref<BitArray> getBlackRow(int y, Ref<BitArray> row); + virtual Ref<BitMatrix> getBlackMatrix(); + static int estimateBlackPoint(ArrayRef<int> const& buckets); + Ref<Binarizer> createBinarizer(Ref<LuminanceSource> source); +private: + void initArrays(int luminanceSize); +}; + +} + +#endif /* GLOBALHISTOGRAMBINARIZER_H_ */
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/HybridBinarizer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/HybridBinarizer.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,67 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __HYBRIDBINARIZER_H__ +#define __HYBRIDBINARIZER_H__ +/* + * HybridBinarizer.h + * zxing + * + * Copyright 2010 ZXing authors 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 <vector> +#include <zxing/Binarizer.h> +#include <zxing/common/GlobalHistogramBinarizer.h> +#include <zxing/common/BitArray.h> +#include <zxing/common/BitMatrix.h> + +namespace zxing { + + class HybridBinarizer : public GlobalHistogramBinarizer { + private: + Ref<BitMatrix> matrix_; + Ref<BitArray> cached_row_; + + public: + HybridBinarizer(Ref<LuminanceSource> source); + virtual ~HybridBinarizer(); + + virtual Ref<BitMatrix> getBlackMatrix(); + Ref<Binarizer> createBinarizer(Ref<LuminanceSource> source); + private: + // We'll be using one-D arrays because C++ can't dynamically allocate 2D + // arrays + ArrayRef<int> calculateBlackPoints(ArrayRef<char> luminances, + int subWidth, + int subHeight, + int width, + int height); + void calculateThresholdForBlock(ArrayRef<char> luminances, + int subWidth, + int subHeight, + int width, + int height, + ArrayRef<int> blackPoints, + Ref<BitMatrix> const& matrix); + void thresholdBlock(ArrayRef<char>luminances, + int xoffset, + int yoffset, + int threshold, + int stride, + Ref<BitMatrix> const& matrix); + }; + +} + +#endif
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/IllegalArgumentException.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/IllegalArgumentException.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,36 @@ +#ifndef __ILLEGAL_ARGUMENT_EXCEPTION_H__ +#define __ILLEGAL_ARGUMENT_EXCEPTION_H__ + +/* + * IllegalArgumentException.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/Exception.h> + +namespace zxing { + +class IllegalArgumentException : public Exception { +public: + IllegalArgumentException(); + IllegalArgumentException(const char *msg); + ~IllegalArgumentException() throw(); +}; + +} + +#endif // __ILLEGAL_ARGUMENT_EXCEPTION_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/Str.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/Str.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,51 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __STR_H__ +#define __STR_H__ + +/* + * Str.h + * zxing + * + * Copyright 2010 ZXing authors 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 <string> +#include <iostream> +#include <zxing/common/Counted.h> + +namespace zxing { + +class String; +std::ostream& operator << (std::ostream& out, String const& s); + +class String : public Counted { +private: + std::string text_; +public: + explicit String(const std::string &text); + explicit String(int); + char charAt(int) const; + Ref<String> substring(int) const; + const std::string& getText() const; + int size() const; + void append(std::string const& tail); + void append(char c); + int length() const; + friend std::ostream& zxing::operator << (std::ostream& out, String const& s); +}; + +} + +#endif // __COMMON__STRING_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/reedsolomon/GenericGF.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/reedsolomon/GenericGF.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,73 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +/* + * GenericGF.h + * zxing + * + * Created by Lukas Stabe on 13/02/2012. + * Copyright 2012 ZXing authors 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. + */ + +#ifndef GENERICGF_H +#define GENERICGF_H + +#include <vector> +#include <zxing/common/Counted.h> + +namespace zxing { + class GenericGFPoly; + + class GenericGF : public Counted { + + private: + std::vector<int> expTable; + std::vector<int> logTable; + Ref<GenericGFPoly> zero; + Ref<GenericGFPoly> one; + int size; + int primitive; + int generatorBase; + bool initialized; + + void initialize(); + void checkInit(); + + public: + static Ref<GenericGF> AZTEC_DATA_12; + static Ref<GenericGF> AZTEC_DATA_10; + static Ref<GenericGF> AZTEC_DATA_8; + static Ref<GenericGF> AZTEC_DATA_6; + static Ref<GenericGF> AZTEC_PARAM; + static Ref<GenericGF> QR_CODE_FIELD_256; + static Ref<GenericGF> DATA_MATRIX_FIELD_256; + static Ref<GenericGF> MAXICODE_FIELD_64; + + GenericGF(int primitive, int size, int b); + + Ref<GenericGFPoly> getZero(); + Ref<GenericGFPoly> getOne(); + int getSize(); + int getGeneratorBase(); + Ref<GenericGFPoly> buildMonomial(int degree, int coefficient); + + static int addOrSubtract(int a, int b); + int exp(int a); + int log(int a); + int inverse(int a); + int multiply(int a, int b); + }; +} + +#endif //GENERICGF_H +
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/reedsolomon/GenericGFPoly.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/reedsolomon/GenericGFPoly.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,56 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +/* + * GenericGFPoly.h + * zxing + * + * Created by Lukas Stabe on 13/02/2012. + * Copyright 2012 ZXing authors 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. + */ + +#ifndef GENERICGFPOLY_H +#define GENERICGFPOLY_H + +#include <vector> +#include <zxing/common/Array.h> +#include <zxing/common/Counted.h> + +namespace zxing { + +class GenericGF; + +class GenericGFPoly : public Counted { +private: + GenericGF &field_; + ArrayRef<int> coefficients_; + +public: + GenericGFPoly(GenericGF &field, ArrayRef<int> coefficients); + ArrayRef<int> getCoefficients(); + int getDegree(); + bool isZero(); + int getCoefficient(int degree); + int evaluateAt(int a); + Ref<GenericGFPoly> addOrSubtract(Ref<GenericGFPoly> other); + Ref<GenericGFPoly> multiply(Ref<GenericGFPoly> other); + Ref<GenericGFPoly> multiply(int scalar); + Ref<GenericGFPoly> multiplyByMonomial(int degree, int coefficient); + std::vector<Ref<GenericGFPoly> > divide(Ref<GenericGFPoly> other); + + +}; + +} + +#endif //GENERICGFPOLY_H
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/common/reedsolomon/ReedSolomonDecoder.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/common/reedsolomon/ReedSolomonDecoder.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,49 @@ +#ifndef __REED_SOLOMON_DECODER_H__ +#define __REED_SOLOMON_DECODER_H__ + +/* + * ReedSolomonDecoder.h + * zxing + * + * Copyright 2010 ZXing authors 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 <memory> +#include <vector> +#include <zxing/common/Counted.h> +#include <zxing/common/Array.h> +#include <zxing/common/reedsolomon/GenericGFPoly.h> +#include <zxing/common/reedsolomon/GenericGF.h> + +namespace zxing { +class GenericGFPoly; +class GenericGF; + +class ReedSolomonDecoder { +private: + Ref<GenericGF> field; +public: + ReedSolomonDecoder(Ref<GenericGF> fld); + ~ReedSolomonDecoder(); + void decode(ArrayRef<int> received, int twoS); + std::vector<Ref<GenericGFPoly> > runEuclideanAlgorithm(Ref<GenericGFPoly> a, Ref<GenericGFPoly> b, int R); + +private: + ArrayRef<int> findErrorLocations(Ref<GenericGFPoly> errorLocator); + ArrayRef<int> findErrorMagnitudes(Ref<GenericGFPoly> errorEvaluator, ArrayRef<int> errorLocations); +}; +} + +#endif // __REED_SOLOMON_DECODER_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/multi/ByQuadrantReader.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/multi/ByQuadrantReader.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,42 @@ +#ifndef __BY_QUADRANT_READER_H__ +#define __BY_QUADRANT_READER_H__ + +/* + * Copyright 2011 ZXing authors 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 <zxing/Reader.h> +#include <zxing/BinaryBitmap.h> +#include <zxing/Result.h> +#include <zxing/DecodeHints.h> + +namespace zxing { +namespace multi { + +class ByQuadrantReader : public Reader { + private: + Reader& delegate_; + + public: + ByQuadrantReader(Reader& delegate); + virtual ~ByQuadrantReader(); + virtual Ref<Result> decode(Ref<BinaryBitmap> image); + virtual Ref<Result> decode(Ref<BinaryBitmap> image, DecodeHints hints); +}; + +} +} + +#endif // __BY_QUADRANT_READER_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/multi/GenericMultipleBarcodeReader.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/multi/GenericMultipleBarcodeReader.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,51 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __GENERIC_MULTIPLE_BARCODE_READER_H__ +#define __GENERIC_MULTIPLE_BARCODE_READER_H__ + +/* + * Copyright 2011 ZXing authors 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 <zxing/multi/MultipleBarcodeReader.h> +#include <zxing/Reader.h> + +namespace zxing { +namespace multi { + +class GenericMultipleBarcodeReader : public MultipleBarcodeReader { + private: + static Ref<Result> translateResultPoints(Ref<Result> result, + int xOffset, + int yOffset); + void doDecodeMultiple(Ref<BinaryBitmap> image, + DecodeHints hints, + std::vector<Ref<Result> >& results, + int xOffset, + int yOffset, + int currentDepth); + Reader& delegate_; + static const int MIN_DIMENSION_TO_RECUR = 100; + static const int MAX_DEPTH = 4; + + public: + GenericMultipleBarcodeReader(Reader& delegate); + virtual ~GenericMultipleBarcodeReader(); + virtual std::vector<Ref<Result> > decodeMultiple(Ref<BinaryBitmap> image, DecodeHints hints); +}; + +} +} + +#endif // __GENERIC_MULTIPLE_BARCODE_READER_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/multi/MultipleBarcodeReader.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/multi/MultipleBarcodeReader.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,41 @@ +#ifndef __MULTIPLE_BARCODE_READER_H__ +#define __MULTIPLE_BARCODE_READER_H__ + +/* + * Copyright 2011 ZXing authors 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 <zxing/common/Counted.h> +#include <zxing/Result.h> +#include <zxing/BinaryBitmap.h> +#include <zxing/DecodeHints.h> +#include <vector> + +namespace zxing { +namespace multi { + +class MultipleBarcodeReader : public Counted { + protected: + MultipleBarcodeReader() {} + public: + virtual std::vector<Ref<Result> > decodeMultiple(Ref<BinaryBitmap> image); + virtual std::vector<Ref<Result> > decodeMultiple(Ref<BinaryBitmap> image, DecodeHints hints) = 0; + virtual ~MultipleBarcodeReader(); +}; + +} +} + +#endif // __MULTIPLE_BARCODE_READER_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/multi/qrcode/QRCodeMultiReader.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/multi/qrcode/QRCodeMultiReader.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,36 @@ +#ifndef __QRCODE_MULTI_READER_H__ +#define __QRCODE_MULTI_READER_H__ + +/* + * Copyright 2011 ZXing authors 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 <zxing/multi/MultipleBarcodeReader.h> +#include <zxing/qrcode/QRCodeReader.h> + +namespace zxing { +namespace multi { + +class QRCodeMultiReader: public zxing::qrcode::QRCodeReader, public MultipleBarcodeReader { + public: + QRCodeMultiReader(); + virtual ~QRCodeMultiReader(); + virtual std::vector<Ref<Result> > decodeMultiple(Ref<BinaryBitmap> image, DecodeHints hints); +}; + +} +} + +#endif // __QRCODE_MULTI_READER_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/qrcode/QRCodeReader.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/qrcode/QRCodeReader.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,48 @@ +// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- +#ifndef __QR_CODE_READER_H__ +#define __QR_CODE_READER_H__ + +/* + * QRCodeReader.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/Reader.h> +#include <zxing/qrcode/decoder/Decoder.h> +#include <zxing/DecodeHints.h> + +namespace zxing { +namespace qrcode { + +class QRCodeReader : public Reader { + private: + Decoder decoder_; + + protected: + Decoder& getDecoder(); + + public: + QRCodeReader(); + virtual ~QRCodeReader(); + + Ref<Result> decode(Ref<BinaryBitmap> image, DecodeHints hints); +}; + +} +} + +#endif // __QR_CODE_READER_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing/qrcode/decoder/Decoder.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zxing_lib/zxing/qrcode/decoder/Decoder.h Thu Nov 24 13:59:16 2016 +0900 @@ -0,0 +1,46 @@ +#ifndef __DECODER_H__ +#define __DECODER_H__ + +/* + * Decoder.h + * zxing + * + * Copyright 2010 ZXing authors 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 <zxing/common/reedsolomon/ReedSolomonDecoder.h> +#include <zxing/common/Counted.h> +#include <zxing/common/Array.h> +#include <zxing/common/DecoderResult.h> +#include <zxing/common/BitMatrix.h> + +namespace zxing { +namespace qrcode { + +class Decoder { +private: + ReedSolomonDecoder rsDecoder_; + + void correctErrors(ArrayRef<char> bytes, int numDataCodewords); + +public: + Decoder(); + Ref<DecoderResult> decode(Ref<BitMatrix> bits); +}; + +} +} + +#endif // __DECODER_H__
diff -r 000000000000 -r ad834d403a8c zxing_lib/zxing_lib.ar Binary file zxing_lib/zxing_lib.ar has changed