Fix overly-enthusiastic .gitignore

This commit is contained in:
polyfractal 2017-01-10 06:42:22 -05:00
parent a83d26d251
commit 76247cfc7a
20 changed files with 7104 additions and 1 deletions

2
.gitignore vendored
View file

@ -1,5 +1,5 @@
target
Cargo.lock
application
./application/
*.o
src/c/inc/build_info.h

View file

@ -0,0 +1,66 @@
/*
File: curve25519-donna.h
Package: WACServer
Version: WACServer-1.14
Disclaimer: IMPORTANT: This Apple software is supplied to you, by Apple Inc. ("Apple"), in your
capacity as a current, and in good standing, Licensee in the MFi Licensing Program. Use of this
Apple software is governed by and subject to the terms and conditions of your MFi License,
including, but not limited to, the restrictions specified in the provision entitled Public
Software, and is further subject to your agreement to the following additional terms, and your
agreement that the use, installation, modification or redistribution of this Apple software
constitutes acceptance of these additional terms. If you do not agree with these additional terms,
please do not use, install, modify or redistribute this Apple software.
Subject to all of these terms and in consideration of your agreement to abide by them, Apple grants
you, for as long as you are a current and in good-standing MFi Licensee, a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, and modify the Apple Software in source form, and to use, reproduce, modify, and
redistribute the Apple Software, with or without modifications, in binary form. While you may not
redistribute the Apple Software in source form, should you redistribute the Apple Software in binary
form, you must retain this notice and the following text and disclaimers in all such redistributions
of the Apple Software. Neither the name, trademarks, service marks, or logos of Apple Inc. may be
used to endorse or promote products derived from the Apple Software without specific prior written
permission from Apple. Except as expressly stated in this notice, no other rights or licenses,
express or implied, are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple Software may be
incorporated.
Unless you explicitly state otherwise, if you provide any ideas, suggestions, recommendations, bug
fixes or enhancements to Apple in connection with this software (Feedback), you hereby grant to
Apple a non-exclusive, fully paid-up, perpetual, irrevocable, worldwide license to make, use,
reproduce, incorporate, modify, display, perform, sell, make or have made derivative works of,
distribute (directly or indirectly) and sublicense, such Feedback in connection with Apple products
and services. Providing this Feedback is voluntary, but if you do provide Feedback to Apple, you
acknowledge and agree that Apple may exercise the license granted above without the payment of
royalties or further consideration to Participant.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR
IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR
IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION
AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2009 Apple Inc. All Rights Reserved.
*/
#ifndef __curve25519_donnaDotH__
#define __curve25519_donnaDotH__
#ifdef __cplusplus
extern "C" {
#endif
void curve25519_donna( unsigned char *outKey, const unsigned char *inSecret, const unsigned char *inBasePoint );
#ifdef __cplusplus
}
#endif
#endif // __curve25519_donnaDotH__

View file

@ -0,0 +1,220 @@
/*
---------------------------------------------------------------------------
Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
The redistribution and use of this software (with or without changes)
is allowed without the payment of fees or royalties provided that:
source code distributions include the above copyright notice, this
list of conditions and the following disclaimer;
binary distributions include the above copyright notice, this list
of conditions and the following disclaimer in their documentation.
This software is provided 'as is' with no explicit or implied warranties
in respect of its operation, including, but not limited to, correctness
and fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 20/12/2007
This file contains the definitions required to use AES in C. See aesopt.h
for optimisation details.
*/
#ifndef _AES_H
#define _AES_H
#include <stdlib.h>
/* This include is used to find 8 & 32 bit unsigned integer types */
#include "rom_wac_brg_types.h"
/* Use AES encrypt/decrypt in wlan ROM codes */
#include "rom_aes.h"
extern int aes_set_key( aes_context *ctx, u8 *key, int nbits );
#if defined(__cplusplus)
extern "C"
{
#endif
#define AES_128 /* if a fast 128 bit key scheduler is needed */
#define AES_192 /* if a fast 192 bit key scheduler is needed */
#define AES_256 /* if a fast 256 bit key scheduler is needed */
#define AES_VAR /* if variable key size scheduler is needed */
#define AES_MODES /* if support is needed for modes */
/* The following must also be set in assembler files if being used */
#define AES_ENCRYPT /* if support for encryption is needed */
#define AES_DECRYPT /* if support for decryption is needed */
#define AES_REV_DKS /* define to reverse decryption key schedule */
#define AES_BLOCK_SIZE 16 /* the AES block size in bytes */
#define N_COLS 4 /* the number of columns in the state */
/* The key schedule length is 11, 13 or 15 16-byte blocks for 128, */
/* 192 or 256-bit keys respectively. That is 176, 208 or 240 bytes */
/* or 44, 52 or 60 32-bit words. */
#if defined( AES_VAR ) || defined( AES_256 )
#define KS_LENGTH 60
#elif defined( AES_192 )
#define KS_LENGTH 52
#else
#define KS_LENGTH 44
#endif
#define AES_RETURN INT_RETURN
/* the character array 'inf' in the following structures is used */
/* to hold AES context information. This AES code uses cx->inf.b[0] */
/* to hold the number of rounds multiplied by 16. The other three */
/* elements can be used by code that implements additional modes */
typedef union
{ uint_32t l;
uint_8t b[4];
} aes_inf;
typedef struct
{
#if 0
uint_32t ks[KS_LENGTH];
#else
aes_context ctx;
#endif
aes_inf inf;
} aes_encrypt_ctx;
typedef struct
{
#if 0
uint_32t ks[KS_LENGTH];
#else
aes_context ctx;
#endif
aes_inf inf;
} aes_decrypt_ctx;
/* This routine must be called before first use if non-static */
/* tables are being used */
AES_RETURN aes_init(void);
/* Key lengths in the range 16 <= key_len <= 32 are given in bytes, */
/* those in the range 128 <= key_len <= 256 are given in bits */
#if defined( AES_ENCRYPT )
#if defined( AES_128 ) || defined( AES_VAR)
AES_RETURN aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1]);
#endif
#if defined( AES_192 ) || defined( AES_VAR)
AES_RETURN aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1]);
#endif
#if defined( AES_256 ) || defined( AES_VAR)
AES_RETURN aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1]);
#endif
#if defined( AES_VAR )
AES_RETURN aes_encrypt_key(const unsigned char *key, int key_len, aes_encrypt_ctx cx[1]);
#endif
#if 0
AES_RETURN aes_encrypt(const unsigned char *in, unsigned char *out, const aes_encrypt_ctx cx[1]);
#else
extern void aes_encrypt( aes_context *ctx, u8 input[16], u8 output[16] );
#endif
#endif
#if defined( AES_DECRYPT )
#if defined( AES_128 ) || defined( AES_VAR)
AES_RETURN aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1]);
#endif
#if defined( AES_192 ) || defined( AES_VAR)
AES_RETURN aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1]);
#endif
#if defined( AES_256 ) || defined( AES_VAR)
AES_RETURN aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1]);
#endif
#if defined( AES_VAR )
AES_RETURN aes_decrypt_key(const unsigned char *key, int key_len, aes_decrypt_ctx cx[1]);
#endif
#if 0
AES_RETURN aes_decrypt(const unsigned char *in, unsigned char *out, const aes_decrypt_ctx cx[1]);
#else
extern void aes_decrypt( aes_context *ctx, u8 input[16], u8 output[16] );
#endif
#endif
#if defined( AES_MODES )
/* Multiple calls to the following subroutines for multiple block */
/* ECB, CBC, CFB, OFB and CTR mode encryption can be used to handle */
/* long messages incremantally provided that the context AND the iv */
/* are preserved between all such calls. For the ECB and CBC modes */
/* each individual call within a series of incremental calls must */
/* process only full blocks (i.e. len must be a multiple of 16) but */
/* the CFB, OFB and CTR mode calls can handle multiple incremental */
/* calls of any length. Each mode is reset when a new AES key is */
/* set but ECB and CBC operations can be reset without setting a */
/* new key by setting a new IV value. To reset CFB, OFB and CTR */
/* without setting the key, aes_mode_reset() must be called and the */
/* IV must be set. NOTE: All these calls update the IV on exit so */
/* this has to be reset if a new operation with the same IV as the */
/* previous one is required (or decryption follows encryption with */
/* the same IV array). */
AES_RETURN aes_test_alignment_detection(unsigned int n);
AES_RETURN aes_ecb_encrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, const aes_encrypt_ctx cx[1]);
AES_RETURN aes_ecb_decrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, const aes_decrypt_ctx cx[1]);
AES_RETURN aes_cbc_encrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *iv, const aes_encrypt_ctx cx[1]);
AES_RETURN aes_cbc_decrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *iv, const aes_decrypt_ctx cx[1]);
AES_RETURN aes_mode_reset(aes_encrypt_ctx cx[1]);
AES_RETURN aes_cfb_encrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *iv, aes_encrypt_ctx cx[1]);
AES_RETURN aes_cfb_decrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *iv, aes_encrypt_ctx cx[1]);
#define aes_ofb_encrypt aes_ofb_crypt
#define aes_ofb_decrypt aes_ofb_crypt
AES_RETURN aes_ofb_crypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *iv, aes_encrypt_ctx cx[1]);
typedef void cbuf_inc(unsigned char *cbuf);
#define aes_ctr_encrypt aes_ctr_crypt
#define aes_ctr_decrypt aes_ctr_crypt
AES_RETURN aes_ctr_crypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *cbuf, cbuf_inc ctr_inc, aes_encrypt_ctx cx[1]);
#endif
#if defined(__cplusplus)
}
#endif
#endif

View file

@ -0,0 +1,229 @@
/*
---------------------------------------------------------------------------
Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
The redistribution and use of this software (with or without changes)
is allowed without the payment of fees or royalties provided that:
source code distributions include the above copyright notice, this
list of conditions and the following disclaimer;
binary distributions include the above copyright notice, this list
of conditions and the following disclaimer in their documentation.
This software is provided 'as is' with no explicit or implied warranties
in respect of its operation, including, but not limited to, correctness
and fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 20/12/2007
The unsigned integer types defined here are of the form uint_<nn>t where
<nn> is the length of the type; for example, the unsigned 32-bit type is
'uint_32t'. These are NOT the same as the 'C99 integer types' that are
defined in the inttypes.h and stdint.h headers since attempts to use these
types have shown that support for them is still highly variable. However,
since the latter are of the form uint<nn>_t, a regular expression search
and replace (in VC++ search on 'uint_{:z}t' and replace with 'uint\1_t')
can be used to convert the types used here to the C99 standard types.
*/
#ifndef _BRG_TYPES_H
#define _BRG_TYPES_H
#if defined(__cplusplus)
extern "C" {
#endif
#include <limits.h>
#if 0
#if defined( _MSC_VER ) && ( _MSC_VER >= 1300 )
# include <stddef.h>
# define ptrint_t intptr_t
#elif defined( __ECOS__ )
# define intptr_t unsigned int
# define ptrint_t intptr_t
#elif defined( __GNUC__ ) && ( __GNUC__ >= 3 )
# include <stdint.h>
# define ptrint_t intptr_t
#else
# define ptrint_t int
#endif
#else
# include <stdint.h>
# define ptrint_t intptr_t
#ifndef u8
typedef uint8_t u8;
#endif
#ifndef u32
typedef uint32_t u32;
#endif
#endif
#ifndef BRG_UI8
# define BRG_UI8
# if UCHAR_MAX == 255u
typedef unsigned char uint_8t;
# else
# error Please define uint_8t as an 8-bit unsigned integer type in brg_types.h
# endif
#endif
#ifndef BRG_UI16
# define BRG_UI16
# if USHRT_MAX == 65535u
typedef unsigned short uint_16t;
# else
# error Please define uint_16t as a 16-bit unsigned short type in brg_types.h
# endif
#endif
#ifndef BRG_UI32
# define BRG_UI32
# if UINT_MAX == 4294967295u
# define li_32(h) 0x##h##u
typedef unsigned int uint_32t;
# elif ULONG_MAX == 4294967295u
# define li_32(h) 0x##h##ul
typedef unsigned long uint_32t;
# elif defined( _CRAY )
# error This code needs 32-bit data types, which Cray machines do not provide
# else
# error Please define uint_32t as a 32-bit unsigned integer type in brg_types.h
# endif
#endif
#ifndef BRG_UI64
# if defined( __BORLANDC__ ) && !defined( __MSDOS__ )
# define BRG_UI64
# define li_64(h) 0x##h##ui64
typedef unsigned __int64 uint_64t;
# elif defined( _MSC_VER ) && ( _MSC_VER < 1300 ) /* 1300 == VC++ 7.0 */
# define BRG_UI64
# define li_64(h) 0x##h##ui64
typedef unsigned __int64 uint_64t;
# elif defined( __sun ) && defined( ULONG_MAX ) && ULONG_MAX == 0xfffffffful
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned long long uint_64t;
# elif defined( __MVS__ )
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned int long long uint_64t;
# elif defined( UINT_MAX ) && UINT_MAX > 4294967295u
# if UINT_MAX == 18446744073709551615u
# define BRG_UI64
# define li_64(h) 0x##h##u
typedef unsigned int uint_64t;
# endif
# elif defined( ULONG_MAX ) && ULONG_MAX > 4294967295u
# if ULONG_MAX == 18446744073709551615ul
# define BRG_UI64
# define li_64(h) 0x##h##ul
typedef unsigned long uint_64t;
# endif
# elif defined( ULLONG_MAX ) && ULLONG_MAX > 4294967295u
# if ULLONG_MAX == 18446744073709551615ull
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned long long uint_64t;
# endif
# elif defined( ULONG_LONG_MAX ) && ULONG_LONG_MAX > 4294967295u
# if ULONG_LONG_MAX == 18446744073709551615ull
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned long long uint_64t;
# endif
# endif
#endif
#if !defined( BRG_UI64 )
# if defined( NEED_UINT_64T )
# error Please define uint_64t as an unsigned 64 bit type in brg_types.h
# endif
#endif
#ifndef RETURN_VALUES
# define RETURN_VALUES
# if defined( DLL_EXPORT )
# if defined( _MSC_VER ) || defined ( __INTEL_COMPILER )
# define VOID_RETURN __declspec( dllexport ) void __stdcall
# define INT_RETURN __declspec( dllexport ) int __stdcall
# elif defined( __GNUC__ )
# define VOID_RETURN __declspec( __dllexport__ ) void
# define INT_RETURN __declspec( __dllexport__ ) int
# else
# error Use of the DLL is only available on the Microsoft, Intel and GCC compilers
# endif
# elif defined( DLL_IMPORT )
# if defined( _MSC_VER ) || defined ( __INTEL_COMPILER )
# define VOID_RETURN __declspec( dllimport ) void __stdcall
# define INT_RETURN __declspec( dllimport ) int __stdcall
# elif defined( __GNUC__ )
# define VOID_RETURN __declspec( __dllimport__ ) void
# define INT_RETURN __declspec( __dllimport__ ) int
# else
# error Use of the DLL is only available on the Microsoft, Intel and GCC compilers
# endif
# elif defined( __WATCOMC__ )
# define VOID_RETURN void __cdecl
# define INT_RETURN int __cdecl
# else
# define VOID_RETURN void
# define INT_RETURN int
# endif
#endif
/* These defines are used to detect and set the memory alignment of pointers.
Note that offsets are in bytes.
ALIGN_OFFSET(x,n) return the positive or zero offset of
the memory addressed by the pointer 'x'
from an address that is aligned on an
'n' byte boundary ('n' is a power of 2)
ALIGN_FLOOR(x,n) return a pointer that points to memory
that is aligned on an 'n' byte boundary
and is not higher than the memory address
pointed to by 'x' ('n' is a power of 2)
ALIGN_CEIL(x,n) return a pointer that points to memory
that is aligned on an 'n' byte boundary
and is not lower than the memory address
pointed to by 'x' ('n' is a power of 2)
*/
#define ALIGN_OFFSET(x,n) (((ptrint_t)(x)) & ((n) - 1))
#define ALIGN_FLOOR(x,n) ((uint_8t*)(x) - ( ((ptrint_t)(x)) & ((n) - 1)))
#define ALIGN_CEIL(x,n) ((uint_8t*)(x) + (-((ptrint_t)(x)) & ((n) - 1)))
/* These defines are used to declare buffers in a way that allows
faster operations on longer variables to be used. In all these
defines 'size' must be a power of 2 and >= 8. NOTE that the
buffer size is in bytes but the type length is in bits
UNIT_TYPEDEF(x,size) declares a variable 'x' of length
'size' bits
BUFR_TYPEDEF(x,size,bsize) declares a buffer 'x' of length 'bsize'
bytes defined as an array of variables
each of 'size' bits (bsize must be a
multiple of size / 8)
UNIT_CAST(x,size) casts a variable to a type of
length 'size' bits
UPTR_CAST(x,size) casts a pointer to a pointer to a
varaiable of length 'size' bits
*/
#define UI_TYPE(size) uint_##size##t
#define UNIT_TYPEDEF(x,size) typedef UI_TYPE(size) x
#define BUFR_TYPEDEF(x,size,bsize) typedef UI_TYPE(size) x[bsize / (size >> 3)]
#define UNIT_CAST(x,size) ((UI_TYPE(size) )(x))
#define UPTR_CAST(x,size) ((UI_TYPE(size)*)(x))
#if defined(__cplusplus)
}
#endif
#endif

View file

@ -0,0 +1,23 @@
#ifndef GOOGLENEST_H
#define GOOGLENEST_H
#include <polarssl/ssl.h>
typedef struct {
int socket;
char *host;
ssl_context ssl;
} googlenest_context;
int gn_connect(googlenest_context *googlenest, char *host, int port);
void gn_close(googlenest_context *googlenest);
int gn_put(googlenest_context *googlenest, char *uri, char *content);
int gn_patch(googlenest_context *googlenest, char *uri, char *content);
int gn_post(googlenest_context *googlenest, char *uri, char *content, unsigned char *out_buffer, size_t out_len);
int gn_get(googlenest_context *googlenest, char *uri, unsigned char *out_buffer, size_t out_len);
int gn_delete(googlenest_context *googlenest, char *uri);
int gn_stream(googlenest_context *googlenest, char *uri);
void google_retrieve_data_hook_callback(void (*callback)(char *));
#endif

View file

@ -0,0 +1,675 @@
/*******************************example_joinlink **************************/
#include "autoconf.h"
#include "platform_stdlib.h"
#include "wifi_conf.h"
#include "wifi_structures.h"
#include "osdep_service.h"
#include "lwip_netconf.h"
#include "task.h"
#include "joinlink.h"
#include "cJSON.h"
#include <lwip/sockets.h>
#include <lwip/raw.h>
#include <lwip/icmp.h>
#include <lwip/inet_chksum.h>
#include <platform/platform_stdlib.h>
#define MASK_SIZE_JOINLINK 3
#define SOURCE_PORT 101
//gloable
static unsigned char cur_channel = 1;
static unsigned char lock_channel = 1;
static _timer timer_handler_phase2;
static _timer timer_handler_phase1;
static u8 joinlink_finished = 0;
static u8 security_type = 0xff;
static u8 jl_rx_flag = 0;
static rtw_scan_result_t *all_channel_scan_result = NULL;
static rtw_scan_result_t *p_result = NULL;
static int all_channel_ret = 0;
static int phase1_finished = 0;
static int phase2_started = 0;
static u32 start_time = 0;
static u32 current_time = 0;
static int idx = 1;
static int phase1_scanned_channel[14];
static char ap_bssid[6];
static char aes_key[] = "123456789";
static void* pre_scan_sema;
static int ack_socket;
static struct sockaddr_in to_addr;
static struct sockaddr_in from_addr;
static char header_cmd[] = "cmd";
static cJSON *ack_content = NULL;
extern struct netif xnetif[];
void example_joinlink(void);
static rtw_result_t joinlink_scan_result_handler(rtw_scan_handler_result_t* malloced_scan_result )
{
static int ApNum = 0;
//TODO: add timer of 2s, wf, 1021
if (malloced_scan_result->scan_complete != RTW_TRUE) {
rtw_scan_result_t* record = &malloced_scan_result->ap_details;
record->SSID.val[record->SSID.len] = 0; /* Ensure the SSID is null terminated */
++ApNum;
if(malloced_scan_result->user_data)
memcpy((void *)((char *)malloced_scan_result->user_data+(ApNum-1)*sizeof(rtw_scan_result_t)), (char *)record, sizeof(rtw_scan_result_t));
}
// scan finished, wf, 1022
else
{
rtw_up_sema(&pre_scan_sema);
ApNum = 0;
}
return RTW_SUCCESS;
}
void* joinlink_all_scan()
{
int ret = 0;
rtw_scan_result_t *joinlink_scan_buf = NULL;
if(joinlink_scan_buf != NULL)
free(joinlink_scan_buf);
joinlink_scan_buf = (rtw_scan_result_t *)malloc(65*sizeof(rtw_scan_result_t));
if(joinlink_scan_buf == NULL){
return 0;
}
memset(joinlink_scan_buf, 0, 65*sizeof(rtw_scan_result_t));
if((ret = wifi_scan_networks(joinlink_scan_result_handler, joinlink_scan_buf)) != RTW_SUCCESS){
printf("[ATWS]ERROR: wifi scan failed\n\r");
free(joinlink_scan_buf);
return 0;
}
return joinlink_scan_buf;
}
void joinlink_deinit_content()
{
rtw_del_timer(&timer_handler_phase2);
rtw_del_timer(&timer_handler_phase1);
if(all_channel_scan_result)
{
free(all_channel_scan_result);
all_channel_scan_result = NULL;
}
rtw_free_sema(&pre_scan_sema);
joinlink_deinit();
return;
}
static char *jl_itoa(int value)
{
char *val_str;
int tmp = value, len = 1;
while((tmp /= 10) > 0)
len ++;
val_str = (char *) malloc(len + 1);
sprintf(val_str, "%d", value);
return val_str;
}
static void get_ip_str(int *ip_int, char *ip_ch)
{
char *ip_single = NULL;
u8 pos = 0, len = 0;
for(int i = 0; i < 4; i++)
{
ip_single = jl_itoa(ip_int[i]);
len = strlen(ip_single);
memcpy(ip_ch + pos, ip_single,len);
free(ip_single);
ip_single = NULL;
pos += len;
if(i == 3)
{
*(ip_ch + pos) = 0;
break;
}
*(ip_ch + pos) = '.';
pos++;
}
}
static int joinlink_set_ack_content(u8 check_sum)
{
cJSON_Hooks memoryHook;
memoryHook.malloc_fn = malloc;
memoryHook.free_fn = free;
cJSON_InitHooks(&memoryHook);
if(ack_content != NULL)
{
cJSON_Delete(ack_content);
ack_content = NULL;
}
if((ack_content = cJSON_CreateObject()) != NULL)
{
char mac_str[18];
u8 pos = 0;
memset(mac_str, 0, sizeof(mac_str));
for(int i = 0; i < 6; i++)
{
sprintf(mac_str + pos, "%02x", xnetif[0].hwaddr[i]);
pos += 2;
if(i != 5)
mac_str[pos++] = ':';
}
cJSON_AddItemToObject(ack_content, "deviceid", cJSON_CreateString(mac_str));
cJSON_AddItemToObject(ack_content, "code", cJSON_CreateNumber(check_sum));
}
else
{
printf("create jSON object failure\n");
return -1;
}
return 0;
}
#if 1
static void recv_cmd(void *para)
{
int rev_len = 0;
char pkt_buf[16];
while(1)
{
vTaskDelay(500);
if((rev_len = recvfrom(ack_socket, pkt_buf, sizeof(pkt_buf), 0, NULL, NULL)) >= 0)
{
if(memcmp(pkt_buf, header_cmd, sizeof(header_cmd)) == 0)
{
printf("received reboot command, restart join_link process\n");
// do we need to reboot?
example_joinlink();
close(ack_socket);
break;
}
}
}
vTaskDelete(NULL);
return;
}
static int send_ack(int *dest_ip, int dest_port, u8 sum)
{
#if CONFIG_LWIP_LAYER
int ack_transmit_round;
char ip[16];
char *jsonString = NULL;
int sended_data = 0;
if(joinlink_set_ack_content(sum) == -1)
return -1;
jsonString = cJSON_Print(ack_content);
if(jsonString == NULL)
{
printf("json string convert failure\n");
cJSON_Delete(ack_content);
return -1;
}
get_ip_str(dest_ip, ip);
ack_socket = socket(PF_INET, SOCK_DGRAM, IP_PROTO_UDP);
if (ack_socket == -1) {
printf("create socket failure\n");
return -1;
}
FD_ZERO(&to_addr);
to_addr.sin_family = AF_INET;
to_addr.sin_port = htons(dest_port);
to_addr.sin_addr.s_addr = htonl(INADDR_ANY);
FD_ZERO(&from_addr);
from_addr.sin_family = AF_INET;
from_addr.sin_port = htons(SOURCE_PORT);
to_addr.sin_addr.s_addr = inet_addr(ip);
if(bind(ack_socket, (struct sockaddr *)&from_addr, sizeof(from_addr)) < 0)
{
printf("bind to source port error\n");
return -1;
}
for (ack_transmit_round = 0; ack_transmit_round < 5; ack_transmit_round++) {
sended_data = sendto(ack_socket, (unsigned char *)jsonString, strlen(jsonString), 0, (struct sockaddr *) &to_addr, sizeof(struct sockaddr));
//printf("\r\nAlready send %d bytes data\n", sended_data);
vTaskDelay(100); /* delay 100 ms */
}
if(xTaskCreate(recv_cmd, (char const *)"recv_cmd", 1512, NULL, tskIDLE_PRIORITY + 2, NULL) != pdPASS)
printf("%s xTaskCreate failed\n", __FUNCTION__);
close(ack_socket);
if(jsonString)
{
free(jsonString);
jsonString = NULL;
}
cJSON_Delete(ack_content);
#endif
return 0;
}
#endif
static void remove_filter()
{
wifi_disable_packet_filter(1);
wifi_disable_packet_filter(2);
wifi_remove_packet_filter(1);
wifi_remove_packet_filter(2);
}
int joinlink_finish(unsigned char security_type)
{
int ret = 0;
int retry = 3;
unsigned char pscan_config = 1;
joinlink_result_t result;
rtw_security_t security_mode;
wifi_set_promisc(RTW_PROMISC_DISABLE,NULL,0);
remove_filter();
pscan_config = PSCAN_ENABLE | PSCAN_SIMPLE_CONFIG;
ret = joinlink_get_result(&result);
if (ret == 0) {
printf("get result OK\n");
//printf("\r\n joinlink get result ok,ssid = %s, pwd = %s,ssid length = %d,pwd length = %d",
// result.ssid, result.pwd, result.ssid_length,result.pwd_length);
}
else{
printf("joinlink result not get!\n");
joinlink_deinit_content();
return -1;
}
//ap security type
switch(security_type){
case RTW_ENCRYPTION_OPEN:
security_mode = RTW_SECURITY_OPEN;
break;
case RTW_ENCRYPTION_WEP40:
case RTW_ENCRYPTION_WEP104:
security_mode = RTW_SECURITY_WEP_PSK;
break;
case RTW_ENCRYPTION_WPA_TKIP:
case RTW_ENCRYPTION_WPA_AES:
case RTW_ENCRYPTION_WPA2_TKIP:
case RTW_ENCRYPTION_WPA2_AES:
case RTW_ENCRYPTION_WPA2_MIXED:
security_mode = RTW_SECURITY_WPA2_AES_PSK;
break;
case RTW_ENCRYPTION_UNKNOWN:
case RTW_ENCRYPTION_UNDEF:
default:
printf("unknow security mode,connect fail!\n");
}
#if 1
while(1){
if(wifi_set_pscan_chan(&lock_channel, &pscan_config, 1) < 0){
printf("ERROR: wifi set partial scan channel fail\n");
break;
}
printf("wifi_connect\n");
//printf("ap_bssid: 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x\n", ap_bssid[0],ap_bssid[1],ap_bssid[2],ap_bssid[3],ap_bssid[4],ap_bssid[5]);
ret = wifi_connect((unsigned char *)result.ssid, security_mode,
(unsigned char *)result.pwd, result.ssid_length,
result.pwd_length,
0,NULL);
if(ret == RTW_SUCCESS){
printf("Connect ok!\n");
#if CONFIG_LWIP_LAYER
/* If not rise priority, LwIP DHCP may timeout */
vTaskPrioritySet(NULL, tskIDLE_PRIORITY + 3);
/* Start DHCP Client */
ret = LwIP_DHCP(0, DHCP_START);
vTaskPrioritySet(NULL, tskIDLE_PRIORITY + 1);
#endif
break;
}
if (retry == 0) {
break;
}
retry--;
}
if(send_ack(result.source_ip, result.source_port, result.sum) != 0)
printf("send ack failure\n");
#endif
joinlink_deinit_content();
return 0;
}
// handler for phase2
void timer_handler_phase2_func(void *FunctionContext)
{
// do not switch channel while handle frames, wf, 1021
if(jl_rx_flag){
rtw_set_timer(&timer_handler_phase2, CHANNEL_SWITCH_TIME - 25);
} else {
if(cur_channel >= 13)
{cur_channel = 1;}
else
cur_channel ++;
wifi_set_channel(cur_channel);
rtw_set_timer(&timer_handler_phase2, CHANNEL_SWITCH_TIME);
}
//printf("phase2:wifi switch channel to %d\n",cur_channel);
return;
}
// timer handler for the 1st phase, wf, 1022
void timer_handler_phase1_func(void *FunctionContext)
{
// do not switch channel while handle frames, wf, 1021
if(jl_rx_flag){
rtw_set_timer(&timer_handler_phase1, SSID_SWITCH_TIME - 25);
}
// switch ssid, wf, 1022
else
{
if(idx >= 14)
{
phase1_finished = 1;
printf("wifi: phase1 scan finished\n");
printf("wifi: start phase2 scan\n");
// move from pkt handler to here in case no pkt to trigue phase2
#if 1
if(phase1_finished)
{
phase1_finished = 0;
phase2_started = 1;
rtw_cancel_timer(&timer_handler_phase1);
//start phase2 for ch1~ch13
cur_channel = 1;
wifi_set_channel(cur_channel);
rtw_init_timer(&timer_handler_phase2, NULL, &timer_handler_phase2_func, NULL, "phase_2");
rtw_set_timer(&timer_handler_phase2, CHANNEL_SWITCH_TIME);
}
#endif
return;
}
while(idx < 14)
{
if(phase1_scanned_channel[idx])
{
wifi_set_channel(idx);
rtw_set_timer(&timer_handler_phase1, SSID_SWITCH_TIME);
//printf("phase1: wifi switch channel to %d\n",idx);
idx++;
break;
}
else
{
if(idx == 13)
rtw_set_timer(&timer_handler_phase1, SSID_SWITCH_TIME);
idx++;
}
}
}
return;
}
static void rtl_frame_recv_handle(unsigned char *buf, int len, unsigned char *da, unsigned char *sa, void *user_data) {
int ret = 0;
int fixed_channel;
char scanned_ssid[50] = {0};
unsigned char *current_bssid = NULL;
int scanned_ssid_len = 0;
//set this flag prevent joinlink_recv interruptted by timer,since timer has higher priority
jl_rx_flag = 1;
if (joinlink_finished) {
jl_rx_flag = 0;
return;
}
ret = joinlink_recv(da, sa, len, user_data);
if(ret == JOINLINK_STATUS_CHANNEL_LOCKED)
{
if(phase2_started)
{
phase2_started = 0;
rtw_cancel_timer(&timer_handler_phase2);
}
else
rtw_cancel_timer(&timer_handler_phase1);
lock_channel = cur_channel;
security_type = ((ieee80211_frame_info_t *)user_data)->encrypt;
printf("JoinLink locked to channel[%d]\n",lock_channel);
current_bssid = buf + 4 + ETH_ALEN;
memcpy(ap_bssid, current_bssid, 6);
fixed_channel = promisc_get_fixed_channel(current_bssid, scanned_ssid, &scanned_ssid_len);
if (fixed_channel != 0) {
printf("JoinLink force fixed to channel[%d]\r\n",fixed_channel);
printf("JoinLink ssid scanned[%s]\r\n",scanned_ssid);
wifi_set_channel(fixed_channel);
}
}
else if(ret == JOINLINK_STATUS_COMPLETE){
//wifi_set_promisc(RTW_PROMISC_DISABLE,NULL,0);
joinlink_finished = 1;
printf("quit promisc mode!\r\n");
}
//release flag
jl_rx_flag = 0;
return;
}
// callback for promisc packets, like rtk_start_parse_packet in SC, wf, 1021
void wifi_promisc_rx(unsigned char* buf, unsigned int len, void* user_data)
{
unsigned char * da = buf;
unsigned char * sa = buf + ETH_ALEN;
if (joinlink_finished)
return;
rtl_frame_recv_handle(buf, len, da, sa, user_data);
return;
}
// the entry point for joinlink
void joinlink_process(void *param)
{
while(1)
{
current_time = xTaskGetTickCount();
if(joinlink_finished)
{
printf("joinlink finished\n");
break;
}
if((current_time - start_time) > JOINLINK_TIME * configTICK_RATE_HZ)
{
printf("joinlink timeout\n");
break;
}
vTaskDelay(500);
}
joinlink_finish(security_type);
vTaskDelete(NULL);
return;
}
int joinlink_init_content()
{
int ret = 0;
ret = joinlink_init();
if(ret < 0){
printf("JoinLink init failed!\n");
return ret;
}
memset(phase1_scanned_channel, 0, sizeof(phase1_scanned_channel));
security_type = 0xff;
cur_channel = 1;
lock_channel = 1;
joinlink_finished = 0;
jl_rx_flag = 0;
p_result = NULL;
all_channel_ret = 0;
phase1_finished = 0;
phase2_started = 0;
idx = 1;
rtw_init_sema(&pre_scan_sema, 0);
memset(ap_bssid, 0, sizeof(ap_bssid));
set_aes_key(aes_key, sizeof(aes_key) - 1);
return 0;
}
// ret:1 indicate suc, else fail
int scan_all_channel()
{
all_channel_scan_result = (rtw_scan_result_t *)joinlink_all_scan();
if(all_channel_scan_result == NULL)
return 0;
else
return 1;
}
void get_phase1_channel()
{
p_result = all_channel_scan_result;
while(p_result->channel)
{
if((p_result->channel >= 1) && (p_result->channel <= 13))
phase1_scanned_channel[p_result->channel] = 1;
p_result++;
}
return;
}
// now only accept mcast and bcast pkt
static void filter_add_enable()
{
u8 mask[MASK_SIZE_JOINLINK]={0xFF,0xFF,0xFF};
u8 pattern[MASK_SIZE_JOINLINK]={0x01,0x00,0x5e};
u8 pattern_bcast[MASK_SIZE_JOINLINK]={0xff,0xff,0xff};
rtw_packet_filter_pattern_t packet_filter;
rtw_packet_filter_pattern_t packet_filter_bcast;
rtw_packet_filter_rule_e rule;
packet_filter.offset = 0;
packet_filter.mask_size = 3;
packet_filter.mask = mask;
packet_filter.pattern = pattern;
packet_filter_bcast.offset = 0;
packet_filter_bcast.mask_size = 3;
packet_filter_bcast.mask = mask;
packet_filter_bcast.pattern = pattern_bcast;
rule = RTW_POSITIVE_MATCHING;
wifi_init_packet_filter();
wifi_add_packet_filter(1, &packet_filter,rule);
wifi_add_packet_filter(2, &packet_filter_bcast,rule);
wifi_enable_packet_filter(1);
wifi_enable_packet_filter(2);
}
void joinlink_start(void *param)
{
joinlink_finished = 0;
start_time = xTaskGetTickCount();
if(xTaskCreate(joinlink_process, (char const *)"JoinLink", 1512, NULL, tskIDLE_PRIORITY + 2, NULL) != pdPASS)
printf("%s xTaskCreate failed\n", __FUNCTION__);
if (joinlink_init_content() < 0)
printf("joinlink init fail!\n");
while(1)
{
if(wifi_is_ready_to_transceive(RTW_STA_INTERFACE) == RTW_SUCCESS)
break;
else
vTaskDelay(3000);
}
all_channel_ret = scan_all_channel();
if (rtw_down_sema(&pre_scan_sema) == _FAIL)
printf("%s, Take Semaphore Fail\n", __FUNCTION__);
//printf("\npre scan finished\n");
//set wifi to station mode,enable promisc mode and timer to change channel
wifi_enter_promisc_mode();
filter_add_enable();
/* enable all 802.11 packets*/
wifi_set_promisc(RTW_PROMISC_ENABLE, wifi_promisc_rx, 1);
//init timer handler,and set timer hanler funcion
if(all_channel_ret)
{
printf("\nstart the phase1 scan\n");
get_phase1_channel();
rtw_init_timer(&timer_handler_phase1, NULL, &timer_handler_phase1_func, NULL, "phase1_timer");
rtw_set_timer(&timer_handler_phase1, SSID_SWITCH_TIME);
}
else
{
printf("phase1 scan fail, start phase2 scan\n");
rtw_init_timer(&timer_handler_phase2, NULL, &timer_handler_phase2_func, NULL, "phase2_timer");
wifi_set_channel(cur_channel);
rtw_set_timer(&timer_handler_phase2, CHANNEL_SWITCH_TIME);
}
vTaskDelete(NULL);
return;
}
void example_joinlink(void)
{
if(xTaskCreate(joinlink_start, (char const *)"JoinLink_entry", 1512, NULL, tskIDLE_PRIORITY + 2, NULL) != pdPASS)
printf("%s xTaskCreate failed\n", __FUNCTION__);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,64 @@
/******************************* joinlink **************************/
#ifndef __JOINLINK_H
#define __JOINLINK_H
#include "autoconf.h"
#include "platform_stdlib.h"
#include "wifi_conf.h"
#include "wifi_structures.h"
#include "osdep_service.h"
#include "lwip_netconf.h"
#include "task.h"
#include "hal_crypto.h"
#define SSID_SWITCH_TIME 500 //ssid switch time in phase1,units:ms, 50
#define CHANNEL_SWITCH_TIME 500 //channel switch time in phase2,units:ms, 50
#define JOINLINK_TIME 120 //timeout for joinlink process, units: s
/*
* store AP profile after successfully decode
* SUM +£¨length£¬pass£©+£¨IP+Port£©+£¨length£¬SSID)
*/
typedef struct
{
unsigned char sum;
unsigned char pwd_length;
char pwd[65];
int source_ip[4];
unsigned int source_port;
unsigned char ssid_length;
char ssid[65];
} joinlink_result_t;
/*
* return value of joinlink_recv()
*/
typedef enum
{
JOINLINK_STATUS_CONTINUE = 0,
JOINLINK_STATUS_CHANNEL_LOCKED = 1,
JOINLINK_STATUS_COMPLETE = 2
} joinlink_status_t;
//initialize the related data structure
int joinlink_init();
/*
handler to decode pkt
*/
joinlink_status_t joinlink_recv(unsigned char *da, unsigned char *sa, int len, void *user_data);
/*
* get the AP profile after decode
*/
int joinlink_get_result(joinlink_result_t *result);
/*
* set the aes_key, the max len should be 16
* ret 1: success; ret 0: the len is invalid;
*/
int set_aes_key(char *key, int len);
// call this after finish join_link process
void joinlink_deinit();
#endif //__JOINLINK_H

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,264 @@
#include "osdep_api.h"
#include "serial_api.h"
#include <timer_api.h>
#include "freertos_pmu.h"
#include <mDNS/mDNS.h>
/******************************************************
* Macros
******************************************************/
#define UA_ERROR 0
#define UA_WARNING 1
#define UA_INFO 2
#define UA_DEBUG 3
#define UA_NONE 0xFF
#define UA_DEBUG_LEVEL UA_INFO
#define UA_UART_THREAD_PRIORITY 5
#define UA_UART_THREAD_STACKSIZE 512
#define UA_TCP_SERVER_FD_NUM 1
#define UA_TCP_CLIENT_FD_NUM 1
#define UA_UART_RECV_BUFFER_LEN 8196
#define UA_UART_FRAME_LEN 1400
#define UA_UART_MAX_DELAY_TIME 100
#define UA_CHAT_SOCKET_PORT 5001
#define UA_CONTROL_SOCKET_PORT 6001
#define UA_UART_TX_PIN PA_7
#define UA_UART_RX_PIN PA_6
#define UA_GPIO_LED_PIN PC_5
#define UA_GPIO_IRQ_PIN PC_4
#define UA_CONTROL_PREFIX "AMEBA_UART"
#define UA_PS_ENABLE 0
#define UA_GPIO_WAKEUP_PIN PC_3
#define UA_WAKELOCK WAKELOCK_USER_BASE
#define UA_FAST_RECONNECT_TCP_DATA (0x80000 - 0x2000)
#if (UA_DEBUG_LEVEL== UA_NONE)
#define ua_printf(level, fmt, arg...)
#else
#define ua_printf(level, fmt, arg...) \
do {\
if (level <= UA_DEBUG_LEVEL) {\
if (level <= UA_ERROR) {\
RtlDownSema(&ua_print_sema);\
printf("\r\nERROR: " fmt, ##arg);\
RtlUpSema(&ua_print_sema);\
} \
else {\
RtlDownSema(&ua_print_sema);\
printf("\r\n"fmt, ##arg);\
RtlUpSema(&ua_print_sema);\
} \
}\
}while(0)
#endif
#define UA_PRINT_DATA(_HexData, _HexDataLen) \
if(UA_DEBUG_LEVEL == UA_DEBUG) \
{ \
int __i; \
u8 *ptr = (u8 *)_HexData; \
printf("--------Len=%d\n\r", _HexDataLen); \
for( __i=0; __i<(int)_HexDataLen; __i++ ) \
{ \
printf("%02X%s", ptr[__i], (((__i + 1) % 4) == 0)?" ":" "); \
if (((__i + 1) % 16) == 0) printf("\n\r"); \
} \
printf("\n\r"); \
}
#define UA_SOCKET_CHECK(_ua_socket) \
if(_ua_socket == NULL) \
{ \
printf("ERROR: ua_socket = NULL\n\r"); \
return; \
}
#define UA_SOCKET_CHECK_2(_ua_socket) \
if(_ua_socket == NULL) \
{ \
printf("ERROR: ua_socket = NULL\n\r"); \
return -1; \
}
/******************************************************
* Constants
******************************************************/
typedef enum
{
UART_ADAPTER_LED_ON = 0,
UART_ADAPTER_LED_OFF = 1,
UART_ADAPTER_LED_FAST_TWINKLE = 2,
UART_ADAPTER_LED_SLOW_TWINKLE = 3,
}ua_led_mode_t;
typedef enum
{
UART_CTRL_MODE_SET_REQ = 0,
UART_CTRL_MODE_SET_RSP = 1,
UART_CTRL_MODE_GET_REQ = 2,
UART_CTRL_MODE_GET_RSP = 3,
}ua_ctrl_mode_t;
typedef enum
{
UART_CTRL_TYPE_BAUD_RATE = 0x01,
UART_CTRL_TYPE_WORD_LEN = 0x02,
UART_CTRL_TYPE_PARITY = 0x04,
UART_CTRL_TYPE_STOP_BIT = 0x08,
UART_CTRL_TYPE_TCP_SERVER_CREATE = 0x10,
UART_CTRL_TYPE_TCP_SERVER_DELETE = 0x20,
UART_CTRL_TYPE_TCP_CLIENT_CONNECT = 0x40,
UART_CTRL_TYPE_TCP_CLIENT_DISCONNECT = 0x80,
UART_CTRL_TYPE_TCP_GROUP_ID = 0x100,
}ua_ctrl_type_t;
enum sc_result {
SC_ERROR = -1, /* default error code*/
SC_NO_CONTROLLER_FOUND = 1, /* cannot get sta(controller) in the air which starts a simple config session */
SC_CONTROLLER_INFO_PARSE_FAIL, /* cannot parse the sta's info */
SC_TARGET_CHANNEL_SCAN_FAIL, /* cannot scan the target channel */
SC_JOIN_BSS_FAIL, /* fail to connect to target ap */
SC_DHCP_FAIL, /* fail to get ip address from target ap */
/* fail to create udp socket to send info to controller. note that client isolation
must be turned off in ap. we cannot know if ap has configured this */
SC_UDP_SOCKET_CREATE_FAIL,
SC_SUCCESS, /* default success code */
};
/******************************************************
* Structures
******************************************************/
typedef struct _ua_uart_param_t
{
u8 WordLen;
u8 Parity;
u8 StopBit;
u8 FlowControl;
int BaudRate;
}ua_uart_param_t;
typedef struct _ua_uart_socket_t
{
int fd;
char rcv_ch;
volatile char overlap;
int recv_bytes;
volatile int pread;
volatile int pwrite;
volatile unsigned int tick_last_update;
unsigned int tick_current;
volatile int tx_busy;
volatile int uart_ps;
volatile int uart_ps_cnt;
char recv_buf[UA_UART_RECV_BUFFER_LEN];
long rx_cnt;
long miss_cnt;
serial_t uart_sobj;
ua_uart_param_t uart_param;
_Sema action_sema;
_Sema tcp_tx_rx_sema;
_Sema dma_tx;
}ua_uart_socket_t;
typedef struct _ua_tcp_socket_t
{
int chat_socket;
int control_socket;
int chat_server_listen_socket;
int control_server_listen_socket;
int transmit_recv_socket;
int transmit_send_socket;
int transmit_server_listen_socket;
int group_id;
u32 server_port;
u32 client_port;
char client_ip[16];
int send_flag;
int recv_flag;
long rx_cnt;
long tx_cnt;
volatile int tcp_ps;
volatile int tcp_ps_cnt;
}ua_tcp_socket_t;
typedef struct _ua_gpio_t
{
gpio_t gpio_led;
gpio_t gpio_btn;
gpio_irq_t gpio_btn_irq;
gtimer_t gpio_timer;
}ua_gpio_t;
typedef struct _ua_socket_t
{
ua_uart_socket_t uart;
ua_tcp_socket_t tcp;
ua_gpio_t gpio;
ip_addr_t ip;
DNSServiceRef dnsServiceRef;
DNSServiceRef dnsServiceRef2;
}ua_socket_t;
typedef struct _ua_mbox_buffer
{
char data[UA_UART_FRAME_LEN];
int data_len;
}ua_mbox_buffer_t;
//Save Uart Settings when get uart information
typedef struct _ua_uart_get_str
{
int BaudRate; //The baud rate
char number; //The number of data bits
char parity; //The parity(0: none, 1:odd, 2:evn, default:0)
char StopBits; //The number of stop bits
char FlowControl; //support flow control is 1
}ua_uart_get_str;
//Uart Setting information
typedef struct _ua_uart_set_str
{
char UartName[8]; // the name of uart
int BaudRate; //The baud rate
char number; //The number of data bits
char parity; //The parity(default NONE)
char StopBits; //The number of stop bits
char FlowControl; //support flow control is 1
}ua_uart_set_str;
int uartadapter_init();
void uartadapter_tcp_send_data(ua_socket_t *ua_socket, char *buffer, int size);
void uartadapter_tcp_send_control(ua_socket_t *ua_socket, char *buffer, int size);
void uartadapter_tcp_transmit_server_thread(void *param);
void uartadapter_tcp_transmit_client_thread(void *param);
int uartadapter_tcpclient(ua_socket_t *ua_socket, const char *host_ip, unsigned short usPort);
void uartadapter_tcp_transmit_client_forever_thread(void *param);
void example_uart_adapter_init();
void cmd_uart_adapter(int argc, char **argv);
void uartadapter_tcp_transmit_socket_handler(ua_socket_t *ua_socket, char *tcp_rxbuf);

View file

@ -0,0 +1,82 @@
#include "FreeRTOS.h"
#include "task.h"
#include "wifi_conf.h"
#include "wifi_ind.h"
#include "google_nest.h"
#include "flash_api.h"
#include "wigadget.h"
#include <lwip/netif.h>
#include "shtc1.h"
#define CLOUD_PORT 443
extern struct netif xnetif[NET_IF_NUM];
void cloud_link_task(void *param){
googlenest_context googlenest;
unsigned char URI[64];
unsigned char data[97] = {0};
unsigned char host_addr[64] = {0};
flash_t cloud_flash;
u8 *mac = (u8 *)LwIP_GetMAC(&xnetif[0]);
char i[16], j[16];
float temperature = 1.123f;
float humidity = 2.456f;
int ret = 0;
vTaskDelay(2000);
sprintf(URI, "ht_sensor/%02x%02x%02x%02x%02x%02x.json", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
memset(host_addr, 0, sizeof(host_addr));
if(flash_stream_read(&cloud_flash, FLASH_IOT_DATA, 97, (uint8_t *) data) == 1){
memset(host_addr, 0 , 64);
memcpy(host_addr, data+33, 64);
while(1) {
printf("\r\n\r\n\r\n\r\n\r\n\r\n=====>START CLOUD LINKING\r\n\r\n");
memset(i, 0, 16);
memset(j, 0, 16);
#if PSEUDO_DATA
sprintf(i,"%.2f", temperature++);
sprintf(j, "%.2f", humidity++);
if(temperature > 60)
temperature = 1.123f;
if(humidity > 98)
humidity = 2.456f;
#else
ret = SHTC_GetTempAndHumi(&temperature, &humidity);
sprintf(i,"%.2f", temperature);
sprintf(j, "%.2f", humidity);
#endif
if(ret < 0)
printf("\r\n\r\n<-----LOCAL LINK FAILED!!(get infor failed)\r\n\r\n");
else{
gen_json_data(i,j, data);
printf("\r\nCLOUD-LINK--Sending data : \r\n%s\r\n", data);
memset(&googlenest, 0, sizeof(googlenest_context));
if(gn_connect(&googlenest, host_addr, CLOUD_PORT) == 0) {
if(gn_put(&googlenest, URI, data) != 0)
printf("\r\n\r\nPUT data failed!\r\n\r\n");
gn_close(&googlenest);
printf("\r\n\r\n<=====CLOUD LINK OK!!\r\n\r\n");
}
else{
printf("\r\n\r\n<=====CLOUD LINK FAILED!!(google nest connecting)\r\n\r\n");
}
free(data);
vTaskDelay(10000);
}
}
}
else
printf("\r\n\r\n<=====CLOUD LINK FAILED!!(flash reading)\r\n\r\n");
}
void start_cloud_link(void)
{
if(xTaskCreate(cloud_link_task, ((const char*)"cloud_link_task"), 3584, NULL, tskIDLE_PRIORITY + 4, NULL) != pdPASS)
printf("\n\r%s xTaskCreate failed", __FUNCTION__);
}

View file

@ -0,0 +1,11 @@
#ifndef CLOUD_LINK_H
#define CLOUD_LINK_THREAD_H
#include "wigadget.h"
void start_cloud_link(void);
void cloud_link_task(void *param);
#endif

View file

@ -0,0 +1,185 @@
#include "device.h"
#include "PinNames.h"
#include "basic_types.h"
#include "diag.h"
#include "osdep_api.h"
#include "i2c_api.h"
#include "pinmap.h"
#include "shtc1.h"
#define MBED_I2C_MTR_SDA PB_3
#define MBED_I2C_MTR_SCL PB_2
#define MBED_I2C_SLAVE_ADDR0 0x70
#define POLYNOMIAL 0x131 // P(x) = x^8 + x^5 + x^4 + 1 = 100110001
#define MBED_I2C_BUS_CLK 100000 //hz
#define I2C_DATA_MAX_LENGTH 16
static uint8_t i2cdata_write[I2C_DATA_MAX_LENGTH];
static uint8_t i2cdata_read[I2C_DATA_MAX_LENGTH];
static int i2cdata_read_pos;
static i2c_t i2cmaster;
// Sensor Commands
#define READ_ID 0xEFC8 // command: read ID register
#define SOFT_RESET 0x805D // soft resetSample Code for SHTC1
#define MEAS_T_RH_POLLING 0x7866 // meas. read T first, clock stretching disabled
#define MEAS_T_RH_CLOCKSTR 0x7CA2 // meas. read T first, clock stretching enabled
#define MEAS_RH_T_POLLING 0x58E0 // meas. read RH first, clock stretching disabled
#define MEAS_RH_T_CLOCKSTR 0x5C24 // meas. read RH first, clock stretching enabled
static int SHTC1_GetID(uint16_t *id);
static void SHTC1_WriteCommand(uint16_t cmd);
static int SHTC1_Read2BytesAndCrc(uint16_t *data);
static int SHTC1_CheckCrc(uint8_t data[], uint8_t nbrOfBytes, uint8_t checksum);
static float SHTC1_CalcTemperature(uint16_t rawValue);
static float SHTC1_CalcHumidity(uint16_t rawValue);
int SHTC_Init(uint16_t *pID)
{
int error = NO_ERROR;
DiagPrintf("SHTC1_Init \r\n");
i2c_init((i2c_t*)&i2cmaster, MBED_I2C_MTR_SDA ,MBED_I2C_MTR_SCL);
i2c_frequency((i2c_t*)&i2cmaster,MBED_I2C_BUS_CLK);
if (pID == NULL )
return NULL_ERROR;
error = SHTC1_GetID(pID);
return error;
}
static int SHTC1_GetID(uint16_t *id)
{
int error = NO_ERROR;
uint8_t bytes[2];
uint8_t checksum;
SHTC1_WriteCommand(READ_ID);
i2c_read((i2c_t*)&i2cmaster, MBED_I2C_SLAVE_ADDR0, (char*)&i2cdata_read[0], 3, 1);
i2cdata_read_pos = 0;
error = SHTC1_Read2BytesAndCrc(id);
return error;
}
static int SHTC1_Read2BytesAndCrc(uint16_t *data)
{
int error;
int readed;
uint8_t bytes[2];
uint8_t checksum;
bytes[0] = i2cdata_read[i2cdata_read_pos++];
bytes[1] = i2cdata_read[i2cdata_read_pos++];
checksum = i2cdata_read[i2cdata_read_pos++];
error = SHTC1_CheckCrc(bytes, 2, checksum);
*data = (bytes[0] << 8) | bytes[1];
return error;
}
static int SHTC1_CheckCrc(uint8_t data[], uint8_t nbrOfBytes, uint8_t checksum)
{
uint8_t bit; // bit mask
uint8_t crc = 0xFF; // calculated checksum
uint8_t byteCtr; // byte counter
for(byteCtr = 0; byteCtr < nbrOfBytes; byteCtr++){
crc ^= (data[byteCtr]);
for(bit = 8; bit > 0; --bit){
if(crc & 0x80)
crc = (crc << 1) ^ POLYNOMIAL;
else
crc = (crc << 1);
}
}
if(crc != checksum)
return CHECKSUM_ERROR;
else
return NO_ERROR;
}
static void SHTC1_WriteCommand(uint16_t cmd)
{
int writebytes;
i2cdata_write[0] = (uint8_t)(cmd >>8);
i2cdata_write[1] = (uint8_t)(cmd&0xFF);
i2c_write((i2c_t*)&i2cmaster, MBED_I2C_SLAVE_ADDR0, &i2cdata_write[0], 2, 1);
}
static float SHTC1_CalcTemperature(uint16_t rawValue)
{
return 175.0 * (float)rawValue / 65536.0 - 45.0;
}
static float SHTC1_CalcHumidity(uint16_t rawValue)
{
return 100.0 * (float)rawValue / 65536.0;
}
int SHTC_GetTempAndHumi(float *temp, float *humi)
{
int error;
uint16_t rawValueTemp;
uint16_t rawValueHumi;
SHTC1_WriteCommand(MEAS_T_RH_CLOCKSTR);
i2c_read((i2c_t*)&i2cmaster, MBED_I2C_SLAVE_ADDR0, (char*)&i2cdata_read[0], 6, 1);
i2cdata_read_pos = 0;
error = NO_ERROR;
error |= SHTC1_Read2BytesAndCrc(&rawValueTemp);
error |= SHTC1_Read2BytesAndCrc(&rawValueHumi);
if ( error == NO_ERROR ) {
*temp = SHTC1_CalcTemperature(rawValueTemp);
*humi = SHTC1_CalcHumidity(rawValueHumi);
}
return error;
}
static void example_shtc1_thread(void *param)
{
int error;
uint16_t shtc1_id;
float temperature = 1.123f;
float humidity = 2.456f;
DBG_8195A("sleep 10 sec. to wait for UART console\n");
RtlMsleepOS(10000);
DBG_8195A("start i2c example - SHTC1\n");
error = SHTC_Init(&shtc1_id);
if ( error == NO_ERROR )
DiagPrintf("SHTC1 init ok, id=0x%x\r\n", shtc1_id);
else {
DiagPrintf("SHTC1 init FAILED! \r\n");
for(;;);
}
while(1){
error = SHTC_GetTempAndHumi(&temperature, &humidity);
rtl_printf("temp=%f, humidity=%f, error=%d\n", temperature, humidity, error);
RtlMsleepOS(1000);
}
}
void example_shtc1(void)
{
if(xTaskCreate(example_shtc1_thread, ((const char*)"example_shtc1_thread"), 512, NULL, tskIDLE_PRIORITY + 1, NULL) != pdPASS)
printf("\n\r%s xTaskCreate(init_thread) failed", __FUNCTION__);
}

View file

@ -0,0 +1,13 @@
#ifndef SHTC1_H
#define SHTC1_H
#define NO_ERROR 0x00
#define ACK_ERROR 0x01
#define CHECKSUM_ERROR 0x02
#define NULL_ERROR 0x03
int SHTC_GetTempAndHumi(float *temp, float *humi);
int SHTC_Init(uint16_t *pID);
void example_shtc1(void);
#endif

View file

@ -0,0 +1,727 @@
#include "FreeRTOS.h"
#include "task.h"
#include "wifi_conf.h"
#include "wifi_ind.h"
#include "sockets.h"
#include <mDNS/mDNS.h>
#include <lwip_netconf.h>
#include <lwip/netif.h>
#include "flash_api.h"
#include <rom_wac_aes.h>
#include "rom_wac_curve25519-donna.h"
#include "gpio_api.h"
#include "gpio_irq_api.h"
#include "cJSON.h"
#include "cloud_link.h"
#include "wigadget.h"
#include "shtc1.h"
#define PORT 6866
#define MAX_BUFFER_SIZE 256
#define ENC_SIZE 64
#define CONTROL_TYPE 1
#define GPIO_SOFTAP_RESET_PIN PC_4
flash_t iot_flash;
uint8_t aes_key[16];
static unsigned char tx_buffer[MAX_BUFFER_SIZE];
static unsigned char rx_buffer[MAX_BUFFER_SIZE];
extern struct netif xnetif[NET_IF_NUM];
#define DEBUG_IOT 1
#define IOT_LOG(level, fmt, ...) printf("\n\r[IOT %s] %s: " fmt "\n", level, __FUNCTION__, ##__VA_ARGS__)
#if DEBUG_IOT == 2
#define IOT_DEBUG(fmt, ...) IOT_LOG("DEBUG", fmt, ##__VA_ARGS__)
#else
#define IOT_DEBUG(fmt, ...)
#endif
#if DEBUG_IOT
#define IOT_ERROR(fmt, ...) IOT_LOG("ERROR", fmt, ##__VA_ARGS__)
#else
#define IOT_ERROR(fmt, ...)
#endif
void encrypt_data_aes(unsigned char *plaint_text, unsigned char *enc_data);
void decrypt_data_aes(unsigned char *enc_data, unsigned char *dec_data, int data_len);
static unsigned int arc4random(void)
{
unsigned int res = xTaskGetTickCount();
static unsigned int seed = 0xDEADB00B;
seed = ((seed & 0x007F00FF) << 7) ^
((seed & 0x0F80FF00) >> 8) ^ // be sure to stir those low bits
(res << 13) ^ (res >> 9); // using the clock too!
return seed;
}
static char *iot_itoa(int value)
{
char *val_str;
int tmp = value, len = 1;
while((tmp /= 10) > 0)
len ++;
val_str = (char *) malloc(len + 1);
sprintf(val_str, "%d", value);
return val_str;
}
void gen_json_data(char *i, char *j, unsigned char *json_data)
{
cJSON_Hooks memoryHook;
memoryHook.malloc_fn = malloc;
memoryHook.free_fn = free;
cJSON_InitHooks(&memoryHook);
memset(json_data, 0, ENC_SIZE);
cJSON *IOTJSObject = NULL;
char *data;
if((IOTJSObject = cJSON_CreateObject()) != NULL) {
cJSON_AddItemToObject(IOTJSObject, "TEM", cJSON_CreateString(i));
cJSON_AddItemToObject(IOTJSObject, "HUM", cJSON_CreateString(j));
data = cJSON_Print(IOTJSObject);
memcpy(json_data, data, strlen(data));
cJSON_Delete(IOTJSObject);
free(data);
}
}
void encrypt_data_aes(unsigned char *plaint_text, unsigned char *enc_data)
{
unsigned char iv[16] = {0};
unsigned char* iv_bak = "AAAAAAAAAAAAAAAA";
aes_encrypt_ctx enc_ctx;
memset(&enc_ctx, 0, sizeof(enc_ctx));
memset(iv, 0, sizeof(iv));
memcpy(iv, iv_bak, sizeof(iv));
memset(enc_data, 0, sizeof(enc_data));
aes_init();
aes_encrypt_key(aes_key, 16, &enc_ctx);
aes_cbc_encrypt(plaint_text, enc_data, ENC_SIZE, iv, &enc_ctx);
}
void decrypt_data_aes(unsigned char *enc_data, unsigned char *dec_data, int data_len)
{
unsigned char iv[16] = {0};
unsigned char* iv_bak = "AAAAAAAAAAAAAAAA";
aes_decrypt_ctx dec_ctx;
memset(&dec_ctx, 0, sizeof(dec_ctx));
memset(iv, 0, sizeof(iv));
memcpy(iv, iv_bak, sizeof(iv));
memset(dec_data, 0, sizeof(dec_data));
aes_init();
aes_decrypt_key(aes_key, 16, &dec_ctx);
aes_cbc_decrypt(enc_data, dec_data, data_len, iv, &dec_ctx);
IOT_DEBUG("Decrypt data: %s\r\n",dec_data);
}
void iotapp_platform_reset(void)
{
HAL_WRITE32(SYSTEM_CTRL_BASE, 0x14, 0x00000021);
osDelay(100);
HAL_WRITE32(0xE000ED00, 0x0C, (0x5FA << 16) |
(HAL_READ32(0xE000ED00, 0x0C) & (7 << 8)) |
(1 << 2));
while(1) osDelay(1000);
}
void iotapp_reset_irq_handler(uint32_t id, gpio_irq_event event)
{
printf("\n\r\n\r\n\r\n\r<<<<<<Reset the device using PC_4>>>>>>>\n\r\n\r\n\r\n\r");
flash_erase_sector(&iot_flash, FLASH_IOT_DATA);
iotapp_platform_reset();
}
int local_link(unsigned char *tx_data)
{
int sockfd, newsockfd;
socklen_t client;
struct sockaddr_in serv_addr, cli_addr;
uint8_t rx_data[ENC_SIZE];
unsigned char enc_data[ENC_SIZE];
unsigned char dec_data[ENC_SIZE];
int ret = 0, opt = 1, k = 1, j;
char *result = NULL, *backup = NULL;
unsigned char *data = NULL;
char *delims = ", ";
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
IOT_ERROR("ERROR opening socket");
ret = -1;
goto exit2;
}
if((setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt))) < 0){
IOT_ERROR("ERROR on setting socket option");
ret = -1;
goto exit2;
}
memset((char *)&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(PORT);
if (bind(sockfd, (struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
IOT_ERROR("ERROR on binding");
ret = -1;
goto exit2;
}
if(listen(sockfd , 20) < 0){
IOT_ERROR("ERROR on listening");
ret = -1;
goto exit2;
}
client = sizeof(cli_addr);
if((newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr,&client)) < 0){
IOT_ERROR("ERROR on accept");
ret = -1;
goto exit;
}
if ((ret = read(newsockfd,rx_buffer,sizeof(rx_buffer))) < 0){
IOT_ERROR("ERROR reading from socket");
ret = -1;
goto exit;
}
IOT_DEBUG("cmd received: %s, length: %d\r\n",rx_buffer, ret);
//Changing received data to string
if (!strncmp(rx_buffer, "[", strlen("["))){
data = rx_buffer + strlen("[");
for(j = 1; j < 5; j++){
if (data[ret - j] == ']')
data[ret -j] = '\0';
}
}
else
strcpy(data, rx_buffer);
memset(rx_data, 0, sizeof(rx_data));
result = strtok_r(data, delims, &backup);
rx_data[0]=(uint8_t)atoi(result);
while((result = strtok_r(NULL, delims, &backup)) != NULL)
rx_data[k++]=(uint8_t)atoi(result);
memset(dec_data, 0, sizeof(dec_data));
//Decrpyt the received data
decrypt_data_aes(rx_data, dec_data, 16);
if(strncmp(dec_data, "request", strlen("request")) == 0){
//Encrypt the sending data
memset(enc_data, 0, strlen(enc_data));
encrypt_data_aes(tx_data, enc_data);
//Changing encrpyt data to JAVA type string
for (j = 0; j < ENC_SIZE; j++){
char *temp;
temp = iot_itoa(enc_data[j]);
if(j == 0)
strcpy(tx_buffer, "[");
strcat(tx_buffer,temp);
if (j == (ENC_SIZE - 1))
strcat(tx_buffer,"]");
else
strcat(tx_buffer,",");
free(temp);
temp = NULL;
}
IOT_DEBUG("Data reply to APP: %s\r\nLength of data: %d\r\n", tx_buffer, strlen(tx_buffer));
if ((ret = write(newsockfd,tx_buffer,strlen(tx_buffer))) < 0){
IOT_ERROR("ERROR writing to socket");
ret = -1;
goto exit;
}
else
IOT_DEBUG("Sending %d bytes data OK!\r\n", ret);
}
else if(strncmp(dec_data, "remove", strlen("remove")) == 0){
printf("\n\r\n\r\n\r\n\r<<<<<<Reset the device >>>>>>>\n\r\n\r\n\r\n\r");
flash_erase_sector(&iot_flash, FLASH_IOT_DATA);
write(newsockfd,"Remove OK",strlen("Remove OK"));
close(newsockfd);
close(sockfd);
iotapp_platform_reset();
}
else{
IOT_ERROR("ERROR wrong KEY or wrong request!");
write(newsockfd,"The KEY or the request is not correct!",strlen("The KEY or the request is not correct!"));
ret = -1;
goto exit;
}
exit:
if(close(newsockfd) != 0)
goto exit;
exit2:
if(close(sockfd) != 0)
goto exit2;
return ret;
}
static void local_link_task(void *param)
{
unsigned char data[ENC_SIZE] = {0};
vTaskDelay(1000);
char i[16], j[16];
float temperature = 1.123f;
float humidity = 2.456f;
int ret = 0;
while(1){
memset(i, 0, 16);
memset(j, 0, 16);
#if PSEUDO_DATA
sprintf(i,"%.2f", temperature++);
sprintf(j, "%.2f", humidity++);
if(temperature > 60)
temperature = 1.123f;
if(humidity > 98)
humidity = 2.456f;
#else
ret = SHTC_GetTempAndHumi(&temperature, &humidity);
sprintf(i,"%.2f", temperature);
sprintf(j, "%.2f", humidity);
#endif
if(ret < 0)
printf("\r\n\r\n<-----LOCAL LINK FAILED!!(get infor failed)\r\n\r\n");
else{
printf("\r\n\r\n----->START LOCAL LINKING\r\n\r\n");
gen_json_data(i, j, data);
printf("Sending data : %s\r\n", data);
if (local_link(data) < 0)
printf("\r\n\r\n<-----LOCAL LINK FAILED!!\r\n\r\n");
else
printf("\r\n\r\n<-----LOCAL LINK OK!!\r\n\r\n");
vTaskDelay(1000);
}
}
}
void start_local_link(void)
{
if(xTaskCreate(local_link_task, ((const char*)"local_link_task"), 5376, NULL, tskIDLE_PRIORITY + 4, NULL) != pdPASS)
printf("\n\r%s xTaskCreate failed", __FUNCTION__);
}
int pair_device(unsigned char *tx_buffer, unsigned char *rx_buffer, int handshake)
{
int sockfd, newsockfd;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
int ret = 0;
int opt = 1;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
IOT_ERROR("ERROR opening socket");
ret = -1;
goto exit;
}
if((setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt))) < 0){
IOT_ERROR("ERROR on setting socket option");
ret = -1;
goto exit;
}
memset((char *)&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_len = sizeof(serv_addr);
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(PORT);
if ((bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))) < 0) {
IOT_ERROR("ERROR on binding");
ret = -1;
goto exit;
}
if ((listen(sockfd, 5)) < 0){
IOT_ERROR("ERROR on listening tcp server socket fd");
ret = -1;
goto exit;
}
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, (socklen_t*)&clilen);
if (newsockfd < 0) {
IOT_ERROR("ERROR on accept");
ret = -1;
goto exit2;
}
ret = read(newsockfd, rx_buffer, MAX_BUFFER_SIZE);
if (ret <= 0){
IOT_ERROR("ERROR reading from socket");
ret = -1;
goto exit2;
}
IOT_DEBUG("Request received: %s, byte: %d\r\n",rx_buffer, ret);
if(handshake == 1){
if(strncmp(rx_buffer,"PAIR", strlen("PAIR")) != 0){
write(newsockfd, "ERROR", strlen("ERROR"));
IOT_ERROR("ERROR on first handshake!");
ret = -1;
goto exit2;
}
}
else if(handshake == 2){
if((rx_buffer == NULL) ||(strlen(rx_buffer) < 32)){
write(newsockfd, "ERROR", strlen("ERROR"));
IOT_ERROR("ERROR on second handshake!");
ret = -1;
goto exit2;
}
}
else if(handshake == 3){
unsigned char account[64];
unsigned char enc_acc[64];
char *result = NULL, *backup = NULL;
unsigned char *data = NULL;
char *delims = ", ";
int j, k = 1;
if (!strncmp(rx_buffer, "[", strlen("["))){
data = rx_buffer + strlen("[");
for(j = 1; j < 5; j++){
if (data[ret - j] == ']')
data[ret -j] = '\0';
}
}
else
strcpy(data, rx_buffer);
memset(enc_acc, 0, sizeof(enc_acc));
result = strtok_r(data, delims, &backup);
enc_acc[0]=(uint8_t)atoi(result);
while((result = strtok_r(NULL, delims, &backup)) != NULL)
enc_acc[k++]=(uint8_t)atoi(result);
IOT_DEBUG("The value of k: %d", k);
memset(account, 0, sizeof(account));
decrypt_data_aes(enc_acc, account, k);
if((strncmp(account,"https://", strlen("https://"))) != 0){
write(newsockfd, "ERROR", strlen("ERROR"));
IOT_ERROR("ERROR on third handshake!");
ret = -1;
goto exit2;
}
else{
IOT_DEBUG("The received Firebase URL:%s", account);
memset(rx_buffer, 0, strlen(rx_buffer));
memcpy(rx_buffer, (account+strlen("https://")), (strlen(account) + strlen("https://")));
}
}
ret = write(newsockfd, tx_buffer, strlen(tx_buffer));
IOT_DEBUG("Data send: %s\r\n",tx_buffer);
if (ret < 0){
IOT_ERROR("ERROR writing to socket");
}
exit:
if(close(newsockfd) != 0)
goto exit;
exit2:
if(close(sockfd) != 0)
goto exit2;
return ret;
}
static void pair_device_task(void)
{
int i, j, k, HANDSHAKE;
uint8_t PAIR_STATE[1] = {0};
if(CONTROL_TYPE == 1){
printf("\r\n\r\n<<<<<<CONTROL_TYPE = 1 Need 3 times handshake>>>>>>\r\n\r\n");
HANDSHAKE = 3;
}
else{
printf("\r\n\r\n<<<<<<CONTROL_TYPE = 0 Need 2 times handshake>>>>>>\r\n\r\n");
HANDSHAKE = 2;
}
printf("\r\n\r\n=========>PAIR_STATE = 0 Start to pair\r\n\r\n");
for(i = 0; i < HANDSHAKE; i++){
static const uint8_t basepoint[32] = {9};
uint8_t mysecret[32];
uint8_t mypublic[32];
uint8_t theirpublic[32] = {0};
uint8_t shared_key[32];
//First handshake
if(i == 0){
printf("\r\n\r\n===>Start the first handshake\r\n\r\n");
memset(tx_buffer, 0, sizeof(tx_buffer));
memset(rx_buffer, 0, sizeof(rx_buffer));
for(j = 0; j < 32; j ++)
mysecret[j] = (uint8_t) arc4random();
mysecret[j] = '\0';
curve25519_donna(mypublic, mysecret, basepoint);
for (j = 0; j < 32; j++){
char *temp;
temp = iot_itoa(mypublic[j]);
if(j == 0)
strcpy(tx_buffer, "[");
strcat(tx_buffer,temp);
if (j == 31)
strcat(tx_buffer,"]");
else
strcat(tx_buffer,",");
free(temp);
temp = NULL;
}
if(pair_device(tx_buffer, rx_buffer, 1) >= 0)
printf("\r\n\r\n<===First handshake OK!!\r\n\r\n");
else{
i--;
printf("\r\n\r\n<===First handshake FAILED!!\r\n\r\n");
}
}
//Second handshake
if(i == 1){
printf("\r\n\r\n=====>Start the second handshake\r\n\r\n");
vTaskDelay(200);
memset(tx_buffer, 0, sizeof(tx_buffer));
if(CONTROL_TYPE == 1)
memcpy(tx_buffer, "FIREBASE URL", sizeof("FIREBASE URL"));
else
memcpy(tx_buffer, "PAIR OK", sizeof("PAIR OK"));
memset(rx_buffer, 0, sizeof(rx_buffer));
if(pair_device(tx_buffer, rx_buffer, 2) >= 0){
char *result = NULL, *backup = NULL;
unsigned char *data = NULL;
char *delims = ", ";
k = 1;
if (!strncmp(rx_buffer, "[", strlen("["))){
data = rx_buffer + strlen("[");
int len;
len = strlen(data);
for(j = 1; j < 5; j++){
if (data[len - j] == ']')
data[len -j] = '\0';
}
}
else
strcpy(data, rx_buffer);
memset(theirpublic, 0, sizeof(theirpublic));
result = strtok_r(data, delims, &backup);
theirpublic[0]=(uint8_t)atoi(result);
while((result = strtok_r(NULL, delims, &backup)) != NULL)
theirpublic[k++] = (uint8_t)atoi(result);
curve25519_donna(shared_key, mysecret, theirpublic);
for(j = 0; j < 16; j ++)
aes_key[j] = shared_key[j];
//Store the KEY in FLASH
if(CONTROL_TYPE == 0){
PAIR_STATE[0] = 1;
uint8_t data[33];
memset(data, 0, 33);
memcpy(data, PAIR_STATE, 1);
memcpy(data+1, shared_key, 32);
flash_erase_sector(&iot_flash, FLASH_IOT_DATA);
flash_stream_write(&iot_flash, FLASH_IOT_DATA, 33, (uint8_t *) data);
IOT_DEBUG("PAIR_STATE: %d\r\n", PAIR_STATE[0]);
}
printf("\r\n\r\n<=====Second handshake OK!!\r\n\r\n");
}
else{
i = i - 2;
printf("\r\n\r\n<=====Second handshake FAILED!!\r\n\r\n");
}
}
//Third handshake
if(i == 2){
printf("\r\n\r\n=======>Start the third handshake\r\n\r\n");
vTaskDelay(200);
memset(tx_buffer, 0, sizeof(tx_buffer));
memcpy(tx_buffer, "PAIR OK", sizeof("PAIR OK"));
memset(rx_buffer, 0, sizeof(rx_buffer));
if(pair_device(tx_buffer, rx_buffer, 3) >= 0){
IOT_DEBUG("rx_buffer: %s, sizeof rx_buffer:%d\r\n", rx_buffer, sizeof(rx_buffer));
PAIR_STATE[0] = 1;
uint8_t data[97];
memset(data, 0, 97);
memcpy(data, PAIR_STATE, 1);
memcpy(data+1, shared_key, 32);
memcpy(data+33, rx_buffer, 64);
flash_erase_sector(&iot_flash, FLASH_IOT_DATA);
flash_stream_write(&iot_flash, FLASH_IOT_DATA, 97, (uint8_t *) data);
IOT_DEBUG("PAIR_STATE: %d\r\n", PAIR_STATE[0]);
printf("\r\n\r\n<=======Third handshake OK!!\r\n\r\n");
}
else{
i = i - 3;
printf("\r\n\r\n<=======Third handshake FAILED!!\r\n\r\n");
}
}
}
printf("\r\n\r\n<=========Pairing OK!!\r\n\r\n");
}
static void mdns_task(void *param)
{
DNSServiceRef dnsServiceRef = NULL;
TXTRecordRef txtRecord;
unsigned char txt_buf[128];
uint8_t *mac, *ip;
int j, ret = 0;
uint8_t *flash_data;
uint8_t PAIR_STATE[1] = {0};
static unsigned char MAC_ADD[21];
static unsigned char IP[16];
static unsigned char port[6];
uint16_t shtc1_id;
// Delay to wait for IP by DHCP and get the information of IP and MAC
printf("\n\r\n\r\n\r\n\r<<<<<<Waiting for 20 seconds to connect Wi-Fi>>>>>>>\n\r\n\r\n\r\n\r");
vTaskDelay(20000);
ip = LwIP_GetIP(&xnetif[0]);
mac = LwIP_GetMAC(&xnetif[0]);
sprintf(MAC_ADD, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
sprintf(IP, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
sprintf(port, "%d", PORT);
IOT_DEBUG("MAC => %s\r\n", MAC_ADD) ;
IOT_DEBUG("IP => %s\r\n", IP);
IOT_DEBUG("PORT => %s\r\n", port);
//Get the value of PAIR_STATE and the AES key in flash
flash_data = (uint8_t *)malloc(33);
flash_stream_read(&iot_flash, FLASH_IOT_DATA, 33, (uint8_t *)flash_data);
memcpy(PAIR_STATE, flash_data, 1);
if(PAIR_STATE[0] != 0x1)
PAIR_STATE[0] = 0;
else{
for(j = 0;j < 16; j++){
aes_key[j] = flash_data[j+1];
}
}
free(flash_data);
IOT_DEBUG("PAIR_STATE now: %d\r\n", PAIR_STATE[0]);
IOT_DEBUG("=>mDNS Init\r\n");
if(mDNSResponderInit() == 0) {
printf("\r\n\r\n========>Start to register mDNS service\r\n\r\n");
//The device not paired before
if(PAIR_STATE[0] == 0){
TXTRecordCreate(&txtRecord, sizeof(txt_buf), txt_buf);
TXTRecordSetValue(&txtRecord, "IP", strlen(IP), IP);
TXTRecordSetValue(&txtRecord, "PORT", strlen(port), port);
TXTRecordSetValue(&txtRecord, "MAC_ADDR", strlen(MAC_ADD), MAC_ADD);
TXTRecordSetValue(&txtRecord, "PAIR_STATE", strlen("0"), "0");
TXTRecordSetValue(&txtRecord, "SERVICE_NAME", strlen("ht_sensor"), "ht_sensor");
if(CONTROL_TYPE == 1)
TXTRecordSetValue(&txtRecord, "CONTROL_TYPE", strlen("1"), "1");
else
TXTRecordSetValue(&txtRecord, "CONTROL_TYPE", strlen("0"), "0");
dnsServiceRef = mDNSRegisterService("ht_sensor", "_Ameba._tcp", "local", PORT, &txtRecord);
TXTRecordDeallocate(&txtRecord);
printf("\r\n\r\n<========Registering mDNS service OK!!\r\n\r\n");
pair_device_task();
}
//The device was paired
else if(PAIR_STATE[0] == 0x1){
TXTRecordCreate(&txtRecord, sizeof(txt_buf), txt_buf);
TXTRecordSetValue(&txtRecord, "IP", strlen(ip), ip);
TXTRecordSetValue(&txtRecord, "PORT", strlen(port), port);
TXTRecordSetValue(&txtRecord, "MAC_ADDR", strlen(MAC_ADD), MAC_ADD);
TXTRecordSetValue(&txtRecord, "PAIR_STATE", strlen("1"), "1");
TXTRecordSetValue(&txtRecord, "SERVICE_NAME", strlen("ht_sensor"), "ht_sensor");
if(CONTROL_TYPE == 1)
TXTRecordSetValue(&txtRecord, "CONTROL_TYPE", strlen("1"), "1");
else
TXTRecordSetValue(&txtRecord, "CONTROL_TYPE", strlen("0"), "0");
dnsServiceRef = mDNSRegisterService("ht_sensor", "_Ameba._tcp", "local", PORT, &txtRecord);
TXTRecordDeallocate(&txtRecord);
printf("\r\n\r\n<========Registering mDNS service OK!! PAIR_STATE = 1\r\n\r\n");
}
#if PSEUDO_DATA
printf("\r\n\r\n========>Using the speudo data\r\n\r\n");
if(CONTROL_TYPE == 1) start_cloud_link();
start_local_link();
#else
//Init the shtc1 sensor
printf("\r\n\r\n========>Init the temperature and humidity sensor\r\n\r\n");
ret = SHTC_Init(&shtc1_id);
if ( ret == NO_ERROR ){
printf("\r\n\r\n<========Senser init OK! ID = 0x%x \r\n\r\n", shtc1_id);
if(CONTROL_TYPE == 1) start_cloud_link();
start_local_link();
}
else {
printf("\r\n\r\n<========Senser init FAILED! ID = 0x%x \r\n\r\n", shtc1_id);
ret = -1;
}
#endif
}
else
ret = -1;
if(ret == 0){
while(1){
IOT_DEBUG("Update the mDNS textrecord!\r\n");
TXTRecordCreate(&txtRecord, sizeof(txt_buf), txt_buf);
TXTRecordSetValue(&txtRecord, "IP", strlen(IP), IP);
TXTRecordSetValue(&txtRecord, "PORT", strlen(port), port);
TXTRecordSetValue(&txtRecord, "MAC_ADDR", strlen(MAC_ADD), MAC_ADD);
TXTRecordSetValue(&txtRecord, "PAIR_STATE", strlen("1"), "1");
if(CONTROL_TYPE == 1)
TXTRecordSetValue(&txtRecord, "CONTROL_TYPE", strlen("1"), "1");
else
TXTRecordSetValue(&txtRecord, "CONTROL_TYPE", strlen("0"), "0");
TXTRecordSetValue(&txtRecord, "SERVICE_NAME", strlen("ht_sensor"), "ht_sensor");
mDNSUpdateService(dnsServiceRef, &txtRecord, 0);
TXTRecordDeallocate(&txtRecord);
vTaskDelay(2*60*1000);
}
}
else{
if(dnsServiceRef)
mDNSDeregisterService(dnsServiceRef);
IOT_DEBUG("<=mDNS Deinit\r\n\r\n");
mDNSResponderDeinit();
}
}
void example_wigadget(void)
{
if(xTaskCreate(mdns_task, ((const char*)"mdns_task"), 3072, NULL, tskIDLE_PRIORITY + 1, NULL) != pdPASS)
printf("\n\r%s xTaskCreate failed", __FUNCTION__);
gpio_t gpio_softap_reset_button;
gpio_irq_t gpioirq_softap_reset_button;
gpio_irq_init(&gpioirq_softap_reset_button, GPIO_SOFTAP_RESET_PIN, iotapp_reset_irq_handler, (uint32_t)(&gpio_softap_reset_button));
gpio_irq_set(&gpioirq_softap_reset_button, IRQ_FALL, 1);
gpio_irq_enable(&gpioirq_softap_reset_button);
}

View file

@ -0,0 +1,11 @@
#ifndef WIGADGET_H
#define WIGADGET_H
#define FLASH_IOT_DATA (0x0007E000)
#define PSEUDO_DATA 1
void example_wigadget(void);
void gen_json_data(char *i, char *j, unsigned char *json_data);
#endif /* WIGADGET_H */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,86 @@
/*
X-Modem Header File
1999/09/03 sprite, support Xmode Tx & Rx
*/
#ifndef _XMODE_H_
#define _XMODE_H_
#include <basic_types.h>
/*****************
* X-Modem status
*****************/
#define XMODEM_OK 1
#define XMODEM_CANCEL 2
#define XMODEM_ACK 3
#define XMODEM_NAK 4
#define XMODEM_COMPLETE 5
#define XMODEM_NO_SESSION 6
#define XMODEM_ABORT 7
#define XMODEM_TIMEOUT 8
/****************************
* flow control character
****************************/
#define SOH 0x01 /* Start of header */
#define STX 0x02 /* Start of header XModem-1K */
#define EOT 0x04 /* End of transmission */
#define ACK 0x06 /* Acknowledge */
#define NAK 0x15 /* Not acknowledge */
#define CAN 0x18 /* Cancel */
#define ESC 0x1b /* User Break */
/****************************
* Xmode paramters
****************************/
#define FRAME_SIZE 132 /* X-modem structure */
#define FRAME_SIZE_1K 1028 /* X-modem structure */
#define XM_BUFFER_SIZE 1024 /* X-modem buffer */
#define TIMEOUT 180 /* max timeout */
#define RETRY_COUNT 20 /* Try times */
#define xWAITTIME 0x00400000 /* waitiing time */
#define WAIT_FRAME_TIME (10000*100) /* 10 sec, wait frame timeout */
#define WAIT_CHAR_TIME (1000*100) /* 1 sec, wait char timeout */
/***********************
* frame structure
***********************/
typedef struct
{
unsigned char soh;
unsigned char recordNo;
unsigned char recordNoInverted;
unsigned char buffer[XM_BUFFER_SIZE];
unsigned char CRC;
} XMODEM_FRAME;
typedef struct _XMODEM_COM_PORT_ {
char (*poll) (void);
char (*get)(void);
void (*put)(char c);
}XMODEM_COM_PORT, *PXMODEM_COM_PORT;
typedef struct _XMODEM_CTRL_ {
u16 xMUsing;
u16 currentFrame; /* current frame number */
u16 previousFrame; /* previous frame number */
u16 expected;
s16 rStatus;
s32 rFinish;
u32 total_frame;
u32 rx_len;
char *pXFrameBuf;
u32 (*RxFrameHandler)(char *ptr, u32 frame_num, u32 frame_size);
XMODEM_COM_PORT ComPort;
}XMODEM_CTRL, *PXMODEM_CTRL;
typedef u32 (*RxFrameHandler_t)(char *ptr, u32 frame_num, u32 frame_size);
extern s16 xModemStart(XMODEM_CTRL *pXMCtrl, char *FrameBuf, RxFrameHandler_t RxFrameHdl);
extern s16 xModemEnd(XMODEM_CTRL *pXMCtrl);
extern s32 xModemRxBuffer(XMODEM_CTRL *pXMCtrl, s32 MaxSize);
#endif /* _XMODE_H_ */

View file

@ -0,0 +1,25 @@
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#ifndef _XMPORT_LOGUART_H_
#define _XMPORT_LOGUART_H_
#include "xmodem.h"
//void xmodem_loguart_init(void);
void xmodem_loguart_init(u32 BaudRate);
void xmodem_loguart_func_hook(XMODEM_COM_PORT *pXComPort);
void xmodem_loguart_deinit(void);
char xmodem_loguart_readable(void);
char xmodem_loguart_writable(void);
char xmodem_loguart_getc(void);
void xmodem_loguart_putc(char c);
#endif // end of "#define _XMPORT_LOGUART_H_"

View file

@ -0,0 +1,24 @@
/*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#ifndef _XMPORT_UART_H_
#define _XMPORT_UART_H_
#include "xmodem.h"
void xmodem_uart_init(u8 uart_idx, u8 pin_mux, u32 baud_rate);
void xmodem_uart_func_hook(XMODEM_COM_PORT *pXComPort);
void xmodem_uart_deinit(void);
char xmodem_uart_readable(void);
char xmodem_uart_writable(void);
char xmodem_uart_getc(void);
void xmodem_uart_putc(char c);
#endif // end of "#define _XMPORT_UART_H_"