Commit a6293e49 authored by aohui.li's avatar aohui.li

wirerope project create (v1.00)

parents
FROM espressif/idf
ARG DEBIAN_FRONTEND=nointeractive
RUN apt-get update \
&& apt install -y -q \
cmake \
git \
hwdata \
libglib2.0-0 \
libnuma1 \
libpixman-1-0 \
linux-tools-virtual \
&& rm -rf /var/lib/apt/lists/*
RUN update-alternatives --install /usr/local/bin/usbip usbip `ls /usr/lib/linux-tools/*/usbip | tail -n1` 20
# QEMU
ENV QEMU_REL=esp-develop-20220919
ENV QEMU_SHA256=f6565d3f0d1e463a63a7f81aec94cce62df662bd42fc7606de4b4418ed55f870
ENV QEMU_DIST=qemu-${QEMU_REL}.tar.bz2
ENV QEMU_URL=https://github.com/espressif/qemu/releases/download/${QEMU_REL}/${QEMU_DIST}
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8
RUN wget --no-verbose ${QEMU_URL} \
&& echo "${QEMU_SHA256} *${QEMU_DIST}" | sha256sum --check --strict - \
&& tar -xf $QEMU_DIST -C /opt \
&& rm ${QEMU_DIST}
ENV PATH=/opt/qemu/bin:${PATH}
RUN echo "source /opt/esp/idf/export.sh > /dev/null 2>&1" >> ~/.bashrc
ENTRYPOINT [ "/opt/esp/entrypoint.sh" ]
CMD ["/bin/bash"]
\ No newline at end of file
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.183.0/containers/ubuntu
{
"name": "ESP-IDF QEMU",
"build": {
"dockerfile": "Dockerfile"
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"ms-vscode.cpptools",
"espressif.esp-idf-extension"
],
"workspaceMount": "source=${localWorkspaceFolder},target=/workspaces,type=bind",
/* the path of workspace folder to be opened after container is running
*/
"workspaceFolder": "/workspaces",
"mounts": [
"source=extensionCache,target=/root/.vscode-server/extensions,type=volume"
],
"settings": {
"terminal.integrated.defaultProfile.linux": "bash",
"idf.espIdfPath": "/opt/esp/idf",
"idf.customExtraPaths": "",
"idf.pythonBinPath": "/opt/esp/python_env/idf5.1_py3.8_env/bin/python",
"idf.toolsPath": "/opt/esp",
"idf.gitPath": "/usr/bin/git"
},
"runArgs": ["--privileged"]
}
\ No newline at end of file
.vscode/
.history/
build/
\ No newline at end of file
# The following four lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
# (Not part of the boilerplate)
# This example uses an extra component for common functions such as Wi-Fi and Ethernet connection.
set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/common_components/protocol_examples_common)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(gatewayble)
#
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
# project subdirectory.
#
PROJECT_NAME := mqtt_tcp
EXTRA_COMPONENT_DIRS = $(IDF_PATH)/examples/common_components/protocol_examples_common
include $(IDF_PATH)/make/project.mk
# 蓝牙网关
## V1.00
## 以太网移植
## 添加mqtt
#include "stddef.h"
#include "stdint.h"
#include "stdbool.h"
#include "stdlib.h"
#include "math.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "GatewayFSM.h"
#include "SensorFSM.h"
#include "pwr_gpio.h"
#include "WIT2FSM.h"
static gw_state_t eState = GW_STATE_IDLE;
static uint32_t u32CollectStartTick = 0;
static uint32_t u32MotorSyncStartTick = 0;
extern sensorFSM_t sensors[6];
extern speedSyncFSM spdSyncFSM;
void vGatewayInit(void)
{
eState = GW_STATE_IDLE;
u32CollectStartTick = 0;
u32MotorSyncStartTick = 0;
}
void vGatewayProcess(void)
{
uint32_t tu32_deviceRun = 0;
uint32_t tu32_ret = 0;
uint32_t tu32_completedCount = 0;
switch (eState)
{
case GW_STATE_IDLE:
{
tu32_deviceRun = WIT2FSM_DeviceRunCheck();
if (tu32_deviceRun == true)
{
if (WIT2FSM_NeedSend() == true)
{
tu32_ret = WIT2FSM_StartCollect();
if (tu32_ret == true)
{
eState = GW_STATE_COLLECTING;
spdSyncFSM.enable = WIT2FSM_GetSpdSyncConfig();
u32CollectStartTick = xTaskGetTickCount();
}
else
{
// Start collect failed 因为modbus 广播不需要返回,所以这里不会进来
eState = GW_STATE_COMPLETED;
}
}
else
{
// Start collect success
if (WIT2FSM_AmlVibCheck() == true)
{
// Has anomaly vibration
tu32_ret = WIT2FSM_StartCollect();
if (tu32_ret == true)
{
WIT2FSM_SendAmlVibAlarm();
eState = GW_STATE_COLLECTING;
spdSyncFSM.enable = false;
u32CollectStartTick = xTaskGetTickCount();
}
else
{
// Start collect failed
// 因为modbus 广播不需要返回,所以这里不会进来
eState = GW_STATE_COMPLETED;
}
}
// else
// {
// // Has not anomaly vibration
// WIT2FSM_PT100Read();
// }
}
}
else
{
// Device not run
// Send Gateway feature addr=0
if (WIT2FSM_SendHeartToServer(0) == true)
{
// Send success
break;
}
else
{
// Send failed
}
}
WIT2FSM_SendError();
vTaskDelay(10);
}
break;
case GW_STATE_COLLECTING:
{
if (abs((long long)xTaskGetTickCount() - (long long)u32CollectStartTick) > TIMEOUT_COLLECT_TICK_MAX)
{
if (spdSyncFSM.enable == true)
{
if (spdSyncFSM.mpsAddr == 0 || spdSyncFSM.mpsAddr > 6)
{
eState = GW_STATE_COMPLETED;
}
else if (sensors[spdSyncFSM.mpsAddr - 1].state != SEN_STATE_COMPLETED)
{
eState = GW_STATE_COMPLETED;
}
else
{
eState = GW_STATE_MOTORSYNC;
}
}
else
{
eState = GW_STATE_COMPLETED;
}
break;
}
tu32_completedCount = 0;
for (size_t i = 0; i < SENSOR_NUMBER_MAX; i++)
{
if (sensors[i].available != true)
{
++tu32_completedCount;
continue;
}
if (sensors[i].state == SEN_STATE_COLLECTING)
{
// ready
}
else if (sensors[i].state == SEN_STATE_COMPLETED)
{
++tu32_completedCount;
}
else
{
}
}
if (tu32_completedCount == SENSOR_NUMBER_MAX)
{
// Sensor collect complete
if (spdSyncFSM.enable == true)
{
eState = GW_STATE_MOTORSYNC;
}
else
{
eState = GW_STATE_COMPLETED;
}
}
}
break;
case GW_STATE_MOTORSYNC:
{
if (spdSyncFSM.mpsAddr == 0 || spdSyncFSM.mpsAddr > 6)
{
eState = GW_STATE_COMPLETED;
}
else if (sensors[spdSyncFSM.mpsAddr].available == true)
{
// motor speed sync
if (WIT2FSM_MotorSpeedSync(&spdSyncFSM) == true)
{
u32MotorSyncStartTick = xTaskGetTickCount();
eState = GW_STATE_WAITFOR_MOTORSYNC;
}
else
{
// motor speed sync failed
eState = GW_STATE_COMPLETED;
}
}
else{
eState = GW_STATE_COMPLETED;
}
}
break;
case GW_STATE_WAITFOR_MOTORSYNC:
{
if (abs((long long)xTaskGetTickCount() - (long long)u32MotorSyncStartTick) > TIMEOUT_MOTORSYNC_TICK_MAX)
{
// Motor sync timeout
eState = GW_STATE_COMPLETED;
break;
}
tu32_completedCount = 0;
for (size_t i = 0; i < SENSOR_NUMBER_MAX; i++)
{
if (sensors[i].available != true)
{
++tu32_completedCount;
continue;
}
if (sensors[i].state == SEN_STATE_RECALCULATE) // 老传感器没有转速同步
{
// ready
}
else if (sensors[i].state == SEN_STATE_COMPLETED)
{
++tu32_completedCount;
}
else
{
// unknow state 依靠超时
}
}
if (tu32_completedCount == SENSOR_NUMBER_MAX)
{
eState = GW_STATE_COMPLETED;
}
}
break;
case GW_STATE_COMPLETED:
{
bool needResetSensor = false;
// Send Gateway feature addr=0
if (WIT2FSM_SendGatewayFeatureToServer(0) == true)
{
// Send success
}
else
{
// Send failed
}
for (size_t i = 0; i < SENSOR_NUMBER_MAX; i++)
{
if (sensors[i].available != true)
{
continue;
}
if (sensors[i].state != SEN_STATE_COMPLETED)
{
sensors[i].u32SensorStateErrCnt++;
needResetSensor = true;
continue;
}
else
{
sensors[i].u32SensorStateErrCnt = 0;
}
// Send Sensor feature
if (WIT2FSM_SendSensorFeatureToServer(0, i + 1) == true)
{
// Send success
}
else
{
// Send failed
}
// Send Sensor data
if (WIT2FSM_SendWaveToServer(0, i + 1) == true)
{
// Send success
}
else
{
// Send failed
}
}
// Clear variable
WIT2FSM_ClearVarible();
if (needResetSensor == true)
{
for (size_t i = 0; i < SENSOR_NUMBER_MAX; i++)
{
if (sensors[i].available == false)
{
continue;
}
if (sensors[i].u32SensorStateErrCnt == 0)
{
continue;
}
if (sensors[i].u32SensorStateErrCnt < 11)
{
// reset sensor
pwr_set(false, true);
vTaskDelay(500);
pwr_set(true, true);
vTaskDelay(2000);
}
else
{
// disable
sensors[i].available = false;
sensors[i].errLastUpdateTick = xTaskGetTickCount();
}
}
}
eState = GW_STATE_IDLE;
}
break;
case GW_STATE_ERROR:
{
eState = GW_STATE_IDLE;
vTaskDelay(2000);
}
break;
default:
{
eState = GW_STATE_IDLE;
vTaskDelay(2000);
}
break;
}
}
gw_state_t xGatewayFSMStateGet(void)
{
return eState;
}
/**
* @file GatewayFSM.h
* @author your name (you@domain.com)
* @brief
* @version 0.1
* @date 2022-09-05
*
* @copyright Copyright (c) 2022
*
*/
#ifndef __GATEWAY_FSM_H
#define __GATEWAY_FSM_H
#define TIMEOUT_COLLECT_TICK_MAX (1000 * 60 * 5)
#define TIMEOUT_MOTORSYNC_TICK_MAX (1000 * 60 * 5)
typedef enum
{
GW_STATE_IDLE,
GW_STATE_COLLECTING,
GW_STATE_COMPLETED,
GW_STATE_ERROR,
GW_STATE_MOTORSYNC,
GW_STATE_WAITFOR_MOTORSYNC,
GW_STATE_MAX
} gw_state_t;
typedef struct
{
uint32_t enable; // enable speedSyncFSM
uint32_t mpsAddr; // motor monitor point addr
float MotorARRate; // motor actual speed
uint32_t state; // now FSM state
} speedSyncFSM;
void vGatewayInit(void);
void vGatewayProcess(void);
gw_state_t xGatewayFSMStateGet(void);
#endif
/**
* @file SensorFSM.c
* @author your name (you@domain.com)
* @brief
* @version 0.1
* @date 2022-09-02
*
* @copyright Copyright (c) 2022
*
*/
#include "SensorFSM.h"
#include "WIT2FSM.h"
#include "math.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
sensorFSM_t sensors[6] = {0};
extern bool g_bIsSensorExist[6];
uint32_t u32SensorStateGet(uint32_t addr, uint16_t *state)
{
return WIT2FSM_SensorStateGet(addr, state);
}
void sensorInit(void)
{
for (uint32_t i = 0; i < SENSOR_NUMBER_MAX; i++)
{
sensors[i].available = g_bIsSensorExist[i];
}
}
void sensorProcess(void)
{
uint16_t state = 0;
// sensor state get
for (uint32_t i = 0; i < SENSOR_NUMBER_MAX; i++)
{
state = 0;
if (sensors[i].available != true)
{
if (sensors[i].errLastUpdateTick != 0)
{
uint32_t newTick= xTaskGetTickCount();
sensors[i].errRestartTick += abs((int)((long long)newTick - (long long)sensors[i].errLastUpdateTick));
if(sensors[i].errRestartTick > SENSOR_RESTART_TIMEOUT)
{
// sensor resume
sensors[i].errLastUpdateTick = 0;
sensors[i].errRestartTick = 0;
sensors[i].available = true;
sensors[i].u32SensorStateErrCnt = 0;
}
else
{
sensors[i].errLastUpdateTick = newTick;
}
}
continue;
}
if (u32SensorStateGet(i + 1, &state) != true)
{
// sensor state get failed
sensors[i].state = SEN_STATE_READERROR;
}
else
{
if (sensors[i].state >= SEN_STATE_MAX)
{
// state invaild
sensors[i].state = SEN_IVLSTATE_ERROR;
}
else
{
sensors[i].state = state;
}
}
}
}
sen_state_t sensorStateGet(unsigned int idx)
{
return sensors[idx % 6].state;
}
bool sensorAvailableGet(uint32_t idx)
{
return sensors[idx % 6].available;
}
void sensorAvailableSet(uint32_t idx, bool state)
{
sensors[idx % 6].available = state;
}
uint32_t sensorsAvailableStateGet(void)
{
uint32_t ret = 0;
for (size_t i = 0; i < SENSOR_NUMBER_MAX; i++)
{
ret |= (sensors[i].available == true) ? (0x02 << i) : 0;
}
return ret;
}
void sensorsAvailableStateSet(uint32_t available)
{
if ((available & 126) > 0)
{
return;
}
for (size_t i = 0; i < SENSOR_NUMBER_MAX; i++)
{
sensors[i].available |= ((available & (0x02 << i)) != 0) ? true : false;
}
return;
}
/**
* @file SensorFSM.h
* @author your name (you@domain.com)
* @brief
* @version 0.1
* @date 2022-09-02
*
* @copyright Copyright (c) 2022
*
*/
#ifndef __SENSOR_FSM_H
#define __SENSOR_FSM_H
#include "stdint.h"
#include "stdbool.h"
#define SENSOR_NUMBER_MAX 6
#define SENSOR_RESTART_TIMEOUT (3 * 60 * 60 *1000)
typedef enum
{
SEN_STATE_IDLE = 0,
SEN_STATE_COLLECTING,
SEN_STATE_COMPLETED,
SEN_STATE_ERROR,
SEN_STATE_RECALCULATE, // 老传感器没有转速同步
SEN_STATE_READERROR,
SEN_IVLSTATE_ERROR,
SEN_STATE_MAX
} sen_state_t;
typedef struct
{
// sen_state_t tostate;
sen_state_t state;
bool bmotor;
uint32_t addr;
bool available;
uint32_t u32SensorStateErrCnt;
uint32_t errRestartTick;
uint32_t errLastUpdateTick;
}sensorFSM_t;
void sensorInit(void);
void sensorProcess(void);
sen_state_t sensorStateGet(unsigned int idx);
bool sensorAvailableGet(uint32_t idx);
void sensorAvailableSet(uint32_t idx, bool state);
uint32_t sensorsAvailableStateGet(void);
void sensorsAvailableStateSet(uint32_t available);
#endif
/**
* @file WIT2FSM.h
* @author your name (you@domain.com)
* @brief
* @version 0.1
* @date 2022-09-05
*
* @copyright Copyright (c) 2022
*
*/
#ifndef __WIT2FSM_H
#define __WIT2FSM_H
#include "stdint.h"
#include "stdbool.h"
#include "GatewayFSM.h"
bool WIT2FSM_SensorStateGet(uint32_t addr, uint16_t *state);
bool WIT2FSM_SendError(void);
bool WIT2FSM_SendAmlVibAlarm(void);
bool WIT2FSM_SendHeartToServer(unsigned char groupId);
bool WIT2FSM_SendGatewayFeatureToServer(unsigned char groupId);
bool WIT2FSM_SendSensorFeatureToServer(unsigned char groupId, unsigned char ucSensorAddr);
bool WIT2FSM_SendWaveToServer(unsigned char groupId, unsigned char ucSensorAddr);
void WIT2FSM_MQTTPubHandler(bool bStatus);
bool WIT2FSM_DeviceRunCheck(void);
bool WIT2FSM_NeedSend(void);
bool WIT2FSM_StartCollect(void);
bool WIT2FSM_MotorSpeedSync(speedSyncFSM *fsm);
bool WIT2FSM_ClearVarible(void);
bool WIT2FSM_AmlVibCheck(void);
bool WIT2FSM_PT100Read(void);
bool WIT2FSM_MqttPub(unsigned char * s);
bool WIT2FSM_GetSpdSyncConfig(void);
#endif
#include "debugFSM.h"
#include "stdbool.h"
#include "WIT2FSM.h"
#include "GatewayFSM.h"
#include "SensorFSM.h"
#include "string.h"
#include "stdio.h"
void debugFSMProcess(unsigned int *cmd)
{
switch (*cmd)
{
case 1:
{
char s[256] = {0};
gw_state_t state = xGatewayFSMStateGet();
sen_state_t senStates[6] = {SEN_STATE_MAX};
for (size_t i = 0; i < 6; i++)
{
senStates[i] = sensorStateGet(i);
}
sprintf(s, "{\"g1\":%d,\"s1\":%d,\"s2\":%d,\"s3\":%d,\"s4\":%d,\"s5\":%d,\"s6\":%d,\"f1\":%d,\"f2\":%d,\"f3\":%d,\"f4\":%d,\"f5\":%d,\"f6\":%d}", state,
senStates[0], senStates[1], senStates[2], senStates[3], senStates[4], senStates[5],
g_bFlagGwFeat, g_bFlagSenFeat, g_bFlagSenWave, g_bCanSendGatewayFeature, g_bCanSendSensorFeature, g_bCanSendWave);
WIT2FSM_MqttPub((unsigned char *)s);
*cmd = 0xff;
}
break;
default:
break;
}
}
/**
* @file debugFSM.h
* @author your name (you@domain.com)
* @brief
* @version 0.1
* @date 2022-09-29
*
* @copyright Copyright (c) 2022
*
*/
#ifndef DEBUGFSM_H
#define DEBUGFSM_H
#include "wit.h"
extern bool g_bFlagGwFeat;
extern bool g_bFlagSenFeat;
extern bool g_bFlagSenWave;
extern bool g_bCanSendGatewayFeature;
extern bool g_bCanSendSensorFeature;
extern bool g_bCanSendWave;
void debugFSMProcess(unsigned int *cmd);
#endif
This diff is collapsed.
#ifndef ALGORITHM_H
#define ALGORITHM_H
/* Includes ------------------------------------------------------------------*/
#include <math.h>
/* Exported macros -----------------------------------------------------------*/
//外部内存空间加速计算,减少外部读取写入的次数 需要额外ACCELERATE_BUFFER_SIZE * 2 * sizeof(Complex)的空间,以空间换时间
#define ALGORITHM_EXT_MEMORY_ACCELERATE 0
#define ACCELERATE_BUFFER_SIZE 1024
//返回数据结果
#define ALGORITHM_RESULT_TYPE float
//处理数据类型
#define ALGORITHM_HANDLE_TYPE float
//一些常用数学定义
#define ALGORITHM_PI 3.141592f
#define ALGORITHM_G 9.80665f
/* Exported types ------------------------------------------------------------*/
typedef struct
{
float fReal;
float fImage;
} Complex;
/* Exported functions --------------------------------------------------------*/
ALGORITHM_RESULT_TYPE Mean(ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress);
ALGORITHM_RESULT_TYPE RMS(ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress);
ALGORITHM_RESULT_TYPE Std(ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress);
ALGORITHM_RESULT_TYPE Var(ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress);
ALGORITHM_RESULT_TYPE Max(ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress);
ALGORITHM_RESULT_TYPE Min(ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress);
ALGORITHM_RESULT_TYPE Kurtosis(ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress);
//ALGORITHM_RESULT_TYPE DFT(ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize, ALGORITHM_HANDLE_TYPE *pxOut,
// void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress,
// void (*pFuncWriteData)(unsigned long, unsigned char *, unsigned long), unsigned long ulWriteAddress);
//ALGORITHM_RESULT_TYPE DFT_GetOnePoint(unsigned long k, ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize,
// void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress);
ALGORITHM_RESULT_TYPE RFFT(ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize, Complex *pxOut,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress,
void (*pFuncWriteData)(unsigned long, unsigned char *, unsigned long), unsigned long ulWriteAddress);
ALGORITHM_RESULT_TYPE IFFT(Complex *pxData, unsigned long ulSize, ALGORITHM_HANDLE_TYPE *pxOut,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress,
void (*pFuncWriteData)(unsigned long, unsigned char *, unsigned long), unsigned long ulWriteAddress);
ALGORITHM_RESULT_TYPE GetMaxComplexInFreqRange(Complex *pxFFTResult, unsigned long ulSize, unsigned long ulSamplingRate, float fFrequency, float fRange,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress);
ALGORITHM_RESULT_TYPE VRMS(Complex *pxFFTResult, unsigned long ulSize, unsigned long ulSamplingRate,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress);
ALGORITHM_RESULT_TYPE HighFrequencyRMS(Complex *pxFFTResult, unsigned long ulSize, unsigned long ulSamplingRate, float *pxIFFTWave,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress,
void (*pFuncWriteData)(unsigned long, unsigned char *, unsigned long), unsigned long ulWriteAddress);
ALGORITHM_RESULT_TYPE Add(ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize, ALGORITHM_HANDLE_TYPE xOffset,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress,
void (*pFuncWriteData)(unsigned long, unsigned char *, unsigned long), unsigned long ulWriteAddress);
ALGORITHM_RESULT_TYPE CalculateAdaptiveThreshold(ALGORITHM_HANDLE_TYPE *pxData, unsigned long ulSize,
ALGORITHM_HANDLE_TYPE *pxHighLimit, ALGORITHM_HANDLE_TYPE *pxLowLimit,
void (*pFuncReadData)(unsigned long, unsigned char *, unsigned long), unsigned long ulReadAddress, float fScale);
ALGORITHM_RESULT_TYPE Complex_Cal(Complex *pxComplex);
Complex Complex_Add(Complex *pxOp1, Complex *pxOp2);
Complex Complex_Sub(Complex *pxOp1, Complex *pxOp2);
Complex Complex_Mul(Complex *pxOp1, Complex *pxOp2);
#endif
This diff is collapsed.
#ifndef __BLE_CLIENT__H__
#define __BLE_CLIENT__H__
#include "nvs_flash.h"
#include "stdbool.h"
/* BLE */
#include "nimble/nimble_port.h"
#include "nimble/nimble_port_freertos.h"
#include "freertos/semphr.h"
#include "host/ble_hs.h"
#include "host/util/util.h"
#include "console/console.h"
#include "services/gap/ble_svc_gap.h"
#include "modlog/modlog.h"
#include "blecent.h"
#include "sdkconfig.h"
#include "wcp.h"
#include "wit.h"
#define WIT_COMPLETE_FUN_CODE 0x0000
typedef struct {
uint16_t addr;
uint16_t group;
uint16_t handle;
bool bIsFind;
bool bIsConnect;
bool bDeliveries;
struct peer *peer;
const struct peer_chr *sensor_chr;
unsigned int gtms;
unsigned long ulVirAddr;
signed char rssi;
char senCode;
char cComplete;
} sDevInfo;
typedef struct {
sDevInfo xDevInfo[WIT_SENSOR_MAX_CONNECT_NUM * WIT_SENSOR_GROUP_MAX_NUM];
unsigned long ulConnnectBit;
} sSenInfo;
typedef enum {
OPERATE_INDICATE = 0,
OPEN_CONNECT
} action_class;
#define BLE_DEBUG_ENABLE 1
bool ble_client_init(void);
void ble_clear_dev_info(void);
void ble_clear_info_from_index(int index);
sDevInfo* ble_find_dev_from_addr(unsigned short usAddr);
sDevInfo* ble_find_dev_from_group(unsigned short usGroup);
unsigned long getBLEConnectNum(void);
bool ble_sensor_write(int index, void *buf, size_t len);
bool ble_sensor_indicate(int index, void *buf, size_t len);
bool send_update_bin(int index);
void ble_set_CheckTime(bool status);
void ble_clear_dev_complete(void);
#endif
/* Includes ------------------------------------------------------------------*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
#include <stdbool.h>
/* Private macros ------------------------------------------------------------*/
#define COMMON_YEAR_SECONDS 31536000 //平年秒数
#define LEAP_YEAR_SECONDS 31622400 //闰年秒数
#define ONE_DAY_SECONDS 86400 //一天的秒数
#define ONE_HOUR_SECONDS 3600 //一小时秒数
#define ONE_MINUTE_SECONDS 60 //一分钟秒数
#define COMMON_YEAR_DAY 365 //平年天数
#define LEAP_YEAR_DAY 366 //闰年天数
#define COMMON_2MONTH_DAY 28 //平年2月天数
#define LEAP_2MONTH_DAY 29 //闰年2月天数
#define SINCE1970 1970
/* Private variables ---------------------------------------------------------*/
static unsigned char g_ucDayOfMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/* Private functions ---------------------------------------------------------*/
static bool IsLeapYear(unsigned short usYear);
/**
* @brief Delay us
* @param dTime_us: t us
* @retval None
*/
void Delay_us(double dTime_us)
{
volatile unsigned long tmpCounter = dTime_us * 10;
while (tmpCounter)
{
tmpCounter--;
}
}
/**
* @brief Delay ms
* @param ulTime_ms: t ms
* @retval None
*/
void Delay_ms(double dTime_ms)
{
Delay_us(dTime_ms * 1000);
}
/**
* @brief Delay s
* @param ulTime_s: t s
* @retval None
*/
void Delay_s(double dTime_s)
{
Delay_ms(dTime_s * 1000);
}
/**
* @brief Split data
* @param
* @retval
*/
void Split(char *pcSplitedData[], unsigned char ucSplitedArraySize, char *pcSource, char *pcSymbol)
{
char *pcPointer = pcSource;
char *pcTemp = NULL;
unsigned char ucIndex = 0;
if (pcSplitedData == NULL || pcSource == NULL || pcSymbol == NULL)
return;
while (true)
{
if ((pcTemp = strstr(pcPointer, pcSymbol)) == NULL)
{
pcSplitedData[ucIndex++] = pcPointer;
break;
}
else
{
memset(pcTemp, 0, strlen(pcSymbol));
pcSplitedData[ucIndex++] = pcPointer;
pcPointer = pcTemp + strlen(pcSymbol);
}
if (ucIndex >= ucSplitedArraySize)
break;
}
}
/**
* @brief Cut string
* @param
* @retval None
*/
void CutString(char *pcDestination, unsigned long ulDestinationSize, char *pcSource, char *pcStart, char *pcEnd)
{
char *pcS, *pcE;
if (pcSource == NULL || pcStart == NULL || pcEnd == NULL)
return;
pcS = strstr(pcSource, pcStart);
pcE = strstr(pcS, pcEnd);
if (pcS && pcE)
{
if (pcE - pcS < ulDestinationSize)
{
unsigned long ulSize = pcE - pcS;
if (pcDestination != NULL)
{
memcpy(pcDestination, pcS, ulSize);
pcDestination[ulSize] = '\0';
}
}
}
}
/**
* @brief Time to time stamp since 1970
* @param
* @retval None
*/
unsigned long TimeToTimeStamp(Calendar *pxCalendar)
{
unsigned char ucCurrentMonth;
unsigned short usCurrentYear;
unsigned long ulTimeStamp = 0;
if (pxCalendar == NULL)
return 0;
//从1970年到今年的秒数
for (usCurrentYear = SINCE1970; usCurrentYear < pxCalendar->usYear; usCurrentYear++)
{
if (IsLeapYear(usCurrentYear))
{
ulTimeStamp += LEAP_YEAR_SECONDS;
}
else
{
ulTimeStamp += COMMON_YEAR_SECONDS;
}
}
//到当月的秒数
for (ucCurrentMonth = 1; ucCurrentMonth < pxCalendar->ucMonth; ucCurrentMonth++)
{
ulTimeStamp += g_ucDayOfMonth[ucCurrentMonth] * ONE_DAY_SECONDS;
if (ucCurrentMonth == 2 && IsLeapYear(usCurrentYear))
{
ulTimeStamp += ONE_DAY_SECONDS;
}
}
//到当日的秒数
if (pxCalendar->ucDay > 0)
ulTimeStamp += (pxCalendar->ucDay - 1) * ONE_DAY_SECONDS;
//到当时的秒数
ulTimeStamp += pxCalendar->ucHour * ONE_HOUR_SECONDS;
ulTimeStamp += pxCalendar->ucMinute * ONE_MINUTE_SECONDS;
ulTimeStamp += pxCalendar->ucSecond;
return ulTimeStamp;
}
/**
* @brief Time stamp to time
* @param
* @retval None
*/
void TimeStampToTime(unsigned long ulTimeStamp, Calendar *pxCalendar)
{
unsigned long ulTotalDay = ulTimeStamp / ONE_DAY_SECONDS;
unsigned long ulDaySeconds = ulTimeStamp % ONE_DAY_SECONDS;
unsigned short usCurrentYear = 1970;
unsigned char ucCurrentMonth = 1;
if (pxCalendar == NULL)
return;
//根据天数推算出现在是哪一年
while (ulTotalDay >= COMMON_YEAR_DAY)
{
if (IsLeapYear(usCurrentYear))
{
if (ulTotalDay >= LEAP_YEAR_DAY)
{
ulTotalDay -= LEAP_YEAR_DAY;
}
else
{
break;
}
}
else
{
ulTotalDay -= COMMON_YEAR_DAY;
}
usCurrentYear++;
}
//根据剩余天数推算出现在是哪一月
while (ulTotalDay >= COMMON_2MONTH_DAY)
{
if (IsLeapYear(usCurrentYear) && ucCurrentMonth == 2)
{
if (ulTotalDay >= LEAP_2MONTH_DAY)
{
ulTotalDay -= LEAP_2MONTH_DAY;
}
else
{
break;
}
}
else
{
if (ulTotalDay >= g_ucDayOfMonth[ucCurrentMonth])
{
ulTotalDay -= g_ucDayOfMonth[ucCurrentMonth];
}
else
{
break;
}
}
ucCurrentMonth++;
}
pxCalendar->usYear = usCurrentYear;
pxCalendar->ucMonth = ucCurrentMonth;
pxCalendar->ucDay = ulTotalDay + 1;
pxCalendar->ucHour = ulDaySeconds / ONE_HOUR_SECONDS;
pxCalendar->ucMinute = (ulDaySeconds % ONE_HOUR_SECONDS) / ONE_MINUTE_SECONDS;
pxCalendar->ucSecond = (ulDaySeconds % ONE_HOUR_SECONDS) % ONE_MINUTE_SECONDS;
}
/**
* @brief Byte to BCD
* @param
* @retval None
*/
unsigned char ByteToBCD(unsigned char ucByte)
{
unsigned long ulBCDHigh = 0;
while (ucByte >= 10)
{
ulBCDHigh++;
ucByte -= 10;
}
return ((unsigned char)(ulBCDHigh << 4) | ucByte);
}
/**
* @brief BCD to byte
* @param
* @retval None
*/
unsigned char BCDToByte(unsigned char ucBCD)
{
unsigned long ulTmp = 0;
ulTmp = ((unsigned char)(ucBCD & (unsigned char)0xF0) >> (unsigned char)0x4) * 10;
return (ulTmp + (ucBCD & (unsigned char)0x0F));
}
/**
* @brief is leap year?
* @param
* @retval true / false
*/
static bool IsLeapYear(unsigned short usYear)
{
if ((usYear % 4 == 0 && usYear % 100 != 0) || (usYear % 400 == 0))
{
return true; //是闰年
}
else
{
return false; //不是闰年
}
}
/**
* @brief get flag
* @param
* @retval true / false
*/
bool GetFlagStatus(unsigned long *pulFlag, unsigned char ucBitPosition)
{
if (pulFlag != NULL)
return (bool)(*pulFlag & (1 << ucBitPosition)) > 0 ? true : false;
return false;
}
/**
* @brief set flag
* @param
* @retval None
*/
void SetFlagStatus(unsigned long *pulFlag, unsigned char ucBitPosition, bool bStatus)
{
if (pulFlag != NULL)
*pulFlag |= (bStatus << ucBitPosition);
}
/**
* @brief find string in memory
* @param
* @retval None
*/
char *memstr(void *pvSrc, char *pcStr, unsigned long ulLength)
{
char *pcSource = NULL;
char *pcResult = NULL;
unsigned long ulHandlerLength = 0;
unsigned long ulCurLength = 0;
if (pvSrc == NULL || pcStr == NULL)
return NULL;
pcSource = (char *)pvSrc;
while (ulHandlerLength < ulLength)
{
if ((pcResult = strstr(pcSource, pcStr)) != NULL)
break;
ulCurLength = strlen(pcSource);
ulHandlerLength += ulCurLength == 0 ? 1 : ulCurLength;
pcSource += ulCurLength == 0 ? 1 : ulCurLength;
}
return pcResult;
}
/* @brief replace specific string
* @param
* @retval None
*/
bool Replace(char *pcOrigin, char *pcSearch, char *pcReplace, char *pcDest, unsigned long ulMaxLength)
{
char *pcHead = pcOrigin;
char *pcTail = pcOrigin;
unsigned long ulCurrentLen = 0;
if (pcOrigin == NULL || pcSearch == NULL || pcReplace == NULL || pcDest == NULL)
return false;
memset(pcDest, 0, ulMaxLength);
while ((pcTail = strstr(pcHead, pcSearch)) != NULL)
{
ulCurrentLen += (pcTail - pcHead) + strlen(pcReplace);
if (ulCurrentLen >= ulMaxLength)
return false;
strncat(pcDest, pcHead, pcTail - pcHead);
strcat(pcDest, pcReplace);
pcHead = pcTail + strlen(pcSearch);
}
ulCurrentLen += strlen(pcHead);
if (ulCurrentLen >= ulMaxLength)
return false;
strcat(pcDest, pcHead);
return true;
}
/** @brief Fixed decimal size
* @param
* @retval double type value
*/
double Round(double dValue, unsigned char ucPrecision)
{
char cFormat[8] = "";
char cDoubleValue[20] = "";
sprintf(cFormat, "%%.%dlf", ucPrecision);
sprintf(cDoubleValue, cFormat, dValue);
dValue = atof(cDoubleValue);
return dValue;
}
#ifndef COMMON_H
#define COMMON_H
/* Exported macros -----------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
#include "stdbool.h"
#include "wit_config.h"
#include "update_config.h"
typedef struct
{
unsigned short usYear;
unsigned char ucMonth;
unsigned char ucDay;
unsigned char ucHour;
unsigned char ucMinute;
unsigned char ucSecond;
} Calendar;
/* Exported functions --------------------------------------------------------*/
void Delay_us(double dTime_us);
void Delay_ms(double dTime_ms);
void Delay_s(double dTime_s);
void Split(char *pcSplitedData[], unsigned char ucSplitedArraySize, char *pcSource, char *pcSymbol);
void CutString(char *pcDestination, unsigned long ulDestinationSize, char *pcSource, char *pcStart, char *pcEnd);
unsigned long TimeToTimeStamp(Calendar *pxCalendar);
void TimeStampToTime(unsigned long ulTimeStamp, Calendar *pxCalendar);
unsigned char ByteToBCD(unsigned char ucByte);
unsigned char BCDToByte(unsigned char ucBCD);
bool GetFlagStatus(unsigned long *pulFlag, unsigned char ucBitPosition);
void SetFlagStatus(unsigned long *pulFlag, unsigned char ucBitPosition, bool bStatus);
char * memstr(void *pvSrc, char *pcStr, unsigned long ulLength);
bool Replace(char *pcOrigin, char *pcSearch, char *pcReplace, char *pcDest, unsigned long ulMaxLength);
double Round(double dValue, unsigned char ucPrecision);
#endif
This diff is collapsed.
#ifndef __IF_BLE_CONFIG__H__
#define __IF_BLE_CONFIG__H__
#include "wcp.h"
#include "acc.h"
#define RETARY_CNT 1
#define WIT_SENSOR_GROUP_MAX_NUM 8
#define SENSOR_MAX_FREQ_X 10
#define SENSOR_BEARING_LOGITIC_MAX_SIZE 12
#define SENSOR_GEAR_LOGITIC_MAX_SIZE 6
#define SENSOR_WAVE_MAX_SIZE (16 * 1024)
//轴承最大数量
#define SENSOR_BEARING_MAX_COUNT 2
//齿轮最大数量
#define SENSOR_GEAR_MAX_COUNT 3
#define SENSOR_PARTS_MAX_NUM 10
// define
#define BEARING_CONFIG_VAR(type, name, n) \
type name[n]; \
type name##Reserved[SENSOR_BEARING_LOGITIC_MAX_SIZE - n]
#define GEAR_CONFIG_VAR(type, name, n) \
type name[n]; \
type name##Reserved[SENSOR_GEAR_LOGITIC_MAX_SIZE - n]
typedef enum
{
Status_Idle = 0, //空闲
Status_Collecting = 1, //采集中
Status_Completed = 2, //采集完成
Status_Error = 3, //采集失败
} Sensor_Status;
/* Type defines --------------------------------------------------------------*/
typedef enum
{
Mode_Passive = 0, //被动模式
Mode_Auto = 1, //自动模式
} Sensor_Mode;
typedef struct
{
float fPassFrequency;
bool bEnable; //是否启用
unsigned short usAlias; //别名
} PwrFreq;
typedef struct
{
/* Base Config */
unsigned long ulAddr;
unsigned long ulSpeed;
unsigned short usPolePairs;
unsigned short usSamplingCount;
unsigned short usAutoModeSamplingPeriod;
short sXOffset;
short sYOffset;
short sZOffset;
unsigned long ulSerialNumber;
unsigned long ulConfigNumber;
/* Component Config */
bool bSetSpeed;
// bearing enabled status (兼容12轴承 6齿轮版本)
BEARING_CONFIG_VAR(bool, bBearingEnabled, SENSOR_BEARING_MAX_COUNT);
// gear enabled status
GEAR_CONFIG_VAR(bool, bGearEnabled, SENSOR_GEAR_MAX_COUNT);
// bearing config parm
BEARING_CONFIG_VAR(Bearing, xBearing, SENSOR_BEARING_MAX_COUNT);
// gear config parm
GEAR_CONFIG_VAR(Gear, xGear, SENSOR_GEAR_MAX_COUNT);
unsigned long ulComponentConfigNumber;
/* Parm1 Config */
bool bAutoDeleteGravity;
unsigned long ulFrequencyRange;
unsigned long ulParmConfigNumber;
/* Parm2 Config */
Sensor_Mode eMode;
bool bCalculateFeature;
unsigned long ulParm2ConfigNumber;
/* Active Config */
unsigned short usActiveThreshold;
unsigned short usActiveRatio;
unsigned long ulActiveParmConfigNumber;
/* Extend Config */
// bearing extend enabled status (2轴承 3齿轮)
bool bBearingExtendEnable[SENSOR_BEARING_MAX_COUNT];
// gear extend enabled status
bool bGearExtendEnable[SENSOR_GEAR_MAX_COUNT];
Base_ExtendConfig xBaseExtendConfig;
// bearing extend config
Bearing_ExtendConfig xBearingExtendConfig[SENSOR_BEARING_MAX_COUNT];
// gear extend config
Gear_ExtendConfig xGearExtendConfig[SENSOR_GEAR_MAX_COUNT];
unsigned long ulExtendParmConfigNumber;
bool bFanEnable;
bool bBeltEnable;
Fan xFan;
Belt xBelt;
unsigned long ulFanAndBeltConfigNumber;
unsigned short usFanAlias;
unsigned short usBeltAlias;
unsigned long ulFanAndBeltAliasConfigNumber;
bool bScrewEnable;
Screw xScrew;
unsigned short usScrewAlias;
unsigned long ulScrewConfigNumber;
unsigned long ulScrewAliasConfigNumber;
bool bMaleScrewEnable;
MaleScrew xMaleScrew;
unsigned short usMaleScrewAlias;
unsigned long ulMaleScrewConfigNumber;
unsigned long ulMaleScrewAliasConfigNumber;
bool bFemaleScrewEnable;
FemaleScrew xFemaleScrew;
unsigned short usFemaleScrewAlias;
unsigned long ulFemaleScrewConfigNumber;
unsigned long ulFemaleScrewAliasConfigNumber;
bool bShaftEnable;
Shaft xShaft;
unsigned short usShaftAlias;
unsigned long ulShaftConfigNumber;
unsigned long ulShaftAliasConfigNumber;
unsigned int odr;
unsigned int amlVibTh;
unsigned int amlVibInterval;
unsigned int amlVibKeepCnt;
unsigned int highTempProtect;
unsigned long v2_20ConfigNumber;
unsigned int vRMSMode;
bool bSleeveEnable;
Sleeve xSleeve;
unsigned short usSleeveAlias;
unsigned long ulSleeveConfigNumber;
unsigned long ulSleeveAliasConfigNumber;
PwrFreq xPwrFreq;
unsigned long ulPowerFrequencyConfigNumber;
unsigned short usxVar;
} Sensor_Config;
void if_sensor_config_init(void);
bool if_sensor_config(unsigned int index, unsigned char point, unsigned long *ulConfigEnable);
Sensor_Config *getSensorConfig(unsigned char index);
void if_clear_config_flag(unsigned char index);
void if_falsh_write_config(void);
void if_falsh_read_config(void);
bool if_synchronize_time(unsigned int index, unsigned long ulSyncTime, bool bCheck);
bool if_set_collect_time(unsigned int index, unsigned long ulConnectTime, bool bCheck);
bool if_set_wakeup_time(unsigned int index, unsigned long ulWakeUpTime, unsigned long ulWakeUpInterval, bool bCheck);
void if_check_change_config(void);
void if_printf(void);
#endif
This diff is collapsed.
#ifndef __IF_GW__H__
#define __IF_GW__H__
#include <stdbool.h>
typedef enum {
IDLE_STATUS = 0,
COLLECT_STATUS,
COMPLETE_STATUS
} sGwStatus;
void if_gataway_process(void);
bool if_check_wakeup_time(unsigned short group, unsigned short addr, unsigned short index);
void if_set_gw_status(sGwStatus xGwStatus);
void if_calibration_time(unsigned long ulLasttime);
#endif
#include <stdio.h>
#include "loopback.h"
#include "socket.h"
#include "wizchip_conf.h"
#if LOOPBACK_MODE == LOOPBACK_MAIN_NOBLCOK
int32_t loopback_tcps(uint8_t sn, uint8_t* buf, uint16_t port)
{
int32_t ret;
uint16_t size = 0, sentsize=0;
#ifdef _LOOPBACK_DEBUG_
uint8_t destip[4];
uint16_t destport;
#endif
switch(getSn_SR(sn))
{
case SOCK_ESTABLISHED :
if(getSn_IR(sn) & Sn_IR_CON)
{
#ifdef _LOOPBACK_DEBUG_
getSn_DIPR(sn, destip);
destport = getSn_DPORT(sn);
printf("%d:Connected - %d.%d.%d.%d : %d\r\n",sn, destip[0], destip[1], destip[2], destip[3], destport);
#endif
setSn_IR(sn,Sn_IR_CON);
}
if((size = getSn_RX_RSR(sn)) > 0) // Don't need to check SOCKERR_BUSY because it doesn't not occur.
{
if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
ret = recv(sn, buf, size);
if(ret <= 0) return ret; // check SOCKERR_BUSY & SOCKERR_XXX. For showing the occurrence of SOCKERR_BUSY.
size = (uint16_t) ret;
sentsize = 0;
while(size != sentsize)
{
ret = send(sn, buf+sentsize, size-sentsize);
if(ret < 0)
{
close(sn);
return ret;
}
sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
}
}
break;
case SOCK_CLOSE_WAIT :
#ifdef _LOOPBACK_DEBUG_
//printf("%d:CloseWait\r\n",sn);
#endif
if((ret = disconnect(sn)) != SOCK_OK) return ret;
#ifdef _LOOPBACK_DEBUG_
printf("%d:Socket Closed\r\n", sn);
#endif
break;
case SOCK_INIT :
#ifdef _LOOPBACK_DEBUG_
printf("%d:Listen, TCP server loopback, port [%d]\r\n", sn, port);
#endif
if( (ret = listen(sn)) != SOCK_OK) return ret;
break;
case SOCK_CLOSED:
#ifdef _LOOPBACK_DEBUG_
//printf("%d:TCP server loopback start\r\n",sn);
#endif
if((ret = my_socket(sn, Sn_MR_TCP, port, 0x00)) != sn) return ret;
#ifdef _LOOPBACK_DEBUG_
//printf("%d:Socket opened\r\n",sn);
#endif
break;
default:
break;
}
return 1;
}
int32_t loopback_tcpc(uint8_t sn, uint8_t* buf, uint8_t* destip, uint16_t destport)
{
int32_t ret; // return value for SOCK_ERRORs
uint16_t size = 0, sentsize=0;
// Destination (TCP Server) IP info (will be connected)
// >> loopback_tcpc() function parameter
// >> Ex)
// uint8_t destip[4] = {192, 168, 0, 214};
// uint16_t destport = 5000;
// Port number for TCP client (will be increased)
static uint16_t any_port = 50000;
// Socket Status Transitions
// Check the W5500 Socket n status register (Sn_SR, The 'Sn_SR' controlled by Sn_CR command or Packet send/recv status)
switch(getSn_SR(sn))
{
case SOCK_ESTABLISHED :
if(getSn_IR(sn) & Sn_IR_CON) // Socket n interrupt register mask; TCP CON interrupt = connection with peer is successful
{
#ifdef _LOOPBACK_DEBUG_
printf("%d:Connected to - %d.%d.%d.%d : %d\r\n",sn, destip[0], destip[1], destip[2], destip[3], destport);
#endif
setSn_IR(sn, Sn_IR_CON); // this interrupt should be write the bit cleared to '1'
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Data Transaction Parts; Handle the [data receive and send] process
//////////////////////////////////////////////////////////////////////////////////////////////
if((size = getSn_RX_RSR(sn)) > 0) // Sn_RX_RSR: Socket n Received Size Register, Receiving data length
{
if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE; // DATA_BUF_SIZE means user defined buffer size (array)
ret = recv(sn, buf, size); // Data Receive process (H/W Rx socket buffer -> User's buffer)
if(ret <= 0) return ret; // If the received data length <= 0, receive failed and process end
size = (uint16_t) ret;
sentsize = 0;
// Data sentsize control
while(size != sentsize)
{
ret = send(sn, buf+sentsize, size-sentsize); // Data send process (User's buffer -> Destination through H/W Tx socket buffer)
if(ret < 0) // Send Error occurred (sent data length < 0)
{
close(sn); // socket close
return ret;
}
sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
break;
case SOCK_CLOSE_WAIT :
#ifdef _LOOPBACK_DEBUG_
//printf("%d:CloseWait\r\n",sn);
#endif
if((ret=disconnect(sn)) != SOCK_OK) return ret;
#ifdef _LOOPBACK_DEBUG_
printf("%d:Socket Closed\r\n", sn);
#endif
break;
case SOCK_INIT :
#ifdef _LOOPBACK_DEBUG_
printf("%d:Try to connect to the %d.%d.%d.%d : %d\r\n", sn, destip[0], destip[1], destip[2], destip[3], destport);
#endif
if( (ret = connect(sn, destip, destport)) != SOCK_OK) return ret; // Try to TCP connect to the TCP server (destination)
break;
case SOCK_CLOSED:
close(sn);
if((ret=my_socket(sn, Sn_MR_TCP, any_port++, 0x00)) != sn){
if(any_port == 0xffff) any_port = 50000;
return ret; // TCP socket open with 'any_port' port number
}
#ifdef _LOOPBACK_DEBUG_
//printf("%d:TCP client loopback start\r\n",sn);
//printf("%d:Socket opened\r\n",sn);
#endif
break;
default:
break;
}
return 1;
}
int32_t loopback_udps(uint8_t sn, uint8_t* buf, uint16_t port)
{
int32_t ret;
uint16_t size, sentsize;
uint8_t destip[4];
uint16_t destport;
switch(getSn_SR(sn))
{
case SOCK_UDP :
if((size = getSn_RX_RSR(sn)) > 0)
{
if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
ret = recvfrom(sn, buf, size, destip, (uint16_t*)&destport);
if(ret <= 0)
{
return ret;
}
size = (uint16_t) ret;
sentsize = 0;
while(sentsize != size)
{
ret = sendto(sn, buf+sentsize, size-sentsize, destip, destport);
if(ret < 0)
{
return ret;
}
sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
}
}
break;
case SOCK_CLOSED:
#ifdef _LOOPBACK_DEBUG_
//printf("%d:UDP loopback start\r\n",sn);
#endif
if((ret = my_socket(sn, Sn_MR_UDP, port, 0x00)) != sn)
return ret;
#ifdef _LOOPBACK_DEBUG_
printf("%d:Opened, UDP loopback, port [%d]\r\n", sn, port);
#endif
break;
default :
break;
}
return 1;
}
#endif
#ifndef _LOOPBACK_H_
#define _LOOPBACK_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
/* Loopback test debug message printout enable */
#define _LOOPBACK_DEBUG_ 1
/* DATA_BUF_SIZE define for Loopback example */
#ifndef DATA_BUF_SIZE
#define DATA_BUF_SIZE 2048
#endif
/************************/
/* Select LOOPBACK_MODE */
/************************/
#define LOOPBACK_MAIN_NOBLOCK 0
#define LOOPBACK_MODE LOOPBACK_MAIN_NOBLOCK
/* TCP server Loopback test example */
int32_t loopback_tcps(uint8_t sn, uint8_t* buf, uint16_t port);
/* TCP client Loopback test example */
int32_t loopback_tcpc(uint8_t sn, uint8_t* buf, uint8_t* destip, uint16_t destport);
/* UDP Loopback test example */
int32_t loopback_udps(uint8_t sn, uint8_t* buf, uint16_t port);
#ifdef __cplusplus
}
#endif
#endif
#include "multicast.h"
#include <stdio.h>
#include "socket.h"
#include "wizchip_conf.h"
int32_t multicast_loopback(uint8_t sn, uint8_t* buf, uint8_t* multicast_ip, uint16_t multicast_port)
{
int32_t ret;
uint16_t size, sentsize;
uint8_t destip[4];
uint16_t destport, port=3000;
switch(getSn_SR(sn))
{
case SOCK_UDP :
if((size = getSn_RX_RSR(sn)) > 0)
{
if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
ret = recvfrom(sn, buf, size, destip, (uint16_t*)&destport);
if(ret <= 0)
{
return ret;
}
size = (uint16_t) ret;
sentsize = 0;
while(sentsize != size)
{
ret = sendto(sn, buf+sentsize, size-sentsize, destip, destport);
if(ret < 0)
{
return ret;
}
sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
}
}
break;
case SOCK_CLOSED:
setSn_DIPR(0, multicast_ip);
setSn_DPORT(0, multicast_port);
if((ret = my_socket(sn, Sn_MR_UDP, port, Sn_MR_MULTI)) != sn)
return ret;
break;
default :
break;
}
return 1;
}
int32_t multicast_recv(uint8_t sn, uint8_t* buf, uint8_t* multicast_ip, uint16_t multicast_port)
{
int32_t ret;
uint16_t size, port=3000;
uint8_t destip[4];
uint16_t destport;
switch(getSn_SR(sn))
{
case SOCK_UDP :
if((size = getSn_RX_RSR(sn)) > 0)
{
if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
ret = recvfrom(sn, buf, size, destip, (uint16_t*)&destport);
if(ret <= 0)
{
return ret;
}
size = (uint16_t) ret;
#ifdef _MULTICAST_DEBUG_
printf("\r\nrecv size : %d\r\n", size);
for(int i=0; i<size; i++)
printf("%c", buf[i]);
printf("\r\n");
#endif
}
break;
case SOCK_CLOSED:
setSn_DIPR(sn, multicast_ip);
setSn_DPORT(sn, multicast_port);
if((ret = my_socket(sn, Sn_MR_UDP, port, Sn_MR_MULTI)) != sn)
return ret;
#ifdef _MULTICAST_DEBUG_
printf("%d:Opened, UDP Multicast Socket\r\n", sn);
printf("%d:Multicast Group IP - %d.%d.%d.%d\r\n", sn, multicast_ip[0], multicast_ip[1], multicast_ip[2], multicast_ip[3]);
printf("%d:Multicast Group Port - %d\r\n", sn, multicast_port);
#endif
break;
default :
break;
}
return 1;
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment