second commit

This commit is contained in:
2025-02-20 13:19:16 +08:00
commit 09256a1972
52 changed files with 8016 additions and 0 deletions

57
src/CastumullSpline.cpp Normal file
View File

@ -0,0 +1,57 @@
float catmullSlope(float x[], float y[], int n, int i)
{
if (x[i + 1] == x[i - 1]) return 0;
return (y[i + 1] - y[i - 1]) / (x[i + 1] - x[i - 1]);
}
float CatmullSpline(float xValues[], float yValues[], int numValues, float pointX, bool trim)
{
if (trim)
{
if (pointX <= xValues[0]) return yValues[0];
if (pointX >= xValues[numValues - 1]) return yValues[numValues - 1];
}
auto i = 0;
if (pointX <= xValues[0]) i = 0;
else if (pointX >= xValues[numValues - 1]) i = numValues - 1;
else while (pointX >= xValues[i + 1]) i++;
if (pointX == xValues[i + 1]) return yValues[i + 1];
auto t = (pointX - xValues[i]) / (xValues[i + 1] - xValues[i]);
auto t_2 = t * t;
auto t_3 = t_2 * t;
auto h00 = 2 * t_3 - 3 * t_2 + 1;
auto h10 = t_3 - 2 * t_2 + t;
auto h01 = 3 * t_2 - 2 * t_3;
auto h11 = t_3 - t_2;
auto x0 = xValues[i];
auto x1 = xValues[i + 1];
auto y0 = yValues[i];
auto y1 = yValues[i + 1];
float m0;
float m1;
if (i == 0)
{
m0 = (yValues[1] - yValues[0]) / (xValues[1] - xValues[0]);
m1 = (yValues[2] - yValues[0]) / (xValues[2] - xValues[0]);
}
else if (i == numValues - 2)
{
m0 = (yValues[numValues - 1] - yValues[numValues - 3]) / (xValues[numValues - 1] - xValues[numValues - 3]);
m1 = (yValues[numValues - 1] - yValues[numValues - 2]) / (xValues[numValues - 1] - xValues[numValues - 2]);
}
else
{
m0 = catmullSlope(xValues, yValues, numValues, i);
m1 = catmullSlope(xValues, yValues, numValues, i + 1);
}
auto rst = h00 * y0 + h01 * y1 + h10 * (x1 - x0) * m0 + h11 * (x1 - x0) * m1;
return rst;
}

9
src/CastumullSpline.h Normal file
View File

@ -0,0 +1,9 @@
#ifndef CASTUMULLSPLINE_H
#define CASTUMULLSPLINE_H
#include <Arduino.h>
float CatmullSpline(float xValues[], float yValues[], int numValues, float pointX, bool trim = true);
#endif

View File

@ -0,0 +1,58 @@
#ifndef COMMUNICATION_PROTOCOL_H
#define COMMUNICATION_PROTOCOL_H
#include <stdint.h>
#include "IRIS_Method.h"
#include <Communication_struct.h>
// DEFINE The protocol Here
//Forexample
// #define MYCOMAN 0x02 //命令全大写
// todo : define your protocol here
/*-------------------------------------------------------------------------------------------------------------*/
// #define Digital_number 0
#define DIGITALNUMBER 0
#define RADIANCE 1
#define REFLECTANCE 2
#define DARKNOISE 3
#define DIRECTIO_UP 0
#define DIRECTION_DOWN 1
#define BANDNUMBER 2048
/// 加时间戳
struct IS11_datastruct
{
u_int8_t type = 0; // 0 DN 1 Radiance 2 重采样 3 Reflectance 4 gain 5 offset 6 fanshelv
u_int8_t direction = 0; //0 up 1 down 2 dark_up 3 dark_down
u_int8_t tuigan_stat =0;//0:伸 1:缩
u_int8_t year= 0;
u_int8_t month= 0;
u_int8_t day= 0;
u_int8_t hour= 0;
u_int8_t minute= 0;
u_int8_t second= 0;
u_int8_t NCa = 0; //手动对齐,方便解析。
u_int8_t NCb = 0;
u_int8_t NCc = 0;
u_int32_t shutter_time = 0;
u_int64_t index = 0; //在获取重采样值时这个表示有多少位数据
float temprature[8];
float data[BANDNUMBER];
};
struct clalidata_struct
{
uint32_t shutter;
float gain[BANDNUMBER];
float offset[BANDNUMBER];
};
/*-------------------------------------------------------------------------------------------------------------*/
/*
在此之下开始定义一些函数
*/
#endif

View File

@ -0,0 +1,33 @@
#ifndef COMMUNICATION_STRUCT_H
#define COMMUNICATION_STRUCT_H
// Define your communication structures here
// For example:
/*
如果发送和接受的数据结构一样,那么就定义一个结构体
struct MyComan_struct //对应的命令结构体 小驼峰命名法+struct
{
uint8_t Command;
uint16_t LenthofIn;
};
如果发送和接受的数据结构不一样,那么就分开定义
struct MyComan_Send_struct //对应的命令结构体 小驼峰命名法+Send_struct
{
uint8_t Command;
uint16_t LenthofIn;
};
struct MyComan_Recv_struct //对应的命令结构体 小驼峰命名法+Recv_struct
{
uint8_t Command;
uint16_t LenthofOut;
};
*/
#endif // COMMUNICATION_STRUCT_H

219
src/DS18B20.cpp Normal file
View File

@ -0,0 +1,219 @@
#include "DS18B20.h"
#include <log.h>
DeviceAddress sensor0 = { 0x28, 0x40, 0xB9, 0x2C ,0xF, 0x0, 0x0 ,0xEA };
DeviceAddress sensor1 = { 0x28, 0xB0, 0xBA, 0x2D ,0xF, 0x0, 0x0 ,0x59 };
DeviceAddress sensor2 = { 0x28, 0x8C ,0xDA ,0x2D, 0xF, 0x0 ,0x0, 0xD8 };
DeviceAddress sensor3 = { 0x28 ,0x4A ,0xD7, 0x2D, 0xF ,0x0 ,0x0 ,0x19 };
DeviceAddress sensor4 = { 0x28, 0x9E ,0xDA, 0x2D ,0xF, 0x0, 0x0, 0xED };
DeviceAddress sensor5 = { 0x28, 0xA9 ,0x0A ,0xFB, 0xD, 0x0, 0x0, 0x9C };
DeviceAddress sensor6 = { 0x28, 0x17 ,0xF6, 0x2C, 0xF ,0x0 ,0x0 ,0xC7 };
DeviceAddress sensor7 = { 0x28, 0xBF, 0x92, 0x2D ,0xF, 0x0, 0x0 ,0xBB };
DeviceAddress sensoraddr[8];
OneWire oneWire(DS18b20_pin);
DallasTemperature DS18b20(&oneWire);
int temp_number;
uint8_t *p[8] = {sensoraddr[0],sensoraddr[1],sensoraddr[2],sensoraddr[3],sensoraddr[4],sensoraddr[5],sensoraddr[6],sensoraddr[7]};
//冒泡排序 将温度地址 DeviceAddress sensoraddr[30]; 从小到大排序
void bubble_sort(DeviceAddress *addr,int n)
{
uint64_t a1 ,a2;
for (int i = 0; i < n; i++)
{
for(uint8_t b = 0 ; b<8;b++)
{
a1 += addr[i][b];
}
for (int j = 0; j < n-i-1; j++)
{
for(uint8_t c = 0 ; c<8;c++)
{
a2 += addr[j][c];
}
if (a1 > a2)
{
uint8_t *temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
}
uint8_t DS18b20_init()
{
//温度模块初始化
// DS18b20.setOneWire(&oneWire);
DS18b20.begin();
temp_number = DS18b20.getDeviceCount();
int i = 0;
while(temp_number <= 0 )
{
temp_number = DS18b20.getDeviceCount();
vTaskDelay(500);
if (i>=5)
{
write_log(log_path,"ds18b2 init failed,no ds18b20",10);
return 0;
}
i++;
}
write_log(log_path,"ds18b20 has" + String(temp_number),10);
for(size_t i = 0; i < temp_number; i++)
{
DS18b20.getAddress(sensoraddr[i],i);
}
bubble_sort(sensoraddr,temp_number);
return temp_number;
}
//温度监测
void getall_temp(float *temp)
{
DS18b20.requestTemperatures(); // Send the command to get temperatures
for(int8_t i ;i<temp_number;i++)
{
temp[i] = DS18b20.getTempC(p[i]);
// temp[i] = getone_temp(i);
}
// write_log(log_path,"get temperatures ok",10);
}
float getone_temp(uint8_t address)
{
float temp;
DS18b20.requestTemperatures(); // Send the command to get temperatures
temp = DS18b20.getTempC(p[address]);
return temp;
}
// void set_ds18b20_address(uint8_t num,uint8_t * addr)
// {
// // uint8_t num = addr[0];
// memcpy(&sensoraddr[num],addr,8);
// }
//测试用
//温度监测
// void getall_temp(float *temp)
// {
// DS18b20.requestTemperatures(); // Send the command to get temperatures
// for (u_int32_t i = 0; i < temp_number; i++)
// {
// temp[i] = DS18b20.getTempC(sensoraddr[i]);
// }
// }
// uint8_t get_ds18b20_addr()
// {
// float temp[8];
// getall_temp(temp);
// for(size_t i = 0; i < temp_number; i++)
// {
// Serial.printf("%d temp: %2f ds18b20 addr :",i,temp[i]);
// for(int a = 0 ; a< 8 ;a++)
// {
// Serial.printf(" %x ",sensoraddr[i][a]);
// }
// Serial.println("");
// }
// return 0;
// }
// {
// "sensor0":{
// "byte0":"",
// "byte1":"",
// "byte2":"",
// "byte3":"",
// "byte4":"",
// "byte5":"",
// "byte6":"",
// "byte7":""
// },
// "sensor1":{
// "byte0":"",
// "byte1":"",
// "byte2":"",
// "byte3":"",
// "byte4":"",
// "byte5":"",
// "byte6":"",
// "byte7":""
// },
// "sensor2":{
// "byte0":"",
// "byte1":"",
// "byte2":"",
// "byte3":"",
// "byte4":"",
// "byte5":"",
// "byte6":"",
// "byte7":""
// },
// "sensor3":{
// "byte0":"",
// "byte1":"",
// "byte2":"",
// "byte3":"",
// "byte4":"",
// "byte5":"",
// "byte6":"",
// "byte7":""
// },
// "sensor4":{
// "byte0":"",
// "byte1":"",
// "byte2":"",
// "byte3":"",
// "byte4":"",
// "byte5":"",
// "byte6":"",
// "byte7":""
// },
// "sensor5":{
// "byte0":"",
// "byte1":"",
// "byte2":"",
// "byte3":"",
// "byte4":"",
// "byte5":"",
// "byte6":"",
// "byte7":""
// },
// "sensor6":{
// "byte0":"",
// "byte1":"",
// "byte2":"",
// "byte3":"",
// "byte4":"",
// "byte5":"",
// "byte6":"",
// "byte7":""
// },
// "sensor7":{
// "byte0":"",
// "byte1":"",
// "byte2":"",
// "byte3":"",
// "byte4":"",
// "byte5":"",
// "byte6":"",
// "byte7":""
// }
// }

14
src/DS18B20.h Normal file
View File

@ -0,0 +1,14 @@
#ifndef _DS18B20_H_
#define _DS18B20_H_
//DS18B20库
#include <OneWire.h>
#include <DallasTemperature.h>
#define DS18b20_pin 4
uint8_t DS18b20_init();
void getall_temp(float *temp);
float getone_temp(uint8_t address);
uint8_t get_ds18b20_addr();
void set_ds18b20_address(uint8_t num,uint8_t * addr);
#endif

10
src/Define.h Normal file
View File

@ -0,0 +1,10 @@
#ifndef Define_h
#define Define_h
//#define DebugCalibration
//#define DINBIAO
//#define Curentvsion "V2.4b"\
#define Curentvsion "V2.5b"
#define Curentvsion "V2.3"
#define TINY_GSM_DEBUG Serial
#endif

166
src/GSMMannager.cpp Normal file
View File

@ -0,0 +1,166 @@
#include "GSMMannager.h"
// #include "SoftwareSerial.h"
// uint32_t AIR_AutoBaud();
const char apn[] = "CMNET";
const char gprsUser[] = "";
const char gprsPass[] = "";
HardwareSerial *MySerial;
GSMMannger::GSMMannger(int serialnumber, int rx, int tx)
{
pinMode(37, OUTPUT); //pin32控制sim800C电源 高电平上电 低电平断电
digitalWrite(37, HIGH);
vTaskDelay(1000*10);
// digitalWrite(37, LOW);
MySerial=new HardwareSerial(serialnumber);
modem = new TinyGsm(*MySerial);
MySerial->begin(115200, SERIAL_8N1, rx, tx);
client = new TinyGsmClient(*modem);
// !!!!!!!!!!! <20>ϵ<EFBFBD>
// Serial.println("Wait...");
write_log(log_path,"Wait...",10);
// Serial.println("Wait...1");
write_log(log_path,"Wait...1",10);
vTaskDelay(1800);
// Set your reset, enable, power pins here
// !!!!!!!!!!!
vTaskDelay(5000);
// Set GSM module baud rate
// MySerial->readString();
int banddd=TinyGsmAutoBaud(*MySerial, rx, tx, 9600,460800);
if (banddd==0)
{
// Serial.println("fail to connect sim800 reboot");
write_log(log_path,"fail to connect sim800 reboot",10);
esp_restart();
/* code */
}
// Serial.println("band is" + String(banddd));
write_log(log_path,"band is" + String(banddd),10);
vTaskDelay(6000);
modem->init();
String modemInfo = modem->getModemInfo();
if (modemInfo=="")
{
// Serial.println("fail to getmode reboot");
write_log(log_path,"fail to getmode reboot",10);
esp_restart();
/* code */
}
// Serial.print("Modem Info: ");
write_log(log_path,"Modem Info: ",10);
//以后用4G再
// SerialMon.println(modemInfo);
write_log(log_path,modemInfo,10);
if (GSM_PIN && modem->getSimStatus() != 3)
{
modem->simUnlock(GSM_PIN);
}
// SerialMon.print("Waiting for network...");
write_log(log_path,"Waiting for network...",10);
if (!modem->waitForNetwork())
{
// SerialMon.println(" fail");
write_log(log_path,"fail",10);
vTaskDelay(10000);
return;
}
// SerialMon.println(" success");
write_log(log_path,"success",10);
if (modem->isNetworkConnected())
{
// SerialMon.println("Network connected");
write_log(log_path,"Network connected",10);
}
// SerialMon.print(F("Connecting to "));
write_log(log_path,"Connecting to ",10);
// SerialMon.print(apn);
write_log(log_path,apn,10);
if (!modem->gprsConnect(apn, gprsUser, gprsPass))
{
// SerialMon.println(" fail");
write_log(log_path,"fail",10);
vTaskDelay(10000);
return;
}
// SerialMon.println(" success");
write_log(log_path,"success",10);
if (modem->isGprsConnected())
{
// SerialMon.println("GPRS connected");
write_log(log_path,"GPRS connected",10);
}
modem->NTPServerSync();
}
String GSMMannger::I2toS(int n)
{
if (n>=10)
{
return String(n);
} else{
return "0"+ String(n);
}
}
String GSMMannger::GetDataAndTime() {
//String str=modem->getGSMDateTime(DATE_FULL);
if(modem->getNetworkTime(&year,&month,&day,&hour,&minute, &second,&timezone))
{
String date=String(year)+"-"+I2toS(month)+"-"+I2toS(day)+" "+I2toS(hour)+":"+I2toS(minute)+":"+I2toS(second);
return date;}
return "-1";
}
void GSMMannger::loop()
{
if (!modem->isNetworkConnected())
{
SerialMon.println("Network disconnected");
if (!modem->waitForNetwork(20000L, true))
{
SerialMon.println(" re wait For Network fail");
esp_restart();
vTaskDelay(10000);
return;
}
if (modem->isNetworkConnected())
{
SerialMon.println("Network re-connected");
}
// and make sure GPRS/EPS is still connected
if (!modem->isGprsConnected())
{
SerialMon.println("GPRS disconnected!");
SerialMon.print(F("Connecting to "));
SerialMon.print(apn);
if (!modem->gprsConnect(apn, gprsUser, gprsPass))
{
SerialMon.println(" set apn gprsuser gprspass fail");
esp_restart();
vTaskDelay(10000);
return;
}
if (modem->isGprsConnected())
{
SerialMon.println("GPRS reconnected");
}
}
}
}

40
src/GSMMannager.h Normal file
View File

@ -0,0 +1,40 @@
#ifndef _GSMMannager_H_
#define _GSMMannager_H_
// #define TINY_GSM_MODEM_SIM800
#define TINY_GSM_MODEM_BG96
#define SerialMon Serial
#include <TinyGsmClient.h>
#include <PubSubClient.h>
#include "log.h"
//#define TINY_GSM_DEBUG SerialMon
#define GSM_AUTOBAUD_MIN 9600
#define GSM_AUTOBAUD_MAX 115200
#define TINY_GSM_USE_GPRS true
#define TINY_GSM_USE_WIFI false
#define GSM_PIN ""
class GSMMannger
{
public:
GSMMannger(int serialnumber,int rx,int tx); // <20><><EFBFBD>ǹ<EFBFBD><C7B9>캯<EFBFBD><ECBAAF>
// GSMMannger();
TinyGsm *modem;
TinyGsmClient *client;
String GetDataAndTime();
void loop();
String I2toS(int n);
int year,month, day, hour,minute, second;
float timezone;
};
#endif

174
src/IRIS_Method.cpp Normal file
View File

@ -0,0 +1,174 @@
/**
******************************************************************************
* @file : IRIS_Method.c
* @author : xin
* @brief : None
* @attention : None
* @date : 2024/2/1
******************************************************************************
*/
//
// Created by xin on 2024/2/1.
//
#include "IRIS_Method.h"
int32_t IRIS_Protocol_Pack(uint8_t Command, uint16_t LenthofIn, uint8_t *BufferIn, uint8_t *PackData) {
if (PackData == NULL || (LenthofIn != 0 && BufferIn == NULL)) {
return -1;
}
PackData[0] = 0x55;
PackData[1] = 0xAA;
PackData[2] = Command;
uint16_t datalenth = LenthofIn;
PackData[3] = (datalenth >> 8) & 0xFF;
PackData[4] = datalenth & 0xFF;
if (LenthofIn != 0) {
memcpy(&PackData[5], BufferIn, LenthofIn);
}
uint16_t crcbytelenth = LenthofIn;
uint16_t CRC = IRIS_calcCRC(PackData + 5, crcbytelenth);
PackData[LenthofIn + 5] = (CRC >> 8) & 0xFF;
PackData[LenthofIn + 6] = CRC & 0xFF;
return LenthofIn + 7;
}
int32_t IRIS_STM32_Protocol_Unpack(uint8_t *PackData, uint16_t LenthofIn, uint8_t *Command, uint8_t *BufferOut) {
if (PackData == NULL || BufferOut == NULL) {
return ERROR_INPUT;
}
if (PackData[0] != 0x55 || PackData[1] != 0xAA) {
return ERROR_HEADER;
}
uint16_t LenthofOut = PackData[4] + (PackData[3] << 8); //减去CRC的两个字节
if (LenthofOut > LenthofIn - 7) {
return ERROR_NOT_ENOUGH_DATA;
}
if (PackData[LenthofOut + 6] == 0xEE && PackData[LenthofOut + 5] == 0xEE) {
} else {
uint16_t CRC = IRIS_calcCRC(PackData + 5, LenthofOut);
if (CRC != (PackData[LenthofOut + 6] + (PackData[LenthofOut + 5] << 8))) {
return ERROR_CRC;
}
}
if (LenthofOut == 0) {
return 0;
}
*Command = PackData[2];
memcpy(BufferOut, &PackData[5], LenthofOut);
return LenthofOut;
}
int32_t IRIS_Protocol_Unpack(uint8_t *PackData, uint16_t LenthofIn, uint8_t Command, uint8_t *BufferOut) {
if (PackData == NULL || BufferOut == NULL) {
return ERROR_INPUT;
}
if (PackData[0] != 0x55 || PackData[1] != 0xAA) {
return ERROR_HEADER;
}
if (PackData[2] != Command) {
return ERROR_COMMAND;
}
uint16_t LenthofOut = PackData[4] + (PackData[3] << 8);
if (LenthofOut > LenthofIn - 7) {
return ERROR_NOT_ENOUGH_DATA;
}
if (PackData[LenthofOut + 6] == 0xEE && PackData[LenthofOut + 5] == 0xEE) {
} else {
uint16_t CRC = IRIS_calcCRC(PackData + 5, LenthofOut);
if (CRC != (PackData[LenthofOut + 6] + (PackData[LenthofOut + 5] << 8))) {
return ERROR_CRC;
}
}
if (LenthofOut == 0) {
return 0;
}
memcpy(BufferOut, &PackData[5], LenthofOut);
return LenthofOut;
}
int32_t IRIS_Cut_Befor_Header(uint8_t *PackData, uint16_t LenthofIn) {
if (PackData == NULL) {
return ERROR_INPUT;
}
uint16_t i = 0;
for (i = 0; i < LenthofIn; i++) {
if (PackData[i] == 0x55 && PackData[i + 1] == 0xAA) {
break;
}
}
if (i == LenthofIn) {
//清空数据
memset(PackData, 0, LenthofIn);
return 0;
}
uint16_t LenthofOut = LenthofIn - i;
memcpy(PackData, &PackData[i], LenthofOut);
return LenthofOut;
}
int32_t IRIS_Check_Data_Valid(uint8_t *PackData, uint16_t LenthofIn) {
if (PackData == NULL) {
return ERROR_INPUT;
}
if (LenthofIn < 7) {
return ERROR_NOT_ENOUGH_DATA;
/* code */
}
if (PackData[0] != 0x55 || PackData[1] != 0xAA) {
return ERROR_HEADER;
}
uint16_t LenthofOut = PackData[4] + (PackData[3] << 8);
if (LenthofOut > LenthofIn - 7) {
return ERROR_NOT_ENOUGH_DATA;
}
if (PackData[LenthofOut + 6] == 0xEE && PackData[LenthofOut + 5] == 0xEE) {
} else {
uint16_t CRC = IRIS_calcCRC(PackData + 5, LenthofOut);
if (CRC != (PackData[LenthofOut + 6] + (PackData[LenthofOut + 5] << 8))) {
return ERROR_CRC;
}
}
return 1;
}
uint16_t IRIS_calcCRC(const void *pBuffer, uint16_t bufferSize) {
const uint8_t *pBytesArray = (const uint8_t *) pBuffer;
uint16_t poly = 0x8408;
uint16_t crc = 0;
uint8_t carry;
uint8_t i_bits;
uint16_t j;
for (j = 0; j < bufferSize; j++) {
crc = crc ^ pBytesArray[j];
for (i_bits = 0; i_bits < 8; i_bits++) {
carry = crc & 1;
crc = crc / 2;
if (carry) {
crc = crc ^ poly;
}
}
}
return crc;
}

60
src/IRIS_Method.h Normal file
View File

@ -0,0 +1,60 @@
/**
******************************************************************************
* @file : IRIS_Method.h
* @author : xin
* @brief : None
* @attention : None
* @date : 2024/2/1
******************************************************************************
*/
//
// Created by xin on 2024/2/1.
//
#ifndef IRIS_COMMUNICATION_PROTOCOL_IRIS_METHOD_H
#define IRIS_COMMUNICATION_PROTOCOL_IRIS_METHOD_H
#define ERROR_NOT_ENOUGH_DATA -200
#define ERROR_HEADER -300
#define ERROR_COMMAND -400
#define ERROR_INPUT -500
#define ERROR_CRC -600
#include <stdint.h>
#include<Arduino.h>
// 成功返回打包后的数据长度
// -1: Error
// 成功返回打包后的数据长度
int32_t IRIS_Protocol_Pack(uint8_t Command,uint16_t LenthofIn, uint8_t *BufferIn, uint8_t *PackData);
// 解包函数 PackData 是接收到的数据 LenthofIn 是数据长度 Command 是命令 BufferOut 是输出
// 下位机使用的打包函数 Command 是输出
// 成功返回解包后的数据长度
// 0: 该命令返回无参数
// 错误返回ERRor
// 成功返回解包后的数据长度
int32_t IRIS_STM32_Protocol_Unpack(uint8_t *PackData, uint16_t LenthofIn, uint8_t *Command, uint8_t *BufferOut);
// 解包函数 PackData 是接收到的数据 LenthofIn 是数据长度 Command 是命令输入 BufferOut 是输出 上位机使用
// 成功返回解包后的数据长度
// 0: 该命令返回无参数
// 错误返回ERRor
// 成功返回解包后的数据长度
int32_t IRIS_Protocol_Unpack(uint8_t *PackData, uint16_t LenthofIn, uint8_t Command, uint8_t *BufferOut);
// 定义裁切命令
// 成功返回裁切后的数据长度
// -1: Error
int32_t IRIS_Cut_Befor_Header(uint8_t *PackData, uint16_t LenthofIn );
// 检查数据是否有效
// 有效返回值1
// 错误返回ERRor
int32_t IRIS_Check_Data_Valid(uint8_t *PackData, uint16_t LenthofIn );
// 返回CRC校验值
uint16_t IRIS_calcCRC(const void *pBuffer, uint16_t bufferSize);
#endif //IRIS_COMMUNICATION_PROTOCOL_IRIS_METHOD_H

212
src/IS11Comon.cpp Normal file
View File

@ -0,0 +1,212 @@
#include "IS11Comon.h"
u_char BufferForRead[10000];
int TotalIndexNow = 0;
u_char BufferFortempWrite[1000];
// MySerialWrite=nullptr;
SERIALWRITE MySerialWrite = nullptr;
SERIALREAD MySerialRead = nullptr;
bool ISIS11Init = false;
uint16_t crc16(const uint8_t *data, size_t len, uint16_t polynomial)
{
uint16_t i, j, tmp, CRC16;
CRC16 = 0xFFFF; // CRC寄存器初始值
for (i = 0; i < len; i++)
{
CRC16 ^= data[i];
for (j = 0; j < 8; j++)
{
tmp = (uint16_t)(CRC16 & 0x0001);
CRC16 >>= 1;
if (tmp == 1)
{
CRC16 ^= polynomial; // 异或多项式
}
}
}
return CRC16;
}
size_t SendSettingCommand(u_char *Command, size_t CommandLenth, u_char *Value, size_t ValueLenth)
{
memcpy(BufferFortempWrite, Command, CommandLenth);
memcpy(BufferFortempWrite + CommandLenth, Value, ValueLenth);
uint16_t crc = crc16(BufferFortempWrite, CommandLenth + ValueLenth);
memcpy(BufferFortempWrite + CommandLenth + ValueLenth, &crc, 2);
SerialWrite(BufferFortempWrite, CommandLenth + ValueLenth + 2);
return GetSetBackFromSensor();
}
size_t SendGetData(int shutter)
{
int lenth = sizeof(GET_ALL_DN);
uint16_t crc = crc16(GET_ALL_DN, lenth);
memcpy(BufferFortempWrite, GET_ALL_DN, lenth);
memcpy(BufferFortempWrite + lenth, &crc, 2);
SerialWrite(BufferFortempWrite, lenth + 2);
vTaskDelay(shutter);
return GetInfoBackFromSensor(true);
}
size_t SendGetSensorInfo(u_char *Command, size_t lenth)
{
uint16_t crc = crc16(Command, lenth);
memcpy(BufferFortempWrite, Command, lenth);
memcpy(BufferFortempWrite + lenth, &crc, 2);
SerialWrite(BufferFortempWrite, lenth + 2);
String datastr;
for (size_t i = 0; i < lenth + 2; i++)
{
datastr += String(BufferFortempWrite[i]);
}
// write_log(gp_log, "send data:" + datastr, 20);
size_t retunnumber = GetInfoBackFromSensor();
return retunnumber;
}
size_t GetSetBackFromSensor()
{
TotalIndexNow = 0;
TotalIndexNow += SerailRead(BufferForRead + TotalIndexNow, 1);
while (TotalIndexNow < 8)
{
TotalIndexNow += SerailRead(BufferForRead + TotalIndexNow, 1);
}
return TotalIndexNow;
}
bool panduanHeader()
{
if (TotalIndexNow < 2)
{
return false;
/* code */
}
int temp = 0;
while (BufferForRead[temp] != 0x01 &&
!(BufferForRead[temp + 1] == 0x03 || BufferForRead[temp + 1] == 0x06 || BufferForRead[temp + 1] == 0x10))
{
if (temp >= TotalIndexNow - 2)
{
break;
/* code */
}
temp++;
/* code */
}
memcpy(BufferForRead, BufferForRead + temp, TotalIndexNow - temp);
TotalIndexNow = TotalIndexNow - temp;
temp = 0;
if (BufferForRead[temp] != 0x01 &&
!(BufferForRead[temp + 1] == 0x03 || BufferForRead[temp + 1] == 0x06 || BufferForRead[temp + 1] == 0x10))
{
return false;
}
return true;
}
size_t GetInfoBackFromSensor(bool isbig) // big 是指用几个字节表示数据长度 暂时只发现采集数据时用两个字节
{
if (isbig)
{
TotalIndexNow = 0;
memset(BufferForRead, 0, sizeof(BufferForRead));
TotalIndexNow += SerailRead(BufferForRead + TotalIndexNow, 2);
while (!panduanHeader())
{
TotalIndexNow += SerailRead(BufferForRead + TotalIndexNow, 1);
}
while (TotalIndexNow < 4)
{
TotalIndexNow += SerailRead(BufferForRead + TotalIndexNow, 1);
}
int lenth = BufferForRead[2] * 256 + BufferForRead[3];
while (TotalIndexNow < lenth + 4)
{
TotalIndexNow += SerailRead(BufferForRead + TotalIndexNow, 1024);
}
return TotalIndexNow;
}
else
{
// 长度用一个字节表示
TotalIndexNow = 0;
TotalIndexNow += SerailRead(BufferForRead + TotalIndexNow, 1);
while (TotalIndexNow < 3)
{
TotalIndexNow += SerailRead(BufferForRead + TotalIndexNow, 1);
}
int lenth = BufferForRead[2];
while (TotalIndexNow < lenth + 5)
{
TotalIndexNow += SerailRead(BufferForRead + TotalIndexNow, 1);
}
return TotalIndexNow;
}
}
size_t SerialWrite(u_char *data, size_t lenth)
{
if (MySerialWrite != nullptr)
{
return MySerialWrite(data, lenth);
}
return 0;
}
size_t SerailRead(u_char *data, size_t lenth)
{
if (MySerialRead != nullptr)
{
return MySerialRead(data, lenth);
}
return 0;
}
void InitFunction(SERIALWRITE a, SERIALREAD readfunc)
{
MySerialWrite = a;
MySerialRead = readfunc;
ISIS11Init = true;
}
u_char *GetDataBufferPTR()
{
return BufferForRead;
}
bool isSensorInit()
{
return ISIS11Init;
}
void CoverLittleAndBig(char *data, int lenth)
{
char *tempdata = new char[lenth];
memcpy(tempdata, data, lenth);
for (size_t i = 0; i < lenth / 2; i++)
{
data[2 * i] = tempdata[2 * i + 1];
data[2 * i + 1] = tempdata[2 * i];
/* code */
}
delete[] tempdata;
}

143
src/IS11Comon.h Normal file
View File

@ -0,0 +1,143 @@
/**
* @brief is11相关底层函数
*
*/
#ifndef __IS11COMON_H__
#define __IS11COMON_H__
#ifndef IS11COMMON_H
#define IS11COMMON_H
#include <stdint.h>
#include <stddef.h>
#include <string>
#include<Arduino.h>
#include "log.h"
#define COMMAND_GET 0x03
#define COMMAND_SET 0x06
#define COMMAND_MULTSET 0x10
#define POLYNOMIAL 0xa001 //modbus crc
typedef unsigned char u_char;
/**
* @brief 串口写函数类型
*
*/
typedef size_t (*SERIALWRITE)(u_char* data,size_t lenth);
/**
* @brief 串口读函数原型
*
*/
typedef size_t (*SERIALREAD)(u_char* data,size_t lenth);
const u_char GET_ADDRESS[] ={0x01,0x03,0x00,0x01,0x00,0x01};
const u_char GET_BANDRATE[] ={0x01,0x03,0x00,0x02,0x00,0x01};
const u_char GET_INTEGRAL_TIME[] ={0x01,0x03,0x00,0x06,0x00,0x01};
const u_char GET_AVERAGE_NUMBER[] ={0x01,0x03,0x00,0x07,0x00,0x01};
const u_char GET_WAVELENTH_AT_BAND[]={0x01,0x03,0x00,0x10,0x00,0x02};
const u_char GET_VALUE_AT_BAND[] ={0x01,0x03,0x00,0x30,0x00,0x02};
const u_char GET_SETTING_OF_LAMP[] ={0x01,0x03,0x00,0x04,0x00,0x01};
const u_char GET_WAVELENTH_COEFF[] ={0x01,0x03,0x00,0x20,0x00,0x08};
const u_char GET_ALL_DN[] ={0x01,0x03,0x01,0x00,0x10,0x00};
const u_char GET_SERIAL_NUMBER[] ={0x01,0x03,0x00,0x40,0x00,0x00};
const u_char GET_PRODUCT_NAME[] ={0x01,0x03,0x00,0x50,0x00,0x00};
const u_char SET_ADDRESS[] ={0x01,0x06,0x00,0x01};
// const u_char SET_BandRATE[] ={0x01,0x06,0x00,0x02};
const u_char SET_INTEGRAL_TIME[] ={0x01,0x06,0x00,0x06};
const u_char SET_AVERAGE_NUMBER[] ={0x01,0x06,0x00,0x07};
const u_char SET_WORK_MODE[] ={0x01,0x06,0x00,0x01};
const u_char SET_WAVELENTH_COEFF[] ={0x01,0x10,0x00,0x20,0x00,0x08,0x16};
/**
* @brief 判断传感器是否初始化完成
*
* @return true
* @return false
*/
bool isSensorInit();
/**
* @brief 初始化传感器
*
* @param writefunc 写函数
* @param readfunc 读函数
*/
void InitFunction(SERIALWRITE writefunc,SERIALREAD readfunc);
/**
* @brief 获取 BufferForRead 的指针 用于读取返回的数据
*
*/
u_char * GetDataBufferPTR();
/**
* @brief 发送获取设备信息的指令 适用于Get指令
*
* @param Command 指令 预定的数组
* @param lenth 指令长度 可以用sizeof来求算
* @return size_t 返回数据的长度 输出存放于 BufferForRead;
*/
size_t SendGetSensorInfo(u_char * Command,size_t lenth);//此过程不适合获取数据
/**
* @brief
*
* @param shutter
* @return size_t
*/
size_t SendGetData(int shutter);
/**
* @brief 发送设置指令
*
* @param Command 指令内容
* @param CommandLenth 指令长度
* @param Value 设置值
* @param ValueLenth 值长度 默认是两个字节
* @return size_t 返回值长度
*/
size_t SendSettingCommand(u_char * Command,size_t CommandLenth,u_char *Value,size_t ValueLenth=2);
//big
/**
* @brief 用来获取信息的返回的数据
*
* @param isbig 是指用几个字节表示数据长度 暂时只发现采集数据时用两个字节
* @return size_t 接收到的数据大小
*/
size_t GetInfoBackFromSensor(bool isbig=false);
/**
* @brief 获取设置后返回数据
*
* @return size_t 返回数据长度;
*/
size_t GetSetBackFromSensor();
/**
* @brief
*
* @param data
* @param lenth
* @return size_t
*/
size_t SerialWrite(u_char* data,size_t lenth);
size_t SerailRead(u_char* data,size_t lenth=0);
/**
* @brief 计算crc16
*
* @param data 数据
* @param len 数据长度
* @param polynomial crc16多项式 默认是A001H
* @return uint16_t crc16的值
*/
uint16_t crc16(const uint8_t *data, size_t len, uint16_t polynomial=POLYNOMIAL) ;
bool panduanHeader();
void CoverLittleAndBig(char *data,int lenth);
#endif
#endif // __IS11COMON_H__

5
src/MyEsp8266.cpp Normal file
View File

@ -0,0 +1,5 @@
//
// Created by xin on 2022/4/28.
//
#include "MyEsp8266.h"

14
src/MyEsp8266.h Normal file
View File

@ -0,0 +1,14 @@
//
// Created by xin on 2022/4/28.
//
#ifndef ESP32MAINBOARD_MYESP8266_H
#define ESP32MAINBOARD_MYESP8266_H
class MyEsp8266 {
};
#endif //ESP32MAINBOARD_MYESP8266_H

139
src/MyWebServer.cpp Normal file
View File

@ -0,0 +1,139 @@
#include "MyWebServer.h"
ESPWebServer *ESPStaticServer;
void webserver::printn(String str)
{
if (serialmy != nullptr)
{
serialmy->print(str);
}
}
void webserver::initme()
{
printn("webserver begain\n");
// wifiMulti.addAP("IRIS", "irishk*******"); // 将需要连接的一系列WiFi ID和密码输入这里
// wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2"); // ESP8266-NodeMCU再启动后会扫描当前网络
// wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3"); // 环境查找是否有这里列出的WiFi ID。如果有
// printn("Connecting ..."); // 则尝试使用此处存储的密码进行连接。
// int i = 0;
// while (wifiMulti.run() != WL_CONNECTED) { // 尝试进行wifi连接。
// vTaskDelay(1000);
// printn("retry to connect wifi");
// }
// WiFi连接成功后将通过串口监视器输出连接成功信息
printn("Connected to \n");
printn(WiFi.SSID()); // 通过串口监视器输出连接的WiFi名称
printn("IP address:\t");
printn(WiFi.localIP().toString()); // 通过串口监视器输出ESP8266-NodeMCU的IP
printn("\n");
if (SPIFFS.begin())
{ // 启动闪存文件系统
printn("SPIFFS Started.\n");
}
else
{
printn("SPIFFS Failed to Start.\n");
}
server->onNotFound(handleUserRequet); // 告知系统如何处理用户请求
server->begin(); // 启动网站服务
printn("HTTP server started\n");
}
webserver::webserver(HardwareSerial *serial)
{
serialmy = serial;
server=new ESPWebServer(80);
ESPStaticServer=server;
initme();
}
webserver::webserver()
{
serialmy = nullptr;
server=new ESPWebServer(80);
ESPStaticServer=server;
initme();
}
webserver::~webserver()
{
}
void webserver::handleUserRequet()
{
// Serial.println("some one come\n");
write_log(log_path,"some one come\n",10);
// 获取用户请求网址信息
String webAddress = ESPStaticServer->uri();
// 通过handleFileRead函数处处理用户访问
bool fileReadOK = handleFileRead(webAddress);
// 如果在SPIFFS无法找到用户访问的资源,则回复404 (Not Found)
if (!fileReadOK)
{
ESPStaticServer->send(404, "text/plain", "404 Not Found");
}
}
bool webserver::handleFileRead(String path)
{ //处理浏览器HTTP访问
if (path.endsWith("/"))
{ // 如果访问地址以"/"为结尾
path = "/index.html"; // 则将访问地址修改为/index.html便于SPIFFS访问
}
String contentType = getContentType(path); // 获取文件类型
if (SPIFFS.exists(path))
{ // 如果访问的文件可以在SPIFFS中找到
File file = SPIFFS.open(path, "r"); // 则尝试打开该文件
ESPStaticServer->streamFile(file, contentType); // 并且将该文件返回给浏览器
file.close(); // 并且关闭文件
return true; // 返回true
}
return false; // 如果文件未找到,则返回false
}
// 获取文件类型
String webserver::getContentType(String filename)
{
if (filename.endsWith(".htm"))
return "text/html";
else if (filename.endsWith(".html"))
return "text/html";
else if (filename.endsWith(".css"))
return "text/css";
else if (filename.endsWith(".js"))
return "application/javascript";
else if (filename.endsWith(".png"))
return "image/png";
else if (filename.endsWith(".gif"))
return "image/gif";
else if (filename.endsWith(".jpg"))
return "image/jpeg";
else if (filename.endsWith(".ico"))
return "image/x-icon";
else if (filename.endsWith(".xml"))
return "text/xml";
else if (filename.endsWith(".pdf"))
return "application/x-pdf";
else if (filename.endsWith(".zip"))
return "application/x-zip";
else if (filename.endsWith(".gz"))
return "application/x-gzip";
return "text/plain";
}
void webserver::loop()
{
ESPStaticServer->handleClient();
// printn("...");
}

40
src/MyWebServer.h Normal file
View File

@ -0,0 +1,40 @@
#ifndef wenserver_H
#define wenserver_H
#define ESP32
#ifdef ESP32
#include "WebServer.h"
#include "WiFi.h"
#include "Arduino.h"
#include "SPIFFS.h"
#define ESPWebServer WebServer
#elif
#include <ESP8266WebServer.h>
#include <ESP8266WiFi.h>
#define ESPWebServer ESP8266WebServer
#endif
#include <FS.h>
#include "log.h"
class webserver
{
private:
public:
webserver(HardwareSerial *serial);
webserver();
void initme();
HardwareSerial *serialmy;
~webserver();
static void handleUserRequet();
static bool handleFileRead(String path);
static String getContentType(String filename);
void loop();
void printn(String str);
ESPWebServer *server;
};
#endif

314
src/SDmanger.cpp Normal file
View File

@ -0,0 +1,314 @@
#include"SDmanger.h"
File Comenfile;
int sdcard::init_sdcard()
{
SD_MMC.setPins(9,10,11,12,13,14);
int succ = SD_MMC.begin("/sdcard", true,true,20000);
if (succ) {
// Serial.printf("SD_MMC Begin: %d\n", succ);
write_log(log_path,"SD_MMC Begin: "+String(succ),10);
uint8_t cardType = SD_MMC.cardType();
// Serial.print("SD_MMC Card Type: ");uj
write_log(log_path,"SD_MMC Card Type: ",10);
if (cardType == CARD_MMC) {
// Serial.println("MMC");
write_log(log_path,"MMC",10);
} else if (cardType == CARD_SD) {
// Serial.println("SDSC");
write_log(log_path,"SDSC",10);
} else if (cardType == CARD_SDHC) {
// Serial.println("SDHC");
write_log(log_path,"SDHC",10);
} else {
// Serial.println("UNKNOWN");
write_log(log_path,"UNKNOWN",10);
}
uint64_t cardSize = SD_MMC.cardSize() / (1024 * 1024);
uint32_t c = cardSize;
// Serial.printf("SD_MMC Card Size: %lluMB\n", cardSize);
write_log(log_path,"SD_MMC Card Size: "+String(c)+"MB",10);
// Serial.printf("Total space: %lluMB\n", SD_MMC.totalBytes() / (1024 * 1024));
float a = SD_MMC.totalBytes() / (1024 * 1024);
write_log(log_path,"Total space: "+String(a)+"MB",10);
// Serial.printf("Used space: %lluMB\n", SD_MMC.usedBytes() / (1024 * 1024));
a = SD_MMC.usedBytes() / (1024 * 1024);
write_log(log_path,"Used space: "+String(a)+"MB",10);
mylistDir( "/", 0);
// File file;
// file.listFiles("/");
// file.flush();
// file.close();
} else {
// Serial.printf("Failed to mount SD card VFAT filesystem. \n");
write_log(log_path,"Failed to mount SD card VFAT filesystem. ",10);
// Serial.println("Do you have an SD Card installed?");
write_log(log_path,"Do you have an SD Card installed?",10);
// Serial.println("Check pin 12 and 13, not grounded, or grounded with 10k resistors!\n\n");
write_log(log_path,"Check pin 12 and 13, not grounded, or grounded with 10k resistors!\n\n",10);
// major_fail();
}
return ESP_OK;
}
void sdcard::mylistDir( const char * dirname, uint8_t levels) {
write_log(log_path,"Listing directory: "+String(dirname),10);
String dir(dirname);
File root = SD_MMC.open(dirname);
if (!root) {
write_log(log_path,"Failed to open directory",10);
return;
}
if (!root.isDirectory()) {
write_log(log_path,"Not a directory",10);
return;
}
File filex = root.openNextFile();
while (filex) {
if (filex.isDirectory())
{
write_log(log_path," DIR : " + String(filex.name()),10);
if (levels) {
String filename=dir+"/"+String(filex.name());
mylistDir( filename.c_str(), levels - 1);
}
}
else
{
write_log(log_path," FILE: " + String(filex.name()) + " size :"+ String(filex.size()) + "B",10);
}
filex = root.openNextFile();
}
}
bool sdcard::ListDir(const char * dirname,Vector <String> &stringlist)
{
stringlist.clear();
// Serial.printf("Listing directory: %s\n", dirname);
write_log(log_path,"Listing directory: "+String(dirname),10);
String dir(dirname);
File root = SD_MMC.open(dirname);
if (!root) {
// Serial.println("Failed to open directory");
write_log(log_path,"Failed to open directory",10);
return true;
}
if (!root.isDirectory()) {
// Serial.println("Not a directory");
write_log(log_path,"Not a directory",10);
return true;
}
File filex = root.openNextFile();
while (filex)
{
if (filex.isDirectory()) {
} else {
String filename=dir+"/"+String(filex.name());
stringlist.push_back(filename);
if (stringlist.size()==stringlist.max_size())
{
return false;
/* code */
}
}
filex = root.openNextFile();
}
return true;
}
void sdcard::delete_old_stuff() {
// Serial.printf("Total space: %lluMB\n", SD_MMC.totalBytes() / (1024 * 1024));
float a = SD_MMC.totalBytes() / (1024 * 1024);
write_log(log_path,"Total space: "+String(a)+"MB",10);
// Serial.printf("Used space: %lluMB\n", SD_MMC.usedBytes() / (1024 * 1024));
a = SD_MMC.usedBytes() / (1024 * 1024);
write_log(log_path,"Used space: "+String(a)+"MB",10);
//listDir( "/", 0);
float full = 1.0 * SD_MMC.usedBytes() / SD_MMC.totalBytes();;
if (full < 0.8) {
// Serial.printf("Nothing deleted, %.1f%% disk full\n", 100.0 * full);
write_log(log_path,"Nothing deleted, "+String(100.0 * full)+"% disk full",10);
} else {
// Serial.printf("Disk is %.1f%% full ... deleting oldest file\n", 100.0 * full);
write_log(log_path,"Disk is "+String(100.0 * full)+"% full ... deleting oldest file",10);
while (full > 0.8) {
double del_number = 999999999;
char del_numbername[50];
File f = SD_MMC.open("/");
File file = f.openNextFile();
while (file) {
//Serial.println(file.name());
if (!file.isDirectory()) {
char foldname[50];
strcpy(foldname, file.name());
for ( int x = 0; x < 50; x++) {
if ( (foldname[x] >= 0x30 && foldname[x] <= 0x39) || foldname[x] == 0x2E) {
} else {
if (foldname[x] != 0) foldname[x] = 0x20;
}
}
double i = atof(foldname);
if ( i > 0 && i < del_number) {
strcpy (del_numbername, file.name());
del_number = i;
}
//Serial.printf("Name is %s, number is %f\n", foldname, i);
}
file = f.openNextFile();
}
// Serial.printf("lowest is Name is %s, number is %f\n", del_numbername, del_number);
write_log(log_path,"lowest is Name is "+String(del_numbername)+", number is "+String(del_number),10);
if (del_number < 999999999) {
deleteFolderOrFile(del_numbername);
}
full = 1.0 * SD_MMC.usedBytes() / SD_MMC.totalBytes();
// Serial.printf("Disk is %.1f%% full ... \n", 100.0 * full);
write_log(log_path,"Disk is "+String(100.0 * full)+"% full ... ",10);
f.close();
}
}
}
void sdcard::deleteFolderOrFile(const char * val) {
write_log(log_path,"Deleting : "+String(val),10);
File f = SD_MMC.open(val);
if (!f) {
write_log(log_path,"Failed to open "+String(val),10);
return;
}
if (f.isDirectory()) {
File file = f.openNextFile();
while (file) {
if (file.isDirectory()) {
write_log(log_path," DIR : ",10);
write_log(log_path,file.name(),10);
} else {
write_log(log_path," FILE: ",10);
write_log(log_path,file.name(),10);
write_log(log_path," SIZE: ",10);
write_log(log_path,String(file.size()),10);
if (SD_MMC.remove(file.name())) {
write_log(log_path," deleted.",10);
} else {
write_log(log_path," FAILED.",10);
}
}
file = f.openNextFile();
}
f.close();
if (SD_MMC.rmdir(val)) {
write_log(log_path,"Dir "+String(val)+" removed",10);
} else {
write_log(log_path,"Remove dir failed",10);
}
} else {
//Remove the file
if (SD_MMC.remove(val)) {
write_log(log_path,"File "+String(val)+" deleted",10);
} else {
write_log(log_path,"Delete failed",10);
}
}
}
void sdcard:: testwriet()
{
File file;
file = SD_MMC.open("/try.txt", "wb");
file.println("hello world");
file.flush();
file.close();
}
void sdcard::WriteStringToFile(String name,String Str)
{
File file;
file = SD_MMC.open(name, "w+");
file.println(Str);
file.flush();
file.close();
}
void sdcard::WriteStringToFile(String name,char *data,size_t lenth)
{
File file;
file = SD_MMC.open(name, "wb");
file.write((const byte *)data,lenth);
file.flush();
file.close();
}
bool sdcard::Mkdir(String path)
{
return SD_MMC.mkdir(path);
}
namespace sdcard
{
void openFileformWirte(String Path)
{
if (Comenfile.available())
{
Comenfile.close();
/* code */
}
Comenfile = SD_MMC.open(Path, "w+");
}
void WritetoFileCommen(String Str)
{
if (Comenfile.available())
{
Comenfile.print(Str);
Comenfile.flush();
/* code */
}
}
void WritetoFileCommen(char *data,size_t lenth)
{
if (Comenfile.available())
{
Comenfile.write((const byte *)data,lenth);
Comenfile.flush();
/* code */
}
}
void closeCommenFile()
{
if (Comenfile.available())
{
Comenfile.close();
/* code */
}
}
}

31
src/SDmanger.h Normal file
View File

@ -0,0 +1,31 @@
#ifndef SDMANGER_H
#define SDMANGER_H
#include "driver/sdmmc_host.h"
#include "driver/sdmmc_defs.h"
#include "sdmmc_cmd.h"
#include "esp_vfs_fat.h"
#include "FS.h"
#include <SD_MMC.h>
#include "Vector.h"
#include "log.h"
#include "Arduino.h"
#include "string.h"
namespace sdcard{
int init_sdcard();
void mylistDir( const char * dirname, uint8_t levels);
bool ListDir(const char * dirname,Vector <String> &stringlist);
void delete_old_stuff();
void deleteFolderOrFile(const char * val) ;
void testwriet();
void WriteStringToFile(String name,String Str);
void WriteStringToFile(String name,char *data,size_t lenth);
bool Mkdir(String path);
void openFileformWirte(String Path);
void WritetoFileCommen(String Str);
void WritetoFileCommen(char *data,size_t lenth);
void closeCommenFile();
}
#endif

1264
src/SensorIS11.cpp Normal file

File diff suppressed because it is too large Load Diff

80
src/SensorIS11.h Normal file
View File

@ -0,0 +1,80 @@
#ifndef SENSORIS11_H
#define SENSORIS11_H
#include <Arduino.h>
#include "comon.h"
#include "IS11Comon.h"
#include "log.h"
#include "Communication_Protocol.h"
#include "tuigan.h"
#include "servo.h"
#include "DS18B20.h"
#include "SoftwareSerial.h"
#include "SDmanger.h"
#include "ds1302.h"
#include "InterpolationLib.h"
#include "CastumullSpline.h"
class SensorIS11 {
public:
SensorIS11();
STRSensorInfo SensorInfo;
STRSensorInfo initSensor();
STRSensorInfo GetSensorInfo();
void SetShutter(int id);// 0 dark 1 green 2 blue
void GetOneDate(int msc);
int OptSnenser(int percent);
unsigned short DATABUFF[2048];
int shutterup,shutterdown;
unsigned short *DownData=nullptr;
unsigned short *UpData=nullptr;
void shortLittletoBiG( unsigned short *data,int lenth);
int Getmaxvalue(unsigned short *data,int lenth);
// void TakeOneJob();
void TakeOneJob1(bool dingbing);
void TakeOneJob();
void servo_direction(int direction);
void send_dn(HardwareSerial *wb485Serial,IS11_datastruct *IS11_datastructure,uint32_t fengbao_num);
void send_radiance(HardwareSerial *wb485Serial,IS11_datastruct *IS11_datastructure,uint32_t fengbao_num);
void senddata(HardwareSerial *wb485Serial,u_int32_t send_data_type,uint32_t fengbao_num);
void save_dingbiao(uint8_t * data);
void save_guangpu_data(IS11_datastruct * data);
// int dingbiao(u_int32_t step,u_int32_t shutter_timer);
void advanced_mode(u_int32_t direction,u_int32_t shutter_time,u_int32_t collect_times,u_int32_t remove_dark);
void opt(u_int32_t direction);
PRINTFUNC PrintFunc;
void send_chongcaiyang(HardwareSerial *wb485Serial,IS11_datastruct *IS11_datastructure,uint32_t fengbao_num);
void get_fanshelv();
void send_fanshelv(HardwareSerial *wb485Serial);
void calculation(float bochang1,float bochang2);
// Ds1302 ds1302;
volatile float calculation_value;
int shutternow;
u_int32_t index = 0;
volatile u_int32_t work_progress;
volatile u_int32_t dingbiao_shutter;
//uint16_t result[2048];
float chongcaiyang_step = 0.2;
clalidata_struct radiance_struct_up;
clalidata_struct radiance_struct_down;
u_char *DataRetrun;
};
#endif

206
src/TCPserver.cpp Normal file
View File

@ -0,0 +1,206 @@
#include "TCPserver.h"
bool fenge(String &zifuchuan, String &outstring, String fengefu)
{
int weizhi = 0; //找查的位置
if (zifuchuan == "")
{
// Serial.print("commanesdafasdf");
return false;
/* code */
}
weizhi = zifuchuan.indexOf(fengefu); //找到位置
if (weizhi != -1) //如果位置不为空
{
// Serial.println(zifuchuan);
outstring = zifuchuan.substring(0, weizhi); //打印取第一个字符
zifuchuan = zifuchuan.substring(weizhi + fengefu.length(), zifuchuan.length());
return true;
//分隔后只取后面一段内容 以方便后面找查
}
else
{
// Serial.print(zifuchuan);
outstring = zifuchuan;
zifuchuan = "";
return true;
}
}
TCPserver::TCPserver(int port)
{
server = new WiFiServer(port);
myserial = nullptr;
isPortOutInit = false;
}
#if ARDUINO_USB_CDC_ON_BOOT && !ARDUINO_USB_MODE
TCPserver::TCPserver(USBCDC *serial,int port)
{
server = new WiFiServer(port);
myserial = serial;
isPortOutInit = true;
}
#elif ARDUINO_USB_CDC_ON_BOOT && ARDUINO_USB_MODE
TCPserver::TCPserver(HWCDC *serial,int port)
{
server = new WiFiServer(port);
myserial = serial;
isPortOutInit = true;
}
#else
TCPserver::TCPserver(HardwareSerial *serial, int port /* args */)
{
server = new WiFiServer(port);
myserial = serial;
isPortOutInit = true;
}
#endif
void TCPserver::initme()
{
server->begin();
//关闭小包合并包功能,不会延时发送数据
server->setNoDelay(true);
}
void TCPserver::loop()
{
uint8_t i;
//检测是否有新的client请求进来
// myserial->print("asdffsd");
if (server->hasClient())
{
for (i = 0; i < MAX_SRV_CLIENTS; i++)
{
//释放旧无效或者断开的client
if (!serverClients[i] || !serverClients[i].connected())
{
if (serverClients[i])
{
serverClients[i].stop();
}
//分配最新的client
serverClients[i] = server->available();
if (isPortOutInit)
{
myserial->print("New client: ");
myserial->print(i);
/* code */
}
break;
}
}
//当达到最大连接数 无法释放无效的client,需要拒绝连接
if (i == MAX_SRV_CLIENTS)
{
WiFiClient serverClient = server->available();
serverClient.stop();
if (isPortOutInit)
{
myserial->print("Connection rejected ");
}
}
}
//检测client发过来的数据
for (i = 0; i < MAX_SRV_CLIENTS; i++)
{
if (serverClients[i] && serverClients[i].connected())
{
if (serverClients[i].available())
{
// get data from the telnet client and push it to the UART
String str = "";
while (serverClients[i].available())
{
//发送到串口调试器
if (isPortOutInit)
{
str = str + String((char)serverClients[i].read());
// myserial->write(serverClients[i].read());
/* code */
}
}
}
}
}
if (isPortOutInit)
{
if (myserial->available())
{
//把串口调试器发过来的数据 发送给client
size_t len = myserial->available();
uint8_t sbuf[len];
myserial->readBytes(sbuf, len);
// push UART data to all connected telnet clients
for (i = 0; i < MAX_SRV_CLIENTS; i++)
{
if (serverClients[i] && serverClients[i].connected())
{
serverClients[i].write(sbuf, len);
vTaskDelay(1);
}
}
}
}
}
void TCPserver::SendDataToClinet(String str, int clinetid)
{
// myserial->print("Connection rejected ");
if (clinetid == -1)
{
int i;
for (i = 0; i < MAX_SRV_CLIENTS; i++)
{
if (serverClients[i] && serverClients[i].connected())
{
serverClients[i].println(str);
vTaskDelay(1);
}
}
/* code */
}
else
{
if (serverClients[clinetid] && serverClients[clinetid].connected())
{
serverClients[clinetid].println(str);
vTaskDelay(1);
}
}
}
void TCPserver::SendDataToClinet(char *str, int clinetid)
{
// push UART data to all connected telnet clients
myserial->print("Connection rejected ");
if (clinetid == -1)
{
int i;
for (i = 0; i < MAX_SRV_CLIENTS; i++)
{
if (serverClients[i] && serverClients[i].connected())
{
serverClients[i].write(str);
vTaskDelay(1);
}
}
/* code */
}
else
{
if (serverClients[clinetid] && serverClients[clinetid].connected())
{
serverClients[clinetid].write(str);
vTaskDelay(1);
}
}
}
TCPserver::~TCPserver()
{
delete server;
}

49
src/TCPserver.h Normal file
View File

@ -0,0 +1,49 @@
#ifndef TCPSERVER_H
#define TCPSERVER_H
#include<HardwareSerial.h>
#ifdef ESP8266
#include <ESP8266WiFi.h>
#else
#include<WiFi.h>
#endif
#define MAX_SRV_CLIENTS 2
class TCPserver
{
private:
/* data */
//创建server 端口号是23
WiFiServer *server;
//管理clients
WiFiClient serverClients[MAX_SRV_CLIENTS];
bool isPortOutInit;
public:
#if ARDUINO_USB_CDC_ON_BOOT && !ARDUINO_USB_MODE //Serial used for USB CDC
USBCDC *myserial;
TCPserver(USBCDC *serial,int port);
#elif ARDUINO_USB_CDC_ON_BOOT && ARDUINO_USB_MODE
HWCDC *myserial;
TCPserver(HWCDC *serial,int port);
#else
HardwareSerial *myserial;
TCPserver(HardwareSerial *serial,int port);
#endif
TCPserver(int port);
void initme();
~TCPserver();
void SendDataToClinet(String str,int clinetid=-1);
void SendDataToClinet(char *str,int clinetid=-1);
void loop();
};
#endif

22
src/adc.cpp Normal file
View File

@ -0,0 +1,22 @@
#include "adc.h"
//电源电压测量
void adc_init()
{
pinMode(ADC_PIN,INPUT);
}
float adc_read()
{
float Value =0;
float power =0;
for(uint8_t i = 0; i < 10; i++)
{
Value = analogRead(ADC_PIN);
power += (Value * 3.3 / 4095.0) * 11;
}
power = power / 10.f + 0.51;
// write_log(log_path,"power: " + String(power),10);
return power;
}

10
src/adc.h Normal file
View File

@ -0,0 +1,10 @@
#ifndef ADC_H
#define ADC_H
#include <Arduino.h>
#include "log.h"
#define ADC_PIN 35
void adc_init();
float adc_read();
#endif

38
src/beep.cpp Normal file
View File

@ -0,0 +1,38 @@
#include "beep.h"
uint8_t chan;
uint8_t bit_num;
void beep_init(uint8_t beep_chan, uint32_t beep_freq, uint8_t beep_bit_num)
{
chan = beep_chan;
bit_num = beep_bit_num;
ledcSetup(chan, beep_freq , bit_num);
ledcAttachPin(BEEP_PIN, chan);
ledcWrite(chan, 0);
}
void beep_run( uint32_t freq,uint32_t duty)
{
ledcSetup(chan, freq , bit_num);
ledcWrite(chan, duty);
}
void beep_stop()
{
ledcWrite(chan, 0);
}
// beep_init(39,0,2000,10);
// while (1)
// {
// beep_run(2000,512);
// vTaskDelay(1000);
// beep_stop();
// vTaskDelay(1000);
// }
//开机成功长响3秒
//光谱仪故障一直滴滴声
//温度异常报警快速滴滴声
//其他功能异常慢速滴滴声

11
src/beep.h Normal file
View File

@ -0,0 +1,11 @@
#ifndef _BEEP_H_
#define _BEEP_H_
#include <Arduino.h>
#define BEEP_PIN 39
void beep_stop();
void beep_run( uint32_t freq,uint32_t duty);
void beep_init(uint8_t beep_chan, uint32_t beep_freq, uint8_t beep_bit_num);
#endif

34
src/comon.h Normal file
View File

@ -0,0 +1,34 @@
#include<Arduino.h>
// struct STRSensorInfo
// {
// std::string SensorName;
// long maxValue;
// long BandNum;
// std::string WavelenthStr;
// float *wavelenthlist;
// //double *wavelenth;
// bool isSensorInit;
// std::string serialnumber;
// float a1,a2,a3,a4;
// };
struct STRSensorInfo
{
String SensorName;
long maxValue;
long BandNum;
String WavelenthStr;
float *wavelenthlist;
//double *wavelenth;
bool isSensorInit;
String serialnumber;
float a1,a2,a3,a4;
};
typedef void (*PRINTFUNC)(std::string );

200
src/ds1302.cpp Normal file
View File

@ -0,0 +1,200 @@
/** Ds1302.cpp
*
* Ds1302 class.
*
* @version 1.0.3
* @author Rafa Couto <caligari@treboada.net>
* @license GNU Affero General Public License v3.0
* @see https://github.com/Treboada/Ds1302
*
*/
#include "ds1302.h"
#include <Arduino.h>
#define REG_SECONDS 0x80
#define REG_MINUTES 0x82
#define REG_HOUR 0x84
#define REG_DATE 0x86
#define REG_MONTH 0x88
#define REG_DAY 0x8A
#define REG_YEAR 0x8C
#define REG_WP 0x8E
#define REG_BURST 0xBE
Ds1302::Ds1302(uint8_t pin_ena, uint8_t pin_clk, uint8_t pin_dat)
{
_pin_ena = pin_ena;
_pin_clk = pin_clk;
_pin_dat = pin_dat;
_dat_direction = INPUT;
}
void Ds1302::init()
{
pinMode(_pin_ena, OUTPUT);
pinMode(_pin_clk, OUTPUT);
pinMode(_pin_dat, _dat_direction);
digitalWrite(_pin_ena, LOW);
digitalWrite(_pin_clk, LOW);
}
bool Ds1302::isHalted()
{
_prepareRead(REG_SECONDS);
uint8_t seconds = _readByte();
_end();
return (seconds & 0b10000000);
}
void Ds1302::getDateTime(DateTime* dt)
{
_prepareRead(REG_BURST);
dt->second = _bcd2dec(_readByte() & 0b01111111);
dt->minute = _bcd2dec(_readByte() & 0b01111111);
dt->hour = _bcd2dec(_readByte() & 0b00111111);
dt->day = _bcd2dec(_readByte() & 0b00111111);
dt->month = _bcd2dec(_readByte() & 0b00011111);
dt->dow = _bcd2dec(_readByte() & 0b00000111);
dt->year = _bcd2dec(_readByte() & 0b11111111);
_end();
}
void Ds1302::setDateTime(DateTime* dt)
{
_prepareWrite(REG_WP);
_writeByte(0b00000000);
_end();
_prepareWrite(REG_BURST);
_writeByte(_dec2bcd(dt->second % 60 ));
_writeByte(_dec2bcd(dt->minute % 60 ));
_writeByte(_dec2bcd(dt->hour % 24 ));
_writeByte(_dec2bcd(dt->day % 32 ));
_writeByte(_dec2bcd(dt->month % 13 ));
_writeByte(_dec2bcd(dt->dow % 8 ));
_writeByte(_dec2bcd(dt->year % 100));
_writeByte(0b10000000);
_end();
}
void Ds1302::halt()
{
_setHaltFlag(true);
}
void Ds1302::start()
{
_setHaltFlag(false);
}
void Ds1302::_setHaltFlag(bool stopped)
{
uint8_t regs[8];
_prepareRead(REG_BURST);
for (int b = 0; b < 8; b++) regs[b] = _readByte();
_end();
if (stopped) regs[0] |= 0b10000000; else regs[0] &= ~0b10000000;
regs[7] = 0b10000000;
_prepareWrite(REG_WP);
_writeByte(0b00000000);
_end();
_prepareWrite(REG_BURST);
for (int b = 0; b < 8; b++) _writeByte(regs[b]);
_end();
}
void Ds1302::_prepareRead(uint8_t address)
{
_setDirection(OUTPUT);
digitalWrite(_pin_ena, HIGH);
uint8_t command = 0b10000001 | address;
_writeByte(command);
_setDirection(INPUT);
}
void Ds1302::_prepareWrite(uint8_t address)
{
_setDirection(OUTPUT);
digitalWrite(_pin_ena, HIGH);
uint8_t command = 0b10000000 | address;
_writeByte(command);
}
void Ds1302::_end()
{
digitalWrite(_pin_ena, LOW);
}
uint8_t Ds1302::_readByte()
{
uint8_t byte = 0;
for(uint8_t b = 0; b < 8; b++)
{
if (digitalRead(_pin_dat) == HIGH) byte |= 0x01 << b;
_nextBit();
}
return byte;
}
void Ds1302::_writeByte(uint8_t value)
{
for(uint8_t b = 0; b < 8; b++)
{
digitalWrite(_pin_dat, (value & 0x01) ? HIGH : LOW);
_nextBit();
value >>= 1;
}
}
void Ds1302::_nextBit()
{
digitalWrite(_pin_clk, HIGH);
delayMicroseconds(1);
digitalWrite(_pin_clk, LOW);
delayMicroseconds(1);
}
void Ds1302::_setDirection(int direction)
{
if (_dat_direction != direction)
{
_dat_direction = direction;
pinMode(_pin_dat, direction);
}
}
uint8_t Ds1302::_dec2bcd(uint8_t dec)
{
return ((dec / 10 * 16) + (dec % 10));
}
uint8_t Ds1302::_bcd2dec(uint8_t bcd)
{
return ((bcd / 16 * 10) + (bcd % 16));
}

120
src/ds1302.h Normal file
View File

@ -0,0 +1,120 @@
/** Ds1302.h
*
* Ds1302 class.
*
* @version 1.0.3
* @author Rafa Couto <caligari@treboada.net>
* @license GNU Affero General Public License v3.0
* @see https://github.com/Treboada/Ds1302
*
*/
#ifndef _DS_1302_H
#define _DS_1302_H
#include <stdint.h>
class Ds1302
{
public:
typedef struct {
uint8_t year;
uint8_t month;
uint8_t day;
uint8_t hour;
uint8_t minute;
uint8_t second;
uint8_t dow;
} DateTime;
/**
* Months of year
*/
enum MONTH : uint8_t {
MONTH_JAN = 1,
MONTH_FEB = 2,
MONTH_MAR = 3,
MONTH_APR = 4,
MONTH_MAY = 5,
MONTH_JUN = 6,
MONTH_JUL = 7,
MONTH_AUG = 8,
MONTH_SEP = 9,
MONTH_OCT = 10,
MONTH_NOV = 11,
MONTH_DEC = 12
};
/**
* Days of week
*/
enum DOW : uint8_t {
DOW_MON = 1,
DOW_TUE = 2,
DOW_WED = 3,
DOW_THU = 4,
DOW_FRI = 5,
DOW_SAT = 6,
DOW_SUN = 7
};
/**
* Constructor (pin configuration).
*/
Ds1302(uint8_t pin_ena, uint8_t pin_clk, uint8_t pin_dat);
/**
* Initializes the DW1302 chip.
*/
void init();
/**
* Returns when the oscillator is disabled.
*/
bool isHalted();
/**
* Stops the oscillator.
*/
void halt();
/**
* Starts the oscillator.
*/
void start();
/**
* Returns the current date and time.
*/
void getDateTime(DateTime* dt);
/**
* Sets the current date and time.
*/
void setDateTime(DateTime* dt);
private:
uint8_t _pin_ena;
uint8_t _pin_clk;
uint8_t _pin_dat;
void _prepareRead(uint8_t address);
void _prepareWrite(uint8_t address);
void _end();
int _dat_direction;
void _setDirection(int direction);
uint8_t _readByte();
void _writeByte(uint8_t value);
void _nextBit();
uint8_t _dec2bcd(uint8_t dec);
uint8_t _bcd2dec(uint8_t bcd);
void _setHaltFlag(bool stopped);
};
#endif // _DS_1302_H

View File

@ -0,0 +1,62 @@
{
"folders": [
{
"path": ".."
}
],
"settings": {
"files.associations": {
"*.tpp": "cpp",
"sstream": "cpp",
"typeinfo": "cpp",
"array": "cpp",
"deque": "cpp",
"string": "cpp",
"unordered_map": "cpp",
"unordered_set": "cpp",
"vector": "cpp",
"string_view": "cpp",
"initializer_list": "cpp",
"*.tcc": "cpp",
"fstream": "cpp",
"utility": "cpp",
"ostream": "cpp",
"random": "cpp",
"atomic": "cpp",
"cctype": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"cstdarg": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"cwctype": "cpp",
"exception": "cpp",
"algorithm": "cpp",
"functional": "cpp",
"iterator": "cpp",
"map": "cpp",
"memory": "cpp",
"memory_resource": "cpp",
"numeric": "cpp",
"optional": "cpp",
"system_error": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"iomanip": "cpp",
"iosfwd": "cpp",
"istream": "cpp",
"limits": "cpp",
"new": "cpp",
"stdexcept": "cpp",
"streambuf": "cpp",
"cinttypes": "cpp",
"ratio": "cpp",
"thread": "cpp"
}
}
}

22
src/jiaresi.cpp Normal file
View File

@ -0,0 +1,22 @@
#include "jiaresi.h"
#include "log.h"
// 控制4组加热丝加热
// status 1:开始加热 0:停止加热
void jiaresi(unsigned char address ,enum jiare_status status)
{
if(status == start_jiare)
{
my74hc595_setpin(address , 1);
updatepin();
}
else
{
my74hc595_setpin(address, 0);
updatepin();
}
}

19
src/jiaresi.h Normal file
View File

@ -0,0 +1,19 @@
#ifndef _jiaresi_H_
#define _jiaresi_H_
#include "Arduino.h"
#include "my74hc595.h"
enum jiare_status
{
stop_jiare,
start_jiare
};
void jiaresi(unsigned char address ,enum jiare_status status);
#endif

81
src/log.cpp Normal file
View File

@ -0,0 +1,81 @@
#include "log.h"
/*
w+以纯文本方式读写,而wb+是以二进制方式进行读写。
mode说明:
w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
wb 只写方式打开或新建一个二进制文件,只允许写数据。
wb+ 读写方式打开或建立一个二进制文件,允许读和写。
r 打开只读文件,该文件必须存在,否则报错。
r+ 打开可读写的文件,该文件必须存在,否则报错。
rb+ 读写方式打开一个二进制文件,只允许读写数据。
a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。(EOF符保留)
a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 (原来的EOF符不保留)
ab+ 读写打开一个二进制文件,允许读或在文件末追加数据。
加入b 字符用来告诉函数库打开的文件为二进制文件,而非纯文字文件。
*/
// SoftwareSerial wb485Serial(wb485PORT_RX,wb485PORT_TX,false);
// void log_init()
// {
// }
#ifdef ARDUINO_USB_CDC_ON_BOOT
#define U0_Serial Serial
#else
SoftwareSerial U0_Serial(19,20,false);
#endif
void log_init()
{
U0_Serial.begin(115200);
}
void write_log(String path,String write_data,unsigned char level)
{
if(level <15) {
U0_Serial.println(write_data);
}
if (level == 20)
{
U0_Serial.println(write_data);
File file;
file = SD_MMC.open(path,"ab+");
file.println(write_data);
file.flush();
file.close();
}
}
void write_log(uint8_t *data,uint32_t size)
{
U0_Serial.write(data,size);
}
void save_data(String path,String write_data)
{
File file;
file = SD_MMC.open(path,"w+");
file.println(write_data);
file.flush();
file.close();
}

28
src/log.h Normal file
View File

@ -0,0 +1,28 @@
#ifndef _LOG_H_
#define _LOG_H_
#include "SDmanger.h"
#include <SoftwareSerial.h>
#define log_path "/log/log.log"
#define gp_log "/gp.log"
#define log_level 10
#define log_level_1 0 //打印到串口
#define log_level_2 5 //写入文件
#define log_level_3 10 //打印到串口和写入文件
void log_init();
void write_log(String path,String write_data,unsigned char level);
void save_data(String path,String write_data);
void write_log(uint8_t *data,uint32_t size);
// void my_println(String data,int level);
#endif

3099
src/main.cpp Normal file

File diff suppressed because it is too large Load Diff

158
src/my74hc595.cpp Normal file
View File

@ -0,0 +1,158 @@
#include "my74hc595.h"
// // #define SHCP 34
// // #define STCP 33
// // #define DS 35
// // int data=100;
// // uint8_t value[8] = {1, 1, 1, 1, 1, 1, 0, 0};
// // void writeto74()
// // {
// // digitalWrite(STCP, LOW);
// // // delay(1);
// // // vTaskDelay(1);
// // for (int i = 0; i < 8; i++)
// // {
// // digitalWrite(SHCP, LOW);
// // // delay(1);
// // // vTaskDelay(1);
// // for(int j = 0; j < 1500; j++)
// // {
// // }
// // digitalWrite(DS, value[i]);
// // // delay(1);
// // // vTaskDelay(1);
// // for(int i = 0; i < 1500; i++)
// // {
// // }
// // digitalWrite(SHCP, HIGH);
// // }
// // // delay(1);
// // // vTaskDelay(1);
// // digitalWrite(STCP, HIGH);
// // }
// // #define SHCP 33
// // #define STCP 34
// // #define DS 35
// // int data=100;
// // uint8_t value[8] = {0, 0, 0, 0, 0, 0, 0, 0};
// // void writeto74()
// // {
// // digitalWrite(STCP, LOW);
// // // delay(1);
// // // vTaskDelay(1);
// // for (int i = 0; i < 8; i++)
// // {
// // digitalWrite(SHCP, LOW);
// // digitalWrite(DS, value[i]);
// // // for(int j = 0; j < 1500; j++)
// // // {
// // // }
// // digitalWrite(SHCP, HIGH);
// // // for(int i = 0; i < 1500; i++)
// // // {
// // // }
// // // digitalWrite(DS, 0);
// // }
// // // delay(1);
// // // vTaskDelay(1);
// // digitalWrite(STCP, HIGH);
// // }
// void updatepin()
// {
// writeto74();
// }
// bool my74hc595_setpin(int index, bool val)
// {
// if (index < 0 || index > 7)
// {
// return false;
// }
// value[index] = val;
// updatepin();
// return true;
// }
// void my74hc595_init(){
// pinMode(SHCP, OUTPUT);
// pinMode(STCP, OUTPUT);
// pinMode(DS, OUTPUT);
// digitalWrite(SHCP, LOW);
// digitalWrite(STCP, LOW);
// digitalWrite(DS, LOW);
// updatepin();
// tuigan(suo);
// }
// void my74hc595_setallpin(bool val)
// {
// for (size_t i = 0; i < 8; i++)
// {
// value[i] = val;
// // my74hc595_setpin(i, value);
// /* code */
// }
// updatepin();
// }
#define SHCP 33
#define STCP 34
#define DS 35
uint8_t data=0x00;
void my74hc595_init(){
pinMode(SHCP, OUTPUT);
pinMode(STCP, OUTPUT);
pinMode(DS, OUTPUT);
digitalWrite(SHCP, LOW);
digitalWrite(STCP, LOW);
digitalWrite(DS, LOW);
updatepin();
tuigan(suo);
vTaskDelay(1000 * 10);
}
bool my74hc595_setpin(int index, bool val)
{
if (index < 0 || index > 7)
{
return false;
}
if(val)
{
data |= (1 << index);
}
else
{
data &= ~(1 << index);
}
return true;
}
void updatepin()
{
digitalWrite(STCP, LOW);
shiftOut(DS, SHCP, MSBFIRST, data);
digitalWrite(STCP, HIGH);
}

13
src/my74hc595.h Normal file
View File

@ -0,0 +1,13 @@
#ifndef _MY74HC595_H
#define _MY74HC595_H
#include "Arduino.h"
#include "jiaresi.h"
#include "log.h"
#include "tuigan.h"
void my74hc595_init();
// void my74hc595_setallpin(bool value);
bool my74hc595_setpin(int index, bool val);
void updatepin();
#endif

80
src/servo.cpp Normal file
View File

@ -0,0 +1,80 @@
#include "servo.h"
uint8_t channel;
float now_angle,servo_offset_angle_up = 0,servo_offset_angle_down = 0;
void servo_init(uint8_t servo_pin,uint8_t servo_channel)
{
int servo_freq = 50; // 频率(20ms周期)
int servo_resolution = 12; // 分辨率(8 ~ 16)
channel = servo_channel;
ledcSetup(servo_channel, servo_freq, servo_resolution);
ledcAttachPin(servo_pin, servo_channel);
servo_set_angle(0);
}
int calculatePWM(float degree)
{
if (degree < 0)
degree = 0;
if (degree > 360)
degree = 360;
return (degree / 360.0) * 410 + 103.0;
}
void servo_off()
{
ledcWrite(channel,0);
}
void servo_set_angle(float angle)
{
now_angle = angle;
ledcWrite(channel, calculatePWM(angle));
}
//获取舵机的角度
float servo_get_angle()
{
return now_angle;
}
void servo_up()
{
float a = 180 + servo_offset_angle_up;
if(a < 0 || a > 270) a = 180;
// servo_set_angle(200);
// servo_set_angle(213);
servo_set_angle(a);
}
void servo_down()
{
float a = 0 + servo_offset_angle_down;
if(a < 0 || a > 270) a = 0;
// servo_set_angle(12);
// servo_set_angle(28);
servo_set_angle(a);
}
/// @brief
/// @param dir 0 down 1 up
/// @param angle
void servo_offset(float angle,uint8_t dir)
{
switch (dir)
{
case 0:
servo_offset_angle_down = angle;
servo_down();
break;
case 1:
servo_offset_angle_up = angle;
servo_up();
break;
default:
break;
}
}

16
src/servo.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef _SERVO_H_
#define _SERVO_H_
#include <Arduino.h>
void servo_init(uint8_t servo_pin,uint8_t servo_channel);
int calculatePWM(float degree);
void servo_set_angle( float angle );
float servo_get_angle();
void servo_off();
void servo_up();
void servo_down();
void servo_offset(float angle,uint8_t dir);
#endif

123
src/slave.cpp Normal file
View File

@ -0,0 +1,123 @@
#include "slave.h"
double new_emissivity =0.95;
Adafruit_MLX90614 mlx = Adafruit_MLX90614();
TwoWire wireme(0);
u_char a[]={0x01,0x04,0x00,0x00,0x00 ,0x06,0x70,0x08};
u_char yuliang[]={0x02, 0x03, 0x00, 0x00 ,0x00, 0x01, 0x84, 0x39};
u_char ClearYL[]={0x02,0x06,0x00, 0x00 ,0x00 ,0x5A ,0X09 ,0Xc2};
u_char yuliangfuliangdu[]={0x02,0x03,0x00,0x02,0x00,0x02,0x65,0xf8};
u_char openGNRMC[]={0xF1,0xD9,0x06,0x01,0x03,0x00,0xF0,0x05,0x01,0x00,0x1A};
u_char gpsSaveConfig[]={0xF1,0xD9,0x06,0x09,0x08,0x00,0x00,0x00,0x00,0x00,0x2F,0x00,0x00,0x00,0x46,0xB7};
SoftwareSerial *my485Port;
void slave::init(int8_t MY485PORT_RX,int8_t MY485PORT_TX){
// put your setup code here, to run once:
//Wire.begin(4,5);
// Serial.println("slave init ...");
write_log(log_path,"slave init ...",10);
my485Port = new SoftwareSerial(MY485PORT_RX ,MY485PORT_TX,false);
my485Port->begin(9600, SWSERIAL_8N1, MY485PORT_RX, MY485PORT_TX, false);
///////////// 光谱电源控制,重启
pinMode(36,OUTPUT);
digitalWrite(36,LOW);
vTaskDelay(2000);
digitalWrite(36,HIGH);
// GPSSeiral.begin(115200, SWSERIAL_8N1, 2, 12, false);
wireme.setPins(7,8);
if (!mlx.begin(MLX90614_I2CADDR,&wireme)) {
// Serial.println("Error connecting to MLX sensor. Check wiring.");
write_log(log_path,"Error connecting to MLX sensor. Check wiring.",10);
//while (1);
};
mlx.writeEmissivity(new_emissivity); // this does the 0x0000 erase write
// Serial.println(sizeof(openGNRMC));
write_log(log_path,String(sizeof(openGNRMC)),10);
}
double slave::getMLX(){
double a = mlx.readObjectTempC();
return a;
// Serial.write((char*) &a,8);
}
void slave::getWehter(){
while (my485Port->read()!=-1);
my485Port->write(a,8);
vTaskDelay(90);
for (int j = 0; j <17 ; ++j) {
ret[j]=my485Port->read();
}
float VV=(ret[3]*256+ret[4])*1.0/100;
float DD=(ret[5]*256+ret[6])*1.0/10;
float TT=(ret[7]*256+ret[8])*1.0/100;
float HH=(ret[9]*256+ret[10])*1.0/100;
long PP=(ret[13]*256+ret[14])*256*256+(ret[11]*256+ret[12]);
#ifdef DEBG
String str_getWehter = "VV:"+String(VV)+" DD:"+String(DD)+" TT:"+String(TT)+" HH:"+String(HH)+" PP:"+String(PP);
// return str;
// Serial.println("VV:"+String(VV)+" DD:"+String(DD)+" TT:"+String(TT)+" HH:"+String(HH)+" PP:"+String(PP));
#endif
// Serial.write(ret,17);
}
float slave::getYuliang(){
while (my485Port->read()!=-1);
my485Port->write(yuliang,8);
vTaskDelay(90);
for (int j = 0; j <7; ++j) {
ret[j]=my485Port->read();
}
float Value=ret[3]*256+ret[4];
Value=Value/10;
// Serial.write(ret,7);
// Serial.print(Value);
// Serial.print("#");
return Value;
}
int32_t slave::getYuliangfuliang(){
while (my485Port->read()!=-1);
my485Port->write(yuliangfuliangdu,8);
vTaskDelay(90);
for (int j = 0; j <7; ++j) {
ret[j]=my485Port->read();
}
int32_t Value=(ret[3]*256+ret[4])*256*256+ret[5]*256+ret[6];
// Value=Value/10;
// Serial.write(ret,7);
// Serial.print(Value);
// Serial.print("#");
return Value;
}
/// 返回1,表示ok
uint8_t slave::claeryuliang(){
while (my485Port->read()!=-1);
my485Port->write(ClearYL,8);
vTaskDelay(90);
for (int j = 0; j <8; ++j) {
ret[j]=my485Port->read();
}
// Serial.print("OK");
return 1;
}

30
src/slave.h Normal file
View File

@ -0,0 +1,30 @@
#ifndef _SLAVE_H_
#define _SLAVE_H_
#include <Arduino.h>
#include "SoftwareSerial.h"
#include "Wire.h"
#include <Adafruit_MLX90614.h>
//#define DEBUG_SERIAL Serial
#include <SPI.h>
#include "SparkFun_Ublox_Arduino_Library.h"
#include "log.h"
class slave
{
public:
u_char ret[17];
String str_getWehter;
void init(int8_t MYPORT_RX,int8_t MYPORT_TX);
double getMLX();
void getWehter();
float getYuliang();
int32_t getYuliangfuliang();
uint8_t claeryuliang();
};
#endif

30
src/tuigan.cpp Normal file
View File

@ -0,0 +1,30 @@
#include "tuigan.h"
#include "log.h"
// //status 0:伸 1:缩
uint8_t tuigan_sta;
void tuigan(enum tuigan_status status)
{
if(status == tui)
{
my74hc595_setpin(0, 0);
my74hc595_setpin(1, 1);
updatepin();
tuigan_sta = tui;
}
else
{
my74hc595_setpin(0, 1);
my74hc595_setpin(1, 0);
updatepin();
tuigan_sta = suo;
}
}
uint8_t get_tuigan_status()
{
return tuigan_sta;
}

17
src/tuigan.h Normal file
View File

@ -0,0 +1,17 @@
#ifndef _TUIGAN_H_
#define _TUIGAN_H_
#include "Arduino.h"
#include "my74hc595.h"
enum tuigan_status
{
tui,
suo
};
void tuigan(enum tuigan_status status);
uint8_t get_tuigan_status();
#endif

233
src/updatebyme.cpp Normal file
View File

@ -0,0 +1,233 @@
#include "updatebyme.h"
#include "SDmanger.h"
void UpDateClassByme::performUpdate(Stream &updateSource, size_t updateSize)
{
if (Update.begin(updateSize))
{
Serial.println("Writes : ");
size_t written = Update.writeStream(updateSource);
if (written == updateSize)
{
Serial.println("Writes : " + String(written) + " successfully");
}
else
{
Serial.println("Written only : " + String(written) + "/" + String(updateSize) + ". Retry?");
}
if (Update.end())
{
Serial.println("OTA finished!");
if (Update.isFinished())
{
Serial.println("Restart ESP device!");
abort();
}
else
{
Serial.println("OTA not fiished");
}
}
else
{
Serial.println("Error occured #: " + String(Update.getError()));
}
}
else
{
Serial.println("Cannot beggin update");
}
}
size_t UpDateClassByme::DownloadFirmwareForurl(String version)
{
String url="/weather/firmware/esp32/firmware_"+version+".bin";
int err = http->get(url.c_str());
if (err != 0)
{
Serial.println(F("Date failed to connect"));
vTaskDelay(10000);
return 0;
}
int status = http->responseStatusCode();
if (!status)
{
vTaskDelay(10000);
return 0;
}
Serial.print(F("Response status code: "));
Serial.println(status);
// SerialMon.println(F("Response Headers:"));
size_t count=0;
while (http->headerAvailable())
{
String headerName = http->readHeaderName();
String headerValue = http->readHeaderValue();
Serial.println("Date: " + headerName + " : " + headerValue);
if (headerName=="Content-Length")
{
count=headerValue.toInt();
/* code */
}
}
Serial.println("lenth is "+String(count));
if (http->isResponseChunked())
{
Serial.println(F("Date The response is chunked"));
}
char *str=new char[1000];
int lent=count/1000;
File file;
file = SD_MMC.open("/update.bin", "wb");
for (size_t i = 0; i < lent; i++)
{
http->readBytes(str,1000);
file.write((const byte *)str,1000);
Serial.print("download ");
Serial.println(String(i*100/lent));
/* code */
}
http->readBytes(str,count%1000);
file.write((const byte *)str,count%1000);
file.flush();
file.close();
//performUpdate(*http,cout);
// http->readBytes
Serial.println("adfasdfsadfsdfsd");
//Serial.write(str,cout);
//Serial.println(body.length());
http->stop();
return count;
// return body;
}
void UpDateClassByme::initme(String Version)
{
CurrentVersion=Version;
}
void UpDateClassByme::updateversion()
{
String Targetversion=GetValueFromNet("/weather/php/upVserion.php",StationID+":"+CurrentVersion);
}
bool UpDateClassByme::CheckAndUpdate()
{
String Targetversion=GetValueFromNet("/weather/php/GetVserion.php",StationID);
if ( Targetversion=="0"||Targetversion==CurrentVersion||Targetversion=="")
{
return true;
}
Serial.println("targetvesion is:"+Targetversion);
//size_t countdownload1=375584;
size_t countdownload1=DownloadFirmwareForurl(Targetversion);
if (countdownload1<10000)
{
return false;
}
Serial.println("count download is:"+String(countdownload1));
String MD5=GetValueFromNet("/weather/php/GetMD5Value.php",Targetversion);
if (MD5=="0")
{
return false;
}
// updater.setMD5(MD5);
MD5Builder md5my;
File file;
file = SD_MMC.open("/update.bin", "rb");
md5my.begin();
md5my.addStream(file,countdownload1);
md5my.calculate();
String md5com=md5my.toString();
Serial.println("md5 comput is:"+md5my.toString());
Serial.println("md5 should is:"+MD5);
file.close();
if (MD5==md5com)
{
file = SD_MMC.open("/update.bin", "rb");
performUpdate(file,countdownload1);
return true;
/* code */
}
return true;
}
UpDateClassByme::UpDateClassByme(HttpClient *httptm)
{
http=httptm;
StationID="000";
}
String UpDateClassByme::GetValueFromNet(String url,String Key)
{
http->beginRequest();
http->post(url.c_str());
http->sendHeader(HTTP_HEADER_CONTENT_LENGTH, Key.length());
http->endRequest();
int err = http->write((const byte *)Key.c_str(), Key.length());
Serial.print("send date size");
Serial.println(err);
if (err == 0)
{
http->stop();
return "-1";
}
int status = http->responseStatusCode();
if (!status)
{
http->stop();
return "-1";
}
int length = http->contentLength();
if (length == 0)
{
http->stop();
return "-1";
}
String body = http->responseBody();
Serial.println("body:"+body);
http->stop();
return body;
}

23
src/updatebyme.h Normal file
View File

@ -0,0 +1,23 @@
#ifndef UPDATEBYME_H
#define UPDATEBYME_H
#include<Update.h>
#include <HTTPClient.h>
class UpDateClassByme{
public:
UpdateClass updater;
UpDateClassByme(HttpClient *httptm);
void performUpdate(Stream &updateSource, size_t updateSize);
HttpClient *http;
size_t DownloadFirmwareForurl(String version);
String CurrentVersion;
void initme(String Version);
bool CheckAndUpdate();
String StationID;
String GetValueFromNet(String url,String Key);
void updateversion();
};
#endif

41
src/wifidebug.cpp Normal file
View File

@ -0,0 +1,41 @@
#include <wifidebug.h>
#include<TCPserver.h>
#ifdef DebugCalibration
const char *ssid = "SmartForCalibration";
const char *password = "123456789";
IPAddress local_IP(192, 168, 1,2);
IPAddress gateway(192, 168, 1, 2);
IPAddress subnet(255, 255, 255, 0);
TCPserver *tcpserver;
void beginWIFI(){
tcpserver=new TCPserver(23);
WiFi.mode( WIFI_MODE_AP );
Serial.println("init webserver ok 33333");
WiFi.softAPConfig(local_IP, gateway, subnet);
boolean result = WiFi.softAP(ssid, password);
tcpserver->loop();
}
void tcploop(){
tcpserver->loop();
}
void printbytcpserver(String str)
{
tcpserver->SendDataToClinet(str);
tcpserver->loop();
// Serial.println(str);
}
#endif
#ifndef DebugCalibration
void beginWIFI(){}
void printbytcpserver(String str){}
void tcploop(){}
#endif

16
src/wifidebug.h Normal file
View File

@ -0,0 +1,16 @@
#include"Arduino.h"
#include"Define.h"
#ifdef DebugCalibration
#include"WiFi.h"
#endif
void beginWIFI();
void printbytcpserver(String str);
void tcploop();