repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
umaru724/TencentOS_E53_IA1
|
kernel/core/include/tos_tick.h
|
/*----------------------------------------------------------------------------
* Tencent is pleased to support the open source community by making TencentOS
* available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* If you have downloaded a copy of the TencentOS binary from Tencent, please
* note that the TencentOS binary is licensed under the BSD 3-Clause License.
*
* If you have downloaded a copy of the TencentOS source code from Tencent,
* please note that TencentOS source code is licensed under the BSD 3-Clause
* License, except for the third-party components listed below which are
* subject to different license terms. Your integration of TencentOS into your
* own projects may require compliance with the BSD 3-Clause License, as well
* as the other licenses applicable to the third-party components included
* within TencentOS.
*---------------------------------------------------------------------------*/
#ifndef _TOS_TICK_H_
#define _TOS_TICK_H_
/**
* @brief Systick interrupt handler.
* systick interrupt handler.
*
* @attention called from the systick interrupt entrance.
*
* @param None
*
* @return None
*/
__API__ void tos_tick_handler(void);
__KNL__ void tick_update(k_tick_t tick);
__KNL__ void tick_list_add(k_task_t *task, k_tick_t timeout);
__KNL__ void tick_list_remove(k_task_t *task);
#if TOS_CFG_TICKLESS_EN > 0u
__KNL__ k_tick_t tick_next_expires_get(void);
#endif
#endif /* _TOS_TICK_H_ */
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/ant/experimental/ant_shared_channel/m2m/asc_master_to_master.c
|
/**
* This software is subject to the ANT+ Shared Source License
* www.thisisant.com/swlicenses
* Copyright (c) Garmin Canada Inc. 2014
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3) Neither the name of Garmin nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior
* written permission.
*
* The following actions are prohibited:
*
* 1) Redistribution of source code containing the ANT+ Network
* Key. The ANT+ Network Key is available to ANT+ Adopters.
* Please refer to http://thisisant.com to become an ANT+
* Adopter and access the key.
*
* 2) Reverse engineering, decompilation, and/or disassembly of
* software provided in binary form under this license.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE HEREBY
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; DAMAGE TO ANY DEVICE, LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE. SOME STATES DO NOT ALLOW
* THE EXCLUSION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE
* ABOVE LIMITATIONS MAY NOT APPLY TO YOU.
*
*/
/**@file
* @defgroup asc_multimaster module
* @{
* @ingroup ant_auto_shared_channel
*
* @brief ANT Auto Shared Channel (ASC) Master implementation.
*/
#include "asc_master_to_master.h"
#include <stdint.h>
#include <string.h>
#include "ant_interface.h"
#include "ant_parameters.h"
#include "app_error.h"
#include "asc_events.h"
#include "asc_parameters.h"
#include "nrf_soc.h"
#define ANT_WILDCARD_DEVICE_NUMBER ((uint16_t) 0)
#define DISCOVERY_SEARCH_TIMEOUT ((uint8_t) 0) // Disable high priority search to avoid channel collisions
#define DISCOVERY_LP_SEARCH_TIMEOUT ((uint8_t) 8) // 20 seconds
#define ASCMM_SEARCH_TIMEOUT ((uint8_t) 0) // Disable high priority search to avoid channel collisions
#define ASCMM_LP_SEARCH_TIMEOUT ((uint8_t) 12) // 30 secondss
typedef struct
{
uint16_t device_number;
uint8_t page_id;
uint16_t payload;
} ascmm_neighbor_update_t;
// Private Variables
static const uint8_t ascmm_idle_page[ANT_STANDARD_DATA_PAYLOAD_SIZE] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static uint16_t m_device_number; //used to perform the comparison between this device and the found neighbor
static uint8_t m_discovery_channel_number;
static uint16_t m_connection_device_number;
static ascmm_neighbor_update_t m_neighbor;
static asc_ant_params_t m_ant_connected_parameters;
static ascmm_states_t m_state;
static uint32_t m_asc_event_flags = 0;
static uint8_t m_tx_buffer[ANT_STANDARD_DATA_PAYLOAD_SIZE] = {0};
static asc_command_data_t m_last_received_command;
static asc_update_data_t m_last_received_update;
static uint8_t m_retries;
// Private Functions
/**@brief Sets the state machine to the specified state.
*/
static void ascmm_set_state(ascmm_states_t new_state)
{
uint32_t err_code;
if (new_state != m_state)
{
switch (new_state)
{
case ASCMM_OFF:
{
//Close the channel
err_code = sd_ant_channel_close(m_discovery_channel_number);
APP_ERROR_CHECK(err_code);
break;
}
case DISCOVERY:
{
if (m_state != ASCMM_OFF)
{
asc_event_set(&m_asc_event_flags, EVENT_ASC_DEVICE_IN_WRONG_STATE);
return;
}
m_state = new_state;
//Open the discovery channel
err_code = sd_ant_channel_open(m_discovery_channel_number);
break;
}
case CONNECTED:
{
if (m_state != DISCOVERY)
{
asc_event_set(&m_asc_event_flags, EVENT_ASC_DEVICE_IN_WRONG_STATE);
return;
}
m_state = new_state;
//Close the channel
err_code = sd_ant_channel_close(m_discovery_channel_number);
APP_ERROR_CHECK(err_code);
//Assign the connection channel
err_code = sd_ant_channel_assign(m_ant_connected_parameters.channel_number,
m_ant_connected_parameters.channel_type,
m_ant_connected_parameters.network_number, 0);
APP_ERROR_CHECK(err_code);
//Set channel id
err_code = sd_ant_channel_id_set (m_ant_connected_parameters.channel_number,
m_connection_device_number,
m_ant_connected_parameters.device_type,
m_ant_connected_parameters.tx_type);
APP_ERROR_CHECK(err_code);
//Set radio frequency
err_code = sd_ant_channel_radio_freq_set (m_ant_connected_parameters.channel_number,
m_ant_connected_parameters.rf_frequency);
APP_ERROR_CHECK(err_code);
if (m_ant_connected_parameters.channel_type == CHANNEL_TYPE_SLAVE)
{
//Configure search timeout for slave channel
err_code = sd_ant_channel_rx_search_timeout_set(m_ant_connected_parameters.channel_number,
ASCMM_SEARCH_TIMEOUT);
APP_ERROR_CHECK(err_code);
err_code = sd_ant_channel_low_priority_rx_search_timeout_set(m_ant_connected_parameters.channel_number,
ASCMM_LP_SEARCH_TIMEOUT);
APP_ERROR_CHECK(err_code);
}
else
{
// Configure Tx power for master chanel
err_code = sd_ant_channel_radio_tx_power_set(m_ant_connected_parameters.channel_number,
m_ant_connected_parameters.tx_power, 0);
APP_ERROR_CHECK(err_code);
}
err_code = sd_ant_channel_open(m_ant_connected_parameters.channel_number);
APP_ERROR_CHECK(err_code);
break;
}
default:
{
//if the new state was not recognized, return to avoid setting the state changed event
asc_event_set(&m_asc_event_flags, EVENT_ASC_DEVICE_IN_WRONG_STATE);
return;
}
}
asc_event_set(&m_asc_event_flags, EVENT_ASC_STATE_CHANGED);
}
//lint --e{438}
}
/**@brief Processes a ANT messages while in the off state.
*
* @param[in] Pointer to the raw ant message received.
*/
static void process_message_off(uint8_t * p_ant_message)
{
//There should be no messages to process
}
/**@brief Processes a ANT messages while in the discovery state.
*
* @param[in] Pointer to the raw ant message received.
*/
static void process_message_discovery(uint8_t * p_ant_message)
{
switch (p_ant_message[ANT_MESSAGE_ID_OFFSET])
{
case MESG_BROADCAST_DATA_ID:
//fall-through
case MESG_ACKNOWLEDGED_DATA_ID:
{
//determine whether this device is to be a master or a slave, and continue to the connected state
if (p_ant_message[ANT_MESSAGE_FLAG_OFFSET] == ANT_EXT_MESG_BITFIELD_DEVICE_ID)
{
//Fill the temporary neighbor with the device number and rssi value from the received message
//page number and payload are not relevant at the moment, so ignore them
m_neighbor.device_number = p_ant_message[ANT_MESSAGE_EXTENDED0_OFFSET] | (((uint16_t) p_ant_message[ANT_MESSAGE_EXTENDED1_OFFSET]) << 8);
if (m_neighbor.device_number < m_device_number)
{
m_connection_device_number = (m_neighbor.device_number & 0xFF) | ((m_device_number & 0xFF) << 8);
m_ant_connected_parameters.channel_type = CHANNEL_TYPE_MASTER;
}
else
{
m_connection_device_number = (m_device_number & 0xFF) | ((m_neighbor.device_number & 0xFF) << 8);
m_ant_connected_parameters.channel_type = CHANNEL_TYPE_SLAVE;
}
ascmm_set_state(CONNECTED);
}
break;
}
default:
break;
}
}
/**@brief Processes a ANT messages while in the connected state.
*
* @param[in] Pointer to the raw ant message received.
*/
static void process_message_connected(uint8_t * p_ant_message)
{
uint32_t err_code;
switch (p_ant_message[ANT_MESSAGE_ID_OFFSET])
{
case MESG_RESPONSE_EVENT_ID:
{
if (p_ant_message[ANT_MESSAGE_DATA0_OFFSET] == MESG_EVENT_ID) //Channel event
{
switch (p_ant_message[ANT_MESSAGE_DATA1_OFFSET])
{
case EVENT_TX:
{
//If this is a slave channel, we will need to controll the reverse-direction communication.
//Otherwise, the last message loaded into the tx buffer will continue to be transmitted anyway
if ( m_retries-- > 0)
{
err_code = sd_ant_broadcast_message_tx(m_ant_connected_parameters.channel_number, ANT_STANDARD_DATA_PAYLOAD_SIZE, m_tx_buffer);
APP_ERROR_CHECK(err_code);
}
else if (m_ant_connected_parameters.channel_type == CHANNEL_TYPE_MASTER)
{
memcpy(m_tx_buffer, ascmm_idle_page, ANT_STANDARD_DATA_PAYLOAD_SIZE);
err_code = sd_ant_broadcast_message_tx(m_ant_connected_parameters.channel_number, ANT_STANDARD_DATA_PAYLOAD_SIZE, m_tx_buffer);
APP_ERROR_CHECK(err_code);
}
break;
}
default:
break;
}
}
break;
}
case MESG_BROADCAST_DATA_ID:
//fall-through
case MESG_ACKNOWLEDGED_DATA_ID:
{
//process by page
switch (p_ant_message[DECODE_PAGE_ID_BYTE_PHONE_FORMAT])
{
case PHONE_COMMAND_PID:
{
//lint --e{534}
asc_decode_phone_command_page(&m_last_received_command, p_ant_message);
asc_event_set(&m_asc_event_flags, EVENT_ASC_COMMAND_RECEIVED);
break;
}
case UPDATE_DATA_PID:
{
//lint --e{534}
asc_decode_phone_update_data_page(&m_last_received_update, p_ant_message);
asc_event_set(&m_asc_event_flags, EVENT_ASC_UPDATE_RECEIVED);
break;
}
default:
{
break;
}
}
break;
}
default:
break;
}
}
// Public Functions
void ascmm_init(const asc_ant_params_t * const p_ant_discovery_parameters, const asc_ant_params_t * const p_ant_connection_parameters, uint16_t device_number)
{
uint32_t err_code;
m_discovery_channel_number = p_ant_discovery_parameters->channel_number;
m_device_number = device_number;
//Assign the slave channel
err_code = sd_ant_channel_assign(m_discovery_channel_number,
p_ant_discovery_parameters->channel_type,
p_ant_discovery_parameters->network_number,
EXT_PARAM_ALWAYS_SEARCH);
APP_ERROR_CHECK(err_code);
//Assign slave channel id.
err_code = sd_ant_channel_id_set(m_discovery_channel_number,
ANT_WILDCARD_DEVICE_NUMBER,
p_ant_discovery_parameters->device_type,
p_ant_discovery_parameters->tx_type);
APP_ERROR_CHECK(err_code);
//Assign slave channel frequency.
err_code = sd_ant_channel_radio_freq_set(m_discovery_channel_number,
p_ant_discovery_parameters->rf_frequency);
APP_ERROR_CHECK(err_code);
//Set the transmission power.
err_code = sd_ant_channel_radio_tx_power_set(m_discovery_channel_number,
p_ant_discovery_parameters->tx_power,
ASC_ANT_CUSTOM_PWR);
APP_ERROR_CHECK(err_code);
//Configure search timeouts
err_code = sd_ant_channel_rx_search_timeout_set(m_discovery_channel_number,
DISCOVERY_SEARCH_TIMEOUT);
APP_ERROR_CHECK(err_code);
err_code = sd_ant_channel_low_priority_rx_search_timeout_set(m_discovery_channel_number,
DISCOVERY_LP_SEARCH_TIMEOUT);
APP_ERROR_CHECK(err_code);
// Configure proximity search
// @todo: JP added trailing 0 parameter
err_code = sd_ant_prox_search_set(m_discovery_channel_number, PROXIMITY_THRESHOLD_2, 0);
APP_ERROR_CHECK(err_code);
//Enable extended messages
err_code = sd_ant_lib_config_set(ANT_LIB_CONFIG_MESG_OUT_INC_DEVICE_ID);
APP_ERROR_CHECK(err_code);
//Initialize the connection parameters struct for later use
//Many of these values are just defaults for now.
//Ex. channel type will be determined before switching to the connected state)
m_ant_connected_parameters.channel_number = p_ant_connection_parameters->channel_number;
m_ant_connected_parameters.network_number = p_ant_connection_parameters->network_number;
m_ant_connected_parameters.p_device_number = &(m_connection_device_number); //This will change over the course of discovery
m_ant_connected_parameters.device_type = p_ant_connection_parameters->device_type;
m_ant_connected_parameters.tx_type = p_ant_connection_parameters->tx_type;
m_ant_connected_parameters.channel_period = p_ant_connection_parameters->channel_period;
m_ant_connected_parameters.channel_type = p_ant_connection_parameters->channel_type;
m_ant_connected_parameters.rf_frequency = p_ant_connection_parameters->rf_frequency;
m_ant_connected_parameters.tx_power = p_ant_connection_parameters->tx_power;
}
void ascmm_turn_on(void)
{
ascmm_set_state(DISCOVERY);
}
void ascmm_handle_ant_event(uint8_t event, uint8_t * p_event_message_buffer)
{
switch (m_state)
{
case ASCMM_OFF:
{
process_message_off(p_event_message_buffer);
break;
}
case DISCOVERY:
{
process_message_discovery(p_event_message_buffer);
break;
}
case CONNECTED:
{
process_message_connected(p_event_message_buffer);
break;
}
default:
break;
}
}
void ascmm_relay_message(uint8_t * p_tx_buffer, uint8_t retries)
{
if (m_state == CONNECTED)
{
uint32_t err_code;
m_retries = retries;
memcpy(m_tx_buffer, p_tx_buffer, ANT_STANDARD_DATA_PAYLOAD_SIZE);
err_code = sd_ant_broadcast_message_tx(m_ant_connected_parameters.channel_number, ANT_STANDARD_DATA_PAYLOAD_SIZE, m_tx_buffer);
APP_ERROR_CHECK(err_code);
}
}
ascmm_states_t ascmm_state_get(void)
{
return m_state;
}
uint32_t ascmm_events_get(void)
{
return m_asc_event_flags;
}
void ascmm_event_clear(uint32_t event)
{
asc_event_clear(&m_asc_event_flags, event);
}
uint16_t ascmm_get_neighbor_id(void)
{
return m_neighbor.device_number;
}
asc_command_data_t ascmm_get_last_command(void)
{
return m_last_received_command;
}
asc_update_data_t ascmm_get_last_update(void)
{
return m_last_received_update;
}
/** @} **/
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/crypto/nrf_crypto/hkdf/main.c
|
/**
* Copyright (c) 2018 - 2019, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/** @file
*
* @defgroup nrf_crypto_example_hkdf main.c
* @{
* @ingroup nrf_crypto_example
*
* @brief HMAC based Key Derivation Function (HKDF) Example Application main file.
*
* @details This file contains the source code for a sample application that demonstrates using the
* nrf_crypto library to do HKDF calculations. Different backends can be used by configuring the
* HMAC backend in @c sdk_config.h accordingly.
*
*/
#include <stdint.h>
#include "app_error.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "nrf_crypto.h"
// Test data from RFC 5869 Test Case 1 (https://tools.ietf.org/html/rfc5869)
// Input key material.
static uint8_t m_ikm[] =
{
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b
};
// Salt.
static uint8_t m_salt[] =
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c
};
// Additional info material optionally used to increase entropy.
static uint8_t m_ainfo[] =
{
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9
};
// Expected output key material (result of HKDF operation).
static uint8_t m_expected_okm[] =
{
0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a,
0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf,
0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65
};
static uint8_t m_okm[sizeof(m_expected_okm)];
static nrf_crypto_hmac_context_t m_context;
static void log_init(void)
{
ret_code_t err_code = NRF_LOG_INIT(NULL);
APP_ERROR_CHECK(err_code);
NRF_LOG_DEFAULT_BACKENDS_INIT();
}
int main(void)
{
uint32_t err_code = NRF_SUCCESS;
size_t okm_len = sizeof(m_okm);
log_init();
err_code = nrf_crypto_init();
APP_ERROR_CHECK(err_code);
NRF_LOG_INFO("HKDF example started.");
err_code = nrf_crypto_hkdf_calculate(&m_context,
&g_nrf_crypto_hmac_sha256_info,
m_okm,
&okm_len,
m_ikm,
sizeof(m_ikm),
m_salt,
sizeof(m_salt),
m_ainfo,
sizeof(m_ainfo),
NRF_CRYPTO_HKDF_EXTRACT_AND_EXPAND);
APP_ERROR_CHECK(err_code);
if (memcmp(m_okm, m_expected_okm, sizeof(m_expected_okm)) == 0)
{
NRF_LOG_INFO("HKDF example executed successfully.");
}
else
{
NRF_LOG_ERROR("HKDF example failed!!!");
}
for (;;)
{
}
}
/**
*@}
**/
|
umaru724/TencentOS_E53_IA1
|
net/lora_module_wrapper/lora_module_wrapper.c
|
#include "lora_module_wrapper.h"
static lora_module_t *g_lora_module = NULL;
int tos_lora_module_register(lora_module_t *module)
{
if (!g_lora_module) {
g_lora_module = module;
return 0;
}
return -1;
}
int tos_lora_module_init(void)
{
if (g_lora_module && g_lora_module->init) {
return g_lora_module->init();
}
return -1;
}
int tos_lora_module_join_otaa(const char *deveui, const char *appkey)
{
if (g_lora_module && g_lora_module->join_otaa) {
return g_lora_module->join_otaa(deveui, appkey);
}
return -1;
}
int tos_lora_module_join_abp(const char *deveui, const char *devaddr, const char *nwkskey, const char *appskey)
{
if (g_lora_module && g_lora_module->join_abp) {
return g_lora_module->join_abp(deveui, devaddr, nwkskey, appskey);
}
return -1;
}
int tos_lora_module_send(const void *buf, size_t len)
{
if (g_lora_module && g_lora_module->send) {
return g_lora_module->send(buf, len);
}
return -1;
}
int tos_lora_module_recvcb_register(lora_recv_callback_t recv_callback)
{
if (g_lora_module) {
g_lora_module->recv_callback = recv_callback;
return 0;
}
return -1;
}
int tos_lora_module_close(void)
{
if (g_lora_module && g_lora_module->close) {
return g_lora_module->close();
}
return -1;
}
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/external/cifra_AES128-EAX/modes.c
|
/*
* cifra - embedded cryptography library
* Written in 2014 by <NAME> <<EMAIL>>
*
* To the extent possible under law, the author(s) have dedicated all
* copyright and related and neighboring rights to this software to the
* public domain worldwide. This software is distributed without any
* warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication
* along with this software. If not, see
* <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
#include "prp.h"
#include "modes.h"
#include "bitops.h"
#include "blockwise.h"
#include <string.h>
#include "tassert.h"
/* CBC */
void cf_cbc_init(cf_cbc *ctx, const cf_prp *prp, void *prpctx, const uint8_t iv[CF_MAXBLOCK])
{
ctx->prp = prp;
ctx->prpctx = prpctx;
memcpy(ctx->block, iv, prp->blocksz);
}
void cf_cbc_encrypt(cf_cbc *ctx, const uint8_t *input, uint8_t *output, size_t blocks)
{
uint8_t buf[CF_MAXBLOCK];
size_t nblk = ctx->prp->blocksz;
while (blocks--)
{
xor_bb(buf, input, ctx->block, nblk);
ctx->prp->encrypt(ctx->prpctx, buf, ctx->block);
memcpy(output, ctx->block, nblk);
input += nblk;
output += nblk;
}
}
void cf_cbc_decrypt(cf_cbc *ctx, const uint8_t *input, uint8_t *output, size_t blocks)
{
uint8_t buf[CF_MAXBLOCK];
size_t nblk = ctx->prp->blocksz;
while (blocks--)
{
ctx->prp->decrypt(ctx->prpctx, input, buf);
xor_bb(output, buf, ctx->block, nblk);
memcpy(ctx->block, input, nblk);
input += nblk;
output += nblk;
}
}
/* CTR */
void cf_ctr_init(cf_ctr *ctx, const cf_prp *prp, void *prpctx, const uint8_t nonce[CF_MAXBLOCK])
{
memset(ctx, 0, sizeof *ctx);
ctx->counter_offset = 0;
ctx->counter_width = prp->blocksz;
ctx->prp = prp;
ctx->prpctx = prpctx;
ctx->nkeymat = 0;
memcpy(ctx->nonce, nonce, prp->blocksz);
}
void cf_ctr_custom_counter(cf_ctr *ctx, size_t offset, size_t width)
{
assert(ctx->prp->blocksz <= offset + width);
ctx->counter_offset = offset;
ctx->counter_width = width;
}
static void ctr_next_block(void *vctx, uint8_t *out)
{
cf_ctr *ctx = vctx;
ctx->prp->encrypt(ctx->prpctx, ctx->nonce, out);
incr_be(ctx->nonce + ctx->counter_offset, ctx->counter_width);
}
void cf_ctr_cipher(cf_ctr *ctx, const uint8_t *input, uint8_t *output, size_t bytes)
{
cf_blockwise_xor(ctx->keymat, &ctx->nkeymat,
ctx->prp->blocksz,
input, output, bytes,
ctr_next_block,
ctx);
}
void cf_ctr_discard_block(cf_ctr *ctx)
{
ctx->nkeymat = 0;
}
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/ant/experimental/ant_shared_channel/m2m/asc_master_to_master.h
|
<reponame>umaru724/TencentOS_E53_IA1
/**
* This software is subject to the ANT+ Shared Source License
* www.thisisant.com/swlicenses
* Copyright (c) Garmin Canada Inc. 2014
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3) Neither the name of Garmin nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior
* written permission.
*
* The following actions are prohibited:
*
* 1) Redistribution of source code containing the ANT+ Network
* Key. The ANT+ Network Key is available to ANT+ Adopters.
* Please refer to http://thisisant.com to become an ANT+
* Adopter and access the key.
*
* 2) Reverse engineering, decompilation, and/or disassembly of
* software provided in binary form under this license.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE HEREBY
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; DAMAGE TO ANY DEVICE, LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE. SOME STATES DO NOT ALLOW
* THE EXCLUSION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE
* ABOVE LIMITATIONS MAY NOT APPLY TO YOU.
*
*/
/**@file
* @defgroup asc_multimaster module
* @{
* @ingroup ant_auto_shared_channel
*
* @brief ANT Auto Shared Channel (ASC)Multi-master implementation.
*/
#ifndef ASC_MASTER_TO_MASTER_H__
#define ASC_MASTER_TO_MASTER_H__
#include <stdint.h>
#include "asc_parameters.h"
#ifdef __cplusplus
extern "C" {
#endif
/**@brief Enumeration defining the possible states of an ASC Multi-master.
*/
typedef enum
{
ASCMM_OFF = 0, /**< ASC Multi-master State: OFF. The ASC Multi-master is neither connected to, nor searching for, other ASC Masters.*/
DISCOVERY, /**< ASC Multi-master State: DISCOVERY. The ASC Multi-master is searching for other ASC Masters.*/
CONNECTED, /**< ASC Multi-master State: CONNECTED. The ASC Multi-master is connected to another ASC Master.*/
} ascmm_states_t;
/**@brief Function for initializing the ASC Multi-master.
*
* @param[in] p_ant_discovery_parameters Pointer to the ANT channel parameters used to assign and configure the discovery channel.
* The device number and channel type contained in this struct are ignored by the module.
*
* @param[in] p_ant_connection_parameters Pointer to the ANT channel parameters used to create the master to master channel.
* The device number and channel type contained in this struct are ignored by the module.
*
* @param[in] device_number The device number to use when determining whether this device should be an ASCMM Master or Slave.
*/
void ascmm_init(const asc_ant_params_t * const p_ant_discovery_parameters,
const asc_ant_params_t * const p_ant_connection_parameters,
uint16_t device_number);
/**@brief Function to turn on the ASC Multi-master and begin the discovery process.
*/
void ascmm_turn_on(void);
/**@brief Function to handle received ANT messages on the ASC Multi-master channel.
*
* @param[in] event The ANT event type that was received.
*
* @param[in] p_event_message_buffer The received message buffer.
*/
void ascmm_handle_ant_event(uint8_t event, uint8_t * p_event_message_buffer);
/**@brief Function to pass an ant message over the master to master channel.
*
* @param[in] p_tx_buffer The raw ANT data to send over the air.
*
* @param[in] retries The number of times that the message will be relayed.
*
* @param[in] maximum_retries The number of times that the message will be sent over the air.
*/
void ascmm_relay_message(uint8_t * p_tx_buffer, uint8_t retries);
/**@brief Function to get the current ASC Multi-master state.
*
* @return A copy of the current ASC Multi-master state.
*/
ascmm_states_t ascmm_state_get(void);
/**@brief Function to get the ASC Multi-master event bitfield.
*
* @note After using this function and checking for an event, be sure to clear that event immediately.
*
* @return A copy of the current event bitfield.
*/
uint32_t ascmm_events_get(void);
/**@brief Clears the specified event from the event bitfield.
*
* @param[in] event The ASC event to clear from the bitfield.
*/
void ascmm_event_clear(uint32_t event);
/**@brief Gets the device number of the connected master device
*
* @return The device number of the connected master device
*/
uint16_t ascmm_get_neighbor_id(void);
/**@brief Gets the last command received on the master to master channel.
*
* @return A copy of the last command received on the master to master channel.
*/
asc_command_data_t ascmm_get_last_command(void);
/**@brief Gets the last update received on the master to master channel.
*
* @return A copy of the last update received on the master to master channel.
*/
asc_update_data_t ascmm_get_last_update(void);
#ifdef __cplusplus
}
#endif
#endif /* ASC_MASTER_TO_MASTER_H__ */
/** @} */
|
umaru724/TencentOS_E53_IA1
|
kernel/pm/include/tos_pm.h
|
<reponame>umaru724/TencentOS_E53_IA1<gh_stars>1-10
/*----------------------------------------------------------------------------
* Tencent is pleased to support the open source community by making TencentOS
* available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* If you have downloaded a copy of the TencentOS binary from Tencent, please
* note that the TencentOS binary is licensed under the BSD 3-Clause License.
*
* If you have downloaded a copy of the TencentOS source code from Tencent,
* please note that TencentOS source code is licensed under the BSD 3-Clause
* License, except for the third-party components listed below which are
* subject to different license terms. Your integration of TencentOS into your
* own projects may require compliance with the BSD 3-Clause License, as well
* as the other licenses applicable to the third-party components included
* within TencentOS.
*---------------------------------------------------------------------------*/
#ifndef _TOS_PM_H_
#define _TOS_PM_H_
#if TOS_CFG_PWR_MGR_EN > 0u
#define K_PM_DEVICE_MAX_COUNT 10u
typedef enum idle_power_manager_mode_en {
IDLE_POWER_MANAGER_MODE_SLEEP,
IDLE_POWER_MANAGER_MODE_TICKLESS,
} idle_pwrmgr_mode_t;
/*
Low-power mode summary
|-------------------------------------------------------------------------------------------------------------------|
| Mode name | Entry | Wakeup | Effect on 1.8V | Effect on VDD | Voltage regulator |
| | | | domain clocks | domain clocks | |
|----------------|------------------|--------------------|--------------------|-----------------|-------------------|
| Sleep | WFI | Any interrupt | CPU clock OFF | | |
| (Sleep now or |------------------|--------------------| no effect on other | None | ON |
| Sleep-on-exit) | WFE | Wakeup event | clocks or analog | | |
| | | | clock sources | | |
|----------------|------------------|--------------------|--------------------|-----------------|-------------------|
| | | | | | ON or in |
| Stop | PDDS and LPDS | Any EXTI line | | | low-power mode |
| | bits + SLEEPDEEP | (configured in the | | | (depends on Power |
| | bit + WFI or WFE | EXTI registers | | | control register |
| | | | | | (PWR_CR) |
|----------------|------------------|--------------------| All 1.8V domain | HSI and HSE |-------------------|
| | | WKUP pin rising | clocks OFF | oscillators OFF | |
| Standby | PDDS bit + | edge, RTC alarm, | | | |
| | SLEEPDEEP bit + | external reset in | | | OFF |
| | WFI or WFE | NRST pin, | | | |
| | | IWDG reset | | | |
| | | | | | |
|-------------------------------------------------------------------------------------------------------------------|
*/
typedef enum k_cpu_low_power_mode_en {
TOS_LOW_POWER_MODE_SLEEP = 0, /* wakeup source: systick/tim/rtc */
TOS_LOW_POWER_MODE_STOP, /* wakeup source: rtc wakeup/alarm */
TOS_LOW_POWER_MODE_STANDBY, /* wakeup source: rtc alarm */
__LOW_POWER_MODE_DUMMY,
} k_cpu_lpwr_mode_t;
typedef struct k_pm_device_st {
char *name;
int (*init)(void);
int (*suspend)(void);
int (*resume)(void);
} k_pm_device_t;
typedef struct pm_device_control_st {
uint8_t count;
k_pm_device_t *mgr[K_PM_DEVICE_MAX_COUNT];
} pm_device_ctl_t;
#if TOS_CFG_TICKLESS_EN > 0u
__API__ k_err_t tos_pm_cpu_lpwr_mode_set(k_cpu_lpwr_mode_t cpu_lpwr_mode);
#endif
__API__ k_err_t tos_pm_device_register(k_pm_device_t *device);
__KNL__ void pm_init(void);
__KNL__ void pm_cpu_lpwr_mode_enter(k_cpu_lpwr_mode_t lpwr_mode);
__KNL__ k_cpu_lpwr_mode_t pm_cpu_lpwr_mode_get(void);
__KNL__ void pm_idle_pwr_mgr_mode_set(idle_pwrmgr_mode_t idle_pwrmgr_mode);
__KNL__ int pm_idle_pwr_mgr_mode_is_sleep(void);
__KNL__ int pm_idle_pwr_mgr_mode_is_tickless(void);
__KNL__ void pm_power_manager(void);
__KNL__ int pm_device_suspend(void);
__KNL__ int pm_device_resume(void);
#endif /* TOS_CFG_PWR_MGR_EN */
#endif /* _TOS_PM_H_ */
|
umaru724/TencentOS_E53_IA1
|
kernel/core/tos_mmblk.c
|
/*----------------------------------------------------------------------------
* Tencent is pleased to support the open source community by making TencentOS
* available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* If you have downloaded a copy of the TencentOS binary from Tencent, please
* note that the TencentOS binary is licensed under the BSD 3-Clause License.
*
* If you have downloaded a copy of the TencentOS source code from Tencent,
* please note that TencentOS source code is licensed under the BSD 3-Clause
* License, except for the third-party components listed below which are
* subject to different license terms. Your integration of TencentOS into your
* own projects may require compliance with the BSD 3-Clause License, as well
* as the other licenses applicable to the third-party components included
* within TencentOS.
*---------------------------------------------------------------------------*/
#include "tos_k.h"
#if TOS_CFG_MMBLK_EN > 0u
__API__ k_err_t tos_mmblk_pool_create(k_mmblk_pool_t *mbp, void *pool_start, size_t blk_num, size_t blk_size)
{
uint32_t i;
void *blk_curr;
void *blk_next;
TOS_IN_IRQ_CHECK();
TOS_PTR_SANITY_CHECK(pool_start);
if (((cpu_addr_t)pool_start & K_MMBLK_ALIGN_MASK) != 0u) {
return K_ERR_MMBLK_INVALID_POOL_ADDR;
}
if ((blk_size & K_MMBLK_ALIGN_MASK) != 0u) {
return K_ERR_MMBLK_INVALID_BLK_SIZE;
}
blk_curr = pool_start;
blk_next = K_MMBLK_NEXT_BLK(blk_curr, blk_size);
for (i = 0; i < blk_num - 1u; ++i) {
*(void **)blk_curr = blk_next;
blk_curr = blk_next;
blk_next = K_MMBLK_NEXT_BLK(blk_next, blk_size);
}
*(void **)blk_next = K_NULL;
mbp->pool_start = pool_start;
mbp->free_list = pool_start;
mbp->blk_free = blk_num;
mbp->blk_max = blk_num;
mbp->blk_size = blk_size;
TOS_OBJ_INIT(mbp, KNL_OBJ_TYPE_MMBLK_POOL);
return K_ERR_NONE;
}
__API__ k_err_t tos_mmblk_pool_destroy(k_mmblk_pool_t *mbp)
{
TOS_PTR_SANITY_CHECK(mbp);
TOS_OBJ_VERIFY(mbp, KNL_OBJ_TYPE_MMBLK_POOL);
mbp->pool_start = K_NULL;
mbp->free_list = K_NULL;
mbp->blk_free = 0;
mbp->blk_max = 0;
mbp->blk_size = 0;
TOS_OBJ_DEINIT(mbp);
return K_ERR_NONE;
}
__API__ k_err_t tos_mmblk_alloc(k_mmblk_pool_t *mbp, void **blk)
{
TOS_CPU_CPSR_ALLOC();
TOS_PTR_SANITY_CHECK(mbp);
TOS_OBJ_VERIFY(mbp, KNL_OBJ_TYPE_MMBLK_POOL);
TOS_CPU_INT_DISABLE();
if (mbp->blk_free == 0) {
TOS_CPU_INT_ENABLE();
*blk = K_NULL;
return K_ERR_MMBLK_POOL_EMPTY;
}
*blk = mbp->free_list;
mbp->free_list = *(void **)mbp->free_list;
--mbp->blk_free;
TOS_CPU_INT_ENABLE();
return K_ERR_NONE;
}
__API__ k_err_t tos_mmblk_free(k_mmblk_pool_t *mbp, void *blk)
{
TOS_CPU_CPSR_ALLOC();
TOS_PTR_SANITY_CHECK(mbp);
TOS_PTR_SANITY_CHECK(blk);
TOS_OBJ_VERIFY(mbp, KNL_OBJ_TYPE_MMBLK_POOL);
TOS_CPU_INT_DISABLE();
if (mbp->blk_free >= mbp->blk_max) {
TOS_CPU_INT_ENABLE();
return K_ERR_MMBLK_POOL_FULL;
}
*(void **)blk = mbp->free_list;
mbp->free_list = blk;
++mbp->blk_free;
TOS_CPU_INT_ENABLE();
return K_ERR_NONE;
}
#endif
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/LoraWAN/system/uart.h
|
/*!
* \file uart.h
*
* \brief UART driver implementation
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* \endcode
*
* \author <NAME> ( Semtech )
*
* \author <NAME> ( Semtech )
*/
#ifndef __UART_H__
#define __UART_H__
#include "fifo.h"
#include "gpio.h"
#include "stdio.h"
/*!
* UART peripheral ID
*/
typedef enum
{
UART_1,
UART_2,
UART_USB_CDC = 255,
}UartId_t;
/*!
* UART notification identifier
*/
typedef enum
{
UART_NOTIFY_TX,
UART_NOTIFY_RX
}UartNotifyId_t;
/*!
* UART object type definition
*/
typedef struct
{
UartId_t UartId;
bool IsInitialized;
Gpio_t Tx;
Gpio_t Rx;
Fifo_t FifoTx;
Fifo_t FifoRx;
/*!
* IRQ user notification callback prototype.
*/
void ( *IrqNotify )( UartNotifyId_t id );
}Uart_t;
/*!
* Operation Mode for the UART
*/
typedef enum
{
TX_ONLY = 0,
RX_ONLY,
RX_TX
}UartMode_t;
/*!
* UART word length
*/
typedef enum
{
UART_8_BIT = 0,
UART_9_BIT
}WordLength_t;
/*!
* UART stop bits
*/
typedef enum
{
UART_1_STOP_BIT = 0,
UART_0_5_STOP_BIT,
UART_2_STOP_BIT,
UART_1_5_STOP_BIT
}StopBits_t;
/*!
* UART parity
*/
typedef enum
{
NO_PARITY = 0,
EVEN_PARITY,
ODD_PARITY
}Parity_t;
/*!
* UART flow control
*/
typedef enum
{
NO_FLOW_CTRL = 0,
RTS_FLOW_CTRL,
CTS_FLOW_CTRL,
RTS_CTS_FLOW_CTRL
}FlowCtrl_t;
/*!
* \brief Initializes the UART object and MCU peripheral
*
* \param [IN] obj UART object
* \param [IN] tx UART Tx pin name to be used
* \param [IN] rx UART Rx pin name to be used
*/
void UartInit( Uart_t *obj, UartId_t uartId, PinNames tx, PinNames rx );
/*!
* \brief Configures the UART object and MCU peripheral
*
* \remark UartInit function must be called first.
*
* \param [IN] obj UART object
* \param [IN] mode Mode of operation for the UART
* \param [IN] baudrate UART baudrate
* \param [IN] wordLength packet length
* \param [IN] stopBits stop bits setup
* \param [IN] parity packet parity
* \param [IN] flowCtrl UART flow control
*/
void UartConfig( Uart_t *obj, UartMode_t mode, uint32_t baudrate, WordLength_t wordLength, StopBits_t stopBits, Parity_t parity, FlowCtrl_t flowCtrl );
/*!
* \brief DeInitializes the UART object and MCU pins
*
* \param [IN] obj UART object
*/
void UartDeInit( Uart_t *obj );
/*!
* \brief Sends a character to the UART
*
* \param [IN] obj UART object
* \param [IN] data Character to be sent
* \retval status [0: OK, 1: Busy]
*/
uint8_t UartPutChar( Uart_t *obj, uint8_t data );
/*!
* \brief Sends a buffer to the UART
*
* \param [IN] obj UART object
* \param [IN] buffer Buffer to be sent
* \param [IN] size Buffer size
* \retval status [0: OK, 1: Busy]
*/
uint8_t UartPutBuffer( Uart_t *obj, uint8_t *buffer, uint16_t size );
/*!
* \brief Gets a character from the UART
*
* \param [IN] obj UART object
* \param [IN] data Received character
* \retval status [0: OK, 1: Busy]
*/
uint8_t UartGetChar( Uart_t *obj, uint8_t *data );
/*!
* \brief Gets a character from the UART
*
* \param [IN] obj UART object
* \param [IN] buffer Received buffer
* \param [IN] size Number of bytes to be received
* \param [OUT] nbReadBytes Number of bytes really read
* \retval status [0: OK, 1: Busy]
*/
uint8_t UartGetBuffer( Uart_t *obj, uint8_t *buffer, uint16_t size, uint16_t *nbReadBytes );
#endif // __UART_H__
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/ble_peripheral/experimental/ble_nfc_pairing_reference/ble_m.c
|
/**
* Copyright (c) 2016 - 2019, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "ble_m.h"
#include "nordic_common.h"
#include "nrf_sdh.h"
#include "nrf_sdh_soc.h"
#include "nrf_sdh_ble.h"
#include "ble_conn_params.h"
#include "ble_conn_state.h"
#include "peer_manager.h"
#include "ble_advdata.h"
#include "app_timer.h"
#include "bsp.h"
#include "fds.h"
#include "nfc_ble_pair_lib.h"
#include "nrf_ble_gatt.h"
#include "nrf_ble_qwr.h"
#define NRF_LOG_MODULE_NAME BLE_M
#include "nrf_log.h"
NRF_LOG_MODULE_REGISTER();
#define MIN_CONN_INTERVAL MSEC_TO_UNITS(100, UNIT_1_25_MS) /**< Minimum acceptable connection interval (0.1 seconds). */
#define MAX_CONN_INTERVAL MSEC_TO_UNITS(200, UNIT_1_25_MS) /**< Maximum acceptable connection interval (0.2 second). */
#define SLAVE_LATENCY 0 /**< Slave latency. */
#define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS) /**< Connection supervisory timeout (4 seconds). */
#define FIRST_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(5000) /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(30000) /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT 3 /**< Number of attempts before giving up the connection parameter negotiation. */
#define MANUFACTURER_NAME "NordicSemiconductor" /**< Manufacturer. Will be passed to Device Information Service. */
#define APP_BLE_OBSERVER_PRIO 3 /**< Application's BLE observer priority. You shouldn't need to modify this value. */
#define APP_BLE_CONN_CFG_TAG 1 /**< A tag for a BLE stack configuration. */
#define APP_ADV_INTERVAL 300 /**< The advertising interval (in units of 0.625 ms. This value corresponds to 187.5 ms). */
#define APP_ADV_DURATION 18000 /**< The advertising duration (180 seconds) in units of 10 milliseconds. */
NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
NRF_BLE_QWR_DEF(m_qwr); /**< Context for the Queued Write module.*/
BLE_ADVERTISING_DEF(m_advertising); /**< Advertising module instance. */
static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the current connection. */
static ble_gap_conn_sec_mode_t m_sec_mode; /**< Holds GAP security requirements. */
static ble_advdata_t m_advdata; /**< Variable holding advertised data. */
static ble_uuid_t m_adv_uuids[] = /**< Universally unique service identifiers. */
{
{BLE_UUID_DEVICE_INFORMATION_SERVICE, BLE_UUID_TYPE_BLE}
};
/**@brief Function for handling BLE events.
*
* @param[in] p_ble_evt Bluetooth stack event.
* @param[in] p_context Unused.
*/
static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
{
ret_code_t err_code = NRF_SUCCESS;
switch (p_ble_evt->header.evt_id)
{
case BLE_GAP_EVT_DISCONNECTED:
NRF_LOG_INFO("Disonnected");
err_code = bsp_indication_set(BSP_INDICATE_IDLE);
APP_ERROR_CHECK(err_code);
m_conn_handle = BLE_CONN_HANDLE_INVALID;
break;
case BLE_GAP_EVT_CONNECTED:
NRF_LOG_INFO("Connected.");
err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
APP_ERROR_CHECK(err_code);
m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
err_code = nrf_ble_qwr_conn_handle_assign(&m_qwr, m_conn_handle);
APP_ERROR_CHECK(err_code);
break;
case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
{
NRF_LOG_DEBUG("PHY update request.");
ble_gap_phys_t const phys =
{
.rx_phys = BLE_GAP_PHY_AUTO,
.tx_phys = BLE_GAP_PHY_AUTO,
};
err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
APP_ERROR_CHECK(err_code);
} break;
case BLE_GATTC_EVT_TIMEOUT:
// Disconnect on GATT Client timeout event.
NRF_LOG_DEBUG("GATT Client Timeout.");
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
break;
case BLE_GATTS_EVT_TIMEOUT:
// Disconnect on GATT Server timeout event.
NRF_LOG_DEBUG("GATT Server Timeout.");
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
break;
case BLE_GAP_EVT_AUTH_STATUS:
NRF_LOG_INFO("BLE_GAP_EVT_AUTH_STATUS");
if (p_ble_evt->evt.gap_evt.params.auth_status.auth_status ==
BLE_GAP_SEC_STATUS_SUCCESS)
{
NRF_LOG_INFO("Authorization succeeded!");
}
else
{
NRF_LOG_INFO("Authorization failed with code: %u!",
p_ble_evt->evt.gap_evt.params.auth_status.auth_status);
}
break;
case BLE_GAP_EVT_CONN_SEC_UPDATE:
NRF_LOG_INFO("BLE_GAP_EVT_CONN_SEC_UPDATE");
NRF_LOG_INFO("Security mode: %u",
p_ble_evt->evt.gap_evt.params.conn_sec_update.conn_sec.sec_mode.lv);
break;
default:
// No implementation needed.
break;
}
UNUSED_VARIABLE(err_code);
}
/**@brief Function for handling the Connection Parameters Module.
*
* @details This function will be called for all events in the Connection Parameters Module which
* are passed to the application.
* @note All this function does is to disconnect. This could have been done by simply
* setting the disconnect_on_fail config parameter, but instead we use the event
* handler mechanism to demonstrate its use.
*
* @param[in] p_evt Event received from the Connection Parameters Module.
*/
static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
{
ret_code_t err_code;
if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
{
err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
APP_ERROR_CHECK(err_code);
}
}
/**@brief Function for handling a Connection Parameters error.
*
* @param[in] nrf_error Error code containing information about what went wrong.
*/
static void conn_params_error_handler(uint32_t nrf_error)
{
APP_ERROR_HANDLER(nrf_error);
}
/**@brief Function for handling Queued Write Module errors.
*
* @details A pointer to this function will be passed to each service which may need to inform the
* application about an error.
*
* @param[in] nrf_error Error code containing information about what went wrong.
*/
static void nrf_qwr_error_handler(uint32_t nrf_error)
{
APP_ERROR_HANDLER(nrf_error);
}
/**@brief Function for handling advertising events.
*
* @details This function will be called for advertising events which are passed to the application.
*
* @param[in] ble_adv_evt Advertising event.
*/
static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
{
ret_code_t err_code;
switch (ble_adv_evt)
{
case BLE_ADV_EVT_FAST:
NRF_LOG_INFO("Fast advertising.");
err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
APP_ERROR_CHECK(err_code);
break;
case BLE_ADV_EVT_IDLE:
NRF_LOG_INFO("Advertising stopped.");
err_code = bsp_indication_set(BSP_INDICATE_IDLE);
APP_ERROR_CHECK(err_code);
break;
default:
break;
}
}
ble_advertising_t * ble_adv_instance_ptr_get(void)
{
return &m_advertising;
}
/**@brief Function for initializing the BLE stack.
*
* @details Initializes the SoftDevice and the BLE event interrupt.
*/
void ble_stack_init(void)
{
ret_code_t err_code;
err_code = nrf_sdh_enable_request();
APP_ERROR_CHECK(err_code);
// Configure the BLE stack using the default settings.
// Fetch the start address of the application RAM.
uint32_t ram_start = 0;
err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
APP_ERROR_CHECK(err_code);
// Enable BLE stack.
err_code = nrf_sdh_ble_enable(&ram_start);
APP_ERROR_CHECK(err_code);
// Register a handler for BLE events.
NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
}
void advertising_init(void)
{
ret_code_t err_code;
ble_advertising_init_t init;
memset(&init, 0, sizeof(init));
// Only set up adv_data. Options will be set depending on if advertising will be enabled or not.
m_advdata.name_type = BLE_ADVDATA_FULL_NAME;
m_advdata.include_appearance = true;
m_advdata.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;
m_advdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
m_advdata.uuids_complete.p_uuids = m_adv_uuids;
init.advdata = m_advdata;
init.config.ble_adv_fast_enabled = true;
init.config.ble_adv_fast_interval = APP_ADV_INTERVAL;
init.config.ble_adv_fast_timeout = APP_ADV_DURATION;
init.config.ble_adv_whitelist_enabled = false;
init.config.ble_adv_on_disconnect_disabled = true;
init.evt_handler = on_adv_evt;
err_code = ble_advertising_init(&m_advertising, &init);
APP_ERROR_CHECK(err_code);
ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
}
void ble_disconnect(void)
{
ret_code_t err_code;
if (m_conn_handle != BLE_CONN_HANDLE_INVALID)
{
err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
}
}
void ble_set_device_name(char const * device_name)
{
ret_code_t err_code;
err_code = sd_ble_gap_device_name_set(&m_sec_mode,
(uint8_t const *)device_name,
strlen(device_name));
APP_ERROR_CHECK(err_code);
}
void gap_params_init(void)
{
ret_code_t err_code;
ble_gap_conn_params_t gap_conn_params;
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&m_sec_mode);
err_code = sd_ble_gap_appearance_set(BLE_APPEARANCE_UNKNOWN);
APP_ERROR_CHECK(err_code);
memset(&gap_conn_params, 0, sizeof(gap_conn_params));
gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
gap_conn_params.slave_latency = SLAVE_LATENCY;
gap_conn_params.conn_sup_timeout = CONN_SUP_TIMEOUT;
err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
APP_ERROR_CHECK(err_code);
}
void gatt_init()
{
ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, NULL);
APP_ERROR_CHECK(err_code);
}
void qwr_init(void)
{
ret_code_t err_code;
nrf_ble_qwr_init_t qwr_init_obj = {0};
qwr_init_obj.error_handler = nrf_qwr_error_handler;
err_code = nrf_ble_qwr_init(&m_qwr, &qwr_init_obj);
APP_ERROR_CHECK(err_code);
}
void conn_params_init(void)
{
ret_code_t err_code;
ble_conn_params_init_t cp_init;
memset(&cp_init, 0, sizeof(cp_init));
cp_init.p_conn_params = NULL;
cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
cp_init.next_conn_params_update_delay = NEXT_CONN_PARAMS_UPDATE_DELAY;
cp_init.max_conn_params_update_count = MAX_CONN_PARAMS_UPDATE_COUNT;
cp_init.start_on_notify_cccd_handle = BLE_GATT_HANDLE_INVALID;
cp_init.disconnect_on_fail = false;
cp_init.evt_handler = on_conn_params_evt;
cp_init.error_handler = conn_params_error_handler;
err_code = ble_conn_params_init(&cp_init);
APP_ERROR_CHECK(err_code);
}
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/include/qcloud_log.h
|
<gh_stars>1-10
#ifndef _QCLOUD_LOG_H_
#define _QCLOUD_LOG_H_
/* 单条日志最大长度 */
#define QCLOUD_LOG_LEN_MAX (1024)
/*用户自定义日志打印函数回调*/
typedef int (*qcloud_log_handler_t)(const char *message);
/**
* @brief 设置日志回调函数,用户接管日志内容用于输出到文件等操作
*
* @param handler 回调函数指针
*
*/
void qcloud_log_handler_set(qcloud_log_handler_t handler);
/**
* @brief 日志打印及上报函数,默认打印到标准输出,当用户设置日志打印handler时,回调handler
*
* 当日志上报功能打开时,会将日志缓存后上报到云端日志服务器
*
* @param file 源文件名
* @param func 函数名
* @param line 行号
* @param level 日志等级
*/
void qcloud_log_write(const char *file, const char *func, const int line, const int level, const char *fmt, ...);
/* 日志打印及上报对外接口*/
#if (QCLOUD_CFG_LOG_LEVEL >= QCLOUD_LOG_LEVEL_DEBUG)
#define QCLOUD_LOG_D(args...) qcloud_log_write(__FILE__, __FUNCTION__, __LINE__, QCLOUD_LOG_LEVEL_DEBUG, args)
#else
#define QCLOUD_LOG_D(args...)
#endif
#if (QCLOUD_CFG_LOG_LEVEL >= QCLOUD_LOG_LEVEL_INFO)
#define QCLOUD_LOG_I(args...) qcloud_log_write(__FILE__, __FUNCTION__, __LINE__, QCLOUD_LOG_LEVEL_INFO, args)
#else
#define QCLOUD_LOG_I(args...)
#endif
#if (QCLOUD_CFG_LOG_LEVEL >= QCLOUD_LOG_LEVEL_WARN)
#define QCLOUD_LOG_W(args...) qcloud_log_write(__FILE__, __FUNCTION__, __LINE__, QCLOUD_LOG_LEVEL_WARN, args)
#else
#define QCLOUD_LOG_W(args...)
#endif
#if (QCLOUD_CFG_LOG_LEVEL >= QCLOUD_LOG_LEVEL_ERROR)
#define QCLOUD_LOG_E(args...) qcloud_log_write(__FILE__, __FUNCTION__, __LINE__, QCLOUD_LOG_LEVEL_ERROR, args)
#else
#define QCLOUD_LOG_E(args...)
#endif
#endif
|
umaru724/TencentOS_E53_IA1
|
kernel/core/tos_binary_heap.c
|
/*----------------------------------------------------------------------------
* Tencent is pleased to support the open source community by making TencentOS
* available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* If you have downloaded a copy of the TencentOS binary from Tencent, please
* note that the TencentOS binary is licensed under the BSD 3-Clause License.
*
* If you have downloaded a copy of the TencentOS source code from Tencent,
* please note that TencentOS source code is licensed under the BSD 3-Clause
* License, except for the third-party components listed below which are
* subject to different license terms. Your integration of TencentOS into your
* own projects may require compliance with the BSD 3-Clause License, as well
* as the other licenses applicable to the third-party components included
* within TencentOS.
*---------------------------------------------------------------------------*/
#include "tos_k.h"
__STATIC_INLINE__ void bin_heap_item_copy_to(k_bin_heap_t *bin_heap, void *item_out, size_t *item_size)
{
memcpy(item_out, BIN_HEAP_FIRST_ITEM(bin_heap), bin_heap->item_size);
if (item_size) {
*item_size = bin_heap->item_size;
}
}
__STATIC_INLINE__ void bin_heap_item_copy_from(k_bin_heap_t *bin_heap, void *item_in)
{
memcpy(BIN_HEAP_LAST_ITEM(bin_heap), item_in, bin_heap->item_size);
}
__STATIC_INLINE__ void bin_heap_item_increase(k_bin_heap_t *bin_heap)
{
++bin_heap->total;
}
__STATIC_INLINE__ void bin_heap_item_decrease(k_bin_heap_t *bin_heap)
{
--bin_heap->total;
}
__STATIC__ void bin_heap_do_percolate_up(k_bin_heap_t *bin_heap, uint16_t hole, void *item_backup)
{
k_bin_heap_cmp cmp;
size_t item_size;
uint16_t parent, top;
void *hole_item, *parent_item;
top = 0u;
parent = BIN_HEAP_PARENT(hole);
cmp = bin_heap->cmp;
item_size = bin_heap->item_size;
hole_item = BIN_HEAP_THE_ITEM(bin_heap, hole);
parent_item = BIN_HEAP_THE_ITEM(bin_heap, parent);
while (hole > top && cmp(item_backup, parent_item)) {
memcpy(hole_item, parent_item, item_size);
hole = parent;
parent = BIN_HEAP_PARENT(hole);
hole_item = BIN_HEAP_THE_ITEM(bin_heap, hole);
parent_item = BIN_HEAP_THE_ITEM(bin_heap, parent);
}
hole_item = BIN_HEAP_THE_ITEM(bin_heap, hole);
memcpy(hole_item, item_backup, item_size);
}
__STATIC__ void bin_heap_percolate_up(k_bin_heap_t *bin_heap, void *item_backup)
{
bin_heap_do_percolate_up(bin_heap, bin_heap->total, item_backup);
}
__STATIC__ void bin_heap_percolate_down(k_bin_heap_t *bin_heap)
{
k_bin_heap_cmp cmp;
size_t item_size;
uint16_t lchild, rchild, the_child, hole;
void *hole_item, *rchild_item, *lchild_item, *the_child_item;
hole = 0u;
rchild = BIN_HEAP_RCHILD(hole);
lchild = BIN_HEAP_LSIBLING(rchild);
the_child = rchild;
cmp = bin_heap->cmp;
item_size = bin_heap->item_size;
hole_item = BIN_HEAP_THE_ITEM(bin_heap, hole);
rchild_item = BIN_HEAP_THE_ITEM(bin_heap, rchild);
lchild_item = BIN_HEAP_THE_ITEM(bin_heap, lchild);
while (the_child < bin_heap->total) {
if (cmp(lchild_item, rchild_item)) {
the_child = lchild;
}
the_child_item = BIN_HEAP_THE_ITEM(bin_heap, the_child);
memcpy(hole_item, the_child_item, item_size);
hole = the_child;
the_child = BIN_HEAP_RCHILD(the_child);
rchild = the_child;
lchild = BIN_HEAP_LSIBLING(rchild);
hole_item = BIN_HEAP_THE_ITEM(bin_heap, hole);
rchild_item = BIN_HEAP_THE_ITEM(bin_heap, rchild);
lchild_item = BIN_HEAP_THE_ITEM(bin_heap, lchild);
}
if (the_child == bin_heap->total) {
memcpy(hole_item, lchild_item, item_size);
hole = lchild;
hole_item = BIN_HEAP_THE_ITEM(bin_heap, hole);
}
bin_heap_do_percolate_up(bin_heap, hole, BIN_HEAP_LAST_ITEM(bin_heap));
}
__API__ k_err_t tos_bin_heap_create(k_bin_heap_t *bin_heap, void *pool, size_t item_cnt, size_t item_size, k_bin_heap_cmp cmp)
{
TOS_PTR_SANITY_CHECK(bin_heap);
TOS_PTR_SANITY_CHECK(pool);
TOS_PTR_SANITY_CHECK(cmp);
bin_heap->total = 0;
bin_heap->cmp = cmp;
bin_heap->item_size = item_size;
bin_heap->item_cnt = item_cnt;
bin_heap->pool = (uint8_t *)pool;
TOS_OBJ_INIT(bin_heap, KNL_OBJ_TYPE_BINARY_HEAP);
#if TOS_CFG_MMHEAP_EN > 0u
knl_object_alloc_set_static(&bin_heap->knl_obj);
#endif
return K_ERR_NONE;
}
__API__ k_err_t tos_bin_heap_destroy(k_bin_heap_t *bin_heap)
{
TOS_PTR_SANITY_CHECK(bin_heap);
TOS_OBJ_VERIFY(bin_heap, KNL_OBJ_TYPE_BINARY_HEAP);
#if TOS_CFG_MMHEAP_EN > 0u
if (!knl_object_alloc_is_static(&bin_heap->knl_obj)) {
return K_ERR_OBJ_INVALID_ALLOC_TYPE;
}
#endif
bin_heap->total = 0;
bin_heap->cmp = K_NULL;
bin_heap->item_size = 0;
bin_heap->item_cnt = 0;
bin_heap->pool = K_NULL;
TOS_OBJ_DEINIT(bin_heap);
#if TOS_CFG_MMHEAP_EN > 0u
knl_object_alloc_reset(&bin_heap->knl_obj);
#endif
return K_ERR_NONE;
}
#if TOS_CFG_MMHEAP_EN > 0u
__API__ k_err_t tos_bin_heap_create_dyn(k_bin_heap_t *bin_heap, size_t item_cnt, size_t item_size, k_bin_heap_cmp cmp)
{
void *pool;
TOS_PTR_SANITY_CHECK(bin_heap);
TOS_PTR_SANITY_CHECK(cmp);
pool = tos_mmheap_alloc(item_cnt * item_size);
if (!pool) {
return K_ERR_OUT_OF_MEMORY;
}
bin_heap->total = 0;
bin_heap->cmp = cmp;
bin_heap->item_size = item_size;
bin_heap->item_cnt = item_cnt;
bin_heap->pool = (uint8_t *)pool;
TOS_OBJ_INIT(bin_heap, KNL_OBJ_TYPE_BINARY_HEAP);
knl_object_alloc_set_dynamic(&bin_heap->knl_obj);
return K_ERR_NONE;
}
__API__ k_err_t tos_bin_heap_destroy_dyn(k_bin_heap_t *bin_heap)
{
TOS_PTR_SANITY_CHECK(bin_heap);
TOS_OBJ_VERIFY(bin_heap, KNL_OBJ_TYPE_BINARY_HEAP);
if (!knl_object_alloc_is_dynamic(&bin_heap->knl_obj)) {
return K_ERR_OBJ_INVALID_ALLOC_TYPE;
}
tos_mmheap_free(bin_heap->pool);
bin_heap->total = 0;
bin_heap->cmp = K_NULL;
bin_heap->item_size = 0;
bin_heap->item_cnt = 0;
bin_heap->pool = K_NULL;
TOS_OBJ_DEINIT(bin_heap);
knl_object_alloc_reset(&bin_heap->knl_obj);
return K_ERR_NONE;
}
#endif
__API__ k_err_t tos_bin_heap_push(k_bin_heap_t *bin_heap, void *item, size_t item_size)
{
TOS_CPU_CPSR_ALLOC();
TOS_PTR_SANITY_CHECK(bin_heap);
TOS_PTR_SANITY_CHECK(item);
TOS_OBJ_VERIFY(bin_heap, KNL_OBJ_TYPE_BINARY_HEAP);
if (item_size != bin_heap->item_size) {
return K_ERR_BIN_HEAP_ITEM_SIZE_NOT_MATCH;
}
if (tos_bin_heap_is_full(bin_heap)) {
return K_ERR_BIN_HEAP_FULL;
}
TOS_CPU_INT_DISABLE();
bin_heap_item_copy_from(bin_heap, item);
bin_heap_percolate_up(bin_heap, item);
bin_heap_item_increase(bin_heap);
TOS_CPU_INT_ENABLE();
return K_ERR_NONE;
}
__API__ k_err_t tos_bin_heap_pop(k_bin_heap_t *bin_heap, void *item, size_t *item_size)
{
TOS_CPU_CPSR_ALLOC();
TOS_PTR_SANITY_CHECK(bin_heap);
TOS_PTR_SANITY_CHECK(item);
TOS_OBJ_VERIFY(bin_heap, KNL_OBJ_TYPE_BINARY_HEAP);
TOS_CPU_INT_DISABLE();
if (tos_bin_heap_is_empty(bin_heap)) {
TOS_CPU_INT_ENABLE();
return K_ERR_BIN_HEAP_EMPTY;
}
bin_heap_item_copy_to(bin_heap, item, item_size);
bin_heap_item_decrease(bin_heap);
bin_heap_percolate_down(bin_heap);
TOS_CPU_INT_ENABLE();
return K_ERR_NONE;
}
__API__ k_err_t tos_bin_heap_flush(k_bin_heap_t *bin_heap)
{
TOS_CPU_CPSR_ALLOC();
TOS_PTR_SANITY_CHECK(bin_heap);
TOS_OBJ_VERIFY(bin_heap, KNL_OBJ_TYPE_BINARY_HEAP);
TOS_CPU_INT_DISABLE();
bin_heap->total = 0;
TOS_CPU_INT_ENABLE();
return K_ERR_NONE;
}
__API__ int tos_bin_heap_is_empty(k_bin_heap_t *bin_heap)
{
TOS_CPU_CPSR_ALLOC();
int is_empty = K_FALSE;
TOS_PTR_SANITY_CHECK_RC(bin_heap, K_FALSE);
TOS_OBJ_VERIFY_RC(bin_heap, KNL_OBJ_TYPE_BINARY_HEAP, K_FALSE);
TOS_CPU_INT_DISABLE();
is_empty = (bin_heap->total == 0);
TOS_CPU_INT_ENABLE();
return is_empty;
}
__API__ int tos_bin_heap_is_full(k_bin_heap_t *bin_heap)
{
TOS_CPU_CPSR_ALLOC();
int is_full = K_FALSE;
TOS_PTR_SANITY_CHECK_RC(bin_heap, K_FALSE);
TOS_OBJ_VERIFY_RC(bin_heap, KNL_OBJ_TYPE_BINARY_HEAP, K_FALSE);
TOS_CPU_INT_DISABLE();
is_full = (bin_heap->total == bin_heap->item_cnt);
TOS_CPU_INT_ENABLE();
return is_full;
}
|
umaru724/TencentOS_E53_IA1
|
components/fs/vfs/include/tos_vfs_fs.h
|
#ifndef _TOS_VFS_FS_H_
#define _TOS_VFS_FS_H_
#if TOS_CFG_VFS_EN > 0u
typedef struct vfs_inode_st vfs_inode_t;
typedef struct vfs_filesystem_operations_st {
int (*open) (vfs_file_t *file, const char *pathname, vfs_oflag_t flags);
int (*close) (vfs_file_t *file);
ssize_t (*read) (vfs_file_t *file, void *buf, size_t count);
ssize_t (*write) (vfs_file_t *file, const void *buf, size_t count);
vfs_off_t (*lseek) (vfs_file_t *file, vfs_off_t offset, vfs_whence_t whence);
int (*ioctl) (vfs_file_t *file, int cmd, unsigned long arg);
int (*sync) (vfs_file_t *file);
int (*dup) (const vfs_file_t *old_file, vfs_file_t *new_file);
int (*fstat) (const vfs_file_t *file, vfs_fstat_t *buf);
int (*truncate) (vfs_file_t *file, vfs_off_t length);
int (*opendir) (vfs_dir_t *dir, const char *pathname);
int (*closedir) (vfs_dir_t *dir);
int (*readdir) (vfs_dir_t *dir, vfs_dirent_t *dirent);
int (*rewinddir) (vfs_dir_t *dir);
int (*bind) (vfs_inode_t *fs, vfs_inode_t *dev);
int (*unbind) (vfs_inode_t *fs);
int (*statfs) (vfs_inode_t *fs, vfs_fsstat_t *buf);
int (*unlink) (vfs_inode_t *fs, const char *pathname);
int (*mkdir) (vfs_inode_t *fs, const char *pathname);
int (*rmdir) (vfs_inode_t *fs, const char *pathname);
int (*rename) (vfs_inode_t *fs, const char *oldpath, const char *newpath);
int (*stat) (vfs_inode_t *fs, const char *pathname, vfs_fstat_t *buf);
int (*mkfs) (vfs_inode_t *dev, int opt, unsigned long arg);
} vfs_fs_ops_t;
typedef struct vfs_filesystem_map_st {
const char *name;
vfs_fs_ops_t *ops;
k_list_t list;
} vfs_fsmap_t;
__API__ vfs_err_t tos_vfs_fs_register(const char *fs_name, vfs_fs_ops_t *ops);
__API__ vfs_err_t tos_vfs_fs_unregister(const char *fs_name);
__API__ vfs_err_t tos_vfs_fs_mount(const char *device_path, const char *dir, const char *fs_name);
__API__ vfs_err_t tos_vfs_fs_umount(const char *dir);
__API__ vfs_err_t tos_vfs_fs_mkfs(const char *device_path, const char *fs_name, int opt, unsigned long arg);
#endif
#endif /* _TOS_VFS_FS_H_ */
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/peripheral/qdec/qenc_sim.h
|
<reponame>umaru724/TencentOS_E53_IA1<filename>platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/peripheral/qdec/qenc_sim.h
/**
* Copyright (c) 2014 - 2019, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef QENC_SIM_H__
#define QENC_SIM_H__
#include <stdbool.h>
#include <stdint.h>
#include "boards.h"
#include "nrf_qdec.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#define QENC_CONFIG_PIO_LED ARDUINO_A3_PIN
#define QENC_CONFIG_PIO_A ARDUINO_A5_PIN
#define QENC_CONFIG_PIO_B ARDUINO_A4_PIN
#define QENC_CONFIG_PIO_PULL_CFG NRF_GPIO_PIN_NOPULL
/**@brief quadrature encoder simulator initialization.
*
* The simulator uses GPIOTE module to generate pulses compatible with QDEC on A,B outputs using LED input as a clocking signal
* The sole purpose of this module is to test software driver
*
* @param[in] active level for LED in QDEC
*
*/
void qenc_init(nrf_qdec_ledpol_t led_pol);
/**@brief quadrature simulator simulator set-up for pulse generation.
* This function starts normal pulse generation if pulse_count is nonzero
* When pulse_count is greater then zero positive pulses are generated and pulse_count is decremented till it reaches zero
* When pulse_count is less then zero negative pulses are generated and pulse_count is incremented till it reaches zero
*
* @param[in] number of normal pulses
*
*/
void qenc_pulse_count_set(int32_t pulse_count);
/**@brief quadrature simulator simulator set-up set-up for pulse and double pulse generation.
* This function starts leading normal pulse generation if pulse_count is nonzero
* and trailing double generation if dble_pulse_count is nonzero
* When pulse_count is greater then zero positive pulses are generated and pulse_count is decremented till it reaches zero
* When pulse_count is less then zero negative pulses are generated and pulse_count is incremented till it reaches zero
* Next if dble_pulse_count is nonzero double pulses are generated and dble_pulse_count is decremented till it reaches zero
*
* @param[in] number of normal pulses
* @param[in] number of double pulses
*/
void qenc_pulse_dblpulse_count_set(int32_t pulse_count, uint32_t dble_pulse_count);
#ifdef __cplusplus
}
#endif
#endif // QENC_SIM_H__
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/external/thedotfactory_fonts/nrf_font.h
|
/* Copyright (c) 2016 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef NRF_FONT_H__
#define NRF_FONT_H__
#include "stdint.h"
/** @file
*
* @defgroup nrf_font Font header
* @{
* @ingroup nrf_gfx
*
* @brief Generated font structures.
*/
/**
* @brief Font char information.
*/
typedef struct
{
uint8_t widthBits; /**< Width in bits (or pixels) of the character. */
uint16_t offset; /**< Offset of the character's bitmap, in bytes, into the FONT_INFO's data array. */
}FONT_CHAR_INFO;
/**
* @brief Font descriptor.
*/
typedef struct
{
uint8_t height; /**< Height in bits (or pixels), of the font's characters. */
uint8_t startChar; /**< The first character in the font (e.g. in charInfo and data). */
uint8_t endChar; /**< The last character in the font. */
uint8_t spacePixels; /**< Number of pixels that the space character takes up. */
const FONT_CHAR_INFO * charInfo; /**< Pointer to array of char information. */
const uint8_t * data; /**< Pointer to a generated array of character visual representation. */
}FONT_INFO;
/** @} */
#endif // NRF_FONT_H__
|
umaru724/TencentOS_E53_IA1
|
kernel/core/include/tos_mmblk.h
|
/*----------------------------------------------------------------------------
* Tencent is pleased to support the open source community by making TencentOS
* available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* If you have downloaded a copy of the TencentOS binary from Tencent, please
* note that the TencentOS binary is licensed under the BSD 3-Clause License.
*
* If you have downloaded a copy of the TencentOS source code from Tencent,
* please note that TencentOS source code is licensed under the BSD 3-Clause
* License, except for the third-party components listed below which are
* subject to different license terms. Your integration of TencentOS into your
* own projects may require compliance with the BSD 3-Clause License, as well
* as the other licenses applicable to the third-party components included
* within TencentOS.
*---------------------------------------------------------------------------*/
#ifndef _TOS_MMBLK_H_
#define _TOS_MMBLK_H_
#if TOS_CFG_MMBLK_EN > 0u
#define K_MMBLK_NEXT_BLK(blk_curr, blk_size) ((void *)((cpu_addr_t)blk_curr + blk_size))
#define K_MMBLK_ALIGN_MASK (sizeof(void *) - 1u)
typedef struct k_mmblk_pool_st {
#if TOS_CFG_OBJECT_VERIFY_EN > 0u
knl_obj_t knl_obj;
#endif
void *pool_start;
void *free_list;
size_t blk_size;
size_t blk_max;
size_t blk_free;
} k_mmblk_pool_t;
/**
* @brief Create a memory manage block pool.
* Create a memory manage block pool.
*
* @attention None
*
* @param[in] mbp pointer to the memory block pool handler.
* @param[in] pool_start start address of the pool.
* @param[in] blk_num number of the blocks in the pool.
* @param[in] blk_size size of each block in the pool.
*
* @return errcode
* @retval #K_ERR_MMBLK_INVALID_POOL_ADDR start address of the pool is invalid.
* @retval #K_ERR_MMBLK_INVALID_BLK_SIZE size of the block is invalid.
* @retval #K_ERR_NONE return successfully.
*/
__API__ k_err_t tos_mmblk_pool_create(k_mmblk_pool_t *mbp, void *pool_start, size_t blk_num, size_t blk_size);
/**
* @brief Destroy a memory manage block pool.
* Destroy a memory manage block pool.
*
* @attention None
*
* @param[in] mbp pointer to the memory block pool handler.
*
* @return errcode
* @retval #K_ERR_OBJ_INVALID mbp is not a valid memory block pool handler.
* @retval #K_ERR_NONE return successfully.
*/
__API__ k_err_t tos_mmblk_pool_destroy(k_mmblk_pool_t *mbp);
/**
* @brief Create a memory manage block pool.
* Create a memory manage block pool.
*
* @attention None
*
* @param[in] mbp pointer to the memory block pool handler.
* @param[in] pool_start start address of the pool.
* @param[in] blk_num number of the blocks in the pool.
* @param[in] blk_size size of each block in the pool.
*
* @return errcode
* @retval #K_ERR_MMBLK_POOL_EMPTY the pool is empty.
* @retval #K_ERR_NONE return successfully.
*/
__API__ k_err_t tos_mmblk_alloc(k_mmblk_pool_t *mbp, void **blk);
/**
* @brief Create a memory manage block pool.
* Create a memory manage block pool.
*
* @attention None
*
* @param[in] mbp pointer to the memory block pool handler.
* @param[in] pool_start start address of the pool.
* @param[in] blk_num number of the blocks in the pool.
* @param[in] blk_size size of each block in the pool.
*
* @return errcode
* @retval #K_ERR_MMBLK_POOL_FULL the pool is full.
* @retval #K_ERR_NONE return successfully.
*/
__API__ k_err_t tos_mmblk_free(k_mmblk_pool_t *mbp, void *blk);
#endif
#endif /* _TOS_MMBLK_H_ */
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/external/infineon/optiga/dtls/DtlsWindowing.c
|
<gh_stars>1-10
/**
* MIT License
*
* Copyright (c) 2018 Infineon Technologies AG
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE
*
*
* \file
*
* \brief This file implements the APIs, types used in the
* for DTLS windowing.
*
* \addtogroup grMutualAuth
* @{
*/
#include <stdint.h>
#include "optiga/dtls/DtlsWindowing.h"
#include "optiga/dtls/DtlsRecordLayer.h"
#ifdef MODULE_ENABLE_DTLS_MUTUAL_AUTH
/// @cond hidden
///Maximum window size supported
#define MAX_WINDOW_SIZE 64
/// @endcond
/**
* Implementation for Record Replay Detection.<br>
* Return status as #OCP_RL_WINDOW_IGNORE if record is already received or record sequence number is less then lower bound of window.<br>
* Under some erroneous conditions, error codes from Record Layer can also be returned.<br>
*
* \param[in] PpsWindow Pointer to the structure that contains details required for windowing like
* record sequence number, lower and higher boundaries.
*
* \retval OCP_RL_WINDOW_UPDATED Valid record is received and window is updated.
* \retval OCP_RL_WINDOW_MOVED Valid record is received and window is updated and moved.
* \retval OCP_RL_WINDOW_IGNORE Failure in execution and record already received.
*
*/
int32_t DtlsCheckReplay(sWindow_d *PpsWindow)
{
int32_t i4Status = (int32_t) OCP_RL_WINDOW_IGNORE;
int32_t i4Retval;
sUint64 sIntermidateVal;
do
{
#ifdef ENABLE_NULL_CHECKS
if((NULL == PpsWindow) || (NULL == PpsWindow->fValidateRecord))
{
break;
}
#endif
if((MAX_WINDOW_SIZE < PpsWindow->bWindowSize) || (WORD_SIZE > PpsWindow->bWindowSize))
{
break;
}
//Compare the received sequence number with the Lower window boundary
i4Retval = CompareUint64(&PpsWindow->sRecvSeqNumber, &PpsWindow->sLowerBound);
//If sequence number is lesser than the low bound of window
if(LESSER_THAN == i4Retval)
{
break;
}
//If sequence number is greater than low bound window
//Compare the received sequence number with the Higher window boundary
i4Retval = CompareUint64(&PpsWindow->sRecvSeqNumber, &PpsWindow->sHigherBound);
//If Sequence number is greater than high bound of the window
//Slide the window
if(GREATER_THAN == i4Retval)
{
//Record validation
i4Retval = PpsWindow->fValidateRecord(PpsWindow->pValidateArgs);
//If record validation fails
if(OCP_RL_OK != i4Retval)
{
if(((int32_t)CMD_LIB_DECRYPT_FAILURE == i4Retval) || ((int32_t)OCP_RL_MALLOC_FAILURE == i4Retval))
{
i4Status = i4Retval;
}
break;
}
else
{
//Calculate the count to slide the window
//lint --e{534} suppress "The return value check is suppressed as this function always return Success.Only error condition where
//RecvSeqNumber < sHigherBound is not possible as it will enter this path only when RecvSeqNumber > sHigherBound"
i4Retval = SubtractUint64(&PpsWindow->sRecvSeqNumber, &PpsWindow->sHigherBound, &sIntermidateVal);
//Slide the window
i4Retval = ShiftLeftUint64(&PpsWindow->sWindowFrame, sIntermidateVal, PpsWindow->bWindowSize, (uint8_t)MAX_WINDOW_SIZE);
if(UTIL_SUCCESS != i4Retval)
{
break;
}
//Set the sequence number received as the Higher Bound
PpsWindow->sHigherBound = PpsWindow->sRecvSeqNumber;
sIntermidateVal.dwHigherByte = DEFAULT_LOWBOUND_DOUBLEWORD ;
sIntermidateVal.dwLowerByte = (uint32_t)PpsWindow->bWindowSize - 1;
//Difference of Higher bound and window size is set as lower bound
i4Retval = SubtractUint64(&PpsWindow->sHigherBound, &sIntermidateVal, &PpsWindow->sLowerBound);
if(UTIL_SUCCESS != i4Retval)
{
break;
}
//Set the bit position of sequence number to 1 which is the MSB of the window frame
i4Retval = Utility_SetBitUint64(&PpsWindow->sWindowFrame, PpsWindow->bWindowSize, PpsWindow->bWindowSize);
if(UTIL_SUCCESS != i4Retval)
{
break;
}
i4Status = (int32_t) OCP_RL_WINDOW_MOVED;
break;
}
}
//Compare the received sequence number with the Higher and Lower window boundary
//lint --e{534} suppress "The return value check is suppressed as this function always return Success.Only error condition where
//RecvSeqNumber > sHigherBound is not possible as it will enter this path only when RecvSeqNumber < sHigherBound"
//Calculate bit position of sequence number from high bound of the window
i4Retval = SubtractUint64(&PpsWindow->sHigherBound, &PpsWindow->sRecvSeqNumber, &sIntermidateVal);
//If window size is equal to 32
if(WORD_SIZE == PpsWindow->bWindowSize)
{
if((MOST_SIGNIFICANT_BIT_HIGH == ((PpsWindow->sWindowFrame.dwHigherByte << (uint32_t)((WORD_SIZE - sIntermidateVal.dwLowerByte) - 1))
& MOST_SIGNIFICANT_BIT_HIGH)))
{
break;
}
}
else
{
//Received sequence number is in the lower byte of the window frame
if((DEFAULT_LOWBOUND_DOUBLEWORD == sIntermidateVal.dwHigherByte) && (sIntermidateVal.dwLowerByte < WORD_SIZE))
{
if((MOST_SIGNIFICANT_BIT_HIGH == ((PpsWindow->sWindowFrame.dwLowerByte << (uint32_t)((WORD_SIZE - sIntermidateVal.dwLowerByte) - 1 )) & MOST_SIGNIFICANT_BIT_HIGH)))
{
break;
}
}
//Received sequence number is in the higher byte of the window frame
else if((DEFAULT_LOWBOUND_DOUBLEWORD == sIntermidateVal.dwHigherByte) && (sIntermidateVal.dwLowerByte >= WORD_SIZE))
{
if((MOST_SIGNIFICANT_BIT_HIGH == ((PpsWindow->sWindowFrame.dwHigherByte << (uint32_t)((MAX_WINDOW_SIZE - sIntermidateVal.dwLowerByte) - 1)) & MOST_SIGNIFICANT_BIT_HIGH)))
{
break;
}
}
}
//Record validation
i4Retval = PpsWindow->fValidateRecord(PpsWindow->pValidateArgs);
//If record validation fails
if(OCP_RL_OK != i4Retval)
{
if(((int32_t)CMD_LIB_DECRYPT_FAILURE == i4Retval) || ((int32_t)OCP_RL_MALLOC_FAILURE == i4Retval))
{
i4Status = i4Retval;
}
break;
}
else
{
i4Retval = SubtractUint64(&PpsWindow->sRecvSeqNumber, &PpsWindow->sLowerBound,&sIntermidateVal);
if(UTIL_SUCCESS != i4Retval)
{
break;
}
//Set the bit position of sequence number to 1
i4Retval = Utility_SetBitUint64(&PpsWindow->sWindowFrame, PpsWindow->bWindowSize, (uint8_t)sIntermidateVal.dwLowerByte);
if(UTIL_SUCCESS != i4Retval)
{
break;
}
if(PpsWindow->bWindowSize > WORD_SIZE)
{
PpsWindow->sWindowFrame.dwHigherByte &= MASK_DOUBLE_WORD >> (MAX_WINDOW_SIZE - PpsWindow->bWindowSize);
}
i4Status = (int32_t)OCP_RL_WINDOW_UPDATED;
}
}while(0);
return i4Status;
}
#endif /*MODULE_ENABLE_DTLS_MUTUAL_AUTH*/
|
umaru724/TencentOS_E53_IA1
|
board/TencentOS_tiny_EVB_MX/BSP/Hardware/ONCHIP_FLASH/onchip_flash.c
|
#include "tos_kv.h"
#include "stm32l4xx.h"
#define ONCHIP_FLASH_ADDR_START 0x08000000 // start address for onchip flash for stm32l431RCTX
#define ONCHIP_FLASH_ADDR_MAX 0x0803FFFF // 256K flash addr for stm32l431RCTX
#define SECTOR_SIZE 2048 // sector size for stm32l431RCTX
#define SECTOR_SIZE_LOG2 11 // 2 ^ 11 = 2048
#define FOR_KV_FLASH_SIZE (2 * SECTOR_SIZE) // storage for kv
#define FOR_KV_FLASH_START 0x803d000
int stm32l4_norflash_onchip_read(uint32_t addr, void *buf, size_t len)
{
memcpy(buf, (void *)addr, len);
return 0;
}
int stm32l4_norflash_onchip_write(uint32_t addr, const void *buf, size_t len)
{
int i = 0;
uint8_t *array = (uint8_t *)buf;
HAL_StatusTypeDef hal_status;
HAL_FLASH_Unlock();
tos_cpu_int_disable();
for (i = 0; i < len; i += 8) {
hal_status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD,
addr + i,
*(uint64_t *)&array[i]);
if (hal_status != HAL_OK) {
return -1;
}
}
HAL_FLASH_Lock();
tos_cpu_int_enable();
return 0;
}
int stm32l4_norflash_onchip_erase(uint32_t addr, size_t size)
{
uint32_t page_err = 0;
HAL_StatusTypeDef hal_status;
FLASH_EraseInitTypeDef erase_para;
erase_para.TypeErase = FLASH_TYPEERASE_PAGES;
erase_para.Banks = FLASH_BANK_1;
erase_para.Page = addr / SECTOR_SIZE;
erase_para.NbPages = size / SECTOR_SIZE;
HAL_FLASH_Unlock();
tos_cpu_int_disable();
hal_status = HAL_FLASHEx_Erase(&erase_para, &page_err);
HAL_FLASH_Lock();
tos_cpu_int_enable();
if (hal_status != HAL_OK) {
return -1;
}
return 0;
}
kv_flash_drv_t stm32l4_norflash_onchip_drv = {
.write = stm32l4_norflash_onchip_write,
.read = stm32l4_norflash_onchip_read,
.erase = stm32l4_norflash_onchip_erase,
};
kv_flash_prop_t stm32l4_norflash_onchip_prop = {
.sector_size_log2 = SECTOR_SIZE_LOG2,
.pgm_type = KV_FLASH_PROGRAM_TYPE_DOUBLEWORD,
.flash_start = FOR_KV_FLASH_START,
.flash_size = FOR_KV_FLASH_SIZE,
};
|
umaru724/TencentOS_E53_IA1
|
arch/arm/arm-v7a/common/include/tos_arm.h
|
<filename>arch/arm/arm-v7a/common/include/tos_arm.h<gh_stars>1-10
/*----------------------------------------------------------------------------
* Tencent is pleased to support the open source community by making TencentOS
* available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* If you have downloaded a copy of the TencentOS binary from Tencent, please
* note that the TencentOS binary is licensed under the BSD 3-Clause License.
*
* If you have downloaded a copy of the TencentOS source code from Tencent,
* please note that TencentOS source code is licensed under the BSD 3-Clause
* License, except for the third-party components listed below which are
* subject to different license terms. Your integration of TencentOS into your
* own projects may require compliance with the BSD 3-Clause License, as well
* as the other licenses applicable to the third-party components included
* within TencentOS.
*---------------------------------------------------------------------------*/
#ifndef _TOS_ARM_H_
#define _TOS_ARM_H_
#define DSB __ASM__ __VOLATILE__("dsb" ::: "memory")
#define DMB __ASM__ __VOLATILE__("dmb" ::: "memory")
#define ISB __ASM__ __VOLATILE__("isb" ::: "memory")
#define __STRINGIFY(x) #x
#define ARM_MCR(coproc, opcode_1, src, CRn, CRm, opcode_2) \
__ASM__ __VOLATILE__ ("MCR " __STRINGIFY(p##coproc) ", " __STRINGIFY(opcode_1) ", " \
"%0, " __STRINGIFY(c##CRn) ", " __STRINGIFY(c##CRm) ", " \
__STRINGIFY(opcode_2) \
: : "r" (src) )
#define ARM_MRC(coproc, opcode_1, CRn, CRm, opcode_2) \
({ \
uint32_t __dst; \
__ASM__ __VOLATILE__ ("MRC " __STRINGIFY(p##coproc) ", " __STRINGIFY(opcode_1) ", " \
"%0, " __STRINGIFY(c##CRn) ", " __STRINGIFY(c##CRm) ", " \
__STRINGIFY(opcode_2) \
: "=r" (__dst) ); \
__dst; \
})
#endif /* _TOS_ARM_H_ */
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/src/mqtt/qcloud_mqtt_glue.c
|
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud.h"
__QCLOUD_STATIC__ mqtt_event_type_t mqtt_glue_event_type_get(qcloud_mqtt_ack_type_t ack_type, int is_nack, int is_timer_expired)
{
mqtt_event_type_t event_type;
if (is_nack) {
switch (ack_type) {
case QCLOUD_MQTT_ACK_TYPE_PUBACK:
event_type = MQTT_EVENT_PUBLISH_NACK;
break;
case QCLOUD_MQTT_ACK_TYPE_SUBACK:
event_type = MQTT_EVENT_SUBCRIBE_NACK;
break;
case QCLOUD_MQTT_ACK_TYPE_UNSUBACK:
event_type = MQTT_EVENT_UNSUBCRIBE_NACK;
break;
}
} else if (is_timer_expired) {
switch (ack_type) {
case QCLOUD_MQTT_ACK_TYPE_PUBACK:
event_type = MQTT_EVENT_PUBLISH_TIMEOUT;
break;
case QCLOUD_MQTT_ACK_TYPE_SUBACK:
event_type = MQTT_EVENT_SUBCRIBE_TIMEOUT;
break;
case QCLOUD_MQTT_ACK_TYPE_UNSUBACK:
event_type = MQTT_EVENT_UNSUBCRIBE_TIMEOUT;
break;
}
} else {
switch (ack_type) {
case QCLOUD_MQTT_ACK_TYPE_PUBACK:
event_type = MQTT_EVENT_PUBLISH_SUCCESS;
break;
case QCLOUD_MQTT_ACK_TYPE_SUBACK:
event_type = MQTT_EVENT_SUBCRIBE_SUCCESS;
break;
case QCLOUD_MQTT_ACK_TYPE_UNSUBACK:
event_type = MQTT_EVENT_UNSUBCRIBE_SUCCESS;
break;
}
}
return event_type;
}
__QCLOUD_INTERNAL__ char *mqtt_glue_string_const2mutable(const char *orig_str, size_t orig_str_len)
{
char *str_mutable = NULL;
str_mutable = osal_malloc(orig_str_len + 1);
if (!str_mutable) {
return NULL;
}
strncpy(str_mutable, orig_str, orig_str_len);
str_mutable[orig_str_len] = 0;
return str_mutable;
}
__QCLOUD_INTERNAL__ void mqtt_glue_string_mutable_free(char *str_mutable)
{
osal_free(str_mutable);
}
__QCLOUD_INTERNAL__ uint16_t mqtt_glue_packet_id_generate(qcloud_mqtt_client_t *client)
{
#define PACKET_ID_MAX (65535)
uint16_t packet_id = client->packet_id;
osal_mutex_lock(client->global_lock);
client->packet_id = (packet_id == PACKET_ID_MAX ? 1 : (packet_id + 1));
osal_mutex_unlock(client->global_lock);
return client->packet_id;
}
__QCLOUD_INTERNAL__ void mqtt_glue_connect_id_generate(char *conn_id)
{
int i, flag;
srand((unsigned)osal_timer_current_sec());
for (i = 0; i < QCLOUD_MQTT_CONNECT_ID_MAX - 1; ++i) {
flag = rand() % 3;
switch (flag) {
case 0:
conn_id[i] = (rand() % 26) + 'a';
break;
case 1:
conn_id[i] = (rand() % 26) + 'A';
break;
case 2:
conn_id[i] = (rand() % 10) + '0';
break;
}
}
conn_id[QCLOUD_MQTT_CONNECT_ID_MAX - 1] = '\0';
}
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_glue_packet_send(qcloud_mqtt_client_t *client, size_t length, osal_timer_t *timer)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(timer, QCLOUD_ERR_INVAL);
qcloud_err_t rc = QCLOUD_ERR_SUCCESS;
size_t cur_bytes_send = 0, total_bytes_send = 0;
if (length >= sizeof(client->tx_buffer)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
while (total_bytes_send < length && !osal_timer_is_expired(timer)) {
rc = client->network.write(&(client->network), &client->tx_buffer[total_bytes_send], length, osal_timer_remain(timer), &cur_bytes_send);
if (rc != QCLOUD_ERR_SUCCESS) {
/* there was an error writing the data */
break;
}
total_bytes_send += cur_bytes_send;
}
if (total_bytes_send == length) {
/* record the fact that we have successfully sent the packet */
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
QCLOUD_FUNC_EXIT_RC(rc);
}
/**
* @brief 解析报文的剩余长度字段
*
* 每从网络中读取一个字节, 按照MQTT协议算法计算剩余长度
*
* @param client Client结构体
* @param value 剩余长度
* @param timeout 超时时间
* @return
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_glue_packet_decode_from_network(qcloud_mqtt_client_t *client, uint32_t *value, uint32_t timeout)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(value, QCLOUD_ERR_INVAL);
uint8_t byte;
uint32_t len = 0, multiplier = 1;
size_t read_len = 0;
/* The value argument is the important value. len is just used temporarily
* and never used by the calling function for anything else */
*value = 0;
do {
#define MAX_NO_OF_REMAINING_LENGTH_BYTES 4
if (++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) {
/* bad data */
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_PACKET_READ)
}
if ((client->network.read(&(client->network), &byte, 1, timeout, &read_len)) !=
QCLOUD_ERR_SUCCESS) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
*value += (byte & 127) * multiplier;
multiplier *= 128;
} while ((byte & 128) != 0);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
__QCLOUD_STATIC__ void mqtt_glue_packet_drain(qcloud_mqtt_client_t *client, osal_timer_t *timer, uint32_t packet_len)
{
qcloud_err_t rc;
uint32_t time_remain = 0;
size_t total_bytes_read = 0, read_len = 0, bytes2read = 0;
time_remain = osal_timer_remain(timer) + QCLOUD_MQTT_REMAIN_WAIT_MS_MAX;
if (packet_len < sizeof(client->rx_buffer)) {
bytes2read = packet_len;
} else {
bytes2read = sizeof(client->rx_buffer);
}
do {
rc = client->network.read(&(client->network), client->rx_buffer,
bytes2read, time_remain, &read_len);
if (rc == QCLOUD_ERR_SUCCESS) {
total_bytes_read += read_len;
if ((packet_len - total_bytes_read) >= sizeof(client->rx_buffer)) {
bytes2read = sizeof(client->rx_buffer);
} else {
bytes2read = packet_len - total_bytes_read;
}
}
} while (total_bytes_read < packet_len && rc == QCLOUD_ERR_SUCCESS);
}
/**
* @brief 从底层SSL/TCP层读取报文数据
*
* 1. 读取第一个字节确定报文的类型;
* 2. 读取剩余长度字段, 最大为四个字节; 剩余长度表示可变包头和有效负载的长度
* 3. 根据剩余长度, 读取剩下的数据, 包括可变包头和有效负荷
*
* @param client Client结构体
* @param timer 定时器
* @param packet_type 报文类型
* @return
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_glue_packet_read(qcloud_mqtt_client_t *client, osal_timer_t *timer, uint8_t *packet_type)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(timer, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(packet_type, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
size_t read_len = 0;
mqtt_header_t header = {0};
uint32_t len = 0, remain_len = 0, time_remain = 0;
time_remain = osal_timer_remain(timer);
if (time_remain == 0) {
// QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_REQUEST_TIMEOUT);
time_remain = 1;
}
// 1. 读取报文固定头部的第一个字节
rc = client->network.read(&(client->network), client->rx_buffer, (len = 1), time_remain, &read_len);
if (rc == QCLOUD_ERR_SSL_NOTHING_TO_READ || rc == QCLOUD_ERR_TCP_NOTHING_TO_READ) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_NOTHING_TO_READ);
}
if (rc != QCLOUD_ERR_SUCCESS) {
QCLOUD_FUNC_EXIT_RC(rc);
}
// 2. 读取报文固定头部剩余长度部分
time_remain = osal_timer_remain(timer) + QCLOUD_MQTT_REMAIN_WAIT_MS_MAX; //确保一包MQTT报文接收完;
rc = mqtt_glue_packet_decode_from_network(client, &remain_len, time_remain);
if (QCLOUD_ERR_SUCCESS != rc) {
QCLOUD_FUNC_EXIT_RC(rc);
}
// 如果读缓冲区的大小小于报文的剩余长度, 报文会被丢弃
if (remain_len >= sizeof(client->rx_buffer)) {
mqtt_glue_packet_drain(client, timer, remain_len);
QCLOUD_LOG_E("rx buffer insufficient[%d] < [%d]", sizeof(client->rx_buffer), remain_len);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
// 将剩余长度写入读缓冲区
len += mqtt_common_packet_encode(client->rx_buffer + len, remain_len);
// 3. 读取报文的剩余部分数据
if ((len + remain_len) > sizeof(client->rx_buffer)) {
mqtt_glue_packet_drain(client, timer, remain_len);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
time_remain = osal_timer_remain(timer) + QCLOUD_MQTT_REMAIN_WAIT_MS_MAX;
rc = client->network.read(&(client->network), client->rx_buffer + len, remain_len, time_remain, &read_len);
if (rc != QCLOUD_ERR_SUCCESS) {
QCLOUD_FUNC_EXIT_RC(rc);
}
header.byte = client->rx_buffer[0];
*packet_type = header.bits.type;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* @brief 消息主题是否相同
*
* @param topic_filter
* @param topicName
* @return
*/
__QCLOUD_INTERNAL__ int mqtt_glue_is_topic_equals(const char *topic_filter, char *topic)
{
int topic_len = 0;
topic_len = strlen(topic);
if (strlen(topic_filter) != topic_len) {
return QCLOUD_FALSE;
}
if (strncmp(topic_filter, topic, topic_len) == 0) {
return QCLOUD_TRUE;
}
return QCLOUD_FALSE;
}
/**
* @brief 消息主题匹配
*
* assume topic filter and name is in correct format
* # can only be at end
* + and # can only be next to separator
*
* @param topic_filter 订阅消息的主题名
* @param topicName 收到消息的主题名, 不能包含通配符
* @param topicNameLen 主题名的长度
* @return
*/
__QCLOUD_INTERNAL__ int mqtt_glue_is_topic_matches(const char *topic_filter, char *topic, uint16_t topic_len)
{
// it's ugly, but it works. keep it, optimize later
char *curf, *curn, *curn_end, *nextpos;
curf = (char *)topic_filter;
curn = topic;
curn_end = curn + topic_len;
while (*curf && (curn < curn_end)) {
if (*curf == '+' && *curn == '/') {
curf++;
continue;
}
if (*curn == '/' && *curf != '/') {
break;
}
if (*curf != '+' && *curf != '#' && *curf != *curn) {
break;
}
if (*curf == '+') {
/* skip until we meet the next separator, or end of string */
nextpos = curn + 1;
while (nextpos < curn_end && *nextpos != '/') {
nextpos = ++curn + 1;
}
} else if (*curf == '#') {
/* skip until end of string */
curn = curn_end - 1;
}
curf++;
curn++;
};
if (*curf == '\0') {
return curn == curn_end;
} else {
return (*curf == '#') || *(curf + 1) == '#' || (*curf == '+' && *(curn - 1) == '/');
}
}
#if (QCLOUD_CFG_DUPLICATED_MSG_REMOVE_EN > 0u)
#define MQTT_MAX_REPEAT_BUF_LEN 50
static uint16_t sg_repeat_packet_id_buf[MQTT_MAX_REPEAT_BUF_LEN];
/**
* @brief 判断packet_id缓存中是否已经存有传入的packet_id;
*/
__QCLOUD_STATIC__ int mqtt_glue_packet_id_is_exist(uint16_t packet_id)
{
int i;
for (i = 0; i < MQTT_MAX_REPEAT_BUF_LEN; ++i) {
if (packet_id == sg_repeat_packet_id_buf[i]) {
return QCLOUD_TRUE;
}
}
return QCLOUD_FALSE;
}
__QCLOUD_STATIC__ static void mqtt_glue_packet_id_cache_add(uint16_t packet_id)
{
static uint16_t current_packet_id_cnt = 0;
if (mqtt_glue_packet_id_is_exist(packet_id)) {
return;
}
sg_repeat_packet_id_buf[current_packet_id_cnt++] = packet_id;
if (current_packet_id_cnt >= MQTT_MAX_REPEAT_BUF_LEN) {
current_packet_id_cnt = current_packet_id_cnt % 50;
}
}
__QCLOUD_INTERNAL__ void mqtt_glue_packet_id_cache_reset(void)
{
int i = 0;
for (i = 0; i < MQTT_MAX_REPEAT_BUF_LEN; ++i) {
sg_repeat_packet_id_buf[i] = 0;
}
}
#endif
__QCLOUD_STATIC__ qcloud_mqtt_msg_handler_t *mqtt_glue_msg_handler_get(qcloud_mqtt_client_t *client, char *topic, uint16_t topic_len)
{
QCLOUD_FUNC_ENTRY;
qcloud_list_t *curr, *next;
qcloud_mqtt_msg_handler_t *msg_handler;
if (!client || !topic) {
return NULL;
}
if (qcloud_list_empty(&client->msg_handler_list)) {
return NULL;
}
osal_mutex_lock(client->msg_handler_list_lock);
QCLOUD_LIST_FOR_EACH_SAFE(curr, next, &client->msg_handler_list) {
msg_handler = QCLOUD_LIST_ENTRY(curr, qcloud_mqtt_msg_handler_t, list);
if (mqtt_glue_is_topic_equals(msg_handler->topic_filter_mutable, topic) ||
mqtt_glue_is_topic_matches(msg_handler->topic_filter_mutable, topic, topic_len)) {
osal_mutex_unlock(client->msg_handler_list_lock);
return msg_handler;
}
}
osal_mutex_unlock(client->msg_handler_list_lock);
return NULL;
}
/**
* @brief 终端收到服务器的的PUBLISH消息之后, 传递消息给消息回调处理函数
*
* @param client
* @param topicName
* @param message
* @return
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_glue_incoming_message_deliver(qcloud_mqtt_client_t *client,
char *topic,
uint16_t topic_len,
mqtt_incoming_msg_t *message)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(topic, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(message, QCLOUD_ERR_INVAL);
qcloud_mqtt_msg_handler_t *msg_handler = NULL;
message->topic = topic;
message->topic_len = (size_t)topic_len;
msg_handler = mqtt_glue_msg_handler_get(client, topic, topic_len);
if (!msg_handler) {
/* message handler not found for topic */
/* call default handler */
mqtt_glue_callback_involve(client, MQTT_EVENT_PUBLISH_RECVEIVED, message);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
msg_handler->handler(client, message, msg_handler->private_data);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
__QCLOUD_STATIC__ void mqtt_glue_ack_info_destroy(qcloud_mqtt_ack_info_t *ack_info)
{
qcloud_list_del(&ack_info->list);
if (ack_info->type == QCLOUD_MQTT_ACK_TYPE_SUBACK && ack_info->handler) {
mqtt_glue_msg_handler_destory(ack_info->handler);
}
osal_free(ack_info);
}
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_glue_ack_list_scan(qcloud_mqtt_client_t *client)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
qcloud_list_t *curr, *next;
mqtt_event_type_t event_type;
qcloud_mqtt_ack_info_t *ack_info;
if (qcloud_list_empty(&client->ack_pend_list)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
osal_mutex_lock(client->ack_pend_list_lock);
QCLOUD_LIST_FOR_EACH_SAFE(curr, next, &client->ack_pend_list) {
ack_info = QCLOUD_LIST_ENTRY(curr, qcloud_mqtt_ack_info_t, list);
if (!qcloud_mqtt_client_is_connected(client)) {
continue;
}
// check whether the ack is timeout
if (!osal_timer_is_expired(&ack_info->ack_timer)) {
continue;
}
event_type = mqtt_glue_event_type_get(ack_info->type, QCLOUD_FALSE, QCLOUD_TRUE);
/* 通知外部网络已经断开 */
mqtt_glue_callback_involve(client, event_type, &ack_info->packet_id);
mqtt_glue_ack_info_destroy(ack_info);
}
osal_mutex_unlock(client->ack_pend_list_lock);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_glue_ack_list_destroy(qcloud_mqtt_client_t *client)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
qcloud_list_t *curr, *next;
qcloud_mqtt_ack_info_t *ack_info;
if (qcloud_list_empty(&client->ack_pend_list)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
osal_mutex_lock(client->ack_pend_list_lock);
QCLOUD_LIST_FOR_EACH_SAFE(curr, next, &client->ack_pend_list) {
ack_info = QCLOUD_LIST_ENTRY(curr, qcloud_mqtt_ack_info_t, list);
mqtt_glue_ack_info_destroy(ack_info);
}
osal_mutex_unlock(client->ack_pend_list_lock);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
__QCLOUD_STATIC__ qcloud_mqtt_ack_info_t *mqtt_glue_ack_info_create(qcloud_mqtt_ack_type_t type,
qcloud_mqtt_msg_handler_t *handler,
uint32_t timeout,
uint16_t packet_id,
uint16_t packet_len,
uint8_t *packet_body)
{
qcloud_mqtt_ack_info_t *ack_info = NULL;
ack_info = (qcloud_mqtt_ack_info_t *)osal_malloc(sizeof(qcloud_mqtt_ack_info_t) + packet_len);
if (!ack_info) {
QCLOUD_LOG_E("memory alloc failed!");
return NULL;
}
qcloud_list_init(&ack_info->list);
osal_timer_init(&ack_info->ack_timer);
osal_timer_countdown_ms(&ack_info->ack_timer, timeout);
ack_info->type = type;
ack_info->handler = handler;
ack_info->packet_id = packet_id;
ack_info->packet_len = packet_len;
ack_info->packet_body = (uint8_t *)ack_info + sizeof(qcloud_mqtt_ack_info_t);
memcpy(ack_info->packet_body, packet_body, packet_len);
return ack_info;
}
__QCLOUD_STATIC__ void mqtt_glue_ack_list_do_unrecord(qcloud_mqtt_client_t *client, qcloud_mqtt_ack_info_t *ack_info)
{
qcloud_list_del(&ack_info->list);
osal_free(ack_info);
}
__QCLOUD_STATIC__ void mqtt_glue_ack_list_unrecord(qcloud_mqtt_client_t *client,
qcloud_mqtt_ack_type_t type,
uint16_t packet_id,
int is_nack,
qcloud_mqtt_msg_handler_t **handler)
{
QCLOUD_FUNC_ENTRY;
qcloud_list_t *curr, *next;
mqtt_event_type_t event_type;
qcloud_mqtt_ack_info_t *ack_info;
if (!client) {
return;
}
if (qcloud_list_empty(&client->ack_pend_list) ||
!qcloud_mqtt_client_is_connected(client)) {
return;
}
osal_mutex_lock(client->ack_pend_list_lock);
QCLOUD_LIST_FOR_EACH_SAFE(curr, next, &client->ack_pend_list) {
ack_info = QCLOUD_LIST_ENTRY(curr, qcloud_mqtt_ack_info_t, list);
if (ack_info->packet_id != packet_id || ack_info->type != type) {
continue;
}
event_type = mqtt_glue_event_type_get(type, is_nack, osal_timer_is_expired(&ack_info->ack_timer));
mqtt_glue_callback_involve(client, event_type, &ack_info->packet_id);
if (handler) {
*handler = ack_info->handler;
}
mqtt_glue_ack_list_do_unrecord(client, ack_info);
}
osal_mutex_unlock(client->ack_pend_list_lock);
}
__QCLOUD_STATIC__ void mqtt_glue_ack_list_do_record(qcloud_mqtt_client_t *client, qcloud_mqtt_ack_info_t *ack_info)
{
osal_mutex_lock(client->ack_pend_list_lock);
qcloud_list_add_tail(&ack_info->list, &client->ack_pend_list);
osal_mutex_unlock(client->ack_pend_list_lock);
}
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_glue_ack_list_record(qcloud_mqtt_client_t *client,
qcloud_mqtt_ack_type_t type,
qcloud_mqtt_msg_handler_t *handler,
uint16_t packet_id,
uint16_t packet_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
qcloud_mqtt_ack_info_t *ack_info = NULL;
ack_info = mqtt_glue_ack_info_create(type, handler, client->command_timeout, packet_id, packet_len, client->tx_buffer);
if (!ack_info) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
mqtt_glue_ack_list_do_record(client, ack_info);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_glue_callback_involve(qcloud_mqtt_client_t *client, mqtt_event_type_t event_type, void *message)
{
mqtt_event_t event;
mqtt_event_handler_t *event_handler;
event_handler = &client->event_handler;
if (!event_handler) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
event.type = event_type;
event.message = message;
event_handler->handler(client, event_handler->context, &event);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* @brief 终端收到服务器的的PUBACK消息之后, 处理收到的PUBACK报文
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_glue_puback_packet_handle(qcloud_mqtt_client_t *client, osal_timer_t *timer)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(timer, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
uint8_t dup, type;
uint16_t packet_id;
rc = mqtt_common_deserialize_ack_packet(&type, &dup, &packet_id, client->rx_buffer, sizeof(client->rx_buffer));
if (QCLOUD_ERR_SUCCESS != rc) {
QCLOUD_FUNC_EXIT_RC(rc);
}
mqtt_glue_ack_list_unrecord(client, QCLOUD_MQTT_ACK_TYPE_PUBACK, packet_id, QCLOUD_FALSE, NULL);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
__QCLOUD_INTERNAL__ void mqtt_glue_msg_handler_destory(qcloud_mqtt_msg_handler_t *msg_handler)
{
qcloud_list_del(&msg_handler->list);
mqtt_glue_string_mutable_free(msg_handler->topic_filter_mutable);
osal_free(msg_handler);
}
__QCLOUD_INTERNAL__ qcloud_mqtt_msg_handler_t * mqtt_glue_msg_handler_create(char *topic_filter_mutable, mqtt_subscribe_opt_t *subscribe_opt)
{
qcloud_mqtt_msg_handler_t *msg_handler = NULL;
msg_handler = (qcloud_mqtt_msg_handler_t *)osal_malloc(sizeof(qcloud_mqtt_msg_handler_t));
if (!msg_handler) {
QCLOUD_LOG_E("malloc failed");
return NULL;
}
qcloud_list_init(&msg_handler->list);
msg_handler->private_data = subscribe_opt->private_data;
msg_handler->handler = subscribe_opt->message_handler;
msg_handler->qos = subscribe_opt->qos;
msg_handler->topic_filter_mutable = topic_filter_mutable;
return msg_handler;
}
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_glue_msg_handler_list_destroy(qcloud_mqtt_client_t *client)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
qcloud_list_t *curr, *next;
qcloud_mqtt_msg_handler_t *msg_handler;
if (qcloud_list_empty(&client->msg_handler_list)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
osal_mutex_lock(client->msg_handler_list_lock);
QCLOUD_LIST_FOR_EACH_SAFE(curr, next, &client->msg_handler_list) {
msg_handler = QCLOUD_LIST_ENTRY(curr, qcloud_mqtt_msg_handler_t, list);
mqtt_glue_msg_handler_destory(msg_handler);
}
osal_mutex_unlock(client->msg_handler_list_lock);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
__QCLOUD_STATIC__ int mqtt_glue_handler_is_exist(qcloud_mqtt_client_t *client, qcloud_mqtt_msg_handler_t *that_handler)
{
QCLOUD_FUNC_ENTRY;
qcloud_list_t *curr, *next;
qcloud_mqtt_msg_handler_t *this_handler;
if (!client || !that_handler) {
return QCLOUD_FALSE;
}
if (qcloud_list_empty(&client->msg_handler_list)) {
return QCLOUD_FALSE;
}
osal_mutex_lock(client->msg_handler_list_lock);
QCLOUD_LIST_FOR_EACH_SAFE(curr, next, &client->msg_handler_list) {
this_handler = QCLOUD_LIST_ENTRY(curr, qcloud_mqtt_msg_handler_t, list);
if (mqtt_glue_is_topic_equals(this_handler->topic_filter_mutable, that_handler->topic_filter_mutable) &&
this_handler->handler == that_handler->handler) {
return QCLOUD_TRUE;
}
}
osal_mutex_unlock(client->msg_handler_list_lock);
return QCLOUD_FALSE;
}
__QCLOUD_STATIC__ qcloud_err_t mqtt_glue_msg_handler_install(qcloud_mqtt_client_t *client, qcloud_mqtt_msg_handler_t *msg_handler)
{
if (mqtt_glue_handler_is_exist(client, msg_handler)) {
QCLOUD_LOG_W("duplicated handler");
mqtt_glue_msg_handler_destory(msg_handler);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
qcloud_list_add(&msg_handler->list, &client->msg_handler_list);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
__QCLOUD_INTERNAL__ void mqtt_glue_msg_handler_uninstall(qcloud_mqtt_client_t *client, const char *topic_filter, int *is_subscribed)
{
char *this_topic = NULL;
int is_topic_filter_wildcard = QCLOUD_FALSE;
qcloud_list_t *curr, *next;
qcloud_mqtt_msg_handler_t *msg_handler = NULL;
*is_subscribed = QCLOUD_FALSE;
is_topic_filter_wildcard = (strstr(topic_filter, "/#") || strstr(topic_filter, "/+"));
if (qcloud_list_empty(&client->msg_handler_list)) {
return;
}
osal_mutex_lock(client->msg_handler_list_lock);
QCLOUD_LIST_FOR_EACH_SAFE(curr, next, &client->msg_handler_list) {
msg_handler = QCLOUD_LIST_ENTRY(curr, qcloud_mqtt_msg_handler_t, list);
if (mqtt_glue_is_topic_equals(topic_filter, this_topic) ||
(is_topic_filter_wildcard &&
mqtt_glue_is_topic_matches(topic_filter, this_topic, strlen(this_topic)))) {
// completely the same, or match the wildcard
mqtt_glue_msg_handler_destory(msg_handler);
*is_subscribed = QCLOUD_TRUE;
}
}
osal_mutex_unlock(client->msg_handler_list_lock);
}
/**
* @brief 终端收到服务器的的 SUBACK 消息之后, 处理收到的 SUBACK 报文
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_glue_suback_packet_handle(qcloud_mqtt_client_t *client, osal_timer_t *timer)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(timer, QCLOUD_ERR_INVAL);
int qos = 0;
qcloud_err_t rc;
uint32_t count = 0;
uint16_t packet_id = 0;
int is_nack = QCLOUD_FALSE;
qcloud_mqtt_msg_handler_t *msg_handler = NULL;
// 反序列化SUBACK报文
rc = mqtt_common_deserialize_suback_packet(&packet_id, 1, &count, &qos, client->rx_buffer, sizeof(client->rx_buffer));
if (rc != QCLOUD_ERR_SUCCESS) {
QCLOUD_FUNC_EXIT_RC(rc);
}
/* check the return code of suback packet:
0x00(QOS0, SUCCESS), 0x01(QOS1, SUCCESS), 0x02(QOS2, SUCCESS), 0x80(Failure)
*/
is_nack = (qos == MQTT_PACKET_SUBACK_RC_FAILURE);
mqtt_glue_ack_list_unrecord(client, QCLOUD_MQTT_ACK_TYPE_SUBACK, packet_id, is_nack, &msg_handler);
if (!msg_handler) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
if (is_nack) {
mqtt_glue_msg_handler_destory(msg_handler);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_SUB);
}
mqtt_glue_msg_handler_install(client, msg_handler);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* @brief 终端收到服务器的的 USUBACK 消息之后, 处理收到的 USUBACK 报文
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_glue_unsuback_packet_handle(qcloud_mqtt_client_t *client, osal_timer_t *timer)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(timer, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
uint16_t packet_id = 0;
rc = mqtt_common_deserialize_unsuback_packet(&packet_id, client->rx_buffer, sizeof(client->rx_buffer));
if (rc != QCLOUD_ERR_SUCCESS) {
QCLOUD_FUNC_EXIT_RC(rc);
}
mqtt_glue_ack_list_unrecord(client, QCLOUD_MQTT_ACK_TYPE_UNSUBACK, packet_id, QCLOUD_FALSE, NULL);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* @brief 终端收到服务器的的PUBLISH消息之后, 处理收到的PUBLISH报文
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_glue_publish_packet_handle(qcloud_mqtt_client_t *client, osal_timer_t *timer)
{
QCLOUD_FUNC_ENTRY;
qcloud_err_t rc;
char *topic_name;
uint16_t topic_len;
uint32_t len = 0;
char topic_mutable[QCLOUD_MQTT_TOPIC_SIZE_MAX + 1] = {0};
mqtt_incoming_msg_t msg;
rc = mqtt_common_deserialize_publish_packet(&msg.dup, (int *)&msg.qos, &msg.retained, &msg.id,
&topic_name, &topic_len,
(uint8_t **) &msg.payload, &msg.payload_len,
client->rx_buffer, sizeof(client->rx_buffer));
if (rc != QCLOUD_ERR_SUCCESS) {
QCLOUD_FUNC_EXIT_RC(rc);
}
if(topic_len > QCLOUD_MQTT_TOPIC_SIZE_MAX) {
QCLOUD_LOG_E("incoming topic len overflow");
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
// 传过来的topicName没有截断,会把payload也带过来
memset(topic_mutable, 0, sizeof(topic_mutable));
memcpy(topic_mutable, topic_name, topic_len);
if (msg.qos == MQTT_QOS0) {
rc = mqtt_glue_incoming_message_deliver(client, topic_mutable, topic_len, &msg);
/* no further processing required for QOS0 */
QCLOUD_FUNC_EXIT_RC(rc);
}
#if (QCLOUD_CFG_DUPLICATED_MSG_REMOVE_EN > 0u)
// 执行订阅消息的回调函数
if (!mqtt_glue_packet_id_is_exist(msg.id)) {
#endif
rc = mqtt_glue_incoming_message_deliver(client, topic_mutable, topic_len, &msg);
if (QCLOUD_ERR_SUCCESS != rc) {
QCLOUD_FUNC_EXIT_RC(rc);
}
#if (QCLOUD_CFG_DUPLICATED_MSG_REMOVE_EN > 0u)
}
mqtt_glue_packet_id_cache_add(msg.id);
#endif
osal_mutex_lock(client->tx_lock);
if (msg.qos == MQTT_QOS1) {
rc = mqtt_common_serialize_puback_packet(client->tx_buffer, sizeof(client->tx_buffer), msg.id, &len);
} else if (msg.qos == MQTT_QOS2) {
rc = mqtt_common_serialize_pubrec_packet(client->tx_buffer, sizeof(client->tx_buffer), msg.id, &len);
}
if (QCLOUD_ERR_SUCCESS != rc) {
osal_mutex_unlock(client->tx_lock);
QCLOUD_FUNC_EXIT_RC(rc);
}
rc = mqtt_glue_packet_send(client, len, timer);
osal_mutex_unlock(client->tx_lock);
QCLOUD_FUNC_EXIT_RC(rc);
}
/**
* @brief 处理PUBREC报文, 并发送PUBREL报文, PUBLISH报文为QOS2时
*
* @param client
* @param timer
* @return
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_glue_pubrec_packet_handle(qcloud_mqtt_client_t *client, osal_timer_t *timer)
{
QCLOUD_FUNC_ENTRY;
qcloud_err_t rc;
uint32_t len;
uint16_t packet_id;
uint8_t dup, type;
rc = mqtt_common_deserialize_ack_packet(&type, &dup, &packet_id, client->rx_buffer, sizeof(client->rx_buffer));
if (QCLOUD_ERR_SUCCESS != rc) {
QCLOUD_FUNC_EXIT_RC(rc);
}
osal_mutex_lock(client->tx_lock);
rc = mqtt_common_serialize_pubrel_packet(client->tx_buffer, sizeof(client->tx_buffer), 0, packet_id, &len);
if (QCLOUD_ERR_SUCCESS != rc) {
osal_mutex_unlock(client->tx_lock);
QCLOUD_FUNC_EXIT_RC(rc);
}
/* send the PUBREL packet */
rc = mqtt_glue_packet_send(client, len, timer);
if (QCLOUD_ERR_SUCCESS != rc) {
osal_mutex_unlock(client->tx_lock);
/* there was a problem */
QCLOUD_FUNC_EXIT_RC(rc);
}
osal_mutex_unlock(client->tx_lock);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* @brief 处理服务器的心跳包回包
*
* @param client
*/
__QCLOUD_STATIC__ void mqtt_glue_pingresp_packet_handle(qcloud_mqtt_client_t *client)
{
QCLOUD_FUNC_ENTRY;
osal_mutex_lock(client->global_lock);
client->ping_outstanding = 0;
osal_timer_countdown(&client->ping_timer, client->keep_alive_interval);
osal_mutex_unlock(client->global_lock);
QCLOUD_FUNC_EXIT;
}
__QCLOUD_STATIC__ qcloud_err_t mqtt_glue_packet_handle(qcloud_mqtt_client_t *client, osal_timer_t *timer, uint8_t packet_type)
{
qcloud_err_t rc = QCLOUD_ERR_SUCCESS;
switch (packet_type) {
case MQTT_PACKET_TYPE_CONNACK:
break;
case MQTT_PACKET_TYPE_PUBACK:
rc = mqtt_glue_puback_packet_handle(client, timer);
break;
case MQTT_PACKET_TYPE_SUBACK:
rc = mqtt_glue_suback_packet_handle(client, timer);
break;
case MQTT_PACKET_TYPE_UNSUBACK:
rc = mqtt_glue_unsuback_packet_handle(client, timer);
break;
case MQTT_PACKET_TYPE_PUBLISH:
rc = mqtt_glue_publish_packet_handle(client, timer);
break;
case MQTT_PACKET_TYPE_PUBREC:
rc = mqtt_glue_pubrec_packet_handle(client, timer);
break;
case MQTT_PACKET_TYPE_PUBREL:
QCLOUD_LOG_E("PUBREL NOT handled!");
break;
case MQTT_PACKET_TYPE_PUBCOMP:
case MQTT_PACKET_TYPE_PINGRESP:
break;
default:
/* either unknown packet type or failure occurred should not happen */
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_RX_MESSAGE_INVAL);
}
switch (packet_type) {
/* recv below msgs are all considered as PING OK */
case MQTT_PACKET_TYPE_PUBACK:
case MQTT_PACKET_TYPE_SUBACK:
case MQTT_PACKET_TYPE_UNSUBACK:
case MQTT_PACKET_TYPE_PINGRESP:
mqtt_glue_pingresp_packet_handle(client);
break;
/* Recv downlink pub means link is OK but we still need to send PING request */
case MQTT_PACKET_TYPE_PUBLISH:
osal_mutex_lock(client->global_lock);
client->ping_outstanding = 0;
osal_mutex_unlock(client->global_lock);
break;
}
QCLOUD_FUNC_EXIT_RC(rc);
}
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_glue_spin(qcloud_mqtt_client_t *client, osal_timer_t *timer, uint8_t *packet_type)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(timer, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(packet_type, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
/* read the socket, see what work is done */
rc = mqtt_glue_packet_read(client, timer, packet_type);
/* nothing to read, not a failure */
QCLOUD_FUNC_EXIT_RC_IF(rc, QCLOUD_ERR_MQTT_NOTHING_TO_READ, QCLOUD_ERR_SUCCESS);
QCLOUD_FUNC_EXIT_RC_IF_NOT(rc, QCLOUD_ERR_SUCCESS, rc);
QCLOUD_FUNC_EXIT_RC(mqtt_glue_packet_handle(client, timer, *packet_type));
}
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_glue_spin4ack(qcloud_mqtt_client_t *client, osal_timer_t *timer, uint8_t packet_type)
{
QCLOUD_FUNC_ENTRY;
qcloud_err_t rc;
uint8_t ack_packet_type = 0;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(timer, QCLOUD_ERR_INVAL);
do {
if (osal_timer_is_expired(timer)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_REQUEST_TIMEOUT);
}
rc = mqtt_glue_spin(client, timer, &ack_packet_type);
} while (QCLOUD_ERR_SUCCESS == rc && ack_packet_type != packet_type);
QCLOUD_FUNC_EXIT_RC(rc);
}
#ifdef __cplusplus
}
#endif
|
umaru724/TencentOS_E53_IA1
|
kernel/evtdrv/include/tos_evtdrv_timer.h
|
<filename>kernel/evtdrv/include/tos_evtdrv_timer.h
/*----------------------------------------------------------------------------
* Tencent is pleased to support the open source community by making TencentOS
* available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* If you have downloaded a copy of the TencentOS binary from Tencent, please
* note that the TencentOS binary is licensed under the BSD 3-Clause License.
*
* If you have downloaded a copy of the TencentOS source code from Tencent,
* please note that TencentOS source code is licensed under the BSD 3-Clause
* License, except for the third-party components listed below which are
* subject to different license terms. Your integration of TencentOS into your
* own projects may require compliance with the BSD 3-Clause License, as well
* as the other licenses applicable to the third-party components included
* within TencentOS.
*---------------------------------------------------------------------------*/
#ifndef _TOS_EVTDRV_TIMER_H_
#define _TOS_EVTDRV_TIMER_H_
#define EVTDRV_TIME_MILLISEC_PER_SEC (1000u)
typedef enum evtdrv_timer_option_en {
EVTDRV_TIMER_OPT_ONESHOT,
EVTDRV_TIMER_OPT_PERIODIC,
} evtdrv_timer_opt_t;
typedef void (*evtdrv_timer_callback_t)(void *arg);
typedef struct evtdrv_timer_st {
evtdrv_timer_callback_t cb;
void *cb_arg;
k_list_t list;
evtdrv_tick_t expires;
evtdrv_tick_t period;
evtdrv_timer_opt_t opt;
} evtdrv_timer_t;
typedef struct evtdrv_timer_control_st {
evtdrv_tick_t next_expires;
evtdrv_tick_t list;
} evtdrv_timer_ctl_t;
/**
* @brief Create a timer.
* Create a timer.
*
* @attention
*
* @param[in] tmr pointer to the handler of the timer.
* @param[in] callback callback function called when the timer expires.
* @param[in] cb_arg argument for the callback.
* @param[in] opt option for the function call.
*
* @return errcode
* @retval #EVTDRV_ERR_PTR_NULL task_id is invalid.
* @retval #EVTDRV_ERR_NONE event_flags is not valid for user use.
*/
__API__ evtdrv_err_t tos_evtdrv_timer_create(evtdrv_timer_t *tmr,
evtdrv_timer_callback_t callback,
void *cb_arg,
evtdrv_timer_opt_t opt);
/**
* @brief Start a timer.
* Start the timer to run.
*
* @attention None
*
* @param[in] tmr pointer to the handler of the timer.
*
* @return errcode
* @retval #EVTDRV_ERR_PTR_NULL tmr is a NULL pointer.
* @retval #EVTDRV_ERR_TIMER_ALREADY_EXIST tmr is already exist.
* @retval #EVTDRV_ERR_NONE return successfully.
*/
__API__ evtdrv_err_t tos_evtdrv_timer_start(evtdrv_timer_t *tmr, evtdrv_tick_t timeout);
/**
* @brief Stop a timer.
* Stop the timer from running.
*
* @attention None
*
* @param[in] tmr pointer to the handler of the timer.
*
* @return errcode
* @retval #EVTDRV_ERR_PTR_NULL tmr is a NULL pointer.
* @retval #EVTDRV_ERR_TIMER_INACTIVE the timer is not active yet.
* @retval #EVTDRV_ERR_NONE return successfully.
*/
__API__ evtdrv_err_t tos_evtdrv_timer_stop(evtdrv_timer_t *tmr);
__KNL__ void evtdrv_timer_update(void);
#endif /* _TOS_EVTDRV_TIMER_H_ */
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/src/mqtt/qcloud_mqtt_connect.c
|
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud.h"
__QCLOUD_STATIC__ qcloud_err_t mqtt_connack2errno(uint8_t connack_rc)
{
switch (connack_rc) {
case MQTT_CONNACK_CONNECTION_ACCEPTED:
return QCLOUD_ERR_MQTT_CONNACK_CONNECTION_ACCEPTED;
case MQTT_CONANCK_UNACCEPTABLE_PROTOCOL_VERSION_ERROR:
return QCLOUD_ERR_MQTT_CONANCK_UNACCEPTABLE_PROTOCOL_VERSION;
case MQTT_CONNACK_IDENTIFIER_REJECTED_ERROR:
return QCLOUD_ERR_MQTT_CONNACK_IDENTIFIER_REJECTED;
case MQTT_CONNACK_SERVER_UNAVAILABLE_ERROR:
return QCLOUD_ERR_MQTT_CONNACK_SERVER_UNAVAILABLE;
case MQTT_CONNACK_BAD_USERDATA_ERROR:
return QCLOUD_ERR_MQTT_CONNACK_BAD_USERDATA;
case MQTT_CONNACK_NOT_AUTHORIZED_ERROR:
return QCLOUD_ERR_MQTT_CONNACK_NOT_AUTHORIZED;
default:
return QCLOUD_ERR_MQTT_CONNACK_UNKNOWN;
}
}
__QCLOUD_API__ qcloud_err_t qcloud_mqtt_connect(qcloud_mqtt_client_t *client, mqtt_connect_opt_t *connect_opt)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(connect_opt, QCLOUD_ERR_INVAL);
osal_timer_t timer;
uint32_t serialized_len = 0;
uint8_t connack_rc = 0, session_present = 0;
qcloud_err_t rc = QCLOUD_ERR_FAILURE;
osal_timer_init(&timer);
osal_timer_countdown_ms(&timer, client->command_timeout);
QCLOUD_FUNC_EXIT_RC_IF_NOT(rc = client->network.connect(&(client->network)), QCLOUD_ERR_SUCCESS, rc);
osal_mutex_lock(client->tx_lock);
// 序列化CONNECT报文
rc = mqtt_common_serialize_connect_packet(client->tx_buffer, sizeof(client->tx_buffer), connect_opt, &serialized_len);
if (rc != QCLOUD_ERR_SUCCESS || serialized_len == 0) {
osal_mutex_unlock(client->tx_lock);
goto errout;
}
// 发送CONNECT报文
rc = mqtt_glue_packet_send(client, serialized_len, &timer);
if (QCLOUD_ERR_SUCCESS != rc) {
osal_mutex_unlock(client->tx_lock);
goto errout;
}
osal_mutex_unlock(client->tx_lock);
// 阻塞等待CONNACK的报文,
rc = mqtt_glue_spin4ack(client, &timer, (uint8_t)MQTT_PACKET_TYPE_CONNACK);
if (QCLOUD_ERR_SUCCESS != rc) {
goto errout;
}
// 反序列化CONNACK包, 检查返回码
rc = mqtt_common_deserialize_connack_packet(&session_present, &connack_rc, client->rx_buffer, sizeof(client->rx_buffer));
if (QCLOUD_ERR_SUCCESS != rc) {
goto errout;
}
rc = mqtt_connack2errno(connack_rc);
if (rc != QCLOUD_ERR_MQTT_CONNACK_CONNECTION_ACCEPTED) {
goto errout;
}
mqtt_client_connection_state_set(client, QCLOUD_MQTT_CONNECTION_STATE_CONNECTED);
client->keep_alive_interval = connect_opt->keep_alive_interval;
osal_mutex_lock(client->global_lock);
client->is_manually_disconnected = QCLOUD_FALSE;
client->ping_outstanding = 0;
osal_timer_countdown(&client->ping_timer, client->keep_alive_interval);
osal_mutex_unlock(client->global_lock);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
errout:
client->network.disconnect(&client->network);
QCLOUD_FUNC_EXIT_RC(rc);
}
__QCLOUD_API__ qcloud_err_t qcloud_mqtt_disconnect(qcloud_mqtt_client_t *client)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
osal_timer_t timer;
uint32_t serialized_len = 0;
if (!qcloud_mqtt_client_is_connected(client)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_NO_CONN);
}
mqtt_glue_msg_handler_list_destroy(client);
// 1. 组disconnect包
osal_mutex_lock(client->tx_lock);
rc = mqtt_common_serialize_zero_payload_packet(client->tx_buffer, sizeof(client->tx_buffer), MQTT_PACKET_TYPE_DISCONNECT, &serialized_len);
if (rc != QCLOUD_ERR_SUCCESS) {
osal_mutex_unlock(client->tx_lock);
QCLOUD_FUNC_EXIT_RC(rc);
}
osal_timer_init(&timer);
osal_timer_countdown_ms(&timer, client->command_timeout);
// 2. 发送disconnect包
if (serialized_len > 0) {
rc = mqtt_glue_packet_send(client, serialized_len, &timer);
if (rc != QCLOUD_ERR_SUCCESS) {
osal_mutex_unlock(client->tx_lock);
QCLOUD_FUNC_EXIT_RC(rc);
}
}
osal_mutex_unlock(client->tx_lock);
// 3. 断开底层TCP连接, 并修改相关标识位
client->network.disconnect(&(client->network));
mqtt_client_connection_state_set(client, QCLOUD_MQTT_CONNECTION_STATE_DISCONNECTED);
client->is_manually_disconnected = QCLOUD_TRUE;
QCLOUD_LOG_I("mqtt disconnect!");
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
#ifdef __cplusplus
}
#endif
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/src/shadow/qcloud_shadow_json.c
|
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud.h"
#define PRIi32 "i"
#define PRIi16 "i"
#define PRIi8 "i"
#define PRIu32 "u"
#define PRIu16 "u"
#define PRIu8 "u"
#define SCNi8 "hhi"
#define SCNu8 "hhu"
#define SCNi16 "hi"
#define SCNu16 "hu"
#define SCNi32 "i"
#define SCNu32 "u"
__QCLOUD_STATIC__ qcloud_err_t shadow_json_value_do_update(char *value, shadow_dev_property_t *dev_property)
{
switch (dev_property->type) {
case JSON_DATA_TYPE_BOOL:
return LITE_get_boolean(dev_property->data, value);
case JSON_DATA_TYPE_INT32:
return LITE_get_int32(dev_property->data, value);
case JSON_DATA_TYPE_INT16:
return LITE_get_int16(dev_property->data, value);
case JSON_DATA_TYPE_INT8:
return LITE_get_int8(dev_property->data, value);
case JSON_DATA_TYPE_UINT32:
return LITE_get_uint32(dev_property->data, value);
case JSON_DATA_TYPE_UINT16:
return LITE_get_uint16(dev_property->data, value);
case JSON_DATA_TYPE_UINT8:
return LITE_get_uint8(dev_property->data, value);
case JSON_DATA_TYPE_FLOAT:
return LITE_get_float(dev_property->data, value);
case JSON_DATA_TYPE_DOUBLE:
return LITE_get_double(dev_property->data, value);
case JSON_DATA_TYPE_STRING:
case JSON_DATA_TYPE_OBJECT:
QCLOUD_LOG_D("string/object to be deal, %d %s", dev_property->type, value);
return QCLOUD_ERR_SUCCESS;
default:
QCLOUD_LOG_E("unknow type, %d",dev_property->type);
return QCLOUD_ERR_FAILURE;
}
}
/**
* @brief 检查函数snprintf的返回值
*
* @param returnCode 函数snprintf的返回值
* @param maxSizeOfWrite 可写最大字节数
* @return 返回QCLOUD_ERR_JSON, 表示出错; 返回QCLOUD_ERR_JSON_BUFFER_TRUNCATED, 表示截断
*/
__QCLOUD_INTERNAL__ qcloud_err_t shadow_json_snprintf_rc2errno(int rc, size_t write_max)
{
if (rc < 0) {
return QCLOUD_ERR_JSON;
}
if (rc >= write_max) {
return QCLOUD_ERR_JSON_BUFFER_TRUNCATED;
}
return QCLOUD_ERR_SUCCESS;
}
__QCLOUD_INTERNAL__ qcloud_err_t shadow_json_client_token_generate(char *json_doc, size_t json_doc_size, uint32_t token_num, char *device_product_id)
{
int rc_snprintf;
rc_snprintf = osal_snprintf(json_doc, json_doc_size, "%s-%u", device_product_id, token_num);
return shadow_json_snprintf_rc2errno(rc_snprintf, json_doc_size);
}
__QCLOUD_INTERNAL__ qcloud_err_t shadow_json_node_add(char *json_doc, size_t json_doc_size, const char *key, void *data, json_data_type_t type)
{
qcloud_err_t rc;
int32_t rc_snprintf = 0;
size_t remain_size = 0;
if ((remain_size = json_doc_size - strlen(json_doc)) <= 1) {
return QCLOUD_ERR_JSON_BUFFER_TOO_SHORT;
}
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "\"%s\":", key);
rc = shadow_json_snprintf_rc2errno(rc_snprintf, remain_size);
QCLOUD_FUNC_EXIT_RC_IF_NOT(rc, QCLOUD_ERR_SUCCESS, rc);
if ((remain_size = json_doc_size - strlen(json_doc)) <= 1) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_JSON_BUFFER_TOO_SHORT);
}
if (!data) {
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "null,");
QCLOUD_FUNC_EXIT_RC(shadow_json_snprintf_rc2errno(rc_snprintf, remain_size));
}
switch (type) {
case JSON_DATA_TYPE_INT32:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIi32
",", *(int32_t *)(data));
break;
case JSON_DATA_TYPE_INT16:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIi16
",", *(int16_t *)(data));
break;
case JSON_DATA_TYPE_INT8:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIi8
",", *(int8_t *)(data));
break;
case JSON_DATA_TYPE_UINT32:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIu32
",", *(uint32_t *)(data));
break;
case JSON_DATA_TYPE_UINT16:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIu16
",", *(uint16_t *)(data));
break;
case JSON_DATA_TYPE_UINT8:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIu8
",", *(uint8_t *)(data));
break;
case JSON_DATA_TYPE_DOUBLE:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%f,", *(double *)(data));
break;
case JSON_DATA_TYPE_FLOAT:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%f,", *(float *)(data));
break;
case JSON_DATA_TYPE_BOOL:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%s,", *(bool *)(data) ? "true" : "false");
break;
case JSON_DATA_TYPE_STRING:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "\"%s\",", (char *)(data));
break;
case JSON_DATA_TYPE_OBJECT:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%s,", (char *)(data));
break;
}
return shadow_json_snprintf_rc2errno(rc_snprintf, remain_size);
}
__QCLOUD_INTERNAL__ qcloud_err_t shadow_json_empty_doc_build(char *json_doc, uint32_t token_num, char *device_product_id)
{
int rc_snprintf;
rc_snprintf = osal_snprintf(json_doc, QCLOUD_SHADOW_JSON_WITH_CLIENT_TOKEN_MAX, "{\"clientToken\":\"%s-%u\"}", device_product_id, token_num);
return shadow_json_snprintf_rc2errno(rc_snprintf, QCLOUD_SHADOW_JSON_WITH_CLIENT_TOKEN_MAX);
}
__QCLOUD_INTERNAL__ int shadow_json_client_token_parse(char *json_doc, char **client_token)
{
*client_token = LITE_json_value_of(SHADOW_FIELD_CLIENT_TOKEN, json_doc);
return *client_token != NULL;
}
__QCLOUD_INTERNAL__ int shadow_json_version_parse(char *json_doc, uint32_t *version)
{
int rc = QCLOUD_TRUE;
char *version_str;
version_str = LITE_json_value_of(SHADOW_PAYLOAD_VERSION, json_doc);
if (!version_str) {
return QCLOUD_FALSE;
}
if (sscanf(version_str, "%" SCNu32, version) != 1) {
QCLOUD_LOG_E("parse shadow version failed, rc: %d", QCLOUD_ERR_JSON_PARSE);
rc = QCLOUD_FALSE;
}
osal_free(version_str);
return rc;
}
__QCLOUD_INTERNAL__ int shadow_json_operation_type_parse(char *json_doc, char **type)
{
*type = LITE_json_value_of(SHADOW_FIELD_TYPE, json_doc);
return *type != NULL;
}
__QCLOUD_INTERNAL__ int shadow_json_operation_result_code_parse(char *json_doc, int16_t *result_code)
{
int rc = QCLOUD_TRUE;
char *result_code_str;
result_code_str = LITE_json_value_of(SHADOW_FIELD_RESULT, json_doc);
if (!result_code_str) {
return QCLOUD_FALSE;
}
if (sscanf(result_code_str, "%" SCNi16, result_code) != 1) {
QCLOUD_LOG_E("parse result code failed, %d", QCLOUD_ERR_JSON_PARSE);
rc = QCLOUD_FALSE;
}
osal_free(result_code_str);
return rc;
}
__QCLOUD_INTERNAL__ int shadow_json_delta_parse(char *json_doc, char **delta)
{
*delta = LITE_json_value_of(SHADOW_PAYLOAD_STATE, json_doc);
return *delta != NULL;
}
__QCLOUD_INTERNAL__ int shadow_json_operation_delta_get(char *json_doc, char **delta)
{
*delta = LITE_json_value_of(SHADOW_PAYLOAD_STATE_DELTA, json_doc);
return *delta != NULL;
}
__QCLOUD_INTERNAL__ int shadow_state_parse(char *json_doc, char **state)
{
*state = LITE_json_value_of(SHADOW_PAYLOAD_VERSION, json_doc);
return *state != NULL;
}
__QCLOUD_INTERNAL__ int shadow_json_value_update(char *json, shadow_dev_property_t *dev_property)
{
char *data;
data = LITE_json_value_of((char *)dev_property->key, json);
if (!data || strncmp(data, "null", 4) == 0 || strncmp(data, "NULL", 4) == 0) {
return QCLOUD_FALSE;
}
shadow_json_value_do_update(data, dev_property);
osal_free(data);
return QCLOUD_TRUE;
}
#ifdef __cplusplus
}
#endif
|
umaru724/TencentOS_E53_IA1
|
kernel/pm/tos_pm.c
|
/*----------------------------------------------------------------------------
* Tencent is pleased to support the open source community by making TencentOS
* available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* If you have downloaded a copy of the TencentOS binary from Tencent, please
* note that the TencentOS binary is licensed under the BSD 3-Clause License.
*
* If you have downloaded a copy of the TencentOS source code from Tencent,
* please note that TencentOS source code is licensed under the BSD 3-Clause
* License, except for the third-party components listed below which are
* subject to different license terms. Your integration of TencentOS into your
* own projects may require compliance with the BSD 3-Clause License, as well
* as the other licenses applicable to the third-party components included
* within TencentOS.
*---------------------------------------------------------------------------*/
#include "tos_k.h"
#if TOS_CFG_PWR_MGR_EN > 0u
#if TOS_CFG_TICKLESS_EN > 0u
__API__ k_err_t tos_pm_cpu_lpwr_mode_set(k_cpu_lpwr_mode_t cpu_lpwr_mode)
{
TOS_CPU_CPSR_ALLOC();
if (!tickless_wkup_alarm_is_installed(cpu_lpwr_mode)) {
return K_ERR_PM_WKUP_SOURCE_NOT_INSTALL;
}
TOS_CPU_INT_DISABLE();
k_cpu_lpwr_mode = cpu_lpwr_mode;
TOS_CPU_INT_ENABLE();
return K_ERR_NONE;
}
#endif
__STATIC__ int pm_device_is_registered(k_pm_device_t *device)
{
uint8_t i = 0;
for (i = 0; i < k_pm_device_ctl.count; ++i) {
if (strcmp(k_pm_device_ctl.mgr[i]->name, device->name) == 0) {
return 1;
}
}
return 0;
}
__API__ k_err_t tos_pm_device_register(k_pm_device_t *device)
{
TOS_PTR_SANITY_CHECK(device);
if (pm_device_is_registered(device)) {
return K_ERR_PM_DEVICE_ALREADY_REG;
}
if (k_pm_device_ctl.count >= K_PM_DEVICE_MAX_COUNT) {
return K_ERR_PM_DEVICE_OVERFLOW;
}
k_pm_device_ctl.mgr[k_pm_device_ctl.count++] = device;
return K_ERR_NONE;
}
__KNL__ void pm_init(void)
{
memset(&k_pm_device_ctl, 0, sizeof(k_pm_device_ctl));
k_pm_device_ctl.count = 0u;
}
__STATIC_INLINE__ void pm_cpu_sleep_mode_enter(void)
{
cpu_sleep_mode_enter();
}
__STATIC_INLINE__ void pm_cpu_stop_mode_enter(void)
{
cpu_stop_mode_enter();
}
__STATIC_INLINE__ void pm_cpu_standby_mode_enter(void)
{
cpu_standby_mode_enter();
}
__KNL__ void pm_cpu_lpwr_mode_enter(k_cpu_lpwr_mode_t lpwr_mode)
{
if (TOS_LOW_POWER_MODE_SLEEP == lpwr_mode) {
pm_cpu_sleep_mode_enter();
} else if (TOS_LOW_POWER_MODE_STOP == lpwr_mode) {
pm_device_suspend();
pm_cpu_stop_mode_enter();
pm_device_resume();
} else if (TOS_LOW_POWER_MODE_STANDBY == lpwr_mode) {
pm_device_suspend();
pm_cpu_standby_mode_enter();
pm_device_resume();
}
}
__KNL__ k_cpu_lpwr_mode_t pm_cpu_lpwr_mode_get(void)
{
return k_cpu_lpwr_mode;
}
__KNL__ void pm_idle_pwr_mgr_mode_set(idle_pwrmgr_mode_t idle_pwrmgr_mode)
{
k_idle_pwr_mgr_mode = idle_pwrmgr_mode;
}
__KNL__ int pm_idle_pwr_mgr_mode_is_sleep(void)
{
return k_idle_pwr_mgr_mode == IDLE_POWER_MANAGER_MODE_SLEEP;
}
__KNL__ int pm_idle_pwr_mgr_mode_is_tickless(void)
{
return k_idle_pwr_mgr_mode == IDLE_POWER_MANAGER_MODE_TICKLESS;
}
__KNL__ void pm_power_manager(void)
{
if (pm_idle_pwr_mgr_mode_is_sleep()) {
pm_cpu_sleep_mode_enter();
}
#if TOS_CFG_TICKLESS_EN > 0u
else if (pm_idle_pwr_mgr_mode_is_tickless()) {
tickless_proc();
}
#endif
}
__KNL__ int pm_device_suspend(void)
{
uint8_t i = 0;
for (i = 0; i < k_pm_device_ctl.count; ++i) {
if (*k_pm_device_ctl.mgr[i]->suspend) {
(*k_pm_device_ctl.mgr[i]->suspend)();
}
}
return 0;
}
__KNL__ int pm_device_resume(void)
{
uint8_t i = 0;
for (i = 0; i < k_pm_device_ctl.count; ++i) {
if (*k_pm_device_ctl.mgr[i]->resume) {
(*k_pm_device_ctl.mgr[i]->resume)();
}
}
return 0;
}
#endif
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/include/qcloud_coap.h
|
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 _QCLOUD_COAP_H_
#define _QCLOUD_COAP_H_
#ifdef __cplusplus
extern "C" {
#endif
static const char *qcloud_coap_server = "iotcloud.tencentdevices.com";
static const int qcloud_coap_port = 5684;
typedef enum qcloud_coap_auth_state_en {
QCLOUD_COAP_AUTH_STATE_NONE,
QCLOUD_COAP_AUTH_STATE_SUCCESS,
QCLOUD_COAP_AUTH_STATE_FAIL,
} qcloud_coap_auth_state_t;
/**
* @brief COAP消息分类
*/
typedef enum coap_code_class_en {
COAP_CODE_CLASS_REQ = 0, // 请求包
COAP_CODE_CLASS_SUCCESS = 2, // 成功回包
COAP_CODE_CLASS_CLIENT_ERR = 4, // 客户端错误回包
COAP_CODE_CLASS_SERVER_ERR = 5, // 后台错误回包
COAP_CODE_CLASS_INTERNAL_ERR = 6,
} coap_code_class_t;
/**
* @brief COAP消息请求方法
*/
typedef enum coap_request_method_en {
COAP_REQUEST_METHOD_GET = 1, // GET请求
COAP_REQUEST_METHOD_POST = 2, // POST请求
COAP_REQUEST_METHOD_PUT = 3,
COAP_REQUEST_METHOD_DELETE = 4,
} coap_request_method_t;
typedef enum coap_code_detail_en {
/* CoAP Success Response code detail */
COAP_CODE_DETAIL_201_CREATED = 01, /* Mapping to CoAP codeClass.codeDetail 2.01 */
COAP_CODE_DETAIL_202_DELETED = 02, /* Mapping to CoAP codeClass.codeDetail 2.02 */
COAP_CODE_DETAIL_203_VALID = 03, /* Mapping to CoAP codeClass.codeDetail 2.03 */
COAP_CODE_DETAIL_204_CHANGED = 04, /* Mapping to CoAP codeClass.codeDetail 2.04 */
COAP_CODE_DETAIL_205_CONTENT = 05, /* Mapping to CoAP codeClass.codeDetail 2.05 */
COAP_CODE_DETAIL_231_CONTINUE = 31, /* Mapping to CoAP codeClass.codeDetail 2.31 */
/* CoAP Client Error Response code detail */
COAP_CODE_DETAIL_400_BAD_REQUEST = 00, /* Mapping to CoAP codeClass.codeDetail 4.00 */
COAP_CODE_DETAIL_401_UNAUTHORIZED = 01, /* Mapping to CoAP codeClass.codeDetail 4.01 */
COAP_CODE_DETAIL_402_BAD_OPTION = 02, /* Mapping to CoAP codeClass.codeDetail 4.02 */
COAP_CODE_DETAIL_403_FORBIDDEN = 03, /* Mapping to CoAP codeClass.codeDetail 4.03 */
COAP_CODE_DETAIL_404_NOT_FOUND = 04, /* Mapping to CoAP codeClass.codeDetail 4.04 */
COAP_CODE_DETAIL_405_METHOD_NOT_ALLOWED = 05, /* Mapping to CoAP codeClass.codeDetail 4.05 */
COAP_CODE_DETAIL_406_NOT_ACCEPTABLE = 06, /* Mapping to CoAP codeClass.codeDetail 4.06 */
COAP_CODE_DETAIL_408_REQUEST_ENTITY_INCOMPLETE = 8, /* Mapping to CoAP codeClass.codeDetail 4.08 */
COAP_CODE_DETAIL_412_PRECONDITION_FAILED = 12, /* Mapping to CoAP codeClass.codeDetail 4.12 */
COAP_CODE_DETAIL_413_REQUEST_ENTITY_TOO_LARGE = 13, /* Mapping to CoAP codeClass.codeDetail 4.13 */
COAP_CODE_DETAIL_415_UNSUPPORTED_CONTENT_FORMAT = 15, /* Mapping to CoAP codeClass.codeDetail 4.15 */
/* CoAP Server Error Response code detail */
COAP_CODE_DETAIL_500_INTERNAL_SERVER_ERROR = 00, /* Mapping to CoAP codeClass.codeDetail 5.00 */
COAP_CODE_DETAIL_501_NOT_IMPLEMENTED = 01, /* Mapping to CoAP codeClass.codeDetail 5.01 */
COAP_CODE_DETAIL_502_BAD_GATEWAY = 02, /* Mapping to CoAP codeClass.codeDetail 5.02 */
COAP_CODE_DETAIL_503_SERVICE_UNAVAILABLE = 03, /* Mapping to CoAP codeClass.codeDetail 5.03 */
COAP_CODE_DETAIL_504_GATEWAY_TIMEOUT = 04, /* Mapping to CoAP codeClass.codeDetail 5.04 */
COAP_CODE_DETAIL_505_PROXYING_NOT_SUPPORTED = 05, /* Mapping to CoAP codeClass.codeDetail 5.05 */
COAP_CODE_DETAIL_600_TIMEOUT = 00, /* Mapping to self define CoAP codeClass.codeDetail 6.00 */
} coap_code_detail_t;
/**
* @brief Option number enumeration
*/
typedef enum coap_message_option_code_en {
COAP_MSG_OPTION_CODE_IF_MATCH = 1, // If-Match option number
COAP_MSG_OPTION_CODE_URI_HOST = 3, // URI-Host option number
COAP_MSG_OPTION_CODE_ETAG = 4, // Entity-Tag option number
COAP_MSG_OPTION_CODE_IF_NONE_MATCH = 5, // If-None-Match option number
COAP_MSG_OPTION_CODE_URI_PORT = 7, // URI-Port option number
COAP_MSG_OPTION_CODE_LOCATION_PATH = 8, // Location-Path option number
COAP_MSG_OPTION_CODE_URI_PATH = 11, // URI-Path option number
COAP_MSG_OPTION_CODE_CONTENT_FORMAT = 12, // Content-Format option number
COAP_MSG_OPTION_CODE_MAX_AGE = 14, // Max-Age option number
COAP_MSG_OPTION_CODE_URI_QUERY = 15, // URI-Query option number
COAP_MSG_OPTION_CODE_ACCEPT = 17, // Accept option number
COAP_MSG_OPTION_CODE_LOCATION_QUERY = 20, // Location-Query option number
COAP_MSG_OPTION_CODE_BLOCK2 = 23, // Block2 option number
COAP_MSG_OPTION_CODE_BLOCK1 = 27, // Block1 option number
COAP_MSG_OPTION_CODE_SIZE2 = 28, // Size2 option number
COAP_MSG_OPTION_CODE_PROXY_URI = 35, // Proxy-URI option number
COAP_MSG_OPTION_CODE_PROXY_SCHEME = 39, // Proxy-Scheme option number
COAP_MSG_OPTION_CODE_SIZE1 = 60, // Size1 option number
COAP_MSG_OPTION_CODE_AUTH_TOKEN = 61, // 设备鉴权token option number
COAP_MSG_OPTION_CODE_NEED_RESP = 62, // CoAP消息是否需要content response option number
} coap_msg_opt_code_t;
typedef enum coap_incoming_msg_type_en {
COAP_INCOMING_MSG_TYPE_PIGGY,
COAP_INCOMING_MSG_TYPE_ACK,
COAP_INCOMING_MSG_TYPE_RESP,
} coap_incoming_msg_type_t;
/**
* @brief CoAP needResp类型消息回调处理函数指针定义
*
* @param message CoAP消息
* @param userContext 发送消息时携带的用户上下文
*/
typedef void (*coap_resp_callback_t)(void *message, void *context);
/**
* @brief COAP发布消息结构体
*/
typedef struct coap_send_option_st {
char *payload; // COAP 消息负载
size_t payload_len; // MQTT 消息负载长度
void *context; // 用于用户传递的消息上下文,SDK不做处理在callback时返回
coap_resp_callback_t resp_cb; // 消息回包callback,仅对need_resp: true 有效
} coap_send_opt_t;
/**
* @brief CoAP Option结构体
*/
typedef struct coap_message_option_st {
qcloud_list_t list;
uint16_t option_code; // Option code
uint32_t val_len; // Option length
char *val; // Pointer to a buffer containing the option value
} coap_msg_option_t;
typedef struct coap_message_sent_info_st {
qcloud_list_t list;
void *context;
int is_acked;
uint8_t token_len;
uint8_t token[COAP_MSG_TOKEN_MAX];
uint8_t transmit_count;
osal_timer_t timer;
void *message;
uint16_t message_id;
uint32_t message_len;
coap_resp_callback_t resp_cb;
} coap_msg_sent_info_t;
/**
* @brief COAP消息类型
*/
typedef enum coap_msg_type_en {
COAP_MSG_TYPE_CON = 0x0, /**< 需要等待回包确认的消息 */
COAP_MSG_TYPE_NON = 0x1, /**< 无需等待回包确认的消息 */
COAP_MSG_TYPE_ACK = 0x2, /**< ACK消息 */
COAP_MSG_TYPE_RST = 0x3, /**< Reset消息 */
} coap_msg_type_t;
/**
* @brief CoAP消息结构体
*/
typedef struct coap_message_st {
uint32_t version; // CoAP协议版本号
uint8_t type; // 消息类型
uint32_t code_class; // Code class
uint32_t code_detail; // Code detail
uint16_t id; // 消息id
char *payload; // 消息负载
size_t payload_len; // 消息负载长度
char token[COAP_MSG_TOKEN_MAX]; // 消息token
uint8_t token_len; // 消息token长度
coap_resp_callback_t resp_cb; // CoAP Response消息回调处理函数
void *context; // 用户上下文
qcloud_list_t option_list;
} coap_message_t;
#define COAP_MESSAGE_INITIALIZER {COAP_VERSION, COAP_MSG_TYPE_CON, COAP_CODE_CLASS_REQ, COAP_REQUEST_METHOD_POST, 0, NULL, 0, {0}, 0, NULL, NULL, {NULL, NULL}}
/**
* CoAP 事件类型
*/
typedef enum coap_event_type_en {
COAP_EVENT_TYPE_RECEIVE_ACK = 0, // 收到消息ACK
COAP_EVENT_TYPE_RECEIVE_RESPCONTENT = 1, // 收到消息回包响应
COAP_EVENT_TYPE_UNAUTHORIZED = -1, // 设备鉴权失败或鉴权token过期
COAP_EVENT_TYPE_FORBIDDEN = -2, // 设备topic无权限
COAP_EVENT_TYPE_INTERNAL_SERVER_ERROR = -3, // 服务端错误
COAP_EVENT_TYPE_ACK_TIMEOUT = -4, // 消息ACK超时
COAP_EVENT_TYPE_SEPRESP_TIMEOUT = -5, // 消息回包响应超时
} coap_event_type_t;
typedef struct coap_event_st {
coap_event_type_t type; /* 事件类型 */
void *message; /* 事件消息 or 内容消息 */
} coap_event_t;
typedef void (*coap_event_handler_fn_t)(void *context, coap_event_t *event);
typedef struct coap_event_handler_st {
coap_event_handler_fn_t handler;
void *context;
} coap_event_handler_t;
typedef struct qcloud_coap_client_st {
qcloud_coap_auth_state_t auth_state;
uint32_t message_token; // 标识请求响应条消息对应
uint16_t packet_id; // COAP报文标识符
uint8_t tx_buffer[QCLOUD_COAP_CLIENT_TX_BUF_LEN];
uint8_t rx_buffer[QCLOUD_COAP_CLIENT_RX_BUF_LEN];
void *tx_lock; // 输出流的锁
void *message_list_lock; // 等待发布消息ack列表的锁
qcloud_list_t message_list; // 请求消息列表
qcloud_network_t network; // 网络调用数据结构
uint32_t command_timeout; // CoAP消息超时时间, 单位:ms
uint8_t retransmit_max; // CoAP消息最大重试次数
coap_event_handler_t event_handler; // 事件回调
char *auth_token; // 鉴权token
int auth_token_len;
char auth_id[QCLOUD_COAP_AUTH_ID_MAX + 1];
char auth_uri[QCLOUD_COAP_AUTH_URI_MAX + 1];
} qcloud_coap_client_t;
__QCLOUD_API__ qcloud_err_t qcloud_coap_client_create(qcloud_coap_client_t *client, qcloud_device_t *device, coap_event_handler_fn_t handler);
__QCLOUD_API__ qcloud_err_t qcloud_coap_client_destroy(qcloud_coap_client_t *client);
__QCLOUD_API__ qcloud_err_t qcloud_coap_client_connect(qcloud_coap_client_t *client);
__QCLOUD_API__ qcloud_err_t qcloud_coap_client_yield(qcloud_coap_client_t *client, uint32_t timeout_ms);
__QCLOUD_API__ qcloud_err_t qcloud_coap_client_msg_send(qcloud_coap_client_t *client,
char *topic,
coap_send_opt_t *send_opt);
__QCLOUD_API__ uint16_t qcloud_coap_msg_id_get(coap_message_t *message);
__QCLOUD_API__ qcloud_err_t qcloud_coap_msg_payload_get(coap_message_t *message, char **payload, int *payload_len);
__QCLOUD_API__ coap_event_type_t qcloud_coap_event_type_get(coap_message_t *message);
__QCLOUD_INTERNAL__ int coap_message_token_get(qcloud_coap_client_t *client, char *buf);
__QCLOUD_INTERNAL__ qcloud_err_t coap_message_type_set(coap_message_t *message, uint8_t type);
__QCLOUD_INTERNAL__ qcloud_err_t coap_message_code_set(coap_message_t *message, uint32_t code_class, uint32_t code_detail);
__QCLOUD_INTERNAL__ qcloud_err_t coap_message_id_set(coap_message_t *message, uint16_t id);
__QCLOUD_INTERNAL__ qcloud_err_t coap_message_token_set(coap_message_t *message, char *buf, uint8_t len);
__QCLOUD_INTERNAL__ qcloud_err_t coap_message_payload_set(coap_message_t *message, char *buf, size_t len);
__QCLOUD_INTERNAL__ coap_msg_option_t *coap_message_option_construct(uint16_t option_code, uint32_t len, const char *val);
__QCLOUD_INTERNAL__ qcloud_err_t coap_message_option_add(coap_message_t *message, coap_msg_opt_code_t option_code, uint32_t len, const char *val);
__QCLOUD_INTERNAL__ qcloud_err_t coap_message_callback_set(coap_message_t *message, coap_resp_callback_t callback);
__QCLOUD_INTERNAL__ qcloud_err_t coap_message_context_set(coap_message_t *message, void *context);
__QCLOUD_INTERNAL__ void coap_message_init(coap_message_t *message);
__QCLOUD_INTERNAL__ void coap_message_destroy(coap_message_t *message);
__QCLOUD_INTERNAL__ void coap_message_dump(coap_message_t* message);
__QCLOUD_INTERNAL__ void coap_glue_connect_id_generate(char *conn_id);
__QCLOUD_INTERNAL__ uint16_t coap_glue_packet_id_generate(qcloud_coap_client_t *client);
__QCLOUD_INTERNAL__ qcloud_err_t coap_glue_message_list_destroy(qcloud_coap_client_t *client);
__QCLOUD_INTERNAL__ qcloud_err_t coap_glue_spin(qcloud_coap_client_t *client, uint32_t timeout_ms);
__QCLOUD_INTERNAL__ qcloud_err_t coap_glue_msg_send(qcloud_coap_client_t *client, coap_message_t *message);
__QCLOUD_INTERNAL__ qcloud_err_t coap_message_deserialize(coap_message_t *message, char *buf, size_t buf_len);
__QCLOUD_INTERNAL__ int coap_message_serialize(coap_message_t *message, char *buf, size_t buf_len);
__QCLOUD_INTERNAL__ qcloud_err_t coap_auth(qcloud_coap_client_t *client, char *connection_id);
#ifdef __cplusplus
}
#endif
#endif
|
umaru724/TencentOS_E53_IA1
|
kernel/core/include/tos_robin.h
|
/*----------------------------------------------------------------------------
* Tencent is pleased to support the open source community by making TencentOS
* available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* If you have downloaded a copy of the TencentOS binary from Tencent, please
* note that the TencentOS binary is licensed under the BSD 3-Clause License.
*
* If you have downloaded a copy of the TencentOS source code from Tencent,
* please note that TencentOS source code is licensed under the BSD 3-Clause
* License, except for the third-party components listed below which are
* subject to different license terms. Your integration of TencentOS into your
* own projects may require compliance with the BSD 3-Clause License, as well
* as the other licenses applicable to the third-party components included
* within TencentOS.
*---------------------------------------------------------------------------*/
#ifndef _TOS_ROBIN_H_
#define _TOS_ROBIN_H_
#if TOS_CFG_ROUND_ROBIN_EN > 0u
/**
* @brief Set time slice.
* Set time slice of a task.
*
* @attention None
*
* @param[in] task pointer to the handler of the task.
* @param[in] timeslice time slice of the task
*
* @return None
*/
__API__ void tos_robin_timeslice_set(k_task_t *task, k_timeslice_t timeslice);
/**
* @brief Configure round robin.
* Set the round robin state and the default time slice of the task.
*
* @attention None
*
* @param[in] robin_state state of the round robin.
* @param[in] default_timeslice default time slice of the task.
*
* @return None
*/
__API__ void tos_robin_default_timeslice_config(k_timeslice_t default_timeslice);
__KNL__ void robin_sched(k_prio_t prio);
#endif
#endif /* _TOS_ROBIN_H_ */
|
umaru724/TencentOS_E53_IA1
|
examples/sensor/sensor_demo.h
|
#ifndef __SENSOR_DEMO_H__
#define __SENSOR_DEMO_H__
#include "mcu_init.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
char data[32];
}ReportData_TypeDef;
void application_entry(void *arg);
#ifdef __cplusplus
}
#endif
#endif /* __APP_DEMO_H__ */
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/LoraWAN/boards_common/lpm-board.h
|
/*!
* \file lpm-board.h
*
* \brief Target board low power modes management
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech - STMicroelectronics
*
* \endcode
*
* \author <NAME> ( Semtech )
*
* \author <NAME> ( Semtech )
*
* \author MCD Application Team (C)( STMicroelectronics International )
*/
#ifndef __LPM_BOARD_H__
#define __LPM_BOARD_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "board-config.h"
/*!
* Low power manager configuration
*/
typedef enum
{
LPM_APPLI_ID = ( 1 << 0 ),
LPM_LIB_ID = ( 1 << 1 ),
LPM_RTC_ID = ( 1 << 2 ),
LPM_GPS_ID = ( 1 << 3 ),
LPM_UART_RX_ID = ( 1 << 4 ),
LPM_UART_TX_ID = ( 1 << 5 ),
} LpmId_t;
/*!
* Low Power Mode selected
*/
typedef enum
{
LPM_ENABLE = 0,
LPM_DISABLE,
} LpmSetMode_t;
typedef enum
{
LPM_SLEEP_MODE,
LPM_STOP_MODE,
LPM_OFF_MODE,
} LpmGetMode_t;
/*!
* \brief This API returns the Low Power Mode selected that will be applied when the system will enter low power mode
* if there is no update between the time the mode is read with this API and the time the system enters
* low power mode.
*
* \retval mode Selected low power mode
*/
LpmGetMode_t LpmGetMode( void );
/*!
* \brief This API notifies the low power manager if the specified user allows the Stop mode or not.
* When the application does not require the system clock, it enters Stop Mode if at least one user disallow
* Off Mode. Otherwise, it enters Off Mode.
* The default mode selection for all users is Off mode enabled
*
* \param [IN] id Process Id
* \param [IN] mode Selected mode
*/
void LpmSetStopMode( LpmId_t id, LpmSetMode_t mode );
/*!
* \brief This API notifies the low power manager if the specified user allows the Off mode or not.
* When the application does not require the system clock, it enters Stop Mode if at least one user disallow
* Off Mode. Otherwise, it enters Off Mode.
* The default mode selection for all users is Off mode enabled
*
* \param [IN] id Process Id
* \param [IN] mode Selected mode
*/
void LpmSetOffMode(LpmId_t id, LpmSetMode_t mode );
/*!
* \brief This API shall be used by the application when there is no more code to execute so that the system may
* enter low-power mode. The mode selected depends on the information received from LpmOffModeSelection( ) and
* LpmSysclockRequest( )
* This function shall be called in critical section
*/
void LpmEnterLowPower( void );
/*!
* \brief This API is called by the low power manager in a critical section (PRIMASK bit set) to allow the
* application to implement dedicated code before entering Sleep Mode
*/
void LpmEnterSleepMode( void );
/*!
* \brief This API is called by the low power manager in a critical section (PRIMASK bit set) to allow the
* application to implement dedicated code before getting out from Sleep Mode
*/
void LpmExitSleepMode( void );
/*!
* \brief This API is called by the low power manager in a critical section (PRIMASK bit set) to allow the
* application to implement dedicated code before entering Stop Mode
*/
void LpmEnterStopMode( void );
/*!
* \brief This API is called by the low power manager in a critical section (PRIMASK bit set) to allow the
* application to implement dedicated code before getting out from Stop Mode. This is where the application
* should reconfigure the clock tree when needed
*/
void LpmExitStopMode( void );
/*!
* \brief This API is called by the low power manager in a critical section (PRIMASK bit set) to allow the
* application to implement dedicated code before entering Off mode. This is where the application could save
* data in the retention memory as the RAM memory content will be lost
*/
void LpmEnterOffMode( void );
/*!
* @brief This API is called by the low power manager in a critical section (PRIMASK bit set) to allow the
* application to implement dedicated code before getting out from Off mode. This can only happen when the
* Off mode is finally not entered. In that case, the application may reverse some configurations done before
* entering Off mode. When Off mode is successful, the system is reset when getting out from this low-power mode
*/
void LpmExitOffMode( void );
#ifdef __cplusplus
}
#endif
#endif /*__LPM_BOARD_H__ */
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/gd/GD32VF103_Firmware_Library/GD32VF103_standard_peripheral/Include/gd32vf103_exmc.h
|
<filename>platform/vendor_bsp/gd/GD32VF103_Firmware_Library/GD32VF103_standard_peripheral/Include/gd32vf103_exmc.h
/*!
\file gd32vf103_exmc.h
\brief definitions for the EXMC
\version 2019-06-05, V1.0.0, firmware for GD32VF103
*/
/*
Copyright (c) 2019, GigaDevice Semiconductor Inc.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/
#ifndef GD32VF103_EXMC_H
#define GD32VF103_EXMC_H
#include "gd32vf103.h"
/* EXMC definitions */
#define EXMC (EXMC_BASE) /*!< EXMC register base address */
/* registers definitions */
/* NOR/PSRAM */
#define EXMC_SNCTL0 REG32(EXMC + 0x00U) /*!< EXMC SRAM/NOR flash control register 0 */
#define EXMC_SNTCFG0 REG32(EXMC + 0x04U) /*!< EXMC SRAM/NOR flash timing configuration register 0 */
#define EXMC_SNWTCFG0 REG32(EXMC + 0x104U) /*!< EXMC SRAM/NOR flash write timing configuration register 0 */
/* bits definitions */
/* NOR/PSRAM */
/* EXMC_SNCTLx, x=0 */
#define EXMC_SNCTL_NRBKEN BIT(0) /*!< NOR bank enable */
#define EXMC_SNCTL_NRMUX BIT(1) /*!< NOR bank memory address/data multiplexing */
#define EXMC_SNCTL_NRTP BITS(2,3) /*!< NOR bank memory type */
#define EXMC_SNCTL_NRW BITS(4,5) /*!< NOR bank memory data bus width */
#define EXMC_SNCTL_NREN BIT(6) /*!< NOR flash access enable */
#define EXMC_SNCTL_NRWTPOL BIT(9) /*!< NWAIT signal polarity */
#define EXMC_SNCTL_WREN BIT(12) /*!< write enable */
#define EXMC_SNCTL_NRWTEN BIT(13) /*!< NWAIT signal enable */
#define EXMC_SNCTL_ASYNCWAIT BIT(15) /*!< asynchronous wait */
/* EXMC_SNTCFGx, x=0 */
#define EXMC_SNTCFG_ASET BITS(0,3) /*!< address setup time */
#define EXMC_SNTCFG_AHLD BITS(4,7) /*!< address hold time */
#define EXMC_SNTCFG_DSET BITS(8,15) /*!< data setup time */
#define EXMC_SNTCFG_BUSLAT BITS(16,19) /*!< bus latency */
/* constants definitions */
/* EXMC NOR/SRAM timing initialize struct */
typedef struct
{
uint32_t bus_latency; /*!< configure the bus latency */
uint32_t asyn_data_setuptime; /*!< configure the data setup time,asynchronous access mode valid */
uint32_t asyn_address_holdtime; /*!< configure the address hold time,asynchronous access mode valid */
uint32_t asyn_address_setuptime; /*!< configure the data setup time,asynchronous access mode valid */
}exmc_norsram_timing_parameter_struct;
/* EXMC NOR/SRAM initialize struct */
typedef struct
{
uint32_t norsram_region; /*!< select the region of EXMC NOR/SRAM bank */
uint32_t asyn_wait; /*!< enable or disable the asynchronous wait function */
uint32_t nwait_signal; /*!< enable or disable the NWAIT signal */
uint32_t memory_write; /*!< enable or disable the write operation */
uint32_t nwait_polarity; /*!< specifies the polarity of NWAIT signal from memory */
uint32_t databus_width; /*!< specifies the databus width of external memory */
uint32_t memory_type; /*!< specifies the type of external memory */
uint32_t address_data_mux; /*!< specifies whether the data bus and address bus are multiplexed */
exmc_norsram_timing_parameter_struct* read_write_timing; /*!< timing parameters for read and write */
}exmc_norsram_parameter_struct;
/* EXMC register address */
#define EXMC_SNCTL(region) REG32(EXMC + 0x08U * (region)) /*!< EXMC SRAM/NOR flash control register */
#define EXMC_SNTCFG(region) REG32(EXMC + 0x04U + 0x08U * (region)) /*!< EXMC SRAM/NOR flash timing configuration register */
/* NOR bank memory data bus width */
#define SNCTL_NRW(regval) (BITS(4,5) & ((uint32_t)(regval) << 4))
#define EXMC_NOR_DATABUS_WIDTH_8B SNCTL_NRW(0) /*!< NOR data width 8 bits */
#define EXMC_NOR_DATABUS_WIDTH_16B SNCTL_NRW(1) /*!< NOR data width 16 bits */
/* NOR bank memory type */
#define SNCTL_NRTP(regval) (BITS(2,3) & ((uint32_t)(regval) << 2))
#define EXMC_MEMORY_TYPE_SRAM SNCTL_NRTP(0) /*!< SRAM,ROM */
#define EXMC_MEMORY_TYPE_PSRAM SNCTL_NRTP(1) /*!< PSRAM,CRAM */
#define EXMC_MEMORY_TYPE_NOR SNCTL_NRTP(2) /*!< NOR flash */
/* EXMC NOR/SRAM bank region definition */
#define EXMC_BANK0_NORSRAM_REGION0 ((uint32_t)0x00000000U) /*!< bank0 NOR/SRAM region0 */
/* EXMC NWAIT signal polarity configuration */
#define EXMC_NWAIT_POLARITY_LOW ((uint32_t)0x00000000U) /*!< low level is active of NWAIT */
#define EXMC_NWAIT_POLARITY_HIGH ((uint32_t)0x00000200U) /*!< high level is active of NWAIT */
/* function declarations */
/* deinitialize EXMC NOR/SRAM region */
void exmc_norsram_deinit(uint32_t norsram_region);
/* exmc_norsram_parameter_struct parameter initialize */
void exmc_norsram_struct_para_init(exmc_norsram_parameter_struct* exmc_norsram_init_struct);
/* initialize EXMC NOR/SRAM region */
void exmc_norsram_init(exmc_norsram_parameter_struct* exmc_norsram_init_struct);
/* EXMC NOR/SRAM bank enable */
void exmc_norsram_enable(uint32_t norsram_region);
/* EXMC NOR/SRAM bank disable */
void exmc_norsram_disable(uint32_t norsram_region);
#endif /* GD32VF103_EXMC_H */
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/include/qcloud_shadow_config.h
|
<filename>components/connectivity/TencentCloud_SDK/source/include/qcloud_shadow_config.h
#ifndef _QCLOUD_SHADOW_CONFIG_
#define _QCLOUD_SHADOW_CONFIG_
/* 接收云端返回的JSON文档的buffer大小 */
#define QCLOUD_SHADOW_JSON_BUF_MAX (QCLOUD_MQTT_CLIENT_RX_BUF_LEN + 1)
#define QCLOUD_SHADOW_CLIENT_TOKEN_MAX (QCLOUD_MQTT_DEVICE_CLIENT_ID_MAX + 10)
/* 一个仅包含clientToken字段的JSON文档的最大长度 */
#define QCLOUD_SHADOW_JSON_WITH_CLIENT_TOKEN_MAX (QCLOUD_SHADOW_CLIENT_TOKEN_MAX + 20)
#define QCLOUD_SHADOW_REQUEST_PENDING_MAX (10)
#endif
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/include/qcloud_osal/osal_dtls.h
|
#ifndef _OSAL_DTLS_H_
#define _OSAL_DTLS_H_
__QCLOUD_OSAL__ void *osal_dtls_connect(qcloud_tls_opt_t *tls_opt, const char *host, int port);
__QCLOUD_OSAL__ void osal_dtls_disconnect(void *handle);
__QCLOUD_OSAL__ qcloud_err_t osal_dtls_write(void *handle, const void *buf, size_t len, size_t *write_len);
__QCLOUD_OSAL__ qcloud_err_t osal_dtls_read(void *handle, void *buf, size_t len, uint32_t timeout, size_t *read_len);
#endif
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/ble_peripheral/experimental/ble_app_queued_writes/nrf_ble_qwrs.h
|
/**
* Copyright (c) 2016 - 2019, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/** @cond To make doxygen skip this file */
#ifndef BLE_QWRS_H__
#define BLE_QWRS_H__
#include <stdint.h>
#include <stdbool.h>
#include "ble.h"
#include "ble_srv_common.h"
#include "nrf_ble_qwr.h"
#ifdef __cplusplus
extern "C" {
#endif
#define NRF_BLE_QWRS_MAX_RCV_SIZE 128
/**@brief Queued Write Example Service event types. */
typedef enum
{
BLE_QWRS_CHECK_RCVD_DATA, /* On this event, the application shall only verify if the data are correct.*/
BLE_QWRS_NEW_DATA_RCVD, /* On this event, the application can act upon the received data*/
} nrf_ble_qwrs_evt_type;
/**@brief Queued Write Example Service event. */
typedef struct
{
nrf_ble_qwrs_evt_type evt_type; //!< Type of event.
uint16_t rcv_length;
uint8_t rcvd_data[NRF_BLE_QWRS_MAX_RCV_SIZE];
} nrf_ble_qwrs_evt_t;
// Forward declaration of the nrf_ble_qwrs_t type.
struct nrf_ble_qwrs_t;
/**@brief Queued Write Example Service event handler type. returns a BLE_GATT_STATUS_CODES */
typedef uint16_t (*nrf_ble_qwrs_evt_handler_t) (struct nrf_ble_qwrs_t * p_qwrs,
nrf_ble_qwrs_evt_t * p_evt);
typedef struct
{
nrf_ble_qwrs_evt_handler_t evt_handler; //!< Event handler to be called for handling events in the Queued Write Example Service.
ble_srv_error_handler_t error_handler; //!< Function to be called in case of an error.
nrf_ble_qwr_t * p_qwr_ctx; //!< pointer to the initialized queued write context
} nrf_ble_qwrs_init_t;
typedef struct nrf_ble_qwrs_t
{
uint8_t uuid_type; //!< UUID type.
uint16_t service_handle; //!< Handle of Queued Write Example Service (as provided by the BLE stack).
uint16_t conn_handle; //!< Handle of the current connection (as provided by the BLE stack, is BLE_CONN_HANDLE_INVALID if not in a connection).
nrf_ble_qwrs_evt_handler_t evt_handler; //!< Event handler to be called for handling events in the Queued Write Example Service.
ble_srv_error_handler_t error_handler; //!< Function to be called in case of an error.
ble_gatts_char_handles_t long_charact_handles; //!< Handles related to the Queued Write Example long characteristic.
ble_gatts_char_handles_t charact_handles; //!< Handles related to the Queued Write Example characteristic.
} nrf_ble_qwrs_t;
/**@brief Function for initializing the Queued Write Example Service.
*
* @details This call allows the application to initialize the Queued Write Example Service.
*
* @param[in] p_qwrs_init Information needed to initialize the service.
* @param[out] p_qwrs Queued Write Example Service structure.
* @return NRF_SUCCESS on successful initialization of service, otherwise an error code.
*/
uint32_t nrf_ble_qwrs_init(nrf_ble_qwrs_init_t *p_qwrs_init, nrf_ble_qwrs_t *p_qwrs);
/**@brief event handler function for handling event from the queued write module.
*
* @param[in] p_qwrs Queued Write Example Service structure.
* @param[in] p_qwr Queued Write structure.
* @param[in] p_evt event received from the QWR module.
*
* @return BLE_GATT_STATUS_SUCCESS if the received data are accepted, error code otherwise.
*/
uint16_t nrf_ble_qwrs_on_qwr_evt(nrf_ble_qwrs_t *p_qwrs,
nrf_ble_qwr_t * p_qwr,
nrf_ble_qwr_evt_t * p_evt);
#ifdef __cplusplus
}
#endif
#endif // BLE_QWRS_H__
/** @} */
/** @endcond */
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nxp/MIMXRT1062/CMSIS/DSP/Source/TransformFunctions/TransformFunctions.c
|
/* ----------------------------------------------------------------------
* Project: CMSIS DSP Library
* Title: TransformFunctions.c
* Description: Combination of all transform function source files.
*
* $Date: 18. March 2019
* $Revision: V1.0.0
*
* Target Processor: Cortex-M cores
* -------------------------------------------------------------------- */
/*
* Copyright (C) 2019 ARM Limited or its affiliates. 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
*
* 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 "arm_bitreversal.c"
#include "arm_bitreversal2.c"
#include "arm_cfft_f32.c"
#include "arm_cfft_q15.c"
#include "arm_cfft_q31.c"
#include "arm_cfft_radix2_f32.c"
#include "arm_cfft_radix2_init_f32.c"
#include "arm_cfft_radix2_init_q15.c"
#include "arm_cfft_radix2_init_q31.c"
#include "arm_cfft_radix2_q15.c"
#include "arm_cfft_radix2_q31.c"
#include "arm_cfft_radix4_f32.c"
#include "arm_cfft_radix4_init_f32.c"
#include "arm_cfft_radix4_init_q15.c"
#include "arm_cfft_radix4_init_q31.c"
#include "arm_cfft_radix4_q15.c"
#include "arm_cfft_radix4_q31.c"
#include "arm_cfft_radix8_f32.c"
#include "arm_dct4_f32.c"
#include "arm_dct4_init_f32.c"
#include "arm_dct4_init_q15.c"
#include "arm_dct4_init_q31.c"
#include "arm_dct4_q15.c"
#include "arm_dct4_q31.c"
#include "arm_rfft_f32.c"
#include "arm_rfft_fast_f32.c"
#include "arm_rfft_fast_init_f32.c"
#include "arm_rfft_init_f32.c"
#include "arm_rfft_init_q15.c"
#include "arm_rfft_init_q31.c"
#include "arm_rfft_q15.c"
#include "arm_rfft_q31.c"
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/qcloud-iot-hub-sdk-3.1.2/3rdparty/samples/gateway/gateway_sample.c
|
<filename>components/connectivity/qcloud-iot-hub-sdk-3.1.2/3rdparty/samples/gateway/gateway_sample.c
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h>
#include "utils_getopt.h"
#include "qcloud_iot_export.h"
#define MAX_SIZE_OF_TOPIC (128)
#define MAX_SIZE_OF_DATA (128)
static int sg_sub_packet_id = -1;
#ifdef AUTH_MODE_CERT
static char sg_cert_file[PATH_MAX + 1]; // full path of device cert file
static char sg_key_file[PATH_MAX + 1]; // full path of device key file
#endif
void _event_handler(void *client, void *context, MQTTEventMsg *msg)
{
MQTTMessage* mqtt_messge = (MQTTMessage*)msg->msg;
uintptr_t packet_id = (uintptr_t)msg->msg;
switch(msg->event_type) {
case MQTT_EVENT_UNDEF:
Log_i("undefined event occur.");
break;
case MQTT_EVENT_DISCONNECT:
Log_i("MQTT disconnect.");
break;
case MQTT_EVENT_RECONNECT:
Log_i("MQTT reconnect.");
break;
case MQTT_EVENT_PUBLISH_RECVEIVED:
Log_i("topic message arrived but without any related handle: topic=%.*s, topic_msg=%.*s",
mqtt_messge->topic_len,
mqtt_messge->ptopic,
mqtt_messge->payload_len,
mqtt_messge->payload);
break;
case MQTT_EVENT_SUBCRIBE_SUCCESS:
Log_i("subscribe success, packet-id=%u", (unsigned int)packet_id);
sg_sub_packet_id = packet_id;
break;
case MQTT_EVENT_SUBCRIBE_TIMEOUT:
Log_i("subscribe wait ack timeout, packet-id=%u", (unsigned int)packet_id);
sg_sub_packet_id = packet_id;
break;
case MQTT_EVENT_SUBCRIBE_NACK:
Log_i("subscribe nack, packet-id=%u", (unsigned int)packet_id);
sg_sub_packet_id = packet_id;
break;
case MQTT_EVENT_UNSUBCRIBE_SUCCESS:
Log_i("unsubscribe success, packet-id=%u", (unsigned int)packet_id);
break;
case MQTT_EVENT_UNSUBCRIBE_TIMEOUT:
Log_i("unsubscribe timeout, packet-id=%u", (unsigned int)packet_id);
break;
case MQTT_EVENT_UNSUBCRIBE_NACK:
Log_i("unsubscribe nack, packet-id=%u", (unsigned int)packet_id);
break;
case MQTT_EVENT_PUBLISH_SUCCESS:
Log_i("publish success, packet-id=%u", (unsigned int)packet_id);
break;
case MQTT_EVENT_PUBLISH_TIMEOUT:
Log_i("publish timeout, packet-id=%u", (unsigned int)packet_id);
break;
case MQTT_EVENT_PUBLISH_NACK:
Log_i("publish nack, packet-id=%u", (unsigned int)packet_id);
break;
default:
Log_i("Should NOT arrive here.");
break;
}
}
static void _message_handler(void *client, MQTTMessage *message, void *user_data)
{
if (message == NULL) {
return;
}
Log_i("Receive Message With topicName:%.*s, payload:%.*s",
(int) message->topic_len, message->ptopic, (int) message->payload_len, (char *) message->payload);
}
static int sg_loop_count = 1;
static int parse_arguments(int argc, char **argv)
{
int c;
while ((c = utils_getopt(argc, argv, "c:l:")) != EOF)
switch (c)
{
case 'c':
if (HAL_SetDevInfoFile(utils_optarg))
return -1;
break;
case 'l':
sg_loop_count = atoi(utils_optarg);
if (sg_loop_count > 10000)
sg_loop_count = 10000;
else if (sg_loop_count < 0)
sg_loop_count = 1;
break;
default:
HAL_Printf("usage: %s [options]\n"
" [-c <config file for DeviceInfo>] \n"
" [-l <loop count>] \n"
, argv[0]);
return -1;
}
return 0;
}
int main(int argc, char **argv)
{
int rc = QCLOUD_ERR_FAILURE;
void* client = NULL;
IOT_Log_Set_Level(eLOG_DEBUG);
// parse arguments for device info file and loop test;
rc = parse_arguments(argc, argv);
if (rc != QCLOUD_RET_SUCCESS) {
Log_e("parse arguments error, rc = %d", rc);
return rc;
}
GatewayDeviceInfo GWdevInfo;
rc = HAL_GetGwDevInfo((void *)&GWdevInfo);
if(QCLOUD_RET_SUCCESS != rc){
Log_e("Get gateway dev info err,rc:%d",rc);
return rc;
}
GatewayInitParam init_params = DEFAULT_GATEWAY_INIT_PARAMS;
init_params.init_param.product_id = GWdevInfo.gw_info.product_id;
init_params.init_param.device_name = GWdevInfo.gw_info.device_name;
#ifdef AUTH_MODE_CERT
char certs_dir[PATH_MAX + 1] = "certs";
char current_path[PATH_MAX + 1];
char *cwd = getcwd(current_path, sizeof(current_path));
if (cwd == NULL)
{
Log_e("getcwd return NULL");
return QCLOUD_ERR_FAILURE;
}
sprintf(sg_cert_file, "%s/%s/%s", current_path, certs_dir, GWdevInfo.gw_info.dev_cert_file_name);
sprintf(sg_key_file, "%s/%s/%s", current_path, certs_dir, GWdevInfo.gw_info.dev_key_file_name);
init_params.init_param.cert_file = sg_cert_file;
init_params.init_param.key_file = sg_key_file;
#else
init_params.init_param.device_secret = GWdevInfo.gw_info.device_secret;
#endif
init_params.init_param.command_timeout = QCLOUD_IOT_MQTT_COMMAND_TIMEOUT;
init_params.init_param.auto_connect_enable = 1;
init_params.init_param.event_handle.h_fp = _event_handler;
client = IOT_Gateway_Construct(&init_params);
if (client == NULL) {
Log_e("client constructed failed.");
return QCLOUD_ERR_FAILURE;
}
// make sub-device online
GatewayParam param = DEFAULT_GATEWAY_PARAMS;;
param.product_id = GWdevInfo.gw_info.product_id;
param.device_name = GWdevInfo.gw_info.device_name;
DeviceInfo *subDevInfo;
subDevInfo = GWdevInfo.sub_dev_info;
param.subdev_product_id = subDevInfo->product_id;
param.subdev_device_name = subDevInfo->device_name;
rc = IOT_Gateway_Subdev_Online(client, ¶m);
if(rc != QCLOUD_RET_SUCCESS) {
Log_e("IOT_Gateway_Subdev_Online fail.");
return rc;
}
// subscribe sub-device topic
char topic_filter[MAX_SIZE_OF_TOPIC+1] = {0};
SubscribeParams sub_param = DEFAULT_SUB_PARAMS;
int size = HAL_Snprintf(topic_filter, MAX_SIZE_OF_TOPIC+1, "%s/%s/data", subDevInfo->product_id, subDevInfo->device_name);
if (size < 0 || size > MAX_SIZE_OF_TOPIC)
{
Log_e("buf size < topic length!");
return QCLOUD_ERR_FAILURE;
}
sub_param.on_message_handler = _message_handler;
rc = IOT_Gateway_Subscribe(client, topic_filter, &sub_param);
if(rc < 0) {
Log_e("IOT_Gateway_Subscribe fail.");
return rc;
}
rc = IOT_Gateway_Yield(client, 200);
// publish msg to sub-device topic
char topic_name[MAX_SIZE_OF_TOPIC+1] = {0};
PublishParams pub_param = DEFAULT_PUB_PARAMS;
size = HAL_Snprintf(topic_name, MAX_SIZE_OF_TOPIC+1, "%s/%s/data", subDevInfo->product_id, subDevInfo->device_name);
if (size < 0 || size > MAX_SIZE_OF_TOPIC)
{
Log_e("buf size < topic length!");
return QCLOUD_ERR_FAILURE;
}
pub_param.qos = QOS1;
pub_param.payload = "{\"data\":\"test gateway\"}";
pub_param.payload_len = sizeof("{\"data\":\"test gateway\"}");
do {
if(sg_sub_packet_id > 0) {
rc = IOT_Gateway_Publish(client, topic_name, &pub_param);
if(rc < 0) {
Log_e("IOT_Gateway_Publish fail.");
}
}
rc = IOT_Gateway_Yield(client, 200);
if (rc == QCLOUD_ERR_MQTT_ATTEMPTING_RECONNECT) {
HAL_SleepMs(1000);
continue;
}
else if (rc != QCLOUD_RET_SUCCESS && rc != QCLOUD_RET_MQTT_RECONNECTED){
Log_e("exit with error: %d", rc);
break;
}
HAL_SleepMs(1000);
} while (--sg_loop_count > 0);
// make sub-device offline
rc = IOT_Gateway_Subdev_Offline(client, ¶m);
if(rc != QCLOUD_RET_SUCCESS) {
Log_e("IOT_Gateway_Subdev_Offline fail.");
return rc;
}
rc = IOT_Gateway_Destroy(client);
return rc;
}
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/external/thedotfactory_fonts/orkney8pts.c
|
/* Font copyrights:
*
* Copyright (c) 2015,
* <NAME> (https://behance.net/pradil),
* <NAME> (http://oakes.co/),
* <NAME> (https://www.behance.net/cssobral20f492),
* with Reserved Font Name Orkney.
*
* Code was generated by The Dot Factory (https://github.com/pavius/the-dot-factory)
*
* This Font Software is licensed under the SIL Open Font License, Version 1.1. See SIL-License.txt
* for more informations.
*
*/
#include "nrf_font.h"
// Character bitmaps for Orkney 8pt
const uint8_t orkney_8ptBitmaps[] =
{
// @0 '!' (2 pixels wide)
0x00, //
0x00, //
0xC0, // ##
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x00, //
0x00, //
0xC0, // ##
0x00, //
0x00, //
0x00, //
0x00, //
// @16 '"' (3 pixels wide)
0x00, //
0x00, //
0xA0, // # #
0xA0, // # #
0xA0, // # #
0xA0, // # #
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
// @32 '#' (8 pixels wide)
0x00, //
0x00, //
0x22, // # #
0x22, // # #
0x22, // # #
0xFF, // ########
0x24, // # #
0x24, // # #
0x24, // # #
0xFF, // ########
0x44, // # #
0x44, // # #
0x00, //
0x00, //
0x00, //
0x00, //
// @48 '$' (6 pixels wide)
0x10, // #
0x38, // ###
0x44, // # #
0x80, // #
0xC0, // ##
0x60, // ##
0x38, // ###
0x0C, // ##
0x04, // #
0x84, // # #
0xC4, // ## #
0x78, // ####
0x10, // #
0x00, //
0x00, //
0x00, //
// @64 '%' (8 pixels wide)
0x00, //
0x00, //
0xE3, // ### ##
0xA2, // # # #
0xA4, // # # #
0xE8, // ### #
0x08, // #
0x10, // #
0x26, // # ##
0x29, // # # #
0x49, // # # #
0x86, // # ##
0x00, //
0x00, //
0x00, //
0x00, //
// @80 '&' (8 pixels wide)
0x00, //
0x00, //
0x38, // ###
0x48, // # #
0x40, // #
0x40, // #
0x20, // #
0x50, // # #
0x89, // # # #
0x86, // # ##
0x46, // # ##
0x39, // ### #
0x00, //
0x00, //
0x00, //
0x00, //
// @96 ''' (1 pixels wide)
0x00, //
0x00, //
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
// @112 '(' (3 pixels wide)
0x20, // #
0x20, // #
0x40, // #
0x40, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x40, // #
0x40, // #
0x20, // #
// @128 ')' (3 pixels wide)
0x80, // #
0xC0, // ##
0x40, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x40, // #
0x80, // #
// @144 '*' (3 pixels wide)
0x00, //
0x00, //
0xC0, // ##
0xE0, // ###
0xC0, // ##
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
// @160 '+' (8 pixels wide)
0x00, //
0x00, //
0x00, //
0x08, // #
0x08, // #
0x08, // #
0x08, // #
0xFF, // ########
0x08, // #
0x08, // #
0x08, // #
0x08, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @176 ',' (1 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x00, //
// @192 '-' (5 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xF8, // #####
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
// @208 '.' (2 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xC0, // ##
0x00, //
0x00, //
0x00, //
0x00, //
// @224 '/' (8 pixels wide)
0x00, //
0x00, //
0x03, // ##
0x02, // #
0x04, // #
0x04, // #
0x08, // #
0x08, // #
0x10, // #
0x10, // #
0x20, // #
0x20, // #
0x40, // #
0x40, // #
0x80, // #
0x00, //
// @240 '0' (7 pixels wide)
0x00, //
0x00, //
0x38, // ###
0x44, // # #
0xC6, // ## ##
0x82, // # #
0x82, // # #
0x82, // # #
0x82, // # #
0xC6, // ## ##
0x44, // # #
0x38, // ###
0x00, //
0x00, //
0x00, //
0x00, //
// @256 '1' (4 pixels wide)
0x00, //
0x00, //
0x30, // ##
0x70, // ###
0xB0, // # ##
0x30, // ##
0x30, // ##
0x30, // ##
0x30, // ##
0x30, // ##
0x30, // ##
0x30, // ##
0x00, //
0x00, //
0x00, //
0x00, //
// @272 '2' (6 pixels wide)
0x00, //
0x00, //
0x78, // ####
0xC8, // ## #
0x84, // # #
0x04, // #
0x08, // #
0x10, // #
0x30, // ##
0x60, // ##
0xC0, // ##
0xFC, // ######
0x00, //
0x00, //
0x00, //
0x00, //
// @288 '3' (6 pixels wide)
0x00, //
0x00, //
0x70, // ###
0xC8, // ## #
0x08, // #
0x08, // #
0x30, // ##
0x08, // #
0x04, // #
0x84, // # #
0xC8, // ## #
0x78, // ####
0x00, //
0x00, //
0x00, //
0x00, //
// @304 '4' (7 pixels wide)
0x00, //
0x00, //
0x0C, // ##
0x0C, // ##
0x14, // # #
0x14, // # #
0x24, // # #
0x44, // # #
0x44, // # #
0xFE, // #######
0x04, // #
0x04, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @320 '5' (6 pixels wide)
0x00, //
0x00, //
0x7C, // #####
0x80, // #
0x80, // #
0xF8, // #####
0x8C, // # ##
0x04, // #
0x04, // #
0x04, // #
0x8C, // # ##
0x78, // ####
0x00, //
0x00, //
0x00, //
0x00, //
// @336 '6' (7 pixels wide)
0x00, //
0x00, //
0x08, // #
0x10, // #
0x20, // #
0x78, // ####
0x44, // # #
0x86, // # ##
0x82, // # #
0x86, // # ##
0xC4, // ## #
0x78, // ####
0x00, //
0x00, //
0x00, //
0x00, //
// @352 '7' (7 pixels wide)
0x00, //
0x00, //
0xFE, // #######
0x06, // ##
0x04, // #
0x0C, // ##
0x08, // #
0x10, // #
0x10, // #
0x20, // #
0x20, // #
0x40, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @368 '8' (6 pixels wide)
0x00, //
0x00, //
0x70, // ###
0xC8, // ## #
0x88, // # #
0xC8, // ## #
0x70, // ###
0x88, // # #
0x84, // # #
0x84, // # #
0x88, // # #
0x78, // ####
0x00, //
0x00, //
0x00, //
0x00, //
// @384 '9' (7 pixels wide)
0x00, //
0x00, //
0x78, // ####
0xC4, // ## #
0x86, // # ##
0x82, // # #
0x84, // # #
0xC4, // ## #
0x78, // ####
0x10, // #
0x30, // ##
0x60, // ##
0x00, //
0x00, //
0x00, //
0x00, //
// @400 ':' (2 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xC0, // ##
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xC0, // ##
0x00, //
0x00, //
0x00, //
0x00, //
// @416 ';' (2 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xC0, // ##
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xC0, // ##
0x40, // #
0x40, // #
0x80, // #
0x00, //
// @432 '<' (7 pixels wide)
0x00, //
0x00, //
0x00, //
0x02, // #
0x0C, // ##
0x30, // ##
0x60, // ##
0xC0, // ##
0x60, // ##
0x18, // ##
0x06, // ##
0x02, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @448 '=' (8 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xFF, // ########
0x00, //
0x00, //
0xFF, // ########
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
// @464 '>' (7 pixels wide)
0x00, //
0x00, //
0x00, //
0x80, // #
0x60, // ##
0x18, // ##
0x06, // ##
0x02, // #
0x0C, // ##
0x30, // ##
0xC0, // ##
0x80, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @480 '?' (5 pixels wide)
0x00, //
0x00, //
0x70, // ###
0x88, // # #
0x88, // # #
0x08, // #
0x18, // ##
0x30, // ##
0x20, // #
0x20, // #
0x00, //
0x20, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @496 '@' (6 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x78, // ####
0x48, // # #
0x9C, // # ###
0xA4, // # # #
0xA4, // # # #
0x9C, // # ###
0x40, // #
0x3C, // ####
0x00, //
0x00, //
0x00, //
0x00, //
// @512 'A' (9 pixels wide)
0x00, 0x00, //
0x00, 0x00, //
0x0C, 0x00, // ##
0x0C, 0x00, // ##
0x14, 0x00, // # #
0x12, 0x00, // # #
0x32, 0x00, // ## #
0x23, 0x00, // # ##
0x21, 0x00, // # #
0x7F, 0x00, // #######
0x40, 0x80, // # #
0xC0, 0x80, // ## #
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
// @544 'B' (7 pixels wide)
0x00, //
0x00, //
0xF8, // #####
0x8C, // # ##
0x84, // # #
0x8C, // # ##
0xF8, // #####
0x84, // # #
0x82, // # #
0x82, // # #
0x86, // # ##
0xFC, // ######
0x00, //
0x00, //
0x00, //
0x00, //
// @560 'C' (7 pixels wide)
0x00, //
0x00, //
0x3E, // #####
0x62, // ## #
0xC0, // ##
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0xC0, // ##
0x62, // ## #
0x3E, // #####
0x00, //
0x00, //
0x00, //
0x00, //
// @576 'D' (8 pixels wide)
0x00, //
0x00, //
0xF8, // #####
0x84, // # #
0x82, // # #
0x82, // # #
0x83, // # ##
0x83, // # ##
0x82, // # #
0x82, // # #
0x84, // # #
0xF8, // #####
0x00, //
0x00, //
0x00, //
0x00, //
// @592 'E' (5 pixels wide)
0x00, //
0x00, //
0xF8, // #####
0x80, // #
0x80, // #
0x80, // #
0xF8, // #####
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0xF8, // #####
0x00, //
0x00, //
0x00, //
0x00, //
// @608 'F' (5 pixels wide)
0x00, //
0x00, //
0xF8, // #####
0x80, // #
0x80, // #
0x80, // #
0xF8, // #####
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @624 'G' (8 pixels wide)
0x00, //
0x00, //
0x1E, // ####
0x61, // ## #
0x40, // #
0x80, // #
0x8F, // # ####
0x81, // # #
0x81, // # #
0x41, // # #
0x61, // ## #
0x1E, // ####
0x00, //
0x00, //
0x00, //
0x00, //
// @640 'H' (8 pixels wide)
0x00, //
0x00, //
0x83, // # ##
0x83, // # ##
0x83, // # ##
0x83, // # ##
0xFF, // ########
0x83, // # ##
0x83, // # ##
0x83, // # ##
0x83, // # ##
0x83, // # ##
0x00, //
0x00, //
0x00, //
0x00, //
// @656 'I' (1 pixels wide)
0x00, //
0x00, //
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @672 'J' (3 pixels wide)
0x00, //
0x00, //
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0xC0, // ##
0x00, //
0x00, //
0x00, //
0x00, //
// @688 'K' (7 pixels wide)
0x00, //
0x00, //
0x86, // # ##
0x88, // # #
0x90, // # #
0xA0, // # #
0xC0, // ##
0xA0, // # #
0x90, // # #
0x88, // # #
0x84, // # #
0x82, // # #
0x00, //
0x00, //
0x00, //
0x00, //
// @704 'L' (5 pixels wide)
0x00, //
0x00, //
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0xF8, // #####
0x00, //
0x00, //
0x00, //
0x00, //
// @720 'M' (10 pixels wide)
0x00, 0x00, //
0x00, 0x00, //
0xC0, 0xC0, // ## ##
0xC0, 0xC0, // ## ##
0xA1, 0x40, // # # # #
0xB3, 0x40, // # ## ## #
0x92, 0x40, // # # # #
0x8C, 0x40, // # ## #
0x8C, 0x40, // # ## #
0x88, 0x40, // # # #
0x80, 0x40, // # #
0x80, 0x40, // # #
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
// @752 'N' (8 pixels wide)
0x00, //
0x00, //
0x81, // # #
0xC1, // ## #
0xA1, // # # #
0xB1, // # ## #
0x91, // # # #
0x89, // # # #
0x8D, // # ## #
0x87, // # ###
0x83, // # ##
0x81, // # #
0x00, //
0x00, //
0x00, //
0x00, //
// @768 'O' (9 pixels wide)
0x00, 0x00, //
0x00, 0x00, //
0x3E, 0x00, // #####
0x63, 0x00, // ## ##
0xC1, 0x80, // ## ##
0x80, 0x80, // # #
0x80, 0x80, // # #
0x80, 0x80, // # #
0x80, 0x80, // # #
0xC1, 0x80, // ## ##
0x63, 0x00, // ## ##
0x3E, 0x00, // #####
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
// @800 'P' (6 pixels wide)
0x00, //
0x00, //
0xF8, // #####
0x84, // # #
0x84, // # #
0x84, // # #
0xF8, // #####
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @816 'Q' (10 pixels wide)
0x00, 0x00, //
0x00, 0x00, //
0x3E, 0x00, // #####
0x63, 0x00, // ## ##
0xC1, 0x80, // ## ##
0x80, 0x80, // # #
0x80, 0x80, // # #
0x80, 0x80, // # #
0x84, 0x80, // # # #
0xC3, 0x80, // ## ###
0x63, 0x00, // ## ##
0x3E, 0xC0, // ##### ##
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
// @848 'R' (7 pixels wide)
0x00, //
0x00, //
0xF8, // #####
0x84, // # #
0x84, // # #
0x84, // # #
0xFC, // ######
0x90, // # #
0x88, // # #
0x88, // # #
0x84, // # #
0x86, // # ##
0x00, //
0x00, //
0x00, //
0x00, //
// @864 'S' (7 pixels wide)
0x00, //
0x00, //
0x78, // ####
0xC4, // ## #
0x80, // #
0xC0, // ##
0x70, // ###
0x0C, // ##
0x04, // #
0x86, // # ##
0x84, // # #
0x78, // ####
0x00, //
0x00, //
0x00, //
0x00, //
// @880 'T' (7 pixels wide)
0x00, //
0x00, //
0xFE, // #######
0x10, // #
0x10, // #
0x10, // #
0x10, // #
0x10, // #
0x10, // #
0x10, // #
0x10, // #
0x10, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @896 'U' (7 pixels wide)
0x00, //
0x00, //
0x82, // # #
0x82, // # #
0x82, // # #
0x82, // # #
0x82, // # #
0x82, // # #
0x82, // # #
0x82, // # #
0x46, // # ##
0x3C, // ####
0x00, //
0x00, //
0x00, //
0x00, //
// @912 'V' (9 pixels wide)
0x00, 0x00, //
0x00, 0x00, //
0xC0, 0x80, // ## #
0x41, 0x80, // # ##
0x41, 0x00, // # #
0x61, 0x00, // ## #
0x22, 0x00, // # #
0x22, 0x00, // # #
0x16, 0x00, // # ##
0x14, 0x00, // # #
0x1C, 0x00, // ###
0x0C, 0x00, // ##
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
// @944 'W' (14 pixels wide)
0x00, 0x00, //
0x00, 0x00, //
0x84, 0x04, // # # #
0xC6, 0x0C, // ## ## ##
0x42, 0x08, // # # #
0x62, 0x18, // ## # ##
0x23, 0x10, // # ## #
0x23, 0x10, // # ## #
0x13, 0xB0, // # ### ##
0x14, 0xA0, // # # # #
0x1C, 0xE0, // ### ###
0x08, 0x40, // # #
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
// @976 'X' (8 pixels wide)
0x00, //
0x00, //
0xC3, // ## ##
0x62, // ## #
0x24, // # #
0x1C, // ###
0x18, // ##
0x18, // ##
0x14, // # #
0x26, // # ##
0x62, // ## #
0xC1, // ## #
0x00, //
0x00, //
0x00, //
0x00, //
// @992 'Y' (8 pixels wide)
0x00, //
0x00, //
0xC1, // ## #
0x62, // ## #
0x26, // # ##
0x14, // # #
0x18, // ##
0x08, // #
0x08, // #
0x08, // #
0x08, // #
0x08, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @1008 'Z' (7 pixels wide)
0x00, //
0x00, //
0xFE, // #######
0x04, // #
0x0C, // ##
0x08, // #
0x10, // #
0x30, // ##
0x20, // #
0x40, // #
0xC0, // ##
0xFE, // #######
0x00, //
0x00, //
0x00, //
0x00, //
// @1024 '[' (3 pixels wide)
0xE0, // ###
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0xE0, // ###
// @1040 '\' (8 pixels wide)
0x00, //
0x00, //
0x80, // #
0x40, // #
0x40, // #
0x20, // #
0x20, // #
0x10, // #
0x10, // #
0x08, // #
0x08, // #
0x04, // #
0x04, // #
0x02, // #
0x03, // ##
0x00, //
// @1056 ']' (3 pixels wide)
0xE0, // ###
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0x20, // #
0xE0, // ###
// @1072 '^' (9 pixels wide)
0x00, 0x00, //
0x08, 0x00, // #
0x0C, 0x00, // ##
0x14, 0x00, // # #
0x16, 0x00, // # ##
0x22, 0x00, // # #
0x22, 0x00, // # #
0x41, 0x00, // # #
0xC1, 0x80, // ## ##
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
// @1104 '_' (7 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xFE, // #######
0x00, //
0x00, //
0x00, //
// @1120 '`' (3 pixels wide)
0x00, //
0x00, //
0xC0, // ##
0x60, // ##
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
// @1136 'a' (5 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x70, // ###
0x88, // # #
0x08, // #
0xF8, // #####
0x88, // # #
0x98, // # ##
0xE8, // ### #
0x00, //
0x00, //
0x00, //
0x00, //
// @1152 'b' (6 pixels wide)
0x00, //
0x00, //
0x80, // #
0x80, // #
0x80, // #
0xB8, // # ###
0xCC, // ## ##
0x84, // # #
0x84, // # #
0x84, // # #
0xCC, // ## ##
0xB8, // # ###
0x00, //
0x00, //
0x00, //
0x00, //
// @1168 'c' (4 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x70, // ###
0x90, // # #
0x80, // #
0x80, // #
0x80, // #
0x90, // # #
0x70, // ###
0x00, //
0x00, //
0x00, //
0x00, //
// @1184 'd' (6 pixels wide)
0x00, //
0x00, //
0x04, // #
0x04, // #
0x04, // #
0x74, // ### #
0x8C, // # ##
0x84, // # #
0x84, // # #
0x84, // # #
0x8C, // # ##
0x74, // ### #
0x00, //
0x00, //
0x00, //
0x00, //
// @1200 'e' (6 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x70, // ###
0x88, // # #
0x88, // # #
0xFC, // ######
0x80, // #
0x88, // # #
0x70, // ###
0x00, //
0x00, //
0x00, //
0x00, //
// @1216 'f' (4 pixels wide)
0x00, //
0x00, //
0x70, // ###
0x40, // #
0x40, // #
0xE0, // ###
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @1232 'g' (6 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x74, // ### #
0x8C, // # ##
0x84, // # #
0x84, // # #
0x84, // # #
0x8C, // # ##
0x74, // ### #
0x04, // #
0x88, // # #
0x70, // ###
0x00, //
// @1248 'h' (6 pixels wide)
0x00, //
0x00, //
0x80, // #
0x80, // #
0x80, // #
0xB8, // # ###
0xC8, // ## #
0x84, // # #
0x84, // # #
0x84, // # #
0x84, // # #
0x84, // # #
0x00, //
0x00, //
0x00, //
0x00, //
// @1264 'i' (2 pixels wide)
0x00, //
0x00, //
0xC0, // ##
0x00, //
0x00, //
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @1280 'j' (3 pixels wide)
0x00, //
0x00, //
0x60, // ##
0x00, //
0x00, //
0x60, // ##
0x60, // ##
0x60, // ##
0x60, // ##
0x60, // ##
0x60, // ##
0x60, // ##
0x60, // ##
0x40, // #
0xC0, // ##
0x00, //
// @1296 'k' (5 pixels wide)
0x00, //
0x00, //
0x80, // #
0x80, // #
0x80, // #
0x98, // # ##
0xB0, // # ##
0xE0, // ###
0xE0, // ###
0xB0, // # ##
0x98, // # ##
0x88, // # #
0x08, // #
0x00, //
0x00, //
0x00, //
// @1312 'l' (3 pixels wide)
0x00, //
0x00, //
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x60, // ##
0x00, //
0x00, //
0x00, //
0x00, //
// @1328 'm' (10 pixels wide)
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0xFB, 0x80, // ##### ###
0xCC, 0xC0, // ## ## ##
0x88, 0x40, // # # #
0x88, 0x40, // # # #
0x88, 0x40, // # # #
0x88, 0x40, // # # #
0x88, 0x40, // # # #
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
// @1360 'n' (6 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xB8, // # ###
0xC8, // ## #
0x84, // # #
0x84, // # #
0x84, // # #
0x84, // # #
0x84, // # #
0x00, //
0x00, //
0x00, //
0x00, //
// @1376 'o' (6 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x70, // ###
0x88, // # #
0x84, // # #
0x84, // # #
0x84, // # #
0x88, // # #
0x70, // ###
0x00, //
0x00, //
0x00, //
0x00, //
// @1392 'p' (6 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xB8, // # ###
0xCC, // ## ##
0x84, // # #
0x84, // # #
0x84, // # #
0xCC, // ## ##
0xB8, // # ###
0x80, // #
0x80, // #
0x80, // #
0x00, //
// @1408 'q' (6 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x74, // ### #
0x8C, // # ##
0x84, // # #
0x84, // # #
0x84, // # #
0x8C, // # ##
0x74, // ### #
0x04, // #
0x04, // #
0x04, // #
0x00, //
// @1424 'r' (4 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xB0, // # ##
0xC0, // ##
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @1440 's' (6 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x38, // ###
0x48, // # #
0x40, // #
0x38, // ###
0x0C, // ##
0xCC, // ## ##
0x78, // ####
0x00, //
0x00, //
0x00, //
0x00, //
// @1456 't' (5 pixels wide)
0x00, //
0x00, //
0x40, // #
0x40, // #
0x40, // #
0xF0, // ####
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x38, // ###
0x00, //
0x00, //
0x00, //
0x00, //
// @1472 'u' (6 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x84, // # #
0x84, // # #
0x84, // # #
0x84, // # #
0x84, // # #
0xCC, // ## ##
0x74, // ### #
0x00, //
0x00, //
0x00, //
0x00, //
// @1488 'v' (6 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xC4, // ## #
0x44, // # #
0x48, // # #
0x68, // ## #
0x28, // # #
0x30, // ##
0x10, // #
0x00, //
0x00, //
0x00, //
0x00, //
// @1504 'w' (9 pixels wide)
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0xD8, 0x80, // ## ## #
0x49, 0x80, // # # ##
0x49, 0x00, // # # #
0x4D, 0x00, // # ## #
0x35, 0x00, // ## # #
0x36, 0x00, // ## ##
0x32, 0x00, // ## #
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
0x00, 0x00, //
// @1536 'x' (7 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xC6, // ## ##
0x4C, // # ##
0x38, // ###
0x10, // #
0x38, // ###
0x4C, // # ##
0xC6, // ## ##
0x00, //
0x00, //
0x00, //
0x00, //
// @1552 'y' (6 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x84, // # #
0x84, // # #
0x84, // # #
0x84, // # #
0x84, // # #
0xCC, // ## ##
0x74, // ### #
0x04, // #
0x88, // # #
0x70, // ###
0x00, //
// @1568 'z' (5 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0xF8, // #####
0x18, // ##
0x30, // ##
0x20, // #
0x40, // #
0xC0, // ##
0xF8, // #####
0x00, //
0x00, //
0x00, //
0x00, //
// @1584 '{' (3 pixels wide)
0x60, // ##
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x60, // ##
// @1600 '|' (1 pixels wide)
0x00, //
0x00, //
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x80, // #
0x00, //
0x00, //
// @1616 '}' (3 pixels wide)
0x80, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x60, // ##
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x40, // #
0x80, // #
// @1632 '~' (7 pixels wide)
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x62, // ## #
0x52, // # # #
0x8C, // # ##
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
0x00, //
};
// Character descriptors for Orkney 8pt
// { [Char width in bits], [Offset into orkney_8ptCharBitmaps in bytes] }
const FONT_CHAR_INFO orkney_8ptDescriptors[] =
{
{2, 0}, // !
{3, 16}, // "
{8, 32}, // #
{6, 48}, // $
{8, 64}, // %
{8, 80}, // &
{1, 96}, // '
{3, 112}, // (
{3, 128}, // )
{3, 144}, // *
{8, 160}, // +
{1, 176}, // ,
{5, 192}, // -
{2, 208}, // .
{8, 224}, // /
{7, 240}, // 0
{4, 256}, // 1
{6, 272}, // 2
{6, 288}, // 3
{7, 304}, // 4
{6, 320}, // 5
{7, 336}, // 6
{7, 352}, // 7
{6, 368}, // 8
{7, 384}, // 9
{2, 400}, // :
{2, 416}, // ;
{7, 432}, // <
{8, 448}, // =
{7, 464}, // >
{5, 480}, // ?
{6, 496}, // @
{9, 512}, // A
{7, 544}, // B
{7, 560}, // C
{8, 576}, // D
{5, 592}, // E
{5, 608}, // F
{8, 624}, // G
{8, 640}, // H
{1, 656}, // I
{3, 672}, // J
{7, 688}, // K
{5, 704}, // L
{10, 720}, // M
{8, 752}, // N
{9, 768}, // O
{6, 800}, // P
{10, 816}, // Q
{7, 848}, // R
{7, 864}, // S
{7, 880}, // T
{7, 896}, // U
{9, 912}, // V
{14, 944}, // W
{8, 976}, // X
{8, 992}, // Y
{7, 1008}, // Z
{3, 1024}, // [
{8, 1040}, // '\'
{3, 1056}, // ]
{9, 1072}, // ^
{7, 1104}, // _
{3, 1120}, // `
{5, 1136}, // a
{6, 1152}, // b
{4, 1168}, // c
{6, 1184}, // d
{6, 1200}, // e
{4, 1216}, // f
{6, 1232}, // g
{6, 1248}, // h
{2, 1264}, // i
{3, 1280}, // j
{5, 1296}, // k
{3, 1312}, // l
{10, 1328}, // m
{6, 1360}, // n
{6, 1376}, // o
{6, 1392}, // p
{6, 1408}, // q
{4, 1424}, // r
{6, 1440}, // s
{5, 1456}, // t
{6, 1472}, // u
{6, 1488}, // v
{9, 1504}, // w
{7, 1536}, // x
{6, 1552}, // y
{5, 1568}, // z
{3, 1584}, // {
{1, 1600}, // |
{3, 1616}, // }
{7, 1632}, // ~
};
// Font information for Orkney 8pt
const FONT_INFO orkney_8ptFontInfo =
{
15, // Character height
'!', // Start character
'~', // End character
2, // Width, in pixels, of space character
orkney_8ptDescriptors, // Character descriptor array
orkney_8ptBitmaps, // Character bitmap array
};
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/src/event/qcloud_event_json.c
|
<filename>components/connectivity/TencentCloud_SDK/source/src/event/qcloud_event_json.c
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud.h"
#define PRIi32 "i"
#define PRIi16 "i"
#define PRIi8 "i"
#define PRIu32 "u"
#define PRIu16 "u"
#define PRIu8 "u"
#define SCNi8 "hhi"
#define SCNu8 "hhu"
#define SCNi16 "hi"
#define SCNu16 "hu"
#define SCNi32 "i"
#define SCNu32 "u"
__QCLOUD_INTERNAL__ qcloud_err_t event_json_node_add(char *json_doc, size_t json_doc_size, const char *key, void *data, json_data_type_t type)
{
qcloud_err_t rc;
int32_t rc_snprintf = 0;
size_t remain_size = 0;
if ((remain_size = json_doc_size - strlen(json_doc)) <= 1) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_JSON_BUFFER_TOO_SHORT);
}
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "\"%s\":", key);
rc = shadow_json_snprintf_rc2errno(rc_snprintf, remain_size);
QCLOUD_FUNC_EXIT_RC_IF_NOT(rc, QCLOUD_ERR_SUCCESS, rc);
if ((remain_size = json_doc_size - strlen(json_doc)) <= 1) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_JSON_BUFFER_TOO_SHORT);
}
if (!data) {
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "null,");
QCLOUD_FUNC_EXIT_RC(shadow_json_snprintf_rc2errno(rc_snprintf, remain_size));
}
switch (type) {
case JSON_DATA_TYPE_INT32:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIi32
",", *(int32_t *)(data));
break;
case JSON_DATA_TYPE_INT16:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIi16
",", *(int16_t *)(data));
break;
case JSON_DATA_TYPE_INT8:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIi8
",", *(int8_t *)(data));
break;
case JSON_DATA_TYPE_UINT32:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIu32
",", *(uint32_t *)(data));
break;
case JSON_DATA_TYPE_UINT16:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIu16
",", *(uint16_t *)(data));
break;
case JSON_DATA_TYPE_UINT8:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%"
PRIu8
",", *(uint8_t *)(data));
break;
case JSON_DATA_TYPE_DOUBLE:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%f,", *(double *)(data));
break;
case JSON_DATA_TYPE_FLOAT:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%f,", *(float *)(data));
break;
case JSON_DATA_TYPE_BOOL:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%u,",
*(bool *) (data) ? 1 : 0);
break;
case JSON_DATA_TYPE_STRING:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "\"%s\",", (char *)(data));
break;
case JSON_DATA_TYPE_OBJECT:
rc_snprintf = osal_snprintf(json_doc + strlen(json_doc), remain_size, "%s,", (char *)(data));
break;
}
QCLOUD_FUNC_EXIT_RC(shadow_json_snprintf_rc2errno(rc_snprintf, remain_size));
}
__QCLOUD_INTERNAL__ int event_json_return_code_parse(char *json_doc, int32_t *return_code)
{
int rc = QCLOUD_TRUE;
char *return_code_str;
return_code_str = LITE_json_value_of(EVENT_REPLY_FIELD_CODE, json_doc);
if (!return_code_str) {
return QCLOUD_FALSE;
}
if (sscanf(return_code_str, "%" SCNi32, return_code) != 1) {
QCLOUD_LOG_E("parse code failed, rc: %d", QCLOUD_ERR_JSON_PARSE);
rc = QCLOUD_FALSE;
}
osal_free(return_code_str);
return rc;
}
__QCLOUD_INTERNAL__ int event_json_status_parse(char *json_doc, char **status)
{
*status = LITE_json_value_of(EVENT_REPLY_FIELD_STATUS, json_doc);
return *status != NULL;
}
#ifdef __cplusplus
}
#endif
|
umaru724/TencentOS_E53_IA1
|
components/lzw/lzwfilter.c
|
<reponame>umaru724/TencentOS_E53_IA1
////////////////////////////////////////////////////////////////////////////
// **** LZW-AB **** //
// Adjusted Binary LZW Compressor/Decompressor //
// Copyright (c) 2016 <NAME> //
// All Rights Reserved //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef _WIN32
#include <fcntl.h>
#endif
#include "lzw-lib.h"
/* This module provides a command-line filter for testing the lzw library.
* It can also optionally calculate and display the compression ratio and
* a simple checksum for informational purposes. Other command-line
* arguments select decoding mode or the maximum symbol size (9 to 12 bits)
* for encoding.
*/
static const char *usage =
" Usage: LZW-AB [-options] [< infile] [> outfile]\n\n"
" Operation: compression is default, use -d to decompress\n\n"
" Options: -d = decompress\n"
" -h = display this \"help\" message\n"
" -1 = maximum symbol size = 9 bits\n"
" -2 = maximum symbol size = 10 bits\n"
" -3 = maximum symbol size = 11 bits\n"
" -4 = maximum symbol size = 12 bits (default)\n"
" -v = verbose (display ratio and checksum)\n\n"
" Web: Visit www.github.com/dbry/lzw-ab for latest version and info\n\n";
static unsigned char read_buffer [65536], write_buffer [65536];
static size_t read_count, write_count;
static int read_checksum, write_checksum;
static int read_head, read_tail, write_head;
static int read_buff (void)
{
int value;
if (read_head == read_tail)
read_tail = (read_head = 0) + fread (read_buffer, 1, sizeof (read_buffer), stdin);
if (read_head < read_tail) {
value = read_buffer [read_head++];
read_checksum = read_checksum * 3 + (unsigned char) value;
read_count++;
}
else
value = EOF;
return value;
}
static void write_buff (int value)
{
if (value == EOF) {
fwrite (write_buffer, 1, write_head, stdout);
return;
}
write_buffer [write_head++] = value;
if (write_head == sizeof (write_buffer)) {
fwrite (write_buffer, 1, write_head, stdout);
write_head = 0;
}
write_checksum = write_checksum * 3 + (unsigned char) value;
write_count++;
}
int main (int argc, char **argv)
{
int decompress = 0, maxbits = 12, verbose = 0, error = 0;
read_checksum = write_checksum = -1;
while (--argc) {
if ((**++argv == '-') && (*argv)[1])
while (*++*argv)
switch (**argv) {
case '1':
maxbits = 9;
break;
case '2':
maxbits = 10;
break;
case '3':
maxbits = 11;
break;
case '4':
maxbits = 12;
break;
case 'D': case 'd':
decompress = 1;
break;
case 'H': case 'h':
fprintf (stderr, "%s", usage);
return 0;
break;
case 'V': case 'v':
verbose = 1;
break;
default:
fprintf (stderr, "illegal option: %c !\n", **argv);
error = 1;
break;
}
else {
fprintf (stderr, "unknown argument: %s\n", *argv);
error = 1;
}
}
if (error) {
fprintf (stderr, "%s", usage);
return 0;
}
#ifdef _WIN32
setmode (fileno (stdin), O_BINARY);
setmode (fileno (stdout), O_BINARY);
#endif
if (decompress) {
if (lzw_decompress (write_buff, read_buff)) {
fprintf (stderr, "lzw_decompress() returned non-zero!\n");
return 1;
}
write_buff (EOF);
if (verbose && write_count)
fprintf (stderr, "output checksum = %x, ratio = %.2f%%\n", write_checksum, read_count * 100.0 / write_count);
}
else {
if (lzw_compress (write_buff, read_buff, maxbits)) {
fprintf (stderr, "lzw_compress() returned non-zero!\n");
return 1;
}
write_buff (EOF);
if (verbose && read_count)
fprintf (stderr, "source checksum = %x, ratio = %.2f%%\n", read_checksum, write_count * 100.0 / read_count);
}
return 0;
}
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/external/cifra_AES128-EAX/cifra_eax_aes.h
|
<filename>platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/external/cifra_AES128-EAX/cifra_eax_aes.h
/*
* cifra - embedded cryptography library
* Written in 2014 by <NAME> <<EMAIL>>
*
* To the extent possible under law, the author(s) have dedicated all
* copyright and related and neighboring rights to this software to the
* public domain worldwide. This software is distributed without any
* warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication
* along with this software. If not, see
* <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
/**
* The AES block cipher
* ====================
*
* This is a small, simple implementation of AES. Key expansion is done
* first, filling in a :c:type:`cf_aes_context`. Then encryption and
* decryption can be performed as desired.
*
* Usually you don't want to use AES directly; you should use it via
* a :doc:`block cipher mode <modes>`.
*/
#ifndef AES_H
#define AES_H
#include <stddef.h>
#include <stdint.h>
#include "prp.h"
/* .. c:macro:: AES_BLOCKSZ
* AES has a 128-bit block size. This quantity is in bytes.
*/
#define AES_BLOCKSZ 16
/* --- Size configuration --- */
/* .. c:macro:: AES128_ROUNDS
* .. c:macro:: AES192_ROUNDS
* .. c:macro:: AES256_ROUNDS
*
* Round counts for different key sizes.
*/
#define AES128_ROUNDS 10
#define AES192_ROUNDS 12
#define AES256_ROUNDS 14
/* .. c:macro:: CF_AES_MAXROUNDS
*
* You can reduce the maximum number of rounds this implementation
* supports. This reduces the storage needed by :c:type:`cf_aes_context`.
*
* The default is :c:macro:`AES256_ROUNDS` and is good for all key
* sizes.
*/
#ifndef CF_AES_MAXROUNDS
# define CF_AES_MAXROUNDS AES256_ROUNDS
#endif
/* .. c:macro:: CF_AES_ENCRYPT_ONLY
*
* Define this to 1 if you don't need to decrypt anything.
* This saves space. :c:func:`cf_aes_decrypt` calls `abort(3)`.
*/
#ifndef CF_AES_ENCRYPT_ONLY
# define CF_AES_ENCRYPT_ONLY 0
#endif
/* .. c:type:: cf_aes_context
* This type represents an expanded AES key. Create one
* using :c:func:`cf_aes_init`, make use of one using
* :c:func:`cf_aes_encrypt` or :c:func:`cf_aes_decrypt`.
*
* The contents of this structure are equivalent to the
* original key material. You should clean the
* contents of this structure with :c:func:`cf_aes_finish`
* when you're done.
*
* .. c:member:: cf_aes_context.rounds
*
* Number of rounds to use, set by :c:func:`cf_aes_init`.
*
* This depends on the original key size, and will be
* :c:macro:`AES128_ROUNDS`, :c:macro:`AES192_ROUNDS` or
* :c:macro:`AES256_ROUNDS`.
*
* .. c:member:: cf_aes_context.ks
*
* Expanded key material. Filled in by :c:func:`cf_aes_init`.
*/
typedef struct
{
uint32_t rounds;
uint32_t ks[AES_BLOCKSZ / 4 * (CF_AES_MAXROUNDS + 1)];
} cf_aes_context;
/* .. c:function:: $DECL
* This function does AES key expansion. It destroys
* existing contents of :c:data:`ctx`.
*
* :param ctx: expanded key context, filled in by this function.
* :param key: pointer to key material, of :c:data:`nkey` bytes.
* :param nkey: length of key material. Must be `16`, `24` or `32`.
*/
extern void cf_aes_init(cf_aes_context *ctx,
const uint8_t *key,
size_t nkey);
/* .. c:function:: $DECL
* Encrypts the given block, from :c:data:`in` to :c:data:`out`.
* These may alias.
*
* Fails at runtime if :c:data:`ctx` is invalid.
*
* :param ctx: expanded key context
* :param in: input block (read)
* :param out: output block (written)
*/
extern void cf_aes_encrypt(const cf_aes_context *ctx,
const uint8_t in[AES_BLOCKSZ],
uint8_t out[AES_BLOCKSZ]);
/* .. c:function:: $DECL
* Decrypts the given block, from :c:data:`in` to :c:data:`out`.
* These may alias.
*
* Fails at runtime if :c:data:`ctx` is invalid.
*
* :param ctx: expanded key context
* :param in: input block (read)
* :param out: output block (written)
*/
extern void cf_aes_decrypt(const cf_aes_context *ctx,
const uint8_t in[AES_BLOCKSZ],
uint8_t out[AES_BLOCKSZ]);
/* .. c:function:: $DECL
* Erase scheduled key material.
*
* Call this when you're done to erase the round keys. */
extern void cf_aes_finish(cf_aes_context *ctx);
/* .. c:var:: const cf_prp cf_aes
* Abstract interface to AES. See :c:type:`cf_prp` for
* more information. */
extern const cf_prp cf_aes;
#endif
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/src/mqtt/qcloud_mqtt_common.c
|
/*******************************************************************************
* Copyright (c) 2014 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* <NAME> - initial API and implementation and/or initial documentation
* <NAME> - non-blocking packet read functions for stream transport
*******************************************************************************/
#include "qcloud.h"
__QCLOUD_STATIC__ int mqtt_common_packet_length_get(int rem_len)
{
rem_len += 1; /* header byte */
/* now remaining_length field */
if (rem_len < 128) {
rem_len += 1;
} else if (rem_len < 16384) {
rem_len += 2;
} else if (rem_len < 2097151) {
rem_len += 3;
} else {
rem_len += 4;
}
return rem_len;
}
/**
* Determines the length of the MQTT connect packet that would be produced using the supplied connect options.
* @param options the options to be used to build the connect packet
* @param the length of buffer needed to contain the serialized version of the packet
* @return int indicating function execution status
*/
__QCLOUD_STATIC__ int mqtt_common_serialize_connect_packet_length(mqtt_connect_opt_t *connect_opt)
{
int len = 0;
/* variable depending on MQTT or MQIsdp */
if (connect_opt->mqtt_version == 3) {
len = 12;
} else if (connect_opt->mqtt_version == 4) {
len = 10;
}
len += strlen(connect_opt->client_id) + 2;
if (connect_opt->username_len) {
len += connect_opt->username_len + 2;
}
if (connect_opt->password_len) {
len += connect_opt->password_len + 2;
}
return len;
}
/**
* Determines the length of the MQTT publish packet that would be produced using the supplied parameters
* @param qos the MQTT QoS of the publish (packetid is omitted for QoS 0)
* @param topicName the topic name to be used in the publish
* @param payload_len the length of the payload to be sent
* @return the length of buffer needed to contain the serialized version of the packet
*/
__QCLOUD_STATIC__ int mqtt_common_serialize_publish_packet_length(int qos, char *topic, size_t payload_len)
{
int len = 0;
len += 2 + strlen(topic) + payload_len;
if (qos > MQTT_QOS0) {
len += 2; /* packet id */
}
return len;
}
/**
* Determines the length of the MQTT subscribe packet that would be produced using the supplied parameters
* @param count the number of topic filter strings in topicFilters
* @param topicFilters the array of topic filter strings to be used in the publish
* @return the length of buffer needed to contain the serialized version of the packet
*/
__QCLOUD_STATIC__ int mqtt_common_serialize_subscribe_packet_length(uint32_t count, char *topic_filters[])
{
int i;
int len = 2; /* packet id */
for (i = 0; i < count; ++i) {
len += 2 + strlen(topic_filters[i]) + 1; /* length + topic + req_qos */
}
return len;
}
/**
* Determines the length of the MQTT unsubscribe packet that would be produced using the supplied parameters
* @param count the number of topic filter strings in topicFilters
* @param topicFilters the array of topic filter strings to be used in the publish
* @return the length of buffer needed to contain the serialized version of the packet
*/
__QCLOUD_STATIC__ int mqtt_common_serialize_unsubscribe_packet_length(uint32_t count, char *topic_filters[])
{
int i = 0;
int len = 2; /* packet id */
for (i = 0; i < count; ++i) {
len += 2 + strlen(topic_filters[i]); /* length + topic*/
}
return len;
}
/**
* Decodes the message length according to the MQTT algorithm
* @param getcharfn pointer to function to read the next character from the data source
* @param value the decoded length returned
* @return the number of bytes read from the socket
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_common_packet_do_decode_from_buf(uint32_t (*getcharfn)(uint8_t *, uint32_t), uint32_t *value, uint32_t *read_bytes_len)
{
QCLOUD_FUNC_ENTRY;
uint8_t c;
uint32_t multiplier = 1;
uint32_t len = 0, get_len;
*value = 0;
do {
#define MAX_NO_OF_REMAINING_LENGTH_BYTES 4
if (++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) {
/* bad data */
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_PACKET_READ);
}
get_len = 0;
get_len = (*getcharfn)(&c, 1);
if (1 != get_len) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
*value += (c & 127) * multiplier;
multiplier *= 128;
} while ((c & 128) != 0);
*read_bytes_len = len;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
static uint8_t *bufptr;
__QCLOUD_STATIC__ uint32_t __bufchar(uint8_t *c, uint32_t count)
{
uint32_t i;
for (i = 0; i < count; ++i) {
*c = *bufptr++;
}
return count;
}
/**
* Encodes the message length according to the MQTT algorithm
* @param buf the buffer into which the encoded data is written
* @param length the length to be encoded
* @return the number of bytes written to buffer
*/
__QCLOUD_INTERNAL__ int mqtt_common_packet_encode(uint8_t *buf, int length)
{
QCLOUD_FUNC_ENTRY;
int rc = 0;
uint8_t encode_byte;
do {
encode_byte = (uint8_t)(length % 128);
length /= 128;
/* if there are more digits to encode, set the top bit of this digit */
if (length > 0) {
encode_byte |= 0x80;
}
buf[rc++] = encode_byte;
} while (length > 0);
return rc;
}
__QCLOUD_STATIC__ qcloud_err_t mqtt_common_packet_decode_from_buf(uint8_t *buf, uint32_t *value, uint32_t *read_bytes_len)
{
bufptr = buf;
return mqtt_common_packet_do_decode_from_buf(__bufchar, value, read_bytes_len);
}
/**
* Calculates uint16 packet id from two bytes read from the input buffer
* @param pptr pointer to the input buffer - incremented by the number of bytes used & returned
* @return the value calculated
*/
__QCLOUD_STATIC__ uint16_t mqtt_common_packet_read_dbyte(uint8_t **pptr)
{
uint8_t *ptr = *pptr;
uint8_t firstByte = (uint8_t) (*ptr);
uint8_t secondByte = (uint8_t) (*(ptr + 1));
uint16_t len = (uint16_t) (secondByte + (256 * firstByte));
*pptr += 2;
return len;
}
/**
* Reads one character from the input buffer.
* @param pptr pointer to the input buffer - incremented by the number of bytes used & returned
* @return the character read
*/
__QCLOUD_STATIC__ uint8_t mqtt_common_packet_read_byte(uint8_t **pptr)
{
uint8_t c = **pptr;
(*pptr)++;
return c;
}
/**
* @param mqttstring the MQTTString structure into which the data is to be read
* @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
* @param enddata pointer to the end of the data: do not read beyond
* @return SUCCESS if successful, FAILURE if not
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_common_packet_read_string(char **string, uint16_t *string_len, uint8_t **pptr, uint8_t *enddata)
{
/* the first two bytes are the length of the string */
if (enddata - (*pptr) <= 1) { /* enough length to read the integer? */
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
*string_len = mqtt_common_packet_read_dbyte(pptr); /* increments pptr to point past length */
if (*string_len > QCLOUD_MQTT_CLIENT_RX_BUF_LEN){
QCLOUD_LOG_E("string length overflow!");
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
if (&(*pptr)[*string_len] > enddata) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
*string = (char *)*pptr;
*pptr += *string_len;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* Writes one character to an output buffer.
* @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
* @param c the character to write
*/
__QCLOUD_STATIC__ void mqtt_common_packet_write_byte(uint8_t **pptr, uint8_t c)
{
**pptr = c;
(*pptr)++;
}
/**
* Writes an integer as 2 bytes to an output buffer.
* @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
* @param anInt the integer to write
*/
__QCLOUD_STATIC__ void mqtt_common_packet_write_dbyte(uint8_t **pptr, uint16_t dbyte)
{
**pptr = (uint8_t)(dbyte / 256);
(*pptr)++;
**pptr = (uint8_t)(dbyte % 256);
(*pptr)++;
}
/**
* Writes a "UTF" string to an output buffer. Converts C string to length-delimited.
* @param pptr pointer to the output buffer - incremented by the number of bytes used & returned
* @param string the C string to write
*/
__QCLOUD_STATIC__ void mqtt_common_packet_write_string(uint8_t **pptr, const char *string)
{
size_t len = strlen(string);
mqtt_common_packet_write_dbyte(pptr, (uint16_t)len);
memcpy(*pptr, string, len);
*pptr += len;
}
/**
* Serializes the ack packet into the supplied buffer.
* @param buf the buffer into which the packet will be serialized
* @param buf_len the length in bytes of the supplied buffer
* @param packet_type the MQTT packet type: 1.PUBACK; 2.PUBREL; 3.PUBCOMP
* @param dup the MQTT dup flag
* @param packet_id the MQTT packet identifier
* @return serialized length, or error if 0
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_common_serialize_ack_packet(uint8_t *buf,
size_t buf_len,
mqtt_packet_t packet_type,
uint8_t dup,
uint16_t packet_id,
uint32_t *serialized_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(serialized_len, QCLOUD_ERR_INVAL);
mqtt_header_t header = {0};
uint8_t *ptr = buf;
/* Minimum byte length required by ACK headers is
* 2 for fixed and 2 for variable part */
if (buf_len < 4) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
header.bits.type = packet_type;
header.bits.dup = dup;
header.bits.qos = (packet_type == MQTT_PACKET_TYPE_PUBREL) ? 1 : 0;
mqtt_common_packet_write_byte(&ptr, header.byte); /* write header */
ptr += mqtt_common_packet_encode(ptr, 2); /* write remaining length */
mqtt_common_packet_write_dbyte(&ptr, packet_id);
*serialized_len = ptr - buf;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* Deserializes the supplied (wire) buffer into an ack
* @param packet_type returned integer - the MQTT packet type
* @param dup returned integer - the MQTT dup flag
* @param packet_id returned integer - the MQTT packet identifier
* @param buf the raw buffer data, of the correct length determined by the remaining length field
* @param buf_len the length in bytes of the data in the supplied buffer
* @return error code. 1 is success, 0 is failure
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_deserialize_ack_packet(uint8_t *packet_type,
uint8_t *dup,
uint16_t *packet_id,
uint8_t *buf,
size_t buf_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(packet_type, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(dup, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(packet_id, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
mqtt_header_t header = {0};
uint8_t ack_code;
uint8_t *curdata = buf, *enddata = NULL;
uint32_t decoded_len = 0, read_bytes_len = 0;
/* PUBACK fixed header size is two bytes, variable header is 2 bytes, MQTT v3.1.1 Specification 3.4.1 */
if (buf_len < 4) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
header.byte = mqtt_common_packet_read_byte(&curdata);
*dup = header.bits.dup;
*packet_type = header.bits.type;
/* read remaining length */
rc = mqtt_common_packet_decode_from_buf(curdata, &decoded_len, &read_bytes_len);
if (QCLOUD_ERR_SUCCESS != rc) {
QCLOUD_FUNC_EXIT_RC(rc);
}
curdata += read_bytes_len;
enddata = curdata + decoded_len;
if (enddata - curdata < 2) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
*packet_id = mqtt_common_packet_read_dbyte(&curdata);
// 返回错误码处理
if (enddata - curdata >= 1) {
ack_code = mqtt_common_packet_read_byte(&curdata);
if (ack_code != 0) {
QCLOUD_LOG_E("deserialize ack packet failure! 0x%02x", ack_code);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
}
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* Deserializes the supplied (wire) buffer into suback data
* @param packet_id returned integer - the MQTT packet identifier
* @param max_count - the maximum number of members allowed in the grantedQoSs array
* @param count returned integer - number of members in the grantedQoSs array
* @param grantedQoSs returned array of integers - the granted qualities of service
* @param buf the raw buffer data, of the correct length determined by the remaining length field
* @param buf_len the length in bytes of the data in the supplied buffer
* @return error code. 1 is success, 0 is failure
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_deserialize_suback_packet(uint16_t *packet_id,
uint32_t max_count,
uint32_t *count,
int granted_qoss[],
uint8_t *buf,
size_t buf_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(packet_id, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(count, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(granted_qoss, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
mqtt_header_t header = {0};
uint8_t *curdata = buf, *enddata = NULL;
uint32_t decoded_len = 0, read_bytes_len = 0;
// SUBACK头部大小为4字节, 负载部分至少为1字节QOS返回码
if (buf_len < 5) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
// 读取报文固定头部的第一个字节
header.byte = mqtt_common_packet_read_byte(&curdata);
if (header.bits.type != MQTT_PACKET_TYPE_SUBACK) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
// 读取报文固定头部的剩余长度
rc = mqtt_common_packet_decode_from_buf(curdata, &decoded_len, &read_bytes_len);
if (rc != QCLOUD_ERR_SUCCESS) {
QCLOUD_FUNC_EXIT_RC(rc);
}
curdata += read_bytes_len;
enddata = curdata + decoded_len;
if (enddata - curdata < 2) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
// 读取报文可变头部的报文标识符
*packet_id = mqtt_common_packet_read_dbyte(&curdata);
// 读取报文的负载部分
*count = 0;
while (curdata < enddata) {
if (*count > max_count) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
granted_qoss[(*count)++] = mqtt_common_packet_read_byte(&curdata);
}
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* Deserializes the supplied (wire) buffer into unsuback data
* @param packet_id returned integer - the MQTT packet identifier
* @param buf the raw buffer data, of the correct length determined by the remaining length field
* @param buf_len the length in bytes of the data in the supplied buffer
* @return int indicating function execution status
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_deserialize_unsuback_packet(uint16_t *packet_id,
uint8_t *buf,
size_t buf_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(packet_id, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
uint8_t type = 0, dup = 0;
rc = mqtt_common_deserialize_ack_packet(&type, &dup, packet_id, buf, buf_len);
if (rc != QCLOUD_ERR_SUCCESS || type != MQTT_PACKET_TYPE_UNSUBACK) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* Serializes the connect options into the buffer.
* @param buf the buffer into which the packet will be serialized
* @param len the length in bytes of the supplied buffer
* @param options the options to be used to build the connect packet
* @param serialized length
* @return int indicating function execution status
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_serialize_connect_packet(uint8_t *buf,
size_t buf_len,
mqtt_connect_opt_t *connect_opt,
uint32_t *serialized_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(connect_opt, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(serialized_len, QCLOUD_ERR_INVAL);
int packet_len = 0;
uint8_t *ptr = buf;
mqtt_header_t header = {0};
mqtt_connect_flag_t flags = {0};
packet_len = mqtt_common_serialize_connect_packet_length(connect_opt);
if (mqtt_common_packet_length_get(packet_len) > buf_len) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
header.byte = 0;
header.bits.type = MQTT_PACKET_TYPE_CONNECT;
// 报文固定头部第一个字节
mqtt_common_packet_write_byte(&ptr, header.byte); /* write header */
// 报文固定头部剩余长度字段
ptr += mqtt_common_packet_encode(ptr, packet_len); /* write remaining length */
// 报文可变头部协议名 + 协议版本号
if (connect_opt->mqtt_version == 4) {
mqtt_common_packet_write_string(&ptr, "MQTT");
mqtt_common_packet_write_byte(&ptr, (uint8_t)4);
} else {
mqtt_common_packet_write_string(&ptr, "MQIsdp");
mqtt_common_packet_write_byte(&ptr, (uint8_t)3);
}
// 报文可变头部连接标识位
flags.all = 0;
flags.bits.cleansession = connect_opt->clean_session;
if (connect_opt->username_len) {
flags.bits.username = 1;
}
if (connect_opt->password_len) {
flags.bits.password = 1;
}
mqtt_common_packet_write_byte(&ptr, flags.all);
// 报文可变头部心跳周期/保持连接, 一个以秒为单位的时间间隔, 表示为一个16位的字
mqtt_common_packet_write_dbyte(&ptr, connect_opt->keep_alive_interval);
// 有效负载部分: 客户端标识符
mqtt_common_packet_write_string(&ptr, connect_opt->client_id);
// 用户名
if (flags.bits.username) {
mqtt_common_packet_write_string(&ptr, connect_opt->username);
}
if (flags.bits.password) {
mqtt_common_packet_write_string(&ptr, connect_opt->password);
}
*serialized_len = ptr - buf;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* Deserializes the supplied (wire) buffer into connack data - return code
* @param sessionPresent the session present flag returned (only for MQTT 3.1.1)
* @param connack_rc returned integer value of the connack return code
* @param buf the raw buffer data, of the correct length determined by the remaining length field
* @param buflen the length in bytes of the data in the supplied buffer
* @return int indicating function execution status
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_deserialize_connack_packet(uint8_t *session_present,
uint8_t *connack_rc,
uint8_t *buf,
size_t buf_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(session_present, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(connack_rc, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
mqtt_header_t header = {0};
mqtt_connack_flags_t flags = {0};
uint8_t *curdata = buf, *enddata = NULL;
uint32_t decoded_len = 0, read_bytes_len = 0;
// CONNACK 头部大小是固定的2字节长度, 可变头部也是两个字节的长度, 无有效负载
if (buf_len < 4) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
// 读取固定头部第一个字节
header.byte = mqtt_common_packet_read_byte(&curdata);
if (header.bits.type != MQTT_PACKET_TYPE_CONNACK) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
// 读取固定头部剩余长度字段
QCLOUD_FUNC_EXIT_RC_IF_NOT(rc = mqtt_common_packet_decode_from_buf(curdata, &decoded_len, &read_bytes_len), QCLOUD_ERR_SUCCESS, rc);
curdata += read_bytes_len;
enddata = curdata + decoded_len;
if (enddata - curdata != 2) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
// 读取可变头部-连接确认标志 参考MQTT协议说明文档3.2.2.1小结
flags.all = mqtt_common_packet_read_byte(&curdata);
*session_present = flags.bits.sessionpresent;
// 读取可变头部-连接返回码 参考MQTT协议说明文档3.2.2.3小结
*connack_rc = mqtt_common_packet_read_byte(&curdata);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* Serializes a 0-length packet into the supplied buffer, ready for writing to a socket
* @param buf the buffer into which the packet will be serialized
* @param buf_len the length in bytes of the supplied buffer, to avoid overruns
* @param packettype the message type
* @param serialized length
* @return int indicating function execution status
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_serialize_zero_payload_packet(uint8_t *buf,
size_t buf_len,
mqtt_packet_t packet_type,
uint32_t *serialized_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(serialized_len, QCLOUD_ERR_INVAL);
uint8_t *ptr = buf;
mqtt_header_t header = {0};
/* Buffer should have at least 2 bytes for the header */
if (buf_len < 2) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
header.byte = 0;
header.bits.type = packet_type;
/* write header */
mqtt_common_packet_write_byte(&ptr, header.byte);
/* write remaining length */
ptr += mqtt_common_packet_encode(ptr, 0);
*serialized_len = ptr - buf;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* Deserializes the supplied (wire) buffer into publish data
* @param dup returned integer - the MQTT dup flag
* @param qos returned integer - the MQTT QoS value
* @param retained returned integer - the MQTT retained flag
* @param packet_id returned integer - the MQTT packet identifier
* @param topicName returned MQTTString - the MQTT topic in the publish
* @param payload returned byte buffer - the MQTT publish payload
* @param payload_len returned integer - the length of the MQTT payload
* @param buf the raw buffer data, of the correct length determined by the remaining length field
* @param buf_len the length in bytes of the data in the supplied buffer
* @return error code. 1 is success
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_deserialize_publish_packet(uint8_t *dup, int *qos,
uint8_t *retained, uint16_t *packet_id,
char **topic, uint16_t *topic_len,
uint8_t **payload, size_t *payload_len,
uint8_t *buf, size_t buf_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(dup, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(qos, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(retained, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(packet_id, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
uint32_t decoded_len = 0, read_bytes_len = 0;
mqtt_header_t header = {0};
uint8_t *curdata = buf, *enddata = NULL;
/* Publish header size is at least four bytes.
* Fixed header is two bytes.
* Variable header size depends on QoS And Topic Name.
* QoS level 0 doesn't have a message identifier (0 - 2 bytes)
* Topic Name length fields decide size of topic name field (at least 2 bytes)
* MQTT v3.1.1 Specification 3.3.1 */
if (buf_len < 4) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
header.byte = mqtt_common_packet_read_byte(&curdata);
if (header.bits.type != MQTT_PACKET_TYPE_PUBLISH) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
*dup = header.bits.dup;
*qos = header.bits.qos;
*retained = header.bits.retain;
/* read remaining length */
rc = mqtt_common_packet_decode_from_buf(curdata, &decoded_len, &read_bytes_len); /* read remaining length */
if (QCLOUD_ERR_SUCCESS != rc) {
QCLOUD_FUNC_EXIT_RC(rc);
}
curdata += read_bytes_len;
enddata = curdata + decoded_len;
/* do we have enough data to read the protocol version byte? */
if (mqtt_common_packet_read_string(topic, topic_len, &curdata, enddata) != QCLOUD_ERR_SUCCESS ||
enddata - curdata < 0) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
if (*qos > MQTT_QOS0) {
*packet_id = mqtt_common_packet_read_dbyte(&curdata);
}
*payload_len = enddata - curdata;
*payload = curdata;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* Serializes a puback packet into the supplied buffer.
* @param buf the buffer into which the packet will be serialized
* @param buflen the length in bytes of the supplied buffer
* @param packetid integer - the MQTT packet identifier
* @return serialized length, or error if 0
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_serialize_puback_packet(uint8_t *buf,
size_t buf_len,
uint16_t packet_id,
uint32_t *serialized_len)
{
return mqtt_common_serialize_ack_packet(buf, buf_len, MQTT_PACKET_TYPE_PUBACK, 0, packet_id, serialized_len);
}
/**
* Serializes a pubrel packet into the supplied buffer.
* @param buf the buffer into which the packet will be serialized
* @param buflen the length in bytes of the supplied buffer
* @param dup integer - the MQTT dup flag
* @param packetid integer - the MQTT packet identifier
* @return serialized length, or error if 0
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_serialize_pubrel_packet(uint8_t *buf,
size_t buf_len,
uint8_t dup,
uint16_t packet_id,
uint32_t *serialized_len)
{
return mqtt_common_serialize_ack_packet(buf, buf_len, MQTT_PACKET_TYPE_PUBREL, dup, packet_id, serialized_len);
}
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_serialize_pubrec_packet(uint8_t *buf,
size_t buf_len,
uint16_t packet_id,
uint32_t *serialized_len)
{
return mqtt_common_serialize_ack_packet(buf, buf_len, MQTT_PACKET_TYPE_PUBREC, 0, packet_id, serialized_len);
}
/**
* Serializes the supplied publish data into the supplied buffer, ready for sending
* @param buf the buffer into which the packet will be serialized
* @param buf_len the length in bytes of the supplied buffer
* @param dup integer - the MQTT dup flag
* @param qos integer - the MQTT QoS value
* @param retained integer - the MQTT retained flag
* @param packet_id integer - the MQTT packet identifier
* @param topicName MQTTString - the MQTT topic in the publish
* @param payload byte buffer - the MQTT publish payload
* @param payload_len integer - the length of the MQTT payload
* @return the length of the serialized data. <= 0 indicates error
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_serialize_publish_packet(uint8_t *buf,
size_t buf_len,
uint8_t dup,
int qos,
uint8_t retained,
uint16_t packet_id,
char *topic,
uint8_t *payload,
size_t payload_len,
uint32_t *serialized_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(serialized_len, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(payload, QCLOUD_ERR_INVAL);
uint8_t *ptr = buf;
mqtt_header_t header = {0};
int rem_len = 0;
rem_len = mqtt_common_serialize_publish_packet_length(qos, topic, payload_len);
if (mqtt_common_packet_length_get(rem_len) > buf_len) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
header.bits.type = MQTT_PACKET_TYPE_PUBLISH;
header.bits.dup = dup;
header.bits.qos = qos;
header.bits.retain = retained;
mqtt_common_packet_write_byte(&ptr, header.byte); /* write header */
ptr += mqtt_common_packet_encode(ptr, rem_len); /* write remaining length */;
mqtt_common_packet_write_string(&ptr, topic); /* Variable Header: Topic Name */
if (qos > MQTT_QOS0) {
mqtt_common_packet_write_dbyte(&ptr, packet_id); /* Variable Header: Topic Name */
}
memcpy(ptr, payload, payload_len);
ptr += payload_len;
*serialized_len = ptr - buf;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* Serializes the supplied subscribe data into the supplied buffer, ready for sending
* @param buf the buffer into which the packet will be serialized
* @param buf_len the length in bytes of the supplied bufferr
* @param dup integer - the MQTT dup flag
* @param packet_id integer - the MQTT packet identifier
* @param count - number of members in the topicFilters and reqQos arrays
* @param topicFilters - array of topic filter names
* @param requestedQoSs - array of requested QoS
* @return the length of the serialized data. <= 0 indicates error
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_serialize_subscribe_packet(uint8_t *buf,
size_t buf_len,
uint8_t dup,
uint16_t packet_id,
uint32_t count,
char *topic_filters[],
int requested_qoss[],
uint32_t *serialized_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(serialized_len, QCLOUD_ERR_INVAL);
int i = 0;
uint8_t *ptr = buf;
mqtt_header_t header = {0};
uint32_t rem_len = 0;
// SUBSCRIBE报文的剩余长度 = 报文标识符(2 byte) + count * (长度字段(2 byte) + topicLen + qos(1 byte))
rem_len = mqtt_common_serialize_subscribe_packet_length(count, topic_filters);
if (mqtt_common_packet_length_get(rem_len) > buf_len) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
// 初始化报文头部
header.byte = 0;
header.bits.type = MQTT_PACKET_TYPE_SUBSCRIBE;
header.bits.dup = dup;
header.bits.qos = MQTT_QOS1;
// 写报文固定头部第一个字节
mqtt_common_packet_write_byte(&ptr, header.byte);
// 写报文固定头部剩余长度字段
ptr += mqtt_common_packet_encode(ptr, rem_len);
// 写可变头部: 报文标识符
mqtt_common_packet_write_dbyte(&ptr, packet_id);
// 写报文的负载部分数据
for (i = 0; i < count; ++i) {
mqtt_common_packet_write_string(&ptr, topic_filters[i]);
mqtt_common_packet_write_byte(&ptr, (uint8_t)requested_qoss[i]);
}
*serialized_len = ptr - buf;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
/**
* Serializes the supplied unsubscribe data into the supplied buffer, ready for sending
* @param buf the raw buffer data, of the correct length determined by the remaining length field
* @param buf_len the length in bytes of the data in the supplied buffer
* @param dup integer - the MQTT dup flag
* @param packet_id integer - the MQTT packet identifier
* @param count - number of members in the topicFilters array
* @param topicFilters - array of topic filter names
* @param serialized_len - the length of the serialized data
* @return int indicating function execution status
*/
__QCLOUD_INTERNAL__ qcloud_err_t mqtt_common_serialize_unsubscribe_packet(uint8_t *buf, size_t buf_len,
uint8_t dup, uint16_t packet_id,
uint32_t count, char *topic_filters[],
uint32_t *serialized_len)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(serialized_len, QCLOUD_ERR_INVAL);
int i = 0;
uint8_t *ptr = buf;
mqtt_header_t header = {0};
uint32_t rem_len = 0;
rem_len = mqtt_common_serialize_unsubscribe_packet_length(count, topic_filters);
if (mqtt_common_packet_length_get(rem_len) > buf_len) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_BUF_TOO_SHORT);
}
header.byte = 0;
header.bits.type = MQTT_PACKET_TYPE_UNSUBSCRIBE;
header.bits.dup = dup;
header.bits.qos = MQTT_QOS1;
mqtt_common_packet_write_byte(&ptr, header.byte); /* write header */
ptr += mqtt_common_packet_encode(ptr, rem_len); /* write remaining length */
mqtt_common_packet_write_dbyte(&ptr, packet_id);
for (i = 0; i < count; ++i) {
mqtt_common_packet_write_string(&ptr, topic_filters[i]);
}
*serialized_len = ptr - buf;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
|
umaru724/TencentOS_E53_IA1
|
components/fs/vfs/include/tos_vfs_device.h
|
#ifndef _TOS_VFS_DEVICE_H_
#define _TOS_VFS_DEVICE_H_
#if TOS_CFG_VFS_EN > 0u
typedef struct vfs_inode_st vfs_inode_t;
typedef struct vfs_char_device_operations_st {
int (*open) (vfs_file_t *file);
int (*close) (vfs_file_t *file);
ssize_t (*read) (vfs_file_t *file, void *buf, size_t count);
ssize_t (*write) (vfs_file_t *file, const void *buf, size_t count);
vfs_off_t (*lseek) (vfs_file_t *file, vfs_off_t offset, vfs_whence_t whence);
int (*ioctl) (vfs_file_t *file, int cmd, unsigned long arg);
int (*suspend) (void);
int (*resume) (void);
} vfs_chrdev_ops_t;
typedef struct vfs_block_device_geometry_t {
int is_available;
uint32_t sector_size;
uint32_t nsectors;
} vfs_blkdev_geo_t;
typedef struct vfs_block_device_operations_st {
int (*open) (vfs_inode_t *dev);
int (*close) (vfs_inode_t *dev);
ssize_t (*read) (vfs_inode_t *dev, void *buf, size_t start_sector, unsigned int nsectors);
ssize_t (*write) (vfs_inode_t *dev, const unsigned char *buf, size_t start_sector, unsigned int nsectors);
int (*geometry) (vfs_inode_t *dev, vfs_blkdev_geo_t *geo);
int (*erase) (vfs_inode_t *dev, size_t start_sector, size_t nsectors);
int (*ioctl) (vfs_inode_t *dev, int cmd, unsigned long arg);
int (*suspend) (void);
int (*resume) (void);
} vfs_blkdev_ops_t;
__API__ vfs_err_t tos_vfs_block_device_register(const char *device_name, vfs_blkdev_ops_t *ops);
__API__ vfs_err_t tos_vfs_block_device_unregister(const char *device_name);
__API__ vfs_err_t tos_vfs_char_device_register(const char *device_name, vfs_chrdev_ops_t *ops);
__API__ vfs_err_t tos_vfs_char_device_unregister(const char *device_name);
#endif
#endif /* _TOS_VFS_DEVICE_H_ */
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/include/qcloud_network.h
|
#ifndef _QCLOUD_NETWORK_H_
#define _QCLOUD_NETWORK_H_
typedef struct qcloud_network_st qcloud_network_t;
typedef struct qcloud_network_st {
qcloud_err_t (*connect) (qcloud_network_t *);
qcloud_err_t (*read) (qcloud_network_t *, void *buf, size_t len, uint32_t timeout, size_t *read_len);
qcloud_err_t (*write) (qcloud_network_t *, const void *buf, size_t len, uint32_t timeout, size_t *write_len);
void (*disconnect) (qcloud_network_t *);
int (*is_connected) (qcloud_network_t *);
int fd;
#if (QCLOUD_CFG_TLS_EN > 0u)
qcloud_tls_opt_t tls_opt;
#endif
char host[QCLOUD_SERVER_DOMAIN_MAX]; // 服务器地址
int port; // 服务器端口
} qcloud_network_t;
__QCLOUD_API__ qcloud_err_t qcloud_network_tcp_init(qcloud_network_t *network);
__QCLOUD_API__ qcloud_err_t qcloud_network_udp_init(qcloud_network_t *network);
__QCLOUD_INTERNAL__ qcloud_err_t qcloud_network_tls_init(qcloud_network_t *network);
__QCLOUD_INTERNAL__ qcloud_err_t qcloud_network_dtls_init(qcloud_network_t *network);
#endif
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/src/coap/qcloud_coap_deserialize.c
|
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud.h"
#define COAP_SWAP_UINT16(n) ((((uint16_t)(n) & 0xff00) >> 8) | (((uint16_t)(n) & 0x00ff) << 8))
/**
* @brief Check a message for correctness
*
* The following checks from RFC7252 are performed:
*
* An Empty message has the Code field set to 0.00. The Token Length
* field MUST be set to 0 and bytes of data MUST NOT be present after
* the Message ID field. If there are any bytes, they MUST be processed
* as a message format error.
*
* The Reset message MUST echo the Message ID of the Confirmable message
* and MUST be Empty.
*
* A Non-confirmable message always carries either a request or response
* and MUST NOT be Empty.
*
* @param[in] msg Pointer to a message structure
* @returns Operation status
* @retval 0 Success
* @retval <0 Error
*/
__QCLOUD_STATIC__ qcloud_err_t coap_message_verify(coap_message_t *message)
{
QCLOUD_FUNC_ENTRY
if (COAP_MSG_IS_EMPTY(message)) {
/* empty message */
if (message->type == COAP_MSG_TYPE_NON ||
message->token_len != 0 ||
!qcloud_list_empty(&message->option_list) ||
message->payload_len != 0) {
QCLOUD_LOG_E("message option not empty");
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
}
/* non-empty message */
if (message->type == COAP_MSG_TYPE_RST) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS)
}
/**
* @brief Allocate an option structure and add it to the end of an option linked-list structure
*
* @param[in,out] list Pointer to an option linked-list structure
* @param[in] num Option number
* @param[in] len Option length
* @param[in] val Pointer to a buffer containing the option value
*
* @returns Operation status
* @retval 0 Success
* @retval <0 Error
*/
__QCLOUD_STATIC__ qcloud_err_t coap_message_option_list_add(coap_message_t *message, uint16_t option_code, uint32_t len, const char *val)
{
QCLOUD_FUNC_ENTRY
coap_msg_option_t *option = NULL;
option = coap_message_option_construct(option_code, len, val);
if (!option) {
QCLOUD_LOG_E("allocate new option failed.");
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE)
}
qcloud_list_add_tail(&option->list, &message->option_list);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS)
}
/**
* @brief Parse the header in a message
*
* @param[out] msg Pointer to a message structure
* @param[in] buf Pointer to a buffer containing the message
* @param[in] len Length of the buffer
*
* @returns Number of bytes parsed or error code
* @retval >0 Number of bytes parsed
* @retval <0 Error
*/
__QCLOUD_STATIC__ int coap_message_deserialize_header(coap_message_t *message, char *buf, size_t len)
{
QCLOUD_FUNC_ENTRY
char *p = buf;
if (len < 4) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE);
}
message->version = (p[0] >> 6) & 0x03;
if (message->version != COAP_VERSION) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_INVAL);
}
message->type = (p[0] >> 4) & 0x03;
message->token_len = p[0] & 0x0f;
if (message->token_len > sizeof(message->token)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
message->code_detail = p[1] & 0x1f;
message->code_class = (p[1] >> 5) & 0x07;
if (message->code_class != COAP_CODE_CLASS_REQ &&
message->code_class != COAP_CODE_CLASS_SUCCESS &&
message->code_class != COAP_CODE_CLASS_CLIENT_ERR &&
message->code_class != COAP_CODE_CLASS_SERVER_ERR) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_BADMSG)
}
message->id = COAP_SWAP_UINT16(*((uint16_t *)(&p[2])));
p += 4;
len -= 4;
QCLOUD_FUNC_EXIT_RC(p - buf)
}
/**
* @brief Parse the token in a message
*
* @param[out] msg Pointer to a message structure
* @param[in] buf Pointer to a buffer containing the message
* @param[in] len Length of the buffer
*
* @returns Number of bytes parsed or error code
* @retval >0 Number of bytes parsed
* @retval <0 Error
*/
__QCLOUD_STATIC__ int coap_message_deserialize_token(coap_message_t *message, char *buf, size_t len)
{
QCLOUD_FUNC_ENTRY
if (len < message->token_len) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
memcpy(message->token, buf, message->token_len);
QCLOUD_FUNC_EXIT_RC(message->token_len)
}
/**
* @brief Parse an option in a message
*
* @param[in,out] msg Pointer to a message structure
* @param[in] buf Pointer to a buffer containing the message
* @param[in] len Length of the buffer
*
* @returns Number of bytes parsed or error code
* @retval >0 Number of bytes parsed
* @retval <0 Error
*/
__QCLOUD_STATIC__ int coap_message_deserialize_option(coap_message_t *message, char *buf, size_t len)
{
QCLOUD_FUNC_ENTRY
char *p = buf;
qcloud_err_t rc;
uint16_t option_code_delta = 0, option_len = 0, option_code = 0;
if (len < 1) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
option_code_delta = (p[0] >> 4) & 0x0f;
option_len = p[0] & 0x0f;
if ((option_code_delta == 15) || (option_len == 15)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
p++;
len--;
if (option_code_delta == 13) {
if (len < 1) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
option_code_delta += p[0];
p++;
len--;
} else if (option_code_delta == 14) {
if (len < 2) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
option_code_delta = 269 + COAP_SWAP_UINT16(*((uint16_t *)(&p[0])));
p += 2;
len -= 2;
}
if (option_len == 13) {
if (len < 1) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
option_len += p[0];
p++;
len--;
} else if (option_len == 14) {
if (len < 2) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
option_len = 269 + COAP_SWAP_UINT16(*((uint16_t *)(&p[0])));
p += 2;
len -= 2;
}
if (len < option_len) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
option_code += option_code_delta;
rc = coap_message_option_list_add(message, option_code, option_len, p);
QCLOUD_FUNC_EXIT_RC_IF_NOT(rc, QCLOUD_ERR_SUCCESS, -1);
p += option_len;
QCLOUD_FUNC_EXIT_RC(p - buf)
}
/**
* @brief Parse the options in a message
*
* @param[in,out] msg Pointer to a message structure
* @param[in] buf Pointer to a buffer containing the message
* @param[in] len Length of the buffer
*
* @returns Number of bytes parsed or error code
* @retval >0 Number of bytes parsed
* @retval <0 Error
*/
__QCLOUD_STATIC__ int coap_message_deserialize_options(coap_message_t *message, char *buf, size_t buf_len)
{
QCLOUD_FUNC_ENTRY
int len = 0;
char *p = buf;
while ((p[0] & 0xff) != 0xff && buf_len != 0) {
len = coap_message_deserialize_option(message, p, buf_len);
if (len < 0) {
return len;
}
p += len;
buf_len -= len;
}
QCLOUD_FUNC_EXIT_RC(p - buf)
}
/**
* @brief Parse the payload in a message
*
* @param[out] msg Pointer to a message structure
* @param[in] buf Pointer to a buffer containing the message
* @param[in] len Length of the buffer
*
* @returns Number of bytes parsed or error code
* @retval >0 Number of bytes parsed
* @retval <0 Error
*/
__QCLOUD_STATIC__ int coap_message_deserialize_payload(coap_message_t *message, char *buf, size_t len)
{
QCLOUD_FUNC_ENTRY
char *p = buf;
if (len == 0) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS)
}
if ((p[0] & 0xff) != 0xff) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
p++;
len--;
if (len == 0) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_DATA_SIZE)
}
message->payload = (char *)osal_malloc(len);
if (!message->payload){
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_INVAL)
}
memcpy(message->payload, p, len);
message->payload_len = len;
p += len;
QCLOUD_FUNC_EXIT_RC(p - buf)
}
__QCLOUD_INTERNAL__ qcloud_err_t coap_message_deserialize(coap_message_t *message, char *buf, size_t buf_len)
{
QCLOUD_FUNC_ENTRY
int len = 0;
char *p = buf;
len = coap_message_deserialize_header(message, p, buf_len);
if (len < 0) {
QCLOUD_LOG_E("coap_message_deserialize_header failed, num:%lu", len);
goto errout;
}
p += len;
buf_len -= len;
len = coap_message_deserialize_token(message, p, buf_len);
if (len < 0) {
QCLOUD_LOG_E("coap_message_deserialize_token failed, num:%lu", len);
goto errout;
}
p += len;
buf_len -= len;
len = coap_message_deserialize_options(message, p, buf_len);
if (len < 0) {
QCLOUD_LOG_E("coap_message_deserialize_options failed, num:%lu", len);
goto errout;
}
p += len;
buf_len -= len;
len = coap_message_deserialize_payload(message, p, buf_len);
if (len < 0) {
QCLOUD_LOG_E("coap_message_deserialize_payload failed, num:%lu", len);
goto errout;
}
QCLOUD_FUNC_EXIT_RC(coap_message_verify(message))
errout:
coap_message_destroy(message);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_COAP_INTERNAL)
}
#ifdef __cplusplus
}
#endif
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/external/cifra_AES128-EAX/cifra_cmac.c
|
<reponame>umaru724/TencentOS_E53_IA1<filename>platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/external/cifra_AES128-EAX/cifra_cmac.c
/*
* cifra - embedded cryptography library
* Written in 2014 by <NAME> <<EMAIL>>
*
* To the extent possible under law, the author(s) have dedicated all
* copyright and related and neighboring rights to this software to the
* public domain worldwide. This software is distributed without any
* warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication
* along with this software. If not, see
* <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
#include "handy.h"
#include "prp.h"
#include "modes.h"
#include "bitops.h"
#include "blockwise.h"
#include "gf128.h"
#include "tassert.h"
#include <string.h>
void cf_cmac_init(cf_cmac *ctx, const cf_prp *prp, void *prpctx)
{
uint8_t L[CF_MAXBLOCK];
assert(prp->blocksz == 16);
mem_clean(ctx, sizeof *ctx);
/* L = E_K(0^n) */
mem_clean(L, prp->blocksz);
prp->encrypt(prpctx, L, L);
/* B = 2L */
cf_gf128 gf;
cf_gf128_frombytes_be(L, gf);
cf_gf128_double(gf, gf);
cf_gf128_tobytes_be(gf, ctx->B);
/* P = 4L */
cf_gf128_double(gf, gf);
cf_gf128_tobytes_be(gf, ctx->P);
ctx->prp = prp;
ctx->prpctx = prpctx;
}
void cf_cmac_sign(cf_cmac *ctx, const uint8_t *data, size_t len, uint8_t out[CF_MAXBLOCK])
{
cf_cmac_stream stream;
stream.cmac = *ctx;
cf_cmac_stream_reset(&stream);
cf_cmac_stream_update(&stream, data, len, 1);
cf_cmac_stream_final(&stream, out);
}
void cf_cmac_stream_init(cf_cmac_stream *ctx, const cf_prp *prp, void *prpctx)
{
cf_cmac_init(&ctx->cmac, prp, prpctx);
cf_cmac_stream_reset(ctx);
}
void cf_cmac_stream_reset(cf_cmac_stream *ctx)
{
uint8_t iv_zero[CF_MAXBLOCK] = { 0 };
cf_cbc_init(&ctx->cbc, ctx->cmac.prp, ctx->cmac.prpctx, iv_zero);
mem_clean(ctx->buffer, sizeof ctx->buffer);
ctx->used = 0;
ctx->processed = 0;
ctx->finalised = 0;
}
static void cmac_process(void *vctx, const uint8_t *block)
{
cf_cmac_stream *ctx = vctx;
uint8_t output[CF_MAXBLOCK];
cf_cbc_encrypt(&ctx->cbc, block, output, 1);
ctx->processed += ctx->cmac.prp->blocksz;
}
static void cmac_process_final(cf_cmac_stream *ctx, const uint8_t *block,
const uint8_t *xor)
{
uint8_t input[CF_MAXBLOCK];
uint8_t output[CF_MAXBLOCK];
xor_bb(input, block, xor, ctx->cmac.prp->blocksz);
cf_cbc_encrypt(&ctx->cbc, input, output, 1);
ctx->processed += ctx->cmac.prp->blocksz;
/* signature is in ctx->cbc.block. */
}
static void cmac_process_final_nopad(void *vctx, const uint8_t *block)
{
cf_cmac_stream *ctx = vctx;
cmac_process_final(ctx, block, ctx->cmac.B);
ctx->finalised = 1;
}
static void cmac_process_final_pad(void *vctx, const uint8_t *block)
{
cf_cmac_stream *ctx = vctx;
cmac_process_final(ctx, block, ctx->cmac.P);
ctx->finalised = 1;
}
void cf_cmac_stream_update(cf_cmac_stream *ctx, const uint8_t *data, size_t len, int isfinal)
{
size_t blocksz = ctx->cmac.prp->blocksz;
cf_blockwise_in_fn final_fn = cmac_process;
int needpad = 0;
if (isfinal)
{
int whole_number_of_blocks = ((len + ctx->used) & 0xf) == 0;
int empty_message = len == 0 && ctx->used == 0 && ctx->processed == 0;
assert(!ctx->finalised); /* finalised before? */
assert(len != 0 || empty_message); /* we can't be told we're done after the fact. */
/* If we have a whole number of blocks, and at least 1 block, we XOR in B.
* Otherwise, we need to pad and XOR in P. */
if (whole_number_of_blocks && !empty_message)
final_fn = cmac_process_final_nopad;
else
needpad = 1;
}
/* Input data */
cf_blockwise_accumulate_final(ctx->buffer, &ctx->used, blocksz,
data, len,
cmac_process,
final_fn, ctx);
/* Input padding */
if (needpad)
{
cf_blockwise_acc_pad(ctx->buffer, &ctx->used, blocksz,
0x80, 0x00, 0x00, blocksz - ctx->used,
cmac_process_final_pad, ctx);
}
}
void cf_cmac_stream_final(cf_cmac_stream *ctx, uint8_t out[CF_MAXBLOCK])
{
assert(ctx->finalised);
memcpy(out, ctx->cbc.block, ctx->cmac.prp->blocksz);
}
|
umaru724/TencentOS_E53_IA1
|
net/sal_module_wrapper/sal_module_wrapper.c
|
#include "sal_module_wrapper.h"
static sal_module_t *g_sal_module = NULL;
int tos_sal_module_register(sal_module_t *module)
{
if (!g_sal_module) {
g_sal_module = module;
return 0;
}
return -1;
}
int tos_sal_module_init(void)
{
if (g_sal_module && g_sal_module->init) {
return g_sal_module->init();
}
return -1;
}
int tos_sal_module_parse_domain(const char *host_name, char *host_ip, size_t host_ip_len)
{
if (g_sal_module && g_sal_module->parse_domain) {
return g_sal_module->parse_domain(host_name, host_ip, host_ip_len);
}
return -1;
}
int tos_sal_module_connect(const char *ip, const char *port, sal_proto_t proto)
{
if (g_sal_module && g_sal_module->connect) {
return g_sal_module->connect(ip, port, proto);
}
return -1;
}
int tos_sal_module_send(int sock, const void *buf, size_t len)
{
if (g_sal_module && g_sal_module->send) {
return g_sal_module->send(sock, buf, len);
}
return -1;
}
int tos_sal_module_recv(int sock, void *buf, size_t len)
{
if (g_sal_module && g_sal_module->recv) {
return g_sal_module->recv(sock, buf, len);
}
return -1;
}
int tos_sal_module_recv_timeout(int sock, void *buf, size_t len, uint32_t timeout)
{
if (g_sal_module && g_sal_module->recv_timeout) {
return g_sal_module->recv_timeout(sock, buf, len, timeout);
}
return -1;
}
int tos_sal_module_sendto(int sock, char *ip, char *port, const void *buf, size_t len)
{
if (g_sal_module && g_sal_module->sendto) {
return g_sal_module->sendto(sock, ip, port, buf, len);
}
return -1;
}
int tos_sal_module_recvfrom(int sock, void *buf, size_t len)
{
if (g_sal_module && g_sal_module->recvfrom) {
return g_sal_module->recvfrom(sock, buf, len);
}
return -1;
}
int tos_sal_module_recvfrom_timeout(int sock, void *buf, size_t len, uint32_t timeout)
{
if (g_sal_module && g_sal_module->recvfrom_timeout) {
return g_sal_module->recvfrom_timeout(sock, buf, len, timeout);
}
return -1;
}
int tos_sal_module_close(int sock)
{
if (g_sal_module && g_sal_module->close) {
return g_sal_module->close(sock);
}
return -1;
}
|
umaru724/TencentOS_E53_IA1
|
kernel/core/tos_priority_mail_queue.c
|
/*----------------------------------------------------------------------------
* Tencent is pleased to support the open source community by making TencentOS
* available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* If you have downloaded a copy of the TencentOS binary from Tencent, please
* note that the TencentOS binary is licensed under the BSD 3-Clause License.
*
* If you have downloaded a copy of the TencentOS source code from Tencent,
* please note that TencentOS source code is licensed under the BSD 3-Clause
* License, except for the third-party components listed below which are
* subject to different license terms. Your integration of TencentOS into your
* own projects may require compliance with the BSD 3-Clause License, as well
* as the other licenses applicable to the third-party components included
* within TencentOS.
*---------------------------------------------------------------------------*/
#include "tos_k.h"
#if TOS_CFG_PRIORITY_MAIL_QUEUE_EN > 0u
__API__ k_err_t tos_prio_mail_q_create(k_prio_mail_q_t *prio_mail_q, void *pool, size_t mail_cnt, size_t mail_size)
{
k_err_t err;
void *prio_q_mgr_array = K_NULL;
TOS_PTR_SANITY_CHECK(prio_mail_q);
prio_q_mgr_array = tos_mmheap_alloc(TOS_PRIO_Q_MGR_ARRAY_SIZE(mail_cnt));
if (!prio_q_mgr_array) {
return K_ERR_OUT_OF_MEMORY;
}
err = tos_prio_q_create(&prio_mail_q->prio_q, prio_q_mgr_array, pool, mail_cnt, mail_size);
if (err != K_ERR_NONE) {
tos_mmheap_free(prio_q_mgr_array);
return err;
}
prio_mail_q->prio_q_mgr_array = prio_q_mgr_array;
pend_object_init(&prio_mail_q->pend_obj);
TOS_OBJ_INIT(prio_mail_q, KNL_OBJ_TYPE_PRIORITY_MAIL_QUEUE);
knl_object_alloc_set_static(&prio_mail_q->knl_obj);
return K_ERR_NONE;
}
__API__ k_err_t tos_prio_mail_q_destroy(k_prio_mail_q_t *prio_mail_q)
{
TOS_CPU_CPSR_ALLOC();
k_err_t err;
TOS_PTR_SANITY_CHECK(prio_mail_q);
TOS_OBJ_VERIFY(prio_mail_q, KNL_OBJ_TYPE_PRIORITY_MAIL_QUEUE);
if (!knl_object_alloc_is_static(&prio_mail_q->knl_obj)) {
return K_ERR_OBJ_INVALID_ALLOC_TYPE;
}
TOS_CPU_INT_DISABLE();
err = tos_prio_q_destroy(&prio_mail_q->prio_q);
if (err != K_ERR_NONE) {
TOS_CPU_INT_ENABLE();
return err;
}
if (!pend_is_nopending(&prio_mail_q->pend_obj)) {
pend_wakeup_all(&prio_mail_q->pend_obj, PEND_STATE_DESTROY);
}
tos_mmheap_free(prio_mail_q->prio_q_mgr_array);
prio_mail_q->prio_q_mgr_array = K_NULL;
pend_object_deinit(&prio_mail_q->pend_obj);
TOS_OBJ_DEINIT(prio_mail_q);
knl_object_alloc_reset(&prio_mail_q->knl_obj);
TOS_CPU_INT_ENABLE();
knl_sched();
return K_ERR_NONE;
}
__API__ k_err_t tos_prio_mail_q_create_dyn(k_prio_mail_q_t *prio_mail_q, size_t mail_cnt, size_t mail_size)
{
k_err_t err;
TOS_PTR_SANITY_CHECK(prio_mail_q);
err = tos_prio_q_create_dyn(&prio_mail_q->prio_q, mail_cnt, mail_size);
if (err != K_ERR_NONE) {
return err;
}
pend_object_init(&prio_mail_q->pend_obj);
TOS_OBJ_INIT(prio_mail_q, KNL_OBJ_TYPE_PRIORITY_MAIL_QUEUE);
knl_object_alloc_set_dynamic(&prio_mail_q->knl_obj);
return K_ERR_NONE;
}
__API__ k_err_t tos_prio_mail_q_destroy_dyn(k_prio_mail_q_t *prio_mail_q)
{
TOS_CPU_CPSR_ALLOC();
k_err_t err;
TOS_PTR_SANITY_CHECK(prio_mail_q);
TOS_OBJ_VERIFY(prio_mail_q, KNL_OBJ_TYPE_PRIORITY_MAIL_QUEUE);
if (!knl_object_alloc_is_dynamic(&prio_mail_q->knl_obj)) {
return K_ERR_OBJ_INVALID_ALLOC_TYPE;
}
TOS_CPU_INT_DISABLE();
err = tos_prio_q_destroy_dyn(&prio_mail_q->prio_q);
if (err != K_ERR_NONE) {
TOS_CPU_INT_ENABLE();
return err;
}
if (!pend_is_nopending(&prio_mail_q->pend_obj)) {
pend_wakeup_all(&prio_mail_q->pend_obj, PEND_STATE_DESTROY);
}
pend_object_deinit(&prio_mail_q->pend_obj);
TOS_OBJ_DEINIT(prio_mail_q);
knl_object_alloc_reset(&prio_mail_q->knl_obj);
TOS_CPU_INT_ENABLE();
knl_sched();
return K_ERR_NONE;
}
__API__ k_err_t tos_prio_mail_q_flush(k_prio_mail_q_t *prio_mail_q)
{
TOS_PTR_SANITY_CHECK(prio_mail_q);
TOS_OBJ_VERIFY(prio_mail_q, KNL_OBJ_TYPE_PRIORITY_MAIL_QUEUE);
return tos_prio_q_flush(&prio_mail_q->prio_q);
}
__API__ k_err_t tos_prio_mail_q_pend(k_prio_mail_q_t *prio_mail_q, void *mail_buf, size_t *mail_size, k_tick_t timeout)
{
TOS_CPU_CPSR_ALLOC();
k_err_t err;
TOS_PTR_SANITY_CHECK(prio_mail_q);
TOS_PTR_SANITY_CHECK(mail_buf);
TOS_OBJ_VERIFY(prio_mail_q, KNL_OBJ_TYPE_PRIORITY_MAIL_QUEUE);
TOS_CPU_INT_DISABLE();
if (tos_prio_q_dequeue(&prio_mail_q->prio_q, mail_buf, mail_size, K_NULL) == K_ERR_NONE) {
TOS_CPU_INT_ENABLE();
return K_ERR_NONE;
}
if (timeout == TOS_TIME_NOWAIT) {
*mail_size = 0;
TOS_CPU_INT_ENABLE();
return K_ERR_PEND_NOWAIT;
}
if (knl_is_sched_locked()) {
TOS_CPU_INT_ENABLE();
return K_ERR_PEND_SCHED_LOCKED;
}
k_curr_task->mail = mail_buf;
pend_task_block(k_curr_task, &prio_mail_q->pend_obj, timeout);
TOS_CPU_INT_ENABLE();
knl_sched();
err = pend_state2errno(k_curr_task->pend_state);
if (err == K_ERR_NONE) {
*mail_size = k_curr_task->mail_size;
k_curr_task->mail = K_NULL;
k_curr_task->mail_size = 0;
}
return err;
}
__STATIC__ void prio_mail_task_recv(k_task_t *task, void *mail_buf, size_t mail_size)
{
memcpy(task->mail, mail_buf, mail_size);
task->mail_size = mail_size;
pend_task_wakeup(task, PEND_STATE_POST);
}
__STATIC__ k_err_t prio_mail_q_do_post(k_prio_mail_q_t *prio_mail_q, void *mail_buf, size_t mail_size, k_prio_t prio, opt_post_t opt)
{
TOS_CPU_CPSR_ALLOC();
k_err_t err;
k_task_t *task, *tmp;
TOS_PTR_SANITY_CHECK(prio_mail_q);
TOS_PTR_SANITY_CHECK(mail_buf);
TOS_OBJ_VERIFY(prio_mail_q, KNL_OBJ_TYPE_PRIORITY_MAIL_QUEUE);
TOS_CPU_INT_DISABLE();
if (pend_is_nopending(&prio_mail_q->pend_obj)) {
err = tos_prio_q_enqueue(&prio_mail_q->prio_q, mail_buf, mail_size, prio);
if (err != K_ERR_NONE) {
TOS_CPU_INT_ENABLE();
return err;
}
TOS_CPU_INT_ENABLE();
return K_ERR_NONE;
}
if (opt == OPT_POST_ONE) {
prio_mail_task_recv(TOS_LIST_FIRST_ENTRY(&prio_mail_q->pend_obj.list, k_task_t, pend_list),
mail_buf, mail_size);
} else { // OPT_POST_ALL
TOS_LIST_FOR_EACH_ENTRY_SAFE(task, tmp, k_task_t, pend_list, &prio_mail_q->pend_obj.list) {
prio_mail_task_recv(task, mail_buf, mail_size);
}
}
TOS_CPU_INT_ENABLE();
knl_sched();
return K_ERR_NONE;
}
__API__ k_err_t tos_prio_mail_q_post(k_prio_mail_q_t *prio_mail_q, void *mail_buf, size_t mail_size, k_prio_t prio)
{
return prio_mail_q_do_post(prio_mail_q, mail_buf, mail_size, prio, OPT_POST_ONE);
}
__API__ k_err_t tos_prio_mail_q_post_all(k_prio_mail_q_t *prio_mail_q, void *mail_buf, size_t mail_size, k_prio_t prio)
{
return prio_mail_q_do_post(prio_mail_q, mail_buf, mail_size, prio, OPT_POST_ALL);
}
#endif
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/LoraWAN/boards_common/display-board.h
|
/*!
* \file display-board.h
*
* \brief Target board OLED low level driver implementation
*
* \remarks Some snippets of these drivers are based on the Adafruit_GFX library.
* https://github.com/adafruit/Adafruit-GFX-Library
* Please take a look at their LICENSE.TXT file.
* Copyright (c) 2012 Adafruit Industries. All rights reserved.
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* \endcode
*
* \author <NAME> ( Semtech )
*
* \author <NAME> ( Semtech )
*/
#ifndef __DISPLAY_BOARD_H__
#define __DISPLAY_BOARD_H__
#include <stdint.h>
#include <stdbool.h>
/*!
* \brief Display colors enumeration
*/
typedef enum
{
DISPLAY_BLACK,
DISPLAY_WHITE,
DISPLAY_INVERSE,
}DisplayColor_t;
/*!
* \brief Initializes the display
*/
void DisplayInit( void );
/*!
* \brief Resets the display
*/
void DisplayReset( void );
/*!
* \brief Sends a command to the display
*
* \param cmd Command to be sent
*/
void DisplaySendCommand( uint8_t cmd );
/*!
* \brief Sends a data buffer to the display
*
* \param buffer Buffer to be sent
* \param size Buffer size to be sent
*/
void DisplaySendData( uint8_t *buffer, uint16_t size );
/*!
* \brief Enables the display
*/
void DisplayOn( void );
/*!
* \brief Disables the display
*/
void DisplayOff( void );
/*!
* \brief Clears the display
*/
void DisplayClear( void );
/*!
* \brief Inverts colors of the display
*
* \param invert [true: invert, false: normal]
*/
void DisplayInvertColors( bool invert );
/*!
* \brief Updates the display with MCU RAM copy
*/
void DisplayUpdate( void );
/*!
* \brief Sets the cursor at coordinates (x,y)
*
* \param x X coordinate
* \param y Y coordinate
*/
void DisplaySetCursor( int16_t x, int16_t y );
/*!
* \brief Gets current X coordinate of the cursor
*
* \retval x X coordinate
*/
int16_t DisplayGetCursorX( void );
/*!
* \brief Gets current Y coordinate of the cursor
*
* \retval y Y coordinate
*/
int16_t DisplayGetCursorY( void );
/*!
* \brief Sets text size
*
* \param s New text size
*/
void DisplaySetTextSize( uint8_t s );
/*!
* \brief Sets text color
*
* \param color New text color
*/
void DisplaySetTextColor( DisplayColor_t color );
/*!
* \brief Sets foreground and background color
*
* \param fg Foreground color
* \param bg Background color
*/
void DisplaySetFgAndBg( DisplayColor_t fg, DisplayColor_t bg );
/*!
* \brief Enables/Disable text wrapping
*
* \param w [true: wrap ON, false: wrap OFF]
*/
void DisplaySetTextWrap( bool w );
/*!
* \brief Gets current display rotation
*
* \retval rotation Display rotation (Vertical/Horizontal)
*/
uint8_t DisplayGetRotation( void );
/*!
* \brief Sets current display rotation
*
* \param x Display rotation (Vertical/Horizontal)
*/
void DisplaySetRotation( uint8_t x );
/*!
* \brief Draws a pixel of color at coordinates (x,y)
*
* \param x X coordinate
* \param y Y coordinate
* \param color Pixel color
*/
void DisplayDrawPixel( int16_t x, int16_t y, DisplayColor_t color );
/*!
* \brief Draws a line starting at coordinates (x0,y0) ending at
* coordinates (x1,y1) of color
*
* \param x0 X0 coordinate
* \param y0 Y0 coordinate
* \param x1 X1 coordinate
* \param y1 Y1 coordinate
* \param color Line color
*/
void DisplayDrawLine( int16_t x0, int16_t y0, int16_t x1, int16_t y1, DisplayColor_t color );
/*!
* \brief Draws a vertical line starting at coordinates (x,y) with given height
*
* \param x X coordinate
* \param y Y coordinate
* \param h Line height
* \param color Line color
*/
void DisplayDrawVerticalLine( int16_t x, int16_t y, int16_t h, DisplayColor_t color );
/*!
* \brief Draws an Horizontal line starting at coordinates (x,y) with given width
*
* \param x X coordinate
* \param y Y coordinate
* \param w Line width
* \param color Line color
*/
void DisplayDrawHorizontalLine( int16_t x, int16_t y, int16_t w, DisplayColor_t color );
/*!
* \brief Draws a rectangle at coordinates (x,y) with given width and height
*
* \param x X coordinate
* \param y Y coordinate
* \param w Line width
* \param h Line height
* \param color Line color
*/
void DisplayDrawRect( int16_t x, int16_t y, int16_t w, int16_t h, DisplayColor_t color );
/*!
* \brief Draws a filled rectangle at coordinates (x,y) with given width and height
*
* \param x X coordinate
* \param y Y coordinate
* \param w Line width
* \param h Line height
* \param color Fill color
*/
void DisplayFillRect( int16_t x, int16_t y, int16_t w, int16_t h, DisplayColor_t color );
/*!
* \brief Fills all display with pixels of color
*
* \param color Fill color
*/
void DisplayFillScreen( DisplayColor_t color );
/*!
* \brief Draws a triangle by giving the 3 vertices coordinates
*
* \param x0 X0 coordinate
* \param y0 Y0 coordinate
* \param x1 X1 coordinate
* \param y1 Y1 coordinate
* \param x2 X2 coordinate
* \param y2 Y2 coordinate
* \param color Line color
*/
void DisplayDrawTriangle( int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, DisplayColor_t color );
/*!
* \brief Draws a filled triangle by giving the 3 vertices coordinates
*
* \param x0 X0 coordinate
* \param y0 Y0 coordinate
* \param x1 X1 coordinate
* \param y1 Y1 coordinate
* \param x2 X2 coordinate
* \param y2 Y2 coordinate
* \param color Fill color
*/
void DisplayFillTriangle( int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, DisplayColor_t color ) ;
/*!
* \brief Draws a character at given coordinates
*
* \param x X coordinate
* \param y Y coordinate
* \param c Character
* \param color Character color
* \param bg Background color
* \param size Character size
*/
void DisplayDrawChar( int16_t x, int16_t y, unsigned char c, DisplayColor_t color, DisplayColor_t bg, uint8_t size );
/*!
* \brief Display putc function. (Mimics standard C putc function)
*
* \param c Character
*/
void DisplayPutc( uint8_t c );
/*!
* \brief Sets cursor at line
*
* \param line Line number
*/
void DisplaySetLine( uint8_t line );
/*!
* \brief Display print function. Prints the given string
*/
void DisplayPrint( const char *string );
/*!
* \brief Display printf function. (Mimics standard C printf function)
*/
void DisplayPrintf( const char *format, ... );
#endif // __DISPLAY_BOARD_H__
|
umaru724/TencentOS_E53_IA1
|
examples/qcloud_iot_explorer_sdk_data_template/data_config.c
|
/*-----------------data config start -------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
#include "qcloud_iot_export.h"
#include "qcloud_iot_import.h"
#include "lite-utils.h"
#include "utils_timer.h"
#include "E53_IA1.h"
#include "tos_k.h"
#define TOTAL_PROPERTY_COUNT 5
static sDataPoint sg_DataTemplate[TOTAL_PROPERTY_COUNT];
typedef struct _ProductDataDefine {
TYPE_DEF_TEMPLATE_BOOL m_motor_power_switch;
TYPE_DEF_TEMPLATE_BOOL m_light_power_switch;
TYPE_DEF_TEMPLATE_INT m_luminance;
TYPE_DEF_TEMPLATE_INT m_temperature;
TYPE_DEF_TEMPLATE_INT m_humidity;
} ProductDataDefine;
static ProductDataDefine sg_ProductData;
/*
static int read_brightness(void){
Init_E53_IA1();
E53_IA1_Read_Data();
return (int)E53_SC1_Data.Lux;
}*/
static void _init_data_template(void)
{
Init_E53_IA1();
E53_IA1_Read_Data();
sg_ProductData.m_motor_power_switch = 0;
sg_DataTemplate[0].data_property.data = &sg_ProductData.m_motor_power_switch;
sg_DataTemplate[0].data_property.key = "motor_power_switch";
sg_DataTemplate[0].data_property.type = TYPE_TEMPLATE_BOOL;
sg_ProductData.m_light_power_switch = 0;
sg_DataTemplate[1].data_property.data = &sg_ProductData.m_light_power_switch;
sg_DataTemplate[1].data_property.key = "light_power_switch";
sg_DataTemplate[1].data_property.type = TYPE_TEMPLATE_BOOL;
sg_ProductData.m_luminance = (int)E53_IA1_Data.Lux;
sg_DataTemplate[2].data_property.data = &sg_ProductData.m_luminance;
sg_DataTemplate[2].data_property.key = "luminance";
sg_DataTemplate[2].data_property.type = TYPE_TEMPLATE_INT;
sg_ProductData.m_temperature = (int)E53_IA1_Data.Temperature;
sg_DataTemplate[3].data_property.data = &sg_ProductData.m_temperature;
sg_DataTemplate[3].data_property.key = "temperature";
sg_DataTemplate[3].data_property.type = TYPE_TEMPLATE_INT;
sg_ProductData.m_humidity = (int)E53_IA1_Data.Humidity;
sg_DataTemplate[4].data_property.data = &sg_ProductData.m_humidity;
sg_DataTemplate[4].data_property.key = "humidity";
sg_DataTemplate[4].data_property.type = TYPE_TEMPLATE_INT;
};
/*
#define TOTAL_PROPERTY_COUNT 3
static sDataPoint sg_DataTemplate[TOTAL_PROPERTY_COUNT];
typedef struct _ProductDataDefine {
TYPE_DEF_TEMPLATE_BOOL m_beep;
TYPE_DEF_TEMPLATE_FLOAT m_longtitude;
TYPE_DEF_TEMPLATE_FLOAT m_latitude;
} ProductDataDefine;
static ProductDataDefine sg_ProductData;
//static E53_ST1_Data_TypeDef E53_ST1_Data;
static void read_location(float *longtitude, float *latitude){
Init_E53_ST1();
E53_ST1_Read_Data();
*longtitude = E53_ST1_Data.Longitude;
*latitude = E53_ST1_Data.Latitude;
}
static void _init_data_template(void)
{
sg_ProductData.m_beep = 1;
sg_DataTemplate[0].data_property.data = &sg_ProductData.m_beep;
sg_DataTemplate[0].data_property.key = "beep";
sg_DataTemplate[0].data_property.type = TYPE_TEMPLATE_BOOL;
//Init_E53_ST1();
//E53_ST1_Read_Data();
sg_ProductData.m_longtitude = E53_ST1_Data.Longitude;
sg_ProductData.m_latitude = E53_ST1_Data.Latitude;
//read_location(&sg_ProductData.m_longtitude, &sg_ProductData.m_latitude);
//sg_ProductData.m_color = 0;
sg_DataTemplate[1].data_property.data = &sg_ProductData.m_longtitude;
sg_DataTemplate[1].data_property.key = "longitude";
sg_DataTemplate[1].data_property.type = TYPE_TEMPLATE_FLOAT;
//sg_ProductData.m_brightness = 0;
sg_DataTemplate[2].data_property.data = &sg_ProductData.m_latitude;
sg_DataTemplate[2].data_property.key = "latitude";
sg_DataTemplate[2].data_property.type = TYPE_TEMPLATE_FLOAT;
};
*/
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/crypto/nrf_crypto/test_app/test_cases/test_vectors_aes_cbc_mac.c
|
<reponame>umaru724/TencentOS_E53_IA1<filename>platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/crypto/nrf_crypto/test_app/test_cases/test_vectors_aes_cbc_mac.c
/**
* Copyright (c) 2018 - 2019, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stddef.h>
#include "nrf_gpio.h"
#include "nrf_delay.h"
#include "nrf_error.h"
#include "app_util.h"
#include "nrf_section.h"
#include "nrf_crypto.h"
#include "common_test.h"
/**@brief AES CBC-MAC is tested using only custom generated test vectors.
*
*/
#if NRF_MODULE_ENABLED(NRF_CRYPTO_AES_CBC_MAC)
/*lint -save -e91 */
#if NRF_MODULE_ENABLED(NRF_CRYPTO_AES_CBC_MAC_128)
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_128_1) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_128_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_FAIL,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 128 message_len=0",
.p_plaintext = "",
.p_ciphertext = "",
.p_key = "<KEY>",
.p_iv = "00000000000000000000000000000000"
};
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_128_2) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_128_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_PASS,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 128 message_len=16",
.p_plaintext = "6bc1bee22e409f96e93d7e117393172a",
.p_ciphertext = "3ad77bb40d7a3660a89ecaf32466ef97",
.p_key = "<KEY>",
.p_iv = "00000000000000000000000000000000"
};
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_128_3) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_128_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_PASS,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 128 message_len=32",
.p_plaintext = "d602b63eebba5b8fe1db84d8ca71abf5023e147508ce206c9732a28cc94eaabc",
.p_ciphertext = "5a88111a1e75ccc0ebad8b7b74e1c6d1",
.p_key = "<KEY>",
.p_iv = "00000000000000000000000000000000"
};
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_128_4) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_128_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_PASS,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 128 message_len=64",
.p_plaintext = "<KEY>",
.p_ciphertext = "289df89c9703958b37b1b9b1f7842984",
.p_key = "<KEY>",
.p_iv = "00000000000000000000000000000000"
};
#endif // NRF_MODULE_ENABLED(NRF_CRYPTO_AES_CBC_MAC_128)
#if NRF_MODULE_ENABLED(NRF_CRYPTO_AES_CBC_MAC_192)
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_192_1) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_192_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_FAIL,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 192 message_len=0",
.p_plaintext = "",
.p_ciphertext = "",
.p_key = "<KEY>",
.p_iv = "00000000000000000000000000000000"
};
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_192_2) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_192_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_PASS,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 192 message_len=16",
.p_plaintext = "6bc1bee22e409f96e93d7e117393172a",
.p_ciphertext = "9cd89b028e16378d71ac45fdc45b7b08",
.p_key = "<KEY>",
.p_iv = "00000000000000000000000000000000"
};
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_192_3) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_192_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_PASS,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 192 message_len=32",
.p_plaintext = "d602b63eebba5b8fe1db84d8ca71abf5023e147508ce206c9732a28cc94eaabc",
.p_ciphertext = "098f08d19aef1c6bf63f38c5aa2b9b31",
.p_key = "<KEY>",
.p_iv = "00000000000000000000000000000000"
};
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_192_4) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_192_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_PASS,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 192 message_len=64",
.p_plaintext = "93cccff91971303929c53d0de3dd7a96851e54fe1b484d240cae8ff2b99051766f4d6f7b500d26e2e43295bd4c6313bca988875944215d8de20298e3bb795d9d",
.p_ciphertext = "5e0eb2751c73e2b7de96c302caed1459",
.p_key = "<KEY>",
.p_iv = "00000000000000000000000000000000"
};
#endif // NRF_MODULE_ENABLED(NRF_CRYPTO_AES_CBC_MAC_192)
#if NRF_MODULE_ENABLED(NRF_CRYPTO_AES_CBC_MAC_256)
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_256_1) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_256_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_FAIL,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 256 message_len=0",
.p_plaintext = "",
.p_ciphertext = "",
.p_key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
.p_iv = "00000000000000000000000000000000"
};
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_256_2) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_256_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_PASS,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 256 message_len=16",
.p_plaintext = "6bc1bee22e409f96e93d7e117393172a",
.p_ciphertext = "f3eed1bdb5d2a03c064b5a7e3db181f8",
.p_key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
.p_iv = "00000000000000000000000000000000"
};
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_256_3) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_256_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_PASS,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 256 message_len=32",
.p_plaintext = "d602b63eebba5b8fe1db84d8ca71abf5023e147508ce206c9732a28cc94eaabc",
.p_ciphertext = "b0d33b64ae39d12fdd26cb39657b9047",
.p_key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
.p_iv = "00000000000000000000000000000000"
};
// AES CBC MAC - Custom test vector
NRF_SECTION_ITEM_REGISTER(test_vector_aes_mac_data, test_vector_aes_t test_vector_aes_cbc_mac_256_4) =
{
.p_aes_info = &g_nrf_crypto_aes_cbc_mac_256_info,
.expected_err_code = NRF_SUCCESS,
.expected_result = EXPECTED_TO_PASS,
.direction = NRF_CRYPTO_ENCRYPT,
.p_test_vector_name = "CBC MAC 256 message_len=64",
.p_plaintext = "<KEY>",
.p_ciphertext = "8dbe503b77ebed416cd0ad049314aaa4",
.p_key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
.p_iv = "00000000000000000000000000000000"
};
#endif // NRF_MODULE_ENABLED(NRF_CRYPTO_AES_CBC_MAC_256)
/*lint -restore */
#endif // NRF_MODULE_ENABLED(NRF_CRYPTO_AES_CBC_MAC)
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/src/coap/qcloud_coap_auth.c
|
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud.h"
__QCLOUD_STATIC__ void coap_auth_callback(void *message, void *context)
{
QCLOUD_FUNC_ENTRY
QCLOUD_POINTER_SANITY_CHECK_RTN(message);
QCLOUD_POINTER_SANITY_CHECK_RTN(context);
coap_message_t *msg = NULL;
qcloud_coap_client_t *client = NULL;
msg = (coap_message_t *)message;
client = (qcloud_coap_client_t *)context;
if (msg->code_class != COAP_CODE_CLASS_SUCCESS ||
msg->code_detail != COAP_CODE_DETAIL_205_CONTENT) {
client->auth_state = QCLOUD_COAP_AUTH_STATE_FAIL;
QCLOUD_LOG_E("auth token failed, code_class: %d code_detail: %d", msg->code_class, msg->code_detail);
return;
}
QCLOUD_LOG_I("auth token success, code_class: %d code_detail: %d", msg->code_class, msg->code_detail);
if (msg->payload_len == 0 ||
msg->payload == NULL ||
strlen(msg->payload) == 0) {
client->auth_state = QCLOUD_COAP_AUTH_STATE_FAIL;
QCLOUD_LOG_E("auth token response empty");
} else {
client->auth_token_len = msg->payload_len;
client->auth_token = osal_malloc(client->auth_token_len);
strncpy(client->auth_token, msg->payload,client->auth_token_len);
client->auth_state = QCLOUD_COAP_AUTH_STATE_SUCCESS;
QCLOUD_LOG_D("auth_token_len = %d, auth_token = %.*s", client->auth_token_len, client->auth_token_len, client->auth_token);
}
QCLOUD_FUNC_EXIT
}
__QCLOUD_INTERNAL__ qcloud_err_t coap_auth(qcloud_coap_client_t *client, char *connection_id)
{
QCLOUD_FUNC_ENTRY
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_COAP_NULL);
int len;
qcloud_err_t rc;
char message_token[8] = {0};
coap_message_t connect_msg = COAP_MESSAGE_INITIALIZER;
coap_message_init(&connect_msg);
coap_message_type_set(&connect_msg, COAP_MSG_TYPE_CON);
coap_message_code_set(&connect_msg, COAP_CODE_CLASS_REQ, COAP_REQUEST_METHOD_POST);
coap_message_id_set(&connect_msg, coap_glue_packet_id_generate(client));
len = coap_message_token_get(client, message_token);
coap_message_token_set(&connect_msg, message_token, len);
coap_message_option_add(&connect_msg, COAP_MSG_OPTION_CODE_URI_PATH, strlen(client->auth_uri), client->auth_uri);
coap_message_option_add(&connect_msg, COAP_MSG_OPTION_CODE_NEED_RESP, 1, "0");
coap_message_callback_set(&connect_msg, coap_auth_callback);
coap_message_context_set(&connect_msg, client);
connect_msg.payload_len = sizeof(client->auth_id);
connect_msg.payload = (char *)osal_malloc(connect_msg.payload_len);
if (!connect_msg.payload) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_INVAL);
}
coap_message_payload_set(&connect_msg, client->auth_id, connect_msg.payload_len);
rc = coap_glue_msg_send(client, &connect_msg);
osal_free(connect_msg.payload);
QCLOUD_FUNC_EXIT_RC(rc)
}
#ifdef __cplusplus
}
#endif
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nxp/MIMXRT1062/CMSIS/DSP/Source/FilteringFunctions/arm_fir_decimate_fast_q31.c
|
<reponame>umaru724/TencentOS_E53_IA1
/* ----------------------------------------------------------------------
* Project: CMSIS DSP Library
* Title: arm_fir_decimate_fast_q31.c
* Description: Fast Q31 FIR Decimator
*
* $Date: 18. March 2019
* $Revision: V1.6.0
*
* Target Processor: Cortex-M cores
* -------------------------------------------------------------------- */
/*
* Copyright (C) 2010-2019 ARM Limited or its affiliates. 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
*
* 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 "arm_math.h"
/**
@ingroup groupFilters
*/
/**
@addtogroup FIR_decimate
@{
*/
/**
@brief Processing function for the Q31 FIR decimator (fast variant).
@param[in] S points to an instance of the Q31 FIR decimator structure
@param[in] pSrc points to the block of input data
@param[out] pDst points to the block of output data
@param[in] blockSize number of samples to process
@return none
@par Scaling and Overflow Behavior
This function is optimized for speed at the expense of fixed-point precision and overflow protection.
The result of each 1.31 x 1.31 multiplication is truncated to 2.30 format.
These intermediate results are added to a 2.30 accumulator.
Finally, the accumulator is saturated and converted to a 1.31 result.
The fast version has the same overflow behavior as the standard version and provides less precision since it discards the low 32 bits of each multiplication result.
In order to avoid overflows completely the input signal must be scaled down by log2(numTaps) bits (where log2 is read as log to the base 2).
@remark
Refer to \ref arm_fir_decimate_q31() for a slower implementation of this function which uses a 64-bit accumulator to provide higher precision.
Both the slow and the fast versions use the same instance structure.
Use function \ref arm_fir_decimate_init_q31() to initialize the filter structure.
*/
void arm_fir_decimate_fast_q31(
const arm_fir_decimate_instance_q31 * S,
const q31_t * pSrc,
q31_t * pDst,
uint32_t blockSize)
{
q31_t *pState = S->pState; /* State pointer */
const q31_t *pCoeffs = S->pCoeffs; /* Coefficient pointer */
q31_t *pStateCur; /* Points to the current sample of the state */
q31_t *px0; /* Temporary pointer for state buffer */
const q31_t *pb; /* Temporary pointer for coefficient buffer */
q31_t x0, c0; /* Temporary variables to hold state and coefficient values */
q63_t acc0; /* Accumulator */
uint32_t numTaps = S->numTaps; /* Number of filter coefficients in the filter */
uint32_t i, tapCnt, blkCnt, outBlockSize = blockSize / S->M; /* Loop counters */
#if defined (ARM_MATH_LOOPUNROLL)
q31_t *px1, *px2, *px3;
q31_t x1, x2, x3;
q63_t acc1, acc2, acc3;
#endif
/* S->pState buffer contains previous frame (numTaps - 1) samples */
/* pStateCur points to the location where the new input data should be written */
pStateCur = S->pState + (numTaps - 1U);
#if defined (ARM_MATH_LOOPUNROLL)
/* Loop unrolling: Compute 4 samples at a time */
blkCnt = outBlockSize >> 2U;
/* Samples loop unrolled by 4 */
while (blkCnt > 0U)
{
/* Copy 4 * decimation factor number of new input samples into the state buffer */
i = S->M * 4;
do
{
*pStateCur++ = *pSrc++;
} while (--i);
/* Set accumulators to zero */
acc0 = 0;
acc1 = 0;
acc2 = 0;
acc3 = 0;
/* Initialize state pointer for all the samples */
px0 = pState;
px1 = pState + S->M;
px2 = pState + 2 * S->M;
px3 = pState + 3 * S->M;
/* Initialize coeff pointer */
pb = pCoeffs;
/* Loop unrolling: Compute 4 taps at a time */
tapCnt = numTaps >> 2U;
while (tapCnt > 0U)
{
/* Read the b[numTaps-1] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-1] sample for acc0 */
x0 = *(px0++);
/* Read x[n-numTaps-1] sample for acc1 */
x1 = *(px1++);
/* Read x[n-numTaps-1] sample for acc2 */
x2 = *(px2++);
/* Read x[n-numTaps-1] sample for acc3 */
x3 = *(px3++);
/* Perform the multiply-accumulate */
acc0 = (q31_t) ((((q63_t) acc0 << 32) + ((q63_t) x0 * c0)) >> 32);
acc1 = (q31_t) ((((q63_t) acc1 << 32) + ((q63_t) x1 * c0)) >> 32);
acc2 = (q31_t) ((((q63_t) acc2 << 32) + ((q63_t) x2 * c0)) >> 32);
acc3 = (q31_t) ((((q63_t) acc3 << 32) + ((q63_t) x3 * c0)) >> 32);
/* Read the b[numTaps-2] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-2] sample for acc0, acc1, acc2, acc3 */
x0 = *(px0++);
x1 = *(px1++);
x2 = *(px2++);
x3 = *(px3++);
/* Perform the multiply-accumulate */
acc0 = (q31_t) ((((q63_t) acc0 << 32) + ((q63_t) x0 * c0)) >> 32);
acc1 = (q31_t) ((((q63_t) acc1 << 32) + ((q63_t) x1 * c0)) >> 32);
acc2 = (q31_t) ((((q63_t) acc2 << 32) + ((q63_t) x2 * c0)) >> 32);
acc3 = (q31_t) ((((q63_t) acc3 << 32) + ((q63_t) x3 * c0)) >> 32);
/* Read the b[numTaps-3] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-3] sample acc0, acc1, acc2, acc3 */
x0 = *(px0++);
x1 = *(px1++);
x2 = *(px2++);
x3 = *(px3++);
/* Perform the multiply-accumulate */
acc0 = (q31_t) ((((q63_t) acc0 << 32) + ((q63_t) x0 * c0)) >> 32);
acc1 = (q31_t) ((((q63_t) acc1 << 32) + ((q63_t) x1 * c0)) >> 32);
acc2 = (q31_t) ((((q63_t) acc2 << 32) + ((q63_t) x2 * c0)) >> 32);
acc3 = (q31_t) ((((q63_t) acc3 << 32) + ((q63_t) x3 * c0)) >> 32);
/* Read the b[numTaps-4] coefficient */
c0 = *(pb++);
/* Read x[n-numTaps-4] sample acc0, acc1, acc2, acc3 */
x0 = *(px0++);
x1 = *(px1++);
x2 = *(px2++);
x3 = *(px3++);
/* Perform the multiply-accumulate */
acc0 = (q31_t) ((((q63_t) acc0 << 32) + ((q63_t) x0 * c0)) >> 32);
acc1 = (q31_t) ((((q63_t) acc1 << 32) + ((q63_t) x1 * c0)) >> 32);
acc2 = (q31_t) ((((q63_t) acc2 << 32) + ((q63_t) x2 * c0)) >> 32);
acc3 = (q31_t) ((((q63_t) acc3 << 32) + ((q63_t) x3 * c0)) >> 32);
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = numTaps % 0x4U;
while (tapCnt > 0U)
{
/* Read coefficients */
c0 = *(pb++);
/* Fetch state variables for acc0, acc1, acc2, acc3 */
x0 = *(px0++);
x1 = *(px1++);
x2 = *(px2++);
x3 = *(px3++);
/* Perform the multiply-accumulate */
acc0 = (q31_t) ((((q63_t) acc0 << 32) + ((q63_t) x0 * c0)) >> 32);
acc1 = (q31_t) ((((q63_t) acc1 << 32) + ((q63_t) x1 * c0)) >> 32);
acc2 = (q31_t) ((((q63_t) acc2 << 32) + ((q63_t) x2 * c0)) >> 32);
acc3 = (q31_t) ((((q63_t) acc3 << 32) + ((q63_t) x3 * c0)) >> 32);
/* Decrement loop counter */
tapCnt--;
}
/* Advance the state pointer by the decimation factor
* to process the next group of decimation factor number samples */
pState = pState + S->M * 4;
/* The result is in the accumulator, store in the destination buffer. */
*pDst++ = (q31_t) (acc0 << 1);
*pDst++ = (q31_t) (acc1 << 1);
*pDst++ = (q31_t) (acc2 << 1);
*pDst++ = (q31_t) (acc3 << 1);
/* Decrement loop counter */
blkCnt--;
}
/* Loop unrolling: Compute remaining samples */
blkCnt = outBlockSize % 0x4U;
#else
/* Initialize blkCnt with number of samples */
blkCnt = outBlockSize;
#endif /* #if defined (ARM_MATH_LOOPUNROLL) */
while (blkCnt > 0U)
{
/* Copy decimation factor number of new input samples into the state buffer */
i = S->M;
do
{
*pStateCur++ = *pSrc++;
} while (--i);
/* Set accumulator to zero */
acc0 = 0;
/* Initialize state pointer */
px0 = pState;
/* Initialize coeff pointer */
pb = pCoeffs;
#if defined (ARM_MATH_LOOPUNROLL)
/* Loop unrolling: Compute 4 taps at a time */
tapCnt = numTaps >> 2U;
while (tapCnt > 0U)
{
/* Read the b[numTaps-1] coefficient */
c0 = *pb++;
/* Read x[n-numTaps-1] sample */
x0 = *px0++;
/* Perform the multiply-accumulate */
acc0 = (q31_t) ((((q63_t) acc0 << 32) + ((q63_t) x0 * c0)) >> 32);
/* Read the b[numTaps-2] coefficient */
c0 = *pb++;
/* Read x[n-numTaps-2] sample */
x0 = *px0++;
/* Perform the multiply-accumulate */
acc0 = (q31_t) ((((q63_t) acc0 << 32) + ((q63_t) x0 * c0)) >> 32);
/* Read the b[numTaps-3] coefficient */
c0 = *pb++;
/* Read x[n-numTaps-3] sample */
x0 = *px0++;
/* Perform the multiply-accumulate */
acc0 = (q31_t) ((((q63_t) acc0 << 32) + ((q63_t) x0 * c0)) >> 32);
/* Read the b[numTaps-4] coefficient */
c0 = *pb++;
/* Read x[n-numTaps-4] sample */
x0 = *px0++;
/* Perform the multiply-accumulate */
acc0 = (q31_t) ((((q63_t) acc0 << 32) + ((q63_t) x0 * c0)) >> 32);
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = numTaps % 0x4U;
#else
/* Initialize tapCnt with number of taps */
tapCnt = numTaps;
#endif /* #if defined (ARM_MATH_LOOPUNROLL) */
while (tapCnt > 0U)
{
/* Read coefficients */
c0 = *pb++;
/* Fetch 1 state variable */
x0 = *px0++;
/* Perform the multiply-accumulate */
acc0 = (q31_t) ((((q63_t) acc0 << 32) + ((q63_t) x0 * c0)) >> 32);
/* Decrement loop counter */
tapCnt--;
}
/* Advance the state pointer by the decimation factor
* to process the next group of decimation factor number samples */
pState = pState + S->M;
/* The result is in the accumulator, store in the destination buffer. */
*pDst++ = (q31_t) (acc0 << 1);
/* Decrement loop counter */
blkCnt--;
}
/* Processing is complete.
Now copy the last numTaps - 1 samples to the satrt of the state buffer.
This prepares the state buffer for the next function call. */
/* Points to the start of the state buffer */
pStateCur = S->pState;
#if defined (ARM_MATH_LOOPUNROLL)
/* Loop unrolling: Compute 4 taps at a time */
tapCnt = (numTaps - 1U) >> 2U;
/* Copy data */
while (tapCnt > 0U)
{
*pStateCur++ = *pState++;
*pStateCur++ = *pState++;
*pStateCur++ = *pState++;
*pStateCur++ = *pState++;
/* Decrement loop counter */
tapCnt--;
}
/* Loop unrolling: Compute remaining taps */
tapCnt = (numTaps - 1U) % 0x04U;
#else
/* Initialize tapCnt with number of taps */
tapCnt = (numTaps - 1U);
#endif /* #if defined (ARM_MATH_LOOPUNROLL) */
/* Copy data */
while (tapCnt > 0U)
{
*pStateCur++ = *pState++;
/* Decrement loop counter */
tapCnt--;
}
}
/**
@} end of FIR_decimate group
*/
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/proprietary_rf/esb_low_power_ptx/main.c
|
<reponame>umaru724/TencentOS_E53_IA1
/**
* Copyright (c) 2014 - 2019, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "nrf_esb.h"
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "sdk_common.h"
#include "nrf.h"
#include "nrf_error.h"
#include "nrf_esb_error_codes.h"
#include "nrf_delay.h"
#include "nrf_gpio.h"
#include "boards.h"
#include "app_util.h"
#define RESET_MEMORY_TEST_BYTE (0x0DUL) /**< Known sequence written to a special register to check if this wake up is from System OFF. */
#define RAM_RETENTION_OFF (0x00000003UL) /**< The flag used to turn off RAM retention on nRF52. */
#define BTN_PRESSED 0 /**< Value of a pressed button. */
#define BTN_RELEASED 1 /**< Value of a released button. */
//#define NRF_ESB_LEGACY
/*lint -save -esym(40, BUTTON_1) -esym(40, BUTTON_2) -esym(40, BUTTON_3) -esym(40, BUTTON_4) -esym(40, LED_1) -esym(40, LED_2) -esym(40, LED_3) -esym(40, LED_4) */
static nrf_esb_payload_t tx_payload = NRF_ESB_CREATE_PAYLOAD(0, 0x01, 0x00);
static nrf_esb_payload_t rx_payload;
static uint32_t button_state_1;
static uint32_t button_state_2;
static uint32_t button_state_3;
static uint32_t button_state_4;
static volatile bool esb_completed = false;
void system_off( void )
{
#ifdef NRF51
NRF_POWER->RAMON |= (POWER_RAMON_OFFRAM0_RAM0Off << POWER_RAMON_OFFRAM0_Pos) |
(POWER_RAMON_OFFRAM1_RAM1Off << POWER_RAMON_OFFRAM1_Pos);
#endif //NRF51
#ifdef NRF52
NRF_POWER->RAM[0].POWER = RAM_RETENTION_OFF;
NRF_POWER->RAM[1].POWER = RAM_RETENTION_OFF;
NRF_POWER->RAM[2].POWER = RAM_RETENTION_OFF;
NRF_POWER->RAM[3].POWER = RAM_RETENTION_OFF;
NRF_POWER->RAM[4].POWER = RAM_RETENTION_OFF;
NRF_POWER->RAM[5].POWER = RAM_RETENTION_OFF;
NRF_POWER->RAM[6].POWER = RAM_RETENTION_OFF;
NRF_POWER->RAM[7].POWER = RAM_RETENTION_OFF;
#endif //NRF52
// Turn off LEDs before sleeping to conserve energy.
bsp_board_leds_off();
// Set nRF5 into System OFF. Reading out value and looping after setting the register
// to guarantee System OFF in nRF52.
NRF_POWER->SYSTEMOFF = 0x1;
(void) NRF_POWER->SYSTEMOFF;
while (true);
}
void nrf_esb_event_handler(nrf_esb_evt_t const * p_event)
{
switch (p_event->evt_id)
{
case NRF_ESB_EVENT_TX_SUCCESS:
break;
case NRF_ESB_EVENT_TX_FAILED:
(void) nrf_esb_flush_tx();
break;
case NRF_ESB_EVENT_RX_RECEIVED:
// Get the most recent element from the RX FIFO.
while (nrf_esb_read_rx_payload(&rx_payload) == NRF_SUCCESS) ;
// For each LED, set it as indicated in the rx_payload, but invert it for the button
// which is pressed. This is because the ack payload from the PRX is reflecting the
// state from before receiving the packet.
nrf_gpio_pin_write(LED_1, !( ((rx_payload.data[0] & 0x01) == 0) ^ (button_state_1 == BTN_PRESSED)) );
nrf_gpio_pin_write(LED_2, !( ((rx_payload.data[0] & 0x02) == 0) ^ (button_state_2 == BTN_PRESSED)) );
nrf_gpio_pin_write(LED_3, !( ((rx_payload.data[0] & 0x04) == 0) ^ (button_state_3 == BTN_PRESSED)) );
nrf_gpio_pin_write(LED_4, !( ((rx_payload.data[0] & 0x08) == 0) ^ (button_state_4 == BTN_PRESSED)) );
break;
}
esb_completed = true;
}
void clocks_start( void )
{
// Start HFCLK and wait for it to start.
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
NRF_CLOCK->TASKS_HFCLKSTART = 1;
while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0);
}
uint32_t esb_init( void )
{
uint32_t err_code;
uint8_t base_addr_0[4] = {0xE7, 0xE7, 0xE7, 0xE7};
uint8_t base_addr_1[4] = {0xC2, 0xC2, 0xC2, 0xC2};
uint8_t addr_prefix[8] = {0xE7, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8 };
#ifndef NRF_ESB_LEGACY
nrf_esb_config_t nrf_esb_config = NRF_ESB_DEFAULT_CONFIG;
#else // NRF_ESB_LEGACY
nrf_esb_config_t nrf_esb_config = NRF_ESB_LEGACY_CONFIG;
#endif // NRF_ESB_LEGACY
nrf_esb_config.retransmit_count = 6;
nrf_esb_config.selective_auto_ack = false;
nrf_esb_config.protocol = NRF_ESB_PROTOCOL_ESB_DPL;
nrf_esb_config.bitrate = NRF_ESB_BITRATE_2MBPS;
nrf_esb_config.event_handler = nrf_esb_event_handler;
nrf_esb_config.mode = NRF_ESB_MODE_PTX;
err_code = nrf_esb_init(&nrf_esb_config);
VERIFY_SUCCESS(err_code);
err_code = nrf_esb_set_base_address_0(base_addr_0);
VERIFY_SUCCESS(err_code);
err_code = nrf_esb_set_base_address_1(base_addr_1);
VERIFY_SUCCESS(err_code);
err_code = nrf_esb_set_prefixes(addr_prefix, 8);
VERIFY_SUCCESS(err_code);
tx_payload.length = 3;
tx_payload.pipe = 0;
tx_payload.data[0] = 0x00;
return NRF_SUCCESS;
}
uint32_t gpio_check_and_esb_tx()
{
uint32_t err_code;
button_state_1 = nrf_gpio_pin_read(BUTTON_1);
button_state_2 = nrf_gpio_pin_read(BUTTON_2);
button_state_3 = nrf_gpio_pin_read(BUTTON_3);
button_state_4 = nrf_gpio_pin_read(BUTTON_4);
if (button_state_1 == BTN_PRESSED)
{
tx_payload.data[0] |= 1 << 0;
}
if (button_state_2 == BTN_PRESSED)
{
tx_payload.data[0] |= 1 << 1;
}
if (button_state_3 == BTN_PRESSED)
{
tx_payload.data[0] |= 1 << 2;
}
if (button_state_4 == BTN_PRESSED)
{
tx_payload.data[0] |= 1 << 3;
}
if (button_state_1 + button_state_2 + button_state_3 + button_state_4 == BTN_PRESSED + 3 * BTN_RELEASED)
{
tx_payload.noack = false;
err_code = nrf_esb_write_payload(&tx_payload);
VERIFY_SUCCESS(err_code);
}
else
{
esb_completed = true;
}
return NRF_SUCCESS;
}
void gpio_init( void )
{
nrf_gpio_cfg_sense_input(BUTTON_1, NRF_GPIO_PIN_PULLUP, NRF_GPIO_PIN_SENSE_LOW);
nrf_gpio_cfg_sense_input(BUTTON_2, NRF_GPIO_PIN_PULLUP, NRF_GPIO_PIN_SENSE_LOW);
nrf_gpio_cfg_sense_input(BUTTON_3, NRF_GPIO_PIN_PULLUP, NRF_GPIO_PIN_SENSE_LOW);
nrf_gpio_cfg_sense_input(BUTTON_4, NRF_GPIO_PIN_PULLUP, NRF_GPIO_PIN_SENSE_LOW);
// Workaround for PAN_028 rev1.1 anomaly 22 - System: Issues with disable System OFF mechanism
nrf_delay_ms(1);
bsp_board_init(BSP_INIT_LEDS);
}
void recover_state()
{
uint32_t loop_count = 0;
if ((NRF_POWER->GPREGRET >> 4) == RESET_MEMORY_TEST_BYTE)
{
// Take the loop_count value.
loop_count = (uint8_t)(NRF_POWER->GPREGRET & 0xFUL);
NRF_POWER->GPREGRET = 0;
}
loop_count++;
NRF_POWER->GPREGRET = ( (RESET_MEMORY_TEST_BYTE << 4) | loop_count);
tx_payload.data[1] = loop_count << 4;
}
int main(void)
{
uint32_t err_code;
// Initialize
clocks_start();
err_code = esb_init();
APP_ERROR_CHECK(err_code);
gpio_init();
// Recover state if the device was woken from System OFF.
recover_state();
// Check state of all buttons and send an esb packet with the button press if there is exactly one.
err_code = gpio_check_and_esb_tx();
APP_ERROR_CHECK(err_code);
while (true)
{
// Wait for esb completed and all buttons released before going to system off.
if (esb_completed)
{
if (nrf_gpio_pin_read(BUTTON_1) == BTN_RELEASED &&
nrf_gpio_pin_read(BUTTON_2) == BTN_RELEASED &&
nrf_gpio_pin_read(BUTTON_3) == BTN_RELEASED &&
nrf_gpio_pin_read(BUTTON_4) == BTN_RELEASED
)
{
system_off();
}
}
}
}
/*lint -restore */
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/connectivity/ble_connectivity/main.c
|
/**
* Copyright (c) 2013 - 2019, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/**@file
*
* @defgroup ble_sdk_app_connectivity_main main.c
* @{
* @ingroup ble_sdk_app_connectivity
*
* @brief BLE Connectivity application.
*/
#include <stdbool.h>
#include "nrf_sdm.h"
#include "nrf_soc.h"
#include "app_error.h"
#include "app_scheduler.h"
#include "nrf_sdh.h"
#include "ser_hal_transport.h"
#include "ser_conn_handlers.h"
#include "boards.h"
#include "nrf_drv_clock.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "app_timer.h"
#include "ser_phy_debug_comm.h"
#if defined(APP_USBD_ENABLED) && APP_USBD_ENABLED
#include "app_usbd_serial_num.h"
#ifdef BOARD_PCA10059
#include "nrf_dfu_trigger_usb.h"
#endif
#include "app_usbd.h"
static volatile bool m_usb_started;
static void usbd_user_evt_handler(app_usbd_event_type_t event)
{
switch (event)
{
case APP_USBD_EVT_DRV_SUSPEND:
break;
case APP_USBD_EVT_DRV_RESUME:
break;
case APP_USBD_EVT_STARTED:
m_usb_started = true;
break;
case APP_USBD_EVT_STOPPED:
app_usbd_disable();
break;
case APP_USBD_EVT_POWER_DETECTED:
NRF_LOG_INFO("USB power detected");
if (!nrf_drv_usbd_is_enabled())
{
app_usbd_enable();
}
break;
case APP_USBD_EVT_POWER_REMOVED:
NRF_LOG_INFO("USB power removed");
app_usbd_stop();
break;
case APP_USBD_EVT_POWER_READY:
NRF_LOG_INFO("USB ready");
app_usbd_start();
break;
default:
break;
}
}
static void usbd_init(void)
{
app_usbd_serial_num_generate();
static const app_usbd_config_t usbd_config = {
.ev_state_proc = usbd_user_evt_handler
};
APP_ERROR_CHECK(app_usbd_init(&usbd_config));
}
static void usbd_enable(void)
{
#ifdef BOARD_PCA10059
APP_ERROR_CHECK(nrf_dfu_trigger_usb_init());
#endif
APP_ERROR_CHECK(app_usbd_power_events_enable());
/* Process USB events until USB is started. This is related to the fact that
* current version of softdevice does not handle USB POWER events. */
while (m_usb_started == false)
{
while (app_usbd_event_queue_process())
{
/* Nothing to do */
}
}
}
#endif //APP_USBD_ENABLED
static void on_idle(void)
{
if (!NRF_LOG_PROCESS())
{
// Wait for an event.
if (nrf_sdh_is_enabled())
{
ret_code_t ret_code = sd_app_evt_wait();
ASSERT((ret_code == NRF_SUCCESS) || (ret_code == NRF_ERROR_SOFTDEVICE_NOT_ENABLED));
UNUSED_VARIABLE(ret_code);
}
else
{
// Wait for an event.
__WFE();
// Clear the internal event register.
__SEV();
__WFE();
}
}
#if defined(APP_USBD_ENABLED) && APP_USBD_ENABLED
while (app_usbd_event_queue_process())
{
/* Nothing to do */
}
#endif
}
/**@brief Main function of the connectivity application. */
int main(void)
{
uint32_t err_code = NRF_SUCCESS;
APP_ERROR_CHECK(NRF_LOG_INIT(NULL));
NRF_LOG_DEFAULT_BACKENDS_INIT();
NRF_LOG_INFO("BLE connectivity started");
bsp_board_init(BSP_INIT_LEDS);
#if (defined(SER_PHY_HCI_DEBUG_ENABLE) || defined(SER_PHY_DEBUG_APP_ENABLE))
debug_init(NULL);
#endif
/* Force constant latency mode to control SPI slave timing */
NRF_POWER->TASKS_CONSTLAT = 1;
/* Initialize scheduler queue. */
//lint -save -e666 -e587
APP_SCHED_INIT(SER_CONN_SCHED_MAX_EVENT_DATA_SIZE, SER_CONN_SCHED_QUEUE_SIZE);
//lint -restore
/* Initialize SoftDevice.
* SoftDevice Event IRQ is not scheduled but immediately copies BLE events to the application
* scheduler queue */
err_code = nrf_drv_clock_init();
if ((err_code != NRF_SUCCESS) &&
(err_code != NRF_ERROR_MODULE_ALREADY_INITIALIZED))
{
APP_ERROR_CHECK(err_code);
}
nrf_drv_clock_hfclk_request(NULL);
while (!nrf_drv_clock_hfclk_is_running())
{}
#if defined(APP_USBD_ENABLED) && APP_USBD_ENABLED
usbd_init();
#endif
/* Open serialization HAL Transport layer and subscribe for HAL Transport events. */
err_code = ser_hal_transport_open(ser_conn_hal_transport_event_handle);
APP_ERROR_CHECK(err_code);
#if defined(APP_USBD_ENABLED) && APP_USBD_ENABLED
usbd_enable();
#endif
err_code = nrf_sdh_enable_request();
APP_ERROR_CHECK(err_code);
err_code = app_timer_init();
APP_ERROR_CHECK(err_code);
ser_conn_on_no_mem_handler_set(on_idle);
/* Enter main loop. */
for (;;)
{
/* Process SoftDevice events. */
app_sched_execute();
if (nrf_sdh_is_suspended())
{
// Resume pulling new events if queue utilization drops below 50%.
if (app_sched_queue_space_get() > (SER_CONN_SCHED_QUEUE_SIZE >> 1))
{
nrf_sdh_resume();
}
}
/* Process received packets.
* We can NOT add received packets as events to the application scheduler queue because
* received packets have to be processed before SoftDevice events but the scheduler queue
* does not have priorities. */
err_code = ser_conn_rx_process();
APP_ERROR_CHECK(err_code);
on_idle();
}
}
/** @} */
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/src/port/TencentOS_tiny/osal_dtls.c
|
<filename>components/connectivity/TencentCloud_SDK/source/src/port/TencentOS_tiny/osal_dtls.c
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud.h"
#include "mbedtls/net_sockets.h"
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"
#include "mbedtls/certs.h"
#include "mbedtls/timing.h"
#include "mbedtls/ssl_cookie.h"
#include "mbedtls/debug.h"
#define DEBUG_LEVEL 0
void mbedtls_dtls_net_init(mbedtls_net_context *ctx);
int mbedtls_dtls_net_connect(mbedtls_net_context *ctx, const char *host, const char *port, int proto);
void mbedtls_dtls_net_usleep(unsigned long usec);
int mbedtls_dtls_net_recv(void *ctx, unsigned char *buf, size_t len);
int mbedtls_dtls_net_recv_timeout(void *ctx, unsigned char *buf, size_t len, uint32_t timeout);
int mbedtls_dtls_net_send(void *ctx, const unsigned char *buf, size_t len);
void mbedtls_dtls_net_free(mbedtls_net_context *ctx);
#if (QCLOUD_CFG_AUTH_MODE == QCLOUD_AUTH_MODE_KEY)
static const int ciphersuites[] = { MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA, 0 };
#endif
typedef struct dtls_paramter_st {
mbedtls_net_context socket_fd; // socket文件描述符
mbedtls_entropy_context entropy; // 保存熵配置
mbedtls_ctr_drbg_context ctr_drbg; // 随机数生成器
mbedtls_ssl_context ssl; // 保存SSL基本数据
mbedtls_ssl_config ssl_conf; // TSL/TLS配置信息
#if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_x509_crt ca_cert; // ca证书信息
mbedtls_x509_crt client_cert; // 客户端证书信息
#endif
mbedtls_pk_context private_key; // 客户端私钥信息
mbedtls_timing_delay_context timer;
mbedtls_ssl_cookie_ctx cookie_ctx;
} dtls_param_t;
/**
* @brief 释放mbedtls开辟的内存
*/
static void mbedtls_dtls_param_free(dtls_param_t *dtls_param)
{
mbedtls_dtls_net_free(&dtls_param->socket_fd);
#if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_x509_crt_free(&dtls_param->client_cert);
mbedtls_x509_crt_free(&dtls_param->ca_cert);
mbedtls_pk_free(&dtls_param->private_key);
#endif
mbedtls_ssl_free(&dtls_param->ssl);
mbedtls_ssl_config_free(&dtls_param->ssl_conf);
mbedtls_ctr_drbg_free(&dtls_param->ctr_drbg);
mbedtls_entropy_free(&dtls_param->entropy);
#if 0
mbedtls_ssl_cookie_free(&(dtls_param->cookie_ctx));
#endif
osal_free(dtls_param);
}
static void mbedtls_debug(void *ctx, int level, const char *file, int line, const char *str)
{
QCLOUD_LOG_I("[mbedTLS]:[%s]:[%d]: %s\r\n", file, line, str);
}
static int mbedtls_client_init(dtls_param_t *dtls_param, qcloud_tls_opt_t *tls_opt)
{
int ret = 0;
#if defined(MBEDTLS_DEBUG_C)
mbedtls_debug_set_threshold(DEBUG_LEVEL);
#endif
mbedtls_dtls_net_init(&dtls_param->socket_fd);
mbedtls_ssl_init(&dtls_param->ssl);
mbedtls_ssl_config_init(&dtls_param->ssl_conf);
#if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_x509_crt_init(&dtls_param->ca_cert);
mbedtls_x509_crt_init(&dtls_param->client_cert);
mbedtls_pk_init(&dtls_param->private_key);
#endif
mbedtls_ctr_drbg_init(&dtls_param->ctr_drbg);
mbedtls_entropy_init(&dtls_param->entropy);
if((ret = mbedtls_ctr_drbg_seed(&dtls_param->ctr_drbg, mbedtls_entropy_func,
&dtls_param->entropy, NULL,0)) != 0) {
QCLOUD_LOG_E("mbedtls_ctr_drbg_seed failed returned -0x%x", -ret);
return QCLOUD_ERR_SSL_INIT;
}
mbedtls_ssl_conf_authmode(&dtls_param->ssl_conf, MBEDTLS_SSL_VERIFY_NONE );
#if defined(MBEDTLS_X509_CRT_PARSE_C)
if (tls_opt->ca_cert != NULL) {
if ((ret = mbedtls_x509_crt_parse(&dtls_param->ca_cert, (const unsigned char *)tls_opt->ca_cert,
(tls_opt->ca_cert_len + 1)))) {
QCLOUD_LOG_E("parse ca crt failed returned -0x%04x", -ret);
return QCLOUD_ERR_SSL_CERT;
}
}
#endif
#if (QCLOUD_CFG_AUTH_MODE == QCLOUD_AUTH_MODE_CERT)
if (tls_opt->cert_path != NULL && tls_opt->priv_key_path != NULL) {
#if defined(MBEDTLS_X509_CRT_PARSE_C)
if ((ret = mbedtls_x509_crt_parse_file(&dtls_param->client_cert, tls_opt->cert_path)) != 0) {
QCLOUD_LOG_E("load client cert file failed returned -0x%x", ret);
return QCLOUD_ERR_SSL_CERT;
}
#endif
if ((ret = mbedtls_pk_parse_keyfile(&dtls_param->private_key, tls_opt->priv_key_path, "")) != 0) {
QCLOUD_LOG_E("load client key file failed returned -0x%x", ret);
return QCLOUD_ERR_SSL_CERT;
}
#if defined(MBEDTLS_X509_CRT_PARSE_C)
if (0 == ret) {
mbedtls_ssl_conf_ca_chain(&dtls_param->ssl_conf, &dtls_param->ca_cert, NULL);
if ((ret = mbedtls_ssl_conf_own_cert(&dtls_param->ssl_conf, &dtls_param->client_cert, &dtls_param->private_key)) != 0) {
QCLOUD_LOG_E("mbedtls_ssl_conf_own_cert failed returned -0x%x", -ret);
return QCLOUD_ERR_SSL_CERT;
}
}
#endif
} else {
QCLOUD_LOG_D("cert_file/key_file is empty!|cert_file=%s|key_file=%s", tls_opt->cert_path, tls_opt->priv_key_path);
}
#else
if (tls_opt->psk != NULL && tls_opt->psk_id !=NULL) {
const char *psk_id = tls_opt->psk_id;
ret = mbedtls_ssl_conf_psk(&dtls_param->ssl_conf, (unsigned char *)tls_opt->psk, tls_opt->psk_len,
(const unsigned char *)psk_id, strlen(psk_id));
} else {
QCLOUD_LOG_D("psk/pskid is empty!|psk=%s|psd_id=%s", tls_opt->psk, tls_opt->psk_id);
}
if (0 != ret) {
QCLOUD_LOG_E("mbedtls_ssl_conf_psk fail: -0x%x", -ret);
return ret;
}
#endif
return ret;
}
/**
* @brief 建立UDP连接
*
* @param socket_fd Socket描述符
* @param host 服务器主机名
* @param port 服务器端口地址
* @return 返回QCLOUD_ERR_SUCCESS, 表示成功
*/
int mbedtls_udp_connect(mbedtls_net_context *socket_fd, const char *host, int port)
{
int ret = 0;
char port_str[6];
osal_snprintf(port_str, 6, "%d", port);
if ((ret = mbedtls_dtls_net_connect(socket_fd, host, port_str, MBEDTLS_NET_PROTO_UDP)) != 0) {
QCLOUD_LOG_E("mbedtls_dtls_net_connect host:%s port:%s returned -0x%04x", host, port_str, -ret);
switch (ret) {
case MBEDTLS_ERR_NET_SOCKET_FAILED:
return QCLOUD_ERR_TCP_SOCKET_FAILED;
case MBEDTLS_ERR_NET_UNKNOWN_HOST:
return QCLOUD_ERR_TCP_UNKNOWN_HOST;
default:
return QCLOUD_ERR_TCP_CONNECT;
}
}
#if 0
if ((ret = mbedtls_net_set_block(socket_fd)) != 0) {
QCLOUD_LOG_E("set block faliled returned -0x%04x", -ret);
return QCLOUD_ERR_TCP_CONNECT;
}
#endif
return QCLOUD_ERR_SUCCESS;
}
__QCLOUD_OSAL__ void *osal_dtls_connect(qcloud_tls_opt_t *tls_opt, const char *host, int port)
{
QCLOUD_FUNC_ENTRY;
int ret = QCLOUD_ERR_SUCCESS;
dtls_param_t *dtls_param = NULL;
if (!tls_opt) {
return NULL;
}
dtls_param = (dtls_param_t *)osal_malloc(sizeof(dtls_param_t));
if (!dtls_param) {
return NULL;
}
if ((ret = mbedtls_client_init(dtls_param, tls_opt)) != QCLOUD_ERR_SUCCESS) {
goto error;
}
QCLOUD_LOG_D(" Connecting to /%s/%d...", host, port);
if ((ret = mbedtls_udp_connect(&dtls_param->socket_fd, host, port)) != QCLOUD_ERR_SUCCESS) {
goto error;
}
QCLOUD_LOG_D(" Setting up the SSL/TLS structure...");
if ((ret = mbedtls_ssl_config_defaults(&dtls_param->ssl_conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_DATAGRAM,
MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
QCLOUD_LOG_E("mbedtls_ssl_config_defaults result 0x%04x", ret);
goto error;
}
mbedtls_ssl_conf_authmode(&dtls_param->ssl_conf, MBEDTLS_SSL_VERIFY_REQUIRED);
mbedtls_ssl_conf_rng(&dtls_param->ssl_conf, mbedtls_ctr_drbg_random, &dtls_param->ctr_drbg);
mbedtls_ssl_conf_dbg(&dtls_param->ssl_conf, mbedtls_debug, NULL);
#if 0
if ((ret = mbedtls_ssl_cookie_setup(&pDataParams->cookie_ctx, mbedtls_ctr_drbg_random, &pDataParams->ctr_drbg)) != 0) {
QCLOUD_LOG_E("mbedtls_ssl_cookie_setup result 0x%04x", ret);
goto error;
}
#endif
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
mbedtls_ssl_conf_dtls_cookies(&dtls_param->ssl_conf, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check, &dtls_param->cookie_ctx);
#endif
#if (QCLOUD_CFG_AUTH_MODE == QCLOUD_AUTH_MODE_KEY)
mbedtls_ssl_conf_ciphersuites(&dtls_param->ssl_conf, ciphersuites);
#endif
#ifdef MBEDTLS_SSL_PROTO_DTLS
if (dtls_param->ssl_conf.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
mbedtls_ssl_conf_min_version(&dtls_param->ssl_conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
mbedtls_ssl_conf_max_version(&dtls_param->ssl_conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
mbedtls_ssl_conf_handshake_timeout(&dtls_param->ssl_conf, (MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN * 2),
(MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN * 2 * 4));
}
#endif
if ((ret = mbedtls_ssl_setup(&dtls_param->ssl, &dtls_param->ssl_conf)) != 0) {
QCLOUD_LOG_E("mbedtls_ssl_setup failed returned -0x%x", -ret);
goto error;
}
if (dtls_param->ssl_conf.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
mbedtls_ssl_set_timer_cb(&dtls_param->ssl, (void *)&dtls_param->timer, mbedtls_timing_set_delay,
mbedtls_timing_get_delay);
}
#if defined(MBEDTLS_X509_CRT_PARSE_C)
if ((ret = mbedtls_ssl_set_hostname(&dtls_param->ssl, host)) != 0) {
QCLOUD_LOG_E("mbedtls_ssl_set_hostname failed returned -0x%x", -ret);
goto error;
}
#endif
mbedtls_ssl_set_bio(&dtls_param->ssl, (void *)&dtls_param->socket_fd, mbedtls_dtls_net_send, mbedtls_dtls_net_recv,
mbedtls_dtls_net_recv_timeout);
QCLOUD_LOG_D("Performing the SSL/TLS handshake...");
while ((ret = mbedtls_ssl_handshake(&dtls_param->ssl)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
QCLOUD_LOG_E("mbedtls_ssl_handshake failed returned -0x%x", -ret);
#if defined(MBEDTLS_X509_CRT_PARSE_C)
if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
QCLOUD_LOG_E("Unable to verify the server's certificate");
}
#endif
goto error;
}
}
if ((ret = mbedtls_ssl_get_verify_result(&dtls_param->ssl)) != 0) {
QCLOUD_LOG_E("mbedtls_ssl_get_verify_result failed returned -0x%x", -ret);
goto error;
}
return dtls_param;
error:
mbedtls_dtls_param_free(dtls_param);
return NULL;
}
__QCLOUD_OSAL__ void osal_dtls_disconnect(void *handle)
{
int rc = 0;
dtls_param_t *dtls_param = NULL;
if (!handle) {
return;
}
dtls_param = (dtls_param_t *)handle;
do {
rc = mbedtls_ssl_close_notify(&dtls_param->ssl);
} while (rc == MBEDTLS_ERR_SSL_WANT_READ || rc == MBEDTLS_ERR_SSL_WANT_WRITE);
mbedtls_dtls_param_free(dtls_param);
}
__QCLOUD_OSAL__ qcloud_err_t osal_dtls_write(void *handle, const void *buf, size_t len, size_t *write_len)
{
QCLOUD_POINTER_SANITY_CHECK(handle, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(write_len, QCLOUD_ERR_INVAL);
int rc;
dtls_param_t *data_params = NULL;
data_params = (dtls_param_t *)handle;
rc = mbedtls_ssl_write(&data_params->ssl, buf, len);
if (rc < 0) {
QCLOUD_LOG_E("ssl_write failed %d", rc);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SSL_WRITE);
}
*write_len = rc;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
__QCLOUD_OSAL__ qcloud_err_t osal_dtls_read(void *handle, void *buf, size_t len, uint32_t timeout, size_t *read_len)
{
QCLOUD_POINTER_SANITY_CHECK(handle, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(read_len, QCLOUD_ERR_INVAL);
int rc = 0;
dtls_param_t *data_params = NULL;
data_params = (dtls_param_t *)handle;
mbedtls_ssl_conf_read_timeout(&data_params->ssl_conf, timeout);
do {
rc = mbedtls_ssl_read(&data_params->ssl, buf, len);
} while (rc == MBEDTLS_ERR_SSL_WANT_READ || rc == MBEDTLS_ERR_SSL_WANT_WRITE);
if (rc > 0) {
*read_len = rc;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
switch (rc) {
case MBEDTLS_ERR_SSL_TIMEOUT:
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SSL_READ_TIMEOUT);
case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
QCLOUD_LOG_E("connection closed");
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_DTLS_PEER_CLOSE_NOTIFY);
default:
QCLOUD_LOG_E("ssl_read returned -0x%x", -rc);
break;
}
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_FAILURE);
}
#ifdef __cplusplus
}
#endif
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/include/qcloud_device_config.h
|
<reponame>umaru724/TencentOS_E53_IA1
#ifndef _QCLOUD_DEVICE_CONFIG_
#define _QCLOUD_DEVICE_CONFIG_
#define QCLOUD_DEVICE_PRODUCT_ID_MAX 14
#define QCLOUD_DEVICE_DEVICE_NAME_MAX 48
#define QCLOUD_DEVICE_USERNAME_MAX (QCLOUD_MQTT_DEVICE_CLIENT_ID_MAX + 8 + QCLOUD_MQTT_CONNECT_ID_MAX + 10 + 4 + 5)
#define QCLOUD_DEVICE_PASSWORD_MAX 52
#define QCLOUD_DEVICE_KEY_MAX 32
#if (QCLOUD_CFG_DEVICE_DYN_REG_EN > 0u)
#define QCLOUD_DEVICE_PRODUCT_KEY_MAX 32
#endif
#endif
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/include/qcloud_lib.h
|
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 _QCLOUD_LIB_H_
#define _QCLOUD_LIB_H_
#if defined(__cplusplus)
extern "C" {
#endif
#define __QCLOUD_API__
#define __QCLOUD_INTERNAL__
#define __QCLOUD_STATIC__ static
#define __QCLOUD_OSAL__
#define QCLOUD_MAX(a,b) ((a) > (b) ? (a) : (b))
#define QCLOUD_MIN(a,b) ((a) < (b) ? (a) : (b))
#if (QCLOUD_CFG_DEVELOP_DEBUG_EN > 0u)
#define QCLOUD_FUNC_ENTRY \
{ \
printf("FUNC_ENTRY: %s L#%d \n", __FUNCTION__, __LINE__); \
}
#define QCLOUD_FUNC_EXIT \
{ \
printf("FUNC_EXIT: %s L#%d \n", __FUNCTION__, __LINE__); \
return; \
}
#define QCLOUD_FUNC_EXIT_RC(x) \
{ \
printf("FUNC_EXIT: %s L#%d Return Code : %ld \n", __FUNCTION__, __LINE__, (long)(x)); \
return x; \
}
#define QCLOUD_FUNC_EXIT_RC_IF(exp, expected, x) \
if ((exp) == (expected)) { \
printf("FUNC_EXIT: %s L#%d Return Code : %ld \n", __FUNCTION__, __LINE__, (long)(x)); \
return (x); \
}
#define QCLOUD_FUNC_EXIT_RC_IF_NOT(exp, expected, x) \
if ((exp) != (expected)) { \
printf("FUNC_EXIT: %s L#%d Return Code : %ld \n", __FUNCTION__, __LINE__, (long)(x)); \
return (x); \
}
#else
#define QCLOUD_FUNC_ENTRY
#define QCLOUD_FUNC_EXIT \
{ \
return;\
}
#define QCLOUD_FUNC_EXIT_RC(x) \
{ \
return x; \
}
#define QCLOUD_FUNC_EXIT_RC_IF(exp, expected, x) \
if ((exp) == (expected)) { \
return (x); \
}
#define QCLOUD_FUNC_EXIT_RC_IF_NOT(exp, expected, x) \
if ((exp) != (expected)) { \
return (x); \
}
#endif
#define QCLOUD_NUMBERIC_SANITY_CHECK(num, err) \
do { \
if (0 == (num)) { \
QCLOUD_LOG_E("Invalid argument, numeric 0"); \
return (err); \
} \
} while(0)
#define QCLOUD_NUMBERIC_SANITY_CHECK_RTN(num) \
do { \
if (0 == (num)) { \
QCLOUD_LOG_E("Invalid argument, numeric 0"); \
return; \
} \
} while(0)
#define QCLOUD_POINTER_SANITY_CHECK(ptr, err) \
do { \
if (NULL == (ptr)) { \
QCLOUD_LOG_E("Invalid argument, %s = %p", #ptr, ptr); \
return (err); \
} \
} while(0)
#define QCLOUD_POINTER_SANITY_CHECK_RTN(ptr) \
do { \
if (NULL == (ptr)) { \
QCLOUD_LOG_E("Invalid argument, %s = %p", #ptr, ptr); \
return; \
} \
} while(0)
#define QCLOUD_STRING_PTR_SANITY_CHECK(ptr, err) \
do { \
if (NULL == (ptr)) { \
QCLOUD_LOG_E("Invalid argument, %s = %p", #ptr, (ptr)); \
return (err); \
} \
if (0 == strlen((ptr))) { \
QCLOUD_LOG_E("Invalid argument, %s = '%s'", #ptr, (ptr)); \
return (err); \
} \
} while(0)
#define QCLOUD_STRING_PTR_SANITY_CHECK_RTN(ptr) \
do { \
if (NULL == (ptr)) { \
QCLOUD_LOG_E("Invalid argument, %s = %p", #ptr, (ptr)); \
return; \
} \
if (0 == strlen((ptr))) { \
QCLOUD_LOG_E("Invalid argument, %s = '%s'", #ptr, (ptr)); \
return; \
} \
} while(0)
#if defined(__cplusplus)
}
#endif
#endif
|
umaru724/TencentOS_E53_IA1
|
examples/qcloud_iot_explorer_sdk_data_template/qcloud_iot_hub_sdk_explorer.c
|
<reponame>umaru724/TencentOS_E53_IA1<gh_stars>0
#include "tos_k.h"
//#include "bc35_28_95_lwm2m.h"
#include "mcu_init.h"
#include "sal_module_wrapper.h"
#include "cmsis_os.h"
/* 用户根据自己的底层通信链路来配置此宏
* 如果是基于以太网lwip的链路,这里应该定义 USE_LWIP
* 如果是基于模组的通信链路,这里应该定义相应的模组宏,如使用ESP8266则定义 USE_ESP8266
* */
#define USE_ESP8266
#ifdef USE_LWIP
#include "lwip/api.h"
#include "lwip/sockets.h"
#include "lwip/err.h"
#include "lwip/sys.h"
#endif
#ifdef USE_ESP8266
#include "esp8266.h"
#endif
int socket_id = 1;
void application_entry(void *arg)
{
#ifdef USE_LWIP
dns_init();
MX_LWIP_Init();
#endif
#ifdef USE_ESP8266
extern int esp8266_sal_init(hal_uart_port_t uart_port);
extern int esp8266_join_ap(const char *ssid, const char *pwd);
esp8266_sal_init(HAL_UART_PORT_0);
esp8266_join_ap("xxxx", "xxxxx"); //need to modify
#endif
#ifdef USE_NB_BC35
extern int bc35_28_95_sal_lwm2m_init(hal_uart_port_t uart_port);
bc35_28_95_sal_lwm2m_init(HAL_UART_PORT_0);
//socket_id = tos_sal_module_connect("192.168.3.11","5683",TOS_SAL_PROTO_UDP);
socket_id = tos_sal_module_connect("172.16.31.10", "5684", TOS_SAL_PROTO_UDP);
if(socket_id !=-1){
printf("connect to cloud success! fd: %d\n", socket_id);
}
else{
printf("connect to cloud failed!\n");
}
#endif
data_template_light_thread();
while (1) {
printf("This is a tencent cloud sdk data template demo!\r\n");
tos_task_delay(1000);
}
}
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/src/mqtt/qcloud_mqtt_yield.c
|
<filename>components/connectivity/TencentCloud_SDK/source/src/mqtt/qcloud_mqtt_yield.c
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud.h"
__QCLOUD_STATIC__ qcloud_err_t mqtt_yield_resubscribe(qcloud_mqtt_client_t *client)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
char *topic = NULL;
mqtt_subscribe_opt_t subscribe_opt;
qcloud_list_t *curr, *next;
qcloud_mqtt_msg_handler_t *msg_handler;
if (!qcloud_mqtt_client_is_connected(client)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_NO_CONN);
}
if (qcloud_list_empty(&client->msg_handler_list)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
osal_mutex_lock(client->msg_handler_list_lock);
QCLOUD_LIST_FOR_EACH_SAFE(curr, next, &client->msg_handler_list) {
msg_handler = QCLOUD_LIST_ENTRY(curr, qcloud_mqtt_msg_handler_t, list);
subscribe_opt.message_handler = msg_handler->handler;
subscribe_opt.qos = msg_handler->qos;
subscribe_opt.private_data = msg_handler->private_data;
rc = qcloud_mqtt_subscribe(client, msg_handler->topic_filter_mutable, &subscribe_opt);
if (rc != QCLOUD_ERR_SUCCESS) {
osal_mutex_unlock(client->msg_handler_list_lock);
QCLOUD_LOG_E("resubscribe failed %d, topic: %s", rc, topic);
QCLOUD_FUNC_EXIT_RC(rc);
}
}
osal_mutex_unlock(client->msg_handler_list_lock);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
__QCLOUD_STATIC__ qcloud_err_t mqtt_yield_do_reconnect(qcloud_mqtt_client_t *client, mqtt_connect_opt_t *connect_opt)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(connect_opt, QCLOUD_ERR_INVAL);
qcloud_err_t rc;
QCLOUD_LOG_I("attempt to reconnect...");
if (qcloud_mqtt_client_is_connected(client)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_ALREADY_CONNECTED);
}
rc = qcloud_mqtt_connect(client, connect_opt);
if (!qcloud_mqtt_client_is_connected(client)) {
QCLOUD_FUNC_EXIT_RC(rc);
}
rc = mqtt_yield_resubscribe(client);
if (rc != QCLOUD_ERR_SUCCESS) {
QCLOUD_FUNC_EXIT_RC(rc);
}
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_RECONNECTED);
}
/**
* @brief 处理非手动断开连接的情况
*
* @param client
* @return
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_yield_try_disconnect(qcloud_mqtt_client_t *client)
{
QCLOUD_FUNC_ENTRY;
qcloud_err_t rc;
if (!qcloud_mqtt_client_is_connected(client)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_NO_CONN);
}
rc = qcloud_mqtt_disconnect(client);
// 若断开连接失败, 强制断开底层TLS层连接
if (rc != QCLOUD_ERR_SUCCESS) {
client->network.disconnect(&(client->network));
mqtt_client_connection_state_set(client, QCLOUD_MQTT_CONNECTION_STATE_DISCONNECTED);
}
mqtt_glue_callback_involve(client, MQTT_EVENT_DISCONNECT, NULL);
// 非手动断开连接
client->is_manually_disconnected = QCLOUD_FALSE;
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_NO_CONN);
}
/**
* @brief 处理自动重连的相关逻辑
*
* @param client
* @return
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_yield_try_reconnect(qcloud_mqtt_client_t *client, mqtt_connect_opt_t *connect_opt)
{
QCLOUD_FUNC_ENTRY;
qcloud_err_t rc = QCLOUD_ERR_MQTT_RECONNECTED;
// 自动重连等待时间还未过期, 还未到重连的时候, 返回正在进行重连
if (!osal_timer_is_expired(&client->reconnect_timer)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_ATTEMPTING_RECONNECT);
}
rc = mqtt_yield_do_reconnect(client, connect_opt);
if (rc == QCLOUD_ERR_MQTT_RECONNECTED) {
QCLOUD_LOG_E("reconnect success");
mqtt_glue_callback_involve(client, MQTT_EVENT_RECONNECT, NULL);
QCLOUD_FUNC_EXIT_RC(rc);
} else {
QCLOUD_LOG_E("attempt reconnect failed %d", rc);
rc = QCLOUD_ERR_MQTT_ATTEMPTING_RECONNECT;
}
client->reconnect_try_duration *= 2;
if (client->reconnect_try_duration > QCLOUD_MQTT_RECONNECT_TRY_THRESHOLD) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_RECONNECT_TIMEOUT);
}
osal_timer_countdown_ms(&client->reconnect_timer, client->reconnect_try_duration);
QCLOUD_FUNC_EXIT_RC(rc);
}
/**
* @brief 处理与服务器维持心跳的相关逻辑
*
* @param client
* @return
*/
__QCLOUD_STATIC__ qcloud_err_t mqtt_yield_keep_alive(qcloud_mqtt_client_t *client, mqtt_connect_opt_t *connect_opt)
{
#define MQTT_PING_RETRY_TIMES 2
QCLOUD_FUNC_ENTRY;
int try = 0;
qcloud_err_t rc;
osal_timer_t timer;
uint32_t serialized_len = 0;
if (!connect_opt->keep_alive_interval) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
if (!osal_timer_is_expired(&client->ping_timer)) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
if (client->ping_outstanding >= MQTT_PING_RETRY_TIMES) {
// reaching here means we haven't received any MQTT packet for a long time(keep_alive_interval)
QCLOUD_LOG_E("fail to recv MQTT msg.");
QCLOUD_FUNC_EXIT_RC(mqtt_yield_try_disconnect(client));
}
/* there is no ping outstanding - send one */
osal_mutex_lock(client->tx_lock);
rc = mqtt_common_serialize_zero_payload_packet(client->tx_buffer, sizeof(client->tx_buffer), MQTT_PACKET_TYPE_PINGREQ, &serialized_len);
if (QCLOUD_ERR_SUCCESS != rc) {
osal_mutex_unlock(client->tx_lock);
QCLOUD_FUNC_EXIT_RC(rc);
}
/* send the ping packet */
osal_timer_init(&timer);
do {
osal_timer_countdown_ms(&timer, client->command_timeout);
rc = mqtt_glue_packet_send(client, serialized_len, &timer);
} while (QCLOUD_ERR_SUCCESS != rc && (try++ < 3));
if (QCLOUD_ERR_SUCCESS != rc) {
osal_mutex_unlock(client->tx_lock);
// if send a PING fails, propably the connection is not OK and we decide to disconnect and begin reconnection attempts
QCLOUD_LOG_E("fail to send PING request.");
rc = mqtt_yield_try_disconnect(client);
QCLOUD_FUNC_EXIT_RC(rc);
}
osal_mutex_unlock(client->tx_lock);
osal_mutex_lock(client->global_lock);
++client->ping_outstanding;
/* start a timer to wait for PINGRESP from server */
osal_timer_countdown(&client->ping_timer, QCLOUD_MIN(5, connect_opt->keep_alive_interval / 2));
osal_mutex_unlock(client->global_lock);
QCLOUD_LOG_D("PING request %u sent.", client->ping_outstanding);
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_SUCCESS);
}
__QCLOUD_API__ qcloud_err_t qcloud_mqtt_yield(qcloud_mqtt_client_t *client, mqtt_connect_opt_t *connect_opt, uint32_t timeout_ms)
{
QCLOUD_FUNC_ENTRY;
QCLOUD_POINTER_SANITY_CHECK(client, QCLOUD_ERR_INVAL);
QCLOUD_NUMBERIC_SANITY_CHECK(timeout_ms, QCLOUD_ERR_INVAL);
qcloud_err_t rc = QCLOUD_ERR_SUCCESS;
osal_timer_t timer;
uint8_t packet_type;
// 1. 检查连接是否已经手动断开
if (!qcloud_mqtt_client_is_connected(client)) {
if (client->is_manually_disconnected) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_MANUALLY_DISCONNECTED);
} else if (client->auto_connect_state != QCLOUD_AUTO_CONN_STATE_ENABLED) {
QCLOUD_FUNC_EXIT_RC(QCLOUD_ERR_MQTT_NO_CONN);
}
}
osal_timer_init(&timer);
osal_timer_countdown_ms(&timer, timeout_ms);
// 3. 循环读取消息以及心跳包管理
while (!osal_timer_is_expired(&timer)) {
if (!qcloud_mqtt_client_is_connected(client)) {
if (client->reconnect_try_duration > QCLOUD_MQTT_RECONNECT_TRY_THRESHOLD) {
rc = QCLOUD_ERR_MQTT_RECONNECT_TIMEOUT;
break;
}
rc = mqtt_yield_try_reconnect(client, connect_opt);
continue;
}
rc = mqtt_glue_spin(client, &timer, &packet_type);
if (rc == QCLOUD_ERR_SUCCESS) {
/* check list of ACK pend list to remove node that is timeout */
mqtt_glue_ack_list_scan(client);
rc = mqtt_yield_keep_alive(client, connect_opt);
} else if (rc == QCLOUD_ERR_SSL_READ_TIMEOUT ||
rc == QCLOUD_ERR_SSL_READ ||
rc == QCLOUD_ERR_TCP_PEER_SHUTDOWN ||
rc == QCLOUD_ERR_TCP_READ_FAIL) {
QCLOUD_LOG_E("network failed, MQTT disconnect %d", rc);
rc = mqtt_yield_try_disconnect(client);
}
if (rc == QCLOUD_ERR_MQTT_NO_CONN) {
++client->network_disconnect_counter;
if (client->auto_connect_state != QCLOUD_AUTO_CONN_STATE_ENABLED) {
break;
}
client->reconnect_try_duration = QCLOUD_MQTT_RECONNECT_TRY_INITIAL;
osal_timer_countdown_ms(&client->reconnect_timer, client->reconnect_try_duration);
// 如果超时时间到了,则会直接返回
rc = QCLOUD_ERR_MQTT_ATTEMPTING_RECONNECT;
} else if (rc != QCLOUD_ERR_SUCCESS) {
break;
}
}
QCLOUD_FUNC_EXIT_RC(rc);
}
#ifdef __cplusplus
}
#endif
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/include/qcloud_utils/qcloud_json.h
|
<filename>components/connectivity/TencentCloud_SDK/source/include/qcloud_utils/qcloud_json.h
/*
* Copyright (c) 2017-2019 Tencent Group. All rights reserved.
* 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 __JSON_PARSER_H__
#define __JSON_PARSER_H__
/**
The descriptions of the json value node type
**/
enum JSONTYPE {
JSNONE = -1,
JSSTRING = 0,
JSOBJECT,
JSARRAY,
JSNUMBER,
JSBOOLEAN,
JSNULL,
JSTYPEMAX
};
/**
The error codes produced by the JSON parsers
**/
enum JSON_PARSE_CODE {
JSON_PARSE_ERR,
JSON_PARSE_OK,
JSON_PARSE_FINISH
};
/**
The return codes produced by the JSON parsers
**/
enum JSON_PARSE_RESULT {
JSON_RESULT_ERR = -1,
JSON_RESULT_OK
};
typedef int (*json_parse_cb)(char *p_cName, int iNameLen, char *p_cValue, int iValueLen, int iValueType,
void *p_Result);
/**
* @brief Parse the JSON string, and iterate through all keys and values,
* then handle the keys and values by callback function.
*
* @param[in] p_cJsonStr @n The JSON string
* @param[in] iStrLen @n The JSON string length
* @param[in] pfnCB @n Callback function
* @param[out] p_CBData @n User data
* @return JSON_RESULT_OK success, JSON_RESULT_ERR failed
* @see None.
* @note None.
**/
int json_parse_name_value(char *p_cJsonStr, int iStrLen, json_parse_cb pfnCB, void *p_CBData);
/**
* @brief Get the value by a specified key from a json string
*
* @param[in] p_cJsonStr @n the JSON string
* @param[in] iStrLen @n the JSON string length
* @param[in] p_cName @n the specified key string
* @param[out] p_iValueLen @n the value length
* @param[out] p_iValueType @n the value type
* @return A pointer to the value
* @see None.
* @note None.
**/
char *json_get_value_by_name(char *p_cJsonStr, int iStrLen, char *p_cName, int *p_iValueLen, int *p_iValueType);
/**
* @brief Get the JSON object point associate with a given type.
*
* @param[in] type @n The object type
* @param[in] str @n The JSON string
* @returns The json object point with the given field type.
* @see None.
* @note None.
*/
char *json_get_object(int type, char *str);
char *json_get_next_object(int type, char *str, char **key, int *key_len, char **val, int *val_len, int *val_type);
/**
* @brief retrieve each key&value pair from the json string
*
* @param[in] str @n Json string to revolve
* @param[in] pos @n cursor
* @param[out] key @n pointer to the next Key object
* @param[out] klen @n Key object length
* @param[out] val @n pointer to the next Value object
* @param[out] vlen @n Value object length
* @param[out] vtype @n Value object type(digital, string, object, array)
* @see None.
* @note None.
*/
#define json_object_for_each_kv(str, pos, key, klen, val, vlen, vtype) \
for (pos = json_get_object(JSOBJECT, str); \
pos!=0 && *pos!=0 && (pos=json_get_next_object(JSOBJECT, pos, &key, &klen, &val, &vlen, &vtype))!=0; )
/**
* @brief retrieve each entry from the json array
*
* @param[in] str @n Json array to revolve
* @param[in] pos @n cursor
* @param[out] entry @n pointer to the next entry from the array
* @param[out] len @n entry length
* @param[out] type @n entry type(digital, string, object, array)
* @see None.
* @note None.
*/
#define json_array_for_each_entry(str, pos, entry, len, type) \
for (pos = json_get_object(JSARRAY, str); \
pos!=0 && *pos!=0 && (pos=json_get_next_object(JSARRAY, ++pos, 0, 0, &entry, &len, &type))!=0; )
/**
* @brief backup the last character to register parameters,
* and set the end character with '\0'
*
* @param[in] json_str @n json string
* @param[in] str_len @n json string lenth
* @param[out] register @n used to backup the last character
* @see None.
* @note None.
*/
#define backup_json_str_last_char(json_str, str_len, register) { \
register = *((char *)json_str + str_len); \
*((char *)json_str + str_len) = '\0'; \
}
/**
* @brief restore the last character from register parameters
*
* @param[in] json_str @n json string
* @param[in] str_len @n json string lenth
* @param[in] register @n used to restore the last character
* @see None.
* @note None.
*/
#define restore_json_str_last_char(json_str, str_len, register) { \
*((char *)json_str + str_len) = register; \
}
#endif /* __JSON_PARSER_H__ */
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/qcloud-iot-hub-sdk-3.1.2/3rdparty/sdk_src/utils/qcloud_iot_ca.c
|
<gh_stars>1-10
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "qcloud_iot_ca.h"
#include "qcloud_iot_import.h"
#include <stdlib.h>
#ifndef AUTH_WITH_NOTLS
#if defined(AUTH_MODE_CERT) || defined(DEV_DYN_REG_ENABLED)
static const char *iot_ca_crt = \
{
"-----BEGIN CERTIFICATE-----\r\n"
"<KEY>" \
"BAYTAkNOMRIwEAYDVQQIDAlHdWFuZ0RvbmcxETAPBgNVBAcMCFNoZW5aaGVuMRAw\r\n" \
"DgYDVQQKDAdUZW5jZW50MRcwFQYDVQQLDA5UZW5jZW50IElvdGh1YjEYMBYGA1UE\r\n" \
"AwwPd3d3LnRlbmNlbnQuY29tMB4XDTE3MTEyNzA0MjA1OVoXDTMyMTEyMzA0MjA1\r\n" \
"OVoweTELMAkGA1UEBhMCQ04xEjAQBgNVBAgMCUd1YW5nRG9uZzERMA8GA1UEBwwI\r\n" \
"<KEY>" \
"aHViMRgwFgYDVQQDDA93d3cudGVuY2VudC5jb20wggEiMA0GCSqGSIb3DQEBAQUA\r\n" \
"A4IBDwAwggEKAoIBAQDVxwDZRVkU5WexneBEkdaKs4ehgQbzpbufrWo5Lb5gJ3i0\r\n" \
"<KEY>" \
"<KEY>" \
"FJOlPPd1idKtFMVNG6LGXEwS/TPElE+grYOxwB7Anx3iC5ZpE5lo5tTioFTHzqbT\r\n" \
"<KEY>" \
"<KEY>W\r\n" \
"<KEY>" \
"mJO7zH4ALzAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQDRSjXnBc3T\r\n" \
"d9VmtTCuALXrQELY8KtM+cXYYNgtodHsxmrRMpJofsPGiqPfb82klvswpXxPK8Xx\r\n" \
"SuUUo74Fo+AEyJxMrRKlbJvlEtnpSilKmG6rO9+bFq3nbeOAfat4lPl0DIscWUx3\r\n" \
"ajXtvMCcSwTlF8rPgXbOaSXZidRYNqSyUjC2Q4m93Cv+KlyB+FgOke8x4aKAkf5p\r\n" \
"XR8i1BN1OiMTIRYhGSfeZbVRq5kTdvtahiWFZu9DGO+hxDZObYGIxGHWPftrhBKz\r\n" \
"RT16Amn780rQLWojr70q7o7QP5tO0wDPfCdFSc6CQFq/ngOzYag0kJ2F+O5U6+kS\r\n" \
"QVrcRBDxzx/G\r\n" \
"-----END CERTIFICATE-----"
};
#endif
#ifdef OTA_USE_HTTPS
static const char *iot_https_ca_crt = \
{
"-----BEGIN CERTIFICATE-----\r\n"
"MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\r\n"
"A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\r\n"
"b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw\r\n"
"MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\r\n"
"YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT\r\n"
"aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ\r\n"
"jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp\r\n"
"xy0Sy6scTHAHoT<KEY>dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp\r\n"
"<KEY>"
"<KEY>"
"<KEY>"
"9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E\r\n"
"BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B\r\n"
"AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz\r\n"
"yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE\r\n"
"38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\r\n"
"AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\r\n"
"DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\r\n"
"HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\r\n"
"-----END CERTIFICATE-----\r\n"
"-----BEGIN CERTIFICATE-----\r\n"
"MIIEaTCCA1GgAwIBAgILBAAAAAABRE7wQkcwDQYJKoZIhvcNAQELBQAwVzELMAkG\r\n"
"A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\r\n"
"b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xNDAyMjAxMDAw\r\n"
"MDBaFw0yNDAyMjAxMDAwMDBaMGYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\r\n"
"YWxTaWduIG52LXNhMTwwOgYDVQQDEzNHbG9iYWxTaWduIE9yZ2FuaXphdGlvbiBW\r\n"
"YWxpZGF0aW9uIENBIC0gU0hBMjU2IC0gRzIwggEiMA0GCSqGSIb3DQEBAQUAA4IB\r\n"
"DwAwggEKAoIBAQDHDmw/I5N/zHClnSDDDlM/fsBOwphJykfVI+8DNIV0yKMCLkZc\r\n"
"C33JiJ1Pi/D4nGyMVTXbv/Kz6vvjVudKRtkTIso21ZvBqOOWQ5PyDLzm+ebomchj\r\n"
"SHh/VzZpGhkdWtHUfcKc1H/hgBKueuqI6lfYygoKOhJJomIZeg0k9zfrtHOSewUj\r\n"
"mxK1zusp36QUArkBpdSmnENkiN74fv7j9R7l/tyjqORmMdlMJekYuYlZCa7pnRxt\r\n"
"<KEY>"
"<KEY>"
"Af8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQUlt5h8b0cFilT\r\n"
"HMDMfTuDAEDmGnwwRwYDVR0gBEAwPjA8BgRVHSAAMDQwMgYIKwYBBQUHAgEWJmh0\r\n"
"dHBzOi8vd3d3Lmdsb2JhbHNpZ24uY29tL3JlcG9zaXRvcnkvMDMGA1UdHwQsMCow\r\n"
"KKAmoCSGImh0dHA6Ly9jcmwuZ2xvYmFsc2lnbi5uZXQvcm9vdC5jcmwwPQYIKwYB\r\n"
"BQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vb2NzcC5nbG9iYWxzaWduLmNv\r\n"
"bS9yb290cjEwHwYDVR0jBBgwFoAUYHtmGkUNl8qJUC99BM00qP/8/UswDQYJKoZI\r\n"
"hvcNAQELBQADggEBAEYq7l69rgFgNzERhnF0tkZJyBAW/i9iIxerH4f4gu3K3w4s\r\n"
"32R1juUYcqeMOovJrKV3UPfvnqTgoI8UV6MqX+x+bRDmuo2wCId2Dkyy2VG7EQLy\r\n"
"XN0cvfNVlg/UBsD84iOKJHDTu/B5GqdhcIOKrwbFINihY9Bsrk8y1658GEV1BSl3\r\n"
"30JAZGSGvip2CTFvHST0mdCF/vIhCPnG9vHQWe3WVjwIKANnuvD58ZAWR65n5ryA\r\n"
"SOlCdjSXVWkkDoPWoC209fN5ikkodBpBocLTJIg1MGCUF7ThBCIxPTsvFwayuJ2G\r\n"
"K1pp74P1S8SqtCr4fKGxhZSM9AyHDPSsQPhZSZg=\r\n"
"-----END CERTIFICATE-----"
};
#endif
#endif
const char *iot_ca_get() {
#ifndef AUTH_WITH_NOTLS
#if defined(AUTH_MODE_CERT) || defined(DEV_DYN_REG_ENABLED)
return iot_ca_crt;
#else
return NULL;
#endif
#else
return NULL;
#endif
}
const char *iot_https_ca_get() {
#ifndef AUTH_WITH_NOTLS
#ifdef OTA_USE_HTTPS
return iot_https_ca_crt;
#else
return NULL;
#endif
#else
return NULL;
#endif
}
#ifdef __cplusplus
}
#endif
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/external/infineon/optiga/comms/ifx_i2c/ifx_i2c_config.c
|
/**
* MIT License
*
* Copyright (c) 2018 Infineon Technologies AG
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE
*
*
* \file ifx_i2c_config.c
*
* \brief This file provides the ifx i2c platform specific context configurations.
*
* \addtogroup grIFXI2C
* @{
*/
/***********************************************************************************************************************
* HEADER FILES
**********************************************************************************************************************/
// Protocol Stack Includes
#include "optiga/pal/pal_ifx_i2c_config.h"
#include "optiga/ifx_i2c/ifx_i2c_config.h"
/***********************************************************************************************************************
* MACROS
**********************************************************************************************************************/
/***********************************************************************************************************************
* ENUMS
**********************************************************************************************************************/
/***********************************************************************************************************************
* DATA STRUCTURES
***********************************************************************************************************************/
/** @brief This is IFX I2C context. Only one context is supported per slave.*/
//lint --e{785} suppress "Only required fields are initialized, the rest are handled by consumer of this structure"
ifx_i2c_context_t ifx_i2c_context_0 =
{
/// Slave address
0x30,
/// i2c-master frequency
400,
/// IFX-I2C frame size
#if (DL_MAX_FRAME_SIZE >= 0x0115)
0x0115,
#else
DL_MAX_FRAME_SIZE,
#endif
/// Vdd pin
&optiga_vdd_0,
/// Reset pin
&optiga_reset_0,
/// optiga pal i2c context
&optiga_pal_i2c_context_0,
};
/***********************************************************************************************************************
* GLOBAL
***********************************************************************************************************************/
/***********************************************************************************************************************
* LOCAL ROUTINES
***********************************************************************************************************************/
/***********************************************************************************************************************
* API PROTOTYPES
**********************************************************************************************************************/
/**
* @}
**/
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/qcloud-iot-hub-sdk-3.1.2/3rdparty/sdk_src/utils/utils_hmac.c
|
<reponame>umaru724/TencentOS_E53_IA1
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.h>
#include "qcloud_iot_export_log.h"
#include "utils_md5.h"
#include "utils_sha1.h"
#include "utils_hmac.h"
#define KEY_IOPAD_SIZE 64
#define MD5_DIGEST_SIZE 16
#define SHA1_DIGEST_SIZE 20
void utils_hmac_md5(const char *msg, int msg_len, char *digest, const char *key, int key_len)
{
if((NULL == msg) || (NULL == digest) || (NULL == key)) {
Log_e("parameter is Null,failed!");
return;
}
if(key_len > KEY_IOPAD_SIZE) {
Log_e("key_len > size(%d) of array",KEY_IOPAD_SIZE);
return;
}
iot_md5_context context;
unsigned char k_ipad[KEY_IOPAD_SIZE]; /* inner padding - key XORd with ipad */
unsigned char k_opad[KEY_IOPAD_SIZE]; /* outer padding - key XORd with opad */
unsigned char out[MD5_DIGEST_SIZE];
int i;
/* start out by storing key in pads */
memset(k_ipad, 0, sizeof(k_ipad));
memset(k_opad, 0, sizeof(k_opad));
memcpy(k_ipad, key, key_len);
memcpy(k_opad, key, key_len);
/* XOR key with ipad and opad values */
for (i = 0; i < KEY_IOPAD_SIZE; i++) {
k_ipad[i] ^= 0x36;
k_opad[i] ^= 0x5c;
}
/* perform inner MD5 */
utils_md5_init(&context); /* init context for 1st pass */
utils_md5_starts(&context); /* setup context for 1st pass */
utils_md5_update(&context, k_ipad, KEY_IOPAD_SIZE); /* start with inner pad */
utils_md5_update(&context, (unsigned char *) msg, msg_len); /* then text of datagram */
utils_md5_finish(&context, out); /* finish up 1st pass */
/* perform outer MD5 */
utils_md5_init(&context); /* init context for 2nd pass */
utils_md5_starts(&context); /* setup context for 2nd pass */
utils_md5_update(&context, k_opad, KEY_IOPAD_SIZE); /* start with outer pad */
utils_md5_update(&context, out, MD5_DIGEST_SIZE); /* then results of 1st hash */
utils_md5_finish(&context, out); /* finish up 2nd pass */
for (i = 0; i < MD5_DIGEST_SIZE; ++i) {
digest[i * 2] = utils_hb2hex(out[i] >> 4);
digest[i * 2 + 1] = utils_hb2hex(out[i]);
}
}
void utils_hmac_sha1(const char *msg, int msg_len, char *digest, const char *key, int key_len)
{
if((NULL == msg) || (NULL == digest) || (NULL == key)) {
Log_e("parameter is Null,failed!");
return;
}
if(key_len > KEY_IOPAD_SIZE) {
Log_e("key_len > size(%d) of array",KEY_IOPAD_SIZE);
return;
}
iot_sha1_context context;
unsigned char k_ipad[KEY_IOPAD_SIZE]; /* inner padding - key XORd with ipad */
unsigned char k_opad[KEY_IOPAD_SIZE]; /* outer padding - key XORd with opad */
unsigned char out[SHA1_DIGEST_SIZE];
int i;
/* start out by storing key in pads */
memset(k_ipad, 0, sizeof(k_ipad));
memset(k_opad, 0, sizeof(k_opad));
memcpy(k_ipad, key, key_len);
memcpy(k_opad, key, key_len);
/* XOR key with ipad and opad values */
for (i = 0; i < KEY_IOPAD_SIZE; i++) {
k_ipad[i] ^= 0x36;
k_opad[i] ^= 0x5c;
}
/* perform inner SHA */
utils_sha1_init(&context); /* init context for 1st pass */
utils_sha1_starts(&context); /* setup context for 1st pass */
utils_sha1_update(&context, k_ipad, KEY_IOPAD_SIZE); /* start with inner pad */
utils_sha1_update(&context, (unsigned char *) msg, msg_len); /* then text of datagram */
utils_sha1_finish(&context, out); /* finish up 1st pass */
/* perform outer SHA */
utils_sha1_init(&context); /* init context for 2nd pass */
utils_sha1_starts(&context); /* setup context for 2nd pass */
utils_sha1_update(&context, k_opad, KEY_IOPAD_SIZE); /* start with outer pad */
utils_sha1_update(&context, out, SHA1_DIGEST_SIZE); /* then results of 1st hash */
utils_sha1_finish(&context, out); /* finish up 2nd pass */
for (i = 0; i < SHA1_DIGEST_SIZE; ++i) {
digest[i * 2] = utils_hb2hex(out[i] >> 4);
digest[i * 2 + 1] = utils_hb2hex(out[i]);
}
}
|
umaru724/TencentOS_E53_IA1
|
components/connectivity/TencentCloud_SDK/source/src/port/TencentOS_tiny/osal_tls.c
|
<gh_stars>1-10
/*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 <stdint.h>
#include <string.h>
#include <errno.h>
#ifdef __cplusplus
extern "C" {
#endif
#include "tos_k.h"
#include "qcloud.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/net_sockets.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"
#include "mbedtls/debug.h"
#define DEBUG_LEVEL 0
#if (QCLOUD_CFG_AUTH_MODE == QCLOUD_AUTH_MODE_KEY)
static const int ciphersuites[] = {MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA, 0};
#endif
/**
* @brief 用于保存SSL连接相关数据结构
*/
typedef struct tls_paramter_st {
mbedtls_net_context socket_fd; // socket文件描述符
mbedtls_entropy_context entropy; // 保存熵配置
mbedtls_ctr_drbg_context ctr_drbg; // 随机数生成器
mbedtls_ssl_context ssl; // 保存SSL基本数据
mbedtls_ssl_config ssl_conf; // TSL/TLS配置信息
#if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_x509_crt ca_cert; // ca证书信息
mbedtls_x509_crt client_cert; // 客户端证书信息
#endif
mbedtls_pk_context private_key; // 客户端私钥信息
} tls_param_t;
/**
* @brief 释放mbedtls开辟的内存
*/
static void mbedtls_tls_param_free(tls_param_t *tls_paramter)
{
mbedtls_net_free(&tls_paramter->socket_fd);
#if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_x509_crt_free(&tls_paramter->client_cert);
mbedtls_x509_crt_free(&tls_paramter->ca_cert);
mbedtls_pk_free(&tls_paramter->private_key);
#endif
mbedtls_ssl_free(&tls_paramter->ssl);
mbedtls_ssl_config_free(&tls_paramter->ssl_conf);
mbedtls_ctr_drbg_free(&tls_paramter->ctr_drbg);
mbedtls_entropy_free(&tls_paramter->entropy);
osal_free(tls_paramter);
}
/**
* @brief mbedtls库初始化
*
* 1. 执行mbedtls库相关初始化函数
* 2. 随机数生成器
* 3. 加载CA证书, 客户端证书及私钥文件/设置psk
*
* @param pDataParams TLS连接相关数据结构
* @param pConnectParams TLS证书密钥相关
* @return 返回QCLOUD_ERR_SUCCESS, 表示成功
*/
static void mbedtls_debug(void *ctx, int level, const char *file, int line, const char *str)
{
QCLOUD_LOG_I("[mbedTLS]:[%s]:[%d]: %s\r\n", file, line, str);
}
static int mbedtls_client_init(tls_param_t *tls_param, qcloud_tls_opt_t *tls_opt)
{
int ret = QCLOUD_ERR_SUCCESS;
#if defined(MBEDTLS_DEBUG_C)
mbedtls_debug_set_threshold(DEBUG_LEVEL);
#endif
mbedtls_net_init(&tls_param->socket_fd);
mbedtls_ssl_init(&tls_param->ssl);
mbedtls_ssl_config_init(&tls_param->ssl_conf);
mbedtls_ctr_drbg_init(&tls_param->ctr_drbg);
#if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_x509_crt_init(&tls_param->ca_cert);
mbedtls_x509_crt_init(&tls_param->client_cert);
mbedtls_pk_init(&tls_param->private_key);
#endif
mbedtls_entropy_init(&tls_param->entropy);
mbedtls_ssl_conf_dbg(&tls_param->ssl_conf, mbedtls_debug, NULL);
// 随机数, 增加custom参数, 目前为NULL
if ((ret = mbedtls_ctr_drbg_seed(&tls_param->ctr_drbg, mbedtls_entropy_func,
&tls_param->entropy, NULL, 0)) != 0) {
QCLOUD_LOG_E("mbedtls_ctr_drbg_seed failed returned -0x%04x", -ret);
return QCLOUD_ERR_SSL_INIT;
}
#if defined(MBEDTLS_X509_CRT_PARSE_C)
if (tls_opt->ca_cert != NULL) {
if ((ret = mbedtls_x509_crt_parse(&tls_param->ca_cert, (const unsigned char *)tls_opt->ca_cert,
(tls_opt->ca_cert_len + 1)))) {
QCLOUD_LOG_E("parse ca crt failed returned -0x%04x", -ret);
return QCLOUD_ERR_SSL_CERT;
}
}
#endif
#if (QCLOUD_CFG_AUTH_MODE == QCLOUD_AUTH_MODE_CERT)
if (tls_opt->cert_path != NULL && tls_opt->priv_key_path != NULL) {
#if defined(MBEDTLS_X509_CRT_PARSE_C)
if ((ret = mbedtls_x509_crt_parse_file(&tls_param->client_cert, tls_opt->cert_path)) != 0) {
QCLOUD_LOG_E("load client cert file failed returned 0x%x", ret<0?-ret:ret);
return QCLOUD_ERR_SSL_CERT;
}
#endif
if ((ret = mbedtls_pk_parse_keyfile(&tls_param->private_key, tls_opt->priv_key_path, "")) != 0) {
QCLOUD_LOG_E("load client key file failed returned 0x%x", ret < 0 ? -ret : ret);
return QCLOUD_ERR_SSL_CERT;
}
} else {
QCLOUD_LOG_E("cert_file/key_file is empty!|cert_file=%s|key_file=%s", tls_opt->cert_path, tls_opt->priv_key_path);
}
#else
if (tls_opt->psk != NULL && tls_opt->psk_id != NULL) {
const char *psk_id = tls_opt->psk_id;
ret = mbedtls_ssl_conf_psk(&tls_param->ssl_conf, (unsigned char *)tls_opt->psk, tls_opt->psk_len,
(const unsigned char *)psk_id, strlen(psk_id));
} else {
QCLOUD_LOG_D("psk/pskid is empty!|psk=%s|psd_id=%s", tls_opt->psk, tls_opt->psk_id);
}
if (0 != ret) {
QCLOUD_LOG_E("mbedtls_ssl_conf_psk fail: -0x%x", -ret);
return ret;
}
#endif
return QCLOUD_ERR_SUCCESS;
}
/**
* @brief 建立TCP连接
*
* @param socket_fd Socket描述符
* @param host 服务器主机名
* @param port 服务器端口地址
* @return 返回QCLOUD_ERR_SUCCESS, 表示成功
*/
int mbedtls_tcp_connect(mbedtls_net_context *socket_fd, const char *host, int port)
{
int ret = 0;
char port_str[6];
osal_snprintf(port_str, 6, "%d", port);
if ((ret = mbedtls_net_connect(socket_fd, host, port_str, MBEDTLS_NET_PROTO_TCP)) != 0) {
QCLOUD_LOG_E("tcp connect failed returned -0x%04x", -ret);
switch (ret) {
case MBEDTLS_ERR_NET_SOCKET_FAILED:
return QCLOUD_ERR_TCP_SOCKET_FAILED;
case MBEDTLS_ERR_NET_UNKNOWN_HOST:
return QCLOUD_ERR_TCP_UNKNOWN_HOST;
default:
return QCLOUD_ERR_TCP_CONNECT;
}
}
#if 0
if ((ret = mbedtls_net_set_block(socket_fd)) != 0) {
QCLOUD_LOG_E("set block faliled returned -0x%04x", -ret);
return QCLOUD_ERR_TCP_CONNECT;
}
#endif
return QCLOUD_ERR_SUCCESS;
}
/**
* @brief 在该函数中可对服务端证书进行自定义的校验
*
* 这种行为发生在握手过程中, 一般是校验连接服务器的主机名与服务器证书中的CN或SAN的域名信息是否一致
* 不过, mbedtls库已经实现该功能, 可以参考函数 `mbedtls_x509_crt_verify_with_profile`
*
* @param hostname 连接服务器的主机名
* @param crt x509格式的证书
* @param depth
* @param flags
* @return
*/
#if defined(MBEDTLS_X509_CRT_PARSE_C)
static int qcloud_server_certificate_verify(void *hostname, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
{
return *flags;
}
#endif
__QCLOUD_OSAL__ void *osal_tls_connect(qcloud_tls_opt_t *tls_opt, const char *host, int port)
{
int ret = 0;
tls_param_t *tls_param = NULL;
if (!tls_opt) {
return NULL;
}
tls_param = (tls_param_t *)osal_malloc(sizeof(tls_param_t));
if (!tls_param) {
return NULL;
}
if ((ret = mbedtls_client_init(tls_param, tls_opt)) != QCLOUD_ERR_SUCCESS) {
goto error;
}
QCLOUD_LOG_D(" Connecting to /%s/%d...", host, port);
if ((ret = mbedtls_tcp_connect(&tls_param->socket_fd, host, port)) != QCLOUD_ERR_SUCCESS) {
goto error;
}
QCLOUD_LOG_D(" Setting up the SSL/TLS structure...");
if ((ret = mbedtls_ssl_config_defaults(&tls_param->ssl_conf, MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
QCLOUD_LOG_E("mbedtls_ssl_config_defaults failed returned -0x%04x", -ret);
goto error;
}
#if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_conf_verify(&tls_param->ssl_conf, qcloud_server_certificate_verify, (void *)host);
mbedtls_ssl_conf_authmode(&tls_param->ssl_conf, MBEDTLS_SSL_VERIFY_REQUIRED);
#endif
mbedtls_ssl_conf_rng(&tls_param->ssl_conf, mbedtls_ctr_drbg_random, &tls_param->ctr_drbg);
#if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_conf_ca_chain(&tls_param->ssl_conf, &tls_param->ca_cert, NULL);
if ((ret = mbedtls_ssl_conf_own_cert(&tls_param->ssl_conf,
&tls_param->client_cert, &tls_param->private_key)) != 0) {
QCLOUD_LOG_E("mbedtls_ssl_conf_own_cert failed returned 0x%04x", -ret);
goto error;
}
#endif
mbedtls_ssl_conf_read_timeout(&tls_param->ssl_conf, tls_opt->timeout);
if ((ret = mbedtls_ssl_setup(&tls_param->ssl, &tls_param->ssl_conf)) != 0) {
QCLOUD_LOG_E("mbedtls_ssl_setup failed returned 0x%04x", -ret);
goto error;
}
#if (QCLOUD_CFG_AUTH_MODE == QCLOUD_AUTH_MODE_KEY)
// 选择加密套件代码,以后不通加密方式合并端口的时候可以用到
if(tls_opt->psk != NULL) {
mbedtls_ssl_conf_ciphersuites(&tls_param->ssl_conf, ciphersuites);
}
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C)
// Set the hostname to check against the received server certificate and sni
if ((ret = mbedtls_ssl_set_hostname(&tls_param->ssl, host)) != 0) {
QCLOUD_LOG_E("mbedtls_ssl_set_hostname failed returned 0x%04x", -ret);
goto error;
}
#endif
mbedtls_ssl_set_bio(&tls_param->ssl, &tls_param->socket_fd, mbedtls_net_send, mbedtls_net_recv,
mbedtls_net_recv_timeout);
QCLOUD_LOG_D("Performing the SSL/TLS handshake...");
while ((ret = mbedtls_ssl_handshake(&tls_param->ssl)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
QCLOUD_LOG_E("mbedtls_ssl_handshake failed returned 0x%04x", -ret);
#if defined(MBEDTLS_X509_CRT_PARSE_C)
if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
QCLOUD_LOG_E("Unable to verify the server's certificate");
}
#endif
goto error;
}
}
if ((ret = mbedtls_ssl_get_verify_result(&tls_param->ssl)) != 0) {
QCLOUD_LOG_E("mbedtls_ssl_get_verify_result failed returned 0x%04x", -ret);
goto error;
}
mbedtls_ssl_conf_read_timeout(&tls_param->ssl_conf, 100);
return tls_param;
error:
mbedtls_tls_param_free(tls_param);
return NULL;
}
__QCLOUD_OSAL__ void osal_tls_disconnect(void *handle)
{
int ret = 0;
tls_param_t *tls_param;
if (!handle) {
QCLOUD_LOG_D("handle is NULL");
return;
}
tls_param = (tls_param_t *)handle;
do {
ret = mbedtls_ssl_close_notify(&tls_param->ssl);
} while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
mbedtls_tls_param_free(tls_param);
}
__QCLOUD_OSAL__ qcloud_err_t osal_tls_write(void *handle, const void *buf, size_t len, uint32_t timeout, size_t *write_len)
{
QCLOUD_POINTER_SANITY_CHECK(handle, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(write_len, QCLOUD_ERR_INVAL);
osal_timer_t timer;
tls_param_t *tls_param;
int error = QCLOUD_FALSE;
int write_rc = 0;
size_t written_so_far;
tls_param = (tls_param_t *)handle;
osal_timer_init(&timer);
osal_timer_countdown_ms(&timer, timeout);
for (written_so_far = 0; written_so_far < len && !osal_timer_is_expired(&timer); written_so_far += write_rc) {
while (!osal_timer_is_expired(&timer) &&
(write_rc = mbedtls_ssl_write(&tls_param->ssl, (uint8_t *)buf + written_so_far, len - written_so_far)) <= 0) {
if (write_rc != MBEDTLS_ERR_SSL_WANT_READ && write_rc != MBEDTLS_ERR_SSL_WANT_WRITE) {
QCLOUD_LOG_E("tls_write failed 0x%04x", -write_rc);
error = QCLOUD_TRUE;
break;
}
}
if (error) {
break;
}
}
*write_len = written_so_far;
if (error) {
return QCLOUD_ERR_SSL_WRITE;
} else if (osal_timer_is_expired(&timer) && written_so_far != len) {
return QCLOUD_ERR_SSL_WRITE_TIMEOUT;
}
return QCLOUD_ERR_SUCCESS;
}
__QCLOUD_OSAL__ qcloud_err_t osal_tls_read(void *handle, void *buf, size_t len, uint32_t timeout, size_t *read_len)
{
//mbedtls_ssl_conf_read_timeout(&(pParams->ssl_conf), timeout_ms); TODO:每次调用这个方法会导致read阻塞, 超时也不返回
// 这里使用非阻塞的方式, 具体的超时操作由上层做
QCLOUD_POINTER_SANITY_CHECK(handle, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(buf, QCLOUD_ERR_INVAL);
QCLOUD_POINTER_SANITY_CHECK(read_len, QCLOUD_ERR_INVAL);
osal_timer_t timer;
tls_param_t *tls_param = NULL;
*read_len = 0;
osal_timer_init(&timer);
osal_timer_countdown_ms(&timer, timeout);
tls_param = (tls_param_t *)handle;
do {
int read_rc = 0;
read_rc = mbedtls_ssl_read(&tls_param->ssl, (uint8_t *)buf + *read_len, len - *read_len);
if (read_rc > 0) {
*read_len += read_rc;
} else if (read_rc == 0 ||
(read_rc != MBEDTLS_ERR_SSL_WANT_WRITE &&
read_rc != MBEDTLS_ERR_SSL_WANT_READ &&
read_rc != MBEDTLS_ERR_SSL_TIMEOUT)) {
QCLOUD_LOG_E("tls_read failed: 0x%04x", -read_rc);
return QCLOUD_ERR_SSL_READ;
}
if (osal_timer_is_expired(&timer)) {
break;
}
} while (*read_len < len);
if (len == *read_len) {
return QCLOUD_ERR_SUCCESS;
}
if (*read_len == 0) {
return QCLOUD_ERR_SSL_NOTHING_TO_READ;
} else {
return QCLOUD_ERR_SSL_READ_TIMEOUT;
}
}
#ifdef __cplusplus
}
#endif
|
umaru724/TencentOS_E53_IA1
|
platform/vendor_bsp/nordic/nRF5_SDK_15.3.0/examples/ant/experimental/ant_shared_channel/slave/asc_device_registry.h
|
/**
* This software is subject to the ANT+ Shared Source License
* www.thisisant.com/swlicenses
* Copyright (c) Garmin Canada Inc. 2014
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3) Neither the name of Garmin nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior
* written permission.
*
* The following actions are prohibited:
*
* 1) Redistribution of source code containing the ANT+ Network
* Key. The ANT+ Network Key is available to ANT+ Adopters.
* Please refer to http://thisisant.com to become an ANT+
* Adopter and access the key.
*
* 2) Reverse engineering, decompilation, and/or disassembly of
* software provided in binary form under this license.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE HEREBY
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; DAMAGE TO ANY DEVICE, LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE. SOME STATES DO NOT ALLOW
* THE EXCLUSION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE
* ABOVE LIMITATIONS MAY NOT APPLY TO YOU.
*
*/
#ifndef ASC_DEVICE_REGISTRY_H__
#define ASC_DEVICE_REGISTRY_H__
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/**@todo add two byte address support */
////////////////////////////////////////////////////////////////////////////////
// Module Description
////////////////////////////////////////////////////////////////////////////////
/*
* This module is responsible for management of the device registry used to store information about peripheral devices that have registered wih the hub
*/
////////////////////////////////////////////////////////////////////////////////
// Public Definitions
////////////////////////////////////////////////////////////////////////////////
#define MAX_DEVICES ((uint8_t) 0x0F)
#define INVALID_SHARED_ADDRESS ((uint8_t) 0x00)
#define DEVICEREGISTRY_EVENT_DEVICE_ADDED ((uint32_t)0x00000001)
#define DEVICEREGISTRY_EVENT_DEVICE_REMOVED ((uint32_t)0x00000002)
////////////////////////////////////////////////////////////////////////////////
// Public structs
////////////////////////////////////////////////////////////////////////////////
typedef struct
{
uint32_t shared_address;
uint32_t serial_number;
uint16_t model_number;
uint8_t hw_revision;
uint8_t sw_revision;
uint8_t missed_polls;
uint8_t poll_count;
} asc_device_t;
typedef struct
{
uint8_t count; //Total number of registered devices
uint32_t event_flags;
uint8_t highest_registered_address; //The highest valued address that is registered
asc_device_t devices[MAX_DEVICES];
} asc_device_registry_t;
////////////////////////////////////////////////////////////////////////////////
// Public Function Prototypes
////////////////////////////////////////////////////////////////////////////////
void deviceregistry_clear_event(asc_device_registry_t * const p_registry, uint32_t event);
void deviceregistry_setup(asc_device_registry_t * p_registry);
uint8_t deviceregistry_get_next_free_shared_address(asc_device_registry_t * p_registry);
uint8_t deviceregistry_get_first_registered_shared_address(asc_device_registry_t * p_registry);
uint8_t deviceregistry_get_next_registered_shared_address(asc_device_registry_t * p_registry, uint8_t previous_shared_address);
bool deviceregistry_add_device(asc_device_registry_t * p_registry, asc_device_t* p_device);
bool deviceregistry_remove_device(asc_device_registry_t * p_registry, uint8_t shared_address);
bool deviceregistry_is_full(asc_device_registry_t * p_registry);
asc_device_t* deviceregistry_get_device(asc_device_registry_t * p_registry, uint8_t shared_address);
bool deviceregistry_is_device_registered(asc_device_registry_t * p_registry, uint8_t shared_address);
#ifdef __cplusplus
}
#endif
#endif /* ASC_DEVICE_REGISTRY_H__ */
|
kr0st/fplog2
|
headers/udp_transport.h
|
#pragma once
#include <fplog_exceptions.h>
#include <sprot.h>
#include <random>
#ifndef _WIN32
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#define SOCKET int
#define SD_BOTH SHUT_RDWR
#define closesocket close
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
#else
#include <winsock2.h>
#endif
#include <mutex>
namespace sprot {
class Udp_Transport: public sprot::Extended_Transport_Interface
{
public:
union Ip_Address
{
unsigned char bytes[4];
unsigned int ip;
};
void enable(const sprot::Params& params);
void disable();
virtual size_t read(void* buf, size_t buf_size, Address& user_data = no_address, size_t timeout = infinite_wait);
virtual size_t write(const void* buf, size_t buf_size, Address& user_data, size_t timeout = infinite_wait);
Udp_Transport();
virtual ~Udp_Transport();
private:
SOCKET socket_;
bool enabled_;
std::recursive_mutex read_mutex_;
std::recursive_mutex write_mutex_;
unsigned char ip_[4];
unsigned short port_;
bool localhost_;
char* read_buffer_;
const int read_buffer_size_ = 1024 * 256;
int bytes_in_buffer_;
int read_position_ = 0;
int chaos_rate_ = 0;
int chaos_counter_ = 0;
std::mt19937 chaos_gen_;
};
};
|
kr0st/fplog2
|
headers/fplog.h
|
#pragma once
#include <string>
#include <set>
#include <vector>
#include <rapidjson/rapidjson.h>
#include <rapidjson/document.h>
#include <typeinfo>
#include <sprot.h>
#include <fplog_exceptions.h>
#include <algorithm>
#include <mutex>
#include <functional>
#ifdef FPLOG_EXPORT
#ifdef __linux__
#define FPLOG_API __attribute__ ((visibility("default")))
#else
#define FPLOG_API __declspec(dllexport)
#endif
#else
#ifdef __linux__
#define FPLOG_API
#endif
#ifdef __APPLE__
#define FPLOG_API
#endif
#ifdef _WIN32_WINNT
#define FPLOG_API __declspec(dllimport)
#endif
#endif
#if defined(__linux__) || defined(__APPLE__)
namespace fplog { std::string demangle_cpp_name(const char* mangled); };
#define CLASSNAME fplog::demangle_cpp_name(typeid(*this).name()).c_str()
#endif
#ifdef _WIN32_WINNT
#define CLASSNAME typeid(*this).name()
#endif
#define CLASSNAME_SHORT \
(strrchr(CLASSNAME,' ') \
? strrchr(CLASSNAME,' ')+1 \
: CLASSNAME \
)
#define FUNCTION_SHORT \
(strrchr(__FUNCTION__,':') \
? strrchr(__FUNCTION__,':')+1 \
: __FUNCTION__ \
)
#ifndef _WIN32_WINNT
#define FPL_TRACE(format, ...) fplog::Message(fplog::Prio::debug, fplog::get_facility(), format, ##__VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT)
#define FPL_INFO(format, ...) fplog::Message(fplog::Prio::info, fplog::get_facility(), format, ##__VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT)
#define FPL_WARN(format, ...) fplog::Message(fplog::Prio::warning, fplog::get_facility(), format, ##__VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT)
#define FPL_ERROR(format, ...) fplog::Message(fplog::Prio::error, fplog::get_facility(), format, ##__VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT)
#define FPL_CTRACE(format, ...) FPL_TRACE(format, ##__VA_ARGS__).set_class(CLASSNAME_SHORT)
#define FPL_CINFO(format, ...) FPL_INFO(format, ##__VA_ARGS__).set_class(CLASSNAME_SHORT)
#define FPL_CWARN(format, ...) FPL_WARN(format, ##__VA_ARGS__).set_class(CLASSNAME_SHORT)
#define FPL_CERROR(format, ...) FPL_ERROR(format, ##__VA_ARGS__).set_class(CLASSNAME_SHORT)
#else
#define FPL_TRACE(format, ...) fplog::Message(fplog::Prio::debug, fplog::get_facility(), format, __VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT)
#define FPL_INFO(format, ...) fplog::Message(fplog::Prio::info, fplog::get_facility(), format, __VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT)
#define FPL_WARN(format, ...) fplog::Message(fplog::Prio::warning, fplog::get_facility(), format, __VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT)
#define FPL_ERROR(format, ...) fplog::Message(fplog::Prio::error, fplog::get_facility(), format, __VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT)
#define FPL_CTRACE(format, ...) FPL_TRACE(format, __VA_ARGS__).set_class(CLASSNAME_SHORT)
#define FPL_CINFO(format, ...) FPL_INFO(format, __VA_ARGS__).set_class(CLASSNAME_SHORT)
#define FPL_CWARN(format, ...) FPL_WARN(format, __VA_ARGS__).set_class(CLASSNAME_SHORT)
#define FPL_CERROR(format, ...) FPL_ERROR(format, __VA_ARGS__).set_class(CLASSNAME_SHORT)
#endif
namespace fplogd
{
class Impl;
};
namespace fplog
{
struct FPLOG_API Facility
{
static const char* system; //message from some system component
static const char* user; //message from user-level component
static const char* security; //security or authorization related message
static const char* fplog; //message from fplog directly, could inform about log system malfunction
};
struct FPLOG_API Prio
{
static const char* emergency; //system is unusable
static const char* alert; //action must be taken immediately
static const char* critical; //critical conditions
static const char* error; //error conditions
static const char* warning; //warning conditions
static const char* notice; //normal but significant condition
static const char* info; //informational
static const char* debug; //debug/trace info for developers
};
class FPLOG_API Message
{
friend class Fplog_Impl;
friend class fplogd::Impl;
public:
struct FPLOG_API Mandatory_Fields
{
static const char* facility; //according to syslog
static const char* priority; //same as severity for syslog
static const char* timestamp; //ISO8601 timestamp with milliseconds and timezone
static const char* hostname; //IP address or any specific sending device id, added by fplogd before sending
static const char* appname; //name of application or service using this logging library, needed for fplog IPC
};
struct FPLOG_API Optional_Fields
{
static const char* text; //log message text
static const char* component; //package name or any logical software component
static const char* class_name; //class name if OOP is used
static const char* method; //method of a given class if OOP is used or just a function name
static const char* module; //source file name
static const char* line; //line number in the above mentioned source file
static const char* options; //for example encryption method + options when encryption is in use
static const char* encrypted; //true/false, if true then Text field contains encrypted JSON values -
//the rest of the log message including the plaintext version of Text field
static const char* file; //filename when sending a file inside the log message
static const char* /*the*/blob; //used when attaching binary fields to the message, resulting JSON object will look
//like this: "blob_name":{ "blob":"xckjhKJSHDKDSdJKShdsdsgr=" }
//where "xckjhKJSHDKDSdJKShdsdsgr=" is base64 encoded binary object
static const char* warning; //contains warning for the user in case there was an issue with this specific log message
static const char* sequence; //sequence number that allows to prevent duplicate messages and also to tell
//which message was first even if timestamps are the same
static const char* batch; //indicator if this message is actually a container for N other shorter messages
};
Message(const char* prio, const char *facility, const char* format = 0, ...);
Message(const rapidjson::Document& msg);
Message(const std::string& msg);
Message(const Message &obj)
{
validate_params_ = obj.validate_params_;
msg_.CopyFrom(obj.msg_, msg_.GetAllocator());
}
Message& operator= (const Message& rhs)
{
validate_params_ = rhs.validate_params_;
msg_.CopyFrom(rhs.msg_, msg_.GetAllocator());
return *this;
}
Message& set_timestamp(const char* timestamp = 0); //either sets provided timestamp or uses current system date/time if timestamp is 0
Message& add(const char* param_name, int param){ return add<int>(param_name, param); }
Message& add(const char* param_name, long long int param){ return add<long long int>(param_name, param); }
Message& add(const char* param_name, double param){ return add<double>(param_name, param); }
Message& add(const char* param_name, std::string& param);
Message& add(const char* param_name, const char* param);
Message& add_binary(const char* param_name, const void* buf, size_t buf_size_bytes);
//before adding JSON element make sure it has a name
Message& add(rapidjson::Document& param);
Message& add(const std::string& json); //here adding json object that is encoded in plaintext string
Message& add_batch(rapidjson::Document& batch);
bool has_batch();
rapidjson::Document get_batch();
Message& set_text(std::string& text);
Message& set_text(const char* text);
Message& set_class(std::string& class_name);
Message& set_class(const char* class_name);
Message& set_module(std::string& module);
Message& set_module(const char* module);
Message& set_method(std::string& method);
Message& set_method(const char* method);
Message& set_line(int line);
Message& set_file(const char* name);
std::string as_string() const;
rapidjson::Document as_json();
private:
Message();
template <typename T> Message& set(const char* param_name, T param)
{
validate_params_ = false;
Message& msg(*this);
try
{
Message& returned(add(param_name, param));
if (&msg != &returned)
msg = returned;
}
catch(std::exception& e)
{
validate_params_ = true;
throw e;
}
catch(fplog::exceptions::Generic_Exception& e)
{
validate_params_ = true;
throw e;
}
validate_params_ = true;
return msg;
}
// trim from start
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int c) {return !std::isspace(c);}));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](int c) {return !std::isspace(c);}).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
template <typename T> bool is_valid(const char* param_name, T param)
{
if (!validate_params_)
return true;
if (!param_name)
return false;
std::string lowercased(param_name);
trim(lowercased);
std::transform(lowercased.begin(), lowercased.end(), lowercased.begin(), ::tolower);
bool valid(std::find(reserved_names_.begin(), reserved_names_.end(), lowercased) == reserved_names_.end());
if (!valid)
set(Optional_Fields::warning, "Some parameters are missing from this log message because they were malformed.");
return valid;
}
bool is_valid(rapidjson::Document& param);
template <typename T> Message& add(const char* param_name, T param)
{
std::string trimmed(param_name);
trim(trimmed);
rapidjson::GenericValue<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>> name(trimmed.c_str(), msg_.GetAllocator());
rapidjson::GenericValue<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>> v(param);
if (param_name && is_valid(trimmed.c_str(), param))
{
auto it(msg_.FindMember(trimmed.c_str()));
if (it == msg_.MemberEnd())
msg_.AddMember(name, v, msg_.GetAllocator());
else
it->value = v;
}
return *this;
}
Message& set_sequence(unsigned long long int sequence);
rapidjson::Document msg_;
bool validate_params_;
static std::vector<std::string> reserved_names_;
static void one_time_init();
};
class FPLOG_API File
{
public:
File(const char* prio, const char* name, const void* content, size_t size);
Message as_message(){ return msg_; }
private:
File();
File(File&);
Message msg_;
char* buf_;
};
class FPLOG_API Filter_Base
{
public:
Filter_Base(const char* filter_id) { if (filter_id) filter_id_ = filter_id; else filter_id_ = ""; }
virtual bool should_pass(const Message& msg) = 0;
std::string get_id(){ std::lock_guard<std::recursive_mutex> lock(mutex_); std::string id(filter_id_); return id; };
virtual ~Filter_Base() {}
protected:
std::string filter_id_; //just a human-readable name for the filter
std::recursive_mutex mutex_;
private:
Filter_Base();
};
//You need to explicitly state messages of which priorities you need to log by using add/remove.
class FPLOG_API Priority_Filter: public Filter_Base
{
public:
Priority_Filter(const char* filter_id): Filter_Base(filter_id){ construct_numeric(); }
virtual ~Priority_Filter() {}
virtual bool should_pass(const Message& msg);
void add(const char* prio){ if (prio) prio_.insert(prio); }
void remove(const char* prio = nullptr) //by default removes all
{
if (prio){ std::set<std::string>::iterator it(prio_.find(prio)); if (it != prio_.end()) { prio_.erase(it); }}
else
prio_.clear();
}
void add_all_above(const char* prio, bool inclusive = false);
void add_all_below(const char* prio, bool inclusive = false);
private:
std::set<std::string> prio_;
std::vector<std::string> prio_numeric_;
void construct_numeric();
};
//One time per application call.
//async_logging means that log messages are going to the queue before dispatching to the destination.
//This process is faster than sync logging but it also means that if app crashes with some messages still
//in the queue, those messages are lost. If you need to debug some app crash, set this parameter to false
//until you find the reason for the crash.
FPLOG_API void initlog(const char* appname, sprot::Basic_Transport_Interface* transport, bool async_logging = true);
FPLOG_API void initlog(const char* appname, sprot::Address local, sprot::Address remote, bool async_logging = true);
//One time per application call to stop logging from an application and free all associated resources.
FPLOG_API void shutdownlog();
//Mandatory call from every thread that wants to log some data. Done to increase flexibility:
//each thread will have its own filters configuration and can decide independently which stuff to log.
//Each filter within one thread must have unique id.
FPLOG_API void openlog(const char* facility, Filter_Base* filter = 0);
//Optional but advised to call from each thread that logs data right before stopping and exiting the thread.
//Doing this will free some memory (amount is really small) that is needed to support logging from a given thread.
//Not doing closelog() does not lead to memory leak because everything will be deallocated in any case on app exit,
//fplog frees its resources when implementation class instance is destroyed.
FPLOG_API void closelog();
//Scope of filter-related functions is a calling thread - all manipulations will apply to calling thread only.
//fplog will take ownership of the filter on adding and will deallocate it on removing, closelog() or shutdownlog().
FPLOG_API void add_filter(Filter_Base* filter);
FPLOG_API void remove_filter(Filter_Base* filter);
FPLOG_API Filter_Base* find_filter(const char* filter_id);
FPLOG_API const char* get_facility();
//Should be used from any thread that opened logger, calling from other threads will have no effect.
FPLOG_API void write(const Message& msg);
FPLOG_API void change_config(const sprot::Params& config);
};
|
kr0st/fplog2
|
headers/fplog_exceptions.h
|
<filename>headers/fplog_exceptions.h
#pragma once
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <cstring>
#ifndef __SHORT_FORM_OF_FILE__
#ifdef _WIN32
#define __SHORT_FORM_OF_FILE_WIN__ \
(strrchr(__FILE__,'\\') \
? strrchr(__FILE__,'\\')+1 \
: __FILE__ \
)
#define __SHORT_FORM_OF_FILE__ __SHORT_FORM_OF_FILE_WIN__
#else
#define __SHORT_FORM_OF_FILE_NIX__ \
(strrchr(__FILE__,'/') \
? strrchr(__FILE__,'/')+1 \
: __FILE__ \
)
#define __SHORT_FORM_OF_FILE__ __SHORT_FORM_OF_FILE_NIX__
#endif
#endif
#define THROW(exception_type) { exception_type e(__FUNCTION__, __SHORT_FORM_OF_FILE__, __LINE__); debug_logging::g_logger.log(e.what()); throw e; }
#define THROW1(exception_type, param1) { exception_type e(__FUNCTION__, __SHORT_FORM_OF_FILE__, __LINE__, param1); debug_logging::g_logger.log(e.what()); throw e; }
#define THROW2(exception_type, param1, param2) { exception_type e(__FUNCTION__, __SHORT_FORM_OF_FILE__, __LINE__, param1, param2); debug_logging::g_logger.log(e.what()); throw e; }
#define THROWM(exception_type, message) { exception_type e(__FUNCTION__, __SHORT_FORM_OF_FILE__, __LINE__, message); debug_logging::g_logger.log(e.what()); throw e; }
#ifdef __linux__
#define NO_ITOA
#endif
#ifdef __APPLE__
#define NO_ITOA
#endif
#ifdef NO_ITOA
inline char *itoa(long i, char* s, int dummy_radix)
{
dummy_radix /= 1;
sprintf(s, "%ld", i);
return s;
}
#endif
namespace fplog { namespace exceptions {
class Generic_Exception
{
public:
Generic_Exception(const char* facility, const char* file = "", int line = 0, const char* message = ""):
facility_(facility),
message_(message),
file_(file),
line_(line)
{
}
std::string what()
{
char buf[256];
#ifdef _WIN32
_itoa_s(line_, buf, sizeof(buf) / sizeof(char), 10);
#else
itoa(line_, buf, 10);
#endif
return "[" + facility_ + ", f:" + file_ + ", l:" + buf + "] " + message_;
}
Generic_Exception():
facility_("N/A"),
message_("This is an empty exception."),
file_("N/A"),
line_(0)
{
}
protected:
std::string facility_;
std::string message_;
std::string file_;
int line_;
};
class Connect_Failed: public Generic_Exception
{
public:
Connect_Failed(const char* facility, const char* file = "", int line = 0, const char* message = "Cannot establish a connection."):
Generic_Exception(facility, file, line, message)
{
}
};
class Write_Failed: public Generic_Exception
{
public:
Write_Failed(const char* facility, const char* file = "", int line = 0, const char* message = "Write operation failed."):
Generic_Exception(facility, file, line, message)
{
}
};
class Read_Failed: public Generic_Exception
{
public:
Read_Failed(const char* facility, const char* file = "", int line = 0, const char* message = "Read operation failed."):
Generic_Exception(facility, file, line, message)
{
}
};
class Incorrect_Parameter: public Generic_Exception
{
public:
Incorrect_Parameter(const char* facility, const char* file = "", int line = 0, const char* message = "Parameter supplied to function has incorrect value."):
Generic_Exception(facility, file, line, message)
{
}
};
class Not_Implemented: public Generic_Exception
{
public:
Not_Implemented(const char* facility, const char* file = "", int line = 0, const char* message = "Feature not implemented yet."):
Generic_Exception(facility, file, line, message)
{
}
};
class Buffer_Overflow: public Generic_Exception
{
public:
Buffer_Overflow(const char* facility, const char* file = "", int line = 0, const char* message = "Buffer too small.", size_t buf_sz = 0):
Generic_Exception(facility, file, line, message),
buf_sz_(buf_sz)
{
}
size_t get_required_size() { return buf_sz_; }
private:
size_t buf_sz_;
};
class Timeout: public Generic_Exception
{
public:
Timeout(const char* facility, const char* file = "", int line = 0, const char* message = "Timeout while reading or writing."):
Generic_Exception(facility, file, line, message)
{
}
};
class Transport_Missing : public Generic_Exception
{
public:
Transport_Missing(const char* facility, const char* file = "", int line = 0, const char* message = "Transport or protocol is missing.") :
Generic_Exception(facility, file, line, message)
{
}
};
class Not_Connected : public Generic_Exception
{
public:
Not_Connected(const char* facility, const char* file = "", int line = 0, const char* message = "Transport or protocol is missing.") :
Generic_Exception(facility, file, line, message)
{
}
};
}};
|
kr0st/fplog2
|
headers/utils.h
|
<filename>headers/utils.h
#pragma once
#include <string>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <algorithm>
#include <vector>
#include <fstream>
#include <queue>
#include <thread>
#include <mutex>
template<typename T>
struct std::hash<std::vector<T>>
{
typedef vector<T> argument_type;
typedef std::size_t result_type;
result_type operator()(argument_type const& in) const
{
size_t size = in.size();
size_t seed = 0;
for (size_t i = 0; i < size; i++)
//Combine the hash of the current vector with the hashes of the previous ones
hash_combine(seed, in[i]);
return seed;
}
};
//using boost::hash_combine
template <class T>
inline void hash_combine(std::size_t& seed, T const& v)
{
seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
namespace debug_logging
{
class Logger
{
public:
Logger();
~Logger();
bool open(const char* file, bool unbuffered = true);
void log(const char* func, const char* file, const int line, const char* msg);
void log(const std::string& message);
bool enabled(){ return (log_ != nullptr); }
private:
std::queue<std::string> messages_;
std::recursive_mutex mutex_;
std::thread writer_;
static void writer_thread(Logger* l);
bool shutdown_ = false;
FILE* log_ = nullptr;
};
extern Logger g_logger;
}
namespace generic_util
{
struct Retryable
{
using Retry_Function = std::function<bool()>;
unsigned int max_retries = 0;
unsigned int actual_retries = 0;
Retryable(Retry_Function func, unsigned int retries_allowed): max_retries(retries_allowed), retryable_function { std::move(func) } {}
bool run()
{
for (; actual_retries < max_retries; actual_retries++)
if (retryable_function())
break;
return (actual_retries < max_retries);
}
Retry_Function retryable_function;
};
uint16_t gen_crc16(const uint8_t *data, uint16_t size);
uint16_t gen_simple_crc16(const uint8_t *data, uint16_t size);
template<typename InputIterator1, typename InputIterator2>
bool
range_equal(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2)
{
while(first1 != last1 && first2 != last2)
{
if(*first1 != *first2) return false;
++first1;
++first2;
}
return (first1 == last1) && (first2 == last2);
}
bool compare_files(const std::string& filename1, const std::string& filename2);
//using boost::hash_combine
template <class T>
inline void hash_combine(std::size_t& seed, T const& v)
{
seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
std::string& remove_json_field(const char* field_name, std::string& source);
void process_suicide(size_t timeout, int signal = 15);
void suicide_prevention();
static inline bool compare_no_case(char ch1, char ch2){ return std::toupper(ch1) == std::toupper(ch2); }
static inline bool find_str_no_case(const std::string& search_where, const std::string& search_what)
{
return (std::search(search_where.begin(), search_where.end(), search_what.begin(), search_what.end(), compare_no_case) != search_where.end());
}
//Returns difference in minutes from UTC
//Example: for UTC+3 function returns 180
int get_system_timezone();
//Converts timezone bias in minutes (returned by get_system_timezone() for example) to iso8601 representation
std::string timezone_from_minutes_to_iso8601(int tz_minute_bias);
//Returns current local date-time in iso 8601 format including timezone information
std::string get_iso8601_timestamp();
//Milliseconds elapsed since 01-Jan-1970
unsigned long long get_msec_time();
bool base64_encode(const void* source, size_t sourcelen, char* dest, size_t destlen);
size_t base64_decode(const char* source, void* dest, size_t destlen);
size_t base64_encoded_length(size_t non_encoded_length);
// trim from start
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::function<int(int)>(isspace))));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::function<int (int)>(isspace))).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
std::vector<std::string> tokenize(const char *str, char c = ' ');
};
|
kr0st/fplog2
|
headers/piped_sequence.h
|
<reponame>kr0st/fplog2
#ifndef PIPED_SEQUENCE_H
#define PIPED_SEQUENCE_H
#include <ctype.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
#include <time.h>
#include <sem_timedwait.h>
namespace sequence_number {
class Sem_Lock
{
public:
Sem_Lock(sem_t *semaphore): sem_(semaphore){}
~Sem_Lock(){ sem_post(sem_); sem_close(sem_); }
bool try_lock(long timeout_ms)
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += timeout_ms / 1000;
ts.tv_nsec += timeout_ms % 1000 * 1000000;
return (sem_timedwait(sem_, &ts) == 0);
}
private:
Sem_Lock();
sem_t *sem_ = nullptr;
};
static const char* sequence_pipe_name = "/tmp/fplog2_shared_sequence";
static const char* sequence_sem_name = "/fp2_shm_sem";
unsigned long long read_sequence_number(size_t timeout = 5000);
};
#endif // PIPED_SEQUENCE_H
|
kr0st/fplog2
|
headers/queue_controller.h
|
#include <string>
#include <queue>
#include <memory>
#include <chrono>
#include <sprot.h>
#ifdef FPLOG_EXPORT
#ifdef __linux__
#define FPLOG_API __attribute__ ((visibility("default")))
#else
#define FPLOG_API __declspec(dllexport)
#endif
#else
#ifdef __linux__
#define FPLOG_API
#else
#define FPLOG_API __declspec(dllimport)
#endif
#ifdef __APPLE__
#define FPLOG_API
#endif
#endif
using namespace std::chrono;
using namespace std;
class FPLOG_API Queue_Controller
{
public:
class Algo
{
public:
struct Result
{
size_t current_size = 0;
size_t removed_count = 0;
};
struct Fallback_Options
{
enum Type
{
Remove_Newest = 765,
Remove_Oldest
};
};
Algo(queue<string*>& mq, size_t max_size, size_t current_size = 0): mq_(mq), max_size_(max_size), current_size_(static_cast<int>(current_size)){}
virtual Result process_queue(size_t current_size) = 0;
private:
Algo();
protected:
queue<string*>& mq_;
size_t max_size_;
int current_size_;
};
class FPLOG_API Remove_Oldest: public Algo
{
public:
Remove_Oldest(Queue_Controller& qc): Algo(qc.mq_, qc.max_size_, qc.mq_size_) {}
Result process_queue(size_t current_size);
};
class FPLOG_API Remove_Newest;
class FPLOG_API Remove_Newest_Below_Priority;
class FPLOG_API Remove_Oldest_Below_Priority;
Queue_Controller(size_t size_limit = 20000000, size_t timeout = 30000);
bool empty();
string *front();
void pop();
void push(string *str);
void change_algo(std::shared_ptr<Algo> algo, Algo::Fallback_Options::Type fallback_algo);
void change_params(size_t size_limit, size_t timeout);
//configuration params as follows:
//max_queue_size = [any positive integer]
//emergency_timeout = [any positive integer]
//emergency_algo = one of { remove_oldest, remove_newest, remove_oldest_below_prio, remove_newest_below_prio }
//emergency_fallback_algo = one of { remove_oldest, remove_newest }
//emergency_prio = use one of the fplog::Prio constants //only needed if algo is based on prio
void apply_config(const sprot::Params& config);
private:
int mq_size_ = 0;
size_t max_size_ = 0;
queue<string*> mq_;
std::shared_ptr<Algo> algo_;
std::shared_ptr<Algo> algo_fallback_;
size_t emergency_time_trigger_ = 0;
time_point<system_clock, system_clock::duration> timer_start_;
bool state_of_emergency();
void handle_emergency();
std::shared_ptr<Algo> make_algo(const std::string& name, const std::string& param);
};
class Queue_Controller::Remove_Newest: public Algo
{
public:
Remove_Newest(Queue_Controller& qc): Algo(qc.mq_, qc.max_size_, qc.mq_size_) {}
Result process_queue(size_t current_size);
};
namespace fplog
{
class Priority_Filter;
};
class Queue_Controller::Remove_Newest_Below_Priority: public Algo
{
public:
Remove_Newest_Below_Priority(Queue_Controller& qc, const char* prio, bool inclusive = false):
Algo(qc.mq_, qc.max_size_, qc.mq_size_), prio_(prio), inclusive_(inclusive) { make_filter(); }
//~Remove_Newest_Below_Priority(){}
Result process_queue(size_t current_size);
private:
Remove_Newest_Below_Priority();
void make_filter();
std::string prio_;
bool inclusive_;
std::shared_ptr<fplog::Priority_Filter> filter_;
};
class Queue_Controller::Remove_Oldest_Below_Priority: public Algo
{
public:
Remove_Oldest_Below_Priority(Queue_Controller& qc, const char* prio, bool inclusive = false):
Algo(qc.mq_, qc.max_size_, qc.mq_size_), prio_(prio), inclusive_(inclusive) { make_filter(); }
//~Remove_Oldest_Below_Priority(){}
Result process_queue(size_t current_size);
private:
Remove_Oldest_Below_Priority();
void make_filter();
std::string prio_;
bool inclusive_;
std::shared_ptr<fplog::Priority_Filter> filter_;
};
|
kr0st/fplog2
|
headers/sprot.h
|
#ifndef SPROT_H
#define SPROT_H
#include <string>
#include <map>
#include <vector>
#include <chrono>
#include <fplog_exceptions.h>
#include <utils.h>
#ifdef _WIN32
#ifdef SPROT_EXPORT
#define SPROT_API __declspec(dllexport)
#else
#define SPROT_API __declspec(dllimport)
#endif
#endif
#ifdef __linux__
#include <netinet/in.h>
#define SPROT_API
#endif
#ifdef __APPLE__
#define SPROT_API
#endif
namespace sprot {
typedef std::pair<std::string, std::string> Param;
typedef std::map<std::string, std::string> Params;
static Params empty_params;
struct Address
{
unsigned int ip;
unsigned short port;
Address(): ip(0), port(0) {}
bool operator== (const Address& rhs) const
{
return (ip == rhs.ip) && (port == rhs.port);
}
bool operator< (const Address& rhs) const
{
if (ip == rhs.ip)
return (port < rhs.port);
return (ip < rhs.ip);
}
Address& from_params(const Params& params)
{
ip = 0;
port = 0;
if (params.size() < 2)
return *this;
for (auto& param : params)
{
if (generic_util::find_str_no_case(param.first, "ip"))
{
std::string ip_addr(param.second);
ip_addr = generic_util::trim(ip_addr);
auto tokens = generic_util::tokenize(ip_addr.c_str(), '.');
int c = 0;
for (auto& token : tokens)
{
unsigned short byte = static_cast<unsigned short>(std::stoi(token));
ip += byte;
c++;
if (c < 4)
ip <<= 8;
}
ip = htonl(ip);
}
if (generic_util::find_str_no_case(param.first, "port"))
port = static_cast<unsigned short>(std::stoi(param.second));
}
return *this;
}
};
static Address no_address;
class SPROT_API Basic_Transport_Interface
{
public:
static const size_t infinite_wait = 4294967295;
virtual size_t read(void* buf, size_t buf_size, size_t timeout = infinite_wait) = 0;
virtual size_t write(const void* buf, size_t buf_size, size_t timeout = infinite_wait) = 0;
virtual ~Basic_Transport_Interface() {}
};
class SPROT_API Extended_Transport_Interface
{
public:
static const size_t infinite_wait = 4294967295;
virtual size_t read(void* buf, size_t buf_size, Address& user_data = no_address, size_t timeout = infinite_wait) = 0;
virtual size_t write(const void* buf, size_t buf_size, Address& user_data = no_address, size_t timeout = infinite_wait) = 0;
virtual ~Extended_Transport_Interface() {}
static bool null_data(const Address& user_data) { return (&user_data == &no_address); }
};
class SPROT_API Protocol_Interface: public Basic_Transport_Interface
{
public:
virtual bool connect(const Params& local_config, const Address& remote, size_t timeout = infinite_wait) = 0;
virtual bool accept(const Params& local_config, Address& remote, size_t timeout = infinite_wait) = 0;
};
struct SPROT_API Session_Configuration
{
Params local_config;
Address remote;
};
class SPROT_API Session: public Protocol_Interface
{
public:
size_t read(void* buf, size_t buf_size, size_t timeout = infinite_wait);
size_t write(const void* buf, size_t buf_size, size_t timeout = infinite_wait);
bool connect(const Params& local_config, const Address& remote, size_t timeout = infinite_wait);
bool accept(const Params& local_config, Address& remote, size_t timeout = infinite_wait);
virtual void disconnect();
Session(Extended_Transport_Interface* l1_transport);
virtual ~Session();
Session_Configuration get_config();
private:
class Session_Implementation;
Session_Implementation* impl_;
};
class SPROT_API Session_Manager
{
public:
virtual Session* connect(const Params& local_config, const Address& remote, size_t timeout = Session::infinite_wait);
virtual Session* accept(const Params& local_config, Address& remote, size_t timeout = Session::infinite_wait);
Session_Manager();
virtual ~Session_Manager();
private:
class Session_Manager_Implementation;
class Session_Manager_Implementation* impl_;
};
namespace exceptions
{
class Unknown_Frame : public fplog::exceptions::Generic_Exception
{
public:
Unknown_Frame(const char* facility, const char* file, int line, int frame_type):
Generic_Exception(facility, file, line)
{
char str[40];
sprintf(str, "Unknown frame type %d detected.", frame_type);
message_ = str;
}
};
class Unexpected_Frame : public fplog::exceptions::Generic_Exception
{
public:
Unexpected_Frame(const char* facility, const char* file, int line, int expected, int actual):
Generic_Exception(facility, file, line)
{
char str[255];
sprintf(str, "Unexpected frame type %d detected when %d was expected.", actual, expected);
message_ = str;
}
};
class Size_Mismatch : public fplog::exceptions::Generic_Exception
{
public:
Size_Mismatch(const char* facility, const char* file, int line, size_t expected, size_t actual):
Generic_Exception(facility, file, line)
{
char str[255];
sprintf(str, "Sent or received bytes mismatch: expected %lu, got %lu.", expected, actual);
message_ = str;
}
};
class Crc_Check_Failed : public fplog::exceptions::Generic_Exception
{
public:
Crc_Check_Failed(const char* facility, const char* file, int line, int expected, int actual):
Generic_Exception(facility, file, line)
{
char str[255];
sprintf(str, "CRC check failed: expected crc = %d, got crc = %d.", expected, actual);
message_ = str;
}
};
class Wrong_Number : public fplog::exceptions::Generic_Exception
{
public:
Wrong_Number(const char* facility, const char* file, int line, unsigned int expected, unsigned int actual):
Generic_Exception(facility, file, line)
{
char str[255];
sprintf(str, "Sequence number check failed: expected %d, got %d.", expected, actual);
message_ = str;
}
};
class Connection_Broken : public fplog::exceptions::Generic_Exception
{
public:
Connection_Broken(const char* facility, const char* file, int line):
Generic_Exception(facility, file, line)
{
char str[255];
sprintf(str, "Connection broke down, please redo accept/connect.");
message_ = str;
}
};
class Repeat_Retransmit : public fplog::exceptions::Generic_Exception
{
public:
Repeat_Retransmit(const char* facility, const char* file, int line):
Generic_Exception(facility, file, line)
{
}
};
};
namespace implementation
{
union Frame
{
struct
{
unsigned short crc;
unsigned short type;
unsigned int origin_ip;
unsigned short origin_listen_port;
char hostname[18];
unsigned int sequence;
unsigned short data_len;
} details;
unsigned char bytes[36];
};
enum Frame_Type
{
Handshake_Frame = 0x13, //19 dec
Goodbye_Frame,
Ack_Frame,
Nack_Frame,
Data_Frame,
Retransmit_Frame,
Unknown_Frame
};
struct Options
{
unsigned int max_frame_size; //maximum size of a single protocol frame
unsigned int mtu; //maximum transfer unit - the largest payload that could be transfered in a single frame
unsigned int no_ack_count; //how many DATA frames could be sent before ACK is requested
unsigned int storage_max; //how many received frames could be temporarily stored
//to ensure error correction (retransmit) will work if needed
unsigned int storage_trim; //how many frames to delete from temporary storage if storage_max is reached
unsigned int op_timeout; //a single operation timeout, should be considerably less than the whole read/write user timeout
unsigned int max_retries; //maximum number of retries of the unsuccessful operation
unsigned int max_connections;//maximum number of pending and established connections
unsigned int max_requests_in_queue;//maximum number of pending requests per established or pending connection
Options();
void Load(Params params);
};
extern Options options;
inline bool crc_check(void* buffer, size_t sz, unsigned short* expected = nullptr, unsigned short* actual = nullptr)
{
if (sz < sizeof(Frame::bytes))
return false;
if (sz > options.max_frame_size)
return false;
Frame frame;
memcpy(frame.bytes, buffer, sizeof(frame.bytes));
unsigned short crc_expected = generic_util::gen_simple_crc16(static_cast<unsigned char*>(buffer) + 2, static_cast<unsigned short>(sz) - 2);
unsigned short crc_actual = frame.details.crc;
if (expected)
*expected = crc_expected;
if (actual)
*actual = crc_actual;
if (crc_actual != crc_expected)
return false;
return true;
}
inline auto check_time_out(unsigned long long timeout,
std::chrono::time_point<std::chrono::system_clock, std::chrono::system_clock::duration> timer_start = std::chrono::system_clock::now())
{
auto timer_start_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(timer_start);
auto timer_stop_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
std::chrono::milliseconds timeout_ms(timeout);
if (timer_stop_ms - timer_start_ms >= timeout_ms)
THROW(fplog::exceptions::Timeout);
return timer_start;
};
}};
#endif // SPROT_H
|
kr0st/fplog2
|
headers/sem_timedwait.h
|
#pragma once
#ifdef __APPLE__
#include <semaphore.h>
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
#endif
|
kr0st/fplog2
|
headers/packet_router.h
|
<filename>headers/packet_router.h
#ifndef L1_TRANSPORT_H
#define PACKET_ROUTER_H
#include <sprot.h>
#include <map>
#include <queue>
#include <condition_variable>
#include <mutex>
#include <utils.h>
#include <thread>
namespace sprot
{
class Packet_Router: public Extended_Transport_Interface
{
public:
Packet_Router(Extended_Transport_Interface* l0_transport);
virtual size_t read(void* buf, size_t buf_size, Address& user_data, size_t timeout = infinite_wait);
virtual size_t write(const void* buf, size_t buf_size, Address& user_data, size_t timeout = infinite_wait);
~Packet_Router();
private:
Extended_Transport_Interface* l0_transport_;
struct Read_Request
{
unsigned char* read_buffer = nullptr;
size_t read_bytes = 0;
volatile bool done = false;
Address read_ext_data;
Read_Request(){ read_buffer = new unsigned char[implementation::options.max_frame_size]; }
~Read_Request() { delete [] read_buffer; read_buffer = nullptr; }
Read_Request(const Read_Request& rhs): Read_Request() { operator=(rhs); }
Read_Request& operator=(const Read_Request& rhs)
{
if ((read_buffer != nullptr) && (rhs.read_buffer != nullptr))
memcpy(read_buffer, rhs.read_buffer, implementation::options.max_frame_size);
read_bytes = rhs.read_bytes;
done = rhs.done;
read_ext_data = rhs.read_ext_data;
return *this;
}
};
std::map<Address, std::vector<Read_Request*>> waitlist_;
std::mutex waitlist_mutex_;
static std::mutex waitlist_trace_mutex_;
Read_Request schedule_read(Address& user_data, size_t timeout = infinite_wait);
static void waste_management_thread(Packet_Router* p);
static void reader_thread(Packet_Router* p);
bool stop_reading_;
std::thread reader_;
std::thread garbage_collector_;
void waitlist_trace();
};
};
#endif // PACKET_ROUTER_H
|
kr0st/fplog2
|
headers/protocol.h
|
#ifndef PROTOCOL_H
#define PROTOCOL_H
#include <mutex>
#include <queue>
#include <sprot.h>
#include <stdint.h>
namespace sprot { namespace implementation {
class Protocol: public Protocol_Interface
{
public:
size_t read(void* buf, size_t buf_size, size_t timeout = infinite_wait);
size_t write(const void* buf, size_t buf_size, size_t timeout = infinite_wait);
virtual bool connect(const Params& local_config, const Address& remote, size_t timeout = infinite_wait);
virtual bool accept(const Params& local_config, Address& remote, size_t timeout = infinite_wait);
Protocol(Extended_Transport_Interface* l1_transport): l1_transport_(l1_transport)
{
read_buffer_ = new unsigned char[options.max_frame_size];
write_buffer_ = new unsigned char[options.max_frame_size];
}
virtual ~Protocol()
{
std::lock_guard lock(mutex_);
connected_ = false;
delete [] read_buffer_;
delete [] write_buffer_;
}
private:
Protocol();
bool connected_ = false, acceptor_ = false;
Address local_, remote_, accepted_remote_;
unsigned int send_sequence_ = 0;
unsigned int recv_sequence_ = 0;
unsigned int prev_seq_ = UINT32_MAX - 2;
std::recursive_mutex mutex_;
Extended_Transport_Interface* l1_transport_ = nullptr;
unsigned char* read_buffer_;
unsigned char* write_buffer_;
struct Packed_Buffer
{
unsigned char* buffer = nullptr;
Packed_Buffer(){ buffer = new unsigned char[options.max_frame_size]; }
~Packed_Buffer() { delete [] buffer; }
Packed_Buffer(const Packed_Buffer& rhs): Packed_Buffer() { operator=(rhs); }
Packed_Buffer& operator=(const Packed_Buffer& rhs)
{
if ((buffer != nullptr) && (rhs.buffer != nullptr)) memcpy(buffer, rhs.buffer, options.max_frame_size);
return *this;
}
};
std::map<unsigned int, Packed_Buffer> stored_writes_;
std::map<unsigned int, Packed_Buffer> stored_reads_;
std::queue<unsigned int> recovered_frames_;
char localhost_[18];
void trim_storage(std::map<unsigned int, Packed_Buffer>& storage);
void empty_storage(std::map<unsigned int, Packed_Buffer>& storage);
void put_in_storage(std::map<unsigned int, Packed_Buffer>& storage, unsigned int sequence, const void* buf);
void take_from_storage(std::map<unsigned int, Packed_Buffer>& storage, unsigned int sequence, void* buf);
Frame make_frame(Frame_Type type, size_t data_len = 0, const void* data = nullptr);
void send_frame(size_t timeout);
Frame receive_frame(size_t timeout);
bool retransmit_request(std::chrono::time_point<std::chrono::system_clock, std::chrono::system_clock::duration> timer_start,
size_t timeout, unsigned int last_received_sequence);
bool retransmit_response(std::chrono::time_point<std::chrono::system_clock, std::chrono::system_clock::duration> timer_start, size_t timeout);
};
}}
#endif // PROTOCOL_H
|
lasalvavida/Zybo-Open-Source-Video-IP-Toolbox
|
examples/zed_dual_fusion/zed_dual_fusion.sdk/axi_vga_buffer/src/helloworld.c
|
<reponame>lasalvavida/Zybo-Open-Source-Video-IP-Toolbox<gh_stars>1-10
/******************************************************************************
*
* Copyright (C) 2009 - 2014 Xilinx, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Use of the Software is limited solely to applications:
* (a) running on a Xilinx device, or
* (b) that interact with a Xilinx device through a bus or interconnect.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* XILINX BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Except as contained in this notice, the name of the Xilinx shall not be used
* in advertising or otherwise to promote the sale, use or other dealings in
* this Software without prior written authorization from Xilinx.
*
******************************************************************************/
/*
* helloworld.c: simple test application
*
* This application configures UART 16550 to baud rate 9600.
* PS7 UART (Zynq) is not initialized by this application, since
* bootrom/bsp configures it to baud rate 115200
*
* ------------------------------------------------
* | UART TYPE BAUD RATE |
* ------------------------------------------------
* uartns550 9600
* uartlite Configurable only in HW design
* ps7_uart 115200 (configured by bootrom/bsp)
*/
#include <stdio.h>
#include "malloc.h"
#include "platform.h"
#include "xil_io.h"
#include "xil_printf.h"
#define BASE 0x43c00000
#define WIDTH 1024
#define HEIGHT 1024
int main()
{
init_platform();
print("Allocating memory...");
uint32_t* memory = malloc(sizeof(uint32_t) * WIDTH * HEIGHT);
print(" done!\r\n");
while(1) {
uint32_t reg0 = Xil_In32(BASE);
uint32_t reg1 = Xil_In32(BASE + 4);
uint32_t reg2 = Xil_In32(BASE + 8);
uint32_t xWrite = reg0 & 0x3FF;
uint32_t yWrite = (reg0 >> 10) & 0x3FF;
uint32_t wen = (reg0 >> 20) & 0x1;
uint32_t xRead = reg1 & 0x3FF;
uint32_t yRead = (reg1 >> 10) & 0x3FF;
Xil_Out32(BASE + 12, memory[yRead * WIDTH + xRead]);
if(wen) {
memory[yWrite * WIDTH + xWrite] = reg2;
}
}
cleanup_platform();
return 0;
}
|
lasalvavida/Zybo-Open-Source-Video-IP-Toolbox
|
video_ip/axi_vga_framebuffer_1.0/drivers/axi_vga_framebuffer_v1_0/src/axi_vga_framebuffer.h
|
#ifndef AXI_VGA_FRAMEBUFFER_H
#define AXI_VGA_FRAMEBUFFER_H
/****************** Include Files ********************/
#include "xil_types.h"
#include "xstatus.h"
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG0_OFFSET 0
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG1_OFFSET 4
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG2_OFFSET 8
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG3_OFFSET 12
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG4_OFFSET 16
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG5_OFFSET 20
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG6_OFFSET 24
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG7_OFFSET 28
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG8_OFFSET 32
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG9_OFFSET 36
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG10_OFFSET 40
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG11_OFFSET 44
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG12_OFFSET 48
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG13_OFFSET 52
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG14_OFFSET 56
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG15_OFFSET 60
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG16_OFFSET 64
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG17_OFFSET 68
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG18_OFFSET 72
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG19_OFFSET 76
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG20_OFFSET 80
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG21_OFFSET 84
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG22_OFFSET 88
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG23_OFFSET 92
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG24_OFFSET 96
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG25_OFFSET 100
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG26_OFFSET 104
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG27_OFFSET 108
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG28_OFFSET 112
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG29_OFFSET 116
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG30_OFFSET 120
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG31_OFFSET 124
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG32_OFFSET 128
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG33_OFFSET 132
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG34_OFFSET 136
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG35_OFFSET 140
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG36_OFFSET 144
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG37_OFFSET 148
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG38_OFFSET 152
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG39_OFFSET 156
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG40_OFFSET 160
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG41_OFFSET 164
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG42_OFFSET 168
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG43_OFFSET 172
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG44_OFFSET 176
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG45_OFFSET 180
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG46_OFFSET 184
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG47_OFFSET 188
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG48_OFFSET 192
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG49_OFFSET 196
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG50_OFFSET 200
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG51_OFFSET 204
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG52_OFFSET 208
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG53_OFFSET 212
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG54_OFFSET 216
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG55_OFFSET 220
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG56_OFFSET 224
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG57_OFFSET 228
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG58_OFFSET 232
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG59_OFFSET 236
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG60_OFFSET 240
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG61_OFFSET 244
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG62_OFFSET 248
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG63_OFFSET 252
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG64_OFFSET 256
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG65_OFFSET 260
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG66_OFFSET 264
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG67_OFFSET 268
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG68_OFFSET 272
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG69_OFFSET 276
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG70_OFFSET 280
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG71_OFFSET 284
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG72_OFFSET 288
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG73_OFFSET 292
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG74_OFFSET 296
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG75_OFFSET 300
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG76_OFFSET 304
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG77_OFFSET 308
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG78_OFFSET 312
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG79_OFFSET 316
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG80_OFFSET 320
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG81_OFFSET 324
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG82_OFFSET 328
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG83_OFFSET 332
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG84_OFFSET 336
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG85_OFFSET 340
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG86_OFFSET 344
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG87_OFFSET 348
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG88_OFFSET 352
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG89_OFFSET 356
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG90_OFFSET 360
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG91_OFFSET 364
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG92_OFFSET 368
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG93_OFFSET 372
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG94_OFFSET 376
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG95_OFFSET 380
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG96_OFFSET 384
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG97_OFFSET 388
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG98_OFFSET 392
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG99_OFFSET 396
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG100_OFFSET 400
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG101_OFFSET 404
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG102_OFFSET 408
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG103_OFFSET 412
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG104_OFFSET 416
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG105_OFFSET 420
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG106_OFFSET 424
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG107_OFFSET 428
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG108_OFFSET 432
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG109_OFFSET 436
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG110_OFFSET 440
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG111_OFFSET 444
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG112_OFFSET 448
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG113_OFFSET 452
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG114_OFFSET 456
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG115_OFFSET 460
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG116_OFFSET 464
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG117_OFFSET 468
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG118_OFFSET 472
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG119_OFFSET 476
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG120_OFFSET 480
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG121_OFFSET 484
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG122_OFFSET 488
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG123_OFFSET 492
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG124_OFFSET 496
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG125_OFFSET 500
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG126_OFFSET 504
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG127_OFFSET 508
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG128_OFFSET 512
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG129_OFFSET 516
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG130_OFFSET 520
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG131_OFFSET 524
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG132_OFFSET 528
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG133_OFFSET 532
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG134_OFFSET 536
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG135_OFFSET 540
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG136_OFFSET 544
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG137_OFFSET 548
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG138_OFFSET 552
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG139_OFFSET 556
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG140_OFFSET 560
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG141_OFFSET 564
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG142_OFFSET 568
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG143_OFFSET 572
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG144_OFFSET 576
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG145_OFFSET 580
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG146_OFFSET 584
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG147_OFFSET 588
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG148_OFFSET 592
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG149_OFFSET 596
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG150_OFFSET 600
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG151_OFFSET 604
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG152_OFFSET 608
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG153_OFFSET 612
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG154_OFFSET 616
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG155_OFFSET 620
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG156_OFFSET 624
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG157_OFFSET 628
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG158_OFFSET 632
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG159_OFFSET 636
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG160_OFFSET 640
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG161_OFFSET 644
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG162_OFFSET 648
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG163_OFFSET 652
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG164_OFFSET 656
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG165_OFFSET 660
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG166_OFFSET 664
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG167_OFFSET 668
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG168_OFFSET 672
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG169_OFFSET 676
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG170_OFFSET 680
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG171_OFFSET 684
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG172_OFFSET 688
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG173_OFFSET 692
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG174_OFFSET 696
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG175_OFFSET 700
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG176_OFFSET 704
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG177_OFFSET 708
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG178_OFFSET 712
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG179_OFFSET 716
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG180_OFFSET 720
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG181_OFFSET 724
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG182_OFFSET 728
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG183_OFFSET 732
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG184_OFFSET 736
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG185_OFFSET 740
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG186_OFFSET 744
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG187_OFFSET 748
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG188_OFFSET 752
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG189_OFFSET 756
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG190_OFFSET 760
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG191_OFFSET 764
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG192_OFFSET 768
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG193_OFFSET 772
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG194_OFFSET 776
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG195_OFFSET 780
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG196_OFFSET 784
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG197_OFFSET 788
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG198_OFFSET 792
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG199_OFFSET 796
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG200_OFFSET 800
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG201_OFFSET 804
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG202_OFFSET 808
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG203_OFFSET 812
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG204_OFFSET 816
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG205_OFFSET 820
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG206_OFFSET 824
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG207_OFFSET 828
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG208_OFFSET 832
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG209_OFFSET 836
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG210_OFFSET 840
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG211_OFFSET 844
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG212_OFFSET 848
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG213_OFFSET 852
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG214_OFFSET 856
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG215_OFFSET 860
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG216_OFFSET 864
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG217_OFFSET 868
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG218_OFFSET 872
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG219_OFFSET 876
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG220_OFFSET 880
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG221_OFFSET 884
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG222_OFFSET 888
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG223_OFFSET 892
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG224_OFFSET 896
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG225_OFFSET 900
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG226_OFFSET 904
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG227_OFFSET 908
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG228_OFFSET 912
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG229_OFFSET 916
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG230_OFFSET 920
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG231_OFFSET 924
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG232_OFFSET 928
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG233_OFFSET 932
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG234_OFFSET 936
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG235_OFFSET 940
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG236_OFFSET 944
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG237_OFFSET 948
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG238_OFFSET 952
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG239_OFFSET 956
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG240_OFFSET 960
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG241_OFFSET 964
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG242_OFFSET 968
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG243_OFFSET 972
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG244_OFFSET 976
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG245_OFFSET 980
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG246_OFFSET 984
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG247_OFFSET 988
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG248_OFFSET 992
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG249_OFFSET 996
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG250_OFFSET 1000
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG251_OFFSET 1004
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG252_OFFSET 1008
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG253_OFFSET 1012
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG254_OFFSET 1016
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG255_OFFSET 1020
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG256_OFFSET 1024
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG257_OFFSET 1028
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG258_OFFSET 1032
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG259_OFFSET 1036
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG260_OFFSET 1040
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG261_OFFSET 1044
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG262_OFFSET 1048
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG263_OFFSET 1052
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG264_OFFSET 1056
#define AXI_VGA_FRAMEBUFFER_S_AXI_SLV_REG265_OFFSET 1060
/**************************** Type Definitions *****************************/
/**
*
* Write a value to a AXI_VGA_FRAMEBUFFER register. A 32 bit write is performed.
* If the component is implemented in a smaller width, only the least
* significant data is written.
*
* @param BaseAddress is the base address of the AXI_VGA_FRAMEBUFFERdevice.
* @param RegOffset is the register offset from the base to write to.
* @param Data is the data written to the register.
*
* @return None.
*
* @note
* C-style signature:
* void AXI_VGA_FRAMEBUFFER_mWriteReg(u32 BaseAddress, unsigned RegOffset, u32 Data)
*
*/
#define AXI_VGA_FRAMEBUFFER_mWriteReg(BaseAddress, RegOffset, Data) \
Xil_Out32((BaseAddress) + (RegOffset), (u32)(Data))
/**
*
* Read a value from a AXI_VGA_FRAMEBUFFER register. A 32 bit read is performed.
* If the component is implemented in a smaller width, only the least
* significant data is read from the register. The most significant data
* will be read as 0.
*
* @param BaseAddress is the base address of the AXI_VGA_FRAMEBUFFER device.
* @param RegOffset is the register offset from the base to write to.
*
* @return Data is the data from the register.
*
* @note
* C-style signature:
* u32 AXI_VGA_FRAMEBUFFER_mReadReg(u32 BaseAddress, unsigned RegOffset)
*
*/
#define AXI_VGA_FRAMEBUFFER_mReadReg(BaseAddress, RegOffset) \
Xil_In32((BaseAddress) + (RegOffset))
/************************** Function Prototypes ****************************/
/**
*
* Run a self-test on the driver/device. Note this may be a destructive test if
* resets of the device are performed.
*
* If the hardware system is not built correctly, this function may never
* return to the caller.
*
* @param baseaddr_p is the base address of the AXI_VGA_FRAMEBUFFER instance to be worked on.
*
* @return
*
* - XST_SUCCESS if all self-test code passed
* - XST_FAILURE if any self-test code failed
*
* @note Caching must be turned off for this function to work.
* @note Self test may fail if data memory and device are not on the same bus.
*
*/
XStatus AXI_VGA_FRAMEBUFFER_Reg_SelfTest(void * baseaddr_p);
#endif // AXI_VGA_FRAMEBUFFER_H
|
yangzecai/2021-Huawei-Embedded-Competition
|
player/sdk/code/include/ACO.h
|
<reponame>yangzecai/2021-Huawei-Embedded-Competition<filename>player/sdk/code/include/ACO.h<gh_stars>0
#pragma once
#include "data.h"
#include <set>
using std::set;
class Ant {
public:
Ant(const vector<double> &envPhers, double alpha, double beta);
~Ant() = default;
Ant(const Ant &) = delete;
Ant &operator=(const Ant &) = delete;
void run();
const set<SateGraph::NodeIndex> &getRecvSateSet() const
{
return recvSateSet_;
}
private:
const vector<double> &envPhers_;
set<SateGraph::NodeIndex> recvSateSet_;
set<SateGraph::NodeIndex> uncoverBases_;
vector<bool> coverStatus_;
const uint8_t alpha_;
const uint8_t beta_;
struct Choice {
SateGraph::NodeIndex sate;
double probability;
size_t newCoverNum;
Power powerSum;
};
bool isCovered(SateGraph::NodeIndex base) const { return coverStatus_[base]; }
void selectRecvSate(SateGraph::NodeIndex base);
SateGraph::NodeIndex getRandUncoverBase()
{
return getRandElemFromSet<SateGraph::NodeIndex>(uncoverBases_);
}
Choice getChoice(SateGraph::NodeIndex sate);
void normProbs(vector<Choice> &choices);
const Choice &roulette(const vector<Choice> &choices);
void determineChoice(const Choice &choice);
void producePher();
void localSearch();
}; // class Ant
class ACO {
public:
ACO(double alpha, double beta, double rho, double epsilon, uint16_t antNum);
~ACO() = default;
void iterate(uint16_t iterNum, clock_t timeout = 270);
Power getMinPowerSum() const { return minPowerSum_; }
const set<SateGraph::NodeIndex> &getMinRecvSateSet() const
{
return minRecvSateSet_;
}
private:
const double alpha_;
const double beta_;
const double rho_;
const double epsilon_;
const uint8_t antNum_;
double maxPher_;
double minPher_;
vector<double> phers_;
vector<double> deltaPhers_;
Power minPowerSum_;
set<SateGraph::NodeIndex> minRecvSateSet_;
clock_t startTime_;
void updatePhers();
void updateDeltaPhers();
}; // class ACO
|
yangzecai/2021-Huawei-Embedded-Competition
|
player/sdk/code/include/Graph.h
|
#pragma once
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using std::vector;
using std::cout;
using std::endl;
using std::unordered_map;
using std::find;
template <typename Node> class Graph {
public:
using NodeIndex = typename vector<Node>::size_type;
using Dist = uint32_t;
struct Edge {
NodeIndex send;
NodeIndex recv;
Dist dist;
};
using Route = vector<NodeIndex>;
using AdjList = vector<vector<NodeIndex>>;
using AdjMatrix = vector<vector<Dist>>;
using Color = uint32_t;
static const Dist kInf;
Graph(const vector<Node> &nodes = vector<Node>(),
const vector<Edge> &edges = vector<Edge>());
virtual ~Graph() = default;
Graph(const Graph &) = delete;
Graph &operator=(const Graph &) = delete;
void swap(Graph &&rhs);
Graph(Graph &&rhs);
Graph &operator=(Graph &&rhs);
void addNode(const Node &node);
void addNode(Node &&node);
const vector<Node> &getNodes() const { return nodes_; }
const Node &getNode(NodeIndex i) const { return nodes_[i]; }
typename Node::ID getNodeID(NodeIndex i) const { return nodes_[i].id; }
void addEdge(const Edge &edge);
void addEdge(Edge &&edge);
const vector<Edge> &getEdges() const { return edges_; }
size_t getOrder() const { return nodes_.size(); }
size_t getDegree(NodeIndex i) const
{
updateAdjList();
return adjList_[i].size();
}
size_t getMaxDegree() const;
Dist getDist(NodeIndex i, NodeIndex j) const
{
updateAdjMatrix();
return adjMatrix_[i][j];
}
const AdjList &getAdjList() const;
const AdjList &getAdjListSorted() const;
const AdjMatrix &getAdjMatrix() const;
const vector<Color> &getColors() const;
Graph getGraphBar() const;
void displayNodesID() const; // for debug
void displayAdjList() const; // for debug
void displayAdjListID() const; // for debug
void displayColors() const; // for debug
private:
vector<Node> nodes_;
vector<Edge> edges_;
mutable bool isAdjListNew_;
mutable AdjList adjList_;
mutable bool isAdjMatrixNew_;
mutable AdjMatrix adjMatrix_;
mutable bool isColorsNew_;
mutable vector<Color> colors_;
void updateAdjList() const;
void updateAdjMatrix() const;
void updateColors() const;
void sortAdjList();
}; // class Graph
/*************************************define************************************/
template <typename Node>
const typename Graph<Node>::Dist Graph<Node>::kInf = UINT32_MAX;
template <typename Node>
Graph<Node>::Graph(const vector<Node> &nodes, const vector<Edge> &edges)
: nodes_(nodes)
, edges_(edges)
, isAdjListNew_(false)
, adjList_()
, isAdjMatrixNew_(false)
, adjMatrix_()
, isColorsNew_(false)
, colors_()
{
}
template <typename Node> void Graph<Node>::swap(Graph &&rhs)
{
using std::swap;
swap(this->nodes_, rhs.nodes_);
swap(this->edges_, rhs.edges_);
swap(this->isAdjListNew_, rhs.isAdjListNew_);
swap(this->adjList_, rhs.adjList_);
swap(this->isAdjMatrixNew_, rhs.isAdjMatrixNew_);
swap(this->adjMatrix_, rhs.adjMatrix_);
swap(this->isColorsNew_, rhs.isColorsNew_);
swap(this->colors_, rhs.colors_);
}
template <typename Node>
Graph<Node>::Graph(Graph &&rhs)
: nodes_(std::move(rhs.nodes_))
, edges_(std::move(rhs.edges_))
, isAdjListNew_(rhs.isAdjListNew_)
, adjList_(std::move(rhs.adjList_))
, isAdjMatrixNew_(rhs.isAdjMatrixNew_)
, adjMatrix_(std::move(rhs.adjMatrix_))
, isColorsNew_(rhs.isColorsNew_)
, colors_(std::move(rhs.colors_))
{
}
template <typename Node> Graph<Node> &Graph<Node>::operator=(Graph &&rhs)
{
swap(std::move(rhs));
return *this;
}
template <typename Node> void Graph<Node>::addNode(const Node &node)
{
isAdjListNew_ = false;
isAdjMatrixNew_ = false;
isColorsNew_ = false;
nodes_.push_back(node);
}
template <typename Node> void Graph<Node>::addNode(Node &&node)
{
isAdjListNew_ = false;
isAdjMatrixNew_ = false;
isColorsNew_ = false;
nodes_.push_back(std::move(node));
}
template <typename Node> void Graph<Node>::addEdge(const Edge &edge)
{
isAdjListNew_ = false;
isAdjMatrixNew_ = false;
isColorsNew_ = false;
edges_.push_back(edge);
}
template <typename Node> void Graph<Node>::addEdge(Edge &&edge)
{
isAdjListNew_ = false;
isAdjMatrixNew_ = false;
isColorsNew_ = false;
edges_.push_back(std::move(edge));
}
template <typename Node> size_t Graph<Node>::getMaxDegree() const
{
updateAdjList();
size_t ret = 0;
for (auto &item : adjList_) {
ret = max(ret, item.size());
}
return ret;
}
template <typename Node>
const typename Graph<Node>::AdjList &Graph<Node>::getAdjList() const
{
updateAdjList();
return adjList_;
}
template <typename Node>
const typename Graph<Node>::AdjList &Graph<Node>::getAdjListSorted() const
{
updateAdjList();
for (auto &item : adjList_) {
sort(item.begin(), item.end());
}
return adjList_;
}
template <typename Node>
const typename Graph<Node>::AdjMatrix &Graph<Node>::getAdjMatrix() const
{
updateAdjMatrix();
return adjMatrix_;
}
template <typename Node>
const vector<typename Graph<Node>::Color> &Graph<Node>::getColors() const
{
updateColors();
return colors_;
}
template <typename Node> void Graph<Node>::updateAdjList() const
{
if (!isAdjListNew_) {
adjList_ = AdjList(getOrder());
for (auto iter = edges_.begin(); iter != edges_.end(); ++iter) {
adjList_[iter->send].push_back(iter->recv);
adjList_[iter->recv].push_back(iter->send);
}
isAdjListNew_ = true;
}
}
template <typename Node> void Graph<Node>::updateAdjMatrix() const
{
if (!isAdjMatrixNew_) {
adjMatrix_ = AdjMatrix(getOrder(), vector<Dist>(getOrder(), kInf));
for (NodeIndex i = 0; i < nodes_.size(); ++i) {
adjMatrix_[i][i] = 0;
}
for (auto iter = edges_.begin(); iter != edges_.end(); ++iter) {
adjMatrix_[iter->send][iter->recv] = iter->dist;
adjMatrix_[iter->recv][iter->send] = iter->dist;
}
isAdjMatrixNew_ = true;
}
}
template <typename Node> void Graph<Node>::updateColors() const
{
if (!isColorsNew_) {
colors_ = vector<Color>(getOrder());
size_t maxColor = getMaxDegree() + 1;
getAdjListSorted();
for (NodeIndex node = 0; node < colors_.size(); ++node) {
vector<bool> usedColor(maxColor, false);
for (NodeIndex adjNode : adjList_[node]) {
if (node > adjNode) {
usedColor[colors_[adjNode]] = true;
} else {
auto iter = std::find(usedColor.begin(), usedColor.end(), false);
colors_[node] = iter - usedColor.begin();
break;
}
}
}
}
}
template <typename Node> Graph<Node> Graph<Node>::getGraphBar() const
{
Graph retGraph(nodes_);
updateAdjMatrix();
for (NodeIndex i = 0; i < adjMatrix_.size(); ++i) {
for (NodeIndex j = i + 1; j < adjMatrix_[0].size(); ++j) {
if (adjMatrix_[i][j] == kInf) {
retGraph.addEdge({i, j, 1});
}
}
}
return retGraph;
}
template <typename Node> void Graph<Node>::displayNodesID() const
{
cout << "------------nodes_id------------" << endl;
for (auto &n : nodes_) {
cout << n.id << " ";
}
cout << endl;
cout << "--------------------------------" << endl;
}
template <typename Node> void Graph<Node>::displayAdjList() const
{
updateAdjList();
cout << "------------adjlist------------" << endl;
for (NodeIndex i = 0; i < adjList_.size(); ++i) {
cout << i << " : ";
for (const NodeIndex j : adjList_[i]) {
cout << j << " ";
}
cout << endl;
}
cout << "-------------------------------" << endl;
}
template <typename Node> void Graph<Node>::displayAdjListID() const
{
updateAdjList();
cout << "-----------adjList_id----------" << endl;
for (NodeIndex i = 0; i < adjList_.size(); ++i) {
cout << getNodeID(i) << " : ";
for (const NodeIndex j : adjList_[i]) {
cout << getNodeID(j) << " ";
}
cout << endl;
}
cout << "-------------------------------" << endl;
}
template <typename Node> void Graph<Node>::displayColors() const
{
updateColors();
cout << "-------------colors--------------" << endl;
for (Color color : colors_) {
cout << color << " ";
}
cout << endl;
cout << "---------------------------------" << endl;
}
|
yangzecai/2021-Huawei-Embedded-Competition
|
player/sdk/code/include/data.h
|
<reponame>yangzecai/2021-Huawei-Embedded-Competition
#pragma once
#include "Graph.h"
#include <set>
#include <vector>
using std::set;
using std::vector;
struct Edge {
uint32_t send; // 发送站点
uint32_t recv; // 接受站点
uint32_t dist; // 距离
};
using Route = vector<uint32_t>;
struct Sate {
using ID = uint32_t;
ID id;
bool isSate;
};
using SateGraph = Graph<Sate>;
using Power = uint32_t;
extern SateGraph aGraph; /* aGraph : 当且仅当不同节点之间存在边时
之间有连线 */
extern SateGraph bGraph; /* bGraph : 当且仅当卫星和基站存在
长度小于最大路径的路时 之间有连线 */
extern Power kPowerPerDist;
extern Power kPowerPerSite;
extern SateGraph::Dist klimitDist;
extern vector<SateGraph::NodeIndex> baseSubset;
extern vector<SateGraph::NodeIndex> sateSubset;
extern vector<int> Csites;
SateGraph::NodeIndex
getNearSateFromSet(const set<SateGraph::NodeIndex> &recvSateSet,
SateGraph::NodeIndex base);
Power getPowerSum(const set<SateGraph::NodeIndex> &recvSateSet);
void removeRedundantSate(set<SateGraph::NodeIndex> &recvSateSet);
template <typename T> T getRandElemFromSet(const set<T> &s)
{
size_t index = rand() % s.size();
auto iter = s.begin();
for (size_t i = 0; i < index; ++i) {
++iter;
}
return *iter;
}
|
izzhong/ArabicToRomanNumeralsConverter
|
ArabicToRomanNumeralsConverterTestCase/ArabicToRomanNumeralsConverterTestCase/arabic_to_roman_mapping.h
|
<reponame>izzhong/ArabicToRomanNumeralsConverter<filename>ArabicToRomanNumeralsConverterTestCase/ArabicToRomanNumeralsConverterTestCase/arabic_to_roman_mapping.h
#pragma once
#include <string>
#include <array>
struct ArabicToRomanMapping
{
unsigned int arabicNumber;
std::string romanNumeral;
};
constexpr std::size_t numberOfMappings{ 13 };
using ArabicToRomanMappings = std::array<ArabicToRomanMapping, numberOfMappings>;
const ArabicToRomanMappings arabicToRomanMappings{ {
{1000,"M"},
{900,"CM"},
{500,"D"},
{400,"CD"},
{100,"C"},
{90,"XC"},
{50,"L"},
{40,"XL"},
{10,"X"},
{9,"IX"},
{5,"V"},
{4,"IV"},
{1,"I"},
} };
|
N1ghtRaven/lcdgfx
|
src/v2/lcd/base/display.h
|
<gh_stars>0
/*
MIT License
Copyright (c) 2018-2020, <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* @file display.h Drawing in hardware buffer
*/
#ifndef _NANO_DISPLAY_H_
#define _NANO_DISPLAY_H_
#include "canvas/point.h"
#include "canvas/rect.h"
#include "canvas/canvas.h"
#include "canvas/font.h"
#include "lcd_hal/io.h"
#include "nano_gfx_types.h"
#include "display_base.h"
/**
* @ingroup LCD_GENERIC_API
* @{
*/
/**
* NanoDisplayOps1 is template class for 1-bit operations.
*/
template <class I>
class NanoDisplayOps1: public NanoDisplayBase<I>
{
public:
/** number of bits per single pixel in buffer */
static const uint8_t BITS_PER_PIXEL = 1;
using NanoDisplayBase<I>::NanoDisplayBase;
/**
* Draws pixel on specified position
* @param x - position X
* @param y - position Y
* @note color can be set via setColor()
*/
void putPixel(lcdint_t x, lcdint_t y) __attribute__ ((noinline));
/**
* Draws horizontal or vertical line
* @param x1 - position X
* @param y1 - position Y
* @param y2 - position Y
* @note color can be set via setColor()
*/
void drawVLine(lcdint_t x1, lcdint_t y1, lcdint_t y2);
/**
* Draws horizontal or vertical line
* @param x1 - position X
* @param y1 - position Y
* @param x2 - position X
* @note color can be set via setColor()
*/
void drawHLine(lcdint_t x1, lcdint_t y1, lcdint_t x2);
/**
* Fills rectangle area
* @param x1 - position X
* @param y1 - position Y
* @param x2 - position X
* @param y2 - position Y
* @note color can be set via setColor()
*/
void fillRect(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) __attribute__((noinline));
/**
* Draws bitmap, located in Flash, on the display
* The bitmap should be in XBMP format
*
* @param x - horizontal position in pixels
* @param y - vertical position in blocks (pixels/8)
* @param w - width of bitmap in pixels
* @param h - height of bitmap in pixels (must be divided by 8)
* @param bitmap - pointer to data, located in Flash: each byte represents 8 vertical pixels.
*/
void drawXBitmap(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* @brief Draws monochrome bitmap in color buffer using color, specified via setColor() method
* Draws monochrome bitmap in color buffer using color, specified via setColor() method
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - monochrome bitmap data, located in flash
*
* @note There are 2 modes: transparent and non-transparent mode, - and 2 colors available: black and white.
* In non-transparent mode, when black color is selected, the monochrome image just inverted.
* In transparent mode, those pixels of source monochrome image, which are black, do not overwrite pixels
* in the screen buffer.
*/
void drawBitmap1(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap) __attribute__ ((noinline));
/**
* Draws bitmap, located in Flash, on the display
*
* @param x - horizontal position in pixels
* @param y - vertical position in pixels
* @param w - width of bitmap in pixels
* @param h - height of bitmap in pixels (must be divided by 8)
* @param buf - pointer to data, located in Flash: each byte represents 8 vertical pixels.
* @warning only for monochrome displays
*/
void gfx_drawMonoBitmap(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buf);
/**
* @brief Draws 4-bit gray-color bitmap in color buffer.
* Draws 4-bit gray-color bitmap in color buffer.
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - 4-bit gray-color bitmap data, located in flash
*/
void drawBitmap4(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* @brief Draws 8-bit color bitmap in color buffer.
* Draws 8-bit color bitmap in color buffer.
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - 8-bit color bitmap data, located in flash
*/
void drawBitmap8(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* Draw 16-bit color bitmap, located in Flash, directly to OLED display GDRAM.
* Each pixel of the bitmap is expected in 5-6-5 format.
*
* @param xpos start horizontal position in pixels
* @param ypos start vertical position in pixels
* @param w bitmap width in pixels
* @param h bitmap height in pixels
* @param bitmap pointer to Flash data, containing 16-bit color bitmap.
*/
void drawBitmap16(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* Draws bitmap, located in RAM, on the display
* Each byte represents 8 vertical pixels.
*
* ~~~~~~~~~~~~~~~{.cpp}
* // Draw small rectangle 3x8 at position 10,8
* uint8_t buffer[3] = { 0xFF, 0x81, 0xFF };
* display.drawBuffer1(10, 1, 3, 8, buffer);
* ~~~~~~~~~~~~~~~
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels (must be divided by 8)
* @param buffer pointer to data, located in SRAM: each byte represents 8 vertical pixels.
*/
void drawBuffer1(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Implements the same behavior as drawBuffer1, but much faster. This method has some limitations
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels (must be divided by 8)
* @param buffer pointer to data, located in SRAM: each byte represents 8 vertical pixels.
*/
void drawBuffer1Fast(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer);
/**
* Draws 4-bit bitmap, located in RAM, on the display
* Each byte represents two pixels in 4-4 format:
* refer to GRAY_COLOR4 to understand scheme, being used.
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in SRAM.
*/
void drawBuffer4(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Draws 8-bit bitmap, located in RAM, on the display
* Each byte represents one pixel in 2-2-3 format:
* refer to RGB_COLOR8 to understand RGB scheme, being used.
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in SRAM.
*/
void drawBuffer8(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Draws 16-bit bitmap, located in RAM, on the display
* Each pixel occupies 2 bytes (5-6-5 format): refer to RGB_COLOR16 to understand RGB scheme, being used.
*
* @param xpos horizontal position in pixels
* @param ypos vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in RAM.
*/
void drawBuffer16(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Clears canvas
*/
void clear();
/**
* Fill screen content with specified color
*
* @param color color to fill display with
*/
void fill(uint16_t color);
/**
* Draws single character to canvas
* @param c - character code to print
* @returns 0 if char is not printed
*/
uint8_t printChar(uint8_t c);
/**
* Writes single character to canvas
* @param c - character code to print
*/
size_t write(uint8_t c) __attribute__ ((noinline));
/**
* Print text at specified position to canvas
*
* @param xpos position in pixels
* @param y position in pixels
* @param ch pointer to NULL-terminated string.
* @param style specific font style to use
*
* @note Supports only STYLE_NORMAL and STYLE_BOLD
*/
void printFixed(lcdint_t xpos, lcdint_t y, const char *ch, EFontStyle style = STYLE_NORMAL) __attribute__ ((noinline));
#ifndef DOXYGEN_SHOULD_SKIP_THIS
void printFixed_oldStyle(uint8_t xpos, uint8_t y, const char *ch, EFontStyle style) __attribute__ ((noinline));
#endif
/**
* Prints text to screen using size fixed font, scaled by factor value. <br>
* Factor value 0 gives regular font size (6x8 for example) <br>
* Factor value 1 gives double font size (12x16 if 6x8 font is used) <br>
* Factor value 2 gives fourth font size (24x32 if 6x8 font is used) <br>
* Factor value 3 gives eighth font size (48x64 if 6x8 font is used) <br>
* @param xpos - horizontal position in pixels
* @param y - vertical position in pixels
* @param ch - NULL-terminated string to print
* @param style - font style (EFontStyle), normal by default.
* @param factor - 0, 1, 2, 3.
* @returns number of chars in string
* @see ssd1306_setFixedFont
* @warning ssd1306_printFixed2x() can output chars at fixed y positions: 0, 8, 16, 24, 32, etc.
* If you specify [10,18], ssd1306_printFixed2x() will output text starting at [10,16] position.
* @warning Be careful with you flash space! Do not mix too many different functions in single sketch.
* ssd1306_printFixedN() uses much flash: ~474 bytes, ssd1306_printFixed() needs 388 bytes.
* Placing both of these functions to your sketch will consume almost 1KiB.
*/
void printFixedN(lcdint_t xpos, lcdint_t y, const char *ch, EFontStyle style, uint8_t factor) __attribute__ ((noinline));
protected:
};
/**
* NanoDisplayOps4 is template class for 4-bit monochrome operations.
*/
template <class I>
class NanoDisplayOps4: public NanoDisplayBase<I>
{
public:
/** number of bits per single pixel in buffer */
static const uint8_t BITS_PER_PIXEL = 4;
using NanoDisplayBase<I>::NanoDisplayBase;
/**
* Draws pixel on specified position
* @param x - position X
* @param y - position Y
* @note color can be set via setColor()
*/
void putPixel(lcdint_t x, lcdint_t y) __attribute__ ((noinline));
/**
* Draws horizontal or vertical line
* @param x1 - position X
* @param y1 - position Y
* @param y2 - position Y
* @note color can be set via setColor()
*/
void drawVLine(lcdint_t x1, lcdint_t y1, lcdint_t y2);
/**
* Draws horizontal or vertical line
* @param x1 - position X
* @param y1 - position Y
* @param x2 - position X
* @note color can be set via setColor()
*/
void drawHLine(lcdint_t x1, lcdint_t y1, lcdint_t x2);
/**
* Fills rectangle area
* @param x1 - position X
* @param y1 - position Y
* @param x2 - position X
* @param y2 - position Y
* @note color can be set via setColor()
*/
void fillRect(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) __attribute__((noinline));
/**
* Draws bitmap, located in Flash, on the display
* The bitmap should be in XBMP format
*
* @param x - horizontal position in pixels
* @param y - vertical position in blocks (pixels/8)
* @param w - width of bitmap in pixels
* @param h - height of bitmap in pixels (must be divided by 8)
* @param bitmap - pointer to data, located in Flash: each byte represents 8 vertical pixels.
*/
void drawXBitmap(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* @brief Draws monochrome bitmap in color buffer using color, specified via setColor() method
* Draws monochrome bitmap in color buffer using color, specified via setColor() method
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - monochrome bitmap data, located in flash
*
* @note There are 2 modes: transparent and non-transparent mode, - and 2 colors available: black and white.
* In non-transparent mode, when black color is selected, the monochrome image just inverted.
* In transparent mode, those pixels of source monochrome image, which are black, do not overwrite pixels
* in the screen buffer.
*/
void drawBitmap1(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap) __attribute__ ((noinline));
/**
* @brief Draws 4-bit gray-color bitmap in color buffer.
* Draws 4-bit gray-color bitmap in color buffer.
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - 4-bit gray-color bitmap data, located in flash
*/
void drawBitmap4(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap) __attribute__ ((noinline));
/**
* @brief Draws 8-bit color bitmap in color buffer.
* Draws 8-bit color bitmap in color buffer.
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - 8-bit color bitmap data, located in flash
*/
void drawBitmap8(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* Draw 16-bit color bitmap, located in Flash, directly to OLED display GDRAM.
* Each pixel of the bitmap is expected in 5-6-5 format.
*
* @param xpos start horizontal position in pixels
* @param ypos start vertical position in pixels
* @param w bitmap width in pixels
* @param h bitmap height in pixels
* @param bitmap pointer to Flash data, containing 16-bit color bitmap.
*/
void drawBitmap16(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* Draws bitmap, located in RAM, on the display
* Each byte represents 8 vertical pixels.
*
* ~~~~~~~~~~~~~~~{.cpp}
* // Draw small rectangle 3x8 at position 10,8
* uint8_t buffer[3] = { 0xFF, 0x81, 0xFF };
* display.drawBuffer1(10, 1, 3, 8, buffer);
* ~~~~~~~~~~~~~~~
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels (must be divided by 8)
* @param buffer pointer to data, located in SRAM: each byte represents 8 vertical pixels.
*/
void drawBuffer1(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Implements the same behavior as drawBuffer1, but much faster. This method has some limitations
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels (must be divided by 8)
* @param buffer pointer to data, located in SRAM: each byte represents 8 vertical pixels.
*/
void drawBuffer1Fast(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer);
/**
* Draws 4-bit bitmap, located in RAM, on the display
* Each byte represents two pixels in 4-4 format:
* refer to GRAY_COLOR4 to understand scheme, being used.
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in SRAM.
*/
void drawBuffer4(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Draws 8-bit bitmap, located in RAM, on the display
* Each byte represents one pixel in 2-2-3 format:
* refer to RGB_COLOR8 to understand RGB scheme, being used.
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in SRAM.
*/
void drawBuffer8(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer);
/**
* Draws 16-bit bitmap, located in RAM, on the display
* Each pixel occupies 2 bytes (5-6-5 format): refer to RGB_COLOR16 to understand RGB scheme, being used.
*
* @param xpos horizontal position in pixels
* @param ypos vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in RAM.
*/
void drawBuffer16(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Clears canvas
*/
void clear();
/**
* Fill screen content with specified color
*
* @param color color to fill display with
*/
void fill(uint16_t color);
/**
* Draws single character to canvas
* @param c - character code to print
* @returns 0 if char is not printed
*/
uint8_t printChar(uint8_t c);
/**
* Writes single character to canvas
* @param c - character code to print
*/
size_t write(uint8_t c) __attribute__ ((noinline));
/**
* Print text at specified position to canvas
*
* @param xpos position in pixels
* @param y position in pixels
* @param ch pointer to NULL-terminated string.
* @param style specific font style to use
*
* @note Supports only STYLE_NORMAL and STYLE_BOLD
*/
void printFixed(lcdint_t xpos, lcdint_t y, const char *ch, EFontStyle style = STYLE_NORMAL) __attribute__ ((noinline));
protected:
};
/**
* NanoDisplayOps8 is template class for 8-bit operations.
*/
template <class I>
class NanoDisplayOps8: public NanoDisplayBase<I>
{
public:
/** number of bits per single pixel in buffer */
static const uint8_t BITS_PER_PIXEL = 8;
using NanoDisplayBase<I>::NanoDisplayBase;
/**
* Draws pixel on specified position
* @param x - position X
* @param y - position Y
* @note color can be set via setColor()
*/
void putPixel(lcdint_t x, lcdint_t y) __attribute__ ((noinline));
/**
* Draws horizontal or vertical line
* @param x1 - position X
* @param y1 - position Y
* @param y2 - position Y
* @note color can be set via setColor()
*/
void drawVLine(lcdint_t x1, lcdint_t y1, lcdint_t y2);
/**
* Draws horizontal or vertical line
* @param x1 - position X
* @param y1 - position Y
* @param x2 - position X
* @note color can be set via setColor()
*/
void drawHLine(lcdint_t x1, lcdint_t y1, lcdint_t x2);
/**
* Fills rectangle area
* @param x1 - position X
* @param y1 - position Y
* @param x2 - position X
* @param y2 - position Y
* @note color can be set via setColor()
*/
void fillRect(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) __attribute__((noinline));
/**
* Draws bitmap, located in Flash, on the display
* The bitmap should be in XBMP format
*
* @param x - horizontal position in pixels
* @param y - vertical position in blocks (pixels/8)
* @param w - width of bitmap in pixels
* @param h - height of bitmap in pixels (must be divided by 8)
* @param bitmap - pointer to data, located in Flash: each byte represents 8 vertical pixels.
*/
void drawXBitmap(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* @brief Draws monochrome bitmap in color buffer using color, specified via setColor() method
* Draws monochrome bitmap in color buffer using color, specified via setColor() method
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - monochrome bitmap data, located in flash
*
* @note There are 2 modes: transparent and non-transparent mode, - and 2 colors available: black and white.
* In non-transparent mode, when black color is selected, the monochrome image just inverted.
* In transparent mode, those pixels of source monochrome image, which are black, do not overwrite pixels
* in the screen buffer.
*/
void drawBitmap1(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap) __attribute__ ((noinline));
/**
* @brief Draws 4-bit gray-color bitmap in color buffer.
* Draws 4-bit gray-color bitmap in color buffer.
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - 4-bit gray-color bitmap data, located in flash
*/
void drawBitmap4(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap) __attribute__ ((noinline));
/**
* @brief Draws 8-bit color bitmap in color buffer.
* Draws 8-bit color bitmap in color buffer.
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - 8-bit color bitmap data, located in flash
*/
void drawBitmap8(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* Draw 16-bit color bitmap, located in Flash, directly to OLED display GDRAM.
* Each pixel of the bitmap is expected in 5-6-5 format.
*
* @param xpos start horizontal position in pixels
* @param ypos start vertical position in pixels
* @param w bitmap width in pixels
* @param h bitmap height in pixels
* @param bitmap pointer to Flash data, containing 16-bit color bitmap.
*/
void drawBitmap16(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* Draws bitmap, located in RAM, on the display
* Each byte represents 8 vertical pixels.
*
* ~~~~~~~~~~~~~~~{.cpp}
* // Draw small rectangle 3x8 at position 10,8
* uint8_t buffer[3] = { 0xFF, 0x81, 0xFF };
* display.drawBuffer1(10, 1, 3, 8, buffer);
* ~~~~~~~~~~~~~~~
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels (must be divided by 8)
* @param buffer pointer to data, located in SRAM: each byte represents 8 vertical pixels.
*/
void drawBuffer1(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Implements the same behavior as drawBuffer1, but much faster. This method has some limitations
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels (must be divided by 8)
* @param buffer pointer to data, located in SRAM: each byte represents 8 vertical pixels.
*/
void drawBuffer1Fast(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer);
/**
* Draws 4-bit bitmap, located in RAM, on the display
* Each byte represents two pixels in 4-4 format:
* refer to GRAY_COLOR4 to understand scheme, being used.
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in SRAM.
*/
void drawBuffer4(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Draws 8-bit bitmap, located in RAM, on the display
* Each byte represents one pixel in 2-2-3 format:
* refer to RGB_COLOR8 to understand RGB scheme, being used.
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in SRAM.
*/
void drawBuffer8(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer);
/**
* Draws 16-bit bitmap, located in RAM, on the display
* Each pixel occupies 2 bytes (5-6-5 format): refer to RGB_COLOR16 to understand RGB scheme, being used.
*
* @param xpos horizontal position in pixels
* @param ypos vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in RAM.
*/
void drawBuffer16(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Clears canvas
*/
void clear();
/**
* Fill screen content with specified color
*
* @param color color to fill display with
*/
void fill(uint16_t color);
/**
* Draws single character to canvas
* @param c - character code to print
* @returns 0 if char is not printed
*/
uint8_t printChar(uint8_t c);
/**
* Writes single character to canvas
* @param c - character code to print
*/
size_t write(uint8_t c) __attribute__ ((noinline));
/**
* Print text at specified position to canvas
*
* @param xpos position in pixels
* @param y position in pixels
* @param ch pointer to NULL-terminated string.
* @param style specific font style to use
*
* @note Supports only STYLE_NORMAL and STYLE_BOLD
*/
void printFixed(lcdint_t xpos, lcdint_t y, const char *ch, EFontStyle style = STYLE_NORMAL) __attribute__ ((noinline));
protected:
};
/**
* NanoDisplayOps16 is template class for 16-bit operations.
*/
template <class I>
class NanoDisplayOps16: public NanoDisplayBase<I>
{
public:
/** number of bits per single pixel in buffer */
static const uint8_t BITS_PER_PIXEL = 1;
using NanoDisplayBase<I>::NanoDisplayBase;
/**
* Draws pixel on specified position
* @param x - position X
* @param y - position Y
* @note color can be set via setColor()
*/
void putPixel(lcdint_t x, lcdint_t y) __attribute__ ((noinline));
/**
* Draws horizontal or vertical line
* @param x1 - position X
* @param y1 - position Y
* @param y2 - position Y
* @note color can be set via setColor()
*/
void drawVLine(lcdint_t x1, lcdint_t y1, lcdint_t y2);
/**
* Draws horizontal or vertical line
* @param x1 - position X
* @param y1 - position Y
* @param x2 - position X
* @note color can be set via setColor()
*/
void drawHLine(lcdint_t x1, lcdint_t y1, lcdint_t x2);
/**
* Fills rectangle area
* @param x1 - position X
* @param y1 - position Y
* @param x2 - position X
* @param y2 - position Y
* @note color can be set via setColor()
*/
void fillRect(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) __attribute__((noinline));
/**
* Draws bitmap, located in Flash, on the display
* The bitmap should be in XBMP format
*
* @param x - horizontal position in pixels
* @param y - vertical position in blocks (pixels/8)
* @param w - width of bitmap in pixels
* @param h - height of bitmap in pixels (must be divided by 8)
* @param bitmap - pointer to data, located in Flash: each byte represents 8 vertical pixels.
*/
void drawXBitmap(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* @brief Draws monochrome bitmap in color buffer using color, specified via setColor() method
* Draws monochrome bitmap in color buffer using color, specified via setColor() method
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - monochrome bitmap data, located in flash
*
* @note There are 2 modes: transparent and non-transparent mode, - and 2 colors available: black and white.
* In non-transparent mode, when black color is selected, the monochrome image just inverted.
* In transparent mode, those pixels of source monochrome image, which are black, do not overwrite pixels
* in the screen buffer.
*/
void drawBitmap1(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap) __attribute__ ((noinline));
/**
* @brief Draws 4-bit gray-color bitmap in color buffer.
* Draws 4-bit gray-color bitmap in color buffer.
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - 4-bit gray-color bitmap data, located in flash
*/
void drawBitmap4(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap) __attribute__ ((noinline));
/**
* @brief Draws 8-bit color bitmap in color buffer.
* Draws 8-bit color bitmap in color buffer.
* @param x - position X in pixels
* @param y - position Y in pixels
* @param w - width in pixels
* @param h - height in pixels
* @param bitmap - 8-bit color bitmap data, located in flash
*/
void drawBitmap8(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* Draw 16-bit color bitmap, located in Flash, directly to OLED display GDRAM.
* Each pixel of the bitmap is expected in 5-6-5 format.
*
* @param xpos start horizontal position in pixels
* @param ypos start vertical position in pixels
* @param w bitmap width in pixels
* @param h bitmap height in pixels
* @param bitmap pointer to Flash data, containing 16-bit color bitmap.
*/
void drawBitmap16(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *bitmap);
/**
* Draws bitmap, located in RAM, on the display
* Each byte represents 8 vertical pixels.
*
* ~~~~~~~~~~~~~~~{.cpp}
* // Draw small rectangle 3x8 at position 10,8
* uint8_t buffer[3] = { 0xFF, 0x81, 0xFF };
* display.drawBuffer1(10, 1, 3, 8, buffer);
* ~~~~~~~~~~~~~~~
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels (must be divided by 8)
* @param buffer pointer to data, located in SRAM: each byte represents 8 vertical pixels.
*/
void drawBuffer1(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Implements the same behavior as drawBuffer1, but much faster. This method has some limitations
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels (must be divided by 8)
* @param buffer pointer to data, located in SRAM: each byte represents 8 vertical pixels.
*/
void drawBuffer1Fast(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer);
/**
* Draws 4-bit bitmap, located in RAM, on the display
* Each byte represents two pixels in 4-4 format:
* refer to GRAY_COLOR4 to understand scheme, being used.
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in SRAM.
*/
void drawBuffer4(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Draws 8-bit bitmap, located in RAM, on the display
* Each byte represents one pixel in 2-2-3 format:
* refer to RGB_COLOR8 to understand RGB scheme, being used.
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in SRAM.
*/
void drawBuffer8(lcdint_t x, lcdint_t y, lcduint_t w, lcduint_t h, const uint8_t *buffer);
/**
* Draws 16-bit bitmap, located in RAM, on the display
* Each pixel occupies 2 bytes (5-6-5 format): refer to RGB_COLOR16 to understand RGB scheme, being used.
*
* @param xpos horizontal position in pixels
* @param ypos vertical position in pixels
* @param w width of bitmap in pixels
* @param h height of bitmap in pixels
* @param buffer pointer to data, located in RAM.
*/
void drawBuffer16(lcdint_t xpos, lcdint_t ypos, lcduint_t w, lcduint_t h, const uint8_t *buffer) __attribute__ ((noinline));
/**
* Clears canvas
*/
void clear();
/**
* Fill screen content with specified color
*
* @param color color to fill display with
*/
void fill(uint16_t color);
/**
* Draws single character to canvas
* @param c - character code to print
* @returns 0 if char is not printed
*/
uint8_t printChar(uint8_t c);
/**
* Writes single character to canvas
* @param c - character code to print
*/
size_t write(uint8_t c) __attribute__ ((noinline));
/**
* Print text at specified position to canvas
*
* @param xpos position in pixels
* @param y position in pixels
* @param ch pointer to NULL-terminated string.
* @param style specific font style to use
*
* @note Supports only STYLE_NORMAL and STYLE_BOLD
*/
void printFixed(lcdint_t xpos, lcdint_t y, const char *ch, EFontStyle style = STYLE_NORMAL) __attribute__ ((noinline));
protected:
};
/**
* NanoCanvasOps provides operations for drawing in memory buffer.
* Depending on BPP argument, this class can work with 1,8,16-bit canvas areas.
*/
template <class O, class I>
class NanoDisplayOps: public O
{
public:
using O::O;
using O::putPixel;
/**
* Draws pixel on specified position
* @param p - NanoPoint
* @note color can be set via setColor()
*/
void putPixel(const NanoPoint &p);
/**
* Draws line
* @param x1 - position X
* @param y1 - position Y
* @param x2 - position X
* @param y2 - position Y
* @note color can be set via setColor()
*/
void drawLine(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2);
/**
* Draws line
* @param rect - structure, describing rectangle area
* @note color can be set via setColor()
*/
void drawLine(const NanoRect &rect);
/**
* Draws rectangle
* @param x1 - position X
* @param y1 - position Y
* @param x2 - position X
* @param y2 - position Y
* @note color can be set via setColor()
*/
void drawRect(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2);
/**
* Draws rectangle
* @param rect - structure, describing rectangle area
* @note color can be set via setColor()
*/
void drawRect(const NanoRect &rect);
using O::fillRect;
/**
* Fills rectangle area
* @param rect - structure, describing rectangle area
* @note color can be set via setColor()
*/
void fillRect(const NanoRect &rect);
/**
* Draws 1-bit canvas on lcd display
*
* @param x x position in pixels
* @param y y position in pixels
* @param canvas 1-bit canvas to draw on the screen.
*/
void drawCanvas(lcdint_t x, lcdint_t y, NanoCanvasOps<1> &canvas) __attribute__ ((noinline));
/**
* Draws 4-bit canvas on lcd display
*
* @param x x position in pixels
* @param y y position in pixels
* @param canvas 4-bit canvas to draw on the screen.
*/
void drawCanvas(lcdint_t x, lcdint_t y, NanoCanvasOps<4> &canvas) __attribute__ ((noinline));
/**
* Draws 8-bit canvas on lcd display
*
* @param x x position in pixels
* @param y y position in pixels
* @param canvas 8-bit canvas to draw on the screen.
*/
void drawCanvas(lcdint_t x, lcdint_t y, NanoCanvasOps<8> &canvas) __attribute__ ((noinline));
/**
* Draws 16-bit canvas on lcd display
*
* @param x x position in pixels
* @param y y position in pixels
* @param canvas 16-bit canvas to draw on the screen.
*/
void drawCanvas(lcdint_t x, lcdint_t y, NanoCanvasOps<16> &canvas) __attribute__ ((noinline));
/**
* Print text at specified position to canvas
*
* @param xpos position in pixels
* @param y position in pixels
* @param ch pointer to NULL-terminated string, located in flash
* @param style specific font style to use
*
* @note Supports only STYLE_NORMAL and STYLE_BOLD
*/
void printFixedPgm(lcdint_t xpos, lcdint_t y, const char *ch, EFontStyle style = STYLE_NORMAL) __attribute__ ((noinline));
using O::write;
/**
* Prints text at current cursor position.
* To specify cursor position using setTextCursor() method.
*
* @param str text to print (null-terminated string)
*/
void write(const char *str);
/**
* Prints number at current cursor position
* To specify cursor position using setTextCursor() method.
*
* @param number integer number to print
*/
void print(int number);
/**
* Creates menu object with the provided list of menu items.
* List of menu items (strings) must exist all until menu object is no longer needed.
* Selection is set to the first item by default.
*
* @param menu pointer to SAppMenu structure
* @param items array of null-termintated strings (located in SRAM)
* @param count count of menu items in the array
* @param rect screen area to use for menu
*/
void createMenu(SAppMenu *menu, const char **items, uint8_t count, const NanoRect &rect = {});
/**
* Shows menu items on the display. If menu items cannot fit the display,
* the function provides scrolling.
*
* @param menu pointer to SAppMenu structure
*/
void showMenu( SAppMenu *menu);
/**
* Shows menu items on the display. If menu items cannot fit the display,
* the function provides scrolling. Unlike showMenu() this implementation
* uses more graph functions and requires more flash, but result looks better.
*
* @param menu pointer to SAppMenu structure
*/
void showMenuSmooth( SAppMenu *menu );
/**
* Updates menu items on the display. That is if selection is changed,
* the function will update only those areas, affected by the change.
*
* @param menu Pointer to SAppMenu structure
*/
void updateMenu(SAppMenu *menu);
/**
* Updates menu items on the display. That is if selection is changed,
* the function will update only those areas, affected by the change.
* Unlike showMenu() this implementation uses more graph functions
* and requires more flash, but result looks better.
*
* @param menu Pointer to SAppMenu structure
*/
void updateMenuSmooth(SAppMenu *menu);
/**
* Returns currently selected menu item.
* First item has zero-index.
*
* @param menu pointer to SAppMenu structure
*
*/
uint8_t menuSelection(SAppMenu *menu);
/**
* Moves selection pointer down by 1 item. If there are no items below,
* it will set selection pointer to the first item.
* Use updateMenu() to refresh menu state on the display.
*
* @param menu pointer to SAppMenu structure
*/
void menuDown(SAppMenu *menu);
/**
* Moves selection pointer up by 1 item. If selected item is the first one,
* then selection pointer will set to the last item in menu list.
* Use updateMenu() to refresh menu state on the display.
*
* @param menu pointer to SAppMenu structure
*/
void menuUp(SAppMenu *menu);
/**
* Displays progress bar in the middle of the display.
*
* @param progress progress in range 0 - 100.
*/
void drawProgressBar(int8_t progress);
/**
* Displays window at specified position and of specified size
*
* @param x x position in pixels from top-lef corner
* @param y y position in pixels from top-lef corner
* @param width width of window to draw. Can be 0.
* @param height height of windows to draw. Can be 0.
* @param caption text to display as caption
* @param blank true if content inside window should be blanked
*/
void drawWindow(lcdint_t x, lcdint_t y,
lcduint_t width, lcduint_t height,
const char *caption, bool blank);
protected:
/**
* Initializes interface and display
*/
virtual void begin() = 0;
/**
* closes interface to lcd display
*/
virtual void end() = 0;
};
#include "ssd1306_1bit.inl"
#include "ssd1306_4bit.inl"
#include "ssd1306_8bit.inl"
#include "ssd1306_16bit.inl"
#include "ssd1306_common.inl"
/**
* @}
*/
#endif
|
N1ghtRaven/lcdgfx
|
src/lcd_hal/UserSettings.h
|
/*
MIT License
Copyright (c) 2018-2019, <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* @file lcd_hal/UserSettings.h lcdgfx modules configuration.
*/
#pragma once
/**
* @defgroup SSD1306_LIBRARY_CONFIG CONFIG: ssd1306 library configuration
* @{
*
* @brief Group of settings allowing to disable/enable library modules
*
* @details Arduino IDE (at least as for 1.8.2) has a lack library configuration functionality.
* Some Arduino standard libraries are built the way, if you include them to the project,
* but do not use any functions from the, they still eat RAM and Flash on you EVK board.
* To avoid this, you need competely avoid including of such libraries. SSD1306 library
* has a wide interfaces support for different platforms, and even if you don't use
* SSD1306 communication via Arduino Wire/Spi/HardwareSerial libraries, those ones do
* bad things with your sketch size.
* To avoid this you can manually disable SSD1306 modules, you don't need in UserSettings.h
* header file, and gain another 100-200 bytes of RAM and 300-500 bytes of Flash.
*/
/* Comment out options below if you don't need support in the library, *
* and want to reduce memory consumption. */
/** Define this macro if you need to enable software I2C module for compilation */
#define CONFIG_SOFTWARE_I2C_ENABLE
/** Define this macro if you need to enable TWI I2C module for compilation */
#define CONFIG_TWI_I2C_ENABLE
/** Define this macro if you need to enable AVR SPI module for compilation */
#define CONFIG_AVR_SPI_ENABLE
/** Define this macro if you need to enable USI SPI module for compilation */
#define CONFIG_USI_SPI_ENABLE
/** Define this macro if you need to enable AVR UART module for compilation */
#define CONFIG_AVR_UART_ENABLE
/** Define this macro if you need to enable VGA module for compilation */
#define CONFIG_VGA_ENABLE
/** Define this macro if you need to enable Adafruit GFX canvas support for compilation */
#ifndef CONFIG_ADAFRUIT_GFX_ENABLE
//#define CONFIG_ADAFRUIT_GFX_ENABLE
#endif
/**
* Define this macro if platform specific i2c interface is implemented in SSD1306 HAL.
* If you use Arduino platform, this macro enables Arduino Wire library module for compilation.
*/
#define CONFIG_PLATFORM_I2C_ENABLE
/**
* Define this macro if platform specific spi interface is implemented in SSD1306 HAL
* If you use Arduino platform, this macro enables Arduino SPI library module for compilation.
*/
#define CONFIG_PLATFORM_SPI_ENABLE
/** Define this macro if you need to enable Linux I2C module for compilation */
#define CONFIG_LINUX_I2C_ENABLE
/** Define this macro if you need to enable Linux SPI module for compilation */
#define CONFIG_LINUX_SPI_ENABLE
/** Define this macro if you need to enable Arduino Wire module for compilation */
#define CONFIG_ARDUINO_I2C_ENABLE
/** Define this macro if you need to enable Arduino SPI module for compilation */
#define CONFIG_ARDUINO_SPI_ENABLE
/** Define this macro if you need to enable ESP32 I2C module for compilation */
#define CONFIG_ESP32_I2C_ENABLE
/** Define this macro if you need to enable ESP32 SPI module for compilation */
#define CONFIG_ESP32_SPI_ENABLE
/**
* Defines, whenever ssd1306 library supports unicode.
* Support of unicode increases RAM and Flasg memory consumption
*/
#define CONFIG_SSD1306_UNICODE_ENABLE
/**
* @}
*/
|
N1ghtRaven/lcdgfx
|
src/canvas/canvas_types.h
|
<filename>src/canvas/canvas_types.h<gh_stars>0
/*
MIT License
Copyright (c) 2017-2019, <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* @file canvas/canvas_types.h Basic structures of canvas gfx library
*/
#pragma once
#include "canvas/UserSettings.h"
#if defined(ARDUINO)
#include <Arduino.h>
#elif defined(__AVR__)
#include <avr/pgmspace.h>
#else
#endif
#include <stdint.h>
#include <stddef.h>
/** Flag means that more chars are required to decode utf-8 */
#define SSD1306_MORE_CHARS_REQUIRED 0xffff
#ifndef DOXYGEN_SHOULD_SKIP_THIS
#ifndef PROGMEM
#define PROGMEM
#endif
#endif
/** Macro to generate 8-bit color */
#define RGB_COLOR8(r,g,b) ( (r & 0xE0) | ((g >> 3)&0x1C) | (b>>6) )
/** Macro to generate 4-bit monochrome color from gray component */
#define GRAY_COLOR4(gray) ( ((gray >> 4) & 0x0F) | (gray & 0xF0) )
/** Macro to generate 4-bit monochrome color from RGB */
#define RGB_COLOR4(r,g,b) ( (r >> 2) + (g >> 1) + (b >> 2) )
/** Macro to convert 8-bit RGB to 4-bit monochrome format */
#define RGB8_TO_GRAY4(rgb) ( (rgb >> 6) + ((rgb >> 2) & 0x07) + (rgb & 0x03) )
/** Macro to generate 16-bit RGB color */
#define RGB_COLOR16(r,g,b) ( ((r<<8) & 0xF800) | ((g << 3)&0x07E0) | (b>>3) )
/** Macro to convert 3-3-2 color to 5-6-5 color */
#define RGB8_TO_RGB16(c) ( (((uint16_t)c & 0b11100000) << 8) | \
(((uint16_t)c & 0b00011100) << 6) | \
(((uint16_t)c & 0b00000011) << 3) )
/** Macro to convert 5-6-5 color to 3-3-2 color */
#define RGB16_TO_RGB8(c) ( ((uint16_t)(c >> 8) & 0b11100000) | \
((uint16_t)(c >> 6) & 0b00011100) | \
((uint16_t)(c >> 3) & 0b00000011) )
#if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) || \
defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
/** internal int type, used by the library. Important for uC with low SRAM */
typedef int8_t lcdint_t;
/** internal int type, used by the library. Important for uC with low SRAM */
typedef uint8_t lcduint_t;
#else
/** internal int type, used by the library. Important for uC with low SRAM */
typedef int lcdint_t;
/** internal int type, used by the library. Important for uC with low SRAM */
typedef unsigned int lcduint_t;
#endif
/** Supported font styles */
typedef enum
{
STYLE_NORMAL,
STYLE_BOLD,
STYLE_ITALIC,
} EFontStyle;
enum
{
CANVAS_MODE_BASIC = 0x00,
/** If the flag is specified, text cursor is moved to new line when end of screen is reached */
CANVAS_TEXT_WRAP = 0x01,
/** This flag make bitmaps transparent (Black color) */
CANVAS_MODE_TRANSPARENT = 0x02,
/** If the flag is specified, text cursor is moved to new line when end of canvas is reached */
CANVAS_TEXT_WRAP_LOCAL = 0x04,
};
/** Supported scale font values */
typedef enum
{
FONT_SIZE_NORMAL = 0,
FONT_SIZE_2X = 1,
FONT_SIZE_4X = 2,
FONT_SIZE_8X = 3,
} EFontSize;
#pragma pack(push, 1)
/** Structure describes font format in memory */
typedef struct
{
uint8_t type; ///< font type: 0 - Fixed Font
uint8_t width; ///< width in pixels
uint8_t height; ///< height in pixels
uint8_t ascii_offset; ///< ascii offset
} SFontHeaderRecord;
#pragma pack(pop)
/** Structure is used for internal font presentation */
typedef struct
{
SFontHeaderRecord h; ///< record, containing information on font
uint8_t count; ///< count of characters
uint8_t pages; ///< height in pages (each page height is 8-pixels)
uint8_t glyph_size; ///< glyph size in bytes
const uint8_t *primary_table; ///< font chars bits
#ifdef CONFIG_SSD1306_UNICODE_ENABLE
const uint8_t *secondary_table; ///< font chars bits
#endif
} SFixedFontInfo;
/** Structure describes single char information */
typedef struct
{
uint8_t width; ///< char width in pixels
uint8_t height; ///< char height in pixels
uint8_t spacing; ///< additional spaces after char in pixels
const uint8_t *glyph; ///< char data, located in progmem.
} SCharInfo;
/**
* Describes menu object
*/
typedef struct
{
/// list of menu items of the menu
const char **items;
/// count of menu items in the menu
uint8_t count;
/// currently selected item. Internally updated.
uint8_t selection;
/// selected item, when last redraw operation was performed. Internally updated.
uint8_t oldSelection;
/// position of menu scrolling. Internally updated
uint8_t scrollPosition;
/// top offset
lcdint_t top;
/// left offset
lcdint_t left;
/// width of menu
lcduint_t width;
/// height of menu
lcduint_t height;
} SAppMenu;
|
N1ghtRaven/lcdgfx
|
src/v2/lcd/base/display_base.h
|
/*
MIT License
Copyright (c) 2018-2020, <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* @file display_base.h Basic display capabilities implementation
*/
#ifndef _DISPLAY_BASE_H_
#define _DISPLAY_BASE_H_
#include "lcd_hal/io.h"
#include "nano_gfx_types.h"
#include "canvas/point.h"
#include "canvas/rect.h"
#include "canvas/font.h"
/**
* @ingroup LCD_GENERIC_API
* @{
*/
#ifdef __cplusplus
extern "C"
{
#endif
extern uint8_t s_ssd1306_invertByte;
#ifdef __cplusplus
}
#endif
/**
* Class implements basic display operations for the library:
* It stores reference to communication interafce, display size, etc.
*/
template <class I>
class NanoDisplayBase
{
public:
/**
* Creates new empty base display object.
* If you this constructor is used, you must call begin() method before
* working with canvas.
*/
NanoDisplayBase(I& intf): m_intf( intf ) {}
/**
* Sets offset
* @param ox - X offset in pixels
* @param oy - Y offset in pixels
*/
void setOffset(lcdint_t ox, lcdint_t oy) { };
/**
* Returns right-bottom point of the canvas in offset terms.
* If offset is (0,0), then offsetEnd() will return (width-1,height-1).
*/
const NanoPoint offsetEnd() const
{
return (NanoPoint){ (lcdint_t)(m_w-1), (lcdint_t)(m_h-1) };
}
/**
* Returns rectangle area, covered by canvas in offset terms.
* If offset is (0,0), then rect() will return ((0,0),(width-1,height-1))
*/
const NanoRect rect() const
{
return { (NanoPoint){0,0}, offsetEnd() };
}
/**
* Returns width of the display in pixels.
*/
lcduint_t width() { return m_w; }
/**
* Returns height of the display in pixels.
*/
lcduint_t height() { return m_h; }
/**
* Swaps width and height dimensions
*/
void swapDimensions()
{
lcduint_t t = m_w;
m_w = m_h;
m_h = t;
}
/**
* Sets color for monochrome operations
* @param color - color to set (refer to RGB_COLOR8 definition)
*/
void setColor(uint16_t color) { m_color = color; };
/**
* All drawing functions start to work in negative mode.
* Old picture on the display remains unchanged.
*/
void negativeMode() { s_ssd1306_invertByte = 0xFF; }
/**
* All drawing functions start to work in positive (default) mode.
* Old picture on the display remains unchanged.
*/
void positiveMode() { s_ssd1306_invertByte = 0x00; }
/**
* Returns reference to interface communicator.
* This interface can be used to use display hardware related
* features.
*/
I& getInterface() { return m_intf; }
/**
* Sets new font to use with print functions.
* If multiple oled displays are used in single application,
* this method allows to use different fonts for different
* displays.
*
* @param font reference to font object (NanoFont)
*/
void setFont( NanoFont &font ) { m_font = &font; }
/**
* Returns reference to NanoFont object, currently used by Display
*/
NanoFont &getFont() { return *m_font; }
/**
* Sets new font to use with print functions.
* If multiple oled displays are used in single application,
* this method can cause conflicts.
*
* @warning use this method only if single display is used in project
*
* @param progmemFont pointer to font data in flash (refer to NanoFont::loadFixedFont)
*/
void setFixedFont( const uint8_t *progmemFont )
{
g_canvas_font.loadFixedFont( progmemFont );
setFont( g_canvas_font );
}
#ifndef DOXYGEN_SHOULD_SKIP_THIS
void setFixedFont_oldStyle( const uint8_t *progmemFont )
{
g_canvas_font.loadFixedFont_oldStyle( progmemFont );
setFont( g_canvas_font );
}
#endif
/**
* Sets new font to use with print functions.
* If multiple oled displays are used in single application,
* this method can cause conflicts.
*
* @warning use this method only if single display is used in project
*
* @param progmemFont pointer to font data in flash (refer to NanoFont::loadFixedFont)
* @param secondaryFont pointer to font data in flash (refer to NanoFont::loadSecondaryFont)
*/
void setFixedFont( const uint8_t *progmemFont, const uint8_t *secondaryFont )
{
g_canvas_font.loadFixedFont( progmemFont );
if ( secondaryFont )
{
g_canvas_font.loadSecondaryFont( secondaryFont );
}
setFont( g_canvas_font );
}
/**
* Sets new font to use with print functions.
* If multiple oled displays are used in single application,
* this method can cause conflicts.
*
* @warning use this method only if single display is used in project
*
* @param progmemFont pointer to font data in flash (refer to NanoFont::loadFreeFont)
* @param secondaryFont pointer to font data in flash (refer to NanoFont::loadSecondaryFont)
*/
void setFreeFont( const uint8_t *progmemFont, const uint8_t *secondaryFont = nullptr )
{
g_canvas_font.loadFreeFont( progmemFont );
if ( secondaryFont )
{
g_canvas_font.loadSecondaryFont( secondaryFont );
}
setFont( g_canvas_font );
}
/**
* Function sets text cursor position for write() functions
*
* @param x horizontal position in pixels
* @param y vertical position in pixels
*/
void setTextCursor( lcdint_t x, lcdint_t y )
{
m_cursorX = x;
m_cursorY = y;
}
protected:
lcduint_t m_w = 0; ///< width of NanoCanvas area in pixels
lcduint_t m_h = 0; ///< height of NanoCanvas area in pixels
lcduint_t m_p = 0; ///< number of bits, used by width value: 3 equals to 8 pixels width
lcdint_t m_cursorX = 0; ///< current X cursor position for text output
lcdint_t m_cursorY = 0; ///< current Y cursor position for text output
uint8_t m_textMode = 0; ///< Flags for current NanoCanvas mode
EFontStyle m_fontStyle; ///< currently active font style
uint16_t m_color = 0xFFFF; ///< current color for monochrome operations
NanoFont *m_font = nullptr; ///< currently set font
I& m_intf; ///< communication interface with the display
};
/**
* @}
*/
#endif
|
N1ghtRaven/lcdgfx
|
src/lcd_hal/interface.h
|
/*
MIT License
Copyright (c) 2017-2019, <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* @file lcd_hal/interface.h LCD interface functions.
*/
#ifndef _LCD_HAL_INTERFACE_H_
#define _LCD_HAL_INTERFACE_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LCD_HW_INTERFACE_API I2C/SPI: physical interface functions
* @{
*
* @brief i2c/spi initialization functions for different platforms
*
* @details This group of API functions serves to prepare the library to work via specific hardware
* interface. There are a bunch of functions for different platforms. In general display
* initialization goes in two steps: hardware interface initialization, and then display
* driver initialization. But there are functions, which combine 2 steps in single call:
* ssd1306_128x64_i2c_initEx(), ssd1351_128x128_spi_init(), etc.
*/
/**
* Structure describes i2c platform configuration
*
* @warning Not all fields are used by specific platforms
*/
typedef struct
{
/**
* bus id number. this parameter is valid for Linux, ESP32.
* If -1 is pointed, it defaults to platform specific i2c bus (Linux i2c-dev0, esp32 I2C_NUM_0).
*/
int8_t busId;
/**
* Address of i2c device to control. This is mandatory argument for all platforms
*/
uint8_t addr;
/**
* Pin to use as i2c clock pin. This parameter is not used in Linux.
* If -1 is pointed, the library uses default clock pin for specific platform.
*/
int8_t scl;
/**
* Pin to use as i2c data pin. This parameter is not used in Linux.
* If -1 is pointed, the library uses default data pin for specific platform.
*/
int8_t sda;
/**
* Frequency in HZ to run spi bus at. Zero value defaults to platform optimal clock
* speed (100kHz or 400kHz depending on platform).
*/
uint32_t frequency;
} SPlatformI2cConfig;
/**
* Structure describes spi platform configuration
*
* @warning Not all fields are used by specific platforms
*/
typedef struct
{
/**
* bus id number. this parameter is valid for Linux, ESP32.
* If -1 is pointed, it defaults to platform specific i2c bus (Linux spidev1.X, esp32 VSPI_HOST).
*/
int8_t busId;
/**
* parameter is optional for all platforms, except Linux.
* If chip select pin is not used, it should be set to -1
* For Linux platform devId should be pointed, if -1, it defaults to spidevX.0
*/
union
{
int8_t cs;
int8_t devId;
};
/**
* Data command control pin number. This pin assignment is mandatory
*/
int8_t dc;
/**
* Frequency in HZ to run spi bus at. If 0, it defaults to max frequency, supported
* by platform
*/
uint32_t frequency;
/**
* Optional - spi clock pin number. -1 if to use default spi clock pin.
* This is required for ESP32 platform only.
*/
int8_t scl; // clk
/**
* Optional - spi data MOSI pin number. -1 if to use default spi MOSI pin.
* This is required for ESP32 platform only.
*/
int8_t sda; // mosi
} SPlatformSpiConfig;
/** Describes low level hardware API for C-style code */
typedef struct
{
/**
* Indicates if spi or i2c interface is used.
*/
uint8_t spi;
/**
* Starts communication with SSD1306 display.
*/
void (*start)(void);
/**
* Ends communication with SSD1306 display.
*/
void (*stop)(void);
/**
* Sends byte to SSD1306 device
* @param data - byte to send
*/
void (*send)(uint8_t data);
/**
* @brief Sends bytes to SSD1306 device
*
* Sends bytes to SSD1306 device. This functions gives
* ~ 30% performance increase than ssd1306_intf.send.
*
* @param buffer - bytes to send
* @param size - number of bytes to send
*/
void (*send_buffer)(const uint8_t *buffer, uint16_t size);
/**
* @brief deinitializes internal resources, allocated for interface.
*
* Deinitializes internal resources, allocated for interface.
* There is no need to use this function for microcontrollers. In general
* the function has meaning in Linux-like systems.
*/
void (*close)(void);
} ssd1306_interface_t;
/**
* Holds pointers to functions of currently initialized interface.
*/
extern ssd1306_interface_t ssd1306_intf;
/**
* chip enable pin to controll lcd display over spi
* @warning C-style API only
*/
extern int8_t s_ssd1306_cs;
/**
* data/command control pin for spi interface of lcd display
* @warning C-style API only
*/
extern int8_t s_ssd1306_dc;
/**
* maximum SPI clock, supported by OLED display
* @warning C-style API only
*/
extern uint32_t s_ssd1306_spi_clock;
/**
* Sends command to SSD1306 device: includes initiating of
* transaction, sending data and completing transaction.
* @param command - command to send
* @warning C-style API only
*/
void ssd1306_sendCommand(uint8_t command);
/**
* Starts transaction for sending commands.
* @warning C-style API only
*/
void ssd1306_commandStart(void);
/**
* Starts transaction for sending bitmap data.
* @warning C-style API only
*/
void ssd1306_dataStart(void);
/**
* Switches spi to data(1) or command(0) mode.
* @param mode - 1 data mode
* 0 command mode
* @warning C-style API only
*/
void ssd1306_spiDataMode(uint8_t mode);
#ifndef DOXYGEN_SHOULD_SKIP_THIS
void ssd1306_resetController(int8_t rstPin, uint8_t delayMs);
void ssd1306_resetController2(int8_t rstPin, uint8_t delayMs);
#endif
#ifdef __cplusplus
}
#endif
/**
* @}
*/
// ----------------------------------------------------------------------------
#endif
|
N1ghtRaven/lcdgfx
|
src/v2/lcd/pcd8544/lcd_pcd8544.h
|
<filename>src/v2/lcd/pcd8544/lcd_pcd8544.h
/*
MIT License
Copyright (c) 2019-2020, <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* !!! THIS FILE IS AUTO GENERATED !!! */
/**
* @file lcd_pcd8544.h support for LCD PCD8544 display
*/
#pragma once
#include "lcd_hal/io.h"
#include "v2/lcd/lcd_common.h"
#include "v2/lcd/base/display.h"
/**
* @ingroup LCD_INTERFACE_API_V2
* @{
*/
/**
* Class implements interface functions to PCD8544 displays
*/
template <class I>
class InterfacePCD8544: public I
{
public:
/**
* Creates instance of interface to LCD display.
*
* @param base Reference to base class, which represents Display
* @param dc Data/command control pin number, for i2c communication should be -1
* @param data variable argument list, accepted by platform interface (PlatformI2c, PlatformSpi)
*/
template <typename... Args>
InterfacePCD8544(NanoDisplayBase<InterfacePCD8544<I>> &base, int8_t dc, Args&&... data)
: I(data...)
, m_dc( dc )
, m_base(base)
{
}
/**
* @brief Sets block in RAM of lcd display controller to write data to.
*
* Sets block in RAM of lcd display controller to write data to.
* For PCD8544 it uses horizontal addressing mode, while for
* sh1106 the function uses page addressing mode.
* Width can be specified as 0, thus the library will set the right boundary to
* region of RAM block to the right column of the display.
* @param x - column (left region)
* @param y - row (top region)
* @param w - width of the block in pixels to control
*
* @warning - this function initiates session (i2c or spi) and does not close it.
* To close session, please, call endBlock().
*/
void startBlock(lcduint_t x, lcduint_t y, lcduint_t w);
/**
* Switches to the start of next RAM page for the block, specified by
* startBlock().
* For PCD8544 it does nothing, while for sh1106 the function moves cursor to
* next page.
*/
void nextBlock();
/**
* Closes data send operation to lcd display.
*/
void endBlock();
/**
* Enables either data or command mode on SPI bus
* @param mode 1 to enable data mode, or 0 to enable command mode
*/
void spiDataMode(uint8_t mode);
/**
* Starts communication with LCD display in command mode.
* To stop communication use m_intf.end().
*/
void commandStart();
private:
const int8_t m_dc = -1; ///< data/command pin for SPI, -1 for i2c
NanoDisplayBase<InterfacePCD8544<I>> &m_base; ///< basic lcd display support interface
uint8_t m_width;
uint8_t m_column;
uint8_t m_page;
};
/**
* Class implements basic functions for 1-bit mode of PCD8544-based displays
*/
template <class I>
class DisplayPCD8544: public NanoDisplayOps<NanoDisplayOps1<I>,I>
{
public:
/**
* Creates instance of PCD8544 controller class for 1-bit mode
*
* @param intf interface to use
* @param rstPin pin to use as HW reset pin for LCD display
*/
DisplayPCD8544(I &intf, int8_t rstPin)
: NanoDisplayOps<NanoDisplayOps1<I>, I>(intf)
, m_rstPin( rstPin ) { }
protected:
int8_t m_rstPin; ///< indicates hardware reset pin used, -1 if it is not required
/**
* Basic PCD8544 initialization
*/
void begin() override;
/**
* Basic PCD8544 deinitialization
*/
void end() override;
};
/**
* Class implements basic functions for 1-bit mode of PCD8544-based displays
*/
template <class I>
class DisplayPCD8544_84x48: public DisplayPCD8544<I>
{
public:
/**
* Creates instance of PCD8544 84x48 controller class for 1-bit mode
*
* @param intf interface to use
* @param rstPin pin to use as HW reset pin for LCD display
*/
DisplayPCD8544_84x48(I &intf, int8_t rstPin)
: DisplayPCD8544<I>(intf, rstPin) { }
protected:
/**
* Basic PCD8544 84x48 initialization
*/
void begin() override;
/**
* Basic PCD8544 deinitialization
*/
void end() override;
};
/**
* Class implements PCD8544 84x48 lcd display in 1 bit mode over SPI
*/
class DisplayPCD8544_84x48_SPI: public DisplayPCD8544_84x48<InterfacePCD8544<PlatformSpi>>
{
public:
/**
* @brief Inits 84x48 lcd display over spi (based on PCD8544 controller): 1-bit mode.
*
* Inits 84x48 lcd display over spi (based on PCD8544 controller): 1-bit mode
* @param rstPin pin controlling LCD reset (-1 if not used)
* @param config platform spi configuration. Please refer to SPlatformSpiConfig.
*/
DisplayPCD8544_84x48_SPI( int8_t rstPin, const SPlatformSpiConfig &config = { -1, { -1 }, -1, 0, -1, -1 } )
: DisplayPCD8544_84x48(m_spi, rstPin)
, m_spi( *this, config.dc,
SPlatformSpiConfig{ config.busId,
{ config.cs },
config.dc,
config.frequency ?: 4000000,
config.scl,
config.sda } ) {}
/**
* Initializes PCD8544 lcd in 1-bit mode
*/
void begin() override;
/**
* Closes connection to display
*/
void end() override;
private:
InterfacePCD8544<PlatformSpi> m_spi;
};
/**
* Template class implements PCD8544 84x48 lcd display in 1 bit mode over custom SPI implementation
* (user-defined spi implementation). I - user custom spi class
*/
template <class I>
class DisplayPCD8544_84x48_CustomSPI: public DisplayPCD8544_84x48<InterfacePCD8544<I>>
{
public:
/**
* @brief Inits 84x48 lcd display over spi (based on PCD8544 controller): 1-bit mode.
*
* Inits 84x48 lcd display over spi (based on PCD8544 controller): 1-bit mode
* @param rstPin pin controlling LCD reset (-1 if not used)
* @param dcPin pin to use as data/command control pin
* @param data variable argument list for custom user spi interface.
*/
template <typename... Args>
DisplayPCD8544_84x48_CustomSPI( int8_t rstPin, int8_t dcPin, Args&&... data )
: DisplayPCD8544_84x48<InterfacePCD8544<I>>(m_spi, rstPin)
, m_spi( *this, dcPin,
data... ) {}
/**
* Initializes PCD8544 lcd in 1-bit mode
*/
void begin() override
{
m_spi.begin();
DisplayPCD8544_84x48<InterfacePCD8544<I>>::begin();
}
/**
* Closes connection to display
*/
void end() override
{
DisplayPCD8544_84x48<InterfacePCD8544<I>>::end();
m_spi.end();
}
private:
InterfacePCD8544<I> m_spi;
};
#include "lcd_pcd8544.inl"
/**
* @}
*/
|
N1ghtRaven/lcdgfx
|
src/v2/nano_engine/tiler.h
|
<gh_stars>0
/*
MIT License
Copyright (c) 2018-2019, <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* @file tiler.h Tiler helper for graphics processing
*/
#ifndef _NANO_ENGINE_TILER_H_
#define _NANO_ENGINE_TILER_H_
#include "canvas/rect.h"
#include "canvas/canvas.h"
#include "v2/lcd/base/display.h"
/**
* @ingroup NANO_ENGINE_API_V2
* @{
*/
#ifndef NE_MAX_TILE_ROWS
#define NE_MAX_TILE_ROWS 20 ///< Maximum tile rows supported. Can be defined outside the library
#endif
/**
* Structure, holding currently set font.
* @warning Only for internal use.
*/
/* The table below defines arguments for NanoEngineTiler. *
* canvas bits */
// Tiles for monochrome displays
#define TILE_128x64_MONO NanoCanvas<128,64,1> ///< Full-screen 1-bit tile for SSD1306
#define TILE_8x8_MONO NanoCanvas<8,8,1> ///< Standard 1-bit tile 8x8 for monochrome mode
#define TILE_16x16_MONO NanoCanvas<16,16,1> ///< Standard 1-bit tile 16x16 for monochrome mode
#define TILE_32x32_MONO NanoCanvas<32,32,1> ///< Standard 1-bit tile 32x32 for monochrome mode
// Tiles for 4-bit displays
#define TILE_16x16_GRAY4 NanoCanvas<16,16,4> ///< Standard 4-bit tile 16x16 for gray-color displays
// Tiles for 8-bit displays
#define TILE_8x8_RGB8 NanoCanvas<8,8,8> ///< Standard 8-bit RGB tile 8x8
#define TILE_16x16_RGB8 NanoCanvas<16,16,8> ///< Standard 8-bit RGB tile 16x16
#define TILE_32x32_RGB8 NanoCanvas<32,32,8> ///< Standard 8-bit RGB tile 32x32
#define TILE_8x8_MONO_8 NanoCanvas<8,8,1> ///< Standard 1-bit tile 8x8 for RGB mode
#define TILE_16x16_MONO_8 NanoCanvas<16,16,1> ///< Standard 1-bit tile 16x16 for RGB mode
// Tiles for 16-bit displays
#define TILE_8x8_RGB16 NanoCanvas<8,8,16> ///< Standard 16-bit RGB tile 8x8
#define TILE_16x16_RGB16 NanoCanvas<16,16,16> ///< Standard 16-bit RGB tile 16x16
// Adafruit tiles
#define ADATILE_8x8_MONO AdafruitCanvas1, 8, 8, 3 ///< Use Adafruit GFX implementation as NanoEngine canvas
#define ADATILE_8x8_RGB8 AdafruitCanvas8, 8, 8, 3 ///< Use Adafruit GFX implementation as NanoEngine canvas
#define ADATILE_8x8_RGB16 AdafruitCanvas16, 8, 8, 3 ///< Use Adafruit GFX implementation as NanoEngine canvas
/**
* Type of user-specified draw callback.
*/
typedef bool (*TNanoEngineOnDraw)(void);
template<class C, class D>
class NanoEngine;
template<class C, class D>
class NanoEngineTiler;
/**
* Template class for all NanoEngine objects
*/
template<class T>
class NanoEngineObject
{
public:
template<class C, class D>
friend class NanoEngineTiler;
/**
* draw() method is called by NanoEngine, when it needs to refresh
* object graphics.
*/
virtual void draw() = 0;
/**
* update() method is called by NanoEngine, when it needs all objects
* to update their logic state.
*/
virtual void update() = 0;
/**
* update() method is called by NanoEngine, when it needs object to
* mark occupied place for refreshing.
*/
virtual void refresh() = 0;
/**
* Sets logic focus on NanoEngineObject
*/
void focus()
{
m_focused = true;
refresh();
}
/**
* Clears logic focus from NanoEngineObject
*/
void defocus()
{
m_focused = false;
refresh();
}
/**
* Returns true if logic focus points to the object.
* At present NanoEngine allows many objects to be in focus at once
*/
bool isFocused()
{
return m_focused;
}
/**
* Returns true if NanoEngineObject is bound to NanoEngine instance
*/
bool hasTiler() { return m_tiler != nullptr; }
/**
* Returns reference to NanoEngine. Before call to this function,
* please check that NanoEngine is valid via hasTiler() function.
*/
T &getTiler() { return *(static_cast<T *>(m_tiler)); }
protected:
T *m_tiler = nullptr; ///< Active tiler, assigned to the NanoEngineObject
NanoEngineObject<T> *m_next = nullptr; ///< Next NanoEngineObject in the list
/**
* Bind NanoEngineObject to specific NanoEngine
*
* @param tiler pointer to NanoEngine object
*/
void setTiler(T *tiler) { m_tiler = tiler; }
private:
bool m_focused;
};
/**
* This class template is responsible for holding and updating data about areas to be refreshed
* on LCD display. It accepts canvas class, tile width in pixels, tile height in pixels and
* number of bits in tile width as arguments for the template.
* For example, for 8x8 8-bit RGB tiles the reference should be NanoEngineTiler<NanoCanvas8,8,8,3>,
* and 3 bits means 3^2 = 8.
* If you need to have single big buffer, holding the whole content for monochrome display,
* you can specify something like this NanoEngineTiler<NanoCanvas1,128,64,7>.
*/
template<class C, class D>
class NanoEngineTiler
{
protected:
/** Only child classes can initialize the engine */
NanoEngineTiler(D &display):
m_display( display ),
m_onDraw(nullptr),
offset{0, 0}
{
refresh();
};
public:
/**
* This type is template argument for all Nano Objects.
*/
typedef NanoEngineTiler<C,D> TilerT;
/**
* Marks all tiles for update. Actual update will take place in display() method.
*/
void refresh()
{
memset(m_refreshFlags,0xFF,sizeof(m_refreshFlags));
}
/**
* Mark specified area in pixels for redrawing by NanoEngine.
* Actual update will take place in display() method.
* @note assumes that rect is in local screen coordinates
*/
void refresh(const NanoRect &rect)
{
refresh(rect.p1.x, rect.p1.y, rect.p2.x, rect.p2.y);
}
/**
* Mark specified area in pixels for redrawing by NanoEngine.
* Actual update will take place in display() method.
*/
void refresh(const NanoPoint &point) __attribute__ ((noinline))
{
if ((point.x<0)||(point.y<0) || ((point.y/canvas.height())>=NE_MAX_TILE_ROWS)) return;
m_refreshFlags[(point.y/canvas.height())] |= (1<<(point.x/canvas.width()));
}
/**
* Mark specified area in pixels for redrawing by NanoEngine.
* Actual update will take place in display() method.
*/
void refresh(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) __attribute__ ((noinline))
{
if (y2 < 0 || x2 < 0) return;
if (y1 < 0) y1 = 0;
if (x1 < 0) x1 = 0;
y1 = y1/canvas.height();
y2 = min((y2/canvas.height()), NE_MAX_TILE_ROWS - 1);
for(uint8_t x=x1/canvas.width(); x<=(x2/canvas.width()); x++)
{
for (uint8_t y=y1; y<=y2; y++)
{
m_refreshFlags[y] |= (1<<x);
}
}
}
/**
* Marks for refresh lcd area, which corresponds to specified rectangle in
* global (World) coordinates. If engine offset is (0,0), then this function
* refreshes the same area as refresh().
*/
void refreshWorld(const NanoRect &rect)
{
refreshWorld(rect.p1.x, rect.p1.y, rect.p2.x, rect.p2.y);
}
/**
* Marks for refresh lcd area, which corresponds to specified rectangle in
* global (World) coordinates. If engine offset is (0,0), then this function
* refreshes the same area as refresh().
*/
void refreshWorld(lcdint_t x1, lcdint_t y1, lcdint_t x2, lcdint_t y2) __attribute__ ((noinline))
{
refresh(x1 - offset.x, y1 - offset.y, x2 - offset.x, y2 - offset.y);
}
/**
* Marks specified pixel area for redrawing by NanoEngine.
* @param point point in global (World) coordinates
*/
void refreshWorld(const NanoPoint &point)
{
refresh( point - offset );
}
/**
* Switches engine canvas to local coordinates system. This method can be useful
* to ease up drawing of some static elements on lcd display.
* @warning do not call twice subsequentally.
*/
void localCoordinates()
{
canvas.offset -= offset;
}
/**
* Switches engine canvas to global (World) coordinates system. This method can be useful
* to create screen moving animation.
* @warning do not call twice subsequentally.
*/
void worldCoordinates()
{
canvas.offset += offset;
}
/**
* Moves engine coordinate to new position (this sets World coordinates offset).
*/
void moveTo(const NanoPoint & position)
{
offset = position;
}
/**
* Moves engine coordinate to new position and mark whole display for refresh
* (this sets World coordinates offset).
*/
void moveToAndRefresh(const NanoPoint & position)
{
moveTo(position);
refresh();
}
/**
* Returns current World offset
*/
const NanoPoint & getPosition() const
{
return offset;
}
/**
* Sets user-defined draw callback. This callback will be called everytime, engine needs
* to update display content. If user callback returns false, engine will not update that area.
* You always have a way to find out, which area is being updated by engine via
* NanoEngine<>::canvas::getOffset() and NanoEngine<>::NE_TILE_SIZE.
* @warning By default canvas in the engine is initialized with world coordinates. So
* graphics object with [0,0] coordinates will be placed at topleft position fo the window
* pointed by offset property of NanoEngine. But engine supports also local coordinates,
* if you need to draw some dialog, for example. In this case actual object
* position depends on current engine offset. Refer to worldCoordinates() and
* localCoordinates().
* @param callback - user-defined draw callback.
* @note you can change draw callback anytime you need.
* @see worldCoordinates()
* @see localCoordinates()
*/
void drawCallback(TNanoEngineOnDraw callback)
{
m_onDraw = callback;
}
/**
* @brief Returns true if point is inside the rectangle area.
* Returns true if point is inside the rectangle area.
* @param p - point to check
* @param rect - rectangle, describing the region to check with the point
* @returns true if point is inside the rectangle area.
*/
bool collision(NanoPoint &p, NanoRect &rect) { return rect.collision( p ); }
/**
* Inserts new NanoEngineObject. This object will be displayed during next call
* to update()/draw() methods.
*
* @param object reference to object to place to NanoEngine
*/
void insert(NanoEngineObject<TilerT> &object) __attribute__ ((noinline))
{
object.m_next = this->m_first;
object.setTiler( this );
m_first = &object;
object.refresh();
}
/**
* Removes NanoEngineObject from the list, but doesn't destroy the object.
* The place occupied by this object will be refreshed during next call
* to update()/draw() methods.
*
* @param object object to remove from NanoEngine
*/
void remove(NanoEngineObject<TilerT> &object) __attribute__ ((noinline))
{
if ( this->m_first == nullptr )
{
}
else if ( &object == m_first )
{
object.refresh();
this->m_first = object.m_next;
object.m_next = nullptr;
object.m_tiler = nullptr;
}
else
{
NanoEngineObject<TilerT> *p = this->m_first;
while ( p->m_next )
{
if ( p->m_next == &object )
{
object.refresh();
p->m_next = object.m_next;
object.m_next = nullptr;
object.m_tiler = nullptr;
break;
}
p = p->m_next;
}
}
}
/**
* Updates all objects. This method doesn't refresh screen content
*/
void update() __attribute__ ((noinline))
{
NanoEngineObject<TilerT> *p = m_first;
while (p)
{
p->update();
p = p->m_next;
}
}
/**
* Returns canvas, used by the NanoEngine.
*/
C& getCanvas() { return canvas; }
/**
* Returns reference to display object.
*/
D& getDisplay() { return m_display; }
protected:
/**
* Reference to display object, used by NanoEngine
*/
D& m_display;
/** Callback to call if specific tile needs to be updated */
TNanoEngineOnDraw m_onDraw;
/**
* Contains information on tiles to be updated.
* Elements of array are rows and bits are columns.
*/
uint16_t m_refreshFlags[NE_MAX_TILE_ROWS];
/**
* @brief refreshes content on oled display.
* Refreshes content on oled display. Call it, if you want to update the screen.
* Engine will update only those areas, which are marked by refresh()
* methods.
*/
void displayBuffer() __attribute__ ((noinline));
/**
* @brief prints popup message over display content
* prints popup message over display content
* @param msg - message to display
*/
void displayPopup(const char *msg);
private:
/** object, representing canvas. Use it in your draw handler */
C canvas;
NanoPoint offset;
NanoEngineObject<TilerT> *m_first;
void draw() __attribute__ ((noinline))
{
NanoEngineObject<TilerT> *p = m_first;
while (p)
{
p->draw();
p = p->m_next;
}
}
};
template<class C, class D>
void NanoEngineTiler<C,D>::displayBuffer()
{
// printf("--------------\n");
for (lcduint_t y = 0; y < m_display.height(); y = y + canvas.height())
{
uint16_t flag = m_refreshFlags[y/canvas.height()];
m_refreshFlags[y/canvas.height()] = 0;
// printf("|%d%d%d%d%d%d%d%d|\n", flag & 1, (flag >> 1) & 1, (flag >> 2) & 1, (flag >> 3) & 1, (flag >> 4) & 1, (flag >> 5) & 1,(flag >> 6) & 1,(flag >> 7) & 1 );
for (lcduint_t x = 0; x < m_display.width(); x = x + canvas.width())
{
if (flag & 0x01)
{
canvas.setOffset(x + offset.x, y + offset.y);
if ( m_onDraw == nullptr )
{
canvas.clear();
draw();
this->m_display.drawCanvas(x,y,canvas);
}
else if ( m_onDraw() )
{
draw();
this->m_display.drawCanvas(x,y,canvas);
}
}
flag >>=1;
}
}
}
template<class C, class D>
void NanoEngineTiler<C,D>::displayPopup(const char *msg)
{
NanoRect rect = { {8, (m_display.height()>>1) - 8}, {m_display.width() - 8, (m_display.height()>>1) + 8} };
// TODO: It would be nice to calculate message height
NanoPoint textPos = { (m_display.width() - (lcdint_t)strlen(msg)*m_display.getFont().getHeader().width) >> 1,
(m_display.height()>>1) - 4 };
refresh(rect);
for (lcduint_t y = 0; y < m_display.height(); y = y + canvas.height())
{
uint16_t flag = m_refreshFlags[y/canvas.height()];
m_refreshFlags[y/canvas.height()] = 0;
for (lcduint_t x = 0; x < m_display.width(); x = x + canvas.width())
{
if (flag & 0x01)
{
canvas.setOffset(x + offset.x, y + offset.y);
if (!m_onDraw)
{
canvas.clear();
draw();
}
else if (m_onDraw())
{
draw();
}
canvas.setOffset(x, y);
canvas.setColor(RGB_COLOR8(0,0,0));
canvas.fillRect(rect);
canvas.setColor(RGB_COLOR8(192,192,192));
canvas.drawRect(rect);
canvas.printFixed( textPos.x, textPos.y, msg);
m_display.drawCanvas(x,y,canvas);
}
flag >>=1;
}
}
}
/**
* @}
*/
#endif
|
nozomi1773/trafficserver
|
iocore/net/quic/QUICRetryIntegrityTag.h
|
/** @file
*
* A brief file description
*
* @section license License
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "QUICTypes.h"
class QUICRetryIntegrityTag
{
public:
static constexpr int LEN = 16;
static bool compute(uint8_t *out, QUICConnectionId odcid, Ptr<IOBufferBlock> header, Ptr<IOBufferBlock> payload);
private:
static constexpr uint8_t KEY_FOR_RETRY_INTEGRITY_TAG[] = {0x4d, 0x32, 0xec, 0xdb, 0x2a, 0x21, 0x33, 0xc8,
0x41, 0xe4, 0x04, 0x3d, 0xf2, 0x7d, 0x44, 0x30};
static constexpr uint8_t NONCE_FOR_RETRY_INTEGRITY_TAG[] = {0x4d, 0x16, 0x11, 0xd0, 0x55, 0x13,
0xa5, 0x52, 0xc5, 0x87, 0xd5, 0x75};
};
|
nozomi1773/trafficserver
|
iocore/net/quic/QUICTLS.h
|
/** @file
*
* QUIC TLS
*
* @section license License
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <openssl/ssl.h>
#ifdef OPENSSL_IS_BORINGSSL
#include <openssl/digest.h>
#include <openssl/cipher.h>
#else
#include <openssl/evp.h>
#endif
#include "I_EventSystem.h"
#include "I_NetVConnection.h"
#include "QUICHandshakeProtocol.h"
// TODO: fix size
static constexpr int MAX_HANDSHAKE_MSG_LEN = 65527;
class QUICTLS : public QUICHandshakeProtocol
{
public:
QUICTLS(QUICPacketProtectionKeyInfo &pp_key_info, SSL_CTX *ssl_ctx, NetVConnectionContext_t nvc_ctx,
const NetVCOptions &netvc_options, const char *session_file = nullptr, const char *keylog_file = nullptr);
~QUICTLS();
// TODO: integrate with _early_data_processed
enum class HandshakeState {
PROCESSING,
ABORTED,
};
static QUICEncryptionLevel get_encryption_level(int msg_type);
static uint64_t convert_to_quic_trans_error_code(uint8_t alert);
std::shared_ptr<const QUICTransportParameters> local_transport_parameters() override;
std::shared_ptr<const QUICTransportParameters> remote_transport_parameters() override;
void set_local_transport_parameters(std::shared_ptr<const QUICTransportParameters> tp) override;
void set_remote_transport_parameters(std::shared_ptr<const QUICTransportParameters> tp) override;
const char *session_file() const;
const char *keylog_file() const;
// FIXME Should not exist
SSL *ssl_handle();
// QUICHandshakeProtocol
int handshake(QUICHandshakeMsgs **out, const QUICHandshakeMsgs *in) override;
void reset() override;
bool is_handshake_finished() const override;
bool is_ready_to_derive() const override;
int initialize_key_materials(QUICConnectionId cid) override;
void update_negotiated_cipher();
void update_key_materials_for_read(QUICEncryptionLevel level, const uint8_t *secret, size_t secret_len);
void update_key_materials_for_write(QUICEncryptionLevel level, const uint8_t *secret, size_t secret_len);
const char *negotiated_cipher_suite() const override;
void negotiated_application_name(const uint8_t **name, unsigned int *len) const override;
QUICEncryptionLevel current_encryption_level() const override;
void abort_handshake() override;
bool has_crypto_error() const override;
uint64_t crypto_error() const override;
void set_ready_for_write();
void on_handshake_data_generated(QUICEncryptionLevel level, const uint8_t *data, size_t len);
void on_tls_alert(uint8_t alert);
private:
QUICKeyGenerator _keygen_for_client = QUICKeyGenerator(QUICKeyGenerator::Context::CLIENT);
QUICKeyGenerator _keygen_for_server = QUICKeyGenerator(QUICKeyGenerator::Context::SERVER);
const EVP_MD *_get_handshake_digest() const;
int _read_early_data();
int _write_early_data();
void _pass_quic_data_to_ssl_impl(const QUICHandshakeMsgs &in);
int _handshake(QUICHandshakeMsgs **out, const QUICHandshakeMsgs *in);
int _process_post_handshake_messages(QUICHandshakeMsgs *out, const QUICHandshakeMsgs *in);
void _generate_0rtt_key();
void _update_encryption_level(QUICEncryptionLevel level);
void _store_negotiated_cipher();
void _store_negotiated_cipher_for_hp();
void _print_km(const char *header, const uint8_t *key_for_hp, size_t key_for_hp_len, const uint8_t *key, size_t key_len,
const uint8_t *iv, size_t iv_len, const uint8_t *secret = nullptr, size_t secret_len = 0,
QUICKeyPhase phase = QUICKeyPhase::INITIAL);
static void _print_hs_message(int content_type, const void *buf, size_t len);
static void _msg_cb(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg);
const char *_session_file = nullptr;
const char *_keylog_file = nullptr;
SSL *_ssl = nullptr;
NetVConnectionContext_t _netvc_context = NET_VCONNECTION_UNSET;
bool _early_data_processed = false;
bool _is_session_reused = false;
bool _early_data = true;
QUICEncryptionLevel _current_level = QUICEncryptionLevel::INITIAL;
HandshakeState _state = HandshakeState::PROCESSING;
std::shared_ptr<const QUICTransportParameters> _local_transport_parameters = nullptr;
std::shared_ptr<const QUICTransportParameters> _remote_transport_parameters = nullptr;
uint8_t _out_buf[MAX_HANDSHAKE_MSG_LEN] = {0};
QUICHandshakeMsgs _out = {_out_buf, MAX_HANDSHAKE_MSG_LEN, {0}, 0};
bool _should_flush = false;
bool _has_crypto_error = false;
uint64_t _crypto_error = 0;
};
|
nozomi1773/trafficserver
|
iocore/net/quic/QUICCongestionController.h
|
/** @file
*
* A brief file description
*
* @section license License
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "QUICFrame.h"
struct QUICPacketInfo {
// 6.3.1. Sent Packet Fields
QUICPacketNumber packet_number;
ink_hrtime time_sent;
bool ack_eliciting;
bool is_crypto_packet;
bool in_flight;
size_t sent_bytes;
// addition
QUICPacketType type;
std::vector<QUICFrameInfo> frames;
QUICPacketNumberSpace pn_space;
// end
};
class QUICCongestionController
{
public:
enum class State : uint8_t {
RECOVERY,
CONGESTION_AVOIDANCE,
SLOW_START,
APPLICATION_LIMITED,
};
virtual ~QUICCongestionController() {}
virtual void on_packet_sent(size_t bytes_sent) = 0;
virtual void on_packet_acked(const QUICPacketInfo &acked_packet) = 0;
virtual void process_ecn(const QUICPacketInfo &acked_largest_packet, const QUICAckFrame::EcnSection *ecn_section) = 0;
virtual void on_packets_lost(const std::map<QUICPacketNumber, QUICPacketInfo *> &packets) = 0;
virtual void add_extra_credit() = 0;
virtual void reset() = 0;
virtual uint32_t credit() const = 0;
// Debug
virtual uint32_t bytes_in_flight() const = 0;
virtual uint32_t congestion_window() const = 0;
virtual uint32_t current_ssthresh() const = 0;
};
|
nozomi1773/trafficserver
|
plugins/experimental/maxmind_acl/mmdb.h
|
<filename>plugins/experimental/maxmind_acl/mmdb.h
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//#pragma once
#include <cstdio>
#include <cstring>
#include <arpa/inet.h>
#include <ts/ts.h>
#include <ts/remap.h>
#include <ts/ts.h>
#include <ts/remap.h>
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
#include <yaml-cpp/yaml.h>
#include <unordered_map>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iterator>
#include <maxminddb.h>
#include "tscore/IpMap.h"
#ifdef HAVE_PCRE_PCRE_H
#include <pcre/pcre.h>
#else
#include <pcre.h>
#endif
#define PLUGIN_NAME "maxmind_acl"
#define CONFIG_TMOUT 60000
typedef struct {
std::string _regex_s;
pcre *_rex;
pcre_extra *_extra;
} plugin_regex;
typedef enum { ALLOW_IP, DENY_IP, UNKNOWN_IP } ipstate;
// Base class for all ACLs
class Acl
{
public:
Acl() {}
~Acl()
{
if (db_loaded) {
MMDB_close(&_mmdb);
}
}
bool eval(TSRemapRequestInfo *rri, TSHttpTxn txnp);
bool init(char const *filename);
void
send_html(TSHttpTxn txnp) const
{
if (_html.size() > 0) {
char *msg = TSstrdup(_html.c_str());
TSHttpTxnErrorBodySet(txnp, msg, _html.size(), nullptr); // Defaults to text/html
}
}
protected:
// Class members
YAML::Node _config;
MMDB_s _mmdb;
std::string _html;
std::unordered_map<std::string, bool> allow_country;
std::unordered_map<std::string, std::vector<plugin_regex>> allow_regex;
std::unordered_map<std::string, std::vector<plugin_regex>> deny_regex;
IpMap allow_ip_map;
IpMap deny_ip_map;
// Do we want to allow by default or not? Useful
// for deny only rules
bool default_allow = false;
bool db_loaded = false;
bool loaddb(YAML::Node dbNode);
bool loadallow(YAML::Node allowNode);
bool loaddeny(YAML::Node denyNode);
void loadhtml(YAML::Node htmlNode);
bool eval_country(MMDB_entry_data_s *entry_data, const char *path, int path_len);
void parseregex(YAML::Node regex, bool allow);
ipstate eval_ip(const sockaddr *sock);
};
|
nozomi1773/trafficserver
|
iocore/net/quic/qlog/QLogListener.h
|
/** @file
*
* A brief file description
*
* @section license License
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "QLog.h"
#include "QLogUtils.h"
#include "QUICPacket.h"
#include "QUICContext.h"
namespace QLog
{
class QLogListener : public QUICCallback
{
public:
QLogListener(QUICContext &ctx, std::string odcid, std::string title = "", std::string desc = "") : _context(ctx)
{
this->_log.new_trace(odcid, title, desc); // initial new trace
}
void
frame_recv_callback(QUICCallbackContext &, const QUICFrame &frame) override
{
this->_recv_frames.push_back(QLogFrameFactory::create(static_cast<const QUICFrame *>(&frame)));
}
void
frame_packetize_callback(QUICCallbackContext &, const QUICFrame &frame) override
{
this->_send_frames.push_back(QLogFrameFactory::create(static_cast<const QUICFrame *>(&frame)));
}
void
packet_send_callback(QUICCallbackContext &, const QUICPacket &packet) override
{
auto qe = std::make_unique<Transport::PacketSent>(PacketTypeToName(packet.type()), QUICPacketToLogPacket(packet));
for (auto &it : this->_send_frames) {
qe->append_frames(std::move(it));
}
this->_send_frames.clear();
this->_log.last_trace().push_event(std::move(qe));
};
void
packet_recv_callback(QUICCallbackContext &, const QUICPacket &packet) override
{
auto qe = std::make_unique<Transport::PacketReceived>(PacketTypeToName(packet.type()), QUICPacketToLogPacket(packet));
for (auto &it : this->_recv_frames) {
qe->append_frames(std::move(it));
}
this->_recv_frames.clear();
this->_log.last_trace().push_event(std::move(qe));
};
void
packet_lost_callback(QUICCallbackContext &, const QUICPacketInfo &packet) override
{
auto qe = std::make_unique<Recovery::PacketLost>(PacketTypeToName(packet.type), packet.packet_number);
this->_log.last_trace().push_event(std::move(qe));
};
void
cc_metrics_update_callback(QUICCallbackContext &, uint64_t congestion_window, uint64_t bytes_in_flight, uint64_t sshresh) override
{
auto qe = std::make_unique<Recovery::MetricsUpdated>();
qe->set_congestion_window(static_cast<int>(congestion_window)).set_bytes_in_flight(bytes_in_flight).set_ssthresh(sshresh);
this->_log.last_trace().push_event(std::move(qe));
}
void
congestion_state_updated_callback(QUICCallbackContext &, QUICCongestionController::State state) override
{
if (state != this->_state) {
this->_log.last_trace().push_event(std::make_unique<Recovery::CongestionStateUpdated>(CongestionStateConvert(state)));
this->_state = state;
}
}
void
connection_close_callback(QUICCallbackContext &) override
{
this->_log.dump(this->_context.config()->qlog_dir());
}
Trace &
last_trace()
{
return this->_log.last_trace();
}
private:
QUICCongestionController::State _state = QUICCongestionController::State::SLOW_START;
std::vector<QLogFrameUPtr> _recv_frames;
std::vector<QLogFrameUPtr> _send_frames;
QLog _log;
QUICContext &_context;
};
} // namespace QLog
|
nozomi1773/trafficserver
|
iocore/net/quic/qlog/QLogEvent.h
|
<reponame>nozomi1773/trafficserver
/** @file
*
* A brief file description
*
* @section license License
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <string>
#include <yaml-cpp/yaml.h>
#include "QUICTypes.h"
#include "QLogEvent.h"
#include "QLogFrame.h"
namespace QLog
{
class QLogEvent
{
public:
virtual ~QLogEvent() {}
virtual std::string category() const = 0;
virtual std::string event() const = 0;
virtual void encode(YAML::Node &) = 0;
virtual ink_hrtime
get_time() const
{
return this->_time;
};
protected:
ink_hrtime _time = Thread::get_hrtime();
};
using QLogEventUPtr = std::unique_ptr<QLogEvent>;
#define SET(field, type) \
void set_##field(type v) { this->_node[#field] = v; }
// enum class PacketType : uint8_t { initial, handshake, zerortt, onertt, retry, version_negotiation, unknown };
using PacketType = std::string;
struct PacketHeader {
std::string packet_number;
uint64_t packet_size;
uint64_t payload_length;
// only if present in the header
// if correctly using NEW_CONNECTION_ID events,
// dcid can be skipped for 1RTT packets
std::string version;
std::string scil;
std::string dcil;
std::string scid;
std::string dcid;
// Note: short vs long header is implicit through PacketType
void
encode(YAML::Node &node)
{
node["packet_number"] = packet_number;
node["packet_size"] = packet_size;
node["payload_length"] = payload_length;
node["version"] = version;
node["scil"] = scil;
node["dcil"] = dcil;
node["scid"] = scid;
node["dcid"] = dcid;
}
};
#define SET_FUNC(cla, field, type) \
public: \
cla &set_##field(type v) \
{ \
this->_##field = v; \
return *this; \
} \
\
private: \
type _##field;
#define APPEND_FUNC(cla, field, type) \
public: \
cla &append_##field(type v) \
{ \
this->_##field.push_back(v); \
return *this; \
} \
\
private: \
std::vector<type> _##field;
#define APPEND_FRAME_FUNC(cla) \
public: \
cla &append_frames(QLogFrameUPtr v) \
{ \
this->_frames.push_back(std::move(v)); \
return *this; \
} \
\
private: \
std::vector<QLogFrameUPtr> _frames;
//
// connectivity
//
namespace Connectivity
{
class ConnectivityEvent : public QLogEvent
{
public:
std::string
category() const override
{
return "connectivity";
}
};
class ServerListening : public ConnectivityEvent
{
public:
ServerListening(int port, bool v6 = false)
{
if (v6) {
set_port_v6(port);
} else {
set_port_v4(port);
}
}
#define _SET(a, b) SET_FUNC(ServerListening, a, b)
#define _APPEND(a, b) APPEND_FUNC(ServerListening, a, b)
_SET(port_v4, int)
_SET(port_v6, int)
_SET(ip_v4, std::string)
_SET(ip_v6, std::string)
_SET(stateless_reset_required, bool)
_APPEND(quic_version, std::string)
_APPEND(alpn_values, std::string)
#undef _SET
#undef _APPEND
void encode(YAML::Node &) override;
std::string
event() const override
{
return "server_listening";
}
};
class ConnectionStarted : public ConnectivityEvent
{
public:
ConnectionStarted(std::string version, std::string sip, std::string dip, int sport, int dport, std::string protocol = "QUIC")
{
set_ip_version(version);
set_protocol(protocol);
set_src_ip(sip);
set_dst_ip(dip);
set_src_port(sport);
set_dst_port(dport);
}
#define _SET(a, b) SET_FUNC(ConnectionStarted, a, b)
#define _APPEND(a, b) APPEND_FUNC(ConnectionStarted, a, b)
_SET(quic_version, std::string);
_SET(src_cid, std::string);
_SET(dst_cid, std::string);
_SET(protocol, std::string);
_SET(ip_version, std::string)
_SET(src_ip, std::string)
_SET(dst_ip, std::string)
_SET(src_port, int)
_SET(dst_port, int)
_APPEND(alpn_values, std::string)
#undef _SET
#undef _APPEND
void encode(YAML::Node &) override;
std::string
event() const override
{
return "connection_started";
}
};
class ConnectionIdUpdated : public ConnectivityEvent
{
public:
ConnectionIdUpdated(std::string old, std::string n, bool peer = false)
{
if (peer) {
set_dst_old(old);
set_dst_new(n);
} else {
set_src_old(old);
set_src_new(n);
}
}
#define _SET(a, b) SET_FUNC(ConnectionIdUpdated, a, b)
#define _APPEND(a, b) APPEND_FUNC(ConnectionIdUpdated, a, b)
_SET(src_old, std::string);
_SET(src_new, std::string);
_SET(dst_old, std::string);
_SET(dst_new, std::string);
#undef _SET
#undef _APPEND
void encode(YAML::Node &) override;
std::string
event() const override
{
return "connection_id_updated";
}
};
class SpinBitUpdated : public ConnectivityEvent
{
public:
SpinBitUpdated(bool state) { set_state(state); }
#define _SET(a, b) SET_FUNC(SpinBitUpdated, a, b)
_SET(state, bool);
#undef _SET
void encode(YAML::Node &) override;
std::string
event() const override
{
return "spin_bit_updated";
}
};
class ConnectionStateUpdated : public ConnectivityEvent
{
public:
enum class ConnectionState : uint8_t {
attempted, // client initial sent
reset, // stateless reset sent
handshake, // handshake in progress
active, // handshake successful, data exchange
keepalive, // no data for a longer period
draining, // CONNECTION_CLOSE sent
closed // connection actually fully closed, memory freed
};
enum class Triggered : uint8_t {
unknown,
error, // when closing because of an unexpected event
clean, // when closing normally
application // e.g., HTTP/3's GOAWAY frame
};
ConnectionStateUpdated(ConnectionState n, Triggered tr = Triggered::unknown)
{
set_new(n);
set_trigger(tr);
}
#define _SET(a, b) SET_FUNC(ConnectionStateUpdated, a, b)
_SET(new, ConnectionState);
_SET(old, ConnectionState);
_SET(trigger, Triggered)
#undef _SET
void encode(YAML::Node &) override;
static const char *
trigger_name(Triggered trigger)
{
switch (trigger) {
case Triggered::error:
return "error";
case Triggered::clean:
return "clean";
case Triggered::application:
return "application";
default:
return nullptr;
}
}
std::string
event() const override
{
return "connection_state_updated";
}
};
} // namespace Connectivity
namespace Security
{
class KeyEvent : public QLogEvent
{
public:
enum class KeyType : uint8_t {
server_initial_secret,
client_initial_secret,
server_handshake_secret,
client_handshake_secret,
server_0rtt_secret,
client_0rtt_secret,
server_1rtt_secret,
client_1rtt_secret
};
enum class Triggered : uint8_t {
unknown,
remote_update,
local_update,
tls,
};
KeyEvent(KeyType ty, std::string n, int generation, Triggered triggered = Triggered::unknown)
{
set_key_type(ty);
set_new(n);
set_generation(generation);
set_trigger(triggered);
}
#define _SET(a, b) SET_FUNC(KeyEvent, a, b)
_SET(key_type, KeyType);
_SET(new, std::string)
_SET(old, std::string);
_SET(generation, int)
_SET(trigger, Triggered)
#undef _SET
void encode(YAML::Node &) override;
const char *
trigger_name(Triggered triggered)
{
switch (triggered) {
case Triggered::remote_update:
return "remote_update";
case Triggered::local_update:
return "local_update";
case Triggered::tls:
return "tls";
default:
return nullptr;
}
}
std::string
category() const override
{
return "security";
}
};
class KeyUpdated : public KeyEvent
{
public:
KeyUpdated(KeyType ty, std::string n, int generation, Triggered triggered = KeyEvent::Triggered::unknown)
: KeyEvent(ty, n, generation, triggered)
{
}
std::string
event() const override
{
return "key_updated";
}
};
class KeyRetired : public KeyEvent
{
public:
KeyRetired(KeyType ty, std::string n, int generation, Triggered triggered = KeyEvent::Triggered::unknown)
: KeyEvent(ty, n, generation, triggered)
{
}
std::string
event() const override
{
return "key_retired";
}
};
} // namespace Security
//
// transport event
//
namespace Transport
{
class TransportEvent : public QLogEvent
{
public:
std::string
category() const override
{
return "transport";
}
};
class ParametersSet : public TransportEvent
{
public:
struct PreferredAddress {
std::string ip;
int port;
std::string connection_id;
std::string stateless_reset_token;
bool ipv4 = true;
};
ParametersSet(bool owner) : _owner(owner) {}
std::string
event() const override
{
return "parameters_set";
}
#define _SET(a, b) SET_FUNC(ParametersSet, a, b)
_SET(resumption_allowed, bool); // early data extension was enabled on the TLS layer
_SET(early_data_enabled, bool); // early data extension was enabled on the TLS layer
_SET(alpn, std::string);
_SET(version, std::string); // hex (e.g. 0x);
_SET(tls_cipher, std::string); // (e.g. AES_128_GCM_SHA256);
_SET(original_connection_id, std::string); // hex
_SET(stateless_reset_token, std::string); // hex
_SET(disable_active_migration, bool);
_SET(idle_timeout, int);
_SET(max_packet_size, int);
_SET(ack_delay_exponent, int);
_SET(max_ack_delay, int);
_SET(active_connection_id_limit, int);
_SET(initial_max_data, std::string);
_SET(initial_max_stream_data_bidi_local, std::string);
_SET(initial_max_stream_data_bidi_remote, std::string);
_SET(initial_max_stream_data_uni, std::string);
_SET(initial_max_streams_bidi, std::string);
_SET(initial_max_streams_uni, std::string);
_SET(max_idle_timeout, int64_t)
_SET(max_udp_payload_size, size_t)
_SET(preferred_address, PreferredAddress)
#undef _SET
void encode(YAML::Node &) override;
private:
bool _owner = false;
};
class PacketEvent : public TransportEvent
{
public:
enum class Triggered : uint8_t {
unknown,
keys_available, // if packet was buffered because it couldn't be decrypted before
retransmit_reordered, // draft-23 5.1.1
retransmit_timeout, // draft-23 5.1.2
pto_probe, // draft-23 5.3.1
retransmit_crypto, // draft-19 6.2
cc_bandwidth_probe, // needed for some CCs to figure out bandwidth allocations when there are no normal sends
};
PacketEvent(PacketType type, PacketHeader h, Triggered tr = Triggered::unknown)
{
set_packet_type(type).set_header(h).set_trigger(tr);
}
#define _SET(a, b) SET_FUNC(PacketEvent, a, b)
#define _APPEND(a, b) APPEND_FUNC(PacketEvent, a, b)
_SET(packet_type, PacketType)
_SET(header, PacketHeader)
_SET(is_coalesced, bool);
_SET(raw_encrypted, std::string);
_SET(raw_decrypted, std::string);
_SET(stateless_reset_token, std::string);
_SET(trigger, Triggered);
_APPEND(supported_version, std::string);
#undef _SET
#undef _APPEND
APPEND_FRAME_FUNC(PacketEvent)
void encode(YAML::Node &) override;
static const char *
trigger_name(Triggered triggered)
{
switch (triggered) {
case Triggered::retransmit_reordered:
return "retransmit_reordered";
case Triggered::retransmit_timeout:
return "retransmit_timeout";
case Triggered::pto_probe:
return "pto_probe";
case Triggered::retransmit_crypto:
return "retransmit_crypto";
case Triggered::cc_bandwidth_probe:
return "cc_bandwidth_probe";
break;
case Triggered::keys_available:
return "keys_available";
default:
return nullptr;
}
}
};
class PacketSent : public PacketEvent
{
public:
PacketSent(PacketType type, PacketHeader h, Triggered tr = Triggered::unknown) : PacketEvent(type, h, tr) {}
std::string
event() const override
{
return "packet_sent";
}
};
class PacketReceived : public PacketEvent
{
public:
PacketReceived(PacketType type, PacketHeader h, Triggered tr = Triggered::unknown) : PacketEvent(type, h, tr) {}
std::string
event() const override
{
return "packet_received";
}
};
class PacketDropped : public TransportEvent
{
public:
enum class Triggered : uint8_t {
unknown,
key_unavailable,
unknown_connection_id,
header_decrypt_error,
payload_decrypt_error,
protocol_violation,
dos_prevention,
unsupported_version,
unexpected_packet,
unexpected_source_connection_id,
unexpected_version,
};
PacketDropped(Triggered tr = Triggered::unknown) { set_trigger(tr); }
#define _SET(a, b) SET_FUNC(PacketDropped, a, b)
_SET(packet_size, int);
_SET(raw, std::string);
_SET(trigger, Triggered);
_SET(packet_type, PacketType)
#undef _SET
void encode(YAML::Node &) override;
std::string
event() const override
{
return "packet_dropped";
}
static const char *
trigger_name(Triggered tr)
{
switch (tr) {
case Triggered::key_unavailable:
return "key_unavailable";
case Triggered::unknown_connection_id:
return "unknown_connection_id";
case Triggered::header_decrypt_error:
return "header_decrypt_error";
case Triggered::payload_decrypt_error:
return "payload_decrypt_error";
case Triggered::protocol_violation:
return "protocol_violation";
case Triggered::dos_prevention:
return "dos_prevention";
case Triggered::unsupported_version:
return "unsupported_version";
case Triggered::unexpected_packet:
return "unexpected_packet";
case Triggered::unexpected_source_connection_id:
return "unexpected_source_connection_id";
case Triggered::unexpected_version:
return "unexpected_version";
default:
return nullptr;
}
}
};
class PacketBuffered : public TransportEvent
{
public:
enum class Triggered : uint8_t {
unknown,
backpressure,
keys_unavailable,
};
PacketBuffered(Triggered tr = Triggered::unknown) { set_trigger(tr); }
#define _SET(a, b) SET_FUNC(PacketBuffered, a, b)
_SET(trigger, Triggered);
_SET(packet_type, PacketType)
_SET(packet_number, std::string)
#undef _SET
void encode(YAML::Node &) override;
std::string
event() const override
{
return "packet_buffered";
}
static const char *
trigger_name(Triggered tr)
{
switch (tr) {
case Triggered::backpressure:
return "backpressure";
case Triggered::keys_unavailable:
return "keys_unavailable";
default:
return nullptr;
}
}
};
class DatagramsEvent : public TransportEvent
{
public:
#define _SET(a, b) SET_FUNC(DatagramsEvent, a, b)
_SET(count, int);
_SET(byte_length, int);
#undef _SET
void encode(YAML::Node &) override;
};
class DatagramsSent : public DatagramsEvent
{
public:
std::string
event() const override
{
return "datagrams_sent";
}
};
class DatagramReceived : public DatagramsEvent
{
public:
std::string
event() const override
{
return "datagrams_received";
}
};
class DatagramsDropped : public TransportEvent
{
public:
#define _SET(a, b) SET_FUNC(DatagramsDropped, a, b)
_SET(byte_length, int);
#undef _SET
void encode(YAML::Node &) override;
std::string
event() const override
{
return "datagrams_dropped";
}
};
class StreamStateUpdated : public TransportEvent
{
enum class StreamState {
// bidirectional stream states, draft-23 3.4.
idle,
open,
half_closed_local,
half_closed_remote,
closed,
// sending-side stream states, draft-23 3.1.
ready,
send,
data_sent,
reset_sent,
reset_received,
// receive-side stream states, draft-23 3.2.
receive,
size_known,
data_read,
reset_read,
// both-side states
data_received,
// qlog-defined
destroyed // memory actually freed
};
StreamStateUpdated(std::string stream_id, StreamState n) { set_new(n).set_stream_id(stream_id); }
void encode(YAML::Node &) override;
#define _SET(a, b) SET_FUNC(StreamStateUpdated, a, b)
_SET(new, StreamState);
_SET(old, StreamState);
_SET(stream_id, std::string);
_SET(bidi, bool);
#undef _SET
std::string
event() const override
{
return "stream_state_updated";
}
};
class FrameProcessed : public TransportEvent
{
public:
APPEND_FRAME_FUNC(FrameProcessed)
void encode(YAML::Node &) override;
std::string
event() const override
{
return "frame_processed";
}
};
} // namespace Transport
namespace Recovery
{
class RecoveryEvent : public QLogEvent
{
public:
std::string
category() const override
{
return "recovery";
}
};
class ParametersSet : public RecoveryEvent
{
public:
#define _SET(a, b) SET_FUNC(ParametersSet, a, b)
_SET(reordering_threshold, int);
_SET(time_threshold, int);
_SET(timer_granularity, int);
_SET(initial_rtt, int);
_SET(max_datagram_size, int);
_SET(initial_congestion_window, int);
_SET(minimum_congestion_window, int);
_SET(loss_reduction_factor, int);
_SET(persistent_congestion_threshold, int);
#undef _SET
void encode(YAML::Node &) override;
std::string
event() const override
{
return "parameters_set";
}
};
class MetricsUpdated : public RecoveryEvent
{
public:
#define _SET(a, b) SET_FUNC(MetricsUpdated, a, b)
_SET(min_rtt, int);
_SET(smoothed_rtt, int);
_SET(latest_rtt, int);
_SET(rtt_variance, int);
_SET(max_ack_delay, int);
_SET(pto_count, int);
_SET(congestion_window, int);
_SET(bytes_in_flight, int);
_SET(ssthresh, int);
_SET(packets_in_flight, int);
_SET(in_recovery, int);
_SET(pacing_rate, int);
#undef _SET
void encode(YAML::Node &) override;
std::string
event() const override
{
return "metrics_updated";
}
};
class CongestionStateUpdated : public RecoveryEvent
{
public:
enum class State : uint8_t {
slow_start,
congestion_avoidance,
application_limited,
recovery,
};
enum class Triggered : uint8_t {
unknown,
persistent_congestion,
ECN,
};
CongestionStateUpdated(State n, Triggered tr = Triggered::unknown) { set_trigger(tr).set_new(n); }
#define _SET(a, b) SET_FUNC(CongestionStateUpdated, a, b)
_SET(trigger, Triggered)
_SET(new, State)
_SET(old, State)
#undef _SET
void encode(YAML::Node &) override;
std::string
event() const override
{
return "congestion_state_updated";
}
static const char *
trigger_name(Triggered tr)
{
switch (tr) {
case Triggered::persistent_congestion:
return "persistent_congestion";
case Triggered::ECN:
return "ECN";
default:
return nullptr;
}
}
static const char *
state_to_string(State s)
{
switch (s) {
case State::slow_start:
return "slow_start";
case State::congestion_avoidance:
return "congestion_avoidance";
case State::application_limited:
return "application_limited";
case State::recovery:
return "recovery";
default:
break;
}
return nullptr;
}
};
class LossTimerUpdated : public RecoveryEvent
{
public:
enum class EventType : uint8_t {
set,
expired,
cancelled,
};
void
set_timer_type(bool ack)
{
this->_timer_type_ack = ack;
}
void encode(YAML::Node &) override;
#define _SET(a, b) SET_FUNC(LossTimerUpdated, a, b)
_SET(event_type, EventType)
_SET(packet_number_space, int);
_SET(delta, int);
#undef _SET
std::string
event() const override
{
return "loss_timer_updated";
}
static const char *
event_type_name(EventType et)
{
switch (et) {
case EventType::set:
return "set";
case EventType::expired:
return "expired";
case EventType::cancelled:
return "cancelled";
default:
break;
}
return nullptr;
}
private:
bool _timer_type_ack = false;
};
class PacketLost : public RecoveryEvent
{
public:
enum class Triggered : uint8_t {
unknown,
reordering_threshold,
time_threshold,
pto_expired,
};
PacketLost(PacketType pt, uint64_t pn, Triggered tr = Triggered::unknown)
{
set_trigger(tr).set_packet_type(pt).set_packet_number(pn);
}
#define _SET(a, b) SET_FUNC(PacketLost, a, b)
_SET(header, PacketHeader)
_SET(packet_number, uint64_t);
_SET(packet_type, PacketType);
_SET(trigger, Triggered)
APPEND_FRAME_FUNC(PacketLost)
#undef _SET
void encode(YAML::Node &) override;
std::string
event() const override
{
return "packet_lost";
}
static const char *
trigger_name(Triggered tr)
{
switch (tr) {
case Triggered::pto_expired:
return "pto_expired";
case Triggered::reordering_threshold:
return "reordering_threshold";
case Triggered::time_threshold:
return "time_threshold";
default:
return nullptr;
}
}
};
class MarkedForRetransmit : public RecoveryEvent
{
public:
APPEND_FRAME_FUNC(MarkedForRetransmit)
void encode(YAML::Node &) override;
std::string
event() const override
{
return "marked_for_retransmit";
}
};
} // namespace Recovery
} // namespace QLog
|
nozomi1773/trafficserver
|
proxy/http3/QPACK.h
|
/** @file
*
* A brief file description
*
* @section license License
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <map>
#include "I_EventSystem.h"
#include "I_Event.h"
#include "I_IOBuffer.h"
#include "tscore/Arena.h"
#include "tscpp/util/IntrusiveDList.h"
#include "MIME.h"
#include "HTTP.h"
#include "QUICApplication.h"
#include "QUICConnection.h"
class HTTPHdr;
enum {
QPACK_EVENT_DECODE_COMPLETE = QPACK_EVENT_EVENTS_START,
QPACK_EVENT_DECODE_FAILED,
};
class QPACK : public QUICApplication
{
public:
QPACK(QUICConnection *qc, uint32_t max_header_list_size, uint16_t max_table_size, uint16_t max_blocking_streams);
virtual ~QPACK();
int event_handler(int event, Event *data);
/*
* header_block must have enough size to store all headers in header_set.
* The maximum size can be estimated with QPACK::estimate_header_block_size().
*/
int encode(uint64_t stream_id, HTTPHdr &header_set, MIOBuffer *header_block, uint64_t &header_block_len);
/*
* This will emit either of two events below:
* - QPACK_EVENT_DECODE_COMPLETE (Data: *HTTPHdr)
* - QPACK_EVENT_DECODE_FAILED (Data: nullptr)
*/
int decode(uint64_t stream_id, const uint8_t *header_block, size_t header_block_len, HTTPHdr &hdr, Continuation *cont,
EThread *thread = this_ethread());
int cancel(uint64_t stream_id);
void set_encoder_stream(QUICStreamIO *stream_io);
void set_decoder_stream(QUICStreamIO *stream_io);
void update_max_header_list_size(uint32_t max_header_list_size);
void update_max_table_size(uint16_t max_table_size);
void update_max_blocking_streams(uint16_t max_blocking_streams);
static size_t estimate_header_block_size(const HTTPHdr &header_set);
private:
struct LookupResult {
uint16_t index = 0;
enum MatchType { NONE, NAME, EXACT } match_type = MatchType::NONE;
};
struct Header {
Header(const char *n, const char *v) : name(n), value(v), name_len(strlen(name)), value_len(strlen(value)) {}
const char *name;
const char *value;
const int name_len;
const int value_len;
};
class StaticTable
{
public:
static const LookupResult lookup(uint16_t index, const char **name, int *name_len, const char **value, int *value_len);
static const LookupResult lookup(const char *name, int name_len, const char *value, int value_len);
private:
static const Header STATIC_HEADER_FIELDS[];
};
struct DynamicTableEntry {
uint16_t index = 0;
uint16_t offset = 0;
uint16_t name_len = 0;
uint16_t value_len = 0;
uint16_t ref_count = 0;
};
class DynamicTableStorage
{
public:
DynamicTableStorage(uint16_t size);
~DynamicTableStorage();
void read(uint16_t offset, const char **name, uint16_t name_len, const char **value, uint16_t value_len);
uint16_t write(const char *name, uint16_t name_len, const char *value, uint16_t value_len);
void erase(uint16_t name_len, uint16_t value_len);
private:
uint16_t _overwrite_threshold = 0;
uint8_t *_data = nullptr;
uint16_t _data_size = 0;
uint16_t _head = 0;
uint16_t _tail = 0;
};
class DynamicTable
{
public:
DynamicTable(uint16_t size);
~DynamicTable();
const LookupResult lookup(uint16_t index, const char **name, int *name_len, const char **value, int *value_len);
const LookupResult lookup(const char *name, int name_len, const char *value, int value_len);
const LookupResult insert_entry(bool is_static, uint16_t index, const char *value, uint16_t value_len);
const LookupResult insert_entry(const char *name, uint16_t name_len, const char *value, uint16_t value_len);
const LookupResult duplicate_entry(uint16_t current_index);
bool should_duplicate(uint16_t index);
void update_size(uint16_t max_size);
void ref_entry(uint16_t index);
void unref_entry(uint16_t index);
uint16_t largest_index();
private:
uint16_t _available = 0;
uint16_t _entries_inserted = 0;
// FIXME It may be better to split this array into small arrays to reduce memory footprint
struct DynamicTableEntry *_entries = nullptr;
uint16_t _max_entries = 0;
uint16_t _entries_head = 0;
uint16_t _entries_tail = 0;
DynamicTableStorage *_storage = nullptr;
};
class DecodeRequest
{
public:
DecodeRequest(uint16_t largest_reference, EThread *thread, Continuation *continuation, uint64_t stream_id,
const uint8_t *header_block, size_t header_block_len, HTTPHdr &hdr)
: _largest_reference(largest_reference),
_thread(thread),
_continuation(continuation),
_stream_id(stream_id),
_header_block(header_block),
_header_block_len(header_block_len),
_hdr(hdr)
{
}
uint16_t
largest_reference()
{
return this->_largest_reference;
}
EThread *
thread()
{
return this->_thread;
}
Continuation *
continuation()
{
return this->_continuation;
}
uint64_t
stream_id()
{
return this->_stream_id;
}
const uint8_t *
header_block()
{
return this->_header_block;
}
size_t
header_block_len()
{
return this->_header_block_len;
}
HTTPHdr &
hdr()
{
return this->_hdr;
}
class Linkage
{
public:
static DecodeRequest *&
next_ptr(DecodeRequest *t)
{
return *reinterpret_cast<DecodeRequest **>(&t->_next);
}
static DecodeRequest *&
prev_ptr(DecodeRequest *t)
{
return *reinterpret_cast<DecodeRequest **>(&t->_prev);
}
};
private:
uint16_t _largest_reference;
EThread *_thread;
Continuation *_continuation;
uint64_t _stream_id;
const uint8_t *_header_block;
size_t _header_block_len;
HTTPHdr &_hdr;
// For IntrusiveDList support
DecodeRequest *_next = nullptr;
DecodeRequest *_prev = nullptr;
};
struct EntryReference {
uint16_t smallest;
uint16_t largest;
};
DynamicTable _dynamic_table;
std::map<uint64_t, struct EntryReference> _references;
uint32_t _max_header_list_size = 0;
uint16_t _max_table_size = 0;
uint16_t _max_blocking_streams = 0;
Continuation *_event_handler = nullptr;
void _resume_decode();
void _abort_decode();
bool _invalid = false;
ts::IntrusiveDList<DecodeRequest::Linkage> _blocked_list;
bool _add_to_blocked_list(DecodeRequest *decode_request);
uint16_t _largest_known_received_index = 0;
void _update_largest_known_received_index_by_insert_count(uint16_t insert_count);
void _update_largest_known_received_index_by_stream_id(uint64_t stream_id);
void _update_reference_counts(uint64_t stream_id);
// Encoder Stream
int _read_insert_with_name_ref(QUICStreamIO &stream_io, bool &is_static, uint16_t &index, Arena &arena, char **value,
uint16_t &value_len);
int _read_insert_without_name_ref(QUICStreamIO &stream_io, Arena &arena, char **name, uint16_t &name_len, char **value,
uint16_t &value_len);
int _read_duplicate(QUICStreamIO &stream_io, uint16_t &index);
int _read_dynamic_table_size_update(QUICStreamIO &stream_io, uint16_t &max_size);
int _write_insert_with_name_ref(uint16_t index, bool dynamic, const char *value, uint16_t value_len);
int _write_insert_without_name_ref(const char *name, int name_len, const char *value, uint16_t value_len);
int _write_duplicate(uint16_t index);
int _write_dynamic_table_size_update(uint16_t max_size);
// Decoder Stream
int _read_table_state_synchronize(QUICStreamIO &stream_io, uint16_t &insert_count);
int _read_header_acknowledgement(QUICStreamIO &stream_io, uint64_t &stream_id);
int _read_stream_cancellation(QUICStreamIO &stream_io, uint64_t &stream_id);
int _write_table_state_synchronize(uint16_t insert_count);
int _write_header_acknowledgement(uint64_t stream_id);
int _write_stream_cancellation(uint64_t stream_id);
// Request and Push Streams
int _encode_prefix(uint16_t largest_reference, uint16_t base_index, IOBufferBlock *prefix);
int _encode_header(const MIMEField &field, uint16_t base_index, IOBufferBlock *compressed_header, uint16_t &referred_index);
int _encode_indexed_header_field(uint16_t index, uint16_t base_index, bool dynamic_table, IOBufferBlock *compressed_header);
int _encode_indexed_header_field_with_postbase_index(uint16_t index, uint16_t base_index, bool never_index,
IOBufferBlock *compressed_header);
int _encode_literal_header_field_with_name_ref(uint16_t index, bool dynamic_table, uint16_t base_index, const char *value,
int value_len, bool never_index, IOBufferBlock *compressed_header);
int _encode_literal_header_field_without_name_ref(const char *name, int name_len, const char *value, int value_len,
bool never_index, IOBufferBlock *compressed_header);
int _encode_literal_header_field_with_postbase_name_ref(uint16_t index, uint16_t base_index, const char *value, int value_len,
bool never_index, IOBufferBlock *compressed_header);
void _decode(EThread *ethread, Continuation *cont, uint64_t stream_id, const uint8_t *header_block, size_t header_block_len,
HTTPHdr &hdr);
int _decode_header(const uint8_t *header_block, size_t header_block_len, HTTPHdr &hdr);
int _decode_indexed_header_field(int16_t base_index, const uint8_t *buf, size_t buf_len, HTTPHdr &hdr, uint32_t &header_len);
int _decode_indexed_header_field_with_postbase_index(int16_t base_index, const uint8_t *buf, size_t buf_len, HTTPHdr &hdr,
uint32_t &header_len);
int _decode_literal_header_field_with_name_ref(int16_t base_index, const uint8_t *buf, size_t buf_len, HTTPHdr &hdr,
uint32_t &header_len);
int _decode_literal_header_field_without_name_ref(const uint8_t *buf, size_t buf_len, HTTPHdr &hdr, uint32_t &header_len);
int _decode_literal_header_field_with_postbase_name_ref(int16_t base_index, const uint8_t *buf, size_t buf_len, HTTPHdr &hdr,
uint32_t &header_len);
// Utilities
uint16_t _calc_absolute_index_from_relative_index(uint16_t base_index, uint16_t relative_index);
uint16_t _calc_absolute_index_from_postbase_index(uint16_t base_index, uint16_t postbase_index);
uint16_t _calc_relative_index_from_absolute_index(uint16_t base_index, uint16_t absolute_index);
uint16_t _calc_postbase_index_from_absolute_index(uint16_t base_index, uint16_t absolute_index);
void _attach_header(HTTPHdr &hdr, const char *name, int name_len, const char *value, int value_len, bool never_index);
int _on_read_ready(QUICStreamIO &stream_io);
int _on_decoder_stream_read_ready(QUICStreamIO &stream_io);
int _on_encoder_stream_read_ready(QUICStreamIO &stream_io);
int _on_write_ready(QUICStreamIO &stream_io);
int _on_decoder_write_ready(QUICStreamIO &stream_io);
int _on_encoder_write_ready(QUICStreamIO &stream_io);
// Stream numbers
// FIXME How are these stream ids negotiated? In interop, encoder stream id have to be 0 and decoder stream id must not be used.
uint64_t _encoder_stream_id = 0;
uint64_t _decoder_stream_id = 9999;
// Chain of sending instructions
MIOBuffer *_encoder_stream_sending_instructions;
MIOBuffer *_decoder_stream_sending_instructions;
IOBufferReader *_encoder_stream_sending_instructions_reader;
IOBufferReader *_decoder_stream_sending_instructions_reader;
};
|
sjinks/qt_socketconnector
|
src/socketconnector_p.h
|
#ifndef SOCKETCONNECTOR_P_H
#define SOCKETCONNECTOR_P_H
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QHostInfo>
#include "qt4compat.h"
#if QT_VERSION >= 0x040400
QT_FORWARD_DECLARE_CLASS(QSocketNotifier)
QT_FORWARD_DECLARE_CLASS(QTimer)
#else
class QSocketNotifier;
class QTimer;
#endif
class SocketConnector;
class Q_DECL_HIDDEN SocketConnectorPrivate {
Q_DECLARE_PUBLIC(SocketConnector)
SocketConnector* const q_ptr;
public:
SocketConnectorPrivate(SocketConnector* const q);
~SocketConnectorPrivate(void);
bool createSocket(int domain, int type, int proto);
bool bindTo(const QHostAddress& a, quint16 port);
void connectToHost(const QString& address, quint16 port);
void disconnectFromHost(void);
void abort(void);
bool waitForConnected(int timeout);
private:
int m_fd;
int m_domain;
int m_type;
int m_proto;
int m_port;
uint m_connectiont_timeout;
QAbstractSocket::SocketState m_state;
QAbstractSocket::SocketError m_error;
QList<QHostAddress> m_addresses;
QHostAddress m_bound_address;
quint16 m_bound_port;
int m_lookup_id;
QSocketNotifier* m_notifier;
QTimer* m_timer;
int recreateSocket(void);
bool bindV4(const QHostAddress& a, quint16 port);
bool bindV6(const QHostAddress& a, quint16 port);
int connectV4(const QHostAddress& a);
int connectV6(const QHostAddress& a);
void _q_startConnecting(const QHostInfo& info);
void _q_connectToNextAddress(void);
void _q_connected(int sock);
void _q_abortConnection(void);
};
#endif // SOCKETCONNECTOR_P_H
|
sjinks/qt_socketconnector
|
src/socketconnector.h
|
<gh_stars>0
#ifndef SOCKETCONNECTOR_H
#define SOCKETCONNECTOR_H
#include <QtCore/QObject>
#include <QtNetwork/QAbstractSocket>
#include <QtNetwork/QHostInfo>
#if QT_VERSION < 0x050000
typedef qptrdiff qintptr;
#endif
class SocketConnectorPrivate;
class SocketConnector : public QObject {
Q_OBJECT
public:
SocketConnector(QObject* parent = 0);
virtual ~SocketConnector(void);
bool createSocket(int domain, int type, int proto = 0);
bool createTcpSocket(void);
bool createUdpSocket(void);
bool bindTo(const QHostAddress& a, quint16 port = 0);
void connectToHost(const QString& address, quint16 port);
void connectToHost(const QHostAddress& address, quint16 port);
void disconnectFromHost(void);
void abort(void);
bool waitForConnected(int timeout = 30000);
bool assignTo(QAbstractSocket* target);
QAbstractSocket::SocketType socketType(void) const;
QAbstractSocket::SocketState state(void) const;
QAbstractSocket::SocketError error(void) const;
qintptr socketDescriptor(void) const;
void setConnectionTimeout(uint timeout);
uint connectionTimeout(void) const;
Q_SIGNALS:
void hostFound(void);
void connected(void);
void disconnected(void);
void stateChanged(QAbstractSocket::SocketState);
void error(QAbstractSocket::SocketError);
private:
Q_DISABLE_COPY(SocketConnector)
Q_DECLARE_PRIVATE(SocketConnector)
#if QT_VERSION >= 0x040600
QScopedPointer<SocketConnectorPrivate> d_ptr;
#else
SocketConnectorPrivate* d_ptr;
#endif
Q_PRIVATE_SLOT(d_func(), void _q_startConnecting(QHostInfo))
Q_PRIVATE_SLOT(d_func(), void _q_connectToNextAddress())
Q_PRIVATE_SLOT(d_func(), void _q_connected(int))
Q_PRIVATE_SLOT(d_func(), void _q_abortConnection())
};
#endif // SOCKETCONNECTOR_H
|
sjinks/qt_socketconnector
|
qtscriptgenerator/master.h
|
#ifndef MASTER_H
#define MASTER_H
#include <QtCore/QObject>
#include <QtNetwork/QAbstractSocket>
#include <QtNetwork/QHostAddress>
#include "../src/socketconnector.h"
#endif
|
ErikZhou/swig-example
|
swig-example.h
|
<filename>swig-example.h
void swig_example_hello();
void link_liba_hello();
|
batukov/AgentFabrix
|
c_src/agent_maths.c
|
<reponame>batukov/AgentFabrix
#include "erl_nif.h"
static ERL_NIF_TERM calc_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
int a;
if (!enif_get_int(env, argv[0], &a))
{
return enif_make_badarg(env);
}
a = a*2;
return enif_make_int(env, a);
}
static ErlNifFunc export_funcs[] = {
{"calc", 1, calc_nif}
};
ERL_NIF_INIT(agent, export_funcs, NULL, NULL, NULL, NULL)
|
zzqcn/udpi
|
src/dpi_api.c
|
/*
*------------------------------------------------------------------
* Copyright (c) 2018 Intel, Travelping and/or its affiliates.
* 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 <vnet/interface.h>
#include <vnet/api_errno.h>
#include <vnet/feature/feature.h>
#include <vnet/fib/fib_table.h>
#include <vppinfra/byte_order.h>
#include <vlibmemory/api.h>
#include "dpi.h"
#define vl_msg_id(n,h) n,
typedef enum
{
#include "dpi.api.h"
/* We'll want to know how many messages IDs we need... */
VL_MSG_FIRST_AVAILABLE,
} vl_msg_id_t;
#undef vl_msg_id
/* define message structures */
#define vl_typedefs
#include "dpi.api.h"
#undef vl_typedefs
/* define generated endian-swappers */
#define vl_endianfun
#include "dpi.api.h"
#undef vl_endianfun
/* instantiate all the print functions we know about */
#define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
#define vl_printfun
#include "dpi.api.h"
#undef vl_printfun
/* Get the API version number */
#define vl_api_version(n,v) static u32 api_version=(v);
#include "dpi.api.h"
#undef vl_api_version
#define vl_msg_name_crc_list
#include "dpi.api.h"
#undef vl_msg_name_crc_list
#define REPLY_MSG_ID_BASE dm->msg_id_base
#include <vlibapi/api_helper_macros.h>
#define foreach_dpi_plugin_api_msg \
_(DPI_FLOW_ADD_DEL, dpi_flow_add_del)
/* API message handler */
static void
vl_api_dpi_flow_add_del_t_handler (vl_api_dpi_flow_add_del_t * mp)
{
vl_api_dpi_flow_add_del_reply_t *rmp = NULL;
dpi_main_t *dm = &dpi_main;
int rv = 0;
u32 fib_index;
u32 flow_id = ~0;
fib_index = fib_table_find (fib_ip_proto (mp->is_ipv6), ntohl (mp->vrf_id));
if (fib_index == ~0)
{
rv = VNET_API_ERROR_NO_SUCH_FIB;
goto out;
}
dpi_add_del_flow_args_t a = {
.is_add = mp->is_add,
.is_ipv6 = mp->is_ipv6,
.src_ip = to_ip46 (mp->is_ipv6, mp->src_ip),
.dst_ip = to_ip46 (mp->is_ipv6, mp->dst_ip),
.src_port = ntohs (mp->src_port),
.dst_port = ntohs (mp->dst_port),
.protocol = mp->protocol,
.fib_index = fib_index,
};
/* Check src ip and dst ip are different */
if (ip46_address_cmp (&a.dst_ip, &a.src_ip) == 0)
{
rv = VNET_API_ERROR_SAME_SRC_DST;
goto out;
}
rv = dpi_flow_add_del (&a, &flow_id);
out:
/* *INDENT-OFF* */
REPLY_MACRO2(VL_API_DPI_FLOW_ADD_DEL_REPLY,
({
rmp->flow_id = htonl (flow_id);
}));
/* *INDENT-ON* */
}
static void
setup_message_id_table (api_main_t * am)
{
#define _(id,n,crc) vl_msg_api_add_msg_name_crc (am, #n "_" #crc, id);
foreach_vl_msg_name_crc_dpi;
#undef _
}
static clib_error_t *
dpi_api_hookup (vlib_main_t * vm)
{
dpi_main_t *dm = &dpi_main;
api_main_t *am = vlibapi_get_main ();
u8 *name = format (0, "dpi_%08x%c", api_version, 0);
dm->msg_id_base = vl_msg_api_get_msg_ids
((char *) name, VL_MSG_FIRST_AVAILABLE);
#define _(N,n) \
vl_msg_api_set_handlers((VL_API_##N + dm->msg_id_base), \
#n, \
vl_api_##n##_t_handler, \
vl_noop_handler, \
vl_api_##n##_t_endian, \
vl_api_##n##_t_print, \
sizeof(vl_api_##n##_t), 1);
foreach_dpi_plugin_api_msg;
#undef _
/* Add our API messages to the global name_crc hash table */
setup_message_id_table (am);
return 0;
}
VLIB_API_INIT_FUNCTION (dpi_api_hookup);
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
zzqcn/udpi
|
src/dpi_cli.c
|
/*
*------------------------------------------------------------------
* Copyright (c) 2018 Intel, Travelping and/or its affiliates.
* 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 <stdint.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <inttypes.h>
#include <vlib/vlib.h>
#include <vlib/unix/unix.h>
#include <vnet/ethernet/ethernet.h>
#include <vnet/plugin/plugin.h>
#include <vnet/fib/fib_entry.h>
#include <vnet/fib/fib_table.h>
//#include <vpp/app/version.h>
#include "dpi.h"
extern dpi_main_t dpi_main;
extern dpi_entry_t *dpi_dbs;
static clib_error_t *
dpi_flow_add_del_command_fn (vlib_main_t * vm,
unformat_input_t * input,
vlib_cli_command_t * cmd_arg)
{
unformat_input_t _line_input, *line_input = &_line_input;
ip46_address_t src_ip = ip46_address_initializer;
ip46_address_t dst_ip = ip46_address_initializer;
u16 src_port = 0, dst_port = 0;
u8 is_add = 0;
u8 ipv4_set = 0;
u8 ipv6_set = 0;
u32 tmp;
int rv;
u8 protocol = 0;
u32 table_id;
u32 fib_index = 0;
u32 dpi_flow_id;
if (!unformat_user (input, unformat_line_input, line_input))
return 0;
while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
{
if (unformat (line_input, "add"))
is_add = 1;
else if (unformat (line_input, "del"))
is_add = 0;
else if (unformat (line_input, "src-ip %U", unformat_ip46_address,
&src_ip, IP46_TYPE_ANY))
{
ip46_address_is_ip4 (&src_ip) ? (ipv4_set = 1) : (ipv6_set = 1);
}
else if (unformat (line_input, "dst-ip %U", unformat_ip46_address,
&dst_ip, IP46_TYPE_ANY))
{
ip46_address_is_ip4 (&dst_ip) ? (ipv4_set = 1) : (ipv6_set = 1);
}
else if (unformat (line_input, "src-port %d", &tmp))
src_port = (u16) tmp;
else if (unformat (line_input, "dst-port %d", &tmp))
dst_port = (u16) tmp;
else
if (unformat (line_input, "protocol %U", unformat_ip_protocol, &tmp))
protocol = (u8) tmp;
else if (unformat (line_input, "protocol %u", &tmp))
protocol = (u8) tmp;
else if (unformat (line_input, "vrf-id %d", &table_id))
{
fib_index = fib_table_find (fib_ip_proto (ipv6_set), table_id);
}
else
return clib_error_return (0, "parse error: '%U'",
format_unformat_error, line_input);
}
unformat_free (line_input);
if (ipv4_set && ipv6_set)
return clib_error_return (0, "both IPv4 and IPv6 addresses specified");
dpi_add_del_flow_args_t a = {.is_add = is_add,
.is_ipv6 = ipv6_set,
#define _(x) .x = x,
foreach_copy_field
#undef _
};
/* Add normal flow */
rv = dpi_flow_add_del (&a, &dpi_flow_id);
if (rv < 0)
return clib_error_return (0, "flow error: %d", rv);
/* Add reverse flow */
rv = dpi_reverse_flow_add_del (&a, dpi_flow_id);
if (rv < 0)
return clib_error_return (0, "reverse flow error: %d", rv);
vlib_cli_output(vm, "dpi flow id\n%u", dpi_flow_id);
return 0;
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (dpi_flow_add_del_command, static) = {
.path = "dpi flow",
.short_help = "dpi flow [add | del] "
"[src-ip <ip-addr>] [dst-ip <ip-addr>] "
"[src-port <port>] [dst-port <port>] "
"[protocol <protocol>] [vrf-id <nn>]",
.function = dpi_flow_add_del_command_fn,
};
/* *INDENT-ON* */
static clib_error_t *
dpi_tcp_reass_command_fn (vlib_main_t * vm,
unformat_input_t * input,
vlib_cli_command_t * cmd_arg)
{
unformat_input_t _line_input, *line_input = &_line_input;
u32 flow_id = ~0;
u8 reass_en = 0;
u8 reass_dir = 0;
int rv;
if (!unformat_user (input, unformat_line_input, line_input))
return 0;
while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
{
if (unformat (line_input, "flow_id %d", &flow_id))
;
else if (unformat (line_input, "enable"))
{
reass_en = 1;
}
else if (unformat (line_input, "disable"))
{
reass_en = 0;
}
else if (unformat (line_input, "client"))
{
reass_dir = REASS_C2S;
}
else if (unformat (line_input, "server"))
{
reass_dir = REASS_S2C;
}
else if (unformat (line_input, "both"))
{
reass_dir = REASS_BOTH;
}
else
return clib_error_return (0, "parse error: '%U'",
format_unformat_error, line_input);
}
unformat_free (line_input);
tcp_reass_args_t a = {.flow_id = flow_id,
.reass_en = reass_en,
.reass_dir = reass_dir,
};
rv = dpi_tcp_reass (&a);
if (rv < 0)
return clib_error_return (0, "flow error: %d", rv);
return 0;
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (dpi_tcp_reass_command, static) = {
.path = "dpi tcp reass",
.short_help = "dpi tcp reass flow_id <nn> <enable|disable> "
"[ <client | server | both> ]",
.function = dpi_tcp_reass_command_fn,
};
/* *INDENT-ON* */
static clib_error_t *
dpi_flow_offload_command_fn (vlib_main_t * vm,
unformat_input_t * input,
vlib_cli_command_t * cmd)
{
unformat_input_t _line_input, *line_input = &_line_input;
dpi_main_t *dm = &dpi_main;
vnet_main_t *vnm = dm->vnet_main;
u32 rx_flow_id = ~0;
u32 hw_if_index = ~0;
int is_add = 1;
u32 is_ipv6 = 0;
u32 is_enable = 1;
dpi_flow_entry_t *flow;
vnet_hw_interface_t *hw_if;
u32 rx_fib_index = ~0;
/* Get a line of input. */
if (!unformat_user (input, unformat_line_input, line_input))
return 0;
while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
{
if (unformat (line_input, "hw %U", unformat_vnet_hw_interface, vnm,
&hw_if_index))
continue;
if (unformat (line_input, "rx %d", &rx_flow_id))
continue;
if (unformat (line_input, "del"))
{
is_add = 0;
continue;
}
return clib_error_return (0, "unknown input `%U'",
format_unformat_error, line_input);
}
if (rx_flow_id == ~0)
return clib_error_return (0, "missing rx flow");
if (hw_if_index == ~0)
return clib_error_return (0, "missing hw interface");
flow = pool_elt_at_index (dm->dpi_flows, rx_flow_id);
hw_if = vnet_get_hw_interface (vnm, hw_if_index);
is_ipv6 = ip46_address_is_ip4 (&(flow->key.src_ip)) ? 0 : 1;
if (is_ipv6)
{
ip6_main_t *im6 = &ip6_main;
rx_fib_index =
vec_elt (im6->fib_index_by_sw_if_index, hw_if->sw_if_index);
}
else
{
ip4_main_t *im4 = &ip4_main;
rx_fib_index =
vec_elt (im4->fib_index_by_sw_if_index, hw_if->sw_if_index);
}
if (flow->key.fib_index != rx_fib_index)
return clib_error_return (0, "interface/flow fib mismatch");
if (dpi_add_del_rx_flow (hw_if_index, rx_flow_id, is_add, is_ipv6))
return clib_error_return (0, "error %s flow",
is_add ? "enabling" : "disabling");
dpi_flow_offload_mode (hw_if_index, is_ipv6, is_enable);
return 0;
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (dpi_flow_offload_command, static) = {
.path = "dpi set flow-offload",
.short_help =
"dpi set flow-offload hw <interface-name> rx <flow-id> [del]",
.function = dpi_flow_offload_command_fn,
};
/* *INDENT-ON* */
static clib_error_t *
dpi_set_flow_bypass (u32 is_ip6,
unformat_input_t * input, vlib_cli_command_t * cmd)
{
unformat_input_t _line_input, *line_input = &_line_input;
vnet_main_t *vnm = vnet_get_main ();
clib_error_t *error = 0;
u32 sw_if_index, is_enable;
sw_if_index = ~0;
is_enable = 1;
if (!unformat_user (input, unformat_line_input, line_input))
return 0;
while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
{
if (unformat_user (line_input, unformat_vnet_sw_interface, vnm,
&sw_if_index))
;
else if (unformat (line_input, "del"))
is_enable = 0;
else
{
error = unformat_parse_error (line_input);
goto done;
}
}
if (~0 == sw_if_index)
{
error = clib_error_return (0, "unknown interface `%U'",
format_unformat_error, line_input);
goto done;
}
dpi_flow_bypass_mode (sw_if_index, is_ip6, is_enable);
done:
unformat_free (line_input);
return error;
}
static clib_error_t *
dpi_set_ip4_flow_bypass_command_fn (vlib_main_t * vm,
unformat_input_t * input,
vlib_cli_command_t * cmd)
{
return dpi_set_flow_bypass (0, input, cmd);
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (dpi_set_ip4_flow_bypass_command, static) =
{
.path = "dpi set ip4 flow-bypass",
.short_help = "dpi set ip4 flow-bypass <interface> [del]",
.function = dpi_set_ip4_flow_bypass_command_fn,
};
/* *INDENT-ON* */
static clib_error_t *
dpi_set_ip6_flow_bypass_command_fn (vlib_main_t * vm,
unformat_input_t * input,
vlib_cli_command_t * cmd)
{
return dpi_set_flow_bypass (0, input, cmd);
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (dpi_set_ip6_flow_bypass_command, static) =
{
.path = "dpi set ip6 flow-bypass",
.short_help = "dpi set ip6 flow-bypass <interface> [del]",
.function = dpi_set_ip6_flow_bypass_command_fn,
};
/* *INDENT-ON* */
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.