Files
newspark110/device/SerialPort/PowerMeter.cpp
Chenwenxuan edac2715f0 init
2024-03-06 14:54:30 +08:00

106 lines
2.4 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "PowerMeter.h"
PowerMeter* PowerMeter::uniqueInstanceMach = nullptr;
PowerMeter* PowerMeter::uniqueInstanceLight = nullptr;
PowerMeter* PowerMeter::MachInstance()
{
if (!uniqueInstanceMach) {
uniqueInstanceMach = new PowerMeter();
}
return uniqueInstanceMach;
}
PowerMeter* PowerMeter::LightInstance()
{
if (!uniqueInstanceLight) {
uniqueInstanceLight = new PowerMeter();
}
return uniqueInstanceLight;
}
PowerMeter::PowerMeter()
{
}
PowerMeter::~PowerMeter()
{
}
//int PowerMeter::GetValue(char *data, unsigned short data_len,float * Value)
int PowerMeter::GetValue(float * Value)
{
int ret;
char cmd[50];
char revBuf[50] = {0};
::EnterCriticalSection(&mCsRead);
memset(revData,0,4096);
sprintf_s(cmd, "$POW\r\n");
ret = SendCmd(reinterpret_cast<char*>(cmd), strlen(cmd) ,reinterpret_cast<unsigned char*>(revData), &revDataLen);
if (ret == 0)
{
//revData[strlen(revData) - 2] = 0;
memcpy_s(revBuf,50,revData,strlen(revData));
for (int i=0;i<(int)strlen(revData);i++)
{
if ((revData[i] == '\r') || (revData[i] == '\n'))
revBuf[i] = 0;
}
*Value = convert(revBuf);
}
::LeaveCriticalSection(&mCsRead);
return ret;
}
float PowerMeter::convert(char *num)
{
//printf("开始转换%s\n", num);
float num1 = 0.0, num2 = 0.0;
int sign = 1;
int exp = 1, cishu = 0;
//表示e后面是正号还是负号正号为1负号为-1
//cishu表示是几次饭
char *p = num;
if (*p == '-') {
sign = -1;
p++;
//如果小数是复数
}
while (isdigit(*p)) {
num1 = num1 * 10 + *p - '0';
p++;
//小数点前面的部分
}
//printf("num1:%f\n", num1);
float i = 0.1;
p++;
while (isdigit(*p)) {
num2 += i * (*p - '0');
i *= 0.1;
p++;
}
//小数点后面的部分
//printf("num2:%f\n", num2);
if (*p == 'e' || *p == 'E')
p++;
if (*p == '-') {
exp = -1;
p++;
}
else if (*p == '+')p++;
while (*p != '\0') {
cishu = cishu * 10 + *p - '0';
p++;
}
//printf("cishu:%d\n", cishu);
float result = sign * (num1 + num2);
if (exp == -1) i = 0.1;
else i = 10;
for (int j = 0; j < cishu; j++) result *= i;
return result;
}