liuguijing 3 months ago
commit 56d42d8774

@ -5,7 +5,7 @@ plugins {
// 10,00,000 major-minor-build // 10,00,000 major-minor-build
def AppMajorVersion = 1 def AppMajorVersion = 1
def AppMinorVersion = 3 def AppMinorVersion = 3
def AppBuildNumber = 75 def AppBuildNumber = 86
def AppVersionName = AppMajorVersion + "." + AppMinorVersion + "." + AppBuildNumber def AppVersionName = AppMajorVersion + "." + AppMinorVersion + "." + AppBuildNumber
def AppVersionCode = AppMajorVersion * 100000 + AppMinorVersion * 1000 + AppBuildNumber def AppVersionCode = AppMajorVersion * 100000 + AppMinorVersion * 1000 + AppBuildNumber
@ -130,6 +130,7 @@ dependencies {
implementation 'androidx.legacy:legacy-support-v13:1.0.0' implementation 'androidx.legacy:legacy-support-v13:1.0.0'
// implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" // implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.0' implementation 'androidx.appcompat:appcompat:1.0.0'
// implementation "androidx.core:core:1.10.0" // 使
implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.android.material:material:1.8.0' implementation 'com.google.android.material:material:1.8.0'
implementation project(path: ':common') implementation project(path: ':common')

@ -61,7 +61,7 @@ size_t GpioControl::turnOnImpl(const IOT_PARAM& param)
SetCamerastatus(param.cmd, true); SetCamerastatus(param.cmd, true);
} }
if (oldRef == 0 || param.cmd != CMD_SET_3V3_PWR_EN) if (oldRef == 0/* || param.cmd != CMD_SET_3V3_PWR_EN*/)
{ {
fd = open(GPIO_NODE_MP, O_RDONLY); fd = open(GPIO_NODE_MP, O_RDONLY);
if( fd > 0 ) if( fd > 0 )
@ -69,9 +69,9 @@ size_t GpioControl::turnOnImpl(const IOT_PARAM& param)
res = ioctl(fd, IOT_PARAM_WRITE, &param); res = ioctl(fd, IOT_PARAM_WRITE, &param);
close(fd); close(fd);
#ifdef OUTPUT_DBG_INFO #ifdef OUTPUT_DBG_INFO
XYLOG(XYLOG_SEVERITY_INFO, "setInt cmd=%d,value=%d,result=%d",param.cmd, param.value, param.result); int realVal = getInt(param.cmd);
XYLOG(XYLOG_SEVERITY_INFO, "setInt cmd=%d,value=%d,result=%d RealVal=%d",param.cmd, param.value, param.result, realVal);
#endif #endif
} }
#ifdef _DEBUG #ifdef _DEBUG
ALOGI("PWR TurnOn cmd=%d,result=%d ref=%u\r\n",param.cmd, param.result, (uint32_t)references); ALOGI("PWR TurnOn cmd=%d,result=%d ref=%u\r\n",param.cmd, param.result, (uint32_t)references);
@ -95,7 +95,7 @@ void GpioControl::setInt(int cmd, int value)
close(fd); close(fd);
#ifdef OUTPUT_DBG_INFO #ifdef OUTPUT_DBG_INFO
int realVal = getInt(param.cmd); int realVal = getInt(param.cmd);
XYLOG(XYLOG_SEVERITY_INFO, "setInt cmd=%d,value=%d,result=%d RealVal=%d",param.cmd, param.value, param.result, realVal); XYLOG(XYLOG_SEVERITY_INFO, "setInt cmd=%d,value=%d,result=%d RealVal=%d",param.cmd, value, param.result, realVal);
#endif #endif
} }
} }

@ -598,7 +598,7 @@ public:
PowerControl(CMD_SET_OTG_STATE, CMD_SET_NETWORK_POWER_EN, CMD_SET_PIC1_POWER, CMD_SET_485_EN_STATE, closeDelayTime) PowerControl(CMD_SET_OTG_STATE, CMD_SET_NETWORK_POWER_EN, CMD_SET_PIC1_POWER, CMD_SET_485_EN_STATE, closeDelayTime)
#else // USING_N938 #else // USING_N938
#ifdef USING_PLZ #ifdef USING_PLZ
PowerControl(CMD_SET_3V3_PWR_EN, CMD_SET_5V_PWR_ENABLE, CMD_SET_OTG_STATE, CMD_SET_485_ENABLE, CMD_SET_100M_ENABLE, CMD_SET_PTZ_PWR_ENABLE, CMD_SET_12V_EN_STATE, CMD_SET_100M_SWITCH_PWR_ENABLE, closeDelayTime) PowerControl(CMD_SET_3V3_PWR_EN, CMD_SET_OTG_STATE, CMD_SET_485_ENABLE, CMD_SET_PTZ_PWR_ENABLE, CMD_SET_12V_EN_STATE, CMD_SET_100M_SWITCH_PWR_ENABLE, closeDelayTime)
#else // USING_PLZ #else // USING_PLZ
PowerControl(CMD_SET_OTG_STATE, CMD_SET_12V_EN_STATE, closeDelayTime) PowerControl(CMD_SET_OTG_STATE, CMD_SET_12V_EN_STATE, closeDelayTime)
#endif // USING_PLZ #endif // USING_PLZ
@ -615,7 +615,8 @@ public:
PowerControl(CMD_SET_OTG_STATE, CMD_SET_NETWORK_POWER_EN, closeDelayTime) PowerControl(CMD_SET_OTG_STATE, CMD_SET_NETWORK_POWER_EN, closeDelayTime)
#else // USING_N938 #else // USING_N938
#ifdef USING_PLZ #ifdef USING_PLZ
PowerControl(CMD_SET_3V3_PWR_EN, CMD_SET_OTG_STATE, CMD_SET_5V_PWR_ENABLE, CMD_SET_100M_ENABLE, CMD_SET_100M_SWITCH_PWR_ENABLE, closeDelayTime) // PowerControl(CMD_SET_3V3_PWR_EN, CMD_SET_OTG_STATE, CMD_SET_5V_PWR_ENABLE, CMD_SET_100M_ENABLE, CMD_SET_100M_SWITCH_PWR_ENABLE, closeDelayTime)
PowerControl(CMD_SET_3V3_PWR_EN, CMD_SET_OTG_STATE, CMD_SET_100M_SWITCH_PWR_ENABLE, closeDelayTime)
#else // USING_PLZ #else // USING_PLZ
// Micro Photo // Micro Photo
PowerControl(CMD_SET_OTG_STATE, CMD_SET_485_EN_STATE/* Only for wp6*/, closeDelayTime) PowerControl(CMD_SET_OTG_STATE, CMD_SET_485_EN_STATE/* Only for wp6*/, closeDelayTime)

@ -488,7 +488,7 @@ int32_t CPhoneDevice::CJpegCamera::getOutputFormat() const
} }
CPhoneDevice::CPhoneDevice(JavaVM* vm, jobject service, const std::string& appPath, uint64_t activeNetHandle, unsigned int versionCode, const std::string& nativeLibDir) CPhoneDevice::CPhoneDevice(JavaVM* vm, jobject service, const std::string& appPath, uint64_t activeNetHandle, unsigned int versionCode, const std::string& nativeLibDir)
: mVersionCode(versionCode), m_nativeLibraryDir(nativeLibDir), m_network(NULL), m_defNetHandle(activeNetHandle), m_ethnetHandle(NETWORK_UNSPECIFIED) : mVersionCode(versionCode), m_nativeLibraryDir(nativeLibDir), m_network(NULL), m_defNetHandle(activeNetHandle), m_ethnetHandle(NETWORK_UNSPECIFIED), m_ethernetFailures(0)
{ {
mCamera = NULL; mCamera = NULL;
m_listener = NULL; m_listener = NULL;
@ -534,7 +534,7 @@ CPhoneDevice::CPhoneDevice(JavaVM* vm, jobject service, const std::string& appPa
mRequestWakelockMid = env->GetMethodID(classService, "requestWakelock", "(Ljava/lang/String;J)V"); mRequestWakelockMid = env->GetMethodID(classService, "requestWakelock", "(Ljava/lang/String;J)V");
mReleaseWakelockMid = env->GetMethodID(classService, "releaseWakelock", "(Ljava/lang/String;)V"); mReleaseWakelockMid = env->GetMethodID(classService, "releaseWakelock", "(Ljava/lang/String;)V");
mGetSystemInfoMid = env->GetMethodID(classService, "getSystemInfo", "()Ljava/lang/String;"); mGetFlowInfoMid = env->GetMethodID(classService, "getFlowInfo", "()Ljava/lang/String;");
mInstallAppMid = env->GetMethodID(classService, "installApp", "(Ljava/lang/String;J)Z"); mInstallAppMid = env->GetMethodID(classService, "installApp", "(Ljava/lang/String;J)Z");
mRebootMid = env->GetMethodID(classService, "reboot", "(IJLjava/lang/String;)V"); mRebootMid = env->GetMethodID(classService, "reboot", "(IJLjava/lang/String;)V");
mEnableGpsMid = env->GetMethodID(classService, "enableGps", "(Z)V"); mEnableGpsMid = env->GetMethodID(classService, "enableGps", "(Z)V");
@ -886,6 +886,7 @@ bool CPhoneDevice::QuerySystemProperties(std::map<std::string, std::string>& pro
std::map<std::string, std::string> powerInfo; std::map<std::string, std::string> powerInfo;
int res = 0; int res = 0;
int bv = -1; int bv = -1;
std::map<std::string, std::string> flowInfo;
for (std::map<std::string, std::string>::iterator it = properties.begin(); it != properties.end(); ++it) for (std::map<std::string, std::string>::iterator it = properties.begin(); it != properties.end(); ++it)
{ {
@ -1045,12 +1046,24 @@ bool CPhoneDevice::QuerySystemProperties(std::map<std::string, std::string>& pro
{ {
it->second = std::to_string(m_signalLevel); it->second = std::to_string(m_signalLevel);
} }
else if ((it->first == (PROP_MOBILE_FLOW_TX)) || (it->first == (PROP_MOBILE_FLOW_RX)))
{
if (flowInfo.empty())
{
QueryFlowInfo(flowInfo);
}
auto it2 = flowInfo.find(it->first);
if (it2 != flowInfo.cend())
{
it->second = it2->second;
}
}
/* /*
else if (startsWith(it->first, PROP_JAVA_PREFIX)) else if (startsWith(it->first, PROP_JAVA_PREFIX))
{ {
if (powerInfo.empty()) if (powerInfo.empty())
{ {
QueryPowerInfo(powerInfo); QueryFlowInfo(powerInfo);
} }
auto it2 = powerInfo.find(it->first); auto it2 = powerInfo.find(it->first);
if (it2 != powerInfo.cend()) if (it2 != powerInfo.cend())
@ -1097,7 +1110,7 @@ std::string CPhoneDevice::QueryCpuTemperature()
return ""; return "";
} }
void CPhoneDevice::QueryPowerInfo(std::map<std::string, std::string>& powerInfo) void CPhoneDevice::QueryFlowInfo(std::map<std::string, std::string>& flowInfo)
{ {
JNIEnv* env = NULL; JNIEnv* env = NULL;
jboolean ret = JNI_FALSE; jboolean ret = JNI_FALSE;
@ -1107,7 +1120,7 @@ void CPhoneDevice::QueryPowerInfo(std::map<std::string, std::string>& powerInfo)
{ {
ALOGE("Failed to get JNI Env"); ALOGE("Failed to get JNI Env");
} }
jobject jobj = env->CallObjectMethod(m_javaService, mGetSystemInfoMid); jobject jobj = env->CallObjectMethod(m_javaService, mGetFlowInfoMid);
std::string str = jstring2string(env, (jstring)jobj); std::string str = jstring2string(env, (jstring)jobj);
if (didAttachThread) if (didAttachThread)
{ {
@ -1117,7 +1130,7 @@ void CPhoneDevice::QueryPowerInfo(std::map<std::string, std::string>& powerInfo)
if (!str.empty()) if (!str.empty())
{ {
std::map<std::string, std::string> queries = parseQuery(str); std::map<std::string, std::string> queries = parseQuery(str);
powerInfo.swap(queries); flowInfo.swap(queries);
} }
} }
@ -1235,32 +1248,43 @@ float CPhoneDevice::QueryBattaryVoltage(int timesForAvg, bool* isCharging)
int val = 0; int val = 0;
int totalVals = 0; int totalVals = 0;
float chargingBusVoltage = 0.0f; float chargingBusVoltage = 0.0f;
for (int idx = 0; idx < timesForAvg; idx++) int idx = 0;
XYLOG(XYLOG_SEVERITY_INFO,"WorkStatus BusVoltage");
for (idx = 0; idx < timesForAvg; idx++)
{ {
auto now = std::chrono::system_clock::now();
val = GpioControl::getChargingBusVoltage(); val = GpioControl::getChargingBusVoltage();
auto now2 = std::chrono::system_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now2 - now).count();
XYLOG(XYLOG_SEVERITY_INFO,"WorkStatus BusVoltage val=%d, time=%lld", val, static_cast<long long>(duration));
if (val > 1000) if (val > 1000)
{ {
chargingBusVoltage = (float)val / 1000.0; chargingBusVoltage = (float)val / 1000.0;
break; break;
} }
} }
XYLOG(XYLOG_SEVERITY_INFO,"WorkStatus BusVoltage end");
if (isCharging != NULL) if (isCharging != NULL)
{ {
*isCharging = chargingBusVoltage > DEFAULT_WARNING_CHARGING_BUS_VOL; *isCharging = chargingBusVoltage > DEFAULT_WARNING_CHARGING_BUS_VOL;
} }
XYLOG(XYLOG_SEVERITY_INFO,"WorkStatus BatteryVoltage");
int matched = 0; int matched = 0;
for (int idx = 0; idx < timesForAvg; idx++) for (int idx = 0; idx < timesForAvg; idx++)
{ {
auto now3 = std::chrono::system_clock::now();
val = GpioControl::getBatteryVoltage(); // // BatVol val = GpioControl::getBatteryVoltage(); // // BatVol
auto now4 = std::chrono::system_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now4 - now3).count();
XYLOG(XYLOG_SEVERITY_INFO,"WorkStatus BatteryVoltage val=%d, time=%lld", val, static_cast<long long>(duration));
if (val > 0) if (val > 0)
{ {
totalVals += val > BATTARY_VOLTAGE_MAX ? BATTARY_VOLTAGE_MAX : val; totalVals += val > BATTARY_VOLTAGE_MAX ? BATTARY_VOLTAGE_MAX : val;
matched++; matched++;
} }
} }
XYLOG(XYLOG_SEVERITY_INFO,"WorkStatus BatteryVoltage end");
return (matched > 0) ? ((float)totalVals / 1000.0 / matched) : 0; return (matched > 0) ? ((float)totalVals / 1000.0 / matched) : 0;
} }
@ -1558,15 +1582,28 @@ bool CPhoneDevice::TakePhotoWithNetCamera(IDevice::PHOTO_INFO& localPhotoInfo, c
if (netHandle == 0) if (netHandle == 0)
{ {
// timeout // timeout
m_ethernetFailures++;
std::string pwrStatus = powerCtrlPtr->GetStatus(); std::string pwrStatus = powerCtrlPtr->GetStatus();
pwrStatus += ethernetPowerCtrl->GetStatus(); pwrStatus += ethernetPowerCtrl->GetStatus();
XYLOG(XYLOG_SEVERITY_ERROR, "Ethernet Not Existing CH=%u PR=%X PHOTOID=%u PWR:%s", XYLOG(XYLOG_SEVERITY_ERROR, "Ethernet Not Existing CH=%u PR=%X PHOTOID=%u EthFailures=%u PWR:%s",
(uint32_t)localPhotoInfo.channel, (uint32_t)localPhotoInfo.preset, localPhotoInfo.photoId, pwrStatus.c_str()); (uint32_t)localPhotoInfo.channel, (uint32_t)localPhotoInfo.preset, localPhotoInfo.photoId, m_ethernetFailures, pwrStatus.c_str());
TakePhotoCb(0, localPhotoInfo, "", 0); TakePhotoCb(0, localPhotoInfo, "", 0);
if (m_ethernetFailures > 3)
{
time_t rebootTime = GetRebootTime();
if (ts - rebootTime > 1800)
{
Reboot(REBOOT_TYPE_DEVICE, false, "Ethernet Not Existing");
}
}
return false; return false;
} }
else else
{ {
m_ethernetFailures = 0;
unsigned int ip = 0; unsigned int ip = 0;
unsigned int netMask = 0; unsigned int netMask = 0;
unsigned int gateway = 0; unsigned int gateway = 0;

@ -323,7 +323,7 @@ protected:
return false; return false;
} }
void QueryPowerInfo(std::map<std::string, std::string>& powerInfo); void QueryFlowInfo(std::map<std::string, std::string>& powerInfo);
std::string QueryCpuTemperature(); std::string QueryCpuTemperature();
bool OnImageReady(cv::Mat mat); bool OnImageReady(cv::Mat mat);
@ -373,7 +373,7 @@ protected:
jmethodID mRequestWakelockMid; jmethodID mRequestWakelockMid;
jmethodID mReleaseWakelockMid; jmethodID mReleaseWakelockMid;
jmethodID mGetSystemInfoMid; jmethodID mGetFlowInfoMid;
jmethodID mRebootMid; jmethodID mRebootMid;
jmethodID mInstallAppMid; jmethodID mInstallAppMid;
@ -408,6 +408,8 @@ protected:
std::thread m_threadClose; std::thread m_threadClose;
std::shared_ptr<PowerControl> m_powerCtrlPtr; std::shared_ptr<PowerControl> m_powerCtrlPtr;
uint32_t m_ethernetFailures;
int m_signalLevel; int m_signalLevel;
time_t m_signalLevelUpdateTime; time_t m_signalLevelUpdateTime;

@ -216,7 +216,7 @@ NdkCamera::NdkCamera(int32_t width, int32_t height, const NdkCamera::CAMERA_PARA
mResult = { 0 }; mResult = { 0 };
mLdr = ~0; mLdr = ~0;
mFinalLdr = 0; mFinalLdr = 0;
mFinalBurstCaptures = m_params.burstRawCapture == 0 ? 1 : m_params.burstCaptures; mFinalBurstCaptures = m_params.burstRawCapture == 0 ? m_params.burstCaptures : m_params.burstCaptures;
if (mFinalBurstCaptures == 0) if (mFinalBurstCaptures == 0)
{ {
mFinalBurstCaptures = 1; mFinalBurstCaptures = 1;
@ -1004,6 +1004,7 @@ void NdkCamera::close()
mPreviewResults.reset(); mPreviewResults.reset();
mCaptureResults.clear(); mCaptureResults.clear();
mCaptureFrames.clear(); mCaptureFrames.clear();
mCaptureResultMap.clear();
if ((ACameraManager *)camera_manager != NULL) if ((ACameraManager *)camera_manager != NULL)
{ {
@ -1216,134 +1217,157 @@ void NdkCamera::onImageAvailable(AImageReader* reader)
else else
{ {
uint32_t burstCaptures = getBurstCaptures(); uint32_t burstCaptures = getBurstCaptures();
uint64_t ts = GetMicroTimeStamp();
size_t expectedTimes = mCaptureRequests.size() - 1;
if (burstCaptures == 0) if (burstCaptures == 0)
{ {
burstCaptures = 1; burstCaptures = 1;
} }
if (burstCaptures == 1) if (m_params.burstRawCapture == 0)
{ {
mstatus = AImageReader_acquireNextImage(reader, &image); while (1)
if (mstatus != AMEDIA_OK)
{ {
// https://stackoverflow.com/questions/67063562 mstatus = AImageReader_acquireNextImage(reader, &image);
if (mstatus != AMEDIA_IMGREADER_NO_BUFFER_AVAILABLE) if (mstatus != AMEDIA_OK)
{ {
if (mCaptureFrames.size() < burstCaptures) // https://stackoverflow.com/questions/67063562
if (mstatus != AMEDIA_IMGREADER_NO_BUFFER_AVAILABLE)
{ {
XYLOG(XYLOG_SEVERITY_ERROR, "Capture AImageReader_acquireNextImage error: %d", mstatus); if (mCaptureFrames.size() < burstCaptures)
{
XYLOG(XYLOG_SEVERITY_ERROR, "Capture AImageReader_acquireNextImage error: %d", mstatus);
}
} }
break;
} }
return;
}
unsigned long long ts = GetMicroTimeStamp(); int32_t format;
mstatus = AImage_getFormat(image, &format);
int32_t format; cv::Mat frame;
mstatus = AImage_getFormat(image, &format); if (format == AIMAGE_FORMAT_YUV_420_888)
if (format == AIMAGE_FORMAT_YUV_420_888)
{
int32_t width;
int32_t height;
mstatus = AImage_getWidth(image, &width);
mstatus = AImage_getHeight(image, &height);
int32_t y_pixelStride = 0;
int32_t u_pixelStride = 0;
int32_t v_pixelStride = 0;
AImage_getPlanePixelStride(image, 0, &y_pixelStride);
AImage_getPlanePixelStride(image, 1, &u_pixelStride);
AImage_getPlanePixelStride(image, 2, &v_pixelStride);
int32_t y_rowStride = 0;
int32_t u_rowStride = 0;
int32_t v_rowStride = 0;
AImage_getPlaneRowStride(image, 0, &y_rowStride);
AImage_getPlaneRowStride(image, 1, &u_rowStride);
AImage_getPlaneRowStride(image, 2, &v_rowStride);
uint8_t* y_data = 0;
uint8_t* u_data = 0;
uint8_t* v_data = 0;
int y_len = 0;
int u_len = 0;
int v_len = 0;
AImage_getPlaneData(image, 0, &y_data, &y_len);
AImage_getPlaneData(image, 1, &u_data, &u_len);
AImage_getPlaneData(image, 2, &v_data, &v_len);
if (u_data == v_data + 1 && v_data == y_data + width * height && y_pixelStride == 1 && u_pixelStride == 2 && v_pixelStride == 2 && y_rowStride == width && u_rowStride == width && v_rowStride == width)
{
// already nv21
ConvertYUV21ToMat(y_data, width, height, mWidth, mHeight, camera_orientation,
camera_facing == ACAMERA_LENS_FACING_FRONT, m_params.orientation, mOneFrame);
}
else
{ {
// construct nv21 int32_t width;
uint8_t* nv21 = new uint8_t[width * height + width * height / 2]; int32_t height;
mstatus = AImage_getWidth(image, &width);
mstatus = AImage_getHeight(image, &height);
int32_t y_pixelStride = 0;
int32_t u_pixelStride = 0;
int32_t v_pixelStride = 0;
AImage_getPlanePixelStride(image, 0, &y_pixelStride);
AImage_getPlanePixelStride(image, 1, &u_pixelStride);
AImage_getPlanePixelStride(image, 2, &v_pixelStride);
int32_t y_rowStride = 0;
int32_t u_rowStride = 0;
int32_t v_rowStride = 0;
AImage_getPlaneRowStride(image, 0, &y_rowStride);
AImage_getPlaneRowStride(image, 1, &u_rowStride);
AImage_getPlaneRowStride(image, 2, &v_rowStride);
uint8_t* y_data = 0;
uint8_t* u_data = 0;
uint8_t* v_data = 0;
int y_len = 0;
int u_len = 0;
int v_len = 0;
AImage_getPlaneData(image, 0, &y_data, &y_len);
AImage_getPlaneData(image, 1, &u_data, &u_len);
AImage_getPlaneData(image, 2, &v_data, &v_len);
if (u_data == v_data + 1 && v_data == y_data + width * height && y_pixelStride == 1 && u_pixelStride == 2 && v_pixelStride == 2 && y_rowStride == width && u_rowStride == width && v_rowStride == width)
{ {
// Y // already nv21
uint8_t* yptr = nv21; ConvertYUV21ToMat(y_data, width, height, mWidth, mHeight, camera_orientation,
for (int y = 0; y < height; y++) camera_facing == ACAMERA_LENS_FACING_FRONT, m_params.orientation, frame);
}
else
{
// construct nv21
uint8_t* nv21 = new uint8_t[width * height + width * height / 2];
{ {
const uint8_t* y_data_ptr = y_data + y_rowStride * y; // Y
for (int x = 0; x < width; x++) uint8_t* yptr = nv21;
for (int y = 0; y < height; y++)
{ {
yptr[0] = y_data_ptr[0]; const uint8_t* y_data_ptr = y_data + y_rowStride * y;
yptr++; for (int x = 0; x < width; x++)
y_data_ptr += y_pixelStride; {
yptr[0] = y_data_ptr[0];
yptr++;
y_data_ptr += y_pixelStride;
}
} }
}
// UV // UV
uint8_t* uvptr = nv21 + width * height; uint8_t* uvptr = nv21 + width * height;
for (int y = 0; y < height / 2; y++) for (int y = 0; y < height / 2; y++)
{
const uint8_t* v_data_ptr = v_data + v_rowStride * y;
const uint8_t* u_data_ptr = u_data + u_rowStride * y;
for (int x = 0; x < width / 2; x++)
{ {
uvptr[0] = v_data_ptr[0]; const uint8_t* v_data_ptr = v_data + v_rowStride * y;
uvptr[1] = u_data_ptr[0]; const uint8_t* u_data_ptr = u_data + u_rowStride * y;
uvptr += 2; for (int x = 0; x < width / 2; x++)
v_data_ptr += v_pixelStride; {
u_data_ptr += u_pixelStride; uvptr[0] = v_data_ptr[0];
uvptr[1] = u_data_ptr[0];
uvptr += 2;
v_data_ptr += v_pixelStride;
u_data_ptr += u_pixelStride;
}
} }
} }
}
ConvertYUV21ToMat(nv21, width, height,mWidth, mHeight, camera_orientation, ConvertYUV21ToMat(nv21, width, height,mWidth, mHeight, camera_orientation,
camera_facing == ACAMERA_LENS_FACING_FRONT, m_params.orientation, mOneFrame); camera_facing == ACAMERA_LENS_FACING_FRONT, m_params.orientation, frame);
delete[] nv21; delete[] nv21;
}
} }
} m_photoTaken = true;
m_photoTaken = true;
AImage_delete(image); int64_t frameTs = 0;
mstatus = AImage_getTimestamp(image, &frameTs);
AImage_delete(image);
std::shared_ptr<ACameraMetadata> result; bool captureCompleted = false;
bool captureCompleted = false; bool captureDispatchable = false;
bool captureDispatchable = false; m_locker.lock();
m_locker.lock(); if (!frame.empty())
if (!mCaptureResults.empty()) {
{ mOneFrame.push_back(std::make_pair<>(frameTs, frame));
captureCompleted = true; }
result = mCaptureResults[0]; if (mOneFrame.size() >= expectedTimes)
} {
if (captureCompleted && !mCaptureDispatched) bool allExisted = true;
{ for (auto itFrame = mOneFrame.cbegin(); itFrame != mOneFrame.cend(); ++itFrame)
mCaptureDispatched = true; {
captureDispatchable = true; if (mCaptureResultMap.find(itFrame->first) == mCaptureResultMap.cend())
} {
m_locker.unlock(); allExisted = false;
break;
}
}
if (allExisted)
{
captureCompleted = true;
}
}
if (captureCompleted && captureDispatchable) if (captureCompleted && !mCaptureDispatched)
{ {
XYLOG(XYLOG_SEVERITY_INFO,"onOneCapture from onImageAvailable"); mCaptureDispatched = true;
camera_status_t status = ACameraCaptureSession_stopRepeating(capture_session); captureDispatchable = true;
onOneCapture(mCharacteristics, result, mFinalLdr, ts - m_startTime, mOneFrame); }
m_locker.unlock();
if (captureCompleted && captureDispatchable)
{
XYLOG(XYLOG_SEVERITY_INFO,"onOneCapture from onImageAvailable");
camera_status_t status = ACameraCaptureSession_stopRepeating(capture_session);
FireOneCapture(ts);
// onOneCapture(mCharacteristics, result, mFinalLdr, ts - m_startTime, mOneFrame);
break;
}
} }
} }
else else
@ -1375,7 +1399,6 @@ void NdkCamera::onImageAvailable(AImageReader* reader)
bool captureCompleted = false; bool captureCompleted = false;
bool captureDispatchable = false; bool captureDispatchable = false;
size_t expectedTimes = mCaptureRequests.size() - 1;
m_locker.lock(); m_locker.lock();
captureCompleted = mCaptureResults.size() >= expectedTimes && mCaptureFrames.size() >= expectedTimes; captureCompleted = mCaptureResults.size() >= expectedTimes && mCaptureFrames.size() >= expectedTimes;
if (captureCompleted && !mCaptureDispatched) if (captureCompleted && !mCaptureDispatched)
@ -1807,12 +1830,32 @@ void NdkCamera::onCaptureCompleted(ACameraCaptureSession* session, ACaptureReque
bool captureDispatchable = false; bool captureDispatchable = false;
size_t expectedTimes = mCaptureRequests.size() - 1; size_t expectedTimes = mCaptureRequests.size() - 1;
int64_t resultTimestamp = GetTimestamp(result);
std::shared_ptr<ACameraMetadata> captureResult(pCopy, ACameraMetadata_free); std::shared_ptr<ACameraMetadata> captureResult(pCopy, ACameraMetadata_free);
if (expectedTimes == 1)
if (m_params.burstRawCapture == 0)
{ {
m_locker.lock(); m_locker.lock();
mCaptureResults.push_back(captureResult); mCaptureResults.push_back(captureResult);
captureCompleted = !mOneFrame.empty(); mCaptureResultMap[resultTimestamp] = captureResult;
if (mOneFrame.size() >= expectedTimes)
{
bool allExisted = true;
for (auto itFrame = mOneFrame.cbegin(); itFrame != mOneFrame.cend(); ++itFrame)
{
if (mCaptureResultMap.find(itFrame->first) == mCaptureResultMap.cend())
{
allExisted = false;
break;
}
}
if (allExisted)
{
captureCompleted = true;
}
}
if (captureCompleted && !mCaptureDispatched) if (captureCompleted && !mCaptureDispatched)
{ {
mCaptureDispatched = true; mCaptureDispatched = true;
@ -1824,7 +1867,8 @@ void NdkCamera::onCaptureCompleted(ACameraCaptureSession* session, ACaptureReque
{ {
XYLOG(XYLOG_SEVERITY_INFO,"onOneCapture from onCaptureCompleted"); XYLOG(XYLOG_SEVERITY_INFO,"onOneCapture from onCaptureCompleted");
camera_status_t status = ACameraCaptureSession_stopRepeating(capture_session); camera_status_t status = ACameraCaptureSession_stopRepeating(capture_session);
onOneCapture(mCharacteristics, captureResult, mFinalLdr, ts - m_startTime, mOneFrame);
FireOneCapture(ts);
} }
} }
else else
@ -1848,6 +1892,44 @@ void NdkCamera::onCaptureCompleted(ACameraCaptureSession* session, ACaptureReque
} }
} }
int64_t NdkCamera::GetTimestamp(const ACameraMetadata* result)
{
ACameraMetadata_const_entry entry;
camera_status_t status = ACameraMetadata_getConstEntry(result, ACAMERA_SENSOR_TIMESTAMP, &entry);
if (status == ACAMERA_OK && entry.count > 0) {
return entry.data.i64[0];
}
return 0;
}
void NdkCamera::FireOneCapture(uint64_t ts)
{
#ifdef OUTPUT_DBG_INFO
if (mWidth == 1920 && mOneFrame.size() > 1)
{
std::string dt = FormatLocalDateTime("%d%02d%02d%02d%02d%02d", ts / 1000);
std::vector<int> params;
params.push_back(cv::IMWRITE_JPEG_QUALITY);
params.push_back(50);
for (auto it = mOneFrame.cbegin(); it != mOneFrame.cend(); ++it)
{
std::string fileName = "/sdcard/com.xypower.mpapp/tmp/" + dt;
size_t idx = std::distance(mOneFrame.cbegin(), it);
std::shared_ptr<ACameraMetadata> result = mCaptureResults[idx];
CAPTURE_RESULT captureResult = { 0 };
EnumCameraResult(result.get(), captureResult);
fileName += "_" + mCameraId + "_" + std::to_string(captureResult.aeState) + "_" + std::to_string(idx) + ".jpg";
cv::imwrite(fileName, it->second, params);
}
}
#endif
onOneCapture(mCharacteristics, mCaptureResults.back(), mFinalLdr, ts - m_startTime, mOneFrame.back().second);
}
void NdkCamera::FireBurstCapture() void NdkCamera::FireBurstCapture()
{ {
camera_status_t status = ACameraCaptureSession_stopRepeating(capture_session); camera_status_t status = ACameraCaptureSession_stopRepeating(capture_session);

@ -23,6 +23,7 @@
#include <opencv2/core/core.hpp> #include <opencv2/core/core.hpp>
#include "Camera2Helper.h" #include "Camera2Helper.h"
#include <mutex> #include <mutex>
#include <map>
#include <set> #include <set>
/** /**
@ -183,6 +184,7 @@ public:
void CopyPreviewRequest(ACaptureRequest* request, const ACameraMetadata* previewResult); void CopyPreviewRequest(ACaptureRequest* request, const ACameraMetadata* previewResult);
void FireBurstCapture(); void FireBurstCapture();
void FireOneCapture(uint64_t ts);
uint32_t GetLdr() const uint32_t GetLdr() const
{ {
@ -195,6 +197,7 @@ public:
} }
bool IsCameraAvailable(const std::string& cameraId); bool IsCameraAvailable(const std::string& cameraId);
int64_t GetTimestamp(const ACameraMetadata* result);
static bool convertAImageToNv21(AImage* image, uint8_t** nv21, int32_t& width, int32_t& height); static bool convertAImageToNv21(AImage* image, uint8_t** nv21, int32_t& width, int32_t& height);
static void EnumCameraResult(ACameraMetadata* result, CAPTURE_RESULT& captureResult); static void EnumCameraResult(ACameraMetadata* result, CAPTURE_RESULT& captureResult);
@ -239,7 +242,7 @@ protected:
bool mCaptureDispatched; bool mCaptureDispatched;
CAPTURE_RESULT mResult; CAPTURE_RESULT mResult;
unsigned long long m_startTime; uint64_t m_startTime;
protected: protected:
@ -272,13 +275,15 @@ protected:
std::shared_ptr<ACameraMetadata> mPreviewResults; std::shared_ptr<ACameraMetadata> mPreviewResults;
std::vector<std::shared_ptr<ACameraMetadata> > mCaptureResults; std::vector<std::shared_ptr<ACameraMetadata> > mCaptureResults;
std::map<int64_t, std::shared_ptr<ACameraMetadata> > mCaptureResultMap;
uint32_t mLdr; uint32_t mLdr;
uint32_t mFinalLdr; uint32_t mFinalLdr;
uint32_t mFinalBurstCaptures; uint32_t mFinalBurstCaptures;
int32_t mFinalOutputFormat; int32_t mFinalOutputFormat;
std::vector<std::shared_ptr<AImage> > mCaptureFrames; std::vector<std::shared_ptr<AImage> > mCaptureFrames;
cv::Mat mOneFrame; // cv::Mat mOneFrame;
std::vector<std::pair<int64_t, cv::Mat> > mOneFrame;
std::vector<std::vector<uint8_t> > mRawFrames; std::vector<std::vector<uint8_t> > mRawFrames;
// AImageReader* image_reader; // AImageReader* image_reader;

@ -50,17 +50,12 @@ public class MainActivity extends AppCompatActivity {
private Messenger mMessenger = null; private Messenger mMessenger = null;
private long mConfigModificationTime = 0;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
int activeSubId = SubscriptionManager.getActiveDataSubscriptionId();
if (activeSubId == -1) {
MicroPhotoContext.selectSimCard(getApplicationContext(), 1);
}
}
Log.d(TAG, "Start inflate"); Log.d(TAG, "Start inflate");
binding = ActivityMainBinding.inflate(getLayoutInflater()); binding = ActivityMainBinding.inflate(getLayoutInflater());
Log.d(TAG, "Finish inflate"); Log.d(TAG, "Finish inflate");
@ -68,80 +63,152 @@ public class MainActivity extends AppCompatActivity {
// getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
ActionBar actionBar = getSupportActionBar(); try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
int activeSubId = SubscriptionManager.getActiveDataSubscriptionId();
if (activeSubId == -1) {
MicroPhotoContext.selectSimCard(getApplicationContext(), 1);
}
}
Date date = new Date(BuildConfig.BUILD_TIMESTAMP); ActionBar actionBar = getSupportActionBar();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String caption = "MP"; Date date = new Date(BuildConfig.BUILD_TIMESTAMP);
switch (MicroPhotoService.getCustomAppId()) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
case 1: String caption = "MP";
caption = "RP"; switch (MicroPhotoService.getCustomAppId()) {
break; case 1:
case 2: caption = "RP";
caption = "N938"; break;
break; case 2:
default: caption = "N938";
break; break;
} default:
caption += " v" + MicroPhotoContext.getVersionName(getApplicationContext()) + " " + sdf.format(date); break;
sdf = new SimpleDateFormat("MM-dd HH:mm:ss"); }
caption += " / " + sdf.format(new Date()); caption += " v" + MicroPhotoContext.getVersionName(getApplicationContext()) + " " + sdf.format(date);
actionBar.setTitle(caption); sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
caption += " / " + sdf.format(new Date());
actionBar.setTitle(caption);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); StrictMode.setThreadPolicy(policy);
initListener(); initListener();
Context appContext = getApplicationContext(); Context appContext = getApplicationContext();
String appPath = MicroPhotoContext.buildMpAppDir(appContext); String appPath = MicroPhotoContext.buildMpAppDir(appContext);
File appPathFile = new File(appPath); File appPathFile = new File(appPath);
if (!appPathFile.exists()) { if (!appPathFile.exists()) {
try { try {
appPathFile.mkdirs(); appPathFile.mkdirs();
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
}
} }
}
if (!MicroPhotoContext.hasMpAppConfig(appContext)) { if (!MicroPhotoContext.hasMpAppConfig(appContext)) {
String mstPath = MicroPhotoContext.buildMasterAppDir(appContext);
File mstPathFile = new File(mstPath);
File mpdataFile = new File(mstPathFile, "mpdata");
String mstPath = MicroPhotoContext.buildMasterAppDir(appContext); if (mpdataFile.exists()) {
File mstPathFile = new File(mstPath); File dataFile = new File(appPathFile, "data");
File mpdataFile = new File(mstPathFile, "mpdata"); if (dataFile.exists()) {
try {
dataFile.delete();
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (mpdataFile.exists()) {
File dataFile = new File(appPathFile, "data");
if (dataFile.exists()) {
try { try {
dataFile.delete(); mpdataFile.renameTo(dataFile);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
}
Intent intent = getIntent();
final int noDelay = intent.getIntExtra("noDelay", 0);
int rebootFlag = intent.getIntExtra("reboot", 0);
String reason = intent.getStringExtra("reason");
if (!TextUtils.isEmpty(reason)) {
Log.w(TAG, "App Started with reason: " + reason);
}
if (rebootFlag == 1) {
Log.i(TAG, "After Reboot");
}
Log.d(TAG, "MainActivity: reboot=" + rebootFlag + " noDelay=" + noDelay);
MicroPhotoContext.AppConfig appConfig = loadConfigInfo();
binding.btnStartServ.setEnabled(!MicroPhotoService.isRunning);
binding.btnStopServ.setEnabled(MicroPhotoService.isRunning);
if (MicroPhotoService.isRunning) {
Intent intent2 = new Intent(MainActivity.this, MicroPhotoService.class);
try { try {
mpdataFile.renameTo(dataFile); // stopService(intent2);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
}
Intent intent = getIntent(); if (MicroPhotoContext.hasMpAppConfig(appContext)) {
final int noDelay = intent.getIntExtra("noDelay", 0); final Runnable runnable = new Runnable() {
int rebootFlag = intent.getIntExtra("reboot", 0); @Override
String reason = intent.getStringExtra("reason"); public void run() {
if (!TextUtils.isEmpty(reason)) {
Log.w(TAG, "App Started with reason: " + reason); if (!MicroPhotoService.isRunning && !TextUtils.isEmpty(appConfig.cmdid) && !TextUtils.isEmpty(appConfig.server) && appConfig.port != 0) {
if (binding.btnStartServ.isEnabled()) {
Log.i(TAG, "Perform AutoStart");
binding.btnStartServ.performClick();
}
}
}
};
long timeout = 500;
if (SystemClock.elapsedRealtime() < 180000) {
// In 3 minutes
timeout = 10000; // in 10 seconds
}
Handler handler = new Handler();
handler.postDelayed(runnable, timeout);
Log.i(TAG, "Set AutoStart after " + Long.toString(timeout) + "ms");
}
} catch (Exception ex) {
ex.printStackTrace();
} }
if (rebootFlag == 1) { }
Log.i(TAG, "After Reboot");
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
try {
File file = MicroPhotoContext.getMpAppConfigFile(getApplicationContext());
if (file.lastModified() > mConfigModificationTime) {
loadConfigInfo();
}
} catch (Exception ex) {
ex.printStackTrace();
} }
}
Log.d(TAG, "MainActivity: reboot=" + rebootFlag + " noDelay=" + noDelay); protected MicroPhotoContext.AppConfig loadConfigInfo() {
final MicroPhotoContext.AppConfig appConfig = MicroPhotoContext.getMpAppConfig(getApplicationContext());
mConfigModificationTime = appConfig.modificationTime;
final MicroPhotoContext.AppConfig appConfig = MicroPhotoContext.getMpAppConfig(appContext);
if (TextUtils.isEmpty(appConfig.cmdid)) { if (TextUtils.isEmpty(appConfig.cmdid)) {
appConfig.cmdid = MicroPhotoService.getSerialNumber(); appConfig.cmdid = MicroPhotoService.getSerialNumber();
binding.cmdid.setText(appConfig.cmdid); binding.cmdid.setText(appConfig.cmdid);
@ -159,9 +226,15 @@ public class MainActivity extends AppCompatActivity {
} }
} }
if (appConfig.networkProtocol < binding.networkProtocol.getCount()) { protocolStr = appConfig.networkProtocol + "-";
binding.networkProtocol.setSelection(appConfig.networkProtocol); for (int idx = 0; idx < binding.networkProtocol.getCount(); idx++) {
String item = binding.networkProtocol.getItemAtPosition(idx).toString();
if (item.startsWith(protocolStr)) {
binding.networkProtocol.setSelection(idx);
break;
}
} }
if (appConfig.encryption < binding.encryptions.getCount()) { if (appConfig.encryption < binding.encryptions.getCount()) {
binding.encryptions.setSelection(appConfig.encryption); binding.encryptions.setSelection(appConfig.encryption);
} }
@ -172,46 +245,7 @@ public class MainActivity extends AppCompatActivity {
binding.network.setSelection(appConfig.network); binding.network.setSelection(appConfig.network);
} }
binding.btnStartServ.setEnabled(!MicroPhotoService.isRunning); return appConfig;
binding.btnStopServ.setEnabled(MicroPhotoService.isRunning);
if (MicroPhotoService.isRunning) {
Intent intent2 = new Intent(MainActivity.this, MicroPhotoService.class);
try {
// stopService(intent2);
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (MicroPhotoContext.hasMpAppConfig(appContext)) {
final Runnable runnable = new Runnable() {
@Override
public void run() {
if (!MicroPhotoService.isRunning && !TextUtils.isEmpty(appConfig.cmdid) && !TextUtils.isEmpty(appConfig.server) && appConfig.port != 0) {
if (binding.btnStartServ.isEnabled()) {
Log.i(TAG, "Perform AutoStart");
binding.btnStartServ.performClick();
}
}
}
};
long timeout = 500;
if (SystemClock.elapsedRealtime() < 180000) {
// In 3 minutes
timeout = 10000; // in 10 seconds
}
Handler handler = new Handler();
handler.postDelayed(runnable, timeout);
Log.i(TAG, "Set AutoStart after " + Long.toString(timeout) + "ms");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
} }
protected void initListener() { protected void initListener() {

@ -362,9 +362,7 @@ public class MicroPhotoService extends Service {
} }
@Override @Override
public void onDestroy() { public void onDestroy() {
try { try {
if (mAppLock != null) { if (mAppLock != null) {
mAppLock.close(); mAppLock.close();
} }
@ -1412,62 +1410,25 @@ public class MicroPhotoService extends Service {
return -1; return -1;
} }
public String getSystemInfo() { public String getFlowInfo() {
boolean isXyPlatform = mModelName.startsWith("tb8788");
StringBuilder sb = new StringBuilder();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent intent = getApplicationContext().registerReceiver(null, intentFilter);
int batteryStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
int isCahrging = ((batteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) ||
(batteryStatus == BatteryManager.BATTERY_STATUS_FULL)) ? 1 : 0;
int level = intent.getIntExtra("level", 0); ///电池剩余电量
int scale = intent.getIntExtra("scale", 0); ///获取电池满电量数值
// intent.getStringExtra("technology"); ///获取电池技术支持
// intent.getIntExtra("status",BatteryManager.BATTERY_STATUS_UNKNOWN); ///获取电池状态
// intent.getIntExtra("plugged", 0); ///获取电源信息
// intent.getIntExtra("health",BatteryManager.BATTERY_HEALTH_UNKNOWN); ///获取电池健康度
int bv = intent.getIntExtra("voltage", 0); /// mv
int temp = intent.getIntExtra("temperature", 0); ///获取电池温度
BatteryManager manager = (BatteryManager) getSystemService(BATTERY_SERVICE);
// manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
int bca = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE);
int bc = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
float bcaVal = (bca < 0) ? ((-bca)/1000000000) : (bca / 1000000000); Date dt = new Date();
dt.setDate(1);
dt.setHours(0);
dt.setMinutes(0);
dt.setSeconds(0);
sb.append("&BC=" + Float.toString(bcaVal)); long startTime = dt.getTime();
sb.append("&BV=" + Float.toString(((float)bv) / 1000)); if (dt.getMonth() == 12) {
sb.append("&BP=" + level); dt.setYear(dt.getYear() + 1);
sb.append("&BS=" + scale); dt.setMonth(1);
sb.append("&CS=" + isCahrging); } else {
dt.setMonth(dt.getMonth() + 1);
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isMetered = cm.isActiveNetworkMetered();
sb.append("&NS=" + (isMetered ? "1" : "0"));
final TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
SignalStrength ss = telephonyManager.getSignalStrength();
// List<CellSignalStrength> css = ss.getCellSignalStrengths();
if (ss != null) {
int signalLevel = ss.getLevel();
sb.append("&Signal4G=" + signalLevel);
sb.append("&Signal2G=" + signalLevel);
sb.append("&SL=" + signalLevel);
} }
long endTime = dt.getTime() - 1;
NetworkUtils.Usage usage = NetworkUtils.getApplicationQuerySummary(this.getApplicationContext(), startTime, endTime, getApplicationInfo().uid);
// SysApi.getCpuRate(); return "RX=" + Long.toString(usage.mobleRxBytes) + "&TX=" + Long.toString(usage.mobleTxBytes);
return sb.toString();
} }
public boolean installApp(final String path, long delayedTime) { public boolean installApp(final String path, long delayedTime) {

@ -1,7 +1,8 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string-array name="networkProtocols"> <string-array name="networkProtocols">
<item>TCP</item> <item>0-TCP</item>
<item>UDP</item> <item>1-UDP</item>
<item>10-MQTT</item>
</string-array> </string-array>
</resources> </resources>

@ -55,6 +55,7 @@ public class MicroPhotoContext {
public int packetSize; public int packetSize;
public int encryption; //0不加密 1明文 2加密 public int encryption; //0不加密 1明文 2加密
public int channels; //摄像头通道数目 public int channels; //摄像头通道数目
public long modificationTime = 0;
} }
public static class MasterConfig { public static class MasterConfig {
@ -241,27 +242,39 @@ public class MicroPhotoContext {
return getMpAppConfig(context, appPath + "data/App.json"); return getMpAppConfig(context, appPath + "data/App.json");
} }
public static File getMpAppConfigFile(Context context) {
String appPath = buildMpAppDir(context);
return new File(appPath + "data/App.json");
}
public static AppConfig getMpAppConfig(Context context, String path) { public static AppConfig getMpAppConfig(Context context, String path) {
AppConfig appConfig = new AppConfig(); AppConfig appConfig = new AppConfig();
File file = new File(path);
try { try {
String content = FilesUtils.readTextFile(path); if (file.exists()) {
JSONObject jsonObject = TextUtils.isEmpty(content) ? new JSONObject() : new JSONObject(content); appConfig.modificationTime = file.lastModified();
appConfig.cmdid = jsonObject.optString(jsonObject.has("cmdid") ? "cmdid" : "CMDID", ""); String content = FilesUtils.readTextFile(path);
appConfig.server = jsonObject.optString(jsonObject.has("server") ? "server" : "Server", "");
appConfig.port = jsonObject.optInt(jsonObject.has("port") ? "port" : "Port", 0); JSONObject jsonObject = TextUtils.isEmpty(content) ? new JSONObject() : new JSONObject(content);
appConfig.protocol = jsonObject.optInt(jsonObject.has("protocol") ? "protocol" : "Protocol", DEFAULT_PROTOCOL); appConfig.cmdid = jsonObject.optString(jsonObject.has("cmdid") ? "cmdid" : "CMDID", "");
appConfig.networkProtocol = jsonObject.optInt(jsonObject.has("networkProtocol") ? "networkProtocol" : "NetworkProtocol", 0); appConfig.server = jsonObject.optString(jsonObject.has("server") ? "server" : "Server", "");
appConfig.network = jsonObject.optInt(jsonObject.has("network") ? "network" : "Network", 0); appConfig.port = jsonObject.optInt(jsonObject.has("port") ? "port" : "Port", 0);
appConfig.heartbeat = jsonObject.optInt("heartbeat", 0); appConfig.protocol = jsonObject.optInt(jsonObject.has("protocol") ? "protocol" : "Protocol", DEFAULT_PROTOCOL);
appConfig.packetSize = jsonObject.optInt("packetSize", 0); appConfig.networkProtocol = jsonObject.optInt(jsonObject.has("networkProtocol") ? "networkProtocol" : "NetworkProtocol", 0);
appConfig.encryption = jsonObject.optInt("encryption", 0); appConfig.network = jsonObject.optInt(jsonObject.has("network") ? "network" : "Network", 0);
appConfig.channels = jsonObject.optInt("channels", 4); appConfig.heartbeat = jsonObject.optInt("heartbeat", 0);
appConfig.packetSize = jsonObject.optInt("packetSize", 0);
if (appConfig.protocol == 0) { appConfig.encryption = jsonObject.optInt("encryption", 0);
appConfig.protocol = DEFAULT_PROTOCOL; appConfig.channels = jsonObject.optInt("channels", 4);
if (appConfig.protocol == 0) {
appConfig.protocol = DEFAULT_PROTOCOL;
}
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();

@ -1,6 +1,8 @@
package com.xypower.common; package com.xypower.common;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
@ -12,6 +14,7 @@ import android.net.NetworkCapabilities;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.net.Uri; import android.net.Uri;
import android.net.wifi.WifiManager; import android.net.wifi.WifiManager;
import android.os.RemoteException;
import android.telephony.TelephonyManager; import android.telephony.TelephonyManager;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.format.Formatter; import android.text.format.Formatter;
@ -193,4 +196,40 @@ public class NetworkUtils {
*/ */
public static class Usage {
public long mobleRxBytes;//移动 下载字节
public long mobleTxBytes;//移动 上传字节
public String uid;//包名
}
/**
*
* @param context
* @param startTime
* @param endTime
* @param uid uid
*/
public static Usage getApplicationQuerySummary(Context context, long startTime, long endTime, int uid) {
Usage usage = new Usage();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
NetworkStatsManager nsm = (NetworkStatsManager) context.getSystemService(Context.NETWORK_STATS_SERVICE);
assert nsm != null;
try {
NetworkStats mobile = nsm.querySummary(ConnectivityManager.TYPE_MOBILE, null, startTime, endTime);
do {
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
mobile.getNextBucket(bucket);
if(bucket.getUid() == uid) {
usage.mobleRxBytes += bucket.getRxBytes();
usage.mobleTxBytes += bucket.getTxBytes();
}
} while (mobile.hasNextBucket());
} catch (RemoteException e) {
e.printStackTrace();
}
}
return usage;
}
} }

@ -464,8 +464,8 @@ public class MpMasterService extends Service {
final long modifiedTimeOfPhoto = getFileModificationTime(appPath + "data/alive/taking"); final long modifiedTimeOfPhoto = getFileModificationTime(appPath + "data/alive/taking");
final long modifiedTimeOfUpload = getFileModificationTime(appPath + "data/alive/upload"); final long modifiedTimeOfUpload = getFileModificationTime(appPath + "data/alive/upload");
if (((ts - modifiedTimeOfHb) > mTimeOfMpAppAlive) //|| if (((ts - modifiedTimeOfHb) > mTimeOfMpAppAlive) ||
// ((ts - modifiedTimeOfPhoto) > mTimeOfMpAppAlive * 4) || ((ts - modifiedTimeOfPhoto) > mTimeOfMpAppAlive * 4)// ||
// ((ts - modifiedTimeOfUpload) > mTimeOfMpAppAlive * 4) // ((ts - modifiedTimeOfUpload) > mTimeOfMpAppAlive * 4)
) { ) {

Loading…
Cancel
Save