blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 122 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
951565ab7fb305eb98042414db665c615da8f273 | 453e647779e0ff590092b12629e759e010ee1223 | /libs/embree/include/renderer/api/render_device.h | 31e8a02303079b3eeb8efebe4c5d5924313105d8 | [] | no_license | xiajiaonly/ofxEmbree | 300361fe83d0c9902c6597e7149c6b0387a83b64 | 2fd9e66cbaa27ecfffa625344a8b042ded739498 | refs/heads/master | 2020-03-13T19:58:45.879441 | 2013-08-12T13:05:59 | 2013-08-12T13:05:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,302 | h | // ======================================================================== //
// Copyright 2009-2012 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#ifndef __EMBREE_RENDER_DEVICE_H__
#define __EMBREE_RENDER_DEVICE_H__
#include "default.h"
#include "api/device.h"
#include "api/swapchain.h"
#include "sys/sync/mutex.h"
namespace embree
{
class RenderDevice : public Device
{
public:
/*! construction */
RenderDevice(size_t numThreadsPerProcessor);
/*! destruction */
~RenderDevice();
/*******************************************************************
creation of objects
*******************************************************************/
RTCamera rtNewCamera(const char* type);
RTData rtNewData(const char* type, size_t bytes, const void* data);
RTData rtNewDataFromFile(const char* type, const char* file, size_t offset, size_t bytes);
RTImage rtNewImage(const char* type, size_t width, size_t height, const void* data);
RTImage rtNewImageFromFile(const char* file);
RTTexture rtNewTexture(const char* type);
RTMaterial rtNewMaterial(const char* type);
RTShape rtNewShape(const char* type);
RTLight rtNewLight(const char* type);
RTPrimitive rtNewShapePrimitive(RTShape shape, RTMaterial material, const float* transform = NULL);
RTPrimitive rtNewLightPrimitive(RTLight light, const float* transform = NULL);
RTPrimitive rtTransformPrimitive(RTPrimitive prim, const float* transform);
RTScene rtNewScene(const char* type, RTPrimitive* prims, size_t size);
RTToneMapper rtNewToneMapper(const char* type);
RTRenderer rtNewRenderer(const char* type);
RTFrameBuffer rtNewFrameBuffer(const char* type, size_t width, size_t height, size_t buffers);
void rtGetFrameBufferSize(RTFrameBuffer frameBuffer, size_t& width, size_t& height);
void* rtMapFrameBuffer(RTFrameBuffer frameBuffer);
void rtUnmapFrameBuffer(RTFrameBuffer frameBuffer);
void rtSwapBuffers(RTFrameBuffer frameBuffer);
void rtIncRef(RTHandle handle);
void rtDecRef(RTHandle handle);
/*******************************************************************
setting of parameters
*******************************************************************/
void rtSetBool1(RTHandle handle, const char* property, bool x);
void rtSetBool2(RTHandle handle, const char* property, bool x, bool y);
void rtSetBool3(RTHandle handle, const char* property, bool x, bool y, bool z);
void rtSetBool4(RTHandle handle, const char* property, bool x, bool y, bool z, bool w);
void rtSetInt1(RTHandle handle, const char* property, int x);
void rtSetInt2(RTHandle handle, const char* property, int x, int y);
void rtSetInt3(RTHandle handle, const char* property, int x, int y, int z);
void rtSetInt4(RTHandle handle, const char* property, int x, int y, int z, int w);
void rtSetFloat1(RTHandle handle, const char* property, float x);
void rtSetFloat2(RTHandle handle, const char* property, float x, float y);
void rtSetFloat3(RTHandle handle, const char* property, float x, float y, float z);
void rtSetFloat4(RTHandle handle, const char* property, float x, float y, float z, float w);
void rtSetArray(RTHandle handle, const char* property, const char* type, RTData data, size_t size, size_t stride, size_t ofs);
void rtSetString(RTHandle handle, const char* property, const char* str);
void rtSetImage(RTHandle handle, const char* property, RTImage img);
void rtSetTexture(RTHandle handle, const char* property, RTTexture tex);
void rtSetTransform(RTHandle handle, const char* property, const float* transform);
void rtClear(RTHandle handle);
void rtCommit(RTHandle handle);
/*******************************************************************
render calls
*******************************************************************/
void rtRenderFrame(RTRenderer renderer, RTCamera camera, RTScene scene, RTToneMapper toneMapper, RTFrameBuffer frameBuffer, int accumulate);
bool rtPick(RTCamera camera, float x, float y, RTScene scene, float& px, float& py, float& pz);
private:
MutexSys mutex;
};
}
#endif
| [
"diagne.cyril@gmail.com"
] | diagne.cyril@gmail.com |
8a796819e38fd99102c378112818a01e5280f5d9 | 4394331a19b099681b0738e02e7f0a2f0713e95d | /libmediainfo_0.7.82/ZenLib/Source/ZenLib/Format/Http/Http_Handler.h | 1ea484d271650f3ec3091284c1cc036530c5e484 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | OLEG4120/MediaInfoCLI-android | b986f2a3a74d502ecfe8c106d0f026082411bca7 | 94cf4fd1edc9b7b9912d56976f1b4b025dfe6119 | refs/heads/master | 2021-01-10T16:00:28.266042 | 2016-01-28T06:44:05 | 2016-01-28T06:44:57 | 50,170,254 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,865 | h | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a zlib-style license that can
* be found in the License.txt file in the root of the source tree.
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// A HTTP Request
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//---------------------------------------------------------------------------
#ifndef ZenLib_Format_Http_RequestH
#define ZenLib_Format_Http_RequestH
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "ZenLib/Format/Http/Http_Cookies.h"
#include <string>
#include <ctime>
#include <map>
#include <vector>
//---------------------------------------------------------------------------
namespace ZenLib
{
namespace Format
{
namespace Http
{
//***************************************************************************
/// @brief
//***************************************************************************
class Handler
{
public:
//Constructor/Destructor
Handler();
//In
std::string Path; //The path being requested by this request
std::map<std::string, std::string> Request_Headers; //All the incoming HTTP headers from the client web browser.
std::map<std::string, std::string> Request_Cookies; //The set of cookies that came from the client along with this request
std::map<std::string, std::string> Request_Queries; //All the key/value pairs in the query string of this request
std::string Foreign_IP; //The foreign ip address for this request
std::string Local_IP; //The foreign port number for this request
unsigned short Foreign_Port; //The IP of the local interface this request is coming in on
unsigned short Local_Port; //The local port number this request is coming in on
bool HeadersOnly; //The request requests only the header
//Out
size_t Response_HTTP_Code; //HTTP code to be sent
std::map<std::string, std::string> Response_Headers; //Additional headers you wish to appear in the HTTP response to this request
Cookies Response_Cookies; //New cookies to pass back to the client along with the result of this request
std::string Response_Body; //To be displayed as the response to this request
};
} //Namespace
} //Namespace
} //Namespace
#endif
| [
"oleg02007@gmail.com"
] | oleg02007@gmail.com |
88ea7b80f4d118f94da626108f911b82018fe9d5 | a2edaed1232234b1b3227f989fc35aece8c26a50 | /TerrificTrafficSimulator/GUI/SCN_SelectMap.h | ce1df35e953784d863bf7360726e39cf86c467ec | [] | no_license | mkay1375/TerrificTrafficSimulator | 690519488c62ddc21ce12321eac4a8e8c820e81a | ade4483abb23712980c8eee17da3feead67d21cd | refs/heads/main | 2023-03-27T01:11:06.164891 | 2021-04-04T16:03:41 | 2021-04-04T16:03:41 | 354,578,362 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 118 | h | #pragma once
#include "Scene.h"
class SCN_SelectMap : public Scene
{
public:
SCN_SelectMap();
~SCN_SelectMap();
};
| [
"mkay1375@gmail.com"
] | mkay1375@gmail.com |
0caf860b2208eba1eceed5d16e0bbf1b1db68f81 | 81dc36fe44f0d9df4f17f70959925816b5fe385e | /license-client/include/tcpclient.h | b955fab05874ff3cec435cf95ad13a8ea91fc5e6 | [
"MIT"
] | permissive | stallion5632/license-services | 6dd5beb076de762ccbcc8bef0bcddc12d1156b9f | e46be0a89fdee4037aa8804411b6ec135ce25887 | refs/heads/master | 2020-03-29T12:13:17.721950 | 2018-09-23T02:00:23 | 2018-09-23T02:00:23 | 149,889,481 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 676 | h |
#ifndef TCP_CLIENT_H
#define TCP_CLIENT_H
#include <boost/asio.hpp>
#include "tcp_message.hpp"
#include "messagebus.hpp"
#include "common.h"
#include "rockapi.h"
struct ClientConfig;
class TcpClientImpl;
class ROCK_NET_API TcpClient
{
public:
TcpClient(boost::asio::io_context& io_context,
const ClientConfig &cfg,
const MessageType_t &messageTypes);
~TcpClient();
// 发送tcp消息
// note: _syncBytes _msgSeq _bodyLen _fullMsgLen这三个字段会自动补全,可以不用填写
void write(TcpMessage &msg);
// 关闭tcpsession
void close();
MessageBus<> &messagebus();
void start();
private:
TcpClientImpl* _pImpl;
};
#endif
| [
"stallion5632@163.com"
] | stallion5632@163.com |
51656438cdc9a7e7a7369e2f651848986f8d3731 | 1fb41938ee808b9bbc416404a06cece52e7e4edc | /euiler_circuit.cpp | 38a756dee787bfc90cf5b3ebd051e78a99927ce4 | [] | no_license | imran1995/tiktok | c7bb9e4317d5aac28683e23c6bffbec90f4cb92e | e6ff5366a105b2c5eab13852dcce4f1560214031 | refs/heads/master | 2020-05-24T16:14:29.521310 | 2017-03-13T17:57:35 | 2017-03-13T17:57:35 | 84,857,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,139 | cpp | #include<bits/stdc++.h>
using namespace std;
#define MAX 100004
#define pi pair<int,int>
#define mp make_pair
int vis[MAX];
vector<pi>g[MAX];
list<int>cir;
void tor(list<int>::iterator j,int u)
{
for(int i=0;i<g[u].size();i++){
pi v=g[u][i];
if(v.second==1){
v.second=0;
for(int k=0;k<g[v.first].size();k++){
pi uu=g[v.first][k];
if(uu.first==u && uu.second==1){
uu.second=0;
break;
}
}
tor(cir.insert(j,u),v.first);
}
}
}
int main()
{
int n,i,j,u,v;
while(scanf("&d&d&d",&u,&v,&w)!=EOF){
memset(vis,0,sizeof(vis));
cin>>u>>v;
g[u].push_back(mp(v,1));
g[v].push_back(mp(u,1));
vis[v]++;
vis[u]++;
int flag=0;
for(i=0;i<MAX;i++){
if(vis[i]%2==1){
flag=1;
break;
}
}
if(flag==0){
tor(cir.begin(),1);
for( i=0;i<cir.size();i++){
printf("%d \n",i);
}
}
}
}
| [
"noreply@github.com"
] | imran1995.noreply@github.com |
ee7e7a92a1f1a1fa9ac67a95c2ec7fa53c1b346f | e426bfa4943daf4206030415cba2012ffc45c532 | /include/common/snippets/asc2bin.h | 3030d16a2c633fcb6fbbcaa15d292dee3aa2f548 | [] | no_license | shawwn/codesuppository | 952c43b48fb12fc70c6c7057119cc4af30e03385 | da9905802797c8e42bb0016d2929d3d768aea332 | refs/heads/master | 2020-03-21T07:14:32.497634 | 2019-06-11T06:56:49 | 2019-06-11T06:56:49 | 138,269,183 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,883 | h | #ifndef ASC2BIN_H
#define ASC2BIN_H
#include "UserMemAlloc.h"
/*!
**
** Copyright (c) 2007 by John W. Ratcliff mailto:jratcliff@infiniplex.net
**
** Portions of this source has been released with the PhysXViewer application, as well as
** Rocket, CreateDynamics, ODF, and as a number of sample code snippets.
**
** If you find this code useful or you are feeling particularily generous I would
** ask that you please go to http://www.amillionpixels.us and make a donation
** to Troy DeMolay.
**
** DeMolay is a youth group for young men between the ages of 12 and 21.
** It teaches strong moral principles, as well as leadership skills and
** public speaking. The donations page uses the 'pay for pixels' paradigm
** where, in this case, a pixel is only a single penny. Donations can be
** made for as small as $4 or as high as a $100 block. Each person who donates
** will get a link to their own site as well as acknowledgement on the
** donations blog located here http://www.amillionpixels.blogspot.com/
**
** If you wish to contact me you can use the following methods:
**
** Skype Phone: 636-486-4040 (let it ring a long time while it goes through switches)
** Skype ID: jratcliff63367
** Yahoo: jratcliff63367
** AOL: jratcliff1961
** email: jratcliff@infiniplex.net
**
**
** The MIT license:
**
** Permission is hereby granted, MEMALLOC_FREE of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is furnished
** to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// types:
//
// f : 4 byte NxF32
// d : 4 byte integer
// c : 1 byte character
// b : 1 byte integer
// h : 2 byte integer
// p : 4 byte const char *
// x1 : 1 byte hex
// x2 : 2 byte hex
// x4 : 4 byte hex (etc)
// example usage:
//
// Asc2Bin("1 2 3 4 5 6",1,"fffff",0);
namespace NVSHARE
{
void * Asc2Bin(const char *source,const NxI32 count,const char *ctype,void *dest=0);
}; //
#endif
| [
"shawnpresser@gmail.com"
] | shawnpresser@gmail.com |
e811c19394f4861bbd3ab100ac1d671a66d6a467 | f67629586414cfe28929c10f30e09ce82ea342bc | /Benchmark Engineering Tool/example/BenchmarkLibUnbuilt/src-gen/stateMachine/AbstractMachineElement.hpp | a875c394458854b66dd69ecb31cbdea2936ad642 | [] | no_license | Mohamedgalil/plug-and-bench | cb259258fbb9a09a7ed084d395ca5a49d17c8a6b | 44d02a6eb0eb7de289364e2dffe5dc0d63cc9516 | refs/heads/master | 2020-04-25T15:31:23.868541 | 2019-04-16T07:20:24 | 2019-04-16T07:20:24 | 172,881,559 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,566 | hpp | // -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*-
/*
* stateMachine/AbstractMachineElement.hpp
* This file was created by EMF4CPP 2.0.0 and is copyrighted by the
* respective user and/or provider of the processed ECORE model.
*
* EMF4CPP is free software. You can obtain it from
* https://github.com/catedrasaes-umu/emf4cpp
*/
#ifndef STATEMACHINE_ABSTRACTMACHINEELEMENT_HPP
#define STATEMACHINE_ABSTRACTMACHINEELEMENT_HPP
#include <ecorecpp/mapping_forward.hpp>
#include <ecore/EObject.hpp>
#include <stateMachine/dllStateMachine.hpp>
#include <stateMachine_forward.hpp>
#include "StateMachinePackage.hpp"
/*PROTECTED REGION ID(AbstractMachineElement_pre) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
namespace stateMachine
{
class EXPORT_STATEMACHINE_DLL AbstractMachineElement : public virtual ::ecore::EObject
{
public:
AbstractMachineElement();
virtual ~AbstractMachineElement();
virtual void _initialize();
// Operations
// Attributes
// References
/* This is the same value as getClassifierId() returns, but as a static
* value it can be used in template expansions. */
static const int classifierId = StateMachinePackage::ABSTRACTMACHINEELEMENT;
/*PROTECTED REGION ID(AbstractMachineElement) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
// EObjectImpl
virtual ::ecore::EJavaObject eGet ( ::ecore::EInt _featureID, ::ecore::EBoolean _resolve);
virtual void eSet ( ::ecore::EInt _featureID, ::ecore::EJavaObject const& _newValue);
virtual ::ecore::EBoolean eIsSet ( ::ecore::EInt _featureID);
virtual void eUnset ( ::ecore::EInt _featureID);
virtual ::ecore::EClass_ptr _eClass ();
virtual void _inverseAdd ( ::ecore::EInt _featureID, ::ecore::EJavaObject const& _newValue);
virtual void _inverseRemove ( ::ecore::EInt _featureID, ::ecore::EJavaObject const& _oldValue);
/*PROTECTED REGION ID(AbstractMachineElementImpl) START*/
// Please, enable the protected region if you add manually written code.
// To do this, add the keyword ENABLED before START.
/*PROTECTED REGION END*/
protected:
AbstractMachineElement_ptr _this()
{ return AbstractMachineElement_ptr(this);}
// Attributes
// References
};
}
// stateMachine
#endif // STATEMACHINE_ABSTRACTMACHINEELEMENT_HPP
| [
"mohamed.el-shamouty@ipa.fraunhofer.de"
] | mohamed.el-shamouty@ipa.fraunhofer.de |
3e1792367200f5f62a365b478174b17382203892 | 87b64a43e2f62d7d6bbcc0c6879586c0eb6e76eb | /button.hpp | 4f4264c0128a77e3812e588f00943d9a8f9caf98 | [
"MIT"
] | permissive | SudhanshuLaroiya/MakeUofT | 145e4a3c405298ff3447a6371952b1e4ea54f6d6 | 13b8f8db4d7f9360ec7a4c88c88f4fd40c18d6f0 | refs/heads/master | 2020-04-23T11:42:19.350950 | 2019-02-17T16:42:04 | 2019-02-17T16:42:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,395 | hpp | /**
* copyright (c) 2018, James Flynn
* SPDX-License-Identifier: MIT
*/
/**
* @file button.hpp
* @brief A small BUTTON class for detecting & debouncing button preesses
*
* @author James Flynn
*
* @date 24-Aug-2018
*/
#include "mbed.h"
#define BUTTON_DEBOUNCE 20 //specify the number of msec to debounce
class Button {
protected:
InterruptIn user_button;
void (*br_cb)(int); //button release callback
void (*bp_cb)(void); //button press callback
Thread *button_thread;
void button_monitor_task(void);
EventQueue button_queue;
uint64_t bp_time, bp_duration; //button press start time and button press duration
int button_pressed; //counts the number of times the button has been pressed
void button_press_handler(void) {
if( (rtos::Kernel::get_ms_count() - bp_time) < BUTTON_DEBOUNCE)
return;
bp_time = rtos::Kernel::get_ms_count();
if( bp_cb )
bp_cb();
}
void button_release_handler(void) {
uint64_t tmp = rtos::Kernel::get_ms_count() - bp_time;
if( tmp > BUTTON_DEBOUNCE ) {
bp_duration = tmp;
button_pressed++;
if( br_cb )
br_cb(bp_duration);
}
}
public:
enum State { ActiveHigh = 0, ActiveLow };
Button(PinName p, State s, void (*cb)(int)=NULL) :
user_button(p),
br_cb(cb),
bp_cb(NULL),
bp_time(0),
bp_duration(0),
button_pressed(0)
{
// The user button is setup for the edge to generate an interrupt.
// The release is caught an event queue callback
button_thread=new Thread(osPriorityNormal,256,NULL,"button_thread");
button_thread->start(callback(&button_queue, &EventQueue::dispatch_forever));
if( s == ActiveHigh ) {
user_button.rise( Callback<void()>(this, &Button::button_press_handler) );
user_button.fall( button_queue.event( Callback<void()>(this, &Button::button_release_handler)));
}
else{
user_button.fall( Callback<void()>(this, &Button::button_press_handler) );
user_button.rise(button_queue.event(Callback<void()>(this, &Button::button_release_handler)));
}
}
~Button() {
button_thread->terminate();
delete button_thread;
}
// will return the number of times the button has been pressed (if it was pressed > 1 time before checked)
// and returns the duration of the last button press in duration
int chkButton_press(int *duration) {
int bp = button_pressed;
if( button_pressed ) {
*duration = bp_duration;
bp_duration = 0;
button_pressed = 0;
}
return bp;
}
//allows the user to set a callback for a button press in
void setButton_press_cb( void (*buttonpresscb)(void) ) {
bp_cb = buttonpresscb;
}
};
| [
"noreply@github.com"
] | SudhanshuLaroiya.noreply@github.com |
1a57ee116aa5abe676104c058972799ea6d6f101 | 4e8ec57b29f8ffab169e97bb5a1cb1e794ee24d9 | /Tema3Object3D.h | b13ea7b245ec62c29832f4bd8fa643e044b1d22d | [] | no_license | remusbompa/New-Vegas | 4ee780a52f0a4f6b95ae73870bf4b06a41654c2c | 80580316894db3e36aa4d4a8b385ebed253c117e | refs/heads/master | 2020-04-23T02:44:17.014961 | 2019-02-15T11:43:52 | 2019-02-15T11:43:52 | 170,855,809 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,566 | h | #pragma once
#include <string>
#include <include/glm.h>
#include <Core/GPU/Mesh.h>
#include "Tema3.h"
/*
Fisierul defineste functiile de construire a obiectelor si de detectare a coliziunilor.
*/
namespace Tema3Object3D
{
Mesh* CreateParaleliped(std::string name, glm::vec3 corner, float height, float depth, float width);
Mesh* CreateSphere(std::string name, glm::vec3 center, float radius, glm::vec3 color);
Mesh* CreateCylinder(std::string name, glm::vec3 bottomCenter, float radius1, float radius2, float height, int nrFragments, int obj);
Mesh* CreateRect(std::string name, glm::vec3 leftBottomCorner, glm::vec3 normal, glm::vec3 tang, float lengthN, float lengthT, glm::vec3 color);
Mesh* CreateQuad(glm::vec3 P1, glm::vec3 P2, glm::vec3 P3, glm::vec3 P4, float depth);
static float min_height = 0.5f;
static float pixels_p_unit_w = 1.0f;
static float pixels_p_unit_h = 2.0f;
static float pixels_p_unit_street_x = 3.0f;
static float pixels_p_unit_street_y = 15.0f;
std::vector<Mesh*> CreateBlockyBuilding(glm::vec3 P);
static float maxHeight = 30.0f;
static float minHeight = 10.0f;
static float radius = 3.0f;
static float bigRadius = 6.0f;
static float widthBlock = 2.0f;
static int maxBlocks = 5;
static int nrCuts = 4;
static float cutDegree = 90.0f;
float getRealDistance(std::vector<int> realIndices, int prevInd, int nextInd, float realStep);
constexpr float PI = 3.1415926535f;
Mesh* CreateCylinderNormal(std::string name, glm::vec3 bottomCenter, float radius1, float radius2, float height, glm::vec3 color);
}
| [
"noreply@github.com"
] | remusbompa.noreply@github.com |
003103d78f3831826fb759695e22661d8469cd70 | 7724d908ff50bf9bf31465a58a99914a8669d5fb | /BOJ/2525.cpp | c371d6ec2ad5ccc93a3215d5c409d8733cc606dd | [] | no_license | HyeonDKIM/AlgorithmStudy | d3e6cb5d1265377a1dd9b33cd416282634e45442 | 3abaf506981c8202f3913b62cbcc0e89daeb0c78 | refs/heads/master | 2021-08-08T17:52:50.046115 | 2021-07-22T00:20:37 | 2021-07-22T00:20:37 | 157,544,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 364 | cpp | #include <iostream>
using namespace std;
int main(void) {
int A = 0;
int B = 0;
int C = 0;
cin >> A >> B;
cin >> C;
int Time_Hour = 0;
int Time_Minute = 0;
Time_Hour = C / 60;
Time_Minute = C % 60;
A = A + Time_Hour;
B = B + Time_Minute;
if (B >= 60) {
B = B - 60;
A = A + 1;
}
if (A >= 24) {
A = A - 24;
}
cout << A << " " << B;
}
| [
"noreply@github.com"
] | HyeonDKIM.noreply@github.com |
5098989ecd4b0ca852ea8bd0aa5940afb369e5d9 | 5f3fe02df7fd5f65ca8966eede31ea01ea7e7316 | /homework2/code.ino/code.ino.ino | a39fdd8692fdb860b13b79b1890b7dddd6409c49 | [] | no_license | CloakedGhost07/Martin_CSE_236 | d6bb2d0b9003399adecee2612c1d1bf0d0837857 | a2b3626388c401be3d6a7f70875cded380b69969 | refs/heads/master | 2020-12-13T08:15:28.879351 | 2020-05-01T15:11:45 | 2020-05-01T15:11:45 | 234,358,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,297 | ino | /*--------------------------------------------------------------------
Name: Michael Martin
Date: 1/30/2020
Course: CSCE 236 Embedded Systems (Spring 2020)
File:
HW/Lab: Lab 1, programming component
Purp: Source code for Arduino board,
Doc:
Academic Integrity Statement: I certify that, while others may have
assisted me in brain storming, debugging and validating this program,
the program itself is my own work. I understand that submitting code
which is the work of other individuals is a violation of the honor
code. I also understand that if I knowingly give my original work to
another individual is also a violation of the honor code.
--------------------------------------------------------------------*/
#include<stdint.h>
#include<Arduino.h>
#define LED_PIN 13
int in_byte =0;
int flashcount = 0;
int speed = 0;
int i;
uint32_t bit32count;
uint16_t bit16count = 0xffff;
uint16_t bit16countB = 0xffff;
uint8_t bit8countA;
uint8_t bit8countB;
uint8_t bit8countC;
void setup() {
Serial.begin(9600);
while(!Serial){};
//pinMode(LED_PIN,OUTPUT);
/*
Serial.println("cycle start");
for(bit16count = 0; bit16count < 0x3fffff; bit16count++){
asm volatile("nop");
}
Serial.println("cycle done");
*/
pinMode(LED_PIN,OUTPUT);
blinkSequenceUsingBits();
}
void blinkSequenceUsingBits(){
Serial.println("cycle start for 3 sec");
digitalWrite(LED_PIN,HIGH);
for(bit32count = 0; bit32count < 0x13ffff ; bit32count++){
asm volatile("nop");
}
digitalWrite(LED_PIN,LOW);
Serial.println("32 bit cycle done");
delay(500);
digitalWrite(LED_PIN,HIGH);
delay(500);
digitalWrite(LED_PIN,LOW);
delay(500);
Serial.println("cycle start for 6 sec");
digitalWrite(LED_PIN,HIGH);
for(bit16countB = 0; bit16countB < 0x48; bit16countB++){
for(bit16count = 0; bit16count < 0xffff; bit16count ++){
asm volatile("nop");
}}
digitalWrite(LED_PIN,LOW);
Serial.println("16 bit cycle done");
delay(500);
digitalWrite(LED_PIN,HIGH);
delay(500);
digitalWrite(LED_PIN,LOW);
delay(500);
digitalWrite(LED_PIN,HIGH);
delay(500);
digitalWrite(LED_PIN,LOW);
delay(500);
digitalWrite(LED_PIN,HIGH);
Serial.println("cycle start for 2 sec");
for(bit8countA = 0; bit8countA < 41; bit8countA++){
for(bit8countB = 0; bit8countB < 0xff; bit8countB++){
for(bit8countC = 0; bit8countC < 0xff; bit8countC++){
asm volatile("nop");
}
}
}
digitalWrite(LED_PIN,LOW);
Serial.println("8 bit cycle done");
}
void flashSerial(){
if(Serial.available()>0){
in_byte = Serial.read();
if(in_byte != 10){
Serial.print("This is what I read: ");
Serial.println(in_byte);
if(in_byte >= 48 && in_byte <= 57){
flashcount = in_byte - 48;
Serial.println(flashcount);
}
else if(in_byte == 102){
speed = 1;
Serial.println("Speed set to fast.");
}
else if(in_byte == 115){
speed = 0;
Serial.println("Speed set to slow");
}
}
for(i = 0; i < flashcount; i++){
digitalWrite(LED_PIN,HIGH);
if(speed == 0){delay(750);}
delay(250);
digitalWrite(LED_PIN,LOW);
if(speed == 0){delay(750);}
delay(250);
}
flashcount = 0;
}
}
void loop() {
flashSerial();
}
| [
"46792241+CloakedGhost07@users.noreply.github.com"
] | 46792241+CloakedGhost07@users.noreply.github.com |
3b139f3fc58ad68d3b2d13e90abf569b968816a5 | 30b7ffd17845db982883a91ce8d04551281658c4 | /Codeforces/Round/Round 496/New folder/New folder/asdasd/A.cpp | da0dc00a172c173d83cff0b5dfb693b6f230ce98 | [] | no_license | shas9/codehub | 95418765b602b52edb0d48a473ad7e7a798f76e5 | bda856bf6ca0f3a1d59980895cfab82f690c75a2 | refs/heads/master | 2023-06-21T01:09:34.275708 | 2021-07-26T14:54:03 | 2021-07-26T14:54:03 | 389,404,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,506 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
vector<ll>graph[123459];
ll ara[123459], chk[200009];
ll node1, dist1 = 0, node2, dist2 = 0;
void dfs(ll u, ll p, ll lv)
{
if(lv > dist1 && chk[u]) {
dist1 = lv;
node1 = u;
}
for(ll i = 0; i < graph[u].size(); i++) {
ll nd = graph[u][i];
if(nd == p)
continue;
dfs(nd, u, lv + 1);
}
}
void dfs2(ll u, ll p, ll lv)
{
if(lv > dist2 && chk[u]) {
dist2 = lv;
node2 = u;
}
else if(lv == dist2 && chk[u]) {
node2 = min(node2, u);
}
for(ll i = 0; i < graph[u].size(); i++) {
ll nd = graph[u][i];
if(nd == p)
continue;
dfs2(nd, u, lv + 1);
}
}
ll dist = 0;
ll dfs3(ll node, ll par, ll lv)
{
for(ll i = 0; i < graph[u].size(); i++) {
ll nd = graph[u][i];
if(nd == p)
continue;
ll tmp = dfs3(nd, u, lv + 1);
if(tmp > 0)
dist += tmp;
}
}
int main()
{
ll n,m;
scanf("%lld %lld",&n,&m);
for(ll i=1;i<n;i++)
{
ll u, v;
scanf("%lld %lld",&u,&v);
graph[u].pb(v);
graph[v].pb(u);
}
for(ll i=1;i<=m;i++){
scanf("%lld",&ara[i]);
chk[ara[i]]=1;
}
dfs(1, -1, 1);
dfs2(node1, -1, 1);
cout << node2 << endl;
ans = dfs3(node, -1);
return 0;
}
| [
"shahwathasnaine@gmail.com"
] | shahwathasnaine@gmail.com |
2abdbeb285bbcf1ab1ac3945151585570162bcc6 | 19a012b6a66374235771a8c2baee19560e98f8d7 | /Codeforces/CR51/a.cpp | e1c9e0ee5f568dcef4d3a1b651505a7efed34706 | [] | no_license | juancate/CompetitivePrograming | 735e992fd6ac9c264059604fb7a2f2dfce74d330 | 8cea3695fd0dec7122c94ab45b4517cb13232fb3 | refs/heads/master | 2021-01-25T10:06:47.576470 | 2018-12-19T01:11:41 | 2018-12-19T01:11:41 | 14,966,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,032 | cpp | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cctype>
#include <cassert>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#define D(x) cerr << #x << " = " << x << endl
#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define FOREACH(it,v) for(typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it)
#define ALL(v) (v).begin(), (v).end()
typedef long long int64;
const int INF = (int)(1e9);
const int64 INFLL = (int64)(1e18);
const double EPS = 1e-13;
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
vector<bool> seen(n+1, false);
int k = 0, pos = 0;
for(;;) {
if(seen[pos])
break;
seen[pos] = true;
pos = (pos + k + 1) % n;
k++;
}
for(int i = 0; i < n; i++) {
if(!seen[i]) {
cout << "NO\n";
return 0;
}
}
cout << "YES\n";
return 0;
}
| [
"jcamargo@gmail.com"
] | jcamargo@gmail.com |
eb79d0f6badde2f8c9cbb97596d00736cd362920 | e2188ff27e1002b665bfe0d9060a1bae1c2e2d37 | /c++/12_EquityMC/Pricer.h | 813448d80740d08b64180e9a52e820e3732e0ade | [] | no_license | Claudio911015/UMA | b8fb28de32cf87d707c1eaf4f9886bb8a345148a | 032b901ea3a558aa703ab00b89a24f96da75ff37 | refs/heads/master | 2021-08-18T05:49:31.676008 | 2019-05-04T19:06:49 | 2019-05-04T19:06:49 | 184,843,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 513 | h | #ifndef PRICER_H
#define PRICER_H
#include <random>
#include "MarketData.h"
#include "Payoff.h"
class Results{
public:
double m_price;
double m_standardDeviation; //the standard error of m_price
double m_delta;
double m_gamma;
};
class Pricer{
public:
Pricer(int nPaths):m_numIndependentPaths(nPaths){}
Results go(const MarketData& m, const Payoff& p);
private:
int m_numIndependentPaths;
std::mt19937 m_rnd;
};
//perhaps add antithetic MC, more greeks, LR greeks, path dependent payoff.
#endif
| [
"claudiocp_2@hotmail.com"
] | claudiocp_2@hotmail.com |
888de065a43c643dab1eed5f4c0d89650b614d2d | f43543ac545c96daf74ee763e7fb1497f7ddf309 | /Chapter5/ass4.cpp | 3acadb4e27c8e4dbe54cda8e92040d4280370a46 | [] | no_license | Cyrus07/Cpp_pp | bb272e5fbdb100ade2aba4c268c0abd6072e4601 | 89450593a63bdc70ec9bf648e3a250e9e0e0f71c | refs/heads/master | 2021-01-10T17:38:26.006926 | 2016-01-07T14:36:24 | 2016-01-07T14:36:24 | 48,879,960 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 294 | cpp | #include<iostream>
int main()
{
using std::cout;
using std::endl;
double Daphne=100.0, Cleo=100.0;
int i=0;
while (Cleo <= Daphne)
{
i++;
Cleo*=1.05;
Daphne+=10;
}
cout << "Daphne: " << Daphne << endl
<< "Cleo: " << Cleo << endl
<< "It's year " << i << endl;
return 0;
}
| [
"teamworkhlc@gmail.com"
] | teamworkhlc@gmail.com |
0624831608292907e205e8c99fbb1cb95176923e | 590b56bc2e6fafd6a906c61f3f6dbd66ac5731f2 | /src/3rdParty/ImGui/imgui.h | f94fc5a7313ad0617162d01126a6be114d21c6c3 | [
"MIT"
] | permissive | erdinckaya/monitorx | 508a7e4a6764b4ef67253d1718e74414ae61576c | 5e100ed4b36dc4c9b01c2ab5a9a2207b99a460c1 | refs/heads/master | 2020-04-14T06:00:03.606503 | 2019-01-07T17:49:17 | 2019-01-07T17:49:17 | 163,675,108 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202,270 | h | // dear imgui, v1.67 WIP
// (headers)
// See imgui.cpp file for documentation.
// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
// Read 'Programmer guide' in imgui.cpp for notes on how to setup ImGui in your codebase.
// Get latest version at https://github.com/ocornut/imgui
/*
Index of this file:
// Header mess
// Forward declarations and basic types
// ImGui API (Dear ImGui end-user API)
// Flags & Enumerations
// ImGuiStyle
// ImGuiIO
// Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload)
// Obsolete functions
// Helpers (ImVector, ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor)
// Draw List API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListFlags, ImDrawList, ImDrawData)
// Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFont)
*/
#pragma once
// Configuration file (edit imconfig.h or define IMGUI_USER_CONFIG to your own filename)
#ifdef IMGUI_USER_CONFIG
#include IMGUI_USER_CONFIG
#endif
#if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H)
#include "imconfig.h"
#endif
//-----------------------------------------------------------------------------
// Header mess
//-----------------------------------------------------------------------------
#include <float.h> // FLT_MAX
#include <stdarg.h> // va_list
#include <stddef.h> // ptrdiff_t, NULL
#include <string.h> // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp
// Version
// (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY00 then bounced up to XYY01 when release tagging happens)
#define IMGUI_VERSION "1.67 WIP"
#define IMGUI_VERSION_NUM 16602
#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert))
// Define attributes of all API symbols declarations (e.g. for DLL under Windows)
// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default bindings files (imgui_impl_xxx.h)
#ifndef IMGUI_API
#define IMGUI_API
#endif
#ifndef IMGUI_IMPL_API
#define IMGUI_IMPL_API IMGUI_API
#endif
// Helper Macros
#ifndef IM_ASSERT
#include <assert.h>
#define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h
#endif
#if defined(__clang__) || defined(__GNUC__)
#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) // Apply printf-style warnings to user functions.
#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0)))
#else
#define IM_FMTARGS(FMT)
#define IM_FMTLIST(FMT)
#endif
#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) // Size of a static C-style array. Don't use on pointers!
#define IM_OFFSETOF(_TYPE,_MEMBER) ((size_t)&(((_TYPE*)0)->_MEMBER)) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in modern C++.
// Warnings
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__) && __GNUC__ >= 8
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#endif
//-----------------------------------------------------------------------------
// Forward declarations and basic types
//-----------------------------------------------------------------------------
struct ImDrawChannel; // Temporary storage for outputting drawing commands out of order, used by ImDrawList::ChannelsSplit()
struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call)
struct ImDrawData; // All draw command lists required to render the frame
struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder)
struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself)
struct ImDrawVert; // A single vertex (20 bytes by default, override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT)
struct ImFont; // Runtime data for a single font within a parent ImFontAtlas
struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader
struct ImFontConfig; // Configuration data when adding a font or merging fonts
struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*obsolete* please avoid using)
#ifndef ImTextureID
typedef void* ImTextureID; // User data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp)
#endif
struct ImGuiContext; // ImGui context (opaque)
struct ImGuiIO; // Main configuration and I/O between your application and ImGui
struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use)
struct ImGuiListClipper; // Helper to manually clip large list of items
struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro
struct ImGuiPayload; // User data payload for drag and drop operations
struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use)
struct ImGuiStorage; // Helper for key->value storage
struct ImGuiStyle; // Runtime data for styling/colors
struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbb][,ccccc]")
struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder)
// Typedefs and Enums/Flags (declared as int for compatibility with old C++, to allow using as flags and to not pollute the top of this file)
// Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists.
typedef unsigned int ImGuiID; // Unique ID used by widgets (typically hashed from a stack of string)
typedef unsigned short ImWchar; // Character for keyboard input/display
typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling
typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for Set*()
typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type
typedef int ImGuiDir; // -> enum ImGuiDir_ // Enum: A cardinal direction
typedef int ImGuiKey; // -> enum ImGuiKey_ // Enum: A key identifier (ImGui-side enum)
typedef int ImGuiNavInput; // -> enum ImGuiNavInput_ // Enum: An input identifier for navigation
typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor identifier
typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling
typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: for ImDrawList::AddRect*() etc.
typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList
typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas
typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags
typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit*(), ColorPicker*()
typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: for Columns(), BeginColumns()
typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags
typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo()
typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for *DragDrop*()
typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused()
typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc.
typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText*()
typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable()
typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar()
typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem()
typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode*(),CollapsingHeader()
typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin*()
typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData *data);
typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data);
// Scalar data types
typedef signed int ImS32; // 32-bit signed integer == int
typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors)
#if defined(_MSC_VER) && !defined(__clang__)
typedef signed __int64 ImS64; // 64-bit signed integer (pre and post C++11 with Visual Studio)
typedef unsigned __int64 ImU64; // 64-bit unsigned integer (pre and post C++11 with Visual Studio)
#elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100)
#include <stdint.h>
typedef int64_t ImS64; // 64-bit signed integer (pre C++11)
typedef uint64_t ImU64; // 64-bit unsigned integer (pre C++11)
#else
typedef signed long long ImS64; // 64-bit signed integer (post C++11)
typedef unsigned long long ImU64; // 64-bit unsigned integer (post C++11)
#endif
// 2D vector (often used to store positions, sizes, etc.)
struct ImVec2
{
float x, y;
ImVec2() { x = y = 0.0f; }
ImVec2(float _x, float _y) { x = _x; y = _y; }
float operator[] (size_t i) const { IM_ASSERT(i <= 1); return (&x)[i]; } // We very rarely use this [] operator, the assert overhead is fine.
#ifdef IM_VEC2_CLASS_EXTRA
IM_VEC2_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2.
#endif
};
// 4D vector (often used to store floating-point colors)
struct ImVec4
{
float x, y, z, w;
ImVec4() { x = y = z = w = 0.0f; }
ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; }
#ifdef IM_VEC4_CLASS_EXTRA
IM_VEC4_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4.
#endif
};
//-----------------------------------------------------------------------------
// ImGui: Dear ImGui end-user API
// (Inside a namespace so you can add extra functions in your own separate file. Please don't modify imgui.cpp/.h!)
//-----------------------------------------------------------------------------
namespace ImGui
{
// Context creation and access
// Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between imgui contexts.
// All those functions are not reliant on the current context.
IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL);
IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context
IMGUI_API ImGuiContext* GetCurrentContext();
IMGUI_API void SetCurrentContext(ImGuiContext* ctx);
IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert);
// Main
IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags)
IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame.
IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until Update()/EndFrame().
IMGUI_API void EndFrame(); // ends the ImGui frame. automatically called by Update(), you likely don't need to call that yourself directly. If you don't need to render data (skipping rendering) you may call EndFrame() but you'll have wasted CPU already! If you don't need to render, better to not create any imgui windows and not call NewFrame() at all!
IMGUI_API void Render(); // ends the ImGui frame, finalize the draw data. (Obsolete: optionally call io.RenderDrawListsFn if set. Nowadays, prefer calling your render function yourself.)
IMGUI_API ImDrawData* GetDrawData(); // valid after Update() and until the next call to NewFrame(). this is what you have to render. (Obsolete: this used to be passed to your io.RenderDrawListsFn() function.)
// Demo, Debug, Information
IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create demo/test window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application!
IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create about window. display Dear ImGui version, credits and build/system information.
IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create metrics window. display Dear ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc.
IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style)
IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles.
IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts.
IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls).
IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.23"
// Styles
IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default)
IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style
IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font
// Windows
// - Begin() = push window to the stack and start appending to it. End() = pop window from the stack.
// - You may append multiple times to the same window during the same frame.
// - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window,
// which clicking will set the boolean to false when clicked.
// - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting
// anything to the window. Always call a matching End() for each Begin() call, regardless of its return value!
// [this is due to legacy reason and is inconsistent with most other functions such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc.
// where the EndXXX call should only be called if the corresponding BeginXXX function returned true.]
// - Note that the bottom of window stack always contains a window called "Debug".
IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0);
IMGUI_API void End();
// Child Windows
// - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child.
// - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400).
// - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window.
// Always call a matching EndChild() for each BeginChild() call, regardless of its return value [this is due to legacy reason and is inconsistent with most other functions such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function returned true.]
IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0);
IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0);
IMGUI_API void EndChild();
// Windows Utilities
// - "current window" = the window we are appending into while inside a Begin()/End() block. "next window" = next window we will Begin() into.
IMGUI_API bool IsWindowAppearing();
IMGUI_API bool IsWindowCollapsed();
IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options.
IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ!
IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the window, to append your own drawing primitives
IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API)
IMGUI_API ImVec2 GetWindowSize(); // get current window size
IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x)
IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y)
IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates
IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos()
IMGUI_API float GetContentRegionAvailWidth(); //
IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates
IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates
IMGUI_API float GetWindowContentRegionWidth(); //
IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0,0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc.
IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin()
IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints.
IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ enforce the range of scrollbars). not including window decorations (title bar, menu bar, etc.). set an axis to 0.0f to leave it automatic. call before Begin()
IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin()
IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin()
IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground.
IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects.
IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects.
IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed().
IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus().
IMGUI_API void SetWindowFontScale(float scale); // set font scale. Adjust IO.FontGlobalScale if you want to scale all windows
IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position.
IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis.
IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state
IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus.
// Windows Scrolling
IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()]
IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()]
IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X
IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y
IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()]
IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()]
IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions.
// Parameters stacks (shared)
IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font
IMGUI_API void PopFont();
IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col);
IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col);
IMGUI_API void PopStyleColor(int count = 1);
IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val);
IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val);
IMGUI_API void PopStyleVar(int count = 1);
IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in.
IMGUI_API ImFont* GetFont(); // get current font
IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied
IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API
IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier
IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied
IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied
// Parameters stacks (current window)
IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side)
IMGUI_API void PopItemWidth();
IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position
IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space
IMGUI_API void PopTextWrapPos();
IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets
IMGUI_API void PopAllowKeyboardFocus();
IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame.
IMGUI_API void PopButtonRepeat();
// Cursor / Layout
// - By "cursor" we mean the current output position.
// - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down.
IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator.
IMGUI_API void SameLine(float local_pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates.
IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in an horizontal-layout context.
IMGUI_API void Spacing(); // add vertical spacing.
IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into.
IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if != 0
IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if != 0
IMGUI_API void BeginGroup(); // lock horizontal starting position
IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
IMGUI_API ImVec2 GetCursorPos(); // cursor position in window coordinates (relative to window position)
IMGUI_API float GetCursorPosX(); // (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion* etc.
IMGUI_API float GetCursorPosY(); // other functions such as GetCursorScreenPos or everything in ImDrawList::
IMGUI_API void SetCursorPos(const ImVec2& local_pos); // are using the main, absolute coordinate system.
IMGUI_API void SetCursorPosX(float local_x); // GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.)
IMGUI_API void SetCursorPosY(float local_y); //
IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position in window coordinates
IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API)
IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize]
IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item)
IMGUI_API float GetTextLineHeight(); // ~ FontSize
IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)
IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2
IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets)
// ID stack/scopes
// - Read the FAQ for more details about how ID are handled in dear imgui. If you are creating widgets in a loop you most
// likely want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them.
// - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others.
// - In this header file we use the "label"/"name" terminology to denote a string that will be displayed and used as an ID,
// whereas "str_id" denote a string that is only used as an ID and not normally displayed.
IMGUI_API void PushID(const char* str_id); // push string identifier into the ID stack. IDs == hash of the entire stack!
IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end);
IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack.
IMGUI_API void PushID(int int_id); // push integer into the ID stack.
IMGUI_API void PopID(); // pop from the ID stack.
IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself
IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end);
IMGUI_API ImGuiID GetID(const void* ptr_id);
// Widgets: Text
IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text.
IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // simple formatted text
IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1);
IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor();
IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor();
IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1);
IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize().
IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1);
IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets
IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text()
IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1);
// Widgets: Main
// - Most widgets return true when the value has been changed or when pressed/selected
IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button
IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text
IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); // button behavior without the visuals, useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.)
IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape
IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0));
IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding
IMGUI_API bool Checkbox(const char* label, bool* v);
IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value);
IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; }
IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer
IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL);
IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses
// Widgets: Combo Box
// - The new BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items.
// - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose.
IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0);
IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true!
IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1);
IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0"
IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1);
// Widgets: Drags
// - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped and can go off-bounds.
// - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
// - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision).
IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound
IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, float power = 1.0f);
IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); // If v_min >= v_max we have no bound
IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d");
IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d");
IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d");
IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL);
IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* v, float v_speed, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f);
IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* v, int components, float v_speed, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f);
// Widgets: Sliders
// - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds.
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders
IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg");
IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d");
IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d");
IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d");
IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d");
IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format = NULL, float power = 1.0f);
IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format = NULL, float power = 1.0f);
IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f);
IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d");
IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format = NULL, float power = 1.0f);
// Widgets: Input with Keyboard
// - If you want to use InputText() with a dynamic string type such as std::string or your own, see misc/cpp/imgui_stdlib.h
IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0f, double step_fast = 0.0f, const char* format = "%.6f", ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* v, const void* step = NULL, const void* step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* step = NULL, const void* step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags extra_flags = 0);
// Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be left-clicked to open a picker, and right-clicked to open an option menu.)
// - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can the pass the address of a first float element out of a contiguous structure, e.g. &myvector.x
IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0);
IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL);
IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0)); // display a colored square/button, hover for details, return true when pressed.
IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls.
// Widgets: Trees
// - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents.
IMGUI_API bool TreeNode(const char* label);
IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to completely decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet().
IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // "
IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0);
IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);
IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);
IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired.
IMGUI_API void TreePush(const void* ptr_id = NULL); // "
IMGUI_API void TreePop(); // ~ Unindent()+PopId()
IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing()
IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode
IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state.
IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop().
IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header
// Widgets: Selectables
// - A selectable highlights when hovered, and can display another color when selected.
// - Neighbors selectable extend their highlight bounds in order to leave no gap between them.
IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height
IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper.
// Widgets: List Boxes
// - FIXME: To be consistent with all the newer API, ListBoxHeader/ListBoxFooter should in reality be called BeginListBox/EndListBox. Will rename them.
IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1);
IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1);
IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards.
IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // "
IMGUI_API void ListBoxFooter(); // terminate the scrolling region. only call ListBoxFooter() if ListBoxHeader() returned true!
// Widgets: Data Plotting
IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float));
IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0));
IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float));
IMGUI_API void PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0));
// Widgets: Value() Helpers.
// - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace)
IMGUI_API void Value(const char* prefix, bool b);
IMGUI_API void Value(const char* prefix, int v);
IMGUI_API void Value(const char* prefix, unsigned int v);
IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL);
// Widgets: Menus
IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar.
IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true!
IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window).
IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true!
IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true!
IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true!
IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment
IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL
// Tooltips
IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of items).
IMGUI_API void EndTooltip();
IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip, typically use with ImGui::IsItemHovered(). overidde any previous call to SetTooltip().
IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1);
// Popups, Modals
// The properties of popups windows are:
// - They block normal mouse hovering detection outside them. (*)
// - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
// - Their visibility state (~bool) is held internally by imgui instead of being held by the programmer as we are used to with regular Begin() calls.
// User can manipulate the visibility state by calling OpenPopup().
// (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even when normally blocked by a popup.
// Those three properties are connected. The library needs to hold their visibility state because it can close popups at any time.
IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true!
IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp!
IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, int mouse_button = 1, bool also_over_items = true); // helper to open and begin popup when clicked on current window.
IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (where there are no imgui windows).
IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside)
IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true!
IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, int mouse_button = 1); // helper to open popup when clicked on last item (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened.
IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current begin-ed level of the popup stack.
IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup.
// Columns
// - You can also use SameLine(pos_x) to mimic simplified columns.
// - The columns API is work-in-progress and rather lacking (columns are arguably the worst part of dear imgui at the moment!)
IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true);
IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished
IMGUI_API int GetColumnIndex(); // get current column index
IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column
IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column
IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f
IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column
IMGUI_API int GetColumnsCount();
// Tab Bars, Tabs
// [BETA API] API may evolve!
IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar
IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true!
IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0);// create a Tab. Returns true if the Tab is selected.
IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true!
IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name.
// Logging/Capture
// - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging.
IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty (stdout)
IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file
IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard
IMGUI_API void LogFinish(); // stop logging (close file, etc.)
IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard
IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed)
// Drag and Drop
// [BETA API] API may evolve!
IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call when the current item is active. If this return true, you can call SetDragDropPayload() + EndDragDropSource()
IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t size, ImGuiCond cond = 0);// type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui.
IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true!
IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget()
IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released.
IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true!
IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for the payload type.
// Clipping
IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect);
IMGUI_API void PopClipRect();
// Focus, Activation
// - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item"
IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window.
IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget.
// Item/Widgets Utilities
// - Most of the functions are referring to the last/previous item we submitted.
// - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions.
IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options.
IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false)
IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation?
IMGUI_API bool IsItemClicked(int mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on) == IsMouseClicked(mouse_button) && IsItemHovered()
IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling)
IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets.
IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing.
IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item).
IMGUI_API bool IsAnyItemHovered();
IMGUI_API bool IsAnyItemActive();
IMGUI_API bool IsAnyItemFocused();
IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space)
IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space)
IMGUI_API ImVec2 GetItemRectSize(); // get size of last item
IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area.
// Miscellaneous Utilities
IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped.
IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side.
IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame.
IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame.
IMGUI_API ImDrawList* GetOverlayDrawList(); // this draw list will be the last rendered one, useful to quickly draw overlays shapes/text
IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances
IMGUI_API const char* GetStyleColorName(ImGuiCol idx);
IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it)
IMGUI_API ImGuiStorage* GetStateStorage();
IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f);
IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can.
IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame
IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window)
// Color Utilities
IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in);
IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in);
IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v);
IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b);
// Inputs Utilities
IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key]
IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your backend/engine stored them into io.KeysDown[]!
IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down). if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate
IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down)..
IMGUI_API int GetKeyPressedAmount(int key_index, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate
IMGUI_API bool IsMouseDown(int button); // is mouse button held (0=left, 1=right, 2=middle)
IMGUI_API bool IsAnyMouseDown(); // is any mouse button held
IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down) (0=left, 1=right, 2=middle)
IMGUI_API bool IsMouseDoubleClicked(int button); // did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime.
IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down)
IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold
IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block.
IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); //
IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls
IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse position at the time of opening popup we have BeginPopup() into
IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position. This is locked and return 0.0f until the mouse moves past a distance threshold at least once. If lock_threshold < -1.0f uses io.MouseDraggingThreshold
IMGUI_API void ResetMouseDragDelta(int button = 0); //
IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Update(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you
IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type
IMGUI_API void CaptureKeyboardFromApp(bool want_capture_keyboard_value = true); // attention: misleading name! manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application to handle). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard_value"; after the next NewFrame() call.
IMGUI_API void CaptureMouseFromApp(bool want_capture_mouse_value = true); // attention: misleading name! manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to handle). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse_value;" after the next NewFrame() call.
// Clipboard Utilities (also see the LogToClipboard() function to capture or output text data to the clipboard)
IMGUI_API const char* GetClipboardText();
IMGUI_API void SetClipboardText(const char* text);
// Settings/.Ini Utilities
// - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini").
// - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually.
IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename).
IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source.
IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename);
IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings.
// Memory Utilities
// - All those functions are not reliant on the current context.
// - If you reload the contents of imgui.cpp at runtime, you may need to call SetCurrentContext() + SetAllocatorFunctions() again.
IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data = NULL);
IMGUI_API void* MemAlloc(size_t size);
IMGUI_API void MemFree(void* ptr);
} // namespace ImGui
//-----------------------------------------------------------------------------
// Flags & Enumerations
//-----------------------------------------------------------------------------
// Flags for ImGui::Begin()
enum ImGuiWindowFlags_
{
ImGuiWindowFlags_None = 0,
ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar
ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip
ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window
ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically)
ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set.
ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it
ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame
ImGuiWindowFlags_NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f).
ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file
ImGuiWindowFlags_NoMouseInputs = 1 << 9, // Disable catching mouse, hovering test with pass through.
ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar
ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section.
ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state
ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus)
ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y)
ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x)
ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient)
ImGuiWindowFlags_NoNavInputs = 1 << 18, // No gamepad/keyboard navigation within the window
ImGuiWindowFlags_NoNavFocus = 1 << 19, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB)
ImGuiWindowFlags_UnsavedDocument = 1 << 20, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. When used in a tab/docking context, tab is selected on closure and closure is deferred by one frame to allow code to cancel the closure (with a confirmation popup, etc.) without flicker.
ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,
ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse,
ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,
// [Internal]
ImGuiWindowFlags_NavFlattened = 1 << 23, // [BETA] Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!)
ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild()
ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip()
ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup()
ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal()
ImGuiWindowFlags_ChildMenu = 1 << 28 // Don't use! For internal use by BeginMenu()
// [Obsolete]
//ImGuiWindowFlags_ShowBorders = 1 << 7, // --> Set style.FrameBorderSize=1.0f / style.WindowBorderSize=1.0f to enable borders around windows and items
//ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // --> Set io.ConfigWindowsResizeFromEdges and make sure mouse cursors are supported by back-end (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors)
};
// Flags for ImGui::InputText()
enum ImGuiInputTextFlags_
{
ImGuiInputTextFlags_None = 0,
ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/
ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef
ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z
ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs
ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus
ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified)
ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Callback on pressing TAB (for completion handling)
ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Callback on pressing Up/Down arrows (for history handling)
ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Callback on each iteration. User code may query cursor position, modify text buffer.
ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.
ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field
ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter).
ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally
ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode
ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode
ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*'
ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID().
ImGuiInputTextFlags_CharsScientific = 1 << 17, // Allow 0123456789.+-*/eE (Scientific notation input)
ImGuiInputTextFlags_CallbackResize = 1 << 18, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this)
// [Internal]
ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline()
};
// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*()
enum ImGuiTreeNodeFlags_
{
ImGuiTreeNodeFlags_None = 0,
ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected
ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader)
ImGuiTreeNodeFlags_AllowItemOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one
ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack
ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes)
ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open
ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node
ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open.
ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes).
ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow
ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding().
//ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 11, // FIXME: TODO: Extend hit box horizontally even if not framed
//ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 12, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible
ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 13, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop)
ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
, ImGuiTreeNodeFlags_AllowOverlapMode = ImGuiTreeNodeFlags_AllowItemOverlap
#endif
};
// Flags for ImGui::Selectable()
enum ImGuiSelectableFlags_
{
ImGuiSelectableFlags_None = 0,
ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window
ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column)
ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too
ImGuiSelectableFlags_Disabled = 1 << 3 // Cannot be selected, display greyed out text
};
// Flags for ImGui::BeginCombo()
enum ImGuiComboFlags_
{
ImGuiComboFlags_None = 0,
ImGuiComboFlags_PopupAlignLeft = 1 << 0, // Align the popup toward the left by default
ImGuiComboFlags_HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo()
ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default)
ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible
ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible
ImGuiComboFlags_NoArrowButton = 1 << 5, // Display on the preview box without the square arrow button
ImGuiComboFlags_NoPreview = 1 << 6, // Display only a square arrow button
ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest
};
// Flags for ImGui::BeginTabBar()
enum ImGuiTabBarFlags_
{
ImGuiTabBarFlags_None = 0,
ImGuiTabBarFlags_Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list
ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear
ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false.
ImGuiTabBarFlags_NoTabListPopupButton = 1 << 3,
ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4,
ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 5, // Resize tabs when they don't fit
ImGuiTabBarFlags_FittingPolicyScroll = 1 << 6, // Add scroll buttons when tabs don't fit
ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll,
ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown
};
// Flags for ImGui::BeginTabItem()
enum ImGuiTabItemFlags_
{
ImGuiTabItemFlags_None = 0,
ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. Also: tab is selected on closure and closure is deferred by one frame to allow code to undo it without flicker.
ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programatically make the tab selected when calling BeginTabItem()
ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false.
ImGuiTabItemFlags_NoPushId = 1 << 3 // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem()
};
// Flags for ImGui::IsWindowFocused()
enum ImGuiFocusedFlags_
{
ImGuiFocusedFlags_None = 0,
ImGuiFocusedFlags_ChildWindows = 1 << 0, // IsWindowFocused(): Return true if any children of the window is focused
ImGuiFocusedFlags_RootWindow = 1 << 1, // IsWindowFocused(): Test from root window (top most parent of the current hierarchy)
ImGuiFocusedFlags_AnyWindow = 1 << 2, // IsWindowFocused(): Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use ImGui::GetIO().WantCaptureMouse instead.
ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows
};
// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered()
// Note: if you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that. Please read the FAQ!
// Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls.
enum ImGuiHoveredFlags_
{
ImGuiHoveredFlags_None = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them.
ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered
ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy)
ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered
ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 3, // Return true even if a popup window is normally blocking access to this item/window
//ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 4, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet.
ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 5, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns.
ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 6, // Return true even if the position is overlapped by another window
ImGuiHoveredFlags_AllowWhenDisabled = 1 << 7, // Return true even if the item is disabled
ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped,
ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows
};
// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload()
enum ImGuiDragDropFlags_
{
ImGuiDragDropFlags_None = 0,
// BeginDragDropSource() flags
ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disable this behavior.
ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item.
ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item.
ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit.
ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously.
ImGuiDragDropFlags_SourceAutoExpirePayload = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged)
// AcceptDragDropPayload() flags
ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered.
ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target.
ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site.
ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect // For peeking ahead and inspecting the payload before delivery.
};
// Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by Dear ImGui.
#define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3]: Standard type for colors, without alpha. User code may use this type.
#define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4]: Standard type for colors. User code may use this type.
// A primary data type
enum ImGuiDataType_
{
ImGuiDataType_S32, // int
ImGuiDataType_U32, // unsigned int
ImGuiDataType_S64, // long long, __int64
ImGuiDataType_U64, // unsigned long long, unsigned __int64
ImGuiDataType_Float, // float
ImGuiDataType_Double, // double
ImGuiDataType_COUNT
};
// A cardinal direction
enum ImGuiDir_
{
ImGuiDir_None = -1,
ImGuiDir_Left = 0,
ImGuiDir_Right = 1,
ImGuiDir_Up = 2,
ImGuiDir_Down = 3,
ImGuiDir_COUNT
};
// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array
enum ImGuiKey_
{
ImGuiKey_Tab,
ImGuiKey_LeftArrow,
ImGuiKey_RightArrow,
ImGuiKey_UpArrow,
ImGuiKey_DownArrow,
ImGuiKey_PageUp,
ImGuiKey_PageDown,
ImGuiKey_Home,
ImGuiKey_End,
ImGuiKey_Insert,
ImGuiKey_Delete,
ImGuiKey_Backspace,
ImGuiKey_Space,
ImGuiKey_Enter,
ImGuiKey_Escape,
ImGuiKey_A, // for text edit CTRL+A: select all
ImGuiKey_C, // for text edit CTRL+C: copy
ImGuiKey_V, // for text edit CTRL+V: paste
ImGuiKey_X, // for text edit CTRL+X: cut
ImGuiKey_Y, // for text edit CTRL+Y: redo
ImGuiKey_Z, // for text edit CTRL+Z: undo
ImGuiKey_COUNT
};
// Gamepad/Keyboard directional navigation
// Keyboard: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
// Gamepad: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. Back-end: set ImGuiBackendFlags_HasGamepad and fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame().
// Read instructions in imgui.cpp for more details. Download PNG/PSD at http://goo.gl/9LgVZW.
enum ImGuiNavInput_
{
// Gamepad Mapping
ImGuiNavInput_Activate, // activate / open / toggle / tweak value // e.g. Cross (PS4), A (Xbox), A (Switch), Space (Keyboard)
ImGuiNavInput_Cancel, // cancel / close / exit // e.g. Circle (PS4), B (Xbox), B (Switch), Escape (Keyboard)
ImGuiNavInput_Input, // text input / on-screen keyboard // e.g. Triang.(PS4), Y (Xbox), X (Switch), Return (Keyboard)
ImGuiNavInput_Menu, // tap: toggle menu / hold: focus, move, resize // e.g. Square (PS4), X (Xbox), Y (Switch), Alt (Keyboard)
ImGuiNavInput_DpadLeft, // move / tweak / resize window (w/ PadMenu) // e.g. D-pad Left/Right/Up/Down (Gamepads), Arrow keys (Keyboard)
ImGuiNavInput_DpadRight, //
ImGuiNavInput_DpadUp, //
ImGuiNavInput_DpadDown, //
ImGuiNavInput_LStickLeft, // scroll / move window (w/ PadMenu) // e.g. Left Analog Stick Left/Right/Up/Down
ImGuiNavInput_LStickRight, //
ImGuiNavInput_LStickUp, //
ImGuiNavInput_LStickDown, //
ImGuiNavInput_FocusPrev, // next window (w/ PadMenu) // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch)
ImGuiNavInput_FocusNext, // prev window (w/ PadMenu) // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch)
ImGuiNavInput_TweakSlow, // slower tweaks // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch)
ImGuiNavInput_TweakFast, // faster tweaks // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch)
// [Internal] Don't use directly! This is used internally to differentiate keyboard from gamepad inputs for behaviors that require to differentiate them.
// Keyboard behavior that have no corresponding gamepad mapping (e.g. CTRL+TAB) will be directly reading from io.KeysDown[] instead of io.NavInputs[].
ImGuiNavInput_KeyMenu_, // toggle menu // = io.KeyAlt
ImGuiNavInput_KeyLeft_, // move left // = Arrow keys
ImGuiNavInput_KeyRight_, // move right
ImGuiNavInput_KeyUp_, // move up
ImGuiNavInput_KeyDown_, // move down
ImGuiNavInput_COUNT,
ImGuiNavInput_InternalStart_ = ImGuiNavInput_KeyMenu_
};
// Configuration flags stored in io.ConfigFlags. Set by user/application.
enum ImGuiConfigFlags_
{
ImGuiConfigFlags_None = 0,
ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. NewFrame() will automatically fill io.NavInputs[] based on io.KeysDown[].
ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. This is mostly to instruct your imgui back-end to fill io.NavInputs[]. Back-end also needs to set ImGuiBackendFlags_HasGamepad.
ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your binding, otherwise ImGui will react as if the mouse is jumping around back and forth.
ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set.
ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the back-end.
ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct back-end to not alter mouse cursor shape and visibility. Use if the back-end cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead.
// User storage (to allow your back-end/engine to communicate to code that may be shared between multiple projects. Those flags are not used by core ImGui)
ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware.
ImGuiConfigFlags_IsTouchScreen = 1 << 21 // Application is using a touch screen instead of a mouse.
};
// Back-end capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom back-end.
enum ImGuiBackendFlags_
{
ImGuiBackendFlags_None = 0,
ImGuiBackendFlags_HasGamepad = 1 << 0, // Back-end supports gamepad and currently has one connected.
ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Back-end supports honoring GetMouseCursor() value to change the OS cursor shape.
ImGuiBackendFlags_HasSetMousePos = 1 << 2 // Back-end supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set).
};
// Enumeration for PushStyleColor() / PopStyleColor()
enum ImGuiCol_
{
ImGuiCol_Text,
ImGuiCol_TextDisabled,
ImGuiCol_WindowBg, // Background of normal windows
ImGuiCol_ChildBg, // Background of child windows
ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows
ImGuiCol_Border,
ImGuiCol_BorderShadow,
ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input
ImGuiCol_FrameBgHovered,
ImGuiCol_FrameBgActive,
ImGuiCol_TitleBg,
ImGuiCol_TitleBgActive,
ImGuiCol_TitleBgCollapsed,
ImGuiCol_MenuBarBg,
ImGuiCol_ScrollbarBg,
ImGuiCol_ScrollbarGrab,
ImGuiCol_ScrollbarGrabHovered,
ImGuiCol_ScrollbarGrabActive,
ImGuiCol_CheckMark,
ImGuiCol_SliderGrab,
ImGuiCol_SliderGrabActive,
ImGuiCol_Button,
ImGuiCol_ButtonHovered,
ImGuiCol_ButtonActive,
ImGuiCol_Header,
ImGuiCol_HeaderHovered,
ImGuiCol_HeaderActive,
ImGuiCol_Separator,
ImGuiCol_SeparatorHovered,
ImGuiCol_SeparatorActive,
ImGuiCol_ResizeGrip,
ImGuiCol_ResizeGripHovered,
ImGuiCol_ResizeGripActive,
ImGuiCol_Tab,
ImGuiCol_TabHovered,
ImGuiCol_TabActive,
ImGuiCol_TabUnfocused,
ImGuiCol_TabUnfocusedActive,
ImGuiCol_PlotLines,
ImGuiCol_PlotLinesHovered,
ImGuiCol_PlotHistogram,
ImGuiCol_PlotHistogramHovered,
ImGuiCol_TextSelectedBg,
ImGuiCol_DragDropTarget,
ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item
ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB
ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active
ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active
ImGuiCol_COUNT
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
, ImGuiCol_ChildWindowBg = ImGuiCol_ChildBg, ImGuiCol_Column = ImGuiCol_Separator, ImGuiCol_ColumnHovered = ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive = ImGuiCol_SeparatorActive
, ImGuiCol_ModalWindowDarkening = ImGuiCol_ModalWindowDimBg
//ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered, // [unused since 1.60+] the close button now uses regular button colors.
//ImGuiCol_ComboBg, // [unused since 1.53+] ComboBg has been merged with PopupBg, so a redirect isn't accurate.
#endif
};
// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure.
// NB: the enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. During initialization, feel free to just poke into ImGuiStyle directly.
// NB: if changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type.
enum ImGuiStyleVar_
{
// Enum name ......................// Member in ImGuiStyle structure (see ImGuiStyle for descriptions)
ImGuiStyleVar_Alpha, // float Alpha
ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding
ImGuiStyleVar_WindowRounding, // float WindowRounding
ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize
ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize
ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign
ImGuiStyleVar_ChildRounding, // float ChildRounding
ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize
ImGuiStyleVar_PopupRounding, // float PopupRounding
ImGuiStyleVar_PopupBorderSize, // float PopupBorderSize
ImGuiStyleVar_FramePadding, // ImVec2 FramePadding
ImGuiStyleVar_FrameRounding, // float FrameRounding
ImGuiStyleVar_FrameBorderSize, // float FrameBorderSize
ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing
ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing
ImGuiStyleVar_IndentSpacing, // float IndentSpacing
ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize
ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding
ImGuiStyleVar_GrabMinSize, // float GrabMinSize
ImGuiStyleVar_GrabRounding, // float GrabRounding
ImGuiStyleVar_TabRounding, // float TabRounding
ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign
ImGuiStyleVar_COUNT
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
, ImGuiStyleVar_Count_ = ImGuiStyleVar_COUNT, ImGuiStyleVar_ChildWindowRounding = ImGuiStyleVar_ChildRounding
#endif
};
// Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton()
enum ImGuiColorEditFlags_
{
ImGuiColorEditFlags_None = 0,
ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (read 3 components from the input pointer).
ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on colored square.
ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview.
ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable colored square preview next to the inputs. (e.g. to show only the inputs)
ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview colored square).
ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview.
ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker).
ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead.
ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source.
// User Options (right-click on widget to change some of them). You can set application defaults using SetColorEditOptions(). The idea is that you probably don't want to override them in most of your calls, let the user choose and/or call SetColorEditOptions() during startup.
ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker.
ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque.
ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque.
ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well).
ImGuiColorEditFlags_RGB = 1 << 20, // [Inputs] // ColorEdit: choose one among RGB/HSV/HEX. ColorPicker: choose any combination using RGB/HSV/HEX.
ImGuiColorEditFlags_HSV = 1 << 21, // [Inputs] // "
ImGuiColorEditFlags_HEX = 1 << 22, // [Inputs] // "
ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255.
ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers.
ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [PickerMode] // ColorPicker: bar for Hue, rectangle for Sat/Value.
ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [PickerMode] // ColorPicker: wheel for Hue, triangle for Sat/Value.
// [Internal] Masks
ImGuiColorEditFlags__InputsMask = ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_HSV|ImGuiColorEditFlags_HEX,
ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float,
ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar,
ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_PickerHueBar // Change application default using SetColorEditOptions()
};
// Enumeration for GetMouseCursor()
// User code may request binding to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here
enum ImGuiMouseCursor_
{
ImGuiMouseCursor_None = -1,
ImGuiMouseCursor_Arrow = 0,
ImGuiMouseCursor_TextInput, // When hovering over InputText, etc.
ImGuiMouseCursor_ResizeAll, // (Unused by imgui functions)
ImGuiMouseCursor_ResizeNS, // When hovering over an horizontal border
ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column
ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window
ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window
ImGuiMouseCursor_Hand, // (Unused by imgui functions. Use for e.g. hyperlinks)
ImGuiMouseCursor_COUNT
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
, ImGuiMouseCursor_Count_ = ImGuiMouseCursor_COUNT
#endif
};
// Enumateration for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions
// Represent a condition.
// Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always.
enum ImGuiCond_
{
ImGuiCond_Always = 1 << 0, // Set the variable
ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed)
ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file)
ImGuiCond_Appearing = 1 << 3 // Set the variable if the object/window is appearing after being hidden/inactive (or the first time)
// Obsolete names (will be removed)
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
, ImGuiSetCond_Always = ImGuiCond_Always, ImGuiSetCond_Once = ImGuiCond_Once, ImGuiSetCond_FirstUseEver = ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing = ImGuiCond_Appearing
#endif
};
//-----------------------------------------------------------------------------
// ImGuiStyle
// You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame().
// During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values,
// and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors.
//-----------------------------------------------------------------------------
struct ImGuiStyle
{
float Alpha; // Global alpha applies to everything in ImGui.
ImVec2 WindowPadding; // Padding within a window.
float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows.
float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints().
ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered.
float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows.
float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding)
float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets).
float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets).
float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines.
ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label).
ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
float ColumnsMinSpacing; // Minimum horizontal spacing between two columns.
float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar.
float ScrollbarRounding; // Radius of grab corners for scrollbar.
float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar.
float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
float TabBorderSize; // Thickness of border around tabs.
ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for horizontally+vertically centered.
ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows.
ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly!
float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU.
bool AntiAliasedFill; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
ImVec4 Colors[ImGuiCol_COUNT];
IMGUI_API ImGuiStyle();
IMGUI_API void ScaleAllSizes(float scale_factor);
};
//-----------------------------------------------------------------------------
// ImGuiIO
// Communicate most settings and inputs/outputs to Dear ImGui using this structure.
// Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage.
//-----------------------------------------------------------------------------
struct ImGuiIO
{
//------------------------------------------------------------------
// Configuration (fill once) // Default value
//------------------------------------------------------------------
ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc.
ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by back-end (imgui_impl_xxx files or custom back-end) to communicate features supported by the back-end.
ImVec2 DisplaySize; // <unset> // Main display size, in pixels. For clamping windows positions.
float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds.
float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds.
const char* IniFilename; // = "imgui.ini" // Path to .ini file. Set NULL to disable automatic .ini loading/saving, if e.g. you want to manually load/save from memory.
const char* LogFilename; // = "imgui_log.txt"// Path to .log file (default parameter to ImGui::LogToFile when no file is specified).
float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds.
float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels.
float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging.
int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array which represent your "native" keyboard state.
float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.).
float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds.
void* UserData; // = NULL // Store your own data for retrieval by callbacks.
ImFontAtlas*Fonts; // <auto> // Load, rasterize and pack one or more fonts into a single texture.
float FontGlobalScale; // = 1.0f // Global scale all fonts
bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel.
ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0].
ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui.
ImVec2 DisplayVisibleMin; // <unset> // [OBSOLETE] If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area.
ImVec2 DisplayVisibleMax; // <unset> // [OBSOLETE] Just use io.DisplaySize! If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize
// Miscellaneous configuration options
bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by back-end implementations.
bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl (was called io.OptMacOSXBehaviors prior to 1.63)
bool ConfigInputTextCursorBlink; // = true // Set to false to disable blinking cursor, for users who consider it distracting. (was called: io.OptCursorBlink prior to 1.63)
bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be the a per-window ImGuiWindowFlags_ResizeFromAnySide flag)
bool ConfigWindowsMoveFromTitleBarOnly;// = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected.
//------------------------------------------------------------------
// Platform Functions
// (the imgui_impl_xxxx back-end files are setting those up for you)
//------------------------------------------------------------------
// Optional: Platform/Renderer back-end name (informational only! will be displayed in About Window) + User data for back-end/wrappers to store their own stuff.
const char* BackendPlatformName; // = NULL
const char* BackendRendererName; // = NULL
void* BackendPlatformUserData; // = NULL
void* BackendRendererUserData; // = NULL
void* BackendLanguageUserData; // = NULL
// Optional: Access OS clipboard
// (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures)
const char* (*GetClipboardTextFn)(void* user_data);
void (*SetClipboardTextFn)(void* user_data, const char* text);
void* ClipboardUserData;
// Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows)
// (default to use native imm32 api on Windows)
void (*ImeSetInputScreenPosFn)(int x, int y);
void* ImeWindowHandle; // = NULL // (Windows) Set this to your HWND to get automatic IME cursor positioning.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
// [OBSOLETE since 1.60+] Rendering function, will be automatically called in Update(). Please call your rendering function yourself now!
// You can obtain the ImDrawData* by calling ImGui::GetDrawData() after Update(). See example applications if you are unsure of how to implement this.
void (*RenderDrawListsFn)(ImDrawData* data);
#else
// This is only here to keep ImGuiIO the same size, so that IMGUI_DISABLE_OBSOLETE_FUNCTIONS can exceptionally be used outside of imconfig.h.
void* RenderDrawListsFnUnused;
#endif
//------------------------------------------------------------------
// Input - Fill before calling NewFrame()
//------------------------------------------------------------------
ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.)
bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API.
float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text.
float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all back-ends.
bool KeyCtrl; // Keyboard modifier pressed: Control
bool KeyShift; // Keyboard modifier pressed: Shift
bool KeyAlt; // Keyboard modifier pressed: Alt
bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows
bool KeysDown[512]; // Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys).
ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper.
float NavInputs[ImGuiNavInput_COUNT]; // Gamepad inputs (keyboard keys will be auto-mapped and be written here by ImGui::NewFrame, all values will be cleared back to zero in ImGui::EndFrame)
// Functions
IMGUI_API void AddInputCharacter(ImWchar c); // Add new character into InputCharacters[]
IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Add new characters into InputCharacters[] from an UTF-8 string
inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Clear the text input buffer manually
//------------------------------------------------------------------
// Output - Retrieve after calling NewFrame()
//------------------------------------------------------------------
bool WantCaptureMouse; // When io.WantCaptureMouse is true, imgui will use the mouse inputs, do not dispatch them to your main game/application (in both cases, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.).
bool WantCaptureKeyboard; // When io.WantCaptureKeyboard is true, imgui will use the keyboard inputs, do not dispatch them to your main game/application (in both cases, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.).
bool WantTextInput; // Mobile/console: when io.WantTextInput is true, you may display an on-screen keyboard. This is set by ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active).
bool WantSetMousePos; // MousePos has been altered, back-end should reposition mouse on next frame. Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled.
bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. IMPORTANT: You need to clear io.WantSaveIniSettings yourself.
bool NavActive; // Directional navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag.
bool NavVisible; // Directional navigation is visible and allowed (will handle ImGuiKey_NavXXX events).
float Framerate; // Application framerate estimation, in frame per second. Solely for convenience. Rolling average estimation based on IO.DeltaTime over 120 frames
int MetricsRenderVertices; // Vertices output during last call to Update()
int MetricsRenderIndices; // Indices output during last call to Update() = number of triangles * 3
int MetricsRenderWindows; // Number of visible windows
int MetricsActiveWindows; // Number of active windows
int MetricsActiveAllocations; // Number of active allocations, updated by MemAlloc/MemFree based on current context. May be off if you have multiple imgui contexts.
ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta.
//------------------------------------------------------------------
// [Internal] ImGui will maintain those fields. Forward compatibility not guaranteed!
//------------------------------------------------------------------
ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid)
ImVec2 MouseClickedPos[5]; // Position at time of clicking
double MouseClickedTime[5]; // Time of last click (used to figure out double-click)
bool MouseClicked[5]; // Mouse button went from !Down to Down
bool MouseDoubleClicked[5]; // Has mouse button been double-clicked?
bool MouseReleased[5]; // Mouse button went from Down to !Down
bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds.
float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked)
float MouseDownDurationPrev[5]; // Previous time the mouse button has been down
ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point
float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point
float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed)
float KeysDownDurationPrev[512]; // Previous duration the key has been down
float NavInputsDownDuration[ImGuiNavInput_COUNT];
float NavInputsDownDurationPrev[ImGuiNavInput_COUNT];
IMGUI_API ImGuiIO();
};
//-----------------------------------------------------------------------------
// Misc data structures
//-----------------------------------------------------------------------------
// Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used.
// The callback function should return 0 by default.
// Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details)
// - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB
// - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows
// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration
// - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.
// - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow.
struct ImGuiInputTextCallbackData
{
ImGuiInputTextFlags EventFlag; // One ImGuiInputTextFlags_Callback* // Read-only
ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only
void* UserData; // What user passed to InputText() // Read-only
// Arguments for the different callback events
// - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary.
// - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state.
ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0;
ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History]
char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer!
int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length()
int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1
bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always]
int CursorPos; // // Read-write // [Completion,History,Always]
int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection)
int SelectionEnd; // // Read-write // [Completion,History,Always]
// Helper functions for text manipulation.
// Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection.
IMGUI_API ImGuiInputTextCallbackData();
IMGUI_API void DeleteChars(int pos, int bytes_count);
IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL);
bool HasSelection() const { return SelectionStart != SelectionEnd; }
};
// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin().
// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough.
struct ImGuiSizeCallbackData
{
void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints()
ImVec2 Pos; // Read-only. Window position, for reference.
ImVec2 CurrentSize; // Read-only. Current window size.
ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing.
};
// Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload()
struct ImGuiPayload
{
// Members
void* Data; // Data (copied and owned by dear imgui)
int DataSize; // Data size
// [Internal]
ImGuiID SourceId; // Source item id
ImGuiID SourceParentId; // Source parent id (if available)
int DataFrameCount; // Data timestamp
char DataType[32+1]; // Data type tag (short user-supplied string, 32 characters max)
bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets)
bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item.
ImGuiPayload() { Clear(); }
void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; }
bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; }
bool IsPreview() const { return Preview; }
bool IsDelivery() const { return Delivery; }
};
//-----------------------------------------------------------------------------
// Obsolete functions (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details)
//-----------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
namespace ImGui
{
// OBSOLETED in 1.66 (from Sep 2018)
static inline void SetScrollHere(float center_ratio=0.5f){ SetScrollHereY(center_ratio); }
// OBSOLETED in 1.63 (from Aug 2018)
static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); }
// OBSOLETED in 1.61 (from Apr 2018)
IMGUI_API bool InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags = 0); // Use the 'const char* format' version instead of 'decimal_precision'!
IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags = 0);
IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags = 0);
// OBSOLETED in 1.60 (from Dec 2017)
static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); }
static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); }
static inline ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = 0.f) { (void)on_edge; (void)outward; IM_ASSERT(0); return pos; }
// OBSOLETED in 1.53 (between Oct 2017 and Dec 2017)
static inline void ShowTestWindow() { return ShowDemoWindow(); }
static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); }
static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); }
static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); }
static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); }
// OBSOLETED in 1.52 (between Aug 2017 and Oct 2017)
IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha_override = -1.0f, ImGuiWindowFlags flags = 0); // Use SetNextWindowSize(size, ImGuiCond_FirstUseEver) + SetNextWindowBgAlpha() instead.
static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); }
static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); }
static inline void SetNextWindowPosCenter(ImGuiCond c=0) { ImGuiIO& io = GetIO(); SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), c, ImVec2(0.5f, 0.5f)); }
// OBSOLETED in 1.51 (between Jun 2017 and Aug 2017)
static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); }
static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // This was misleading and partly broken. You probably want to use the ImGui::GetIO().WantCaptureMouse flag instead.
static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); }
static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); }
}
typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETE in 1.63 (from Aug 2018): made the names consistent
typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData;
#endif
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
// Helper: Lightweight std::vector<> like class to avoid dragging dependencies (also: Windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug).
// *Important* Our implementation does NOT call C++ constructors/destructors. This is intentional, we do not require it but you have to be mindful of that. Do _not_ use this class as a std::vector replacement in your code!
template<typename T>
class ImVector
{
public:
int Size;
int Capacity;
T* Data;
typedef T value_type;
typedef value_type* iterator;
typedef const value_type* const_iterator;
inline ImVector() { Size = Capacity = 0; Data = NULL; }
inline ~ImVector() { if (Data) ImGui::MemFree(Data); }
inline ImVector(const ImVector<T>& src) { Size = Capacity = 0; Data = NULL; operator=(src); }
inline ImVector<T>& operator=(const ImVector<T>& src) { clear(); resize(src.Size); memcpy(Data, src.Data, (size_t)Size * sizeof(value_type)); return *this; }
inline bool empty() const { return Size == 0; }
inline int size() const { return Size; }
inline int capacity() const { return Capacity; }
inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; }
inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; }
inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } }
inline iterator begin() { return Data; }
inline const_iterator begin() const { return Data; }
inline iterator end() { return Data + Size; }
inline const_iterator end() const { return Data + Size; }
inline value_type& front() { IM_ASSERT(Size > 0); return Data[0]; }
inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; }
inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; }
inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; }
inline void swap(ImVector<value_type>& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; }
inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; }
inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; }
inline void resize(int new_size,const value_type& v){ if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; }
inline void reserve(int new_capacity)
{
if (new_capacity <= Capacity)
return;
value_type* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(value_type));
if (Data)
{
memcpy(new_data, Data, (size_t)Size * sizeof(value_type));
ImGui::MemFree(Data);
}
Data = new_data;
Capacity = new_capacity;
}
// NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden.
inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; }
inline void pop_back() { IM_ASSERT(Size > 0); Size--; }
inline void push_front(const value_type& v) { if (Size == 0) push_back(v); else insert(Data, v); }
inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; }
inline iterator erase(const_iterator it, const_iterator it_last){ IM_ASSERT(it >= Data && it < Data+Size && it_last > it && it_last <= Data+Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - count) * sizeof(value_type)); Size -= (int)count; return Data + off; }
inline iterator erase_unsorted(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; if (it < Data+Size-1) memcpy(Data + off, Data + Size - 1, sizeof(value_type)); Size--; return Data + off; }
inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; }
inline bool contains(const value_type& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; }
inline int index_from_pointer(const_iterator it) const { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; return (int)off; }
};
// Helper: IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() macros to call MemAlloc + Placement New, Placement Delete + MemFree
// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax.
// Defining a custom placement new() with a dummy parameter allows us to bypass including <new> which on some platforms complains when user has disabled exceptions.
struct ImNewDummy {};
inline void* operator new(size_t, ImNewDummy, void* ptr) { return ptr; }
inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symetrical new()
#define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR)
#define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE
template<typename T> void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } }
// Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame.
// Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame");
struct ImGuiOnceUponAFrame
{
ImGuiOnceUponAFrame() { RefFrame = -1; }
mutable int RefFrame;
operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; }
};
// Helper: Macro for ImGuiOnceUponAFrame. Attention: The macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Will obsolete
#define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf; if (imgui_oaf)
#endif
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
struct ImGuiTextFilter
{
IMGUI_API ImGuiTextFilter(const char* default_filter = "");
IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build
IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const;
IMGUI_API void Build();
void Clear() { InputBuf[0] = 0; Build(); }
bool IsActive() const { return !Filters.empty(); }
// [Internal]
struct TextRange
{
const char* b;
const char* e;
TextRange() { b = e = NULL; }
TextRange(const char* _b, const char* _e) { b = _b; e = _e; }
const char* begin() const { return b; }
const char* end () const { return e; }
bool empty() const { return b == e; }
IMGUI_API void split(char separator, ImVector<TextRange>* out) const;
};
char InputBuf[256];
ImVector<TextRange> Filters;
int CountGrep;
};
// Helper: Growable text buffer for logging/accumulating text
// (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder')
struct ImGuiTextBuffer
{
ImVector<char> Buf;
static char EmptyString[1];
ImGuiTextBuffer() { }
inline char operator[](int i) { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; }
const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; }
const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator
int size() const { return Buf.Data ? Buf.Size - 1 : 0; }
bool empty() { return Buf.Size <= 1; }
void clear() { Buf.clear(); }
void reserve(int capacity) { Buf.reserve(capacity); }
const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; }
IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2);
IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2);
};
// Helper: Key->Value storage
// Typically you don't have to worry about this since a storage is held within each Window.
// We use it to e.g. store collapse state for a tree (Int 0/1)
// This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame)
// You can use it as custom user storage for temporary values. Declare your own storage if, for example:
// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state).
// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient)
// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types.
struct ImGuiStorage
{
struct Pair
{
ImGuiID key;
union { int val_i; float val_f; void* val_p; };
Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; }
Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; }
Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; }
};
ImVector<Pair> Data;
// - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N)
// - Set***() functions find pair, insertion on demand if missing.
// - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair.
void Clear() { Data.clear(); }
IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const;
IMGUI_API void SetInt(ImGuiID key, int val);
IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const;
IMGUI_API void SetBool(ImGuiID key, bool val);
IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const;
IMGUI_API void SetFloat(ImGuiID key, float val);
IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL
IMGUI_API void SetVoidPtr(ImGuiID key, void* val);
// - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set.
// - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
// - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct)
// float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar;
IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0);
IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false);
IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f);
IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL);
// Use on your own storage if you know only integer are being stored (open/close all tree nodes)
IMGUI_API void SetAllInt(int val);
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
IMGUI_API void BuildSortByKey();
};
// Helper: Manually clip large list of items.
// If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all.
// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped.
// ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null.
// Usage:
// ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced.
// while (clipper.Step())
// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
// ImGui::Text("line number %d", i);
// - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor).
// - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
// - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.)
// - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
struct ImGuiListClipper
{
float StartPosY;
float ItemsHeight;
int ItemsCount, StepNo, DisplayStart, DisplayEnd;
// items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step).
// items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing().
// If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step().
ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want).
~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false.
IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items.
IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1.
IMGUI_API void End(); // Automatically called on the last call of Step() that returns false.
};
// Helpers macros to generate 32-bits encoded colors
#ifdef IMGUI_USE_BGRA_PACKED_COLOR
#define IM_COL32_R_SHIFT 16
#define IM_COL32_G_SHIFT 8
#define IM_COL32_B_SHIFT 0
#define IM_COL32_A_SHIFT 24
#define IM_COL32_A_MASK 0xFF000000
#else
#define IM_COL32_R_SHIFT 0
#define IM_COL32_G_SHIFT 8
#define IM_COL32_B_SHIFT 16
#define IM_COL32_A_SHIFT 24
#define IM_COL32_A_MASK 0xFF000000
#endif
#define IM_COL32(R,G,B,A) (((ImU32)(A)<<IM_COL32_A_SHIFT) | ((ImU32)(B)<<IM_COL32_B_SHIFT) | ((ImU32)(G)<<IM_COL32_G_SHIFT) | ((ImU32)(R)<<IM_COL32_R_SHIFT))
#define IM_COL32_WHITE IM_COL32(255,255,255,255) // Opaque white = 0xFFFFFFFF
#define IM_COL32_BLACK IM_COL32(0,0,0,255) // Opaque black
#define IM_COL32_BLACK_TRANS IM_COL32(0,0,0,0) // Transparent black = 0x00000000
// Helper: ImColor() implicity converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float)
// Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API.
// **Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. MAY OBSOLETE.
// **None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. Explicitly cast to ImU32 or ImVec4 if needed.
struct ImColor
{
ImVec4 Value;
ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; }
ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; }
ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; }
ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; }
ImColor(const ImVec4& col) { Value = col; }
inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); }
inline operator ImVec4() const { return Value; }
// FIXME-OBSOLETE: May need to obsolete/cleanup those helpers.
inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; }
static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); }
};
//-----------------------------------------------------------------------------
// Draw List API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListFlags, ImDrawList, ImDrawData)
// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList.
//-----------------------------------------------------------------------------
// Draw callbacks for advanced uses.
// NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering,
// you can poke into the draw list for that! Draw callback may be useful for example to: A) Change your GPU render state,
// B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc.
// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }'
typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd);
// Typically, 1 command = 1 GPU draw call (unless command is a callback)
struct ImDrawCmd
{
unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[].
ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates
ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas.
ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally.
void* UserCallbackData; // The draw callback code can access this.
ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = ClipRect.z = ClipRect.w = 0.0f; TextureId = (ImTextureID)NULL; UserCallback = NULL; UserCallbackData = NULL; }
};
// Vertex index (override with '#define ImDrawIdx unsigned int' in imconfig.h)
#ifndef ImDrawIdx
typedef unsigned short ImDrawIdx;
#endif
// Vertex layout
#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT
struct ImDrawVert
{
ImVec2 pos;
ImVec2 uv;
ImU32 col;
};
#else
// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h
// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine.
// The type has to be described within the macro (you can either declare the struct or use a typedef)
// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM.
IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT;
#endif
// Draw channels are used by the Columns API to "split" the render list into different channels while building, so items of each column can be batched together.
// You can also use them to simulate drawing layers and submit primitives in a different order than how they will be rendered.
struct ImDrawChannel
{
ImVector<ImDrawCmd> CmdBuffer;
ImVector<ImDrawIdx> IdxBuffer;
};
enum ImDrawCornerFlags_
{
ImDrawCornerFlags_TopLeft = 1 << 0, // 0x1
ImDrawCornerFlags_TopRight = 1 << 1, // 0x2
ImDrawCornerFlags_BotLeft = 1 << 2, // 0x4
ImDrawCornerFlags_BotRight = 1 << 3, // 0x8
ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, // 0x3
ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, // 0xC
ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, // 0x5
ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, // 0xA
ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience
};
enum ImDrawListFlags_
{
ImDrawListFlags_None = 0,
ImDrawListFlags_AntiAliasedLines = 1 << 0, // Lines are anti-aliased (*2 the number of triangles for 1.0f wide line, otherwise *3 the number of triangles)
ImDrawListFlags_AntiAliasedFill = 1 << 1 // Filled shapes have anti-aliased edges (*2 the number of vertices)
};
// Draw command list
// This is the low-level list of polygons that ImGui functions are filling. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering.
// Each ImGui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to access the current window draw list and draw custom primitives.
// You can interleave normal ImGui:: calls and adding primitives to the current draw list.
// All positions are generally in pixel coordinates (top-left at (0,0), bottom-right at io.DisplaySize), but you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well)
// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects.
struct ImDrawList
{
// This is what you have to render
ImVector<ImDrawCmd> CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback.
ImVector<ImDrawIdx> IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those
ImVector<ImDrawVert> VtxBuffer; // Vertex buffer.
ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive.
// [Internal, used while building lists]
const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context)
const char* _OwnerName; // Pointer to owner window's name for debugging
unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size
ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)
ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)
ImVector<ImVec4> _ClipRectStack; // [Internal]
ImVector<ImTextureID> _TextureIdStack; // [Internal]
ImVector<ImVec2> _Path; // [Internal] current path building
int _ChannelsCurrent; // [Internal] current channel number (0)
int _ChannelsCount; // [Internal] number of active channels (1+)
ImVector<ImDrawChannel> _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size)
// If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui)
ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; _OwnerName = NULL; Clear(); }
~ImDrawList() { ClearFreeMemory(); }
IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Update-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)
IMGUI_API void PushClipRectFullScreen();
IMGUI_API void PopClipRect();
IMGUI_API void PushTextureID(ImTextureID texture_id);
IMGUI_API void PopTextureID();
inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); }
inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); }
// Primitives
IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f);
IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round
IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); // a: upper-left, b: lower-right
IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left);
IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f);
IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col);
IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f);
IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col);
IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f);
IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12);
IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL);
IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL);
IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF);
IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF);
IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners = ImDrawCornerFlags_All);
IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness);
IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col); // Note: Anti-aliased filling requires points to be in clockwise order.
IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0);
// Stateful path API, add points then finish with PathFillConvex() or PathStroke()
inline void PathClear() { _Path.resize(0); }
inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); }
inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); }
inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); PathClear(); } // Note: Anti-aliased filling requires points to be in clockwise order.
inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness); PathClear(); }
IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10);
IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle
IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0);
IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All);
// Channels
// - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives)
// - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end)
IMGUI_API void ChannelsSplit(int channels_count);
IMGUI_API void ChannelsMerge();
IMGUI_API void ChannelsSetCurrent(int channel_index);
// Advanced
IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles.
IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible
IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer.
// Internal helpers
// NB: all primitives needs to be reserved via PrimReserve() beforehand!
IMGUI_API void Clear();
IMGUI_API void ClearFreeMemory();
IMGUI_API void PrimReserve(int idx_count, int vtx_count);
IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles)
IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col);
IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col);
inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; }
inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; }
inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); }
IMGUI_API void UpdateClipRect();
IMGUI_API void UpdateTextureID();
};
// All draw data to render an ImGui frame
// (NB: the style and the naming convention here is a little inconsistent but we preserve them for backward compatibility purpose)
struct ImDrawData
{
bool Valid; // Only valid after Update() is called and before the next NewFrame() is called.
ImDrawList** CmdLists; // Array of ImDrawList* to render. The ImDrawList are owned by ImGuiContext and only pointed to from here.
int CmdListsCount; // Number of ImDrawList* to render
int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size
int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size
ImVec2 DisplayPos; // Upper-left position of the viewport to render (== upper-left of the orthogonal projection matrix to use)
ImVec2 DisplaySize; // Size of the viewport to render (== io.DisplaySize for the main viewport) (DisplayPos + DisplaySize == lower-right of the orthogonal projection matrix to use)
// Functions
ImDrawData() { Valid = false; Clear(); }
~ImDrawData() { Clear(); }
void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; DisplayPos = DisplaySize = ImVec2(0.f, 0.f); } // The ImDrawList are owned by ImGuiContext!
IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution.
};
//-----------------------------------------------------------------------------
// Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFont)
//-----------------------------------------------------------------------------
struct ImFontConfig
{
void* FontData; // // TTF/OTF data
int FontDataSize; // // TTF/OTF data size
bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself).
int FontNo; // 0 // Index of font within TTF/OTF file
float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height).
int OversampleH; // 3 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis.
int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis.
bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input.
const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.
float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font
float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs
bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights.
unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one.
float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable.
// [Internal]
char Name[40]; // Name (strictly to ease debugging)
ImFont* DstFont;
IMGUI_API ImFontConfig();
};
struct ImFontGlyph
{
ImWchar Codepoint; // 0x0000..0xFFFF
float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in)
float X0, Y0, X1, Y1; // Glyph corners
float U0, V0, U1, V1; // Texture coordinates
};
enum ImFontAtlasFlags_
{
ImFontAtlasFlags_None = 0,
ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two
ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas
};
// Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding:
// - One or more fonts.
// - Custom graphics data needed to render the shapes needed by Dear ImGui.
// - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas).
// It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api.
// - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you.
// - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data.
// - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples)
// - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API.
// This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details.
// Common pitfalls:
// - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the
// atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data.
// - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction.
// You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed,
// - Even though many functions are suffixed with "TTF", OTF data is supported just as well.
// - This is an old API and it is currently awkward for those and and various other reasons! We will address them in the future!
struct ImFontAtlas
{
IMGUI_API ImFontAtlas();
IMGUI_API ~ImFontAtlas();
IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg);
IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL);
IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL);
IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed.
IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp.
IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter.
IMGUI_API void ClearInputData(); // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts.
IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory.
IMGUI_API void ClearFonts(); // Clear output font data (glyphs storage, UV coordinates).
IMGUI_API void Clear(); // Clear all input and output.
// Build atlas, retrieve pixel data.
// User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID().
// The pitch is always = Width * BytesPerPixels (1 or 4)
// Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into
// the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste.
IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions.
IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel
IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel
bool IsBuilt() { return Fonts.Size > 0 && (TexPixelsAlpha8 != NULL || TexPixelsRGBA32 != NULL); }
void SetTexID(ImTextureID id) { TexID = id; }
//-------------------------------------------
// Glyph Ranges
//-------------------------------------------
// Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list)
// NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. See FAQ for details.
// NB: Consider using GlyphRangesBuilder to build glyph ranges from textual data.
IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin
IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters
IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs
IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese
IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters
IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters
// Helpers to build glyph ranges from text data. Feed your application strings/characters to it then call BuildRanges().
struct GlyphRangesBuilder
{
ImVector<unsigned char> UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used)
GlyphRangesBuilder() { UsedChars.resize(0x10000 / 8); memset(UsedChars.Data, 0, 0x10000 / 8); }
bool GetBit(int n) const { return (UsedChars[n >> 3] & (1 << (n & 7))) != 0; }
void SetBit(int n) { UsedChars[n >> 3] |= 1 << (n & 7); } // Set bit 'c' in the array
void AddChar(ImWchar c) { SetBit(c); } // Add character
IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added)
IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext
IMGUI_API void BuildRanges(ImVector<ImWchar>* out_ranges); // Output new ranges
};
//-------------------------------------------
// Custom Rectangles/Glyphs API
//-------------------------------------------
// You can request arbitrary rectangles to be packed into the atlas, for your own purposes. After calling Build(), you can query the rectangle position and render your pixels.
// You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs.
struct CustomRect
{
unsigned int ID; // Input // User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom texture data.
unsigned short Width, Height; // Input // Desired rectangle dimension
unsigned short X, Y; // Output // Packed position in Atlas
float GlyphAdvanceX; // Input // For custom font glyphs only (ID<0x10000): glyph xadvance
ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID<0x10000): glyph display offset
ImFont* Font; // Input // For custom font glyphs only (ID<0x10000): target font
CustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; }
bool IsPacked() const { return X != 0xFFFF; }
};
IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x10000. Id >= 0x80000000 are reserved for ImGui and ImDrawList
IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); // Id needs to be < 0x10000 to register a rectangle to map into a specific font.
const CustomRect* GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; }
// [Internal]
IMGUI_API void CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max);
IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]);
//-------------------------------------------
// Members
//-------------------------------------------
bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert.
ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_)
ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure.
int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.
int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1.
// [Internal]
// NB: Access texture data via GetTexData*() calls! Which will setup a default font for you.
unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight
unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4
int TexWidth; // Texture width calculated during Build().
int TexHeight; // Texture height calculated during Build().
ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight)
ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel
ImVector<ImFont*> Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font.
ImVector<CustomRect> CustomRects; // Rectangles for packing custom texture data into the atlas.
ImVector<ImFontConfig> ConfigData; // Internal data
int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList
};
// Font runtime data and rendering
// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32().
struct ImFont
{
// Members: Hot ~62/78 bytes
float FontSize; // <user set> // Height of characters, set during loading (don't change after loading)
float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale()
ImVec2 DisplayOffset; // = (0.f,0.f) // Offset font rendering by xx pixels
ImVector<ImFontGlyph> Glyphs; // // All glyphs.
ImVector<float> IndexAdvanceX; // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI).
ImVector<ImWchar> IndexLookup; // // Sparse. Index glyphs by Unicode code-point.
const ImFontGlyph* FallbackGlyph; // == FindGlyph(FontFallbackChar)
float FallbackAdvanceX; // == FallbackGlyph->AdvanceX
ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar()
// Members: Cold ~18/26 bytes
short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont.
ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData
ImFontAtlas* ContainerAtlas; // // What we has been loaded into
float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize]
bool DirtyLookupTables;
int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs)
// Methods
IMGUI_API ImFont();
IMGUI_API ~ImFont();
IMGUI_API void ClearOutputData();
IMGUI_API void BuildLookupTable();
IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const;
IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const;
IMGUI_API void SetFallbackChar(ImWchar c);
float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; }
bool IsLoaded() const { return ContainerAtlas != NULL; }
const char* GetDebugName() const { return ConfigData ? ConfigData->Name : "<unknown>"; }
// 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable.
// 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable.
IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8
IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const;
IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c) const;
IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const;
// [Internal]
IMGUI_API void GrowIndex(int new_size);
IMGUI_API void AddGlyph(ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x);
IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
typedef ImFontGlyph Glyph; // OBSOLETE 1.52+
#endif
};
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__) && __GNUC__ >= 8
#pragma GCC diagnostic pop
#endif
// Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h)
#ifdef IMGUI_INCLUDE_IMGUI_USER_H
#include "imgui_user.h"
#endif
| [
"erdinckaya@yandex.com"
] | erdinckaya@yandex.com |
1f8199c241d96eab456cc804103218b6e89b1e4c | a19c02e59d9d5990a92ee64d97d3deab2d8b7f0f | /src/Robot.cpp | b06d36d0cee76b87fe81cb141955d9f1b43304fd | [] | no_license | CloverBots/steamworks-2017 | 556b08dd546c54738656c15b09208e671692491c | 174d807b4bd33e8c846d5833a594176112895e5d | refs/heads/master | 2021-01-14T08:03:09.567910 | 2017-08-05T23:32:04 | 2017-08-05T23:32:04 | 81,898,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,222 | cpp | #include <memory>
#include <Commands/Command.h>
#include <Commands/PlaceGearCenter.h>
#include <Commands/PlaceGearLeft.h>
#include <Commands/PlaceGearRight.h>
#include <Commands/ShootSequence.h>
#include <Commands/Scheduler.h>
#include <IterativeRobot.h>
#include <LiveWindow/LiveWindow.h>
#include <SmartDashboard/SendableChooser.h>
#include <SmartDashboard/SmartDashboard.h>
#include "CommandBase.h"
#include "Commands/DriveForward.h"
class Robot : public frc::IterativeRobot {
public:
void RobotInit() override {
CommandBase::Init();
chooser.AddDefault("Do Nothing", 0);
chooser.AddObject("Shoot Immediately", new ShootSequence());
chooser.AddObject("Drive Forward", new DriveForward());
chooser.AddObject("Place Gear (Center)", new PlaceGearCenter());
chooser.AddObject("Place Gear (Left)", new PlaceGearLeft(false));
chooser.AddObject("Place Gear (Left, Boiler)", new PlaceGearLeft(true));
chooser.AddObject("Place Gear (Right)", new PlaceGearRight(false));
chooser.AddObject("Place Gear (Right, Boiler)", new PlaceGearRight(true));
frc::SmartDashboard::PutData("Auto Modes", &chooser);
// frc::SmartDashboard::PutNumber("Shooter Speed", 0.0);
// frc::SmartDashboard::PutNumber("Shooter P", 0.0);
// frc::SmartDashboard::PutNumber("Shooter I", 0.0);
// frc::SmartDashboard::PutNumber("Shooter D", 0.0);
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
void DisabledInit() override {
CommandBase::shooterSubsystem->SetPIDEnabled(false);
//SmartDashboard::PutString("Enabled:", "False");
}
void DisabledPeriodic() override {
frc::Scheduler::GetInstance()->Run();
}
/**
* This autonomous (along with the chooser code above) shows how to select
* between different autonomous modes using the dashboard. The sendable
* chooser code works with the Java SmartDashboard. If you prefer the
* LabVIEW Dashboard, remove all of the chooser code and uncomment the
* GetString code to get the auto name from the text box below the Gyro.
*
* You can add additional auto modes by adding additional commands to the
* chooser code above (like the commented example) or additional comparisons
* to the if-else structure below with additional strings & commands.
*/
void AutonomousInit() override {
//CommandBase::shooterSubsystem->SetPIDEnabled(true);
CommandBase::pDriveSystem->ResetGyro();
/* std::string autoSelected = frc::SmartDashboard::GetString("Auto Selector", "Default");
if (autoSelected == "My Auto") {
autonomousCommand.reset(new MyAutoCommand());
}
else {
autonomousCommand.reset(new ExampleCommand());
} */
autonomousCommand.reset(chooser.GetSelected());
if (autonomousCommand.get() != nullptr) {
autonomousCommand->Start();
}
}
void AutonomousPeriodic() override {
frc::Scheduler::GetInstance()->Run();
}
void TeleopInit() override {
CommandBase::shooterSubsystem->SetPIDEnabled(false);
CommandBase::pDriveSystem->ResetGyro();
//SmartDashboard::PutString("Enabled:", "True");
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != nullptr) {
autonomousCommand->Cancel();
}
}
void TeleopPeriodic() override {
// if (CommandBase::oi->GetOperatorStick()->GetRawButton(7) || CommandBase::oi->GetDriveStick()->GetRawButton(7))
// {
// frc::Scheduler::GetInstance()->SetEnabled(false);
// frc::Scheduler::GetInstance()->
// SmartDashboard::PutString("Enabled:", "False");
// }
// else if (CommandBase::oi->GetOperatorStick()->GetRawButton(8) || CommandBase::oi->GetDriveStick()->GetRawButton(8))
// {
// frc::Scheduler::GetInstance()->SetEnabled(true);
// SmartDashboard::PutString("Enabled:", "True");
// }
frc::Scheduler::GetInstance()->Run();
}
void TestPeriodic() override {
frc::LiveWindow::GetInstance()->Run();
}
private:
std::unique_ptr<frc::Command> autonomousCommand;
frc::SendableChooser<frc::Command*> chooser;
};
START_ROBOT_CLASS(Robot)
| [
"mackinnonman@icloud.com"
] | mackinnonman@icloud.com |
a00ab0642d22ffd0b62a967a91bcec20b63cf7c3 | b26964bc265d51da810be3f3b874faeedcfd2056 | /observer/Observable.cpp | 20315d88d4d8c80de6f9f2330f5168419fda7389 | [] | no_license | Preant/design-pattern-workshop | b1aaf03f097bfe77ce237f94c3c25fc7e00fe433 | 3bcfb7f542b0f4c575cf4fc499ea4b4cf6d58628 | refs/heads/master | 2023-04-11T08:24:09.840142 | 2021-04-16T12:56:56 | 2021-04-16T12:56:56 | 356,162,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 306 | cpp | /*
** EPITECH PROJECT, 2020
** hub
** File description:
** Observable.cpp
*/
#include "Observable.hpp"
void
Observable::notify(std::string data) const
{
/*to do*/
}
bool
Observable::subscribe(IObserver *observer)
{
/*to do*/
}
bool
Observable::unsubscribe(IObserver *observer)
{
/*to do*/
} | [
"paolo.reant-hamadi@epitech.eu"
] | paolo.reant-hamadi@epitech.eu |
fb2180a2d18769f3b385f371856efbb2ede9d67b | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/f2/72edad4d84f47a/main.cpp | 4470ae6eff6c0f6fa0922d36cced79597c37b590 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,590 | cpp | #include <iostream>
#include <string>
#include <sstream>
struct name_value_pair { std::string name; int value; };
// convert object of type name_value_pair into a sequence of characters
std::string to_string( name_value_pair nvpair )
{
// step 1. create an output stringstream
std::ostringstream stm;
// step 2. write name and value into the stream
stm << "{ name: '" << nvpair.name << "', value: " << nvpair.value << " }";
// step 3. get a copy of the underlying string; and return it.
return stm.str();
}
// convert string back to object of type name_value_pair
name_value_pair to_nvpair( std::string str )
{
// step 1. crate a name_value_pair object
name_value_pair nvpair = { "anonymous", 0 };
// step 2. create an input stringstream to read from the given string
std::istringstream stm(str);
// step 2. read the information in the string
std::string temp ;
std::getline( stm, temp, '\'' ); // 2a. discard everuthing upto the first '
std::getline( stm, nvpair.name, '\'' ); // 2b. read the name
std::getline( stm, temp, ':' ); // 2c. discard everuthing upto the next :
stm >> nvpair.value; // 2d. read the value
// step 3. return the object.
return nvpair ;
}
int main()
{
name_value_pair pcount = { "post count", 59 };
const std::string str = to_string(pcount);
std::cout << "str contains: " << str << '\n';
name_value_pair pcount2 = to_nvpair(str) ;
std::cout << pcount2.name << " => " << pcount2.value << '\n' ;
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
36db34649a60e9c0ca55183ddfab404c9c31988c | 89be38f4428c37df62fae8a3f1a0d44f4b68f93d | /src/main.h | 936f0c7eea91728da04bd7920b8e53515232b4e2 | [
"MIT"
] | permissive | blackwhitecoin/Blackwhitecoin | 1a2e9fde6a86e30d0ae9a3a73967b049abd7a1a1 | 78f2774a3f5ee2d2e381f2707ea6d63ce76932bb | refs/heads/master | 2016-09-05T09:02:03.761406 | 2014-04-23T13:52:25 | 2014-04-23T13:52:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,167 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#include "bignum.h"
#include "sync.h"
#include "net.h"
#include "script.h"
#include "scrypt_mine.h"
#include <list>
class CWallet;
class CBlock;
class CBlockIndex;
class CKeyItem;
class CReserveKey;
class COutPoint;
class CAddress;
class CInv;
class CRequestTracker;
class CNode;
static const unsigned int MAX_BLOCK_SIZE = 1000000;
static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
static const unsigned int MAX_INV_SZ = 30000;
static const int64 MIN_TX_FEE = .01 * CENT;
static const int64 MIN_RELAY_TX_FEE = .01 * CENT;
static const int64 MAX_MONEY = 500000000 * COIN;
static const int64 MAX_MONEY2 = 300000000 * COIN; // 70 bil
static const int64 CIRCULATION_MONEY = MAX_MONEY2;
static const double TAX_PERCENTAGE = 0.0078;
static const int64 MAX_MINT_PROOF_OF_STAKE = 0.02 * COIN; // 5% annual interest
static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
// Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
#ifdef USE_UPNP
static const int fHaveUPnP = true;
#else
static const int fHaveUPnP = false;
#endif
static const uint256 hashGenesisBlockOfficial("0x00000549c9a6f5ad16ad5b614827a5a82bf9f1f8cad6fb2dec45080993470468");
static const uint256 hashGenesisBlockTestNet ("0x");
static const int64 nMaxClockDrift = 2 * 60 * 60; // two hours
extern CScript COINBASE_FLAGS;
extern CCriticalSection cs_main;
extern std::map<uint256, CBlockIndex*> mapBlockIndex;
extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
extern uint256 hashGenesisBlock;
extern CBlockIndex* pindexGenesisBlock;
extern unsigned int nStakeMinAge;
extern int nCoinbaseMaturity;
extern int nBestHeight;
extern CBigNum bnBestChainTrust;
extern CBigNum bnBestInvalidTrust;
extern uint256 hashBestChain;
extern CBlockIndex* pindexBest;
extern unsigned int nTransactionsUpdated;
extern uint64 nLastBlockTx;
extern uint64 nLastBlockSize;
extern int64 nLastCoinStakeSearchInterval;
extern const std::string strMessageMagic;
extern double dHashesPerSec;
extern int64 nHPSTimerStart;
extern int64 nTimeBestReceived;
extern CCriticalSection cs_setpwalletRegistered;
extern std::set<CWallet*> setpwalletRegistered;
extern unsigned char pchMessageStart[4];
extern std::map<uint256, CBlock*> mapOrphanBlocks;
// Settings
extern int64 nTransactionFee;
// Minimum disk space required - used in CheckDiskSpace()
static const uint64 nMinDiskSpace = 52428800;
class CReserveKey;
class CTxDB;
class CTxIndex;
void RegisterWallet(CWallet* pwalletIn);
void UnregisterWallet(CWallet* pwalletIn);
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
bool ProcessBlock(CNode* pfrom, CBlock* pblock);
bool CheckDiskSpace(uint64 nAdditionalBytes=0);
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
FILE* AppendBlockFile(unsigned int& nFileRet);
bool LoadBlockIndex(bool fAllowNew=true);
void PrintBlockTree();
CBlockIndex* FindBlockByHeight(int nHeight);
bool ProcessMessages(CNode* pfrom);
bool SendMessages(CNode* pto, bool fSendTrickle);
bool LoadExternalBlockFile(FILE* fileIn);
void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
int64 GetProofOfWorkReward(int nHeight, int64 nFees, uint256 prevHash);
int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, int nHeight);
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
int GetNumBlocksOfPeers();
bool IsInitialBlockDownload();
std::string GetWarnings(std::string strFor);
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
uint256 WantedByOrphan(const CBlock* pblockOrphan);
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
void ResendWalletTransactions();
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
/** Position on disk for a particular transaction. */
class CDiskTxPos
{
public:
unsigned int nFile;
unsigned int nBlockPos;
unsigned int nTxPos;
CDiskTxPos()
{
SetNull();
}
CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
{
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nTxPos = nTxPosIn;
}
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
bool IsNull() const { return (nFile == (unsigned int) -1); }
friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
{
return (a.nFile == b.nFile &&
a.nBlockPos == b.nBlockPos &&
a.nTxPos == b.nTxPos);
}
friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
{
return !(a == b);
}
std::string ToString() const
{
if (IsNull())
return "null";
else
return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
}
void print() const
{
printf("%s", ToString().c_str());
}
};
/** An inpoint - a combination of a transaction and an index n into its vin */
class CInPoint
{
public:
CTransaction* ptx;
unsigned int n;
CInPoint() { SetNull(); }
CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
void SetNull() { ptx = NULL; n = (unsigned int) -1; }
bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
};
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
unsigned int n;
COutPoint() { SetNull(); }
COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { hash = 0; n = (unsigned int) -1; }
bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An input of a transaction. It contains the location of the previous
* transaction's output that it claims and a signature that matches the
* output's public key.
*/
class CTxIn
{
public:
COutPoint prevout;
CScript scriptSig;
unsigned int nSequence;
CTxIn()
{
nSequence = std::numeric_limits<unsigned int>::max();
}
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(prevout);
READWRITE(scriptSig);
READWRITE(nSequence);
)
bool IsFinal() const
{
return (nSequence == std::numeric_limits<unsigned int>::max());
}
friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}
friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}
std::string ToStringShort() const
{
return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
}
std::string ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
else
str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An output of a transaction. It contains the public key that the next input
* must be able to sign with to claim it.
*/
class CTxOut
{
public:
int64 nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(nValue);
READWRITE(scriptPubKey);
)
void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}
bool IsNull()
{
return (nValue == -1);
}
void SetEmpty()
{
nValue = 0;
scriptPubKey.clear();
}
bool IsEmpty() const
{
return (nValue == 0 && scriptPubKey.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
std::string ToStringShort() const
{
return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
}
std::string ToString() const
{
if (IsEmpty()) return "CTxOut(empty)";
if (scriptPubKey.size() < 6)
return "CTxOut(error)";
return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
enum GetMinFee_mode
{
GMF_BLOCK,
GMF_RELAY,
GMF_SEND,
};
typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
public:
static const int CURRENT_VERSION=1;
int nVersion;
unsigned int nTime;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
unsigned int nLockTime;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CTransaction()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(nTime);
READWRITE(vin);
READWRITE(vout);
READWRITE(nLockTime);
)
void SetNull()
{
nVersion = CTransaction::CURRENT_VERSION;
nTime = GetAdjustedTime();
vin.clear();
vout.clear();
nLockTime = 0;
nDoS = 0; // Denial-of-service prevention
}
bool IsNull() const
{
return (vin.empty() && vout.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
{
// Time based nLockTime implemented in 0.1.6
if (nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = nBestHeight;
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
if (!txin.IsFinal())
return false;
return true;
}
bool IsNewerThan(const CTransaction& old) const
{
if (vin.size() != old.vin.size())
return false;
for (unsigned int i = 0; i < vin.size(); i++)
if (vin[i].prevout != old.vin[i].prevout)
return false;
bool fNewer = false;
unsigned int nLowest = std::numeric_limits<unsigned int>::max();
for (unsigned int i = 0; i < vin.size(); i++)
{
if (vin[i].nSequence != old.vin[i].nSequence)
{
if (vin[i].nSequence <= nLowest)
{
fNewer = false;
nLowest = vin[i].nSequence;
}
if (old.vin[i].nSequence < nLowest)
{
fNewer = true;
nLowest = old.vin[i].nSequence;
}
}
}
return fNewer;
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
}
bool IsCoinStake() const
{
// ppcoin: the coin stake transaction is marked with the first output empty
return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
}
/** Check for standard transaction types
@return True if all outputs (scriptPubKeys) use only standard transaction forms
*/
bool IsStandard() const;
/** Check for standard transaction types
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return True if all inputs (scriptSigs) use only standard transaction forms
@see CTransaction::FetchInputs
*/
bool AreInputsStandard(const MapPrevTx& mapInputs) const;
/** Count ECDSA signature operations the old-fashioned (pre-0.6) way
@return number of sigops this transaction's outputs will produce when spent
@see CTransaction::FetchInputs
*/
unsigned int GetLegacySigOpCount() const;
/** Count ECDSA signature operations in pay-to-script-hash inputs.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return maximum number of sigops required to validate this transaction's inputs
@see CTransaction::FetchInputs
*/
unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
/** Amount of bitcoins spent by this transaction.
@return sum of all outputs (note: does not include fees)
*/
int64 GetValueOut() const
{
int64 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
}
return nValueOut;
}
/** Amount of bitcoins coming in to this transaction
Note that lightweight clients may not know anything besides the hash of previous transactions,
so may not be able to calculate this.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return Sum of value of all inputs (scriptSigs)
@see CTransaction::FetchInputs
*/
int64 GetValueIn(const MapPrevTx& mapInputs) const;
static bool AllowFree(double dPriority)
{
// Large (in bytes) low-priority (new, small-coin) transactions
// need a fee.
return dPriority > COIN * 2880 / 250;
}
int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const;
bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
{
CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
// Read transaction
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : fseek failed");
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Return file pointer
if (pfileRet)
{
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : second fseek failed");
*pfileRet = filein.release();
}
return true;
}
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return (a.nVersion == b.nVersion &&
a.nTime == b.nTime &&
a.vin == b.vin &&
a.vout == b.vout &&
a.nLockTime == b.nLockTime);
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return !(a == b);
}
std::string ToStringShort() const
{
std::string str;
str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
return str;
}
std::string ToString() const
{
std::string str;
str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
GetHash().ToString().substr(0,10).c_str(),
nTime,
nVersion,
vin.size(),
vout.size(),
nLockTime
);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
void print() const
{
printf("%s", ToString().c_str());
}
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
bool ReadFromDisk(COutPoint prevout);
bool DisconnectInputs(CTxDB& txdb);
/** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
@param[in] txdb Transaction database
@param[in] mapTestPool List of pending changes to the transaction index database
@param[in] fBlock True if being called to add a new best-block to the chain
@param[in] fMiner True if being called by CreateNewBlock
@param[out] inputsRet Pointers to this transaction's inputs
@param[out] fInvalid returns true if transaction is invalid
@return Returns true if all inputs are in txdb or mapTestPool
*/
bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
/** Sanity check previous transactions, then, if all checks succeed,
mark them as spent by this transaction.
@param[in] inputs Previous transactions (from FetchInputs)
@param[out] mapTestPool Keeps track of inputs that need to be updated on disk
@param[in] posThisTx Position of this transaction on disk
@param[in] pindexBlock
@param[in] fBlock true if called from ConnectBlock
@param[in] fMiner true if called from CreateNewBlock
@param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
@return Returns true if all checks succeed
*/
bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
bool ClientConnectInputs();
bool CheckTransaction() const;
bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
protected:
const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
};
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
public:
uint256 hashBlock;
std::vector<uint256> vMerkleBranch;
int nIndex;
// memory only
mutable bool fMerkleVerified;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = 0;
nIndex = -1;
fMerkleVerified = false;
}
IMPLEMENT_SERIALIZE
(
nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
)
int SetMerkleBranch(const CBlock* pblock=NULL);
int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
bool AcceptToMemoryPool();
};
/** A txdb record that contains the disk location of a transaction and the
* locations of transactions that spend its outputs. vSpent is really only
* used as a flag, but having the location is very helpful for debugging.
*/
class CTxIndex
{
public:
CDiskTxPos pos;
std::vector<CDiskTxPos> vSpent;
CTxIndex()
{
SetNull();
}
CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
{
pos = posIn;
vSpent.resize(nOutputs);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(pos);
READWRITE(vSpent);
)
void SetNull()
{
pos.SetNull();
vSpent.clear();
}
bool IsNull()
{
return pos.IsNull();
}
friend bool operator==(const CTxIndex& a, const CTxIndex& b)
{
return (a.pos == b.pos &&
a.vSpent == b.vSpent);
}
friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
{
return !(a == b);
}
int GetDepthInMainChain() const;
};
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*
* Blocks are appended to blk0001.dat files on disk. Their location on disk
* is indexed by CBlockIndex objects in memory.
*/
class CBlock
{
public:
// header
static const int CURRENT_VERSION=4;
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
// network and disk
std::vector<CTransaction> vtx;
// ppcoin: block signature - signed by one of the coin base txout[N]'s owner
std::vector<unsigned char> vchBlockSig;
// memory only
mutable std::vector<uint256> vMerkleTree;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CBlock()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
// ConnectBlock depends on vtx following header to generate CDiskTxPos
if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
{
READWRITE(vtx);
READWRITE(vchBlockSig);
}
else if (fRead)
{
const_cast<CBlock*>(this)->vtx.clear();
const_cast<CBlock*>(this)->vchBlockSig.clear();
}
)
void SetNull()
{
nVersion = CBlock::CURRENT_VERSION;
hashPrevBlock = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
vtx.clear();
vchBlockSig.clear();
vMerkleTree.clear();
nDoS = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const
{
uint256 thash;
void * scratchbuff = scrypt_buffer_alloc();
scrypt_hash(CVOIDBEGIN(nVersion), sizeof(block_header), UINTBEGIN(thash), scratchbuff);
scrypt_buffer_free(scratchbuff);
return thash;
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
void UpdateTime(const CBlockIndex* pindexPrev);
// ppcoin: entropy bit for stake modifier if chosen by modifier
unsigned int GetStakeEntropyBit(unsigned int nHeight) const
{
// Take last bit of block hash as entropy bit
unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
if (fDebug && GetBoolArg("-printstakemodifier"))
printf("GetStakeEntropyBit: nHeight=%u hashBlock=%s nEntropyBit=%u\n", nHeight, GetHash().ToString().c_str(), nEntropyBit);
return nEntropyBit;
}
// ppcoin: two types of block: proof-of-work or proof-of-stake
bool IsProofOfStake() const
{
return (vtx.size() > 1 && vtx[1].IsCoinStake());
}
bool IsProofOfWork() const
{
return !IsProofOfStake();
}
std::pair<COutPoint, unsigned int> GetProofOfStake() const
{
return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
}
// ppcoin: get max transaction timestamp
int64 GetMaxTransactionTime() const
{
int64 maxTransactionTime = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
return maxTransactionTime;
}
uint256 BuildMerkleTree() const
{
vMerkleTree.clear();
BOOST_FOREACH(const CTransaction& tx, vtx)
vMerkleTree.push_back(tx.GetHash());
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
std::vector<uint256> GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
{
if (nIndex & 1)
hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
nIndex >>= 1;
}
return hash;
}
bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
{
// Open history file to append
CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlock::WriteToDisk() : AppendBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write block
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlock::WriteToDisk() : ftell failed");
nBlockPosRet = fileOutPos;
fileout << *this;
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
FileCommit(fileout);
return true;
}
bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
{
SetNull();
// Open history file to read
CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
if (!fReadTransactions)
filein.nType |= SER_BLOCKHEADERONLY;
// Read block
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Check the header
if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
return error("CBlock::ReadFromDisk() : errors in block header");
return true;
}
void print() const
{
printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
GetHash().ToString().c_str(),
nVersion,
hashPrevBlock.ToString().c_str(),
hashMerkleRoot.ToString().c_str(),
nTime, nBits, nNonce,
vtx.size(),
HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
for (unsigned int i = 0; i < vtx.size(); i++)
{
printf(" ");
vtx[i].print();
}
printf(" vMerkleTree: ");
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
printf("\n");
}
bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
bool AcceptBlock();
bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
bool SignBlock(const CKeyStore& keystore);
bool CheckBlockSignature() const;
private:
bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. pprev and pnext link a path through the
* main/longest chain. A blockindex may have multiple pprev pointing back
* to it, but pnext will only point forward to the longest branch, or will
* be null if the block is not part of the longest chain.
*/
class CBlockIndex
{
public:
const uint256* phashBlock;
CBlockIndex* pprev;
CBlockIndex* pnext;
unsigned int nFile;
unsigned int nBlockPos;
CBigNum bnChainTrust; // ppcoin: trust score of block chain
int nHeight;
int64 nMint;
int64 nMoneySupply;
unsigned int nFlags; // ppcoin: block index flags
enum
{
BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
};
uint64 nStakeModifier; // hash modifier for proof-of-stake
unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
// proof-of-stake specific fields
COutPoint prevoutStake;
unsigned int nStakeTime;
uint256 hashProofOfStake;
// block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockIndex()
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = 0;
nBlockPos = 0;
nHeight = 0;
bnChainTrust = 0;
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
nStakeModifierChecksum = 0;
hashProofOfStake = 0;
prevoutStake.SetNull();
nStakeTime = 0;
nVersion = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nHeight = 0;
bnChainTrust = 0;
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
nStakeModifierChecksum = 0;
hashProofOfStake = 0;
if (block.IsProofOfStake())
{
SetProofOfStake();
prevoutStake = block.vtx[1].vin[0].prevout;
nStakeTime = block.vtx[1].nTime;
}
else
{
prevoutStake.SetNull();
nStakeTime = 0;
}
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
}
CBlock GetBlockHeader() const
{
CBlock block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
CBigNum GetBlockTrust() const;
bool IsInMainChain() const
{
return (pnext || this == pindexBest);
}
bool CheckIndex() const
{
return true;
}
enum { nMedianTimeSpan=11 };
int64 GetMedianTimePast() const
{
int64 pmedian[nMedianTimeSpan];
int64* pbegin = &pmedian[nMedianTimeSpan];
int64* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2];
}
int64 GetMedianTime() const
{
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan/2; i++)
{
if (!pindex->pnext)
return GetBlockTime();
pindex = pindex->pnext;
}
return pindex->GetMedianTimePast();
}
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last nToCheck blocks, starting at pstart and going backwards.
*/
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
unsigned int nRequired, unsigned int nToCheck);
bool IsProofOfWork() const
{
return !(nFlags & BLOCK_PROOF_OF_STAKE);
}
bool IsProofOfStake() const
{
return (nFlags & BLOCK_PROOF_OF_STAKE);
}
void SetProofOfStake()
{
nFlags |= BLOCK_PROOF_OF_STAKE;
}
unsigned int GetStakeEntropyBit() const
{
return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
}
bool SetStakeEntropyBit(unsigned int nEntropyBit)
{
if (nEntropyBit > 1)
return false;
nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
return true;
}
bool GeneratedStakeModifier() const
{
return (nFlags & BLOCK_STAKE_MODIFIER);
}
void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
{
nStakeModifier = nModifier;
if (fGeneratedStakeModifier)
nFlags |= BLOCK_STAKE_MODIFIER;
}
std::string ToString() const
{
return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
pprev, pnext, nFile, nBlockPos, nHeight,
FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
nStakeModifier, nStakeModifierChecksum,
hashProofOfStake.ToString().c_str(),
prevoutStake.ToString().c_str(), nStakeTime,
hashMerkleRoot.ToString().c_str(),
GetBlockHash().ToString().c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
uint256 hashNext;
CDiskBlockIndex()
{
hashPrev = 0;
hashNext = 0;
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
{
hashPrev = (pprev ? pprev->GetBlockHash() : 0);
hashNext = (pnext ? pnext->GetBlockHash() : 0);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(hashNext);
READWRITE(nFile);
READWRITE(nBlockPos);
READWRITE(nHeight);
READWRITE(nMint);
READWRITE(nMoneySupply);
READWRITE(nFlags);
READWRITE(nStakeModifier);
if (IsProofOfStake())
{
READWRITE(prevoutStake);
READWRITE(nStakeTime);
READWRITE(hashProofOfStake);
}
else if (fRead)
{
const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
}
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
uint256 GetBlockHash() const
{
CBlock block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block.GetHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
GetBlockHash().ToString().c_str(),
hashPrev.ToString().c_str(),
hashNext.ToString().c_str());
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
class CBlockLocator
{
protected:
std::vector<uint256> vHave;
public:
CBlockLocator()
{
}
explicit CBlockLocator(const CBlockIndex* pindex)
{
Set(pindex);
}
explicit CBlockLocator(uint256 hashBlock)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end())
Set((*mi).second);
}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
)
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
void Set(const CBlockIndex* pindex)
{
vHave.clear();
int nStep = 1;
while (pindex)
{
vHave.push_back(pindex->GetBlockHash());
// Exponentially larger steps back
for (int i = 0; pindex && i < nStep; i++)
pindex = pindex->pprev;
if (vHave.size() > 10)
nStep *= 2;
}
vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
}
int GetDistanceBack()
{
// Retrace how far back it was in the sender's branch
int nDistance = 0;
int nStep = 1;
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return nDistance;
}
nDistance += nStep;
if (nDistance > 10)
nStep *= 2;
}
return nDistance;
}
CBlockIndex* GetBlockIndex()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return pindex;
}
}
return pindexGenesisBlock;
}
uint256 GetBlockHash()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return hash;
}
}
return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
}
int GetHeight()
{
CBlockIndex* pindex = GetBlockIndex();
if (!pindex)
return 0;
return pindex->nHeight;
}
};
class CTxMemPool
{
public:
mutable CCriticalSection cs;
std::map<uint256, CTransaction> mapTx;
std::map<COutPoint, CInPoint> mapNextTx;
bool accept(CTxDB& txdb, CTransaction &tx,
bool fCheckInputs, bool* pfMissingInputs);
bool addUnchecked(const uint256& hash, CTransaction &tx);
bool remove(CTransaction &tx);
void clear();
void queryHashes(std::vector<uint256>& vtxid);
unsigned long size()
{
LOCK(cs);
return mapTx.size();
}
bool exists(uint256 hash)
{
return (mapTx.count(hash) != 0);
}
CTransaction& lookup(uint256 hash)
{
return mapTx[hash];
}
};
extern CTxMemPool mempool;
#endif
| [
"root@localhost.localdomain"
] | root@localhost.localdomain |
131f145dd496b4e3e4b758cf8387a2d1afd82b92 | 77a1e8b6e3181b097a196bda951ae5ed05115729 | /libraries/chain/apply_context.cpp | a72b6732fcc748556bdaaf4bc1194043cf78569a | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | yinchengtsinghua/EOSIOChineseCPP | 04888f80cb7a946fb54c2494137868cb86685ff1 | dceabf6315ab8c9a064c76e943b2b44037165a85 | refs/heads/master | 2020-04-18T01:20:58.685186 | 2019-01-23T04:17:07 | 2019-01-23T04:17:07 | 167,115,462 | 21 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 29,164 | cpp |
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
#include <algorithm>
#include <eosio/chain/apply_context.hpp>
#include <eosio/chain/controller.hpp>
#include <eosio/chain/transaction_context.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/wasm_interface.hpp>
#include <eosio/chain/generated_transaction_object.hpp>
#include <eosio/chain/authorization_manager.hpp>
#include <eosio/chain/resource_limits.hpp>
#include <eosio/chain/account_object.hpp>
#include <eosio/chain/global_property_object.hpp>
#include <boost/container/flat_set.hpp>
using boost::container::flat_set;
namespace eosio { namespace chain {
static inline void print_debug(account_name receiver, const action_trace& ar) {
if (!ar.console.empty()) {
auto prefix = fc::format_string(
"\n[(${a},${n})->${r}]",
fc::mutable_variant_object()
("a", ar.act.account)
("n", ar.act.name)
("r", receiver));
dlog(prefix + ": CONSOLE OUTPUT BEGIN =====================\n"
+ ar.console
+ prefix + ": CONSOLE OUTPUT END =====================" );
}
}
void apply_context::exec_one( action_trace& trace )
{
auto start = fc::time_point::now();
action_receipt r;
r.receiver = receiver;
r.act_digest = digest_type::hash(act);
trace.trx_id = trx_context.id;
trace.block_num = control.pending_block_state()->block_num;
trace.block_time = control.pending_block_time();
trace.producer_block_id = control.pending_producer_block_id();
trace.act = act;
trace.context_free = context_free;
const auto& cfg = control.get_global_properties().configuration;
try {
try {
const auto& a = control.get_account( receiver );
privileged = a.privileged;
auto native = control.find_apply_handler( receiver, act.account, act.name );
if( native ) {
if( trx_context.enforce_whiteblacklist && control.is_producing_block() ) {
control.check_contract_list( receiver );
control.check_action_list( act.account, act.name );
}
(*native)( *this );
}
if( a.code.size() > 0
&& !(act.account == config::system_account_name && act.name == N( setcode ) &&
receiver == config::system_account_name) ) {
if( trx_context.enforce_whiteblacklist && control.is_producing_block() ) {
control.check_contract_list( receiver );
control.check_action_list( act.account, act.name );
}
try {
control.get_wasm_interface().apply( a.code_version, a.code, *this );
} catch( const wasm_exit& ) {}
}
} FC_RETHROW_EXCEPTIONS( warn, "pending console output: ${console}", ("console", _pending_console_output.str()) )
} catch( fc::exception& e ) {
trace.receipt = r; //用已知数据填充
trace.except = e;
finalize_trace( trace, start );
throw;
}
r.global_sequence = next_global_sequence();
r.recv_sequence = next_recv_sequence( receiver );
const auto& account_sequence = db.get<account_sequence_object, by_name>(act.account);
r.code_sequence = account_sequence.code_sequence; //可以通过上面的操作执行进行修改
r.abi_sequence = account_sequence.abi_sequence; //可以通过上面的操作执行进行修改
for( const auto& auth : act.authorization ) {
r.auth_sequence[auth.actor] = next_auth_sequence( auth.actor );
}
trace.receipt = r;
trx_context.executed.emplace_back( move(r) );
finalize_trace( trace, start );
if ( control.contracts_console() ) {
print_debug(receiver, trace);
}
}
void apply_context::finalize_trace( action_trace& trace, const fc::time_point& start )
{
trace.account_ram_deltas = std::move( _account_ram_deltas );
_account_ram_deltas.clear();
trace.console = _pending_console_output.str();
reset_console();
trace.elapsed = fc::time_point::now() - start;
}
void apply_context::exec( action_trace& trace )
{
_notified.push_back(receiver);
exec_one( trace );
for( uint32_t i = 1; i < _notified.size(); ++i ) {
receiver = _notified[i];
trace.inline_traces.emplace_back( );
exec_one( trace.inline_traces.back() );
}
if( _cfa_inline_actions.size() > 0 || _inline_actions.size() > 0 ) {
EOS_ASSERT( recurse_depth < control.get_global_properties().configuration.max_inline_action_depth,
transaction_exception, "max inline action depth per transaction reached" );
}
for( const auto& inline_action : _cfa_inline_actions ) {
trace.inline_traces.emplace_back();
trx_context.dispatch_action( trace.inline_traces.back(), inline_action, inline_action.account, true, recurse_depth + 1 );
}
for( const auto& inline_action : _inline_actions ) {
trace.inline_traces.emplace_back();
trx_context.dispatch_action( trace.inline_traces.back(), inline_action, inline_action.account, false, recurse_depth + 1 );
}
} ///执行()
bool apply_context::is_account( const account_name& account )const {
return nullptr != db.find<account_object,by_name>( account );
}
void apply_context::require_authorization( const account_name& account ) {
for( uint32_t i=0; i < act.authorization.size(); i++ ) {
if( act.authorization[i].actor == account ) {
used_authorizations[i] = true;
return;
}
}
EOS_ASSERT( false, missing_auth_exception, "missing authority of ${account}", ("account",account));
}
bool apply_context::has_authorization( const account_name& account )const {
for( const auto& auth : act.authorization )
if( auth.actor == account )
return true;
return false;
}
void apply_context::require_authorization(const account_name& account,
const permission_name& permission) {
for( uint32_t i=0; i < act.authorization.size(); i++ )
if( act.authorization[i].actor == account ) {
if( act.authorization[i].permission == permission ) {
used_authorizations[i] = true;
return;
}
}
EOS_ASSERT( false, missing_auth_exception, "missing authority of ${account}/${permission}",
("account",account)("permission",permission) );
}
bool apply_context::has_recipient( account_name code )const {
for( auto a : _notified )
if( a == code )
return true;
return false;
}
void apply_context::require_recipient( account_name recipient ) {
if( !has_recipient(recipient) ) {
_notified.push_back(recipient);
}
}
/*
*这将在检查授权后执行一个操作。内联事务是
*由当前接收器隐式授权(运行代码)。这种方法有重要意义
*考虑了安全因素和几种选择:
*
* 1。特权账户(由区块生产商标记的账户)可以授权任何行动。
* 2。所有其他行动仅由“接收者”授权,这意味着:
*a.用户必须为其帐户设置权限,以允许“接收者”代表其行事。
*
*放弃实施:我们曾经允许任何授权当前交易的账户
*隐式授权内联事务。这种方法将允许权限升级和
*使用户与某些合同交互不安全。我们选择了申请
*请求用户允许采取某些操作,而不是使其隐式操作。这种方式的用户
*能够更好地了解安全风险。
**/
void apply_context::execute_inline( action&& a ) {
auto* code = control.db().find<account_object, by_name>(a.account);
EOS_ASSERT( code != nullptr, action_validate_exception,
"inline action's code account ${account} does not exist", ("account", a.account) );
bool enforce_actor_whitelist_blacklist = trx_context.enforce_whiteblacklist && control.is_producing_block();
flat_set<account_name> actors;
bool disallow_send_to_self_bypass = false; //最终设置为是否激活了适当的协议功能
bool send_to_self = (a.account == receiver);
bool inherit_parent_authorizations = (!disallow_send_to_self_bypass && send_to_self && (receiver == act.account) && control.is_producing_block());
flat_set<permission_level> inherited_authorizations;
if( inherit_parent_authorizations ) {
inherited_authorizations.reserve( a.authorization.size() );
}
for( const auto& auth : a.authorization ) {
auto* actor = control.db().find<account_object, by_name>(auth.actor);
EOS_ASSERT( actor != nullptr, action_validate_exception,
"inline action's authorizing actor ${account} does not exist", ("account", auth.actor) );
EOS_ASSERT( control.get_authorization_manager().find_permission(auth) != nullptr, action_validate_exception,
"inline action's authorizations include a non-existent permission: ${permission}",
("permission", auth) );
if( enforce_actor_whitelist_blacklist )
actors.insert( auth.actor );
if( inherit_parent_authorizations && std::find(act.authorization.begin(), act.authorization.end(), auth) != act.authorization.end() ) {
inherited_authorizations.insert( auth );
}
}
if( enforce_actor_whitelist_blacklist ) {
control.check_actor_list( actors );
}
//如果重放不可逆块或协定是特权的,则无需检查授权
if( !control.skip_auth_check() && !privileged ) {
try {
control.get_authorization_manager()
.check_authorization( {a},
{},
{{receiver, config::eosio_code_name}},
control.pending_block_time() - trx_context.published,
std::bind(&transaction_context::checktime, &this->trx_context),
false,
inherited_authorizations
);
//问题:允许延迟了一段时间的事务离开是否明智?
//发送一个需要延迟的内联操作,即使决定发送该内联
//在执行延迟事务时采取了可能没有预警的措施?
} catch( const fc::exception& e ) {
if( disallow_send_to_self_bypass || !send_to_self ) {
throw;
} else if( control.is_producing_block() ) {
subjective_block_production_exception new_exception(FC_LOG_MESSAGE( error, "Authorization failure with inline action sent to self"));
for (const auto& log: e.get_log()) {
new_exception.append_log(log);
}
throw new_exception;
}
} catch( ... ) {
if( disallow_send_to_self_bypass || !send_to_self ) {
throw;
} else if( control.is_producing_block() ) {
EOS_THROW(subjective_block_production_exception, "Unexpected exception occurred validating inline action sent to self");
}
}
}
_inline_actions.emplace_back( move(a) );
}
void apply_context::execute_context_free_inline( action&& a ) {
auto* code = control.db().find<account_object, by_name>(a.account);
EOS_ASSERT( code != nullptr, action_validate_exception,
"inline action's code account ${account} does not exist", ("account", a.account) );
EOS_ASSERT( a.authorization.size() == 0, action_validate_exception,
"context-free actions cannot have authorizations" );
_cfa_inline_actions.emplace_back( move(a) );
}
void apply_context::schedule_deferred_transaction( const uint128_t& sender_id, account_name payer, transaction&& trx, bool replace_existing ) {
EOS_ASSERT( trx.context_free_actions.size() == 0, cfa_inside_generated_tx, "context free actions are not currently allowed in generated transactions" );
trx.expiration = control.pending_block_time() + fc::microseconds(999'999); //四舍五入到最接近的秒(使到期检查不必要)
trx.set_reference_block(control.head_block_id()); //无需Tapos检查
bool enforce_actor_whitelist_blacklist = trx_context.enforce_whiteblacklist && control.is_producing_block()
&& !control.sender_avoids_whitelist_blacklist_enforcement( receiver );
trx_context.validate_referenced_accounts( trx, enforce_actor_whitelist_blacklist );
//提前收取注销延期交易所需的额外净使用费
//无论是通过成功执行、软故障、硬故障还是过期。
const auto& cfg = control.get_global_properties().configuration;
trx_context.add_net_usage( static_cast<uint64_t>(cfg.base_per_transaction_net_usage)
+ static_cast<uint64_t>(config::transaction_id_net_usage) ); //如果无法支付净使用费,将提前退出。
auto delay = fc::seconds(trx.delay_sec);
if( !control.skip_auth_check() && !privileged ) { //如果重放不可逆块或合同具有特权,则不需要检查授权。
if( payer != receiver ) {
require_authorization(payer); ///使用付款人的存储
}
//最初,如果契约只将操作延迟到自身,则此代码将跳过授权检查。
//其想法是,代码已经可以做任何延迟事务可以做的事情,所以没有必要检查授权。
//但这不是真的。原始实现没有验证允许权限提升的操作的授权。
//这将使向一些不相关的账户开单成为可能。
//此外,即使授权被强制为当前操作授权的一个子集,它仍然会违反预期。
//原始事务的签名者,因为延迟的事务将允许比最大限制计费更多的CPU和网络带宽
//在原始交易记录上指定。
//因此,如果延迟事务不是由特权契约发送的,那么它必须始终通过授权检查。
//但是,必须考虑旧的逻辑,因为在共识协议升级之前,它不能客观地改变。
bool disallow_send_to_self_bypass = false; //最终设置为是否激活了适当的协议功能
auto is_sending_only_to_self = [&trx]( const account_name& self ) {
bool send_to_self = true;
for( const auto& act : trx.actions ) {
if( act.account != self ) {
send_to_self = false;
break;
}
}
return send_to_self;
};
try {
control.get_authorization_manager()
.check_authorization( trx.actions,
{},
{{receiver, config::eosio_code_name}},
delay,
std::bind(&transaction_context::checktime, &this->trx_context),
false
);
} catch( const fc::exception& e ) {
if( disallow_send_to_self_bypass || !is_sending_only_to_self(receiver) ) {
throw;
} else if( control.is_producing_block() ) {
subjective_block_production_exception new_exception(FC_LOG_MESSAGE( error, "Authorization failure with sent deferred transaction consisting only of actions to self"));
for (const auto& log: e.get_log()) {
new_exception.append_log(log);
}
throw new_exception;
}
} catch( ... ) {
if( disallow_send_to_self_bypass || !is_sending_only_to_self(receiver) ) {
throw;
} else if( control.is_producing_block() ) {
EOS_THROW(subjective_block_production_exception, "Unexpected exception occurred validating sent deferred transaction consisting only of actions to self");
}
}
}
uint32_t trx_size = 0;
if ( auto ptr = db.find<generated_transaction_object,by_sender_id>(boost::make_tuple(receiver, sender_id)) ) {
EOS_ASSERT( replace_existing, deferred_tx_duplicate, "deferred transaction with the same sender_id and payer already exists" );
//TODO:在用硬分叉修复延迟的TRX替换RAM错误时,删除以下主观检查。
EOS_ASSERT( !control.is_producing_block(), subjective_block_production_exception,
"Replacing a deferred transaction is temporarily disabled." );
//TODO:下一行的逻辑需要合并到下一个硬分叉中。
//添加_-ram-usage(ptr->payer-(config::billable_-size_v<generated_-transaction_-object-+ptr->packed_-trx.size());
db.modify<generated_transaction_object>( *ptr, [&]( auto& gtx ) {
gtx.sender = receiver;
gtx.sender_id = sender_id;
gtx.payer = payer;
gtx.published = control.pending_block_time();
gtx.delay_until = gtx.published + delay;
gtx.expiration = gtx.delay_until + fc::seconds(control.get_global_properties().configuration.deferred_trx_expiration_window);
trx_size = gtx.set( trx );
});
} else {
db.create<generated_transaction_object>( [&]( auto& gtx ) {
gtx.trx_id = trx.id();
gtx.sender = receiver;
gtx.sender_id = sender_id;
gtx.payer = payer;
gtx.published = control.pending_block_time();
gtx.delay_until = gtx.published + delay;
gtx.expiration = gtx.delay_until + fc::seconds(control.get_global_properties().configuration.deferred_trx_expiration_window);
trx_size = gtx.set( trx );
});
}
EOS_ASSERT( control.is_ram_billing_in_notify_allowed() || (receiver == act.account) || (receiver == payer) || privileged,
subjective_block_production_exception, "Cannot charge RAM to other accounts during notify." );
add_ram_usage( payer, (config::billable_size_v<generated_transaction_object> + trx_size) );
}
bool apply_context::cancel_deferred_transaction( const uint128_t& sender_id, account_name sender ) {
auto& generated_transaction_idx = db.get_mutable_index<generated_transaction_multi_index>();
const auto* gto = db.find<generated_transaction_object,by_sender_id>(boost::make_tuple(sender, sender_id));
if ( gto ) {
add_ram_usage( gto->payer, -(config::billable_size_v<generated_transaction_object> + gto->packed_trx.size()) );
generated_transaction_idx.remove(*gto);
}
return gto;
}
const table_id_object* apply_context::find_table( name code, name scope, name table ) {
return db.find<table_id_object, by_code_scope_table>(boost::make_tuple(code, scope, table));
}
const table_id_object& apply_context::find_or_create_table( name code, name scope, name table, const account_name &payer ) {
const auto* existing_tid = db.find<table_id_object, by_code_scope_table>(boost::make_tuple(code, scope, table));
if (existing_tid != nullptr) {
return *existing_tid;
}
update_db_usage(payer, config::billable_size_v<table_id_object>);
return db.create<table_id_object>([&](table_id_object &t_id){
t_id.code = code;
t_id.scope = scope;
t_id.table = table;
t_id.payer = payer;
});
}
void apply_context::remove_table( const table_id_object& tid ) {
update_db_usage(tid.payer, - config::billable_size_v<table_id_object>);
db.remove(tid);
}
vector<account_name> apply_context::get_active_producers() const {
const auto& ap = control.active_producers();
vector<account_name> accounts; accounts.reserve( ap.producers.size() );
for(const auto& producer : ap.producers )
accounts.push_back(producer.producer_name);
return accounts;
}
void apply_context::reset_console() {
_pending_console_output = std::ostringstream();
_pending_console_output.setf( std::ios::scientific, std::ios::floatfield );
}
bytes apply_context::get_packed_transaction() {
auto r = fc::raw::pack( static_cast<const transaction&>(trx_context.trx) );
return r;
}
void apply_context::update_db_usage( const account_name& payer, int64_t delta ) {
if( delta > 0 ) {
if( !(privileged || payer == account_name(receiver)) ) {
EOS_ASSERT( control.is_ram_billing_in_notify_allowed() || (receiver == act.account),
subjective_block_production_exception, "Cannot charge RAM to other accounts during notify." );
require_authorization( payer );
}
}
add_ram_usage(payer, delta);
}
int apply_context::get_action( uint32_t type, uint32_t index, char* buffer, size_t buffer_size )const
{
const auto& trx = trx_context.trx;
const action* act_ptr = nullptr;
if( type == 0 ) {
if( index >= trx.context_free_actions.size() )
return -1;
act_ptr = &trx.context_free_actions[index];
}
else if( type == 1 ) {
if( index >= trx.actions.size() )
return -1;
act_ptr = &trx.actions[index];
}
EOS_ASSERT(act_ptr, action_not_found_exception, "action is not found" );
auto ps = fc::raw::pack_size( *act_ptr );
if( ps <= buffer_size ) {
fc::datastream<char*> ds(buffer, buffer_size);
fc::raw::pack( ds, *act_ptr );
}
return ps;
}
int apply_context::get_context_free_data( uint32_t index, char* buffer, size_t buffer_size )const
{
const auto& trx = trx_context.trx;
if( index >= trx.context_free_data.size() ) return -1;
auto s = trx.context_free_data[index].size();
if( buffer_size == 0 ) return s;
auto copy_size = std::min( buffer_size, s );
memcpy( buffer, trx.context_free_data[index].data(), copy_size );
return copy_size;
}
int apply_context::db_store_i64( uint64_t scope, uint64_t table, const account_name& payer, uint64_t id, const char* buffer, size_t buffer_size ) {
return db_store_i64( receiver, scope, table, payer, id, buffer, buffer_size);
}
int apply_context::db_store_i64( uint64_t code, uint64_t scope, uint64_t table, const account_name& payer, uint64_t id, const char* buffer, size_t buffer_size ) {
//需要写锁(作用域);
const auto& tab = find_or_create_table( code, scope, table, payer );
auto tableid = tab.id;
EOS_ASSERT( payer != account_name(), invalid_table_payer, "must specify a valid account to pay for new record" );
const auto& obj = db.create<key_value_object>( [&]( auto& o ) {
o.t_id = tableid;
o.primary_key = id;
o.value.assign( buffer, buffer_size );
o.payer = payer;
});
db.modify( tab, [&]( auto& t ) {
++t.count;
});
int64_t billable_size = (int64_t)(buffer_size + config::billable_size_v<key_value_object>);
update_db_usage( payer, billable_size);
keyval_cache.cache_table( tab );
return keyval_cache.add( obj );
}
void apply_context::db_update_i64( int iterator, account_name payer, const char* buffer, size_t buffer_size ) {
const key_value_object& obj = keyval_cache.get( iterator );
const auto& table_obj = keyval_cache.get_table( obj.t_id );
EOS_ASSERT( table_obj.code == receiver, table_access_violation, "db access violation" );
//需要写锁(表\obj.scope);
const int64_t overhead = config::billable_size_v<key_value_object>;
int64_t old_size = (int64_t)(obj.value.size() + overhead);
int64_t new_size = (int64_t)(buffer_size + overhead);
if( payer == account_name() ) payer = obj.payer;
if( account_name(obj.payer) != payer ) {
//退还现有付款人
update_db_usage( obj.payer, -(old_size) );
//向新付款人收费
update_db_usage( payer, (new_size));
} else if(old_size != new_size) {
//向现有付款人收取/退还差额
update_db_usage( obj.payer, new_size - old_size);
}
db.modify( obj, [&]( auto& o ) {
o.value.assign( buffer, buffer_size );
o.payer = payer;
});
}
void apply_context::db_remove_i64( int iterator ) {
const key_value_object& obj = keyval_cache.get( iterator );
const auto& table_obj = keyval_cache.get_table( obj.t_id );
EOS_ASSERT( table_obj.code == receiver, table_access_violation, "db access violation" );
//需要写锁(表\obj.scope);
update_db_usage( obj.payer, -(obj.value.size() + config::billable_size_v<key_value_object>) );
db.modify( table_obj, [&]( auto& t ) {
--t.count;
});
db.remove( obj );
if (table_obj.count == 0) {
remove_table(table_obj);
}
keyval_cache.remove( iterator );
}
int apply_context::db_get_i64( int iterator, char* buffer, size_t buffer_size ) {
const key_value_object& obj = keyval_cache.get( iterator );
auto s = obj.value.size();
if( buffer_size == 0 ) return s;
auto copy_size = std::min( buffer_size, s );
memcpy( buffer, obj.value.data(), copy_size );
return copy_size;
}
int apply_context::db_next_i64( int iterator, uint64_t& primary ) {
if( iterator < -1 ) return -1; //无法增量超过表的结束迭代器
const auto& obj = keyval_cache.get( iterator ); //检查迭代器!=-1在这个呼叫中发生
const auto& idx = db.get_index<key_value_index, by_scope_primary>();
auto itr = idx.iterator_to( obj );
++itr;
if( itr == idx.end() || itr->t_id != obj.t_id ) return keyval_cache.get_end_iterator_by_table_id(obj.t_id);
primary = itr->primary_key;
return keyval_cache.add( *itr );
}
int apply_context::db_previous_i64( int iterator, uint64_t& primary ) {
const auto& idx = db.get_index<key_value_index, by_scope_primary>();
if( iterator < -1 ) //结束迭代器
{
auto tab = keyval_cache.find_table_by_end_iterator(iterator);
EOS_ASSERT( tab, invalid_table_iterator, "not a valid end iterator" );
auto itr = idx.upper_bound(tab->id);
if( idx.begin() == idx.end() || itr == idx.begin() ) return -1; //空表
--itr;
if( itr->t_id != tab->id ) return -1; //空表
primary = itr->primary_key;
return keyval_cache.add(*itr);
}
const auto& obj = keyval_cache.get(iterator); //检查迭代器!=-1在这个呼叫中发生
auto itr = idx.iterator_to(obj);
if( itr == idx.begin() ) return -1; //不能在表的起始迭代器之后递减
--itr;
if( itr->t_id != obj.t_id ) return -1; //不能在表的起始迭代器之后递减
primary = itr->primary_key;
return keyval_cache.add(*itr);
}
int apply_context::db_find_i64( uint64_t code, uint64_t scope, uint64_t table, uint64_t id ) {
//需要读锁(code,scope);//冗余?
const auto* tab = find_table( code, scope, table );
if( !tab ) return -1;
auto table_end_itr = keyval_cache.cache_table( *tab );
const key_value_object* obj = db.find<key_value_object, by_scope_primary>( boost::make_tuple( tab->id, id ) );
if( !obj ) return table_end_itr;
return keyval_cache.add( *obj );
}
int apply_context::db_lowerbound_i64( uint64_t code, uint64_t scope, uint64_t table, uint64_t id ) {
//需要读锁(code,scope);//冗余?
const auto* tab = find_table( code, scope, table );
if( !tab ) return -1;
auto table_end_itr = keyval_cache.cache_table( *tab );
const auto& idx = db.get_index<key_value_index, by_scope_primary>();
auto itr = idx.lower_bound( boost::make_tuple( tab->id, id ) );
if( itr == idx.end() ) return table_end_itr;
if( itr->t_id != tab->id ) return table_end_itr;
return keyval_cache.add( *itr );
}
int apply_context::db_upperbound_i64( uint64_t code, uint64_t scope, uint64_t table, uint64_t id ) {
//需要读锁(code,scope);//冗余?
const auto* tab = find_table( code, scope, table );
if( !tab ) return -1;
auto table_end_itr = keyval_cache.cache_table( *tab );
const auto& idx = db.get_index<key_value_index, by_scope_primary>();
auto itr = idx.upper_bound( boost::make_tuple( tab->id, id ) );
if( itr == idx.end() ) return table_end_itr;
if( itr->t_id != tab->id ) return table_end_itr;
return keyval_cache.add( *itr );
}
int apply_context::db_end_i64( uint64_t code, uint64_t scope, uint64_t table ) {
//需要读锁(code,scope);//冗余?
const auto* tab = find_table( code, scope, table );
if( !tab ) return -1;
return keyval_cache.cache_table( *tab );
}
uint64_t apply_context::next_global_sequence() {
const auto& p = control.get_dynamic_global_properties();
db.modify( p, [&]( auto& dgp ) {
++dgp.global_action_sequence;
});
return p.global_action_sequence;
}
uint64_t apply_context::next_recv_sequence( account_name receiver ) {
const auto& rs = db.get<account_sequence_object,by_name>( receiver );
db.modify( rs, [&]( auto& mrs ) {
++mrs.recv_sequence;
});
return rs.recv_sequence;
}
uint64_t apply_context::next_auth_sequence( account_name actor ) {
const auto& rs = db.get<account_sequence_object,by_name>( actor );
db.modify( rs, [&](auto& mrs ){
++mrs.auth_sequence;
});
return rs.auth_sequence;
}
void apply_context::add_ram_usage( account_name account, int64_t ram_delta ) {
trx_context.add_ram_usage( account, ram_delta );
auto p = _account_ram_deltas.emplace( account, ram_delta );
if( !p.second ) {
p.first->delta += ram_delta;
}
}
} } ///EOSIO:链
| [
"openaichain"
] | openaichain |
c720aac13d9977afcd42b98c62af3e23a7cf99f8 | 39f9ae6bdbda7f3b42cf4a006fb2a469fb44e4cf | /Farol/AssemblyInfo.cpp | 4b46aa567e0d2ef8993d1f2dc527747d40b59ecd | [] | no_license | maochy/farol | 30b2af11cf951d128797ec79c0d419883b7bbc11 | 486928695c3658e7646606d14c3bf6b8bc9d8933 | refs/heads/master | 2021-01-10T01:17:40.086620 | 2010-03-12T04:10:39 | 2010-03-12T04:10:39 | 38,855,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,326 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("Farol")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("Farol")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) 2009")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
| [
"renanrv@5a151274-b240-11de-8e13-c326f17d7b4c"
] | renanrv@5a151274-b240-11de-8e13-c326f17d7b4c |
8871d673d5d2d1d2fed836530caf4ba084fde102 | 777a75e6ed0934c193aece9de4421f8d8db01aac | /src/Providers/UNIXProviders/ProvidesEndpoint/UNIX_ProvidesEndpoint_SOLARIS.hxx | 0e588878e083edfb93d18e7bf5b4eb13b7077919 | [
"MIT"
] | permissive | brunolauze/openpegasus-providers-old | 20fc13958016e35dc4d87f93d1999db0eae9010a | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | refs/heads/master | 2021-01-01T20:05:44.559362 | 2014-04-30T17:50:06 | 2014-04-30T17:50:06 | 19,132,738 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 130 | hxx | #ifdef PEGASUS_OS_SOLARIS
#ifndef __UNIX_PROVIDESENDPOINT_PRIVATE_H
#define __UNIX_PROVIDESENDPOINT_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
f5df5f0d53a68282c66781eac485e1df32edc16b | ad54cec63c2873dad1321818fd2863f079b5ffa7 | /RepoFile.cpp | 12374a1e05fa7b0d0f9ea38d8b6b597bfed6b457 | [] | no_license | LauraDiosan-CS/lab5-6-template-stl-SintamareanCristina | db870bb36f7172d93b02b0b5ab239f23bc89590c | a893c1dbe4af9edb7975bb04aeaee015b028742e | refs/heads/master | 2021-05-20T00:39:20.613235 | 2020-04-15T06:28:30 | 2020-04-15T06:28:30 | 252,110,894 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,260 | cpp | #include "Repo.h"
#include "RepoFile.h"
#include <fstream>
#include <string.h>
#include <list>
#include "Car.h"
#include "Repo.cpp"
class RepoFile : public Repo {
private:
const char* fis;
public:
RepoFile(); RepoFile(const char* fileName) {
fis = fileName;
ifstream f(fileName);
string linie;
char* numePosesor = new char[30];
char* nrInmatriculare = new char[15];
char* status = new char[10];
while (!f.eof()) {
f >> numePosesor >> nrInmatriculare >> status;
if (numePosesor != "") {
Car c(numePosesor, nrInmatriculare, status);
addElem(c);
}
}
delete[] numePosesor;
delete[] nrInmatriculare;
delete[] status;
f.close();
}
~RepoFile() {
}
void loadFromFile(const char* fileName)
{
fis = fileName;
ifstream f(fileName);
char* numePosesor = new char[30];
char* nrInmatriculare = new char[15];
char* status = new char[10];
while (!f.eof()) {
f >> numePosesor >> nrInmatriculare >> status;
if (strcmp(numePosesor, "") != 0) {
Car s(numePosesor, nrInmatriculare, status);
addElem(s);
}
}
delete[] numePosesor;
delete[] nrInmatriculare;
delete[] status;
f.close();
};
int addElem(Car c)
{
list<Car>::iterator it;
int ok = 1;
for (it = elem.begin(); it != elem.end(); it++)
if (strcmp((*it).getNrInmatriculare(), c.getNrInmatriculare()) == 0)
ok = 0;
it = find(elem.begin(), elem.end(), c);
if (it == elem.end() and ok == 1)
{
addElem(c);
saveToFile();
return 0;
}
return -1;
}
void updateElem(Car c, const char* numePosesor, const char* nrInmatriculare, const char* status)
{
list<Car>::iterator it;
it = find(elem.begin(), elem.end(), c);
if (it != elem.end())
{
updateElem(c, numePosesor, nrInmatriculare, status);
}
saveToFile();
}
int delElem(Car c)
{
list<Car>::iterator it;
it = find(elem.begin(), elem.end(), c);
if (it != elem.end())
{
delElem(*it);
saveToFile();
return 0;
}
else
return -1;
}
void saveToFile()
{
ofstream f(fis);
for (int i = 0; i < dim(); i++)
if (i == dim() - 1)
f << getItemFromPos(i).getNumePosesor() << " " << getItemFromPos(i).getNrInmatriculare() << " " << getItemFromPos(i).getStatus();
else
f << getItemFromPos(i);
f.close();
}
}; | [
"sintamareancris@yahoo.com"
] | sintamareancris@yahoo.com |
ec8e715cb0a16d43dd690c92d1c69168e966752d | cd4dc874e9b5bcd6a9436ed383dc775af4868380 | /CPPProjects/RectangleSum.cpp | 1699fbeb6b920c7ffb9a03a33867501ae475e1cd | [
"MIT"
] | permissive | RafiulIslamRafi/ContestNeko | fcd5969f6b7fa9307d5f28ee1505f2210a603eb4 | 4dd7867e5bae92a3d60569a4aac9b894a4855fba | refs/heads/master | 2020-06-12T12:07:13.209347 | 2018-09-08T06:08:05 | 2018-09-08T06:08:05 | 194,293,411 | 2 | 0 | MIT | 2019-06-28T15:10:59 | 2019-06-28T15:10:58 | null | UTF-8 | C++ | false | false | 7,935 | cpp | #define LOGLEVEL 0
#define NDEBUG
// BEGIN CUT HERE
#define LOGLEVEL 1
// END CUT HERE
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cassert>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <cmath>
#include <cstdlib>
#include <array>
#include <type_traits>
#include <queue>
#include <stack>
#include <functional>
#include <sstream>
#include <unordered_set>
#include <unordered_map>
#include <deque>
#include <climits>
#include <cfloat>
#include <random>
using namespace std;
#define LOG(l, x) if (l <= LOGLEVEL) cout << x << endl
#define int64 long long
#define repeat(x) for (auto repeat_var = 0; repeat_var < x; ++repeat_var)
#define for_inc(i, x) for (auto i = 0; i < x; ++i)
#define for_dec(i, x) for (auto i = x - 1; i >= 0; --i)
#define for_inc_range(i, x, y) for (auto i = x; i <= y; ++i)
#define for_dec_range(i, x, y) for (auto i = x; i >= y; --i)
#define fill0(x) memset(x, 0, sizeof(x))
#define INT_INF ((int)2E9L)
#define INT64_INF ((int64)1E18L)
#define MOD 1000000007
template <class T> class RectangleSum {
vector<vector<T>> sum;
vector<vector<T>> a;
bool built;
int nRow, nCol;
public:
RectangleSum(int nRow, int nCol) {
this->nRow = nRow;
this->nCol = nCol;
sum.resize(nRow + 1);
for_inc_range(i, 0, nRow) sum[i].resize(nCol + 1);
a.resize(nRow + 1);
for_inc_range(i, 0, nRow) a[i].resize(nCol + 1);
built = false;
}
void set(int r, int c, T v) {
a[r][c] = v;
built = false;
}
void build() {
for_inc_range(r, 1, nRow) for_inc_range(c, 1, nCol) {
sum[r][c] = sum[r][c - 1] + sum[r - 1][c] - sum[r - 1][c - 1] + a[r][c];
}
built = true;
}
T getSum(int r1, int c1, int r2, int c2) const {
assert(built);
return sum[r2][c2] - sum[r1 -1][c2] - sum[r2][c1 - 1] + sum[r1 - 1][c1 - 1];
}
};
// SRM636 - P1
class ChocolateDividingEasy {
public:
int findBest( vector <string> a ) {
int nRow = (int) a.size();
int nCol = (int) a[0].size();
RectangleSum<int> sum(nRow, nCol);
for_inc_range(r, 1, nRow) for_inc_range(c, 1, nCol) sum.set(r, c, a[r - 1][c - 1] - '0');
sum.build();
int best = 0;
for_inc_range(cutR1, 1, nRow - 1) {
for_inc_range(cutR2, cutR1 + 1, nRow - 1) {
for_inc_range(cutC1, 1, nCol - 1) {
for_inc_range(cutC2, cutC1 + 1, nCol - 1) {
vector<int> r1s = {1, cutR1 + 1, cutR2 + 1};
vector<int> r2s = {cutR1, cutR2, nRow};
vector<int> c1s = {1, cutC1 + 1, cutC2 + 1};
vector<int> c2s = {cutC1, cutC2, nCol};
int ans = INT_INF;
for_inc(id1, 3) {
for_inc(id2, 3) {
int cur = sum.getSum(r1s[id1], c1s[id2], r2s[id1], c2s[id2]);
ans = min(ans, cur);
}
}
best = max(best, ans);
}
}
}
}
return best;
}
};
// BEGIN CUT HERE
#include <cstdio>
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
namespace moj_harness {
using std::string;
using std::vector;
int run_test_case(int);
void run_test(int casenum = -1, bool quiet = false) {
if (casenum != -1) {
if (run_test_case(casenum) == -1 && !quiet) {
std::cerr << "Illegal input! Test case " << casenum << " does not exist." << std::endl;
}
return;
}
int correct = 0, total = 0;
for (int i=0;; ++i) {
int x = run_test_case(i);
if (x == -1) {
if (i >= 100) break;
continue;
}
correct += x;
++total;
}
if (total == 0) {
std::cerr << "No test cases run." << std::endl;
} else if (correct < total) {
std::cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << std::endl;
} else {
std::cerr << "All " << total << " tests passed!" << std::endl;
}
}
int verify_case(int casenum, const int &expected, const int &received, std::clock_t elapsed) {
std::cerr << "Example " << casenum << "... ";
string verdict;
vector<string> info;
char buf[100];
if (elapsed > CLOCKS_PER_SEC / 200) {
std::sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC));
info.push_back(buf);
}
if (expected == received) {
verdict = "PASSED";
} else {
verdict = "FAILED";
}
std::cerr << verdict;
if (!info.empty()) {
std::cerr << " (";
for (size_t i=0; i<info.size(); ++i) {
if (i > 0) std::cerr << ", ";
std::cerr << info[i];
}
std::cerr << ")";
}
std::cerr << std::endl;
if (verdict == "FAILED") {
std::cerr << " Expected: " << expected << std::endl;
std::cerr << " Received: " << received << std::endl;
}
return verdict == "PASSED";
}
int run_test_case(int casenum__) {
switch (casenum__) {
case 0: {
string chocolate[] = {
"9768",
"6767",
"5313"
};
int expected__ = 3;
std::clock_t start__ = std::clock();
int received__ = ChocolateDividingEasy().findBest(vector <string>(chocolate, chocolate + (sizeof chocolate / sizeof chocolate[0])));
return verify_case(casenum__, expected__, received__, clock()-start__);
}
case 1: {
string chocolate[] = {
"36753562",
"91270936",
"06261879",
"20237592",
"28973612",
"93194784"
};
int expected__ = 15;
std::clock_t start__ = std::clock();
int received__ = ChocolateDividingEasy().findBest(vector <string>(chocolate, chocolate + (sizeof chocolate / sizeof chocolate[0])));
return verify_case(casenum__, expected__, received__, clock()-start__);
}
case 2: {
string chocolate[] = {
"012",
"345",
"678"
};
int expected__ = 0;
std::clock_t start__ = std::clock();
int received__ = ChocolateDividingEasy().findBest(vector <string>(chocolate, chocolate + (sizeof chocolate / sizeof chocolate[0])));
return verify_case(casenum__, expected__, received__, clock()-start__);
}
// custom cases
/* case 3: {
string chocolate[] = ;
int expected__ = ;
std::clock_t start__ = std::clock();
int received__ = ChocolateDividingEasy().findBest(vector <string>(chocolate, chocolate + (sizeof chocolate / sizeof chocolate[0])));
return verify_case(casenum__, expected__, received__, clock()-start__);
}*/
/* case 4: {
string chocolate[] = ;
int expected__ = ;
std::clock_t start__ = std::clock();
int received__ = ChocolateDividingEasy().findBest(vector <string>(chocolate, chocolate + (sizeof chocolate / sizeof chocolate[0])));
return verify_case(casenum__, expected__, received__, clock()-start__);
}*/
/* case 5: {
string chocolate[] = ;
int expected__ = ;
std::clock_t start__ = std::clock();
int received__ = ChocolateDividingEasy().findBest(vector <string>(chocolate, chocolate + (sizeof chocolate / sizeof chocolate[0])));
return verify_case(casenum__, expected__, received__, clock()-start__);
}*/
default:
return -1;
}
}
}
#include <cstdlib>
int main(int argc, char *argv[]) {
if (argc == 1) {
moj_harness::run_test();
} else {
for (int i=1; i<argc; ++i)
moj_harness::run_test(std::atoi(argv[i]));
}
}
// END CUT HERE
| [
"ducnm0@gmail.com"
] | ducnm0@gmail.com |
ffeeb41db0f671fe7b9c4d4c9afb2d7b78534a72 | 7a92206984e9007948afaa363adbb95c06897a74 | /demo/DesignPatternsTest/Builder.cpp | 646c6359c29d5dd56c74ef7a9a828aaebf77ab5d | [] | no_license | fengbingchun/Messy_Test | 6a801414a36581bce16edbde122b66ac86b57ddb | b55fcfc4b8adc538f9ac70bf78aa391a50b20241 | refs/heads/master | 2023-06-26T18:07:59.679346 | 2023-06-22T06:23:16 | 2023-06-22T06:23:16 | 55,020,860 | 305 | 171 | null | null | null | null | UTF-8 | C++ | false | false | 1,729 | cpp | #include "Builder.hpp"
#include "director.hpp"
// Blog: http://blog.csdn.net/fengbingchun/article/details/22593157
Builder_1::Builder_1()
{
}
Builder_1::~Builder_1()
{
}
ConcreteBuilder::ConcreteBuilder()
{
}
ConcreteBuilder::~ConcreteBuilder()
{
}
void ConcreteBuilder::BuildPartA(const std::string& buildPara)
{
std::cout << "Step1:Build PartA ..." << buildPara << std::endl;
}
void ConcreteBuilder::BuildPartB(const std::string& buildPara)
{
std::cout << "Step1:Build PartB ..." << buildPara << std::endl;
}
void ConcreteBuilder::BuildPartC(const std::string& buildPara)
{
std::cout << "Step1:Build PartC ..." << buildPara << std::endl;
}
Product* ConcreteBuilder::GetProduct()
{
BuildPartA("pre-defined");
BuildPartB("pre-defined");
BuildPartC("pre-defined");
return new Product();
}
int test_Builder1()
{
Direct* p = new Direct();
Builder* b1 = new ConCreteBuilder1();
Builder* b2 = new ConcreteBuilder2();
p->Construct(b1);//调用第一种方式
Product* pb1 = b1->GetResult();
pb1->Show();
p->Construct(b2);//调用第二种方式
Product* pb2 = b2->GetResult();
pb2->Show();
/* result:
one
two
A
B
*/
return 0;
}
int test_Builder2()
{
Person* p = new ThickPerson();
Direct_* d = new Direct_(p);
d->Create();
delete d;
delete p;
/*result:
ThickPerson head
ThickPerson hand
ThickPerson body
ThickPerson foot
*/
return 0;
}
int test_Builder3()
{
Director* d = new Director(new ConcreteBuilder());
d->Construct();
/*result:
Step1:Build PartA ...user-defined
Step1:Build PartB ...user-defined
Step1:Build PartC ...user-defined
*/
return 0;
}
| [
"fengbingchun@163.com"
] | fengbingchun@163.com |
2d318f4e6113cf57a7545631601a94e3a85d9179 | 62a9e86743572b2c1c485809d181419e5229ae22 | /leetcode/apple/461-Hamming-Distance.cpp | f44d8b5da918b1d53ef637554499fd37a9253bf3 | [] | no_license | BinWangGBLW/leetcode | 7fbe7d02fb9a7667f708cd8d9d4fa75f0fa48a7a | cd8c0b25866d7a25dc12c137ac92ae35627c99b3 | refs/heads/master | 2021-04-06T05:58:43.554030 | 2018-03-20T21:38:34 | 2018-03-20T21:38:34 | 125,078,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 783 | cpp | #include <iostream>
#include <vector>
/*
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
*/
using namespace std;
class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0;
for (int i = 0; i < 32; ++i) {
if ((x & (1 << i)) ^ (y & (1 << i))) {
++res;
}
}
return res;
}
};
int main () {
Solution s;
cout << s.hammingDistance(1, 4) << endl;
}
| [
"b.wang@qub.ac.uk"
] | b.wang@qub.ac.uk |
dfe77ffc7c011ddc24d2762108661b8c81071fe4 | 7cce0635a50e8d2db92b7b1bf4ad49fc218fb0b8 | /郭鑫程序交接/line.2012.06.12/line/line3/WndInstrument.cpp | 438876d922050056752ac2b0f34d2e8a04c6096a | [] | no_license | liquanhai/cxm-hitech-matrix428 | dcebcacea58123aabcd9541704b42b3491444220 | d06042a3de79379a77b0e4e276de42de3c1c6d23 | refs/heads/master | 2021-01-20T12:06:23.622153 | 2013-01-24T01:05:10 | 2013-01-24T01:05:10 | 54,619,320 | 2 | 2 | null | null | null | null | GB18030 | C++ | false | false | 3,096 | cpp | // WndInstrument.cpp : 实现文件
//
#include "stdafx.h"
#include "line.h"
#include "WndInstrument.h"
// CWndInstrument
IMPLEMENT_DYNAMIC(CWndInstrument, CBCGPStatic)
CWndInstrument::CWndInstrument()
{
/** 仪器总数*/
m_uiInstrumentCountAll = 0;
/** 图形单元间隔X*/
m_iGridX = 50;
/** 图形单元间隔Y*/
m_iGridY = 50;
/** 图形单元宽度*/
m_iUnitWidth = 32;
/** 图形单元高度*/
m_iUnitHight = 32;
/** 图形高度X*/
m_iPaperHight = 100;
}
CWndInstrument::~CWndInstrument()
{
}
BEGIN_MESSAGE_MAP(CWndInstrument, CBCGPStatic)
ON_WM_SIZE()
ON_WM_PAINT()
END_MESSAGE_MAP()
// CWndInstrument 消息处理程序
void CWndInstrument::OnSize(UINT nType, int cx, int cy)
{
CBCGPStatic::OnSize(nType, cx, cy);
RedrawWindow();
}
void CWndInstrument::OnPaint()
{
CPaintDC dc(this);
GetClientRect(&m_oRect);
m_iPaperHight = m_oRect.bottom - m_iGridY;
// 画背景
DrawBackground(&dc);
// 画连接线
DrawLinkLine(&dc);
// 画全部单元图
if(1 < m_uiInstrumentCountAll)
{
for(unsigned int i = 0; i < m_uiInstrumentCountAll; i++)
{
DrawUnit(&dc, i);
}
}
}
/**
* 画背景
* @param CDC* pDC 画图句柄
* @return void
*/
void CWndInstrument::DrawBackground(CDC* pDC)
{
CBrush oBrush;
CBrush* pOldPenBrush;
oBrush.CreateSolidBrush(RGB(255, 255, 255));
pOldPenBrush = pDC->SelectObject(&oBrush);
pDC->FillRect(&m_oRect, &oBrush);
pDC->SelectObject(pOldPenBrush);
}
/**
* 画连接线
* @param CDC* pDC 画图句柄
* @return void
*/
void CWndInstrument::DrawLinkLine(CDC* pDC)
{
CPen oPenLine;
CPen* pOldPen;
oPenLine.CreatePen(PS_SOLID, 3, RGB(0, 128, 0));
pOldPen = pDC->SelectObject(&oPenLine);
CPoint ptStart, ptEnd;
ptStart.x = m_iGridX;
ptStart.y = m_iPaperHight;
ptEnd.x = (m_uiInstrumentCountAll) * m_iGridX;
ptEnd.y = m_iPaperHight;
pDC->MoveTo(ptStart);
pDC->LineTo(ptEnd);
pDC->SelectObject(pOldPen);
}
/**
* 函数说明
* @param CDC* pDC 画图句柄
* @param int iIndex 图形单元索引
* @return void
*/
// 画单元图
void CWndInstrument::DrawUnit(CDC* pDC, int iIndex)
{
CPen oPenUnit;
CPen* pOldPen;
CBrush oBrushUnit;
CBrush* pOldPenBrush;
int iCenterX = m_iGridX + iIndex * m_iGridX;
int iCenterY = m_iPaperHight;
CRect oRect;
oRect.left = iCenterX - m_iUnitWidth / 2;
oRect.top = iCenterY - m_iUnitHight / 2;
oRect.right = oRect.left + m_iUnitWidth;
oRect.bottom = oRect.top + m_iUnitHight;
oPenUnit.CreatePen(PS_SOLID, 0, RGB(0, 0, 0));
oBrushUnit.CreateSolidBrush(RGB(0, 255, 0)); // 绿色
pOldPen = pDC->SelectObject(&oPenUnit);
pOldPenBrush = pDC->SelectObject(&oBrushUnit);
pDC->Ellipse(&oRect);
pDC->SelectObject(pOldPen);
pDC->SelectObject(pOldPenBrush);
}
/**
* 响应显示迂回道图形视图
* @param unsigned int uiCount 迂回道中仪器数量
* @return void
*/
void CWndInstrument::OnShowDetourGraphView(unsigned int uiCount)
{
m_uiInstrumentCountAll = uiCount;
RedrawWindow();
}
| [
"chengxianming1981@gmail.com"
] | chengxianming1981@gmail.com |
4277d7e725dcae1ee05b89d4f024b5a4c1139927 | 4769bb26031102e53e0f15a46c45946f38b90214 | /CPU_STACK 1.1/CPU.cpp | 3dd670b7f4d0ec78bbc5f7158805212bb4bb1a42 | [] | no_license | eduardgorbunov/edscorp | 9233d33bbef107e3da236139237f10f943690f58 | 4b6a45234cc022c0cc8c9fd58cffd0291cbe125c | refs/heads/master | 2016-08-11T08:37:03.616267 | 2015-06-04T20:36:35 | 2015-06-04T20:36:35 | 36,892,705 | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 14,837 | cpp | #include <string.h>
#include <conio.h>
#include <locale.h>
#include <ctype.h>
#include "Stack_Instructions.cpp"
#define assert_cpu(cond) if (!cond) {CPU_info(cp);\
printf("ERROR in the line number %d\n", __LINE__); assert(cond);}
#define NUMBER_OF_COMANDS 30
struct EDCPU_t
{
double ax;
double bx;
double cx;
double dx;
EDStack_t Stack;
};
enum Commands_t
{
#define DEF_CMD_(name, num, code) name = num,
#include "Comands.h"
#undef DEF_CMD_
CMD_MAX
};
ERRORS CPU_popr (EDCPU_t* cp, int nreg);
ERRORS CPU_ok (EDCPU_t* cp);
void CPU_info (EDCPU_t* cp);
ERRORS CPU_add (EDCPU_t* cp);
ERRORS CPU_mul (EDCPU_t* cp);
ERRORS CPU_outr (EDCPU_t* cp, int nreg);
ERRORS CPU_in (EDCPU_t* cp, int nreg);
ERRORS CPU_div (EDCPU_t* cp);
ERRORS CPU_pow (EDCPU_t* cp, double exponent);
void ReadFileInBuffer (char** buf, int* len, FILE* f);
int CountOf (char* buf, char a, int length);
void CreateArrayOfPointersToStr (char*** str, int* AmountOfStr, char* buf, int len);
ERRORS CPU_pushr(EDCPU_t* cp, int nreg);
int main (int argc, const char* argv[])
{
EDCPU_t cp = {};
FILE *f = fopen ((argv[1]? argv[1] : "FIBO.TXT"), "r");
Stack_construct(&(cp.Stack));
assert(f != NULL);
char* buf = NULL;
int len = POISON;
ReadFileInBuffer (&buf, &len, f);
char** str = NULL;
int AmountOfStr = POISON;
CreateArrayOfPointersToStr(&str, &AmountOfStr, buf, len);
#include "assembler.h"
#include "disassembler.h"
EDStack_t CallStack = {};
Stack_construct(&(CallStack));
int i = 0;
double value = POISON; //it's a pocket for Comands.h
assert(i == 0);
while (i < NumOfCellIncmds)
{
if (0 <= (int) cmds[i] && (int) cmds[i] <= 9)
{
i++;
}
else
{
#define DEF_CMD_(name, num, code) case num: code; break;
switch ((int) cmds[i])
{
#include "Comands.h"
default: printf("WRONG ASSERT IN ASSEMBLER.H");
assert(0);
break;
}
#undef DEF_CMD_
}
}
Stack_destruct(&(cp.Stack));
Stack_destruct(&(CallStack));
fclose(f);
free(buf);
free(str);
free(cmds);
free(labels);
if (argv[1])
{
printf("\n");
printf("Write something\n");
double forMain = 0;
scanf("%lg", &forMain);
}
return 0;
}
//{==================================================================================
//! CPU_popr - program which take the last element from stack and push it in register
//!
//! @param stk - Pointer to a structure
//! @param nreg - The number of register
//!
//! @return Number of an error
//}==================================================================================
ERRORS CPU_popr (EDCPU_t* cp, int nreg)
{
ERRORS nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
assert(0 < nreg && nreg < 5);
switch (nreg)
{
case 1: Stack_pop(&(cp->Stack), &(cp->ax));
break;
case 2: Stack_pop(&(cp->Stack), &(cp->bx));
break;
case 3: Stack_pop(&(cp->Stack), &(cp->cx));
break;
case 4: Stack_pop(&(cp->Stack), &(cp->dx));
break;
default: printf("FAILURE IN MATRIX: WRONG ASSERT");
break;
}
nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
return nerrorcp;
}
//{=================================================================================
//! CPU_ok - program which check cpu for errors
//!
//! @param stk - Pointer to a cpu
//!
//! @return Number of an error
//}=================================================================================
ERRORS CPU_ok (EDCPU_t* cp)
{
ERRORS nerrorcp = OK;
if (cp != NULL)
{
nerrorcp = Stack_ok(&(cp->Stack));
if (nerrorcp == OK)
{
if (&(cp->ax) == NULL) nerrorcp = NULL_POINTER_ON_REGISTER_ax;
if (&(cp->bx) == NULL) nerrorcp = NULL_POINTER_ON_REGISTER_bx;
if (&(cp->cx) == NULL) nerrorcp = NULL_POINTER_ON_REGISTER_cx;
if (&(cp->dx) == NULL) nerrorcp = NULL_POINTER_ON_REGISTER_dx;
}
}
else nerrorcp = NULL_POINTER_ON_CPU;
return nerrorcp;
}
//{=================================================================================
//! CPU_info - program which print some useful information about cpu
//!
//! @param stk - Pointer to a structure
//}=================================================================================
void CPU_info (EDCPU_t* cp)
{
printf("================================================================================\n");
printf("The list of ERRORS:\n");
printf("OK = 0: stack is normal\n");
printf("BAD_PUSH = 1: stack has elements in zero cell\n");
printf("BAD_NTOP = 2: the number of the last element in stack is more\n");
printf(" than the maximum allowable number or it's less\n");
printf(" than zero\n");
printf("STRERROR = 3: NULL pointer on the body of stack\n");
printf("BAD_INPUT = 4: bad parameters were transmitted to function\n");
printf("NULL_POINTER_ON_STACK = 5: null pointer on structure\n");
printf("NULL_POINTER_ON_REGISTER_ax = 6: null pointer on register ax\n");
printf("NULL_POINTER_ON_REGISTER_bx = 7: null pointer on register bx\n");
printf("NULL_POINTER_ON_REGISTER_cx = 8: null pointer on register cx\n");
printf("NULL_POINTER_ON_REGISTER_dx = 9: null pointer on register dx\n");
printf("NULL_POINTER_ON_CPU = 10: null pointer on cpu\n");
printf("BAD_ZERO_CELL = 11: there is not a POISON = %d in zero cell\n", POISON);
printf("--------------------------------------------------------------------------------\n");
ERRORS nerrorcp = CPU_ok(cp);
printf("EDCPU_t (%d) [%p]\n", nerrorcp, cp);
if (nerrorcp != NULL_POINTER_ON_CPU)
{
if (nerrorcp != NULL_POINTER_ON_REGISTER_ax) printf("Register ax = %lg\n", cp->ax);
if (nerrorcp != NULL_POINTER_ON_REGISTER_bx) printf("Register bx = %lg\n", cp->bx);
if (nerrorcp != NULL_POINTER_ON_REGISTER_cx) printf("Register cx = %lg\n", cp->cx);
if (nerrorcp != NULL_POINTER_ON_REGISTER_dx) printf("Register dx = %lg\n", cp->dx);
ERRORS nerror = Stack_ok(&(cp->Stack));
if (nerror != NULL_POINTER_ON_STACK)
{
printf(" {\n");
printf(" ntop = %d\n", (cp->Stack).ntop);
printf(" body [%d] [%p]\n", (cp->Stack).maxntop, (cp->Stack).body);
printf(" {\n");
printf(" [0] = %lg *\n", (cp->Stack).body[0]);
int i = 0;
for (i = 1; i <= (cp->Stack).ntop; i++)
printf(" [%d] = %lg\n", i, (cp->Stack).body[i]);
for (i = (cp->Stack).ntop + 1; i <= (cp->Stack).maxntop; i++)
printf(" [%d] = %lg *\n", i, (cp->Stack).body[i]);
printf(" }\n");
printf(" }\n");
}
}
printf("================================================================================\n");
}
//{=================================================================================
//! CPU_add - program which add two last elements in stack
//!
//! @param cp - Pointer to a cpu
//!
//! @return Number of an error
//}=================================================================================
ERRORS CPU_add (EDCPU_t* cp)
{
ERRORS nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
if ((cp->Stack).ntop < 2)
{
nerrorcp = BAD_INPUT;
assert_cpu(nerrorcp == OK);
}
else
{
(cp->Stack).body[(cp->Stack).ntop - 1] = (cp->Stack).body[(cp->Stack).ntop - 1] + (cp->Stack).body[(cp->Stack).ntop];
(cp->Stack).body[(cp->Stack).ntop] = POISON;
(cp->Stack).ntop--;
nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
}
return nerrorcp;
}
//{=================================================================================
//! CPU_mul - program which multiple two last elements in stack
//!
//! @param cp - Pointer to a cpu
//!
//! @return Number of an error
//}=================================================================================
ERRORS CPU_mul (EDCPU_t* cp)
{
ERRORS nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
if ((cp->Stack).ntop < 2)
{
nerrorcp = BAD_INPUT;
assert_cpu(nerrorcp == OK);
}
else
{
(cp->Stack).body[(cp->Stack).ntop - 1] = (cp->Stack).body[(cp->Stack).ntop - 1] * (cp->Stack).body[(cp->Stack).ntop];
(cp->Stack).body[(cp->Stack).ntop] = POISON;
(cp->Stack).ntop--;
nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
}
return nerrorcp;
}
//{=================================================================================
//! CPU_outr - program which print out value of register
//!
//! @param cp - Pointer to a cpu
//!
//! @return Number of an error
//}=================================================================================
ERRORS CPU_outr (EDCPU_t* cp, int nreg)
{
ERRORS nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
assert(0 < nreg && nreg < 5);
switch (nreg)
{
case 1: printf("%lg\n", cp->ax);
break;
case 2: printf("%lg\n", cp->bx);
break;
case 3: printf("%lg\n", cp->cx);
break;
case 4: printf("%lg\n", cp->dx);
break;
default: printf("FAILURE IN MATRIX: WRONG ASSERT\n");
assert(0);
break;
}
nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
return nerrorcp;
}
//{=================================================================================
//! CPU_in - program which scan value from keyboard and put it in register
//!
//! @param cp - Pointer to a cpu
//! @param nreg - The number of register
//!
//! @return Number of an error
//}=================================================================================
ERRORS CPU_in (EDCPU_t* cp, int nreg)
{
ERRORS nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
double value = POISON;
assert(&value != NULL);
int Input = scanf("%lg", &value);
assert(Input == 1);
assert(0 < nreg && nreg < 5);
switch (nreg)
{
case 1: cp->ax = value;
break;
case 2: cp->bx = value;
break;
case 3: cp->cx = value;
break;
case 4: cp->dx = value;
break;
default: printf("FAILURE IN MATRIX: WRONG ASSERT");
break;
}
nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
return nerrorcp;
}
//{=================================================================================
//! CPU_div - program which divide the last element on the last but one element
//! from stack
//!
//! @param cp - Pointer to a cpu
//!
//! @return Number of an error
//}=================================================================================
ERRORS CPU_div (EDCPU_t* cp)
{
ERRORS nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
if ((cp->Stack).ntop < 2 || (cp->Stack).body[(cp->Stack).ntop - 1] == 0)
{
nerrorcp = BAD_INPUT;
assert_cpu(nerrorcp == OK);
}
else
{
(cp->Stack).body[(cp->Stack).ntop - 1] = (cp->Stack).body[(cp->Stack).ntop]/(cp->Stack).body[(cp->Stack).ntop - 1];
(cp->Stack).body[(cp->Stack).ntop] = POISON;
(cp->Stack).ntop--;
}
nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
return nerrorcp;
}
//{=================================================================================
//! CPU_pow - program which involute last element from stack in degree exponent
//!
//! @param cp - Pointer to a cpu
//! @param exponent - exponent
//!
//! @return Number of an error
//}=================================================================================
ERRORS CPU_pow (EDCPU_t* cp, double exponent)
{
ERRORS nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
if (Stack_isEmpty(&(cp->Stack)) == 1)
{
nerrorcp = BAD_INPUT;
assert_cpu(nerrorcp == OK);
}
else
{
(cp->Stack).body[(cp->Stack).ntop] = pow((cp->Stack).body[(cp->Stack).ntop], exponent);
}
nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
return nerrorcp;
}
//{=================================================================================
//! ReadFileInBuffer - program which read file in buffer
//!
//! @param[out] buf - Pointer to the buffer
//! @param[out] len - The length of the buffer
//! @param[out] f - Pointer to the file
//}=================================================================================
void ReadFileInBuffer (char** buf, int* len, FILE* f)
{
assert(f != NULL);
assert(buf != NULL);
assert((*buf) == NULL);
assert(len != NULL);
fseek (f, 0, SEEK_END);
*len = ftell (f);
rewind (f);
*buf = (char*) calloc ((*len) + 1, sizeof (char));
assert((*buf) != NULL);
fread (*buf, *len, sizeof(char), f);
(*buf)[*len] = '\n';
(*len)++;
}
//{=================================================================================
//! CountOf - ņounting the number of occurrences of the symbol in the string.
//!
//! @param buf A pointer to the beginning of the string
//! @param a Symbol
//! @param length The length of the string
//!
//! @return Number of occurrences of the symbol a (the second parameter)
//}=================================================================================
int CountOf (char* buf, char a, int length)
{
assert(buf != NULL);
int i = 0, counter = 0;
for (i = 0; i < length; i++)
{
if (buf[i] == a) counter++;
}
return counter;
}
//{=================================================================================
//! CreateArrayOfPointersToStr - program which create array of pointer to strings
//!
//! @param[out] str - Pointer to the char**
//! @param[out] AmountOfStr - The amount of strings
//! @param[out] buf - Pointer to the buffer
//! @param[out] len - The length of the buffer
//}=================================================================================
void CreateArrayOfPointersToStr (char*** str, int* AmountOfStr, char* buf, int len)
{
assert(AmountOfStr != NULL);
assert(str != NULL);
assert(*str == NULL);
*AmountOfStr = CountOf(buf, '\n', len);
*str = (char**) calloc(*AmountOfStr, sizeof(char*));
assert((*str) != NULL);
int i = 0, startStr = 0, nStr = 0;
for (i = 0; i < len; i++)
{
if (buf[i] == '\n')
{
(*str)[nStr] = buf + startStr;
nStr++;
startStr = i + 1;
}
}
}
//{==================================================================================
//! CPU_pushr - program which put value from register in stack
//!
//! @param stk - Pointer to a structure
//! @param nreg - The number of register
//!
//! @return Number of an error
//}==================================================================================
ERRORS CPU_pushr(EDCPU_t* cp, int nreg)
{
ERRORS nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
assert(0 < nreg && nreg < 5);
switch (nreg)
{
case 1: Stack_push(&(cp->Stack), cp->ax);
break;
case 2: Stack_push(&(cp->Stack), cp->bx);
break;
case 3: Stack_push(&(cp->Stack), cp->cx);
break;
case 4: Stack_push(&(cp->Stack), cp->dx);
break;
default: printf("WRONG ASSERT\n");
assert(0);
break;
}
nerrorcp = CPU_ok(cp);
assert_cpu(nerrorcp == OK);
return nerrorcp;
}
| [
"ed-gorbunov@yandex.ru"
] | ed-gorbunov@yandex.ru |
7ce9cf0571433f8b2542c5fa638a2c18f56a7209 | 11f77b4c947c3869dbd2398d20fd2394e7c62daf | /melodic/src/rviz/src/rviz/time_panel.cpp | ec73b23241e718f044c96d0d8d7c230c7c888bf2 | [
"CC-PDDC",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause"
] | permissive | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 4658fd1732461d9065cd3ff94ba10aec7f60fd2e | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | refs/heads/master | 2022-07-18T15:11:23.740964 | 2020-05-23T06:57:58 | 2020-05-23T06:57:58 | 279,299,388 | 3 | 0 | null | 2020-07-13T12:41:32 | 2020-07-13T12:41:31 | null | UTF-8 | C++ | false | false | 9,216 | cpp |
/*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QHBoxLayout>
#include <QButtonGroup>
#include <QCheckBox>
#include <QSlider>
#include <QComboBox>
#include "visualization_manager.h"
#include "frame_manager.h"
#include "display_group.h"
#include "time_panel.h"
namespace rviz
{
TimePanel::TimePanel( QWidget* parent )
: Panel( parent )
{
wall_time_label_ = makeTimeLabel();
wall_elapsed_label_ = makeTimeLabel();
ros_time_label_ = makeTimeLabel();
ros_elapsed_label_ = makeTimeLabel();
experimental_cb_ = new QCheckBox("Experimental");
experimental_cb_->setSizePolicy( QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum) );
pause_button_ = new QPushButton( "Pause" );
pause_button_->setToolTip("Freeze ROS time.");
pause_button_->setCheckable(true);
sync_mode_selector_ = new QComboBox(this);
sync_mode_selector_->addItem( "Off" );
sync_mode_selector_->addItem( "Exact" );
sync_mode_selector_->addItem( "Approximate" );
sync_mode_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
sync_mode_selector_->setToolTip("Allows you to synchronize the ROS time and Tf transforms to a given source.");
// choose time sync signal
sync_source_selector_ = new QComboBox(this);
sync_source_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
sync_source_selector_->setToolTip("Time source to use for synchronization.");
experimental_widget_ = new QWidget(this);
QHBoxLayout* experimental_layout = new QHBoxLayout(this);
experimental_layout->addWidget( pause_button_ );
experimental_layout->addWidget( new QLabel( "Synchronization:" ));
experimental_layout->addWidget( sync_mode_selector_ );
experimental_layout->addWidget( new QLabel( "Source:" ));
experimental_layout->addWidget( sync_source_selector_ );
experimental_layout->addSpacing(20);
experimental_layout->setContentsMargins( 0, 0, 20, 0 );
experimental_widget_->setLayout(experimental_layout);
old_widget_ = new QWidget(this);
QHBoxLayout* old_layout = new QHBoxLayout(this);
old_layout->addWidget( new QLabel( "ROS Elapsed:" ));
old_layout->addWidget( ros_elapsed_label_ );
old_layout->addWidget( new QLabel( "Wall Time:" ));
old_layout->addWidget( wall_time_label_ );
old_layout->addWidget( new QLabel( "Wall Elapsed:" ));
old_layout->addWidget( wall_elapsed_label_ );
old_layout->setContentsMargins( 0, 0, 20, 0 );
old_widget_->setLayout(old_layout);
QHBoxLayout* layout = new QHBoxLayout(this);
layout->addWidget(experimental_widget_);
layout->addWidget( new QLabel( "ROS Time:" ));
layout->addWidget( ros_time_label_ );
layout->addWidget(old_widget_);
layout->addStretch(100);
layout->addWidget( experimental_cb_ );
layout->addStretch();
layout->setContentsMargins( 11, 5, 11, 5 );
connect( experimental_cb_, SIGNAL( toggled( bool )), this, SLOT( experimentalToggled( bool ) ));
connect( pause_button_, SIGNAL( toggled( bool )), this, SLOT( pauseToggled( bool ) ));
connect( sync_mode_selector_, SIGNAL( activated( int )), this, SLOT( syncModeSelected( int ) ));
connect( sync_source_selector_, SIGNAL( activated( int )), this, SLOT( syncSourceSelected( int ) ));
}
void TimePanel::onInitialize()
{
connect( vis_manager_, SIGNAL( preUpdate() ), this, SLOT( update() ));
DisplayGroup *display_group = vis_manager_->getRootDisplayGroup();
onDisplayAdded(display_group);
syncModeSelected(0);
pauseToggled(false);
}
void TimePanel::load( const Config& config )
{
Panel::load(config);
int sync_mode;
if( config.mapGetInt( "SyncMode", &sync_mode ))
{
sync_mode_selector_->setCurrentIndex(sync_mode);
syncModeSelected(sync_mode);
}
config.mapGetString( "SyncSource", &config_sync_source_ );
bool experimental = false;
config.mapGetBool( "Experimental", &experimental );
experimental_cb_->setChecked(experimental);
experimentalToggled(experimental);
}
void TimePanel::save( Config config ) const
{
Panel::save(config);
config.mapSetValue( "SyncMode", sync_mode_selector_->currentIndex() );
config.mapSetValue( "SyncSource", sync_source_selector_->currentText() );
config.mapSetValue( "Experimental", experimental_cb_->checkState() == Qt::Checked );
}
void TimePanel::onDisplayAdded( Display* display )
{
DisplayGroup* display_group = qobject_cast<DisplayGroup*>( display );
if( display_group )
{
connect( display_group, SIGNAL( displayAdded( rviz::Display* ) ), this, SLOT( onDisplayAdded( rviz::Display* ) ));
connect( display_group, SIGNAL( displayRemoved( rviz::Display* ) ), this, SLOT( onDisplayRemoved( rviz::Display* ) ));
for( int i = 0; i < display_group->numDisplays(); i++ )
{
rviz::Display* display = display_group->getDisplayAt( i );
onDisplayAdded( display );
}
}
else
{
connect( display, SIGNAL( timeSignal( rviz::Display*, ros::Time ) ), this, SLOT( onTimeSignal( rviz::Display*, ros::Time ) ));
}
}
void TimePanel::onDisplayRemoved( Display* display )
{
QString name = display->getName();
int index = sync_source_selector_->findData( QVariant( (qulonglong)display ) );
if ( index >= 0 )
{
sync_source_selector_->removeItem( index );
}
}
void TimePanel::onTimeSignal( Display* display, ros::Time time )
{
QString name = display->getName();
int index = sync_source_selector_->findData( QVariant( (qulonglong)display ) );
// if we loaded the sync source name from the config, we need to
// switch to it as soon as we get a signal
if ( index < 0 && name == config_sync_source_ )
{
sync_source_selector_->addItem( name, QVariant( (qulonglong)display ) );
index = sync_source_selector_->findData( QVariant( (qulonglong)display ) );
sync_source_selector_->setCurrentIndex(index);
config_sync_source_.clear();
}
if ( index < 0 )
{
sync_source_selector_->addItem( name, QVariant( (qulonglong)display ) );
}
else
{
sync_source_selector_->setItemText( index, name );
if ( sync_source_selector_->currentIndex() == index )
{
vis_manager_->getFrameManager()->syncTime( time );
}
}
}
QLineEdit* TimePanel::makeTimeLabel()
{
QLineEdit* label = new QLineEdit;
label->setReadOnly( true );
return label;
}
void TimePanel::fillTimeLabel( QLineEdit* label, double time )
{
label->setText( QString::number( time, 'f', 2 ));
}
void TimePanel::update()
{
fillTimeLabel( ros_time_label_, vis_manager_->getROSTime() );
fillTimeLabel( ros_elapsed_label_, vis_manager_->getROSTimeElapsed() );
fillTimeLabel( wall_time_label_, vis_manager_->getWallClock() );
fillTimeLabel( wall_elapsed_label_, vis_manager_->getWallClockElapsed() );
}
void TimePanel::pauseToggled( bool checked )
{
vis_manager_->getFrameManager()->setPause( checked );
}
void TimePanel::experimentalToggled( bool checked )
{
old_widget_->setVisible(!checked);
experimental_widget_->setVisible(checked);
if ( vis_manager_ && vis_manager_->getFrameManager() )
{
if ( !checked )
{
pauseToggled(false);
syncModeSelected(0);
}
else
{
pauseToggled(pause_button_->isChecked());
syncModeSelected(sync_mode_selector_->currentIndex());
}
}
}
void TimePanel::syncSourceSelected( int /*index*/ )
{
// clear whatever was loaded from the config
config_sync_source_.clear();
vis_manager_->notifyConfigChanged();
}
void TimePanel::syncModeSelected( int mode )
{
vis_manager_->getFrameManager()->setSyncMode( (FrameManager::SyncMode)mode );
sync_source_selector_->setEnabled( mode != FrameManager::SyncOff );
vis_manager_->notifyConfigChanged();
}
} // namespace rviz
| [
"chiioleong519@gmail.com"
] | chiioleong519@gmail.com |
bddfcacada3b737a025fcf7c7eccf3ad326725b3 | 7d2a0e66f73ff0746f3195566321e39f0b7f13c9 | /talk/media/webrtc/webrtcvideoengine.cc | e95e1422d77dc2188aff7e1a87e4d8a3da690326 | [] | no_license | jeidee/xmpp_p2p_exported_from_libjingle | 7027eb0e5ad2cfb2bdd7edb9c2dfabfa40219ad6 | 738183945910c66d0de6b55b3fbe2a8e9e1880ea | refs/heads/master | 2020-03-27T19:04:57.951621 | 2016-06-21T12:46:36 | 2016-06-21T12:46:36 | 61,092,613 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 121,519 | cc | /*
* libjingle
* Copyright 2004 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_WEBRTC_VIDEO
#include "talk/media/webrtc/webrtcvideoengine.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <math.h>
#include <set>
#include "talk/base/basictypes.h"
#include "talk/base/buffer.h"
#include "talk/base/byteorder.h"
#include "talk/base/common.h"
#include "talk/base/cpumonitor.h"
#include "talk/base/logging.h"
#include "talk/base/stringutils.h"
#include "talk/base/thread.h"
#include "talk/base/timeutils.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/rtputils.h"
#include "talk/media/base/streamparams.h"
#include "talk/media/base/videoadapter.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videorenderer.h"
#include "talk/media/devices/filevideocapturer.h"
#include "talk/media/webrtc/webrtcvideodecoderfactory.h"
#include "talk/media/webrtc/webrtcvideoencoderfactory.h"
#include "talk/media/webrtc/webrtcpassthroughrender.h"
#include "talk/media/webrtc/webrtcvideocapturer.h"
#include "talk/media/webrtc/webrtcvideoframe.h"
#include "talk/media/webrtc/webrtcvie.h"
#include "talk/media/webrtc/webrtcvoe.h"
#include "talk/media/webrtc/webrtcvoiceengine.h"
#if !defined(LIBPEERCONNECTION_LIB)
#ifndef HAVE_WEBRTC_VIDEO
#error Need webrtc video
#endif
#include "talk/media/webrtc/webrtcmediaengine.h"
WRME_EXPORT
cricket::MediaEngineInterface* CreateWebRtcMediaEngine(
webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc,
cricket::WebRtcVideoEncoderFactory* encoder_factory,
cricket::WebRtcVideoDecoderFactory* decoder_factory) {
return new cricket::WebRtcMediaEngine(adm, adm_sc, encoder_factory,
decoder_factory);
}
WRME_EXPORT
void DestroyWebRtcMediaEngine(cricket::MediaEngineInterface* media_engine) {
delete static_cast<cricket::WebRtcMediaEngine*>(media_engine);
}
#endif
namespace cricket {
static const int kDefaultLogSeverity = talk_base::LS_WARNING;
static const int kMinVideoBitrate = 50;
static const int kStartVideoBitrate = 300;
static const int kMaxVideoBitrate = 2000;
static const int kDefaultConferenceModeMaxVideoBitrate = 500;
static const int kVideoMtu = 1200;
static const int kVideoRtpBufferSize = 65536;
static const char kVp8PayloadName[] = "VP8";
static const char kRedPayloadName[] = "red";
static const char kFecPayloadName[] = "ulpfec";
static const int kDefaultNumberOfTemporalLayers = 1; // 1:1
static const int kTimestampDeltaInSecondsForWarning = 2;
static const int kMaxExternalVideoCodecs = 8;
static const int kExternalVideoPayloadTypeBase = 120;
// Static allocation of payload type values for external video codec.
static int GetExternalVideoPayloadType(int index) {
ASSERT(index >= 0 && index < kMaxExternalVideoCodecs);
return kExternalVideoPayloadTypeBase + index;
}
static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
const char* delim = "\r\n";
// TODO(fbarchard): Fix strtok lint warning.
for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
LOG_V(sev) << tok;
}
}
// Severity is an integer because it comes is assumed to be from command line.
static int SeverityToFilter(int severity) {
int filter = webrtc::kTraceNone;
switch (severity) {
case talk_base::LS_VERBOSE:
filter |= webrtc::kTraceAll;
case talk_base::LS_INFO:
filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
case talk_base::LS_WARNING:
filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
case talk_base::LS_ERROR:
filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
}
return filter;
}
static const int kCpuMonitorPeriodMs = 2000; // 2 seconds.
static const bool kNotSending = false;
// Extension header for RTP timestamp offset, see RFC 5450 for details:
// http://tools.ietf.org/html/rfc5450
static const char kRtpTimestampOffsetHeaderExtension[] =
"urn:ietf:params:rtp-hdrext:toffset";
static const int kRtpTimeOffsetExtensionId = 2;
// Extension header for absolute send time, see url for details:
// http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
static const char kRtpAbsoluteSendTimeHeaderExtension[] =
"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time";
static const int kRtpAbsoluteSendTimeExtensionId = 3;
static bool IsNackEnabled(const VideoCodec& codec) {
return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
kParamValueEmpty));
}
// Returns true if Receiver Estimated Max Bitrate is enabled.
static bool IsRembEnabled(const VideoCodec& codec) {
return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamRemb,
kParamValueEmpty));
}
struct FlushBlackFrameData : public talk_base::MessageData {
FlushBlackFrameData(uint32 s, int64 t) : ssrc(s), timestamp(t) {
}
uint32 ssrc;
int64 timestamp;
};
class WebRtcRenderAdapter : public webrtc::ExternalRenderer {
public:
explicit WebRtcRenderAdapter(VideoRenderer* renderer)
: renderer_(renderer), width_(0), height_(0), watermark_enabled_(false) {
}
virtual ~WebRtcRenderAdapter() {
}
void set_watermark_enabled(bool enable) {
talk_base::CritScope cs(&crit_);
watermark_enabled_ = enable;
}
void SetRenderer(VideoRenderer* renderer) {
talk_base::CritScope cs(&crit_);
renderer_ = renderer;
// FrameSizeChange may have already been called when renderer was not set.
// If so we should call SetSize here.
// TODO(ronghuawu): Add unit test for this case. Didn't do it now
// because the WebRtcRenderAdapter is currently hiding in cc file. No
// good way to get access to it from the unit test.
if (width_ > 0 && height_ > 0 && renderer_ != NULL) {
if (!renderer_->SetSize(width_, height_, 0)) {
LOG(LS_ERROR)
<< "WebRtcRenderAdapter SetRenderer failed to SetSize to: "
<< width_ << "x" << height_;
}
}
}
// Implementation of webrtc::ExternalRenderer.
virtual int FrameSizeChange(unsigned int width, unsigned int height,
unsigned int /*number_of_streams*/) {
talk_base::CritScope cs(&crit_);
width_ = width;
height_ = height;
LOG(LS_INFO) << "WebRtcRenderAdapter frame size changed to: "
<< width << "x" << height;
if (renderer_ == NULL) {
LOG(LS_VERBOSE) << "WebRtcRenderAdapter the renderer has not been set. "
<< "SetSize will be called later in SetRenderer.";
return 0;
}
return renderer_->SetSize(width_, height_, 0) ? 0 : -1;
}
virtual int DeliverFrame(unsigned char* buffer, int buffer_size,
uint32_t time_stamp, int64_t render_time) {
talk_base::CritScope cs(&crit_);
frame_rate_tracker_.Update(1);
if (renderer_ == NULL) {
return 0;
}
WebRtcVideoFrame video_frame;
// Convert 90K rtp timestamp to ns timestamp.
int64 rtp_time_stamp_in_ns = (time_stamp / 90) *
talk_base::kNumNanosecsPerMillisec;
// Convert milisecond render time to ns timestamp.
int64 render_time_stamp_in_ns = render_time *
talk_base::kNumNanosecsPerMillisec;
// Send the rtp timestamp to renderer as the VideoFrame timestamp.
// and the render timestamp as the VideoFrame elapsed_time.
video_frame.Attach(buffer, buffer_size, width_, height_,
1, 1, render_time_stamp_in_ns,
rtp_time_stamp_in_ns, 0);
// Sanity check on decoded frame size.
if (buffer_size != static_cast<int>(VideoFrame::SizeOf(width_, height_))) {
LOG(LS_WARNING) << "WebRtcRenderAdapter received a strange frame size: "
<< buffer_size;
}
int ret = renderer_->RenderFrame(&video_frame) ? 0 : -1;
uint8* buffer_temp;
size_t buffer_size_temp;
video_frame.Detach(&buffer_temp, &buffer_size_temp);
return ret;
}
unsigned int width() {
talk_base::CritScope cs(&crit_);
return width_;
}
unsigned int height() {
talk_base::CritScope cs(&crit_);
return height_;
}
int framerate() {
talk_base::CritScope cs(&crit_);
return static_cast<int>(frame_rate_tracker_.units_second());
}
VideoRenderer* renderer() {
talk_base::CritScope cs(&crit_);
return renderer_;
}
private:
talk_base::CriticalSection crit_;
VideoRenderer* renderer_;
unsigned int width_;
unsigned int height_;
talk_base::RateTracker frame_rate_tracker_;
bool watermark_enabled_;
};
class WebRtcDecoderObserver : public webrtc::ViEDecoderObserver {
public:
explicit WebRtcDecoderObserver(int video_channel)
: video_channel_(video_channel),
framerate_(0),
bitrate_(0),
firs_requested_(0) {
}
// virtual functions from VieDecoderObserver.
virtual void IncomingCodecChanged(const int videoChannel,
const webrtc::VideoCodec& videoCodec) {}
virtual void IncomingRate(const int videoChannel,
const unsigned int framerate,
const unsigned int bitrate) {
ASSERT(video_channel_ == videoChannel);
framerate_ = framerate;
bitrate_ = bitrate;
}
virtual void RequestNewKeyFrame(const int videoChannel) {
ASSERT(video_channel_ == videoChannel);
++firs_requested_;
}
int framerate() const { return framerate_; }
int bitrate() const { return bitrate_; }
int firs_requested() const { return firs_requested_; }
private:
int video_channel_;
int framerate_;
int bitrate_;
int firs_requested_;
};
class WebRtcEncoderObserver : public webrtc::ViEEncoderObserver {
public:
explicit WebRtcEncoderObserver(int video_channel)
: video_channel_(video_channel),
framerate_(0),
bitrate_(0) {
}
// virtual functions from VieEncoderObserver.
virtual void OutgoingRate(const int videoChannel,
const unsigned int framerate,
const unsigned int bitrate) {
ASSERT(video_channel_ == videoChannel);
framerate_ = framerate;
bitrate_ = bitrate;
}
int framerate() const { return framerate_; }
int bitrate() const { return bitrate_; }
private:
int video_channel_;
int framerate_;
int bitrate_;
};
class WebRtcLocalStreamInfo {
public:
WebRtcLocalStreamInfo()
: width_(0), height_(0), elapsed_time_(-1), time_stamp_(-1) {}
size_t width() const {
talk_base::CritScope cs(&crit_);
return width_;
}
size_t height() const {
talk_base::CritScope cs(&crit_);
return height_;
}
int64 elapsed_time() const {
talk_base::CritScope cs(&crit_);
return elapsed_time_;
}
int64 time_stamp() const {
talk_base::CritScope cs(&crit_);
return time_stamp_;
}
int framerate() {
talk_base::CritScope cs(&crit_);
return static_cast<int>(rate_tracker_.units_second());
}
void GetLastFrameInfo(
size_t* width, size_t* height, int64* elapsed_time) const {
talk_base::CritScope cs(&crit_);
*width = width_;
*height = height_;
*elapsed_time = elapsed_time_;
}
void UpdateFrame(const VideoFrame* frame) {
talk_base::CritScope cs(&crit_);
width_ = frame->GetWidth();
height_ = frame->GetHeight();
elapsed_time_ = frame->GetElapsedTime();
time_stamp_ = frame->GetTimeStamp();
rate_tracker_.Update(1);
}
private:
mutable talk_base::CriticalSection crit_;
size_t width_;
size_t height_;
int64 elapsed_time_;
int64 time_stamp_;
talk_base::RateTracker rate_tracker_;
DISALLOW_COPY_AND_ASSIGN(WebRtcLocalStreamInfo);
};
// WebRtcVideoChannelRecvInfo is a container class with members such as renderer
// and a decoder observer that is used by receive channels.
// It must exist as long as the receive channel is connected to renderer or a
// decoder observer in this class and methods in the class should only be called
// from the worker thread.
class WebRtcVideoChannelRecvInfo {
public:
typedef std::map<int, webrtc::VideoDecoder*> DecoderMap; // key: payload type
explicit WebRtcVideoChannelRecvInfo(int channel_id)
: channel_id_(channel_id),
render_adapter_(NULL),
decoder_observer_(channel_id) {
}
int channel_id() { return channel_id_; }
void SetRenderer(VideoRenderer* renderer) {
render_adapter_.SetRenderer(renderer);
}
WebRtcRenderAdapter* render_adapter() { return &render_adapter_; }
WebRtcDecoderObserver* decoder_observer() { return &decoder_observer_; }
void RegisterDecoder(int pl_type, webrtc::VideoDecoder* decoder) {
ASSERT(!IsDecoderRegistered(pl_type));
registered_decoders_[pl_type] = decoder;
}
bool IsDecoderRegistered(int pl_type) {
return registered_decoders_.count(pl_type) != 0;
}
const DecoderMap& registered_decoders() {
return registered_decoders_;
}
void ClearRegisteredDecoders() {
registered_decoders_.clear();
}
private:
int channel_id_; // Webrtc video channel number.
// Renderer for this channel.
WebRtcRenderAdapter render_adapter_;
WebRtcDecoderObserver decoder_observer_;
DecoderMap registered_decoders_;
};
class WebRtcVideoChannelSendInfo {
public:
typedef std::map<int, webrtc::VideoEncoder*> EncoderMap; // key: payload type
WebRtcVideoChannelSendInfo(int channel_id, int capture_id,
webrtc::ViEExternalCapture* external_capture,
talk_base::CpuMonitor* cpu_monitor)
: channel_id_(channel_id),
capture_id_(capture_id),
sending_(false),
muted_(false),
video_capturer_(NULL),
encoder_observer_(channel_id),
external_capture_(external_capture),
capturer_updated_(false),
interval_(0),
video_adapter_(new CoordinatedVideoAdapter) {
// TODO(asapersson):
// video_adapter_->SignalCpuAdaptationUnable.connect(
// this, &WebRtcVideoChannelSendInfo::OnCpuAdaptationUnable);
if (cpu_monitor) {
cpu_monitor->SignalUpdate.connect(
video_adapter_.get(), &CoordinatedVideoAdapter::OnCpuLoadUpdated);
}
}
int channel_id() const { return channel_id_; }
int capture_id() const { return capture_id_; }
void set_sending(bool sending) { sending_ = sending; }
bool sending() const { return sending_; }
void set_muted(bool on) {
// TODO(asapersson): add support.
// video_adapter_->SetBlackOutput(on);
muted_ = on;
}
bool muted() {return muted_; }
WebRtcEncoderObserver* encoder_observer() { return &encoder_observer_; }
webrtc::ViEExternalCapture* external_capture() { return external_capture_; }
const VideoFormat& video_format() const {
return video_format_;
}
void set_video_format(const VideoFormat& video_format) {
video_format_ = video_format;
if (video_format_ != cricket::VideoFormat()) {
interval_ = video_format_.interval;
}
video_adapter_->OnOutputFormatRequest(video_format_);
}
void set_interval(int64 interval) {
if (video_format() == cricket::VideoFormat()) {
interval_ = interval;
}
}
int64 interval() { return interval_; }
void InitializeAdapterOutputFormat(const webrtc::VideoCodec& codec) {
VideoFormat format(codec.width, codec.height,
VideoFormat::FpsToInterval(codec.maxFramerate),
FOURCC_I420);
if (video_adapter_->output_format().IsSize0x0()) {
video_adapter_->SetOutputFormat(format);
}
}
bool AdaptFrame(const VideoFrame* in_frame, const VideoFrame** out_frame) {
*out_frame = NULL;
return video_adapter_->AdaptFrame(in_frame, out_frame);
}
int CurrentAdaptReason() const {
return video_adapter_->adapt_reason();
}
StreamParams* stream_params() { return stream_params_.get(); }
void set_stream_params(const StreamParams& sp) {
stream_params_.reset(new StreamParams(sp));
}
void ClearStreamParams() { stream_params_.reset(); }
bool has_ssrc(uint32 local_ssrc) const {
return !stream_params_ ? false :
stream_params_->has_ssrc(local_ssrc);
}
WebRtcLocalStreamInfo* local_stream_info() {
return &local_stream_info_;
}
VideoCapturer* video_capturer() {
return video_capturer_;
}
void set_video_capturer(VideoCapturer* video_capturer) {
if (video_capturer == video_capturer_) {
return;
}
capturer_updated_ = true;
video_capturer_ = video_capturer;
if (video_capturer && !video_capturer->IsScreencast()) {
const VideoFormat* capture_format = video_capturer->GetCaptureFormat();
if (capture_format) {
// TODO(thorcarpenter): This is broken. Video capturer doesn't have
// a capture format until the capturer is started. So, if
// the capturer is started immediately after calling set_video_capturer
// video adapter may not have the input format set, the interval may
// be zero, and all frames may be dropped.
// Consider fixing this by having video_adapter keep a pointer to the
// video capturer.
video_adapter_->SetInputFormat(*capture_format);
}
}
}
void ApplyCpuOptions(const VideoOptions& options) {
bool cpu_adapt, cpu_smoothing;
float low, med, high;
if (options.adapt_input_to_cpu_usage.Get(&cpu_adapt)) {
video_adapter_->set_cpu_adaptation(cpu_adapt);
}
if (options.adapt_cpu_with_smoothing.Get(&cpu_smoothing)) {
video_adapter_->set_cpu_smoothing(cpu_smoothing);
}
if (options.process_adaptation_threshhold.Get(&med)) {
video_adapter_->set_process_threshold(med);
}
if (options.system_low_adaptation_threshhold.Get(&low)) {
video_adapter_->set_low_system_threshold(low);
}
if (options.system_high_adaptation_threshhold.Get(&high)) {
video_adapter_->set_high_system_threshold(high);
}
}
void ProcessFrame(const VideoFrame& original_frame, bool mute,
VideoFrame** processed_frame) {
if (!mute) {
*processed_frame = original_frame.Copy();
} else {
WebRtcVideoFrame* black_frame = new WebRtcVideoFrame();
black_frame->InitToBlack(static_cast<int>(original_frame.GetWidth()),
static_cast<int>(original_frame.GetHeight()),
1, 1,
original_frame.GetElapsedTime(),
original_frame.GetTimeStamp());
*processed_frame = black_frame;
}
local_stream_info_.UpdateFrame(*processed_frame);
}
void RegisterEncoder(int pl_type, webrtc::VideoEncoder* encoder) {
ASSERT(!IsEncoderRegistered(pl_type));
registered_encoders_[pl_type] = encoder;
}
bool IsEncoderRegistered(int pl_type) {
return registered_encoders_.count(pl_type) != 0;
}
const EncoderMap& registered_encoders() {
return registered_encoders_;
}
void ClearRegisteredEncoders() {
registered_encoders_.clear();
}
private:
int channel_id_;
int capture_id_;
bool sending_;
bool muted_;
VideoCapturer* video_capturer_;
WebRtcEncoderObserver encoder_observer_;
webrtc::ViEExternalCapture* external_capture_;
EncoderMap registered_encoders_;
VideoFormat video_format_;
talk_base::scoped_ptr<StreamParams> stream_params_;
WebRtcLocalStreamInfo local_stream_info_;
bool capturer_updated_;
int64 interval_;
talk_base::scoped_ptr<CoordinatedVideoAdapter> video_adapter_;
};
const WebRtcVideoEngine::VideoCodecPref
WebRtcVideoEngine::kVideoCodecPrefs[] = {
{kVp8PayloadName, 100, 0},
{kRedPayloadName, 116, 1},
{kFecPayloadName, 117, 2},
};
// The formats are sorted by the descending order of width. We use the order to
// find the next format for CPU and bandwidth adaptation.
const VideoFormatPod WebRtcVideoEngine::kVideoFormats[] = {
{1280, 800, FPS_TO_INTERVAL(30), FOURCC_ANY},
{1280, 720, FPS_TO_INTERVAL(30), FOURCC_ANY},
{960, 600, FPS_TO_INTERVAL(30), FOURCC_ANY},
{960, 540, FPS_TO_INTERVAL(30), FOURCC_ANY},
{640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY},
{640, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
{640, 480, FPS_TO_INTERVAL(30), FOURCC_ANY},
{480, 300, FPS_TO_INTERVAL(30), FOURCC_ANY},
{480, 270, FPS_TO_INTERVAL(30), FOURCC_ANY},
{480, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
{320, 200, FPS_TO_INTERVAL(30), FOURCC_ANY},
{320, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
{320, 240, FPS_TO_INTERVAL(30), FOURCC_ANY},
{240, 150, FPS_TO_INTERVAL(30), FOURCC_ANY},
{240, 135, FPS_TO_INTERVAL(30), FOURCC_ANY},
{240, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
{160, 100, FPS_TO_INTERVAL(30), FOURCC_ANY},
{160, 90, FPS_TO_INTERVAL(30), FOURCC_ANY},
{160, 120, FPS_TO_INTERVAL(30), FOURCC_ANY},
};
const VideoFormatPod WebRtcVideoEngine::kDefaultVideoFormat =
{640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY};
static void UpdateVideoCodec(const cricket::VideoFormat& video_format,
webrtc::VideoCodec* target_codec) {
if ((target_codec == NULL) || (video_format == cricket::VideoFormat())) {
return;
}
target_codec->width = video_format.width;
target_codec->height = video_format.height;
target_codec->maxFramerate = cricket::VideoFormat::IntervalToFps(
video_format.interval);
}
WebRtcVideoEngine::WebRtcVideoEngine() {
Construct(new ViEWrapper(), new ViETraceWrapper(), NULL,
new talk_base::CpuMonitor(NULL));
}
WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
ViEWrapper* vie_wrapper,
talk_base::CpuMonitor* cpu_monitor) {
Construct(vie_wrapper, new ViETraceWrapper(), voice_engine, cpu_monitor);
}
WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
ViEWrapper* vie_wrapper,
ViETraceWrapper* tracing,
talk_base::CpuMonitor* cpu_monitor) {
Construct(vie_wrapper, tracing, voice_engine, cpu_monitor);
}
void WebRtcVideoEngine::Construct(ViEWrapper* vie_wrapper,
ViETraceWrapper* tracing,
WebRtcVoiceEngine* voice_engine,
talk_base::CpuMonitor* cpu_monitor) {
LOG(LS_INFO) << "WebRtcVideoEngine::WebRtcVideoEngine";
worker_thread_ = NULL;
vie_wrapper_.reset(vie_wrapper);
vie_wrapper_base_initialized_ = false;
tracing_.reset(tracing);
voice_engine_ = voice_engine;
initialized_ = false;
SetTraceFilter(SeverityToFilter(kDefaultLogSeverity));
render_module_.reset(new WebRtcPassthroughRender());
local_renderer_w_ = local_renderer_h_ = 0;
local_renderer_ = NULL;
capture_started_ = false;
decoder_factory_ = NULL;
encoder_factory_ = NULL;
cpu_monitor_.reset(cpu_monitor);
SetTraceOptions("");
if (tracing_->SetTraceCallback(this) != 0) {
LOG_RTCERR1(SetTraceCallback, this);
}
// Set default quality levels for our supported codecs. We override them here
// if we know your cpu performance is low, and they can be updated explicitly
// by calling SetDefaultCodec. For example by a flute preference setting, or
// by the server with a jec in response to our reported system info.
VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
kVideoCodecPrefs[0].name,
kDefaultVideoFormat.width,
kDefaultVideoFormat.height,
VideoFormat::IntervalToFps(kDefaultVideoFormat.interval),
0);
if (!SetDefaultCodec(max_codec)) {
LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
}
// Load our RTP Header extensions.
rtp_header_extensions_.push_back(
RtpHeaderExtension(kRtpTimestampOffsetHeaderExtension,
kRtpTimeOffsetExtensionId));
rtp_header_extensions_.push_back(
RtpHeaderExtension(kRtpAbsoluteSendTimeHeaderExtension,
kRtpAbsoluteSendTimeExtensionId));
}
WebRtcVideoEngine::~WebRtcVideoEngine() {
LOG(LS_INFO) << "WebRtcVideoEngine::~WebRtcVideoEngine";
if (initialized_) {
Terminate();
}
if (encoder_factory_) {
encoder_factory_->RemoveObserver(this);
}
tracing_->SetTraceCallback(NULL);
// Test to see if the media processor was deregistered properly.
ASSERT(SignalMediaFrame.is_empty());
}
bool WebRtcVideoEngine::Init(talk_base::Thread* worker_thread) {
LOG(LS_INFO) << "WebRtcVideoEngine::Init";
worker_thread_ = worker_thread;
ASSERT(worker_thread_ != NULL);
cpu_monitor_->set_thread(worker_thread_);
if (!cpu_monitor_->Start(kCpuMonitorPeriodMs)) {
LOG(LS_ERROR) << "Failed to start CPU monitor.";
cpu_monitor_.reset();
}
bool result = InitVideoEngine();
if (result) {
LOG(LS_INFO) << "VideoEngine Init done";
} else {
LOG(LS_ERROR) << "VideoEngine Init failed, releasing";
Terminate();
}
return result;
}
bool WebRtcVideoEngine::InitVideoEngine() {
LOG(LS_INFO) << "WebRtcVideoEngine::InitVideoEngine";
// Init WebRTC VideoEngine.
if (!vie_wrapper_base_initialized_) {
if (vie_wrapper_->base()->Init() != 0) {
LOG_RTCERR0(Init);
return false;
}
vie_wrapper_base_initialized_ = true;
}
// Log the VoiceEngine version info.
char buffer[1024] = "";
if (vie_wrapper_->base()->GetVersion(buffer) != 0) {
LOG_RTCERR0(GetVersion);
return false;
}
LOG(LS_INFO) << "WebRtc VideoEngine Version:";
LogMultiline(talk_base::LS_INFO, buffer);
// Hook up to VoiceEngine for sync purposes, if supplied.
if (!voice_engine_) {
LOG(LS_WARNING) << "NULL voice engine";
} else if ((vie_wrapper_->base()->SetVoiceEngine(
voice_engine_->voe()->engine())) != 0) {
LOG_RTCERR0(SetVoiceEngine);
return false;
}
// Register our custom render module.
if (vie_wrapper_->render()->RegisterVideoRenderModule(
*render_module_.get()) != 0) {
LOG_RTCERR0(RegisterVideoRenderModule);
return false;
}
initialized_ = true;
return true;
}
void WebRtcVideoEngine::Terminate() {
LOG(LS_INFO) << "WebRtcVideoEngine::Terminate";
initialized_ = false;
if (vie_wrapper_->render()->DeRegisterVideoRenderModule(
*render_module_.get()) != 0) {
LOG_RTCERR0(DeRegisterVideoRenderModule);
}
if (vie_wrapper_->base()->SetVoiceEngine(NULL) != 0) {
LOG_RTCERR0(SetVoiceEngine);
}
cpu_monitor_->Stop();
}
int WebRtcVideoEngine::GetCapabilities() {
return VIDEO_RECV | VIDEO_SEND;
}
bool WebRtcVideoEngine::SetOptions(int options) {
return true;
}
bool WebRtcVideoEngine::SetDefaultEncoderConfig(
const VideoEncoderConfig& config) {
return SetDefaultCodec(config.max_codec);
}
// SetDefaultCodec may be called while the capturer is running. For example, a
// test call is started in a page with QVGA default codec, and then a real call
// is started in another page with VGA default codec. This is the corner case
// and happens only when a session is started. We ignore this case currently.
bool WebRtcVideoEngine::SetDefaultCodec(const VideoCodec& codec) {
if (!RebuildCodecList(codec)) {
LOG(LS_WARNING) << "Failed to RebuildCodecList";
return false;
}
default_codec_format_ = VideoFormat(
video_codecs_[0].width,
video_codecs_[0].height,
VideoFormat::FpsToInterval(video_codecs_[0].framerate),
FOURCC_ANY);
return true;
}
WebRtcVideoMediaChannel* WebRtcVideoEngine::CreateChannel(
VoiceMediaChannel* voice_channel) {
WebRtcVideoMediaChannel* channel =
new WebRtcVideoMediaChannel(this, voice_channel);
if (!channel->Init()) {
delete channel;
channel = NULL;
}
return channel;
}
bool WebRtcVideoEngine::SetLocalRenderer(VideoRenderer* renderer) {
local_renderer_w_ = local_renderer_h_ = 0;
local_renderer_ = renderer;
return true;
}
const std::vector<VideoCodec>& WebRtcVideoEngine::codecs() const {
return video_codecs_;
}
const std::vector<RtpHeaderExtension>&
WebRtcVideoEngine::rtp_header_extensions() const {
return rtp_header_extensions_;
}
void WebRtcVideoEngine::SetLogging(int min_sev, const char* filter) {
// if min_sev == -1, we keep the current log level.
if (min_sev >= 0) {
SetTraceFilter(SeverityToFilter(min_sev));
}
SetTraceOptions(filter);
}
int WebRtcVideoEngine::GetLastEngineError() {
return vie_wrapper_->error();
}
// Checks to see whether we comprehend and could receive a particular codec
bool WebRtcVideoEngine::FindCodec(const VideoCodec& in) {
for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
const VideoFormat fmt(kVideoFormats[i]);
if ((in.width == 0 && in.height == 0) ||
(fmt.width == in.width && fmt.height == in.height)) {
if (encoder_factory_) {
const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
encoder_factory_->codecs();
for (size_t j = 0; j < codecs.size(); ++j) {
VideoCodec codec(GetExternalVideoPayloadType(static_cast<int>(j)),
codecs[j].name, 0, 0, 0, 0);
if (codec.Matches(in))
return true;
}
}
for (size_t j = 0; j < ARRAY_SIZE(kVideoCodecPrefs); ++j) {
VideoCodec codec(kVideoCodecPrefs[j].payload_type,
kVideoCodecPrefs[j].name, 0, 0, 0, 0);
if (codec.Matches(in)) {
return true;
}
}
}
}
return false;
}
// Given the requested codec, returns true if we can send that codec type and
// updates out with the best quality we could send for that codec. If current is
// not empty, we constrain out so that its aspect ratio matches current's.
bool WebRtcVideoEngine::CanSendCodec(const VideoCodec& requested,
const VideoCodec& current,
VideoCodec* out) {
if (!out) {
return false;
}
std::vector<VideoCodec>::const_iterator local_max;
for (local_max = video_codecs_.begin();
local_max < video_codecs_.end();
++local_max) {
// First match codecs by payload type
if (!requested.Matches(*local_max)) {
continue;
}
out->id = requested.id;
out->name = requested.name;
out->preference = requested.preference;
out->params = requested.params;
out->framerate = talk_base::_min(requested.framerate, local_max->framerate);
out->width = 0;
out->height = 0;
out->params = requested.params;
out->feedback_params = requested.feedback_params;
if (0 == requested.width && 0 == requested.height) {
// Special case with resolution 0. The channel should not send frames.
return true;
} else if (0 == requested.width || 0 == requested.height) {
// 0xn and nx0 are invalid resolutions.
return false;
}
// Pick the best quality that is within their and our bounds and has the
// correct aspect ratio.
for (int j = 0; j < ARRAY_SIZE(kVideoFormats); ++j) {
const VideoFormat format(kVideoFormats[j]);
// Skip any format that is larger than the local or remote maximums, or
// smaller than the current best match
if (format.width > requested.width || format.height > requested.height ||
format.width > local_max->width ||
(format.width < out->width && format.height < out->height)) {
continue;
}
bool better = false;
// Check any further constraints on this prospective format
if (!out->width || !out->height) {
// If we don't have any matches yet, this is the best so far.
better = true;
} else if (current.width && current.height) {
// current is set so format must match its ratio exactly.
better =
(format.width * current.height == format.height * current.width);
} else {
// Prefer closer aspect ratios i.e
// format.aspect - requested.aspect < out.aspect - requested.aspect
better = abs(format.width * requested.height * out->height -
requested.width * format.height * out->height) <
abs(out->width * format.height * requested.height -
requested.width * format.height * out->height);
}
if (better) {
out->width = format.width;
out->height = format.height;
}
}
if (out->width > 0) {
return true;
}
}
return false;
}
static void ConvertToCricketVideoCodec(
const webrtc::VideoCodec& in_codec, VideoCodec* out_codec) {
out_codec->id = in_codec.plType;
out_codec->name = in_codec.plName;
out_codec->width = in_codec.width;
out_codec->height = in_codec.height;
out_codec->framerate = in_codec.maxFramerate;
out_codec->SetParam(kCodecParamMinBitrate, in_codec.minBitrate);
out_codec->SetParam(kCodecParamMaxBitrate, in_codec.maxBitrate);
if (in_codec.qpMax) {
out_codec->SetParam(kCodecParamMaxQuantization, in_codec.qpMax);
}
}
bool WebRtcVideoEngine::ConvertFromCricketVideoCodec(
const VideoCodec& in_codec, webrtc::VideoCodec* out_codec) {
bool found = false;
int ncodecs = vie_wrapper_->codec()->NumberOfCodecs();
for (int i = 0; i < ncodecs; ++i) {
if (vie_wrapper_->codec()->GetCodec(i, *out_codec) == 0 &&
_stricmp(in_codec.name.c_str(), out_codec->plName) == 0) {
found = true;
break;
}
}
// If not found, check if this is supported by external encoder factory.
if (!found && encoder_factory_) {
const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
encoder_factory_->codecs();
for (size_t i = 0; i < codecs.size(); ++i) {
if (_stricmp(in_codec.name.c_str(), codecs[i].name.c_str()) == 0) {
out_codec->codecType = codecs[i].type;
out_codec->plType = GetExternalVideoPayloadType(static_cast<int>(i));
talk_base::strcpyn(out_codec->plName, sizeof(out_codec->plName),
codecs[i].name.c_str(), codecs[i].name.length());
found = true;
break;
}
}
}
if (!found) {
LOG(LS_ERROR) << "invalid codec type";
return false;
}
if (in_codec.id != 0)
out_codec->plType = in_codec.id;
if (in_codec.width != 0)
out_codec->width = in_codec.width;
if (in_codec.height != 0)
out_codec->height = in_codec.height;
if (in_codec.framerate != 0)
out_codec->maxFramerate = in_codec.framerate;
// Convert bitrate parameters.
int max_bitrate = kMaxVideoBitrate;
int min_bitrate = kMinVideoBitrate;
int start_bitrate = kStartVideoBitrate;
in_codec.GetParam(kCodecParamMinBitrate, &min_bitrate);
in_codec.GetParam(kCodecParamMaxBitrate, &max_bitrate);
if (max_bitrate < min_bitrate) {
return false;
}
start_bitrate = talk_base::_max(start_bitrate, min_bitrate);
start_bitrate = talk_base::_min(start_bitrate, max_bitrate);
out_codec->minBitrate = min_bitrate;
out_codec->startBitrate = start_bitrate;
out_codec->maxBitrate = max_bitrate;
// Convert general codec parameters.
int max_quantization = 0;
if (in_codec.GetParam(kCodecParamMaxQuantization, &max_quantization)) {
if (max_quantization < 0) {
return false;
}
out_codec->qpMax = max_quantization;
}
return true;
}
void WebRtcVideoEngine::RegisterChannel(WebRtcVideoMediaChannel *channel) {
talk_base::CritScope cs(&channels_crit_);
channels_.push_back(channel);
}
void WebRtcVideoEngine::UnregisterChannel(WebRtcVideoMediaChannel *channel) {
talk_base::CritScope cs(&channels_crit_);
channels_.erase(std::remove(channels_.begin(), channels_.end(), channel),
channels_.end());
}
bool WebRtcVideoEngine::SetVoiceEngine(WebRtcVoiceEngine* voice_engine) {
if (initialized_) {
LOG(LS_WARNING) << "SetVoiceEngine can not be called after Init";
return false;
}
voice_engine_ = voice_engine;
return true;
}
bool WebRtcVideoEngine::EnableTimedRender() {
if (initialized_) {
LOG(LS_WARNING) << "EnableTimedRender can not be called after Init";
return false;
}
render_module_.reset(webrtc::VideoRender::CreateVideoRender(0, NULL,
false, webrtc::kRenderExternal));
return true;
}
void WebRtcVideoEngine::SetTraceFilter(int filter) {
tracing_->SetTraceFilter(filter);
}
// See https://sites.google.com/a/google.com/wavelet/
// Home/Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters
// for all supported command line setttings.
void WebRtcVideoEngine::SetTraceOptions(const std::string& options) {
// Set WebRTC trace file.
std::vector<std::string> opts;
talk_base::tokenize(options, ' ', '"', '"', &opts);
std::vector<std::string>::iterator tracefile =
std::find(opts.begin(), opts.end(), "tracefile");
if (tracefile != opts.end() && ++tracefile != opts.end()) {
// Write WebRTC debug output (at same loglevel) to file
if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
LOG_RTCERR1(SetTraceFile, *tracefile);
}
}
}
static void AddDefaultFeedbackParams(VideoCodec* codec) {
const FeedbackParam kFir(kRtcpFbParamCcm, kRtcpFbCcmParamFir);
codec->AddFeedbackParam(kFir);
const FeedbackParam kNack(kRtcpFbParamNack, kParamValueEmpty);
codec->AddFeedbackParam(kNack);
const FeedbackParam kRemb(kRtcpFbParamRemb, kParamValueEmpty);
codec->AddFeedbackParam(kRemb);
}
// Rebuilds the codec list to be only those that are less intensive
// than the specified codec.
bool WebRtcVideoEngine::RebuildCodecList(const VideoCodec& in_codec) {
if (!FindCodec(in_codec))
return false;
video_codecs_.clear();
bool found = false;
std::set<std::string> external_codec_names;
if (encoder_factory_) {
const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
encoder_factory_->codecs();
for (size_t i = 0; i < codecs.size(); ++i) {
if (!found)
found = (in_codec.name == codecs[i].name);
VideoCodec codec(
GetExternalVideoPayloadType(static_cast<int>(i)),
codecs[i].name,
codecs[i].max_width,
codecs[i].max_height,
codecs[i].max_fps,
static_cast<int>(codecs.size() + ARRAY_SIZE(kVideoCodecPrefs) - i));
AddDefaultFeedbackParams(&codec);
video_codecs_.push_back(codec);
external_codec_names.insert(codecs[i].name);
}
}
for (size_t i = 0; i < ARRAY_SIZE(kVideoCodecPrefs); ++i) {
const VideoCodecPref& pref(kVideoCodecPrefs[i]);
if (!found)
found = (in_codec.name == pref.name);
bool is_external_codec = external_codec_names.find(pref.name) !=
external_codec_names.end();
if (found && !is_external_codec) {
VideoCodec codec(pref.payload_type, pref.name,
in_codec.width, in_codec.height, in_codec.framerate,
static_cast<int>(ARRAY_SIZE(kVideoCodecPrefs) - i));
if (_stricmp(kVp8PayloadName, codec.name.c_str()) == 0) {
AddDefaultFeedbackParams(&codec);
}
video_codecs_.push_back(codec);
}
}
ASSERT(found);
return true;
}
// Ignore spammy trace messages, mostly from the stats API when we haven't
// gotten RTCP info yet from the remote side.
bool WebRtcVideoEngine::ShouldIgnoreTrace(const std::string& trace) {
static const char* const kTracesToIgnore[] = {
NULL
};
for (const char* const* p = kTracesToIgnore; *p; ++p) {
if (trace.find(*p) == 0) {
return true;
}
}
return false;
}
int WebRtcVideoEngine::GetNumOfChannels() {
talk_base::CritScope cs(&channels_crit_);
return static_cast<int>(channels_.size());
}
void WebRtcVideoEngine::Print(webrtc::TraceLevel level, const char* trace,
int length) {
talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
sev = talk_base::LS_ERROR;
else if (level == webrtc::kTraceWarning)
sev = talk_base::LS_WARNING;
else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
sev = talk_base::LS_INFO;
else if (level == webrtc::kTraceTerseInfo)
sev = talk_base::LS_INFO;
// Skip past boilerplate prefix text
if (length < 72) {
std::string msg(trace, length);
LOG(LS_ERROR) << "Malformed webrtc log message: ";
LOG_V(sev) << msg;
} else {
std::string msg(trace + 71, length - 72);
if (!ShouldIgnoreTrace(msg) &&
(!voice_engine_ || !voice_engine_->ShouldIgnoreTrace(msg))) {
LOG_V(sev) << "webrtc: " << msg;
}
}
}
webrtc::VideoDecoder* WebRtcVideoEngine::CreateExternalDecoder(
webrtc::VideoCodecType type) {
if (decoder_factory_ == NULL) {
return NULL;
}
return decoder_factory_->CreateVideoDecoder(type);
}
void WebRtcVideoEngine::DestroyExternalDecoder(webrtc::VideoDecoder* decoder) {
ASSERT(decoder_factory_ != NULL);
if (decoder_factory_ == NULL)
return;
decoder_factory_->DestroyVideoDecoder(decoder);
}
webrtc::VideoEncoder* WebRtcVideoEngine::CreateExternalEncoder(
webrtc::VideoCodecType type) {
if (encoder_factory_ == NULL) {
return NULL;
}
return encoder_factory_->CreateVideoEncoder(type);
}
void WebRtcVideoEngine::DestroyExternalEncoder(webrtc::VideoEncoder* encoder) {
ASSERT(encoder_factory_ != NULL);
if (encoder_factory_ == NULL)
return;
encoder_factory_->DestroyVideoEncoder(encoder);
}
bool WebRtcVideoEngine::IsExternalEncoderCodecType(
webrtc::VideoCodecType type) const {
if (!encoder_factory_)
return false;
const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
encoder_factory_->codecs();
std::vector<WebRtcVideoEncoderFactory::VideoCodec>::const_iterator it;
for (it = codecs.begin(); it != codecs.end(); ++it) {
if (it->type == type)
return true;
}
return false;
}
void WebRtcVideoEngine::SetExternalDecoderFactory(
WebRtcVideoDecoderFactory* decoder_factory) {
decoder_factory_ = decoder_factory;
}
void WebRtcVideoEngine::SetExternalEncoderFactory(
WebRtcVideoEncoderFactory* encoder_factory) {
if (encoder_factory_ == encoder_factory)
return;
if (encoder_factory_) {
encoder_factory_->RemoveObserver(this);
}
encoder_factory_ = encoder_factory;
if (encoder_factory_) {
encoder_factory_->AddObserver(this);
}
// Invoke OnCodecAvailable() here in case the list of codecs is already
// available when the encoder factory is installed. If not the encoder
// factory will invoke the callback later when the codecs become available.
OnCodecsAvailable();
}
void WebRtcVideoEngine::OnCodecsAvailable() {
// Rebuild codec list while reapplying the current default codec format.
VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
kVideoCodecPrefs[0].name,
video_codecs_[0].width,
video_codecs_[0].height,
video_codecs_[0].framerate,
0);
if (!RebuildCodecList(max_codec)) {
LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
}
}
// WebRtcVideoMediaChannel
WebRtcVideoMediaChannel::WebRtcVideoMediaChannel(
WebRtcVideoEngine* engine,
VoiceMediaChannel* channel)
: engine_(engine),
voice_channel_(channel),
vie_channel_(-1),
nack_enabled_(true),
remb_enabled_(false),
render_started_(false),
first_receive_ssrc_(0),
send_red_type_(-1),
send_fec_type_(-1),
send_min_bitrate_(kMinVideoBitrate),
send_start_bitrate_(kStartVideoBitrate),
send_max_bitrate_(kMaxVideoBitrate),
sending_(false),
ratio_w_(0),
ratio_h_(0) {
engine->RegisterChannel(this);
}
bool WebRtcVideoMediaChannel::Init() {
const uint32 ssrc_key = 0;
return CreateChannel(ssrc_key, MD_SENDRECV, &vie_channel_);
}
WebRtcVideoMediaChannel::~WebRtcVideoMediaChannel() {
const bool send = false;
SetSend(send);
const bool render = false;
SetRender(render);
while (!send_channels_.empty()) {
if (!DeleteSendChannel(send_channels_.begin()->first)) {
LOG(LS_ERROR) << "Unable to delete channel with ssrc key "
<< send_channels_.begin()->first;
ASSERT(false);
break;
}
}
// Remove all receive streams and the default channel.
while (!recv_channels_.empty()) {
RemoveRecvStream(recv_channels_.begin()->first);
}
// Unregister the channel from the engine.
engine()->UnregisterChannel(this);
if (worker_thread()) {
worker_thread()->Clear(this);
}
}
bool WebRtcVideoMediaChannel::SetRecvCodecs(
const std::vector<VideoCodec>& codecs) {
receive_codecs_.clear();
for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
iter != codecs.end(); ++iter) {
if (engine()->FindCodec(*iter)) {
webrtc::VideoCodec wcodec;
if (engine()->ConvertFromCricketVideoCodec(*iter, &wcodec)) {
receive_codecs_.push_back(wcodec);
}
} else {
LOG(LS_INFO) << "Unknown codec " << iter->name;
return false;
}
}
for (RecvChannelMap::iterator it = recv_channels_.begin();
it != recv_channels_.end(); ++it) {
if (!SetReceiveCodecs(it->second))
return false;
}
return true;
}
bool WebRtcVideoMediaChannel::SetSendCodecs(
const std::vector<VideoCodec>& codecs) {
// Match with local video codec list.
std::vector<webrtc::VideoCodec> send_codecs;
VideoCodec checked_codec;
VideoCodec current; // defaults to 0x0
if (sending_) {
ConvertToCricketVideoCodec(*send_codec_, ¤t);
}
for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
iter != codecs.end(); ++iter) {
if (_stricmp(iter->name.c_str(), kRedPayloadName) == 0) {
send_red_type_ = iter->id;
} else if (_stricmp(iter->name.c_str(), kFecPayloadName) == 0) {
send_fec_type_ = iter->id;
} else if (engine()->CanSendCodec(*iter, current, &checked_codec)) {
webrtc::VideoCodec wcodec;
if (engine()->ConvertFromCricketVideoCodec(checked_codec, &wcodec)) {
if (send_codecs.empty()) {
nack_enabled_ = IsNackEnabled(checked_codec);
remb_enabled_ = IsRembEnabled(checked_codec);
}
send_codecs.push_back(wcodec);
}
} else {
LOG(LS_WARNING) << "Unknown codec " << iter->name;
}
}
// Fail if we don't have a match.
if (send_codecs.empty()) {
LOG(LS_WARNING) << "No matching codecs available";
return false;
}
// Recv protection.
for (RecvChannelMap::iterator it = recv_channels_.begin();
it != recv_channels_.end(); ++it) {
int channel_id = it->second->channel_id();
if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
nack_enabled_)) {
return false;
}
if (engine_->vie()->rtp()->SetRembStatus(channel_id,
kNotSending,
remb_enabled_) != 0) {
LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
return false;
}
}
// Send settings.
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
int channel_id = iter->second->channel_id();
if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
nack_enabled_)) {
return false;
}
if (engine_->vie()->rtp()->SetRembStatus(channel_id,
remb_enabled_,
remb_enabled_) != 0) {
LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled_, remb_enabled_);
return false;
}
}
// Select the first matched codec.
webrtc::VideoCodec& codec(send_codecs[0]);
if (!SetSendCodec(
codec, codec.minBitrate, codec.startBitrate, codec.maxBitrate)) {
return false;
}
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
send_channel->InitializeAdapterOutputFormat(codec);
}
LogSendCodecChange("SetSendCodecs()");
return true;
}
bool WebRtcVideoMediaChannel::GetSendCodec(VideoCodec* send_codec) {
if (!send_codec_) {
return false;
}
ConvertToCricketVideoCodec(*send_codec_, send_codec);
return true;
}
bool WebRtcVideoMediaChannel::SetSendStreamFormat(uint32 ssrc,
const VideoFormat& format) {
if (!send_codec_) {
LOG(LS_ERROR) << "The send codec has not been set yet.";
return false;
}
WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
if (!send_channel) {
LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
return false;
}
send_channel->set_video_format(format);
return true;
}
bool WebRtcVideoMediaChannel::SetRender(bool render) {
if (render == render_started_) {
return true; // no action required
}
bool ret = true;
for (RecvChannelMap::iterator it = recv_channels_.begin();
it != recv_channels_.end(); ++it) {
if (render) {
if (engine()->vie()->render()->StartRender(
it->second->channel_id()) != 0) {
LOG_RTCERR1(StartRender, it->second->channel_id());
ret = false;
}
} else {
if (engine()->vie()->render()->StopRender(
it->second->channel_id()) != 0) {
LOG_RTCERR1(StopRender, it->second->channel_id());
ret = false;
}
}
}
if (ret) {
render_started_ = render;
}
return ret;
}
bool WebRtcVideoMediaChannel::SetSend(bool send) {
if (!HasReadySendChannels() && send) {
LOG(LS_ERROR) << "No stream added";
return false;
}
if (send == sending()) {
return true; // No action required.
}
if (send) {
// We've been asked to start sending.
// SetSendCodecs must have been called already.
if (!send_codec_) {
return false;
}
// Start send now.
if (!StartSend()) {
return false;
}
} else {
// We've been asked to stop sending.
if (!StopSend()) {
return false;
}
}
sending_ = send;
return true;
}
bool WebRtcVideoMediaChannel::AddSendStream(const StreamParams& sp) {
LOG(LS_INFO) << "AddSendStream " << sp.ToString();
if (!IsOneSsrcStream(sp)) {
LOG(LS_ERROR) << "AddSendStream: bad local stream parameters";
return false;
}
uint32 ssrc_key;
if (!CreateSendChannelKey(sp.first_ssrc(), &ssrc_key)) {
LOG(LS_ERROR) << "Trying to register duplicate ssrc: " << sp.first_ssrc();
return false;
}
// If the default channel is already used for sending create a new channel
// otherwise use the default channel for sending.
int channel_id = -1;
if (send_channels_[0]->stream_params() == NULL) {
channel_id = vie_channel_;
} else {
if (!CreateChannel(ssrc_key, MD_SEND, &channel_id)) {
LOG(LS_ERROR) << "AddSendStream: unable to create channel";
return false;
}
}
WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
// Set the send (local) SSRC.
// If there are multiple send SSRCs, we can only set the first one here, and
// the rest of the SSRC(s) need to be set after SetSendCodec has been called
// (with a codec requires multiple SSRC(s)).
if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
sp.first_ssrc()) != 0) {
LOG_RTCERR2(SetLocalSSRC, channel_id, sp.first_ssrc());
return false;
}
// Set RTCP CName.
if (engine()->vie()->rtp()->SetRTCPCName(channel_id,
sp.cname.c_str()) != 0) {
LOG_RTCERR2(SetRTCPCName, channel_id, sp.cname.c_str());
return false;
}
// At this point the channel's local SSRC has been updated. If the channel is
// the default channel make sure that all the receive channels are updated as
// well. Receive channels have to have the same SSRC as the default channel in
// order to send receiver reports with this SSRC.
if (IsDefaultChannel(channel_id)) {
for (RecvChannelMap::const_iterator it = recv_channels_.begin();
it != recv_channels_.end(); ++it) {
WebRtcVideoChannelRecvInfo* info = it->second;
int channel_id = info->channel_id();
if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
sp.first_ssrc()) != 0) {
LOG_RTCERR1(SetLocalSSRC, it->first);
return false;
}
}
}
send_channel->set_stream_params(sp);
// Reset send codec after stream parameters changed.
if (send_codec_) {
if (!SetSendCodec(send_channel, *send_codec_, send_min_bitrate_,
send_start_bitrate_, send_max_bitrate_)) {
return false;
}
LogSendCodecChange("SetSendStreamFormat()");
}
if (sending_) {
return StartSend(send_channel);
}
return true;
}
bool WebRtcVideoMediaChannel::RemoveSendStream(uint32 ssrc) {
uint32 ssrc_key;
if (!GetSendChannelKey(ssrc, &ssrc_key)) {
LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
<< " which doesn't exist.";
return false;
}
WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
int channel_id = send_channel->channel_id();
if (IsDefaultChannel(channel_id) && (send_channel->stream_params() == NULL)) {
// Default channel will still exist. However, if stream_params() is NULL
// there is no stream to remove.
return false;
}
if (sending_) {
StopSend(send_channel);
}
const WebRtcVideoChannelSendInfo::EncoderMap& encoder_map =
send_channel->registered_encoders();
for (WebRtcVideoChannelSendInfo::EncoderMap::const_iterator it =
encoder_map.begin(); it != encoder_map.end(); ++it) {
if (engine()->vie()->ext_codec()->DeRegisterExternalSendCodec(
channel_id, it->first) != 0) {
LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
}
engine()->DestroyExternalEncoder(it->second);
}
send_channel->ClearRegisteredEncoders();
// The receive channels depend on the default channel, recycle it instead.
if (IsDefaultChannel(channel_id)) {
SetCapturer(GetDefaultChannelSsrc(), NULL);
send_channel->ClearStreamParams();
} else {
return DeleteSendChannel(ssrc_key);
}
return true;
}
bool WebRtcVideoMediaChannel::AddRecvStream(const StreamParams& sp) {
// TODO(zhurunz) Remove this once BWE works properly across different send
// and receive channels.
// Reuse default channel for recv stream in 1:1 call.
if (!InConferenceMode() && first_receive_ssrc_ == 0) {
LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
<< " reuse default channel #"
<< vie_channel_;
first_receive_ssrc_ = sp.first_ssrc();
if (render_started_) {
if (engine()->vie()->render()->StartRender(vie_channel_) !=0) {
LOG_RTCERR1(StartRender, vie_channel_);
}
}
return true;
}
if (recv_channels_.find(sp.first_ssrc()) != recv_channels_.end() ||
first_receive_ssrc_ == sp.first_ssrc()) {
LOG(LS_ERROR) << "Stream already exists";
return false;
}
// TODO(perkj): Implement recv media from multiple SSRCs per stream.
if (sp.ssrcs.size() != 1) {
LOG(LS_ERROR) << "WebRtcVideoMediaChannel supports one receiving SSRC per"
<< " stream";
return false;
}
// Create a new channel for receiving video data.
// In order to get the bandwidth estimation work fine for
// receive only channels, we connect all receiving channels
// to our master send channel.
int channel_id = -1;
if (!CreateChannel(sp.first_ssrc(), MD_RECV, &channel_id)) {
return false;
}
// Get the default renderer.
VideoRenderer* default_renderer = NULL;
if (InConferenceMode()) {
// The recv_channels_ size start out being 1, so if it is two here this
// is the first receive channel created (vie_channel_ is not used for
// receiving in a conference call). This means that the renderer stored
// inside vie_channel_ should be used for the just created channel.
if (recv_channels_.size() == 2 &&
recv_channels_.find(0) != recv_channels_.end()) {
GetRenderer(0, &default_renderer);
}
}
// The first recv stream reuses the default renderer (if a default renderer
// has been set).
if (default_renderer) {
SetRenderer(sp.first_ssrc(), default_renderer);
}
LOG(LS_INFO) << "New video stream " << sp.first_ssrc()
<< " registered to VideoEngine channel #"
<< channel_id << " and connected to channel #" << vie_channel_;
return true;
}
bool WebRtcVideoMediaChannel::RemoveRecvStream(uint32 ssrc) {
RecvChannelMap::iterator it = recv_channels_.find(ssrc);
if (it == recv_channels_.end()) {
// TODO(perkj): Remove this once BWE works properly across different send
// and receive channels.
// The default channel is reused for recv stream in 1:1 call.
if (first_receive_ssrc_ == ssrc) {
first_receive_ssrc_ = 0;
// Need to stop the renderer and remove it since the render window can be
// deleted after this.
if (render_started_) {
if (engine()->vie()->render()->StopRender(vie_channel_) !=0) {
LOG_RTCERR1(StopRender, it->second->channel_id());
}
}
recv_channels_[0]->SetRenderer(NULL);
return true;
}
return false;
}
WebRtcVideoChannelRecvInfo* info = it->second;
int channel_id = info->channel_id();
if (engine()->vie()->render()->RemoveRenderer(channel_id) != 0) {
LOG_RTCERR1(RemoveRenderer, channel_id);
}
if (engine()->vie()->network()->DeregisterSendTransport(channel_id) !=0) {
LOG_RTCERR1(DeRegisterSendTransport, channel_id);
}
if (engine()->vie()->codec()->DeregisterDecoderObserver(
channel_id) != 0) {
LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
}
const WebRtcVideoChannelRecvInfo::DecoderMap& decoder_map =
info->registered_decoders();
for (WebRtcVideoChannelRecvInfo::DecoderMap::const_iterator it =
decoder_map.begin(); it != decoder_map.end(); ++it) {
if (engine()->vie()->ext_codec()->DeRegisterExternalReceiveCodec(
channel_id, it->first) != 0) {
LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
}
engine()->DestroyExternalDecoder(it->second);
}
info->ClearRegisteredDecoders();
LOG(LS_INFO) << "Removing video stream " << ssrc
<< " with VideoEngine channel #"
<< channel_id;
if (engine()->vie()->base()->DeleteChannel(channel_id) == -1) {
LOG_RTCERR1(DeleteChannel, channel_id);
// Leak the WebRtcVideoChannelRecvInfo owned by |it| but remove the channel
// from recv_channels_.
recv_channels_.erase(it);
return false;
}
// Delete the WebRtcVideoChannelRecvInfo pointed to by it->second.
delete info;
recv_channels_.erase(it);
return true;
}
bool WebRtcVideoMediaChannel::StartSend() {
bool success = true;
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
if (!StartSend(send_channel)) {
success = false;
}
}
return success;
}
bool WebRtcVideoMediaChannel::StartSend(
WebRtcVideoChannelSendInfo* send_channel) {
const int channel_id = send_channel->channel_id();
if (engine()->vie()->base()->StartSend(channel_id) != 0) {
LOG_RTCERR1(StartSend, channel_id);
return false;
}
send_channel->set_sending(true);
return true;
}
bool WebRtcVideoMediaChannel::StopSend() {
bool success = true;
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
if (!StopSend(send_channel)) {
success = false;
}
}
return success;
}
bool WebRtcVideoMediaChannel::StopSend(
WebRtcVideoChannelSendInfo* send_channel) {
const int channel_id = send_channel->channel_id();
if (engine()->vie()->base()->StopSend(channel_id) != 0) {
LOG_RTCERR1(StopSend, channel_id);
return false;
}
send_channel->set_sending(false);
return true;
}
bool WebRtcVideoMediaChannel::SendIntraFrame() {
bool success = true;
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end();
++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
const int channel_id = send_channel->channel_id();
if (engine()->vie()->codec()->SendKeyFrame(channel_id) != 0) {
LOG_RTCERR1(SendKeyFrame, channel_id);
success = false;
}
}
return success;
}
bool WebRtcVideoMediaChannel::IsOneSsrcStream(const StreamParams& sp) {
return (sp.ssrcs.size() == 1 && sp.ssrc_groups.size() == 0);
}
bool WebRtcVideoMediaChannel::HasReadySendChannels() {
return !send_channels_.empty() &&
((send_channels_.size() > 1) ||
(send_channels_[0]->stream_params() != NULL));
}
bool WebRtcVideoMediaChannel::GetSendChannelKey(uint32 local_ssrc,
uint32* key) {
*key = 0;
// If a send channel is not ready to send it will not have local_ssrc
// registered to it.
if (!HasReadySendChannels()) {
return false;
}
// The default channel is stored with key 0. The key therefore does not match
// the SSRC associated with the default channel. Check if the SSRC provided
// corresponds to the default channel's SSRC.
if (local_ssrc == GetDefaultChannelSsrc()) {
return true;
}
if (send_channels_.find(local_ssrc) == send_channels_.end()) {
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
if (send_channel->has_ssrc(local_ssrc)) {
*key = iter->first;
return true;
}
}
return false;
}
// The key was found in the above std::map::find call. This means that the
// ssrc is the key.
*key = local_ssrc;
return true;
}
WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannel(
VideoCapturer* video_capturer) {
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
if (send_channel->video_capturer() == video_capturer) {
return send_channel;
}
}
return NULL;
}
WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannel(
uint32 local_ssrc) {
uint32 key;
if (!GetSendChannelKey(local_ssrc, &key)) {
return NULL;
}
return send_channels_[key];
}
bool WebRtcVideoMediaChannel::CreateSendChannelKey(uint32 local_ssrc,
uint32* key) {
if (GetSendChannelKey(local_ssrc, key)) {
// If there is a key corresponding to |local_ssrc|, the SSRC is already in
// use. SSRCs need to be unique in a session and at this point a duplicate
// SSRC has been detected.
return false;
}
if (send_channels_[0]->stream_params() == NULL) {
// key should be 0 here as the default channel should be re-used whenever it
// is not used.
*key = 0;
return true;
}
// SSRC is currently not in use and the default channel is already in use. Use
// the SSRC as key since it is supposed to be unique in a session.
*key = local_ssrc;
return true;
}
uint32 WebRtcVideoMediaChannel::GetDefaultChannelSsrc() {
WebRtcVideoChannelSendInfo* send_channel = send_channels_[0];
const StreamParams* sp = send_channel->stream_params();
if (sp == NULL) {
// This happens if no send stream is currently registered.
return 0;
}
return sp->first_ssrc();
}
bool WebRtcVideoMediaChannel::DeleteSendChannel(uint32 ssrc_key) {
if (send_channels_.find(ssrc_key) == send_channels_.end()) {
return false;
}
WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
VideoCapturer* capturer = send_channel->video_capturer();
if (capturer != NULL) {
capturer->SignalVideoFrame.disconnect(this);
send_channel->set_video_capturer(NULL);
}
int channel_id = send_channel->channel_id();
int capture_id = send_channel->capture_id();
if (engine()->vie()->codec()->DeregisterEncoderObserver(
channel_id) != 0) {
LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
}
// Destroy the external capture interface.
if (engine()->vie()->capture()->DisconnectCaptureDevice(
channel_id) != 0) {
LOG_RTCERR1(DisconnectCaptureDevice, channel_id);
}
if (engine()->vie()->capture()->ReleaseCaptureDevice(
capture_id) != 0) {
LOG_RTCERR1(ReleaseCaptureDevice, capture_id);
}
// The default channel is stored in both |send_channels_| and
// |recv_channels_|. To make sure it is only deleted once from vie let the
// delete call happen when tearing down |recv_channels_| and not here.
if (!IsDefaultChannel(channel_id)) {
engine_->vie()->base()->DeleteChannel(channel_id);
}
delete send_channel;
send_channels_.erase(ssrc_key);
return true;
}
bool WebRtcVideoMediaChannel::RemoveCapturer(uint32 ssrc) {
WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
if (!send_channel) {
return false;
}
VideoCapturer* capturer = send_channel->video_capturer();
if (capturer == NULL) {
return false;
}
capturer->SignalVideoFrame.disconnect(this);
send_channel->set_video_capturer(NULL);
const int64 timestamp = send_channel->local_stream_info()->time_stamp();
if (send_codec_) {
QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
}
return true;
}
bool WebRtcVideoMediaChannel::SetRenderer(uint32 ssrc,
VideoRenderer* renderer) {
if (recv_channels_.find(ssrc) == recv_channels_.end()) {
// TODO(perkj): Remove this once BWE works properly across different send
// and receive channels.
// The default channel is reused for recv stream in 1:1 call.
if (first_receive_ssrc_ == ssrc &&
recv_channels_.find(0) != recv_channels_.end()) {
LOG(LS_INFO) << "SetRenderer " << ssrc
<< " reuse default channel #"
<< vie_channel_;
recv_channels_[0]->SetRenderer(renderer);
return true;
}
return false;
}
recv_channels_[ssrc]->SetRenderer(renderer);
return true;
}
bool WebRtcVideoMediaChannel::GetStats(VideoMediaInfo* info) {
// Get sender statistics and build VideoSenderInfo.
unsigned int total_bitrate_sent = 0;
unsigned int video_bitrate_sent = 0;
unsigned int fec_bitrate_sent = 0;
unsigned int nack_bitrate_sent = 0;
unsigned int estimated_send_bandwidth = 0;
unsigned int target_enc_bitrate = 0;
if (send_codec_) {
for (SendChannelMap::const_iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
const int channel_id = send_channel->channel_id();
VideoSenderInfo sinfo;
const StreamParams* send_params = send_channel->stream_params();
if (send_params == NULL) {
// This should only happen if the default vie channel is not in use.
// This can happen if no streams have ever been added or the stream
// corresponding to the default channel has been removed. Note that
// there may be non-default vie channels in use when this happen so
// asserting send_channels_.size() == 1 is not correct and neither is
// breaking out of the loop.
ASSERT(channel_id == vie_channel_);
continue;
}
unsigned int bytes_sent, packets_sent, bytes_recv, packets_recv;
if (engine_->vie()->rtp()->GetRTPStatistics(channel_id, bytes_sent,
packets_sent, bytes_recv,
packets_recv) != 0) {
LOG_RTCERR1(GetRTPStatistics, vie_channel_);
continue;
}
WebRtcLocalStreamInfo* channel_stream_info =
send_channel->local_stream_info();
sinfo.ssrcs = send_params->ssrcs;
sinfo.codec_name = send_codec_->plName;
sinfo.bytes_sent = bytes_sent;
sinfo.packets_sent = packets_sent;
sinfo.packets_cached = -1;
sinfo.packets_lost = -1;
sinfo.fraction_lost = -1;
sinfo.firs_rcvd = -1;
sinfo.nacks_rcvd = -1;
sinfo.rtt_ms = -1;
sinfo.frame_width = static_cast<int>(channel_stream_info->width());
sinfo.frame_height = static_cast<int>(channel_stream_info->height());
sinfo.framerate_input = channel_stream_info->framerate();
sinfo.framerate_sent = send_channel->encoder_observer()->framerate();
sinfo.nominal_bitrate = send_channel->encoder_observer()->bitrate();
sinfo.preferred_bitrate = send_max_bitrate_;
sinfo.adapt_reason = send_channel->CurrentAdaptReason();
// Get received RTCP statistics for the sender, if available.
// It's not a fatal error if we can't, since RTCP may not have arrived
// yet.
uint16 r_fraction_lost;
unsigned int r_cumulative_lost;
unsigned int r_extended_max;
unsigned int r_jitter;
int r_rtt_ms;
if (engine_->vie()->rtp()->GetSentRTCPStatistics(
channel_id,
r_fraction_lost,
r_cumulative_lost,
r_extended_max,
r_jitter, r_rtt_ms) == 0) {
// Convert Q8 to float.
sinfo.packets_lost = r_cumulative_lost;
sinfo.fraction_lost = static_cast<float>(r_fraction_lost) / (1 << 8);
sinfo.rtt_ms = r_rtt_ms;
}
info->senders.push_back(sinfo);
unsigned int channel_total_bitrate_sent = 0;
unsigned int channel_video_bitrate_sent = 0;
unsigned int channel_fec_bitrate_sent = 0;
unsigned int channel_nack_bitrate_sent = 0;
if (engine_->vie()->rtp()->GetBandwidthUsage(
channel_id, channel_total_bitrate_sent, channel_video_bitrate_sent,
channel_fec_bitrate_sent, channel_nack_bitrate_sent) == 0) {
total_bitrate_sent += channel_total_bitrate_sent;
video_bitrate_sent += channel_video_bitrate_sent;
fec_bitrate_sent += channel_fec_bitrate_sent;
nack_bitrate_sent += channel_nack_bitrate_sent;
} else {
LOG_RTCERR1(GetBandwidthUsage, channel_id);
}
unsigned int estimated_stream_send_bandwidth = 0;
if (engine_->vie()->rtp()->GetEstimatedSendBandwidth(
channel_id, &estimated_stream_send_bandwidth) == 0) {
estimated_send_bandwidth += estimated_stream_send_bandwidth;
} else {
LOG_RTCERR1(GetEstimatedSendBandwidth, channel_id);
}
unsigned int target_enc_stream_bitrate = 0;
if (engine_->vie()->codec()->GetCodecTargetBitrate(
channel_id, &target_enc_stream_bitrate) == 0) {
target_enc_bitrate += target_enc_stream_bitrate;
} else {
LOG_RTCERR1(GetCodecTargetBitrate, channel_id);
}
}
} else {
LOG(LS_WARNING) << "GetStats: sender information not ready.";
}
// Get the SSRC and stats for each receiver, based on our own calculations.
unsigned int estimated_recv_bandwidth = 0;
for (RecvChannelMap::const_iterator it = recv_channels_.begin();
it != recv_channels_.end(); ++it) {
// Don't report receive statistics from the default channel if we have
// specified receive channels.
if (it->first == 0 && recv_channels_.size() > 1)
continue;
WebRtcVideoChannelRecvInfo* channel = it->second;
unsigned int ssrc;
// Get receiver statistics and build VideoReceiverInfo, if we have data.
if (engine_->vie()->rtp()->GetRemoteSSRC(channel->channel_id(), ssrc) != 0)
continue;
unsigned int bytes_sent, packets_sent, bytes_recv, packets_recv;
if (engine_->vie()->rtp()->GetRTPStatistics(
channel->channel_id(), bytes_sent, packets_sent, bytes_recv,
packets_recv) != 0) {
LOG_RTCERR1(GetRTPStatistics, channel->channel_id());
return false;
}
VideoReceiverInfo rinfo;
rinfo.ssrcs.push_back(ssrc);
rinfo.bytes_rcvd = bytes_recv;
rinfo.packets_rcvd = packets_recv;
rinfo.packets_lost = -1;
rinfo.packets_concealed = -1;
rinfo.fraction_lost = -1; // from SentRTCP
rinfo.firs_sent = channel->decoder_observer()->firs_requested();
rinfo.nacks_sent = -1;
rinfo.frame_width = channel->render_adapter()->width();
rinfo.frame_height = channel->render_adapter()->height();
rinfo.framerate_rcvd = channel->decoder_observer()->framerate();
int fps = channel->render_adapter()->framerate();
rinfo.framerate_decoded = fps;
rinfo.framerate_output = fps;
// Get sent RTCP statistics.
uint16 s_fraction_lost;
unsigned int s_cumulative_lost;
unsigned int s_extended_max;
unsigned int s_jitter;
int s_rtt_ms;
if (engine_->vie()->rtp()->GetReceivedRTCPStatistics(channel->channel_id(),
s_fraction_lost, s_cumulative_lost, s_extended_max,
s_jitter, s_rtt_ms) == 0) {
// Convert Q8 to float.
rinfo.packets_lost = s_cumulative_lost;
rinfo.fraction_lost = static_cast<float>(s_fraction_lost) / (1 << 8);
}
info->receivers.push_back(rinfo);
unsigned int estimated_recv_stream_bandwidth = 0;
if (engine_->vie()->rtp()->GetEstimatedReceiveBandwidth(
channel->channel_id(), &estimated_recv_stream_bandwidth) == 0) {
estimated_recv_bandwidth += estimated_recv_stream_bandwidth;
} else {
LOG_RTCERR1(GetEstimatedReceiveBandwidth, channel->channel_id());
}
}
// Build BandwidthEstimationInfo.
// TODO(zhurunz): Add real unittest for this.
BandwidthEstimationInfo bwe;
// Calculations done above per send/receive stream.
bwe.actual_enc_bitrate = video_bitrate_sent;
bwe.transmit_bitrate = total_bitrate_sent;
bwe.retransmit_bitrate = nack_bitrate_sent;
bwe.available_send_bandwidth = estimated_send_bandwidth;
bwe.available_recv_bandwidth = estimated_recv_bandwidth;
bwe.target_enc_bitrate = target_enc_bitrate;
info->bw_estimations.push_back(bwe);
return true;
}
bool WebRtcVideoMediaChannel::SetCapturer(uint32 ssrc,
VideoCapturer* capturer) {
ASSERT(ssrc != 0);
if (!capturer) {
return RemoveCapturer(ssrc);
}
WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
if (!send_channel) {
return false;
}
VideoCapturer* old_capturer = send_channel->video_capturer();
if (old_capturer) {
old_capturer->SignalVideoFrame.disconnect(this);
}
send_channel->set_video_capturer(capturer);
capturer->SignalVideoFrame.connect(
this,
&WebRtcVideoMediaChannel::AdaptAndSendFrame);
if (!capturer->IsScreencast() && ratio_w_ != 0 && ratio_h_ != 0) {
capturer->UpdateAspectRatio(ratio_w_, ratio_h_);
}
const int64 timestamp = send_channel->local_stream_info()->time_stamp();
if (send_codec_) {
QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
}
return true;
}
bool WebRtcVideoMediaChannel::RequestIntraFrame() {
// There is no API exposed to application to request a key frame
// ViE does this internally when there are errors from decoder
return false;
}
void WebRtcVideoMediaChannel::OnPacketReceived(talk_base::Buffer* packet) {
// Pick which channel to send this packet to. If this packet doesn't match
// any multiplexed streams, just send it to the default channel. Otherwise,
// send it to the specific decoder instance for that stream.
uint32 ssrc = 0;
if (!GetRtpSsrc(packet->data(), packet->length(), &ssrc))
return;
int which_channel = GetRecvChannelNum(ssrc);
if (which_channel == -1) {
which_channel = video_channel();
}
engine()->vie()->network()->ReceivedRTPPacket(
which_channel,
packet->data(),
static_cast<int>(packet->length()));
}
void WebRtcVideoMediaChannel::OnRtcpReceived(talk_base::Buffer* packet) {
// Sending channels need all RTCP packets with feedback information.
// Even sender reports can contain attached report blocks.
// Receiving channels need sender reports in order to create
// correct receiver reports.
uint32 ssrc = 0;
if (!GetRtcpSsrc(packet->data(), packet->length(), &ssrc)) {
LOG(LS_WARNING) << "Failed to parse SSRC from received RTCP packet";
return;
}
int type = 0;
if (!GetRtcpType(packet->data(), packet->length(), &type)) {
LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
return;
}
// If it is a sender report, find the channel that is listening.
if (type == kRtcpTypeSR) {
int which_channel = GetRecvChannelNum(ssrc);
if (which_channel != -1 && !IsDefaultChannel(which_channel)) {
engine_->vie()->network()->ReceivedRTCPPacket(
which_channel,
packet->data(),
static_cast<int>(packet->length()));
}
}
// SR may continue RR and any RR entry may correspond to any one of the send
// channels. So all RTCP packets must be forwarded all send channels. ViE
// will filter out RR internally.
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
int channel_id = send_channel->channel_id();
engine_->vie()->network()->ReceivedRTCPPacket(
channel_id,
packet->data(),
static_cast<int>(packet->length()));
}
}
void WebRtcVideoMediaChannel::OnReadyToSend(bool ready) {
SetNetworkTransmissionState(ready);
}
bool WebRtcVideoMediaChannel::MuteStream(uint32 ssrc, bool muted) {
WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
if (!send_channel) {
LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
return false;
}
send_channel->set_muted(muted);
return true;
}
bool WebRtcVideoMediaChannel::SetRecvRtpHeaderExtensions(
const std::vector<RtpHeaderExtension>& extensions) {
if (receive_extensions_ == extensions) {
return true;
}
receive_extensions_ = extensions;
const RtpHeaderExtension* offset_extension =
FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
const RtpHeaderExtension* send_time_extension =
FindHeaderExtension(extensions, kRtpAbsoluteSendTimeHeaderExtension);
// Loop through all receive channels and enable/disable the extensions.
for (RecvChannelMap::iterator channel_it = recv_channels_.begin();
channel_it != recv_channels_.end(); ++channel_it) {
int channel_id = channel_it->second->channel_id();
if (!SetHeaderExtension(
&webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus, channel_id,
offset_extension)) {
return false;
}
if (!SetHeaderExtension(
&webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
send_time_extension)) {
return false;
}
}
return true;
}
bool WebRtcVideoMediaChannel::SetSendRtpHeaderExtensions(
const std::vector<RtpHeaderExtension>& extensions) {
send_extensions_ = extensions;
const RtpHeaderExtension* offset_extension =
FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
const RtpHeaderExtension* send_time_extension =
FindHeaderExtension(extensions, kRtpAbsoluteSendTimeHeaderExtension);
// Loop through all send channels and enable/disable the extensions.
for (SendChannelMap::iterator channel_it = send_channels_.begin();
channel_it != send_channels_.end(); ++channel_it) {
int channel_id = channel_it->second->channel_id();
if (!SetHeaderExtension(
&webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus, channel_id,
offset_extension)) {
return false;
}
if (!SetHeaderExtension(
&webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus, channel_id,
send_time_extension)) {
return false;
}
}
return true;
}
bool WebRtcVideoMediaChannel::SetSendBandwidth(bool autobw, int bps) {
LOG(LS_INFO) << "WebRtcVideoMediaChanne::SetSendBandwidth";
if (InConferenceMode()) {
LOG(LS_INFO) << "Conference mode ignores SetSendBandWidth";
return true;
}
if (!send_codec_) {
LOG(LS_INFO) << "The send codec has not been set up yet";
return true;
}
int min_bitrate;
int start_bitrate;
int max_bitrate;
if (autobw) {
// Use the default values for min bitrate.
min_bitrate = kMinVideoBitrate;
// Use the default value or the bps for the max
max_bitrate = (bps <= 0) ? send_max_bitrate_ : (bps / 1000);
// Maximum start bitrate can be kStartVideoBitrate.
start_bitrate = talk_base::_min(kStartVideoBitrate, max_bitrate);
} else {
// Use the default start or the bps as the target bitrate.
int target_bitrate = (bps <= 0) ? kStartVideoBitrate : (bps / 1000);
min_bitrate = target_bitrate;
start_bitrate = target_bitrate;
max_bitrate = target_bitrate;
}
if (!SetSendCodec(*send_codec_, min_bitrate, start_bitrate, max_bitrate)) {
return false;
}
LogSendCodecChange("SetSendBandwidth()");
return true;
}
bool WebRtcVideoMediaChannel::SetOptions(const VideoOptions &options) {
// Always accept options that are unchanged.
if (options_ == options) {
return true;
}
// Trigger SetSendCodec to set correct noise reduction state if the option has
// changed.
bool denoiser_changed = options.video_noise_reduction.IsSet() &&
(options_.video_noise_reduction != options.video_noise_reduction);
bool leaky_bucket_changed = options.video_leaky_bucket.IsSet() &&
(options_.video_leaky_bucket != options.video_leaky_bucket);
bool buffer_latency_changed = options.buffered_mode_latency.IsSet() &&
(options_.buffered_mode_latency != options.buffered_mode_latency);
bool conference_mode_turned_off = false;
if (options_.conference_mode.IsSet() && options.conference_mode.IsSet() &&
options_.conference_mode.GetWithDefaultIfUnset(false) &&
!options.conference_mode.GetWithDefaultIfUnset(false)) {
conference_mode_turned_off = true;
}
// Save the options, to be interpreted where appropriate.
// Use options_.SetAll() instead of assignment so that unset value in options
// will not overwrite the previous option value.
options_.SetAll(options);
// Set CPU options for all send channels.
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
send_channel->ApplyCpuOptions(options_);
}
// Adjust send codec bitrate if needed.
int conf_max_bitrate = kDefaultConferenceModeMaxVideoBitrate;
int expected_bitrate = send_max_bitrate_;
if (InConferenceMode()) {
expected_bitrate = conf_max_bitrate;
} else if (conference_mode_turned_off) {
// This is a special case for turning conference mode off.
// Max bitrate should go back to the default maximum value instead
// of the current maximum.
expected_bitrate = kMaxVideoBitrate;
}
if (send_codec_ &&
(send_max_bitrate_ != expected_bitrate || denoiser_changed)) {
// On success, SetSendCodec() will reset send_max_bitrate_ to
// expected_bitrate.
if (!SetSendCodec(*send_codec_,
send_min_bitrate_,
send_start_bitrate_,
expected_bitrate)) {
return false;
}
LogSendCodecChange("SetOptions()");
}
if (leaky_bucket_changed) {
bool enable_leaky_bucket =
options_.video_leaky_bucket.GetWithDefaultIfUnset(false);
for (SendChannelMap::iterator it = send_channels_.begin();
it != send_channels_.end(); ++it) {
if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(
it->second->channel_id(), enable_leaky_bucket) != 0) {
LOG_RTCERR2(SetTransmissionSmoothingStatus, it->second->channel_id(),
enable_leaky_bucket);
}
}
}
if (buffer_latency_changed) {
int buffer_latency =
options_.buffered_mode_latency.GetWithDefaultIfUnset(
cricket::kBufferedModeDisabled);
for (SendChannelMap::iterator it = send_channels_.begin();
it != send_channels_.end(); ++it) {
if (engine()->vie()->rtp()->SetSenderBufferingMode(
it->second->channel_id(), buffer_latency) != 0) {
LOG_RTCERR2(SetSenderBufferingMode, it->second->channel_id(),
buffer_latency);
}
}
for (RecvChannelMap::iterator it = recv_channels_.begin();
it != recv_channels_.end(); ++it) {
if (engine()->vie()->rtp()->SetReceiverBufferingMode(
it->second->channel_id(), buffer_latency) != 0) {
LOG_RTCERR2(SetReceiverBufferingMode, it->second->channel_id(),
buffer_latency);
}
}
}
return true;
}
void WebRtcVideoMediaChannel::SetInterface(NetworkInterface* iface) {
MediaChannel::SetInterface(iface);
// Set the RTP recv/send buffer to a bigger size
if (network_interface_) {
network_interface_->SetOption(NetworkInterface::ST_RTP,
talk_base::Socket::OPT_RCVBUF,
kVideoRtpBufferSize);
// TODO(sriniv): Remove or re-enable this.
// As part of b/8030474, send-buffer is size now controlled through
// portallocator flags.
// network_interface_->SetOption(NetworkInterface::ST_RTP,
// talk_base::Socket::OPT_SNDBUF,
// kVideoRtpBufferSize);
}
}
void WebRtcVideoMediaChannel::UpdateAspectRatio(int ratio_w, int ratio_h) {
ASSERT(ratio_w != 0);
ASSERT(ratio_h != 0);
ratio_w_ = ratio_w;
ratio_h_ = ratio_h;
// For now assume that all streams want the same aspect ratio.
// TODO(hellner): remove the need for this assumption.
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
VideoCapturer* capturer = send_channel->video_capturer();
if (capturer) {
capturer->UpdateAspectRatio(ratio_w, ratio_h);
}
}
}
bool WebRtcVideoMediaChannel::GetRenderer(uint32 ssrc,
VideoRenderer** renderer) {
RecvChannelMap::const_iterator it = recv_channels_.find(ssrc);
if (it == recv_channels_.end()) {
if (first_receive_ssrc_ == ssrc &&
recv_channels_.find(0) != recv_channels_.end()) {
LOG(LS_INFO) << " GetRenderer " << ssrc
<< " reuse default renderer #"
<< vie_channel_;
*renderer = recv_channels_[0]->render_adapter()->renderer();
return true;
}
return false;
}
*renderer = it->second->render_adapter()->renderer();
return true;
}
void WebRtcVideoMediaChannel::AdaptAndSendFrame(VideoCapturer* capturer,
const VideoFrame* frame) {
if (capturer->IsScreencast()) {
// Do not adapt frames that are screencast.
SendFrame(capturer, frame);
return;
}
// TODO(thorcarpenter): This is broken. One capturer registered on two ssrc
// will not send any video to the second ssrc send channel. We should remove
// GetSendChannel(capturer) and pass in an ssrc here.
WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(capturer);
if (!send_channel) {
SendFrame(capturer, frame);
return;
}
const VideoFrame* output_frame = NULL;
send_channel->AdaptFrame(frame, &output_frame);
if (output_frame) {
SendFrame(send_channel, output_frame, capturer->IsScreencast());
}
}
// TODO(zhurunz): Add unittests to test this function.
void WebRtcVideoMediaChannel::SendFrame(VideoCapturer* capturer,
const VideoFrame* frame) {
// If there's send channel registers to the |capturer|, then only send the
// frame to that channel and return. Otherwise send the frame to the default
// channel, which currently taking frames from the engine.
WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(capturer);
if (send_channel) {
SendFrame(send_channel, frame, capturer->IsScreencast());
return;
}
// TODO(hellner): Remove below for loop once the captured frame no longer
// come from the engine, i.e. the engine no longer owns a capturer.
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
if (send_channel->video_capturer() == NULL) {
SendFrame(send_channel, frame, capturer->IsScreencast());
}
}
}
bool WebRtcVideoMediaChannel::SendFrame(
WebRtcVideoChannelSendInfo* send_channel,
const VideoFrame* frame,
bool is_screencast) {
if (!send_channel) {
return false;
}
if (!send_codec_) {
// Send codec has not been set. No reason to process the frame any further.
return false;
}
const VideoFormat& video_format = send_channel->video_format();
// If the frame should be dropped.
const bool video_format_set = video_format != cricket::VideoFormat();
if (video_format_set &&
(video_format.width == 0 && video_format.height == 0)) {
return true;
}
// Checks if we need to reset vie send codec.
if (!MaybeResetVieSendCodec(send_channel,
static_cast<int>(frame->GetWidth()),
static_cast<int>(frame->GetHeight()),
is_screencast, NULL)) {
LOG(LS_ERROR) << "MaybeResetVieSendCodec failed with "
<< frame->GetWidth() << "x" << frame->GetHeight();
return false;
}
const VideoFrame* frame_out = frame;
talk_base::scoped_ptr<VideoFrame> processed_frame;
// Disable muting for screencast.
const bool mute = (send_channel->muted() && !is_screencast);
send_channel->ProcessFrame(*frame_out, mute, processed_frame.use());
if (processed_frame) {
frame_out = processed_frame.get();
}
webrtc::ViEVideoFrameI420 frame_i420;
// TODO(ronghuawu): Update the webrtc::ViEVideoFrameI420
// to use const unsigned char*
frame_i420.y_plane = const_cast<unsigned char*>(frame_out->GetYPlane());
frame_i420.u_plane = const_cast<unsigned char*>(frame_out->GetUPlane());
frame_i420.v_plane = const_cast<unsigned char*>(frame_out->GetVPlane());
frame_i420.y_pitch = frame_out->GetYPitch();
frame_i420.u_pitch = frame_out->GetUPitch();
frame_i420.v_pitch = frame_out->GetVPitch();
frame_i420.width = static_cast<unsigned short>(frame_out->GetWidth());
frame_i420.height = static_cast<unsigned short>(frame_out->GetHeight());
int64 timestamp_ntp_ms = 0;
// TODO(justinlin): Reenable after Windows issues with clock drift are fixed.
// Currently reverted to old behavior of discarding capture timestamp.
#if 0
// If the frame timestamp is 0, we will use the deliver time.
const int64 frame_timestamp = frame->GetTimeStamp();
if (frame_timestamp != 0) {
if (abs(time(NULL) - frame_timestamp / talk_base::kNumNanosecsPerSec) >
kTimestampDeltaInSecondsForWarning) {
LOG(LS_WARNING) << "Frame timestamp differs by more than "
<< kTimestampDeltaInSecondsForWarning << " seconds from "
<< "current Unix timestamp.";
}
timestamp_ntp_ms =
talk_base::UnixTimestampNanosecsToNtpMillisecs(frame_timestamp);
}
#endif
return send_channel->external_capture()->IncomingFrameI420(
frame_i420, timestamp_ntp_ms) == 0;
}
bool WebRtcVideoMediaChannel::CreateChannel(uint32 ssrc_key,
MediaDirection direction,
int* channel_id) {
// There are 3 types of channels. Sending only, receiving only and
// sending and receiving. The sending and receiving channel is the
// default channel and there is only one. All other channels that are created
// are associated with the default channel which must exist. The default
// channel id is stored in |vie_channel_|. All channels need to know about
// the default channel to properly handle remb which is why there are
// different ViE create channel calls.
// For this channel the local and remote ssrc key is 0. However, it may
// have a non-zero local and/or remote ssrc depending on if it is currently
// sending and/or receiving.
if ((vie_channel_ == -1 || direction == MD_SENDRECV) &&
(!send_channels_.empty() || !recv_channels_.empty())) {
ASSERT(false);
return false;
}
*channel_id = -1;
if (direction == MD_RECV) {
// All rec channels are associated with the default channel |vie_channel_|
if (engine_->vie()->base()->CreateReceiveChannel(*channel_id,
vie_channel_) != 0) {
LOG_RTCERR2(CreateReceiveChannel, *channel_id, vie_channel_);
return false;
}
} else if (direction == MD_SEND) {
if (engine_->vie()->base()->CreateChannel(*channel_id,
vie_channel_) != 0) {
LOG_RTCERR2(CreateChannel, *channel_id, vie_channel_);
return false;
}
} else {
ASSERT(direction == MD_SENDRECV);
if (engine_->vie()->base()->CreateChannel(*channel_id) != 0) {
LOG_RTCERR1(CreateChannel, *channel_id);
return false;
}
}
if (!ConfigureChannel(*channel_id, direction, ssrc_key)) {
engine_->vie()->base()->DeleteChannel(*channel_id);
*channel_id = -1;
return false;
}
return true;
}
bool WebRtcVideoMediaChannel::ConfigureChannel(int channel_id,
MediaDirection direction,
uint32 ssrc_key) {
const bool receiving = (direction == MD_RECV) || (direction == MD_SENDRECV);
const bool sending = (direction == MD_SEND) || (direction == MD_SENDRECV);
// Register external transport.
if (engine_->vie()->network()->RegisterSendTransport(
channel_id, *this) != 0) {
LOG_RTCERR1(RegisterSendTransport, channel_id);
return false;
}
// Set MTU.
if (engine_->vie()->network()->SetMTU(channel_id, kVideoMtu) != 0) {
LOG_RTCERR2(SetMTU, channel_id, kVideoMtu);
return false;
}
// Turn on RTCP and loss feedback reporting.
if (engine()->vie()->rtp()->SetRTCPStatus(
channel_id, webrtc::kRtcpCompound_RFC4585) != 0) {
LOG_RTCERR2(SetRTCPStatus, channel_id, webrtc::kRtcpCompound_RFC4585);
return false;
}
// Enable pli as key frame request method.
if (engine_->vie()->rtp()->SetKeyFrameRequestMethod(
channel_id, webrtc::kViEKeyFrameRequestPliRtcp) != 0) {
LOG_RTCERR2(SetKeyFrameRequestMethod,
channel_id, webrtc::kViEKeyFrameRequestPliRtcp);
return false;
}
if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
// Logged in SetNackFec. Don't spam the logs.
return false;
}
// Note that receiving must always be configured before sending to ensure
// that send and receive channel is configured correctly (ConfigureReceiving
// assumes no sending).
if (receiving) {
if (!ConfigureReceiving(channel_id, ssrc_key)) {
return false;
}
}
if (sending) {
if (!ConfigureSending(channel_id, ssrc_key)) {
return false;
}
}
return true;
}
bool WebRtcVideoMediaChannel::ConfigureReceiving(int channel_id,
uint32 remote_ssrc_key) {
// Make sure that an SSRC/key isn't registered more than once.
if (recv_channels_.find(remote_ssrc_key) != recv_channels_.end()) {
return false;
}
// Connect the voice channel, if there is one.
// TODO(perkj): The A/V is synched by the receiving channel. So we need to
// know the SSRC of the remote audio channel in order to fetch the correct
// webrtc VoiceEngine channel. For now- only sync the default channel used
// in 1-1 calls.
if (remote_ssrc_key == 0 && voice_channel_) {
WebRtcVoiceMediaChannel* voice_channel =
static_cast<WebRtcVoiceMediaChannel*>(voice_channel_);
if (engine_->vie()->base()->ConnectAudioChannel(
vie_channel_, voice_channel->voe_channel()) != 0) {
LOG_RTCERR2(ConnectAudioChannel, channel_id,
voice_channel->voe_channel());
LOG(LS_WARNING) << "A/V not synchronized";
// Not a fatal error.
}
}
talk_base::scoped_ptr<WebRtcVideoChannelRecvInfo> channel_info(
new WebRtcVideoChannelRecvInfo(channel_id));
// Install a render adapter.
if (engine_->vie()->render()->AddRenderer(channel_id,
webrtc::kVideoI420, channel_info->render_adapter()) != 0) {
LOG_RTCERR3(AddRenderer, channel_id, webrtc::kVideoI420,
channel_info->render_adapter());
return false;
}
if (engine_->vie()->rtp()->SetRembStatus(channel_id,
kNotSending,
remb_enabled_) != 0) {
LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
return false;
}
if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus,
channel_id, receive_extensions_, kRtpTimestampOffsetHeaderExtension)) {
return false;
}
if (!SetHeaderExtension(
&webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
receive_extensions_, kRtpAbsoluteSendTimeHeaderExtension)) {
return false;
}
if (remote_ssrc_key != 0) {
// Use the same SSRC as our default channel
// (so the RTCP reports are correct).
unsigned int send_ssrc = 0;
webrtc::ViERTP_RTCP* rtp = engine()->vie()->rtp();
if (rtp->GetLocalSSRC(vie_channel_, send_ssrc) == -1) {
LOG_RTCERR2(GetLocalSSRC, vie_channel_, send_ssrc);
return false;
}
if (rtp->SetLocalSSRC(channel_id, send_ssrc) == -1) {
LOG_RTCERR2(SetLocalSSRC, channel_id, send_ssrc);
return false;
}
} // Else this is the the default channel and we don't change the SSRC.
// Disable color enhancement since it is a bit too aggressive.
if (engine()->vie()->image()->EnableColorEnhancement(channel_id,
false) != 0) {
LOG_RTCERR1(EnableColorEnhancement, channel_id);
return false;
}
if (!SetReceiveCodecs(channel_info.get())) {
return false;
}
int buffer_latency =
options_.buffered_mode_latency.GetWithDefaultIfUnset(
cricket::kBufferedModeDisabled);
if (buffer_latency != cricket::kBufferedModeDisabled) {
if (engine()->vie()->rtp()->SetReceiverBufferingMode(
channel_id, buffer_latency) != 0) {
LOG_RTCERR2(SetReceiverBufferingMode, channel_id, buffer_latency);
}
}
if (render_started_) {
if (engine_->vie()->render()->StartRender(channel_id) != 0) {
LOG_RTCERR1(StartRender, channel_id);
return false;
}
}
// Register decoder observer for incoming framerate and bitrate.
if (engine()->vie()->codec()->RegisterDecoderObserver(
channel_id, *channel_info->decoder_observer()) != 0) {
LOG_RTCERR1(RegisterDecoderObserver, channel_info->decoder_observer());
return false;
}
recv_channels_[remote_ssrc_key] = channel_info.release();
return true;
}
bool WebRtcVideoMediaChannel::ConfigureSending(int channel_id,
uint32 local_ssrc_key) {
// The ssrc key can be zero or correspond to an SSRC.
// Make sure the default channel isn't configured more than once.
if (local_ssrc_key == 0 && send_channels_.find(0) != send_channels_.end()) {
return false;
}
// Make sure that the SSRC is not already in use.
uint32 dummy_key;
if (GetSendChannelKey(local_ssrc_key, &dummy_key)) {
return false;
}
int vie_capture = 0;
webrtc::ViEExternalCapture* external_capture = NULL;
// Register external capture.
if (engine()->vie()->capture()->AllocateExternalCaptureDevice(
vie_capture, external_capture) != 0) {
LOG_RTCERR0(AllocateExternalCaptureDevice);
return false;
}
// Connect external capture.
if (engine()->vie()->capture()->ConnectCaptureDevice(
vie_capture, channel_id) != 0) {
LOG_RTCERR2(ConnectCaptureDevice, vie_capture, channel_id);
return false;
}
talk_base::scoped_ptr<WebRtcVideoChannelSendInfo> send_channel(
new WebRtcVideoChannelSendInfo(channel_id, vie_capture,
external_capture,
engine()->cpu_monitor()));
send_channel->ApplyCpuOptions(options_);
// Register encoder observer for outgoing framerate and bitrate.
if (engine()->vie()->codec()->RegisterEncoderObserver(
channel_id, *send_channel->encoder_observer()) != 0) {
LOG_RTCERR1(RegisterEncoderObserver, send_channel->encoder_observer());
return false;
}
if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus,
channel_id, send_extensions_, kRtpTimestampOffsetHeaderExtension)) {
return false;
}
if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus,
channel_id, send_extensions_, kRtpAbsoluteSendTimeHeaderExtension)) {
return false;
}
if (options_.video_leaky_bucket.GetWithDefaultIfUnset(false)) {
if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(channel_id,
true) != 0) {
LOG_RTCERR2(SetTransmissionSmoothingStatus, channel_id, true);
return false;
}
}
int buffer_latency =
options_.buffered_mode_latency.GetWithDefaultIfUnset(
cricket::kBufferedModeDisabled);
if (buffer_latency != cricket::kBufferedModeDisabled) {
if (engine()->vie()->rtp()->SetSenderBufferingMode(
channel_id, buffer_latency) != 0) {
LOG_RTCERR2(SetSenderBufferingMode, channel_id, buffer_latency);
}
}
// The remb status direction correspond to the RTP stream (and not the RTCP
// stream). I.e. if send remb is enabled it means it is receiving remote
// rembs and should use them to estimate bandwidth. Receive remb mean that
// remb packets will be generated and that the channel should be included in
// it. If remb is enabled all channels are allowed to contribute to the remb
// but only receive channels will ever end up actually contributing. This
// keeps the logic simple.
if (engine_->vie()->rtp()->SetRembStatus(channel_id,
remb_enabled_,
remb_enabled_) != 0) {
LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled_, remb_enabled_);
return false;
}
if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
// Logged in SetNackFec. Don't spam the logs.
return false;
}
send_channels_[local_ssrc_key] = send_channel.release();
return true;
}
bool WebRtcVideoMediaChannel::SetNackFec(int channel_id,
int red_payload_type,
int fec_payload_type,
bool nack_enabled) {
bool enable = (red_payload_type != -1 && fec_payload_type != -1 &&
!InConferenceMode());
if (enable) {
if (engine_->vie()->rtp()->SetHybridNACKFECStatus(
channel_id, nack_enabled, red_payload_type, fec_payload_type) != 0) {
LOG_RTCERR4(SetHybridNACKFECStatus,
channel_id, nack_enabled, red_payload_type, fec_payload_type);
return false;
}
LOG(LS_INFO) << "Hybrid NACK/FEC enabled for channel " << channel_id;
} else {
if (engine_->vie()->rtp()->SetNACKStatus(channel_id, nack_enabled) != 0) {
LOG_RTCERR1(SetNACKStatus, channel_id);
return false;
}
LOG(LS_INFO) << "NACK enabled for channel " << channel_id;
}
return true;
}
bool WebRtcVideoMediaChannel::SetSendCodec(const webrtc::VideoCodec& codec,
int min_bitrate,
int start_bitrate,
int max_bitrate) {
bool ret_val = true;
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
ret_val = SetSendCodec(send_channel, codec, min_bitrate, start_bitrate,
max_bitrate) && ret_val;
}
if (ret_val) {
// All SetSendCodec calls were successful. Update the global state
// accordingly.
send_codec_.reset(new webrtc::VideoCodec(codec));
send_min_bitrate_ = min_bitrate;
send_start_bitrate_ = start_bitrate;
send_max_bitrate_ = max_bitrate;
} else {
// At least one SetSendCodec call failed, rollback.
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
if (send_codec_) {
SetSendCodec(send_channel, *send_codec_.get(), send_min_bitrate_,
send_start_bitrate_, send_max_bitrate_);
}
}
}
return ret_val;
}
bool WebRtcVideoMediaChannel::SetSendCodec(
WebRtcVideoChannelSendInfo* send_channel,
const webrtc::VideoCodec& codec,
int min_bitrate,
int start_bitrate,
int max_bitrate) {
if (!send_channel) {
return false;
}
const int channel_id = send_channel->channel_id();
// Make a copy of the codec
webrtc::VideoCodec target_codec = codec;
target_codec.startBitrate = start_bitrate;
target_codec.minBitrate = min_bitrate;
target_codec.maxBitrate = max_bitrate;
// Set the default number of temporal layers for VP8.
if (webrtc::kVideoCodecVP8 == codec.codecType) {
target_codec.codecSpecific.VP8.numberOfTemporalLayers =
kDefaultNumberOfTemporalLayers;
// Turn off the VP8 error resilience
target_codec.codecSpecific.VP8.resilience = webrtc::kResilienceOff;
bool enable_denoising =
options_.video_noise_reduction.GetWithDefaultIfUnset(false);
target_codec.codecSpecific.VP8.denoisingOn = enable_denoising;
}
// Register external encoder if codec type is supported by encoder factory.
if (engine()->IsExternalEncoderCodecType(codec.codecType) &&
!send_channel->IsEncoderRegistered(target_codec.plType)) {
webrtc::VideoEncoder* encoder =
engine()->CreateExternalEncoder(codec.codecType);
if (encoder) {
if (engine()->vie()->ext_codec()->RegisterExternalSendCodec(
channel_id, target_codec.plType, encoder, false) == 0) {
send_channel->RegisterEncoder(target_codec.plType, encoder);
} else {
LOG_RTCERR2(RegisterExternalSendCodec, channel_id, target_codec.plName);
engine()->DestroyExternalEncoder(encoder);
}
}
}
// Resolution and framerate may vary for different send channels.
const VideoFormat& video_format = send_channel->video_format();
UpdateVideoCodec(video_format, &target_codec);
if (target_codec.width == 0 && target_codec.height == 0) {
const uint32 ssrc = send_channel->stream_params()->first_ssrc();
LOG(LS_INFO) << "0x0 resolution selected. Captured frames will be dropped "
<< "for ssrc: " << ssrc << ".";
} else {
MaybeChangeStartBitrate(channel_id, &target_codec);
if (0 != engine()->vie()->codec()->SetSendCodec(channel_id, target_codec)) {
LOG_RTCERR2(SetSendCodec, channel_id, target_codec.plName);
return false;
}
}
send_channel->set_interval(
cricket::VideoFormat::FpsToInterval(target_codec.maxFramerate));
return true;
}
static std::string ToString(webrtc::VideoCodecComplexity complexity) {
switch (complexity) {
case webrtc::kComplexityNormal:
return "normal";
case webrtc::kComplexityHigh:
return "high";
case webrtc::kComplexityHigher:
return "higher";
case webrtc::kComplexityMax:
return "max";
default:
return "unknown";
}
}
static std::string ToString(webrtc::VP8ResilienceMode resilience) {
switch (resilience) {
case webrtc::kResilienceOff:
return "off";
case webrtc::kResilientStream:
return "stream";
case webrtc::kResilientFrames:
return "frames";
default:
return "unknown";
}
}
void WebRtcVideoMediaChannel::LogSendCodecChange(const std::string& reason) {
webrtc::VideoCodec vie_codec;
if (engine()->vie()->codec()->GetSendCodec(vie_channel_, vie_codec) != 0) {
LOG_RTCERR1(GetSendCodec, vie_channel_);
return;
}
LOG(LS_INFO) << reason << " : selected video codec "
<< vie_codec.plName << "/"
<< vie_codec.width << "x" << vie_codec.height << "x"
<< static_cast<int>(vie_codec.maxFramerate) << "fps"
<< "@" << vie_codec.maxBitrate << "kbps"
<< " (min=" << vie_codec.minBitrate << "kbps,"
<< " start=" << vie_codec.startBitrate << "kbps)";
LOG(LS_INFO) << "Video max quantization: " << vie_codec.qpMax;
if (webrtc::kVideoCodecVP8 == vie_codec.codecType) {
LOG(LS_INFO) << "VP8 number of temporal layers: "
<< static_cast<int>(
vie_codec.codecSpecific.VP8.numberOfTemporalLayers);
LOG(LS_INFO) << "VP8 options : "
<< "picture loss indication = "
<< vie_codec.codecSpecific.VP8.pictureLossIndicationOn
<< ", feedback mode = "
<< vie_codec.codecSpecific.VP8.feedbackModeOn
<< ", complexity = "
<< ToString(vie_codec.codecSpecific.VP8.complexity)
<< ", resilience = "
<< ToString(vie_codec.codecSpecific.VP8.resilience)
<< ", denoising = "
<< vie_codec.codecSpecific.VP8.denoisingOn
<< ", error concealment = "
<< vie_codec.codecSpecific.VP8.errorConcealmentOn
<< ", automatic resize = "
<< vie_codec.codecSpecific.VP8.automaticResizeOn
<< ", frame dropping = "
<< vie_codec.codecSpecific.VP8.frameDroppingOn
<< ", key frame interval = "
<< vie_codec.codecSpecific.VP8.keyFrameInterval;
}
}
bool WebRtcVideoMediaChannel::SetReceiveCodecs(
WebRtcVideoChannelRecvInfo* info) {
int red_type = -1;
int fec_type = -1;
int channel_id = info->channel_id();
for (std::vector<webrtc::VideoCodec>::iterator it = receive_codecs_.begin();
it != receive_codecs_.end(); ++it) {
if (it->codecType == webrtc::kVideoCodecRED) {
red_type = it->plType;
} else if (it->codecType == webrtc::kVideoCodecULPFEC) {
fec_type = it->plType;
}
if (engine()->vie()->codec()->SetReceiveCodec(channel_id, *it) != 0) {
LOG_RTCERR2(SetReceiveCodec, channel_id, it->plName);
return false;
}
if (!info->IsDecoderRegistered(it->plType) &&
it->codecType != webrtc::kVideoCodecRED &&
it->codecType != webrtc::kVideoCodecULPFEC) {
webrtc::VideoDecoder* decoder =
engine()->CreateExternalDecoder(it->codecType);
if (decoder) {
if (engine()->vie()->ext_codec()->RegisterExternalReceiveCodec(
channel_id, it->plType, decoder) == 0) {
info->RegisterDecoder(it->plType, decoder);
} else {
LOG_RTCERR2(RegisterExternalReceiveCodec, channel_id, it->plName);
engine()->DestroyExternalDecoder(decoder);
}
}
}
}
// Start receiving packets if at least one receive codec has been set.
if (!receive_codecs_.empty()) {
if (engine()->vie()->base()->StartReceive(channel_id) != 0) {
LOG_RTCERR1(StartReceive, channel_id);
return false;
}
}
return true;
}
int WebRtcVideoMediaChannel::GetRecvChannelNum(uint32 ssrc) {
if (ssrc == first_receive_ssrc_) {
return vie_channel_;
}
RecvChannelMap::iterator it = recv_channels_.find(ssrc);
return (it != recv_channels_.end()) ? it->second->channel_id() : -1;
}
// If the new frame size is different from the send codec size we set on vie,
// we need to reset the send codec on vie.
// The new send codec size should not exceed send_codec_ which is controlled
// only by the 'jec' logic.
bool WebRtcVideoMediaChannel::MaybeResetVieSendCodec(
WebRtcVideoChannelSendInfo* send_channel,
int new_width,
int new_height,
bool is_screencast,
bool* reset) {
if (reset) {
*reset = false;
}
ASSERT(send_codec_.get() != NULL);
webrtc::VideoCodec target_codec = *send_codec_.get();
const VideoFormat& video_format = send_channel->video_format();
UpdateVideoCodec(video_format, &target_codec);
// Vie send codec size should not exceed target_codec.
int target_width = new_width;
int target_height = new_height;
if (!is_screencast &&
(new_width > target_codec.width || new_height > target_codec.height)) {
target_width = target_codec.width;
target_height = target_codec.height;
}
// Get current vie codec.
webrtc::VideoCodec vie_codec;
const int channel_id = send_channel->channel_id();
if (engine()->vie()->codec()->GetSendCodec(channel_id, vie_codec) != 0) {
LOG_RTCERR1(GetSendCodec, channel_id);
return false;
}
const int cur_width = vie_codec.width;
const int cur_height = vie_codec.height;
// Only reset send codec when there is a size change. Additionally,
// automatic resize needs to be turned off when screencasting and on when
// not screencasting.
// Don't allow automatic resizing for screencasting.
bool automatic_resize = !is_screencast;
// Turn off VP8 frame dropping when screensharing as the current model does
// not work well at low fps.
bool vp8_frame_dropping = !is_screencast;
// Disable denoising for screencasting.
bool enable_denoising =
options_.video_noise_reduction.GetWithDefaultIfUnset(false);
bool denoising = !is_screencast && enable_denoising;
bool reset_send_codec =
target_width != cur_width || target_height != cur_height ||
automatic_resize != vie_codec.codecSpecific.VP8.automaticResizeOn ||
denoising != vie_codec.codecSpecific.VP8.denoisingOn ||
vp8_frame_dropping != vie_codec.codecSpecific.VP8.frameDroppingOn;
if (reset_send_codec) {
// Set the new codec on vie.
vie_codec.width = target_width;
vie_codec.height = target_height;
vie_codec.maxFramerate = target_codec.maxFramerate;
vie_codec.startBitrate = target_codec.startBitrate;
vie_codec.codecSpecific.VP8.automaticResizeOn = automatic_resize;
vie_codec.codecSpecific.VP8.denoisingOn = denoising;
vie_codec.codecSpecific.VP8.frameDroppingOn = vp8_frame_dropping;
// TODO(mflodman): Remove 'is_screencast' check when screen cast settings
// are treated correctly in WebRTC.
if (!is_screencast)
MaybeChangeStartBitrate(channel_id, &vie_codec);
if (engine()->vie()->codec()->SetSendCodec(channel_id, vie_codec) != 0) {
LOG_RTCERR1(SetSendCodec, channel_id);
return false;
}
if (reset) {
*reset = true;
}
LogSendCodecChange("Capture size changed");
}
return true;
}
void WebRtcVideoMediaChannel::MaybeChangeStartBitrate(
int channel_id, webrtc::VideoCodec* video_codec) {
if (video_codec->startBitrate < video_codec->minBitrate) {
video_codec->startBitrate = video_codec->minBitrate;
} else if (video_codec->startBitrate > video_codec->maxBitrate) {
video_codec->startBitrate = video_codec->maxBitrate;
}
// Use a previous target bitrate, if there is one.
unsigned int current_target_bitrate = 0;
if (engine()->vie()->codec()->GetCodecTargetBitrate(
channel_id, ¤t_target_bitrate) == 0) {
// Convert to kbps.
current_target_bitrate /= 1000;
if (current_target_bitrate > video_codec->maxBitrate) {
current_target_bitrate = video_codec->maxBitrate;
}
if (current_target_bitrate > video_codec->startBitrate) {
video_codec->startBitrate = current_target_bitrate;
}
}
}
void WebRtcVideoMediaChannel::OnMessage(talk_base::Message* msg) {
FlushBlackFrameData* black_frame_data =
static_cast<FlushBlackFrameData*>(msg->pdata);
FlushBlackFrame(black_frame_data->ssrc, black_frame_data->timestamp);
delete black_frame_data;
}
int WebRtcVideoMediaChannel::SendPacket(int channel, const void* data,
int len) {
if (!network_interface_) {
return -1;
}
talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
return network_interface_->SendPacket(&packet) ? len : -1;
}
int WebRtcVideoMediaChannel::SendRTCPPacket(int channel,
const void* data,
int len) {
if (!network_interface_) {
return -1;
}
talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
return network_interface_->SendRtcp(&packet) ? len : -1;
}
void WebRtcVideoMediaChannel::QueueBlackFrame(uint32 ssrc, int64 timestamp,
int framerate) {
if (timestamp) {
FlushBlackFrameData* black_frame_data = new FlushBlackFrameData(
ssrc,
timestamp);
const int delay_ms = static_cast<int>(
2 * cricket::VideoFormat::FpsToInterval(framerate) *
talk_base::kNumMillisecsPerSec / talk_base::kNumNanosecsPerSec);
worker_thread()->PostDelayed(delay_ms, this, 0, black_frame_data);
}
}
void WebRtcVideoMediaChannel::FlushBlackFrame(uint32 ssrc, int64 timestamp) {
WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
if (!send_channel) {
return;
}
talk_base::scoped_ptr<const VideoFrame> black_frame_ptr;
const WebRtcLocalStreamInfo* channel_stream_info =
send_channel->local_stream_info();
int64 last_frame_time_stamp = channel_stream_info->time_stamp();
if (last_frame_time_stamp == timestamp) {
size_t last_frame_width = 0;
size_t last_frame_height = 0;
int64 last_frame_elapsed_time = 0;
channel_stream_info->GetLastFrameInfo(&last_frame_width, &last_frame_height,
&last_frame_elapsed_time);
if (!last_frame_width || !last_frame_height) {
return;
}
WebRtcVideoFrame black_frame;
// Black frame is not screencast.
const bool screencasting = false;
const int64 timestamp_delta = send_channel->interval();
if (!black_frame.InitToBlack(send_codec_->width, send_codec_->height, 1, 1,
last_frame_elapsed_time + timestamp_delta,
last_frame_time_stamp + timestamp_delta) ||
!SendFrame(send_channel, &black_frame, screencasting)) {
LOG(LS_ERROR) << "Failed to send black frame.";
}
}
}
void WebRtcVideoMediaChannel::SetNetworkTransmissionState(
bool is_transmitting) {
LOG(LS_INFO) << "SetNetworkTransmissionState: " << is_transmitting;
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
int channel_id = send_channel->channel_id();
engine_->vie()->network()->SetNetworkTransmissionState(channel_id,
is_transmitting);
}
}
bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
int channel_id, const RtpHeaderExtension* extension) {
bool enable = false;
int id = 0;
if (extension) {
enable = true;
id = extension->id;
}
if ((engine_->vie()->rtp()->*setter)(channel_id, enable, id) != 0) {
LOG_RTCERR4(*setter, extension->uri, channel_id, enable, id);
return false;
}
return true;
}
bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
int channel_id, const std::vector<RtpHeaderExtension>& extensions,
const char header_extension_uri[]) {
const RtpHeaderExtension* extension = FindHeaderExtension(extensions,
header_extension_uri);
return SetHeaderExtension(setter, channel_id, extension);
}
} // namespace cricket
#endif // HAVE_WEBRTC_VIDEO
| [
"jeidee@gmail.com"
] | jeidee@gmail.com |
8e81e2bfad6995aae369f5e14963ff71a22c6eeb | 191bf92db1a9f6df7c30e37a8f0a14d1c220a3bd | /LEETCODEMAYDAY4.cpp | 34059017d376f22d774aaba2e120d28bf9834c1e | [] | no_license | doomsday861/Allofit | 958fa379296e1a4c9a78b25ab0fd7c222bb1f81a | 94d644e52a64ff2949ea731c569478e721fc71bf | refs/heads/master | 2023-01-04T12:35:10.447467 | 2022-12-28T09:30:18 | 2022-12-28T09:30:18 | 250,110,669 | 0 | 1 | null | 2021-01-11T09:20:21 | 2020-03-25T22:59:54 | C++ | UTF-8 | C++ | false | false | 614 | cpp | class Solution {
public:
long long findComplement(int num) {
if(num==2)
return 1;
vector<int> com(33);
int i=0;
while(num)
{
com[i] = num%2;
num /=2;
i++;
}
string s="";
for(int j=i-1;j>=0;j--)
{
// cout<<com[j];
if(com[j])
com[j] = 0;
else
com[j]=1;
//char c = itoa(com[j]);
s +=com[j]+'0';
}
// cout<<endl;
// cout<<s<<endl;
int ans = stoi(s,0,2);
return ans;
}
}; | [
"kartikeyasrivastava861@gmail.com"
] | kartikeyasrivastava861@gmail.com |
441c436eee96eac46c98caa4cef251ff35c4008c | 6e22d7679ebeb092232de6052ced81c7d8ab97a6 | /ISocket/EventSelectClient/Client.h | 4e62f0578b43d71b136ba6ae9c1ef8d30439b47a | [] | no_license | chengguixing/iArt | e3de63161bd91a18522612d6320453431824061d | c2d60e36f2f2a6a04b2188f20e7264cfc5d05dc4 | refs/heads/master | 2021-01-02T09:27:11.010862 | 2014-06-28T12:34:56 | 2014-06-28T12:34:56 | 22,207,953 | 4 | 5 | null | null | null | null | GB18030 | C++ | false | false | 302 | h |
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h"
class CClientApp : public CWinApp
{
public:
CClientApp();
public:
virtual BOOL InitInstance();
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
| [
"izhuxin@gmail.com"
] | izhuxin@gmail.com |
eb3ddbd3866f65121ccf982f636a2f2c39acad5c | f2d47951fb3738bff966f83c090d91846e491994 | /tools/gvsoc/common/models/devices/spiflash/spiflash_impl.cpp | e8d3909e1107b1e5b916d4e46b23fabfc7e40efe | [
"Apache-2.0"
] | permissive | EEESlab/gvsoc-old | cb5f630f6a7bf99664ee57755454a6e6d6b2fc59 | 19917f1789a3f771e1ec42e11c4f5897d1f9fda2 | refs/heads/main | 2023-08-01T05:00:54.614155 | 2021-08-18T13:10:30 | 2021-08-19T16:22:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,996 | cpp | /*
* Copyright (C) 2020 GreenWaves Technologies, SAS, ETH Zurich and
* University of Bologna
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Authors: Germain Haugou, GreenWaves Technologies (germain.haugou@greenwaves-technologies.com)
*/
#include <vp/vp.hpp>
#include <stdio.h>
#include <string.h>
#include <vp/itf/qspim.hpp>
#define CMD_READ_ID 0x9f
#define CMD_RDCR 0x35
#define CMD_WREN 0x06
#define CMD_WRR 0x48
#define CMD_WRAR 0x71
#define CMD_RDSR1 0x05
#define CMD_P4E 0x20
#define CMD_PP 0x02
#define CMD_QIOR 0xEB
#define CMD_QIOR_4B 0xEC
#define CMD_READ 0x0C
#define CMD_READ_SIMPLE 0x03
#define CMD_SND_MODE_BYTE 0x0A
#define CMD_RESET_ENABLE 0x66
#define CMD_RESET 0x99
#define CMD_SECTOR_ERASE 0xD8
#define CMD_READ_SR2V 0x07
class spiflash;
typedef struct {
unsigned char id;
string desc;
void (*handler)(void*,int,int,int,int);
void (*start_handler)(void*);
} command_t;
typedef union {
struct {
int freeze:1;
int quad:1;
int tbparm:1;
int bpnv:1;
int rfu:1;
int tbprot:1;
int lc0:1;
int lc1:1;
};
uint8_t raw;
} reg_cr1_t;
typedef union {
struct {
int ps:1;
int es:1;
int estat:1;
};
uint8_t raw;
} reg_sr2v_t;
#define REGS_AREA_SIZE 1024
#define FLASH_STATE_IDLE 0
#define FLASH_STATE_WRITE_BUFFER_WAIT_SIZE 1
#define FLASH_STATE_WRITE_BUFFER 2
#define FLASH_STATE_WRITE_BUFFER_WAIT_CONFIRM 3
#define FLASH_STATE_CMD_0 4
#define FLASH_STATE_CMD_1 5
#define FLASH_STATE_LOAD_VCR 6
class spiflash;
class spiflash : public vp::component
{
public:
spiflash(js::config *config);
int build();
void start();
static void sector_erase(void *__this, int data_0, int data_1, int data_2, int data_3);
static void sector_erase_done(void *__this, vp::clock_event *event);
static void quad_read(void *__this, int data_0, int data_1, int data_2, int data_3);
static void single_read(void *__this, int data_0, int data_1, int data_2, int data_3);
static void write_any_register(void *__this, int data_0, int data_1, int data_2, int data_3);
static void read_sr2v(void *__this, int data_0, int data_1, int data_2, int data_3);
static void read_sr2v_start(void *__this);
static void page_program(void *__this, int data_0, int data_1, int data_2, int data_3);
protected:
vp::qspim_slave in_itf;
vp::wire_slave<bool> cs_itf;
private:
static void sync(void *__this, int sck, int data_0, int data_1, int data_2, int data_3, int mask);
static void sync_cycle(void *__this, int data_0, int data_1, int data_2, int data_3, int mask);
static void cs_sync(void *__this, bool active);
void handle_data(int data_0, int data_1, int data_2, int data_3);
void start_command();
void enqueue_bits(int data_0, int data_1, int data_2, int data_3);
void send_bits();
vp::trace trace;
int size;
command_t *commands[256];
uint8_t *mem_data;
unsigned int pending_word;
unsigned int pending_addr;
int pending_bits;
unsigned char pending_command_id;
command_t *pending_command;
int pending_post_addr_cmd;
int pending_bytes;
reg_cr1_t cr1;
reg_sr2v_t sr2v;
bool quad;
bool read;
bool waiting_command;
unsigned int current_addr;
vp::clock_event *sector_erase_event;
};
static command_t commands_descs[] = {
{ CMD_READ_ID , "read ID" , NULL , NULL},
{ CMD_RDCR , "read config" , NULL , NULL},
{ CMD_WREN , "write enable" , NULL , NULL},
{ CMD_WRR , "write register" , NULL , NULL},
{ CMD_WRAR , "write any register" , &spiflash::write_any_register , NULL},
{ CMD_RDSR1 , "read status register", NULL , NULL},
{ CMD_P4E , "parameter 4k erase" , NULL , NULL},
{ CMD_PP , "page program" , &spiflash::page_program , NULL},
{ CMD_QIOR , "quad IO read" , NULL , NULL},
{ CMD_QIOR_4B , "quad IO read" , &spiflash::quad_read , NULL},
{ CMD_READ , "IO read" , &spiflash::single_read , NULL},
{ CMD_READ_SIMPLE , "IO read" , &spiflash::single_read , NULL},
{ CMD_RESET_ENABLE , "Reset enable" , NULL , NULL},
{ CMD_RESET , "Reset" , NULL , NULL},
{ CMD_SECTOR_ERASE , "Sector erase" , &spiflash::sector_erase , NULL},
{ CMD_READ_SR2V , "Read SR2V" , &spiflash::read_sr2v , &spiflash::read_sr2v_start}
};
void spiflash::page_program(void *__this, int data_0, int data_1, int data_2, int data_3)
{
spiflash *_this = (spiflash *)__this;
_this->enqueue_bits(data_0, data_1, data_2, data_3);
if (_this->pending_bits == 24)
{
_this->current_addr = _this->pending_word & 0xffffff;
_this->read = false;
_this->trace.msg(vp::trace::LEVEL_INFO, "Received address (address: 0x%x)\n", _this->current_addr);
}
if (_this->pending_bits >= 32)
{
if (_this->pending_bits % 8 == 0)
{
if (_this->current_addr >= _this->size) {
_this->warning.force_warning("Received out-of-bound request (address: 0x%x, memSize: 0x%x)\n", _this->current_addr, _this->size);
return;
}
_this->trace.msg(vp::trace::LEVEL_DEBUG, "Writing byte (address: 0x%x, value: 0x%x)\n", _this->current_addr, (uint8_t)_this->pending_word);
_this->mem_data[_this->current_addr++] = _this->pending_word;
}
}
}
void spiflash::sector_erase_done(void *__this, vp::clock_event *event)
{
spiflash *_this = (spiflash *)__this;
_this->trace.msg(vp::trace::LEVEL_INFO, "Sector erase done\n");
_this->sr2v.raw |= 1<<2;
}
void spiflash::sector_erase(void *__this, int data_0, int data_1, int data_2, int data_3)
{
spiflash *_this = (spiflash *)__this;
if (_this->pending_bits == 0)
_this->sr2v.raw &= ~(1<<2);
_this->enqueue_bits(data_0, data_1, data_2, data_3);
if (_this->pending_bits == 24)
{
_this->current_addr = _this->pending_word;
_this->trace.msg(vp::trace::LEVEL_INFO, "Received address (address: 0x%x)\n", _this->current_addr);
_this->event_enqueue(_this->sector_erase_event, 1000000);
}
}
void spiflash::read_sr2v_start(void *__this)
{
spiflash *_this = (spiflash *)__this;
_this->pending_word = _this->sr2v.raw;
_this->read = true;
_this->send_bits();
}
void spiflash::read_sr2v(void *__this, int data_0, int data_1, int data_2, int data_3)
{
spiflash *_this = (spiflash *)__this;
_this->send_bits();
}
void spiflash::quad_read(void *__this, int data_0, int data_1, int data_2, int data_3)
{
spiflash *_this = (spiflash *)__this;
if (_this->pending_bits == 0)
{
_this->quad = true;
}
_this->enqueue_bits(data_0, data_1, data_2, data_3);
if (_this->pending_bits == 32)
{
_this->current_addr = _this->pending_word;
_this->trace.msg(vp::trace::LEVEL_INFO, "Received address (address: 0x%x)\n", _this->current_addr);
}
if (_this->pending_bits == 40)
{
int mode = _this->pending_word & 0xff;
_this->trace.msg(vp::trace::LEVEL_INFO, "Received mode (value: 0x%x)\n", mode);
_this->read = true;
}
if (_this->pending_bits >= 40)
{
if (_this->pending_bits % 8 == 0)
{
if (_this->current_addr >= _this->size) {
_this->warning.force_warning("Received out-of-bound request (address: 0x%x, memSize: 0x%x)\n", _this->current_addr, _this->size);
return;
}
_this->pending_word = _this->mem_data[_this->current_addr++];
}
}
_this->send_bits();
}
void spiflash::single_read(void *__this, int data_0, int data_1, int data_2, int data_3)
{
spiflash *_this = (spiflash *)__this;
_this->enqueue_bits(data_0, data_1, data_2, data_3);
if (_this->pending_bits == 24)
{
_this->current_addr = _this->pending_word & 0xffffff;
_this->read = true;
_this->trace.msg(vp::trace::LEVEL_INFO, "Received address (address: 0x%x)\n", _this->current_addr);
}
if (_this->pending_bits >= 24)
{
if (_this->pending_bits % 8 == 0)
{
if (_this->current_addr >= _this->size) {
_this->warning.force_warning("Received out-of-bound request (address: 0x%x, memSize: 0x%x)\n", _this->current_addr, _this->size);
return;
}
_this->pending_word = _this->mem_data[_this->current_addr++];
}
}
_this->send_bits();
}
void spiflash::enqueue_bits(int data_0, int data_1, int data_2, int data_3)
{
if (!this->quad)
{
if (!this->read)
{
this->trace.msg(vp::trace::LEVEL_TRACE, "Handling single data (data_0: %d)\n", data_0);
this->pending_word = (this->pending_word << 1) | data_0;
}
this->pending_bits++;
}
else
{
if (!this->read)
{
this->trace.msg(vp::trace::LEVEL_TRACE, "Handling quad data (data_0: %d, data_1: %d, data_2: %d, data_3: %d)\n", data_0, data_1, data_2, data_3);
this->pending_word = (this->pending_word << 4) | (data_3 << 3) | (data_2 << 2) | (data_1 << 1) | (data_0 << 0);
}
this->pending_bits += 4;
}
}
void spiflash::send_bits()
{
if (this->read)
{
if (!this->quad)
{
unsigned int value = (this->pending_word >> 7) & 0x1;
this->pending_word <<= 1;
this->trace.msg(vp::trace::LEVEL_TRACE, "Sending single data (data_0: %d)\n", value);
this->in_itf.sync(0, value, 0, 0, 2);
}
else
{
unsigned int value = (this->pending_word >> 4) & 0xf;
this->pending_word <<= 4;
this->trace.msg(vp::trace::LEVEL_TRACE, "Sending quad data (data_0: %d, data_1: %d, data_2: %d, data_3: %d)\n", (value >> 0) & 1, (value >> 1) & 1, (value >> 2) & 1, (value >> 3) & 1);
this->in_itf.sync((value >> 0) & 1, (value >> 1) & 1, (value >> 2) & 1, (value >> 3) & 1, 0xf);
}
}
}
void spiflash::write_any_register(void *__this, int data_0, int data_1, int data_2, int data_3)
{
spiflash *_this = (spiflash *)__this;
_this->enqueue_bits(data_0, data_1, data_2, data_3);
if (_this->pending_bits == 32)
{
unsigned int addr = _this->pending_word >> 8;
unsigned int value = _this->pending_word & 0xff;
if (addr == 0x800002)
{
_this->trace.msg(vp::trace::LEVEL_INFO, "Writing cr1 register (value: %d)\n", value);
_this->cr1.raw = value;
}
_this->start_command();
}
}
void spiflash::start_command()
{
this->waiting_command = true;
this->pending_bits = 8;
this->quad = false;
this->read = false;
this->pending_word = 0;
}
void spiflash::handle_data(int data_0, int data_1, int data_2, int data_3)
{
if (this->waiting_command)
{
this->trace.msg(vp::trace::LEVEL_TRACE, "Handling single data (data_0: %d)\n", data_0);
this->pending_word = (this->pending_word << 1) | data_0;
this->pending_bits--;
if (this->pending_bits == 0)
{
this->waiting_command = false;
this->pending_command_id = this->pending_word & 0xff;
this->pending_command = this->commands[this->pending_command_id];
if (this->pending_command == NULL)
{
this->warning.force_warning("Received unknown command (cmd: 0x%x)\n", this->pending_command_id);
this->start_command();
return;
}
this->trace.msg(vp::trace::LEVEL_TRACE, "Received command (ID: 0x%x, name: %s)\n", this->pending_command_id, this->pending_command->desc.c_str());
if (this->pending_command->start_handler)
this->pending_command->start_handler(this);
}
}
else
{
if (this->pending_command->handler)
this->pending_command->handler(this, data_0, data_1, data_2, data_3);
}
}
void spiflash::sync(void *__this, int sck, int data_0, int data_1, int data_2, int data_3, int mask)
{
spiflash *_this = (spiflash *)__this;
_this->trace.msg(vp::trace::LEVEL_TRACE, "Received edge (sck: %d, data_0: %d, data_1: %d, data_2: %d, data_3: %d)\n", sck, data_0, data_1, data_2, data_3);
if (sck)
_this->handle_data(data_0, data_1, data_2, data_3);
}
void spiflash::sync_cycle(void *__this, int data_0, int data_1, int data_2, int data_3, int mask)
{
spiflash *_this = (spiflash *)__this;
_this->handle_data(data_0, data_1, data_2, data_3);
}
void spiflash::cs_sync(void *__this, bool active)
{
spiflash *_this = (spiflash *)__this;
_this->trace.msg(vp::trace::LEVEL_TRACE, "Received CS sync (value: %d)\n", active);
if (active == false)
{
_this->start_command();
}
}
int spiflash::build()
{
traces.new_trace("trace", &trace, vp::DEBUG);
this->in_itf.set_sync_meth(&spiflash::sync);
this->in_itf.set_sync_cycle_meth(&spiflash::sync_cycle);
this->new_slave_port("input", &this->in_itf);
this->cs_itf.set_sync_meth(&spiflash::cs_sync);
this->new_slave_port("cs", &this->cs_itf);
memset((void *)this->commands, 0, sizeof(commands));
for (unsigned int i=0; i<sizeof(commands_descs)/sizeof(command_t) ; i++)
{
command_t *command = &commands_descs[i];
this->commands[command->id] = command;
}
this->size = this->get_config_int("size");
this->mem_data = new uint8_t[this->size];
memset(this->mem_data, 0x57, this->size);
this->cr1.raw = 0;
this->quad = false;
this->sector_erase_event = event_new(spiflash::sector_erase_done);
this->sr2v.raw = 0;
return 0;
}
void spiflash::start()
{
this->trace.msg(vp::trace::LEVEL_INFO, "Building spiFlash (size: 0x%x)\n", this->size);
// Preload the memory
js::config *stim_file_conf = this->get_js_config()->get("stim_file");
if (stim_file_conf == NULL)
{
stim_file_conf = this->get_js_config()->get("content/image");
}
if (stim_file_conf == NULL)
{
stim_file_conf = this->get_js_config()->get("preload_file");
}
if (stim_file_conf != NULL)
{
string path = stim_file_conf->get_str();
this->get_trace()->msg(vp::trace::LEVEL_INFO, "Preloading memory with stimuli file (path: %s)\n", path.c_str());
FILE *file = fopen(path.c_str(), "rb");
if (file == NULL)
{
this->get_trace()->fatal("Unable to open stim file: %s, %s\n", path.c_str(), strerror(errno));
return;
}
if (fread(this->mem_data, 1, size, file) == 0)
{
this->get_trace()->fatal("Failed to read stim file: %s, %s\n", path.c_str(), strerror(errno));
return;
}
}
js::config *slm_stim_file_conf = this->get_js_config()->get("slm_stim_file");
if (slm_stim_file_conf != NULL)
{
string path = stim_file_conf->get_str();
this->get_trace()->msg(vp::trace::LEVEL_INFO, "Preloading memory with slm stimuli file (path: %s)\n", path.c_str());
FILE *file = fopen(path.c_str(), "r");
if (file == NULL)
{
this->get_trace()->fatal("Unable to open stim file: %s, %s\n", path.c_str(), strerror(errno));
return;
}
while(1)
{
unsigned int addr, value;
int err;
if ((err = fscanf(file, "@%x %x\n", &addr, &value)) != 2) {
if (err == EOF) break;
this->get_trace()->fatal("Incorrect stimuli file (path: %s)\n", path.c_str());
return;
}
if (addr < size) this->mem_data[addr] = value;
}
}
}
spiflash::spiflash(js::config *config)
: vp::component(config)
{
}
extern "C" vp::component *vp_constructor(js::config *config)
{
return new spiflash(config);
}
| [
"nazareno.bruschi@studio.unibo.it"
] | nazareno.bruschi@studio.unibo.it |
1a49edbbe8caf228a5702b85e7ec2bb97462599c | 2755f1ea5aa4dca8b446b0192f244e246a0d5596 | /cds_and_led/cds_and_led.ino | 84ddd5d8f1551d897427d9eda8d37be83c266add | [] | no_license | forearth/arduino-learning-sample | e958fe4e15f6e099dc9b377b0425528f9b47df2e | 8620bea1c07e530291f9cd485edf04d3c60e062b | refs/heads/master | 2021-06-24T05:15:27.247810 | 2021-01-07T02:32:17 | 2021-01-07T02:32:17 | 48,705,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | ino | #define LIGHT_PIN A0
#define LED 3
void setup()
{
Serial.begin(9600);
pinMode(LED, OUTPUT);
}
void loop()
{
int val = 0;
val = analogRead(LIGHT_PIN);
Serial.println(val);
delay(1000);
if(val>400){
digitalWrite(LED, LOW);
}else{
digitalWrite(LED, HIGH);
}
}
| [
"noreply@github.com"
] | forearth.noreply@github.com |
161d728fc2a9b1ec2679cf5f0fcc7bc98a00a132 | 83f1ae33762440d2246fbe2bf5d965d749074d09 | /PAT/1011.cpp | da47c8826bf09a216f4b6e853eb91367c1d379a1 | [] | no_license | Zendq1998/program_practice | aacef80d3f89ae08c3b740bd0cbf4926806919a8 | 850818ee75abe3511c4951e961e1bf2e821543c8 | refs/heads/master | 2021-07-19T13:23:41.498743 | 2018-12-07T14:18:09 | 2018-12-07T14:18:09 | 105,018,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 697 | cpp | //
// main.cpp
// 1011A+B和C
//
// Created by 1 on 2017/12/5.
// Copyright © 2017年 zendq1998. All rights reserved.
//
#include <iostream>
#include <stdlib.h>
using namespace std;
struct ABC {
long A;
long B;
long C;
bool greater = false;
};
int main() {
int T;
cin>>T;
ABC test[T];
for(int i=0;i<T;i++) {
cin>>test[i].A;
cin>>test[i].B;
cin>>test[i].C;
if(test[i].A + test[i].B > test[i].C) {
test[i].greater = true;
}
}
for(int i=0;i<T;i++) {
cout<<"Case #"<<i+1<<": "<<(test[i].greater?"true":"false");
if(i != T - 1) {
cout<<endl;
}
}
return 0;
}
| [
"a1@1deMacBook-Pro.local"
] | a1@1deMacBook-Pro.local |
769e6d09b38408bbe0894ba3aa1bfa27d2de8141 | 7f64f76f1a45e2c92a9d47ecc96b0a629a12a37f | /bgfx/examples/01-cubes/cubes.cpp | 62ab6b9a4cea3141849b5d15f2d61adc4e991529 | [
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | louis-tru/SummerTraining | 275b4d406a7ff6106b604502c9422ece10d04b63 | 347afd07b94f5f47ed1c84b10be54e6500d64fe1 | refs/heads/master | 2020-04-28T22:06:35.750532 | 2015-08-23T08:23:59 | 2015-08-23T08:23:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,738 | cpp | /*
* Copyright 2011-2015 Branimir Karadzic. All rights reserved.
* License: http://www.opensource.org/licenses/BSD-2-Clause
*/
#include "common.h"
#include "bgfx_utils.h"
struct PosColorVertex
{
float m_x;
float m_y;
float m_z;
uint32_t m_abgr;
static void init()
{
ms_decl
.begin()
.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
.end();
};
static bgfx::VertexDecl ms_decl;
};
bgfx::VertexDecl PosColorVertex::ms_decl;
static PosColorVertex s_cubeVertices[8] =
{
{-1.0f, 1.0f, 1.0f, 0xff000000 },
{ 1.0f, 1.0f, 1.0f, 0xff0000ff },
{-1.0f, -1.0f, 1.0f, 0xff00ff00 },
{ 1.0f, -1.0f, 1.0f, 0xff00ffff },
{-1.0f, 1.0f, -1.0f, 0xffff0000 },
{ 1.0f, 1.0f, -1.0f, 0xffff00ff },
{-1.0f, -1.0f, -1.0f, 0xffffff00 },
{ 1.0f, -1.0f, -1.0f, 0xffffffff },
};
static const uint16_t s_cubeIndices[36] =
{
0, 1, 2, // 0
1, 3, 2,
4, 6, 5, // 2
5, 6, 7,
0, 2, 4, // 4
4, 2, 6,
1, 5, 3, // 6
5, 7, 3,
0, 4, 1, // 8
4, 5, 1,
2, 3, 6, // 10
6, 3, 7,
};
int _main_(int /*_argc*/, char** /*_argv*/)
{
uint32_t width = 1280;
uint32_t height = 720;
uint32_t debug = BGFX_DEBUG_TEXT;
uint32_t reset = BGFX_RESET_VSYNC;
bgfx::init();
bgfx::reset(width, height, reset);
// Enable debug text.
bgfx::setDebug(debug);
// Set view 0 clear state.
bgfx::setViewClear(0
, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
, 0x303030ff
, 1.0f
, 0
);
// Create vertex stream declaration.
PosColorVertex::init();
// Create static vertex buffer.
bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(
// Static data can be passed with bgfx::makeRef
bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
, PosColorVertex::ms_decl
);
// Create static index buffer.
bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(
// Static data can be passed with bgfx::makeRef
bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) )
);
// Create program from shaders.
bgfx::ProgramHandle program = loadProgram("vs_cubes", "fs_cubes");
int64_t timeOffset = bx::getHPCounter();
while (!entry::processEvents(width, height, debug, reset) )
{
int64_t now = bx::getHPCounter();
static int64_t last = now;
const int64_t frameTime = now - last;
last = now;
const double freq = double(bx::getHPFrequency() );
const double toMs = 1000.0/freq;
float time = (float)( (now-timeOffset)/double(bx::getHPFrequency() ) );
// Use debug font to print information about this example.
bgfx::dbgTextClear();
bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/01-cube");
bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Rendering simple static mesh.");
bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);
float at[3] = { 0.0f, 0.0f, 0.0f };
float eye[3] = { 0.0f, 0.0f, -35.0f };
// Set view and projection matrix for view 0.
const bgfx::HMD* hmd = bgfx::getHMD();
if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) )
{
float view[16];
bx::mtxQuatTranslationHMD(view, hmd->eye[0].rotation, eye);
float proj[16];
bx::mtxProj(proj, hmd->eye[0].fov, 0.1f, 100.0f);
bgfx::setViewTransform(0, view, proj);
// Set view 0 default viewport.
//
// Use HMD's width/height since HMD's internal frame buffer size
// might be much larger than window size.
bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height);
}
else
{
float view[16];
bx::mtxLookAt(view, eye, at);
float proj[16];
bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f);
bgfx::setViewTransform(0, view, proj);
// Set view 0 default viewport.
bgfx::setViewRect(0, 0, 0, width, height);
}
// This dummy draw call is here to make sure that view 0 is cleared
// if no other draw calls are submitted to view 0.
bgfx::touch(0);
// Submit 11x11 cubes.
for (uint32_t yy = 0; yy < 11; ++yy)
{
for (uint32_t xx = 0; xx < 11; ++xx)
{
float mtx[16];
bx::mtxRotateXY(mtx, time + xx*0.21f, time + yy*0.37f);
mtx[12] = -15.0f + float(xx)*3.0f;
mtx[13] = -15.0f + float(yy)*3.0f;
mtx[14] = 0.0f;
// Set model matrix for rendering.
bgfx::setTransform(mtx);
// Set vertex and index buffer.
bgfx::setVertexBuffer(vbh);
bgfx::setIndexBuffer(ibh);
// Set render states.
bgfx::setState(BGFX_STATE_DEFAULT);
// Submit primitive for rendering to view 0.
bgfx::submit(0, program);
}
}
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
bgfx::frame();
}
// Cleanup.
bgfx::destroyIndexBuffer(ibh);
bgfx::destroyVertexBuffer(vbh);
bgfx::destroyProgram(program);
// Shutdown bgfx.
bgfx::shutdown();
return 0;
}
| [
"myspace@inbox.ru"
] | myspace@inbox.ru |
ce6f872f3536b9ff6c0bf2b90e1a6ed51de2db6f | 8fc945ec94827f0c64a914873fcefc0eb68944cf | /Google Code Jam 2015/pancakes.cpp | c51b12f0baf8d315766d225b43cfc8c51c5f7cd4 | [] | no_license | mateuscgc/maratonas | 641a5396d64ce14d32fe0ae2c8f9b30d7545f69d | 3ed87f1e0307beb7f89934598440869d88c74495 | refs/heads/master | 2020-04-24T06:21:19.963512 | 2017-09-28T20:03:53 | 2017-09-28T20:03:53 | 26,088,854 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,301 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int nT;
cin >> nT;
for (int i = 1; i <= nT; i++) {
int nD;
cin >> nD;
int nP[1001] = {0};
int num;
int max = -1;
for(int j = 0; j < nD; j++) {
cin >> num;
nP[num]++;
if (num > max)
max = num;
}
int min = max+1;
for (int j = 1; j <= max; j++) {
int nM = 0;
int cp[max+1];
copy(nP, nP+max+1, cp);
for (int k = max; k > j; k--) {
if (cp[k] > 0) {
int ini = 2, end = k;
while(ini < end) {
int center = (ini+end)/2;
if ((k+center-1)/center <= j)
end = center;
else
ini = center+1;
}
cp[(k+ini-1)/ini] = k % ini * cp[k];
cp[k/ini] = (ini - k % ini) * cp[k];
nM += (ini-1)*cp[k];
}
}
nM += j;
if (nM < min)
min = nM;
}
cout << "Case #" << i << ": " << min << endl;
}
return 0;
}
| [
"mateus_cgc@hotmail.com"
] | mateus_cgc@hotmail.com |
bc96401ad73c65c6873149399e3967110f665612 | f30b2d33c209eca780e645a0237738ccd5ef2b78 | /Compiler/_backup/MidCode/Quaternary.cpp | 22db457290290f3c1b86fc9a26e7b4f41421efeb | [] | no_license | DreamChaserMXF/Compiler | cfa55e7476858c2be6a856a9efceb56a7fad6ef2 | 3aae54ccfcfe3d68002f82056281a38f1581720b | refs/heads/master | 2021-07-09T01:04:02.192725 | 2016-04-24T14:26:03 | 2016-04-24T14:26:03 | 48,437,970 | 2 | 1 | null | 2016-04-24T14:26:03 | 2015-12-22T14:58:55 | Assembly | GB18030 | C++ | false | false | 3,296 | cpp | #include "Quaternary.h"
#include <assert.h>
const char* Quaternary::OPCodeString[] = {
"NIL_OP",
"NEG", "ADD", "SUB", "MUL", "DIV", "ASG", "AASG", "STORE",
"JMP", "JE", "JNE", "JG", "JNG", "JL", "JNL",
"FUNC_CALL", "PROC_CALL", "READ", "WRITE", "SETP", "RET",
"BEGIN", "END", "LABEL"
};
Quaternary::Quaternary() throw()
: op_(NIL_OP), type1_(NIL_OPERAND), src1_(0), type2_(NIL_OPERAND), src2_(0), type3_(NIL_OPERAND), dst_(0)
{}
Quaternary::Quaternary(OPCode op, OperandType type1, int src1, OperandType type2, int src2, OperandType type3, int dst) throw()
: op_(op), type1_(type1), src1_(src1), type2_(type2), src2_(src2), type3_(type3), dst_(dst)
{}
void Quaternary::UpdateTempVarSpace(std::vector<Quaternary> &quaternarytable) throw()
{
std::vector<Quaternary>::iterator iter = quaternarytable.begin();
assert(Quaternary::BEGIN == iter->op_);
FindTempVar(iter, quaternarytable.end());
}
// 从一个函数的BEGIN语句的迭代器开始,寻找这个函数用到的临时变量的个数,并更新到BEGIN语句中
// 最后返回指向该函数结束后的下一条语句的迭代器
// end_iter表明即使没有找到END语句,也应该停止的迭代器位置
// 如果这个函数有嵌套的函数,则对嵌套函数的BEGIN语句进行同样的更新
std::vector<Quaternary>::iterator Quaternary::FindTempVar(const std::vector<Quaternary>::iterator &begin_iter,
const std::vector<Quaternary>::const_iterator &end_iter) throw()
{
std::vector<Quaternary>::iterator next_iter = begin_iter + 1;
while(Quaternary::BEGIN == next_iter->op_)
{
next_iter = FindTempVar(next_iter, end_iter);
}
// 现在next_iter指向该函数的BEGIN语句之后的第一条属于该函数的语句
int max_temp_index = -1;
do
{
// 在已有的逻辑下,如果申请了新的临时变量,则一定会用在dst操作数上
// 所以前两个if语句并不是必要的
//if(Quaternary::TEMPORARY_OPERAND == next_iter->type1_
// && next_iter->src1_ > max_temp_index)
//{
// max_temp_index = next_iter->src1_;
//}
//if(Quaternary::TEMPORARY_OPERAND == next_iter->type2_
// && next_iter->src2_ > max_temp_index)
//{
// max_temp_index = next_iter->src2_;
//}
if(Quaternary::TEMPORARY_OPERAND == next_iter->type3_
&& next_iter->dst_ > max_temp_index)
{
max_temp_index = next_iter->dst_;
}
++next_iter;
} while(Quaternary::END != next_iter->op_);
// 更新BEGIN语句
begin_iter->src2_ = max_temp_index + 1;
// 返回指向函数结束后的下一个语句的迭代器
return ++next_iter;
}
// 通过过程/函数在四元式表中的BEGIN语句的迭代器,找到其过程/函数体的第一条语句的迭代器
// 这里要求过程/函数的BEGIN和END一定要配对
std::vector<Quaternary>::const_iterator Quaternary::GetFunctionBody(std::vector<Quaternary>::const_iterator begin_iter) throw()
{
++begin_iter;
if(Quaternary::BEGIN != begin_iter->op_)
{
return begin_iter;
}
int func_num = 1; // 已经读到了一个begin
while(func_num > 0)
{
++begin_iter;
if(Quaternary::BEGIN == begin_iter->op_)
{
++func_num;
}
else if(Quaternary::END == begin_iter->op_)
{
--func_num;
}
}
return ++begin_iter;
} | [
"sad_sugar@163.com"
] | sad_sugar@163.com |
241838aa5359d482cbfe107b0a818ec7d1fc8223 | d72ed530c9e14bcdaef73ca1bd6ce13dbd7085c3 | /solved/0-3/copsandrobbers.cpp | 9797cfa0c5a9fd3700796b078b6cac3daeb0eda4 | [] | no_license | Tetragonal/kattis-solutions | 2fa8e8bda68a6656b34415d1a8c3a5e233642bec | fa3c6be58ac5a79fbbb27320f76ad27680a02c54 | refs/heads/master | 2020-05-17T16:53:49.556352 | 2019-12-31T01:27:15 | 2019-12-31T01:27:15 | 183,831,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,160 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5+1, INF = 1e9;
struct edge {int v, c, f;};
int n, src, snk, h[N], ptr[N];
vector<edge> edgs;
vector<int> g[N];
void add_edge (int u, int v, int c) {
int k = edgs.size();
edgs.push_back({v, c, 0});
edgs.push_back({u, 0, 0});
g[u].push_back(k);
g[v].push_back(k+1);
}
bool bfs() {
memset(h, 0, sizeof h);
queue<int> q;
h[src] = 1;
q.push(src);
while(!q.empty()) {
int u = q.front(); q.pop();
for(int i : g[u]) {
int v = edgs[i].v;
if (!h[v] and edgs[i].f < edgs[i].c)
q.push(v), h[v] = h[u] + 1;
}
}
return h[snk];
}
int dfs (int u, int flow) {
if (!flow or u == snk) return flow;
for (int &i = ptr[u]; i < g[u].size(); ++i) {
edge &dir = edgs[g[u][i]], &rev = edgs[g[u][i]^1];
int v = dir.v;
if (h[v] != h[u] + 1) continue;
int inc = min(flow, dir.c - dir.f);
inc = dfs(v, inc);
if (inc) {
dir.f += inc, rev.f -= inc;
return inc;
}
}
return 0;
}
int dinic() {
int flow = 0;
while (bfs()) {
memset(ptr, 0, sizeof ptr);
while (int inc = dfs(src, INF)) flow += inc;
}
return flow;
}
int main() {
int n, m, c;
cin >> n >> m >> c;
vector<string> input;
for(int i = 0; i < m; i++) {
string in;
cin >> in;
input.push_back(in);
}
map<char, int> costs;
costs['.'] = INF;
costs['B'] = INF;
for(int i = 0; i < c; i++) {
int cost;
cin >> cost;
costs['a'+i] = cost;
}
snk = N-5;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
int vidx = i*n + j;
int idx = vidx + n*m;
if(input[i][j] == 'B') {
src = vidx;
}
add_edge(vidx, idx, costs[input[i][j]]);
if((i==0) || (j==0) || (i==m-1) || (j==n-1)) {
add_edge(idx, snk, INF);
} else {
if(j!=n-1) add_edge(idx, vidx+1, INF);
if(j!=0) add_edge(idx, vidx-1, INF);
if(i!=m-1) add_edge(idx, vidx+n, INF);
if(i!=0) add_edge(idx, vidx-n, INF);
}
}
}
int maxflow = dinic();
if(maxflow >= INF) {
cout << -1 << endl;
} else {
cout << maxflow << endl;
}
}
| [
"kevin_m_tang@yahoo.com"
] | kevin_m_tang@yahoo.com |
c6336fcad3e09ef36e41c95008c5bddc7408e1f2 | 8633303b5f570856d8e2d47621574a82b093f60e | /binaryTree/binaryTreeOperations.cpp | 1f519140e0c9bdb2d67b9825cfd68020982ad094 | [] | no_license | ApostaC/dsalgo | 9c01ce317cf189894c8adde3edbbd26edf91d905 | c747d1699f62a815dae0e8dbd0af798a2cb6f780 | refs/heads/master | 2021-08-28T18:41:15.710665 | 2017-12-13T00:30:55 | 2017-12-13T00:30:55 | 109,796,414 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,060 | cpp | #include <iostream>
#define MAXN 110
using namespace std;
struct Node
{
int l,r,p;
Node(int ll=-1,int rr=-1,int pp=-1):l(ll),r(rr),p(pp){}
void setl(int ll){l=ll;}
void setr(int rr){r=rr;}
void setp(int pp){p=pp;}
void exchange(){int t=l;l=r;r=t;}
};
int t,n,m;
Node nodes[MAXN];
void swap(int a,int b)
{
int pa=nodes[a].p,pb=nodes[b].p;
Node & npa=nodes[pa], & npb=nodes[pb];
if(pa==pb)
{
npa.exchange();
return;
}
if(npa.l==a) npa.setl(b);
else npa.setr(b);
if(npb.l==b) npb.setl(a);
else npb.setr(b);
}
int query(int x)
{
Node & nd=nodes[x];
if(nd.l==-1) return x;
return query(nd.l);
}
void operate()
{
int a,x,y;
cin>>a;
if(a==1)
{
cin>>x>>y;swap(x,y);
}
if(a==2)
{
cin>>x;cout<<query(x)<<endl;
}
}
int main1()
{
for(int i=0;i<MAXN;i++) nodes[i]=Node();
cin>>n>>m;
int x,y,z;
for(int i=0;i<n;i++)
{
cin>>x>>y>>z;
Node & nd=nodes[x];
nd.setl(y);nd.setr(z);
nodes[y].setp(x);nodes[z].setp(x);
}
for(int i=0;i<m;i++) operate();
return 0;
}
int main()
{
cin>>t;
for(int i=0;i<t;i++)
main1();
return 0;
}
| [
"Aposta@pku.edu.cn"
] | Aposta@pku.edu.cn |
804696e2787be299fd68405b2d556688fa36d3fb | 75fc8b7594b2075ff487dc05afdd5ad0a7408c1f | /ElDorito/Source/Blam/Tags/Sounds/Sound/Sound.cpp | b3101f5943bda975158508ea6c0e7af01a4c0843 | [] | no_license | NoShotz/ElDorito | 929e7b4e033914d15257419c8978d0f5fa598177 | a6d2d681e999d2d21f3f8bb3bd272f0771f2d1fe | refs/heads/master | 2021-07-25T18:26:25.982270 | 2020-05-08T17:17:17 | 2020-05-08T17:17:17 | 167,758,023 | 26 | 35 | null | 2019-11-24T05:36:13 | 2019-01-27T01:35:22 | C++ | UTF-8 | C++ | false | false | 1,497 | cpp | #include "Sound.hpp"
namespace Blam::Tags::Sounds
{
Scale* GetScale(Sound* sound) {
return &sound->Scale;
}
PlaybackParameters* GetPlaybackParameters(Sound* sound) {
return &sound->PlaybackParameters;
}
SampleRate GetSampleRate(Sound* sound) {
return sound->SampleRate;
}
PitchRange* GetPitchRange(Sound* sound, int32_t index) {
return &sound->PitchRanges[index];
}
int32_t GetPitchRangeCount(Sound* sound) {
return sound->PitchRanges.Count;
}
Permutation* GetPermutation(PitchRange* pitchRange, int32_t index) {
return &pitchRange->Permutations[index];
}
PermutationChunk* GetPermutationChunk(Permutation* permutation, int32_t index) {
return &permutation->PermutationChunks[index];
}
int32_t GetPermutationCount(PitchRange* pitchRange) {
return pitchRange->Permutations.Count;
}
int32_t GetPermutationChunkCount(Permutation* permutation) {
return permutation->PermutationChunks.Count;
}
int8_t GetCompression(Sound* sound) {
return sound->PlatformCodec.Compression;
}
int8_t GetLoadMode(Sound* sound) {
return sound->PlatformCodec.LoadMode;
}
int8_t GetEncoding(Sound* sound) {
return sound->PlatformCodec.Encoding;
}
int32_t GetNextPermutationChunkIndex(Permutation* permutation, int32_t currentIndex) {
if (permutation && currentIndex < permutation->PermutationChunks.Count - 1)
return currentIndex + 1;
else
return -1;
}
Math::Bounds<int16_t>* GetBendBounds(PitchRange* pitchRange) {
return &pitchRange->Bend;
}
} | [
"noshotz@protonmail.com"
] | noshotz@protonmail.com |
83184b7823427dbb500e80b21cc18d05f9552848 | 406b4b18f5c58c689d2324f49db972377fe8feb6 | /ANE/Include/Memory/IMemoryPool.h | cd118b1a3cd79d2f003a329221fb47c1e0b00b8c | [] | no_license | Mobiwoom/ane | e17167de36699c451ed92eab7bf733e7d41fe847 | ec20667c556a99351024f3ae9c8880e944c5bfbd | refs/heads/master | 2021-01-17T13:09:57.966141 | 2010-03-23T16:30:17 | 2010-03-23T16:30:17 | 33,132,357 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 258 | h | #pragma once
namespace Ane
{
class IMemoryPool
{
public:
IMemoryPool(){}
virtual ~IMemoryPool(){}
virtual void* Alloc() = 0;
virtual void* Alloc(unsigned int Size) = 0;
virtual void Free(void* pMemory) = 0;
};
} | [
"inthejm@5abed23c-1faa-11df-9e62-c93c6248c2ac"
] | inthejm@5abed23c-1faa-11df-9e62-c93c6248c2ac |
b8f59d73669f20e8cc100512e4068fc9582c1a55 | 706dd85e8712b80bc03a316ca8cdc8a7e3980d05 | /ClientDemoDlg.cpp | 35634c65250336ba6df56b734257a81493ff9fbb | [] | no_license | yyj8209/HikSyn | fa6be917d125501b1f80eb5959841dbc91cb5561 | a2e819e5d3bbae9850b6abc6c27945f42b98f777 | refs/heads/master | 2021-06-21T14:31:36.296142 | 2020-04-09T23:07:50 | 2020-04-09T23:07:50 | 254,497,210 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 839,396 | cpp | /**********************************************************
FileName: ClientDemoDlg.cpp
Description: main dialog, show the main function
Date: 2008/12/12
Note: the global Macro definition and structure is in "GeneralDef.h", global variable and function is in "ClientDemo.cpp"
Modification History:
<version> <time> <desc>
<1.0 > <2008/12/12> <created>
***********************************************************/
#include "stdafx.h"
#include "string.h"
#include "ClientDemo.h"
#include ".\clientdemodlg.h"
#include "DlgAddDevice.h"
#include "DlgRemoteCfg.h"
#include "math.h"
#include "winver.h"
#include "DlgDeviceInfo.h"
#include "DlgUpgrade.h"
#include "DlgFormatHD.h"
#include "DlgRemoteKey.h"
#include "DlgDeviceState.h"
#include "DlgLocalLogConfig.h"
#include "DlgJPEGSnatchConfig.h"
#include "DlgBroadCast.h"
#include "DlgHardDiskCfg.h"
#include "DlgRemoteIPAccess.h"
#include "DlgVoiceTalk.h"
#include "DlgFortify.h"
#include "DlgLogSearch.h"
#include "DlgDeviceState.h"
#include "DlgCheckTime.h"
#include "DlgSerialTrans.h"
#include "DlgConfigFlash.h"
#include "DlgDoTest.h"
#include "process.h"
#include "DlgAtmFrameFormatV30.h"
#include "DlgInquestDvr.h"
#include "DlgPtzScope.h"
#include "DlgSensorAddPreview.h"
#include "DlgHolidayCfg.h"
#include "DlgNetServiceCfg.h"
#include "DlgCertInfo.h"
#include "DlgT1test.h"
#include "DlgDevServer.h"
#include "DlgProductionTest.h"
#include "DlgVedioAudioInCfg.h"
#include "DlgProductCfg.h"
#include "DlgVCADetionCfg.h"
#include "DlgTalkMREx.h"
#include "DlgVideoIntercomCall.h"
#include "DlgDebug.h"
#include "DlgUploadCalibrationFile.h"
#include "DlgIperf.h"
#include "MimeProtocolParsing.h"
#include "cjson/cJSON.h"
#include "DlgAlarmInfo.h"
#include "DlgAsynloginWait.h"
using namespace std;
#pragma comment (lib, "version.lib")
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static unsigned long ulAlarmPic = 0;
extern HINSTANCE g_hDSSDK;
extern HINSTANCE g_hDllInst;
extern HINSTANCE g_hDllCalib;
extern HINSTANCE g_hDllCurlLib;
CRITICAL_SECTION g_cs;
extern void InfoMinorTypeMap(const NET_DVR_LOG_V50 &stLogInfo, CString &szTemp);
extern void EventMinorTypeMap(const NET_DVR_LOG_V50 &stLogInfo, CString &szTemp);
extern void OperationMinorTypeMap(const NET_DVR_LOG_V50 &stLogInfo, CString &szTemp);
extern void ExceptionMinorTypeMap(const NET_DVR_LOG_V50 &stLogInfo, CString &szTemp);
extern void AlarmMinorTypeMap(const NET_DVR_LOG_V50 &stLogInfo, CString &szTemp);
extern void ParaTypeMap(const NET_DVR_LOG_V50 &stLogInfo, CString &szTemp);
int g_iCount = 0;
BOOL g_bJSONBroken = FALSE;//JSON Broken flag
extern int m_giAsynLoginReturn;
extern bool m_gbAsynLogin;
extern int m_giErrNo;
extern const char* m_gpErrMsg;
extern CDlgAsynloginWait* m_gpDlgAsynloginWait;
//Alarm host
typedef struct tagLOCAL_ALARM_INFO
{
int iDeviceIndex;
LONG lCommand;
char sDeviceIP[128]; /* IP地址 */
DWORD dwBufLen;
WORD wLinkPort;
tagLOCAL_ALARM_INFO()
{
iDeviceIndex = -1;
lCommand = -1;
memset(&sDeviceIP, 0, 128);
dwBufLen = 0;
wLinkPort = 0;
}
}LOCAL_ALARM_INFO, *LPLOCAL_ALARM_INFO;
string UTF82ASCII(const char* cont)
{
if (NULL == cont)
{
return string("");
}
int num = MultiByteToWideChar(CP_UTF8, NULL, cont, -1, NULL, NULL);
wchar_t* buffw = new wchar_t[(unsigned int)num];
MultiByteToWideChar(CP_UTF8, NULL, cont, -1, buffw, num);
int len = WideCharToMultiByte(CP_ACP, 0, buffw, num - 1, NULL, NULL, NULL, NULL);
char* lpsz = new char[(unsigned int)len + 1];
WideCharToMultiByte(CP_ACP, 0, buffw, num - 1, lpsz, len, NULL, NULL);
lpsz[len]='\0';
delete[] buffw;
string rtn(lpsz);
delete[] lpsz;
return rtn ;
}
/*********************************************************
函数名: A2UTF8
函数描述: 多字节转UTF8
输入参数: cont - 多字节字符串
输出参数:
返回值: UTF8编码的字符串
**********************************************************/
string ASCII2UTF8(const char* cont)
{
if (NULL == cont)
{
return string("");
}
int num = MultiByteToWideChar(CP_ACP, NULL, cont, -1, NULL, NULL);
wchar_t* buffw = new wchar_t[(unsigned int)num];
MultiByteToWideChar(CP_ACP, NULL, cont, -1, buffw, num);
int len = WideCharToMultiByte(CP_UTF8, 0, buffw, num - 1, NULL, NULL, NULL, NULL);
char* lpsz = new char[(unsigned int)len + 1];
WideCharToMultiByte(CP_UTF8, 0, buffw, num - 1, lpsz, len, NULL, NULL);
lpsz[len]='\0';
delete[] buffw;
string rtn(lpsz);
delete[] lpsz;
return rtn;
}
/*********************************************************
Function: g_ExceptionCallBack
Desc: exception callback function
Input: dwType: message type;lUserID: log-in device ID;lHandle, handle of connected channel ; pUser, user data;
Output:
Return:
**********************************************************/
void CALLBACK g_ExceptionCallBack(DWORD dwType, LONG lUserID, LONG lHandle, void *pUser)
{
UNREFERENCED_PARAMETER(pUser);
if (g_bExitDemo)
{
return;
}
int i = 0, j=0;
int iDeviceIndex = -1;
CString sTemp;
// char szTmpBuf[256] = {0};
for (i = 0; i < MAX_DEVICES ; i++)
{
if (g_struDeviceInfo[i].lLoginID == lUserID)
{
iDeviceIndex = i;
break;
}
}
switch (dwType)
{
case EXCEPTION_RELOGIN:
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "EXCEPTION_RELOGIN");
break;
case RELOGIN_SUCCESS:
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "RELOGIN_SUCCESS");
break;
case EXCEPTION_EXCHANGE://the device is off line
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "EXCEPTION_EXCHANGE");
break;
case RESUME_EXCHANGE://the device is on line
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "RESUME_EXCHANGE");
break;
case EXCEPTION_AUDIOEXCHANGE: //network exception while voice talk
if (g_lVoiceHandle != -1)
{
if (lHandle == g_lVoiceHandle)
{//sdk do not reconnect, so close the exception thread
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "EXCEPTION_AUDIOEXCHANGE vt dev[%d],handle[%d]", iDeviceIndex,lHandle);
goto ExceptionOut;
}
}
else
{
for (i = 0; i<MAX_DEVICES; i++)
{
for (j = 0; j<MAX_AUDIO_V40; j++)
{
if (g_struDeviceInfo[i].lVoiceCom[j] == lHandle)
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AUDIOEXCHANGE mr dev[%d]exception[%d]", iDeviceIndex, dwType);
if (NET_DVR_StopVoiceCom(lHandle))
{
g_pMainDlg->AddLog(i, OPERATION_SUCC_T, "NET_DVR_StopVoiceCom audioindex[%d]", j);
g_struDeviceInfo[i].lVoiceCom[j] = -1;
}
else
{
g_pMainDlg->AddLog(i, OPERATION_FAIL_T, "NET_DVR_StopVoiceCom audioindex[%d]", j);
}
goto ExceptionOut;
}
}
}
}
if (g_struLocalParam.bBroadCast)
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AUDIOEXCHANGE BC dev[%d]handle[%d]exception[%d]", iDeviceIndex, lHandle, dwType);
NET_DVR_DelDVR_V30(lHandle);
}
break;
case EXCEPTION_ALARM: //network exception while uploading alarm
for (i = 0; i < MAX_DEVICES; i++)
{
if (g_struDeviceInfo[i].lFortifyHandle >= 0)
{
if (lHandle == g_struDeviceInfo[i].lFortifyHandle)
{
// if (NET_DVR_CloseAlarmChan_V30(g_struDeviceInfo[i].lFortifyHandle))
// {
g_pMainDlg->AddLog(i, OPERATION_FAIL_T, "alarm fortify exception!");
// g_struDeviceInfo[i].lFortifyHandle = -1;
// }
// else
// {
// }
goto ExceptionOut;
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "ALARM dev[%d]exception[%d]", iDeviceIndex, dwType);
break;
case EXCEPTION_PREVIEW: // exception while preview
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "PREVIEW dev[%d]exception[%d]", iDeviceIndex, dwType);
for (i = 0; i < MAX_OUTPUTS; i++)
{
if (lHandle == g_dlgOutput[i].m_lPlayHandle)
{
g_dlgOutput[i].AddLog(OPERATION_FAIL_T, "preview exception!");
if (g_dlgOutput[i].m_bLocalManualRec)
{
g_dlgOutput[i].StopLocalRecord();
}
g_dlgOutput[i].StopPlay();
g_pMainDlg->ChangePlayBtnState();
goto ExceptionOut;
}
}
break;
case EXCEPTION_SERIAL: //exception while connecting in a transparent channel mode
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "EXCEPTION_SERIAL dev[%d]", iDeviceIndex);
for (i = 0; i < MAX_DEVICES ; i++)
{
if (g_struDeviceInfo[i].lTranHandle >= 0)
{
if (lHandle == g_struDeviceInfo[i].lTranHandle)
{
g_pMainDlg->AddLog(i, OPERATION_FAIL_T, "serial transparent exception!!");
goto ExceptionOut;
}
}
}
break;
case EXCEPTION_RECONNECT: //reconnect while preview
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "preview RECONNECT dev[%d]", iDeviceIndex);
for (i = 0; i < MAX_OUTPUTS; i++)
{
if (lHandle == g_dlgOutput[i].m_lPlayHandle)
{
g_dlgOutput[i].AddLog(OPERATION_SUCC_T, "preview reconneting!");//reconnect to network while preview
goto ExceptionOut;
}
}
break;
case PREVIEW_RECONNECTSUCCESS: //reconnect successfully while preview
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "PREVIEW_RECONNECTSUCCESS dev[%d]", iDeviceIndex);
break;
case EXCEPTION_ALARMRECONNECT://reconnect alarm guard channel
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "ALARMRECONNECT dev[%d]", iDeviceIndex);
for (i = 0; i < MAX_DEVICES ; i++)
{
if (g_struDeviceInfo[i].lFortifyHandle >= 0)
{
if (lHandle == g_struDeviceInfo[i].lFortifyHandle)
{
g_pMainDlg->AddLog(i, OPERATION_SUCC_T, "alarm Fortify reconnecting!!");
goto ExceptionOut;
}
}
}
break;
case ALARM_RECONNECTSUCCESS://reconnect alarm guard channel successfully
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "ALARM_RECONNECTSUCCESS dev[%d]", iDeviceIndex);
break;
case EXCEPTION_SERIALRECONNECT://reconnect transparent channel
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "SERIALRECONNECT dev[%d]exception[0x%x]", iDeviceIndex, dwType);
for (i = 0; i < MAX_DEVICES ; i++)
{
if (g_struDeviceInfo[i].lLoginID == lUserID)
{
g_pMainDlg->AddLog(i, OPERATION_SUCC_T, "serial transparent reconnecting!");
goto ExceptionOut;
}
}
break;
case EXCEPTION_PLAYBACK:
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "EXCEPTION_PLAYBACK dev[%d] exception[0x%x] error[%d]", iDeviceIndex, dwType, NET_DVR_GetLastError());
break;
case EXCEPTION_DISKFMT:
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "EXCEPTION_DISKFMT dev[%d]DISKFMT exception[0x%x]", iDeviceIndex, dwType);
break;
case EXCEPTION_PASSIVEDECODE:
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "EXCEPTION_PASSIVEDECODE dev[%d]PASSIVEDECODE exception[0x%x]", iDeviceIndex, dwType);
//NET_DVR_MatrixStopPassiveDecode(lHandle);
break;
case SERIAL_RECONNECTSUCCESS:
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "SERIAL_RECONNECTSUCCESS dev[%d]", iDeviceIndex);
break;
case EXCEPTION_LOST_ALARM:
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "EXCEPTION_LOST_ALARM");
break;
case EXCEPTION_MAX_ALARM_INFO:
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "EXCEPTION_MAX_ALARM_INFO");
break;
case EXCEPTION_PASSIVEDECODE_RECONNNECT:
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "EXCEPTION_PASSIVEDECODE_RECONNNECT");
break;
case EXCEPTION_VIDEO_DOWNLOAD: // [add] by yangzheng 2019/11/09 增加录像文件下载异常
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "EXCEPTION_VIDEO_DOWNLOAD");
break;
default:
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "else exception dev[%d]exception[0x%x]", iDeviceIndex, dwType);
break;
}
ExceptionOut:
return;
}
/*********************************************************
Function: AlarmMessage
Desc: alarm
Input: lCommand,message type; pAlarmer,info of device which upload message;pAlarmInfo, message info content;dwBufLen,message length;
Output:
Return:
**********************************************************/
void AlarmMessage(LONG lCommand, NET_DVR_ALARMER *pAlarmer, char *pAlarmInfo, DWORD dwBufLen)
{
UINT iDeviceIndex = 0xffff;
UINT i = 0;
if (g_pMainDlg == NULL || g_bExitDemo)
{
TRACE("exit ...\n");
//return;
}
for (i = 0; i < MAX_DEVICES; i++)
{//IP address that client have acquired
if (strcmp(g_struDeviceInfo[i].chDeviceIP, pAlarmer->sDeviceIP) == 0)
{
iDeviceIndex = i;
break;
}
//监听时候的设备IP为sSocketIP
if (strcmp(g_struDeviceInfo[i].chDeviceIP, pAlarmer->sSocketIP) == 0)
{
iDeviceIndex = i;
break;
}
}
if (pAlarmer->bJSONBroken)
{
g_bJSONBroken = 1;
}
else
{
g_bJSONBroken = 0;
}
if (iDeviceIndex >= MAX_DEVICES || iDeviceIndex < 0)
{
g_pMainDlg->AddLog(-1, ALARM_INFO_T, "alarm host get alarm[%x] from device[%s] port[%d]", lCommand, pAlarmer->sDeviceIP, pAlarmer->wLinkPort);
//return;
}
else
{
char szDeviceName[NAME_LEN] = { 0 };
if (g_struDeviceInfo[iDeviceIndex].byCharaterEncodeType == ENUM_MEM_CHAR_ENCODE_UNICODE)
{
TranslateNetWcharToMutilChar(szDeviceName, (unsigned char*)(pAlarmer->sDeviceName), NAME_LEN);
}
else
{
strncpy(szDeviceName, pAlarmer->sDeviceName, NAME_LEN);
}
if (!(pAlarmer->byDeviceNameValid || pAlarmer->byMacAddrValid))
{
g_pMainDlg->AddLog(-1, ALARM_INFO_T, "alarm host get alarm[%x] from device[%s] port[%d] serial:%s", \
lCommand, pAlarmer->sDeviceIP, pAlarmer->wLinkPort,pAlarmer->sSerialNumber);
}
else
{
g_pMainDlg->AddLog(-1, ALARM_INFO_T, "alarm host get alarm[%x] from device[%s] port[%d] name[%s] mac:%x:%x:%x:%x:%x:%x serial:%s", \
lCommand, pAlarmer->sDeviceIP, pAlarmer->wLinkPort, szDeviceName, pAlarmer->byMacAddr[0], pAlarmer->byMacAddr[1], pAlarmer->byMacAddr[2], \
pAlarmer->byMacAddr[3], pAlarmer->byMacAddr[4], pAlarmer->byMacAddr[5],
pAlarmer->sSerialNumber);
}
}
try
{
char *pAlarmMsg = NULL;
if (lCommand == COMM_ALARM_WALL_CONFERNECE)
{
pAlarmMsg = new char[sizeof(DWORD) + dwBufLen];
if (pAlarmMsg == NULL)
{
return;
}
memset(pAlarmMsg, 0, sizeof(DWORD) + dwBufLen);
memcpy(pAlarmMsg, &dwBufLen, sizeof(DWORD));
memcpy(pAlarmMsg + sizeof(DWORD), pAlarmInfo, dwBufLen);
}
else
{
pAlarmMsg = new char[dwBufLen];
if (pAlarmMsg == NULL)
{
return;
}
memset(pAlarmMsg, 0, dwBufLen);
memcpy(pAlarmMsg, pAlarmInfo, dwBufLen);
}
if (lCommand == COMM_ISAPI_ALARM)
{
((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pAlarmData = new char[((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->dwAlarmDataLen + 1];
memset(((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pAlarmData, 0, ((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->dwAlarmDataLen + 1);
memcpy(((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pAlarmData, ((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmInfo)->pAlarmData, ((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->dwAlarmDataLen);
if (((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmInfo)->byPicturesNumber != 0)
{
((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pPicPackData = (NET_DVR_ALARM_ISAPI_PICDATA *)new BYTE[sizeof(NET_DVR_ALARM_ISAPI_PICDATA)* ((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmInfo)->byPicturesNumber];
memset(((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pPicPackData, 0, sizeof(NET_DVR_ALARM_ISAPI_PICDATA)* ((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmInfo)->byPicturesNumber);
memcpy(((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pPicPackData, ((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmInfo)->pPicPackData, sizeof(NET_DVR_ALARM_ISAPI_PICDATA)* ((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmInfo)->byPicturesNumber);
for (int i = 0; i < ((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmInfo)->byPicturesNumber; i++)
{
((NET_DVR_ALARM_ISAPI_PICDATA *)((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pPicPackData)[i].pPicData = new BYTE[((NET_DVR_ALARM_ISAPI_PICDATA *)((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pPicPackData)[i].dwPicLen];
memset(((NET_DVR_ALARM_ISAPI_PICDATA *)((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pPicPackData)[i].pPicData, 0, ((NET_DVR_ALARM_ISAPI_PICDATA *)((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pPicPackData)[i].dwPicLen);
memcpy(((NET_DVR_ALARM_ISAPI_PICDATA *)((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pPicPackData)[i].pPicData, ((NET_DVR_ALARM_ISAPI_PICDATA *)((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmInfo)->pPicPackData)[i].pPicData, ((NET_DVR_ALARM_ISAPI_PICDATA *)((LPNET_DVR_ALARM_ISAPI_INFO)pAlarmMsg)->pPicPackData)[i].dwPicLen);
}
}
}
else if (lCommand == COMM_ALARM_RULE)
{
((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pImage = new BYTE[((LPNET_VCA_RULE_ALARM)pAlarmMsg)->dwPicDataLen];
memset(((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pImage, 0, ((LPNET_VCA_RULE_ALARM)pAlarmMsg)->dwPicDataLen);
memcpy(((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pImage, ((LPNET_VCA_RULE_ALARM)pAlarmInfo)->pImage, ((LPNET_VCA_RULE_ALARM)pAlarmMsg)->dwPicDataLen);
if (((LPNET_VCA_RULE_ALARM)pAlarmMsg)->byAppendInfoUploadEnabled == 1)
{
((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pAppendInfo = new BYTE[sizeof(NET_VCA_APPEND_INFO)];
memset(((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pAppendInfo, 0, sizeof(NET_VCA_APPEND_INFO));
memcpy(((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pAppendInfo, ((LPNET_VCA_RULE_ALARM)pAlarmInfo)->pAppendInfo, sizeof(NET_VCA_APPEND_INFO));
((LPNET_VCA_APPEND_INFO)((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pAppendInfo)->pAppendPicBuff = new BYTE[((LPNET_VCA_APPEND_INFO)((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pAppendInfo)->dwAppendPicLen];
memset(((LPNET_VCA_APPEND_INFO)((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pAppendInfo)->pAppendPicBuff, 0, ((LPNET_VCA_APPEND_INFO)((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pAppendInfo)->dwAppendPicLen);
memcpy(((LPNET_VCA_APPEND_INFO)((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pAppendInfo)->pAppendPicBuff, ((LPNET_VCA_APPEND_INFO)((LPNET_VCA_RULE_ALARM)pAlarmInfo)->pAppendInfo)->pAppendPicBuff, ((LPNET_VCA_APPEND_INFO)((LPNET_VCA_RULE_ALARM)pAlarmMsg)->pAppendInfo)->dwAppendPicLen);
}
}
else if (lCommand == COMM_ALARM_PDC)
{
((LPNET_DVR_PDC_ALRAM_INFO)pAlarmMsg)->pXmlBuf = new char[((LPNET_DVR_PDC_ALRAM_INFO)pAlarmMsg)->dwXmlLen];
memset(((LPNET_DVR_PDC_ALRAM_INFO)pAlarmMsg)->pXmlBuf, 0, ((LPNET_DVR_PDC_ALRAM_INFO)pAlarmMsg)->dwXmlLen);
memcpy(((LPNET_DVR_PDC_ALRAM_INFO)pAlarmMsg)->pXmlBuf, ((LPNET_DVR_PDC_ALRAM_INFO)pAlarmInfo)->pXmlBuf, ((LPNET_DVR_PDC_ALRAM_INFO)pAlarmMsg)->dwXmlLen);
}
else if (COMM_ALARM_AID == lCommand)
{
((LPNET_DVR_AID_ALARM)pAlarmMsg)->pImage = new BYTE[((LPNET_DVR_AID_ALARM)pAlarmMsg)->dwPicDataLen];
memset(((LPNET_DVR_AID_ALARM)pAlarmMsg)->pImage, 0, ((LPNET_DVR_AID_ALARM)pAlarmMsg)->dwPicDataLen);
memcpy(((LPNET_DVR_AID_ALARM)pAlarmMsg)->pImage, ((LPNET_DVR_AID_ALARM)pAlarmInfo)->pImage, ((LPNET_DVR_AID_ALARM)pAlarmMsg)->dwPicDataLen);
}
else if (COMM_ALARM_FACE == lCommand)
{
((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->pImage = new BYTE[((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->dwPicDataLen];
memset(((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->pImage, 0, ((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->dwPicDataLen);
memcpy(((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->pImage, ((LPNET_DVR_FACEDETECT_ALARM)pAlarmInfo)->pImage, ((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->dwPicDataLen);
((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->pFaceImage = new BYTE[((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->dwFacePicDataLen];
memset(((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->pFaceImage, 0, ((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->dwFacePicDataLen);
memcpy(((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->pFaceImage, ((LPNET_DVR_FACEDETECT_ALARM)pAlarmInfo)->pFaceImage, ((LPNET_DVR_FACEDETECT_ALARM)pAlarmMsg)->dwFacePicDataLen);
}
else if (COMM_UPLOAD_FACESNAP_RESULT == lCommand)
{
DWORD dwPrePicLen = 0;
if (((LPNET_VCA_FACESNAP_RESULT)pAlarmMsg)->dwFacePicLen > 0)
{
((LPNET_VCA_FACESNAP_RESULT)pAlarmMsg)->pBuffer1 = (BYTE*)pAlarmMsg + sizeof(NET_VCA_FACESNAP_RESULT) + dwPrePicLen;
dwPrePicLen += ((LPNET_VCA_FACESNAP_RESULT)pAlarmMsg)->dwFacePicLen;
}
if (((LPNET_VCA_FACESNAP_RESULT)pAlarmMsg)->dwBackgroundPicLen > 0)
{
((LPNET_VCA_FACESNAP_RESULT)pAlarmMsg)->pBuffer2 = (BYTE*)pAlarmMsg + sizeof(NET_VCA_FACESNAP_RESULT) + dwPrePicLen;
dwPrePicLen += ((LPNET_VCA_FACESNAP_RESULT)pAlarmMsg)->dwBackgroundPicLen;
}
if (((LPNET_VCA_FACESNAP_RESULT)pAlarmMsg)->byUIDLen > 0)
{
((LPNET_VCA_FACESNAP_RESULT)pAlarmMsg)->pUIDBuffer = (BYTE*)pAlarmMsg + sizeof(NET_VCA_FACESNAP_RESULT) + dwPrePicLen;
dwPrePicLen += ((LPNET_VCA_FACESNAP_RESULT)pAlarmMsg)->byUIDLen;
}
if (((LPNET_VCA_FACESNAP_RESULT)pAlarmMsg)->byAddInfo > 0)
{
((LPNET_VCA_FACESNAP_RESULT)pAlarmMsg)->pAddInfoBuffer = (BYTE*)pAlarmMsg + sizeof(NET_VCA_FACESNAP_RESULT) + dwPrePicLen;
dwPrePicLen += sizeof(NET_VCA_FACESNAP_ADDINFO);
}
}
else if (COMM_ALARM_FACE_DETECTION == lCommand)
{
((LPNET_DVR_FACE_DETECTION)pAlarmMsg)->pBackgroundPicpBuffer = new BYTE[((LPNET_DVR_FACE_DETECTION)pAlarmMsg)->dwBackgroundPicLen];
memset(((LPNET_DVR_FACE_DETECTION)pAlarmMsg)->pBackgroundPicpBuffer, 0, ((LPNET_DVR_FACE_DETECTION)pAlarmMsg)->dwBackgroundPicLen);
memcpy(((LPNET_DVR_FACE_DETECTION)pAlarmMsg)->pBackgroundPicpBuffer, ((LPNET_DVR_FACE_DETECTION)pAlarmInfo)->pBackgroundPicpBuffer, \
((LPNET_DVR_FACE_DETECTION)pAlarmMsg)->dwBackgroundPicLen);
}
else if (COMM_SNAP_MATCH_ALARM == lCommand)
{
if (((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.dwSnapFacePicLen > 0)
{
((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.pBuffer1 = new BYTE[((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.dwSnapFacePicLen];
memset(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.pBuffer1, 0, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.dwSnapFacePicLen);
memcpy(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.pBuffer1, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmInfo)->struSnapInfo.pBuffer1, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.dwSnapFacePicLen);
}
if (((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwBlackListPicLen > 0)
{
((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.pBuffer1 = new BYTE[((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwBlackListPicLen];
memset(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.pBuffer1, 0, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwBlackListPicLen);
memcpy(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.pBuffer1, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmInfo)->struBlackListInfo.pBuffer1, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwBlackListPicLen);
}
if (((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->dwSnapPicLen > 0)
{
((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->pSnapPicBuffer = new BYTE[((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->dwSnapPicLen];
memset(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->pSnapPicBuffer, 0, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->dwSnapPicLen);
memcpy(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->pSnapPicBuffer, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmInfo)->pSnapPicBuffer, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->dwSnapPicLen);
}
if (((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->dwModelDataLen > 0)
{
((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->pModelDataBuffer = new BYTE[((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->dwModelDataLen];
memset(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->pModelDataBuffer, 0, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->dwModelDataLen);
memcpy(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->pModelDataBuffer, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmInfo)->pModelDataBuffer, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->dwModelDataLen);
}
if (((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.struAttribute.dwPersonInfoExtendLen > 0)
{
((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend = new BYTE[((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.struAttribute.dwPersonInfoExtendLen];
memset(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend, 0, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.struAttribute.dwPersonInfoExtendLen);
memcpy(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmInfo)->struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.struAttribute.dwPersonInfoExtendLen);
}
if (((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.dwUIDLen > 0)
{
((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.pUIDBuffer = new BYTE[((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.dwUIDLen];
memset(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.pUIDBuffer, 0, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.dwUIDLen);
memcpy(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.pUIDBuffer, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmInfo)->struSnapInfo.pUIDBuffer, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struSnapInfo.dwUIDLen);
}
if (((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwFDIDLen > 0)
{
((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.pFDID = new BYTE[((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwFDIDLen];
memset(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.pFDID, 0, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwFDIDLen);
memcpy(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.pFDID, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmInfo)->struBlackListInfo.pFDID, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwFDIDLen);
}
if (((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwPIDLen > 0)
{
((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.pPID = new BYTE[((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwPIDLen];
memset(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.pPID, 0, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwPIDLen);
memcpy(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.pPID, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmInfo)->struBlackListInfo.pPID, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.dwPIDLen);
}
if (((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.dwFDDescriptionLen > 0)
{
((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.pFDDescriptionBuffer = new BYTE[((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.dwFDDescriptionLen];
memset(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.pFDDescriptionBuffer, 0, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.dwFDDescriptionLen);
memcpy(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.pFDDescriptionBuffer, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmInfo)->struBlackListInfo.struBlackListInfo.pFDDescriptionBuffer, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.dwFDDescriptionLen);
}
if (((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.dwFCAdditionInfoLen > 0)
{
((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.pFCAdditionInfoBuffer = new BYTE[((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.dwFCAdditionInfoLen];
memset(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.pFCAdditionInfoBuffer, 0, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.dwFCAdditionInfoLen);
memcpy(((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.pFCAdditionInfoBuffer, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmInfo)->struBlackListInfo.struBlackListInfo.pFCAdditionInfoBuffer, ((LPNET_VCA_FACESNAP_MATCH_ALARM)pAlarmMsg)->struBlackListInfo.struBlackListInfo.dwFCAdditionInfoLen);
}
}
else if (COMM_ALARM_CAPTURE_UPLOAD == lCommand)
{
((LPNET_DVR_CAPTURE_UPLOAD)pAlarmMsg)->pBuffer = new BYTE[((LPNET_DVR_CAPTURE_UPLOAD)pAlarmMsg)->dwPicLen];
memset(((LPNET_DVR_CAPTURE_UPLOAD)pAlarmMsg)->pBuffer, 0, ((LPNET_DVR_CAPTURE_UPLOAD)pAlarmMsg)->dwPicLen);
memcpy(((LPNET_DVR_CAPTURE_UPLOAD)pAlarmMsg)->pBuffer, ((LPNET_DVR_CAPTURE_UPLOAD)pAlarmInfo)->pBuffer, ((LPNET_DVR_CAPTURE_UPLOAD)pAlarmMsg)->dwPicLen);
}
else if (COMM_FACESNAP_RAWDATA_ALARM == lCommand)
{
((LPNET_VCA_FACESNAP_RAWDATA_ALARM)pAlarmMsg)->pJsonBuff = new BYTE[((LPNET_VCA_FACESNAP_RAWDATA_ALARM)pAlarmMsg)->dwJsonDataLen];
memset(((LPNET_VCA_FACESNAP_RAWDATA_ALARM)pAlarmMsg)->pJsonBuff, 0, ((LPNET_VCA_FACESNAP_RAWDATA_ALARM)pAlarmMsg)->dwJsonDataLen);
memcpy(((LPNET_VCA_FACESNAP_RAWDATA_ALARM)pAlarmMsg)->pJsonBuff, ((LPNET_VCA_FACESNAP_RAWDATA_ALARM)pAlarmInfo)->pJsonBuff, ((LPNET_VCA_FACESNAP_RAWDATA_ALARM)pAlarmMsg)->dwJsonDataLen);
}
else if (COMM_FRAMES_PEOPLE_COUNTING_ALARM == lCommand)
{
((LPNET_DVR_FRAMES_PEOPLE_COUNTING)pAlarmMsg)->pPicBuffer = new BYTE[((LPNET_DVR_FRAMES_PEOPLE_COUNTING)pAlarmMsg)->dwPicLen];
memset(((LPNET_DVR_FRAMES_PEOPLE_COUNTING)pAlarmMsg)->pPicBuffer, 0, ((LPNET_DVR_FRAMES_PEOPLE_COUNTING)pAlarmMsg)->dwPicLen);
memcpy(((LPNET_DVR_FRAMES_PEOPLE_COUNTING)pAlarmMsg)->pPicBuffer, ((LPNET_DVR_FRAMES_PEOPLE_COUNTING)pAlarmInfo)->pPicBuffer, ((LPNET_DVR_FRAMES_PEOPLE_COUNTING)pAlarmMsg)->dwPicLen);
}
else if (COMM_FIREDETECTION_ALARM == lCommand)
{
((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->pBuffer = new BYTE[((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->dwPicDataLen];
memset(((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->pBuffer, 0, ((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->dwPicDataLen);
memcpy(((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->pBuffer, ((LPNET_DVR_FIREDETECTION_ALARM)pAlarmInfo)->pBuffer, ((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->dwPicDataLen);
((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->pVisiblePicBuf = new BYTE[((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->dwVisiblePicLen];
memset(((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->pVisiblePicBuf, 0, ((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->dwVisiblePicLen);
memcpy(((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->pVisiblePicBuf, ((LPNET_DVR_FIREDETECTION_ALARM)pAlarmInfo)->pVisiblePicBuf, ((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->dwVisiblePicLen);
if (((LPNET_DVR_FIREDETECTION_ALARM)pAlarmInfo)->byAlarmSubType == 1 || ((LPNET_DVR_FIREDETECTION_ALARM)pAlarmInfo)->byAlarmSubType == 2)
{
((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->pSmokeBuf = new BYTE[sizeof(NET_DVR_SMOKEDETECTION_ALARM)];
memset(((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->pSmokeBuf, 0, sizeof(NET_DVR_SMOKEDETECTION_ALARM));
memcpy(((LPNET_DVR_FIREDETECTION_ALARM)pAlarmMsg)->pSmokeBuf, ((LPNET_DVR_FIREDETECTION_ALARM)pAlarmInfo)->pSmokeBuf, sizeof(NET_DVR_SMOKEDETECTION_ALARM));
}
}
else if (COMM_FACE_THERMOMETRY_ALARM == lCommand)
{
((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->pVisibleLightImage = new BYTE[((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->dwVisibleLightImageLen];
memset(((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->pVisibleLightImage, 0, ((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->dwVisibleLightImageLen);
memcpy(((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->pVisibleLightImage, ((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmInfo)->pVisibleLightImage, ((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->dwVisibleLightImageLen);
((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->pFaceImage = new BYTE[((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->dwFaceImageLen];
memset(((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->pFaceImage, 0, ((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->dwFaceImageLen);
memcpy(((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->pFaceImage, ((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmInfo)->pFaceImage, ((LPNET_DVR_FACE_THERMOMETRY_ALARM)pAlarmMsg)->dwFaceImageLen);
}
else if (COMM_ALARM_SHIPSDETECTION == lCommand)
{
((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->pPicBuffer = new BYTE[((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->dwPicLen];
memset(((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->pPicBuffer, 0, ((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->dwPicLen);
memcpy(((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->pPicBuffer, ((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmInfo)->pPicBuffer, ((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->dwPicLen);
((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->pThermalPicBuffer = new BYTE[((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->dwThermalPicLen];
memset(((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->pThermalPicBuffer, 0, ((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->dwThermalPicLen);
memcpy(((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->pThermalPicBuffer, ((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmInfo)->pThermalPicBuffer, ((LPNET_DVR_SHIPSDETECTION_ALARM)pAlarmMsg)->dwThermalPicLen);
}
else if (COMM_VEHICLE_CONTROL_ALARM == lCommand)
{
((LPNET_DVR_VEHICLE_CONTROL_ALARM)pAlarmMsg)->pPicData = new char[((LPNET_DVR_VEHICLE_CONTROL_ALARM)pAlarmMsg)->dwPicDataLen];
memset(((LPNET_DVR_VEHICLE_CONTROL_ALARM)pAlarmMsg)->pPicData, 0, ((LPNET_DVR_VEHICLE_CONTROL_ALARM)pAlarmMsg)->dwPicDataLen);
memcpy(((LPNET_DVR_VEHICLE_CONTROL_ALARM)pAlarmMsg)->pPicData, ((LPNET_DVR_VEHICLE_CONTROL_ALARM)pAlarmInfo)->pPicData, ((LPNET_DVR_VEHICLE_CONTROL_ALARM)pAlarmMsg)->dwPicDataLen);
}
else if (COMM_THERMOMETRY_ALARM == lCommand)
{
((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->pPicBuff = new char[((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->dwPicLen];
memset(((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->pPicBuff, 0, ((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->dwPicLen);
memcpy(((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->pPicBuff, ((LPNET_DVR_THERMOMETRY_ALARM)pAlarmInfo)->pPicBuff, ((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->dwPicLen);
((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->pThermalPicBuff = new char[((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->dwThermalPicLen];
memset(((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->pThermalPicBuff, 0, ((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->dwThermalPicLen);
memcpy(((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->pThermalPicBuff, ((LPNET_DVR_THERMOMETRY_ALARM)pAlarmInfo)->pThermalPicBuff, ((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->dwThermalPicLen);
((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->pThermalInfoBuff = new char[((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->dwThermalInfoLen];
memset(((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->pThermalInfoBuff, 0, ((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->dwThermalInfoLen);
memcpy(((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->pThermalInfoBuff, ((LPNET_DVR_THERMOMETRY_ALARM)pAlarmInfo)->pThermalInfoBuff, ((LPNET_DVR_THERMOMETRY_ALARM)pAlarmMsg)->dwThermalInfoLen);
}
else if (COMM_THERMOMETRY_DIFF_ALARM == lCommand)
{
((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->pPicBuff = new char[((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->dwPicLen];
memset(((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->pPicBuff, 0, ((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->dwPicLen);
memcpy(((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->pPicBuff, ((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmInfo)->pPicBuff, ((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->dwPicLen);
((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->pThermalPicBuff = new char[((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->dwThermalPicLen];
memset(((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->pThermalPicBuff, 0, ((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->dwThermalPicLen);
memcpy(((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->pThermalPicBuff, ((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmInfo)->pThermalPicBuff, ((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->dwThermalPicLen);
((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->pThermalInfoBuff = new char[((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->dwThermalInfoLen];
memset(((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->pThermalInfoBuff, 0, ((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->dwThermalInfoLen);
memcpy(((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->pThermalInfoBuff, ((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmInfo)->pThermalInfoBuff, ((LPNET_DVR_THERMOMETRY_DIFF_ALARM)pAlarmMsg)->dwThermalInfoLen);
}
else if (COMM_VEHICLE_RECOG_RESULT == lCommand)
{
//车辆
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pVehicleBuffer = new BYTE[((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwVehicleBufferLen];
memset(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pVehicleBuffer, 0, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwVehicleBufferLen);
memcpy(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pVehicleBuffer, \
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmInfo)->pVehicleBuffer, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwVehicleBufferLen);
//车牌
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pPlateBuffer = new BYTE[((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwPlateBufferLen];
memset(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pPlateBuffer, 0, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwPlateBufferLen);
memcpy(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pPlateBuffer, \
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmInfo)->pPlateBuffer, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwPlateBufferLen);
//人脸(主驾驶)
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pPilotFaceBuffer = new BYTE[((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwPilotFaceBufferLen];
memset(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pPilotFaceBuffer, 0, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwPilotFaceBufferLen);
memcpy(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pPilotFaceBuffer, \
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmInfo)->pPilotFaceBuffer, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwPilotFaceBufferLen);
//人脸(副驾驶)
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pCopilotFaceBuffer = new BYTE[((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwCopilotFaceBufferLen];
memset(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pCopilotFaceBuffer, 0, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwCopilotFaceBufferLen);
memcpy(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pCopilotFaceBuffer, \
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmInfo)->pCopilotFaceBuffer, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwCopilotFaceBufferLen);
//安全带(主驾驶)
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pPilotSafebeltBuffer = new BYTE[((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwPilotSafebeltBufferLen];
memset(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pPilotSafebeltBuffer, 0, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwPilotSafebeltBufferLen);
memcpy(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pPilotSafebeltBuffer, \
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmInfo)->pPilotSafebeltBuffer, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwPilotSafebeltBufferLen);
//安全带(副驾驶)
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pCopilotSafebeltBuffer = new BYTE[((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwCopilotSafebeltBufferLen];
memset(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pCopilotSafebeltBuffer, 0, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwCopilotSafebeltBufferLen);
memcpy(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pCopilotSafebeltBuffer, \
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmInfo)->pCopilotSafebeltBuffer, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwCopilotSafebeltBufferLen);
//json
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pJsonBuffer = new BYTE[((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwJsonBufferLen];
memset(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pJsonBuffer, 0, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwJsonBufferLen);
memcpy(((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->pJsonBuffer, \
((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmInfo)->pJsonBuffer, ((LPNET_DVR_VEHICLE_RECOG_RESULT)pAlarmMsg)->dwJsonBufferLen);
}
else if (COMM_ITS_PLATE_RESULT == lCommand)
{
int i = 0;
DWORD dwPrePicLen = 0;
int iIllegalInfoLen = 0;
for (i = 0; i < 6; i++)
{
if (((LPNET_ITS_PLATE_RESULT)pAlarmMsg)->struPicInfo[i].dwDataLen > 0)
{
((LPNET_ITS_PLATE_RESULT)pAlarmMsg)->struPicInfo[i].pBuffer = (BYTE*)pAlarmMsg + sizeof(NET_ITS_PLATE_RESULT) + dwPrePicLen;
dwPrePicLen += ((LPNET_ITS_PLATE_RESULT)pAlarmMsg)->struPicInfo[i].dwDataLen;
}
}
if (1 == ((LPNET_ITS_PLATE_RESULT)pAlarmMsg)->byIllegalFromatType)
{
((LPNET_ITS_PLATE_RESULT)pAlarmMsg)->pIllegalInfoBuf = (BYTE*)pAlarmMsg + sizeof(NET_ITS_PLATE_RESULT) + dwPrePicLen;
iIllegalInfoLen = sizeof(NET_ITS_ILLEGAL_INFO);
}
if (((LPNET_ITS_PLATE_RESULT)pAlarmMsg)->struPlateInfo.dwXmlLen > 0)
{
((LPNET_ITS_PLATE_RESULT)pAlarmMsg)->struPlateInfo.pXmlBuf =
(char*)pAlarmMsg + sizeof(NET_ITS_PLATE_RESULT) + dwPrePicLen + iIllegalInfoLen;
}if (((LPNET_ITS_PLATE_RESULT)pAlarmMsg)->struPlateInfo.byAddInfoFlag > 0)
{
((LPNET_ITS_PLATE_RESULT)pAlarmMsg)->struPlateInfo.pAddInfoBuffer =
(BYTE*)pAlarmMsg + sizeof(NET_ITS_PLATE_RESULT) + dwPrePicLen + iIllegalInfoLen + ((LPNET_ITS_PLATE_RESULT)pAlarmMsg)->struPlateInfo.dwXmlLen;
}
}
else if (COMM_ALARM_TPS_REAL_TIME == lCommand)
{
if (((LPNET_DVR_TPS_REAL_TIME_INFO)pAlarmMsg)->byAddInfoFlag > 0)
{
((LPNET_DVR_TPS_REAL_TIME_INFO)pAlarmMsg)->pAddInfoBuffer =
(BYTE*)pAlarmMsg + sizeof(NET_DVR_TPS_REAL_TIME_INFO);
}
}
else if (COMM_PEOPLE_DETECTION_UPLOAD == lCommand)
{
int i = 0;
DWORD dwPrePicLen = 0;
for (i = 0; i < MAX_PEOPLE_DETECTION_NUM; i++)
{
if (((LPNET_DVR_PEOPLE_DETECTION_RESULT)pAlarmMsg)->struPeopleRegion[i].dwPicLen > 0)
{
((LPNET_DVR_PEOPLE_DETECTION_RESULT)pAlarmMsg)->struPeopleRegion[i].pPicBuffer = (char*)pAlarmMsg + sizeof(NET_DVR_PEOPLE_DETECTION_RESULT) + dwPrePicLen;
dwPrePicLen += ((LPNET_DVR_PEOPLE_DETECTION_RESULT)pAlarmMsg)->struPeopleRegion[i].dwPicLen;
}
}
}
else if (COMM_TME_VEHICLE_INDENTIFICATION == lCommand)
{
int i = 0;
DWORD dwPrePicLen = 0;
for (i = 0; i < 4; i++)
{
if (((LPNET_DVR_TME_VEHICLE_RESULT)pAlarmMsg)->struPicInfo[i].dwDataLen > 0)
{
((LPNET_DVR_TME_VEHICLE_RESULT)pAlarmMsg)->struPicInfo[i].pBuffer = (BYTE*)pAlarmMsg + sizeof(NET_DVR_TME_VEHICLE_RESULT) + dwPrePicLen;
dwPrePicLen += ((LPNET_DVR_TME_VEHICLE_RESULT)pAlarmMsg)->struPicInfo[i].dwDataLen;
}
}
}
else if (COMM_PLATE_RESULT_V50 == lCommand)
{
int i = 0;
DWORD dwPrePicLen = 0;
for (i = 0; i < 6; i++)
{
if (((LPNET_DVR_PLATE_RESULT_V50)pAlarmMsg)->struPicInfo[i].dwDataLen > 0)
{
((LPNET_DVR_PLATE_RESULT_V50)pAlarmMsg)->struPicInfo[i].pBuffer = (BYTE*)pAlarmMsg + sizeof(NET_DVR_PLATE_RESULT_V50) + dwPrePicLen;
dwPrePicLen += ((LPNET_DVR_PLATE_RESULT_V50)pAlarmMsg)->struPicInfo[i].dwDataLen;
}
}
}
else if (COMM_ITS_GATE_VEHICLE == lCommand)
{
int i = 0;
DWORD dwPrePicLen = 0;
for (i = 0; i < 4; i++)
{
if (((LPNET_ITS_GATE_VEHICLE)pAlarmMsg)->struPicInfo[i].dwDataLen > 0)
{
((LPNET_ITS_GATE_VEHICLE)pAlarmMsg)->struPicInfo[i].pBuffer = (BYTE*)pAlarmMsg + sizeof(NET_ITS_GATE_VEHICLE) + dwPrePicLen;
dwPrePicLen += ((LPNET_ITS_GATE_VEHICLE)pAlarmMsg)->struPicInfo[i].dwDataLen;
}
}
}
else if (COMM_ITS_GATE_FACE == lCommand)
{
((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.pBuffer1 = new BYTE[((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.dwFacePicLen];
memset(((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.pBuffer1, 0, ((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.dwFacePicLen);
memcpy(((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.pBuffer1, ((LPNET_ITS_GATE_FACE)pAlarmInfo)->struFaceInfo.pBuffer1, \
((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.dwFacePicLen);
((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.pBuffer2 = new BYTE[((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.dwBackgroundPicLen];
memset(((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.pBuffer2, 0, ((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.dwBackgroundPicLen);
memcpy(((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.pBuffer2, ((LPNET_ITS_GATE_FACE)pAlarmInfo)->struFaceInfo.pBuffer2, \
((LPNET_ITS_GATE_FACE)pAlarmMsg)->struFaceInfo.dwBackgroundPicLen);
}
else if (COMM_ITS_PARK_VEHICLE == lCommand)
{
int i = 0;
DWORD dwPrePicLen = 0;
for (i = 0; i < 2; i++)
{
if (((LPNET_ITS_PARK_VEHICLE)pAlarmMsg)->struPicInfo[i].dwDataLen > 0)
{
((LPNET_ITS_PARK_VEHICLE)pAlarmMsg)->struPicInfo[i].pBuffer = (BYTE*)pAlarmMsg + sizeof(NET_ITS_PARK_VEHICLE) + dwPrePicLen;
dwPrePicLen += ((LPNET_ITS_PARK_VEHICLE)pAlarmMsg)->struPicInfo[i].dwDataLen;
}
}
}
else if (COMM_ALARM_AID_V41 == lCommand)
{
((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->pImage = new BYTE[((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->dwPicDataLen];
memset(((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->pImage, 0, ((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->dwPicDataLen);
memcpy(((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->pImage, ((LPNET_DVR_AID_ALARM_V41)pAlarmInfo)->pImage, ((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->dwPicDataLen);
((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->pXmlBuf = new char[((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->dwXmlLen];
memset(((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->pXmlBuf, 0, ((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->dwXmlLen);
memcpy(((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->pXmlBuf, ((LPNET_DVR_AID_ALARM_V41)pAlarmInfo)->pXmlBuf, ((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->dwXmlLen);
((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->pPlateSmallImage = new char[((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->dwPlateSmallPicDataLen];
memset(((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->pPlateSmallImage, 0, ((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->dwPlateSmallPicDataLen);
memcpy(((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->pPlateSmallImage, ((LPNET_DVR_AID_ALARM_V41)pAlarmInfo)->pPlateSmallImage, ((LPNET_DVR_AID_ALARM_V41)pAlarmMsg)->dwPlateSmallPicDataLen);
}
else if (COMM_ALARM_TFS == lCommand)
{
int i = 0;
DWORD dwPrePicLen = 0;
for (i = 0; i < 8; i++)
{
if (((LPNET_DVR_TFS_ALARM)pAlarmMsg)->struPicInfo[i].dwDataLen > 0)
{
((LPNET_DVR_TFS_ALARM)pAlarmMsg)->struPicInfo[i].pBuffer = (BYTE*)pAlarmMsg + sizeof(NET_DVR_TFS_ALARM) + dwPrePicLen;
dwPrePicLen += ((LPNET_DVR_TFS_ALARM)pAlarmMsg)->struPicInfo[i].dwDataLen;
}
}
}
else if (COMM_ALARM_VQD_EX == lCommand)
{
if (((LPNET_DVR_VQD_ALARM)pAlarmMsg)->dwPicDataLen > 0)
{
((LPNET_DVR_VQD_ALARM)pAlarmMsg)->pImage = new BYTE[((LPNET_DVR_VQD_ALARM)pAlarmMsg)->dwPicDataLen];
memset(((LPNET_DVR_VQD_ALARM)pAlarmMsg)->pImage, 0, ((LPNET_DVR_VQD_ALARM)pAlarmMsg)->dwPicDataLen);
memcpy(((LPNET_DVR_VQD_ALARM)pAlarmMsg)->pImage, ((LPNET_DVR_VQD_ALARM)pAlarmInfo)->pImage, ((LPNET_DVR_VQD_ALARM)pAlarmMsg)->dwPicDataLen);
}
}
else if (COMM_UPLOAD_HEATMAP_RESULT == lCommand || COMM_UPLOAD_HEATMAP_RESULT_DURATION == lCommand || COMM_UPLOAD_HEATMAP_RESULT_INTERSECTION == lCommand)
{
if ((((LPNET_DVR_HEATMAP_RESULT)pAlarmMsg)->wArrayColumn > 0) || (((LPNET_DVR_HEATMAP_RESULT)pAlarmMsg)->wArrayLine > 0))
{
((LPNET_DVR_HEATMAP_RESULT)pAlarmMsg)->pBuffer = (BYTE *)pAlarmMsg + sizeof(NET_DVR_HEATMAP_RESULT);
}
}
else if (COMM_ALARM_V40 == lCommand)
{
DWORD dwVerDataNum = 0;
switch (((LPNET_DVR_ALARMINFO_V40)pAlarmMsg)->struAlarmFixedHeader.dwAlarmType)
{
case 0:
case 23:
dwVerDataNum = (((LPNET_DVR_ALARMINFO_V40)pAlarmMsg)->struAlarmFixedHeader.uStruAlarm.struIOAlarm.dwTrigerAlarmOutNum + \
((LPNET_DVR_ALARMINFO_V40)pAlarmMsg)->struAlarmFixedHeader.uStruAlarm.struIOAlarm.dwTrigerRecordChanNum);
break;
case 1:
case 4:
case 5:
dwVerDataNum = ((LPNET_DVR_ALARMINFO_V40)pAlarmMsg)->struAlarmFixedHeader.uStruAlarm.struAlarmHardDisk.dwAlarmHardDiskNum;
break;
case 2:
case 3:
case 6:
case 9:
case 10:
case 11:
case 13:
case 15:
case 19:
case 28:
dwVerDataNum = ((LPNET_DVR_ALARMINFO_V40)pAlarmMsg)->struAlarmFixedHeader.uStruAlarm.struAlarmChannel.dwAlarmChanNum;
break;
default:
dwVerDataNum = 0;
break;
}
if (dwVerDataNum != 0)
{
((LPNET_DVR_ALARMINFO_V40)pAlarmMsg)->pAlarmData = new DWORD[dwVerDataNum];
memset(((LPNET_DVR_ALARMINFO_V40)pAlarmMsg)->pAlarmData, 0, dwVerDataNum * sizeof(DWORD));
memcpy(((LPNET_DVR_ALARMINFO_V40)pAlarmMsg)->pAlarmData, ((LPNET_DVR_ALARMINFO_V40)pAlarmInfo)->pAlarmData, dwVerDataNum* sizeof(DWORD));
}
else
{
((LPNET_DVR_ALARMINFO_V40)pAlarmMsg)->pAlarmData = NULL;
}
}
else if (COMM_UPLOAD_VIDEO_INTERCOM_EVENT == lCommand)
{
LPNET_DVR_VIDEO_INTERCOM_EVENT pVideoIntercomEvent = (LPNET_DVR_VIDEO_INTERCOM_EVENT)pAlarmMsg;
if (pVideoIntercomEvent->byEventType == 1 && pVideoIntercomEvent->uEventInfo.struUnlockRecord.dwPicDataLen > 0)
{
pVideoIntercomEvent->uEventInfo.struUnlockRecord.pImage = new BYTE[pVideoIntercomEvent->uEventInfo.struUnlockRecord.dwPicDataLen];
memcpy(pVideoIntercomEvent->uEventInfo.struUnlockRecord.pImage, ((LPNET_DVR_VIDEO_INTERCOM_EVENT)pAlarmInfo)->uEventInfo.struUnlockRecord.pImage,
pVideoIntercomEvent->uEventInfo.struUnlockRecord.dwPicDataLen);
}
if (pVideoIntercomEvent->byEventType == 3 && pVideoIntercomEvent->uEventInfo.struAuthInfo.dwPicDataLen > 0)
{
pVideoIntercomEvent->uEventInfo.struAuthInfo.pImage = new BYTE[pVideoIntercomEvent->uEventInfo.struAuthInfo.dwPicDataLen];
memcpy(pVideoIntercomEvent->uEventInfo.struAuthInfo.pImage, ((LPNET_DVR_VIDEO_INTERCOM_EVENT)pAlarmInfo)->uEventInfo.struAuthInfo.pImage,
pVideoIntercomEvent->uEventInfo.struAuthInfo.dwPicDataLen);
}
}
else if (lCommand == COMM_UPLOAD_NOTICE_DATA)
{
for (int i = 0; i < MAX_NOTICE_PIC_NUM; i++)
{
if (((LPNET_DVR_NOTICE_DATA)pAlarmMsg)->struNoticePic[i].dwPicDataLen > 0)
{
((LPNET_DVR_NOTICE_DATA)pAlarmMsg)->struNoticePic[i].pPicData = new BYTE[((LPNET_DVR_NOTICE_DATA)pAlarmMsg)->struNoticePic[i].dwPicDataLen];
memset(((LPNET_DVR_NOTICE_DATA)pAlarmMsg)->struNoticePic[i].pPicData, 0, ((LPNET_DVR_NOTICE_DATA)pAlarmMsg)->struNoticePic[i].dwPicDataLen);
memcpy(((LPNET_DVR_NOTICE_DATA)pAlarmMsg)->struNoticePic[i].pPicData, ((LPNET_DVR_NOTICE_DATA)pAlarmInfo)->struNoticePic[i].pPicData, ((LPNET_DVR_NOTICE_DATA)pAlarmMsg)->struNoticePic[i].dwPicDataLen);
}
}
}
else if (lCommand == COMM_SWITCH_LAMP_ALARM)
{
if (((LPNET_DVR_SWITCH_LAMP_ALARM)pAlarmMsg)->pPicData > 0 && ((LPNET_DVR_SWITCH_LAMP_ALARM)pAlarmInfo)->pPicData != NULL)
{
((LPNET_DVR_SWITCH_LAMP_ALARM)pAlarmMsg)->pPicData = new char[((LPNET_DVR_SWITCH_LAMP_ALARM)pAlarmMsg)->dwPicDataLen];
memset(((LPNET_DVR_SWITCH_LAMP_ALARM)pAlarmMsg)->pPicData, 0, ((LPNET_DVR_SWITCH_LAMP_ALARM)pAlarmMsg)->dwPicDataLen);
memcpy(((LPNET_DVR_SWITCH_LAMP_ALARM)pAlarmMsg)->pPicData, ((LPNET_DVR_SWITCH_LAMP_ALARM)pAlarmInfo)->pPicData, ((LPNET_DVR_SWITCH_LAMP_ALARM)pAlarmMsg)->dwPicDataLen);
}
}
else if (lCommand == COMM_LOADING_DOCK_OPERATEINFO) //月台作业上传
{
if (((LPNET_LOADING_DOCK_OPERATEINFO)pAlarmMsg)->pBackPicDataBuffer > 0 && ((LPNET_LOADING_DOCK_OPERATEINFO)pAlarmInfo)->pBackPicDataBuffer != NULL)
{
((LPNET_LOADING_DOCK_OPERATEINFO)pAlarmMsg)->pBackPicDataBuffer = new BYTE[((LPNET_LOADING_DOCK_OPERATEINFO)pAlarmMsg)->dwBackPicDataLength];
memset(((LPNET_LOADING_DOCK_OPERATEINFO)pAlarmMsg)->pBackPicDataBuffer, 0, ((LPNET_LOADING_DOCK_OPERATEINFO)pAlarmMsg)->dwBackPicDataLength);
memcpy(((LPNET_LOADING_DOCK_OPERATEINFO)pAlarmMsg)->pBackPicDataBuffer, ((LPNET_LOADING_DOCK_OPERATEINFO)pAlarmInfo)->pBackPicDataBuffer, ((LPNET_LOADING_DOCK_OPERATEINFO)pAlarmMsg)->dwBackPicDataLength);
}
}
else if (lCommand == COMM_ALARM_ACS)
{
if (((LPNET_DVR_ACS_ALARM_INFO)pAlarmMsg)->pPicData > 0 && ((LPNET_DVR_ACS_ALARM_INFO)pAlarmInfo)->pPicData != NULL)
{
((LPNET_DVR_ACS_ALARM_INFO)pAlarmMsg)->pPicData = new char[((LPNET_DVR_ACS_ALARM_INFO)pAlarmMsg)->dwPicDataLen];
memset(((LPNET_DVR_ACS_ALARM_INFO)pAlarmMsg)->pPicData, 0, ((LPNET_DVR_ACS_ALARM_INFO)pAlarmMsg)->dwPicDataLen);
memcpy(((LPNET_DVR_ACS_ALARM_INFO)pAlarmMsg)->pPicData, ((LPNET_DVR_ACS_ALARM_INFO)pAlarmInfo)->pPicData, ((LPNET_DVR_ACS_ALARM_INFO)pAlarmMsg)->dwPicDataLen);
}
if (((LPNET_DVR_ACS_ALARM_INFO)pAlarmMsg)->pAcsEventInfoExtend > 0 && ((LPNET_DVR_ACS_ALARM_INFO)pAlarmInfo)->pAcsEventInfoExtend != NULL)
{
((LPNET_DVR_ACS_ALARM_INFO)pAlarmMsg)->pAcsEventInfoExtend = new char[sizeof(NET_DVR_ACS_EVENT_INFO_EXTEND)];
memset(((LPNET_DVR_ACS_ALARM_INFO)pAlarmMsg)->pAcsEventInfoExtend, 0, sizeof(NET_DVR_ACS_EVENT_INFO_EXTEND));
memcpy(((LPNET_DVR_ACS_ALARM_INFO)pAlarmMsg)->pAcsEventInfoExtend, ((LPNET_DVR_ACS_ALARM_INFO)pAlarmInfo)->pAcsEventInfoExtend, sizeof(NET_DVR_ACS_EVENT_INFO_EXTEND));
}
}
else if (lCommand == COMM_ID_INFO_ALARM)
{
if (((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pPicData > 0 && ((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmInfo)->pPicData != NULL)
{
((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pPicData = new char[((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->dwPicDataLen];
memset(((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pPicData, 0, ((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->dwPicDataLen);
memcpy(((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pPicData, ((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmInfo)->pPicData, ((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->dwPicDataLen);
}
if ((((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pFingerPrintData > 0) && (((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmInfo)->pFingerPrintData != NULL))
{
((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pFingerPrintData = new char[((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->dwFingerPrintDataLen];
memset(((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pFingerPrintData, 0, ((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->dwFingerPrintDataLen);
memcpy(((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pFingerPrintData, ((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmInfo)->pFingerPrintData, ((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->dwFingerPrintDataLen);
}
if ((((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pCapturePicData > 0) && (((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmInfo)->pCapturePicData != NULL))
{
((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pCapturePicData = new char[((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->dwCapturePicDataLen];
memset(((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pCapturePicData, 0, ((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->dwCapturePicDataLen);
memcpy(((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->pCapturePicData, ((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmInfo)->pCapturePicData, ((LPNET_DVR_ID_CARD_INFO_ALARM)pAlarmMsg)->dwCapturePicDataLen);
}
}
else if (lCommand == COMM_PASSPORT_ALARM)
{
if (((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pFaceData > 0 && ((LPNET_DVR_PASSPORT_ALARM)pAlarmInfo)->pFaceData != NULL)
{
((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pFaceData = new char[((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->dwFaceDataLen];
memset(((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pFaceData, 0, ((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->dwFaceDataLen);
memcpy(((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pFaceData, ((LPNET_DVR_PASSPORT_ALARM)pAlarmInfo)->pFaceData, ((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->dwFaceDataLen);
}
if ((((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pPicData > 0) && (((LPNET_DVR_PASSPORT_ALARM)pAlarmInfo)->pPicData != NULL))
{
((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pPicData = new char[((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->dwPicDataLen];
memset(((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pPicData, 0, ((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->dwPicDataLen);
memcpy(((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pPicData, ((LPNET_DVR_PASSPORT_ALARM)pAlarmInfo)->pPicData, ((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->dwPicDataLen);
}
if ((((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pCapturePicData > 0) && (((LPNET_DVR_PASSPORT_ALARM)pAlarmInfo)->pCapturePicData != NULL))
{
((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pCapturePicData = new char[((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->dwCapturePicDataLen];
memset(((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pCapturePicData, 0, ((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->dwCapturePicDataLen);
memcpy(((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->pCapturePicData, ((LPNET_DVR_PASSPORT_ALARM)pAlarmInfo)->pCapturePicData, ((LPNET_DVR_PASSPORT_ALARM)pAlarmMsg)->dwCapturePicDataLen);
}
}
else if (lCommand == COMM_PANORAMIC_LINKAGE_ALARM)
{
if (((LPNET_DVR_PANORAMIC_LINKAGE)pAlarmMsg)->pPicBuff > 0 && ((LPNET_DVR_PANORAMIC_LINKAGE)pAlarmInfo)->pPicBuff != NULL)
{
((LPNET_DVR_PANORAMIC_LINKAGE)pAlarmMsg)->pPicBuff = new char[((LPNET_DVR_PANORAMIC_LINKAGE)pAlarmMsg)->dwPicLen];
memset(((LPNET_DVR_PANORAMIC_LINKAGE)pAlarmMsg)->pPicBuff, 0, ((LPNET_DVR_PANORAMIC_LINKAGE)pAlarmMsg)->dwPicLen);
memcpy(((LPNET_DVR_PANORAMIC_LINKAGE)pAlarmMsg)->pPicBuff, ((LPNET_DVR_PANORAMIC_LINKAGE)pAlarmInfo)->pPicBuff, ((LPNET_DVR_PANORAMIC_LINKAGE)pAlarmMsg)->dwPicLen);
}
}
else if (COMM_UPLOAD_HEATMAP_RESULT_PDC == lCommand)
{
int iLen = 0;
int iArrayUnitType = ((LPNET_DVR_HEATMAP_RESULT_PDC)pAlarmMsg)->byArrayUnitType;
for (int i = 0; i < 2; i++)
{
if ((((LPNET_DVR_HEATMAP_RESULT_PDC)pAlarmMsg)->struSingleHeatMap[i].wArrayColumn > 0) || (((LPNET_DVR_HEATMAP_RESULT_PDC)pAlarmMsg)->struSingleHeatMap[i].wArrayLine > 0))
{
((LPNET_DVR_HEATMAP_RESULT_PDC)pAlarmMsg)->struSingleHeatMap[i].pBuffer = (BYTE*)pAlarmMsg + sizeof(NET_DVR_HEATMAP_RESULT_PDC) + iLen;
iLen = ((LPNET_DVR_HEATMAP_RESULT_PDC)pAlarmMsg)->struSingleHeatMap[i].wArrayColumn * ((LPNET_DVR_HEATMAP_RESULT_PDC)pAlarmMsg)->struSingleHeatMap[i].wArrayLine * iArrayUnitType;
}
}
}
else if (COMM_VCA_DBD_ALARM == lCommand)
{
DWORD dwPicLen = ((LPNET_DVR_DBD_ALRAM_INFO)pAlarmMsg)->struPicInfo.dwPicLen;
if (dwPicLen > 0)
{
((LPNET_DVR_DBD_ALRAM_INFO)pAlarmMsg)->struPicInfo.pPicBuf = new char[dwPicLen];
if (((LPNET_DVR_DBD_ALRAM_INFO)pAlarmMsg)->struPicInfo.pPicBuf != NULL)
{
memcpy(((LPNET_DVR_DBD_ALRAM_INFO)pAlarmMsg)->struPicInfo.pPicBuf, ((LPNET_DVR_DBD_ALRAM_INFO)pAlarmInfo)->struPicInfo.pPicBuf, dwPicLen);
}
}
DWORD dwVideoLen = ((LPNET_DVR_DBD_ALRAM_INFO)pAlarmMsg)->struPicInfo.dwVideoLen;
if (dwVideoLen > 0)
{
((LPNET_DVR_DBD_ALRAM_INFO)pAlarmMsg)->struPicInfo.pVideoBuf = new char[dwVideoLen];
if (((LPNET_DVR_DBD_ALRAM_INFO)pAlarmMsg)->struPicInfo.pVideoBuf != NULL)
{
memcpy(((LPNET_DVR_DBD_ALRAM_INFO)pAlarmMsg)->struPicInfo.pVideoBuf, ((LPNET_DVR_DBD_ALRAM_INFO)pAlarmInfo)->struPicInfo.pVideoBuf, dwVideoLen);
}
}
}
else if (COMM_VCA_ADAS_ALARM == lCommand)
{
DWORD dwPicLen = ((LPNET_DVR_ADAS_ALRAM_INFO)pAlarmMsg)->struPicInfo.dwPicLen;
if (dwPicLen > 0)
{
((LPNET_DVR_ADAS_ALRAM_INFO)pAlarmMsg)->struPicInfo.pPicBuf = new char[dwPicLen];
if (((LPNET_DVR_ADAS_ALRAM_INFO)pAlarmMsg)->struPicInfo.pPicBuf != NULL)
{
memcpy(((LPNET_DVR_ADAS_ALRAM_INFO)pAlarmMsg)->struPicInfo.pPicBuf, ((LPNET_DVR_ADAS_ALRAM_INFO)pAlarmInfo)->struPicInfo.pPicBuf, dwPicLen);
}
}
DWORD dwVideoLen = ((LPNET_DVR_ADAS_ALRAM_INFO)pAlarmMsg)->struPicInfo.dwVideoLen;
if (dwVideoLen > 0)
{
((LPNET_DVR_ADAS_ALRAM_INFO)pAlarmMsg)->struPicInfo.pVideoBuf = new char[dwVideoLen];
if (((LPNET_DVR_ADAS_ALRAM_INFO)pAlarmMsg)->struPicInfo.pVideoBuf != NULL)
{
memcpy(((LPNET_DVR_ADAS_ALRAM_INFO)pAlarmMsg)->struPicInfo.pVideoBuf, ((LPNET_DVR_ADAS_ALRAM_INFO)pAlarmInfo)->struPicInfo.pVideoBuf, dwVideoLen);
}
}
}
else if (COMM_UPLOAD_AIOP_VIDEO == lCommand)
{
DWORD dwPrePicLen = 0;
if (((LPNET_AIOP_VIDEO_HEAD)pAlarmMsg)->dwAIOPDataSize > 0 && ((LPNET_AIOP_VIDEO_HEAD)pAlarmInfo)->pBufferAIOPData != NULL)
{
((LPNET_AIOP_VIDEO_HEAD)pAlarmMsg)->pBufferAIOPData = (BYTE *)pAlarmMsg + sizeof(NET_AIOP_VIDEO_HEAD) + dwPrePicLen;
dwPrePicLen += ((LPNET_AIOP_VIDEO_HEAD)pAlarmMsg)->dwAIOPDataSize;
}
if (((LPNET_AIOP_VIDEO_HEAD)pAlarmMsg)->dwPictureSize > 0 && ((LPNET_AIOP_VIDEO_HEAD)pAlarmInfo)->pBufferPicture != NULL)
{
((LPNET_AIOP_VIDEO_HEAD)pAlarmMsg)->pBufferPicture = (BYTE *)pAlarmMsg + sizeof(NET_AIOP_VIDEO_HEAD) + dwPrePicLen;
dwPrePicLen += ((LPNET_AIOP_VIDEO_HEAD)pAlarmMsg)->dwPictureSize;
}
}
else if (COMM_UPLOAD_AIOP_PICTURE == lCommand)
{
if (((LPNET_AIOP_PICTURE_HEAD)pAlarmMsg)->dwAIOPDataSize > 0 && ((LPNET_AIOP_PICTURE_HEAD)pAlarmInfo)->pBufferAIOPData != NULL)
{
((LPNET_AIOP_PICTURE_HEAD)pAlarmMsg)->pBufferAIOPData = (BYTE *)pAlarmMsg + sizeof(NET_AIOP_PICTURE_HEAD);
}
}
else if (COMM_UPLOAD_AIOP_POLLING_SNAP == lCommand)
{
DWORD dwDataLen = 0;
if (((LPNET_AIOP_POLLING_SNAP_HEAD)pAlarmMsg)->dwAIOPDataSize > 0 && ((LPNET_AIOP_POLLING_SNAP_HEAD)pAlarmInfo)->pBufferAIOPData != NULL)
{
((LPNET_AIOP_POLLING_SNAP_HEAD)pAlarmMsg)->pBufferAIOPData = (BYTE *)pAlarmMsg + sizeof(NET_AIOP_POLLING_SNAP_HEAD) + dwDataLen;
dwDataLen += ((LPNET_AIOP_POLLING_SNAP_HEAD)pAlarmMsg)->dwAIOPDataSize;
}
if (((LPNET_AIOP_POLLING_SNAP_HEAD)pAlarmMsg)->dwPictureSize > 0 && ((LPNET_AIOP_POLLING_SNAP_HEAD)pAlarmInfo)->pBufferPicture != NULL)
{
((LPNET_AIOP_POLLING_SNAP_HEAD)pAlarmMsg)->pBufferPicture = (BYTE *)pAlarmMsg + sizeof(NET_AIOP_POLLING_SNAP_HEAD) + dwDataLen;
dwDataLen += ((LPNET_AIOP_POLLING_SNAP_HEAD)pAlarmMsg)->dwPictureSize;
}
}
else if (COMM_UPLOAD_AIOP_POLLING_VIDEO == lCommand)
{
DWORD dwDataLen = 0;
if (((LPNET_AIOP_POLLING_VIDEO_HEAD)pAlarmMsg)->dwAIOPDataSize > 0 && ((LPNET_AIOP_POLLING_VIDEO_HEAD)pAlarmInfo)->pBufferAIOPData != NULL)
{
((LPNET_AIOP_POLLING_VIDEO_HEAD)pAlarmMsg)->pBufferAIOPData = (BYTE*)pAlarmMsg + sizeof(NET_AIOP_POLLING_VIDEO_HEAD) + dwDataLen;
dwDataLen += ((LPNET_AIOP_POLLING_VIDEO_HEAD)pAlarmMsg)->dwAIOPDataSize;
}
if (((LPNET_AIOP_POLLING_VIDEO_HEAD)pAlarmMsg)->dwPictureSize > 0 && ((LPNET_AIOP_POLLING_VIDEO_HEAD)pAlarmInfo)->pBufferPicture != NULL)
{
((LPNET_AIOP_POLLING_VIDEO_HEAD)pAlarmMsg)->pBufferPicture = (BYTE*)pAlarmMsg + sizeof(NET_AIOP_POLLING_VIDEO_HEAD) + dwDataLen;
dwDataLen += ((LPNET_AIOP_POLLING_VIDEO_HEAD)pAlarmMsg)->dwPictureSize;
}
}
LPLOCAL_ALARM_INFO pAlarmDev = new LOCAL_ALARM_INFO;
if (pAlarmDev == NULL)
{
delete[] pAlarmMsg;
pAlarmMsg = NULL;
return;
}
pAlarmDev->iDeviceIndex = iDeviceIndex;
pAlarmDev->lCommand = lCommand;
memcpy(pAlarmDev->sDeviceIP, pAlarmer->sDeviceIP, 128);
pAlarmDev->dwBufLen = dwBufLen;
pAlarmDev->wLinkPort = pAlarmer->wLinkPort;
//the memery may be free.
//g_pMainDlg->ProcDeviceAlarm((DWORD)pAlarmDev, (LONG)pAlarmMsg);
::PostMessage(g_pMainDlg->m_hWnd, WM_PROC_ALARM, (WPARAM)pAlarmDev, (LPARAM)pAlarmMsg);
}
catch (...)
{
OutputDebugString("New Alarm Exception!\n");
}
return;
}
/*********************************************************
Function: MessageCallback
Desc: alarm, callback functions dealing with the info of card in ATM
Input: lCommand,message type; pAlarmer,info of device which upload message;pAlarmInfo, message info content;dwBufLen,message length; pUser, user parameter
Output:
Return:
**********************************************************/
void CALLBACK MessageCallback(LONG lCommand, NET_DVR_ALARMER *pAlarmer, char *pAlarmInfo, DWORD dwBufLen, void* pUser)
{
//Sleep(100000);
UNREFERENCED_PARAMETER(pUser);
AlarmMessage(lCommand, pAlarmer, pAlarmInfo, dwBufLen);
}
/*********************************************************
Function: CClientDemoDlg
Desc: Constructor
Input:
Output:
Return:
**********************************************************/
IMPLEMENT_DYNAMIC(CClientDemoDlg, CDialog)
CClientDemoDlg::CClientDemoDlg(CWnd* pParent /*=NULL*/)
: CDialog(CClientDemoDlg::IDD, pParent)
, m_iCurDeviceIndex(-1)
, m_iCurChanIndex(-1)
, m_iCurWndIndex(0)//select current Output
, m_iMainType(PREVIEW_T)
, m_hCurDeviceItem(NULL)
, m_hCurChanItem(NULL)
, m_iCurRecDriver(0)
, m_pAutoRecTimer(NULL)
, m_pChkDevTimer(NULL)
, m_pCyclePlayTimer(NULL)
, m_pFreeSpaceTimer(NULL)
, m_pFileIntervalTimer(NULL)
, m_pSysTimer(NULL)
, m_iCardChanCount(0)
, m_iDriverNum(0)
, m_iTreeWidth(0)
, m_iRightWidth(0)
, m_iFunBtnHeight(0)
, m_iListLogHeight(0)
, m_bDrag(FALSE)
, m_iDragType(0)
, m_iDragChanIndex(-1)
, m_iDragParentIndex(-1)
, m_iCurWndNum(4)
, m_bListLogEnlarge(FALSE)
, m_bListAlarmEnlarge(FALSE)
, m_lListenHandle(-1)
, m_fLog(NULL)
, m_fAlarm(NULL)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
memset(&m_cHardDriver[0], 0, 26);
memset(&m_struOldWndpl, 0, sizeof(WINDOWPLACEMENT));
memset(&m_struSensorAlarm, 0, sizeof(m_struSensorAlarm));
InitializeCriticalSection(&m_struLock); //most thread might use log print function, especially alarm part, needing to add a lock
InitializeCriticalSection(&g_cs);
m_bSupportChanEx = FALSE;
memset(&m_struVcaCtrlInfo, 0, sizeof(m_struVcaCtrlInfo));
memset(&m_struIFrame, 0, sizeof(m_struIFrame));
}
/*********************************************************
Function: ~CClientDemoDlg
Desc: destructor
Input:
Output:
Return:
**********************************************************/
CClientDemoDlg::~CClientDemoDlg()
{
if (m_fLog != NULL)
{
fclose(m_fLog);
}
if (m_fAlarm!= NULL)
{
fclose(m_fAlarm);
}
m_hIcon = NULL;
m_hCurDeviceItem = NULL;
m_hCurChanItem = NULL;
g_pMainDlg = NULL;
delete m_dlgRemoteCfg;
delete m_dlgLocalCfg;
delete m_dlgIPAccess;
delete m_dlgHDConfig;
delete m_dlgConfigAll;
delete m_dlgOutputCtrl;
delete m_dlgPlayBack;
//delete m_pStreamIDDlg;
delete m_dlgBatchCfg;
delete m_dlgProductCfg;
for (int i = 0; i < MAX_DEVICES; i++)
{
if (g_struDeviceInfo[i].pStruChanInfo != NULL)
{
delete[] g_struDeviceInfo[i].pStruChanInfo;
g_struDeviceInfo[i].pStruChanInfo = NULL;
}
if (g_struDeviceInfo[i].pStruIPParaCfgV40 != NULL)
{
delete[] g_struDeviceInfo[i].pStruIPParaCfgV40;
g_struDeviceInfo[i].pStruIPParaCfgV40 = NULL;
}
if (g_struDeviceInfo[i].pStruIPAlarmInCfgV40 != NULL)
{
delete[] g_struDeviceInfo[i].pStruIPAlarmInCfgV40 ;
g_struDeviceInfo[i].pStruIPAlarmInCfgV40 = NULL;
}
if (g_struDeviceInfo[i].pStruIPAlarmOutCfgV40 != NULL)
{
delete[] g_struDeviceInfo[i].pStruIPAlarmOutCfgV40;
g_struDeviceInfo[i].pStruIPAlarmOutCfgV40 = NULL;
}
}
DeleteCriticalSection(&g_cs);
DeleteCriticalSection(&m_struLock);
}
/*********************************************************
Function: DoDataExchange
Desc: the map between control and variable
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CClientDemoDlg)
DDX_Control(pDX, IDC_BTN_PLAY, m_btnPlay);
DDX_Control(pDX, IDC_BTN_RECORD, m_btnRecord);
DDX_Control(pDX, IDC_TREE_DEVICE_LIST, m_treeDeviceList);
DDX_Control(pDX, IDC_COMBO_WNDNUM, m_comboWinNum);
DDX_Control(pDX, IDC_COMBO_NETDELAY, m_comboNetDelayBufNum);
DDX_Control(pDX, IDC_LIST_ALL_LOG, m_listAllLog);
DDX_Control(pDX, IDC_LIST_ALARM_INFO, m_listAlarmInfo);
//}}AFX_DATA_MAP
}
/*********************************************************
Function: BEGIN_MESSAGE_MAP
Desc: the map between control and function
Input:
Output:
Return:
**********************************************************/
BEGIN_MESSAGE_MAP(CClientDemoDlg, CDialog)
//{{AFX_MSG_MAP(CClientDemoDlg)
ON_WM_TIMER()
ON_WM_MOVE()
ON_NOTIFY(NM_CLICK, IDC_TREE_DEVICE_LIST, OnNMClickTreeDeviceList)
ON_NOTIFY(NM_RCLICK, IDC_TREE_DEVICE_LIST, OnNMRclickTreeDeviceList)
ON_NOTIFY(NM_DBLCLK, IDC_TREE_DEVICE_LIST, OnNMDblclkTreeDeviceList)
ON_CBN_SELCHANGE(IDC_COMBO_WNDNUM, OnCbnSelchangeComboWndNum)
ON_BN_CLICKED(IDC_BTN_CONFIG, OnBnClickedBtnConfig)
ON_BN_CLICKED(IDC_BTN_RECORD, OnBnClickedBtnRecord)
ON_CBN_SELCHANGE(IDC_COMBO_NETDELAY, OnCbnSelchangeComboNetdelay)
ON_BN_CLICKED(IDC_BTN_PLAY_BACK, OnBnClickedBtnPlayback)
ON_BN_CLICKED(IDC_BTN_MANAGE, OnBnClickedBtnManage)
ON_BN_CLICKED(IDC_BTN_LOG_CLEAR, OnBnClickedBtnLogClear)
ON_BN_CLICKED(IDC_BTN_LOG_SAVE, OnBnClickedBtnLogSave)
ON_BN_CLICKED(IDC_BTN_MAKE_IFRAME, OnBnClickedBtnMakeIframe)
ON_BN_CLICKED(IDC_BTN_LOG_CONFIG, OnBnClickedBtnLogConfig)
ON_NOTIFY(NM_CLICK, IDC_LIST_ALL_LOG, OnNMClickListAllLog)
ON_BN_CLICKED(IDC_BTN_PREVIEW, OnBnClickedBtnPreview)
ON_BN_CLICKED(IDC_BTN_EXIT, OnBnClickedBtnExit)
ON_BN_CLICKED(IDC_BTN_PLAY, OnBnClickedBtnPlay)
ON_BN_CLICKED(IDC_BTN_PICTURE_SNATCH, OnBnClickedBtnPictureSnatch)
ON_BN_CLICKED(IDC_BTN_ELSE, OnBnClickedBtnElse)
ON_NOTIFY(NM_DBLCLK, IDC_LIST_ALL_LOG, OnDblclkListAllLog)
ON_NOTIFY(NM_DBLCLK, IDC_LIST_ALARM_INFO, OnDblclkListAlarmInfo)
ON_NOTIFY(LVN_COLUMNCLICK, IDC_LIST_ALL_LOG, OnColumnclickListAllLog)
ON_NOTIFY(LVN_COLUMNCLICK, IDC_LIST_ALARM_INFO, OnColumnclickListAlarmInfo)
ON_BN_CLICKED(IDC_BTN_TEST, OnBtnTest)
ON_BN_CLICKED(IDC_RADIO_LOCAL_LOG, OnRadioLocalLog)
ON_BN_CLICKED(IDC_RADIO_ALARM_INFO, OnRadioAlarmInfo)
ON_COMMAND(ID_MENU_SENSOR_ADD_PREVIEW, OnMenuSensorAddPreview)
ON_COMMAND(ID_MENU_HOLIDAY_CFG, OnMenuHolidayCfg)
ON_COMMAND(ID_MENU_T1Test, OnMENUT1Test)
ON_COMMAND(ID_MENU_T1Test, OnMENUT1Test)
ON_COMMAND(ID_MENU_PRODUCTION_LINE_TEST, OnMenuProductionLineTest)
ON_COMMAND(ID_MEMU_IPERF, OnMenuIperf)
ON_WM_HSCROLL()
ON_COMMAND(ID_MENU_DEVICE_ADD, OnMenuDeviceAdd)
ON_COMMAND(ID_MENU_DEVICE_DELETE, OnMenuDeviceDelete)
ON_COMMAND(ID_MENU_LOGOUT, OnMenuLogout)
ON_COMMAND(ID_MENU_DEVICE_INFO, OnMenuDeviceInfo)
ON_COMMAND(ID_MENU_CHANNEL_INFO, OnMenuChannelInfo)
ON_COMMAND(ID_MENU_JPEG_SNATCH_CONFIG, OnMenuJPEGSnatchConfig)
ON_COMMAND(ID_MENU_DEVICE_CHECK_TIME, OnMenuCheckTime)
ON_COMMAND(ID_MENU_UPGRADE, OnMenuUpgrade)
ON_COMMAND(ID_MENU_REBOOT, OnMenuReboot)
ON_COMMAND(ID_MENU_HD_FORMAT, OnMenuHDFormat)
ON_COMMAND(ID_MENU_POWEROFF, OnMenuPoweroff)
ON_COMMAND(ID_MENU_FORTIFY, OnMenuFortify)
ON_COMMAND(ID_MENU_VOICE_TALK, OnMenuVoiceTalk)
ON_COMMAND(ID_MENU_REMOTE_KEY, OnMenuRemoteKey)
ON_COMMAND(ID_MENU_VOICE_BROADCAST, OnMenuBroadCast)
ON_COMMAND(ID_MENU_DVR_LOCAL_RECORD, OnMenuDVRRecordStart)
ON_COMMAND(ID_MENU_LOG_SEARCH, OnMenuLogSearch)
ON_COMMAND(ID_MENU_WORK_STATE, OnMenuWorkState)
ON_COMMAND(ID_MENU_CONFIG_RESTORE, OnMenuDefaultConfig)
ON_COMMAND(ID_MENU_SERIAL_TRANS, OnMenuSerialTrans)
ON_COMMAND(ID_MENU_CONFIG_FLASH, OnMenuConfigFlash)
ON_COMMAND(ID_MENU_TALK_MR, OnMenuTalkMR)
ON_MESSAGE(WM_PROC_ALARM, OnWMProcAlarm)
ON_MESSAGE(WM_CHANGE_CHANNEL_ITEM_IMAGE,ChangeChannelItemImage)
ON_MESSAGE(WM_CHANGE_DEVICE_ITEM_IMAGE,ChangeDeviceItemImage)
ON_MESSAGE(WM_ADD_LOG, OnWMAddLog)
ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
ON_COMMAND(ID_MENU_PRODUCTION_LINE_TEST_EN, OnMenuProductionLineTest)
ON_COMMAND(IDM_MENU_VCA, OnMenuVca)
ON_BN_CLICKED(IDC_BTN_PRODUCT_CFG,OnBtntProductCfg)
ON_COMMAND(ID_MENU_COMPLETE_RESTORE, OnMenuCompleteRestore)
ON_COMMAND(ID_MENU_DEBUG, OnMenuDebug)
ON_COMMAND(ID_MENU_UPLOAD_CALIBRATION_FILE, OnMenuUploadCalibrationFile)
//}}AFX_MSG_MAP
ON_COMMAND(ID_ALARM_SEARCH, &CClientDemoDlg::OnMenuSearchAlarm)
END_MESSAGE_MAP()
// CClientDemoDlg message handlers
/*********************************************************
Function: OnInitDialog
Desc: Initialize the dialog
Input:
Output:
Return:
**********************************************************/
BOOL CClientDemoDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
//CBrush cbr.CreateSolidBrush(COLORREF(0xffffff));//white
// TODO: Add extra initialization here//////////////////////////////////////////////////////////////
//
//get path of configuration file
char szLan[128] = {0};
memset(g_szWorkDir, 0, MAX_PATH);
GetCurrentPath(g_szWorkDir);
//2012-06-21 先按照默认目录创建,否则当本地配置文件无数据时将无保存目录,此时导出配置文件将失败
g_CreateLocalDir();
ReadLocalConfig();
g_ReadDeviceConfig();
g_ReadLocalReadSensorAdd();
InitGlobalSysInfo();
InitChildWindow();
//initialize main window
InitMainWin();
LoadTreeImage();
CreateTree();
//for the demo log and alarm info
CreateNewLogFile(g_struLocalParam.bAutoSaveLog);
m_iCurRecDriver = m_cHardDriver[g_struLocalParam.iStartRecordDriver];
m_pAutoRecTimer = SetTimer(AUTORECORD_TIMER, 2000, NULL);
if (g_struLocalParam.bAutoCheckDeviceTime)
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "Start DVR timing, the school time is %06d", g_struLocalParam.lCheckDeviceTime);
m_pChkDevTimer = SetTimer(CHECK_DEVICE_TIMER, 1000, NULL);
}
m_pFreeSpaceTimer = SetTimer(FREESPACE_TIMER, 5000, NULL);
m_pFileIntervalTimer = SetTimer(FILEINTERVAL_TIMER, 2000, NULL);
m_pSysTimer = SetTimer(SYSTEM_TIMER, 1000, NULL);//refresh time on time
//SDK uploads the info such as alarm and log sent from DVR by calling callback function
//NET_DVR_SetDVRMessageCallBack_V30(MessageCallback, NULL);
//设置NET_DVR_SetDVRMessageCallBack_V51回调后所有json报文默认走新格式返回,如果需要收到老格式json报文,需要调用NET_DVR_SetSDKLocalCfg接口,命令码NET_DVR_LOCAL_CFG_MESSAGE_CALLBACK_V51,设置byVcaAlarmJsonType为老格式回调
//demo默认修改为走老格式回调,改动位置在ClientDemo.cpp文件中
NET_DVR_SetDVRMessageCallBack_V51(0, MessageCallback, NULL);
//SDK detects exception and uploads it, such as network disconnect
NET_DVR_SetLogToFile(g_struLocalParam.nLogLevel, "c:\\SdkLogTest\\", g_struLocalParam.bCycleWriteLog);
AddLog(-1, OPERATION_SUCC_T, "sdk v%x", NET_DVR_GetSDKBuildVersion());
NET_DVR_SetExceptionCallBack_V30(WM_NULL/*WM_MYCOMMAND*/, NULL/*this->m_hWnd*/, g_ExceptionCallBack, NULL);
NET_DVR_SetReconnect(5000, g_struLocalParam.bReconnect);
if (!NET_DVR_SetShowMode(NORMALMODE, RGB(255, 255, 255)))
{
AddLog(-1, OPERATION_FAIL_T, "NET_DVR_SetShowMode");
}
PlayM4_InitDDrawDevice();
char exeFullPath[MAX_PATH] = { 0 }; // Full path
CString strExePath = "";
//获取exe所在路径
GetModuleFileName(NULL, exeFullPath, MAX_PATH);
strExePath = exeFullPath; // Get full path of the file
int pos = strExePath.ReverseFind('\\');
CString stringXSDPath = strExePath.Left(pos); // Return the directory without the file name
stringXSDPath = stringXSDPath + "\\ClientDemoDll\\libxml2.dll";
g_hDllInst = LoadLibraryEx(stringXSDPath ,NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
//calib.dll
CString stringcalibath = strExePath.Left(pos); // Return the directory without the file name
stringcalibath = stringXSDPath + "\\ClientDemoDll\\calib.dll";
g_hDllCalib = LoadLibraryEx(stringcalibath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
//libcurl.dll
CString stringCurlPath = strExePath.Left(pos); // Return the directory without the file name
stringCurlPath = strExePath.Left(pos) + "\\ClientDemoDll\\libcurl.dll";
g_hDllCurlLib = LoadLibraryEx(stringCurlPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
return TRUE; // return TRUE unless you set the focus to a control
}
/*********************************************************
Function: RegisterPlayer
Desc: register the player or unregister
Input: bRegister, TRUE=register, FALSE=unregister;
Output: none
Return: TRUE/FALSE
**********************************************************/
BOOL CClientDemoDlg::RegisterPlayer(BOOL bRegister)
{
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof STARTUPINFO;
char* pCmdLine=new char[4096];
PROCESS_INFORMATION pi;
BOOL res = FALSE;
char szCurPath[256] = {0};
GetCurrentPath(szCurPath);
//sprintf(szCurPath, "%s\\", szCurPath);
if (bRegister)
{
sprintf(pCmdLine, "regsvr32 %s\\PLAYSDK_DefSource.dll /s\
%s\\PLAYSDK_StreamSource.dll /s\
%s\\PLAYSDK_Sample.dll /s\
%s\\PLAYSDK_DefDemux.dll /s\
%s\\PLAYSDK_RFCDemux.dll /s\
%s\\PLAYSDK_MPEG2Source.dll /s\
%s\\PLAYSDK_MPEG2Demux.dll /s\
%s\\PLAYSDK_H264Dec.dll /s\
%s\\PLAYSDK_Mpeg4Dec.dll /s\
%s\\PLAYSDK_G722Dec.dll /s\
%s\\PLAYSDK_G711Dec.dll /s\
%s\\PLAYSDK_VTrans.dll /s\
%s\\PLAYSDK_ARenderer.dll /s\
%s\\PLAYSDK_VRenderer.dll /s\
%s\\PLAYSDK_Image.dll /s",\
szCurPath, szCurPath, szCurPath, szCurPath, szCurPath\
, szCurPath, szCurPath, szCurPath, szCurPath, szCurPath,\
szCurPath, szCurPath, szCurPath, szCurPath, szCurPath);
}
else
{
sprintf(pCmdLine, "regsvr32 -u %s\\PLAYSDK_DefSource.dll /s\
-u %s\\PLAYSDK_StreamSource.dll /s\
-u %s\\PLAYSDK_Sample.dll /s\
-u %s\\PLAYSDK_DefDemux.dll /s\
-u %s\\PLAYSDK_RFCDemux.dll /s\
-u %s\\PLAYSDK_MPEG2Source.dll /s\
-u %s\\PLAYSDK_MPEG2Demux.dll /s\
-u %s\\PLAYSDK_H264Dec.dll /s\
-u %s\\PLAYSDK_Mpeg4Dec.dll /s\
-u %s\\PLAYSDK_G722Dec.dll /s\
-u %s\\PLAYSDK_G711Dec.dll /s\
-u %s\\PLAYSDK_VTrans.dll /s\
-u %s\\PLAYSDK_ARenderer.dll /s\
-u %s\\PLAYSDK_VRenderer.dll /s\
-u %s\\PLAYSDK_Image.dll /s",\
szCurPath, szCurPath, szCurPath, szCurPath, szCurPath\
, szCurPath, szCurPath, szCurPath, szCurPath, szCurPath,\
szCurPath, szCurPath, szCurPath, szCurPath, szCurPath);
}
res = CreateProcess(NULL,
pCmdLine, // execute dos command
NULL,
NULL,
NULL,
NORMAL_PRIORITY_CLASS,// | CREATE_NO_WINDOW,
NULL,
NULL,
&si,
&pi);
if (TRUE == res)
{
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
else
{
g_pMainDlg->AddLog(-1, OPERATION_FAIL_T, "register player fail!");
}
if (pCmdLine != NULL)
{
delete [] pCmdLine;
}
return res;
}
/*********************************************************
Function: OnPaint
Desc: refresh dialog
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the szUser drags
// the minimized window.
/*********************************************************
Function: OnQueryDragIcon
Desc: drag mouse to initialize function
Input:
Output:
Return:
**********************************************************/
HCURSOR CClientDemoDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
/*********************************************************
Function: InitHardDriver
Desc: get pc basic info
Input:
Output:
Return:
**********************************************************/
BOOL CClientDemoDlg::InitHardDriver()
{
DWORD dw=GetLogicalDriveStrings(0,NULL);
LPTSTR pAllDrivers=new char[dw];
::GetLogicalDriveStrings(dw,pAllDrivers);
LPTSTR pDriver=pAllDrivers;
char tempDriver[26];
DWORD nDriverNum=0;
char *pTmp;
while (pDriver[0]!=0)
{
tempDriver[nDriverNum++]=*pDriver;
if ( (pTmp = _tcschr(pDriver,0)) != NULL)
{
pDriver=pTmp+1; //locate to next driver
}
}
//volume information
TCHAR lpVolumeNameBuffer[200];
DWORD dwVolumeSerialNumber,dwMaxComLength;
DWORD dwFileSystemFlags;
TCHAR lpFileSystemNameBuffer[50];
DWORD nHardNum=0;
for (DWORD i=0;i<nDriverNum;i++)
{
CString csRecRootPath;
csRecRootPath.Format("%c%s",tempDriver[i],":\\");
if (GetDriveType(csRecRootPath)==DRIVE_FIXED)
{
if (GetVolumeInformation(csRecRootPath,lpVolumeNameBuffer,sizeof(lpVolumeNameBuffer),&dwVolumeSerialNumber,
&dwMaxComLength,&dwFileSystemFlags,lpFileSystemNameBuffer,sizeof(lpFileSystemNameBuffer)))
{
this->m_cHardDriver[nHardNum++]=tempDriver[i];
}
}
}
m_iDriverNum=nHardNum;
delete[] pAllDrivers;
return TRUE;
}
/*********************************************************
Function: InitDecodeCard
Desc: initialize decode card
Input:
Output:
Return: TRUE,initialization succeed;FALSE,initialization failed;
**********************************************************/
BOOL CClientDemoDlg::InitDecodeCard()
{
SetDecoderVideoExtOutputProc DLINK_SetDecoderVideoExtOutput;
SetDisplayRegionProc DLINK_SetDisplayRegion;
SetDisplayStandardProc DLINK_SetDisplayStandard;
GetDisplayChannelCountProc DLINK_GetDisplayChannelCount;
DLINK_SetDecoderVideoExtOutput = (SetDecoderVideoExtOutputProc)GetProcAddress(g_hDSSDK, "SetDecoderVideoExtOutput");
DLINK_SetDisplayRegion = (SetDisplayRegionProc)GetProcAddress(g_hDSSDK, "SetDisplayRegion");
DLINK_SetDisplayStandard = (SetDisplayStandardProc)GetProcAddress(g_hDSSDK, "SetDisplayStandard");
DLINK_GetDisplayChannelCount = (GetDisplayChannelCountProc)GetProcAddress(g_hDSSDK, "GetDisplayChannelCount");
int nDispNum = 0;
char szLan[128] = {0};
if (!NET_DVR_InitDDraw_Card(GetDlgItem(IDC_STATIC_PREVIEWBG)->m_hWnd,0xffffff))//dark blue 0xff2200
{
AddLog(-1, OPERATION_FAIL_T, "NET_DVR_InitDDraw_Card\n");
return FALSE;
}
m_iCardChanCount = 0;
if (!NET_DVR_InitDevice_Card(&m_iCardChanCount))
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "NET_DVR_InitDevice_Card\n");
return FALSE;
}
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "Decoder Card Channel Num=%d", m_iCardChanCount);
if (m_iCardChanCount <= 0)
{
g_StringLanType(szLan, "请插入解码卡", "Please Insert Decoder Card");
//AfxMessageBox(szLan);
return FALSE;
}
else if (m_iCardChanCount > 16)
{
m_iCardChanCount = 16;
}
if (g_struLocalParam.bNTSC)
{
nDispNum = DLINK_GetDisplayChannelCount();
if (nDispNum >= 2)
{
REGION_PARAM struDisplayRegion[MAX_DISPLAY_REGION];
int i;
memset(struDisplayRegion, 0, sizeof(struDisplayRegion));
for (i=0; i<MAX_DISPLAY_REGION; i++)
struDisplayRegion[i].color = RGB(i, i*8, i*16);
for (i=0; i<nDispNum/2; i++)
{
DLINK_SetDisplayStandard(2*i,StandardNTSC);
struDisplayRegion[0].left=0; struDisplayRegion[0].top=0; struDisplayRegion[0].width=352; struDisplayRegion[0].height=240;
struDisplayRegion[1].left=352; struDisplayRegion[1].top=0; struDisplayRegion[1].width=352; struDisplayRegion[1].height=240;
struDisplayRegion[2].left=0; struDisplayRegion[2].top=240; struDisplayRegion[2].width=352; struDisplayRegion[2].height=240;
struDisplayRegion[3].left=352; struDisplayRegion[3].top=240; struDisplayRegion[3].width=352; struDisplayRegion[3].height=240;
if (DLINK_SetDisplayRegion(2*i, 4, struDisplayRegion, 0) != HWERR_SUCCESS)
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "SetDisplayRegion!");
}
DLINK_SetDecoderVideoExtOutput(4*i, 0, 1, 2*i, 0, 0);
DLINK_SetDecoderVideoExtOutput(4*i+1, 0, 1, 2*i, 1, 0);
DLINK_SetDecoderVideoExtOutput(4*i+2, 0, 1, 2*i, 2, 0);
DLINK_SetDecoderVideoExtOutput(4*i+3, 0, 1, 2*i, 3, 0);
DLINK_SetDisplayStandard(2*i+1,StandardNTSC);
struDisplayRegion[0].left=0; struDisplayRegion[0].top=0; struDisplayRegion[0].width=704; struDisplayRegion[0].height=480;
if (DLINK_SetDisplayRegion(2*i+1, 1, struDisplayRegion, 0) != HWERR_SUCCESS)
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "SetDisplayRegion failed!");
}
DLINK_SetDecoderVideoExtOutput(4*i, 1, 1, 2*i+1, 0, 0);
}
}
}
else
{
nDispNum = DLINK_GetDisplayChannelCount();
if (nDispNum >= 2)
{
REGION_PARAM struDisplayRegion[MAX_DISPLAY_REGION];
int i;
memset(struDisplayRegion, 0, sizeof(struDisplayRegion));
for (i=0; i<MAX_DISPLAY_REGION; i++)
struDisplayRegion[i].color = RGB(i, i*8, i*16);
for (i=0; i<nDispNum/2; i++)
{
DLINK_SetDisplayStandard(2*i,StandardPAL);
struDisplayRegion[0].left=0; struDisplayRegion[0].top=0; struDisplayRegion[0].width=352; struDisplayRegion[0].height=288;
struDisplayRegion[1].left=352; struDisplayRegion[1].top=0; struDisplayRegion[1].width=352; struDisplayRegion[1].height=288;
struDisplayRegion[2].left=0; struDisplayRegion[2].top=288; struDisplayRegion[2].width=352; struDisplayRegion[2].height=288;
struDisplayRegion[3].left=352; struDisplayRegion[3].top=288; struDisplayRegion[3].width=352; struDisplayRegion[3].height=288;
if (DLINK_SetDisplayRegion(2*i, 4, struDisplayRegion, 0) != HWERR_SUCCESS)
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "SetDisplayRegion failed!");
}
DLINK_SetDecoderVideoExtOutput(4*i, 0, 1, 2*i, 0, 0);
DLINK_SetDecoderVideoExtOutput(4*i+1, 0, 1, 2*i, 1, 0);
DLINK_SetDecoderVideoExtOutput(4*i+2, 0, 1, 2*i, 2, 0);
DLINK_SetDecoderVideoExtOutput(4*i+3, 0, 1, 2*i, 3, 0);
DLINK_SetDisplayStandard(2*i+1,StandardPAL);
struDisplayRegion[0].left=0; struDisplayRegion[0].top=0; struDisplayRegion[0].width=704; struDisplayRegion[0].height=576;
if (DLINK_SetDisplayRegion(2*i+1, 1, struDisplayRegion, 0) != HWERR_SUCCESS)
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "SetDisplayRegion failed!");
}
DLINK_SetDecoderVideoExtOutput(4*i, 1, 1, 2*i+1, 0, 0);
}
}
}
if (m_iCardChanCount==1)
{
m_iCurWndNum =1;
m_comboWinNum.SetCurSel(0);
}
else if (m_iCardChanCount<=4)
{
m_iCurWndNum = 4;
m_comboWinNum.SetCurSel(1);
}
else if (m_iCardChanCount<=9)
{
m_iCurWndNum = 9;
m_comboWinNum.SetCurSel(2);
}
else
{
m_iCurWndNum = 16;
m_comboWinNum.SetCurSel(3);
}
m_comboWinNum.EnableWindow(FALSE);
return TRUE;
}
/*********************************************************
Function: InitGlobalSysInfo
Desc: initialize global system info
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::InitGlobalSysInfo()
{
InitHardDriver();
g_pMainDlg = this;
//initialize hardware decode background
g_hPlayHardBgBrush = ::CreateSolidBrush(COLORREF(0xff2200));//dark blue0xff2200
//initialize software decode background
g_hPlaySoftBgBrush = ::CreateSolidBrush(COLORREF(0xffffff));//white
if (g_struLocalParam.bUseCard)
{
if (InitDecodeCard())
{
g_bCardInit = TRUE;
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "InitDecodeCard success");
}
else
{
g_bCardInit = FALSE;
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "InitDecodeCard fail");
}
}
//get current system resolution
g_iCurScreenWidth = GetSystemMetrics(SM_CXSCREEN);
g_iCurScreenHeight = GetSystemMetrics(SM_CYSCREEN);
}
/*********************************************************
Function: GetVersionInfor
Desc: get version information
Input:
Output:
Return:
**********************************************************/
typedef DWORD (WINAPI *VGetFileVersionInfoSize)(LPSTR lptstrFilename, LPDWORD lpdwHandle);
typedef BOOL (WINAPI *VGetFileVersionInfo)(LPSTR lptstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData);
typedef BOOL(WINAPI *VVerQueryValue)(const LPVOID pBlock,LPSTR lpSubBlock,LPVOID * lplpBuffer, PUINT puLen);
VGetFileVersionInfoSize vgetsize;
VGetFileVersionInfo vfileinfo;
VVerQueryValue vqureyvalue;
void CClientDemoDlg::GetVersionInfor()
{
DWORD m_dwSize = 0;
HMODULE handle = LoadLibrary("version.dll"); //there is no this library on win2000
if (handle == NULL)
{
return;
}
vgetsize = (VGetFileVersionInfoSize)GetProcAddress(handle, "GetFileVersionInfoSizeA");
m_dwSize = GetLastError();
vfileinfo = (VGetFileVersionInfo)GetProcAddress(handle, "GetFileVersionInfoA");
vqureyvalue = (VVerQueryValue)GetProcAddress(handle, "VerQueryValueA");
char szInfo[128] = {0};
m_dwSize = vgetsize("HCNetSDK.dll", NULL);
if (m_dwSize > 0)
{
char * m_lpBuffer = new char[m_dwSize];
char *lpSDKVersion = NULL;
//Get the versioninformation block
BOOL bRet = vfileinfo("HCNetSDK.dll", 0, m_dwSize, m_lpBuffer);
struct LANGANDCODEPAGE {
WORD wLanguage;
WORD wCodePage;
} *lpTranslate;
DWORD cbTranslate = 0;
vqureyvalue(m_lpBuffer,
TEXT("\\VarFileInfo\\Translation"),
(LPVOID*)&lpTranslate,
(PUINT)&cbTranslate);
wsprintf(szInfo, TEXT( "\\StringFileInfo\\%04x%04x\\FileVersion"),
lpTranslate-> wLanguage,
lpTranslate-> wCodePage);
bRet = vqureyvalue(m_lpBuffer,
szInfo,
(void **) &lpSDKVersion,
NULL);
char * m_lpSDKBuild = NULL;
wsprintf(szInfo, TEXT( "\\StringFileInfo\\%04x%04x\\FileDescription"),
lpTranslate-> wLanguage,
lpTranslate-> wCodePage);
bRet = vqureyvalue(m_lpBuffer,
szInfo,
(void **) &m_lpSDKBuild,
NULL);
GetDlgItem(IDC_STATIC_DEMO_VERSION)->SetWindowText(m_lpSDKBuild);
AddLog(-1, OPERATION_SUCC_T, "FileVersion%s %s", lpSDKVersion, m_lpSDKBuild);
delete [] m_lpBuffer;
}
else
{
m_dwSize = GetLastError();
}
}
/*********************************************************
Function: InitMainWin
Desc: demo main window layout
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::InitMainWin()
{
m_iTreeWidth = 165; //device tree width
m_iRightWidth = 160; //PTZ pic box width
m_iFunBtnHeight = 85; //column height
m_iListLogHeight = 110 ;//list log height
char szLan[128] = {0};
m_listAlarmInfo.InsertColumn(0,"",LVCFMT_LEFT,0,-1);
g_StringLanType(szLan, "时间", "Time");
m_listAlarmInfo.InsertColumn(1, szLan,LVCFMT_LEFT,150);
g_StringLanType(szLan, "报警信息", "Alarm Info");
m_listAlarmInfo.InsertColumn(2, szLan,LVCFMT_LEFT,400);
g_StringLanType(szLan, "设备信息", "Device Info");
m_listAlarmInfo.InsertColumn(3, szLan,LVCFMT_LEFT,160);
m_listAlarmInfo.SetExtendedStyle(m_listAlarmInfo.GetExtendedStyle()|LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT|LVS_EX_SUBITEMIMAGES);
m_listAllLog.InsertColumn(0, "", LVCFMT_LEFT, 0, -1);
g_StringLanType(szLan, "时间", "Time");
m_listAllLog.InsertColumn(1, szLan, LVCFMT_LEFT, 120);
g_StringLanType(szLan, "状态", "State");
m_listAllLog.InsertColumn(2, szLan, LVCFMT_LEFT, 40);
g_StringLanType(szLan, "操作", "Operation");
m_listAllLog.InsertColumn(3, szLan, LVCFMT_LEFT, 300);
g_StringLanType(szLan, "设备信息", "Device Info");
m_listAllLog.InsertColumn(4,szLan,LVCFMT_LEFT,140);
g_StringLanType(szLan, "错误信息", "Error Info");
m_listAllLog.InsertColumn(5,szLan,LVCFMT_LEFT,80);
m_listAllLog.SetExtendedStyle(m_listAllLog.GetExtendedStyle()|LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT|LVS_EX_SUBITEMIMAGES);
if (g_bInSide)
{
m_comboWinNum.ResetContent();
m_comboWinNum.AddString("1");
m_comboWinNum.AddString("4");
m_comboWinNum.AddString("9");
m_comboWinNum.AddString("16");
m_comboWinNum.AddString("25");
/* m_comboWinNum.AddString("36");
m_comboWinNum.AddString("49");
m_comboWinNum.AddString("64");
m_comboWinNum.AddString("81");
m_comboWinNum.AddString("100");
m_comboWinNum.AddString("121");
m_comboWinNum.AddString("144");
m_comboWinNum.AddString("169");
m_comboWinNum.AddString("196");
m_comboWinNum.AddString("225");
m_comboWinNum.AddString("256");
*/ }
m_iSelListType = 0;//local log
((CButton *)GetDlgItem(IDC_RADIO_LOCAL_LOG))->SetCheck(TRUE);
((CButton *)GetDlgItem(IDC_RADIO_ALARM_INFO))->SetCheck(FALSE);
OnSelchangeComboListType();
MoveWindow(0, 0, DEMO_FULL_WIDTH, DEMO_FULL_HEIGHT, TRUE);
// MoveWindow(0, 0, GetSystemMetrics(SM_CXFULLSCREEN), GetSystemMetrics(SM_CYFULLSCREEN), TRUE);
GetVersionInfor();
CString csTemp = _T("");
DWORD dwVersion = NET_DVR_GetSDKBuildVersion();
csTemp.Format("HCNetSDK V%d.%d.%d.%d", (0xff000000 & dwVersion)>>24, (0x00ff0000 & dwVersion)>>16,\
(0x0000ff00 & dwVersion)>>8, (0x000000ff & dwVersion));//%.d,0x0000ff & dwVersion,build NO. do not expose
GetDlgItem(IDC_STATIC_SDK_VERSION)->SetWindowText(csTemp);
dwVersion = PlayM4_GetSdkVersion();
csTemp.Format("PlayCtrl V%d.%d.%d.%d", (0xff000000 & dwVersion)>>24, (0x00ff0000 & dwVersion)>>16,\
(0x0000ff00 & dwVersion)>>8, (0x000000ff & dwVersion));
GetDlgItem(IDC_STATIC_PLAYM4_VERSION)->SetWindowText(csTemp);
InitPreviewRect();//preview window, part of main window
}
/*********************************************************
Function: InitChildWindow
Desc: initialize child window
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::InitChildWindow(void)
{
for (int i = 0; i < MAX_OUTPUTS; i++)
{
g_dlgOutput[i].m_iSubWndIndex = i;
g_dlgOutput[i].Create(IDD_DLG_OUTPUT,this);
}
m_dlgRemoteCfg = new CDlgRemoteCfg;
m_dlgRemoteCfg->Create(IDD_DLG_REMOTE_CFG,this);
m_dlgRemoteCfg->ShowWindow(SW_HIDE);
m_dlgLocalCfg = new CDlgLocalConfig;
m_dlgLocalCfg->Create(IDD_DLG_LOCAL_CONFIG, this);
m_dlgLocalCfg->ShowWindow(SW_HIDE);
m_dlgIPAccess = new CDlgRemoteIPAccess;
m_dlgIPAccess->Create(IDD_DLG_REMOTE_IP_ACCESS_CFG, this);
m_dlgIPAccess->ShowWindow(SW_HIDE);
m_dlgHDConfig = new CDlgHardDiskCfg;
m_dlgHDConfig->Create(IDD_DLG_HARD_DISK_CFG, this);
m_dlgHDConfig->ShowWindow(SW_HIDE);
m_dlgConfigAll = new CDlgConfigAll;
m_dlgConfigAll->Create(IDD_DLG_CONFIG_ALL, this);
m_dlgConfigAll->ShowWindow(SW_HIDE);
m_dlgOutputCtrl = new CDlgOutputCtrl;
m_dlgOutputCtrl->Create(IDD_DLG_OUTPUT_CTRL, this);
m_dlgOutputCtrl->ShowWindow(SW_HIDE);
m_dlgPlayBack = new CDlgPlayBack;
m_dlgPlayBack->Create(IDD_DLG_PLAY_BACK, this);
m_dlgPlayBack->ShowWindow(SW_HIDE);
// m_pStreamIDDlg = new CDlgStreamID;
// m_pStreamIDDlg->Create(IDD_DLG_STREAM_ID, this);
// m_pStreamIDDlg->ShowWindow(SW_HIDE);
m_dlgBatchCfg = new CDlgBatchConfig;
m_dlgBatchCfg->Create(IDD_DLG_BATCH_CONFIG, this);
m_dlgBatchCfg->ShowWindow(SW_HIDE);
m_dlgProductCfg = new CDlgProductCfg;
m_dlgProductCfg->Create(IDD_DLG_PRODUCT_CFG,this);
m_dlgProductCfg->ShowWindow(SW_HIDE);
}
/*********************************************************
Function: CreateTree
Desc: create device tree
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::CreateTree(void)
{
m_treeDeviceList.DeleteAllItems();
char szLan[128] = {0};
g_StringLanType(szLan, "设备树(右击添加设备)", "Device Tree(Right Click to Add Device)");
HTREEITEM hRoot = m_treeDeviceList.InsertItem(szLan, TREE_ALL, TREE_ALL);
CString strTemp =_T("");
CString strChanTmp = _T("");
int i = 0;
int j = 0;
HTREEITEM hDevice = NULL;
HTREEITEM hChan = NULL;
for (i = 0; i < MAX_DEVICES; i++)
{
if (g_struDeviceInfo[i].iDeviceChanNum != -1)
{
strTemp.Format("%s", g_struDeviceInfo[i].chLocalNodeName);
hDevice = m_treeDeviceList.InsertItem(strTemp, g_struDeviceInfo[i].dwImageType, g_struDeviceInfo[i].dwImageType, hRoot);
m_treeDeviceList.SetItemData(hDevice, DEVICETYPE*1000 + g_struDeviceInfo[i].iDeviceIndex);
for (j=0; j< MAX_CHANNUM_V40; j++)
{
if (g_struDeviceInfo[i].pStruChanInfo[j].bEnable)
{
strChanTmp.Format("%s", g_struDeviceInfo[i].pStruChanInfo[j].chChanName);
hChan = m_treeDeviceList.InsertItem(strChanTmp, g_struDeviceInfo[i].pStruChanInfo[j].dwImageType, g_struDeviceInfo[i].pStruChanInfo[j].dwImageType, hDevice);
m_treeDeviceList.SetItemData(hChan,CHANNELTYPE * 1000 + g_struDeviceInfo[i].pStruChanInfo[j].iChanIndex);
}
else
{
g_struDeviceInfo[i].pStruChanInfo[j].iChanIndex = -1;
}
}
if (g_struDeviceInfo[i].lLoginID >= 0)
{
m_treeDeviceList.Expand(hDevice,TVE_EXPAND);
}
else
{
m_treeDeviceList.Expand(hDevice,TVE_COLLAPSE);
}
}
}
m_treeDeviceList.Expand(hRoot,TVE_EXPAND);
m_treeDeviceList.Expand(m_treeDeviceList.GetRootItem(),TVE_EXPAND);
}
/*********************************************************
Function: OnBnClickedBtnPreview
Desc: preview button response, switch to preview interface
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnPreview()
{
if (m_iMainType != PREVIEW_T)
{
//modify preview flag
m_iMainType = PREVIEW_T;
//hide configuration and button control
ConfigAllHide();
m_dlgPlayBack->HideAll();
if (g_struLocalParam.bUseCard)
{
if (!g_bCardInit)
{
if (InitDecodeCard())
{
g_bCardInit = TRUE;
}
else
{
g_bCardInit = FALSE;
}
}
}
else
{
if (g_bCardInit)
{
g_bCardInit = FALSE;
NET_DVR_ReleaseDevice_Card();
NET_DVR_ReleaseDDraw_Card();
}
}
PreviewReferShow(TRUE);
}
}
/*********************************************************
Function: LoopSvc
Desc: preview loop service
Input: none
Output: none
Return: none
**********************************************************/
void *LoopSvc(void *pParam)
{
int i = 0;
while (1)
{
for (i=0; i<g_struLocalParam.iCycleTime; i++)
{
Sleep(1000);
if (!g_struLocalParam.bCycling)
{
goto exitsvc;
}
}
g_pMainDlg->CyclePlayAllDevicesLogined();
}
exitsvc:
g_pMainDlg->StopPlayAll();
g_pMainDlg->ChangePlayBtnState();
return NULL;
}
/*********************************************************
Function: StartPlayAll
Desc: play all, only log-in device
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::StartPlayAll(void)
{
//stop all play window
StopPlayAll();
//get and save all surveillance points that can be previewed
int i = 0;
int j = 0;
int iFirstPlayNum = 0;//first surveillance point
int iDeviceIndex = -1;
int iChanIndex = -1;
int iSurveillanceNumLeft = 0;
g_nSurveillanceTotalNum = 0;
//get current surveillance to play
for (i = 0; i < MAX_DEVICES; i++)
{
if (g_struDeviceInfo[i].byURL && g_struDeviceInfo[i].lLoginID != -1)
{
//配置使用URL预览时,在设备没有通道时,使能第一个通道作为预览通道
g_struDeviceInfo[i].pStruChanInfo[0].bEnable = TRUE;
if (g_struDeviceInfo[i].pStruChanInfo[0].iChannelNO == -1)
{
g_struDeviceInfo[i].pStruChanInfo[0].iChannelNO = 1;
}
}
if ((-1 != g_struDeviceInfo[i].iDeviceChanNum || g_struDeviceInfo[i].byURL) && g_struDeviceInfo[i].lLoginID != -1)
{
for (j = 0; j < MAX_CHANNUM_V30; j++)
{
if (g_struDeviceInfo[i].pStruChanInfo[j].bEnable)
{
g_struPlayAllInfo[g_nSurveillanceTotalNum].iDeviceIndex = i;//serial starts from 0
g_struPlayAllInfo[g_nSurveillanceTotalNum].iChanIndex = j;
g_nSurveillanceTotalNum ++;
}
}
}
}
if (g_nSurveillanceTotalNum == 0)
{
return;//no monitoring points that can be played
}
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "StartPlayAll:Total Chan Number= %d", g_nSurveillanceTotalNum);
if (g_nSurveillanceTotalNum > m_iCurWndNum)
{//first group of mornitoring points
iFirstPlayNum = m_iCurWndNum;
iSurveillanceNumLeft = g_nSurveillanceTotalNum - m_iCurWndNum;
g_iNextSurveillanceIndex = m_iCurWndNum;
g_struLocalParam.bNextPage = TRUE;
g_struLocalParam.bFrontPage =FALSE ;
}
else//only one group
{
iFirstPlayNum = g_nSurveillanceTotalNum;
iSurveillanceNumLeft = 0;
g_iNextSurveillanceIndex = g_nSurveillanceTotalNum;
g_struLocalParam.bFrontPage = FALSE;
g_struLocalParam.bNextPage = FALSE;
}
//preview first group
for (i = 0; i < iFirstPlayNum; i++)
{
iDeviceIndex = g_struPlayAllInfo[i].iDeviceIndex;
iChanIndex = g_struPlayAllInfo[i].iChanIndex;
//没有通道设置了URL方式预览
if (g_struDeviceInfo[iDeviceIndex].byURL && g_nSurveillanceTotalNum == 1)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[0].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[0].iChanIndex = 0;
}
g_dlgOutput[i].StartPlay(&g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex], GetChanItem(iDeviceIndex, iChanIndex));
Sleep(10);
}
//cycle play
if (g_struLocalParam.bCyclePlay)
{
if (!g_struLocalParam.bCycling)
{
g_struLocalParam.bCycling = TRUE;
g_struLocalParam.bPaused = FALSE;
_beginthread((void (__cdecl *)(void *))LoopSvc, 0, NULL);
}
// if (g_pCycleTimer == NULL)
// {
// g_pCycleTimer = SetTimer(CYCLE_PREVIEW_TIMER, g_struLocalParam.iCycleTime*1000, NULL);
// }
// g_struLocalParam.bCycling = TRUE;
// g_struLocalParam.bPaused = FALSE;
}
if (iSurveillanceNumLeft != 0)
{
g_struLocalParam.bNextPage = TRUE;
}
else
{
g_struLocalParam.bNextPage = FALSE;
}
g_struLocalParam.bFrontPage = FALSE;
g_bPlayAllDevice = TRUE;
ChangePlayBtnState();
}
/*********************************************************
Function: OnBnClickedBtnPlay
Desc: play all or stop all
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnPlay()
{
if (IsPlaying())//stop all playing windows
{
if (!g_struLocalParam.bCycling)
{
StopPlayAll();
ChangePlayBtnState();
}
g_struLocalParam.bPaused = TRUE;
g_bPlayAllDevice = FALSE;
g_struLocalParam.bCycling = FALSE;
// if (g_pCycleTimer != NULL)
// KillTimer(CYCLE_PREVIEW_TIMER);
// g_pCycleTimer = NULL;
// }
return;
}
StartPlayAll();
}
/*********************************************************
Function: OnBnClickedBtnMakeIframe
Desc: mandatory I frame
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnMakeIframe()
{
int i = m_iCurWndIndex;
if (g_dlgOutput[i].m_lPlayHandle < 0)
{
return;
}
int iDeviceIndex = g_dlgOutput[i].m_struChanInfo.iDeviceIndex;
int iChanIndex = g_dlgOutput[i].m_struChanInfo.iChanIndex;
if (iDeviceIndex == -1 || iChanIndex == -1)
{
return;
}
if (iChanIndex < ZERO_CHAN_INDEX) // 500 以上为零通道
{
if (((g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].dwProtocol>>31)&0x1) == 0)
{
//if (!NET_DVR_MakeKeyFrame(g_struDeviceInfo[iDeviceIndex].lLoginID, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].iChannelNO))
memset(&m_struIFrame, 0, sizeof(m_struIFrame));
m_struIFrame.dwSize = sizeof(NET_DVR_I_FRAME);
if (g_struDeviceInfo[iDeviceIndex].byMirrorChanNum > 0 && iChanIndex >= MIRROR_CHAN_INDEX)
{
m_struIFrame.dwChan = g_struDeviceInfo[iDeviceIndex].struMirrorChan[iChanIndex - MIRROR_CHAN_INDEX].iChannelNO;
}
else
{
m_struIFrame.dwChan = g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].iChannelNO;
}
m_struIFrame.byStreamType = g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].dwStreamType;
if(!NET_DVR_RemoteControl(g_struDeviceInfo[iDeviceIndex].lLoginID, NET_DVR_MAKE_I_FRAME, &m_struIFrame, sizeof(m_struIFrame)))
{
AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_MAKE_I_FRAME");
char szLan[128] = {0};
g_StringLanType(szLan, "强制I帧失败!", "Make I Frame Failed");
AfxMessageBox(szLan);
}
else
{
AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_MAKE_I_FRAME");
}
}
else
{
//if (!NET_DVR_MakeKeyFrameSub(g_struDeviceInfo[iDeviceIndex].lLoginID, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].iChannelNO))
memset(&m_struIFrame, 0, sizeof(m_struIFrame));
m_struIFrame.dwSize = sizeof(NET_DVR_I_FRAME);
if (g_struDeviceInfo[iDeviceIndex].byMirrorChanNum > 0 && iChanIndex >= MIRROR_CHAN_INDEX)
{
m_struIFrame.dwChan = g_struDeviceInfo[iDeviceIndex].struMirrorChan[iChanIndex - MIRROR_CHAN_INDEX].iChannelNO;
}
else
{
m_struIFrame.dwChan = g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].iChannelNO;
}
m_struIFrame.byStreamType = g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].dwStreamType;
if(!NET_DVR_RemoteControl(g_struDeviceInfo[iDeviceIndex].lLoginID, NET_DVR_MAKE_I_FRAME, &m_struIFrame, sizeof(m_struIFrame)))
{
AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_MAKE_I_FRAME");
char szLan[128] = {0};
g_StringLanType(szLan, "强制I帧失败!", "Make I Frame Failed");
AfxMessageBox(szLan);
}
else
{
AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_MAKE_I_FRAME");
}
}
}
else
{
int iZeroChannel = iChanIndex - ZERO_CHAN_INDEX + g_struDeviceInfo[iDeviceIndex].iStartChan;
if (!NET_DVR_ZeroMakeKeyFrame(g_struDeviceInfo[iDeviceIndex].lLoginID, iChanIndex - ZERO_CHAN_INDEX + g_struDeviceInfo[iDeviceIndex].iStartChan))
{
AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_ZeroMakeKeyFrame Chan[%d]", iZeroChannel);
}
else
{
AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_ZeroMakeKeyFrame Chan[%d]", iZeroChannel);
}
}
}
/*********************************************************
Function: PreviewReferShow
Desc: display or hide control and dialog related to preview
Input: bShow,TRUE,display,FALSE,hide;
Output:
Return:
**********************************************************/
void CClientDemoDlg::PreviewReferShow(BOOL bShow)
{
int iShowStat = bShow?SW_SHOW:SW_HIDE;
if (bShow)
{
if (g_struLocalParam.bUseCard)
{
NET_DVR_ClearSurface_Card();
}
if (g_struLocalParam.bEnlarged)
{
ArrangeOutputs(1);
}
else
{
ArrangeOutputs(m_iCurWndNum);
}
}
else
{
if (g_struLocalParam.bUseCard)
{
NET_DVR_ClearSurface_Card();
}
for (int i=0; i<MAX_OUTPUTS; i++)
{
g_dlgOutput[i].ShowWindow(SW_HIDE);
}
}
GetDlgItem(IDC_STATIC_PREVIEWBG)->ShowWindow(iShowStat);
//GetDlgItem(IDC_STATIC_PREVIEWBG)->Invalidate(!bShow);
GetDlgItem(IDC_BTN_PLAY)->ShowWindow(iShowStat);
GetDlgItem(IDC_BTN_RECORD)->ShowWindow(iShowStat);
GetDlgItem(IDC_BTN_PICTURE_SNATCH)->ShowWindow(iShowStat);
GetDlgItem(IDC_BTN_MAKE_IFRAME)->ShowWindow(iShowStat);
GetDlgItem(IDC_STATIC_PREVIEW1)->ShowWindow(iShowStat);
GetDlgItem(IDC_STATIC_PREVIEW2)->ShowWindow(iShowStat);
GetDlgItem(IDC_STATIC_PREVIEW3)->ShowWindow(iShowStat);
GetDlgItem(IDC_STATIC_NETDELAY)->ShowWindow(iShowStat);
GetDlgItem(IDC_STATIC_WIN_NUM)->ShowWindow(iShowStat);
GetDlgItem(IDC_COMBONETDELAY)->ShowWindow(iShowStat);
GetDlgItem(IDC_COMBO_WNDNUM)->ShowWindow(iShowStat);
m_dlgOutputCtrl->ShowWindow(iShowStat);
}
/*********************************************************
Function: InitPreviewRect
Desc: initialize preview area
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::InitPreviewRect()
{
m_rectPreviewBG.top = m_iFunBtnHeight;
m_rectPreviewBG.left = m_iTreeWidth;
m_rectPreviewBG.right = DEMO_FULL_WIDTH - m_iRightWidth;
m_rectPreviewBG.bottom = m_rectPreviewBG.Width()*3/4 + m_iFunBtnHeight+4;//+4
m_rectRightArea.top = m_iFunBtnHeight - 3;
m_rectRightArea.left = DEMO_FULL_WIDTH - m_iRightWidth + 5;//
m_rectRightArea.right = DEMO_FULL_WIDTH;//
m_rectRightArea.bottom = m_rectPreviewBG.Width()*3/4 + m_iFunBtnHeight + 55; //+55button height
GetDlgItem(IDC_STATIC_PREVIEWBG)->MoveWindow(&m_rectPreviewBG,TRUE);
m_dlgOutputCtrl->MoveWindow(&m_rectRightArea,TRUE);
m_dlgOutputCtrl->ShowWindow(SW_SHOW);
if (!g_struLocalParam.bUseCard)
{
m_iCurWndNum = 4;//default window number is 4
m_comboWinNum.SetCurSel(1);
}
m_comboNetDelayBufNum.SetCurSel(1);
//output box layout
ArrangeOutputs(m_iCurWndNum);//
}
/*********************************************************
Function: LoadTreeImage
Desc: load tree iamge
Input:
Output:
Return:
**********************************************************/
#define MAX_BMPS 14
void CClientDemoDlg::LoadTreeImage(void)
{
CBitmap cBmp[MAX_BMPS];
m_imageTreeList.Create(16,16,ILC_COLOR32 | ILC_MASK,1,1);
cBmp[TREE_ALL].LoadBitmap(IDB_BITMAP_TREE);
m_imageTreeList.Add(&cBmp[TREE_ALL],RGB(1,1,1));
cBmp[DEVICE_LOGOUT].LoadBitmap(IDB_BITMAP_LOGOUT);
m_imageTreeList.Add(&cBmp[DEVICE_LOGOUT],RGB(1,1,1));
cBmp[DEVICE_LOGIN].LoadBitmap(IDB_BITMAP_LOGIN);
m_imageTreeList.Add(&cBmp[DEVICE_LOGIN],RGB(1,1,1));
cBmp[DEVICE_FORTIFY].LoadBitmap(IDB_BITMAP_FORTIFY);
m_imageTreeList.Add(&cBmp[DEVICE_FORTIFY],RGB(1,1,1));
cBmp[DEVICE_ALARM].LoadBitmap(IDB_BITMAP_DEV_ALARM);
m_imageTreeList.Add(&cBmp[DEVICE_ALARM],RGB(1,1,1));
cBmp[DEVICE_FORTIFY_ALARM].LoadBitmap(IDB_BITMAP_FORTIFY_ALARM);
m_imageTreeList.Add(&cBmp[DEVICE_FORTIFY_ALARM],RGB(1,1,1));
cBmp[CHAN_ORIGINAL].LoadBitmap(IDB_BITMAP_CAMERA);
m_imageTreeList.Add(&cBmp[CHAN_ORIGINAL],RGB(1,1,1));
cBmp[CHAN_PLAY].LoadBitmap(IDB_BITMAP_PLAY);
m_imageTreeList.Add(&cBmp[CHAN_PLAY],RGB(1,1,1));
cBmp[CHAN_RECORD].LoadBitmap(IDB_BITMAP_REC);
m_imageTreeList.Add(&cBmp[CHAN_RECORD],RGB(1,1,1));
cBmp[CHAN_PLAY_RECORD].LoadBitmap(IDB_BITMAP_PLAYANDREC);
m_imageTreeList.Add(&cBmp[CHAN_PLAY_RECORD],RGB(1,1,1));
cBmp[CHAN_ALARM].LoadBitmap(IDB_BITMAP_ALARM);
m_imageTreeList.Add(&cBmp[CHAN_ALARM],RGB(1,1,1));
cBmp[CHAN_PLAY_ALARM].LoadBitmap(IDB_BITMAP_PLAY_ALARM);
m_imageTreeList.Add(&cBmp[CHAN_PLAY_ALARM],RGB(1,1,1));
cBmp[CHAN_PLAY_RECORD_ALARM].LoadBitmap(IDB_BITMAP_P_R_A);
m_imageTreeList.Add(&cBmp[CHAN_PLAY_RECORD_ALARM],RGB(1,1,1));
cBmp[CHAN_OFF_LINE].LoadBitmap(IDB_BITMAP_CHAN_OFF);
m_imageTreeList.Add(&cBmp[CHAN_OFF_LINE],RGB(1,1,1));
m_treeDeviceList.SetImageList(&m_imageTreeList, LVSIL_NORMAL);
}
/*********************************************************
Function: IsPlaying
Desc: whether any window is previewing
Input:
Output:
Return:
**********************************************************/
BOOL CClientDemoDlg::IsPlaying(void)
{
if (m_iMainType == PREVIEW_T)
{
for (int i = 0; i < MAX_OUTPUTS; i ++)
{
if (g_dlgOutput[i].m_lPlayHandle >= 0)
{
return TRUE;
}
}
}
return FALSE;
}
/*********************************************************
Function: ArrangeOutputs
Desc: output layout
Input: iNumber, current output number
Output:
Return:
**********************************************************/
void CClientDemoDlg::ArrangeOutputs(int iNumber)
{
if (iNumber == 0)
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "ArrangeOutputs number=0!");
return;
}
int i = 0;
CRect crect;
int iSqrtNum = 0;//sqrt value of window number
int iWidth = 0;//window width
int iHeight = 0;//window height
iSqrtNum = (int)sqrt((double)iNumber);
for (i = 0;i < MAX_OUTPUTS;i++)
{
g_dlgOutput[i].ShowWindow(SW_HIDE);
}
if (g_struLocalParam.bMultiScreen)
{//muti-window full screen
iWidth = (g_iCurScreenWidth - OUTPUT_INTERVAL*(iSqrtNum-1))/iSqrtNum;
iHeight = (g_iCurScreenHeight - OUTPUT_INTERVAL*(iSqrtNum-1))/iSqrtNum;
for (i = 0; i < iNumber; i++)
{
g_dlgOutput[i].MoveWindow((i%iSqrtNum)*(iWidth+OUTPUT_INTERVAL),(i/iSqrtNum)*(iHeight+OUTPUT_INTERVAL),iWidth,iHeight,TRUE);
g_dlgOutput[i].m_struCardPlayParam.nLeft = (i%iSqrtNum)*(iWidth+OUTPUT_INTERVAL);
g_dlgOutput[i].m_struCardPlayParam.nTop = (i/iSqrtNum)*(iHeight+OUTPUT_INTERVAL);
g_dlgOutput[i].m_struCardPlayParam.nWidth = iWidth;
g_dlgOutput[i].m_struCardPlayParam.nHeight = iHeight;
g_dlgOutput[i].ShowWindow(SW_SHOW);
}
}
else
{
iWidth = (m_rectPreviewBG.Width()-OUTPUT_INTERVAL*(iSqrtNum-1))/iSqrtNum;//a single pic width in partition
iHeight = (m_rectPreviewBG.Height()-OUTPUT_INTERVAL*(iSqrtNum-1))/iSqrtNum;//a single pic height in partition
int iPlayIndex = 0;
for (i = 0; i < iNumber; i++)
{
if (g_struLocalParam.bEnlarged)
{//double click to zoom some pic, iNumber = 1
iPlayIndex = m_iCurWndIndex;
}
else
{
iPlayIndex = i;
}
g_dlgOutput[iPlayIndex].MoveWindow(m_iTreeWidth + (i%iSqrtNum)*(iWidth+OUTPUT_INTERVAL),\
m_iFunBtnHeight+(i/iSqrtNum)*(iHeight+OUTPUT_INTERVAL),iWidth,iHeight,TRUE);
g_dlgOutput[iPlayIndex].m_struCardPlayParam.nLeft = (i%iSqrtNum)*(iWidth+OUTPUT_INTERVAL);//m_iTreeWidth+
g_dlgOutput[iPlayIndex].m_struCardPlayParam.nTop = (i/iSqrtNum)*(iHeight+OUTPUT_INTERVAL);//m_iFunBtnHeight+
g_dlgOutput[iPlayIndex].m_struCardPlayParam.nWidth = iWidth;
g_dlgOutput[iPlayIndex].m_struCardPlayParam.nHeight = iHeight;
g_dlgOutput[iPlayIndex].ShowWindow(SW_SHOW);
g_dlgOutput[iPlayIndex].DrawOutputBorder();
}
}
//hardware decode window set
NET_DVR_DISPLAY_PARA struDisPlayParam;
if (g_struLocalParam.bUseCard)
{
//clear and hide previous pic
NET_DVR_ClearSurface_Card();
for (i = 0; i < MAX_OUTPUTS; i++)
{
struDisPlayParam.bToScreen = 0;
struDisPlayParam.bToVideoOut = 1;
struDisPlayParam.nLeft = g_dlgOutput[i].m_struCardPlayParam.nLeft;
struDisPlayParam.nTop = g_dlgOutput[i].m_struCardPlayParam.nTop;
struDisPlayParam.nWidth = g_dlgOutput[i].m_struCardPlayParam.nWidth;
struDisPlayParam.nHeight = g_dlgOutput[i].m_struCardPlayParam.nHeight;
NET_DVR_ResetPara_Card(g_dlgOutput[i].m_lPlayHandle,&struDisPlayParam);
}
if (g_struLocalParam.bMultiScreen)
{
for (i = 0; i < m_iCurWndNum; i++)
{
struDisPlayParam.bToScreen = 1;
struDisPlayParam.bToVideoOut = 1;
struDisPlayParam.nLeft = g_dlgOutput[i].m_struCardPlayParam.nLeft;
struDisPlayParam.nTop = g_dlgOutput[i].m_struCardPlayParam.nTop;
struDisPlayParam.nWidth = g_dlgOutput[i].m_struCardPlayParam.nWidth;
struDisPlayParam.nHeight = g_dlgOutput[i].m_struCardPlayParam.nHeight;
NET_DVR_ResetPara_Card(g_dlgOutput[i].m_lPlayHandle,&struDisPlayParam);
}
}
else
{
if (iNumber == 1)
{//single channel hardware decode or single window zoom
struDisPlayParam.bToScreen = 1;
struDisPlayParam.bToVideoOut = 1;
struDisPlayParam.nLeft = g_dlgOutput[m_iCurWndIndex].m_struCardPlayParam.nLeft;
struDisPlayParam.nTop = g_dlgOutput[m_iCurWndIndex].m_struCardPlayParam.nTop;
struDisPlayParam.nWidth = g_dlgOutput[m_iCurWndIndex].m_struCardPlayParam.nWidth;
struDisPlayParam.nHeight = g_dlgOutput[m_iCurWndIndex].m_struCardPlayParam.nHeight;
NET_DVR_ResetPara_Card(g_dlgOutput[m_iCurWndIndex].m_lPlayHandle,&struDisPlayParam);
}
else
{//narrow
for (i = 0; i < iNumber; i++)
{
struDisPlayParam.bToScreen = 1;
struDisPlayParam.bToVideoOut = 1;
struDisPlayParam.nLeft = g_dlgOutput[i].m_struCardPlayParam.nLeft;
struDisPlayParam.nTop = g_dlgOutput[i].m_struCardPlayParam.nTop;
struDisPlayParam.nWidth = g_dlgOutput[i].m_struCardPlayParam.nWidth;
struDisPlayParam.nHeight = g_dlgOutput[i].m_struCardPlayParam.nHeight;
NET_DVR_ResetPara_Card(g_dlgOutput[i].m_lPlayHandle,&struDisPlayParam);
}
}
}
}
}
/*********************************************************
Function: FullScreen
Desc: display/hide main control while single or multiple pic preview in full screen
Input: bFullScreen: TRUE, full screen, hide some control, FALSE, recover display control and previous pic
Output:
Return:
**********************************************************/
void CClientDemoDlg::FullScreen(BOOL bFullScreen)
{
int iShowStat = bFullScreen?SW_HIDE:SW_SHOW;
m_treeDeviceList.ShowWindow(iShowStat);
GetDlgItem(IDC_BTN_LOG_SAVE)->ShowWindow(iShowStat);
GetDlgItem(IDC_RADIO_LOCAL_LOG)->ShowWindow(iShowStat);
GetDlgItem(IDC_RADIO_ALARM_INFO)->ShowWindow(iShowStat);
// GetDlgItem(IDC_COMBO_LIST_TYPE)->ShowWindow(iShowStat);
// GetDlgItem(IDC_STATIC_LIST_TYPE)->ShowWindow(iShowStat);
GetDlgItem(IDC_BTN_LOG_CLEAR)->ShowWindow(iShowStat);
GetDlgItem(IDC_BTN_LOG_CONFIG)->ShowWindow(iShowStat);
GetDlgItem(IDC_STATIC_MAIN)->ShowWindow(iShowStat);
GetDlgItem(IDC_BTN_CONFIG)->ShowWindow(iShowStat);
GetDlgItem(IDC_BTN_PREVIEW)->ShowWindow(iShowStat);
GetDlgItem(IDC_BTN_PLAY_BACK)->ShowWindow(iShowStat);
//GetDlgItem(IDC_BTN_MANAGE)->ShowWindow(iShowStat);
//GetDlgItem(IDC_BTN_ELSE)->ShowWindow(iShowStat);
GetDlgItem(IDC_BTN_EXIT)->ShowWindow(iShowStat);
GetDlgItem(IDC_STATIC_VERSION)->ShowWindow(iShowStat);
//GetDlgItem(IDC_STATIC_SYS)->ShowWindow(iShowStat);
GetDlgItem(IDC_STATIC_DEMO_VERSION)->ShowWindow(iShowStat);
GetDlgItem(IDC_STATIC_SDK_VERSION)->ShowWindow(iShowStat);
GetDlgItem(IDC_STATIC_PLAYM4_VERSION)->ShowWindow(iShowStat);
if (bFullScreen)
{
//for full screen while backplay
GetWindowPlacement(&m_struOldWndpl);
CRect rectWholeDlg;//entire client(including title bar)
CRect rectClient;//client area(not including title bar)
CRect rectFullScreen;
GetWindowRect(&rectWholeDlg);
RepositionBars(0, 0xffff, AFX_IDW_PANE_FIRST, reposQuery, &rectClient);
ClientToScreen(&rectClient);
rectFullScreen.left = rectWholeDlg.left-rectClient.left;
rectFullScreen.top = rectWholeDlg.top-rectClient.top;
rectFullScreen.right = rectWholeDlg.right+g_iCurScreenWidth - rectClient.right;
rectFullScreen.bottom = rectWholeDlg.bottom+g_iCurScreenHeight - rectClient.bottom;
//enter into full screen;
WINDOWPLACEMENT struWndpl;
struWndpl.length = sizeof(WINDOWPLACEMENT);
struWndpl.flags = 0;
struWndpl.showCmd = SW_SHOWNORMAL;
struWndpl.rcNormalPosition = rectFullScreen;
SetWindowPlacement(&struWndpl);
}
else
{
SetWindowPlacement(&m_struOldWndpl);
}
if (m_iMainType == PREVIEW_T)//dealing while preview
{
//refresh backgroud box
if (bFullScreen)
{
GetDlgItem(IDC_STATIC_PREVIEWBG)->MoveWindow(0,0,g_iCurScreenWidth,g_iCurScreenHeight,true);
}
else
{
GetDlgItem(IDC_STATIC_PREVIEWBG)->MoveWindow(&m_rectPreviewBG,true);
}
PreviewReferShow(!bFullScreen);
GetDlgItem(IDC_STATIC_PREVIEWBG)->ShowWindow(SW_SHOW);
if (g_struLocalParam.bFullScreen)
{
if (g_struLocalParam.bUseCard)
{
NET_DVR_DISPLAY_PARA struDisPlayParam;
struDisPlayParam.bToVideoOut = 1;
struDisPlayParam.bToScreen = 1;
struDisPlayParam.nLeft = 0;
struDisPlayParam.nTop = 0;
struDisPlayParam.nWidth = g_iCurScreenWidth;
struDisPlayParam.nHeight = g_iCurScreenHeight;
NET_DVR_ResetPara_Card(g_dlgOutput[m_iCurWndIndex].m_lPlayHandle,&struDisPlayParam);
g_dlgOutput[m_iCurWndIndex].MoveWindow(0,0,g_iCurScreenWidth, g_iCurScreenHeight, TRUE);
g_dlgOutput[m_iCurWndIndex].ShowWindow(SW_SHOW);
}
else
{
g_dlgOutput[m_iCurWndIndex].MoveWindow(0,0,g_iCurScreenWidth, g_iCurScreenHeight, TRUE);
g_dlgOutput[m_iCurWndIndex].ShowWindow(SW_SHOW);
}
}
}
if (bFullScreen)
{
m_listAlarmInfo.ShowWindow(SW_HIDE);
m_listAllLog.ShowWindow(SW_HIDE);
}
else
{
OnSelchangeComboListType();
}
}
/*********************************************************
Function: OnNMClickTreeDeviceList
Desc: click tree node response function, type of node; device node, log in operation, clear device and its related alarm
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnNMClickTreeDeviceList(NMHDR *pNMHDR, LRESULT *pResult)
{
//get node handle through mouse position
CPoint pt(0,0);
GetCursorPos(&pt);
CRect rect(0,0,0,0);
ScreenToClient(&pt);
GetDlgItem(IDC_TREE_DEVICE_LIST)->GetWindowRect(&rect);
ScreenToClient(&rect);
pt.x = pt.x-rect.left;
pt.y = pt.y-rect.top;
UINT uFlags = 0;
HTREEITEM hSelect = m_treeDeviceList.HitTest(pt,&uFlags);
if (hSelect == NULL)
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "please click the right node!");
return;
}
BOOL bLogined = FALSE;
DWORD dwNoteData = m_treeDeviceList.GetItemData(hSelect);
int iType = dwNoteData/1000;
int iIndex = dwNoteData%1000;
if (DEVICETYPE == iType)
{
m_iCurDeviceIndex = iIndex;
m_hCurDeviceItem = hSelect;
m_iCurChanIndex = -1;
m_hCurChanItem = NULL;
bLogined = DoLogin(m_iCurDeviceIndex, hSelect);
}
else if (CHANNELTYPE == iType)
{
m_iCurChanIndex = iIndex;
m_hCurChanItem = hSelect;
HTREEITEM hParent = m_treeDeviceList.GetParentItem(hSelect);
if (hParent != NULL)
{
dwNoteData = m_treeDeviceList.GetItemData(hParent);
iType = dwNoteData/1000;
iIndex = dwNoteData%1000;
if (DEVICETYPE == iType)
{
m_iCurDeviceIndex = iIndex;
m_hCurDeviceItem = hParent;
bLogined = DoLogin(m_iCurDeviceIndex, hParent);
}
}
}
else
{
m_iCurDeviceIndex = -1;
m_hCurDeviceItem = NULL;
m_iCurChanIndex = -1;
m_hCurChanItem = NULL;
}
if (m_iMainType == CONFIG_ALL_T)
{
m_dlgConfigAll->ConfigWndUpdate();
}
else if (m_iMainType == PLAY_BACK_T)
{
m_dlgPlayBack->PlayBackWinUpdate();
}
else if (m_iMainType == PRODUCT_RELATE_T)
{
m_dlgProductCfg->UpdateWindowParam(GetCurDeviceIndex(),GetCurChanIndex());
}
//clear alarm status on manual
if (bLogined)
{
ManualClearAlarm(m_iCurDeviceIndex, m_iCurChanIndex);
}
*pResult = 0;
}
/*********************************************************
Function: OnNMDblclkTreeDeviceList
Desc: double click tree node response function, play one channel or whole device
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnNMDblclkTreeDeviceList(NMHDR *pNMHDR, LRESULT *pResult)
{
HTREEITEM hSelect = m_treeDeviceList.GetSelectedItem();
if (NULL == hSelect || m_iMainType != PREVIEW_T)//it works to double click device tree only while preview
{
return;
}
if (g_bPlayAllDevice)//disable to single designated play while all play
{
char szLan[128] = {0};
g_StringLanType(szLan, "请先停止全部播放", "Please stop all play first");
AfxMessageBox(szLan);
return;
}
DWORD dwNodeData = (DWORD)m_treeDeviceList.GetItemData(hSelect);
HTREEITEM hParent = NULL;
int iType = dwNodeData/1000;
int iIndex = dwNodeData%1000;
int iDeviceIndex = GetCurDeviceIndex();
switch (iType)
{
case TREE_ALL_T:
DblAllTree();
break;
case DEVICETYPE:
m_iCurDeviceIndex = iIndex;
m_hCurDeviceItem = hSelect;
m_iCurChanIndex = -1;
m_hCurChanItem = NULL;
if (GetCurDeviceIndex() != -1)
{
DblPlayDevice(m_iCurDeviceIndex, m_iCurWndIndex);
}
m_treeDeviceList.Expand(hSelect, TVE_COLLAPSE);//expend reverse operation
// m_treeDeviceList.Expand(hSelect,TVE_EXPAND);
break;
case CHANNELTYPE: //double click channel
m_iCurChanIndex = iIndex;
m_hCurChanItem = hSelect;
hParent = m_treeDeviceList.GetParentItem(hSelect);
if (hParent != NULL)
{
if (DEVICETYPE == m_treeDeviceList.GetItemData(hParent)/1000)
{
m_iCurDeviceIndex = m_treeDeviceList.GetItemData(hParent)%1000;
m_hCurDeviceItem = hParent;
}
}
if (m_iCurDeviceIndex >= 0)
{
if (iIndex < MIRROR_CHAN_INDEX)
{
DblPlayChan(m_iCurDeviceIndex,iIndex,hSelect);
}
else if (iIndex < ZERO_CHAN_INDEX)
{
PlayMirrorChan(m_iCurDeviceIndex,iIndex,hSelect);
}
else
{
PlayZeroChan(m_iCurDeviceIndex,iIndex,hSelect);
}
}
break;
default:
{
m_iCurChanIndex = -1;
m_hCurChanItem = NULL;
m_iCurDeviceIndex = -1;
m_hCurDeviceItem = NULL;
}
break;
}
*pResult = 0;
}
/*********************************************************
Function: OnNMRclickTreeDeviceList
Desc: right-click tree node, pop up related menu
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnNMRclickTreeDeviceList(NMHDR *pNMHDR, LRESULT *pResult)
{
CMenu pMenu;
HTREEITEM hParent=NULL;
CPoint pt(0,0);
GetCursorPos(&pt);
HTREEITEM hRoot = m_treeDeviceList.GetRootItem();
if (hRoot == NULL)
{
if (!pMenu.LoadMenu(IDR_MENU_TREE_ALL))
{
return;
}
}
else
{
CRect rect(0,0,0,0);
ScreenToClient(&pt);
GetDlgItem(IDC_TREE_DEVICE_LIST)->GetWindowRect(&rect);
ScreenToClient(&rect);
pt.x = pt.x-rect.left;
pt.y = pt.y-rect.top;
//while select first node or blank
//HTREEITEM hSelect = m_treeDeviceList.GetSelectedItem();
UINT uFlags = 0;
HTREEITEM hSelect = m_treeDeviceList.HitTest(pt,&uFlags);
if (hSelect == NULL )//|| m_iMainType != PREVIEW_T
{
return;
}
m_treeDeviceList.SelectItem(hSelect);
int iType = int(m_treeDeviceList.GetItemData(hSelect) / 1000);
switch (iType)
{
case TREE_ALL_T:
// if (!pMenu.LoadMenu(IDR_MENU_TREE_ALL))
// {
// return;
// }
OnMenuDeviceAdd();
return;
break;
case DEVICETYPE:
m_iCurDeviceIndex = int(m_treeDeviceList.GetItemData(hSelect) % 1000);
m_hCurDeviceItem = hSelect;
m_iCurChanIndex = -1;
m_hCurChanItem = NULL;
if (!pMenu.LoadMenu(IDR_MENU_DEVICE))
{
return;
}
break;
case CHANNELTYPE:
m_iCurChanIndex = int(m_treeDeviceList.GetItemData(hSelect) % 1000);
m_hCurChanItem = hSelect;
hParent = m_treeDeviceList.GetParentItem(hSelect);
if (hParent != NULL)
{
if (DEVICETYPE == m_treeDeviceList.GetItemData(hParent)/1000)
{
m_iCurDeviceIndex = m_treeDeviceList.GetItemData(hParent)%1000;
m_hCurDeviceItem = hParent;
}
}
if (!pMenu.LoadMenu(IDR_MENU_CHANNEL))
{
return;
}
break;
default:
break;
}
}
//display menu
GetCursorPos(&pt);
pMenu.GetSubMenu(0)->TrackPopupMenu(TPM_LEFTALIGN,pt.x ,pt.y,this);
*pResult = 0;
}
/*********************************************************
Function: GetAfterItem
Desc: get device insert point, make sure new device insert afterword last node
Input: hRoot:handle of item tree root
Output:
Return:
**********************************************************/
HTREEITEM CClientDemoDlg::GetAfterItem(HTREEITEM hRoot)
{
HTREEITEM hReturn = TVI_FIRST;
HTREEITEM hChild = m_treeDeviceList.GetChildItem(hRoot);
while (hChild)
{
if (TREE_ALL_T == m_treeDeviceList.GetItemData(hChild) / 1000) //break if it si device tree node
{
break;
}
hReturn = hChild;
hChild = m_treeDeviceList.GetNextSiblingItem(hChild);
}
return hReturn;
}
/*********************************************************
Function: OnMenuDeviceAdd
Desc: menu,device adding response
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuDeviceAdd()
{
int i = 0;
int j = 0;
for (i = 0; i < MAX_DEVICES; i++)
{
if (-1 == g_struDeviceInfo[i].iDeviceChanNum)
{
break;
}
}
char szLan[128] = {0};
if (i == MAX_DEVICES)
{
g_StringLanType(szLan, "所添加的设备已达到最大数", "Added device has reached the maximum number");
AfxMessageBox(szLan);
return;
}
HTREEITEM hSelect = m_treeDeviceList.GetSelectedItem();
for (i = 0; i < MAX_DEVICES; i++)
{
if (g_struDeviceInfo[i].iDeviceChanNum == -1)
{
CDlgAddDevice dlg;
dlg.m_iDeviceIndex = i;
//memset(&g_struDeviceInfo[i], 0, sizeof(STRU_DEVICE_INFO));
if (dlg.DoModal() == IDOK)
{
HTREEITEM hDevice = m_treeDeviceList.InsertItem(g_struDeviceInfo[i].chLocalNodeName, DEVICE_LOGIN, DEVICE_LOGIN,hSelect,GetAfterItem(hSelect));
m_treeDeviceList.SetItemData(hDevice, DEVICETYPE * 1000 + g_struDeviceInfo[i].iDeviceIndex);//
HTREEITEM hChannel = NULL;
//analog channel & IP channel
for (j= 0; j < MAX_CHANNUM_V40; j++)
{
if (g_struDeviceInfo[i].pStruChanInfo[j].iChanIndex != -1 )
{
if (g_struDeviceInfo[i].pStruChanInfo[j].bEnable)
{
hChannel = m_treeDeviceList.InsertItem(g_struDeviceInfo[i].pStruChanInfo[j].chChanName,CHAN_ORIGINAL,CHAN_ORIGINAL,hDevice);
}
else
{
hChannel = m_treeDeviceList.InsertItem(g_struDeviceInfo[i].pStruChanInfo[j].chChanName,CHAN_OFF_LINE,CHAN_OFF_LINE,hDevice);
}
m_treeDeviceList.SetItemData(hChannel, CHANNELTYPE * 1000 + g_struDeviceInfo[i].pStruChanInfo[j].iChanIndex);
}
}
//zero
for (j= 0; j < g_struDeviceInfo[i].byZeroChanNum; j++)
{
hChannel = m_treeDeviceList.InsertItem(g_struDeviceInfo[i].struZeroChan[j].chChanName,CHAN_ORIGINAL,CHAN_ORIGINAL,hDevice);
m_treeDeviceList.SetItemData(hChannel, CHANNELTYPE * 1000 + g_struDeviceInfo[i].struZeroChan[j].iChanIndex);
}
for (j= 0; j < g_struDeviceInfo[i].byMirrorChanNum&&j < 16; j++)
{
hChannel = m_treeDeviceList.InsertItem(g_struDeviceInfo[i].struMirrorChan[j].chChanName,CHAN_ORIGINAL,CHAN_ORIGINAL,hDevice);
m_treeDeviceList.SetItemData(hChannel, CHANNELTYPE * 1000 + g_struDeviceInfo[i].struMirrorChan[j].iChanIndex);
}
m_iCurDeviceIndex = dlg.m_iDeviceIndex;
m_treeDeviceList.Expand(hSelect,TVE_EXPAND);
m_treeDeviceList.Expand(hDevice,TVE_EXPAND);
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_DEVICE_ITEM_IMAGE, WPARAM(hDevice), LPARAM(i));
}
return;
}
}
g_StringLanType(szLan, "超过最大设备数", "Exceeds the maximum number of Devices");
AfxMessageBox(szLan);
}
/*********************************************************
Function: DblPlayChan
Desc: double click playing channel, stop if it is already playing
Input: hChanItem,pic switch wile play status changes;iChanIndex:channel index;hChanItem,channel node pointer;
Output:
Return:
**********************************************************/
void CClientDemoDlg::DblPlayChan(int iDeviceIndex, int iChanIndex,HTREEITEM hChanItem)
{
if (!DoLogin(iDeviceIndex, m_treeDeviceList.GetParentItem(hChanItem)))
{
return;
}
char szLan[128] = {0};
if (g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].lRealHandle < 0)
{
CHANNEL_INFO pStruChanInfo;
if (iChanIndex >= MIRROR_CHAN_INDEX)
{
memcpy(&pStruChanInfo, &g_struDeviceInfo[iDeviceIndex].struMirrorChan[iChanIndex- MIRROR_CHAN_INDEX], sizeof(CHANNEL_INFO));
}
else
{
memcpy(&pStruChanInfo, &g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex], sizeof(CHANNEL_INFO));
}
if (g_dlgOutput[m_iCurWndIndex].StartPlay(&pStruChanInfo,hChanItem)<0)
{
g_StringLanType(szLan, "预览失败!", "Preview Failed");
AfxMessageBox(szLan);
}
ChangePlayBtnState();
return;
}
//if the channel is already previewed, stop it
if (!StopPlayedChan(iDeviceIndex,iChanIndex))
{
g_StringLanType(szLan, "停止预览失败!", "Stop previewing Failed");
AfxMessageBox(szLan);
}
ChangePlayBtnState();
}
void CClientDemoDlg::PlayMirrorChan(int iDeviceIndex, int iChanIndex,HTREEITEM hChanItem)
{
if (!DoLogin(iDeviceIndex, m_treeDeviceList.GetParentItem(hChanItem)))
{
return;
}
char szLan[128] = {0};
if (g_struDeviceInfo[iDeviceIndex].struMirrorChan[iChanIndex - MIRROR_CHAN_INDEX].lRealHandle < 0)
{
CHANNEL_INFO struMirrorChan;
memcpy(&struMirrorChan, &g_struDeviceInfo[iDeviceIndex].struMirrorChan[iChanIndex - MIRROR_CHAN_INDEX], sizeof(CHANNEL_INFO));
if (g_dlgOutput[m_iCurWndIndex].MirrorStartPlay(&struMirrorChan,hChanItem) <0)
{
g_StringLanType(szLan, "预览失败!", "Preview Failed");
//AddLog(iDeviceIndex, OPERATION_FAIL_T, "Zero play chan", iChanIndex-ZERO_CHAN_INDEX);
AfxMessageBox(szLan);
}
ChangePlayBtnState();
return;
}
//if the channel is already previewed, stop it
if (!StopPlayedChan(iDeviceIndex,iChanIndex))
{
g_StringLanType(szLan, "停止预览失败!", "Stop previewing Failed");
AfxMessageBox(szLan);
}
ChangePlayBtnState();
}
/*********************************************************
Function: PlayZeroChan
Desc: double click playing channel, stop if it is already playing
Input: hChanItem,pic switch wile play status changes;iChanIndex:channel index;hChanItem,channel node pointer;
Output:
Return:
**********************************************************/
void CClientDemoDlg::PlayZeroChan(int iDeviceIndex, int iChanIndex,HTREEITEM hChanItem)
{
if (!DoLogin(iDeviceIndex, m_treeDeviceList.GetParentItem(hChanItem)))
{
return;
}
char szLan[128] = {0};
if (g_struDeviceInfo[iDeviceIndex].struZeroChan[iChanIndex-ZERO_CHAN_INDEX].lRealHandle < 0)
{
CHANNEL_INFO struZeroChan;
memcpy(&struZeroChan, &g_struDeviceInfo[iDeviceIndex].struZeroChan[iChanIndex-ZERO_CHAN_INDEX], sizeof(CHANNEL_INFO));
if (g_dlgOutput[m_iCurWndIndex].ZeroStartPlay(&struZeroChan,hChanItem)<0)
{
g_StringLanType(szLan, "预览失败!", "Preview Failed");
//AddLog(iDeviceIndex, OPERATION_FAIL_T, "Zero play chan", iChanIndex-ZERO_CHAN_INDEX);
AfxMessageBox(szLan);
}
ChangePlayBtnState();
return;
}
//if the channel is already previewed, stop it
if (!StopPlayedChan(iDeviceIndex,iChanIndex))
{
g_StringLanType(szLan, "停止预览失败!", "Stop previewing Failed");
AfxMessageBox(szLan);
}
ChangePlayBtnState();
}
/*********************************************************
Function: OnMenuLogout
Desc: menu on logout response function
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuLogout()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
HTREEITEM hDeviceItem = m_treeDeviceList.GetSelectedItem();
if (hDeviceItem == NULL)
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "CClientDemoDlg::OnMenuLogout: hDeviceItem err\n");
return;
}
DoLogout(iDeviceIndex, hDeviceItem);
ManualClearAlarm(iDeviceIndex, -1);
}
/*********************************************************
Function: DoLogout
Desc: logout
Input: iDeviceIndex:device serial number;hDeviceItem,device pointer;
Output:
Return: TRUE,log out successfullyFALSE,log out failed
**********************************************************/
BOOL CClientDemoDlg::DoLogout(int iDeviceIndex, HTREEITEM hDeviceItem)
{
int i = 0;
char szLan[128] = {0};
g_StringLanType(szLan, "该设备有通道正在预览或录像", "Some channels of this device is recording or preview");
for (i = 0; i<g_struDeviceInfo[iDeviceIndex].iDeviceChanNum; i++)
{
if ((g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].lRealHandle >= 0 && i < MAX_CHANNUM_V30*2)|| g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bLocalManualRec )
{
AfxMessageBox(szLan);
return FALSE;
}
}
// 2011-11-16 silujie
g_StringLanType(szLan, "该设备有通道正在被动解码", "some channels of this device is passive decode");
for(i =0; i<256; i++)
{
if (g_struDeviceInfo[iDeviceIndex].struPassiveDecode[i].lPassiveHandle >=0 || g_struDeviceInfo[iDeviceIndex].struPassiveDecode[i].hFileThread != NULL)
{
AfxMessageBox(szLan);
return FALSE;
}
}
g_StringLanType(szLan, "该设备有通道正在语音对讲", "Some channels of this device is voice talk");
if (g_lVoiceHandle >= 0)
{
AfxMessageBox(szLan);
return FALSE;
}
if (g_struDeviceInfo[iDeviceIndex].lLoginID >= 0)
{
//remove guard
if (g_struDeviceInfo[iDeviceIndex].lFortifyHandle >= 0)
{
if (NET_DVR_CloseAlarmChan_V30(g_struDeviceInfo[iDeviceIndex].lFortifyHandle))
{
g_struDeviceInfo[iDeviceIndex].lFortifyHandle = -1;
}
}
if (!NET_DVR_Logout_V30(g_struDeviceInfo[iDeviceIndex].lLoginID))
{
//g_struDeviceInfo[iDeviceIndex].lLoginID = -1;
g_StringLanType(szLan, "注销失败", "Logout Failed");
AfxMessageBox(szLan);
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_DEVICE_ITEM_IMAGE, WPARAM(hDeviceItem), LPARAM(iDeviceIndex));
return FALSE;
}
}
AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_Logout_V30");
g_struDeviceInfo[iDeviceIndex].lLoginID = -1;
g_struDeviceInfo[iDeviceIndex].bPlayDevice = FALSE;
for (i = 0; i < g_struDeviceInfo[iDeviceIndex].iDeviceChanNum; i++)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].lRealHandle = -1;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = FALSE;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bLocalManualRec = FALSE;
}
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_DEVICE_ITEM_IMAGE, WPARAM(hDeviceItem), LPARAM(iDeviceIndex));
return TRUE;
}
/*********************************************************
Function: OnMenuDeviceDelete
Desc: delete devices, and initialize structure
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuDeviceDelete()
{
char szLan[128] = {0};
g_StringLanType(szLan, "确定要删除该结点", "Sure to delete this node");
if (MessageBox(szLan,"Warning",MB_OKCANCEL) == IDOK)
{
int iDeviceIndex = GetCurDeviceIndex();
HTREEITEM hDeviceItem = m_treeDeviceList.GetSelectedItem();
if (DoLogout(iDeviceIndex, hDeviceItem))//先注销这个设备
{
LOCAL_DEVICE_INFO struDevInfo;
//memcpy(&(g_struDeviceInfo[iDeviceIndex]), &struDevInfo, sizeof(LOCAL_DEVICE_INFO));
sprintf(g_struDeviceInfo[iDeviceIndex].chLoginUserName , "%s", _T(""));
sprintf(g_struDeviceInfo[iDeviceIndex].chLoginPwd , "%s", _T(""));
sprintf(g_struDeviceInfo[iDeviceIndex].chLocalNodeName , "%s", _T(""));
sprintf(g_struDeviceInfo[iDeviceIndex].chDeviceIP, "%s", _T(""));
// sprintf(g_struDeviceInfo[iDeviceIndex].chDevNetCard1IP, "%s", _T(""));
sprintf(g_struDeviceInfo[iDeviceIndex].chDeviceMultiIP , "%s", _T(""));
sprintf(g_struDeviceInfo[iDeviceIndex].chSerialNumber , "%s", _T(""));
// sprintf(g_struDeviceInfo[iDeviceIndex].chIPServerIP, "%s", _T(""));
g_struDeviceInfo[iDeviceIndex].lLoginID = -1;
g_struDeviceInfo[iDeviceIndex].iDeviceChanNum = -1;
g_struDeviceInfo[iDeviceIndex].lDevicePort = 8000;
g_struDeviceInfo[iDeviceIndex].iDeviceType = 0;
g_struDeviceInfo[iDeviceIndex].iDeviceLoginType = 0;
g_struDeviceInfo[iDeviceIndex].byHttps = 0;
g_struDeviceInfo[iDeviceIndex].byLoginMode = 0;
g_struDeviceInfo[iDeviceIndex].byLoginModeRes = 0;
for (int j = 0; j < g_struDeviceInfo[iDeviceIndex].iDeviceChanNum; j++)
{
sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[j].chChanName ,"%s", _T(""));
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[j].iChanIndex = -1;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[j].dwProtocol = 0;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[j].iDeviceIndex = -1;
}
m_treeDeviceList.DeleteItem(hDeviceItem);
g_SaveDeviceConfig();
}
}
}
/*********************************************************
Function: OnMenuDeviceInfo
Desc: menu on device info response function
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuDeviceInfo()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1 )
{
return;
}
CDlgDeviceInfo dlgDeviceInfo;
dlgDeviceInfo.m_iDeviceIndex = iDeviceIndex;
if (IDOK == dlgDeviceInfo.DoModal())
{
HTREEITEM hSelect = m_treeDeviceList.GetSelectedItem();
m_treeDeviceList.SetItemText(hSelect,g_struDeviceInfo[iDeviceIndex].chLocalNodeName);
}
}
/*********************************************************
Function: OnMenuJPEGSnatchConfig
Desc: local 'jpeg' capture pic configuration
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuJPEGSnatchConfig()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
int iChanIndex = GetCurChanIndex();
if (iChanIndex == -1)
{
char szLan[128] = {0};
g_StringLanType(szLan, "通道号错误!", "Channel Error");
AfxMessageBox(szLan);
return;
}
if (iChanIndex >= ZERO_CHAN_INDEX)
{
AfxMessageBox("Zero not support NET_DVR_CaptureJPEGPicture");
}
CDlgJPEGSnatchConfig dlg;
if (g_struDeviceInfo[iDeviceIndex].byMirrorChanNum > 0 && iChanIndex >= MIRROR_CHAN_INDEX)
{
dlg.m_pChanInfo = &g_struDeviceInfo[iDeviceIndex].struMirrorChan[iChanIndex - MIRROR_CHAN_INDEX];
}
else
{
dlg.m_pChanInfo = &g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex];
}
dlg.DoModal();
}
/*********************************************************
Function: OnMenuChannelInfo
Desc: menu on channel info response function
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuChannelInfo()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
int iChanIndex = GetCurChanIndex();
if (iChanIndex == -1)
{
char szLan[128] = {0};
g_StringLanType(szLan, "通道号错误!", "Channel Error");
AfxMessageBox(szLan);
return;
}
CDlgChannelInfo dlgChannelInfo;
if (iChanIndex >= ZERO_CHAN_INDEX)
{
dlgChannelInfo.m_pChanInfo = &g_struDeviceInfo[iDeviceIndex].struZeroChan[iChanIndex - ZERO_CHAN_INDEX];
}
else if (iChanIndex >= g_struDeviceInfo[iDeviceIndex].iDeviceChanNum)
{
dlgChannelInfo.m_pChanInfo = &g_struDeviceInfo[iDeviceIndex].struMirrorChan[iChanIndex - MIRROR_CHAN_INDEX];
}
else if (iChanIndex >= 0 && iChanIndex < g_struDeviceInfo[iDeviceIndex].iDeviceChanNum)
{
dlgChannelInfo.m_pChanInfo = &g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex];
}
if (IDOK == dlgChannelInfo.DoModal() && dlgChannelInfo.m_bChanged)
{
HTREEITEM hSelect = m_treeDeviceList.GetSelectedItem();
if (iChanIndex >= ZERO_CHAN_INDEX)
{
m_treeDeviceList.SetItemText(hSelect,g_struDeviceInfo[iDeviceIndex].struZeroChan[iChanIndex-ZERO_CHAN_INDEX].chChanName);
}
else if (iChanIndex >= MIRROR_CHAN_INDEX)
{
m_treeDeviceList.SetItemText(hSelect,g_struDeviceInfo[iDeviceIndex].struMirrorChan[iChanIndex-MIRROR_CHAN_INDEX].chChanName);
}
else
{
m_treeDeviceList.SetItemText(hSelect,g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].chChanName);
}
g_SaveDeviceConfig();
}
}
/*********************************************************
Function: ChangeChannelItemImage
Desc: change status icon related to channel node, including play, record, alarm status
Input: wParam, tree channel pointer;lParam,Pointer to channel structure;
Output:
Return: 0 succeed
**********************************************************/
LRESULT CClientDemoDlg::ChangeChannelItemImage(WPARAM wParam, LPARAM lParam)
{
int iDeviceIndex = int(wParam);
int iChanIndex = int(lParam);
if (iDeviceIndex < 0 || iDeviceIndex >MAX_DEVICES\
|| iChanIndex > 512 || iChanIndex < 0)
{
OutputDebugString("dev index and chan num err!\n");
return NULL;
}
HTREEITEM hChanItem = GetChanItem(iDeviceIndex, iChanIndex);
if (NULL == hChanItem)
{
OutputDebugString("chan item NULL!\n");
return NULL;
}
int iImage = CHAN_ORIGINAL;
CHANNEL_INFO pStruChanInfo;
BOOL bPlaying = FALSE;
if (iChanIndex >= ZERO_CHAN_INDEX)
{
memcpy(&pStruChanInfo, &g_struDeviceInfo[iDeviceIndex].struZeroChan[iChanIndex - ZERO_CHAN_INDEX], sizeof(pStruChanInfo));
}
else if (iChanIndex >= MIRROR_CHAN_INDEX)
{
memcpy(&pStruChanInfo, &g_struDeviceInfo[iDeviceIndex].struMirrorChan[iChanIndex - MIRROR_CHAN_INDEX], sizeof(pStruChanInfo));
}
else
{
memcpy(&pStruChanInfo, &g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex], sizeof(pStruChanInfo));
}
bPlaying = pStruChanInfo.lRealHandle >= 0? TRUE:FALSE;
if (bPlaying && !pStruChanInfo.bLocalManualRec && !pStruChanInfo.bAlarm)
{
iImage = CHAN_PLAY;
}
else if ( bPlaying && pStruChanInfo.bLocalManualRec && !pStruChanInfo.bAlarm)
{
iImage = CHAN_PLAY_RECORD;
}
else if (!bPlaying && pStruChanInfo.bLocalManualRec && !pStruChanInfo.bAlarm)
{
iImage = CHAN_RECORD;
}
else if (!bPlaying && !pStruChanInfo.bLocalManualRec && pStruChanInfo.bAlarm)
{
iImage = CHAN_ALARM;
}
else if (bPlaying && !pStruChanInfo.bLocalManualRec && pStruChanInfo.bAlarm)
{
iImage = CHAN_PLAY_ALARM;
}
else if (bPlaying && pStruChanInfo.bLocalManualRec && pStruChanInfo.bAlarm)
{
iImage = CHAN_PLAY_RECORD_ALARM;
}
else if (!bPlaying && !pStruChanInfo.bLocalManualRec && !pStruChanInfo.bAlarm)
{
iImage = CHAN_ORIGINAL;
}
m_treeDeviceList.SetItemImage(hChanItem,iImage,iImage);
//modify status!!
if (iChanIndex >= ZERO_CHAN_INDEX)
{
g_struDeviceInfo[pStruChanInfo.iDeviceIndex].struZeroChan[iChanIndex - ZERO_CHAN_INDEX].dwImageType = iImage;
}
else if (iChanIndex >= MIRROR_CHAN_INDEX)
{
g_struDeviceInfo[pStruChanInfo.iDeviceIndex].struMirrorChan[iChanIndex - MIRROR_CHAN_INDEX].dwImageType = iImage;
}
else
{
g_struDeviceInfo[pStruChanInfo.iDeviceIndex].pStruChanInfo[pStruChanInfo.iChanIndex].dwImageType = iImage;
}
return 0;
}
/*********************************************************
Function: ChangeDeviceItemImage
Desc: 设备节点状态改变的消息函数,维护设备"登陆","布防","告警"等状态
Input: wParam,树设备节点的指针;lParam,设备的序列号;
Output:
Return: 0 成功
**********************************************************/
LRESULT CClientDemoDlg::ChangeDeviceItemImage(WPARAM wParam, LPARAM lParam)
{
HTREEITEM hDeviceItem = HTREEITEM(wParam);
int iDeviceIndex = int(lParam);
if (NULL == hDeviceItem || iDeviceIndex < 0)
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "change dev item");
return NULL;
}
int iImage = DEVICE_LOGOUT;
if (g_struDeviceInfo[iDeviceIndex].lLoginID >= 0 \
&& g_struDeviceInfo[iDeviceIndex].lFortifyHandle < 0&& !g_struDeviceInfo[iDeviceIndex].bAlarm)
{
iImage = DEVICE_LOGIN;
}
else if (g_struDeviceInfo[iDeviceIndex].lLoginID >= 0 \
&& g_struDeviceInfo[iDeviceIndex].lFortifyHandle >= 0&& !g_struDeviceInfo[iDeviceIndex].bAlarm)
{
iImage = DEVICE_FORTIFY;
}
else if (g_struDeviceInfo[iDeviceIndex].lLoginID >= 0 \
&& g_struDeviceInfo[iDeviceIndex].lFortifyHandle >= 0 && g_struDeviceInfo[iDeviceIndex].bAlarm)
{
iImage = DEVICE_FORTIFY_ALARM;
}
else if (g_struDeviceInfo[iDeviceIndex].lLoginID >= 0 \
&&g_struDeviceInfo[iDeviceIndex].lFortifyHandle < 0 && g_struDeviceInfo[iDeviceIndex].bAlarm)
{
iImage = DEVICE_ALARM;
}
else
{
iImage = DEVICE_LOGOUT;
}
m_treeDeviceList.SetItemImage(hDeviceItem,iImage,iImage);
g_struDeviceInfo[iDeviceIndex].dwImageType = iImage;
return 0;
}
typedef struct tagLOCAL_LOGIN_PARAM
{
int iDeviceIndex;
HTREEITEM hSelect;
BOOL bMsgBox;
}LOCAL_LOGIN_PARAM, *LPLOCAL_LOGIN_PARAM;
void ClassifyDevClass(char *pDevClass, unsigned long ulDevClassLen, unsigned short wDevClass)
{
if (pDevClass == NULL)
{
return;
}
if (ulDevClassLen < 100)
{
return;
}
if ((wDevClass >= 1) && (wDevClass <= 50))
{
sprintf(pDevClass, "DVR\n");
}
else if ((wDevClass >= 51) && (wDevClass <= 100))
{
sprintf(pDevClass, "DVS\n");
}
else if ((wDevClass >= 101) && (wDevClass <= 150))
{
sprintf(pDevClass, "NVR\n");
}
else if ((wDevClass >= 151) && (wDevClass <= 200))
{
sprintf(pDevClass, "IPC\n");
}
//
else if ((wDevClass >= 201) && (wDevClass <= 250))
{
sprintf(pDevClass, "CVR\n");
}
else if ((wDevClass >= 251) && (wDevClass <= 300))
{
sprintf(pDevClass, "Transfer & Display\n");
}
else if ((wDevClass >= 301) && (wDevClass <= 350))
{
sprintf(pDevClass, "Alarm Host\n");
}
else if ((wDevClass >= 351) && (wDevClass <= 400))
{
sprintf(pDevClass, "Access Control\n");
}
else if ((wDevClass >= 401) && (wDevClass <= 450))
{
sprintf(pDevClass, "Video Intercom\n");
}
else if ((wDevClass >= 451) && (wDevClass <= 500))
{
sprintf(pDevClass, "Ummanned Aerial Vehicle\n");
}
else if ((wDevClass >= 501) && (wDevClass <= 550))
{
sprintf(pDevClass, "Mobile\n");
}
else if ((wDevClass >= 551) && (wDevClass <= 600))
{
sprintf(pDevClass, "MObile Vehicle\n");
}
//智能分析仪
else if ((wDevClass >= 601) && (wDevClass <= 650))
{
sprintf(pDevClass, "Intelligent analyzer\n");
}
//智能交通服务器
else if ((wDevClass >= 651) && (wDevClass <= 700))
{
sprintf(pDevClass, "Intelligent traffic server \n");
}
//NVS
else if ((wDevClass >= 701) && (wDevClass <= 750))
{
sprintf(pDevClass, "NVS\n");
}
//SMART LOCK
else if ((wDevClass >= 851) && (wDevClass <= 900))
{
sprintf(pDevClass, "Smart Lock\n");
}
else
{
sprintf(pDevClass, "the others\n");
}
return;
}
void CALLBACK LoginResultCallBack(LONG lUserID, DWORD dwResult, LPNET_DVR_DEVICEINFO_V30 lpDeviceInfo, void* pUser)
{
char strTmp[125] = { 0 };
sprintf(strTmp, "%d\n", dwResult);
OutputDebugString(strTmp);
if (dwResult == ASYN_LOGIN_SUCC && pUser != NULL)
{
memcpy(pUser, lpDeviceInfo, sizeof(NET_DVR_DEVICEINFO_V30));
m_giAsynLoginReturn = 1;
}
else
{
m_giAsynLoginReturn = 2;
}
if (m_gpDlgAsynloginWait != NULL)
{
m_gpDlgAsynloginWait->PostMessageA(WM_CLOSE, NULL, NULL);
}
m_giErrNo = NET_DVR_GetLastError();
m_gpErrMsg = NET_DVR_GetErrorMsg();
}
/*********************************************************
Function: DoLogin
Desc: check the device has logged in, if not, log in
Input: iDeviceIndex,device serial number ;hDeviceItem pointer to device node
Output:
Return: FALSE,device log in failed;TRUE; logged in;
**********************************************************/
void *CClientDemoDlg::DoLoginEx(void *lpParam)
{
if (lpParam == NULL)
{
return FALSE;
}
int iDeviceIndex = ((LPLOCAL_LOGIN_PARAM)lpParam)->iDeviceIndex;
HTREEITEM hDeviceItem = ((LPLOCAL_LOGIN_PARAM)lpParam)->hSelect;
BOOL bMsgBox = ((LPLOCAL_LOGIN_PARAM)lpParam)->bMsgBox;
delete lpParam;
lpParam = NULL;
NET_DVR_NETCFG_V30* pStruNetCfg = new NET_DVR_NETCFG_V30;
NET_DVR_DEVICECFG_V40* pStruDevCfg = new NET_DVR_DEVICECFG_V40;
if (pStruNetCfg == NULL || pStruDevCfg == NULL)
{
return NULL;
}
memset(pStruNetCfg, 0, sizeof(NET_DVR_NETCFG_V30));
memset(pStruDevCfg, 0, sizeof(NET_DVR_DEVICECFG_V40));
DWORD dwReturned = 0;
CString csTemp;
int i = 0;
if (g_struDeviceInfo[iDeviceIndex].lLoginID < 0)
{
LONG lUserID = -1;
NET_DVR_DEVICEINFO_V30 struDeviceInfo;
// char szDeviceSN[SERIALNO_LEN] = {0};
memset(&struDeviceInfo, 0, sizeof(NET_DVR_DEVICEINFO_V30));
m_giAsynLoginReturn = 0;
m_giErrNo = 0;
m_gpErrMsg = NULL;
NET_DVR_USER_LOGIN_INFO struLoginInfo = {0};
NET_DVR_DEVICEINFO_V40 struDeviceInfoV40 = {0};
if (m_gbAsynLogin)
{
struLoginInfo.bUseAsynLogin = true;
struLoginInfo.cbLoginResult = LoginResultCallBack;
struLoginInfo.pUser = &struDeviceInfoV40;
}
else
{
struLoginInfo.bUseAsynLogin = false;
}
struLoginInfo.wPort = g_struDeviceInfo[iDeviceIndex].lDevicePort;
memcpy(struLoginInfo.sDeviceAddress, g_struDeviceInfo[iDeviceIndex].chDeviceIP, NET_DVR_DEV_ADDRESS_MAX_LEN);
memcpy(struLoginInfo.sUserName, g_struDeviceInfo[iDeviceIndex].chLoginUserName, NAME_LEN);
memcpy(struLoginInfo.sPassword, g_struDeviceInfo[iDeviceIndex].chLoginPwd, NAME_LEN);
struLoginInfo.byProxyType = g_struDeviceInfo[iDeviceIndex].byProxyType;
//struLoginInfo.byUseTransport = 1;
//struLoginInfo.byRes3[119] = 2;
//DEBUG
//struLoginInfo.byHttps = 2;
//struLoginInfo.byLoginMode = 2;
struLoginInfo.byHttps = g_struDeviceInfo[iDeviceIndex].byHttps;
struLoginInfo.byLoginMode = g_struDeviceInfo[iDeviceIndex].byLoginMode; //自适应方式
// struLoginInfo.byVerifyMode = 2;
lUserID = NET_DVR_Login_V40(&struLoginInfo, &struDeviceInfoV40);
if (m_gbAsynLogin)
{
m_gpDlgAsynloginWait = new CDlgAsynloginWait();
m_gpDlgAsynloginWait->DoModal();
delete m_gpDlgAsynloginWait;
m_gpDlgAsynloginWait = NULL;
}
if ((m_gbAsynLogin && m_giAsynLoginReturn == 2) || lUserID < 0)
{
char szLan[1024] = {0};
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_Login_V30");
if (bMsgBox)
{
if (NET_DVR_GetLastError() == NET_DVR_PASSWORD_ERROR)
{
g_StringLanType(szLan, "用户名密码错误!", "user name or password error!");
AfxMessageBox(szLan);
if (1 == struDeviceInfoV40.bySupportLock)
{
sprintf(szLan, "还剩%d尝试机会", struDeviceInfoV40.byRetryLoginTime);
AfxMessageBox(szLan);
}
}
else if (NET_DVR_GetLastError() == NET_DVR_USER_LOCKED)
{
if (1 == struDeviceInfoV40.bySupportLock)
{
sprintf(szLan, "IP被锁定,剩余锁定时间%d秒", struDeviceInfoV40.dwSurplusLockTime);
AfxMessageBox(szLan);
}
}
else
{
g_StringLanType(szLan, "由于网络原因或DVR忙, 注册失败!", "net error or dvr is busy!");
AfxMessageBox(szLan);
}
}
if (pStruNetCfg != NULL)
{
delete pStruNetCfg ;
pStruNetCfg = NULL;
}
if (pStruDevCfg != NULL)
{
delete pStruDevCfg;
pStruDevCfg = NULL;
}
if (lUserID > 0)
{
NET_DVR_Logout_V30(lUserID);
}
m_giAsynLoginReturn = 0;
return NULL;
}
else
{
g_struDeviceInfo[iDeviceIndex].byLoginModeRes = struDeviceInfoV40.byLoginMode;
if (struDeviceInfoV40.byLoginMode == 0)
{
char szLan[128] = { 0 };
g_StringLanType(szLan, "登录成功,采用协议为私有协议", "Login SUCC, Use Private");
//AfxMessageBox(szLan);
g_pMainDlg->AddLog(-1, OPERATION_SUCC_T, szLan);
}
else
{
char szLan[128] = { 0 };
g_StringLanType(szLan, "登录成功,采用协议为ISAPI", "Login SUCC, Use ISAPI");
//AfxMessageBox(szLan);
g_pMainDlg->AddLog(-1, OPERATION_SUCC_T, szLan);
}
if (1 == struDeviceInfoV40.byPassWordResetLevel)
{
char szLan[128] = { 0 };
g_StringLanType(szLan, "请修改初始登录密码", "Please change the initial login password");
AfxMessageBox(szLan);
}
else if (2 == struDeviceInfoV40.byPassWordResetLevel)
{
char szLan[128] = { 0 };
g_StringLanType(szLan, "请重新设置登录密码", "Please reset your login password");
AfxMessageBox(szLan);
}
if (1 == struDeviceInfoV40.byPasswordLevel)
{
char szLan[128] = {0};
g_StringLanType(szLan, "默认密码,请修改", "default password, please change the password");
AfxMessageBox(szLan);
}
else if (3 == struDeviceInfoV40.byPasswordLevel)
{
char szLan[128] = {0};
g_StringLanType(szLan, "风险密码,请修改", "risk password, please change the password");
AfxMessageBox(szLan);
}
if (struDeviceInfoV40.byResidualValidity != 0)
{
if (struDeviceInfoV40.iResidualValidity <= 3 && struDeviceInfoV40.iResidualValidity >= 0)//密码还有3天到期时,弹窗提示
{
char szLan[128] = { 0 };
g_StringLanType(szLan, "您的密码即将到期,请尽快修改密码!", "Your password is about to expire, please change the password as soon as possible!");
AfxMessageBox(szLan);
}
else if (struDeviceInfoV40.iResidualValidity < 0)//密码已经到期时,弹窗提示
{
char szLan[128] = { 0 };
g_StringLanType(szLan, "您的密码已经到期,请尽快修改密码!", "Your password has expired, please change the password as soon as possible!");
AfxMessageBox(szLan);
}
else
{
char szLan[128] = { 0 };
g_StringLanType(szLan, "该用户密码剩余有效天数:", "Valid days remaining for this user password:");
//AfxMessageBox(szLan);
g_pMainDlg->AddLog(-1, OPERATION_SUCC_T, "%s%d", szLan, struDeviceInfoV40.iResidualValidity);
}
}
memcpy(&struDeviceInfo, &struDeviceInfoV40.struDeviceV30, sizeof(struDeviceInfo));
g_pMainDlg->AddLog(-1, OPERATION_SUCC_T, "NET_DVR_Login_V40, RTSP能力:%d", struDeviceInfoV40.bySupportStreamEncrypt);
}
m_giAsynLoginReturn = 0;
g_struDeviceInfo[iDeviceIndex].byCharaterEncodeType = struDeviceInfoV40.byCharEncodeType;
g_struDeviceInfo[iDeviceIndex].byAudioInputChanNum = struDeviceInfo.byVoiceInChanNum;
g_struDeviceInfo[iDeviceIndex].byStartAudioInputChanNo = struDeviceInfo.byStartVoiceInChanNo;
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_Login_V30");
LOCAL_DEVICE_INFO temp, temp1;
//initialize the information of device
memcpy(&temp1, &(g_struDeviceInfo[iDeviceIndex]), sizeof(LOCAL_DEVICE_INFO));
//memcpy(&(g_struDeviceInfo[iDeviceIndex]), &temp, sizeof(LOCAL_DEVICE_INFO));
g_struDeviceInfo[iDeviceIndex].lLoginID = lUserID;// located ID from re-log in
g_struDeviceInfo[iDeviceIndex].iDeviceIndex = iDeviceIndex;
sprintf(g_struDeviceInfo[iDeviceIndex].chDeviceIP, "%s", temp1.chDeviceIP);
//if the device ip is in ipv6 version, change the ':' to '.' ,
//for ':' is not allowed in Windows OS's file name
char sIPV6Addr[130] = {0};
int i = 0;
for (;i < sizeof(g_struDeviceInfo[iDeviceIndex].chDeviceIP); i ++)
{
if(g_struDeviceInfo[iDeviceIndex].chDeviceIP[i] == '\0')
{
break;
}
else if(g_struDeviceInfo[iDeviceIndex].chDeviceIP[i] == ':')
{
sIPV6Addr[i] = '.';
}
else
{
sIPV6Addr[i] = g_struDeviceInfo[iDeviceIndex].chDeviceIP[i];
}
}
strncpy(g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, sIPV6Addr, sizeof(sIPV6Addr));
sprintf(g_struDeviceInfo[iDeviceIndex].chLocalNodeName, "%s", temp1.chLocalNodeName);
g_struDeviceInfo[iDeviceIndex].lDevicePort = temp1.lDevicePort;
g_struDeviceInfo[iDeviceIndex].byHttps = temp1.byHttps;
g_struDeviceInfo[iDeviceIndex].byLoginMode = temp1.byLoginMode;
sprintf(g_struDeviceInfo[iDeviceIndex].chLoginPwd, "%s", temp1.chLoginPwd);
sprintf(g_struDeviceInfo[iDeviceIndex].chLoginUserName, "%s", temp1.chLoginUserName);
sprintf(g_struDeviceInfo[iDeviceIndex].chLoginUserName, "%s", temp1.chLoginUserName);
g_struDeviceInfo[iDeviceIndex].dwImageType = DEVICE_LOGIN;
g_struDeviceInfo[iDeviceIndex].lLoginID = lUserID;
sprintf(g_struDeviceInfo[iDeviceIndex].chSerialNumber, "%s", struDeviceInfo.sSerialNumber);
g_struDeviceInfo[iDeviceIndex].iDeviceType = struDeviceInfo.wDevType; //扩展字段表示类型,原为byDVRType
g_struDeviceInfo[iDeviceIndex].iDeviceChanNum = struDeviceInfo.byChanNum + struDeviceInfo.byIPChanNum+ struDeviceInfo.byHighDChanNum *256;
g_struDeviceInfo[iDeviceIndex].iStartChan = struDeviceInfo.byStartChan;
g_struDeviceInfo[iDeviceIndex].iDiskNum = struDeviceInfo.byDiskNum;
g_struDeviceInfo[iDeviceIndex].iAlarmOutNum = struDeviceInfo.byAlarmOutPortNum;
g_struDeviceInfo[iDeviceIndex].iAlarmInNum = struDeviceInfo.byAlarmInPortNum;
g_struDeviceInfo[iDeviceIndex].iAudioNum = struDeviceInfo.byAudioChanNum;
g_struDeviceInfo[iDeviceIndex].iAnalogChanNum = struDeviceInfo.byChanNum;
g_struDeviceInfo[iDeviceIndex].iIPChanNum = struDeviceInfo.byIPChanNum + struDeviceInfo.byHighDChanNum*256;
g_struDeviceInfo[iDeviceIndex].byZeroChanNum = struDeviceInfo.byZeroChanNum;
g_struDeviceInfo[iDeviceIndex].byStartDTalkChan = struDeviceInfo.byStartDTalkChan;
g_struDeviceInfo[iDeviceIndex].byLanguageType = struDeviceInfo.byLanguageType;
g_struDeviceInfo[iDeviceIndex].byMirrorChanNum = struDeviceInfo.byMirrorChanNum;
g_struDeviceInfo[iDeviceIndex].wStartMirrorChanNo = struDeviceInfo.wStartMirrorChanNo;
if (struDeviceInfo.bySupport & 0x80)
{
g_struDeviceInfo[iDeviceIndex].byMainProto = struDeviceInfo.byMainProto + 2;
g_struDeviceInfo[iDeviceIndex].bySubProto = struDeviceInfo.bySubProto + 2;
}
else
{
g_struDeviceInfo[iDeviceIndex].byMainProto = struDeviceInfo.byMainProto;
g_struDeviceInfo[iDeviceIndex].bySubProto = struDeviceInfo.bySubProto;
}
g_struDeviceInfo[iDeviceIndex].bySupport = struDeviceInfo.bySupport;
g_struDeviceInfo[iDeviceIndex].bySupport1 = struDeviceInfo.bySupport1;
g_struDeviceInfo[iDeviceIndex].bySupport2 = struDeviceInfo.bySupport2;
g_struDeviceInfo[iDeviceIndex].bySupport5 = struDeviceInfo.bySupport5;
g_struDeviceInfo[iDeviceIndex].bySupport7 = struDeviceInfo.bySupport7;
for (i = 0; i<MAX_CHANNUM_V40; i++)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].dwProtocol = temp1.pStruChanInfo[i].dwProtocol;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iPicResolution = temp1.pStruChanInfo[i].iPicResolution;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iPicQuality = temp1.pStruChanInfo[i].iPicQuality;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].dwPreviewMode = temp1.pStruChanInfo[i].dwPreviewMode;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].nPreviewProtocolType = temp1.pStruChanInfo[i].nPreviewProtocolType;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].nVideoCodingType = temp1.pStruChanInfo[i].nVideoCodingType;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChannelNO = temp1.pStruChanInfo[i].iChannelNO;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].lRealHandle = -1;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanIndex = -1;
}
if (g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_B20_MSU_NP || \
g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_MMC_B20_CLASS || \
g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_B21_MCU_NP_CLASS || \
g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_C20N_VWMS || \
g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_AIOH_MCU_NP || \
g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_Y10_MCU) //B20/B21/C20N主控
{
int nAllChanNums = 0;
int nPreChanNums = 0;
NET_DVR_ALLSUBSYSTEMINFO_V40 struSubSystemInfoV40 = { 0 };
if (NET_DVR_MatrixGetSubSystemInfo_V40(lUserID, &struSubSystemInfoV40))
{
for (int nSysCnt = 0; nSysCnt < MAX_SUBSYSTEM_NUM_V40; nSysCnt++)
{
if (struSubSystemInfoV40.struSubSystemInfo[nSysCnt].bySubSystemType == 2 &&
struSubSystemInfoV40.struSubSystemInfo[nSysCnt].byBelongBoard != 0xff &&
struSubSystemInfoV40.struSubSystemInfo[nSysCnt].byInterfaceNums != 0)
{
for (int nChanCnt = 0; nChanCnt < struSubSystemInfoV40.struSubSystemInfo[nSysCnt].byInterfaceNums; nChanCnt++)
{
DWORD dwDevNo = 1;
DWORD dwBelongBoard = struSubSystemInfoV40.struSubSystemInfo[nSysCnt].byBelongBoard;
DWORD dwChanNo = struSubSystemInfoV40.struSubSystemInfo[nSysCnt].byInterfaceStartNum + nChanCnt;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt].iChanIndex = nPreChanNums + nChanCnt;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt].bEnable = TRUE;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt].iChanType = DEMO_CHANNEL_TYPE_ANALOG;
sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt].chChanName, "Camera_%d_%d_%d", dwDevNo, dwBelongBoard, dwChanNo);
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt].iChannelNO = dwDevNo << 24 | dwBelongBoard << 16 | dwChanNo;
}
nAllChanNums += struSubSystemInfoV40.struSubSystemInfo[nSysCnt].byInterfaceNums;
nPreChanNums = nAllChanNums;
}
}
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_MatrixGetSubSystemInfo_V40");
}
else
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_MatrixGetSubSystemInfo_V40");
char szLan[128] = { 0 };
g_StringLanType(szLan, "获取主板子系统信息失败", "failed to get subsystem information");
AfxMessageBox(szLan);
return NULL;
}
g_struDeviceInfo[iDeviceIndex].iAnalogChanNum = nAllChanNums;
if (g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_C20N_VWMS || g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_Y10_MCU || DS_B21_MCU_NP_CLASS) //C20N服务器有预监通道
{
int iMinWallNo = 0;
int iMaxWallNo = 0;
char *pszBuf = new char[XML_BUF];
memset(pszBuf, 0, XML_BUF);
if (!NET_DVR_GetDeviceAbility(lUserID, WALL_ABILITY, NULL, 0, pszBuf, XML_BUF))
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GetDeviceAbility WALL_ABILITY");
char szLan[128] = { 0 };
g_StringLanType(szLan, "获取电视墙能力集失败", "failed to get video wall ability");
AfxMessageBox(szLan);
return NULL;
}
char *pStart = strstr(pszBuf, "<wallNo min=\"");
if (pStart == NULL)
{
char szLan[128] = { 0 };
g_StringLanType(szLan, "电视墙能力集中wallNo字段返回有误", "the format of wallNo of video wall ability is error");
AfxMessageBox(szLan);
return NULL;
}
pStart += strlen("<wallNo min=\"");
char* pEnd = strstr(pStart, "\"");
if (pEnd == NULL)
{
char szLan[128] = { 0 };
g_StringLanType(szLan, "电视墙能力集中wallNo字段返回有误", "the format of wallNo of video wall ability is error");
AfxMessageBox(szLan);
}
char sMinWallNo[32] = { 0 };
memcpy(sMinWallNo, pStart, pEnd - pStart);
iMinWallNo = atoi(sMinWallNo); //从能力集中解析到电视墙编号的最小值
pStart = strstr(pEnd, "max=\"");
if (pStart == NULL)
{
char szLan[128] = { 0 };
g_StringLanType(szLan, "电视墙能力集中wallNo字段返回有误", "the format of wallNo of video wall ability is error");
AfxMessageBox(szLan);
return NULL;
}
pStart += strlen("max=\"");
pEnd = strstr(pStart, "\"");
if (pEnd == NULL)
{
char szLan[128] = { 0 };
g_StringLanType(szLan, "电视墙能力集中wallNo字段返回有误", "the format of wallNo of video wall ability is error");
AfxMessageBox(szLan);
return NULL;
}
char sMaxWallNo[32] = { 0 };
memcpy(sMaxWallNo, pStart, pEnd - pStart);
iMaxWallNo = atoi(sMaxWallNo); //从能力集中解析到电视墙编号的最大值
//生成电视墙预监通道
for (int nChanCnt = iMinWallNo; nChanCnt < iMaxWallNo + 1; nChanCnt++)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt - iMinWallNo].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt - iMinWallNo].iChanIndex = nPreChanNums + nChanCnt - iMinWallNo;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt - iMinWallNo].bEnable = TRUE;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt - iMinWallNo].iChanType = DEMO_CHANNEL_TYPE_IP;
sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt - iMinWallNo].chChanName, "PreMonitor_%02d", nChanCnt);
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[nPreChanNums + nChanCnt - iMinWallNo].iChannelNO = 0xff000000 | nChanCnt;
}
nAllChanNums += (iMaxWallNo - iMinWallNo + 1);
nPreChanNums = nAllChanNums;
g_struDeviceInfo[iDeviceIndex].iIPChanNum = iMaxWallNo - iMinWallNo + 1;
}
g_struDeviceInfo[iDeviceIndex].iDeviceChanNum = nAllChanNums;
}
else
{
for (i = 0; i < g_struDeviceInfo[iDeviceIndex].iAnalogChanNum; i++)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanIndex = i;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChannelNO = i + g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable = TRUE;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanType = DEMO_CHANNEL_TYPE_ANALOG;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].dwImageType = CHAN_ORIGINAL;
sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName, ANALOG_C_FORMAT, i+g_struDeviceInfo[iDeviceIndex].iStartChan);
}
}
for (i = 0; i < g_struDeviceInfo[iDeviceIndex].byMirrorChanNum && i < 16; i++)
{
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].iChanIndex = i+MIRROR_CHAN_INDEX;
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].iChannelNO = i + g_struDeviceInfo[iDeviceIndex].wStartMirrorChanNo;
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].bEnable = TRUE;
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].iChanType = DEMO_CHANNEL_TYPE_MIRROR;
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].dwImageType = CHAN_ORIGINAL;
sprintf(g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].chChanName, MIRROR_C_FORMAT, i+g_struDeviceInfo[iDeviceIndex].wStartMirrorChanNo);
}
if (g_struDeviceInfo[iDeviceIndex].byZeroChanNum > 0)
{
for (i=0; i<g_struDeviceInfo[iDeviceIndex].byZeroChanNum; i++)
{
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].iChanIndex = i+ZERO_CHAN_INDEX;
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].iChannelNO = 0;
sprintf(g_struDeviceInfo[iDeviceIndex].struZeroChan[i].chChanName, "ZeroChan%d", i);
//analog devices
if (1)
{
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].bEnable = TRUE;
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].dwImageType = CHAN_ORIGINAL;
// g_struDeviceInfo[iDeviceIndex].iEnableChanNum ++;
}
else
{
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].dwImageType = CHAN_OFF_LINE;
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].bEnable = FALSE;
}
}
}
if (!NET_DVR_GetDVRConfig(lUserID, NET_DVR_GET_NETCFG_V30, 0,pStruNetCfg, sizeof(NET_DVR_NETCFG_V30), &dwReturned))
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GET_NETCFG_V30");
}
else
{
//sprintf(g_struDeviceInfo[m_iDeviceIndex].chDevNetCard1IP, "%s", struNetCfg.struEtherNet[0].struDVRIP.sIpV4);
if (!g_ValidIPv6((BYTE *)(g_struDeviceInfo[iDeviceIndex].chDeviceIP)))
{
sprintf(g_struDeviceInfo[iDeviceIndex].chDeviceMultiIP, "%s", pStruNetCfg->struMulticastIpAddr.sIpV4);
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "multi-cast ipv4[%s]", pStruNetCfg->struMulticastIpAddr.sIpV4);
}
else //ipv6
{
sprintf(g_struDeviceInfo[iDeviceIndex].chDeviceMultiIP, "%s", pStruNetCfg->struMulticastIpAddr.byIPv6);
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "multi-cast ipv6[%s]", pStruNetCfg->struMulticastIpAddr.byIPv6);
}
#if 0
//IPv6多播测试,临时性地址写死
memset(g_struDeviceInfo[iDeviceIndex].chDeviceMultiIP, 0, sizeof(g_struDeviceInfo[iDeviceIndex].chDeviceMultiIP));
sprintf(g_struDeviceInfo[iDeviceIndex].chDeviceMultiIP, "ff02::1234");
#endif
}
// string strContent = "<?xml version=\"1.0\"><StorageServer version=\"1.0\"><PCNVRUI>1<PCNVRUI> </StorageServer>";
// NET_DVR_SetTransparentParam(lUserID, (char*)strContent.c_str(), strContent.size());
NET_DVR_GetDVRConfig(lUserID, NET_DVR_GET_DEVICECFG_V40, 0, pStruDevCfg, sizeof(NET_DVR_DEVICECFG_V40), &dwReturned);
NET_DVR_DEVICEINFO_V40 struDevInfoV40 = { 0 };
if (!NET_DVR_GetDVRConfig(lUserID, NET_DVR_GET_DEV_LOGIN_RET_INFO, 0, &struDevInfoV40, sizeof(NET_DVR_DEVICEINFO_V40), &dwReturned))
{
int nError = NET_DVR_GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GET_DEV_LOGIN_RET_INFO");
}
else
{
//
pStruDevCfg->byDVRType = struDevInfoV40.struDeviceV30.byDVRType;
pStruDevCfg->wDevType = struDevInfoV40.struDeviceV30.wDevType;
pStruDevCfg->byChanNum = struDevInfoV40.struDeviceV30.byChanNum;
pStruDevCfg->byStartChan = struDevInfoV40.struDeviceV30.byStartChan;
pStruDevCfg->byIPChanNum = struDevInfoV40.struDeviceV30.byIPChanNum;
pStruDevCfg->byZeroChanNum = struDevInfoV40.struDeviceV30.byZeroChanNum;
if (g_struDeviceInfo[iDeviceIndex].iDeviceType != (int)pStruDevCfg->wDevType)
{
char szLan[256] = {0};
char szLanShow[256] = {0};
g_StringLanType(szLan, "登陆返回设备类型值与获取设备参数返回设备类型值不同", "returned device type is different between login and get device config");
sprintf(szLanShow,"%s %d,%d",szLan,g_struDeviceInfo[iDeviceIndex].iDeviceType,pStruDevCfg->wDevType);
AfxMessageBox(szLanShow);
}
sprintf(g_struDeviceInfo[iDeviceIndex].chDeviceName,"%s",pStruDevCfg->byDevTypeName);
g_struDeviceInfo[iDeviceIndex].dwDevSoftVer = pStruDevCfg->dwSoftwareVersion;
ClassifyDevClass(g_struDeviceInfo[iDeviceIndex].chDeviceClassName, 100, pStruDevCfg->wDevClass);
}
g_pMainDlg->m_treeDeviceList.Expand(hDeviceItem,TVE_EXPAND);
//get the new device resource configure when login device/
if (g_pMainDlg->DoGetDeviceResoureCfg(iDeviceIndex))
{
g_pMainDlg->DoGetIPAlarmInCfg(iDeviceIndex);
g_pMainDlg->DoGetIPAlarmOutCfg(iDeviceIndex);
}
g_pMainDlg->RedrawDeviceNode(iDeviceIndex);
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_DEVICE_ITEM_IMAGE, WPARAM(hDeviceItem), LPARAM(iDeviceIndex));
}
//return if already logged in
if (pStruNetCfg != NULL)
{
delete pStruNetCfg;
pStruNetCfg = NULL;
}
if (pStruDevCfg != NULL)
{
delete pStruDevCfg ;
pStruDevCfg = NULL;
}
return NULL;
}
/*********************************************************
Function: DoLogin
Desc: check the device has logged in, if not, log in
Input: iDeviceIndex,device serial number ;hDeviceItem pointer to device node
Output:
Return: FALSE,device log in failed;TRUE; logged in;
**********************************************************/
BOOL CClientDemoDlg::DoLogin(int iDeviceIndex, HTREEITEM hDeviceItem)
{
LPLOCAL_LOGIN_PARAM lpParam = new LOCAL_LOGIN_PARAM;
if (lpParam == NULL)
{
return FALSE;
}
lpParam->iDeviceIndex = iDeviceIndex;
lpParam->hSelect = hDeviceItem;
lpParam->bMsgBox = TRUE;
DoLoginEx(lpParam);
//return if already logged in
return TRUE;
}
/*********************************************************
Function: StopPlayedChan
Desc: stop one play channel in preview
Input: iDeviceIndex, device index, iChanIndex,channel index
Output:
Return:
**********************************************************/
BOOL CClientDemoDlg::StopPlayedChan(int iDeviceIndex, int iChanIndex)
{
for (int i = 0; i < MAX_OUTPUTS; i ++)
{
if (g_dlgOutput[i].m_lPlayHandle < 0)
{
continue;
}
if (g_dlgOutput[i].m_struChanInfo.iDeviceIndex == iDeviceIndex && \
g_dlgOutput[i].m_struChanInfo.iChanIndex == iChanIndex )
{
if (g_dlgOutput[i].m_struChanInfo.iChanIndex < MIRROR_CHAN_INDEX)
{
return g_dlgOutput[i].StopPlay();
}
else if (g_dlgOutput[i].m_struChanInfo.iChanIndex < ZERO_CHAN_INDEX)
{
return g_dlgOutput[i].MirrorStopPlay();
}
else
{
return g_dlgOutput[i].ZeroStopPlay();
}
}
}
return TRUE;
}
/*********************************************************
Function: CreateNewLogFile
Desc: create new log file
Input: bCreate, TRUE/FALSE
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::CreateNewLogFile(BOOL bCreate)
{
CString csLogFile;
// if ((LONG *)m_fLog.m_hFile != INVALID_HANDLE_VALUE)
// {
// TRACE("Close alarm file");
// m_fLog.Close();
// m_fLog.Abort();
// }
//
// if ((LONG *)m_fAlarm.m_hFile != INVALID_HANDLE_VALUE)
// {
// TRACE("Close alarm file");
//
// m_fAlarm.Close();
// m_fAlarm.Abort();
// }
if (m_fLog != NULL)
{
fclose(m_fLog);
}
if (m_fAlarm!= NULL)
{
fclose(m_fAlarm);
}
if (!bCreate)
{
return;
}
COleDateTime dtCurTime = COleDateTime::GetCurrentTime();
csLogFile.Format("%s\\LogFile_%4d%02d%02d.txt",\
g_struLocalParam.chRemoteCfgSavePath, dtCurTime.GetYear(), dtCurTime.GetMonth(),\
dtCurTime.GetDay());
if ((m_fLog = fopen(csLogFile.GetBuffer(0), "a+")) == NULL)
{
GetDlgItem(IDC_BTN_LOG_SAVE)->EnableWindow(FALSE);
g_struLocalParam.bAutoSaveLog = FALSE;
}
csLogFile.Format("%s\\AlarmInfo_%4d%02d%02d.txt",\
g_struLocalParam.chRemoteCfgSavePath, dtCurTime.GetYear(), dtCurTime.GetMonth(),\
dtCurTime.GetDay());
if ((m_fAlarm = fopen(csLogFile.GetBuffer(0), "a+")) == NULL)
{
GetDlgItem(IDC_BTN_LOG_SAVE)->EnableWindow(FALSE);
g_struLocalParam.bAutoSaveLog = FALSE;
}
}
/*********************************************************
Function: OnTimer
Desc: timer response function
Input: nIDEvent, ID event value
Output:
Return:
**********************************************************/
#if (_MSC_VER >= 1500) //vs2008
void CClientDemoDlg::OnTimer(UINT_PTR nIDEvent)
#else
void CClientDemoDlg::OnTimer(UINT nIDEvent)
#endif
{
// TODO: Add your message handler code here and/or call default
char szLan[128] = {0};
CString csTemp = _T("");
int i = 0;
int j = 0;
time_t lCurrentTime;
CString csRecRootPath;
CTime ctCurTime = CTime::GetCurrentTime();
int iWeekday = ctCurTime.GetDayOfWeek() - 1;
WORD iNowTime = (WORD)(ctCurTime.GetHour() * 100 + ctCurTime.GetMinute());
NET_DVR_TIME CurTime;
CurTime.dwYear = ctCurTime.GetYear();
CurTime.dwMonth = ctCurTime.GetMonth();
CurTime.dwDay = ctCurTime.GetDay();
CurTime.dwHour = ctCurTime.GetHour();
CurTime.dwMinute = ctCurTime.GetMinute();
CurTime.dwSecond = ctCurTime.GetSecond();
switch (nIDEvent)
{
case SYSTEM_TIMER:
if (g_struLocalParam.bAutoSaveLog && ctCurTime.GetHour() == 0\
&& ctCurTime.GetMinute() == 0 && ctCurTime.GetSecond() == 0)
{//one day
CreateNewLogFile(TRUE);
}
break;
case CYCLE_PREVIEW_TIMER:
CyclePlayAllDevicesLogined();
break;
case FREESPACE_TIMER:
csRecRootPath.Format("%c:\\", m_iCurRecDriver);
ULARGE_INTEGER FreeSpace,CallerSpace,TotalSpace;
GetDiskFreeSpaceEx(csRecRootPath,&CallerSpace,&TotalSpace,&FreeSpace);
g_struLocalParam.bAllDiskFull = FALSE;
if (CallerSpace.QuadPart < MINSPACE)
{
csTemp.Format("%4d-%02d-%02d %02d:%02d:%02d HD Partition%c is Full", CurTime.dwYear, CurTime.dwMonth,\
CurTime.dwDay, CurTime.dwHour, CurTime.dwMinute, CurTime.dwSecond, m_iCurRecDriver);
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, csTemp.GetBuffer(0));
if (IsDiskFull()) //delete first 8 record files if hard disk is full
{
if (g_struLocalParam.bCycleRecord)
{
DeleteClientRecordFile();
}
else
{
for (i = 0; i < MAX_OUTPUTS; i++)
{
if ((g_dlgOutput[i].m_lPlayHandle >= 0) && (g_dlgOutput[i].m_bLocalManualRec))
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "CClientDemoDlg::FREESPACE_TIMER stop");
g_dlgOutput[i].StopLocalRecord();
}
}
g_StringLanType(szLan, "客户端录像硬盘驱动器已满,无法继续录像", "Client hard disk drive is full, unable to continue record");
g_pMainDlg->AddLog(-1, OPERATION_FAIL_T, szLan);
return;
}
}
else
{ //storage to other partition which is free
if (MakeRecDir())
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "switch to Hard disk partition%c", m_iCurRecDriver);
for (i = 0; i < MAX_OUTPUTS; i++)
{
if ((g_dlgOutput[i].m_lPlayHandle >= 0) && (g_dlgOutput[i].m_bLocalManualRec))
{
g_dlgOutput[i].ChangeRecordFileName();
}
}
}
}
}
break;
case FILEINTERVAL_TIMER:
for (i = 0; i < MAX_OUTPUTS; i++)
{
if ((g_dlgOutput[i].m_lPlayHandle >= 0) && (g_dlgOutput[i].m_bLocalManualRec))
{
lCurrentTime = (time_t)ctCurTime.GetTime();
if (lCurrentTime - g_dlgOutput[i].m_lChangeFileNameTime >= 0)
{
if (MakeRecDir())
{
g_dlgOutput[i].ChangeRecordFileName();
}
}
}
}
break;
case AUTORECORD_TIMER:
if (g_struLocalParam.bCycling)
{
return; //no record in client while cycle play
}
if (!g_struLocalParam.bAutoRecord)
{
return;
}
for (i = 0; i < 4; i++)
{
if ((iNowTime >= g_struLocalParam.struLocalRecordTime[iWeekday][i].iStartTime) &&
(iNowTime < g_struLocalParam.struLocalRecordTime[iWeekday][i].iStopTime))
{ //it is time auto record
for (j = 0; j < MAX_OUTPUTS; j++)
{
if (g_dlgOutput[j].m_lPlayHandle >= 0)
{
if ( !g_dlgOutput[j].m_bLocalManualRec)
{
if (g_struLocalParam.bAllDiskFull)
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "Client Hard Disk is full, pause recording");
return; //no record if client hard disk is full
}
if (MakeRecDir())
{
g_dlgOutput[j].AddLog(OPERATION_SUCC_T, "%02d:%02d start auto record", CurTime.dwHour, CurTime.dwMinute);
g_dlgOutput[j].StartLocalRecord();
}
}
}
}
break;
}
else
i++;
}
if (i == 4)
{
for (j = 0; j < MAX_OUTPUTS; j++)
{
if (g_dlgOutput[j].m_bLocalManualRec)
{
g_dlgOutput[j].AddLog(OPERATION_SUCC_T, "%02d:%02d stop auto record", CurTime.dwHour, CurTime.dwMinute);
g_dlgOutput[j].StopLocalRecord();
}
}
}
break;
case CHECK_DEVICE_TIMER:
if (g_struLocalParam.lCheckDeviceTime == (LONG)(CurTime.dwHour*10000 + CurTime.dwMinute*100 + CurTime.dwSecond))
{
for (i = 0; i < MAX_DEVICES; i++)
{
if (g_struDeviceInfo[i].lLoginID >= 0)
{
if (NET_DVR_SetDVRConfig(g_struDeviceInfo[i].lLoginID, NET_DVR_SET_TIMECFG, 0, &CurTime, sizeof(NET_DVR_TIME)))
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "NET_DVR_SetDVRConfig");
}
else
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "NET_DVR_SetDVRConfig");
}
}
}
}
break;
default:
break;
}
CDialog::OnTimer(nIDEvent);
}
/*********************************************************
Function: OnCbnSelchangeComboWndNum
Desc: change pic number in preview
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnCbnSelchangeComboWndNum()
{
int iIndex = m_comboWinNum.GetCurSel();
m_iCurWndNum = (int)pow(double(iIndex+1), 2);//current window number
if (!IsPlaying())
{
m_iCurWndIndex = 0;//initialize current window index while switch window
ArrangeOutputs(m_iCurWndNum);
GetDlgItem(IDC_STATIC_PREVIEWBG)->Invalidate(TRUE);
}
else
{
char szLan[128] = {0};
g_StringLanType(szLan, "请先停止播放", "Please stop previewing");
AfxMessageBox(szLan);
}
}
/*********************************************************
Function: OnWMProcAlarm
Desc: process alarm information when
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::ProcAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
// int iRet = 0;
BOOL bDisk = FALSE;
int i = 0;
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] ={0};
NET_DVR_ALARMINFO m_struAlarmInfo;
memcpy(&m_struAlarmInfo, pAlarmInfo, sizeof(NET_DVR_ALARMINFO));
if (!(g_struDeviceInfo[iDeviceIndex].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_DEVICE_ITEM_IMAGE, WPARAM(g_pMainDlg->GetDeviceItem(iDeviceIndex)), LPARAM(iDeviceIndex));
}
int iAChanNum = g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].dwAChanNum;
switch (m_struAlarmInfo.dwAlarmType)
{
case 0://signal alarm
g_StringLanType(szLan, "信号量报警 报警输入", "Signal alarm input");
sprintf(szInfoBuf,"%s%d", szLan, m_struAlarmInfo.dwAlarmInputNumber+1);
g_StringLanType(szLan, ",触发通道录像:", ", Invoke record Channel:");
sprintf(szInfoBuf,"%s%s", szInfoBuf, szLan);
for (i=0; i<MAX_CHANNUM; i++)
{
if (m_struAlarmInfo.dwAlarmRelateChannel[i] == 1)
{
sprintf(szInfoBuf,"%s %d,", szInfoBuf, i+g_struDeviceInfo[iDeviceIndex].iStartChan);
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T,szInfoBuf);
break;
case 1://hard disk full alarm
g_StringLanType(szInfoBuf, "硬盘满报警:", "HDD is Full:");
for (i=0; i<MAX_DISKNUM; i++)
{
if (m_struAlarmInfo.dwDiskNumber[i] == 1)
{
sprintf(szInfoBuf, "%s HDD%d ", szInfoBuf, i);
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T,szInfoBuf);
break;
case 2://video loss alarm
g_StringLanType(szInfoBuf, "视频信号丢失报警:", "The video signal lost:");
for (i=0; i<MAX_CHANNUM; i++)
{
if (m_struAlarmInfo.dwChannel[i] == 1)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 3://motion detection alarm
g_StringLanType(szInfoBuf, "移动侦测报警", "motion detection");
for (i=0; i<MAX_CHANNUM_V40; i++)
{
if (m_struAlarmInfo.dwChannel[i] == 1)
{
if (g_struDeviceInfo[iDeviceIndex].iStartChan ==0)
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else // 数字通道,i
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i-32+iAChanNum].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i-32+iAChanNum].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i-32+iAChanNum));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i-32+iAChanNum].chChanName);
}
}
else
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i-g_struDeviceInfo[iDeviceIndex].iStartChan+iAChanNum));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i-g_struDeviceInfo[iDeviceIndex].iStartChan+iAChanNum].chChanName);
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 4://hard disk unformatted alarm
g_StringLanType(szInfoBuf, "硬盘未格式化报警", "HDD not formatted:");
for (i=0; i<MAX_DISKNUM; i++)
{
if (m_struAlarmInfo.dwDiskNumber[i] == 1)
{
sprintf(szInfoBuf, "%s HDD%d", szInfoBuf, i);
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 5://hard disk alarm
for (i=0; i<MAX_DISKNUM; i++)
{
if (m_struAlarmInfo.dwDiskNumber[i] == 1)
{
bDisk = TRUE;
g_StringLanType(szLan, "读写硬盘出错", "failed to read and write HDD");
sprintf(szInfoBuf, "%sHDD%d ", szLan, i);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
}
if (bDisk == FALSE)
{
g_StringLanType(szInfoBuf, "未接硬盘出错报警", "no HDD");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
bDisk = FALSE;
break;
case 6://mask alarm
g_StringLanType(szInfoBuf, "发生遮挡报警", "Mask alarm");
for (i=0; i<MAX_CHANNUM; i++)
{
if (m_struAlarmInfo.dwChannel[i] == 1)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 7: //type unmatched
g_StringLanType(szInfoBuf, "制式不匹配", "input and output video standard not match");
for (i=0; i<MAX_CHANNUM; i++)
{
if (m_struAlarmInfo.dwChannel[i] == 1)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 8:
g_StringLanType(szInfoBuf, "非法访问", "illegal access");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 9:
g_StringLanType(szInfoBuf, "视频信号异常", "video exception");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 10:
g_StringLanType(szInfoBuf, "录像异常", "record exception");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 11:
g_StringLanType(szInfoBuf, "智能场景变化", "Vca scene change");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T,szInfoBuf);
break;
default:
g_StringLanType(szLan, "未知报警类型:", "Unknown Alarm Type:");
sprintf(szInfoBuf, "%s 0x%x", szLan, m_struAlarmInfo.dwAlarmType);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
}
}
/*********************************************************
Function: ProcAlarmV30
Desc: process alarm information for version 30
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::ProcAlarmV30(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
BOOL bDisk = FALSE;
int i = 0;
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
if (iDeviceIndex > 512)
{
return;
}
char szLan[128] ={0};
NET_DVR_ALARMINFO_V30 m_struAlarmInfoV30;
memcpy(&m_struAlarmInfoV30, pAlarmInfo, sizeof(NET_DVR_ALARMINFO_V30));
if (!(g_struDeviceInfo[iDeviceIndex].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_DEVICE_ITEM_IMAGE, WPARAM(g_pMainDlg->GetDeviceItem(iDeviceIndex)), LPARAM(iDeviceIndex));
}
//模拟通道数
int iAChanNum = g_struDeviceInfo[iDeviceIndex].iAnalogChanNum;
//数字通道数
int iDChanNum = g_struDeviceInfo[iDeviceIndex].iIPChanNum;
switch (m_struAlarmInfoV30.dwAlarmType)
{
case 0://signal alarm
g_StringLanType(szLan, "信号量报警 报警输入", "Signal alarm input");
sprintf(szInfoBuf,"%s%d", szLan, m_struAlarmInfoV30.dwAlarmInputNumber+1);
g_StringLanType(szLan, ",触发通道录像:", "Invoke record Channel:");
sprintf(szInfoBuf,"%s%s", szInfoBuf, szLan);
for (i=0; i<MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byAlarmRelateChannel[i] == 1)
{
// if (i<MAX_ANALOG_CHANNUM)
// {
sprintf(szInfoBuf,"%s %d,", szInfoBuf, i+g_struDeviceInfo[iDeviceIndex].iStartChan);
// }
// else
// {
// sprintf(szInfoBuf,"%s %s%d,", szInfoBuf,"IPChan", i+g_struDeviceInfo[iDeviceIndex].iStartChan);
// }
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T,szInfoBuf);
break;
case 1://hard disk full alarm
g_StringLanType(szInfoBuf, "硬盘满报警", "HD is full:");
for (i=0; i<MAX_DISKNUM_V30; i++)
{
if (m_struAlarmInfoV30.byDiskNumber[i] == 1)
{
sprintf(szInfoBuf, "%s HDD%d ", szInfoBuf, i+1);
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T,szInfoBuf);
break;
case 2://video loss alarm
g_StringLanType(szInfoBuf, "视频信号丢失报警", "The signal lost");
for (i=0; i<MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byChannel[i] == 1)
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i-32+iAChanNum].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i-32+iAChanNum].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i-32+iAChanNum));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i-32+iAChanNum].chChanName);
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T,szInfoBuf);
break;
case 3://motion detection alarm
g_StringLanType(szInfoBuf, "移动侦测报警", "motion detection");
for (i=0; i<MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byChannel[i] == 1)
{
//纯模拟通道或纯数字通道
if (0 == iDChanNum || 0 == iAChanNum)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else if(iAChanNum > 0 && iDChanNum > 0) //混合通道
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else //数字通道
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(iAChanNum+i-MAX_ANALOG_CHANNUM));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].chChanName);
}
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 4://hard disk unformatted alarm
g_StringLanType(szInfoBuf, "硬盘未格式化报警", "not formatted");
for (i=0; i<MAX_DISKNUM_V30; i++)
{
if (m_struAlarmInfoV30.byDiskNumber[i] == 1)
{
sprintf(szInfoBuf, "%s HDD%d ", szInfoBuf, i);
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 5://hard disk alarm
for (i=0; i<MAX_DISKNUM_V30; i++)
{
if (m_struAlarmInfoV30.byDiskNumber[i] == 1)
{
bDisk = TRUE;
g_StringLanType(szLan, "读写硬盘出错", "failed to read and write HDD");
sprintf(szInfoBuf, "%sHDD%d ", szLan, i+1);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
}
if (bDisk == FALSE)
{
g_StringLanType(szInfoBuf, "未接硬盘出错报警", "No HDD");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
bDisk = FALSE;
break;
case 6://mask alarm
g_StringLanType(szInfoBuf, "发生遮挡报警", "Mask alarm");
for (i=0; i<MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byChannel[i] == 1)
{
//纯模拟通道或纯数字通道
if (0 == iDChanNum || 0 == iAChanNum)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else if(iAChanNum > 0 && iDChanNum > 0) //混合通道
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else //数字通道
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(iAChanNum+i-MAX_ANALOG_CHANNUM));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].chChanName);
}
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 7: //type unmatched
g_StringLanType(szInfoBuf, "制式不匹配", "input and output video standard not match");
for (i=0; i<MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byChannel[i] == 1)
{
//纯模拟通道或纯数字通道
if (0 == iDChanNum || 0 == iAChanNum)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else if(iAChanNum > 0 && iDChanNum > 0) //混合通道
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else //数字通道
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(iAChanNum+i-MAX_ANALOG_CHANNUM));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].chChanName);
}
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 8:
g_StringLanType(szInfoBuf, "非法访问", "illegal access");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 9:
g_StringLanType(szInfoBuf, "视频信号异常", "video exception");
for (i=0; i<MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byChannel[i] == 1)
{
//纯模拟通道或纯数字通道
if (0 == iDChanNum || 0 == iAChanNum)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else if(iAChanNum > 0 && iDChanNum > 0) //混合通道
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else //数字通道
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(iAChanNum+i-MAX_ANALOG_CHANNUM));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].chChanName);
}
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 10:
g_StringLanType(szInfoBuf, "录像异常", "record exception");
for (i=0; i<MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byChannel[i] == 1)
{
//纯模拟通道或纯数字通道
if (0 == iDChanNum || 0 == iAChanNum)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else if(iAChanNum > 0 && iDChanNum > 0) //混合通道
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else //数字通道
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(iAChanNum+i-MAX_ANALOG_CHANNUM));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].chChanName);
}
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 11:
g_StringLanType(szInfoBuf, "智能场景变化", "Vca scene change");
for (i=0; i<MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byChannel[i] == 1)
{
//纯模拟通道或纯数字通道
if (0 == iDChanNum || 0 == iAChanNum)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else if(iAChanNum > 0 && iDChanNum > 0) //混合通道
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else //数字通道
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(iAChanNum+i-MAX_ANALOG_CHANNUM));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].chChanName);
}
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 12:
g_StringLanType(szInfoBuf, "阵列异常", "Array exception");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T,szInfoBuf);
break;
case 13:
g_StringLanType(szInfoBuf, "前端/录像分辨率不匹配", "resolution mismatch");
for (i=0; i<MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byChannel[i] == 1)
{
//纯模拟通道或纯数字通道
if (0 == iDChanNum || 0 == iAChanNum)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else if(iAChanNum > 0 && iDChanNum > 0) //混合通道
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else //数字通道
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(iAChanNum+i-MAX_ANALOG_CHANNUM));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].chChanName);
}
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 14:
g_StringLanType(szInfoBuf, "申请解码资源失败", "Alloc decoede resource fail");
for (i=0; i<MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byChannel[i] == 1)
{
//纯模拟通道或纯数字通道
if (0 == iDChanNum || 0 == iAChanNum)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else if(iAChanNum > 0 && iDChanNum > 0) //混合通道
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else //数字通道
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(iAChanNum+i-MAX_ANALOG_CHANNUM));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+i-MAX_ANALOG_CHANNUM].chChanName);
}
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 15:
g_StringLanType(szInfoBuf, "智能侦测", "VCA Detction");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 16:
g_StringLanType(szInfoBuf, "POE供电异常", "POE Power Exception");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 17:
g_StringLanType(szInfoBuf, "闪光灯异常", "Flash anomaly");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 18:
g_StringLanType(szInfoBuf, "磁盘满负荷异常", "Disk full load anomaly");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 19:
g_StringLanType(szInfoBuf, "音频信号丢失报警", "The audio signal lost");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 23:
g_StringLanType(szLan, "脉冲报警 报警输入", "Pulse alarm input");
sprintf(szInfoBuf, "%s%d", szLan, m_struAlarmInfoV30.dwAlarmInputNumber + 1);
g_StringLanType(szLan, ",触发通道录像:", "Invoke record Channel:");
sprintf(szInfoBuf, "%s%s", szInfoBuf, szLan);
for (i = 0; i < MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byAlarmRelateChannel[i] == 1)
{
sprintf(szInfoBuf, "%s %d,", szInfoBuf, i + g_struDeviceInfo[iDeviceIndex].iStartChan);
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 24:
g_StringLanType(szInfoBuf, "人脸库硬盘异常", "FDLib Disk lost alarm");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 25:
g_StringLanType(szInfoBuf, "人脸库变更", "FDLib changed");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 26:
g_StringLanType(szInfoBuf, "人脸库图片变更", "FDLib picture changed");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 27:
g_StringLanType(szInfoBuf, "POC 异常", "POC Exception");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 28://camera angle anomaly
g_StringLanType(szInfoBuf, "相机视角异常", "camera angle anomaly");
for (i = 0; i < MAX_CHANNUM_V30; i++)
{
if (m_struAlarmInfoV30.byChannel[i] == 1)
{
//纯模拟通道或纯数字通道
if (0 == iDChanNum || 0 == iAChanNum)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else if (iAChanNum > 0 && iDChanNum > 0) //混合通道
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else //数字通道
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum + i - MAX_ANALOG_CHANNUM].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum + i - MAX_ANALOG_CHANNUM].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(iAChanNum + i - MAX_ANALOG_CHANNUM));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum + i - MAX_ANALOG_CHANNUM].chChanName);
}
}
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 30:
g_StringLanType(szInfoBuf, "SD卡 拔出", "Lack of SD card");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
default:
g_StringLanType(szLan, "未知报警类型:", "Unknown Alarm Type:");
sprintf(szInfoBuf, "%s 0x%x-htonl%d", szLan, m_struAlarmInfoV30.dwAlarmType, ntohl(m_struAlarmInfoV30.dwAlarmType));
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
}
}
/*********************************************************
Function: ProcAlarmV40
Desc: process alarm information for version 40
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::ProcAlarmV40(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[10240] = {0};
BOOL bDisk = FALSE;
int i = 0;
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
if (MAX_DEVICES < iDeviceIndex || 0 > iDeviceIndex)
{
return;
}
char szLan[128] ={0};
NET_DVR_ALARMINFO_V40 m_struAlarmInfoV40 = {0};
memcpy(&m_struAlarmInfoV40, pAlarmInfo, sizeof(NET_DVR_ALARMINFO_V40));
DWORD *pContent = m_struAlarmInfoV40.pAlarmData;
if (!(g_struDeviceInfo[iDeviceIndex].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_DEVICE_ITEM_IMAGE, WPARAM(g_pMainDlg->GetDeviceItem(iDeviceIndex)), LPARAM(iDeviceIndex));
}
//模拟通道数
int iAChanNum = g_struDeviceInfo[iDeviceIndex].iAnalogChanNum;
//数字通道数
int iDChanNum = g_struDeviceInfo[iDeviceIndex].iIPChanNum;
int dwOffSetLen = 0;
DWORD dwTemp = 0;
BOOL bAlarmOut = FALSE;
//打印时间
char szTimeLog[256] = { 0 };
sprintf(szTimeLog, "%04d-%02d-%02d %02d:%02d:%02d flag(%d)%02d%02d", m_struAlarmInfoV40.struAlarmFixedHeader.struAlarmTime.wYear,
m_struAlarmInfoV40.struAlarmFixedHeader.struAlarmTime.byMonth,
m_struAlarmInfoV40.struAlarmFixedHeader.struAlarmTime.byDay,
m_struAlarmInfoV40.struAlarmFixedHeader.struAlarmTime.byHour,
m_struAlarmInfoV40.struAlarmFixedHeader.struAlarmTime.byMinute,
m_struAlarmInfoV40.struAlarmFixedHeader.struAlarmTime.bySecond,
m_struAlarmInfoV40.struAlarmFixedHeader.byTimeDiffFlag,
m_struAlarmInfoV40.struAlarmFixedHeader.cTimeDifferenceH,
m_struAlarmInfoV40.struAlarmFixedHeader.cTimeDifferenceM);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szTimeLog);
float fTemp = 0.0;
switch (m_struAlarmInfoV40.struAlarmFixedHeader.dwAlarmType)
{
case 0://signal alarm
g_StringLanType(szLan, "信号量报警 报警输入号", "Signal alarm input No.");
sprintf(szInfoBuf,"%s%d", szLan, m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struIOAlarm.dwAlarmInputNo +1);
g_StringLanType(szLan, ",关联报警输出号:", "Invoke Alarm Out:");
sprintf(szInfoBuf,"%s%s", szInfoBuf, szLan);
for (i=0; i<m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struIOAlarm.dwTrigerAlarmOutNum; i++)
{
if (*(m_struAlarmInfoV40.pAlarmData + i) != 0xffffffff)
{
sprintf(szInfoBuf,"%s %d,", szInfoBuf, *(m_struAlarmInfoV40.pAlarmData + i));
}
}
g_StringLanType(szLan, ",触发通道录像:", "Invoke record Channel:");
sprintf(szInfoBuf,"%s%s", szInfoBuf, szLan);
dwOffSetLen += m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struIOAlarm.dwTrigerAlarmOutNum;
for (i=0; i<m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struIOAlarm.dwTrigerRecordChanNum; i++)
{
if (*(m_struAlarmInfoV40.pAlarmData + dwOffSetLen) != 0xffffffff)
{
sprintf(szInfoBuf,"%s %d,", szInfoBuf, *(m_struAlarmInfoV40.pAlarmData + dwOffSetLen));
dwOffSetLen++;
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T,szInfoBuf);
break;
case 1://hard disk full alarm
g_StringLanType(szInfoBuf, "硬盘满报警", "HD is full:");
for (i=0; i<m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struAlarmHardDisk.dwAlarmHardDiskNum; i++)
{
// if (m_struAlarmInfoV40.dwAlarmData[dwOffSetLen/4] != 0xffffffff )
// {
// sprintf(szInfoBuf, "%s HDD%d ", szInfoBuf, m_struAlarmInfoV40.dwAlarmData[dwOffSetLen/4]);
// dwOffSetLen ++;
// }
if (*(m_struAlarmInfoV40.pAlarmData + dwOffSetLen) != 0xffffffff )
{
sprintf(szInfoBuf, "%s HDD%d ", szInfoBuf, *(m_struAlarmInfoV40.pAlarmData + dwOffSetLen));
dwOffSetLen ++;
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T,szInfoBuf);
break;
case 4://hard disk unformatted alarm
g_StringLanType(szInfoBuf, "硬盘未格式化报警", "not formatted");
for (i=0; i<m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struAlarmHardDisk.dwAlarmHardDiskNum; i++)
{
dwTemp = *(m_struAlarmInfoV40.pAlarmData + dwOffSetLen);
if (dwTemp > 0)
{
sprintf(szInfoBuf, "%s HDD%d ", szInfoBuf,dwTemp);
dwOffSetLen++;
}
else
{
break;
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 5://hard disk alarm
for (i=0; i<m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struAlarmHardDisk.dwAlarmHardDiskNum; i++)
{
dwTemp = *(m_struAlarmInfoV40.pAlarmData + dwOffSetLen);
if (dwTemp > 0)
{
bDisk = TRUE;
g_StringLanType(szLan, "读写硬盘出错", "failed to read and write HDD");
sprintf(szInfoBuf, "%sHDD%d ", szLan, dwTemp);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
dwOffSetLen++;
}
else
{
break;
}
}
if (bDisk == FALSE)
{
g_StringLanType(szInfoBuf, "未接硬盘导致出错报警", "No HDD");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
bDisk = FALSE;
break;
case 2://video loss alarm
bAlarmOut = TRUE;
g_StringLanType(szInfoBuf, "视频信号丢失报警", "The signal lost");
break;
case 3://motion detection alarm
bAlarmOut = TRUE;
g_StringLanType(szInfoBuf, "移动侦测报警", "motion detection");
break;
case 6://mask alarm
bAlarmOut = TRUE;
g_StringLanType(szInfoBuf, "发生遮挡报警", "Mask alarm");
break;
case 9:
bAlarmOut = TRUE;
g_StringLanType(szInfoBuf, "视频信号异常", "video exception");
break;
case 10:
bAlarmOut = TRUE;
g_StringLanType(szInfoBuf, "录像异常", "record exception");
break;
case 11:
bAlarmOut = TRUE;
g_StringLanType(szInfoBuf, "智能场景变化", "Vca scene change");
break;
case 13:
bAlarmOut = TRUE;
g_StringLanType(szInfoBuf, "前端/录像分辨率不匹配", "resolution mismatch");
break;
case 7: //type unmatched
g_StringLanType(szInfoBuf, "制式不匹配", "input and output video standard not match");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 8:
g_StringLanType(szInfoBuf, "非法访问", "illegal access");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 12:
g_StringLanType(szInfoBuf, "阵列异常", "Array exception");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T,szInfoBuf);
break;
case 14:
g_StringLanType(szInfoBuf, "申请解码资源失败", "Alloc decoede resource fail");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 15:
bAlarmOut = TRUE;
g_StringLanType(szInfoBuf, "智能侦测报警", "VCA Detection");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 16:
g_StringLanType(szInfoBuf, "热备异常报警", "host record alarm");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 17:
g_StringLanType(szInfoBuf, "录播主机报警", "hot spare alarm");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 18:
g_StringLanType(szInfoBuf, "语音对讲请求报警", "Talkback requesting alarm");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 19:
bAlarmOut = TRUE;
g_StringLanType(szInfoBuf, "音频信号丢失报警", "The audio signal lost");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 22:
g_StringLanType(szInfoBuf, "车辆检测算法异常报警", "Vehicle Detection Algorithm alarm");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 23:
g_StringLanType(szLan, "脉冲报警 报警输入号", "Pulse alarm input No.");
sprintf(szInfoBuf, "%s%d", szLan, m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struIOAlarm.dwAlarmInputNo + 1);
g_StringLanType(szLan, ",关联报警输出号:", "Invoke Alarm Out:");
sprintf(szInfoBuf, "%s%s", szInfoBuf, szLan);
for (i = 0; i < m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struIOAlarm.dwTrigerAlarmOutNum; i++)
{
if (*(m_struAlarmInfoV40.pAlarmData + i) != 0xffffffff)
{
sprintf(szInfoBuf, "%s %d,", szInfoBuf, *(m_struAlarmInfoV40.pAlarmData + i));
}
}
g_StringLanType(szLan, ",触发通道录像:", "Invoke record Channel:");
sprintf(szInfoBuf, "%s%s", szInfoBuf, szLan);
dwOffSetLen += m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struIOAlarm.dwTrigerAlarmOutNum;
for (i = 0; i < m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struIOAlarm.dwTrigerRecordChanNum; i++)
{
if (*(m_struAlarmInfoV40.pAlarmData + dwOffSetLen) != 0xffffffff)
{
sprintf(szInfoBuf, "%s %d,", szInfoBuf, *(m_struAlarmInfoV40.pAlarmData + dwOffSetLen));
dwOffSetLen++;
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 24:
g_StringLanType(szInfoBuf, "人脸库硬盘异常", "FDLib Disk lost alarm");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 25:
g_StringLanType(szInfoBuf, "人脸库变更", "FDLib changed");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 26:
g_StringLanType(szInfoBuf, "人脸库图片变更", "FDLib picture changed");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 27:
g_StringLanType(szInfoBuf, "POC 异常", "POC Exception");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 28:
bAlarmOut = TRUE;
g_StringLanType(szInfoBuf, "相机视角异常", "camera angle anomaly");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 30:
g_StringLanType(szInfoBuf, "缺少 SD卡", "Lack of SD card");
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case 31:
fTemp= m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struVoltageInstable.fVoltageValue;
g_StringLanType(szInfoBuf, "电源电压报警", "Lack of SD card");
g_StringLanType(szLan, "电压报警类型", "Voltage Alarm Type");
sprintf(szInfoBuf, "%s:%s[%d]", szInfoBuf, szLan, m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struVoltageInstable.byVoltageAlarmType);
g_StringLanType(szLan, "电源电压值", "Voltage Value of Power Supply");
sprintf(szInfoBuf, "%s %s[%0.1f]", szInfoBuf, szLan, m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struVoltageInstable.fVoltageValue);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
default:
g_StringLanType(szLan, "未知报警类型:", "Unknown Alarm Type:");
sprintf(szInfoBuf, "%s 0x%x-htonl%d", szLan, m_struAlarmInfoV40.struAlarmFixedHeader.dwAlarmType, ntohl(m_struAlarmInfoV40.struAlarmFixedHeader.dwAlarmType));
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
}
if (bAlarmOut && pContent != NULL)
{
for (i=0; i<m_struAlarmInfoV40.struAlarmFixedHeader.uStruAlarm.struAlarmChannel.dwAlarmChanNum; i++)
{
dwTemp = *(m_struAlarmInfoV40.pAlarmData + dwOffSetLen);
dwTemp = *(pContent + i);
sprintf(szInfoBuf, "%s ,AlarmChan[%d]", szInfoBuf, dwTemp);
if (dwTemp > 0 && dwTemp < MAX_CHANNUM_V40)
{
//纯模拟通道或纯数字通道
if (0 == iDChanNum || 0 == iAChanNum)
{
if (!(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwTemp- 1].bAlarm))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwTemp- 1].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(dwTemp- 1));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwTemp- 1].chChanName);
}
else if(iAChanNum > 0 && iDChanNum > 0) //混合通道
{
//模拟通道
if (i < MAX_ANALOG_CHANNUM)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwTemp- 1].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwTemp- 1].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(dwTemp- 1));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwTemp- 1].chChanName);
}
else //数字通道
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+dwTemp- 1-MAX_ANALOG_CHANNUM].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+dwTemp- 1-MAX_ANALOG_CHANNUM].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(iAChanNum+dwTemp- 1-MAX_ANALOG_CHANNUM));
}
sprintf(szInfoBuf, "%s %s", szInfoBuf, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iAChanNum+dwTemp- 1-MAX_ANALOG_CHANNUM].chChanName);
}
}
dwOffSetLen++;
}
else
{
break;
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
if (m_struAlarmInfoV40.pAlarmData != NULL)
{
delete[](m_struAlarmInfoV40.pAlarmData);
m_struAlarmInfoV40.pAlarmData = NULL;
}
}
/*********************************************************
Function:
Desc:
Input: void
Output: void
Return: 0, same, else-difference
**********************************************************/
int CmpIPCfgAndIPCfgV31(LPNET_DVR_IPDEVINFO_V31 lpDevInfoV31, LPNET_DVR_IPDEVINFO lpDevInfo)
{
if (lpDevInfo->dwEnable != lpDevInfoV31->byEnable)
{
return -1;
}
if (lpDevInfo->wDVRPort != lpDevInfoV31->wDVRPort)
{
return -1;
}
if (memcmp((char *)(lpDevInfoV31->sPassword), (char *)(lpDevInfoV31->sPassword), PASSWD_LEN) != 0)
{
return -1;
}
if (memcmp((char *)(lpDevInfo->sUserName), (char *)(lpDevInfoV31->sUserName), MAX_NAMELEN) != 0)
{
return -1;
}
if (memcmp((char *)&(lpDevInfo->struIP), (char *)&(lpDevInfoV31->struIP), sizeof(NET_DVR_IPDEVINFO)) != 0)
{
return -1;
}
memset((char *)(lpDevInfoV31->byDomain), 0, MAX_DOMAIN_NAME);//the old ipc parameter change need to clear domain information
return 0;
}
/*********************************************************
Function: ProcIPCfgAlarm
Desc: process alarm information when
Input: void
Output: void
Return: void
**********************************************************/
void CClientDemoDlg::ProcIPCfgAlarm(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
int iRet = 0;
int i = 0;
NET_DVR_IPALARMINFO struIPAlarmInfo;
memcpy(&struIPAlarmInfo, pAlarmInfo, sizeof(NET_DVR_IPALARMINFO));
for (i = 0; i < ARRAY_SIZE(struIPAlarmInfo.struIPChanInfo); i++)
{
memcpy(&g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].struStreamMode[i].uGetStream.struChanInfo, \
&struIPAlarmInfo.struIPChanInfo[i], sizeof(NET_DVR_IPCHANINFO));
}
iRet |= memcmp(g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].byAnalogChanEnable, struIPAlarmInfo.byAnalogChanEnable, sizeof(struIPAlarmInfo.byAnalogChanEnable));
for (i=0; i < MAX_IP_DEVICE; i++)
{
iRet |= CmpIPCfgAndIPCfgV31(&(g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].struIPDevInfo[i]), &(struIPAlarmInfo.struIPDevInfo[i]));
}
if (iRet != 0)
{
for (i = 0; i < ARRAY_SIZE(struIPAlarmInfo.struIPChanInfo); i++)
{
memcpy(&g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].struStreamMode[i].uGetStream.struChanInfo, \
&struIPAlarmInfo.struIPChanInfo[i], sizeof(NET_DVR_IPCHANINFO));
}
memcpy(g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].byAnalogChanEnable, struIPAlarmInfo.byAnalogChanEnable, sizeof(struIPAlarmInfo.byAnalogChanEnable));
memcpy(g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].struIPDevInfo, struIPAlarmInfo.struIPDevInfo, sizeof(struIPAlarmInfo.struIPDevInfo));
// memcpy(g_struDeviceInfo[iDeviceIndex].struAlarmInCfg.struIPAlarmInInfo, struIPAlarmInfo.struIPAlarmInInfo, MAX_IP_ALARMIN*sizeof(NET_DVR_IPALARMININFO));
// memcpy(g_struDeviceInfo[iDeviceIndex].struAlarmOutCfg.struIPAlarmOutInfo, struIPAlarmInfo.struIPAlarmOutInfo, MAX_IP_ALARMOUT*sizeof(NET_DVR_IPALARMOUTINFO));
g_pMainDlg->RefreshIPDevLocalCfg(iDeviceIndex);
g_pMainDlg->RedrawDeviceNode(iDeviceIndex);
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, "ip parameter is channged!");
}
/*********************************************************
Function: ProcIPCfgAlarmV31
Desc: process alarm information when
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::ProcIPCfgAlarmV31(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
int iRet = 0;
NET_DVR_IPALARMINFO_V31 struIPAlarmInfo;
memcpy(&struIPAlarmInfo, pAlarmInfo, sizeof(NET_DVR_IPALARMINFO_V31));
int i = 0;
for (i = 0; i < ARRAY_SIZE(struIPAlarmInfo.struIPChanInfo); i++)
{
memcpy(&g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].struStreamMode[i].uGetStream.struChanInfo, \
&struIPAlarmInfo.struIPChanInfo[i], sizeof(NET_DVR_IPCHANINFO));
}
iRet |= memcmp(g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].byAnalogChanEnable, struIPAlarmInfo.byAnalogChanEnable, sizeof(struIPAlarmInfo.byAnalogChanEnable));
iRet |= memcmp(g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].struIPDevInfo, struIPAlarmInfo.struIPDevInfo, sizeof(struIPAlarmInfo.struIPDevInfo));//9000_1.1 need change
if (iRet != 0)
{
for (i = 0; i < ARRAY_SIZE(struIPAlarmInfo.struIPChanInfo); i++)
{
memcpy(&g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].struStreamMode[i].uGetStream.struChanInfo, \
&struIPAlarmInfo.struIPChanInfo[i], sizeof(NET_DVR_IPCHANINFO));
}
memcpy(g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].byAnalogChanEnable, struIPAlarmInfo.byAnalogChanEnable, sizeof(struIPAlarmInfo.struIPChanInfo));
memcpy(g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].struIPDevInfo, struIPAlarmInfo.struIPDevInfo, sizeof(struIPAlarmInfo.struIPDevInfo));
//memcpy(g_struDeviceInfo[iDeviceIndex].struAlarmInCfg.struIPAlarmInInfo, struIPAlarmInfo.struIPAlarmInInfo, MAX_IP_ALARMIN*sizeof(NET_DVR_IPALARMININFO));
//memcpy(g_struDeviceInfo[iDeviceIndex].struAlarmOutCfg.struIPAlarmOutInfo, struIPAlarmInfo.struIPAlarmOutInfo, MAX_IP_ALARMOUT*sizeof(NET_DVR_IPALARMOUTINFO));
g_pMainDlg->RefreshIPDevLocalCfg(iDeviceIndex);
g_pMainDlg->RedrawDeviceNode(iDeviceIndex);
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, "ip parameter v31 is channged!");
}
void CClientDemoDlg::ProcPdcAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
int iPort = pAlarmDev->wLinkPort;
NET_DVR_PDC_ALRAM_INFO struPDCAlarmInfo;
memset(&struPDCAlarmInfo, 0, sizeof(struPDCAlarmInfo));
CTime time = CTime::GetCurrentTime();
memcpy(&struPDCAlarmInfo, pAlarmInfo, sizeof(struPDCAlarmInfo));
i = struPDCAlarmInfo.byChannel-g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
if (struPDCAlarmInfo.byMode == 0 )
{
// 打印信息
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwAbsTime);
NET_DVR_TIME struRelativeTime = {0};
struRelativeTime.dwYear = GET_YEAR(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwRelativeTime);
struRelativeTime.dwMonth = GET_MONTH(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwRelativeTime);
struRelativeTime.dwDay = GET_DAY(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwRelativeTime);
struRelativeTime.dwHour = GET_HOUR(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwRelativeTime);
struRelativeTime.dwMinute = GET_MINUTE(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwRelativeTime);
struRelativeTime.dwSecond = GET_SECOND(struPDCAlarmInfo.uStatModeParam.struStatFrame.dwRelativeTime);
sprintf(szInfoBuf, "Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d flag[%d] %2.2d%2.2d]] Rel[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] \
DevIP:[%s]Port[%d]Channel[%d] IvmsChannel[%d]IvmsChannelEx[%d] \
single frame:Channel[%d]LeaveNum[%d]EnterNum[%d]Passing[%d]Smart[%d] \
BrokenNetHttp[%d] ChildLeaveNum[%d] ChildEnterNum[%d] DuplicatePeople[%d]",
struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond,
struPDCAlarmInfo.uStatModeParam.struStatFrame.byTimeDiffFlag, struPDCAlarmInfo.uStatModeParam.struStatFrame.cTimeDifferenceH, struPDCAlarmInfo.uStatModeParam.struStatFrame.cTimeDifferenceM,
struRelativeTime.dwYear, struRelativeTime.dwMonth, struRelativeTime.dwDay, struRelativeTime.dwHour, struRelativeTime.dwMinute, struRelativeTime.dwSecond,
struPDCAlarmInfo.struDevInfo.struDevIP.sIpV4, struPDCAlarmInfo.struDevInfo.wPort, struPDCAlarmInfo.struDevInfo.byChannel,
struPDCAlarmInfo.struDevInfo.byIvmsChannel, struPDCAlarmInfo.wDevInfoIvmsChannelEx,
struPDCAlarmInfo.byChannel, struPDCAlarmInfo.dwLeaveNum, struPDCAlarmInfo.dwEnterNum,
struPDCAlarmInfo.dwPassingNum, struPDCAlarmInfo.bySmart, struPDCAlarmInfo.byBrokenNetHttp,
struPDCAlarmInfo.dwChildLeaveNum, struPDCAlarmInfo.dwChildEnterNum,
struPDCAlarmInfo.dwDuplicatePeople);
}
else if (struPDCAlarmInfo.byMode == 1 || struPDCAlarmInfo.byMode == 2)
{
sprintf(szInfoBuf, "DevIP:[%s]Port[%d]Channel[%d]:time range:Start Y[%d]M[%d]D[%d]H[%d]M[%d]S[%d] \
flag[%d] [%2.2d%2.2d] End Y[%d]M[%d]D[%d]H[%d]M[%d]S[%d] [%2.2d%2.2d]\
IvmsChannel[%d]IvmsChannelEx[%d]Channel[%d]LeaveNum[%d]EnterNum[%d]\
Passing[%d]Smart[%d]BrokenNetHttp[%d]Mode[%d] ChildLeaveNum[%d] \
ChildEnterNum[%d] DuplicatePeople[%d]",
struPDCAlarmInfo.struDevInfo.struDevIP.sIpV4, struPDCAlarmInfo.struDevInfo.wPort, struPDCAlarmInfo.struDevInfo.byChannel,
struPDCAlarmInfo.uStatModeParam.struStatTime.tmStart.dwYear,struPDCAlarmInfo.uStatModeParam.struStatTime.tmStart.dwMonth,struPDCAlarmInfo.uStatModeParam.struStatTime.tmStart.dwDay,
struPDCAlarmInfo.uStatModeParam.struStatTime.tmStart.dwHour,struPDCAlarmInfo.uStatModeParam.struStatTime.tmStart.dwMinute,struPDCAlarmInfo.uStatModeParam.struStatTime.tmStart.dwSecond,
struPDCAlarmInfo.uStatModeParam.struStatTime.byTimeDifferenceFlag, struPDCAlarmInfo.uStatModeParam.struStatTime.cStartTimeDifferenceH, struPDCAlarmInfo.uStatModeParam.struStatTime.cStartTimeDifferenceM,
struPDCAlarmInfo.uStatModeParam.struStatTime.tmEnd.dwYear,struPDCAlarmInfo.uStatModeParam.struStatTime.tmEnd.dwMonth,struPDCAlarmInfo.uStatModeParam.struStatTime.tmEnd.dwDay,
struPDCAlarmInfo.uStatModeParam.struStatTime.tmEnd.dwHour,struPDCAlarmInfo.uStatModeParam.struStatTime.tmEnd.dwMinute,struPDCAlarmInfo.uStatModeParam.struStatTime.tmEnd.dwSecond,
struPDCAlarmInfo.uStatModeParam.struStatTime.cStopTimeDifferenceH, struPDCAlarmInfo.uStatModeParam.struStatTime.cStopTimeDifferenceM,
struPDCAlarmInfo.struDevInfo.byIvmsChannel, struPDCAlarmInfo.wDevInfoIvmsChannelEx,
struPDCAlarmInfo.byChannel, struPDCAlarmInfo.dwLeaveNum, struPDCAlarmInfo.dwEnterNum,
struPDCAlarmInfo.dwPassingNum, struPDCAlarmInfo.bySmart, struPDCAlarmInfo.byBrokenNetHttp,
struPDCAlarmInfo.byMode, struPDCAlarmInfo.dwChildLeaveNum, struPDCAlarmInfo.dwChildEnterNum,
struPDCAlarmInfo.dwDuplicatePeople);
}
g_pMainDlg->AddLog(iDeviceIndex,ALARM_INFO_T,szInfoBuf);
if (struPDCAlarmInfo.dwXmlLen > 0)
{
char sXMLFileName[256] = { 0 };
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
sprintf(sXMLFileName, "%s\\%s[%d]_channel[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, struPDCAlarmInfo.byChannel);
if (GetFileAttributes(sXMLFileName) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(sXMLFileName, NULL);
}
SYSTEMTIME tNow = { 0 };
GetLocalTime(&tNow);
sprintf(sXMLFileName, "%s\\PDC_XML[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d].xml",
sXMLFileName, tNow.wYear, tNow.wMonth, tNow.wDay, tNow.wHour, tNow.wMinute, tNow.wSecond, tNow.wMilliseconds);
HANDLE hXMLFile = CreateFile(sXMLFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hXMLFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwReturn = 0;
WriteFile(hXMLFile, struPDCAlarmInfo.pXmlBuf, struPDCAlarmInfo.dwXmlLen, &dwReturn, NULL);
CloseHandle(hXMLFile);
hXMLFile = NULL;
sprintf(szInfoBuf, "PDC XML Block Path:%s", sXMLFileName);
szInfoBuf[sizeof(szInfoBuf) - 1] = 0; //防止溢出
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
if (struPDCAlarmInfo.pXmlBuf != NULL)
{
delete[](struPDCAlarmInfo.pXmlBuf);
struPDCAlarmInfo.pXmlBuf = NULL;
}
}
/*********************************************************
Function: ProcRuleAlarm
Desc: process behavior alarm information
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::ProcRuleAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
if (iDeviceIndex > 512)
{
return;
}
int iPort = pAlarmDev->wLinkPort;
NET_VCA_RULE_ALARM struVcaRuleAlarm;
CTime time = CTime::GetCurrentTime();
memcpy(&struVcaRuleAlarm, pAlarmInfo, sizeof(NET_VCA_RULE_ALARM));
i = struVcaRuleAlarm.struDevInfo.byIvmsChannel-g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
if (g_pMainDlg != NULL)
{
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
char szAlarmBufEx[64] = { 0 };
switch(struVcaRuleAlarm.struRuleInfo.wEventTypeEx)
{
case ENUM_VCA_EVENT_TRAVERSE_PLANE:
sprintf(szAlarmBufEx, "traverse plane detection byDetectionTarget[%d]", struVcaRuleAlarm.struRuleInfo.uEventParam.struTraversePlane.byDetectionTarget);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szAlarmBufEx);
break;
case ENUM_VCA_EVENT_INTRUSION:
sprintf(szAlarmBufEx, "field detection byDetectionTarget[%d]", struVcaRuleAlarm.struRuleInfo.uEventParam.struIntrusion.byDetectionTarget);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szAlarmBufEx);
break;
case ENUM_VCA_EVENT_ENTER_AREA:
sprintf(szAlarmBufEx, "enter area detection byDetectionTarget[%d]", struVcaRuleAlarm.struRuleInfo.uEventParam.struArea.byDetectionTarget);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szAlarmBufEx);
break;
case ENUM_VCA_EVENT_EXIT_AREA:
sprintf(szAlarmBufEx, "exit area detection byDetectionTarget[%d]", struVcaRuleAlarm.struRuleInfo.uEventParam.struArea.byDetectionTarget);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szAlarmBufEx);
break;
default:
break;
}
NET_DVR_TIME struAbsTime = { 0 };
struAbsTime.dwYear = GET_YEAR(struVcaRuleAlarm.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struVcaRuleAlarm.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struVcaRuleAlarm.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struVcaRuleAlarm.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struVcaRuleAlarm.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struVcaRuleAlarm.dwAbsTime);
NET_DVR_TIME struRelativeTime = { 0 };
struRelativeTime.dwYear = GET_YEAR(struVcaRuleAlarm.dwRelativeTime);
struRelativeTime.dwMonth = GET_MONTH(struVcaRuleAlarm.dwRelativeTime);
struRelativeTime.dwDay = GET_DAY(struVcaRuleAlarm.dwRelativeTime);
struRelativeTime.dwHour = GET_HOUR(struVcaRuleAlarm.dwRelativeTime);
struRelativeTime.dwMinute = GET_MINUTE(struVcaRuleAlarm.dwRelativeTime);
struRelativeTime.dwSecond = GET_SECOND(struVcaRuleAlarm.dwRelativeTime);
char szTime[128] = {0};
sprintf(szTime, "VCA Alarm time flag[%d] Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] relative[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d]", struVcaRuleAlarm.byRelativeTimeFlag,
struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond,
struRelativeTime.dwYear, struRelativeTime.dwMonth, struRelativeTime.dwDay, struRelativeTime.dwHour, struRelativeTime.dwMinute, struRelativeTime.dwSecond);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szTime);
char csRuleName[33] = {0};
memcpy(csRuleName, struVcaRuleAlarm.struRuleInfo.byRuleName, 32);
//行为分析结果上报结构
sprintf(szInfoBuf, "Smart:[%d] DevIP:[%s]TargetID[%d]RuleID[%d]RuleName[%s]AbsTime[%d]piclen[%d]PicType[%d]RelAlarmPicNum[%d]AlarmID[%d]IvmsChannel[%d]IvmsChannelEx[%d]EventTypeEx[%d]byPicTransType[%d]RECT[X:%f][Y:%f][H:%f][W:%f]bySceneID[%d]",
struVcaRuleAlarm.bySmart,
struVcaRuleAlarm.struDevInfo.struDevIP.sIpV4,struVcaRuleAlarm.struTargetInfo.dwID,
struVcaRuleAlarm.struRuleInfo.byRuleID, csRuleName,
struVcaRuleAlarm.dwAbsTime, struVcaRuleAlarm.dwPicDataLen, struVcaRuleAlarm.byPicType,struVcaRuleAlarm.byRelAlarmPicNum,struVcaRuleAlarm.dwAlarmID,
struVcaRuleAlarm.struDevInfo.byIvmsChannel, struVcaRuleAlarm.wDevInfoIvmsChannelEx,\
struVcaRuleAlarm.struRuleInfo.wEventTypeEx, struVcaRuleAlarm.byPicTransType, struVcaRuleAlarm.struTargetInfo.struRect.fX, struVcaRuleAlarm.struTargetInfo.struRect.fY,
struVcaRuleAlarm.struTargetInfo.struRect.fHeight, struVcaRuleAlarm.struTargetInfo.struRect.fWidth, struVcaRuleAlarm.struRuleInfo.bySceneID);
g_pMainDlg->AddLog(iDeviceIndex,ALARM_INFO_T,szInfoBuf);
NET_VCA_DEV_INFO tmpDevInfo;
memcpy(&tmpDevInfo, &struVcaRuleAlarm.struDevInfo, sizeof(NET_VCA_DEV_INFO));
sprintf(szInfoBuf,"\nNET_VCA_DEV_INFO:DevIP[%s]Port[%d]Channel[%d]\n",
tmpDevInfo.struDevIP.sIpV4, tmpDevInfo.wPort, tmpDevInfo.byChannel);
OutputDebugString(szInfoBuf);
NET_VCA_TARGET_INFO tmpTargetInfo;
memcpy(&tmpTargetInfo, &struVcaRuleAlarm.struTargetInfo, sizeof(NET_VCA_TARGET_INFO));
sprintf(szInfoBuf, "NET_VCA_TARGET_INFO:ID[%d]RECT[%f][%f][%f][%f]\n",
tmpTargetInfo.dwID, tmpTargetInfo.struRect.fX, tmpTargetInfo.struRect.fY,
tmpTargetInfo.struRect.fWidth, tmpTargetInfo.struRect.fHeight);
OutputDebugString(szInfoBuf);
switch (struVcaRuleAlarm.struRuleInfo.wEventTypeEx)
{
case ENUM_VCA_EVENT_TRAVERSE_PLANE://
{
sprintf(szInfoBuf,"ENUM_VCA_EVENT_TRAVERSE_PLANE:struRul:start[%f][%f]end[%f][%f]\ndwCrossDirection:[%d]bySensitivity[%d]\n"
,struVcaRuleAlarm.struRuleInfo.uEventParam.struTraversePlane.struPlaneBottom.struStart.fX,
struVcaRuleAlarm.struRuleInfo.uEventParam.struTraversePlane.struPlaneBottom.struStart.fY,
struVcaRuleAlarm.struRuleInfo.uEventParam.struTraversePlane.struPlaneBottom.struEnd.fX,
struVcaRuleAlarm.struRuleInfo.uEventParam.struTraversePlane.struPlaneBottom.struEnd.fY,
struVcaRuleAlarm.struRuleInfo.uEventParam.struTraversePlane.dwCrossDirection/*,
struVcaRuleAlarm.struRuleInfo.uEventParam.struTraversePlane.bySensitivity*/);
OutputDebugString(szInfoBuf);
}
break;
case ENUM_VCA_EVENT_ENTER_AREA:
{
// sprintf(szInfoBuf,"VCA_ENTER_AREA:Senetity[%d]\nNET_VCA_POLYGON",struVcaRuleAlarm.struRuleInfo.uEventParam.struArea.bySensitivity);
// OutputDebugString(szInfoBuf);
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon,&struVcaRuleAlarm.struRuleInfo.uEventParam.struArea.struRegion,sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Enter area");
for (i = 0; i < (int)tempPolygon.dwPointNum ;i ++)
{
sprintf(szInfoBuf,"[%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
}
break;
case ENUM_VCA_EVENT_EXIT_AREA:
{
// sprintf(szInfoBuf,"VCA_EXIT_AREA:Senetity[%d]\nNET_VCA_POLYGON",struVcaRuleAlarm.struRuleInfo.uEventParam.struArea.bySensitivity);
// OutputDebugString(szInfoBuf);
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon,&struVcaRuleAlarm.struRuleInfo.uEventParam.struArea.struRegion,sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Exit Area");
for (i = 0; i < (int)tempPolygon.dwPointNum ;i ++)
{
sprintf(szInfoBuf,"[%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
}
break;
case ENUM_VCA_EVENT_INTRUSION:
{
// sprintf(szInfoBuf,"VCA_INTRUSION:Sensitivity[%d]\nNET_VCA_POLYGON",
// struVcaRuleAlarm.struRuleInfo.uEventParam.struIntrusion.bySensitivity);
// OutputDebugString(szInfoBuf);
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon,&struVcaRuleAlarm.struRuleInfo.uEventParam.struIntrusion.struRegion,sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Event Intrusion");
for (i = 0; i < (int)tempPolygon.dwPointNum ;i ++)
{
sprintf(szInfoBuf,"[%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
}
break;
case ENUM_VCA_EVENT_LOITER:
{
// sprintf(szInfoBuf,"VCA_LOITER:Senetity[%d]\nNET_VCA_POLYGON",
// struVcaRuleAlarm.struRuleInfo.uEventParam.struLoiter.bySensitivity);
// OutputDebugString(szInfoBuf);
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon,&struVcaRuleAlarm.struRuleInfo.uEventParam.struLoiter.struRegion,sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Loiter");
for (i = 0; i < (int)tempPolygon.dwPointNum ;i ++)
{
sprintf(szInfoBuf,"[%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
}
break;
case ENUM_VCA_EVENT_LEFT_TAKE:
{
// sprintf(szInfoBuf,"VCA_LEFT_TAKE:Senetity[%d]\nNET_VCA_POLYGON",
// struVcaRuleAlarm.struRuleInfo.uEventParam.struTakeTeft.bySensitivity);
// OutputDebugString(szInfoBuf);
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon,&struVcaRuleAlarm.struRuleInfo.uEventParam.struTakeTeft.struRegion,sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Left Take");
for (i = 0; i < (int)tempPolygon.dwPointNum ;i ++)
{
sprintf(szInfoBuf,"[%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
}
break;
case ENUM_VCA_EVENT_PARKING:
{
// sprintf(szInfoBuf,"VCA_PARKING:Senetity[%d]\nNET_VCA_POLYGON",
// struVcaRuleAlarm.struRuleInfo.uEventParam.struParking.bySensitivity);
// OutputDebugString(szInfoBuf);
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon,&struVcaRuleAlarm.struRuleInfo.uEventParam.struParking.struRegion,sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Parking");
for (i = 0; i < (int)tempPolygon.dwPointNum ;i ++)
{
sprintf(szInfoBuf,"[%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
}
break;
case ENUM_VCA_EVENT_RUN:
{
// sprintf(szInfoBuf,"VCA_RUN:Senetity[%d]\nNET_VCA_POLYGON",
// struVcaRuleAlarm.struRuleInfo.uEventParam.struRun.bySensitivity);
// OutputDebugString(szInfoBuf);
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon,&struVcaRuleAlarm.struRuleInfo.uEventParam.struRun.struRegion,sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Run");
for (i = 0; i < (int)tempPolygon.dwPointNum ;i ++)
{
sprintf(szInfoBuf,"[%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
}
break;
case ENUM_VCA_EVENT_HIGH_DENSITY:
{
// sprintf(szInfoBuf,"VCA_HIGH_DENSITY:Senetity[%d]\nNET_VCA_POLYGON",
// struVcaRuleAlarm.struRuleInfo.uEventParam.struHighDensity.bySensitivity);
// OutputDebugString(szInfoBuf);
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon,&struVcaRuleAlarm.struRuleInfo.uEventParam.struHighDensity.struRegion,sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "High Density");
for (i = 0; i < (int)tempPolygon.dwPointNum ;i ++)
{
sprintf(szInfoBuf,"[%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
}
break;
case ENUM_VCA_EVENT_VIOLENT_MOTION:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struHighDensity.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Violent Motion");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "[%f][%f]", tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
sprintf(szInfoBuf, "%s [%d] bySensitivity[%d] byMode[%d] ", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struViolentMotion.wDuration, struVcaRuleAlarm.struRuleInfo.uEventParam.struViolentMotion.bySensitivity, struVcaRuleAlarm.struRuleInfo.uEventParam.struViolentMotion.byMode);
OutputDebugString(szInfoBuf);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_GET_UP:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struGetUp.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Get Up:");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "[%f][%f]", tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
sprintf(szInfoBuf, "%s [%d] byMode[%d] bySensitivity[%d] ", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struGetUp.wDuration, struVcaRuleAlarm.struRuleInfo.uEventParam.struGetUp.byMode, struVcaRuleAlarm.struRuleInfo.uEventParam.struGetUp.bySensitivity);
OutputDebugString(szInfoBuf);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_LEAVE_POSITION:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struHighDensity.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Leave Position:");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "[%f][%f]", tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
sprintf(szInfoBuf, "%s [%d] wStaticDelay[%d] byMode[%d] byPersonType[%d] byOnPosition[%d] ", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struLeavePos.wLeaveDelay, struVcaRuleAlarm.struRuleInfo.uEventParam.struLeavePos.wStaticDelay, struVcaRuleAlarm.struRuleInfo.uEventParam.struLeavePos.byMode, struVcaRuleAlarm.struRuleInfo.uEventParam.struLeavePos.byPersonType, struVcaRuleAlarm.struRuleInfo.uEventParam.struLeavePos.byOnPosition);
OutputDebugString(szInfoBuf);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_FALL_DOWN:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struHighDensity.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Fall Down: ");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "[%f][%f]", tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
sprintf(szInfoBuf, "%s [%d] bySensitivity[%d] byHeightThreshold[%d]", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struFallDown.wDuration, struVcaRuleAlarm.struRuleInfo.uEventParam.struFallDown.bySensitivity, struVcaRuleAlarm.struRuleInfo.uEventParam.struFallDown.byHeightThreshold);
OutputDebugString(szInfoBuf);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_TOILET_TARRY:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struToiletTarry.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Toilet Tarry: ");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "[%f][%f]", tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
sprintf(szInfoBuf, "%s wDelay[%d]", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struToiletTarry.wDelay);
OutputDebugString(szInfoBuf);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_LECTURE:
case VCA_LECTURE:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon,&struVcaRuleAlarm.struRuleInfo.uEventParam.struLecture.struRegion,sizeof(NET_VCA_POLYGON));
for (i = 0; i < (int)tempPolygon.dwPointNum ;i ++)
{
if (struVcaRuleAlarm.struRuleInfo.uEventParam.struLecture.byAlarmState == 1)
{
sprintf(szInfoBuf,"Lecture Event Start[%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
}
else if (struVcaRuleAlarm.struRuleInfo.uEventParam.struLecture.byAlarmState == 2)
{
sprintf(szInfoBuf,"Lecture Event End[%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
}
sprintf(szInfoBuf, "%s ZoomOver[%d]", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struLecture.byZoomOver);
OutputDebugString(szInfoBuf);
g_pMainDlg->AddLog(iDeviceIndex,ALARM_INFO_T,szInfoBuf);
}
}
break;
case ENUM_VCA_EVENT_ANSWER:
case VCA_ANSWER:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon,&struVcaRuleAlarm.struRuleInfo.uEventParam.struAnswer.struRegion,sizeof(NET_VCA_POLYGON));
for (i = 0; i < (int)tempPolygon.dwPointNum ;i ++)
{
if (struVcaRuleAlarm.struRuleInfo.uEventParam.struAnswer.byAlarmState == 1)
{
sprintf(szInfoBuf,"Answering Questions Event [%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
}
else if(struVcaRuleAlarm.struRuleInfo.uEventParam.struAnswer.byAlarmState == 2)
{
sprintf(szInfoBuf,"Answering Questions Event [%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
}
sprintf(szInfoBuf, "%s ZoomOver[%d] AnswerStudent[%d]", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struAnswer.byZoomOver, struVcaRuleAlarm.struRuleInfo.uEventParam.struAnswer.byAnswerStudent);
OutputDebugString(szInfoBuf);
g_pMainDlg->AddLog(iDeviceIndex,ALARM_INFO_T,szInfoBuf);
}
}
break;
case ENUM_VCA_EVENT_COMBINED_RULE:
{
sprintf(szInfoBuf, "Combined Rule, RuleSequence[%d] MinInterval[%d] MaxInterval[%d] RuleID1[%d] RuleID2[%d]", struVcaRuleAlarm.struRuleInfo.uEventParam.struCombinedRule.byRuleSequence,\
struVcaRuleAlarm.struRuleInfo.uEventParam.struCombinedRule.dwMinInterval, struVcaRuleAlarm.struRuleInfo.uEventParam.struCombinedRule.dwMaxInterval, \
struVcaRuleAlarm.struRuleInfo.uEventParam.struCombinedRule.struRule1Raram.byRuleID, struVcaRuleAlarm.struRuleInfo.uEventParam.struCombinedRule.struRule2Raram.byRuleID);
OutputDebugString(szInfoBuf);
g_pMainDlg->AddLog(iDeviceIndex,ALARM_INFO_T,szInfoBuf);
}
break;
case ENUM_VCA_EVENT_HIGH_DENSITY_STATUS:
{
// sprintf(szInfoBuf,"VCA_HIGH_DENSITY:Senetity[%d]\nNET_VCA_POLYGON",
// struVcaRuleAlarm.struRuleInfo.uEventParam.struHighDensity.bySensitivity);
// OutputDebugString(szInfoBuf);
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon,&struVcaRuleAlarm.struRuleInfo.uEventParam.struHighDensityStatus.struRegion,sizeof(NET_VCA_POLYGON));
for (i = 0; i < (int)tempPolygon.dwPointNum ;i ++)
{
sprintf(szInfoBuf,"[%f][%f]",tempPolygon.struPos[i].fX,tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
}
break;
case ENUM_VCA_EVENT_PEOPLENUM_CHANGE:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struHighDensityStatus.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "People number change");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "%s Point[%d] [%f][%f]", szInfoBuf, i, tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
}
sprintf(szInfoBuf, "%s byPeopleNumThreshold[%d] byDetectMode[%d] byNoneStateEffective[%d] wDuration[%d] byPeopleNum[%d]",
szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struPeopleNumChange.byPeopleNumThreshold, \
struVcaRuleAlarm.struRuleInfo.uEventParam.struPeopleNumChange.byDetectMode, struVcaRuleAlarm.struRuleInfo.uEventParam.struPeopleNumChange.byNoneStateEffective, \
struVcaRuleAlarm.struRuleInfo.uEventParam.struPeopleNumChange.wDuration, struVcaRuleAlarm.struRuleInfo.uEventParam.struPeopleNumChange.byPeopleNum);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_RUNNING:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struHighDensityStatus.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Running:");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "%s Point[%d] [%f][%f]", szInfoBuf, i, tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
sprintf(szInfoBuf, "%s dwSpeed[%d]",
szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struRunning.dwSpeed);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_RETENTION:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struHighDensityStatus.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Retention:");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "%s Point[%d] [%f][%f]", szInfoBuf, i, tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
sprintf(szInfoBuf, "%s wDuration[%d]",
szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struRetention.wDuration);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_SITUATION_ANALYSIS:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struSituationAnalysis.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Situation analysis:");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "%s Point[%d] [%f][%f]", szInfoBuf, i, tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
sprintf(szInfoBuf, "%s wPeopleNum[%d]", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struSituationAnalysis.wPeopleNum);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_PLAY_CELLPHONE:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struPlayCellphone.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "Play cellphone:");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "%s Point[%d] [%f][%f]", szInfoBuf, i, tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
sprintf(szInfoBuf, "%s wDuration[%d]", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struPlayCellphone.wDuration);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_DURATION:
{
sprintf(szInfoBuf, "duration:");
sprintf(szInfoBuf, "%s wRelationEventType[%d]", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struDruation.wRelationEventType);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_LEFT:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struTakeTeft.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "unattendedBaggage");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "%s Point[%d] [%f][%f]", szInfoBuf, i, tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
sprintf(szInfoBuf, "%s bySensitivity[%d] wDuration[%d]", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struTakeTeft.bySensitivity, struVcaRuleAlarm.struRuleInfo.uEventParam.struTakeTeft.wDuration);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
case ENUM_VCA_EVENT_TAKE:
{
NET_VCA_POLYGON tempPolygon;
memcpy(&tempPolygon, &struVcaRuleAlarm.struRuleInfo.uEventParam.struTakeTeft.struRegion, sizeof(NET_VCA_POLYGON));
sprintf(szInfoBuf, "attendedBaggage");
for (i = 0; i < (int)tempPolygon.dwPointNum; i++)
{
sprintf(szInfoBuf, "%s Point[%d] [%f][%f]", szInfoBuf, i, tempPolygon.struPos[i].fX, tempPolygon.struPos[i].fY);
OutputDebugString(szInfoBuf);
}
sprintf(szInfoBuf, "%s bySensitivity[%d] wDuration[%d]", szInfoBuf, struVcaRuleAlarm.struRuleInfo.uEventParam.struTakeTeft.bySensitivity, struVcaRuleAlarm.struRuleInfo.uEventParam.struTakeTeft.wDuration);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
break;
default:
break;
}
int appendnum = 0;
if (struVcaRuleAlarm.dwPicDataLen > 0 && struVcaRuleAlarm.pImage != NULL)
{
int num = ulAlarmPic/1000+1;
appendnum = num;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d][%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struVcaRuleAlarm.byPicTransType)
{
sprintf(cFilename, "%s\\LocalTime[%s]TargetID[%d]RuleName[%s]AlarmID[%d]_%d.txt", cFilename, chTime, \
struVcaRuleAlarm.struTargetInfo.dwID, csRuleName, struVcaRuleAlarm.dwAlarmID, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\LocalTime[%s]TargetID[%d]RuleName[%s]AlarmID[%d]_%d.jpg", cFilename, chTime, \
struVcaRuleAlarm.struTargetInfo.dwID, csRuleName, struVcaRuleAlarm.dwAlarmID, rand() % GetTickCount());
}
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struVcaRuleAlarm.pImage, struVcaRuleAlarm.dwPicDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struVcaRuleAlarm.byAppendInfoUploadEnabled==1)
{
NET_VCA_APPEND_INFO struAppendInfo = { 0 };
memset(&struAppendInfo, 0, sizeof(struAppendInfo));
memcpy(&struAppendInfo, struVcaRuleAlarm.pAppendInfo, sizeof(struAppendInfo));
sprintf(szInfoBuf, "append info:append pic type[%d];append pic len[%d];append UID[%s]",
struAppendInfo.byAppendPicType, struAppendInfo.dwAppendPicLen, struAppendInfo.byUID);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struAppendInfo.dwAppendPicLen>0 && struAppendInfo.pAppendPicBuff!=NULL)
{
char cFilename[256] = { 0 };
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d][%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, appendnum);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_appendPic.jpg", cFilename, chTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struAppendInfo.pAppendPicBuff, struAppendInfo.dwAppendPicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struAppendInfo.pAppendPicBuff != NULL)
{
delete[](struAppendInfo.pAppendPicBuff);
}
}
if (struVcaRuleAlarm.pImage != NULL)
{
delete [] (struVcaRuleAlarm.pImage);
}
if (struVcaRuleAlarm.pAppendInfo != NULL)
{
delete[](struVcaRuleAlarm.pAppendInfo);
}
}
void CClientDemoDlg::ProcAidAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_AID_ALARM struAidAlarm = {0};
CTime time = CTime::GetCurrentTime();
memcpy(&struAidAlarm, pAlarmInfo, sizeof(struAidAlarm));
i = struAidAlarm.struDevInfo.byIvmsChannel-g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struAidAlarm.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struAidAlarm.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struAidAlarm.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struAidAlarm.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struAidAlarm.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struAidAlarm.dwAbsTime);
CString str = "";
sprintf(szInfoBuf, "Aid Alarm IvmsChan[%d]ID[%d]Name[%s]Type[%d]Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d]Dev IP[%s]Port[%d]Chan[%d] \
Direction Start[%0.3f,%0.3f]Stop[%0.3f,%0.3f]",
struAidAlarm.struDevInfo.byIvmsChannel, struAidAlarm.struAIDInfo.byRuleID, struAidAlarm.struAIDInfo.byRuleName,
struAidAlarm.struAIDInfo.dwAIDType, struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay,
struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond, struAidAlarm.struDevInfo.struDevIP.sIpV4,
struAidAlarm.struDevInfo.wPort, struAidAlarm.struDevInfo.byChannel,
struAidAlarm.struAIDInfo.struDirect.struStartPoint.fX, struAidAlarm.struAIDInfo.struDirect.struStartPoint.fY,
struAidAlarm.struAIDInfo.struDirect.struEndPoint.fX, struAidAlarm.struAIDInfo.struDirect.struEndPoint.fY);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struAidAlarm.dwPicDataLen > 0 && struAidAlarm.pImage != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s_channel[%d]_AID", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, struAidAlarm.struDevInfo.byChannel);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\AIDAlarm_LocalTime[%s].jpg", cFilename, chTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struAidAlarm.pImage, struAidAlarm.dwPicDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struAidAlarm.pImage != NULL)
{
delete [] (struAidAlarm.pImage);
struAidAlarm.pImage = NULL;
}
}
void CClientDemoDlg::ProcTpsAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
unsigned int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_TPS_ALARM struTpsAlarm = {0};
memcpy(&struTpsAlarm, pAlarmInfo, sizeof(struTpsAlarm));
i = struTpsAlarm.struDevInfo.byIvmsChannel - g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struTpsAlarm.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struTpsAlarm.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struTpsAlarm.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struTpsAlarm.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struTpsAlarm.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struTpsAlarm.dwAbsTime);
sprintf(szInfoBuf, "Tps alarm Dev ip[%s]port[%d]Chan[%d] IvmsChan[%d] Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] LaneNum[%d]" , \
struTpsAlarm.struDevInfo.struDevIP.sIpV4, struTpsAlarm.struDevInfo.wPort, struTpsAlarm.struDevInfo.byChannel,struTpsAlarm.struDevInfo.byIvmsChannel,
struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
for (i = 0; i < struTpsAlarm.struTPSInfo.dwLanNum; i++)
{
sprintf(szInfoBuf, "ID[%d] Name[%s] VaryType[%d] LaneType[%d] Volume[%d] Velocity[%d] TimeHeadway[%d] SpaceHeadway[%d] SpceOccupy[%0.3f]",
struTpsAlarm.struTPSInfo.struLaneParam[i].byRuleID, struTpsAlarm.struTPSInfo.struLaneParam[i].byRuleName,
struTpsAlarm.struTPSInfo.struLaneParam[i].byVaryType, struTpsAlarm.struTPSInfo.struLaneParam[i].byLaneType,
struTpsAlarm.struTPSInfo.struLaneParam[i].dwLaneVolume, struTpsAlarm.struTPSInfo.struLaneParam[i].dwLaneVelocity,
struTpsAlarm.struTPSInfo.struLaneParam[i].dwTimeHeadway, struTpsAlarm.struTPSInfo.struLaneParam[i].dwSpaceHeadway,
struTpsAlarm.struTPSInfo.struLaneParam[i].fSpaceOccupyRation);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
}
void CClientDemoDlg::ProcTpsAlarmV41(WPARAM wParam,LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
if (iDeviceIndex < 0 || iDeviceIndex >= MAX_DEVICES)
{
return;
}
NET_DVR_TPS_ALARM_V41 struTpsAlarm = {0};
memcpy(&struTpsAlarm, pAlarmInfo, sizeof(struTpsAlarm));
i = struTpsAlarm.struDevInfo.byIvmsChannel - g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struTpsAlarm.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struTpsAlarm.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struTpsAlarm.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struTpsAlarm.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struTpsAlarm.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struTpsAlarm.dwAbsTime);
NET_DVR_TIME struStartTime = {0};
struStartTime.dwYear = GET_YEAR(struTpsAlarm.dwStartTime);
struStartTime.dwMonth = GET_MONTH(struTpsAlarm.dwStartTime);
struStartTime.dwDay = GET_DAY(struTpsAlarm.dwStartTime);
struStartTime.dwHour = GET_HOUR(struTpsAlarm.dwStartTime);
struStartTime.dwMinute = GET_MINUTE(struTpsAlarm.dwStartTime);
struStartTime.dwSecond = GET_SECOND(struTpsAlarm.dwStartTime);
NET_DVR_TIME struStopTime = {0};
struStopTime.dwYear = GET_YEAR(struTpsAlarm.dwStopTime);
struStopTime.dwMonth = GET_MONTH(struTpsAlarm.dwStopTime);
struStopTime.dwDay = GET_DAY(struTpsAlarm.dwStopTime);
struStopTime.dwHour = GET_HOUR(struTpsAlarm.dwStopTime);
struStopTime.dwMinute = GET_MINUTE(struTpsAlarm.dwStopTime);
struStopTime.dwSecond = GET_SECOND(struTpsAlarm.dwStopTime);
sprintf(szInfoBuf, "Tps alarm v41 Dev ip[%s]port[%d]Chan[%d] IvmsChan[%d] Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] LaneNum[%d]SceneId[%d] MonitoringSiteID[%s] DeviceID[%s] StartTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] StopTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d]" , \
struTpsAlarm.struDevInfo.struDevIP.sIpV4, struTpsAlarm.struDevInfo.wPort, struTpsAlarm.struDevInfo.byChannel,struTpsAlarm.struDevInfo.byIvmsChannel,
struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond,struTpsAlarm.struTPSInfo.dwLanNum,
struTpsAlarm.struTPSInfo.dwSceneID, struTpsAlarm.byMonitoringSiteID, struTpsAlarm.byDeviceID,
struStartTime.dwYear, struStartTime.dwMonth, struStartTime.dwDay, struStartTime.dwHour, struStartTime.dwMinute, struStartTime.dwSecond,
struStopTime.dwYear, struStopTime.dwMonth, struStopTime.dwDay, struStopTime.dwHour, struStopTime.dwMinute, struStopTime.dwSecond);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
for (i = 0; i < struTpsAlarm.struTPSInfo.dwLanNum; i++)
{
sprintf(szInfoBuf, "ID[%d] Name[%s] VaryType[%d] LaneType[%d] Volume[%d] Velocity[%d] TimeHeadway[%d] SpaceHeadway[%d] SpaceOccupy[%0.3f] \
TimeOccupy[%.3f] LightVehicle[%d] MidVehicle[%d] HeavyVehicle[%d] OversizeVehicle[%d] TrafficState[%d] LaneQueueHead[%0.3f,%0.3f] LaneQueueTail[%0.3f,%0.3f] \
LaneQueueLength[%d] LaneNo[%d]",
struTpsAlarm.struTPSInfo.struLaneParam[i].byRuleID, struTpsAlarm.struTPSInfo.struLaneParam[i].byRuleName,
struTpsAlarm.struTPSInfo.struLaneParam[i].dwVaryType, struTpsAlarm.struTPSInfo.struLaneParam[i].byLaneType,
struTpsAlarm.struTPSInfo.struLaneParam[i].dwLaneVolume, struTpsAlarm.struTPSInfo.struLaneParam[i].dwLaneVelocity,
struTpsAlarm.struTPSInfo.struLaneParam[i].dwTimeHeadway, struTpsAlarm.struTPSInfo.struLaneParam[i].dwSpaceHeadway,
struTpsAlarm.struTPSInfo.struLaneParam[i].fSpaceOccupyRation, struTpsAlarm.struTPSInfo.struLaneParam[i].fTimeOccupyRation,
struTpsAlarm.struTPSInfo.struLaneParam[i].dwLightVehicle, struTpsAlarm.struTPSInfo.struLaneParam[i].dwMidVehicle,
struTpsAlarm.struTPSInfo.struLaneParam[i].dwHeavyVehicle, struTpsAlarm.struTPSInfo.struLaneParam[i].dwOversizeVehicle,
struTpsAlarm.struTPSInfo.struLaneParam[i].byTrafficState,
struTpsAlarm.struTPSInfo.struLaneParam[i].struLaneQueue.struHead.fX,struTpsAlarm.struTPSInfo.struLaneParam[i].struLaneQueue.struHead.fY,
struTpsAlarm.struTPSInfo.struLaneParam[i].struLaneQueue.struTail.fX,struTpsAlarm.struTPSInfo.struLaneParam[i].struLaneQueue.struTail.fY,
struTpsAlarm.struTPSInfo.struLaneParam[i].struLaneQueue.dwLength,
struTpsAlarm.struTPSInfo.struLaneParam[i].byLaneNo);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
}
void CClientDemoDlg::ProcAidAlarmV41(WPARAM wParam,LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_AID_ALARM_V41 struAidAlarm = {0};
CTime time = CTime::GetCurrentTime();
memcpy(&struAidAlarm, pAlarmInfo, sizeof(struAidAlarm));
if (iDeviceIndex != -1 && iDeviceIndex <MAX_DEVICES)
{
i = struAidAlarm.struDevInfo.byIvmsChannel - g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struAidAlarm.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struAidAlarm.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struAidAlarm.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struAidAlarm.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struAidAlarm.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struAidAlarm.dwAbsTime);
char szAIDType[32] = { 0 };
if ((struAidAlarm.struAIDInfo.dwAIDType&ROADBLOCK) != 0)
{
g_StringLanType(szAIDType, "路障", "RoadBlock");
}
if ((struAidAlarm.struAIDInfo.dwAIDType&CONSTRUCTION) != 0)
{
char szAIDTypeTmp[32] = { 0 };
g_StringLanType(szAIDTypeTmp, "施工", "Construction");
sprintf(szAIDType, "%s%s", szAIDType, szAIDTypeTmp);
}
if ((struAidAlarm.struAIDInfo.dwAIDType&PEDESTRIAN) != 0)
{
char szAIDTypeTmp[32] = { 0 };
g_StringLanType(szAIDTypeTmp, "行人", "Passengers");
sprintf(szAIDType, "%s%s", szAIDType, szAIDTypeTmp);
}
if ((struAidAlarm.struAIDInfo.dwAIDType&TFS_MANUAL_TRIGGER) != 0)
{
char szAIDTypeTmp[32] = { 0 };
g_StringLanType(szAIDTypeTmp, "手动违章取证事件 ", "TFS_MANUAL_TRIGGER");
sprintf(szAIDType, "%s%s", szAIDType, szAIDTypeTmp);
}
//重新拷贝,解决48个字节时,打印乱码的问题
BYTE tempMonitoringSiteID[MONITORSITE_ID_LEN + 1/*49*/] = { 0 };
memcpy(tempMonitoringSiteID, struAidAlarm.byMonitoringSiteID, sizeof(struAidAlarm.byMonitoringSiteID));
CString str = "";
sprintf(szInfoBuf, "Aid AlarmV41 xmlLen[%d]IvmsChan[%d]ID[%d]Name[%s]Type[%d]VisibilityLevel[%d]newType[%s] TargetType[%d] LaneNo[%d] Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d]Dev IP[%s]Port[%d]Chan[%d] \
Direction Start[%0.3f,%0.3f]Stop[%0.3f,%0.3f] SceneID[%d] SceneName[%s] Direction[%d] PTZ[%d,%d,%d] MonitoringSiteID[%s] DeviceID[%s] VehicleEnterState[%d] State[%d] ParkingID[%s]",
struAidAlarm.dwXmlLen, struAidAlarm.struDevInfo.byIvmsChannel, struAidAlarm.struAIDInfo.byRuleID, struAidAlarm.struAIDInfo.byRuleName,
struAidAlarm.struAIDInfo.dwAIDType, struAidAlarm.struAIDInfo.byVisibilityLevel, szAIDType, struAidAlarm.byTargetType, struAidAlarm.byLaneNo, struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay,
struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond, struAidAlarm.struDevInfo.struDevIP.sIpV4,
struAidAlarm.struDevInfo.wPort, struAidAlarm.struDevInfo.byChannel,
struAidAlarm.struAIDInfo.struDirect.struStartPoint.fX, struAidAlarm.struAIDInfo.struDirect.struStartPoint.fY,
struAidAlarm.struAIDInfo.struDirect.struEndPoint.fX, struAidAlarm.struAIDInfo.struDirect.struEndPoint.fY,
struAidAlarm.struSceneInfo.dwSceneID,struAidAlarm.struSceneInfo.bySceneName,struAidAlarm.struSceneInfo.byDirection,
struAidAlarm.struSceneInfo.struPtzPos.wPanPos,struAidAlarm.struSceneInfo.struPtzPos.wTiltPos,struAidAlarm.struSceneInfo.struPtzPos.wZoomPos,
tempMonitoringSiteID, struAidAlarm.byDeviceID, struAidAlarm.struAIDInfo.byVehicleEnterState,
struAidAlarm.struAIDInfo.byState, struAidAlarm.struAIDInfo.byParkingID);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struAidAlarm.dwPicDataLen > 0 && struAidAlarm.pImage != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s_channel[%d]_AID", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, struAidAlarm.struDevInfo.byChannel);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struAidAlarm.byDataType == 0)
{
sprintf(cFilename, "%s\\AIDPic_LocalTime[%s].jpg", cFilename, chTime);
}
else if (struAidAlarm.byDataType == 1)
{
sprintf(cFilename, "%s\\AIDPic_URL_LocalTime[%s].txt", cFilename, chTime);
}
//sprintf(cFilename, "%s\\LocalTime[%s].jpg",cFilename, chTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struAidAlarm.pImage, struAidAlarm.dwPicDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struAidAlarm.dwXmlLen > 0 && struAidAlarm.pXmlBuf != NULL)
{
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
char cFilename[256] = { 0 };
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\%s_channel[%d]_AID", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, struAidAlarm.struDevInfo.byChannel);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\AIDXml_[%s].txt", cFilename, chTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struAidAlarm.pXmlBuf, struAidAlarm.dwXmlLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
//保存车牌子图
if (struAidAlarm.dwPlateSmallPicDataLen > 0 && struAidAlarm.pPlateSmallImage != NULL)
{
char cFilename[256] = { 0 };
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\%s_channel[%d]_AID", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, struAidAlarm.struDevInfo.byChannel);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struAidAlarm.byDataType == 0)
{
sprintf(cFilename, "%s\\AIDPlateSmallPic_LocalTime[%s].jpg", cFilename, chTime);
}
else if (struAidAlarm.byDataType == 1)
{
sprintf(cFilename, "%s\\AIDPlateSmallPic_URL_LocalTime[%s].txt", cFilename, chTime);
}
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struAidAlarm.pPlateSmallImage, struAidAlarm.dwPlateSmallPicDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struAidAlarm.pImage != NULL)
{
delete [] (struAidAlarm.pImage);
struAidAlarm.pImage = NULL;
}
if (struAidAlarm.pXmlBuf != NULL)
{
delete[](struAidAlarm.pXmlBuf);
struAidAlarm.pXmlBuf = NULL;
}
if (struAidAlarm.pPlateSmallImage != NULL)
{
delete[](struAidAlarm.pPlateSmallImage);
struAidAlarm.pPlateSmallImage = NULL;
}
}
void CClientDemoDlg::ProcTpsStatistics(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szInfoBuf[1024] = { 0 };
NET_DVR_TPS_STATISTICS_INFO struTpsStatistics = { 0 };
memcpy(&struTpsStatistics, pAlarmInfo, sizeof(struTpsStatistics));
sprintf(szInfoBuf, "TPS Alarm Start[%d]CMD[%d]DeviceID[%d]TotalLaneNum[%d]DataLen[%d]StartTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d]SamplePeriod[%d]Chan[%d]", \
struTpsStatistics.struTPSStatisticsInfo.byStart, \
struTpsStatistics.struTPSStatisticsInfo.byCMD, struTpsStatistics.struTPSStatisticsInfo.wDeviceID, \
struTpsStatistics.struTPSStatisticsInfo.byTotalLaneNum, struTpsStatistics.struTPSStatisticsInfo.wDataLen, \
struTpsStatistics.struTPSStatisticsInfo.struStartTime.wYear, struTpsStatistics.struTPSStatisticsInfo.struStartTime.byMonth, \
struTpsStatistics.struTPSStatisticsInfo.struStartTime.byDay, struTpsStatistics.struTPSStatisticsInfo.struStartTime.byHour, \
struTpsStatistics.struTPSStatisticsInfo.struStartTime.byMinute, struTpsStatistics.struTPSStatisticsInfo.struStartTime.bySecond, \
struTpsStatistics.struTPSStatisticsInfo.struStartTime.wMilliSec, struTpsStatistics.struTPSStatisticsInfo.dwSamplePeriod, struTpsStatistics.dwChan);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
for (int i = 0; i < struTpsStatistics.struTPSStatisticsInfo.byTotalLaneNum; i++)
{
sprintf(szInfoBuf, "LaneNum[%d](Lane[%d]Speed[%d]ArrivalFlow[%d]VehicelNum[%d]LightVehicle[%d]MidVehicle[%d]HeavyVehicle[%d]TimeHeadway[%d]SpaceHeadway[%d]SpaceOccupyRation[%0.3f]TimeOccupyRation[%0.3f])StoppingTimes[%d]Delay[%d],QueueLen[%d]Flag[%d]Nonmotor[%d]",
(i + 1), struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].byLane, struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].bySpeed,\
struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].wArrivalFlow, struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].byVehicelNum, \
struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].dwLightVehicle, struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].dwMidVehicle,\
struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].dwHeavyVehicle, struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].dwTimeHeadway,\
struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].dwSpaceHeadway, struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].fSpaceOccupyRation,\
struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].fTimeOccupyRation, struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].byStoppingTimes, \
struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].wDelay, struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].byQueueLen, \
struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].byFlag, struTpsStatistics.struTPSStatisticsInfo.struLaneParam[i].dwNonMotor);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
return;
}
void CClientDemoDlg::ProcTpsRealtime(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szInfoBuf[1024] = { 0 };
NET_DVR_TPS_REAL_TIME_INFO struTpsRealtime = { 0 };
memcpy(&struTpsRealtime, pAlarmInfo, sizeof(struTpsRealtime));
sprintf(szInfoBuf, "TPS Real Time Alarm Channel[%d]Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d]Start[%d]CMD[%d]SpaceHeadway[%d]TimeHeadway[%d]DeviceID[%d]DataLen[%d]Lane[%d] \
Speed[%d]LaneState[%d]QueueLen[%d]LoopState[%d]StateMask[%d]DownwardFlow[%d]UpwardFlow[%d]JamLevel[%d]VehicleDirection[%d]JamFlow[%d]", \
struTpsRealtime.dwChan, \
struTpsRealtime.struTime.wYear, struTpsRealtime.struTime.byMonth, struTpsRealtime.struTime.byDay, \
struTpsRealtime.struTime.byHour, struTpsRealtime.struTime.byMinute, struTpsRealtime.struTime.bySecond, \
struTpsRealtime.struTime.wMilliSec, struTpsRealtime.struTPSRealTimeInfo.byStart, \
struTpsRealtime.struTPSRealTimeInfo.byCMD, struTpsRealtime.struTPSRealTimeInfo.wSpaceHeadway, \
struTpsRealtime.struTPSRealTimeInfo.wTimeHeadway, struTpsRealtime.struTPSRealTimeInfo.wDeviceID, \
struTpsRealtime.struTPSRealTimeInfo.wDataLen, struTpsRealtime.struTPSRealTimeInfo.byLane, \
struTpsRealtime.struTPSRealTimeInfo.bySpeed, struTpsRealtime.struTPSRealTimeInfo.byLaneState, \
struTpsRealtime.struTPSRealTimeInfo.byQueueLen, struTpsRealtime.struTPSRealTimeInfo.wLoopState, \
struTpsRealtime.struTPSRealTimeInfo.wStateMask, struTpsRealtime.struTPSRealTimeInfo.dwDownwardFlow, \
struTpsRealtime.struTPSRealTimeInfo.dwUpwardFlow, struTpsRealtime.struTPSRealTimeInfo.byJamLevel, \
struTpsRealtime.struTPSRealTimeInfo.byVehicleDirection, struTpsRealtime.struTPSRealTimeInfo.byJamFlow);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (1 == struTpsRealtime.byAddInfoFlag)
{
NET_DVR_TPS_ADDINFO struTPSAddInfo = { 0 };
memcpy(&struTPSAddInfo, struTpsRealtime.pAddInfoBuffer, sizeof(NET_DVR_TPS_ADDINFO));
sprintf(szInfoBuf, "AddInfoFlag [%d] First Car:LatitudeType [%d] Degree[%d] Minute[%d] fSec[%f] LongitudeType [%d] Degree[%d] Minute[%d] fSec[%f], \
Last Car:LatitudeType [%d] Degree[%d] Minute[%d] fSec[%f] LongitudeType [%d] Degree[%d] Minute[%d] fSec[%f]", \
struTpsRealtime.byAddInfoFlag, struTPSAddInfo.struFirstLLPos.byLatitudeType, struTPSAddInfo.struFirstLLPos.struLatitude.byDegree, \
struTPSAddInfo.struFirstLLPos.struLatitude.byMinute, struTPSAddInfo.struFirstLLPos.struLatitude.fSec, \
struTPSAddInfo.struFirstLLPos.byLongitudeType, struTPSAddInfo.struFirstLLPos.struLongitude.byDegree, \
struTPSAddInfo.struFirstLLPos.struLongitude.byMinute, struTPSAddInfo.struFirstLLPos.struLongitude.fSec, \
struTPSAddInfo.struLastLLPos.byLatitudeType, struTPSAddInfo.struLastLLPos.struLatitude.byDegree, \
struTPSAddInfo.struLastLLPos.struLatitude.byMinute, struTPSAddInfo.struLastLLPos.struLatitude.fSec, \
struTPSAddInfo.struLastLLPos.byLongitudeType, struTPSAddInfo.struLastLLPos.struLongitude.byDegree, \
struTPSAddInfo.struLastLLPos.struLongitude.byMinute, struTPSAddInfo.struLastLLPos.struLongitude.fSec
);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
return;
}
void CClientDemoDlg::ProcTfsAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[2048] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_TFS_ALARM struTfsAlarm = { 0 };
memcpy(&struTfsAlarm, pAlarmInfo, sizeof(struTfsAlarm));
if (iDeviceIndex != -1 && iDeviceIndex < MAX_DEVICES)
{
i = struTfsAlarm.struDevInfo.byIvmsChannel - g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
NET_DVR_TIME struAbsTime = { 0 };
struAbsTime.dwYear = GET_YEAR(struTfsAlarm.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struTfsAlarm.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struTfsAlarm.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struTfsAlarm.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struTfsAlarm.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struTfsAlarm.dwAbsTime);
CString str = "";
char chTfsTime[128] = { 0 };
sprintf(chTfsTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", struTfsAlarm.struTime.wYear, struTfsAlarm.struTime.byMonth, struTfsAlarm.struTime.byDay, \
struTfsAlarm.struTime.byHour, struTfsAlarm.struTime.byMinute, struTfsAlarm.struTime.bySecond, struTfsAlarm.struTime.wMilliSec);
//重新拷贝,解决48个字节时,打印乱码的问题
BYTE tempMonitoringSiteID[MONITORSITE_ID_LEN + 1/*49*/] = { 0 };
memcpy(tempMonitoringSiteID, struTfsAlarm.byMonitoringSiteID, sizeof(struTfsAlarm.byMonitoringSiteID));
//demo显示第一次打印,已经显示到最多了,新增的需要在第二次打印增加
sprintf(szInfoBuf, "Tfs Alarm IvmsChan: [%d] RuleID: [%d] RuleName: [%s] AIDType: [%d] AbsTime: [%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] DevIP: [%s] Port: [%d] Chan: [%d] SpecificVehicleType: [%d]\
LaneNo: [%d] Direction Start: [%0.3f,%0.3f] Stop: [%0.3f,%0.3f] SceneID: [%d] SceneName: [%s] Direction: [%d] PTZ: [%d,%d,%d] IllegalType: [%u] IlleagelDuration: [%d] MonitoringSiteID: [%s]\
DeviceID: [%s] Licence: [%s] Believe: [%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u] Time: [%s] SerialNo: [%d] VehicleAttribute: [%d] PilotSafebelt: [%d] CopilotSafebelt: [%d]\
PilotSunVisor: [%d] CopilotSunVisor: [%d] PilotCall: [%d] IllegalCode: [%s] VehicleEnterState: [%d] Country: [%d] Region: [%d] State:[%d] ParkingID:[%s] CrossLine:[%d] ParkingSerialNO:[%s]\
CrossSpaces:[%d] AngledParking:[%d] AlarmValidity:[%d] DoorStatus:[%d] byVehicleHeadTailStatus:[%d] BeginRecTime:[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] EndRecTime:[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] PlateType:[%d] PlateColor[%d] EntireBelieve[%d]",
struTfsAlarm.struDevInfo.byIvmsChannel, struTfsAlarm.struAIDInfo.byRuleID, struTfsAlarm.struAIDInfo.byRuleName,
struTfsAlarm.struAIDInfo.dwAIDType, struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay,
struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond, struTfsAlarm.struDevInfo.struDevIP.sIpV4,
struTfsAlarm.struDevInfo.wPort, struTfsAlarm.struDevInfo.byChannel, struTfsAlarm.bySpecificVehicleType,
struTfsAlarm.byLaneNo, struTfsAlarm.struAIDInfo.struDirect.struStartPoint.fX, struTfsAlarm.struAIDInfo.struDirect.struStartPoint.fY,
struTfsAlarm.struAIDInfo.struDirect.struEndPoint.fX, struTfsAlarm.struAIDInfo.struDirect.struEndPoint.fY,
struTfsAlarm.struSceneInfo.dwSceneID, struTfsAlarm.struSceneInfo.bySceneName, struTfsAlarm.struSceneInfo.byDirection,
struTfsAlarm.struSceneInfo.struPtzPos.wPanPos, struTfsAlarm.struSceneInfo.struPtzPos.wTiltPos, struTfsAlarm.struSceneInfo.struPtzPos.wZoomPos,
struTfsAlarm.dwIllegalType, struTfsAlarm.dwIllegalDuration, tempMonitoringSiteID, struTfsAlarm.byDeviceID,
struTfsAlarm.struPlateInfo.sLicense, struTfsAlarm.struPlateInfo.byBelieve[0], struTfsAlarm.struPlateInfo.byBelieve[1], struTfsAlarm.struPlateInfo.byBelieve[2], struTfsAlarm.struPlateInfo.byBelieve[3],
struTfsAlarm.struPlateInfo.byBelieve[4], struTfsAlarm.struPlateInfo.byBelieve[5], struTfsAlarm.struPlateInfo.byBelieve[6], struTfsAlarm.struPlateInfo.byBelieve[7],
struTfsAlarm.struPlateInfo.byBelieve[8], struTfsAlarm.struPlateInfo.byBelieve[9], struTfsAlarm.struPlateInfo.byBelieve[10], struTfsAlarm.struPlateInfo.byBelieve[11],
struTfsAlarm.struPlateInfo.byBelieve[12], struTfsAlarm.struPlateInfo.byBelieve[13], struTfsAlarm.struPlateInfo.byBelieve[14], struTfsAlarm.struPlateInfo.byBelieve[15],
chTfsTime, struTfsAlarm.dwSerialNo, struTfsAlarm.byVehicleAttribute, struTfsAlarm.byPilotSafebelt, struTfsAlarm.byCopilotSafebelt, struTfsAlarm.byPilotSunVisor,
struTfsAlarm.byCopilotSunVisor, struTfsAlarm.byPilotCall, struTfsAlarm.byIllegalCode, struTfsAlarm.struAIDInfo.byVehicleEnterState, struTfsAlarm.wCountry,
struTfsAlarm.byRegion, struTfsAlarm.struAIDInfo.byState, struTfsAlarm.struAIDInfo.byParkingID, struTfsAlarm.byCrossLine, struTfsAlarm.byParkingSerialNO, struTfsAlarm.byCrossSpaces,
struTfsAlarm.byAngledParking, struTfsAlarm.byAlarmValidity, struTfsAlarm.byDoorsStatus, struTfsAlarm.byVehicleHeadTailStatus, struTfsAlarm.struBeginRecTime.wYear, struTfsAlarm.struBeginRecTime.byMonth, struTfsAlarm.struBeginRecTime.byDay,
struTfsAlarm.struBeginRecTime.byHour, struTfsAlarm.struBeginRecTime.byMinute, struTfsAlarm.struBeginRecTime.bySecond, struTfsAlarm.struEndRecTime.wYear, struTfsAlarm.struEndRecTime.byMonth, struTfsAlarm.struEndRecTime.byDay,
struTfsAlarm.struEndRecTime.byHour, struTfsAlarm.struEndRecTime.byMinute, struTfsAlarm.struEndRecTime.bySecond, struTfsAlarm.struPlateInfo.byPlateType, struTfsAlarm.struPlateInfo.byColor, struTfsAlarm.struPlateInfo.byEntireBelieve);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
memset(szInfoBuf, 0, sizeof(szInfoBuf));
//第二次打印
sprintf(szInfoBuf, "Tfs Alarm VehicleIndex:[%d] VehicleType:[%d] ColorDepth:[%d] VehicleColor:[%d] VehicleLogoRecog:[%d] VehicleSubLogoRecog:[%d] VehicleModel:[%d] PicNum:[%d] byIllegalType[%d] byBelieve[%d]",
struTfsAlarm.struVehicleInfo.dwIndex,struTfsAlarm.struVehicleInfo.byVehicleType, struTfsAlarm.struVehicleInfo.byColorDepth, struTfsAlarm.struVehicleInfo.byColor, struTfsAlarm.struVehicleInfo.wVehicleLogoRecog, struTfsAlarm.struVehicleInfo.byVehicleSubLogoRecog,
struTfsAlarm.struVehicleInfo.byVehicleModel, struTfsAlarm.dwPicNum, struTfsAlarm.struVehicleInfo.byIllegalType, struTfsAlarm.struVehicleInfo.byBelieve);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
memset(szInfoBuf, 0, sizeof(szInfoBuf));
//保存文本
sprintf(szInfoBuf, "Tfs Alarm IvmsChan: [%d]\r\nRuleID: [%d]\r\nRuleName: [%s]\r\nAIDType: [%d]\r\nAbsTime: [%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d]\r\nDevIP: [%s]\r\nPort: [%d]\r\nChan: [%d]\r\nSpecificVehicleType: [%d]\
\r\nLaneNo: [%d]\r\nDirection Start: [%0.3f,%0.3f]\r\nStop: [%0.3f,%0.3f]\r\nSceneID: [%d]\r\nSceneName: [%s]\r\nDirection: [%d]\r\nPTZ: [%d,%d,%d]\r\nIllegalType: [%u]\r\nIlleagelDuration: [%d]\r\nMonitoringSiteID: [%s]\
\r\nDeviceID: [%s]\r\nLicence: [%s]\r\nBelieve: [%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u]\r\nTime: [%s]\r\nSerialNo: [%d]\r\nVehicleAttribute: [%d]\r\nPilotSafebelt: [%d]\r\nCopilotSafebelt: [%d]\
\r\nPilotSunVisor: [%d]\r\nCopilotSunVisor: [%d]\r\nPilotCall: [%d]\r\nIllegalCode: [%s]\r\nVehicleEnterState: [%d]\r\nCountry: [%d]\r\nRegion: [%d]\r\nState:[%d]\r\nParkingID:[%s]\r\nCrossLine:[%d]\r\nParkingSerialNO:[%s]\
\r\nCrossSpaces:[%d]\r\nAngledParking:[%d]\r\nAlarmValidity:[%d]\r\nbyVehicleHeadTailStatus:[%d]\r\nBeginRecTime:[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d]\r\nEndRecTime:[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d]\r\nPlateType:[%d]\r\nPlateColor[%d]\r\nEntireBelieve[%d]\
\r\nVehicleIndex:[%d]\r\nVehicleType:[%d]\r\nColorDepth:[%d]\r\nVehicleColor:[%d]\r\nVehicleLogoRecog:[%d]\r\nVehicleSubLogoRecog:[%d]\r\nVehicleModel:[%d]\r\nPicNum:[%d],\r\nstruVehicleInfo.byIllegalType[%d]\r\nstruVehicleInfo.byBelieve[%d]",
struTfsAlarm.struDevInfo.byIvmsChannel, struTfsAlarm.struAIDInfo.byRuleID, struTfsAlarm.struAIDInfo.byRuleName,
struTfsAlarm.struAIDInfo.dwAIDType, struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay,
struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond, struTfsAlarm.struDevInfo.struDevIP.sIpV4,
struTfsAlarm.struDevInfo.wPort, struTfsAlarm.struDevInfo.byChannel, struTfsAlarm.bySpecificVehicleType,
struTfsAlarm.byLaneNo, struTfsAlarm.struAIDInfo.struDirect.struStartPoint.fX, struTfsAlarm.struAIDInfo.struDirect.struStartPoint.fY,
struTfsAlarm.struAIDInfo.struDirect.struEndPoint.fX, struTfsAlarm.struAIDInfo.struDirect.struEndPoint.fY,
struTfsAlarm.struSceneInfo.dwSceneID, struTfsAlarm.struSceneInfo.bySceneName, struTfsAlarm.struSceneInfo.byDirection,
struTfsAlarm.struSceneInfo.struPtzPos.wPanPos, struTfsAlarm.struSceneInfo.struPtzPos.wTiltPos, struTfsAlarm.struSceneInfo.struPtzPos.wZoomPos,
struTfsAlarm.dwIllegalType, struTfsAlarm.dwIllegalDuration, tempMonitoringSiteID, struTfsAlarm.byDeviceID,
struTfsAlarm.struPlateInfo.sLicense, struTfsAlarm.struPlateInfo.byBelieve[0], struTfsAlarm.struPlateInfo.byBelieve[1], struTfsAlarm.struPlateInfo.byBelieve[2], struTfsAlarm.struPlateInfo.byBelieve[3],
struTfsAlarm.struPlateInfo.byBelieve[4], struTfsAlarm.struPlateInfo.byBelieve[5], struTfsAlarm.struPlateInfo.byBelieve[6], struTfsAlarm.struPlateInfo.byBelieve[7],
struTfsAlarm.struPlateInfo.byBelieve[8], struTfsAlarm.struPlateInfo.byBelieve[9], struTfsAlarm.struPlateInfo.byBelieve[10], struTfsAlarm.struPlateInfo.byBelieve[11],
struTfsAlarm.struPlateInfo.byBelieve[12], struTfsAlarm.struPlateInfo.byBelieve[13], struTfsAlarm.struPlateInfo.byBelieve[14], struTfsAlarm.struPlateInfo.byBelieve[15],
chTfsTime, struTfsAlarm.dwSerialNo, struTfsAlarm.byVehicleAttribute, struTfsAlarm.byPilotSafebelt, struTfsAlarm.byCopilotSafebelt, struTfsAlarm.byPilotSunVisor,
struTfsAlarm.byCopilotSunVisor, struTfsAlarm.byPilotCall, struTfsAlarm.byIllegalCode, struTfsAlarm.struAIDInfo.byVehicleEnterState, struTfsAlarm.wCountry,
struTfsAlarm.byRegion, struTfsAlarm.struAIDInfo.byState, struTfsAlarm.struAIDInfo.byParkingID, struTfsAlarm.byCrossLine, struTfsAlarm.byParkingSerialNO, struTfsAlarm.byCrossSpaces,
struTfsAlarm.byAngledParking, struTfsAlarm.byAlarmValidity,struTfsAlarm.byVehicleHeadTailStatus, struTfsAlarm.struBeginRecTime.wYear, struTfsAlarm.struBeginRecTime.byMonth, struTfsAlarm.struBeginRecTime.byDay,
struTfsAlarm.struBeginRecTime.byHour, struTfsAlarm.struBeginRecTime.byMinute, struTfsAlarm.struBeginRecTime.bySecond, struTfsAlarm.struEndRecTime.wYear, struTfsAlarm.struEndRecTime.byMonth, struTfsAlarm.struEndRecTime.byDay,
struTfsAlarm.struEndRecTime.byHour, struTfsAlarm.struEndRecTime.byMinute, struTfsAlarm.struEndRecTime.bySecond,struTfsAlarm.struPlateInfo.byPlateType,struTfsAlarm.struPlateInfo.byColor,struTfsAlarm.struPlateInfo.byEntireBelieve,
struTfsAlarm.struVehicleInfo.dwIndex, struTfsAlarm.struVehicleInfo.byVehicleType, struTfsAlarm.struVehicleInfo.byColorDepth, struTfsAlarm.struVehicleInfo.byColor, struTfsAlarm.struVehicleInfo.wVehicleLogoRecog, struTfsAlarm.struVehicleInfo.byVehicleSubLogoRecog,
struTfsAlarm.struVehicleInfo.byVehicleModel, struTfsAlarm.dwPicNum, struTfsAlarm.struVehicleInfo.byIllegalType, struTfsAlarm.struVehicleInfo.byBelieve);
SYSTEMTIME t;
GetLocalTime(&t);
char dataFilename[256] = { 0 };
char chTime[128] = { 0 };
char txtFilename[256] = { 0 };
char cFilename[256] = { 0 };
HANDLE hFile;
DWORD dwReturn;
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(dataFilename, "%s\\%s_channel[%d]_TFS", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, struTfsAlarm.struDevInfo.byChannel);
if (GetFileAttributes(dataFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(dataFilename, NULL);
}
sprintf(txtFilename, "%s\\TFSAlarm_%s.txt", dataFilename, chTime);
hFile = CreateFile(txtFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, szInfoBuf, strlen(szInfoBuf), &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
for (int i = 0; i < 8; i++)
{
if (struTfsAlarm.struPicInfo[i].dwDataLen > 0 && struTfsAlarm.struPicInfo[i].pBuffer != NULL)
{
char cPicType[256] = { 0 };
if (struTfsAlarm.struPicInfo[i].byDataType == 0)
{
if (0 == struTfsAlarm.struPicInfo[i].byType)
{
sprintf(cPicType, "License");
}
else if (1 == struTfsAlarm.struPicInfo[i].byType)
{
sprintf(cPicType, "Scene");
}
else if (15 == struTfsAlarm.struPicInfo[i].byType)
{
sprintf(cPicType, "custom");
}
sprintf(cFilename, "%s\\%s_LocalTime[%s]_%d.jpg", dataFilename, cPicType, chTime, i);
}
else if (struTfsAlarm.struPicInfo[i].byDataType == 1)
{
if (0 == struTfsAlarm.struPicInfo[i].byType)
{
sprintf(cPicType, "License");
}
else if (1 == struTfsAlarm.struPicInfo[i].byType)
{
sprintf(cPicType, "Scene");
}
else if (15 == struTfsAlarm.struPicInfo[i].byType)
{
sprintf(cPicType, "custom");
}
sprintf(cFilename, "%s\\%s_URL_LocalTime[%s]_%d.txt", dataFilename, cPicType, chTime, i);
}
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struTfsAlarm.struPicInfo[i].pBuffer, struTfsAlarm.struPicInfo[i].dwDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
}
}
void CClientDemoDlg::ProcFaceDetectAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
const char *szFaceType[] = { "abn", "nor", "mul", "sgl", "cal" };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_FACEDETECT_ALARM struFaceDetectAlarm = {0};
memcpy(&struFaceDetectAlarm, pAlarmInfo, sizeof(struFaceDetectAlarm));
int i = struFaceDetectAlarm.struDevInfo.byChannel - g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
// 打印信息
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struFaceDetectAlarm.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struFaceDetectAlarm.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struFaceDetectAlarm.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struFaceDetectAlarm.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struFaceDetectAlarm.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struFaceDetectAlarm.dwAbsTime);
NET_DVR_TIME struRelativeTime = { 0 };
struRelativeTime.dwYear = GET_YEAR(struFaceDetectAlarm.dwRelativeTime);
struRelativeTime.dwMonth = GET_MONTH(struFaceDetectAlarm.dwRelativeTime);
struRelativeTime.dwDay = GET_DAY(struFaceDetectAlarm.dwRelativeTime);
struRelativeTime.dwHour = GET_HOUR(struFaceDetectAlarm.dwRelativeTime);
struRelativeTime.dwMinute = GET_MINUTE(struFaceDetectAlarm.dwRelativeTime);
struRelativeTime.dwSecond = GET_SECOND(struFaceDetectAlarm.dwRelativeTime);
sprintf(szInfoBuf, "Face alarm Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] RelativeTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] RuleName[%s] AlarmPicType[%d] PanelChan[%d] RelAlarmPicNum[%d] AlarmID[%d] IvmsChannel[%d]IvmsChannelEx[%d]",
struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour,
struAbsTime.dwMinute, struAbsTime.dwSecond, struRelativeTime.dwYear, struRelativeTime.dwMonth,
struRelativeTime.dwDay, struRelativeTime.dwHour,struRelativeTime.dwMinute, struRelativeTime.dwSecond,
struFaceDetectAlarm.byRuleName,struFaceDetectAlarm.byAlarmPicType,struFaceDetectAlarm.byPanelChan,
struFaceDetectAlarm.byRelAlarmPicNum,struFaceDetectAlarm.dwAlarmID,\
struFaceDetectAlarm.struDevInfo.byIvmsChannel, struFaceDetectAlarm.wDevInfoIvmsChannelEx);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struFaceDetectAlarm.dwPicDataLen > 0 && struFaceDetectAlarm.pImage != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
if (struFaceDetectAlarm.byAlarmPicType < 0 || struFaceDetectAlarm.byAlarmPicType > 4)
{
return;
}
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]AlarmID[%d]_%d_%s.jpg", cFilename, chTime, struFaceDetectAlarm.dwAlarmID, rand() % GetTickCount(), szFaceType[struFaceDetectAlarm.byAlarmPicType]);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceDetectAlarm.pImage, struFaceDetectAlarm.dwPicDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struFaceDetectAlarm.dwFacePicDataLen > 0 && struFaceDetectAlarm.pFaceImage != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struFaceDetectAlarm.byAlarmPicType < 0 || struFaceDetectAlarm.byAlarmPicType > 4)
{
return;
}
sprintf(cFilename, "%s\\Face_LocalTime[%s]AlarmID[%d]_%d_%s.jpg", cFilename, chTime, struFaceDetectAlarm.dwAlarmID, rand() % GetTickCount(), szFaceType[struFaceDetectAlarm.byAlarmPicType]);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceDetectAlarm.pFaceImage, struFaceDetectAlarm.dwFacePicDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struFaceDetectAlarm.pImage != NULL)
{
delete [] (struFaceDetectAlarm.pImage);
struFaceDetectAlarm.pImage = NULL;
}
if (struFaceDetectAlarm.pFaceImage != NULL)
{
delete [] (struFaceDetectAlarm.pFaceImage);
struFaceDetectAlarm.pFaceImage = NULL;
}
}
void CClientDemoDlg::ProcFaceSnapAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_VCA_FACESNAP_RESULT struFaceSnapAlarm = {0};
memcpy(&struFaceSnapAlarm, pAlarmInfo, sizeof(struFaceSnapAlarm));
if (iDeviceIndex >= 0 && iDeviceIndex < MAX_DEVICES)
{
int i = struFaceSnapAlarm.struDevInfo.byChannel - g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
// 打印信息
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struFaceSnapAlarm.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struFaceSnapAlarm.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struFaceSnapAlarm.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struFaceSnapAlarm.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struFaceSnapAlarm.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struFaceSnapAlarm.dwAbsTime);
NET_DVR_TIME struRelativeTime = { 0 };
struRelativeTime.dwYear = GET_YEAR(struFaceSnapAlarm.dwRelativeTime);
struRelativeTime.dwMonth = GET_MONTH(struFaceSnapAlarm.dwRelativeTime);
struRelativeTime.dwDay = GET_DAY(struFaceSnapAlarm.dwRelativeTime);
struRelativeTime.dwHour = GET_HOUR(struFaceSnapAlarm.dwRelativeTime);
struRelativeTime.dwMinute = GET_MINUTE(struFaceSnapAlarm.dwRelativeTime);
struRelativeTime.dwSecond = GET_SECOND(struFaceSnapAlarm.dwRelativeTime);
NET_VCA_FACESNAP_ADDINFO struFaceSnapAddInfo = { 0 };
if (struFaceSnapAlarm.byAddInfo > 0 && struFaceSnapAlarm.pAddInfoBuffer != NULL)
{
memcpy(&struFaceSnapAddInfo, struFaceSnapAlarm.pAddInfoBuffer, sizeof(struFaceSnapAddInfo));
}
sprintf(szInfoBuf, "Face Snap alarm BrokenNetHttp[%d]Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] flag[%d] %2.2d%2.2d] \
Relalative[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] FaceID[%d] Smart[%d] AgeGroup[%d] Sex[%d] EyeGlass[%d] \
StayDuration[%.3f] FaceScore[%d] AlarmEndMark[%d] RepeatTimes[%d]-StorageIP[%s] Storage Port[%d],TargeInfo :IvmsChannel[%d]IvmsChannelEx[%d] \
Age[%d], AgeDeviation[%d] FacePicQuality[%d] UIDLen[%d] Ethnic[%d] Mask[%d] Smile[%d] \
TargeInfo: ID[%d] X[%.3f] Y[%.3f] Height[%.3f] Width[%.3f] \
Rect:X[%.3f] Y[%.3f] Height[%.3f] Width[%.3f] \
AddInfo[%d] FacePicRect:X[%.3f] Y[%.3f] Height[%.3f] Width[%.3f] \
SwingAngle[%d] TiltAngle[%d] PupilDistance[%d] BlockingState[%d] LivenessDetectionStatus[%d] \
FaceExpression[%d] Beard[%d] Race[%d] Hat[%d]\
EnterTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] \
ExitTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d]\n",
struFaceSnapAlarm.byBrokenNetHttp, struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond, \
struFaceSnapAlarm.byTimeDiffFlag, struFaceSnapAlarm.cTimeDifferenceH, struFaceSnapAlarm.cTimeDifferenceM, \
struRelativeTime.dwYear, struRelativeTime.dwMonth, struRelativeTime.dwDay, struRelativeTime.dwHour, struRelativeTime.dwMinute, struRelativeTime.dwSecond, \
struFaceSnapAlarm.dwFacePicID, struFaceSnapAlarm.bySmart, struFaceSnapAlarm.struFeature.byAgeGroup, struFaceSnapAlarm.struFeature.bySex, \
struFaceSnapAlarm.struFeature.byEyeGlass, struFaceSnapAlarm.fStayDuration, struFaceSnapAlarm.dwFaceScore, struFaceSnapAlarm.byAlarmEndMark, \
struFaceSnapAlarm.byRepeatTimes, struFaceSnapAlarm.sStorageIP, struFaceSnapAlarm.wStoragePort, \
struFaceSnapAlarm.struDevInfo.byIvmsChannel, struFaceSnapAlarm.wDevInfoIvmsChannelEx, struFaceSnapAlarm.struFeature.byAge, struFaceSnapAlarm.struFeature.byAgeDeviation, struFaceSnapAlarm.byFacePicQuality, struFaceSnapAlarm.byUIDLen, \
struFaceSnapAlarm.struFeature.byEthnic, struFaceSnapAlarm.struFeature.byMask, struFaceSnapAlarm.struFeature.bySmile,
struFaceSnapAlarm.struTargetInfo.dwID, struFaceSnapAlarm.struTargetInfo.struRect.fX, struFaceSnapAlarm.struTargetInfo.struRect.fY, struFaceSnapAlarm.struTargetInfo.struRect.fHeight, struFaceSnapAlarm.struTargetInfo.struRect.fWidth,
struFaceSnapAlarm.struRect.fX, struFaceSnapAlarm.struRect.fY, struFaceSnapAlarm.struRect.fHeight, struFaceSnapAlarm.struRect.fWidth,
struFaceSnapAlarm.byAddInfo, struFaceSnapAddInfo.struFacePicRect.fX, struFaceSnapAddInfo.struFacePicRect.fY, \
struFaceSnapAddInfo.struFacePicRect.fHeight, struFaceSnapAddInfo.struFacePicRect.fWidth, struFaceSnapAddInfo.iSwingAngle, struFaceSnapAddInfo.iTiltAngle, struFaceSnapAddInfo.dwPupilDistance, struFaceSnapAddInfo.byBlockingState, \
struFaceSnapAlarm.byLivenessDetectionStatus, struFaceSnapAlarm.struFeature.byFaceExpression,\
struFaceSnapAlarm.struFeature.byBeard, struFaceSnapAlarm.struFeature.byRace, struFaceSnapAlarm.struFeature.byHat, \
struFaceSnapAddInfo.struEnterTime.wYear, struFaceSnapAddInfo.struEnterTime.byMonth, struFaceSnapAddInfo.struEnterTime.byDay, struFaceSnapAddInfo.struEnterTime.byHour, struFaceSnapAddInfo.struEnterTime.byMinute, struFaceSnapAddInfo.struEnterTime.bySecond, \
struFaceSnapAddInfo.struExitTime.wYear, struFaceSnapAddInfo.struExitTime.byMonth, struFaceSnapAddInfo.struExitTime.byDay, struFaceSnapAddInfo.struExitTime.byHour, struFaceSnapAddInfo.struExitTime.byMinute, struFaceSnapAddInfo.struExitTime.bySecond);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
int iPort = pAlarmDev->wLinkPort;
if (struFaceSnapAlarm.byUIDLen > 0 && struFaceSnapAlarm.pUIDBuffer != NULL)
{
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
char cFilename[256] = { 0 };
HANDLE hFile;
DWORD dwReturn;
sprintf(cFilename, "%s\\%s[%d][%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\SnapUID[%s].txt", cFilename, chTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceSnapAlarm.pUIDBuffer, struFaceSnapAlarm.byUIDLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struFaceSnapAlarm.dwFacePicLen > 0 && struFaceSnapAlarm.pBuffer1 != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
sprintf(cFilename, "%s\\%s[%d][%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struFaceSnapAlarm.byUploadEventDataType == 0)
{
sprintf(cFilename, "%s\\SnapPic[%s].jpg", cFilename, chTime);
}
else
{
sprintf(cFilename, "%s\\SnapURL[%s].txt", cFilename, chTime);
}
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceSnapAlarm.pBuffer1, struFaceSnapAlarm.dwFacePicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struFaceSnapAlarm.dwBackgroundPicLen > 0 && struFaceSnapAlarm.pBuffer2 != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
sprintf(cFilename, "%s\\%s[%d][%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struFaceSnapAlarm.byUploadEventDataType == 0)
{
sprintf(cFilename, "%s\\BackgroundPic[%s].jpg", cFilename, chTime);
}
else
{
sprintf(cFilename, "%s\\BackgroundPic[%s].txt", cFilename, chTime);
}
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceSnapAlarm.pBuffer2, struFaceSnapAlarm.dwBackgroundPicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
}
void CClientDemoDlg::ProcFaceDetectionAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
char szPicFace[1024] = {0};
//char *pPicFace = szPicFace;
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_FACE_DETECTION struFaceDetectionAlarm = {0};
memcpy(&struFaceDetectionAlarm, pAlarmInfo, sizeof(struFaceDetectionAlarm));
// 打印信息
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struFaceDetectionAlarm.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struFaceDetectionAlarm.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struFaceDetectionAlarm.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struFaceDetectionAlarm.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struFaceDetectionAlarm.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struFaceDetectionAlarm.dwAbsTime);
NET_DVR_TIME struRelativeTime = {0};
struRelativeTime.dwYear = GET_YEAR(struFaceDetectionAlarm.dwRelativeTime);
struRelativeTime.dwMonth = GET_MONTH(struFaceDetectionAlarm.dwRelativeTime);
struRelativeTime.dwDay = GET_DAY(struFaceDetectionAlarm.dwRelativeTime);
struRelativeTime.dwHour = GET_HOUR(struFaceDetectionAlarm.dwRelativeTime);
struRelativeTime.dwMinute = GET_MINUTE(struFaceDetectionAlarm.dwRelativeTime);
struRelativeTime.dwSecond = GET_SECOND(struFaceDetectionAlarm.dwRelativeTime);
for (int i = 0; i < MAX_FACE_PIC_NUM; i++)
{
if (struFaceDetectionAlarm.struFacePic[i].fHeight != 0 && \
struFaceDetectionAlarm.struFacePic[i].fWidth != 0)
// struFaceDetectionAlarm.struFacePic[i].fX != 0 && \
// struFaceDetectionAlarm.struFacePic[i].fY != 0)
{
sprintf(szPicFace, "[Detection Face Snap alarm]facePic:%d fHeight:%f,fWidth:%f,fX:%f,fY:%f \n", i+1, \
struFaceDetectionAlarm.struFacePic[i].fHeight,
struFaceDetectionAlarm.struFacePic[i].fWidth,
struFaceDetectionAlarm.struFacePic[i].fX,
struFaceDetectionAlarm.struFacePic[i].fY);
//pPicFace = pPicFace + strlen(pPicFace);
AddLog(m_iCurDeviceIndex, ALARM_INFO_T, szPicFace);
}
}
sprintf(szInfoBuf, "[Detection Face Snap alarm] Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d flag[%d] %2.2d%2.2d] RelativeTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] Dev[ip:%s,port:%d,ivmsChan:%d] IvmsChannelEx[%d] UploadEventDataType[%d] \n", \
struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour,struAbsTime.dwMinute, struAbsTime.dwSecond, \
struFaceDetectionAlarm.byTimeDiffFlag, struFaceDetectionAlarm.cTimeDifferenceH, struFaceDetectionAlarm.cTimeDifferenceM, \
struRelativeTime.dwYear, struRelativeTime.dwMonth, struRelativeTime.dwDay, struRelativeTime.dwHour,struRelativeTime.dwMinute, struRelativeTime.dwSecond, \
struFaceDetectionAlarm.struDevInfo.struDevIP.sIpV4, struFaceDetectionAlarm.struDevInfo.wPort, struFaceDetectionAlarm.struDevInfo.byIvmsChannel,\
struFaceDetectionAlarm.wDevInfoIvmsChannelEx, struFaceDetectionAlarm.byUploadEventDataType/*szPicFace*/);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struFaceDetectionAlarm.dwBackgroundPicLen > 0 && struFaceDetectionAlarm.pBackgroundPicpBuffer != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
//sprintf(cFilename, "%s\\%s", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struFaceDetectionAlarm.byUploadEventDataType == 0)
{
sprintf(cFilename, "%s\\Face Detection BackGround Pic[%s].jpg", cFilename, chTime);
}
else
{
sprintf(cFilename, "%s\\Face Detection BackGround Pic[%s].txt", cFilename, chTime);
}
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
delete[](struFaceDetectionAlarm.pBackgroundPicpBuffer);
struFaceDetectionAlarm.pBackgroundPicpBuffer = NULL;
return;
}
WriteFile(hFile, struFaceDetectionAlarm.pBackgroundPicpBuffer, struFaceDetectionAlarm.dwBackgroundPicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
delete[] (struFaceDetectionAlarm.pBackgroundPicpBuffer);
struFaceDetectionAlarm.pBackgroundPicpBuffer = NULL;
}
}
void CClientDemoDlg::ProcTargetLeftRegionAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_TARGET_LEFT_REGION_ALARM struTargetLeftRegionAlarm = {0};
memcpy(&struTargetLeftRegionAlarm, pAlarmInfo, sizeof(struTargetLeftRegionAlarm));
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struTargetLeftRegionAlarm.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struTargetLeftRegionAlarm.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struTargetLeftRegionAlarm.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struTargetLeftRegionAlarm.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struTargetLeftRegionAlarm.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struTargetLeftRegionAlarm.dwAbsTime);
NET_DVR_TIME struRelativeTime = {0};
struRelativeTime.dwYear = GET_YEAR(struTargetLeftRegionAlarm.dwRelativeTime);
struRelativeTime.dwMonth = GET_MONTH(struTargetLeftRegionAlarm.dwRelativeTime);
struRelativeTime.dwDay = GET_DAY(struTargetLeftRegionAlarm.dwRelativeTime);
struRelativeTime.dwHour = GET_HOUR(struTargetLeftRegionAlarm.dwRelativeTime);
struRelativeTime.dwMinute = GET_MINUTE(struTargetLeftRegionAlarm.dwRelativeTime);
struRelativeTime.dwSecond = GET_SECOND(struTargetLeftRegionAlarm.dwRelativeTime);
sprintf(szInfoBuf, "Target Left Region alarm Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] RelativeTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] Dev[ip:%s,port:%d,ivmsChan:%d] TargetType[%d] leftDirection[%d]\n",\
struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour,struAbsTime.dwMinute, struAbsTime.dwSecond, \
struRelativeTime.dwYear, struRelativeTime.dwMonth, struRelativeTime.dwDay, struRelativeTime.dwHour,struRelativeTime.dwMinute, struRelativeTime.dwSecond, \
struTargetLeftRegionAlarm.struDevInfo.struDevIP.sIpV4, struTargetLeftRegionAlarm.struDevInfo.wPort, struTargetLeftRegionAlarm.struDevInfo.byIvmsChannel, \
struTargetLeftRegionAlarm.byTargetType, struTargetLeftRegionAlarm.byLeftDirection);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcFaceSnapMatchAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[2048] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_VCA_FACESNAP_MATCH_ALARM struFaceSnapMatchAlarm = {0};
memcpy(&struFaceSnapMatchAlarm, pAlarmInfo, sizeof(struFaceSnapMatchAlarm));
// 打印信息
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
if (struFaceSnapMatchAlarm.struSnapInfo.dwUIDLen > 0 && struFaceSnapMatchAlarm.struSnapInfo.pUIDBuffer != NULL)
{
FaceSnapMatchAlarmInfo(wParam, lParam);
return;
}
char tempFDID[256] = {0};
if (struFaceSnapMatchAlarm.struBlackListInfo.dwFDIDLen > 0
&& struFaceSnapMatchAlarm.struBlackListInfo.dwFDIDLen < sizeof(tempFDID)
&& struFaceSnapMatchAlarm.struBlackListInfo.pFDID != NULL)
{
memcpy(tempFDID, struFaceSnapMatchAlarm.struBlackListInfo.pFDID, struFaceSnapMatchAlarm.struBlackListInfo.dwFDIDLen);
}
char temppID[256] = { 0 };
if (struFaceSnapMatchAlarm.struBlackListInfo.dwPIDLen > 0
&& struFaceSnapMatchAlarm.struBlackListInfo.dwPIDLen < sizeof(temppID)
&& struFaceSnapMatchAlarm.struBlackListInfo.pPID != NULL)
{
memcpy(temppID, struFaceSnapMatchAlarm.struBlackListInfo.pPID, struFaceSnapMatchAlarm.struBlackListInfo.dwPIDLen);
}
char tempFDDesc[256] = { 0 };
if (struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFDDescriptionLen > 0
&& struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFDDescriptionLen < sizeof(tempFDDesc)
&& struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.pFDDescriptionBuffer != NULL)
{
memcpy(tempFDDesc, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.pFDDescriptionBuffer, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFDDescriptionLen);
}
string strFDDesc = UTF82ASCII(tempFDDesc);
char tempFCAddition[256] = { 0 };
if (struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFCAdditionInfoLen > 0
&& struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFCAdditionInfoLen < sizeof(tempFCAddition)
&& struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.pFCAdditionInfoBuffer != NULL)
{
memcpy(tempFCAddition, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.pFCAdditionInfoBuffer, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFCAdditionInfoLen);
}
string strFCAddition = UTF82ASCII(tempFCAddition);
sprintf(szInfoBuf, "Face Snap Match alarm Channel[%d] IvmsChannel[%d] BrokenNetHttp[%d] Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d diff[%2.2d%2.2d] FaceID[%d] BlackList ID[%d] StorageIP[%s]-StoragePort[%d] Sex[%d] Glasses[%d] Age[%d] FacePicQuality[%d]\
StayDuration[%0.3f] MatchPicNum[%d] struRegion[%0.1f, %0.1f, %0.1f, %0.1f] PicTransType[%d] FDID[%s] PID[%s] FDDesc[%s] Similarity[%f] ThresholdValue[%d]\
ListType[%d] ContrastStatus[%d] ModelingStatus[%d] Mask[%d] Smile[%d] FCAddtion[%s] Ethnic[%d] LivenessDetectionStatus[%d] IsNoSaveFDPicture[%d] byRealTimeContrast[%d]\n",
struFaceSnapMatchAlarm.struSnapInfo.struDevInfo.byChannel, struFaceSnapMatchAlarm.struSnapInfo.struDevInfo.byIvmsChannel, struFaceSnapMatchAlarm.byBrokenNetHttp, struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour,
struAbsTime.dwMinute, struAbsTime.dwSecond, \
struFaceSnapMatchAlarm.cTimeDifferenceH, struFaceSnapMatchAlarm.cTimeDifferenceM, \
struFaceSnapMatchAlarm.struSnapInfo.dwSnapFacePicID, \
struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwRegisterID, \
struFaceSnapMatchAlarm.sStorageIP, struFaceSnapMatchAlarm.wStoragePort, \
struFaceSnapMatchAlarm.struSnapInfo.bySex, struFaceSnapMatchAlarm.struSnapInfo.byGlasses, \
struFaceSnapMatchAlarm.struSnapInfo.byAge, struFaceSnapMatchAlarm.struSnapInfo.byFacePicQuality, struFaceSnapMatchAlarm.struSnapInfo.fStayDuration, struFaceSnapMatchAlarm.byMatchPicNum, \
struFaceSnapMatchAlarm.struRegion.fX, struFaceSnapMatchAlarm.struRegion.fY, struFaceSnapMatchAlarm.struRegion.fWidth, struFaceSnapMatchAlarm.struRegion.fHeight, struFaceSnapMatchAlarm.byPicTransType, tempFDID, temppID, strFDDesc.c_str(), struFaceSnapMatchAlarm.fSimilarity, struFaceSnapMatchAlarm.struBlackListInfo.wThresholdValue, \
struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.byType, struFaceSnapMatchAlarm.byContrastStatus, struFaceSnapMatchAlarm.byModelingStatus, struFaceSnapMatchAlarm.byMask, struFaceSnapMatchAlarm.bySmile, (char*)tempFCAddition, struFaceSnapMatchAlarm.struSnapInfo.byEthnic, struFaceSnapMatchAlarm.byLivenessDetectionStatus, \
struFaceSnapMatchAlarm.struBlackListInfo.byIsNoSaveFDPicture, struFaceSnapMatchAlarm.struBlackListInfo.byRealTimeContrast);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
if (struFaceSnapMatchAlarm.struSnapInfo.dwSnapFacePicLen > 0 && struFaceSnapMatchAlarm.struSnapInfo.pBuffer1 != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
// SYSTEMTIME t;
// GetLocalTime(&t);
// char chTime[128];
// sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struFaceSnapMatchAlarm.byPicTransType)
{
sprintf(cFilename, "%s\\Match_SnapPic[%s].txt", cFilename, chTime);
}
else
{
sprintf(cFilename, "%s\\Match SnapPic[%s].jpg", cFilename, chTime);
}
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceSnapMatchAlarm.struSnapInfo.pBuffer1, struFaceSnapMatchAlarm.struSnapInfo.dwSnapFacePicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struFaceSnapMatchAlarm.struBlackListInfo.dwBlackListPicLen > 0 && struFaceSnapMatchAlarm.struBlackListInfo.pBuffer1 != NULL)
{
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
char cFilename[256] = { 0 };
HANDLE hFile;
DWORD dwReturn;
// SYSTEMTIME t;
// GetLocalTime(&t);
// char chTime[128];
// sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struFaceSnapMatchAlarm.byPicTransType)
{
sprintf(cFilename, "%s\\Match_BlackList_Pic[%s].txt", cFilename, chTime);
}
else
{
sprintf(cFilename, "%s\\Match BlackList Pic[%s].jpg", cFilename, chTime);
}
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceSnapMatchAlarm.struBlackListInfo.pBuffer1, struFaceSnapMatchAlarm.struBlackListInfo.dwBlackListPicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struFaceSnapMatchAlarm.dwSnapPicLen > 0 && struFaceSnapMatchAlarm.pSnapPicBuffer != NULL)
{
char cFilename[256] = { 0 };
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
HANDLE hFile;
DWORD dwReturn;
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struFaceSnapMatchAlarm.byPicTransType)
sprintf(cFilename, "%s\\Match_SnapBigPic[%s].txt", cFilename, chTime);
else
sprintf(cFilename, "%s\\MatchSnapBigPic[%s].jpg", cFilename, chTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceSnapMatchAlarm.pSnapPicBuffer, struFaceSnapMatchAlarm.dwSnapPicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.dwPersonInfoExtendLen > 0 && struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend != NULL)
{
char cFilename[256] = { 0 };
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
HANDLE hFile;
DWORD dwReturn;
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\PersonInfoXML[%s].txt", cFilename, chTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.dwPersonInfoExtendLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struFaceSnapMatchAlarm.struSnapInfo.pBuffer1 != NULL)
{
delete []struFaceSnapMatchAlarm.struSnapInfo.pBuffer1;
struFaceSnapMatchAlarm.struSnapInfo.pBuffer1 = NULL;
}
if (struFaceSnapMatchAlarm.struBlackListInfo.pBuffer1 != NULL)
{
delete []struFaceSnapMatchAlarm.struBlackListInfo.pBuffer1;
struFaceSnapMatchAlarm.struBlackListInfo.pBuffer1 = NULL;
}
if (struFaceSnapMatchAlarm.pSnapPicBuffer != NULL)
{
delete[]struFaceSnapMatchAlarm.pSnapPicBuffer;
struFaceSnapMatchAlarm.pSnapPicBuffer = NULL;
}
if (struFaceSnapMatchAlarm.pModelDataBuffer != NULL)
{
delete[]struFaceSnapMatchAlarm.pModelDataBuffer;
struFaceSnapMatchAlarm.pModelDataBuffer = NULL;
}
if (struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend != NULL)
{
delete[]struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend;
struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend = NULL;
}
if (struFaceSnapMatchAlarm.struSnapInfo.pUIDBuffer != NULL)
{
delete[]struFaceSnapMatchAlarm.struSnapInfo.pUIDBuffer;
struFaceSnapMatchAlarm.struSnapInfo.pUIDBuffer = NULL;
}
if (struFaceSnapMatchAlarm.struBlackListInfo.pFDID != NULL)
{
delete[]struFaceSnapMatchAlarm.struBlackListInfo.pFDID;
struFaceSnapMatchAlarm.struBlackListInfo.pFDID = NULL;
}
if (struFaceSnapMatchAlarm.struBlackListInfo.pPID != NULL)
{
delete[]struFaceSnapMatchAlarm.struBlackListInfo.pPID;
struFaceSnapMatchAlarm.struBlackListInfo.pPID = NULL;
}
}
void CClientDemoDlg::FaceSnapMatchAlarmInfo(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[2048] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_VCA_FACESNAP_MATCH_ALARM struFaceSnapMatchAlarm = { 0 };
memcpy(&struFaceSnapMatchAlarm, pAlarmInfo, sizeof(struFaceSnapMatchAlarm));
char sInfo[5120] = { 0 };
// NET_VCA_FACESNAP_MATCH_ALARM
sprintf(sInfo, "NET_VCA_FACESNAP_MATCH_ALARM \r\n");
sprintf(sInfo, "%s fSimilarity=%0.3f \r\n", sInfo, struFaceSnapMatchAlarm.fSimilarity);
sprintf(sInfo, "%s byMatchPicNum=%d \r\n", sInfo, struFaceSnapMatchAlarm.byMatchPicNum);
sprintf(sInfo, "%s wStoragePort=%d \r\n", sInfo, struFaceSnapMatchAlarm.wStoragePort);
sprintf(sInfo, "%s dwSnapPicLen=%d \r\n", sInfo, struFaceSnapMatchAlarm.dwSnapPicLen);
sprintf(sInfo, "%s dwModelDataLen=%d \r\n", sInfo, struFaceSnapMatchAlarm.dwModelDataLen);
sprintf(sInfo, "%s sStorageIP=%s \r\n", sInfo, struFaceSnapMatchAlarm.sStorageIP);
sprintf(sInfo, "%s struRegion[%0.1f, %0.1f, %0.1f, %0.1f] \r\n", sInfo, \
struFaceSnapMatchAlarm.struRegion.fX, struFaceSnapMatchAlarm.struRegion.fY, struFaceSnapMatchAlarm.struRegion.fWidth, struFaceSnapMatchAlarm.struRegion.fHeight);
sprintf(sInfo, "%s byLivenessDetectionStatus=%d \r\n", sInfo, struFaceSnapMatchAlarm.byLivenessDetectionStatus);
// NET_VCA_FACESNAP_INFO_ALARM
sprintf(sInfo, "%sNET_VCA_FACESNAP_INFO_ALARM \r\n", sInfo);
sprintf(sInfo, "%s dwRelativeTime=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.dwRelativeTime);
sprintf(sInfo, "%s dwAbsTime=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
sprintf(sInfo, "%s dwSnapFacePicID=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.dwSnapFacePicID);
sprintf(sInfo, "%s dwSnapFacePicLen=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.dwSnapFacePicLen);
sprintf(sInfo, "%s byFaceScore=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.byFaceScore);
sprintf(sInfo, "%s bySex=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.bySex);
sprintf(sInfo, "%s byGlasses=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.byGlasses);
sprintf(sInfo, "%s byAge=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.byAge);
sprintf(sInfo, "%s byAgeDeviation=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.byAgeDeviation);
sprintf(sInfo, "%s byAgeGroup=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.byAgeGroup);
sprintf(sInfo, "%s byFacePicQuality=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.byFacePicQuality);
sprintf(sInfo, "%s dwUIDLen=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.dwUIDLen);
sprintf(sInfo, "%s fStayDuration=%0.3f \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.fStayDuration);
sprintf(sInfo, "%s byEthnic=%d \r\n", sInfo, struFaceSnapMatchAlarm.struSnapInfo.byEthnic);
// NET_VCA_BLACKLIST_INFO_ALARM
sprintf(sInfo, "%sNET_VCA_BLACKLIST_INFO_ALARM", sInfo);
sprintf(sInfo, "%s dwBlackListPicLen=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.dwBlackListPicLen);
sprintf(sInfo, "%s byIsNoSaveFDPicture=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.byIsNoSaveFDPicture);
sprintf(sInfo, "%s byRealTimeContrast=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.byRealTimeContrast);
// NET_VCA_BLACKLIST_INFO
sprintf(sInfo, "%sNET_VCA_BLACKLIST_INFO", sInfo);
sprintf(sInfo, "%s dwRelativeTime=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwRegisterID);
sprintf(sInfo, "%s dwGroupNo=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwGroupNo);
sprintf(sInfo, "%s byType=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.byType);
sprintf(sInfo, "%s byLevel=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.byLevel);
sprintf(sInfo, "%s byRemark=%s \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.byRemark);
// NET_VCA_HUMAN_ATTRIBUTE
sprintf(sInfo, "%sNET_VCA_HUMAN_ATTRIBUTE\r\n", sInfo);
sprintf(sInfo, "%s bySex=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.bySex);
sprintf(sInfo, "%s byCertificateType=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.byCertificateType);
sprintf(sInfo, "%s byBirthDate=%s \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.byBirthDate);
sprintf(sInfo, "%s byName=%s \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.byName);
sprintf(sInfo, "%s byCertificateNumber=%s \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.byCertificateNumber);
sprintf(sInfo, "%s byAgeGroup=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.byAgeGroup);
// NET_DVR_AREAINFOCFG
sprintf(sInfo, "%sNET_DVR_AREAINFOCFG \r\n", sInfo);
sprintf(sInfo, "%s dwCode=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.struNativePlace.dwCode);
sprintf(sInfo, "%s wNationalityID=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.struNativePlace.wNationalityID);
sprintf(sInfo, "%s wProvinceID=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.struNativePlace.wProvinceID);
sprintf(sInfo, "%s wCityID=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.struNativePlace.wCityID);
sprintf(sInfo, "%s wCountyID=%d \r\n", sInfo, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.struNativePlace.wCountyID);
// 打印信息
NET_DVR_TIME struAbsTime = { 0 };
struAbsTime.dwYear = GET_YEAR(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struFaceSnapMatchAlarm.struSnapInfo.dwAbsTime);
NET_DVR_TIME struRelativeTime = { 0 };
struRelativeTime.dwYear = GET_YEAR(struFaceSnapMatchAlarm.struSnapInfo.dwRelativeTime);
struRelativeTime.dwMonth = GET_MONTH(struFaceSnapMatchAlarm.struSnapInfo.dwRelativeTime);
struRelativeTime.dwDay = GET_DAY(struFaceSnapMatchAlarm.struSnapInfo.dwRelativeTime);
struRelativeTime.dwHour = GET_HOUR(struFaceSnapMatchAlarm.struSnapInfo.dwRelativeTime);
struRelativeTime.dwMinute = GET_MINUTE(struFaceSnapMatchAlarm.struSnapInfo.dwRelativeTime);
struRelativeTime.dwSecond = GET_SECOND(struFaceSnapMatchAlarm.struSnapInfo.dwRelativeTime);
char tempFDID[256] = { 0 };
if (struFaceSnapMatchAlarm.struBlackListInfo.dwFDIDLen > 0 && struFaceSnapMatchAlarm.struBlackListInfo.pFDID != NULL)
{
memcpy(tempFDID, struFaceSnapMatchAlarm.struBlackListInfo.pFDID, struFaceSnapMatchAlarm.struBlackListInfo.dwFDIDLen);
}
char temppID[256] = { 0 };
if (struFaceSnapMatchAlarm.struBlackListInfo.dwPIDLen > 0 && struFaceSnapMatchAlarm.struBlackListInfo.pPID != NULL)
{
memcpy(temppID, struFaceSnapMatchAlarm.struBlackListInfo.pPID, struFaceSnapMatchAlarm.struBlackListInfo.dwPIDLen);
}
char *tempFDDesc = new char[struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFDDescriptionLen];
if (struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFDDescriptionLen > 0 && struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.pFDDescriptionBuffer != NULL)
{
memcpy(tempFDDesc, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.pFDDescriptionBuffer, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFDDescriptionLen);
}
string strFDDesc = UTF82ASCII(tempFDDesc);
char *tempFCAddition = new char[struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFCAdditionInfoLen];
if (struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFCAdditionInfoLen > 0
&& struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.pFCAdditionInfoBuffer != NULL)
{
memcpy(tempFCAddition, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.pFCAdditionInfoBuffer, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwFCAdditionInfoLen);
}
string strFCAddition = UTF82ASCII(tempFCAddition);
sprintf(szInfoBuf, "Face Snap Match alarm Channel[%d] IvmsChannel[%d] BrokenNetHttp[%d] Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d diff[%2.2d%2.2d] \
Relate[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] \
FaceID[%d] BlackList ID[%d] StorageIP[%s]-StoragePort[%d] Sex[%d] Glasses[%d] Age[%d] FacePicQuality[%d]\
StayDuration[%0.3f] MatchPicNum[%d] struRegion[%0.1f, %0.1f, %0.1f, %0.1f] PicTransType[%d] FDID[%s] PID[%s] FDDesc[%s] Similarity[%f] ThresholdValue[%d]\
ListType[%d] ContrastStatus[%d] ModelingStatus[%d] Mask[%d] Smile[%d] \
FCAddtion[%s] Ethnic[%d] LivenessDetectionStatus[%d] IsNoSaveFDPicture[%d] byRealTimeContrast[%d]\n",
struFaceSnapMatchAlarm.struSnapInfo.struDevInfo.byChannel, struFaceSnapMatchAlarm.struSnapInfo.struDevInfo.byIvmsChannel, struFaceSnapMatchAlarm.byBrokenNetHttp, struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour,
struAbsTime.dwMinute, struAbsTime.dwSecond, \
struFaceSnapMatchAlarm.cTimeDifferenceH, struFaceSnapMatchAlarm.cTimeDifferenceM, \
struRelativeTime.dwYear, struRelativeTime.dwMonth, struRelativeTime.dwDay, struRelativeTime.dwHour, struRelativeTime.dwMinute, struRelativeTime.dwSecond,\
struFaceSnapMatchAlarm.struSnapInfo.dwSnapFacePicID, \
struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.dwRegisterID, \
struFaceSnapMatchAlarm.sStorageIP, struFaceSnapMatchAlarm.wStoragePort, \
struFaceSnapMatchAlarm.struSnapInfo.bySex, struFaceSnapMatchAlarm.struSnapInfo.byGlasses, \
struFaceSnapMatchAlarm.struSnapInfo.byAge, struFaceSnapMatchAlarm.struSnapInfo.byFacePicQuality, struFaceSnapMatchAlarm.struSnapInfo.fStayDuration, struFaceSnapMatchAlarm.byMatchPicNum, \
struFaceSnapMatchAlarm.struRegion.fX, struFaceSnapMatchAlarm.struRegion.fY, struFaceSnapMatchAlarm.struRegion.fWidth, struFaceSnapMatchAlarm.struRegion.fHeight, struFaceSnapMatchAlarm.byPicTransType, tempFDID, temppID, strFDDesc.c_str(), struFaceSnapMatchAlarm.fSimilarity, struFaceSnapMatchAlarm.struBlackListInfo.wThresholdValue, \
struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.byType, struFaceSnapMatchAlarm.byContrastStatus, struFaceSnapMatchAlarm.byModelingStatus, struFaceSnapMatchAlarm.byMask, struFaceSnapMatchAlarm.bySmile, strFCAddition.c_str(), struFaceSnapMatchAlarm.struSnapInfo.byEthnic, struFaceSnapMatchAlarm.byLivenessDetectionStatus, \
struFaceSnapMatchAlarm.struBlackListInfo.byIsNoSaveFDPicture, struFaceSnapMatchAlarm.struBlackListInfo.byRealTimeContrast);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
delete[] tempFDDesc;
tempFDDesc = NULL;
delete[] tempFCAddition;
tempFCAddition = NULL;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
int iPort = pAlarmDev->wLinkPort;
char cFilename[256] = { 0 };
char cFilenameTemp[256] = { 0 };
memset(cFilenameTemp, 0, 256);
BYTE cUID[64] = { 0 };
if (struFaceSnapMatchAlarm.struSnapInfo.dwUIDLen > 0 && struFaceSnapMatchAlarm.struSnapInfo.pUIDBuffer != NULL)
{
memcpy(cUID, struFaceSnapMatchAlarm.struSnapInfo.pUIDBuffer, struFaceSnapMatchAlarm.struSnapInfo.dwUIDLen - 1);
sprintf(cFilename, "%s\\%s[%d][facematch]\\", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
int i = GetLastError();
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%sAbs_%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d_", cFilename, struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, \
struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond);
for (int i = 0; i < 17; i++)
{
if (cUID[i] != '0')
{
sprintf(cFilename, "%s%c", cFilename, cUID[i]);
}
}
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
int i = GetLastError();
CreateDirectory(cFilename, NULL);
}
DWORD dwReturn = 0;
HANDLE hFile = NULL;
sprintf(cFilenameTemp, "%s\\AlarmInfo[%s--fSimilarity=%0.3f].txt", cFilename, chTime, struFaceSnapMatchAlarm.fSimilarity);
hFile = CreateFile(cFilenameTemp, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
int i = GetLastError();
return;
}
WriteFile(hFile, sInfo, 5120, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
else
{
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d][%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
}
memset(cFilenameTemp, 0, 256);
if (struFaceSnapMatchAlarm.struSnapInfo.dwSnapFacePicLen > 0 && struFaceSnapMatchAlarm.struSnapInfo.pBuffer1 != NULL)
{
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
HANDLE hFile;
DWORD dwReturn;
if (struFaceSnapMatchAlarm.byPicTransType)
{
sprintf(cFilenameTemp, "%s\\Match_SnapPic[%s].txt", cFilename, chTime);
}
else
{
sprintf(cFilenameTemp, "%s\\MatchSnapPic[%s].jpg", cFilename, chTime);
}
hFile = CreateFile(cFilenameTemp, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
int i = GetLastError();
return;
}
WriteFile(hFile, struFaceSnapMatchAlarm.struSnapInfo.pBuffer1, struFaceSnapMatchAlarm.struSnapInfo.dwSnapFacePicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
memset(cFilenameTemp, 0, 256);
if (struFaceSnapMatchAlarm.dwSnapPicLen > 0 && struFaceSnapMatchAlarm.pSnapPicBuffer != NULL)
{
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
HANDLE hFile;
DWORD dwReturn;
if (struFaceSnapMatchAlarm.byPicTransType)
{
sprintf(cFilenameTemp, "%s\\Match_SnapBigPic[%s].txt", cFilename, chTime);
}
else
{
sprintf(cFilenameTemp, "%s\\MatchSnapBigPic[%s].jpg", cFilename, chTime);
}
hFile = CreateFile(cFilenameTemp, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceSnapMatchAlarm.pSnapPicBuffer, struFaceSnapMatchAlarm.dwSnapPicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
memset(cFilenameTemp, 0, 256);
if (struFaceSnapMatchAlarm.struBlackListInfo.dwBlackListPicLen > 0 && struFaceSnapMatchAlarm.struBlackListInfo.pBuffer1 != NULL)
{
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
HANDLE hFile;
DWORD dwReturn;
if (struFaceSnapMatchAlarm.byPicTransType)
{
sprintf(cFilenameTemp, "%s\\Match_BlackList_Pic[%s].txt", cFilename, chTime);
}
else
{
sprintf(cFilenameTemp, "%s\\MatchBlackListPic[%d%d].jpg", cFilename, struFaceSnapMatchAlarm.struBlackListInfo.dwBlackListPicLen, g_iCount);
}
hFile = CreateFile(cFilenameTemp, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceSnapMatchAlarm.struBlackListInfo.pBuffer1, struFaceSnapMatchAlarm.struBlackListInfo.dwBlackListPicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
memset(cFilenameTemp, 0, 256);
if (struFaceSnapMatchAlarm.dwModelDataLen > 0 && struFaceSnapMatchAlarm.pModelDataBuffer != NULL)
{
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
HANDLE hFile;
DWORD dwReturn;
sprintf(cFilenameTemp, "%s\\MatchBlackLisModelData[%s].txt", cFilename, chTime);
hFile = CreateFile(cFilenameTemp, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceSnapMatchAlarm.pModelDataBuffer, struFaceSnapMatchAlarm.dwModelDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
memset(cFilenameTemp, 0, 256);
if (struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.dwPersonInfoExtendLen > 0 && struFaceSnapMatchAlarm.pModelDataBuffer != NULL)
{
HANDLE hFile;
DWORD dwReturn;
sprintf(cFilenameTemp, "%s\\MatchBlackListCustomInfoLen[%d%d].txt", cFilename, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.dwPersonInfoExtendLen, g_iCount);
hFile = CreateFile(cFilenameTemp, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend, struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.dwPersonInfoExtendLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
g_iCount++;
if (struFaceSnapMatchAlarm.struSnapInfo.pBuffer1 != NULL)
{
delete[]struFaceSnapMatchAlarm.struSnapInfo.pBuffer1;
struFaceSnapMatchAlarm.struSnapInfo.pBuffer1 = NULL;
}
if (struFaceSnapMatchAlarm.struBlackListInfo.pBuffer1 != NULL)
{
delete[]struFaceSnapMatchAlarm.struBlackListInfo.pBuffer1;
struFaceSnapMatchAlarm.struBlackListInfo.pBuffer1 = NULL;
}
if (struFaceSnapMatchAlarm.pSnapPicBuffer != NULL)
{
delete[]struFaceSnapMatchAlarm.pSnapPicBuffer;
struFaceSnapMatchAlarm.pSnapPicBuffer = NULL;
}
if (struFaceSnapMatchAlarm.struSnapInfo.pUIDBuffer != NULL)
{
delete[]struFaceSnapMatchAlarm.struSnapInfo.pUIDBuffer;
struFaceSnapMatchAlarm.struSnapInfo.pUIDBuffer = NULL;
}
if (struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend != NULL)
{
delete[]struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend;
struFaceSnapMatchAlarm.struBlackListInfo.struBlackListInfo.struAttribute.pPersonInfoExtend = NULL;
}
if (struFaceSnapMatchAlarm.pModelDataBuffer != NULL)
{
delete[]struFaceSnapMatchAlarm.pModelDataBuffer;
struFaceSnapMatchAlarm.pModelDataBuffer = NULL;
}
if (struFaceSnapMatchAlarm.struBlackListInfo.pFDID != NULL)
{
delete[]struFaceSnapMatchAlarm.struBlackListInfo.pFDID;
struFaceSnapMatchAlarm.struBlackListInfo.pFDID = NULL;
}
}
void CClientDemoDlg::ProcRuleInfoUpload(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_RULE_INFO_ALARM struRuleInfo = {0};
memcpy(&struRuleInfo, pAlarmInfo, sizeof(struRuleInfo));
int i = struRuleInfo.struDevInfo.byChannel - g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struRuleInfo.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struRuleInfo.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struRuleInfo.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struRuleInfo.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struRuleInfo.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struRuleInfo.dwAbsTime);
sprintf(szInfoBuf, "Rule info Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] relative[%d] DevInfo ip[%d]port[%d]chan[%d]",
struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour,
struAbsTime.dwMinute, struAbsTime.dwSecond, struRuleInfo.dwRelativeTime,
struRuleInfo.struDevInfo.struDevIP.sIpV4, struRuleInfo.struDevInfo.wPort, struRuleInfo.struDevInfo.byChannel);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
NET_DVR_EVENT_INFO struEventInfo = {0};
for ( i = 0; i < struRuleInfo.struEventInfoList.byNum; i++)
{
memcpy(&struEventInfo, &struRuleInfo.struEventInfoList.struEventInfo[i], sizeof(struEventInfo));
if (VCA_HIGH_DENSITY == struEventInfo.dwEventType)
{
sprintf(szInfoBuf, "High density RuleID[%d]Name[%s]density[%f]", struEventInfo.byRuleID, struEventInfo.byRuleName,
struEventInfo.uEventParam.fCrowdDensity);
}
else if (VCA_HUMAN_ENTER == struEventInfo.dwEventType)
{
sprintf(szInfoBuf, "Human enter RuleID[%d]Name[%s]Human enter[%d]",struEventInfo.byRuleID,
struEventInfo.byRuleName, struEventInfo.uEventParam.dwHumanIn);
}
else
{
sprintf(szInfoBuf, "event info RuleID[%d]Name[%s]", struEventInfo.byRuleID, struEventInfo.byRuleName);
}
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
}
void CClientDemoDlg::ProcSensorAlarm(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_SENSOR_ALARM struSensorAlarm = {0};
memcpy(&struSensorAlarm, pAlarmInfo, sizeof(struSensorAlarm));
if (struSensorAlarm.bySensorChannel>48)
{
AfxMessageBox("模拟量通道号异常");
return;
}
memcpy(&m_struSensorAlarm[struSensorAlarm.bySensorChannel - 1], &struSensorAlarm, sizeof(struSensorAlarm));
// memcpy(&m_struSensorAlarm, &struSensorAlarm, sizeof(m_struSensorAlarm));
char szLan[1024] = {0};
char szName[33] = { 0 };
strncpy(szName, (char*)struSensorAlarm.byName, NAME_LEN);
sprintf(szLan, "Sensor Alarm:AbsTime[%d]Name[%s]SensorChan[%d]Type[%d]AlramType[%d]AlarmMode[%u]Value[%f]",
struSensorAlarm.dwAbsTime, szName, struSensorAlarm.bySensorChannel,
struSensorAlarm.byType, struSensorAlarm.byAlarmType, struSensorAlarm.byAlarmMode, struSensorAlarm.fValue);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
if (g_pDlgSensor != NULL)
{
g_pDlgSensor->SetSensorDate(struSensorAlarm);
}
}
void CClientDemoDlg::ProcCVRAlarm(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_CVR_ALARM struCVRAlarm = {0};
memcpy(&struCVRAlarm, pAlarmInfo, sizeof(struCVRAlarm));
char szLan[1024] = {0};
sprintf(szLan, "CVR ALARM Time[%04d-%02d-%02d %02d-%02d-%02d] AlarmLevel[%d] Status[%d] FirstType[%s] FirstIndex[%s] SecondType[%s] SecondIndex[%s] \
ThirdType[%s] ThirdIndex[%s] FourthType[%s] FourthIndex[%s]",
struCVRAlarm.struTime.dwYear, struCVRAlarm.struTime.dwMonth, struCVRAlarm.struTime.dwDay,
struCVRAlarm.struTime.dwHour, struCVRAlarm.struTime.dwMinute, struCVRAlarm.struTime.dwSecond,
struCVRAlarm.byAlarmLevel, struCVRAlarm.byStatus,
struCVRAlarm.szFirstType, struCVRAlarm.szFirstIndex, struCVRAlarm.szSecondType, struCVRAlarm.szSecondIndex,
struCVRAlarm.szThirdType, struCVRAlarm.szThirdIndex, struCVRAlarm.szFourthType, struCVRAlarm.szFourthIndex);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
}
void CClientDemoDlg::ProcSensorValueUpload(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_SENSOR_ALARM struSensorValue = {0};
memcpy(&struSensorValue, pAlarmInfo, sizeof(struSensorValue));
if (struSensorValue.bySensorChannel > 48)
{
AfxMessageBox("模拟量通道号异常");
return;
}
memcpy(&m_struSensorAlarm[struSensorValue.bySensorChannel - 1], &struSensorValue, sizeof(struSensorValue));
// memcpy(&m_struSensorAlarm, &struSensorValue, sizeof(m_struSensorAlarm));
char szLan[1024] = {0};
sprintf(szLan, "ValueUpload:AbsTime[%d]Name[%s]SensorChan[%d]Type[%d]Value[%f]",
struSensorValue.dwAbsTime, struSensorValue.byName, struSensorValue.bySensorChannel,
struSensorValue.byType, struSensorValue.fValue);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
if (g_pDlgSensor != NULL)
{
g_pDlgSensor->SetSensorDate(struSensorValue);
}
}
void CClientDemoDlg::ProcSwitchAlarm(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_SWITCH_ALARM struSwitchAlarm = {0};
memcpy(&struSwitchAlarm, pAlarmInfo, sizeof(struSwitchAlarm));
char szLan[1024] = {0};
char szName[33] = {0};
memcpy(szName, struSwitchAlarm.byName, NAME_LEN);
//报警
CString tmp;
if (struSwitchAlarm.byAlarmType == 0)
{
tmp = "normal";
}
else if (struSwitchAlarm.byAlarmType == 1)
{
tmp = "short circuit";
}
else if (struSwitchAlarm.byAlarmType == 2)
{
tmp = "broken circuit";
}
else if (struSwitchAlarm.byAlarmType == 3)
{
tmp = "exception";
}
else
{
tmp = "unknown";
}
sprintf(szLan, "Switch alarm[%s], Name[%s]AlarmIn[%d]"\
, tmp, szName, struSwitchAlarm.wSwitchChannel);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
}
void CClientDemoDlg::ProcAlarmHostException(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_ALARMHOST_EXCEPTION_ALARM struAlarmHostException = {0};
memcpy(&struAlarmHostException, pAlarmInfo, sizeof(struAlarmHostException));
CString tmType;
// 异常参数 1-设备防拆报警 2-设备防拆后后恢复正常 3-主电源掉电报警 4-主电源掉电后恢复正常 5-内部通信故障报警
// 6-内部通信故障后恢复正常 7-电话线断线 8-电话线断线恢复 9-自检失败报警 10-自检失败后恢复正常
// 11蓄电池欠压 12蓄电池电压恢复正常,13-蓄电池故障;14-MBUS模块掉线;15-MBUS模块掉线恢复;16-键盘掉线;
//17-键盘掉线恢复;18-设备被移动;19-设备被移动复位 20-485外设线路断报警 21-485外设线路断后恢复正常
//100-子板1插上,101-子板1拔出, 103-子板2插上,104-子板2拔出
if (struAlarmHostException.dwExceptionType == 1)
{
tmType = "设备防拆报警";
}
else if (struAlarmHostException.dwExceptionType == 2)
{
tmType = "设备防拆后后恢复正常";
}
else if (struAlarmHostException.dwExceptionType == 3)
{
tmType = "主电源掉电报警";
}
else if (struAlarmHostException.dwExceptionType == 4)
{
tmType = "主电源掉电后恢复正常";
}
else if (struAlarmHostException.dwExceptionType == 5)
{
tmType = "内部通信故障报警";
}
else if (struAlarmHostException.dwExceptionType == 6)
{
tmType = "内部通信故障后恢复正常";
}
else if (struAlarmHostException.dwExceptionType == 7)
{
tmType = "电话线断线";
}
else if (struAlarmHostException.dwExceptionType == 8)
{
tmType = "电话线断线恢复";
}
else if (struAlarmHostException.dwExceptionType == 9)
{
tmType = "自检失败报警";
}
else if (struAlarmHostException.dwExceptionType == 10)
{
tmType = "自检失败后恢复正常";
}
else if (struAlarmHostException.dwExceptionType == 11)
{
tmType = "蓄电池欠压";
}
else if (struAlarmHostException.dwExceptionType == 12)
{
tmType = "蓄电池电压恢复正常";
}
else if (struAlarmHostException.dwExceptionType == 13)
{
tmType = "蓄电池故障";
}
else if (struAlarmHostException.dwExceptionType == 14)
{
tmType = "MBUS模块掉线";
}
else if (struAlarmHostException.dwExceptionType == 15)
{
tmType = "MBUS模块掉线恢复";
}
else if (struAlarmHostException.dwExceptionType == 16)
{
tmType = "键盘掉线";
}
else if (struAlarmHostException.dwExceptionType == 17)
{
tmType = "键盘掉线恢复";
}
else if (struAlarmHostException.dwExceptionType == 18)
{
tmType = "设备被移动";
}
else if (struAlarmHostException.dwExceptionType == 19)
{
tmType = "设备被移动复位";
}
else if (struAlarmHostException.dwExceptionType == 20)
{
tmType = "485外设线路断报警";
}
else if (struAlarmHostException.dwExceptionType == 21)
{
tmType = "485外设线路断后恢复正常";
}
else if (struAlarmHostException.dwExceptionType == 22)
{
tmType = "硬盘满";
}
else if (struAlarmHostException.dwExceptionType == 23)
{
tmType = "硬盘未格式化";
}
else if (struAlarmHostException.dwExceptionType == 24)
{
tmType = "硬盘读写出错";
}
else if (struAlarmHostException.dwExceptionType == 25)
{
tmType = "子板1插上";
}
else if (struAlarmHostException.dwExceptionType == 26)
{
tmType = "子板1拔出";
}
else if (struAlarmHostException.dwExceptionType == 27)
{
tmType = "子板2插上";
}
else if (struAlarmHostException.dwExceptionType == 28)
{
tmType = "子板2拔出";
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, tmType);
}
void CClientDemoDlg::ProcDeviceAlarm(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
if (COMM_ALARM_DEVICE == pAlarmDev->lCommand)
{
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_ALARMINFO_DEV struDeviceAlarm = {0};
memcpy(&struDeviceAlarm, pAlarmInfo, sizeof(struDeviceAlarm));
char szLan[1024] = {0};
sprintf(szLan, "Device Alarm(CVR): type[%d], num[%d]", struDeviceAlarm.dwAlarmType, struDeviceAlarm.dwNumber);
int iNumber = struDeviceAlarm.dwNumber;
WORD *pContent = struDeviceAlarm.pNO;
for (int i = 0; i < iNumber && i < 10; i++)
{
sprintf(szLan, "%s %d", szLan, *(pContent));
pContent = pContent + 1;
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
}
}
void CClientDemoDlg::ProcDeviceV40Alarm(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
if (COMM_ALARM_DEVICE_V40 == pAlarmDev->lCommand)
{
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_ALARMINFO_DEV_V40 struDeviceAlarm = {0};
memcpy(&struDeviceAlarm, pAlarmInfo, sizeof(struDeviceAlarm));
char szLan[1024] = {0};
sprintf(szLan, "Device Alarm(COMM_ALARM_DEVICE_V40): type[%d], num[%d],byLevel[%d]", struDeviceAlarm.dwAlarmType, struDeviceAlarm.dwNumber,struDeviceAlarm.uSubAlarmInfo.struResourceUsage.byLevel);
int iNumber = struDeviceAlarm.dwNumber;
WORD *pContent = struDeviceAlarm.pNO;
for (int i = 0; i < iNumber && i < 10; i++)
{
sprintf(szLan, "%s %d", szLan, *(pContent));
pContent = pContent + 1;
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
}
}
void CClientDemoDlg::ProcAlarmHostSatetyCabinState(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_ALARMHOST_SAFETYCABINSTATE struAlarm = {0};
memcpy(&struAlarm, pAlarmInfo, sizeof(struAlarm));
char szLan[1024] = {0};
char szLan1[64] = {0};
char szLan2[64] = {0};
char szLan3[64] = {0};
char szLan4[64] = {0};
char szLan5[64] = {0};
char szLan6[64] = {0};
char szLan7[64] = {0};
char szLan8[64] = {0};
char szLan9[64] = {0};
char szLan10[64] = {0};
char szLan11[64] = {0};
char szLan12[64] = {0};
char szLan13[64] = { 0 };
if (1 == struAlarm.byManState)
{
g_StringLanType(szLan1, "舱内有人; ", "someone in the cabin; ");
}
else
{
g_StringLanType(szLan1, "舱内没有人; ", "no one in the cabin; ");
}
if (1 == struAlarm.byEnterButton)
{
g_StringLanType(szLan2, "进门按钮: 按下; ", "EnterButton: on; ");
}
else
{
g_StringLanType(szLan2, "进门按钮: 不按下; ", "EnterButton: off; ");
}
if (1 == struAlarm.byExitButton)
{
g_StringLanType(szLan3, "出门按钮: 按下; ", "ExitButton: on; ");
}
else
{
g_StringLanType(szLan3, "出门按钮: 不按下; ", "ExitButton: off; ");
}
if (1 == struAlarm.byUrgencyButton)
{
g_StringLanType(szLan4, "紧急按钮: 按下; ", "UrgencyButton: off; ");
}
else
{
g_StringLanType(szLan4, "紧急按钮: 不按下; ", "UrgencyButton: off; ");
}
if (0 == struAlarm.byDoorState)
{
g_StringLanType(szLan5, "门关; ", "Door: close; ");
}
else
{
g_StringLanType(szLan5, "门开; ", "Door: open; ");
}
if (0 == struAlarm.byLockState)
{
g_StringLanType(szLan6, "锁关; ", "locker: close; ");
}
else
{
g_StringLanType(szLan6, "锁开; ", "locker: open; ");
}
if (0 == struAlarm.byAbnormal)
{
g_StringLanType(szLan7, "正常;", "Normal");
}
else
{
g_StringLanType(szLan7, "异常;", "Abnormal");
}
if (0 == struAlarm.byFanState)
{
g_StringLanType(szLan8, "风扇关; ", "Fan: off; ");
}
else
{
g_StringLanType(szLan8, "风扇开; ", "Fan: on; ");
}
if (0 == struAlarm.byLightState)
{
g_StringLanType(szLan9, "灯光关; ", "Light: off; ");
}
else
{
g_StringLanType(szLan9, "灯光开; ", "Light: on; ");
}
if (0 == struAlarm.byFollow)
{
g_StringLanType(szLan10, "无尾随", "Follow: no");
}
else
{
g_StringLanType(szLan10, "有尾随", "Follow: yes");
}
if (0 == struAlarm.byFaint)
{
g_StringLanType(szLan11, "无晕倒", "Faint: no");
}
else
{
g_StringLanType(szLan11, "有晕倒", "Faint: yes");
}
if (0 == struAlarm.byManyPerson)
{
g_StringLanType(szLan12, "无多人", "Single");
}
else
{
g_StringLanType(szLan12, "有多人", "ManyPerson");
}
if (0 == struAlarm.byFighting)
{
g_StringLanType(szLan13, "无打斗", "Not fight");
}
else
{
g_StringLanType(szLan13, "有打斗", "Fighting");
}
sprintf(szLan, "%s %s %s %s %s %s %s %s %s %s %s %s %s", szLan1, szLan2, szLan3, szLan4, szLan5, szLan6, szLan7, szLan8, szLan9, szLan10, szLan11, szLan12, szLan13);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
}
void CClientDemoDlg::ProcAlarmHostAlarmoutStatus(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_ALARMHOST_ALARMOUTSTATUS struAlarm = {0};
memcpy(&struAlarm, pAlarmInfo, sizeof(struAlarm));
char szLan[1024] = {0};
char szLanCn[1024] = {0};
char szLanEn[1024] = {0};
switch(struAlarm.byAlarmType)
{
case 1: //报警输出口状态
if(struAlarm.byAlarmStatus == 1)
{
sprintf(szLanCn, "报警输出口 %d(%s) 报警", struAlarm.wChan, struAlarm.byName);
sprintf(szLanEn, "Get Alarm from AlarmOut channel %d(%s)", struAlarm.wChan, struAlarm.byName);
g_StringLanType(szLan, szLanCn, szLanEn);
}
else
{
sprintf(szLanCn, "报警输出口 %d(%s) 报警取消", struAlarm.wChan, struAlarm.byName);
sprintf(szLanEn, "Alarm from AlarmOut channel %d(%s) clean", struAlarm.wChan, struAlarm.byName);
g_StringLanType(szLan, szLanCn, szLanEn);
}
break;
case 2: //警号状态
if(struAlarm.byAlarmStatus == 1)
{
sprintf(szLanCn, "警号 %d(%s) 警号输出", struAlarm.wChan, struAlarm.byName);
sprintf(szLanEn, "Get Alarm from siren %d(%s)", struAlarm.wChan, struAlarm.byName);
g_StringLanType(szLan, szLanCn, szLanEn);
}
else
{
sprintf(szLanCn, "警号 %d(%s) 警号关闭", struAlarm.wChan, struAlarm.byName);
sprintf(szLanEn, "Alarm from siren %d(%s) clean", struAlarm.wChan, struAlarm.byName);
g_StringLanType(szLan, szLanCn, szLanEn);
}
break;
default:
break;
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
}
void CClientDemoDlg::ProcAlarmHostCIDAlarm(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_CID_ALARM struAlarm = {0};
memcpy(&struAlarm, pAlarmInfo, sizeof(struAlarm));
char szLan[1024] = {0};
char szLanCn[1024] = {0};
char szLanEn[1024] = {0};
switch (struAlarm.byReportType)
{
case NET_DVR_DEFENCE_ALARM:
sprintf(szLanCn, "防区报警: ");
sprintf(szLanEn, "Zone Alarm: ");
break;
case NET_DVR_VIDEO_ALARM:
sprintf(szLanCn, "视频报警:");
sprintf(szLanEn, "Video Alarm:");
break;
case NET_DVR_VIRTUAL_DEFENCE_ALARM:
sprintf(szLanCn, "软防区报警:");
sprintf(szLanEn, "Soft Zone Alarm:");
break;
case NET_DVR_HOSTAGE_ALARM:
sprintf(szLanCn, "挟持报警: ");
sprintf(szLanEn, "Hostage Alarm:");
break;
case NET_DVR_KNOCK_DOWN_ALARM:
sprintf(szLanCn, "防拆报警: ");
sprintf(szLanEn, "Tamper Alarm: ");
break;
case NET_DVR_OPERATE_ALARM:
sprintf(szLanCn, "操作:");
sprintf(szLanEn, "Operate:");
break;
case NET_DVR_OHTER_ABNORMAL_ALARM:
sprintf(szLanCn, "异常:");
sprintf(szLanEn, "Abnormal:");
break;
case 0:
sprintf(szLanCn, "CID报警:");
sprintf(szLanEn, "CID alarm:");
break;
default:
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, "Unknown Alarm");
return;
}
char sTemp1[5] = {0};
char sTemp2[33] = {0};
memcpy(sTemp1, struAlarm.sCIDCode, 4);
sprintf(szLanCn, "%sCID事件号:%s", szLanCn, sTemp1);
sprintf(szLanEn, "%sCID:%s", szLanEn, sTemp1);
if (memcmp((char*)struAlarm.sCIDDescribe, "", NAME_LEN) != 0)
{
memcpy(sTemp2, struAlarm.sCIDDescribe, NAME_LEN);
sprintf(szLanCn, "%s, CID事件名:%s", szLanCn, sTemp2);
sprintf(szLanEn, "%s, CID describe:%s", szLanEn, sTemp2);
}
else
{
char sTempCn[64] = {0};
char sTempEn[64] = {0};
switch (atoi((char*)struAlarm.sCIDCode))
{
case CID_ENTER+CID_ALARM:
sprintf(sTempCn, "即时防区报警");
sprintf(sTempEn, "Instant Zone Alarm");
break;
case CID_ENTER+CID_FIRE_ALARM:
sprintf(sTempCn, "火警报警");
sprintf(sTempEn, "Fire Zone Alarm");
break;
case CID_ENTER+CID_ABDUCT_REPORT:
sprintf(sTempCn, "挟持报告");
sprintf(sTempEn, "Hostage Report");
break;
case CID_ENTER+CID_SILENT_24:
sprintf(sTempCn, "24小时无声防区报警");
sprintf(sTempEn, "24 H Non-audio Zone Alarm");
break;
case CID_ENTER+CID_AUDIO_24:
sprintf(sTempCn, "24小时有声防区报警");
sprintf(sTempEn, "24 H Audio Zone Alarm");
break;
case CID_ENTER+CID_AUXILIARY_24:
sprintf(sTempCn, "24小时辅助防区报警");
sprintf(sTempEn, "24 H Aux Zone Alarm");
break;
case CID_ENTER+CID_SHOCK_24:
sprintf(sTempCn, "24小时震动防区报警");
sprintf(sTempEn, "24 H Vib Zone Alarm");
break;
case CID_ENTER+CID_PERIMETER_ALARM:
sprintf(sTempCn, "周界防区报警");
sprintf(sTempEn, "Perimeter Zone Alarm");
break;
case CID_ENTER+CID_INNET_ALARM:
sprintf(sTempCn, "内部延时防区报警");
sprintf(sTempEn, "Internal Delay Zone Alarm");
break;
case CID_ENTER+CID_ENTER_EXIT:
sprintf(sTempCn, "延时防区报警");
sprintf(sTempEn, "Delay Zone Alarm");
break;
case CID_ENTER+CID_DEVICE_OPEN:
sprintf(sTempCn, "设备防拆");
sprintf(sTempEn, "Device Tampering Alarm");
break;
case CID_ENTER+CID_AC_LOSS:
sprintf(sTempCn, "交流电掉电");
sprintf(sTempEn, "AC Power Down");
break;
case CID_ENTER+CID_LOW_BATT_VOL:
sprintf(sTempCn, "蓄电池电压低");
sprintf(sTempEn, "Low Battery Voltage");
break;
case CID_ENTER+CID_DEV_RESET:
sprintf(sTempCn, "主机复位");
sprintf(sTempEn, "Host Reset");
break;
case CID_ENTER+CID_PRINTER_FAIL:
sprintf(sTempCn, "打印机掉线");
sprintf(sTempEn, "Printer Disconnected");
break;
case CID_ENTER+CID_LINE_LOSS:
sprintf(sTempCn, "电话线断开");
sprintf(sTempEn, "Telephone Disconnected");
break;
case CID_ENTER+CID_BUS_LOSS:
sprintf(sTempCn, "扩展总线模块掉线");
sprintf(sTempEn, "XBUS Module Disconnection");
break;
case CID_ENTER+CID_DETECTOR_OPEN:
sprintf(sTempCn, "防区感应器被拆");
sprintf(sTempEn, "Zone Sensor Demolishing");
break;
case CID_ENTER+CID_GUARD:
sprintf(sTempCn, "撤防");
sprintf(sTempEn, "Disarming");
break;
case CID_ENTER+CID_GUARD_AUTO:
sprintf(sTempCn, "自动撤防");
sprintf(sTempEn, "Auto Disarming");
break;
case CID_ENTER+CID_CANCEL_ARM:
sprintf(sTempCn, "消警");
sprintf(sTempEn, "Clear");
break;
case CID_ENTER+CID_GUARD_IMME:
sprintf(sTempCn, "即时撤防");
sprintf(sTempEn, "Instant Disarming");
break;
case CID_ENTER+CID_KEY_ZONE_GUARD:
sprintf(sTempCn, "钥匙防区撤防");
sprintf(sTempEn, "Key Zone Disarming");
break;
case CID_ENTER+CID_GUARD_STAY:
sprintf(sTempCn, "留守撤防");
sprintf(sTempEn, "Stay Disarming");
break;
case CID_ENTER+CID_AUTOCTRL_TRIG:
sprintf(sTempCn, "定时开启触发器");
sprintf(sTempEn, "Activate Trigger by Schedule");
break;
case CID_ENTER + CID_ONETOUCH_AWAY_ARMING:
sprintf(sTempCn, "一键外出布防");
sprintf(sTempEn, "One-touch away arming");
break;
case CID_ENTER + CID_ONETOUCH_STAY_ARMING:
sprintf(sTempCn, "一键留守布防");
sprintf(sTempEn, "One-touch stay arming");
break;
case CID_ENTER + CID_CARD_ARMING_OR_DISARMING:
sprintf(sTempCn, "刷卡撤防");
sprintf(sTempEn, "Card disarming");
break;
case CID_ENTER+CID_AUTOGUARD_FAIL:
sprintf(sTempCn, "自动布撤防失败");
sprintf(sTempEn, "Failed to automatically arm");
break;
case CID_ENTER+CID_AOPEN_TRIG_FAIL:
sprintf(sTempCn, "定时开启触发器失败");
sprintf(sTempEn, "Failed to activate the trigger");
break;
case CID_ENTER+CID_ACLOSE_TRIG_FAIL:
sprintf(sTempCn, "定时关闭触发器失败");
sprintf(sTempEn, "Failed to deactivate the trigger");
break;
case CID_ENTER+CID_AUTOUNGUARD_FAIL:
sprintf(sTempCn, "自动撤防失败");
sprintf(sTempEn, "Failed to auto disarm");
break;
case CID_ENTER+CID_BYPASS:
sprintf(sTempCn, "旁路");
sprintf(sTempEn, "Bypass");
break;
case CID_ENTER+CID_GROUP_BYPASS:
sprintf(sTempCn, "子系统组旁路");
sprintf(sTempEn, "Partition Group Bypass");
break;
case CID_ENTER+CID_MANUAL_TEST_RPT:
sprintf(sTempCn, "手动测试报告");
sprintf(sTempEn, "Manual Test Report");
break;
case CID_ENTER+CID_AUTO_TEST_RPT:
sprintf(sTempCn, "定时测试报告");
sprintf(sTempEn, "Timing Test Report");
break;
case CID_ENTER+CID_ENTER_PROG:
sprintf(sTempCn, "进入编程");
sprintf(sTempEn, "Enter Programming");
break;
case CID_ENTER+CID_EXIT_PROG:
sprintf(sTempCn, "退出编程");
sprintf(sTempEn, "Exit Programming");
break;
case CID_ENTER + CID_FIELD_DETECTION:
sprintf(sTempCn, "区域入侵");
sprintf(sTempEn, "Field Detection");
break;
case CID_EXIT + CID_FIELD_DETECTION:
sprintf(sTempCn, "区域入侵恢复");
sprintf(sTempEn, "Field Detection Reset");
break;
case CID_ENTER + CID_LINE_DETECTION:
sprintf(sTempCn, "跨界报警");
sprintf(sTempEn, "Line Detection");
break;
case CID_EXIT + CID_LINE_DETECTION:
sprintf(sTempCn, "跨界报警恢复");
sprintf(sTempEn, "Line Detection Reset");
break;
case CID_ENTER + CID_PIR_ALARM:
sprintf(sTempCn, "PIR报警");
sprintf(sTempEn, "PIR Alarm");
break;
case CID_EXIT + CID_PIR_ALARM:
sprintf(sTempCn, "PIR报警恢复");
sprintf(sTempEn, "PIR Alarm Reset");
break;
case CID_ENTER + CID_SOUND_INTENSITY_RISE:
sprintf(sTempCn, "声强陡升报警");
sprintf(sTempEn, "Sound Intensity Rise");
break;
case CID_EXIT + CID_SOUND_INTENSITY_RISE:
sprintf(sTempCn, "声强陡升报警恢复");
sprintf(sTempEn, "Sound Intensity Rise Reset");
break;
case CID_ENTER + CID_SOUND_INTENSITY_DROP:
sprintf(sTempCn, "声强陡降报警");
sprintf(sTempEn, "Sound Intensity Drop");
break;
case CID_EXIT + CID_SOUND_INTENSITY_DROP:
sprintf(sTempCn, "声强陡降报警恢复");
sprintf(sTempEn, "Sound Intensity Drop Reset");
break;
case CID_ENTER + CID_AUDIO_INPUT_EXCEPTION:
sprintf(sTempCn, "音频输入异常报警");
sprintf(sTempEn, "Audio Input Exception");
break;
case CID_EXIT + CID_AUDIO_INPUT_EXCEPTION:
sprintf(sTempCn, "音频输入异常报警恢复");
sprintf(sTempEn, "Audio Input Exception Reset");
break;
case CID_ENTER+CID_SOFT_INSTAND:
sprintf(sTempCn, "软防区紧急报警");
sprintf(sTempEn, "Soft Zone Emergency Alarm");
break;
case CID_ENTER+CID_SOFT_FIRE:
sprintf(sTempCn, "软防区火警");
sprintf(sTempEn, "Soft Zone Fire Alarm");
break;
case CID_ENTER+CID_SOFT_MOBS:
sprintf(sTempCn, "软防区匪警");
sprintf(sTempEn, "Soft Zone Bandit Alarm");
break;
case CID_ENTER+CID_KEY_FAIL:
sprintf(sTempCn, "键盘掉线");
sprintf(sTempEn, "Keyboard Loss Connection");
break;
case CID_ENTER+CID_TRIGGER_FAIL:
sprintf(sTempCn, "键盘总线上触发器掉线");
sprintf(sTempEn, "KBUS Trigger Disconnection");
break;
case CID_ENTER+CID_GPK_FAIL:
sprintf(sTempCn, "键盘总线上GP/K掉线");
sprintf(sTempEn, "KBUS GP/K Disconnection");
break;
case CID_ENTER+CID_MODULE_FAIL:
sprintf(sTempCn, "键盘总线上MN/K掉线");
sprintf(sTempEn, "KBUS MN/K Disconnection");
break;
case CID_ENTER + CID_WIRELESS_DETECTOR_FAIL:
sprintf(sTempCn, "无线探测器掉线");
sprintf(sTempEn, "Wireless Detector fail");
break;
case CID_ENTER + CID_WIRELESS_DETECTOR_BATTERY_LOW:
sprintf(sTempCn, "无线探测器欠压");
sprintf(sTempEn, "Wireless Detector battery low");
break;
case CID_ENTER+CID_WRIE_LESS_NET:
sprintf(sTempCn, "无线网络异常");
sprintf(sTempEn, "Wireless Network Exception");
break;
case CID_ENTER+CID_SIM_FAULT:
sprintf(sTempCn, "SIM卡异常");
sprintf(sTempEn, "SIM Card Exception");
break;
case CID_ENTER + CID_WIFI_ABNORMAL:
sprintf(sTempCn, "WIFI通信异常");
sprintf(sTempEn, "Wifi Abnormal");
break;
case CID_ENTER + CID_RF_ABNORMAL:
sprintf(sTempCn, "RF信号异常");
sprintf(sTempEn, "Rf signal Abnormal");
break;
case CID_ENTER+CID_IPADDR_CONFLICT:
sprintf(sTempCn, "IP冲突");
sprintf(sTempEn, "IP Address Conflict");
break;
case CID_ENTER+CID_ETHERNET_BROKEN:
sprintf(sTempCn, "网线断");
sprintf(sTempEn, "Network Disconnected");
break;
case CID_ENTER+CID_MOTION_DECTECT:
sprintf(sTempCn, "移动侦测报警开始");
sprintf(sTempEn, "Motion Detection Alarm Started");
break;
case CID_ENTER+CID_MASK_ALARM:
sprintf(sTempCn, "遮挡报警开始");
sprintf(sTempEn, "Tampering Alarm Started");
break;
case CID_ENTER+CID_VI_LOST:
sprintf(sTempCn, "视频信号丢失");
sprintf(sTempEn, "Video Signal Loss");
break;
case CID_ENTER+CID_VS_MISMATCH:
sprintf(sTempCn, "输入/输出视频制式不匹配");
sprintf(sTempEn, "Input/output Format Mismatch");
break;
case CID_ENTER+CID_VI_EXCEPTION:
sprintf(sTempCn, "视频输入异常");
sprintf(sTempEn, "Video Input Exception");
break;
case CID_ENTER+CID_HD_FULL:
sprintf(sTempCn, "硬盘满");
sprintf(sTempEn, "Hard disk is full");
break;
case CID_ENTER+CID_HD_ERROR:
sprintf(sTempCn, "硬盘出错");
sprintf(sTempEn, "Hard Disk Exception");
break;
case CID_ENTER+CID_PIC_SEND_FAILED:
sprintf(sTempCn, "图片上传失败");
sprintf(sTempEn, "Failed to upload the picture");
break;
case CID_ENTER + CID_KEY_LOCKED:
sprintf(sTempCn, "键盘锁定");
sprintf(sTempEn, "Keyboard locked");
break;
case CID_ENTER+CID_GUARD_SINGLE:
sprintf(sTempCn, "单防区撤防");
sprintf(sTempEn, "Single-Zone Disarming");
break;
case CID_ENTER + CID_ZONE_ASSOCIATED_DETECTOR:
sprintf(sTempCn, "防区添加探测器");
sprintf(sTempEn, "Zone add detector");
break;
case CID_EXIT+CID_ALARM:
sprintf(sTempCn, "即时防区恢复");
sprintf(sTempEn, "Instant Zone Recovered");
break;
case CID_EXIT+CID_FIRE_ALARM:
sprintf(sTempCn, "火警报警恢复");
sprintf(sTempEn, "Fire Zone Recovered");
break;
case CID_EXIT+CID_SILENT_24:
sprintf(sTempCn, "24小时无声防区恢复");
sprintf(sTempEn, "24 H Non-audio Zone Recovered");
break;
case CID_EXIT+CID_AUDIO_24:
sprintf(sTempCn, "24小时有声防区恢复");
sprintf(sTempEn, "24 H Audio Zone Recovered");
break;
case CID_EXIT+CID_AUXILIARY_24:
sprintf(sTempCn, "24小时辅助防区恢复");
sprintf(sTempEn, "24 H Aux Zone Recovered");
break;
case CID_EXIT+CID_SHOCK_24:
sprintf(sTempCn, "24小时震动防区恢复");
sprintf(sTempEn, "24 H Vib Zone Recovered");
break;
case CID_EXIT+CID_PERIMETER_ALARM:
sprintf(sTempCn, "周界防区恢复");
sprintf(sTempEn, "Perimeter Zone Recovered");
break;
case CID_EXIT+CID_INNET_ALARM:
sprintf(sTempCn, "内部延时防区恢复");
sprintf(sTempEn, "Internal Delay Zone Recovered");
break;
case CID_EXIT+CID_ENTER_EXIT:
sprintf(sTempCn, "延时防区恢复");
sprintf(sTempEn, "Delay Zone Recovered");
break;
case CID_EXIT+CID_DEVICE_OPEN:
sprintf(sTempCn, "设备防拆恢复");
sprintf(sTempEn, "Device Tampering Recovered");
break;
case CID_EXIT+CID_AC_LOSS:
sprintf(sTempCn, "交流电恢复");
sprintf(sTempEn, "AC Recovered");
break;
case CID_EXIT+CID_LOW_BATT_VOL:
sprintf(sTempCn, "蓄电池电压正常");
sprintf(sTempEn, "Normal Battery Voltage");
break;
case CID_EXIT+CID_PRINTER_FAIL:
sprintf(sTempCn, "打印机恢复");
sprintf(sTempEn, "Printer Recovered");
break;
case CID_EXIT+CID_LINE_LOSS:
sprintf(sTempCn, "电话线连接");
sprintf(sTempEn, "Telephone Connected");
break;
case CID_EXIT+CID_BUS_LOSS:
sprintf(sTempCn, "扩展总线模块恢复");
sprintf(sTempEn, "XBUS Module Connectioned");
break;
case CID_EXIT+CID_DETECTOR_OPEN:
sprintf(sTempCn, "防区感应器被拆恢复");
sprintf(sTempEn, "Zone Sensor Recovered");
break;
case CID_EXIT+CID_GUARD:
sprintf(sTempCn, "布防");
sprintf(sTempEn, "Arming");
break;
case CID_EXIT+CID_GUARD_AUTO:
sprintf(sTempCn, "自动布防");
sprintf(sTempEn, "Auto Arming");
break;
case CID_EXIT+CID_GUARD_IMME:
sprintf(sTempCn, "即时布防");
sprintf(sTempEn, "Instant Arming");
break;
case CID_EXIT+CID_KEY_ZONE_GUARD:
sprintf(sTempCn, "钥匙防区布防");
sprintf(sTempEn, "Key Zone Arming");
break;
case CID_EXIT+CID_GUARD_STAY:
sprintf(sTempCn, "留守布防");
sprintf(sTempEn, "Stay Arming");
break;
case CID_EXIT+CID_FORCED_ARM:
sprintf(sTempCn, "强制布防");
sprintf(sTempEn, "Forced Arming");
break;
case CID_EXIT+CID_AUTOCTRL_TRIG:
sprintf(sTempCn, "定时关闭触发器");
sprintf(sTempEn, "Deactivate Trigger by Schedule");
break;
case CID_EXIT + CID_ONETOUCH_AWAY_ARMING:
sprintf(sTempCn, "一键外出布防");
sprintf(sTempEn, "One-touch away arming");
break;
case CID_EXIT + CID_ONETOUCH_STAY_ARMING:
sprintf(sTempCn, "一键留守布防");
sprintf(sTempEn, "One-touch stay arming");
break;
case CID_EXIT + CID_CARD_ARMING_OR_DISARMING:
sprintf(sTempCn, "刷卡布防");
sprintf(sTempEn, "Card arming");
break;
case CID_EXIT+CID_BYPASS:
sprintf(sTempCn, "旁路恢复");
sprintf(sTempEn, "Bypass Recovered");
break;
case CID_EXIT+CID_GROUP_BYPASS:
sprintf(sTempCn, "子系统组旁路恢复");
sprintf(sTempEn, "Partition Group Bypass Recovered");
break;
case CID_EXIT+CID_KEY_FAIL:
sprintf(sTempCn, "键盘恢复");
sprintf(sTempEn, "Keyboard Recovered");
break;
case CID_EXIT+CID_TRIGGER_FAIL:
sprintf(sTempCn, "键盘总线上触发器恢复");
sprintf(sTempEn, "KBUS Trigger Recovered");
break;
case CID_EXIT+CID_GPK_FAIL:
sprintf(sTempCn, "键盘总线上GP/K恢复");
sprintf(sTempEn, "KBUS GP/K Recovered");
break;
case CID_EXIT+CID_MODULE_FAIL:
sprintf(sTempCn, "键盘总线上MN/K恢复");
sprintf(sTempEn, "KBUS MN/K Recovered");
break;
case CID_EXIT + CID_WIRELESS_DETECTOR_FAIL:
sprintf(sTempCn, "无线探测器恢复");
sprintf(sTempEn, "Wireless Detector Recovered");
break;
case CID_EXIT + CID_WIRELESS_DETECTOR_BATTERY_LOW:
sprintf(sTempCn, "无线探测器电量恢复正常");
sprintf(sTempEn, "Wireless Detector battery Recovered");
break;
case CID_EXIT+CID_WRIE_LESS_NET:
sprintf(sTempCn, "无线网络正常");
sprintf(sTempEn, "Wireless Network Recovered");
break;
case CID_EXIT+CID_SIM_FAULT:
sprintf(sTempCn, "SIM卡正常");
sprintf(sTempEn, "SIM Card Recovered");
break;
case CID_EXIT + CID_WIFI_ABNORMAL:
sprintf(sTempCn, "WIFI通信恢复");
sprintf(sTempEn, "Wifi Recovered");
break;
case CID_EXIT + CID_RF_ABNORMAL:
sprintf(sTempCn, "RF信号恢复");
sprintf(sTempEn, "Rf signal Recovered");
break;
case CID_EXIT+CID_IPADDR_CONFLICT:
sprintf(sTempCn, "IP正常");
sprintf(sTempEn, "IP address is normal");
break;
case CID_EXIT+CID_ETHERNET_BROKEN:
sprintf(sTempCn, "网线正常");
sprintf(sTempEn, "Network is normal");
break;
case CID_EXIT+CID_MOTION_DECTECT:
sprintf(sTempCn, "移动侦测报警结束");
sprintf(sTempEn, "Motion Detection Alarm Stopped");
break;
case CID_EXIT+CID_MASK_ALARM:
sprintf(sTempCn, "遮挡报警结束");
sprintf(sTempEn, "Tampering Alarm Stopped");
break;
case CID_EXIT+CID_VI_LOST:
sprintf(sTempCn, "视频信号恢复");
sprintf(sTempEn, "Video Signal Recovered");
break;
case CID_EXIT+CID_VS_MISMATCH:
sprintf(sTempCn, "输入/输出视频制式恢复正常");
sprintf(sTempEn, "Input/output Format Recovered");
break;
case CID_EXIT+CID_VI_EXCEPTION:
sprintf(sTempCn, "视频输入恢复正常");
sprintf(sTempEn, "Video Input Recovered");
break;
case CID_EXIT+CID_HD_FULL:
sprintf(sTempCn, "硬盘空闲");
sprintf(sTempEn, "Hard disk is free");
break;
case CID_EXIT+CID_HD_ERROR:
sprintf(sTempCn, "硬盘恢复正常");
sprintf(sTempEn, "Hard Disk Recovered");
break;
case CID_EXIT + CID_KEY_LOCKED:
sprintf(sTempCn, "键盘解锁");
sprintf(sTempEn, "Keyboard locked");
break;
case CID_EXIT+CID_GUARD_SINGLE:
sprintf(sTempCn, "单防区布防");
sprintf(sTempEn, "Single-Zone Arming");
break;
case CID_EXIT + CID_ZONE_ASSOCIATED_DETECTOR:
sprintf(sTempCn, "防区删除探测器");
sprintf(sTempEn, "Zone delete associated detector");
break;
default:
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, "Unknown CID describe");
return;
}
sprintf(szLanCn, "%s, CID事件名:%s", szLanCn, sTempCn);
sprintf(szLanEn, "%s, CID describe:%s", szLanEn, sTempEn);
}
//中心账号
//if (strcmp((char*)struAlarm.sCenterAccount, ""))
{
memset(sTemp2, 0, sizeof(sTemp2));
memcpy(sTemp2, struAlarm.sCenterAccount, ACCOUNTNUM_LEN);
if (0 == struAlarm.byCenterType || 1 == struAlarm.byCenterType)
{
memcpy(sTemp2, struAlarm.sCenterAccount, ACCOUNTNUM_LEN);
}
else if (2 == struAlarm.byCenterType)
{
memcpy(sTemp2, struAlarm.sCenterAccountV40, ACCOUNTNUM_LEN_V40);
}
sprintf(szLanCn, "%s, 中心账号:%s", szLanCn, sTemp2);
sprintf(szLanEn, "%s, Center account:%s", szLanEn, sTemp2);
}
//用户名
if (0xff != struAlarm.byUserType)
{
if (0 == struAlarm.byUserType)//网络用户
{
memset(sTemp2, 0, sizeof(sTemp2));
memcpy(sTemp2, struAlarm.sUserName, NAME_LEN);
sprintf(szLanCn, "%s,网络用户名:%s", szLanCn, struAlarm.sUserName);
sprintf(szLanEn, "%s,Net User Name:%s", szLanEn, struAlarm.sUserName);
}
else if(1 == struAlarm.byUserType)//键盘用户
{
sprintf(szLanCn, "%s, 键盘用户号:%d", szLanCn, struAlarm.wKeyUserNo);
sprintf(szLanEn, "%s, Keypad UserID:%d", szLanEn, struAlarm.wKeyUserNo);
}
else if(2 == struAlarm.byUserType)//手机用户
{
memset(sTemp2, 0, sizeof(sTemp2));
memcpy(sTemp2, struAlarm.sUserName, NAME_LEN);
sprintf(szLanCn, "%s,手机号:%s", szLanCn, struAlarm.sUserName);
sprintf(szLanEn, "%s,Cellphone No:%s", szLanEn, struAlarm.sUserName);
}
else if(3 == struAlarm.byUserType)//系统用户
{
memset(sTemp2, 0, sizeof(sTemp2));
memcpy(sTemp2, struAlarm.sUserName, NAME_LEN);
sprintf(szLanCn, "%s,系统用户名:%s", szLanCn, struAlarm.sUserName);
sprintf(szLanEn, "%s,System User Name:%s", szLanEn, struAlarm.sUserName);
}
else
{
sprintf(szLanCn, "%s, 未知用户类型", szLanCn);
sprintf(szLanEn, "%s, Unknown User Type", szLanEn);
}
}
//键盘号
if (0xff != struAlarm.byKeypadNo)
{
sprintf(szLanCn, "%s, 键盘号:%d", szLanCn, struAlarm.byKeypadNo);
sprintf(szLanEn, "%s, KeyPad No:%d", szLanEn, struAlarm.byKeypadNo);
}
//子系统号
if (0xff != struAlarm.bySubSysNo)
{
sprintf(szLanCn, "%s, 子系统号:%d", szLanCn, struAlarm.bySubSysNo);
sprintf(szLanEn, "%s, Subsystem No:%d", szLanEn, struAlarm.bySubSysNo);
}
//防区号
if (0xffff != struAlarm.wDefenceNo)
{
sprintf(szLanCn, "%s, 防区号:%d", szLanCn, struAlarm.wDefenceNo+1);
sprintf(szLanEn, "%s, Zone No:%d", szLanEn, struAlarm.wDefenceNo+1);
}
//视频通道号
if (0xff != struAlarm.byVideoChanNo)
{
sprintf(szLanCn, "%s, 视频通道号:%d", szLanCn, struAlarm.byVideoChanNo);
sprintf(szLanEn, "%s, Viedo Chan No:%d", szLanEn, struAlarm.byVideoChanNo);
}
//外接的一个视频通道号
if (0 != struAlarm.byRelativeChannel)
{
sprintf(szLanCn, "%s,关联通道号1:%d", szLanCn, struAlarm.byRelativeChannel);
sprintf(szLanEn, "%s,Relative Chanel1 No:%d", szLanEn, struAlarm.byRelativeChannel);
}
//硬盘号
if (0xff != struAlarm.byDiskNo)
{
sprintf(szLanCn, "%s, 硬盘号:%d", szLanCn, struAlarm.byDiskNo);
sprintf(szLanEn, "%s, HD No:%d", szLanEn, struAlarm.byDiskNo);
}
//模块地址号
if (0xffff != struAlarm.wModuleAddr)
{
sprintf(szLanCn, "%s, 模块地址:%d", szLanCn, struAlarm.wModuleAddr);
sprintf(szLanEn, "%s, Module Address:%d", szLanEn, struAlarm.wModuleAddr);
}
//中继器号
if (0 != struAlarm.byRepeaterNo)
{
sprintf(szLanCn, "%s, 中继器号:%d", szLanCn, struAlarm.byRepeaterNo);
sprintf(szLanEn, "%s, Repeater No:%d", szLanEn, struAlarm.byRepeaterNo);
}
//遥控器用户号
if (0 != struAlarm.wRemoteCtrllerUserNo)
{
sprintf(szLanCn, "%s, 遥控器用户号:%d", szLanCn, struAlarm.wRemoteCtrllerUserNo);
sprintf(szLanEn, "%s, RemoteCtrller User No:%d", szLanEn, struAlarm.wRemoteCtrllerUserNo);
}
//IOT通道号
if (0 != struAlarm.dwIOTChannelNo)
{
sprintf(szLanCn, "%s, IOT通道号:%d", szLanCn, struAlarm.dwIOTChannelNo);
sprintf(szLanEn, "%s, IOT Chan No:%d", szLanEn, struAlarm.dwIOTChannelNo);
}
if (memcmp((char*)struAlarm.byDevSerialNo, "", DEV_SERIAL_LEN) != 0)
{
memset(sTemp2, 0, sizeof(sTemp2));
memcpy(sTemp2, struAlarm.byDevSerialNo, DEV_SERIAL_LEN);
sprintf(szLanCn, "%s, 序列号:%s", szLanCn, sTemp2);
sprintf(szLanEn, "%s, serial:%s", szLanEn, sTemp2);
}
//sprintf(szLanCn, "标准CID号%d", struAlarm.standardCIDcode);
//sprintf(szLanEn, "standardCIDcode:%d", struAlarm.standardCIDcode);
g_StringLanType(szLan, szLanCn, szLanEn);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
memset(szLanCn, 0, sizeof(szLanCn));
memset(szLanEn, 0, sizeof(szLanEn));
memset(szLan, 0, sizeof(szLan));
sprintf(szLanCn, "触发报警时间:%04d-%02d-%02d %02d:%02d:%02d, 上传报警时间:%04d-%02d-%02d %02d:%02d:%02d", struAlarm.struTriggerTime.wYear, struAlarm.struTriggerTime.byMonth, struAlarm.struTriggerTime.byDay, struAlarm.struTriggerTime.byHour, \
struAlarm.struTriggerTime.byMinute, struAlarm.struTriggerTime.bySecond, struAlarm.struUploadTime.wYear, struAlarm.struUploadTime.byMonth, struAlarm.struUploadTime.byDay, struAlarm.struUploadTime.byHour\
, struAlarm.struUploadTime.byMinute, struAlarm.struUploadTime.bySecond);
sprintf(szLanEn, "Trigger Time:%d-%d-%d %d:%d:%d, Upload Time:%d-%d-%d %d:%d:%d", struAlarm.struTriggerTime.wYear, struAlarm.struTriggerTime.byMonth, struAlarm.struTriggerTime.byDay, struAlarm.struTriggerTime.byHour, \
struAlarm.struTriggerTime.byMinute, struAlarm.struTriggerTime.bySecond, struAlarm.struUploadTime.wYear, struAlarm.struUploadTime.byMonth, struAlarm.struUploadTime.byDay, struAlarm.struUploadTime.byHour\
, struAlarm.struUploadTime.byMinute, struAlarm.struUploadTime.bySecond);
g_StringLanType(szLan, szLanCn, szLanEn);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
memset(szLanCn, 0, sizeof(szLanCn));
memset(szLanEn, 0, sizeof(szLanEn));
memset(szLan, 0, sizeof(szLan));
sprintf(szLanCn, "标准CID号%d", struAlarm.standardCIDcode);
sprintf(szLanEn, "standardCIDcode:%d", struAlarm.standardCIDcode);
g_StringLanType(szLan, szLanCn, szLanEn);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
}
void CClientDemoDlg::ProcessAlarmhostUPSAlarm(char* szLanCn, char* szLanEn, LPNET_DVR_ALARMHOST_UPS_ALARMINFO lpAlarm)
{
//默认除以10
DWORD dwDivisionCoefficient = 10;
switch (lpAlarm->byAlarmType)
{
case 1:
sprintf(szLanCn, "%s", "A相输入电压越限");
break;
case 2:
sprintf(szLanCn, "%s", "B相输入电压越限");
break;
case 3:
sprintf(szLanCn, "%s", "C相输入电压越限");
break;
case 4:
sprintf(szLanCn, "%s", "A相输出电压越限5");
break;
case 5:
sprintf(szLanCn, "%s", "B相输出电压越限");
break;
case 6:
sprintf(szLanCn, "%s", "C相输出电压越限");
break;
case 7:
sprintf(szLanCn, "%s", "A相输入频率越限");
break;
case 8:
sprintf(szLanCn, "%s", "B相输入频率越限");
break;
case 9:
sprintf(szLanCn, "%s", "C相输入频率越限");
break;
case 10:
sprintf(szLanCn, "%s", "整流器电压越限报警");
break;
case 11:
sprintf(szLanCn, "%s", "过载报警");
break;
case 12:
sprintf(szLanCn, "%s", "电池电压低报警");
break;
case 13:
sprintf(szLanCn, "%s", "电池后备时间超低报警");
dwDivisionCoefficient = 1;
break;
case 14:
sprintf(szLanCn, "%s", "电池温度超高报警");
break;
case 15:
sprintf(szLanCn, "%s", "逆变器关闭报警");
break;
case 16:
sprintf(szLanCn, "%s", "自动旁路开报警");
break;
case 17:
sprintf(szLanCn, "%s", "整流器故障报警");
break;
case 18:
sprintf(szLanCn, "%s", "逆变器故障报警");
break;
case 19:
sprintf(szLanCn, "%s", "充电器故障报警");
break;
case 20:
sprintf(szLanCn, "%s", "电池故障报警");
break;
case 21:
sprintf(szLanCn, "%s", "自动旁路故障报警");
break;
default:
sprintf(szLanCn, "%s", "未知报警类型");
break;
}
if (0xffffffff == lpAlarm->iAlarmValue)
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo);
}
else
{
if (1 == dwDivisionCoefficient)
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d, 报警值:%d", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo, lpAlarm->iAlarmValue);
}
else
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d, 报警值:%0.1f", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo, (float)lpAlarm->iAlarmValue/dwDivisionCoefficient);
}
}
}
void CClientDemoDlg::ProcessAlarmhostSwitchPowerAlarm(char* szLanCn, char* szLanEn, LPNET_DVR_ALARMHOST_SWITCH_POWER_SUPPLY_ALARMINFO lpAlarm)
{
//默认除以10
DWORD dwDivisionCoefficient = 10;
/*报警类型:1-电池测试失败 2-AC-DC转换器故障,3-输入线/相电压AB/A越限,4-输入线/相电压BC/B越限,5-输入线/相电压CA/C越限,
6-输出电流A越限,7-输出电流B越限,8-输出电流C越限,9整流模块故障,10-风扇故障,11-直流电压越限*/
switch (lpAlarm->byAlarmType)
{
case 1:
sprintf(szLanCn, "%s", "电池测试失败");
break;
case 2:
sprintf(szLanCn, "%s", "AC-DC转换器故障");
break;
case 3:
sprintf(szLanCn, "%s", "输入线/相电压AB/A越限");
break;
case 4:
sprintf(szLanCn, "%s", "输入线/相电压BC/B越限");
break;
case 5:
sprintf(szLanCn, "%s", "输入线/相电压CA/C越限");
break;
case 6:
sprintf(szLanCn, "%s", "A相输出电流越限");
break;
case 7:
sprintf(szLanCn, "%s", "B相输出电流越限");
break;
case 8:
sprintf(szLanCn, "%s", "C相输出电流越限");
break;
case 9:
sprintf(szLanCn, "%s", "整流模块故障");
break;
case 10:
sprintf(szLanCn, "%s", "风扇故障");
break;
case 11:
sprintf(szLanCn, "%s", "直流电压越限");
break;
default:
sprintf(szLanCn, "%s", "未知报警类型");
break;
}
if (0xffffffff == lpAlarm->iAlarmValue)
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo);
}
else
{
if (1 == dwDivisionCoefficient)
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d, 报警值:%d", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo, lpAlarm->iAlarmValue);
}
else
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d, 报警值:%0.1f", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo, (float)lpAlarm->iAlarmValue/dwDivisionCoefficient);
}
}
}
void CClientDemoDlg::ProcessAlarmhostGasDetectAlarm(char* szLanCn, char* szLanEn, LPNET_DVR_ALARMHOST_GAS_DETECT_SYS_ALARMINFO lpAlarm)
{
//默认除以10
DWORD dwDivisionCoefficient = 10;
/*报警类型:1- SF6气体含量异常,2-氧气含量异常,3-温度值异常,4-湿度值异常,5-流量*/
switch (lpAlarm->byAlarmType)
{
case 1:
sprintf(szLanCn, "%s", "SF6气体含量异常");
dwDivisionCoefficient = 1;
break;
case 2:
sprintf(szLanCn, "%s", "氧气含量异常");
break;
case 3:
sprintf(szLanCn, "%s", "温度值异常");
break;
case 4:
sprintf(szLanCn, "%s", "湿度值异常");
break;
case 5:
sprintf(szLanCn, "%s", "流量");
dwDivisionCoefficient = 1;
break;
default:
sprintf(szLanCn, "%s", "未知报警类型");
break;
}
if (0xffffffff == lpAlarm->iAlarmValue)
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo);
}
else
{
if (1 == dwDivisionCoefficient)
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d, 报警值:%d", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo, lpAlarm->iAlarmValue);
}
else
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d, 报警值:%0.1f", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo, (float)lpAlarm->iAlarmValue/dwDivisionCoefficient);
}
}
}
void CClientDemoDlg::ProcessAlarmhostTempHumiSensorAlarm(char* szLanCn, char* szLanEn, LPNET_DVR_ALARMHOST_TEMP_HUMIDITY_SENSOR_ALARMINFO lpAlarm)
{
//默认除以10
DWORD dwDivisionCoefficient = 10;
//1-温度异常,2-湿度异常
switch (lpAlarm->byAlarmType)
{
case 1:
sprintf(szLanCn, "%s", "温度异常");
break;
case 2:
sprintf(szLanCn, "%s", "湿度异常");
break;
default:
sprintf(szLanCn, "%s", "未知报警类型");
break;
}
if (0xffffffff == lpAlarm->iAlarmValue)
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo);
}
else
{
if (1 == dwDivisionCoefficient)
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d, 报警值:%d", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo, lpAlarm->iAlarmValue);
}
else
{
sprintf(szLanCn, "%s, 485通道:%d, 槽位号:%d, 报警值:%0.1f", szLanCn, lpAlarm->byChanNo, lpAlarm->bySlotNo, (float)lpAlarm->iAlarmValue/dwDivisionCoefficient);
}
}
}
void CClientDemoDlg::ProcAlarmHostExternalDevAlarm(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_485_EXTERNAL_DEVICE_ALARMINFO struAlarm = {0};
memcpy(&struAlarm, pAlarmInfo, sizeof(struAlarm));
char szLan[1024] = {0};
char szLanCn[1024] = {0};
char szLanEn[1024] = {0};
switch (struAlarm.byAlarmType)
{
case 1:
ProcessAlarmhostUPSAlarm(szLanCn, szLanEn, &struAlarm.struAlarmInfo.struUPSAlarm);
break;
case 2:
ProcessAlarmhostSwitchPowerAlarm(szLanCn, szLanEn, &struAlarm.struAlarmInfo.struSwitchPowerAlarm);
break;
case 3:
ProcessAlarmhostGasDetectAlarm(szLanCn, szLanEn, &struAlarm.struAlarmInfo.struGasDetectSystemAlarm);
break;
case 4:
ProcessAlarmhostTempHumiSensorAlarm(szLanCn, szLanEn, &struAlarm.struAlarmInfo.struTempHumiditySensorAlarm);
break;
default:
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, "Unknown Alarm");
return;
}
g_StringLanType(szLan, szLanCn, szLanEn);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
}
void CClientDemoDlg::ProcessAlarmhostPointValue(char* szLanCn, char* szLanEn, LPNET_DVR_ALARMHOST_POINT_VALUE lpAlarm)
{
//默认除以10
DWORD dwDivisionCoefficient = 1;
if (1 == lpAlarm->byPointType)
{
dwDivisionCoefficient = 1000;
}
//1-本地模拟量通道,2-本地开关量通道,3-485通道,4-网络通道
switch (lpAlarm->byChanType)
{
case 1:
sprintf(szLanCn, "本地模拟量通道%u,变量号:%u,点号%u 报警值:%0.3f", lpAlarm->dwChanNo, lpAlarm->dwVariableNo, lpAlarm->dwPointNo, (float)((float)(lpAlarm->iValue)/dwDivisionCoefficient));
break;
case 2:
sprintf(szLanCn, "本地开关量通道%u,变量号:%u,点号%u 报警值:%d", lpAlarm->dwChanNo, lpAlarm->dwVariableNo, lpAlarm->dwPointNo, lpAlarm->iValue);
break;
case 3:
sprintf(szLanCn, "485通道%u槽位%u,变量号:%u,点号%u 报警值:%0.3f", lpAlarm->dwChanNo, lpAlarm->dwSubChanNo, lpAlarm->dwVariableNo, lpAlarm->dwPointNo, (float)((float)(lpAlarm->iValue)/dwDivisionCoefficient));
break;
case 4:
sprintf(szLanCn, "网络通道%u,变量号:%u,点号%u 报警值:%0.3f", lpAlarm->dwChanNo, lpAlarm->dwVariableNo, lpAlarm->dwPointNo, (float)((float)(lpAlarm->iValue)/dwDivisionCoefficient));
break;
default:
sprintf(szLanCn, "%s", "未知通道类型");
break;
}
}
void CClientDemoDlg::ProcAlarmHostData(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_ALARMHOST_DATA_UPLOAD struAlarm = {0};
memcpy(&struAlarm, pAlarmInfo, sizeof(struAlarm));
char szLan[1024] = {0};
char szLanCn[1024] = {0};
char szLanEn[1024] = {0};
switch (struAlarm.byDataType)
{
case 1: //监测点数据上传
ProcessAlarmhostPointValue(szLanCn, szLanEn, &struAlarm.struAlarmData.struPointValue);
break;
default:
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, "Unknown Alarm");
return;
}
g_StringLanType(szLan, szLanCn, szLanEn);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
}
void CClientDemoDlg::ProcGateAlarmHostData(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_GATE_ALARMINFO struAlarm = {0};
memcpy(&struAlarm, pAlarmInfo, sizeof(struAlarm));
sprintf(szInfoBuf, "AlarmType:[%d] DevType[%d] DevStatus[%d] AlarmTime[%d:%d:%d %d:%d:%d]\n",\
struAlarm.byAlarmType, struAlarm.byExternalDevType, struAlarm.byExternalDevStatus, struAlarm.struAlarmTime.wYear, struAlarm.struAlarmTime.byMonth, struAlarm.struAlarmTime.byDay, \
struAlarm.struAlarmTime.byHour, struAlarm.struAlarmTime.byMinute, struAlarm.struAlarmTime.bySecond);
if (struAlarm.byAlarmType == 0x01)
{
sprintf(szInfoBuf, "%s License[%s] VehicleType[%d]", szInfoBuf, struAlarm.uAlarmInfo.struVehicleInfo.sLicense, \
struAlarm.uAlarmInfo.struVehicleInfo.byVehicleType);
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcAlarmHostWirelessInfo(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_ALARMWIRELESSINFO struAlarm = { 0 };
memcpy(&struAlarm, pAlarmInfo, sizeof(struAlarm));
sprintf(szInfoBuf, "deveciID[%s] dataTraffic[%f] signalIntensity[%d]\n", struAlarm.byDeviceID, struAlarm.fDataTraffic, struAlarm.bySignalIntensity);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcExternalControlAlarmHostData(WPARAM wParam, LPARAM lParam)//布防报警(外控报警)2013-06-09
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_EXTERNAL_CONTROL_ALARM struAlarm = {0};
memcpy(&struAlarm, pAlarmInfo, sizeof(struAlarm));
sprintf(szInfoBuf,"ChannelNo:[%d] Flicker:[%d] IONo:[%d] ParkingIndex:[%d] ExternalBeginTime:[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] \n",
struAlarm.dwChannelNo, struAlarm.struLampStateCtrl.byFlicker, struAlarm.struLampStateCtrl.dwIONo, struAlarm.struLampStateCtrl.byParkingIndex
,struAlarm.struExternalBeginTime.dwYear, struAlarm.struExternalBeginTime.dwMonth, struAlarm.struExternalBeginTime.dwDay,
struAlarm.struExternalBeginTime.dwHour, struAlarm.struExternalBeginTime.dwMinute,struAlarm.struExternalBeginTime.dwSecond);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcSceneChangeDetection(WPARAM wParam, LPARAM lParam)//2013-07-17场景变更侦测报警
{
char szInfoBuf[1024] = {0};
char szLan[128] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_SCENECHANGE_DETECTION_RESULT struSceneChange = {0};
memcpy(&struSceneChange, pAlarmInfo, sizeof(struSceneChange));
g_StringLanType(szLan, "场景变更侦测报警","Scene Change Detection");
sprintf(szInfoBuf, "%s: (Device IP:[%s] Port:[%d] Device Channel:[%d] Ivms Channel:[%d]IvmsChannelEx[%d])\n", szLan,
struSceneChange.struDevInfo.struDevIP.sIpV4, struSceneChange.struDevInfo.wPort,
struSceneChange.struDevInfo.byChannel, struSceneChange.struDevInfo.byIvmsChannel, struSceneChange.wDevInfoIvmsChannelEx);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcHotSpare(WPARAM wParam, LPARAM lParam)//2013-07-17热备异常报警
{
char szInfoBuf[1024] = {0};
char szLan[128] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_ALARM_HOT_SPARE struAlarmHotSpare = {0};
memcpy(&struAlarmHotSpare, pAlarmInfo, sizeof(struAlarmHotSpare));
g_StringLanType(szLan, "热备异常报警","Scene Change Detection");
switch (struAlarmHotSpare.dwExceptionCase)
{
case 0:
sprintf(szInfoBuf, "%s: (网络异常 Device IP:[%s])\n", szLan,
struAlarmHotSpare.struDeviceIP.sIpV4);
}
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcVehCostItem(WPARAM wParam, LPARAM lParam)//2013-11-19 出入口过车收费明细
{
char szInfoBuf1[1024] = {0};
char szInfoBuf2[1024] = {0};
char szInfoBuf3[1024] = {0};
char szInfoBuf4[1024] = {0};
char szLan[128] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_ITS_PASSVEHICLE_COST_ITEM struVehCostItem = {0};
memset(&struVehCostItem, 0, sizeof(NET_ITS_PASSVEHICLE_COST_ITEM));
memcpy(&struVehCostItem, pAlarmInfo, sizeof(NET_ITS_PASSVEHICLE_COST_ITEM));
g_StringLanType(szLan, "出入口过车收费明细","Vehicle Cost Item");
sprintf(szInfoBuf4,"%s End: \n", szLan);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf4);
sprintf(szInfoBuf3, "Operator Name:[%s]; Vehicle Type:[%d]; Pay Rule ID:[%d]; Free Rule ID:[%d]\n",struVehCostItem.byOperatorName,\
struVehCostItem.byVehicleType, struVehCostItem.dwPayRuleID, struVehCostItem.dwFreeRuleID);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf3);
sprintf(szInfoBuf2, "Vehicle ID:[%d]; In Time:[%s]; Out Time:[%s]; Card No:[%s]; Plate No:[%s]; Pay Cost:[%0.2f]\n", struVehCostItem.dwPassVehicleID,\
struVehCostItem.byIntime, struVehCostItem.byOuttime, struVehCostItem.byCardNo, struVehCostItem.byPlateInfo, struVehCostItem.fPayCost);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf2);
sprintf(szInfoBuf1,"%s Begin: \n", szLan);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf1);
}
void CClientDemoDlg::ProcVehHandOver(WPARAM wParam, LPARAM lParam)//2013-11-19 出入口交接班数据
{
char szInfoBuf[1024] = {0};
char szLan[128] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_ITS_HANDOVER_INFO struHandOverInfo = {0};
memset(&struHandOverInfo, 0, sizeof(NET_ITS_HANDOVER_INFO));
memcpy(&struHandOverInfo, pAlarmInfo, sizeof(NET_ITS_HANDOVER_INFO));
g_StringLanType(szLan, "出入口交接班数据","Vehicle Handover Info");
sprintf(szInfoBuf, "%s(Operator Name:[%s]; Operator Card:[%s]; Start Time:[%s]; End Time:[%s]; Total Pay:[%0.2f]; Total Records:[%d])\n", szLan,\
struHandOverInfo.byOperatorName, struHandOverInfo.byOperatorCard, struHandOverInfo.byStartTime, struHandOverInfo.byEndTime,\
struHandOverInfo.fTotal_Pay, struHandOverInfo.dwTotal_Records);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcDefocus(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
char szAlarmType[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_DEFOCUS_ALARM struDefocus = { 0 };
memset(&struDefocus, 0, sizeof(NET_DVR_DEFOCUS_ALARM));
memcpy(&struDefocus, pAlarmInfo, sizeof(NET_DVR_DEFOCUS_ALARM));
NET_DVR_TIME struAbsTime = { 0 };
struAbsTime.dwYear = GET_YEAR(struDefocus.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struDefocus.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struDefocus.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struDefocus.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struDefocus.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struDefocus.dwAbsTime);
g_StringLanType(szLan, "虚焦报警", "Audio Exception");
sprintf(szInfoBuf, "flag[%d] Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d %2.2d%2.2d]%s: IvmsChannel:%d]IvmsChannelEx[%d]\n", \
struDefocus.byTimeDiffFlag, struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, \
struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond, struDefocus.cTimeDifferenceH, struDefocus.cTimeDifferenceM, \
szLan, struDefocus.struDevInfo.byIvmsChannel, struDefocus.wDevInfoIvmsChannelEx);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcAudioException(WPARAM wParam, LPARAM lParam)//声音异常报警上传 2014-03-21
{
char szInfoBuf[1024] = {0};
char szLan[128] = {0};
char szAlarmType[128] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_AUDIOEXCEPTION_ALARM struAudioException = {0};
memset(&struAudioException, 0, sizeof(NET_DVR_AUDIOEXCEPTION_ALARM));
memcpy(&struAudioException, pAlarmInfo, sizeof(NET_DVR_AUDIOEXCEPTION_ALARM));
switch (struAudioException.byAlarmType)
{
case 1:
g_StringLanType(szAlarmType, "音频输入异常","Audio Input Exception");
break;
case 2:
g_StringLanType(szAlarmType, "音频输入突变","Audio Input Mutation");
break;
case 3:
g_StringLanType(szAlarmType, "声强陡降","Audio Decibel Dropped");
break;
case 4:
g_StringLanType(szAlarmType, "音频丢失","Audio Loss");
break;
default:
g_StringLanType(szAlarmType, "未知","Unknow");
break;
}
g_StringLanType(szLan, "声音异常报警","Audio Exception");
sprintf(szInfoBuf, "%s:[AlarmType:%s AudioDecibel:%d IP:%s Port:%d Channel:%d IvmsChannel:%d]IvmsChannelEx[%d]\n", szLan,\
szAlarmType, struAudioException.wAudioDecibel, struAudioException.struDevInfo.struDevIP.sIpV4, struAudioException.struDevInfo.wPort, \
struAudioException.struDevInfo.byChannel, struAudioException.struDevInfo.byIvmsChannel, struAudioException.wDevInfoIvmsChannelEx);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcHeatMapResult(WPARAM wParam, LPARAM lParam)//热度图报警上传 2014-03-21
{
char szInfoBuf[1024] = {0};
char szLan[128] = {0};
char szAlarmType[128] = {0};
char cFilename[256] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
int iPort = pAlarmDev->wLinkPort;
NET_DVR_HEATMAP_RESULT struHeatMapResult = {0};
memset(&struHeatMapResult, 0, sizeof(NET_DVR_HEATMAP_RESULT));
memcpy(&struHeatMapResult, pAlarmInfo, sizeof(NET_DVR_HEATMAP_RESULT));
sprintf(cFilename, "No heat map");
if (struHeatMapResult.wArrayColumn > 0 && struHeatMapResult.wArrayLine > 0 && struHeatMapResult.pBuffer != NULL)
{
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName,iPort);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\HeatMapValue[%s].txt", cFilename, chTime);
HANDLE hFile;
DWORD dwReturn = 0;
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struHeatMapResult.pBuffer, struHeatMapResult.wArrayColumn*struHeatMapResult.wArrayLine*struHeatMapResult.byArrayUnitType, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
g_StringLanType(szLan, "热度图报警","Heat Map Result");
sprintf(szInfoBuf, "%s:[IP:%s Port:%d Channel:%d IvmsChannel:%d StartTime%d-%d-%d %d:%d:%d flag[%d] %2.2d%2.2d] EndTime:%d-%d-%d %d:%d:%d %2.2d%2.2d] ArrayLine:%d ArrayColumn:%d HeatMapPath:%s \
MaxHeatMapValue:%d MinHeatMapValue:%d TimeHeatMapValue:%d DetSceneID:%d BrokenNetHttp:%d]IvmsChannel[%d]IvmsChannelEx[%d] ArrayUnitType[d%]\n", \
szLan, struHeatMapResult.struDevInfo.struDevIP.sIpV4, struHeatMapResult.struDevInfo.wPort, struHeatMapResult.struDevInfo.byChannel,\
struHeatMapResult.struDevInfo.byIvmsChannel, struHeatMapResult.struStartTime.wYear, struHeatMapResult.struStartTime.byMonth,\
struHeatMapResult.struStartTime.byDay, struHeatMapResult.struStartTime.byHour, struHeatMapResult.struStartTime.byMinute,\
struHeatMapResult.struStartTime.bySecond, struHeatMapResult.byTimeDiffFlag, struHeatMapResult.cStartTimeDifferenceH, struHeatMapResult.cStartTimeDifferenceM,
struHeatMapResult.struEndTime.wYear, struHeatMapResult.struEndTime.byMonth, struHeatMapResult.struEndTime.byDay, \
struHeatMapResult.struEndTime.byHour, struHeatMapResult.struEndTime.byMinute, struHeatMapResult.struEndTime.bySecond, \
struHeatMapResult.cStopTimeDifferenceH, struHeatMapResult.cStopTimeDifferenceM,\
struHeatMapResult.wArrayLine,\
struHeatMapResult.wArrayColumn, cFilename, struHeatMapResult.dwMaxHeatMapValue, struHeatMapResult.dwMinHeatMapValue, struHeatMapResult.dwTimeHeatMapValue,\
struHeatMapResult.byDetSceneID, struHeatMapResult.byBrokenNetHttp, struHeatMapResult.struDevInfo.byIvmsChannel, struHeatMapResult.wDevInfoIvmsChannelEx, struHeatMapResult.byArrayUnitType);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProVCAAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
LPNET_DVR_DEC_VCA_ALARM pStruVcaAlarm = (LPNET_DVR_DEC_VCA_ALARM)pAlarmInfo;
sprintf(szInfoBuf, "COMM_ALARM_DEC_VCA dwDisplayNo[%d] bySubWinNo[%d] dwAlarmPicSize[%d]",\
pStruVcaAlarm->dwDisplayNo, pStruVcaAlarm->bySubWinNo, pStruVcaAlarm->dwAlarmPicSize);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProLCDAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
//char *szAlarmType[] = {"温度异常", "风扇异常", "屏幕离线" };
LPNET_DVR_LCD_ALARM pStruLCDAlarm = (LPNET_DVR_LCD_ALARM)pAlarmInfo;
//DWORD dwIndex = (pStruLCDAlarm->byAlarmType-1)%3;
// sprintf(szInfoBuf, "COMM_ALARM_LCD dwScreenID[%d], byOnOffLine[%d], byTempState[%d],byFanState[%d],byTemperature[%d] ",
// pStruLCDAlarm->dwScreenID, pStruLCDAlarm->byOnOffLine,pStruLCDAlarm->byTempState, pStruLCDAlarm->byFanState, pStruLCDAlarm->byTemperature );
sprintf(szInfoBuf, "COMM_ALARM_LCD dwScreenID[%d]", pStruLCDAlarm->dwScreenID);
if (! pStruLCDAlarm->byOnOffLine) //离线
{
sprintf(szInfoBuf+strlen(szInfoBuf), ", 屏幕离线");
}
else
{
sprintf(szInfoBuf+strlen(szInfoBuf), ", 屏幕在线");
sprintf(szInfoBuf+strlen(szInfoBuf), ", 板卡温度%s", (pStruLCDAlarm->byTempState==0)?"正常":"异常");
sprintf(szInfoBuf+strlen(szInfoBuf), ", 风扇%s", (pStruLCDAlarm->byFanState==0)?"关":"开");
sprintf(szInfoBuf+strlen(szInfoBuf), ", 板卡温度[%d]", pStruLCDAlarm->byTemperature);
switch(pStruLCDAlarm->byFanException)
{
case 0:
sprintf(szInfoBuf+strlen(szInfoBuf), ", 风扇异常状态: 不支持");
break;
case 1:
sprintf(szInfoBuf+strlen(szInfoBuf), ", 风扇异常状态: 正常");
break;
case 2:
sprintf(szInfoBuf+strlen(szInfoBuf), ", 风扇异常状态: 异常");
break;
default:
;
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
//门禁主机报警 2014-07-23
void CClientDemoDlg::ProcAccessCardAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
char szLan[128] = {0};
char szAlarmType[128] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_ACS_ALARM_INFO struAcsAlarmInfo = {0};
memset(&struAcsAlarmInfo, 0, sizeof(struAcsAlarmInfo));
memcpy(&struAcsAlarmInfo,pAlarmInfo, sizeof(struAcsAlarmInfo) );
NET_DVR_LOG_V50 struFileInfo = {0};
struFileInfo.dwMajorType = struAcsAlarmInfo.dwMajor;
struFileInfo.dwMinorType = struAcsAlarmInfo.dwMinor;
CString csTmp;
if (MAJOR_ALARM == struFileInfo.dwMajorType )
{
AlarmMinorTypeMap(struFileInfo, csTmp);
}
else if(MAJOR_OPERATION == struFileInfo.dwMajorType)
{
OperationMinorTypeMap(struFileInfo, csTmp);
}
else if(MAJOR_EXCEPTION == struFileInfo.dwMajorType)
{
ExceptionMinorTypeMap(struFileInfo, csTmp);
}
else if(MAJOR_EVENT == struFileInfo.dwMajorType)
{
EventMinorTypeMap(struFileInfo, csTmp);
}
sprintf(szInfoBuf, "[%s] ", (LPCSTR)csTmp);
// strcpy(szInfoBuf, szLan);
char szNetUser[sizeof(struAcsAlarmInfo.sNetUser)+1] = {0};
memcpy(szNetUser, struAcsAlarmInfo.sNetUser, sizeof(struAcsAlarmInfo.sNetUser));
//时间
sprintf( szInfoBuf + strlen(szInfoBuf), " %4d-%2d-%d %2d:%2d:%2d [%s](%s) TimeType:%d", struAcsAlarmInfo.struTime.dwYear, struAcsAlarmInfo.struTime.dwMonth ,\
struAcsAlarmInfo.struTime.dwDay, struAcsAlarmInfo.struTime.dwHour, struAcsAlarmInfo.struTime.dwMinute, struAcsAlarmInfo.struTime.dwSecond, \
struAcsAlarmInfo.struRemoteHostAddr.sIpV4, szNetUser, struAcsAlarmInfo.byTimeType);
if (struAcsAlarmInfo.struAcsEventInfo.byCardNo[0] != 0 )
{
sprintf(szInfoBuf + strlen(szInfoBuf), " CardNo:%s", (char *)struAcsAlarmInfo.struAcsEventInfo.byCardNo);
}
#ifdef DEMO_LAN_CN
const char *szCardType[] = { "未知卡", "普通卡", "残疾人卡", "黑名单卡", "巡更卡", "胁迫卡", "超级卡", "来宾卡", "解除卡" };
#else
const char *szCardType[] = { "unknow", "normalcard", "disabledcard", "blacklistcard", "nightwatchcard", "stresscard", "supercard", "guestcard" , "releasecard" };
#endif
BYTE byCardType = struAcsAlarmInfo.struAcsEventInfo.byCardType;
if (byCardType > 0 && byCardType <= sizeof(szCardType) / sizeof(szCardType[0]))
{
sprintf(szInfoBuf + strlen(szInfoBuf), " CardType:%s", szCardType[byCardType]);
}
if (struAcsAlarmInfo.struAcsEventInfo.dwCardReaderNo != 0 )
{
sprintf(szInfoBuf + strlen(szInfoBuf), " CardReaderNo:%d", struAcsAlarmInfo.struAcsEventInfo.dwCardReaderNo);
}
if (struAcsAlarmInfo.struAcsEventInfo.dwDoorNo != 0 )
{
sprintf(szInfoBuf + strlen(szInfoBuf), " DoorNo:%d", struAcsAlarmInfo.struAcsEventInfo.dwDoorNo);
}
if (struAcsAlarmInfo.struAcsEventInfo.dwVerifyNo != 0 )
{
sprintf(szInfoBuf + strlen(szInfoBuf), " VerifyNo:%d", struAcsAlarmInfo.struAcsEventInfo.dwVerifyNo);
}
if (struAcsAlarmInfo.struAcsEventInfo.dwAlarmInNo != 0 )
{
sprintf(szInfoBuf + strlen(szInfoBuf), " AlarmInNo:%d", struAcsAlarmInfo.struAcsEventInfo.dwAlarmInNo);
}
if (struAcsAlarmInfo.struAcsEventInfo.dwAlarmOutNo != 0 )
{
sprintf(szInfoBuf + strlen(szInfoBuf), " AlarmOutNo:%d", struAcsAlarmInfo.struAcsEventInfo.dwAlarmOutNo);
}
if (struAcsAlarmInfo.struAcsEventInfo.dwCaseSensorNo != 0 )
{
sprintf(szInfoBuf + strlen(szInfoBuf), " CaseSensorNo:%d", struAcsAlarmInfo.struAcsEventInfo.dwCaseSensorNo);
}
if (struAcsAlarmInfo.struAcsEventInfo.dwRs485No != 0 )
{
sprintf(szInfoBuf + strlen(szInfoBuf), " Rs485No:%d", struAcsAlarmInfo.struAcsEventInfo.dwRs485No);
}
if (struAcsAlarmInfo.struAcsEventInfo.dwMultiCardGroupNo != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " MultiCardGroupNo:%d", struAcsAlarmInfo.struAcsEventInfo.dwMultiCardGroupNo);
}
if (struAcsAlarmInfo.struAcsEventInfo.byCardReaderKind != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " CardReaderKind:%d", struAcsAlarmInfo.struAcsEventInfo.byCardReaderKind);
}
if (struAcsAlarmInfo.struAcsEventInfo.wAccessChannel >= 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " wAccessChannel:%d", struAcsAlarmInfo.struAcsEventInfo.wAccessChannel);
}
if (struAcsAlarmInfo.struAcsEventInfo.dwEmployeeNo != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " EmployeeNo:%d", struAcsAlarmInfo.struAcsEventInfo.dwEmployeeNo);
}
if (struAcsAlarmInfo.struAcsEventInfo.byDeviceNo != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " DeviceNo:%d", struAcsAlarmInfo.struAcsEventInfo.byDeviceNo);
}
if (struAcsAlarmInfo.struAcsEventInfo.byDistractControlNo != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " DistractControlNo:%d", struAcsAlarmInfo.struAcsEventInfo.byDistractControlNo);
}
if (struAcsAlarmInfo.struAcsEventInfo.wLocalControllerID >= 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " wLocalControllerID:%d", struAcsAlarmInfo.struAcsEventInfo.wLocalControllerID);
}
if (struAcsAlarmInfo.struAcsEventInfo.byInternetAccess >= 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " byInternetAccess:%d", struAcsAlarmInfo.struAcsEventInfo.byInternetAccess);
}
if (struAcsAlarmInfo.struAcsEventInfo.byType >= 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " byType:%d", struAcsAlarmInfo.struAcsEventInfo.byType);
}
if (struAcsAlarmInfo.struAcsEventInfo.bySwipeCardType != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " bySwipeCardType:%d", struAcsAlarmInfo.struAcsEventInfo.bySwipeCardType);
}
if (struAcsAlarmInfo.struAcsEventInfo.byChannelControllerID != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " byChannelControllerID:%d", struAcsAlarmInfo.struAcsEventInfo.byChannelControllerID);
}
if (struAcsAlarmInfo.struAcsEventInfo.byChannelControllerLampID != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " byChannelControllerLampID:%d", struAcsAlarmInfo.struAcsEventInfo.byChannelControllerLampID);
}
if (struAcsAlarmInfo.struAcsEventInfo.byChannelControllerIRAdaptorID != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " byChannelControllerIRAdaptorID:%d", struAcsAlarmInfo.struAcsEventInfo.byChannelControllerIRAdaptorID);
}
if (struAcsAlarmInfo.struAcsEventInfo.byChannelControllerIREmitterID != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " byChannelControllerIREmitterID:%d", struAcsAlarmInfo.struAcsEventInfo.byChannelControllerIREmitterID);
}
if (struAcsAlarmInfo.struAcsEventInfo.byMACAddr[0] != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " MACAddr:%02x:%02x:%02x:%02x:%02x:%02x", struAcsAlarmInfo.struAcsEventInfo.byMACAddr[0], \
struAcsAlarmInfo.struAcsEventInfo.byMACAddr[1], struAcsAlarmInfo.struAcsEventInfo.byMACAddr[2], struAcsAlarmInfo.struAcsEventInfo.byMACAddr[3], \
struAcsAlarmInfo.struAcsEventInfo.byMACAddr[4], struAcsAlarmInfo.struAcsEventInfo.byMACAddr[5]);
}
if (struAcsAlarmInfo.struAcsEventInfo.dwSerialNo != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " dwSerialNo:%u", struAcsAlarmInfo.struAcsEventInfo.dwSerialNo);
}
if (struAcsAlarmInfo.wInductiveEventType != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " wInductiveEventType:%d", struAcsAlarmInfo.wInductiveEventType);
}
if (struAcsAlarmInfo.dwIOTChannelNo != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " dwIOTChannelNo:%d", struAcsAlarmInfo.dwIOTChannelNo);
}
if (struAcsAlarmInfo.byAcsEventInfoExtend == 1)
{
NET_DVR_ACS_EVENT_INFO_EXTEND struAcsEventInfoExtend = { 0 };
memset(&struAcsEventInfoExtend, 0, sizeof(struAcsEventInfoExtend));
memcpy(&struAcsEventInfoExtend, struAcsAlarmInfo.pAcsEventInfoExtend, sizeof(struAcsEventInfoExtend));
if (struAcsEventInfoExtend.dwFrontSerialNo != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " dwFrontSerialNo:%u", struAcsEventInfoExtend.dwFrontSerialNo);
}
#ifdef DEMO_LAN_CN
const char *szUserType[] = { "未知人", "普通人(主人)", "来宾(访客)", "黑名单人", "管理员" };
#else
const char *szUserType[] = { "unknow", "normal", "visitor", "blackList", "administrators" };
#endif
BYTE byUserType = struAcsEventInfoExtend.byUserType;
if (byUserType > 0 && byUserType < sizeof(szUserType) / sizeof(szUserType[0]))
{
sprintf(szInfoBuf + strlen(szInfoBuf), " UserType:%s", szUserType[byUserType]);
}
#ifdef DEMO_LAN_CN
const char *szCurrentVerifyMode[] = { "无效", "休眠", "刷卡+密码", "刷卡", "刷卡或密码", "指纹", "指纹+密码", \
"指纹或刷卡", "指纹+刷卡", "指纹+刷卡+密码", "人脸或指纹或刷卡或密码", "人脸+指纹", "人脸+密码", "人脸+刷卡", \
"人脸", "工号+密码", "指纹或密码", "工号+指纹", "工号+指纹+密码", "人脸+指纹+刷卡", "人脸+密码+指纹", \
"工号+人脸", "人脸或人脸+刷卡", "指纹或人脸", "刷卡或人脸或密码", "刷卡或人脸", "刷卡或人脸或指纹", "刷卡或指纹或密码"};
#else
const char *szCurrentVerifyMode[] = { "invalid", "sleep", "cardAndPw", "card", "cardOrPw", "fp", "fpAndPw", \
"fpOrCard", "fpAndCard", "fpAndCardAndPw", "faceOrFpOrCardOrPw", "faceAndFp", "faceAndPw", "faceAndCard", \
"face", "employeeNoAndPw", "fpOrPw", "employeeNoAndFp", "employeeNoAndFpAndPw", "faceAndFpAndCard", "faceAndPwAndFp", \
"employeeNoAndFace", "faceOrfaceAndCard", "fpOrface", "cardOrfaceOrPw" , "cardOrFace", "cardOrFaceOrFp", "cardOrFpOrPw"};
#endif
BYTE byCurrentVerifyMode = struAcsEventInfoExtend.byCurrentVerifyMode;
if (byCurrentVerifyMode > 0 && byCurrentVerifyMode < sizeof(szCurrentVerifyMode) / sizeof(szCurrentVerifyMode[0]))
{
sprintf(szInfoBuf + strlen(szInfoBuf), " CurrentVerifyMode:%s", szCurrentVerifyMode[byCurrentVerifyMode]);
}
if (struAcsEventInfoExtend.byCurrentEvent == 1)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " Real Time Event");
}
else if (struAcsEventInfoExtend.byCurrentEvent == 2)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " Off Line Event");
}
if (struAcsEventInfoExtend.byEmployeeNo[0] != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " EmployeeNo:%s", (char *)struAcsEventInfoExtend.byEmployeeNo);
}
#ifdef DEMO_LAN_CN
const char *szAttendanceStatus[] = { "未定义", "上班", "下班", "开始休息", "结束休息", "开始加班", "结束加班" };
#else
const char *szAttendanceStatus[] = { "undefined", "checkIn", "checkOut", "breakOut", "breakIn", "overtimeIn", "overtimeOut" };
#endif
BYTE byAttendanceStatus = struAcsEventInfoExtend.byAttendanceStatus;
if (byAttendanceStatus > 0 && byAttendanceStatus < sizeof(szAttendanceStatus) / sizeof(szAttendanceStatus[0]))
{
sprintf(szInfoBuf + strlen(szInfoBuf), " AttendanceStatus:%s", szAttendanceStatus[byAttendanceStatus]);
sprintf(szInfoBuf + strlen(szInfoBuf), " StatusValue:%d", struAcsEventInfoExtend.byStatusValue);
}
if (struAcsEventInfoExtend.byUUID[0] != 0)
{
sprintf(szInfoBuf + strlen(szInfoBuf), " UUID:%s", (char *)struAcsEventInfoExtend.byUUID);
}
}
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struAcsAlarmInfo.dwPicDataLen > 0 && struAcsAlarmInfo.pPicData != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, struAcsAlarmInfo.struRemoteHostAddr.sIpV4/*g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName*/, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struAcsAlarmInfo.byPicTransType)
{
sprintf(cFilename, "%s\\LocalTime[%s]Major[%d]Minor[%d]NetUser[%s]_%d.txt", cFilename, chTime, \
struAcsAlarmInfo.dwMajor, struAcsAlarmInfo.dwMinor, struAcsAlarmInfo.sNetUser, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\LocalTime[%s]Major[%d]Minor[%d]NetUser[%s]_%d.png", cFilename, chTime, \
struAcsAlarmInfo.dwMajor, struAcsAlarmInfo.dwMinor, struAcsAlarmInfo.sNetUser, rand() % GetTickCount());
}
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
AddLog(iDeviceIndex, ALARM_INFO_T, cFilename);
WriteFile(hFile, struAcsAlarmInfo.pPicData, struAcsAlarmInfo.dwPicDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struAcsAlarmInfo.pPicData != NULL)
{
delete [] (struAcsAlarmInfo.pPicData);
}
}
//压线报警暂时不对外开放。
void CClientDemoDlg::ProcCrossLineData(WPARAM wParam, LPARAM lParam)//2013-09-27 压线报警
{
char szInfoBuf[1024] = {0};
char szTriggerTime[128] = {0};
char szLan[128] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_CROSSLINE_ALARM struCrossLine = {0};
memcpy(&struCrossLine, pAlarmInfo, sizeof(struCrossLine));
g_StringLanType(szLan, "压线报警","Cross Line");
sprintf(szTriggerTime, "%d-%d-%d %d:%d:%d", struCrossLine.struTriggerTime.wYear,
struCrossLine.struTriggerTime.byMonth, struCrossLine.struTriggerTime.byDay,
struCrossLine.struTriggerTime.byHour, struCrossLine.struTriggerTime.byMinute,
struCrossLine.struTriggerTime.byDay);
sprintf(szInfoBuf, "%s: (Trigger Time:[%s] Device IP:[%s] Port:[%d] Device Channel:[%d] Ivms Channel:[%d] Plate Number:[%s] Park Index:[%s])\n",
szLan, szTriggerTime, struCrossLine.struDevInfo.struDevIP.sIpV4, struCrossLine.struDevInfo.wPort,
struCrossLine.struDevInfo.byChannel, struCrossLine.struDevInfo.byIvmsChannel, struCrossLine.struParkInfo.sPlateNo,
struCrossLine.struParkInfo.sParkIndex);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcAuxAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
char sAlarmName[33] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_IPC_AUXALARM_RESULT struAuxAlarm = {0};
memcpy(&struAuxAlarm, pAlarmInfo, sizeof(struAuxAlarm));
// g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
// ::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
// 打印信息
CTime time = CTime::GetCurrentTime();
if (struAuxAlarm.byAlarmType == IPC_AUXALARM_PIR)
{
memcpy(sAlarmName, struAuxAlarm.struAuxAlarm.struPIRAlarm.byAlarmName, NAME_LEN);
}
else if (struAuxAlarm.byAlarmType == IPC_AUXALARM_WIRELESS)
{
memcpy(sAlarmName, struAuxAlarm.struAuxAlarm.struWirelessAlarm.byAlarmName, NAME_LEN);
}
else
{
strncpy(sAlarmName, "Call help", NAME_LEN);
}
sprintf(szInfoBuf, "AuxAlarm Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] Type[%d] AlarmName[%s]\n",
time.GetYear(), time.GetMonth(), time.GetDay(), time.GetHour(),
time.GetMinute(), time.GetSecond(), struAuxAlarm.byAlarmType, sAlarmName);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcTMEVehicleAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_TME_VEHICLE_RESULT struTMEVehicle = {0};
memcpy(&struTMEVehicle, pAlarmInfo, sizeof(struTMEVehicle));
sprintf(szInfoBuf, "TME Vehicle Alarm Region[%d]Country[%d]LaneID[%d]CamLaneId[%d]ChanIndex[%d]MonitoringSiteID[%s]DeviceID[%s]Dir[%d]PicNum[%d]License[%s]VehicleLogoRecog[%d]VehicleSubLogoRecog[%d]PassVehicleID[%s]CardNo[%s]SwipeTime[%s]Charge[%d]History[%d]LetPass[%d]",
struTMEVehicle.struPlateInfo.byRegion, struTMEVehicle.struPlateInfo.byCountry,
struTMEVehicle.wLaneid, struTMEVehicle.byCamLaneId, struTMEVehicle.dwChanIndex, \
struTMEVehicle.byMonitoringSiteID, struTMEVehicle.byDeviceID, \
struTMEVehicle.byDir, struTMEVehicle.dwPicNum,struTMEVehicle.struPlateInfo.sLicense, \
struTMEVehicle.struVehicleInfo.byVehicleLogoRecog, struTMEVehicle.struVehicleInfo.byVehicleSubLogoRecog, \
struTMEVehicle.byPassVehicleID, struTMEVehicle.byCardNo, struTMEVehicle.bySwipeTime, struTMEVehicle.dwCharge,\
struTMEVehicle.byHistory, struTMEVehicle.byLetPass);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
for (i = 0; i < 4; i++)
{
if (struTMEVehicle.struPicInfo[i].dwDataLen > 0 && struTMEVehicle.struPicInfo[i].pBuffer != NULL)
{
sprintf(szInfoBuf, "TME picture[%d]infoType[%d]RedLightTime[%d]AbsTime[%s]CloseUpType[%d]Len[%d]", i+1, struTMEVehicle.struPicInfo[i].byType,
struTMEVehicle.struPicInfo[i].dwRedLightTime, struTMEVehicle.struPicInfo[i].byAbsTime, struTMEVehicle.struPicInfo[i].byCloseUpType,\
struTMEVehicle.struPicInfo[i].dwDataLen);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struTMEVehicle.struPicInfo[i].byDataType == 0)
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime,rand() % GetTickCount());
}
else if (struTMEVehicle.struPicInfo[i].byDataType == 1)
{
sprintf(cFilename, "%s\\URL_LocalTime[%s]_%d.txt",cFilename, chTime,rand() % GetTickCount());
}
//sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime, i);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struTMEVehicle.struPicInfo[i].pBuffer, struTMEVehicle.struPicInfo[i].dwDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
}
}
void CClientDemoDlg::ProcITSPlateAlarm(WPARAM wParam, LPARAM lParam)
{
//有扩展的XML要打印,防止不够
char szInfoBuf[2048 * 2] = {0};
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
int iPort = pAlarmDev->wLinkPort;
NET_ITS_PLATE_RESULT struPlateResult = {0};
memcpy(&struPlateResult, pAlarmInfo, sizeof(struPlateResult));
//对应通道添加报警图标
if (iDeviceIndex != -1 && iDeviceIndex < 512)
{
i = struPlateResult.byChanIndexEx * 256 + struPlateResult.byChanIndex - g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
// CString str = "";
//新增区域和国家信息的打印 2015-01-21
char sIllegalInfo[MAX_ILLEGAL_LEN/*64*/] = { 0 };
if (1 == struPlateResult.byIllegalFromatType)
{
LPNET_ITS_ILLEGAL_INFO pIllegalInfo = (LPNET_ITS_ILLEGAL_INFO)struPlateResult.pIllegalInfoBuf;
if (NULL != pIllegalInfo)
{
memcpy(sIllegalInfo, pIllegalInfo->byIllegalInfo, MAX_ILLEGAL_LEN);
}
}
sprintf(szInfoBuf, "ITS Plate Alarm Channel NO[%d] DriveChan[%d] IllegalFromatType[%d]IllegalInfo[%s]Analysis[%d]YellowLabel[%d]DangerousVeh[%d]MatchNo[%d]IllegalType[%d]IllegalSubType[%s]\
MonitoringSiteID[%s]DeviceID[%s]Dir[%d]CarDirectionType[%d]PicNum[%d] DetSceneID[%d] VehicleType[%d] DetectType[%d] Type[%d] DataType[%d] CloseUpType[%d]", \
struPlateResult.byChanIndexEx * 256 + struPlateResult.byChanIndex, struPlateResult.byDriveChan, \
struPlateResult.byIllegalFromatType, sIllegalInfo, \
struPlateResult.byDataAnalysis, struPlateResult.byYellowLabelCar, struPlateResult.byDangerousVehicles,\
struPlateResult.dwMatchNo, struPlateResult.wIllegalType,
struPlateResult.byIllegalSubType, struPlateResult.byMonitoringSiteID, struPlateResult.byDeviceID,
struPlateResult.byDir, struPlateResult.byCarDirectionType, struPlateResult.dwPicNum, struPlateResult.byDetSceneID, struPlateResult.byVehicleType, struPlateResult.byDetectType, \
struPlateResult.struPicInfo->byType, struPlateResult.struPicInfo->byDataType, struPlateResult.struPicInfo->byCloseUpType);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
sprintf(szInfoBuf, "ITS Plate Alarm PlateInfo PlateType[%d]Color[%d]Bright[%d]LicenseLen[%d]EntireBelieve[%d]Region[%d]Country[%d]Area[%d]PlateSize[%d]PlateCategory[%s]License[%s]PlateRect[x-%f y-%f w-%f h-%f] \
VehicleInfo:Index[%d]VehicleType[%d] Color[%d] RadarState[%d] Speed[%d] VehicleLogoRecog[%d] VehicleSubLogoRecog[%d] VehicleModel[%d] byIsParking[%d] dwParkingTime[%d] byIllegalType[%d] byBelieve[%d] VehiclePositionControl [%d]", \
struPlateResult.struPlateInfo.byPlateType, struPlateResult.struPlateInfo.byColor, struPlateResult.struPlateInfo.byBright,
struPlateResult.struPlateInfo.byLicenseLen, struPlateResult.struPlateInfo.byEntireBelieve, struPlateResult.struPlateInfo.byRegion, struPlateResult.struPlateInfo.byCountry,
struPlateResult.struPlateInfo.byArea, struPlateResult.struPlateInfo.byPlateSize, struPlateResult.struPlateInfo.sPlateCategory,
struPlateResult.struPlateInfo.sLicense, struPlateResult.struPlateInfo.struPlateRect.fX, struPlateResult.struPlateInfo.struPlateRect.fY, \
struPlateResult.struPlateInfo.struPlateRect.fWidth, struPlateResult.struPlateInfo.struPlateRect.fHeight, struPlateResult.struVehicleInfo.dwIndex,\
struPlateResult.struVehicleInfo.byVehicleType, struPlateResult.struVehicleInfo.byColor,
struPlateResult.struVehicleInfo.byRadarState, struPlateResult.struVehicleInfo.wSpeed, \
struPlateResult.struVehicleInfo.wVehicleLogoRecog, struPlateResult.struVehicleInfo.byVehicleSubLogoRecog, \
struPlateResult.struVehicleInfo.byVehicleModel, struPlateResult.struVehicleInfo.byIsParking, \
struPlateResult.struVehicleInfo.dwParkingTime, struPlateResult.struVehicleInfo.byIllegalType, \
struPlateResult.struVehicleInfo.byBelieve, struPlateResult.byVehiclePositionControl);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
for (i = 0; i < 6; i++)
{
if (struPlateResult.struPicInfo[i].dwDataLen > 0 && struPlateResult.struPicInfo[i].pBuffer != NULL)
{
sprintf(szInfoBuf, "ITS picture[%d] info Type[%d] RedLightTime[%d] AbsTime[%s %2.2d%2.2d] flag[%d] CloseUpType[%d]PlateRect[x-%f y-%f w-%f h-%f]PlateRecgRect[x-%f y-%f w-%f h-%f]", i+1, struPlateResult.struPicInfo[i].byType,
struPlateResult.struPicInfo[i].dwRedLightTime, struPlateResult.struPicInfo[i].byAbsTime, struPlateResult.struPicInfo[i].cTimeDifferenceH, struPlateResult.struPicInfo[i].cTimeDifferenceM, struPlateResult.struPicInfo[i].byTimeDiffFlag,
struPlateResult.struPicInfo[i].byCloseUpType, struPlateResult.struPicInfo[i].struPlateRect.fX, struPlateResult.struPicInfo[i].struPlateRect.fY, struPlateResult.struPicInfo[i].struPlateRect.fWidth, struPlateResult.struPicInfo[i].struPlateRect.fHeight,
struPlateResult.struPicInfo[i].struPlateRecgRect.fX, struPlateResult.struPicInfo[i].struPlateRecgRect.fY, struPlateResult.struPicInfo[i].struPlateRecgRect.fWidth, struPlateResult.struPicInfo[i].struPlateRecgRect.fHeight);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%s flag[%d] %2.2d%2.2d", struPlateResult.struPicInfo[i].byAbsTime,
struPlateResult.struPicInfo[i].byTimeDiffFlag, struPlateResult.struPicInfo[i].cTimeDifferenceH, struPlateResult.struPicInfo[i].cTimeDifferenceM);
if (iDeviceIndex != -1 && iDeviceIndex < 512)
{
sprintf(cFilename, "%s\\%s[%d]_channel[%d]_ITS", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, struPlateResult.byChanIndex);
}
else
{
sprintf(cFilename, "%s\\%s[%d]_channel[%d]_ITS", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, struPlateResult.byChanIndex);
}
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
char cPicType[256] = {0};
if (struPlateResult.struPicInfo[i].byDataType == 0)
{
if (0 == struPlateResult.struPicInfo[i].byType)
{
sprintf(cPicType,"License");
}
else if (1 == struPlateResult.struPicInfo[i].byType)
{
sprintf(cPicType,"Scene");
}
sprintf(cFilename, "%s\\%s_LocalTime[%s]_%d.jpg",cFilename, cPicType, chTime,rand() % GetTickCount());
}
else if (struPlateResult.struPicInfo[i].byDataType == 1)
{
if (0 == struPlateResult.struPicInfo[i].byType)
{
sprintf(cPicType,"License");
}
else if (1 == struPlateResult.struPicInfo[i].byType)
{
sprintf(cPicType,"Scene");
}
sprintf(cFilename, "%s\\%s_URL_LocalTime[%s]_%d.txt",cFilename, cPicType, chTime,rand() % GetTickCount());
}
//sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime, i);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struPlateResult.struPicInfo[i].pBuffer, struPlateResult.struPicInfo[i].dwDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
}
if (struPlateResult.struPlateInfo.dwXmlLen > 0)
{
char sXMLFileName[256] = { 0 };
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
if (iDeviceIndex != -1 && iDeviceIndex < 512)
{
sprintf(sXMLFileName, "%s\\%s[%d]_channel[%d]_ITS", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIP, iPort, struPlateResult.byChanIndex);
}
else
{
sprintf(sXMLFileName, "%s\\%s[%d]%s_channel[%d]_ITS", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP, iPort, struPlateResult.byChanIndex);
}
if (GetFileAttributes(sXMLFileName) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(sXMLFileName, NULL);
}
SYSTEMTIME tNow = { 0 };
GetLocalTime(&tNow);
sprintf(sXMLFileName, "%s\\ANPR_XML[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d].xml",
sXMLFileName, tNow.wYear, tNow.wMonth, tNow.wDay, tNow.wHour, tNow.wMinute, tNow.wSecond, tNow.wMilliseconds);
HANDLE hXMLFile = CreateFile(sXMLFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hXMLFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwReturn = 0;
WriteFile(hXMLFile, struPlateResult.struPlateInfo.pXmlBuf, struPlateResult.struPlateInfo.dwXmlLen, &dwReturn, NULL);
CloseHandle(hXMLFile);
hXMLFile = NULL;
sprintf(szInfoBuf, "ANPR XML Block Path:%s", sXMLFileName);
szInfoBuf[sizeof(szInfoBuf) - 1] = 0; //防止溢出
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
if (1 == struPlateResult.struPlateInfo.byAddInfoFlag)
{
NET_DVR_VEHICLE_ADDINFO struVehicleAddInfo = { 0 };
memcpy(&struVehicleAddInfo, struPlateResult.struPlateInfo.pAddInfoBuffer, sizeof(NET_DVR_VEHICLE_ADDINFO));
sprintf(szInfoBuf, "AddInfoFlag [%d] LatitudeType [%d] Degree[%d] Minute[%d] fSec[%f] \
LongitudeType [%d] Degree[%d] Minute[%d] fSec[%f] VehicleNo[%s] byVehicleMonitorTaskID[%s] byUUID[%s]",
struPlateResult.struPlateInfo.byAddInfoFlag,
struVehicleAddInfo.struLLPos.byLatitudeType, struVehicleAddInfo.struLLPos.struLatitude.byDegree,
struVehicleAddInfo.struLLPos.struLatitude.byMinute, struVehicleAddInfo.struLLPos.struLatitude.fSec,
struVehicleAddInfo.struLLPos.byLongitudeType, struVehicleAddInfo.struLLPos.struLongitude.byDegree,
struVehicleAddInfo.struLLPos.struLongitude.byMinute, struVehicleAddInfo.struLLPos.struLongitude.fSec,
struVehicleAddInfo.sVehicleNo, struVehicleAddInfo.byVehicleMonitorTaskID, struVehicleAddInfo.byUUID);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
}
void CClientDemoDlg::ProcITSPlateAlarmV50(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
if (iDeviceIndex < 0 || iDeviceIndex >= MAX_DEVICES)
{
return;
}
NET_DVR_PLATE_RESULT_V50 struPlateResult = {0};
memcpy(&struPlateResult, pAlarmInfo, sizeof(struPlateResult));
i = struPlateResult.byChanIndex;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
// CString str = "";
//新增区域和国家信息的打印 2015-01-21
sprintf(szInfoBuf, "ITS Plate Alarm V50;IsOverWeight[%d]AxleNum[%d]AxleModel[%d]OverWeight[%f]Weight[%f]LimitWeight[%f]AxleLen[%f]DevDescInfo[%s]\
Region[%d]Country[%d]MatchNo[%d]DriveChan[%d]IllegalType[%d]IllegalSubType[%s]\
MonitoringSiteID[%s]DeviceID[%s]Dir[%d]PicNum[%d]License[%s]VehicleLogoRecog[%d]\
VehicleSubLogoRecog[%d]DetSceneID[%d]VehicleType[%d]DetectType[%d]\
Type[%d]DataType[%d]CloseUpType[%d]",
struPlateResult.struWeightResult.byIsOverWeight, struPlateResult.struWeightResult.byAxleNum, struPlateResult.struWeightResult.wAxleModel,
struPlateResult.struWeightResult.fOverWeight,struPlateResult.struWeightResult.fWeight,
struPlateResult.struWeightResult.fLimitWeight,struPlateResult.struWeightResult.fAxleLen,
struPlateResult.struWeightResult.sDevDescInfo,
struPlateResult.struPlateInfo.byRegion, struPlateResult.struPlateInfo.byCountry,
struPlateResult.dwMatchNo, struPlateResult.byDriveChan, struPlateResult.wIllegalType,
struPlateResult.byIllegalSubType, struPlateResult.byMonitoringSiteID, struPlateResult.byDeviceID,
struPlateResult.byDir, struPlateResult.dwPicNum,struPlateResult.struPlateInfo.sLicense, \
struPlateResult.struVehicleInfo.byVehicleLogoRecog, struPlateResult.struVehicleInfo.byVehicleSubLogoRecog, \
struPlateResult.byDetSceneID, struPlateResult.byVehicleType, struPlateResult.byDetectType, \
struPlateResult.struPicInfo->byType, struPlateResult.struPicInfo->byDataType, struPlateResult.struPicInfo->byCloseUpType);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
std::string strInfo = "AxleWeight[";
for (i = 0; i < ARRAY_SIZE(struPlateResult.struWeightResult.wAxleWeight); ++i)
{
sprintf(szInfoBuf, " %d", struPlateResult.struWeightResult.wAxleWeight[i]);
strInfo += szInfoBuf;
}
strInfo += "]\nAxleDistance[";
for (i = 0; i < ARRAY_SIZE(struPlateResult.struWeightResult.wAxleDistance); ++i)
{
sprintf(szInfoBuf, " %d", struPlateResult.struWeightResult.wAxleDistance[i]);
strInfo += szInfoBuf;
}
strInfo += "]";
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, strInfo.c_str());
for (i = 0; i < 6; i++)
{
if (struPlateResult.struPicInfo[i].dwDataLen > 0 && struPlateResult.struPicInfo[i].pBuffer != NULL)
{
sprintf(szInfoBuf, "ITS picture[%d] info Type[%d] RedLightTime[%d] AbsTime[%s] CloseUpType[%d]", i+1, struPlateResult.struPicInfo[i].byType,
struPlateResult.struPicInfo[i].dwRedLightTime, struPlateResult.struPicInfo[i].byAbsTime, struPlateResult.struPicInfo[i].byCloseUpType);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%s", struPlateResult.struPicInfo[i].byAbsTime);
sprintf(cFilename, "%s\\%s_channel[%d]_ITS", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIP, struPlateResult.byChanIndex);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
char cPicType[256] = {0};
if (struPlateResult.struPicInfo[i].byDataType == 0)
{
if (0 == struPlateResult.struPicInfo[i].byType)
{
sprintf(cPicType,"License");
}
else if (1 == struPlateResult.struPicInfo[i].byType)
{
sprintf(cPicType,"Scene");
}
sprintf(cFilename, "%s\\%s_LocalTime[%s]_%d.jpg",cFilename, cPicType, chTime,rand() % GetTickCount());
}
else if (struPlateResult.struPicInfo[i].byDataType == 1)
{
if (0 == struPlateResult.struPicInfo[i].byType)
{
sprintf(cPicType,"License");
}
else if (1 == struPlateResult.struPicInfo[i].byType)
{
sprintf(cPicType,"Scene");
}
sprintf(cFilename, "%s\\%s_URL_LocalTime[%s]_%d.txt",cFilename, cPicType, chTime,rand() % GetTickCount());
}
//sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime, i);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struPlateResult.struPicInfo[i].pBuffer, struPlateResult.struPicInfo[i].dwDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
}
}
void CClientDemoDlg::ProcITSGateVehicle(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_ITS_GATE_VEHICLE struGateVehicle = {0};
memcpy(&struGateVehicle, pAlarmInfo, sizeof(struGateVehicle));
sprintf(szInfoBuf, "ITS Gate Vehicle MatchNo[%d] LaneID[%d] CamLaneId[%d] ChanIndex[%d] MonitoringSiteID[%s] DeviceID[%s] Dir[%d] PicNum[%d]",\
struGateVehicle.dwMatchNo, struGateVehicle.wLaneid, struGateVehicle.byCamLaneId, struGateVehicle.dwChanIndex,\
struGateVehicle.byMonitoringSiteID, struGateVehicle.byDeviceID, struGateVehicle.byDir, struGateVehicle.dwPicNum);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
for (i = 0; i < 4; i++)
{
if (struGateVehicle.struPicInfo[i].dwDataLen > 0 && struGateVehicle.struPicInfo[i].pBuffer != NULL)
{
sprintf(szInfoBuf, "ITS picture[%d] info Type[%d] RedLightTime[%d] AbsTime[%s]", i+1, struGateVehicle.struPicInfo[i].byType,
struGateVehicle.struPicInfo[i].dwRedLightTime, struGateVehicle.struPicInfo[i].byAbsTime);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%s", struGateVehicle.struPicInfo[i].byAbsTime);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\ITSGateVehicle[%s]_%d.jpg",cFilename, chTime, i);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struGateVehicle.struPicInfo[i].pBuffer, struGateVehicle.struPicInfo[i].dwDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
}
}
void CClientDemoDlg::ProcITSGateFace(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_ITS_GATE_FACE struGateFace = {0};
memcpy(&struGateFace, pAlarmInfo, sizeof(struGateFace));
sprintf(szInfoBuf, "ITS Gate Face Laneid[%d] CamLaneId[%d] MonitoringSiteID[%s] DeviceID[%s]",\
struGateFace.wLaneid, struGateFace.byCamLaneId, struGateFace.byMonitoringSiteID, struGateFace.byDeviceID);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
// 打印信息
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struGateFace.struFaceInfo.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struGateFace.struFaceInfo.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struGateFace.struFaceInfo.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struGateFace.struFaceInfo.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struGateFace.struFaceInfo.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struGateFace.struFaceInfo.dwAbsTime);
sprintf(szInfoBuf, "Face Snap alarm Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] FaceID[%d]\n",
struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour,
struAbsTime.dwMinute, struAbsTime.dwSecond, struGateFace.struFaceInfo.dwFacePicID);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struGateFace.struFaceInfo.dwFacePicLen > 0 && struGateFace.struFaceInfo.pBuffer1 != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\ITSGateFace[%s].jpg",cFilename, chTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struGateFace.struFaceInfo.pBuffer1, struGateFace.struFaceInfo.dwFacePicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struGateFace.struFaceInfo.dwBackgroundPicLen > 0 && struGateFace.struFaceInfo.pBuffer2 != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\BackgroundPic[%s].jpg",cFilename, chTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struGateFace.struFaceInfo.pBuffer2, struGateFace.struFaceInfo.dwBackgroundPicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struGateFace.struFaceInfo.pBuffer1 != NULL)
{
delete []struGateFace.struFaceInfo.pBuffer1;
struGateFace.struFaceInfo.pBuffer1 = NULL;
}
if (struGateFace.struFaceInfo.pBuffer2 != NULL)
{
delete []struGateFace.struFaceInfo.pBuffer2;
struGateFace.struFaceInfo.pBuffer2 = NULL;
}
}
void CClientDemoDlg::ProcITSParkVehicle(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_ITS_PARK_VEHICLE struParkVehicle = {0};
memcpy(&struParkVehicle, pAlarmInfo, sizeof(struParkVehicle));
sprintf(szInfoBuf, "ITS Park Vehicle LocationStatus[%d] MonitoringSiteID[%s] DeviceID[%s] PicNum[%d] struPlateRect0[%f,%f,%f,%f] struPlateRect1[%f,%f,%f,%f] CurrentWorkerNumber[%d] CurrentGoodsLoadingRate[%d] DoorsStatus[%d]", \
struParkVehicle.byLocationStatus, struParkVehicle.byMonitoringSiteID, struParkVehicle.byDeviceID, struParkVehicle.dwPicNum,
struParkVehicle.struPicInfo[0].struPlateRect.fX, struParkVehicle.struPicInfo[0].struPlateRect.fY,
struParkVehicle.struPicInfo[0].struPlateRect.fWidth, struParkVehicle.struPicInfo[0].struPlateRect.fHeight,
struParkVehicle.struPicInfo[1].struPlateRect.fX, struParkVehicle.struPicInfo[1].struPlateRect.fY,
struParkVehicle.struPicInfo[1].struPlateRect.fWidth, struParkVehicle.struPicInfo[1].struPlateRect.fHeight,struParkVehicle.struVehicleInfo.byCurrentWorkerNumber,
struParkVehicle.struVehicleInfo.byCurrentGoodsLoadingRate,struParkVehicle.struVehicleInfo.byDoorsStatus);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
for (i = 0; i < 2; i++)
{
if (struParkVehicle.struPicInfo[i].dwDataLen > 0 && struParkVehicle.struPicInfo[i].pBuffer != NULL)
{
sprintf(szInfoBuf, "ITS picture[%d] info Type[%d] RedLightTime[%d] AbsTime[%s]", i+1, struParkVehicle.struPicInfo[i].byType,
struParkVehicle.struPicInfo[i].dwRedLightTime, struParkVehicle.struPicInfo[i].byAbsTime);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%s", struParkVehicle.struPicInfo[i].byAbsTime);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTimeITSParkVehicle[%s]_%d.jpg",cFilename, chTime, i);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struParkVehicle.struPicInfo[i].pBuffer, struParkVehicle.struPicInfo[i].dwDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
}
}
void CClientDemoDlg::ProcITSBalckListInfo(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_ITS_ECT_BLACKLIST struBlackList = {0};
memcpy(&struBlackList, pAlarmInfo, sizeof(struBlackList));
sprintf(szInfoBuf, "ITS BLACK LIST INFO Channel[%d] LogicalLaneNo[%d] LaneName[%d] License[%s]",\
struBlackList.dwChannel, struBlackList.bylogicalLaneNo, struBlackList.bylogicalLaneNo, struBlackList.struPlateInfo.sLicense);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcVehicleControlListDS(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = { 0 };
g_StringLanType(szLan, "车辆黑白名单数据需要同步报警上传", "Vehicle control list");
NET_DVR_VEHICLE_CONTROL_LIST_DSALARM struVehicleControl;
memset(&struVehicleControl, 0, sizeof(struVehicleControl));
memcpy(&struVehicleControl, pAlarmInfo, sizeof(struVehicleControl));
LPNET_DVR_VEHICLE_CONTROL_LIST_DSALARM pVehicle = (LPNET_DVR_VEHICLE_CONTROL_LIST_DSALARM)(pAlarmInfo);
sprintf(szInfoBuf, "%s: Data index[%d] sOperateIndex[%s]", \
szLan, pVehicle->dwDataIndex, pVehicle->sOperateIndex);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcVehicleControl(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
int iPort = pAlarmDev->wLinkPort;
char szLan[128] = { 0 };
g_StringLanType(szLan, "黑白名单车辆报警上传", "Vehicle control");
LPNET_DVR_VEHICLE_CONTROL_ALARM pVehicle = (LPNET_DVR_VEHICLE_CONTROL_ALARM)(pAlarmInfo);
sprintf(szInfoBuf, "time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d flag[%d] %2.2d%2.2d] %s: byListType[%d] byPlateType[%d] byPlateColor[%d] sLicense[%s] dwChannel[%d]byPicTransType[%d]", \
pVehicle->struAlarmTime.wYear, pVehicle->struAlarmTime.byMonth, pVehicle->struAlarmTime.byDay,
pVehicle->struAlarmTime.byHour, pVehicle->struAlarmTime.byMinute, pVehicle->struAlarmTime.bySecond,
pVehicle->struAlarmTime.byISO8601, pVehicle->struAlarmTime.cTimeDifferenceH, pVehicle->struAlarmTime.cTimeDifferenceM,
szLan, pVehicle->byListType, pVehicle->byPlateType, pVehicle->byPlateColor, pVehicle->sLicense, pVehicle->dwChannel, pVehicle->byPicTransType);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
if (pVehicle->dwPicDataLen > 0 && pVehicle->pPicData != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%d][%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, "blackwhitelist");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (pVehicle->byPicTransType)
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
}
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, pVehicle->pPicData, pVehicle->dwPicDataLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < pVehicle->dwPicDataLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Plate Picture Wtite to File Fail.System Error:%d, dwPlateBufferLen:%d, dwWrittenBytes:%d ", dwError, pVehicle->dwPicDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
//释放图片内存
if (pVehicle->pPicData != NULL)
{
delete[](pVehicle->pPicData);
pVehicle->pPicData = NULL;
}
}
void CClientDemoDlg::ProcITSRoadException(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_ITS_ROADINFO struResult = {0};
memcpy(&struResult, pAlarmInfo, sizeof(struResult));
if (iDeviceIndex>=0 && iDeviceIndex<MAX_DEVICES)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
// CString str = "";
sprintf(szInfoBuf, "ITS Road Exception ChanNo[%d]DeviceNum[%d]",
struResult.dwChannel, struResult.dwDeviceNum);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
char sInfo[10240] = {0};
sprintf(sInfo, "NET_ITS_ROADINFO \r\n");
sprintf(sInfo, "%s dwChannel=%d \r\n", sInfo, struResult.dwChannel);
sprintf(sInfo, "%s byTriggerMode=%d \r\n", sInfo, struResult.byTriggerMode);
sprintf(sInfo, "%s dwDeviceNum=%d \r\n", sInfo, struResult.dwDeviceNum);
sprintf(sInfo, "%s byMonitoringSiteID=%s \r\n", sInfo, struResult.byMonitoringSiteID);
sprintf(sInfo, "%s byRoadInfo=%s \r\n", sInfo, struResult.byRoadInfo);
for (i = 0; i < ITS_MAX_DEVICE_NUM; i++)
{
sprintf(sInfo, "%s NET_ITS_SINGLE_DEVICE_INFO[i] \r\n", sInfo, i);
sprintf(sInfo, "%s dwDeviceType=%d \r\n", sInfo, struResult.struSingleDevice[i].dwDeviceType);
sprintf(sInfo, "%s dwDirID=%d \r\n", sInfo, struResult.struSingleDevice[i].dwDirID);
sprintf(sInfo, "%s dwLaneID=%d \r\n", sInfo, struResult.struSingleDevice[i].dwLaneID);
sprintf(sInfo, "%s dwDeviceState=%d \r\n", sInfo, struResult.struSingleDevice[i].dwDeviceState);
sprintf(sInfo, "%s byDeviceName=%s \r\n", sInfo, struResult.struSingleDevice[i].byDeviceName);
sprintf(sInfo, "%s byDeviceID=%s \r\n", sInfo, struResult.struSingleDevice[i].byDeviceID);
sprintf(sInfo, "%s struTriggerTime=%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d \r\n", sInfo, \
struResult.struSingleDevice[i].struTriggerTime.wYear, struResult.struSingleDevice[i].struTriggerTime.byMonth,\
struResult.struSingleDevice[i].struTriggerTime.byDay, struResult.struSingleDevice[i].struTriggerTime.byHour,\
struResult.struSingleDevice[i].struTriggerTime.byMinute, struResult.struSingleDevice[i].struTriggerTime.bySecond,\
struResult.struSingleDevice[i].struTriggerTime.wMilliSec);
sprintf(sInfo, "%s byRelateChan=%d \r\n", sInfo, struResult.struSingleDevice[i].byRelateChan);
}
char cFilename[256] = {0};
DWORD dwWrittenBytes = 0;
HANDLE hFile = NULL;
SYSTEMTIME t;
GetLocalTime(&t);
char chLocalTime[128];
sprintf(chLocalTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[ITSRoadException]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s].txt",cFilename, chLocalTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, sInfo, 10240, &dwWrittenBytes, NULL);
CloseHandle(hFile);
hFile = NULL;
}
/*********************************************************
Function: OnWMProcAlarm
Desc: process alarm information when
Input: none
Output: none
Return: none
**********************************************************/
LRESULT CClientDemoDlg::OnWMProcAlarm(WPARAM wParam, LPARAM lParam)
{
//EnterCriticalSection(&g_cs);
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
if (iDeviceIndex < 0 && iDeviceIndex >= MAX_DEVICES)
{
delete [] pAlarmInfo;
delete pAlarmDev;
return NULL;
}
char szLan[128] ={0};
char szInfoBuf[1024] = {0};
switch (pAlarmDev->lCommand)
{
case COMM_ISAPI_ALARM:
ProcISAPIAlarm(wParam, lParam);
break;
case COMM_IPC_AUXALARM_RESULT:
ProcAuxAlarm(wParam, lParam);
break;
case COMM_ALARM:
ProcAlarm(wParam, lParam);
break;
case COMM_ALARM_V30:
ProcAlarmV30(wParam, lParam);
break;
case COMM_ALARM_V40:
ProcAlarmV40(wParam, lParam);
break;
case COMM_TRADEINFO:
NET_DVR_TRADEINFO m_TradeInfo;
memcpy(&m_TradeInfo, pAlarmInfo, sizeof(NET_DVR_TRADEINFO));
g_StringLanType(szLan, "收到卡号信息", "receive trade card number");
sprintf(szInfoBuf, "%s%s", m_TradeInfo.CardNumber);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case COMM_IPCCFG://input parameters modified
ProcIPCfgAlarm(wParam, lParam);
break;
case COMM_IPCCFG_V31:
ProcIPCfgAlarmV31(wParam, lParam);
break;
case COMM_ALARM_RULE:
ProcRuleAlarm(wParam, lParam);
break;
case COMM_ALARM_PDC:
ProcPdcAlarm(wParam, lParam);
break;
case COMM_SENSOR_VALUE_UPLOAD:
ProcSensorValueUpload(wParam, lParam);
break;
case COMM_SENSOR_ALARM:
ProcSensorAlarm(wParam, lParam);
break;
case COMM_ALARM_AID:
ProcAidAlarm(wParam, lParam);
break;
case COMM_ALARM_TPS:
ProcTpsAlarm(wParam, lParam);
break;
case COMM_ALARM_AID_V41:
ProcAidAlarmV41(wParam,lParam);
break;
case COMM_ALARM_TPS_REAL_TIME:
ProcTpsRealtime(wParam, lParam);
break;
case COMM_ALARM_TPS_STATISTICS:
ProcTpsStatistics(wParam, lParam);
break;
case COMM_ALARM_TFS:
ProcTfsAlarm(wParam,lParam);
break;
case COMM_ALARM_TPS_V41:
ProcTpsAlarmV41(wParam,lParam);
break;
case COMM_ALARM_FACE:
ProcFaceDetectAlarm(wParam, lParam);
break;
case COMM_UPLOAD_FACESNAP_RESULT:
ProcFaceSnapAlarm(wParam, lParam);
break;
case COMM_ALARM_FACE_DETECTION:
ProcFaceDetectionAlarm(wParam, lParam);
break;
case COMM_SNAP_MATCH_ALARM:
ProcFaceSnapMatchAlarm(wParam, lParam);
break;
case COMM_ALARM_TARGET_LEFT_REGION:
ProcTargetLeftRegionAlarm(wParam, lParam);
break;
case COMM_RULE_INFO_UPLOAD:
ProcRuleInfoUpload(wParam, lParam);
break;
//2010-06-01
case COMM_ALARM_VIDEOPLATFORM:
memset(&m_struVideoPlatform, 0, sizeof(m_struVideoPlatform));
memcpy(&m_struVideoPlatform, pAlarmInfo, sizeof(m_struVideoPlatform));
if (m_struVideoPlatform.byAlarmType == 0)
{
g_StringLanType(szLan, "收到视频综合平台拔出子板报警,起始槽位号:", "receive videoplatform pull board alarm, start slotnum:");
sprintf(szInfoBuf, "%s%d", szLan, m_struVideoPlatform.bySubSystemChan[0]);
}
else if (m_struVideoPlatform.byAlarmType == 1)
{
g_StringLanType(szLan, "收到视频综合平台插入子板报警,起始槽位号:", "receive videoplatform push board alarm, start slotnum:");
sprintf(szInfoBuf, "%s%d", szLan, m_struVideoPlatform.bySubSystemChan[0]);
}
else if (m_struVideoPlatform.byAlarmType == 2)
{
g_StringLanType(szLan, "收到视频综合平台温度超上限报警,温度:", "receive videoplatform temperature uplimited alarm, temp:");
sprintf(szInfoBuf, "%s%d.%d", szLan, (m_struVideoPlatform.iTemperature / 100), m_struVideoPlatform.iTemperature % 100);
}
else if (m_struVideoPlatform.byAlarmType == 3)
{
g_StringLanType(szLan, "收到视频综合平台温度超下限报警,温度:", "receive videoplatform temperature downlimited alarm, temp:");
sprintf(szInfoBuf, "%s%d.%d", szLan, (m_struVideoPlatform.iTemperature / 100), m_struVideoPlatform.iTemperature % 100);
}
else if (m_struVideoPlatform.byAlarmType == 4)
{
g_StringLanType(szLan, "收到视频综合平台风扇状态异常报警,风扇号:", "receive videoplatform fan exception alarm, fan num:");
sprintf(szInfoBuf, "%s", szLan);
for (int i = 0; i < 32; i++)
{
sprintf(&szInfoBuf[i + strlen(szLan)], "%d", m_struVideoPlatform.byFanSequence[i]);
}
}
else if (m_struVideoPlatform.byAlarmType == 5)
{
g_StringLanType(szLan, "收到视频综合平台子系统异常报警,子系统号:", "receive videoplatform sub system exception alarm, sub system slot:");
sprintf(szInfoBuf, "%s%d", szLan, m_struVideoPlatform.bySubSystemChan[0]);
}
else if (m_struVideoPlatform.byAlarmType == 6)
{
g_StringLanType(szLan, "收到视频综合平台非法访问报警", "receive videoplatform illegal visit alarm");
sprintf(szInfoBuf, "%s", szLan);
}
if (m_struVideoPlatform.byBoardNum != 0xff)
{
g_StringLanType(szLan, "子板号:", "Board number:");
sprintf(szInfoBuf, "%s%s%d", szInfoBuf, szLan, m_struVideoPlatform.byBoardNum);
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
break;
case COMM_ALARM_ALARMHOST:
//2010-06-30
ProcAlarmHostAlarm(wParam, lParam);
break;
case COMM_SWITCH_ALARM:
ProcSwitchAlarm(wParam, lParam);
break;
case COMM_ALARMHOST_EXCEPTION:
ProcAlarmHostException(wParam, lParam);
break;
case COMM_ALARM_DEVICE:
ProcDeviceAlarm(wParam, lParam);
break;
case COMM_ALARM_DEVICE_V40:
ProcDeviceV40Alarm(wParam, lParam);
break;
case COMM_ALARM_CVR:
ProcCVRAlarm(wParam, lParam);
break;
case COMM_ALARMHOST_SAFETYCABINSTATE:
ProcAlarmHostSatetyCabinState(wParam, lParam);
break;
case COMM_ALARMHOST_ALARMOUTSTATUS:
ProcAlarmHostAlarmoutStatus(wParam, lParam);
break;
case COMM_ITS_PLATE_RESULT:
ProcITSPlateAlarm(wParam, lParam);
break;
case COMM_TME_VEHICLE_INDENTIFICATION:
ProcTMEVehicleAlarm(wParam, lParam);
break;
case COMM_PLATE_RESULT_V50:
ProcITSPlateAlarmV50(wParam, lParam);
break;
case COMM_ITS_ROAD_EXCEPTION:
ProcITSRoadException(wParam, lParam);
break;
case COMM_ALARMHOST_CID_ALARM:
ProcAlarmHostCIDAlarm(wParam, lParam);
break;
case COMM_ALARMHOST_EXTERNAL_DEVICE_ALARM:
ProcAlarmHostExternalDevAlarm(wParam, lParam);
break;
case COMM_ALARM_VQD:
ProcAlarmVQD(wParam,lParam);
break;
case COMM_ALARM_VQD_EX:
ProcAlarmVQDEx(wParam,lParam);
break;
case COMM_ITS_GATE_VEHICLE:
ProcITSGateVehicle(wParam, lParam);
break;
case COMM_ITS_GATE_FACE:
ProcITSGateFace(wParam, lParam);
break;
case COMM_ITS_PARK_VEHICLE:
ProcITSParkVehicle(wParam, lParam);
break;
case COMM_ITS_BLACKLIST_ALARM:
ProcITSBalckListInfo(wParam, lParam);
break;
case COMM_VEHICLE_CONTROL_LIST_DSALARM:
ProcVehicleControlListDS(wParam, lParam);
break;
case COMM_VEHICLE_CONTROL_ALARM:
ProcVehicleControl(wParam, lParam);
break;
case COMM_ALARMHOST_DATA_UPLOAD:
ProcAlarmHostData(wParam, lParam);
break;
case COMM_ALARM_WIRELESS_INFO:
ProcAlarmHostWirelessInfo(wParam, lParam);
break;
case COMM_ITS_GATE_ALARMINFO:
ProcGateAlarmHostData(wParam, lParam);
break;
case COMM_ITS_EXTERNAL_CONTROL_ALARM://布防报警(外控报警)2013-06-09
ProcExternalControlAlarmHostData(wParam, lParam);
break;
case COMM_SCENECHANGE_DETECTION_UPLOAD://2013-07-17场景变更侦测报警
ProcSceneChangeDetection(wParam, lParam);
break;
case COMM_FACECAPTURE_STATISTICS_RESULT://人脸抓拍统计上传
ProcFacecaptureStatistics(wParam, lParam);
break;
case COMM_VIDEO_PARKING_POLE_ALARM:
ProcVideoParkingPoleAlarm(wParam, lParam);
break;
case COMM_CROSSLINE_ALARM://压线报警 2013-09-27
ProcCrossLineData(wParam, lParam);
break;
case COMM_ALARM_HOT_SPARE:
ProcHotSpare(wParam,lParam);
break;
//2013-11-19
case COMM_ITS_GATE_COSTITEM://出入口过车收费明细
ProcVehCostItem(wParam, lParam);
break;
case COMM_ITS_GATE_HANDOVER://出入口交接班数据
ProcVehHandOver(wParam, lParam);
break;
case COMM_ALARM_AUDIOEXCEPTION://声音异常报警上传 2014-03-21
ProcAudioException(wParam, lParam);
break;
case COMM_ALARM_DEFOCUS:
ProcDefocus(wParam, lParam);
break;
case COMM_UPLOAD_HEATMAP_RESULT://热度图报警上传 2014-03-21
ProcHeatMapResult(wParam, lParam);
break;
case COMM_ALARM_ACS: //门禁主机报警 2014-7-23
ProcAccessCardAlarm(wParam, lParam);
break;
case COMM_ALARM_DEC_VCA:
ProVCAAlarm(wParam, lParam);
break;
case COMM_VEHICLE_RECOG_RESULT://车辆二次识别数据上传2014-11-12
ProVehicleRecogResult(wParam, lParam);
break;
case COMM_ALARM_LCD:
ProLCDAlarm(wParam, lParam);
break;
case COMM_ALARM_SENSORINFO_UPLOAD:
ProSensorInfoAlarm(wParam, lParam);
break;
case COMM_ALARM_CAPTURE_UPLOAD:
ProCaptureAlarm(wParam, lParam);
break;
case COMM_FIREDETECTION_ALARM:
ProFirDetectionAlarm(wParam, lParam);
break;
case COMM_FACE_THERMOMETRY_ALARM:
ProFaceThermometryAlarm(wParam, lParam);
break;
case COMM_PANORAMIC_LINKAGE_ALARM:
ProPicInfoUploadAlarm(wParam, lParam);
break;
case COMM_GISINFO_UPLOAD:
ProGISInfoAlarm(wParam, lParam);
break;
case COMM_VANDALPROOF_ALARM:
ProVandalproofAlarm(wParam, lParam);
break;
case COMM_UPLOAD_VIDEO_INTERCOM_EVENT:
ProcVideoIntercomEvent(wParam,lParam);
break;
case COMM_ALARM_VIDEO_INTERCOM:
ProcVideoIntercomAlarm(wParam,lParam);
break;
case COMM_UPLOAD_NOTICE_DATA:
ProcUploadNoticeData(wParam, lParam);
break;
case COMM_PEOPLE_DETECTION_UPLOAD:
ProcPeopleDetectionUpload(wParam,lParam);
break;
case COMM_ALARM_FIBER_CONVERT:
ProcFiberConvertAlarm(wParam, lParam);
break;
case COMM_ALARM_SWITCH_CONVERT:
ProcNetSwitchAlarm(wParam, lParam);
break;
case COMM_SWITCH_LAMP_ALARM:
ProcSwicthLampAlarm(wParam, lParam);
break;
case COMM_GATE_CARDINFO_UPLOAD: //出入口卡片信息上传
ProGateCardIndoAlarm(wParam, lParam);
break;
case COMM_LOADING_DOCK_OPERATEINFO: //月台作业上传
ProLoadingDockOperateInfo(wParam, lParam);
break;
case COMM_GATE_CHARGEINFO_UPLOAD:
ProGateCardChargeAlarm(wParam, lParam);
break;
case COMM_CONFERENCE_CALL_ALARM:
ProConferenceAlarm(wParam, lParam);
break;
case COMM_ID_INFO_ALARM:
ProcIDInfoAlarm(wParam, lParam);
break;
case COMM_PASSPORT_ALARM:
ProcPassportAlarm(wParam, lParam);
break;
case COMM_PASSNUM_INFO_ALARM:
ProcPassNumInfoAlarm(wParam, lParam);
break;
case COMM_ALARM_STORAGE_DETECTION:
ProcStorageDetAlarm(wParam, lParam);
break;
case COMM_MVM_REGISTER:
ProcMVMRegisterInfo(wParam, lParam);
break;
case COMM_MVM_STATUS_INFO:
ProcMVMStatusInfo(wParam, lParam);
break;
case COMM_ALARM_SHIPSDETECTION:
ProcShipsDetAlarm(wParam, lParam);
break;
case COMM_THERMOMETRY_ALARM:
ProThermometryAlarm(wParam, lParam);
break;
case COMM_BASE_STATION_INFO_ALARM:
ProBaseStationInfoAlarm(wParam, lParam);
break;
case COMM_THERMOMETRY_DIFF_ALARM:
ProThermometryDiffAlarm(wParam, lParam);
break;
case COMM_DIAGNOSIS_UPLOAD:
ProDiagnosisUpload(wParam, lParam);
break;
case COMM_ALARM_WALL_CONFERNECE:
ProcessWallConferenceAlarm(wParam, lParam);
break;
case COMM_GPS_STATUS_ALARM:
ProGPSStatusUpload(wParam, lParam);
break;
case COMM_TAG_INFO_ALARM:
ProTagInfoUpload(wParam, lParam);
break;
case COMM_INQUEST_ALARM:
ProcessInquestAlarm(wParam, lParam);
break;
case COMM_FACESNAP_RAWDATA_ALARM:
ProFaceSnapRawData(wParam, lParam);
break;
case COMM_VCA_ALARM:
ProcessEventWithJsonData(wParam, lParam);
break;
case COMM_ALARM_ALARMGPS:
ProcessAlarmGps(wParam, lParam);
break;
case COMM_FRAMES_PEOPLE_COUNTING_ALARM:
ProFramesPeopleCounting(wParam, lParam);
break;
case COMM_CLUSTER_ALARM:
ProcessClusterAlarm(wParam, lParam);
break;
case COMM_SIGN_ABNORMAL_ALARM:
ProcessEventWithJsonData(wParam, lParam);
break;
case COMM_TAPE_ARCHIVE_ALARM:
ProcessEventWithJsonData(wParam, lParam);
break;
case COMM_HFPD_ALARM:
ProcessEventWithJsonData(wParam, lParam);
break;
case COMM_ALARM_SUBSCRIBE_EVENT:
ProcessSubCribeEvent(wParam, lParam);
break;
case COMM_DEV_STATUS_CHANGED:
ProcessEventWithJsonDataNoBoundary(wParam, lParam);
break;
case COMM_UPLOAD_HEATMAP_RESULT_PDC://热度图按人数统计数据上传事件 2018-07-17
ProcHeatMapResultPDC(wParam, lParam);
break;
case COMM_UPLOAD_HEATMAP_RESULT_DURATION://热度图按人员停留时间统计数据上传事件 2018-07-17
ProcHeatMapResultDuration(wParam, lParam);
break;
case COMM_UPLOAD_HEATMAP_RESULT_INTERSECTION://路口分析热度值结果上传 2018-07-17
ProcHeatMapResultIntersection(wParam, lParam);
break;
case COMM_UPLOAD_AIOP_VIDEO:
ProcAIOPVideo(wParam, lParam);
break;
case COMM_UPLOAD_AIOP_PICTURE:
ProcAIOPPicture(wParam, lParam);
break;
case COMM_ITS_TRAFFIC_COLLECT:
ProcTrafficCollect(wParam, lParam);
break;
case COMM_VCA_DBD_ALARM:
ProcessVcaDbdAlarm(wParam, lParam);
break;
case COMM_VCA_ADAS_ALARM:
ProcessVcaAdasAlarm(wParam, lParam);
break;
case COMM_VEH_REALTIME_INFO:
ProcessVehRealtimeInfo(wParam, lParam);
break;
case COMM_UPLOAD_AIOP_POLLING_SNAP:
ProcAIOPPollingSnap(wParam, lParam);
break;
case COMM_UPLOAD_AIOP_POLLING_VIDEO:
ProcAIOPPollingVideo(wParam, lParam);
break;
default:
break;
}
if (pAlarmInfo != NULL)
{
delete[] pAlarmInfo;
pAlarmInfo = NULL;
}
if (pAlarmDev != NULL)
{
delete pAlarmDev;
pAlarmDev = NULL;
}
//LeaveCriticalSection(&g_cs);
return NULL;
}
//the structure of the log information
typedef struct tagLOCAL_LOG_INFO
{
int iLogType;
char szTime[64];
char szLogInfo[1024];
char szDevInfo[128];
char szErrInfo[256];
tagLOCAL_LOG_INFO ()
{
iLogType = 0;
szTime[0] = '\0';
szLogInfo[0] = '\0';
szDevInfo[0] = '\0';
szErrInfo[0] = '\0';
}
}LOCAL_LOG_INFO, *LPLOCAL_LOG_INFO;
/*********************************************************
Function: OnWMAddLog
Desc: responding to the message WM_ADD_LOG
Input: wParam, parameter 1;lParam, parameter 2;
Output: none
Return: result code
**********************************************************/
LRESULT CClientDemoDlg::OnWMAddLog(WPARAM wParam, LPARAM lParam)
{
EnterCriticalSection(&g_cs);
LPLOCAL_LOG_INFO pLogInfo = LPLOCAL_LOG_INFO(lParam);
if (NULL == pLogInfo)
{
LeaveCriticalSection(&g_cs);
return 0;
}
char szLogType[32] = "FAIL";
char szTime[64] = {0};
char szLogInfo[1024*5] = {0};
char szDevInfo[128] = {0};
char szErrInfo[256] = {0};
memcpy(szTime, pLogInfo->szTime, 64);
memcpy(szLogInfo, pLogInfo->szLogInfo, 1024);
memcpy(szDevInfo, pLogInfo->szDevInfo, 128);
memcpy(szErrInfo, pLogInfo->szErrInfo, 256);
if ( m_listAllLog.GetItemCount() >= 5000)
{
m_listAllLog.DeleteAllItems();
}
if ( m_listAlarmInfo.GetItemCount() >= 5000)
{
m_listAlarmInfo.DeleteAllItems();
}
switch (pLogInfo->iLogType)
{
case ALARM_INFO_T:
sprintf(szLogType, "Alarm");
m_listAlarmInfo.InsertItem(0, "", -1);
m_listAlarmInfo.SetItemText(0, 1, szTime);
m_listAlarmInfo.SetItemText(0, 2, szLogInfo);
m_listAlarmInfo.SetItemText(0, 3, szDevInfo);
break;
case DDNS_SUCC_T:
sprintf(szLogType, "SUCC");
if (g_struLocalParam.bSuccLog)
{
m_listAllLog.InsertItem(0, "", -1);
m_listAllLog.SetItemText(0, 1, szTime);
m_listAllLog.SetItemText(0, 2, szLogType);
m_listAllLog.SetItemText(0, 3, szLogInfo);
m_listAllLog.SetItemText(0, 4, szDevInfo);
m_listAllLog.SetItemText(0, 5, szErrInfo);
}
break;
case OPERATION_SUCC_T:
sprintf(szLogType, "SUCC");
if (g_struLocalParam.bSuccLog)
{
m_listAllLog.InsertItem(0, "", -1);
m_listAllLog.SetItemText(0, 1, szTime);
m_listAllLog.SetItemText(0, 2, szLogType);
m_listAllLog.SetItemText(0, 3, szLogInfo);
m_listAllLog.SetItemText(0, 4, szDevInfo);
m_listAllLog.SetItemText(0, 5, szErrInfo);
}
break;
case OPERATION_FAIL_T:
sprintf(szLogType, "FAIL");
if (g_struLocalParam.bFailLog)
{
m_listAllLog.InsertItem(0, "", -1);
m_listAllLog.SetItemText(0, 1, szTime);
m_listAllLog.SetItemText(0, 2, szLogType);
m_listAllLog.SetItemText(0, 3, szLogInfo);
m_listAllLog.SetItemText(0, 4, szDevInfo);
m_listAllLog.SetItemText(0, 5, szErrInfo);
}
break;
case PLAY_SUCC_T:
sprintf(szLogType, "SUCC");
if (g_struLocalParam.bSuccLog)
{
m_listAllLog.InsertItem(0, "", -1);
m_listAllLog.SetItemText(0, 1, szTime);
m_listAllLog.SetItemText(0, 2, szLogType);
m_listAllLog.SetItemText(0, 3, szLogInfo);
m_listAllLog.SetItemText(0, 4, szDevInfo);
m_listAllLog.SetItemText(0, 5, szErrInfo);
}
break;
case DDNS_FAIL_T:
sprintf(szLogType, "FAIL");
if (g_struLocalParam.bFailLog)
{
m_listAllLog.InsertItem(0, "", -1);
m_listAllLog.SetItemText(0, 1, szTime);
m_listAllLog.SetItemText(0, 2, szLogType);
m_listAllLog.SetItemText(0, 3, szLogInfo);
m_listAllLog.SetItemText(0, 4, szDevInfo);
m_listAllLog.SetItemText(0, 5, szErrInfo);
}
break;
case PLAY_FAIL_T:
sprintf(szLogType, "FAIL");
if (g_struLocalParam.bFailLog)
{
m_listAllLog.InsertItem(0, "", -1);
m_listAllLog.SetItemText(0, 1, szTime);
m_listAllLog.SetItemText(0, 2, szLogType);
m_listAllLog.SetItemText(0, 3, szLogInfo);
m_listAllLog.SetItemText(0, 4, szDevInfo);
m_listAllLog.SetItemText(0, 5, szErrInfo);
}
break;
default:
sprintf(szLogType, "FAIL");
if (g_struLocalParam.bFailLog)
{
m_listAllLog.InsertItem(0, "", -1);
m_listAllLog.SetItemText(0, 1, szTime);
m_listAllLog.SetItemText(0, 2, szLogType);
m_listAllLog.SetItemText(0, 3, szLogInfo);
m_listAllLog.SetItemText(0, 4, szDevInfo);
m_listAllLog.SetItemText(0, 5, szErrInfo);
}
break;
}
if (pLogInfo != NULL)
{
delete pLogInfo;
pLogInfo = NULL;
}
LeaveCriticalSection(&g_cs);
return 0;
}
/*********************************************************
Function: AddLog
Desc: add local log
Input: iLogType, log type, 0-alam, 1-operate log, 2-debug info; csLogInfo log info
Output:
Return:
**********************************************************/
void CClientDemoDlg::AddLog(int iDeviceIndex, int iLogType, const char* format, ...)
{
if (g_bExitDemo)
{
return;
}
CTime cTime = CTime::GetCurrentTime();
int iLen = 0;
char szTime[64] = {0};
char szLogType[32] = "FAIL";
char szLogInfo[1024*5] = {0};
char szDevInfo[256] = {0};
char szErrInfo[256] = {0};
char szLog[1024*5] = {0};
va_list arglist;
va_start(arglist,format);
vsprintf(szLogInfo,format,arglist);
va_end(arglist);
sprintf(szTime, "%s", cTime.Format("%y-%m-%d %H:%M:%S").GetBuffer(0));
if (iDeviceIndex != -1 && iDeviceIndex < 512)
{
sprintf(szDevInfo, "[%s]-[%s]", g_struDeviceInfo[iDeviceIndex].chDeviceIP, g_struDeviceInfo[iDeviceIndex].chLocalNodeName);
}
switch (iLogType)
{
case OPERATION_SUCC_T:
case PLAY_SUCC_T:
sprintf(szErrInfo, "");
sprintf(szLogType, "SUCC");
break;
case PLAY_FAIL_T:
sprintf(szErrInfo, "PLAY_M4 Eorror!!!");
break;
case OPERATION_FAIL_T:
default:
if (m_giAsynLoginReturn != 0)
{
sprintf(szErrInfo, "err[%d:%s]",
m_giErrNo, m_gpErrMsg);
}
else
{
sprintf(szErrInfo, "err[%d:%s]", NET_DVR_GetLastError(), NET_DVR_GetErrorMsg());
}
break;
}
//sprintf(szErrInfo, "err[%d:%s]", NET_DVR_GetLastError(), NET_DVR_GetErrorMsg());
if (iLogType == ALARM_INFO_T )
{
iLen = sprintf(szLog, "%s %s %s\n", szTime, szLogInfo, szDevInfo);
if (m_fAlarm != NULL && g_struLocalParam.bAutoSaveLog)
{
if (fwrite(szLog, 1, iLen, m_fAlarm) != (unsigned)iLen)
{
OutputDebugString("write err");
}
}
}
else
{
iLen = sprintf(szLog, "%s %s %s %s %s\n", szTime, szLogType, szLogInfo, szDevInfo, szErrInfo);
if (m_fLog != NULL && g_struLocalParam.bAutoSaveLog)
{
if (fwrite(szLog, 1, iLen, m_fLog) != (unsigned)iLen)
{
OutputDebugString("write err");
}
}
}
if (g_struLocalParam.bOutputDebugString)
{
OutputDebugString(szLog);
}
if (!g_struLocalParam.bSuccLog && !g_struLocalParam.bFailLog && (iLogType != ALARM_INFO_T ))
{
return;
}
LPLOCAL_LOG_INFO pLogInfo = NULL;
try
{
pLogInfo = new LOCAL_LOG_INFO;
memset(pLogInfo, 0, sizeof(LOCAL_LOG_INFO));
if (pLogInfo == NULL)
{
return;
}
pLogInfo->iLogType = iLogType;
memcpy(pLogInfo->szTime, szTime, 64);
memcpy(pLogInfo->szLogInfo, szLogInfo, 1024);
memcpy(pLogInfo->szDevInfo, szDevInfo, 128);
memcpy(pLogInfo->szErrInfo, szErrInfo, 256);
::PostMessage(g_pMainDlg->m_hWnd, WM_ADD_LOG, iDeviceIndex, (LPARAM)pLogInfo);
}
catch (...)
{
if (pLogInfo != NULL)
{
return;
}
OutputDebugString("New Log Exception!!\n");
}
}
/*************************************************
Function: DblAllTree
Description: preview all device if some are not previewed, or stop all previewing devices
Input: iDeviceIndex, device index; iStartOutputIndex, preview start index;
Return: 无
*************************************************/
void CClientDemoDlg::DblAllTree()
{
HTREEITEM hSelect = m_treeDeviceList.GetSelectedItem();
int i=0;
int iDevIndex = 0;
hSelect = m_treeDeviceList.GetChildItem(hSelect);
for (i=0; i<MAX_DEVICES; i++)
{
//shut down all play channel
if (g_struDeviceInfo[i].lLoginID < 0)
{//play the window that is not previewed
iDevIndex = m_treeDeviceList.GetItemData(hSelect)%1000;
/*LPLOCAL_LOGIN_PARAM lpParam = new LOCAL_LOGIN_PARAM;
lpParam->iDeviceIndex = iDevIndex;
lpParam->hSelect = hSelect;
lpParam->bMsgBox = FALSE;*/
// _beginthread((void (__cdecl *)(void *))DoLoginEx, 0, lpParam);
// Sleep(200);
LONG lReturn = DoLogin(iDevIndex, hSelect);
hSelect = m_treeDeviceList.GetNextSiblingItem(hSelect);
if (hSelect == NULL)
{
break;
}
}
}
}
/*************************************************
Function: DblPlayDevice
Description: preview all device if some are not previewed, or stop all previewing devices
Input: iDeviceIndex, device index; iStartOutputIndex, preview start index;
Return: 无
*************************************************/
void CClientDemoDlg::DblPlayDevice(int iDeviceIndex, int iStartOutputIndex)
{
HTREEITEM hSelect = m_treeDeviceList.GetSelectedItem();
if (!DoLogin(iDeviceIndex, hSelect))
{
return;
}
int i=0;
int iChanIndex = 0;
HTREEITEM hChannel = m_treeDeviceList.GetChildItem(hSelect);
//既未配置URL方式预览时又无通道
if (hChannel == NULL && !g_struDeviceInfo[iDeviceIndex].byURL)
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "there is no channels!!");
return;
}
if (g_struDeviceInfo[iDeviceIndex].bPlayDevice)
{
g_struDeviceInfo[iDeviceIndex].bPlayDevice = FALSE;
//StopPlayAll();
for (i=0; i< m_iCurWndNum; i++)
{
if (g_dlgOutput[i].m_struChanInfo.iDeviceIndex == iDeviceIndex)
{
g_dlgOutput[i].StopPlay();
}
}
}
else
{
for (i=0; i<m_iCurWndNum; i++)
{
//shut down all play channel
if (g_dlgOutput[i].m_struChanInfo.iDeviceIndex == iDeviceIndex)
{
g_dlgOutput[i].StopPlay();
}
if (g_dlgOutput[i].m_lPlayHandle < 0)
{//play the window that is not previewed
//没有通道配置了URL预览,此时要收到设置通道号(虚假的通道,用于后续代码逻辑复用有通道的设备)
if (g_struDeviceInfo[iDeviceIndex].byURL && hChannel == NULL)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[0].iChannelNO = 1;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[0].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[0].iChanIndex = 0;
LONG lReturn = g_dlgOutput[i].StartPlay(&g_struDeviceInfo[iDeviceIndex].pStruChanInfo[0], hChannel);
break;
}
else
{
iChanIndex = m_treeDeviceList.GetItemData(hChannel) % 1000;
if ((g_struDeviceInfo[iDeviceIndex].wStartMirrorChanNo != 0) && (iChanIndex >= MIRROR_CHAN_INDEX))
{
LONG lReturn = g_dlgOutput[i].StartPlay(&g_struDeviceInfo[iDeviceIndex].struMirrorChan[iChanIndex - MIRROR_CHAN_INDEX], hChannel);
}
else
{
LONG lReturn = g_dlgOutput[i].StartPlay(&g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex], hChannel);
}
hChannel = m_treeDeviceList.GetNextSiblingItem(hChannel);
if (hChannel == NULL)
{
break;
}
}
}
}
g_struDeviceInfo[iDeviceIndex].bPlayDevice = TRUE;
}
ChangePlayBtnState();
}
/*********************************************************
Function: StopPlayAll
Desc: stop all playing windows
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::StopPlayAll(void)
{
int i = 0;
for (i = 0; i < MAX_OUTPUTS; i ++)
{
if (g_dlgOutput[i].m_lPlayHandle < 0)
{
continue;
}
g_dlgOutput[i].StopPlay();
}
}
/*********************************************************
Function: ChangePlayBtnState
Desc: change 'play' button text state
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::ChangePlayBtnState(void)
{
int i = 0;
char szLan[32] = {0};
if (m_iMainType == PREVIEW_T)
{
for (i = 0; i < MAX_OUTPUTS; i++)
{
if (g_dlgOutput[i].m_lPlayHandle < 0)
{
if (!g_bPlayAllDevice && i == m_iCurWndIndex)
{//change network delay
m_comboNetDelayBufNum.EnableWindow(TRUE);
}
continue;
}
if (i == m_iCurWndIndex)
{
m_comboNetDelayBufNum.EnableWindow(FALSE);
}
m_comboWinNum.EnableWindow(FALSE);
g_StringLanType(szLan, "停止", "Stop");
GetDlgItem(IDC_BTN_PLAY)->SetWindowText(szLan);
return;
}
}
m_comboWinNum.EnableWindow(TRUE);
g_StringLanType(szLan, "播放", "Play");
g_bPlayAllDevice = FALSE;
GetDlgItem(IDC_BTN_PLAY)->SetWindowText(szLan);
}
/*********************************************************
Function: GetChanItem
Desc: get channel item and its structure
Input: iDeviceIndex,device serial number;iChanIndex,channel index;
Output:
Return:
**********************************************************/
HTREEITEM CClientDemoDlg::GetChanItem(int iDeviceIndex, int iChanIndex)
{
HTREEITEM hRoot = m_treeDeviceList.GetRootItem();
if (hRoot == NULL)
{
return NULL;
}
int iChanData = 0;
HTREEITEM hChannel = NULL;
HTREEITEM hDevItem = m_treeDeviceList.GetChildItem(hRoot);
while (hDevItem != NULL)
{
if (DEVICETYPE == (int)m_treeDeviceList.GetItemData(hDevItem)/1000)
{
if (iDeviceIndex == (int)m_treeDeviceList.GetItemData(hDevItem)%1000)
{
hChannel = m_treeDeviceList.GetChildItem(hDevItem);
if (hChannel == NULL)
{
return NULL;
}
iChanData = m_treeDeviceList.GetItemData(hChannel);
while (iChanData%1000 != iChanIndex)
{
hChannel = m_treeDeviceList.GetNextSiblingItem(hChannel);
if (hChannel == NULL)
{
AddLog(iDeviceIndex, OPERATION_FAIL_T, "don't find chanindex[%d] node!!!", iChanIndex);
return NULL;
}
else
{
iChanData = m_treeDeviceList.GetItemData(hChannel);
}
}
return hChannel;
}
}
hDevItem = m_treeDeviceList.GetNextVisibleItem(hDevItem);
}//end while
return NULL;
}
/*********************************************************
Function: GetDeviceItem
Desc: get device item and its structure
Input: iDeviceIndex, device index
Output:
Return:
**********************************************************/
HTREEITEM CClientDemoDlg::GetDeviceItem(int iDeviceIndex)
{
HTREEITEM hRoot = m_treeDeviceList.GetRootItem();
if (hRoot == NULL)
{
return NULL;
}
HTREEITEM hItem = m_treeDeviceList.GetChildItem(hRoot);
while (hItem)
{
if (DEVICETYPE == m_treeDeviceList.GetItemData(hItem)/1000)
{
if (iDeviceIndex == (int)m_treeDeviceList.GetItemData(hItem)%1000)
{
return hItem;
}
}//end else if
hItem = m_treeDeviceList.GetNextVisibleItem(hItem);
}//end while
return NULL;
}
/*********************************************************
Function: GetCurDeviceIndex
Desc: check the channel, return device index related to this channel
Input:
Output:
Return:
**********************************************************/
int CClientDemoDlg::GetCurDeviceIndex()
{
if (m_iCurDeviceIndex < MAX_DEVICES && m_iCurDeviceIndex >= 0)
{
return m_iCurDeviceIndex;
}
AddLog(-1, OPERATION_SUCC_T, "please select a device at first!");
return -1;
}
/*********************************************************
Function: GetCurChanIndex
Desc: Get current channel serial number. When channel number < 64, this function is used.
Input:
Output:
Return:
**********************************************************/
int CClientDemoDlg::GetCurChanIndex()
{
if (m_iCurChanIndex >= 0 && m_iCurChanIndex < 512)
{
return m_iCurChanIndex;
}
//AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "please select a camera at first!");
return -1;
}
int CClientDemoDlg::GetCurChanIndexInTree()
{
if (m_iCurChanIndex >= 0 && m_iCurChanIndex < 512)
{
return m_iCurChanIndex;
}
//AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "please select a camera at first!");
return -1;
}
/*********************************************************
Function: OnBnClickedBtnElse
Desc: other operation
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnElse()
{
CMenu pMenu;
CRect rectBtnElse(0,0,0,0);
GetDlgItem(IDC_BTN_ELSE)->GetWindowRect(&rectBtnElse);
// int iDeviceIndex = GetCurDeviceIndex();
// if (iDeviceIndex == -1)
// {
// AfxMessageBox("请选中对应的设备!");
// return;
// }
if (!pMenu.LoadMenu(IDR_MENU_ELSE))
{
return;
}
// if (g_struDeviceInfo[iDeviceIndex].iDiskNum > 0)
// {//device local record on disk or other store devices
// pMenu.GetSubMenu(0)->EnableMenuItem(5, MF_BYPOSITION | MF_ENABLED);
// }
// else
// {
// pMenu.GetSubMenu(0)->EnableMenuItem(5, MF_BYPOSITION | MF_DISABLED | MF_GRAYED);
// }
pMenu.GetSubMenu(0)->TrackPopupMenu(TPM_LEFTALIGN, rectBtnElse.left,rectBtnElse.bottom,this);
}
/*********************************************************
Function: OnMenuRemoteKey
Desc: menu on remote key response function
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuRemoteKey()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
CDlgRemoteKey dlgRemoteKey;
dlgRemoteKey.m_lServerID = g_struDeviceInfo[iDeviceIndex].lLoginID;
dlgRemoteKey.DoModal();
}
/*********************************************************
Function: OnMenuCheckTime
Desc: menu on time checking response function
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuCheckTime()
{
CDlgCheckTime dlg;
dlg.DoModal();
}
/*********************************************************
Function: OnMenuWorkState
Desc: get device work sate
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnMenuWorkState()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
CDlgDeviceState dlg;
dlg.m_lLoginID = g_struDeviceInfo[iDeviceIndex].lLoginID;
dlg.DoModal();
}
/*********************************************************
Function: OnMenuLogSearch
Desc: dvr log search
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnMenuLogSearch()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
CDlgLogSearch dlg;
dlg.m_lLoginID = g_struDeviceInfo[iDeviceIndex].lLoginID;
dlg.DoModal();
}
/*********************************************************
Function: OnMenuDVRRecordStart
Desc: DVR local record
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuDVRRecordStart()
{
int iDeviceIndex = GetCurDeviceIndex();
int iChanIndex = GetCurChanIndex();
int iChanShowNum = 1;
int i= 0;
CString sTemp;
if (iDeviceIndex == -1)
{
return;
}
NET_DVR_WORKSTATE_V40 *pStruWorkStateV40 = new NET_DVR_WORKSTATE_V40;
if (pStruWorkStateV40 == NULL)
{
char szLan[128] = {0};
g_StringLanType(szLan, "申请内存失败", "alloc memory error");
AfxMessageBox(szLan);
return;
}
NET_DVR_GETWORKSTATE_COND struWorkStateCond = {0};
struWorkStateCond.dwSize = sizeof(NET_DVR_GETWORKSTATE_COND);
struWorkStateCond.byFindChanByCond = 0;
struWorkStateCond.byFindHardByCond = 0;
DWORD dwStatusChanIndex = 0;
DWORD dwList = 0;
if (!NET_DVR_GetDeviceConfig(g_struDeviceInfo[iDeviceIndex].lLoginID, NET_DVR_GET_WORK_STATUS,1,\
&struWorkStateCond,sizeof(NET_DVR_GETWORKSTATE_COND),&dwList,pStruWorkStateV40, sizeof(NET_DVR_WORKSTATE_V40)) ||(dwList != 0))
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GET_WORK_STATUS");
return;
}
if (iChanIndex == -1) // All Cameras
{
for (i=0; i<MAX_CHANNUM_V40; i++)
{
if (!g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable)
{
continue;
}
int iChannelNO = -1;
if (g_struDeviceInfo[iDeviceIndex].byMirrorChanNum&&iChanIndex >= MIRROR_CHAN_INDEX)
{
iChannelNO = g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].iChannelNO;
}
else
{
iChannelNO = g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChannelNO;
}
for (int j = 0;j<MAX_CHANNUM_V40;j++)
{
if (iChannelNO == pStruWorkStateV40->struChanStatic[j].dwChannelNo)
{
dwStatusChanIndex = j;
break;
}
}
if (pStruWorkStateV40->struChanStatic[dwStatusChanIndex].byRecordStatic == 0) //
{
if (NET_DVR_StartDVRRecord(g_struDeviceInfo[iDeviceIndex].lLoginID, iChannelNO, 0))
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "NET_DVR_StartDVRRecord %s", g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "NET_DVR_StartDVRRecord %s", g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
}
else if(pStruWorkStateV40->struChanStatic[dwStatusChanIndex].byRecordStatic == 1) //
{
if (NET_DVR_StopDVRRecord(g_struDeviceInfo[iDeviceIndex].lLoginID, iChannelNO))
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "NET_DVR_StopDVRRecord %s", g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
else
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "NET_DVR_StopDVRRecord %s", g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
}
}
}
}
else
{
i = iChanIndex;
if (g_struDeviceInfo[iDeviceIndex].byMirrorChanNum&&iChanIndex >= MIRROR_CHAN_INDEX)
{
iChanShowNum = g_struDeviceInfo[iDeviceIndex].struMirrorChan[iChanIndex].iChannelNO;
}
else
{
iChanShowNum = g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].iChannelNO;
}
for (int j = 0;j<MAX_CHANNUM_V40;j++)
{
if (iChanShowNum == pStruWorkStateV40->struChanStatic[j].dwChannelNo)
{
dwStatusChanIndex = j;
break;
}
}
if (pStruWorkStateV40->struChanStatic[dwStatusChanIndex].byRecordStatic == 0)
{
if (NET_DVR_StartDVRRecord(g_struDeviceInfo[iDeviceIndex].lLoginID, iChanShowNum, 0))
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "NET_DVR_StartDVRRecord %s", g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].chChanName);
char szLan[128] = {0};
g_StringLanType(szLan, "开始DVR本地录像成功", "Start Local Record successfully");
AfxMessageBox(szLan);
}
else
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "NET_DVR_StartDVRRecord %s", g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].chChanName);
}
}
else if (pStruWorkStateV40->struChanStatic[dwStatusChanIndex].byRecordStatic == 1)
{
if (NET_DVR_StopDVRRecord(g_struDeviceInfo[iDeviceIndex].lLoginID, iChanShowNum))
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "NET_DVR_StopDVRRecord %s", g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].chChanName);
char szLan[128] = {0};
g_StringLanType(szLan, "停止DVR本地录像成功", "Stop Local Record successfully");
AfxMessageBox(szLan);
}
else
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "NET_DVR_StopDVRRecord %s", g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].chChanName);
}
}
}
if (pStruWorkStateV40 != NULL)
{
delete pStruWorkStateV40 ;
pStruWorkStateV40 = NULL;
}
}
/*********************************************************
Function: ConfigAllHide
Desc: hide all configure box
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::ConfigAllHide()
{
m_dlgConfigAll->ShowWindow(SW_HIDE);
m_dlgRemoteCfg->ShowWindow(SW_HIDE);
m_dlgLocalCfg->ShowWindow(SW_HIDE);
m_dlgIPAccess->ShowWindow(SW_HIDE);
m_dlgHDConfig->ShowWindow(SW_HIDE);
// m_pStreamIDDlg->ShowWindow(SW_HIDE);
m_dlgBatchCfg->ShowWindow(SW_HIDE);
m_dlgProductCfg->ShowWindow(SW_HIDE);
m_dlgPlayBack->ShowWindow(SW_HIDE);
}
/*********************************************************
Function: OnCbnSelchangeComboNetdelay
Desc: set current network delay
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnCbnSelchangeComboNetdelay()
{
UpdateData(TRUE);
int iTmp = m_comboNetDelayBufNum.GetCurSel();
switch (iTmp)
{
case 0:
g_dlgOutput[m_iCurWndIndex].m_iNetDelayBufNum = 1;
break;
case 1:
g_dlgOutput[m_iCurWndIndex].m_iNetDelayBufNum = 3;
break;
case 2:
g_dlgOutput[m_iCurWndIndex].m_iNetDelayBufNum = 6;
break;
case 3:
g_dlgOutput[m_iCurWndIndex].m_iNetDelayBufNum = 15;
break;
default:
g_dlgOutput[m_iCurWndIndex].m_iNetDelayBufNum= 1;
break;
}
}
/*********************************************************
Function: CyclePlayAllDevicesLogined
Desc: 循环播放已经登陆的设备
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::CyclePlayAllDevicesLogined()
{
int i = 0;
int iPlayNum = 0;//current monitoring points that will be played
int iFirstIndex = -1;//current first monitoring point index
int iDeviceIndex = -1;
int iChanIndex = -1;
int iSurveillanceNumLeft = 0;
if (g_nSurveillanceTotalNum<=m_iCurWndNum)
{
return;
}
if (g_nSurveillanceTotalNum == g_iNextSurveillanceIndex) //turn to first page while cycle to last page
{
iPlayNum = m_iCurWndNum;
iFirstIndex = 0;
}
else
{
iPlayNum = g_nSurveillanceTotalNum - g_iNextSurveillanceIndex;
if (iPlayNum > m_iCurWndNum)
{
iPlayNum = m_iCurWndNum;
}
iFirstIndex = g_iNextSurveillanceIndex;
}
//stop all the windows which is playing
StopPlayAll();
for (i = 0; i < iPlayNum; i++)
{
if (i+iFirstIndex < MAX_PREVIEWS)
{
iDeviceIndex = g_struPlayAllInfo[i+iFirstIndex].iDeviceIndex;
iChanIndex = g_struPlayAllInfo[i+iFirstIndex].iChanIndex;
g_dlgOutput[i].StartPlay(&g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex], GetChanItem(iDeviceIndex, iChanIndex));
}
}
iSurveillanceNumLeft = g_nSurveillanceTotalNum - g_iNextSurveillanceIndex;
if (iSurveillanceNumLeft == 0)//restart afer a cycle
{
g_iNextSurveillanceIndex = m_iCurWndNum;
g_struLocalParam.bFrontPage = FALSE;
g_struLocalParam.bNextPage = TRUE;
}
else if (iSurveillanceNumLeft <= m_iCurWndNum)//last several monitoring points
{
g_iNextSurveillanceIndex = g_nSurveillanceTotalNum;
g_struLocalParam.bNextPage = FALSE;
g_struLocalParam.bFrontPage = TRUE;
}
else
{
g_struLocalParam.bFrontPage = TRUE;
g_struLocalParam.bNextPage = TRUE;
g_iNextSurveillanceIndex += m_iCurWndNum;
}
//UpdateData(FALSE);
}
/*********************************************************
Function: PlayNextPage
Desc: preview next pic in play list
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::PlayNextPage()
{
int iPlayNum = 0;
int i = 0;
int iDeviceIndex = -1;
int iChanIndex = -1;
int iSurveillanceLeftNum = 0;
if ((g_struLocalParam.bEnlarged)||(g_struLocalParam.bFullScreen))
{
if (g_struLocalParam.bFullScreen)
{
g_struLocalParam.bFullScreen = FALSE;
FullScreen(g_struLocalParam.bFullScreen);
}
g_struLocalParam.bEnlarged = FALSE;
ArrangeOutputs(m_iCurWndNum);
}
iSurveillanceLeftNum = g_nSurveillanceTotalNum - g_iNextSurveillanceIndex;
if (iSurveillanceLeftNum > m_iCurWndNum)
{// left monitoring points surpass current playing windows number
iPlayNum = m_iCurWndNum;
g_struLocalParam.bNextPage = TRUE;
}
else
{
iPlayNum = iSurveillanceLeftNum;
g_struLocalParam.bNextPage = FALSE;
}
StopPlayAll();//shut down previous page preview
for (i=0;i<iPlayNum;i++)
{
if (i+g_iNextSurveillanceIndex < MAX_PREVIEWS)
{
iDeviceIndex = g_struPlayAllInfo[i+g_iNextSurveillanceIndex].iDeviceIndex;
iChanIndex = g_struPlayAllInfo[i+g_iNextSurveillanceIndex].iChanIndex;
g_dlgOutput[i].StartPlay(&g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex], GetChanItem(iDeviceIndex, iChanIndex));
Sleep(100);
}
}
g_iNextSurveillanceIndex += iPlayNum;
g_struLocalParam.bFrontPage = TRUE;
ChangePlayBtnState();
UpdateData(FALSE);
}
/*********************************************************
Function: PlayFrontPage
Desc: play front group of monitoring points
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::PlayFrontPage()
{
int iPlayIndex = 0;
int i = 0;
int iDeviceIndex = -1;
int iChanIndex = -1;
if (g_iNextSurveillanceIndex <= m_iCurWndNum || m_iCurWndNum == 0)
{
return;
}
if ((g_struLocalParam.bEnlarged) || (g_struLocalParam.bFullScreen))
{
if (g_struLocalParam.bFullScreen)
{
g_struLocalParam.bFullScreen = FALSE;
FullScreen(g_struLocalParam.bFullScreen);
}
g_struLocalParam.bEnlarged = FALSE;
ArrangeOutputs(m_iCurWndNum); //while windos is zoomed, turn to next pic and restore original window number
}
if (g_iNextSurveillanceIndex < 2*m_iCurWndNum)
{
iPlayIndex = 0;//if front page is first index, set play index as 0
}
else
{
i = g_iNextSurveillanceIndex % m_iCurWndNum;
if (i == 0)
{
iPlayIndex = g_iNextSurveillanceIndex - 2*m_iCurWndNum ;
}
else
{
iPlayIndex = g_iNextSurveillanceIndex - m_iCurWndNum - i;
}
}
StopPlayAll();//stop all preview
for (i=0;i<m_iCurWndNum;i++)
{
if (i+iPlayIndex < MAX_PREVIEWS)
{
iDeviceIndex = g_struPlayAllInfo[i+iPlayIndex].iDeviceIndex;
iChanIndex = g_struPlayAllInfo[i+iPlayIndex].iChanIndex;
g_dlgOutput[i].StartPlay(&g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex], GetChanItem(iDeviceIndex, iChanIndex));
Sleep(100);
}
}
if (g_iNextSurveillanceIndex <= 2*m_iCurWndNum)
{
g_iNextSurveillanceIndex = m_iCurWndNum;
g_struLocalParam.bFrontPage = FALSE; //no front page
}
else
{
i = g_iNextSurveillanceIndex % m_iCurWndNum;
if (i == 0)
{
g_iNextSurveillanceIndex -= m_iCurWndNum;
}
else
{
g_iNextSurveillanceIndex -= i;
}
g_struLocalParam.bFrontPage = TRUE;
}
g_struLocalParam.bNextPage = TRUE;
}
/*********************************************************
Function: CyclePause
Desc: suspend or continue cycle
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::CyclePause()
{
if (!g_struLocalParam.bPaused)
{
g_struLocalParam.bPaused = TRUE;
if (g_pCycleTimer != NULL)
{
KillTimer(CYCLE_PREVIEW_TIMER);
g_pCycleTimer = NULL;
}
}
else//continue cycle
{
CyclePlayAllDevicesLogined();
if (g_pCycleTimer == NULL)
{
g_pCycleTimer = SetTimer(CYCLE_PREVIEW_TIMER, g_struLocalParam.iCycleTime*1000,NULL);
}
g_struLocalParam.bPaused = FALSE;
}
ChangePlayBtnState();
}
/*********************************************************
Function: OnMove
Desc: dealing with preview and backplay in double screen
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMove(int x, int y)
{
CDialog::OnMove(x, y);
GetWindowRect(&g_rcWindow);
if (g_rcWindow.left < 0)
{
return;
}
int iTmpMonitorNum = 0;
int i=0;
//#if (WINVER > 0x0400)
DWORD dwNewDeviceNum = 0;
LONG lTmpHandle = -1;
if (((DWORD)g_rcWindow.right + (DWORD)g_rcWindow.left > (DWORD)2 * g_iCurScreenWidth )||((DWORD)g_rcWindow.top + (DWORD)g_rcWindow.bottom > (DWORD)2 * g_iCurScreenHeight))
{
dwNewDeviceNum = 1;
}
else
{
dwNewDeviceNum = 0;
}
if (dwNewDeviceNum != g_dwOldDeviceNum)
{
if (m_iMainType == PREVIEW_T)
{
int iPlayNum = 0;
// if (g_nSurveillanceTotalNum == 0)
// {
// return;
// }
if (g_nSurveillanceTotalNum < m_iCurWndNum)
{
iPlayNum = g_nSurveillanceTotalNum;
}
else
{
iPlayNum = g_nSurveillanceTotalNum;
}
iTmpMonitorNum = PlayM4_GetDDrawDeviceTotalNums();
if (iTmpMonitorNum >= 1)
{
for (i=0; i<m_iCurWndNum; i++)
{
if (g_dlgOutput[i].m_lPlayHandle>=0)
{
LONG lPort = -1;
if (g_dlgOutput[i].m_lPort >= 0)
{
lPort = g_dlgOutput[i].m_lPort;
}
else
{
lPort = NET_DVR_GetRealPlayerIndex(g_dlgOutput[i].m_lPlayHandle);
}
if (lPort < 0)
{
return;
}
if (PlayM4_SetDDrawDevice(lPort, dwNewDeviceNum + 1))//
{
AddLog(m_iCurDeviceIndex, PLAY_SUCC_T, "PlayM4_SetDDrawDevice output[%d]", i);
}
else
{
AddLog(m_iCurDeviceIndex, PLAY_FAIL_T, "PlayM4_SetDDrawDevice output[%d] err[%d]", i, PlayM4_GetLastError(NET_DVR_GetRealPlayerIndex(g_dlgOutput[i].m_lPlayHandle)));
}
}
}
}
}
else if (m_iMainType == PLAY_BACK_T)
{
switch (m_dlgPlayBack->m_iPlayBackType)
{
case 0://remote file
if (m_dlgPlayBack->m_dlgPlayRemoteFile.m_nPlayHandle == -1)
{
return;
}
iTmpMonitorNum = PlayM4_GetDDrawDeviceTotalNums();
lTmpHandle = NET_DVR_GetPlayBackPlayerIndex(m_dlgPlayBack->m_dlgPlayRemoteFile.m_nPlayHandle);
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "lTmpHandle is %d", lTmpHandle);
PlayM4_SetDDrawDevice(lTmpHandle, dwNewDeviceNum + 1);
g_dwOldDeviceNum = dwNewDeviceNum;
break;
case 1://local
iTmpMonitorNum = PlayM4_GetDDrawDeviceTotalNums();
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "iTmpMonitorNum is %d", iTmpMonitorNum);
PlayM4_SetDDrawDevice(99, dwNewDeviceNum + 1);
break;
case 2://play back by time
if (m_dlgPlayBack->m_dlgPlayRemoteTime.m_lPlayHandle == -1)
{
return;
}
//nVal = NET_DVR_GetDDrawDeviceTotalNums();
iTmpMonitorNum = PlayM4_GetDDrawDeviceTotalNums();
lTmpHandle = NET_DVR_GetPlayBackPlayerIndex(m_dlgPlayBack->m_dlgPlayRemoteTime.m_lPlayHandle);
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "lTmpHandle is %d", lTmpHandle);
//NET_DVR_SetDDrawDevice(temp, dwNewDeviceNum + 1);
PlayM4_SetDDrawDevice(lTmpHandle, dwNewDeviceNum + 1);
break;
default:
break;
}
}
g_dwOldDeviceNum = dwNewDeviceNum;
}
//#endif
if (g_struLocalParam.bUseCard)
{
NET_DVR_RefreshSurface_Card();
}
UpdateWindow();
}
/*********************************************************
Function: OnBnClickedBtnConfig
Desc: configure operation
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnConfig()
{
if (m_iMainType != CONFIG_ALL_T)
{
m_iMainType = CONFIG_ALL_T;
PreviewReferShow(FALSE);
ConfigAllHide();
m_dlgPlayBack->HideAll();
InitConfigAllRefer();
}
}
/*********************************************************
Function: InitConfigAllRefer
Desc: initialize interface dealing related to configuration
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::InitConfigAllRefer()
{
if (!m_dlgConfigAll->IsWindowVisible())
{
CRect rectConfig(0,0,0,0);
rectConfig.top = m_iFunBtnHeight-2;
rectConfig.left = m_iTreeWidth-2;//-2 cover preview box
rectConfig.right = DEMO_FULL_WIDTH - m_iRightWidth ;
rectConfig.bottom = DEMO_FULL_HEIGHT - m_iListLogHeight;//+4
m_dlgLocalCfg->MoveWindow(&rectConfig,TRUE);
m_dlgLocalCfg->ShowWindow(SW_HIDE);
m_dlgRemoteCfg->MoveWindow(&rectConfig,TRUE);
m_dlgRemoteCfg->ShowWindow(SW_SHOW);
m_dlgIPAccess->MoveWindow(&rectConfig,TRUE);
m_dlgIPAccess->ShowWindow(SW_SHOW);
m_dlgHDConfig->MoveWindow(&rectConfig,TRUE);
m_dlgHDConfig->ShowWindow(SW_SHOW);
m_dlgBatchCfg->MoveWindow(&rectConfig,TRUE);
m_dlgBatchCfg->ShowWindow(SW_SHOW);
m_dlgConfigAll->MoveWindow(&m_rectRightArea,TRUE);
m_dlgConfigAll->ShowWindow(SW_SHOW);
m_dlgConfigAll->ConfigWndUpdate();
}
}
/*********************************************************
Function: OnBnClickedBtnPlayback
Desc: switch to backplay interface
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnPlayback()
{
if (m_iMainType != PLAY_BACK_T)
{
m_iMainType = PLAY_BACK_T;
ListRestore();
PreviewReferShow(FALSE);
ConfigAllHide();
InitPlayBackRefer();
}
}
/*********************************************************
Function: InitPlayBackRefer
Desc: initialize backplay interface operation
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::InitPlayBackRefer()
{
if (!m_dlgPlayBack->IsWindowVisible())
{
CRect rectPlayBack(0,0,0,0);
rectPlayBack.top = m_iFunBtnHeight-2;
rectPlayBack.left = m_iTreeWidth-2;//-2 cover preview box
rectPlayBack.right = DEMO_FULL_WIDTH;
rectPlayBack.bottom = DEMO_FULL_HEIGHT - m_iListLogHeight;//+4
m_dlgPlayBack->MoveWindow(&rectPlayBack,TRUE);
m_dlgPlayBack->PlayBackWinUpdate();
m_dlgPlayBack->ShowWindow(SW_SHOW);
}
}
/*********************************************************
Function: OnBnClickedBtnRecord
Desc: manually record uner preview interface
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnRecord()
{
if (g_struLocalParam.bAutoRecord)
{
OnTimer(AUTORECORD_TIMER);
return;
}
if ((g_dlgOutput[m_iCurWndIndex].m_lPlayHandle >= 0) && (!g_dlgOutput[m_iCurWndIndex].m_bLocalManualRec))
{
if (MakeRecDir())
{
g_dlgOutput[m_iCurWndIndex].StartLocalRecord();
}
NET_DVR_I_FRAME struIFrame;
memset(&struIFrame, 0, sizeof(struIFrame));
struIFrame.dwSize = sizeof(NET_DVR_I_FRAME);
struIFrame.dwChan = g_dlgOutput[m_iCurWndIndex].m_lChannel;
//增加数组最大长度异常判断,解决异常崩溃
if (g_dlgOutput[m_iCurWndIndex].m_lChannel - MIRROR_CHAN_INDEX > 16)
{
return;
}
struIFrame.byStreamType = g_struDeviceInfo[g_dlgOutput[m_iCurWndIndex].m_struChanInfo.iDeviceIndex].struMirrorChan[g_dlgOutput[m_iCurWndIndex].m_lChannel - MIRROR_CHAN_INDEX].dwStreamType;
if (!NET_DVR_RemoteControl(g_struDeviceInfo[g_dlgOutput[m_iCurWndIndex].m_struChanInfo.iDeviceIndex].lLoginID, NET_DVR_MAKE_I_FRAME, &struIFrame, sizeof(struIFrame)))
{
g_pMainDlg->AddLog(g_dlgOutput[m_iCurWndIndex].m_struChanInfo.iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_MAKE_I_FRAME %s", g_struDeviceInfo[g_dlgOutput[m_iCurWndIndex].m_struChanInfo.iDeviceIndex].struMirrorChan[g_dlgOutput[m_iCurWndIndex].m_lChannel - MIRROR_CHAN_INDEX].chChanName);
}
}
else if (g_dlgOutput[m_iCurWndIndex].m_bLocalManualRec)
{
g_dlgOutput[m_iCurWndIndex].StopLocalRecord();
g_dlgOutput[m_iCurWndIndex].m_bSaveHead = FALSE;
}
}
/*********************************************************
Function: MakeRecDir
Desc: create record directory
Input:
Output:
Return: TRUE,create successful;FALSE,create failed;
**********************************************************/
BOOL CClientDemoDlg::MakeRecDir()
{
CString sTemp;
DWORD dwDirAttr;
CTime time = CTime::GetCurrentTime();
char szLan[256] = {0};
//m_iCurRecDriver = g_pMainDlg->m_cHardDriver[g_struLocalParam.iStartRecordDriver];
sTemp.Format("%c:\\mpeg4record\\", m_iCurRecDriver);
dwDirAttr = GetFileAttributes(sTemp);
if ((dwDirAttr == -1) || !(dwDirAttr & FILE_ATTRIBUTE_DIRECTORY))
{
if (!CreateDirectory(sTemp, NULL))
{
g_StringLanType(szLan, "创建年月日目录失败", "create year-month-day directory failed");
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, szLan);
AfxMessageBox(szLan);
return FALSE;
}
}
else
{
sTemp.Format("%c:\\mpeg4record\\%4d-%02d-%02d\\", m_iCurRecDriver, time.GetYear(), time.GetMonth(), time.GetDay());
dwDirAttr=GetFileAttributes(sTemp);
if ((dwDirAttr == -1) || !(dwDirAttr & FILE_ATTRIBUTE_DIRECTORY))
{
if (!CreateDirectory(sTemp, NULL))
{
g_StringLanType(szLan, "创建年月日目录失败", "create year-month-day directory failed");
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, szLan);
AfxMessageBox(szLan);
return FALSE;
}
else
{
sprintf(g_struLocalParam.chClientRecordPath, "%s", sTemp.GetBuffer(0));
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "create %c:\\mpeg4record\\%4d-%02d-%02d", m_iCurRecDriver, time.GetYear(), time.GetMonth(), time.GetDay());
return TRUE;
}
}
else
{
sprintf(g_struLocalParam.chClientRecordPath, "%s", sTemp.GetBuffer(0));
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "create directory:%s", sTemp.GetBuffer(0));
return TRUE;
}
}
sTemp.Format("%c:\\mpeg4record\\%4d-%02d-%02d\\",m_iCurRecDriver, time.GetYear(), time.GetMonth(), time.GetDay());
if (!CreateDirectory(sTemp, NULL))
{
return FALSE;
}
sprintf(g_struLocalParam.chClientRecordPath, "%s", sTemp.GetBuffer(0));
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "create %c:\\mpeg4record first, then create %4d-%02d-%02d", m_iCurRecDriver, time.GetYear(), time.GetMonth(), time.GetDay());
return TRUE;
}
/*********************************************************
Function: IsDiskFull
Desc: check disk full
Input:
Output:
Return: TRUE,disk is full;FALSE,disk is not full
**********************************************************/
BOOL CClientDemoDlg::IsDiskFull()
{
int i;
ULARGE_INTEGER FreeSpace,CallerSpace,TotalSpace;
CString csRecRootPath;
for (i = g_struLocalParam.iStartRecordDriver; i < g_struLocalParam.iEndRecordDriver + 1; i++)
{
csRecRootPath.Format("%c%s",m_cHardDriver[i],":\\"); //start from hard driver
GetDiskFreeSpaceEx(csRecRootPath,&CallerSpace,&TotalSpace,&FreeSpace);
if (CallerSpace.QuadPart > MINSPACE)
{
m_iCurRecDriver = m_cHardDriver[i];
g_struLocalParam.bAllDiskFull = FALSE;
return FALSE;
}
}
g_struLocalParam.bAllDiskFull = TRUE;
return TRUE;
}
/*********************************************************
Function: DeleteClientRecordFile
Desc: delete local record file
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::DeleteClientRecordFile()
{
CFileFind cFile,cFileMp4;
BOOL bFineDir,bFileFind;
CString sDeleteDir,sTempDelete;
CString sDir;
CString sDate;
CString sFileName;
CTime time,temptime;
int i = 0;
// int iDelNum = 0;
sDeleteDir.Format("0000-00-00");
sTempDelete.Format("3000-00-00");
time=CTime::GetCurrentTime();
for (i = g_struLocalParam.iStartRecordDriver; i < (g_struLocalParam.iEndRecordDriver + 1); i++)
{
sDir.Format("%c:\\mpeg4record\\*.*",m_cHardDriver[i]);
bFineDir=cFile.FindFile(sDir);//judge whether the current directory has files
while (bFineDir)
{
bFineDir=cFile.FindNextFile();
if (cFile.IsDots())//'.'mean current directory, & '..' means up directory.
{
continue;
}
if (cFile.IsDirectory())
{
if (cFile.GetFileName()==_T("download"))//not download record
{
continue;
}
if (cFile.GetFileName()==_T("alarm"))//not alarm record
{
continue;
}
sFileName.Format("%c:\\mpeg4record\\%s\\*.mp4", m_cHardDriver[i], cFile.GetFileName().GetBuffer(0));
bFileFind=cFileMp4.FindFile(sFileName);
if (!bFileFind)
{
RemoveDirectory(cFile.GetFilePath());
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, cFile.GetFilePath().GetBuffer(0));
}
while (bFileFind)
{
bFileFind=cFileMp4.FindNextFile();
if (cFile.IsDots())
{
continue;
}
cFileMp4.GetCreationTime(temptime);
if (temptime<time)
{
time=temptime;
sTempDelete.Format("%s",cFileMp4.GetFilePath().GetBuffer(0));
}
}
}
}
}
sFileName.Format("%s",sTempDelete.GetBuffer(0));
sTempDelete.Format("delete[%s]",sFileName.GetBuffer(0));
if (!DeleteFile(sFileName))
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T,sTempDelete.GetBuffer(0));
for (i = 0; i < MAX_OUTPUTS; i++)
{
if ((g_dlgOutput[i].m_lPlayHandle >= 0) || (g_dlgOutput[i].m_bLocalManualRec))
{
g_dlgOutput[i].StopLocalRecord();
}
}
char szLan[128] = {0};
g_StringLanType(szLan, "硬盘容量不足,自动删除文件失败,请清理硬盘后重新开始录像!",\
"Lack of hard drive capacity, automatic delete file failed, please clean up after the hard disk to start record!");
AfxMessageBox(szLan);
}
else
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, sTempDelete.GetBuffer(0));
//iDelNum++;
}
}
/*********************************************************
Function: OnBnClickedBtnManage
Desc: advanded management operantion
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnManage()
{
CMenu pMenu;
CRect cRectBtnManage(0,0,0,0);
//GetCursorPos(&pt);
GetDlgItem(IDC_BTN_MANAGE)->GetWindowRect(&cRectBtnManage);
//select first node or blank
if (!pMenu.LoadMenu(IDR_MENU_MANAGE))
{
return;
}
pMenu.GetSubMenu(0)->TrackPopupMenu(TPM_LEFTALIGN,cRectBtnManage.left ,cRectBtnManage.bottom,this);
}
/*********************************************************
Function: OnMenuUpgrade
Desc: device upgrade
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuUpgrade()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
int iChanIndex = GetCurChanIndex();
if (iChanIndex < 0)
{
iChanIndex = 0;
}
CDlgUpgrade dlgUpgrade;
dlgUpgrade.m_lServerID = g_struDeviceInfo[iDeviceIndex].lLoginID;
dlgUpgrade.m_lChannel = iChanIndex + g_struDeviceInfo[iDeviceIndex].iStartChan;
dlgUpgrade.m_iDeviceIndex = iDeviceIndex;
dlgUpgrade.DoModal();
}
/*********************************************************
Function: OnMenuReboot
Desc: device reboot
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuReboot()
{
int iDeviceIndex = GetCurDeviceIndex();
int i = 0;
char szLan[128] = {0};
if (iDeviceIndex == -1)
{
return;
}
g_StringLanType(szLan, "确定要重启设备?", "Sure to reboot device?");
if (IDOK!=MessageBox(szLan, "Warning",IDOK))
{
return;
}
if (NET_DVR_RebootDVR(g_struDeviceInfo[iDeviceIndex].lLoginID))
{
g_struDeviceInfo[iDeviceIndex].bAlarm = FALSE;
g_struDeviceInfo[iDeviceIndex].bPlayDevice = FALSE;
g_struDeviceInfo[iDeviceIndex].bVoiceTalk = FALSE;
// g_struDeviceInfo[iDeviceIndex].dwImageType = DEVICE_LOGOUT;
for (i = 0; i<MAX_CHANNUM_V30; i++)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = FALSE;
}
AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_RebootDVR");
g_StringLanType(szLan, "设备正在重启", "Device is rebooting");
AfxMessageBox(szLan);
}
else
{
AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_RebootDVR");
g_StringLanType(szLan, "设备重启失败", "Reboot device failed");
AfxMessageBox(szLan);
}
}
/*********************************************************
Function: OnMenuHDFormat
Desc: disk format
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuHDFormat()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
CDlgFormatHD dlgFormatDisk;
dlgFormatDisk.m_iDeviceIndex = iDeviceIndex;
dlgFormatDisk.m_dwDiskNum = g_struDeviceInfo[iDeviceIndex].iDiskNum;
dlgFormatDisk.DoModal();
}
/*********************************************************
Function: OnMenuPoweroff
Desc: power off
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuPoweroff()
{
int iDeviceIndex = GetCurDeviceIndex();
char szLan[128] = {0};
if (iDeviceIndex == -1)
{
return;
}
g_StringLanType(szLan, "确定要关闭设备?", "Sure to shut down device?");
if (IDOK!=MessageBox(szLan, "Warning",IDOK))
{
return;
}
if (NET_DVR_ShutDownDVR(g_struDeviceInfo[iDeviceIndex].lLoginID))
{
AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_ShutDownDVR");
g_StringLanType(szLan, "设备正在关机", "Device is shutting down");
AfxMessageBox(szLan);
}
else
{
AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_ShutDownDVR");
g_StringLanType(szLan, "设备关机失败", "Shut down device failed");
AfxMessageBox(szLan);
}
}
/*********************************************************
Function: OnMenuFortify
Desc: switch between setting guard and removing guard
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuFortify()
{
CDlgFortify dlg;
int i = 0;
dlg.DoModal();
if (dlg.m_bFortify)
{
for (i=0; i<MAX_DEVICES; i++)
{
if (g_struDeviceInfo[i].lLoginID >= 0)
{
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_DEVICE_ITEM_IMAGE, WPARAM(GetDeviceItem(i)), LPARAM(i));
}
}
}
}
/*********************************************************
Function: OnMenuVoiceTalk
Desc: start or stop voice talk
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuVoiceTalk()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
CDlgVoiceTalk dlg;
dlg.m_dwDeviceIndex = iDeviceIndex;
dlg.DoModal();
}
/*********************************************************
Function: OnMenuSerialTrans
Desc: transport the data on serial ports
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnMenuSerialTrans()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
CTransparentTrans dlg;
dlg.m_iDeviceIndex = iDeviceIndex;
dlg.DoModal();
}
void CClientDemoDlg::OnMenuDebug()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
CDlgDebug dlg;
dlg.m_iDevIndex = iDeviceIndex;
dlg.m_lServerID = g_struDeviceInfo[iDeviceIndex].lLoginID;
dlg.DoModal();
}
void CClientDemoDlg::OnMenuUploadCalibrationFile()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex == -1)
{
return;
}
CDlgUploadCalibrationFile dlg;
dlg.m_iDevIndex = iDeviceIndex;
dlg.m_lUserID = g_struDeviceInfo[iDeviceIndex].lLoginID;
dlg.DoModal();
}
void CClientDemoDlg::OnMenuIperf()
{
CDlgIperf dlg;
dlg.DoModal();
}
void CClientDemoDlg::OnMenuCompleteRestore()
{
int iDeviceIndex = GetCurDeviceIndex();
char szLan[128] = {0};
if (iDeviceIndex == -1)
{
return;
}
int iChanIndex = GetCurChanIndex();
if (iChanIndex < 0)
{
iChanIndex = 0;
}
g_StringLanType(szLan, "确定要完全恢复默认参数?", "Sure to Complete restore the default parameters?");
if (IDOK!=MessageBox(szLan, "Warning",IDOK))
{
return;
}
if (g_struDeviceInfo[iDeviceIndex].lLoginID<0)
{
return;
}
NET_DVR_COMPLETE_RESTORE_INFO m_struRestoreInfo = {0};
m_struRestoreInfo.dwSize = sizeof(NET_DVR_COMPLETE_RESTORE_INFO);
m_struRestoreInfo.dwChannel = iChanIndex + g_struDeviceInfo[iDeviceIndex].iStartChan;
if (!NET_DVR_RemoteControl(g_struDeviceInfo[iDeviceIndex].lLoginID, NET_DVR_COMPLETE_RESTORE_CTRL, &m_struRestoreInfo, sizeof(NET_DVR_COMPLETE_RESTORE_INFO)))
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_RemoteControl NET_DVR_COMPLETE_RESTORE_CTRL ");
g_StringLanType(szLan, "恢复默认值失败", "Restore the default parameters failed");
AfxMessageBox(szLan);//DS9000 restore configure, reboot auto
}
else
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_RemoteControl NET_DVR_COMPLETE_RESTORE_CTRL");
g_StringLanType(szLan, "恢复默认值成功,请重启", "Restore the default parameters successfully");
AfxMessageBox(szLan);
}
}
/*********************************************************
Function: OnMenuDefaultConfig
Desc: restore the default configure of the device
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnMenuDefaultConfig()
{
int iDeviceIndex = GetCurDeviceIndex();
char szLan[128] = {0};
if (iDeviceIndex == -1)
{
return;
}
g_StringLanType(szLan, "确定要恢复默认参数?", "Sure to restore the default parameters?");
if (IDOK!=MessageBox(szLan, "Warning",IDOK))
{
return;
}
if (g_struDeviceInfo[iDeviceIndex].lLoginID<0)
{
return;
}
if (NET_DVR_RestoreConfig(g_struDeviceInfo[iDeviceIndex].lLoginID))
{
AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_RestoreConfig");
g_StringLanType(szLan, "恢复默认值成功,请重启", "Restore the default parameters successfully");
AfxMessageBox(szLan);//DS9000 restore configure, reboot auto
}
else
{
AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_RestoreConfig");
g_StringLanType(szLan, "恢复默认值失败", "Restore the default parameters failed");
AfxMessageBox(szLan);
}
}
/*********************************************************
Function: OnMenuConfigFlash
Desc: set or get the configure file
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnMenuConfigFlash()
{
CDlgConfigFlash dlg;
dlg.DoModal();
}
/*********************************************************
Function: OnMenuImExportIPCCfgFile
Desc: set or get the configure file
Input: none
Output: none
Return: none
**********************************************************/
// void CClientDemoDlg::OnMenuImExportIPCCfgFile()
// {
// DlgImexporIPCCfgFile dlg;
// dlg.DoModal();
// }
/*********************************************************
Function: OnMenuTalkMR
Desc: voice media redirect
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnMenuTalkMR()
{
CDlgTalkMREx dlg;
int iDevIndex = GetCurDeviceIndex();
if (iDevIndex < 0)
{
return;
}
dlg.m_iDeviceIndex = iDevIndex;
dlg.DoModal();
}
/*********************************************************
Function: OnBnClickedBtnPictureSnatch
Desc: capture pic in bmp under preview
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::PictureSnatchInSide()
{
int i = m_iCurWndIndex;
if (g_dlgOutput[i].m_lPlayHandle < 0)
{
return;
}
char cFilename[256];
CString sTemp;
CTime time = CTime::GetCurrentTime();
sTemp.Format("%s\\", g_struLocalParam.chPictureSavePath);
DWORD dwRet = GetFileAttributes(sTemp);
if ((dwRet == -1) || !(dwRet & FILE_ATTRIBUTE_DIRECTORY))
{
CreateDirectory(sTemp, NULL);
}
PCHANNEL_INFO pChanInfo = &(g_dlgOutput[i].m_struChanInfo);
sprintf(cFilename, "%s\\Preview_%s_%02d_%4d%02d%02d_%02d%02d%02d_%d.bmp", \
g_struLocalParam.chPictureSavePath, g_struDeviceInfo[pChanInfo->iDeviceIndex].chDeviceIPInFileName, \
g_struDeviceInfo[pChanInfo->iDeviceIndex].iStartChan+pChanInfo->iChanIndex, \
time.GetYear(), time.GetMonth(), time.GetDay(), time.GetHour(), time.GetMinute(), time.GetSecond(), GetTickCount());
if (g_struLocalParam.bUseCard)
{
if (NET_DVR_CapturePicture_Card(g_dlgOutput[i].m_lPlayHandle, cFilename))
{
CString sTemp;
sTemp.Format("Capture picture succeed %s!",cFilename);
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, sTemp.GetBuffer(0));
return;
}
else
{
AfxMessageBox("Failed to capture picture!");
}
}
else
{
if (NET_DVR_CapturePicture(g_dlgOutput[i].m_lPlayHandle, cFilename))
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "NET_DVR_CapturePicture[%s]", cFilename);
}
else if (NET_DVR_GetLastError() == NET_DVR_NONBLOCKING_CAPTURE_NOTSUPPORT)
{
if (NET_DVR_CapturePictureBlock(g_dlgOutput[i].m_lPlayHandle, cFilename, 500))
{
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "NET_DVR_CapturePictureBlock[%s]", cFilename);
}
else
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "NET_DVR_CapturePictureBlock[%s]", cFilename);
char szLan[128] = { 0 };
g_StringLanType(szLan, "bmp抓图失败", "bmp snatch failed");
AfxMessageBox(szLan);
}
}
else
{
AddLog(m_iCurDeviceIndex, OPERATION_FAIL_T, "NET_DVR_CapturePicture[%s]", cFilename);
char szLan[128] = {0};
g_StringLanType(szLan, "bmp抓图失败", "bmp snatch failed");
AfxMessageBox(szLan);
}
}
}
void CClientDemoDlg::OnBnClickedBtnPictureSnatch()
{
if (g_bInSide)
{
PictureSnatchInSide();
return;
}
if (g_struLocalParam.bUseCard)
{
g_dlgOutput[m_iCurWndIndex].CapturePicture();
}
g_bCapPic[m_iCurWndIndex] = TRUE;
}
/*********************************************************
Function: OnMenuBroadCast
Desc: audio broadcast deal
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnMenuBroadCast()
{
CBroadCast dlg;
dlg.DoModal();
}
/*********************************************************
Function: OnBnClickedBtnLogClear
Desc: clear up all log items in list
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnLogClear()
{
char szLan[128] = {0};
g_StringLanType(szLan, "确定清空列表吗?", "Sure to clear list?");
if (IDOK==MessageBox(szLan,"Warning",IDOK))
{
if (m_iSelListType == 1)
{
m_listAlarmInfo.DeleteAllItems();
for (int i = 0; i< MAX_DEVICES; i++)
{
if (g_struDeviceInfo[i].lFortifyHandle >= 0)
{
ManualClearAlarm(i, -1);
}
}
}
else
{
m_listAllLog.DeleteAllItems();
}
}
}
/*********************************************************
Function: OnBnClickedBtnLogSave
Desc: save all the log items in list
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnLogSave()
{
CString csFileName;
CTime time;
if (g_struLocalParam.bAutoSaveLog)
{
return;
}
int i;
CString sTemp;
CStdioFile myFile;
int iCount = 0;
time = CTime::GetCurrentTime();
if (m_iSelListType == 1)
{
iCount = m_listAlarmInfo.GetItemCount();
csFileName.Format("%s\\AlarmInfo_%4d%02d%02d_%02d%02d%02d.txt",\
g_struLocalParam.chRemoteCfgSavePath, time.GetYear(), time.GetMonth(),\
time.GetDay(), time.GetHour(), time.GetMinute(), time.GetSecond());
}
else
{
iCount = m_listAllLog.GetItemCount();
csFileName.Format("%s\\LogFile_%4d%02d%02d_%02d%02d%02d.txt",\
g_struLocalParam.chRemoteCfgSavePath, time.GetYear(), time.GetMonth(),\
time.GetDay(), time.GetHour(), time.GetMinute(), time.GetSecond());
}
if (iCount <= 0)
{
return;
}
if (myFile.Open(csFileName, CFile::modeCreate|CFile::modeWrite) == FALSE)
{
char szLan[128] = {0};
g_StringLanType(szLan, "文件创建失败", "create file failed");
AfxMessageBox(szLan);
return;
}
for (i = 0; i < iCount; i++)
{
if (m_iSelListType == 1)
{
sTemp.Format("%s\t%s\n", m_listAllLog.GetItemText(i, 1).GetBuffer(0),\
m_listAllLog.GetItemText(i, 2).GetBuffer(0));
}
else
{
sTemp.Format("%s\t%s\t%s\t%s\r\n", m_listAllLog.GetItemText(i, 1).GetBuffer(0),\
m_listAllLog.GetItemText(i, 2).GetBuffer(0), m_listAllLog.GetItemText(i, 3).GetBuffer(0),\
m_listAllLog.GetItemText(i, 4).GetBuffer(0));
}
myFile.WriteString(sTemp);
}
myFile.Close();
}
/*********************************************************
Function: ManualClearAlarm
Desc: clear alarm manually
Input: iDeviceIndex,device index; iChanIndex,channel index, -1 clear all channel;
Output:
Return:
**********************************************************/
void CClientDemoDlg::ManualClearAlarm(int iDeviceIndex, int iChanIndex)
{
CString csTemp;
int i=0;
if (iChanIndex == -1)
{//select device node
//give out hints while switch alarm logo
if (g_struDeviceInfo[iDeviceIndex].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].bAlarm = FALSE;
::PostMessage(m_hWnd, WM_CHANGE_DEVICE_ITEM_IMAGE, WPARAM(GetDeviceItem(iDeviceIndex)), LPARAM(iDeviceIndex));
}
for (i=0; i<MAX_CHANNUM_V30; i++)
{
if (g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable && g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = FALSE;
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "ch[%d] clear alarm status", i+g_struDeviceInfo[iDeviceIndex].iStartChan);
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
}
}
}
else
{
if (g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].bAlarm)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].bAlarm = FALSE;
AddLog(m_iCurDeviceIndex, OPERATION_SUCC_T, "ch[%d] clear alarm status", iChanIndex+g_struDeviceInfo[iDeviceIndex].iStartChan);
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(m_iCurDeviceIndex), LPARAM(iChanIndex));
}
}
}
/*********************************************************
Function: OnBnClickedBtnLogConfig
Desc: local log configuration
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnLogConfig()
{
CDlgLocalLogConfig dlg;
dlg.DoModal();
}
/*********************************************************
Function: IsCurDevMatDec
Desc: check current device is decoder
Input:
Output:
Return:
**********************************************************/
BOOL CClientDemoDlg::IsCurDevMatDec(int iDeviceIndex)
{
BOOL bRet = FALSE;
if (iDeviceIndex != -1)
{
if (DEC == g_struDeviceInfo[iDeviceIndex].iDeviceType||DEC_MAT == g_struDeviceInfo[iDeviceIndex].iDeviceType || \
DS_6504D_B10 == g_struDeviceInfo[iDeviceIndex].iDeviceType||DS630X_D == g_struDeviceInfo[iDeviceIndex].iDeviceType
|| DS640X_HD == g_struDeviceInfo[iDeviceIndex].iDeviceType \
|| DS_B10_XY == g_struDeviceInfo[iDeviceIndex].iDeviceType || DS610X_D == g_struDeviceInfo[iDeviceIndex].iDeviceType)
{
bRet = TRUE;
}
}
return TRUE;
}
/*********************************************************
Function: IsNeedRebootDevType
Desc: some devices(8-ch,16-ch 7000,8000HS_S)need to reboot after modifying resolution
Input:
Output:
Return:
**********************************************************/
BOOL CClientDemoDlg::IsNeedRebootDevType(void)
{
int iDevIndex = GetCurDeviceIndex();
BOOL bRet = FALSE;
if (iDevIndex != -1)
{
if ((DVR_HS_S == g_struDeviceInfo[iDevIndex].iDeviceType)\
||(( DVR_7000H== g_struDeviceInfo[iDevIndex].iDeviceType) && (g_struDeviceInfo[iDevIndex].iDeviceChanNum == 8))\
||(( DVR_7000H== g_struDeviceInfo[iDevIndex].iDeviceType) && (g_struDeviceInfo[iDevIndex].iDeviceChanNum == 16)))
{
bRet = TRUE;
}
}
return bRet;
}
/*********************************************************
Function: OnNMClickListAllLog
Desc: Copy the contents to the clipboard
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnNMClickListAllLog(NMHDR *pNMHDR, LRESULT *pResult)
{
int iItemSel = 0;
CString csTxt;
POSITION iPos = m_listAllLog.GetFirstSelectedItemPosition();
if (iPos == NULL)
{
return;
}
iItemSel = m_listAllLog.GetNextSelectedItem(iPos);
csTxt.Format("%s",m_listAllLog.GetItemText(iItemSel,3));
if (OpenClipboard())
{
HGLOBAL clipbuffer;
char * buffer;
EmptyClipboard();
clipbuffer = GlobalAlloc(GMEM_DDESHARE, csTxt.GetLength()+1);
buffer = (char*)GlobalLock(clipbuffer);
strcpy(buffer, LPCSTR(csTxt));
GlobalUnlock(clipbuffer);
SetClipboardData(CF_TEXT,clipbuffer);
CloseClipboard();
}
*pResult = 0;
}
/*********************************************************
Function: PreTranslateMessage
Desc: capture push enter button or esc button
Input: none
Output: none
Return: none
**********************************************************/
BOOL CClientDemoDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if (pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_ESCAPE)
{
if (g_struLocalParam.bFullScreen)
{
g_struLocalParam.bEnlarged = FALSE;
g_struLocalParam.bMultiScreen = FALSE;
g_struLocalParam.bFullScreen = FALSE;
g_pMainDlg->GetDlgItem(IDC_COMBO_WNDNUM)->EnableWindow(TRUE);
g_pMainDlg->FullScreen(g_struLocalParam.bFullScreen);
if (g_struLocalParam.bFullScreen)
{
g_pMainDlg->ArrangeOutputs(g_pMainDlg->m_iCurWndNum);
}
else//multi-pic zoom
{
g_pMainDlg->ArrangeOutputs(g_pMainDlg->m_iCurWndNum);
g_pMainDlg->GetDlgItem(IDC_STATIC_PREVIEWBG)->Invalidate(TRUE);
}
}
else
{
GetDlgItem(IDC_BTN_TEST)->ShowWindow(SW_HIDE);
}
return TRUE;
}
if (pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_RETURN)
{
GetDlgItem(IDC_BTN_TEST)->ShowWindow(SW_SHOW);
return TRUE;
}
else
{
return CDialog::PreTranslateMessage(pMsg);
}
}
/*********************************************************
Function: OnBnClickedBtnExit
Desc: leave response function, release resource and exit demo
Input:
Output:
Return:
**********************************************************/
void CClientDemoDlg::OnBnClickedBtnExit()
{
char szLan[128] = {0};
g_bExitDemo = TRUE;//make not post message
g_StringLanType(szLan, "确定要退出吗?", "Sure to exit?");
if (IDOK != MessageBox(szLan,"Warning",IDOK))
{
return;
}
StopPlayAll();//stop all previews
m_dlgPlayBack->FinishAll();//stop all play back
if (m_pCyclePlayTimer)
{
KillTimer(CYCLE_PREVIEW_TIMER);
m_pCyclePlayTimer = 0;
}
if (m_pFreeSpaceTimer)
{
KillTimer(FREESPACE_TIMER);
m_pFreeSpaceTimer = 0;
}
if (m_pFileIntervalTimer)
{
KillTimer(FILEINTERVAL_TIMER);
m_pFileIntervalTimer = 0;
}
if (m_pChkDevTimer)
{
KillTimer(CHECK_DEVICE_TIMER);
m_pChkDevTimer = 0;
}
if (m_pSysTimer)
{
KillTimer(SYSTEM_TIMER);
m_pSysTimer=0;
}
if (g_struLocalParam.bUseCard)
{
NET_DVR_ReleaseDevice_Card();
NET_DVR_ReleaseDDraw_Card();
}
if (m_lListenHandle > 0)
{
NET_DVR_StopListen_V30(m_lListenHandle);
}
if (g_struLocalParam.bBroadCast)
{
NET_DVR_ClientAudioStop();
}
//remove guard, log out
int i = 0, j = 0;
for (i=0; i<MAX_DEVICES; i++)
{
if (g_struDeviceInfo[i].lLoginID >= 0)
{
for (j=0; j<MAX_AUDIO_V40; j++)
{
if (g_struDeviceInfo[i].lVoiceCom[j] >= 0)
{
if (NET_DVR_StopVoiceCom(g_struDeviceInfo[i].lVoiceCom[j]))
{
g_struDeviceInfo[i].lVoiceCom[j] = -1;
}
}
}
if (g_struDeviceInfo[i].lFortifyHandle >= 0)
{
if (NET_DVR_CloseAlarmChan(g_struDeviceInfo[i].lFortifyHandle))
{
g_struDeviceInfo[i].lFortifyHandle = -1;
}
}
NET_DVR_Logout_V30(g_struDeviceInfo[i].lLoginID);
g_struDeviceInfo[i].lLoginID = -1;
}
}
//2011-11-16退出被动解码
int iPassiveChanIndex = 0;
CString csStr;
for (i=0; i<MAX_DEVICES; i++)
{
//64-T解码器被动解码通道为32个
for (int iPassiveChanIndex=0; iPassiveChanIndex<32; iPassiveChanIndex++)
{
if (g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].lRealHandle >= 0)
{
NET_DVR_SetRealDataCallBack(g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].lRealHandle, NULL, iPassiveChanIndex);
if (!NET_DVR_StopRealPlay(g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].lRealHandle))
{
g_pMainDlg->AddLog(i, OPERATION_FAIL_T, "NET_DVR_StopRealPlay FAILED");
}
else
{
g_pMainDlg->AddLog(i, OPERATION_SUCC_T, "NET_DVR_StopRealPlay SUCC");
g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].lRealHandle = -1;
}
}
if (g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].lUserID >= 0)
{
if (!NET_DVR_Logout(g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].lUserID))
{
g_pMainDlg->AddLog(i, OPERATION_FAIL_T, "NET_DVR_Logout FAILED");
}
else
{
g_pMainDlg->AddLog(i, OPERATION_SUCC_T, "NET_DVR_Logout SUCC");
g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].lUserID = -1;
}
}
if (g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].hFileThread != NULL)
{
SetEvent(g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].hExitThread);
WaitForSingleObject(g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].hThreadExit, INFINITE);
TRACE("### Wait for Thread Exit...\n");
}
if (g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].lPassiveHandle >= 0)
{
if (!NET_DVR_MatrixStopPassiveDecode(g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].lPassiveHandle))
{
g_pMainDlg->AddLog(i, OPERATION_FAIL_T, "NET_DVR_MatrixStopPassiveDecode FAILED");
//return;
}
else
{
g_pMainDlg->AddLog(i, OPERATION_SUCC_T, "NET_DVR_MatrixStopPassiveDecode SUCC");
g_struDeviceInfo[i].struPassiveDecode[iPassiveChanIndex].lPassiveHandle = -1;
}
}
}
}
g_SaveDeviceConfig();
i = 0;
OnButton1();
CDialog::OnCancel();
}
/*********************************************************
Function: OnCancel
Desc: shutdown button response deal
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnCancel()
{
OnBnClickedBtnExit();
}
/*********************************************************
Function: DoGetDeviceResoureCfg
Desc: get input device IP parameters
Input: iDeviceIndex, the device index
Output: none
Return: TRUE/FALSE
**********************************************************/
BOOL CClientDemoDlg::DoGetDeviceResoureCfg(int iDeviceIndex, int iGroupNO)
{
int i = 0;
CString csTemp;
LPNET_DVR_IPPARACFG_V40 lpIPAccessCfgV40 = &g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[iGroupNO];
DWORD dwReturned = 0;
if (lpIPAccessCfgV40 == NULL)
{
return FALSE;
}
memset(lpIPAccessCfgV40, 0, sizeof(NET_DVR_IPPARACFG_V40));
//2008-9-15 13:44 ip input configuration
g_struDeviceInfo[iDeviceIndex].bIPRet = NET_DVR_GetDVRConfig(g_struDeviceInfo[iDeviceIndex].lLoginID, NET_DVR_GET_IPPARACFG_V40, iGroupNO, &g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[iGroupNO], sizeof(NET_DVR_IPPARACFG_V40), &dwReturned);
if (!g_struDeviceInfo[iDeviceIndex].bIPRet && g_struDeviceInfo[iDeviceIndex].byLoginModeRes == 0)
{ ///device no support ip access
if (g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_B20_MSU_NP || \
g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_MMC_B20_CLASS || \
g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_B21_MCU_NP_CLASS || \
g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_C20N_VWMS || \
g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_AIOH_MCU_NP || \
g_struDeviceInfo[iDeviceIndex].iDeviceType == DS_Y10_MCU) //B20/B21主控
{
//这里不需要做任何处理
}
else
{
g_struDeviceInfo[iDeviceIndex].lFirstEnableChanIndex = 0;
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GET_IPPARACFG_V40");
for (i = 0; i < MAX_CHANNUM_V30; i++)
{
if (i < g_struDeviceInfo[iDeviceIndex].iAnalogChanNum)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanIndex = i;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChannelNO = i + g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable = TRUE;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanType = DEMO_CHANNEL_TYPE_ANALOG;
sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName, ANALOG_C_FORMAT, i + g_struDeviceInfo[iDeviceIndex].iStartChan);
}
else//clear the state of other channel
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iDeviceIndex = -1;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanIndex = -1;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable = FALSE;
sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName, "");
}
}
g_struDeviceInfo[iDeviceIndex].iGroupNO = -1;
}
}
else
{
//ISAPI登录时,NET_DVR_GET_IPPARACFG_V40会失败,此时利用登录返回参数刷新数组通道
if (g_struDeviceInfo[iDeviceIndex].byLoginModeRes == 1)
{
for (i = 0; i < MAX_CHANNUM_V30; i++)
{
if (i < g_struDeviceInfo[iDeviceIndex].iIPChanNum)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanIndex = i;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChannelNO = i + g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable = TRUE; //此处默认显示在线,因为暂时没有获取状态,通过这个获取/ISAPI/ContentMgmt/InputProxy/channels/status
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanType = DEMO_CHANNEL_TYPE_IP;
sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName, DIGITAL_C_FORMAT, i + g_struDeviceInfo[iDeviceIndex].iStartChan);
}
else//clear the state of other channel
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iDeviceIndex = -1;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanIndex = -1;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable = FALSE;
sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName, "");
}
}
lpIPAccessCfgV40->dwDChanNum = g_struDeviceInfo[iDeviceIndex].iIPChanNum;
lpIPAccessCfgV40->dwStartDChan = g_struDeviceInfo[iDeviceIndex].iStartChan;
}
g_struDeviceInfo[iDeviceIndex].iGroupNO = iGroupNO;
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_GET_IPPARACFG_V40");
RefreshIPDevLocalCfg(iDeviceIndex);
}
if (g_struDeviceInfo[iDeviceIndex].byMirrorChanNum > 0 && g_struDeviceInfo[iDeviceIndex].wStartMirrorChanNo > g_struDeviceInfo[iDeviceIndex].iDeviceChanNum)
{
for (i=0; i<g_struDeviceInfo[iDeviceIndex].byMirrorChanNum&&i < 16; i++)
{
if (1)
{
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].iChanIndex = i+MIRROR_CHAN_INDEX;
sprintf(g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].chChanName, "MirrorChan%d", i+1);
//analog devices
if (1)
{
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].bEnable = TRUE;
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].dwImageType = CHAN_ORIGINAL;
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].iChannelNO = i + g_struDeviceInfo[iDeviceIndex].wStartMirrorChanNo;
// g_struDeviceInfo[iDeviceIndex].iEnableChanNum ++;
}
else
{
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].dwImageType = CHAN_OFF_LINE;
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].bEnable = FALSE;
}
}
}
}
if (g_struDeviceInfo[iDeviceIndex].byZeroChanNum > 0)
{
for (i=0; i<g_struDeviceInfo[iDeviceIndex].byZeroChanNum; i++)
{
if (1)
{
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].iChanIndex = i+ZERO_CHAN_INDEX;
sprintf(g_struDeviceInfo[iDeviceIndex].struZeroChan[i].chChanName, "ZeroChan%d", i);
//analog devices
if (1)
{
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].bEnable = TRUE;
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].dwImageType = CHAN_ORIGINAL;
// g_struDeviceInfo[iDeviceIndex].iEnableChanNum ++;
}
else
{
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].dwImageType = CHAN_OFF_LINE;
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].bEnable = FALSE;
}
}
}
}
return g_struDeviceInfo[iDeviceIndex].bIPRet;
}
/*********************************************************
Function: DoGetIPAlarmInCfg
Desc: get device alarm input configuration
Input: iDeviceIndex, the device index
bSupportMultiGroup, support multi group
GroupNo, group number
Output: none
Return: TRUE/FALSE
**********************************************************/
BOOL CClientDemoDlg::DoGetIPAlarmInCfg(int iDeviceIndex, BOOL bSupportMultiGroup, int GroupNO)
{
int i = 0;
char szTmp[1024*5] = { 0 };
char szTmp1[32] = {0};
DWORD dwReturned = 0;
// memset(&g_struDeviceInfo[iDeviceIndex].struAlarmInCfg, 0, sizeof(NET_DVR_IPALARMINCFG));
if (g_struDeviceInfo[iDeviceIndex].pStruIPAlarmInCfgV40 == NULL)
{
return FALSE;
}
memset(g_struDeviceInfo[iDeviceIndex].pStruIPAlarmInCfgV40, 0, sizeof(NET_DVR_IPALARMINCFG_V40));
if (bSupportMultiGroup)
{
g_struDeviceInfo[iDeviceIndex].bIPRet = NET_DVR_GetDVRConfig(g_struDeviceInfo[iDeviceIndex].lLoginID, NET_DVR_GET_IP_ALARM_IN, GroupNO, &g_struDeviceInfo[iDeviceIndex].struAlarmInCfg, sizeof(NET_DVR_IPALARMINCFG), &dwReturned);
}
else
{
g_struDeviceInfo[iDeviceIndex].bIPRet = NET_DVR_GetDVRConfig(g_struDeviceInfo[iDeviceIndex].lLoginID, NET_DVR_GET_IPALARMINCFG_V40, 0, g_struDeviceInfo[iDeviceIndex].pStruIPAlarmInCfgV40 , sizeof(NET_DVR_IPALARMINCFG_V40), &dwReturned);
}
if (g_struDeviceInfo[iDeviceIndex].bIPRet)
{ //8000 device
// for (i=0; i< MAX_IP_ALARMIN; i++)
// {
// if (g_struDeviceInfo[iDeviceIndex].struAlarmInCfg.struIPAlarmInInfo[i].byIPID != 0)
// {
// sprintf(szTmp1, "%d[%d-%d]", i, g_struDeviceInfo[iDeviceIndex].struAlarmInCfg.struIPAlarmInInfo[i].byIPID, \
// g_struDeviceInfo[iDeviceIndex].struAlarmInCfg.struIPAlarmInInfo[i].byAlarmIn);
// strcat(szTmp, szTmp1);
// }
// }
for (i= 0; i < MAX_IP_ALARMIN_V40; i++)
{
if (g_struDeviceInfo[iDeviceIndex].pStruIPAlarmInCfgV40->struIPAlarmInInfo[i].dwIPID != 0)
{
sprintf(szTmp1, "%d[%d-%d]", i, g_struDeviceInfo[iDeviceIndex].pStruIPAlarmInCfgV40->struIPAlarmInInfo[i].dwIPID, \
g_struDeviceInfo[iDeviceIndex].pStruIPAlarmInCfgV40->struIPAlarmInInfo[i].dwAlarmIn);
strcat(szTmp, szTmp1);
}
}
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_GET_IPALARMINCFG:%s", szTmp);
}
else
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GET_IPALARMINCFG");
}
return g_struDeviceInfo[iDeviceIndex].bIPRet;
}
/*********************************************************
Function: DoGetIPAlarmOutCfg
Desc: get device output configuration
Input: iDeviceIndex, the device index
bSupportMultiGroup, support multi group
GroupNo, group number
Output: none
Return: TRUE/FALSE
**********************************************************/
BOOL CClientDemoDlg::DoGetIPAlarmOutCfg(int iDeviceIndex, BOOL bSupportMultiGroup, int GroupNO)
{
int i = 0;
char szTmp[1024] = {0};
char szTmp1[32] = {0};
DWORD dwReturned = 0;
// memset(&g_struDeviceInfo[iDeviceIndex].struAlarmOutCfg, 0, sizeof(NET_DVR_IPALARMOUTCFG));
if (g_struDeviceInfo[iDeviceIndex].pStruIPAlarmOutCfgV40 == NULL)
{
return FALSE;
}
memset(g_struDeviceInfo[iDeviceIndex].pStruIPAlarmOutCfgV40, 0, sizeof(NET_DVR_IPALARMOUTCFG_V40));
if (bSupportMultiGroup)
{
g_struDeviceInfo[iDeviceIndex].bIPRet = NET_DVR_GetDVRConfig(g_struDeviceInfo[iDeviceIndex].lLoginID, NET_DVR_GET_IP_ALARM_OUT, GroupNO, &g_struDeviceInfo[iDeviceIndex].struAlarmOutCfg, sizeof(NET_DVR_IPALARMOUTCFG), &dwReturned);
}
else
{
g_struDeviceInfo[iDeviceIndex].bIPRet = NET_DVR_GetDVRConfig(g_struDeviceInfo[iDeviceIndex].lLoginID, NET_DVR_GET_IPALARMOUTCFG_V40, 0, g_struDeviceInfo[iDeviceIndex].pStruIPAlarmOutCfgV40, sizeof(NET_DVR_IPALARMOUTCFG_V40), &dwReturned);
}
if (g_struDeviceInfo[iDeviceIndex].bIPRet)
{ //8000 device
for (i=0; i< MAX_IP_ALARMOUT_V40; i++)
{
if (g_struDeviceInfo[iDeviceIndex].pStruIPAlarmOutCfgV40->struIPAlarmOutInfo[i].dwIPID != 0)
{
sprintf(szTmp1, "%d[%d-%d]", i, g_struDeviceInfo[iDeviceIndex].pStruIPAlarmOutCfgV40->struIPAlarmOutInfo[i].dwIPID, \
g_struDeviceInfo[iDeviceIndex].pStruIPAlarmOutCfgV40->struIPAlarmOutInfo[i].dwAlarmOut);
strcat(szTmp, szTmp1);
}
}
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_GET_IPALARMOUTCFG_V40-%s", szTmp);
}
else
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_GET_IPALARMOUTCFG_V40");
}
return g_struDeviceInfo[iDeviceIndex].bIPRet;
}
/*********************************************************
Function: DoSetIPAccessCfg
Desc: set the ip configure of device/设备ip接入参数
Input: iDeviceIndex, the device index
dwGroupNo Group No.
Output: none
Return: TRUE/FALSE
**********************************************************/
BOOL CClientDemoDlg::DoSetIPAccessCfg(int iDeviceIndex, DWORD dwGroupNo)
{
BOOL bIPRet = FALSE;
//2008-9-15 13:44 ip input configuration
bIPRet = NET_DVR_SetDVRConfig(g_struDeviceInfo[iDeviceIndex].lLoginID, NET_DVR_SET_IPPARACFG_V40, dwGroupNo, &g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[dwGroupNo], sizeof(g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0]));
if (bIPRet)
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "NET_DVR_SET_IPPARACFG_V40");
RefreshIPDevLocalCfg(iDeviceIndex);
}
else
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "NET_DVR_SET_IPPARACFG_V40");
}
return bIPRet;
}
/*********************************************************
Function: RefreshIPDevLocalCfg
Desc: refresh the ip device configure of local device configure
Input: iDeviceIndex, the device index in the local device group
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::RefreshIPDevLocalCfg(int iDeviceIndex)
{
EnterCriticalSection(&m_struLock);
LPNET_DVR_IPPARACFG_V40 lpIPAccessCfgV40 = &g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[g_struDeviceInfo[iDeviceIndex].iGroupNO];
DWORD dwChanShow = 0;
int iIPChanIndex = 0;
int i = 0;
// for (i=0; i<MAX_IP_DEVICE; i++)
// {
// AddLog(-1, OPERATION_SUCC_T, "IP dev chan[%d] ip=%s name=%s", i,\
// lpIPAccessCfg->struIPDevInfo[i].struIP.sIpV4, lpIPAccessCfg->struIPDevInfo[i].sUserName);
// }
//Update MAX IP channel number.
g_struDeviceInfo[iDeviceIndex].iIPChanNum = lpIPAccessCfgV40->dwDChanNum;
int iAnalogChanCount = 0;
int iIPChanCount = 0;
int iGroupNO = g_struDeviceInfo[iDeviceIndex].iGroupNO; //Group NO.
int iGroupNum = lpIPAccessCfgV40->dwGroupNum;
int iIPChanNum = g_struDeviceInfo[iDeviceIndex].iIPChanNum;
int iMaxGroupDeviceNum = 0;
if (0 == iGroupNO)
{
iMaxGroupDeviceNum = MAX_CHANNUM_V30 + g_struDeviceInfo[iDeviceIndex].iAnalogChanNum;
}
else
{
iMaxGroupDeviceNum = MAX_CHANNUM_V30;
}
for (i = 0; i < iMaxGroupDeviceNum; i++)
{
//analog channel
if (iAnalogChanCount < g_struDeviceInfo[iDeviceIndex].iAnalogChanNum && 0 == iGroupNO)
{
dwChanShow = iAnalogChanCount + g_struDeviceInfo[iDeviceIndex].iStartChan/* + g_struDeviceInfo[iDeviceIndex].iGroupNO*64*/;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanIndex = i;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanType = DEMO_CHANNEL_TYPE_ANALOG;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChannelNO = dwChanShow;
sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName, ANALOG_C_FORMAT, dwChanShow);
//analog devices
if (lpIPAccessCfgV40->byAnalogChanEnable[i])
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable = TRUE;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].dwImageType = CHAN_ORIGINAL;
//g_struDeviceInfo[iDeviceIndex].iEnableChanNum ++;
}
else
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable = FALSE;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].dwImageType = CHAN_OFF_LINE;
}
iAnalogChanCount++;
}
//IP channel //(i>=MAX_ANALOG_CHANNUM && i<MAX_ANALOG_CHANNUM+g_struDeviceInfo[iDeviceIndex].iIPChanNum) )
// else if (iGroupNO >= 0 && ((iIPChanCount + iGroupNO * MAX_CHANNUM_V30) < iIPChanNum) && (iIPChanCount < iIPChanNum ))
// {
// dwChanShow = iIPChanCount + iGroupNO * MAX_CHANNUM_V30 + lpIPAccessCfgV40->dwStartDChan - 1;
//
// g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwChanShow].iChanType = DEMO_CHANNEL_TYPE_IP;
// g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwChanShow].iChannelNO = dwChanShow + 1;
//
// iIPChanIndex = iIPChanCount;
// g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwChanShow].iDeviceIndex = iDeviceIndex;
// g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwChanShow].iChanIndex =i + g_struDeviceInfo[iDeviceIndex].iGroupNO*64;
// sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i + g_struDeviceInfo[iDeviceIndex].iGroupNO*64].chChanName, DIGITAL_C_FORMAT, iIPChanCount + iGroupNO * MAX_CHANNUM_V30 + 1);
// // AddLog(-1, OPERATION_SUCC_T, "IPc%d id%d chan[%d] ", iIPChanIndex,\
// // lpIPAccessCfg->struIPChanInfo[iIPChanIndex].byIPID, lpIPAccessCfg->struIPChanInfo[iIPChanIndex].byChannel);
// if (lpIPAccessCfgV40->struStreamMode[iIPChanIndex].uGetStream.struChanInfo.byIPID != 0 && lpIPAccessCfgV40->struStreamMode[iIPChanIndex].uGetStream.struChanInfo.byEnable == TRUE)
// {
// g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwChanShow].bEnable = TRUE;//
// if (lpIPAccessCfgV40->struStreamMode[iIPChanIndex].uGetStream.struChanInfo.byEnable)
// {
// g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwChanShow].dwImageType = CHAN_ORIGINAL;
// }
// else
// {
// g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwChanShow].dwImageType = CHAN_OFF_LINE;
// }
//
// // g_struDeviceInfo[iDeviceIndex].iEnableChanNum ++;
// }
// else
// {
// g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwChanShow].dwImageType = CHAN_OFF_LINE;
// g_struDeviceInfo[iDeviceIndex].pStruChanInfo[dwChanShow].bEnable = FALSE;
// //g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = FALSE;
// }
//
// iIPChanCount++;
// }
else if (iGroupNO >= 0 && ((iIPChanCount + iGroupNO * MAX_CHANNUM_V30) < iIPChanNum) && (iIPChanCount < iIPChanNum))
{
dwChanShow = iIPChanCount + iGroupNO * MAX_CHANNUM_V30 + lpIPAccessCfgV40->dwStartDChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanType = DEMO_CHANNEL_TYPE_IP;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChannelNO = dwChanShow;
iIPChanIndex = iIPChanCount;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iDeviceIndex = iDeviceIndex;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanIndex = i;
sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName, DIGITAL_C_FORMAT, iIPChanCount + iGroupNO * MAX_CHANNUM_V30 + 1);
if (g_struDeviceInfo[iDeviceIndex].byLoginModeRes == 1 || (lpIPAccessCfgV40->struStreamMode[iIPChanIndex].uGetStream.struChanInfo.byIPID != 0 && lpIPAccessCfgV40->struStreamMode[iIPChanIndex].uGetStream.struChanInfo.byEnable == TRUE))
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable = TRUE;//ISAPI登录需要获取通道是否在线
if (lpIPAccessCfgV40->struStreamMode[iIPChanIndex].uGetStream.struChanInfo.byEnable)
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].dwImageType = CHAN_ORIGINAL;
}
else
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].dwImageType = CHAN_OFF_LINE;
}
// g_struDeviceInfo[iDeviceIndex].iEnableChanNum ++;
}
else
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].dwImageType = CHAN_OFF_LINE;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable = FALSE;
//g_struDeviceInfo[iDeviceIndex].struChanInfo[i].bAlarm = FALSE;
}
iIPChanCount++;
}
else
{
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iDeviceIndex = -1;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanIndex = -1;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanType = DEMO_CHANNEL_TYPE_INVALID;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChannelNO = -1;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable = FALSE;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = FALSE;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bLocalManualRec = FALSE;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].lRealHandle = -1;
sprintf(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName, "");
}
}
for (i = 0; i < iMaxGroupDeviceNum; i++)
{
if (g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable)
{
g_struDeviceInfo[iDeviceIndex].lFirstEnableChanIndex = i;
break;
}
}
if (g_struDeviceInfo[iDeviceIndex].byZeroChanNum > 0)
{
//get配置
}
LeaveCriticalSection(&m_struLock);
}
/*********************************************************
Function: RedrawDeviceNode
Desc: redraw the device node on device tree, delete all channels node first, then add new channels
Input: iDeviceIndex, the device index in the local device group
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::RedrawDeviceNode(int iDeviceIndex)
{
HTREEITEM hChanItem = NULL;
HTREEITEM hPreItem = NULL;
CString csTmp;
int i = 0;
int iData = 0;
int iLoginStat = DEVICE_LOGIN;
if (iDeviceIndex >= 1000)//设备序号大于1000时表示只添加不登陆
{
iDeviceIndex-=1000;
iLoginStat = DEVICE_LOGOUT;
}
else
{
iLoginStat = DEVICE_LOGIN;
}
if (g_bPlayAllDevice || g_struDeviceInfo[iDeviceIndex].bPlayDevice)
{
return;
}
HTREEITEM hRoot = m_treeDeviceList.GetRootItem();
if (hRoot == NULL)
{
return;
}
HTREEITEM hDevItem = m_treeDeviceList.GetChildItem(hRoot);
//find the select device
while (hDevItem != NULL)
{
iData = m_treeDeviceList.GetItemData(hDevItem);
if (DEVICETYPE == iData/1000)
{
if (iDeviceIndex == iData%1000)
{
HTREEITEM hChanItem = m_treeDeviceList.GetChildItem(hDevItem);
while (i < MAX_CHANNUM_V30 * 2 + g_struDeviceInfo[iDeviceIndex].byZeroChanNum && hChanItem != NULL)
{
hPreItem = hChanItem;
hChanItem = m_treeDeviceList.GetNextSiblingItem(hChanItem);
if (CHANNELTYPE != (int)m_treeDeviceList.GetItemData(hPreItem)/1000)
{
AddLog(iDeviceIndex, OPERATION_FAIL_T, "to next channel node error");
break;
}
i++;
}
break;
}
}//end else if
hDevItem = m_treeDeviceList.GetNextVisibleItem(hDevItem);
}//end while
if (hDevItem != NULL)
{
while(i>0 && hPreItem != NULL)
{
hChanItem = hPreItem;
hPreItem = m_treeDeviceList.GetPrevSiblingItem(hChanItem);
if (hPreItem == NULL)
{
// AddLog(iDeviceIndex, OPERATION_SUCC_T, "del last chan[%d]", m_treeDeviceList.GetItemData(hChanItem)%1000);
hPreItem = m_treeDeviceList.GetParentItem(hChanItem);
m_treeDeviceList.DeleteItem(hChanItem);
if (hPreItem == NULL)
{
AddLog(-1, OPERATION_FAIL_T, "get the device node err");
break;
}
if (CHANNELTYPE != (int)m_treeDeviceList.GetItemData(hPreItem)/1000)
{
// AddLog(iDeviceIndex, OPERATION_SUCC_T, "dev[%d] node all delete", m_treeDeviceList.GetItemData(hPreItem)%1000);
break;
}
}
//AddLog(iDeviceIndex, OPERATION_SUCC_T, "del chan[%d]", m_treeDeviceList.GetItemData(hChanItem)%1000);
m_treeDeviceList.DeleteItem(hChanItem);
i--;
}
}
if (hDevItem == NULL)
{//added 9000 devices
hDevItem = m_treeDeviceList.InsertItem(g_struDeviceInfo[iDeviceIndex].chLocalNodeName, iLoginStat, iLoginStat, hRoot, GetAfterItem(hRoot));
}
//add channel node//g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bEnable ||
for (i = 0; i< MAX_CHANNUM_V30 * 2; i++)
{
if (g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanIndex != -1 )
{
csTmp.Format("%s", g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].chChanName);
hChanItem = m_treeDeviceList.InsertItem(csTmp, g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].dwImageType, \
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].dwImageType, hDevItem);
m_treeDeviceList.SetItemData(hChanItem, CHANNELTYPE * 1000 + g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].iChanIndex);
}
}
for (i=0; i< g_struDeviceInfo[iDeviceIndex].byZeroChanNum; i++)
{
if (g_struDeviceInfo[iDeviceIndex].struZeroChan[i].iChanIndex != -1 )
{
csTmp.Format("%s", g_struDeviceInfo[iDeviceIndex].struZeroChan[i].chChanName);
hChanItem = m_treeDeviceList.InsertItem(csTmp, g_struDeviceInfo[iDeviceIndex].struZeroChan[i].dwImageType, \
g_struDeviceInfo[iDeviceIndex].struZeroChan[i].dwImageType, hDevItem);
m_treeDeviceList.SetItemData(hChanItem, CHANNELTYPE * 1000 + g_struDeviceInfo[iDeviceIndex].struZeroChan[i].iChanIndex);
}
}
for (i=0; i< g_struDeviceInfo[iDeviceIndex].byMirrorChanNum && i < 16; i++)
{
if (g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].iChanIndex != -1 )
{
csTmp.Format("%s", g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].chChanName);
hChanItem = m_treeDeviceList.InsertItem(csTmp, g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].dwImageType, \
g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].dwImageType, hDevItem);
m_treeDeviceList.SetItemData(hChanItem, CHANNELTYPE * 1000 + g_struDeviceInfo[iDeviceIndex].struMirrorChan[i].iChanIndex);
}
}
}
/*********************************************************
Function: DoTestElseFunction
Desc: test
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::DoTestElseFunction()
{
int iDevIndex = GetCurDeviceIndex();
CDlgDoTest dlg;
dlg.m_iDeviceIndex = iDevIndex;
dlg.DoModal();
}
/*********************************************************
Function: OnDbclkListAllLog
Desc: get current device fault info
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnDblclkListAllLog(NMHDR* pNMHDR, LRESULT* pResult)
{
int iItemSel = 0;
CString csTxt;
POSITION iPos = m_listAllLog.GetFirstSelectedItemPosition();
if (iPos == NULL)
{
return;
}
iItemSel = m_listAllLog.GetNextSelectedItem(iPos);//%s\t%s\tm_listAllLog.GetItemText(iItemSel,1),\m_listAllLog.GetItemText(iItemSel,2)
csTxt.Format("%s",m_listAllLog.GetItemText(iItemSel,5));
if (csTxt.GetLength() > 3)
{
AfxMessageBox(csTxt);
}
*pResult = 0;
}
/*********************************************************
Function: OnDblclkListAlarmInfo
Desc: get current Alarm Info
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnDblclkListAlarmInfo(NMHDR* pNMHDR, LRESULT* pResult)
{
int iItemSel = 0;
CString csTxt;
POSITION iPos = m_listAlarmInfo.GetFirstSelectedItemPosition();
if (iPos == NULL)
{
return;
}
iItemSel = m_listAlarmInfo.GetNextSelectedItem(iPos);
csTxt.Format("%s",m_listAlarmInfo.GetItemText(iItemSel,2));
if (csTxt.GetLength() > 3)
{
AfxMessageBox(csTxt);
}
*pResult = 0;
}
/*********************************************************
Function: OnSelchangeComboListType
Desc: select the corresponding list, alarm or log
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnSelchangeComboListType()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
ListRestore();
if (m_iMainType == CONFIG_ALL_T)
{
m_dlgConfigAll->ConfigWndUpdate();
}
else if (m_iMainType == PLAY_BACK_T)
{
m_dlgPlayBack->ShowWindow(SW_SHOW);
m_dlgPlayBack->PlayBackWinUpdate();
}
else if (m_iMainType == PREVIEW_T)
{
PreviewReferShow(TRUE);
}
switch (m_iSelListType)
{
case 0:
m_listAlarmInfo.ShowWindow(SW_HIDE);
m_listAllLog.ShowWindow(SW_SHOW);
break;
case 1:
m_listAllLog.ShowWindow(SW_HIDE);
m_listAlarmInfo.ShowWindow(SW_SHOW);
break;
default:
break;
}
}
/*********************************************************
Function: OnColumnclickListAllLog
Desc: response the Column-click of all log list
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnColumnclickListAllLog(NMHDR* pNMHDR, LRESULT* pResult)
{
EnlargeList(m_listAllLog, m_bListLogEnlarge);
*pResult = 0;
}
/*********************************************************
Function: OnColumnclickListAlarmInfo
Desc: response the Column-click of all log list
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnColumnclickListAlarmInfo(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
EnlargeList(m_listAlarmInfo, m_bListAlarmEnlarge);
*pResult = 0;
}
/*********************************************************
Function: EnlargeList
Desc: enlarge list when click the column
Input: list, log or alarm information tree; bEnargeList, TRUE/FALSE;
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::EnlargeList(CListCtrl &list, BOOL &bEnargeList)
{
CRect rc(0,0,0,0);
list.GetWindowRect(&rc);
ScreenToClient(&rc);
if (!bEnargeList)
{
rc.top-=LIST_ENLARGE_HIGH;//move top upper, stretch
list.MoveWindow(&rc);
bEnargeList = TRUE;
if (m_iMainType == CONFIG_ALL_T)
{
m_dlgRemoteCfg->ShowWindow(SW_HIDE);
// m_dlgRemoteCfg->ChangeCurConfigWnd(REMOTE_MAT_DEC_CFG_T+1);
m_dlgRemoteCfg->ChangeCurConfigWnd(REMOTE_DEVICE_CFG_T);
m_dlgLocalCfg->ShowWindow(SW_HIDE);
m_dlgIPAccess->ShowWindow(SW_HIDE);
m_dlgHDConfig->ShowWindow(SW_HIDE);
m_dlgBatchCfg->ShowWindow(SW_HIDE);
}
else if (m_iMainType == PLAY_BACK_T)
{
m_dlgPlayBack->ShowWindow(SW_HIDE);
// m_dlgPlayBack->m_dlgPlayRemoteFile.ShowWindow(SW_HIDE);
// m_dlgPlayBack->m_dlgPlayLocalFile.ShowWindow(SW_HIDE);
// m_dlgPlayBack->m_dlgPlayRemoteTime.ShowWindow(SW_HIDE);
}
else if(m_iMainType == STREAM_ID_T)
{
// m_pStreamIDDlg->ShowWindow(SW_HIDE);
}
else if (m_iMainType == PRODUCT_RELATE_T)
{
m_dlgProductCfg->ShowWindow(SW_HIDE);
}
else
{
PreviewReferShow(FALSE);
m_dlgOutputCtrl->ShowWindow(SW_SHOW);
}
}
else
{
rc.top+=LIST_ENLARGE_HIGH;//move top down, compress
list.MoveWindow(&rc);
bEnargeList = FALSE;
if (m_iMainType == CONFIG_ALL_T)
{
m_dlgConfigAll->ConfigWndUpdate();
}
else if (m_iMainType == PLAY_BACK_T)
{
m_dlgPlayBack->ShowWindow(SW_SHOW);
// m_dlgPlayBack->PlayBackWinUpdate();
}
else if (m_iMainType == STREAM_ID_T)
{
//m_pStreamIDDlg->ShowWindow(SW_SHOW);
}
else if (m_iMainType == PRODUCT_RELATE_T)
{
m_dlgProductCfg->ShowWindow(SW_SHOW);
}
else
{
PreviewReferShow(TRUE);
}
}
if (!g_struLocalParam.bFullScreen)
{
list.ShowWindow(SW_SHOW);
}
}
void CClientDemoDlg::ProcAlarmHostAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
char szLan[128] ={0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_ALARMHOST_ALARMINFO struAlarmInfo;
memset(&struAlarmInfo, 0, sizeof(struAlarmInfo));
CTime time = CTime::GetCurrentTime();
memcpy(&struAlarmInfo, pAlarmInfo, sizeof(struAlarmInfo));
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
g_StringLanType(szLan, "收到网络报警主机报警", "receive alarmhost alarm");
memcpy(szInfoBuf, szLan, strlen(szLan));
for (i = 0; i < ARRAY_SIZE(struAlarmInfo.byAlarmInputNumber); i++)
{
sprintf(&szInfoBuf[i + strlen(szLan)], "%d", struAlarmInfo.byAlarmInputNumber[i]);
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
/*********************************************************
Function: OnBtnTest
Desc: for testing the interfaces those are not used usually
Input: none
Output: none
Return: none
**********************************************************/
void CClientDemoDlg::OnBtnTest()
{
// TODO: Add your control notification handler code here
DoTestElseFunction();
NET_DVR_SDKSTATE SDKState;
NET_DVR_GetSDKState( &SDKState );
g_pMainDlg->AddLog(-1, OPERATION_SUCC_T, "SDKState.dwTotalRealPlayNum %d", SDKState.dwTotalRealPlayNum);
return;
}
void CClientDemoDlg::ListRestore()
{
CRect rc(0,0,0,0);
if (m_bListLogEnlarge)
{
m_listAllLog.GetWindowRect(&rc);
ScreenToClient(&rc);
rc.top+=LIST_ENLARGE_HIGH;//move top down, compress
m_listAllLog.MoveWindow(&rc);
m_bListLogEnlarge = FALSE;
}
if (m_bListAlarmEnlarge)
{
m_listAlarmInfo.GetWindowRect(&rc);
ScreenToClient(&rc);
rc.top+=LIST_ENLARGE_HIGH;//move top down, compress
m_listAlarmInfo.MoveWindow(&rc);
m_bListAlarmEnlarge = FALSE;
}
}
void CClientDemoDlg::OnRadioLocalLog()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_iSelListType = 0;
OnSelchangeComboListType();
UpdateData(FALSE);
}
void CClientDemoDlg::OnRadioAlarmInfo()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_iSelListType = 1;
OnSelchangeComboListType();
UpdateData(FALSE);
}
void CClientDemoDlg::OnMenuAtmFrameFormat()
{
// TODO: Add your command handler code here
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex < 0)
{
return;
}
int iChanIndex = GetCurChanIndex();
if (iChanIndex < 0)
{
iChanIndex = 0;//default to config channel one
}
CDlgAtmFrameFormatV30 dlg;
dlg.m_lServerID = g_struDeviceInfo[iDeviceIndex].lLoginID;
dlg.m_iDevIndex = iDeviceIndex;
dlg.m_iChannelNum = g_struDeviceInfo[iDeviceIndex].iDeviceChanNum;
dlg.DoModal();
}
void CClientDemoDlg::OnMenuSensorAddPreview()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex < 0)
{
return;
}
CDlgSensorAddPreview dlg;
dlg.m_lServerID = g_struDeviceInfo[iDeviceIndex].lLoginID;
dlg.m_iDevIndex = iDeviceIndex;
dlg.DoModal();
}
void CClientDemoDlg::OnMenuHolidayCfg()
{
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex < 0)
{
return;
}
CDlgHolidayCfg dlg;
dlg.m_lServerID = g_struDeviceInfo[iDeviceIndex].lLoginID;
dlg.m_iDevIndex = iDeviceIndex;
dlg.DoModal();
DWORD dwGetCommand = NET_DVR_GET_ALARMOUT_HOLIDAY_HANDLE;
DWORD dwSetCommand = NET_DVR_SET_ALARMOUT_HOLIDAY_HANDLE;
NET_DVR_HOLIDAY_HANDLE struHolidayHandle = {0};
DWORD dwReturn = 0;
if (NET_DVR_GetDVRConfig(g_struDeviceInfo[iDeviceIndex].lLoginID, dwGetCommand, 1, &struHolidayHandle, sizeof(struHolidayHandle), &dwReturn))
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "Get Holiday handle");
}
else
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Get Holiday handle");
}
memset(&struHolidayHandle, 0, sizeof(struHolidayHandle));
if (NET_DVR_SetDVRConfig(g_struDeviceInfo[iDeviceIndex].lLoginID, dwSetCommand, 1, &struHolidayHandle, sizeof(struHolidayHandle)))
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "Set Holiday handle");
}
else
{
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_SUCC_T, "Set Holiday handle");
}
}
void CClientDemoDlg::OnButton1()
{
// TODO: Add your control notification handler code here
NET_DVR_Cleanup();
NET_DVR_Init();
NET_DVR_SDKSTATE SDKState;
NET_DVR_GetSDKState(&SDKState);
}
void CClientDemoDlg::ProcAlarmVQD(WPARAM wParam, LPARAM lParam)
{
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_VQD_DIAGNOSE_INFO struVQDAlarm = {0};
memcpy(&struVQDAlarm, pAlarmInfo, sizeof(struVQDAlarm));
char szLan[1024] = {0};
char szLanCn[1024] = {0};
char szLanEn[1024] = {0};
if (struVQDAlarm.struVQDDiagnoseExceptionInfo.dwChannelNO <= g_struDeviceInfo[iDeviceIndex].iAnalogChanNum)
{
sprintf(szLanCn,"Camera%d",struVQDAlarm.struVQDDiagnoseExceptionInfo.dwChannelNO);
sprintf(szLanEn,"Camera%d",struVQDAlarm.struVQDDiagnoseExceptionInfo.dwChannelNO);
}
else
{
sprintf(szLanCn,"IPCamera%02d",struVQDAlarm.struVQDDiagnoseExceptionInfo.dwChannelNO);
sprintf(szLanEn,"IPCamera%02d",struVQDAlarm.struVQDDiagnoseExceptionInfo.dwChannelNO);
}
switch (struVQDAlarm.struVQDDiagnoseExceptionInfo.dwVQDType)
{
case VQD_BLUR_FLAG:
sprintf(szLanCn,"%s 图像模糊",szLanCn);
sprintf(szLanEn,"%s Blur",szLanEn);
break;
case VQD_LUMA_FLAG:
sprintf(szLanCn,"%s 亮度异常",szLanCn);
sprintf(szLanEn,"%s Luma",szLanEn);
break;
case VQD_CHROMA_FLAG:
sprintf(szLanCn,"%s 图像偏色",szLanCn);
sprintf(szLanEn,"%s Chroma",szLanEn);
break;
case VQD_SNOW_FLAG:
sprintf(szLanCn,"%s 雪花干扰",szLanCn);
sprintf(szLanEn,"%s Snow",szLanEn);
break;
case VQD_STREAK_FLAG:
sprintf(szLanCn,"%s 条纹干扰",szLanCn);
sprintf(szLanEn,"%s Streak",szLanEn);
break;
case VQD_FREEZE_FLAG:
sprintf(szLanCn,"%s 画面冻结",szLanCn);
sprintf(szLanEn,"%s Freeze",szLanEn);
break;
case VQD_SIGLOSE_FLAG:
sprintf(szLanCn,"%s 信号丢失",szLanCn);
sprintf(szLanEn,"%s Signal Lose",szLanEn);
break;
case VQD_PTZ_FLAG:
sprintf(szLanCn,"%s 云台失控",szLanCn);
sprintf(szLanEn,"%s PTZ",szLanEn);
break;
default:
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, "Unknown Alarm");
return;
}
sprintf(szLanCn,"%s %4d-%2d-%2d %2d:%2d:%2d",szLanCn, struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwYear,\
struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwMonth, struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwDay,\
struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwHour, struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwMinute,\
struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwSecond);
sprintf(szLanEn,"%s %4d-%2d-%2d %2d:%2d:%2d",szLanEn, struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwYear,\
struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwMonth, struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwDay,\
struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwHour, struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwMinute,\
struVQDAlarm.struVQDDiagnoseExceptionInfo.struDiagnoseTime.dwSecond);
g_StringLanType(szLan,szLanCn,szLanEn);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
}
void CClientDemoDlg::ProcAlarmVQDEx(WPARAM wParam,LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_VQD_ALARM struVQDAlarm = {0};
CTime time = CTime::GetCurrentTime();
memcpy(&struVQDAlarm, pAlarmInfo, sizeof(struVQDAlarm));
i = struVQDAlarm .struDevInfo.byIvmsChannel-g_struDeviceInfo[iDeviceIndex].iStartChan;
g_struDeviceInfo[iDeviceIndex].pStruChanInfo[i].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_CHANNEL_ITEM_IMAGE, WPARAM(iDeviceIndex), LPARAM(i));
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struVQDAlarm.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struVQDAlarm.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struVQDAlarm.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struVQDAlarm.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struVQDAlarm.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struVQDAlarm.dwAbsTime);
CString str = "";
sprintf(szInfoBuf, "VQD extended Alarm Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d]Dev IP[%s] Port[%d] Chan[%d] \
EventType[%d],Threshold[%.3f]",
struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay,
struAbsTime.dwHour, struAbsTime.dwMinute, struAbsTime.dwSecond, struVQDAlarm.struDevInfo.struDevIP.sIpV4,
struVQDAlarm.struDevInfo.wPort, struVQDAlarm.struDevInfo.byChannel,struVQDAlarm.dwEventType,struVQDAlarm.fThreshold);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struVQDAlarm.dwPicDataLen > 0 && struVQDAlarm.pImage != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s].jpg",cFilename, chTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struVQDAlarm.pImage, struVQDAlarm.dwPicDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struVQDAlarm.pImage != NULL)
{
delete [] (struVQDAlarm.pImage);
struVQDAlarm.pImage = NULL;
}
}
// void CClientDemoDlg::OnMenuTs()
// {
// int iDeviceIndex = GetCurDeviceIndex();
// if (iDeviceIndex < 0)
// {
// return;
// }
//
// int iChanIndex = GetCurChanIndex();
// if (iChanIndex < 0)
// {
// iChanIndex = 0;//default to config channel one
// }
//
// STRU_CHANNEL_INFO *pChannelInfo = &(g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex]);
// int iChanShow = pChannelInfo->iChannelNO;
//
// CDlgTsSeries dlg;
// dlg.m_lLoginID = g_struDeviceInfo[iDeviceIndex].lLoginID;
// dlg.m_iDeviceIndex = iDeviceIndex;
// dlg.m_lChannel = iChanShow;
// dlg.DoModal();
// }
// void CClientDemoDlg::OnMenuIPIntell()
// {
// // TODO: Add your command handler code here
// int iDeviceIndex = GetCurDeviceIndex();
// if (iDeviceIndex < 0)
// {
// return;
// }
//
//
// int iChanIndex = GetCurChanIndex();
// if (iChanIndex < 0)
// {
// iChanIndex = 0;//default to config channel one
// }
//
// CDlgIPCSimpIntellCfg dlg;
// dlg.m_lLoginID = g_struDeviceInfo[iDeviceIndex].lLoginID;
// dlg.m_iDeviceIndex = iDeviceIndex;
// dlg.m_lChannel = iChanIndex + g_struDeviceInfo[iDeviceIndex].iStartChan;
// dlg.m_iChanCount = g_struDeviceInfo[iDeviceIndex].iDeviceChanNum;
// dlg.m_iAnaChanCount = g_struDeviceInfo[iDeviceIndex].iAnalogChanNum;
// dlg.m_iDStartChannel = g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].dwStartDChan;
//
// dlg.DoModal();
// }
// void CClientDemoDlg::OnMenuIpcSpecialex()
// {
// //2013-06-17
// int iDeviceIndex = GetCurDeviceIndex();
// if (iDeviceIndex < 0)
// {
// return;
// }
//
//
// int iChanIndex = GetCurChanIndex();
// if (iChanIndex < 0)
// {
// iChanIndex = 0;
// }
//
// CDlgIPCSpeclalEx dlg;
// dlg.m_lLoginID = g_struDeviceInfo[iDeviceIndex].lLoginID;
// dlg.m_iDeviceIndex = iDeviceIndex;
// dlg.m_lChannel = iChanIndex + g_struDeviceInfo[iDeviceIndex].iStartChan;
// dlg.m_iChanCount = g_struDeviceInfo[iDeviceIndex].iDeviceChanNum;
// dlg.m_iAnaChanCount = g_struDeviceInfo[iDeviceIndex].iAnalogChanNum;
// dlg.m_iDStartChannel = g_struDeviceInfo[iDeviceIndex].pStruIPParaCfgV40[0].dwStartDChan;
//
// dlg.DoModal();
// }
void CClientDemoDlg::OnMENUT1Test()
{
// TODO: Add your command handler code here
CDlgT1test dlg;
int iDevIndex = GetCurDeviceIndex();
if (iDevIndex < 0)
{
return;
}
dlg.m_iDeviceIndex = iDevIndex;
dlg.DoModal();
}
// void CClientDemoDlg::OnMenuGBT28181Protocol()
// {
// int iDeviceIndex = GetCurDeviceIndex();
// if (iDeviceIndex < 0)
// {
// return;
// }
// CDlgGBT28181ProtocolAccess dlg;
// dlg.m_lServerID = g_struDeviceInfo[iDeviceIndex].lLoginID;
// dlg.m_dwAlarmOutNum = g_struDeviceInfo[iDeviceIndex].iAlarmOutNum;
// dlg.m_dwDevIndex = iDeviceIndex;
// dlg.m_nChannel = g_struDeviceInfo[iDeviceIndex].iDeviceChanNum;
// dlg.m_lStartChan = g_struDeviceInfo[iDeviceIndex].iStartChan;
// dlg.m_dwAlarmInNum = g_struDeviceInfo[iDeviceIndex].iAlarmInNum;
// dlg.DoModal();
// }
// void CClientDemoDlg::OnMenuDevServer()
// {
// int iDeviceIndex = GetCurDeviceIndex();
// if (iDeviceIndex < 0)
// {
// return;
// }
// CDlgDevServer dlg;
// dlg.m_lServerID = g_struDeviceInfo[iDeviceIndex].lLoginID;
// dlg.m_dwAlarmOutNum = g_struDeviceInfo[iDeviceIndex].iAlarmOutNum;
// dlg.m_dwDevIndex = iDeviceIndex;
// dlg.m_nChannel = g_struDeviceInfo[iDeviceIndex].iDeviceChanNum;
// dlg.m_lStartChan = g_struDeviceInfo[iDeviceIndex].iStartChan;
// dlg.m_dwAlarmInNum = g_struDeviceInfo[iDeviceIndex].iAlarmInNum;
// dlg.DoModal();
// }
void CClientDemoDlg::OnMenuProductionLineTest()
{
// TODO: Add your command handler code here
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex < 0)
{
return;
}
int iChanIndex = GetCurChanIndex();
if (iChanIndex < 0)
{
iChanIndex = 0;
}
CDlgProductionTest dlg;
dlg.m_lUserID = g_struDeviceInfo[iDeviceIndex].lLoginID;
dlg.m_dwChannel = iChanIndex + g_struDeviceInfo[iDeviceIndex].iStartChan;
dlg.m_iDevIndex = iDeviceIndex;
dlg.DoModal();
}
void CClientDemoDlg::OnMenuVca()
{
// TODO: Add your command handler code here
DlgVCADetionCfg dlg;
dlg.DoModal();
}
// void CClientDemoDlg::OnMenuItsIoinCfg()
// {
// // TODO: Add your command handler code here
// int iDeviceIndex = GetCurDeviceIndex();
// if (iDeviceIndex < 0)
// {
// return;
// }
// int iChanIndex = GetCurChanIndex();
// if (iChanIndex < 0)
// {
// iChanIndex = 0;
// }
// CDlgITSIOinCfg dlg;
// dlg.m_lUserID = g_struDeviceInfo[iDeviceIndex].lLoginID;
// dlg.m_dwChannel = iChanIndex + g_struDeviceInfo[iDeviceIndex].iStartChan;
// dlg.m_iDevIndex = iDeviceIndex;
// dlg.DoModal();
// }
void CClientDemoDlg::OnBtntProductCfg()
{
CRect rectConfig(0,0,0,0);
rectConfig.top = m_iFunBtnHeight-2;
rectConfig.left = m_iTreeWidth-2;//-2 cover preview box
rectConfig.right = DEMO_FULL_WIDTH - m_iRightWidth ;
rectConfig.bottom = DEMO_FULL_HEIGHT - m_iListLogHeight;//+4
if (m_iMainType != PRODUCT_RELATE_T)
{
m_iMainType = PRODUCT_RELATE_T;
PreviewReferShow(FALSE);
ConfigAllHide();
// m_dlgPlayBack->HideAll();
//InitConfigAllRefer();
// m_dlgProductCfg->MoveWindow(rectConfig);
// m_dlgProductCfg->ShowWindow(SW_SHOW);
InitProdouctCfgRefer();
m_dlgProductCfg->UpdateWindowParam(GetCurDeviceIndex(),GetCurChanIndex());
}
/*
int iDeviceIndex = GetCurDeviceIndex();
if (iDeviceIndex < 0)
{
return;
}
if (g_struDeviceInfo[iDeviceIndex].lLoginID < 0)
{
AddLog(-1, OPERATION_SUCC_T, "device is offline!");
return;
}
LONG lChannel = -1;
int iChanIndex = GetCurChanIndex();
if (iChanIndex >= 0)
{
lChannel = g_struDeviceInfo[iDeviceIndex].pStruChanInfo[iChanIndex].iChannelNO;
}
CDlgProductCfg dlg;
dlg.m_lUserID = g_struDeviceInfo[iDeviceIndex].lLoginID;
dlg.m_lChannel = lChannel;
dlg.m_iDevIndex = iDeviceIndex;
dlg.DoModal();
*/
}
void CClientDemoDlg::InitProdouctCfgRefer()
{
if (!m_dlgProductCfg->IsWindowVisible())
{
CRect rectProductCfg(0,0,0,0);
rectProductCfg.top = m_iFunBtnHeight-2;
rectProductCfg.left = m_iTreeWidth-2;//-2 cover preview box
rectProductCfg.right = DEMO_FULL_WIDTH;
rectProductCfg.bottom = DEMO_FULL_HEIGHT - m_iListLogHeight;//+4
m_dlgProductCfg->MoveWindow(&rectProductCfg,TRUE);
m_dlgProductCfg->ShowWindow(SW_SHOW);
}
}
//车辆二次识别数据上传
void CClientDemoDlg::ProVehicleRecogResult( WPARAM wParam, LPARAM lParam )
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = {0};
g_StringLanType(szLan, "车辆二次识别数据上传","Upload a secondary vehicle identification data");
NET_DVR_VEHICLE_RECOG_RESULT struVehicleRecogResult;
memset(&struVehicleRecogResult, 0, sizeof(struVehicleRecogResult));
memcpy(&struVehicleRecogResult, pAlarmInfo, sizeof(struVehicleRecogResult));
sprintf(szInfoBuf, "%s:PostID[%d] PostTime{wYear[%d] byMonth[%d] byDay[%d] byHour[%d] byMinute[%d] bySecond[%d] wMilliSec[%d]}DataIndex[%s] TaskNo[%d] PlateRect{fX[%f] fY[%f] fWidth[%f] fHeight[%f]} sLicense[%s] VehicleType[%d] ColorDepth[%d] CarColor[%d] \
VehicleLogoRecog[%d] VehicleSubLogoRecog[%d] PilotSafebelt[%d] CopilotSafebelt[%d] PilotSunVisor[%d] CopilotSunVisor[%d] DataType[%d] PicType[%d] \
VehicleModel[%d] VehicleLogoRecogEx[%d] VehicleRect{fX[%f] fY[%f] fWidth[%f] fHeight[%f]} PilotRect{fX[%f] fY[%f] fWidth[%f] fHeight[%f]} CopilotRect{fX[%f] fY[%f] fWidth[%f] fHeight[%f]}", \
szLan, struVehicleRecogResult.dwPostID, struVehicleRecogResult.struPostTime.wYear, struVehicleRecogResult.struPostTime.byMonth, struVehicleRecogResult.struPostTime.byDay, \
struVehicleRecogResult.struPostTime.byHour, struVehicleRecogResult.struPostTime.byMinute, struVehicleRecogResult.struPostTime.bySecond, struVehicleRecogResult.struPostTime.wMilliSec, \
struVehicleRecogResult.sDataIndex, struVehicleRecogResult.wTaskNo, struVehicleRecogResult.struPlateRect.fX, struVehicleRecogResult.struPlateRect.fY, \
struVehicleRecogResult.struPlateRect.fWidth, struVehicleRecogResult.struPlateRect.fHeight, struVehicleRecogResult.sLicense, struVehicleRecogResult.byVehicleType, \
struVehicleRecogResult.byColorDepth, struVehicleRecogResult.byColor, struVehicleRecogResult.byVehicleLogoRecog, struVehicleRecogResult.byVehicleSubLogoRecog, \
struVehicleRecogResult.byPilotSafebelt, struVehicleRecogResult.byCopilotSafebelt, struVehicleRecogResult.byPilotSunVisor, struVehicleRecogResult.byCopilotSunVisor, \
struVehicleRecogResult.byDataType, struVehicleRecogResult.dwPicType, struVehicleRecogResult.byVehicleLogoRecog, struVehicleRecogResult.wVehicleLogoRecog, \
struVehicleRecogResult.struVehicleRect.fX, struVehicleRecogResult.struVehicleRect.fY, struVehicleRecogResult.struVehicleRect.fWidth, struVehicleRecogResult.struVehicleRect.fHeight, \
struVehicleRecogResult.struPilotRect.fX, struVehicleRecogResult.struPilotRect.fY, struVehicleRecogResult.struPilotRect.fWidth, struVehicleRecogResult.struPilotRect.fHeight, \
struVehicleRecogResult.struCopilotRect.fX, struVehicleRecogResult.struCopilotRect.fY, struVehicleRecogResult.struCopilotRect.fWidth, struVehicleRecogResult.struCopilotRect.fHeight);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
if (struVehicleRecogResult.dwVehicleBufferLen > 0 && struVehicleRecogResult.pVehicleBuffer != NULL)
{
char cFilename[256] = {0};
DWORD dwWrittenBytes = 0;
if (iDeviceIndex != -1 && iDeviceIndex < 512)
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[Vehicle]");
}
else
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP, "[Vehicle]");
}
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime,rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struVehicleRecogResult.pVehicleBuffer, struVehicleRecogResult.dwVehicleBufferLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struVehicleRecogResult.dwVehicleBufferLen )
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Vehicle Picture Wtite to File Fail.System Error:%d, dwVehicleBufferLen:%d, dwWrittenBytes:%d ", dwError, struVehicleRecogResult.dwVehicleBufferLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struVehicleRecogResult.dwPlateBufferLen> 0 && struVehicleRecogResult.pPlateBuffer != NULL)
{
char cFilename[256] = {0};
DWORD dwWrittenBytes = 0;
if (iDeviceIndex != -1 && iDeviceIndex < 512)
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[Plate]");
}
else
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP, "[Plate]");
}
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime,rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struVehicleRecogResult.pPlateBuffer, struVehicleRecogResult.dwPlateBufferLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struVehicleRecogResult.dwPlateBufferLen )
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Plate Picture Wtite to File Fail.System Error:%d, dwPlateBufferLen:%d, dwWrittenBytes:%d ", dwError, struVehicleRecogResult.dwPlateBufferLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struVehicleRecogResult.dwPilotFaceBufferLen > 0 && struVehicleRecogResult.pPilotFaceBuffer != NULL)
{
char cFilename[256] = {0};
DWORD dwWrittenBytes = 0;
if (iDeviceIndex != -1 && iDeviceIndex < 512)
{
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[PilotFace]");
}
else
{
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP, "[PilotFace]");
}
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime,rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struVehicleRecogResult.pPilotFaceBuffer, struVehicleRecogResult.dwPilotFaceBufferLen , &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struVehicleRecogResult.dwPilotFaceBufferLen )
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "PilotFace Picture Wtite to File Fail.System Error:%d, dwPilotFaceBufferLen:%d, dwWrittenBytes:%d ", dwError, struVehicleRecogResult.dwPilotFaceBufferLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struVehicleRecogResult.dwCopilotFaceBufferLen > 0 && struVehicleRecogResult.pCopilotFaceBuffer != NULL)
{
char cFilename[256] = {0};
DWORD dwWrittenBytes = 0;
if (iDeviceIndex != -1 && iDeviceIndex < 512)
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[CopilotFace]");
}
else
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP, "[CopilotFace]");
}
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime,rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struVehicleRecogResult.pCopilotFaceBuffer, struVehicleRecogResult.dwCopilotFaceBufferLen , &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struVehicleRecogResult.dwCopilotFaceBufferLen )
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "CopilotFace Picture Wtite to File Fail.System Error:%d, dwCopilotFaceBufferLen:%d, dwWrittenBytes:%d ", dwError, struVehicleRecogResult.dwCopilotFaceBufferLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struVehicleRecogResult.dwPilotSafebeltBufferLen > 0 && struVehicleRecogResult.pPilotSafebeltBuffer != NULL)
{
char cFilename[256] = {0};
DWORD dwWrittenBytes = 0;
if (iDeviceIndex != -1 && iDeviceIndex < 512)
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[PilotSafe]");
}
else
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP, "[PilotSafe]");
}
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime,rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struVehicleRecogResult.pPilotSafebeltBuffer, struVehicleRecogResult.dwPilotSafebeltBufferLen , &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struVehicleRecogResult.dwPilotSafebeltBufferLen )
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "PilotSafe Picture Wtite to File Fail.System Error:%d, dwPilotSafebeltBufferLen:%d, dwWrittenBytes:%d ", dwError, struVehicleRecogResult.dwPilotSafebeltBufferLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struVehicleRecogResult.dwCopilotSafebeltBufferLen > 0 && struVehicleRecogResult.pCopilotSafebeltBuffer != NULL)
{
char cFilename[256] = {0};
DWORD dwWrittenBytes = 0;
if (iDeviceIndex != -1 && iDeviceIndex < 512)
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[CopilotSafe]");
}
else
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP, "[CopilotSafe]");
}
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime,rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struVehicleRecogResult.pCopilotSafebeltBuffer, struVehicleRecogResult.dwCopilotSafebeltBufferLen , &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struVehicleRecogResult.dwCopilotSafebeltBufferLen )
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "CopilotSafe Picture Wtite to File Fail.System Error:%d, dwCopilotSafebeltBufferLen:%d, dwWrittenBytes:%d ", dwError, struVehicleRecogResult.dwCopilotSafebeltBufferLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struVehicleRecogResult.dwJsonBufferLen > 0 && struVehicleRecogResult.pJsonBuffer != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
if (iDeviceIndex != -1 && iDeviceIndex < 512)
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[JSON]");
}
else
{
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP, "[JSON]");
}
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struVehicleRecogResult.pJsonBuffer, struVehicleRecogResult.dwJsonBufferLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struVehicleRecogResult.dwJsonBufferLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Json Data Write to File Fail.System Error:%d, dwJsonBufferLen :%d, dwWrittenBytes:%d ", dwError, struVehicleRecogResult.dwJsonBufferLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
//释放图片内存
if (struVehicleRecogResult.pVehicleBuffer != NULL)
{
delete [] (struVehicleRecogResult.pVehicleBuffer);
struVehicleRecogResult.pVehicleBuffer = NULL;
}
//释放图片内存
if (struVehicleRecogResult.pPlateBuffer != NULL)
{
delete [] (struVehicleRecogResult.pPlateBuffer);
struVehicleRecogResult.pPlateBuffer = NULL;
}
//释放图片内存
if (struVehicleRecogResult.pPilotFaceBuffer != NULL)
{
delete [] (struVehicleRecogResult.pPilotFaceBuffer);
struVehicleRecogResult.pPilotFaceBuffer = NULL;
}
//释放图片内存
if (struVehicleRecogResult.pCopilotFaceBuffer != NULL)
{
delete [] (struVehicleRecogResult.pCopilotFaceBuffer);
struVehicleRecogResult.pCopilotFaceBuffer = NULL;
}
//释放图片内存
if (struVehicleRecogResult.pPilotSafebeltBuffer != NULL)
{
delete [] (struVehicleRecogResult.pPilotSafebeltBuffer);
struVehicleRecogResult.pPilotSafebeltBuffer = NULL;
}
//释放图片内存
if (struVehicleRecogResult.pCopilotSafebeltBuffer != NULL)
{
delete [] (struVehicleRecogResult.pCopilotSafebeltBuffer);
struVehicleRecogResult.pCopilotSafebeltBuffer = NULL;
}
//释放JSON内存
if (struVehicleRecogResult.pJsonBuffer != NULL)
{
delete[](struVehicleRecogResult.pJsonBuffer);
struVehicleRecogResult.pJsonBuffer = NULL;
}
}
void CClientDemoDlg::ProSensorInfoAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = {0};
g_StringLanType(szLan, "传感器信息上传","Sensor Info Upload");
NET_DVR_SENSOR_INFO_UPLOAD struSensorInfo;
memset(&struSensorInfo, 0, sizeof(struSensorInfo));
memcpy(&struSensorInfo, pAlarmInfo, sizeof(struSensorInfo));
sprintf(szInfoBuf, "%s: Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d] SensorName[%s] SensorChan[%s] Reboot[%d] PowerSupply[%d] StatusType[%d],\
SensorType[%d] VoltageValue[%f] CurrentValue[%f] ActualValue[%f] Description[%s]", szLan, struSensorInfo.struTime.wYear, struSensorInfo.struTime.byMonth, \
struSensorInfo.struTime.byDay, struSensorInfo.struTime.byHour, struSensorInfo.struTime.byMinute, struSensorInfo.struTime.bySecond, struSensorInfo.struTime.wMilliSec, \
struSensorInfo.szSensorName, struSensorInfo.szSensorChan, struSensorInfo.byReboot, struSensorInfo.byPowerSupply, struSensorInfo.byStatusType, \
struSensorInfo.bySensorType, struSensorInfo.fVoltageValue, struSensorInfo.fCurrentValue, struSensorInfo.fActualValue, struSensorInfo.szDescription);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProCaptureAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = {0};
g_StringLanType(szLan, "抓拍图片上传","Capture Upload");
NET_DVR_CAPTURE_UPLOAD struCaptureUplad;
memset(&struCaptureUplad, 0, sizeof(struCaptureUplad));
memcpy(&struCaptureUplad, pAlarmInfo, sizeof(struCaptureUplad));
sprintf(szInfoBuf, "%s: Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d], Channel[%d], DevName[%s], PicLen[%d]", szLan, struCaptureUplad.struTime.wYear,\
struCaptureUplad.struTime.byMonth, struCaptureUplad.struTime.byDay, struCaptureUplad.struTime.byHour, struCaptureUplad.struTime.byMinute,\
struCaptureUplad.struTime.bySecond, struCaptureUplad.struTime.wMilliSec, struCaptureUplad.dwChannel, struCaptureUplad.szDevName, struCaptureUplad.dwPicLen);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
if (struCaptureUplad.dwPicLen > 0 && struCaptureUplad.pBuffer != NULL)
{
char cFilename[256] = {0};
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[Sensor]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime,rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struCaptureUplad.pBuffer, struCaptureUplad.dwPicLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struCaptureUplad.dwPicLen )
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Vehicle Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struCaptureUplad.dwPicLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struCaptureUplad.pBuffer != NULL)
{
delete [] (struCaptureUplad.pBuffer);
struCaptureUplad.pBuffer = NULL;
}
}
void CClientDemoDlg::ProFaceThermometryAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = { 0 };
g_StringLanType(szLan, "人脸测温报警上传", "Fire Detection");
NET_DVR_FACE_THERMOMETRY_ALARM struFaceThermometry;
memset(&struFaceThermometry, 0, sizeof(struFaceThermometry));
memcpy(&struFaceThermometry, pAlarmInfo, sizeof(struFaceThermometry));
sprintf(szInfoBuf, "%s Channel[%d] AlarmRule[%d] RuleID[%d] RuleName[%s]\
RelativeTime[%d] AbsTime[%d] FaceDetectionState[%d] ThermometryUnit[%d]\
AlarmTemperature[%0.1f] RuleTemperature[%0.1f] VisibleLightImageLen[%d] FaceImageLen[%d]\
FaceRect[x:%0.3f y:%0.3f width:%0.3f hight:%0.3f]\
MinTemperature[%0.1f] AverageTemperature[%0.1f]\
MinTemperaturePoint[X:%0.2f Y:%0.2f] MaxTemperaturePoint[X:%0.2f Y:%0.2f] ",
szLan, struFaceThermometry.dwChannel,struFaceThermometry.byAlarmRule, struFaceThermometry.byRuleID,struFaceThermometry.byRuleName,
struFaceThermometry.dwRelativeTime, struFaceThermometry.dwAbsTime, struFaceThermometry.byFaceDetectionState, struFaceThermometry.byThermometryUnit,
struFaceThermometry.fAlarmTemperature, struFaceThermometry.fRuleTemperature, struFaceThermometry.dwVisibleLightImageLen, struFaceThermometry.dwFaceImageLen,
struFaceThermometry.struFaceRegion.fX, struFaceThermometry.struFaceRegion.fY, struFaceThermometry.struFaceRegion.fWidth,struFaceThermometry.struFaceRegion.fHeight,
struFaceThermometry.fMinTemperature, struFaceThermometry.fAverageTemperature,
struFaceThermometry.struMinTemperaturePoint.fX, struFaceThermometry.struMinTemperaturePoint.fY,
struFaceThermometry.struMaxTemperaturePoint.fX, struFaceThermometry.struMaxTemperaturePoint.fY);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
char cFilepath[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilepath, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[Sensor]");
if (GetFileAttributes(cFilepath) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilepath, NULL);
}
if (struFaceThermometry.dwVisibleLightImageLen > 0 && struFaceThermometry.pVisibleLightImage != NULL)
{
char cFilename[256] = { 0 };
sprintf(cFilename, "%s\\FT_Vis[%s].jpg", cFilepath, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struFaceThermometry.pVisibleLightImage, struFaceThermometry.dwVisibleLightImageLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struFaceThermometry.dwVisibleLightImageLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "FaceThermometry vis Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struFaceThermometry.dwVisibleLightImageLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struFaceThermometry.pVisibleLightImage != NULL)
{
delete[](struFaceThermometry.pVisibleLightImage);
struFaceThermometry.pVisibleLightImage = NULL;
}
if (struFaceThermometry.dwFaceImageLen > 0 && struFaceThermometry.pFaceImage != NULL)
{
char cFilename[256] = { 0 };
sprintf(cFilename, "%s\\FT_Face[%s].jpg", cFilepath, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struFaceThermometry.pFaceImage, struFaceThermometry.dwFaceImageLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struFaceThermometry.dwFaceImageLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "FaceThermometry face Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struFaceThermometry.dwFaceImageLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struFaceThermometry.pFaceImage != NULL)
{
delete[](struFaceThermometry.pFaceImage);
struFaceThermometry.pFaceImage = NULL;
}
}
void CClientDemoDlg::ProFirDetectionAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
char szSmokeInfoBuf[1024] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
int iPort = pAlarmDev->wLinkPort;
char szLan[128] = {0};
g_StringLanType(szLan, "火点检测报警上传","Fire Detection");
NET_DVR_FIREDETECTION_ALARM struFireDetection;
memset(&struFireDetection, 0, sizeof(struFireDetection));
memcpy(&struFireDetection, pAlarmInfo, sizeof(struFireDetection));
sprintf(szInfoBuf, "flag[%d] %2.2d%2.2d] %s,FireScanWaitMode[%d] VisibleChannel[%d] RelativeTime:%d, AbsTime:%d, PTZ{PanPos:%d, TiltPos:%d, ZoomPos:%d}, PicDataLen:%d, DevInfo{DevIP:%s, Port:%d, Channel:%d, IvmsChannel:%d, IvmsChannelEx:%d}, \
FireMaxTemperature:%d, TargetDistance:%d, fireRectInfo{fX:%f,fY:%f,fWidth%f,fHeight%f}, fireMaxTemperaturePoint{fX:%f,fY:%f}, PTZEx{P:%f,T:%f,Z:%f,F:%d},AlarmSubType:%d",
struFireDetection.byTimeDiffFlag, struFireDetection.cTimeDifferenceH, struFireDetection.cTimeDifferenceM, \
szLan, struFireDetection.byFireScanWaitMode, struFireDetection.dwVisibleChannel, struFireDetection.dwRelativeTime, struFireDetection.dwAbsTime, struFireDetection.wPanPos, struFireDetection.wTiltPos, struFireDetection.wZoomPos, \
struFireDetection.dwPicDataLen, struFireDetection.struDevInfo.struDevIP.sIpV4, struFireDetection.struDevInfo.wPort, struFireDetection.struDevInfo.byChannel, \
struFireDetection.struDevInfo.byIvmsChannel, struFireDetection.wDevInfoIvmsChannelEx, \
struFireDetection.wFireMaxTemperature, struFireDetection.wTargetDistance, \
struFireDetection.struRect.fX, struFireDetection.struRect.fY, struFireDetection.struRect.fWidth, struFireDetection.struRect.fHeight, \
struFireDetection.struPoint.fX, struFireDetection.struPoint.fY, \
struFireDetection.struPtzPosEx.fPan, struFireDetection.struPtzPosEx.fTilt, struFireDetection.struPtzPosEx.fZoom, struFireDetection.struPtzPosEx.dwFocus, struFireDetection.byAlarmSubType);
if (struFireDetection.byAlarmSubType > 0 && struFireDetection.pSmokeBuf != NULL)
{
NET_DVR_SMOKEDETECTION_ALARM struSmokeDetection;
memset(&struSmokeDetection, 0, sizeof(struSmokeDetection));
memcpy(&struSmokeDetection, struFireDetection.pSmokeBuf, sizeof(struSmokeDetection));
sprintf_s(szSmokeInfoBuf, "SMOKEDELETECTION ALARM INFO: PTZPos{P:%f, T:%f, Z:%f, Focus:%d}, ThermalPTZPos{P:%f, T:%f, Z:%f, Focus:%d}, Latitude{Type:%d, Sec:%f, Degree:%d, Minute:%d}, Longitude{Type:%d, Sec:%f, Degree:%d, Minute:%d}, SmokePos{X:%f, Y:%f, Width:%f, Height:%f}",
struSmokeDetection.struPTZPos.fPan, struSmokeDetection.struPTZPos.fTilt, struSmokeDetection.struPTZPos.fZoom, struSmokeDetection.struPTZPos.dwFocus, \
struSmokeDetection.struThermalPTZPos.fPan, struSmokeDetection.struThermalPTZPos.fTilt, struSmokeDetection.struThermalPTZPos.fZoom, struSmokeDetection.struThermalPTZPos.dwFocus, \
struSmokeDetection.struLLPos.byLatitudeType, struSmokeDetection.struLLPos.struLatitude.fSec, struSmokeDetection.struLLPos.struLatitude.byDegree, struSmokeDetection.struLLPos.struLatitude.byMinute, \
struSmokeDetection.struLLPos.byLongitudeType, struSmokeDetection.struLLPos.struLongitude.fSec, struSmokeDetection.struLLPos.struLongitude.byDegree, struSmokeDetection.struLLPos.struLongitude.byMinute, \
struSmokeDetection.struSmokePos.fX, struSmokeDetection.struSmokePos.fY, struSmokeDetection.struSmokePos.fWidth, struSmokeDetection.struSmokePos.fHeight);
strcat(szInfoBuf, szSmokeInfoBuf);
}
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struFireDetection.pSmokeBuf != NULL)
{
delete[](struFireDetection.pSmokeBuf);
struFireDetection.pSmokeBuf = NULL;
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
if (struFireDetection.dwPicDataLen > 0 && struFireDetection.pBuffer != NULL)
{
char cFilename[256] = {0};
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%d][%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, "[Sensor]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struFireDetection.byPicTransType)
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
}
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struFireDetection.pBuffer, struFireDetection.dwPicDataLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struFireDetection.dwPicDataLen )
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Fire Detection Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struFireDetection.dwPicDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struFireDetection.pBuffer != NULL)
{
delete [] (struFireDetection.pBuffer);
struFireDetection.pBuffer = NULL;
}
if (struFireDetection.dwVisiblePicLen > 0 && struFireDetection.pVisiblePicBuf != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%d][%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, "[Sensor]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struFireDetection.byPicTransType)
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
}
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struFireDetection.pVisiblePicBuf, struFireDetection.dwVisiblePicLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struFireDetection.dwVisiblePicLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Fire Detection VisiblePicture Wtite to File Fail.System Error:%d, dwVisiblePicLen:%d, pVisibleBuffer:%d ", dwError, struFireDetection.dwVisiblePicLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struFireDetection.pVisiblePicBuf != NULL)
{
delete[](struFireDetection.pVisiblePicBuf);
struFireDetection.pVisiblePicBuf = NULL;
}
}
void CClientDemoDlg::ProPicInfoUploadAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = { 0 };
g_StringLanType(szLan, "图片信息上传报警", "PicInfo Upload");
NET_DVR_PANORAMIC_LINKAGE struPicInfoUpload;
memset(&struPicInfoUpload, 0, sizeof(struPicInfoUpload));
memcpy(&struPicInfoUpload, pAlarmInfo, sizeof(struPicInfoUpload));
sprintf(szInfoBuf, "%s, Channel:%d, Type:%d, MACAddr:%x:%x:%x:%x:%x:%x, PicDataLen:%d",
szLan, struPicInfoUpload.dwChannel, struPicInfoUpload.byType, struPicInfoUpload.byMACAddr[0], struPicInfoUpload.byMACAddr[1], struPicInfoUpload.byMACAddr[2], struPicInfoUpload.byMACAddr[3], struPicInfoUpload.byMACAddr[4], struPicInfoUpload.byMACAddr[5], struPicInfoUpload.dwPicLen);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
if (struPicInfoUpload.dwPicLen > 0 && struPicInfoUpload.pPicBuff != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[Sensor]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struPicInfoUpload.pPicBuff, struPicInfoUpload.dwPicLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struPicInfoUpload.dwPicLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "PicInfo Upload Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struPicInfoUpload.dwPicLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struPicInfoUpload.pPicBuff != NULL)
{
delete[](struPicInfoUpload.pPicBuff);
struPicInfoUpload.pPicBuff = NULL;
}
}
void CClientDemoDlg::ProGISInfoAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = {0};
g_StringLanType(szLan, "GIS信息报警上传","GIS Info");
NET_DVR_GIS_UPLOADINFO struGISInfo;
memset(&struGISInfo, 0, sizeof(struGISInfo));
memcpy(&struGISInfo, pAlarmInfo, sizeof(struGISInfo));
sprintf(szInfoBuf, "%s:PtzPos{PanPos:%.1fTiltPos:%.1fZoomPos:%.1f}RelTime:%dAbsTime:%dAzimuth:%fLongitudeType:%dLatitudeType:%dLongitude{Sec:%.6fDegree:%dMinute:%d}Latitude{Sec:%.6fDegree:%dMinute:%d}Horizontal:%fVertical:%fVisibleRadius:%fMaxView:%fSensor{Type:%dWidth:%fWidth:%fFold:%f}DevInfo{DevIP:%sPort:%dChan:%dIvmsChan:%d}",
szLan, struGISInfo.struPtzPos.fPanPos, struGISInfo.struPtzPos.fTiltPos, struGISInfo.struPtzPos.fZoomPos, struGISInfo.dwRelativeTime, struGISInfo.dwAbsTime, \
struGISInfo.fAzimuth, struGISInfo.byLongitudeType,\
struGISInfo.byLatitudeType, struGISInfo.struLongitude.fSec, struGISInfo.struLongitude.byDegree, struGISInfo.struLongitude.byMinute,\
struGISInfo.struLatitude.fSec, struGISInfo.struLatitude.byDegree, struGISInfo.struLatitude.byMinute, struGISInfo.fHorizontalValue, struGISInfo.fVerticalValue, struGISInfo.fVisibleRadius, struGISInfo.fMaxViewRadius,\
struGISInfo.struSensorParam.bySensorType, struGISInfo.struSensorParam.fHorWidth, struGISInfo.struSensorParam.fVerWidth, struGISInfo.struSensorParam.fFold,\
struGISInfo.struDevInfo.struDevIP.sIpV4, struGISInfo.struDevInfo.wPort, struGISInfo.struDevInfo.byChannel, struGISInfo.struDevInfo.byIvmsChannel);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProVandalproofAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = {0};
g_StringLanType(szLan, "防破坏报警上传","Vandalproof Alarm");
NET_DVR_VANDALPROOF_ALARM struVandalproof;
memset(&struVandalproof, 0, sizeof(struVandalproof));
memcpy(&struVandalproof, pAlarmInfo, sizeof(struVandalproof));
sprintf(szInfoBuf, "%s: RelativeTime:%d, AbsTime:%d, DevInfo{DevIP:%s, Port:%d, Channel:%d, IvmsChannel:%d}", szLan, struVandalproof.dwRelativeTime, struVandalproof.dwAbsTime, struVandalproof.struDevInfo.struDevIP.sIpV4, \
struVandalproof.struDevInfo.wPort, struVandalproof.struDevInfo.byChannel, struVandalproof.struDevInfo.byIvmsChannel);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcVideoIntercomEvent(WPARAM wParam,LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_VIDEO_INTERCOM_EVENT struVideoIntercomEvent = {0};
CTime time = CTime::GetCurrentTime();
memcpy(&struVideoIntercomEvent, pAlarmInfo, sizeof(struVideoIntercomEvent));
if (struVideoIntercomEvent.byEventType == 3)
{
sprintf(szInfoBuf, "Video Intercom Event Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] DevNumber[%s] EventType[%d] AuthResult[%d] AuthType[%d] CardNo[%s]",
struVideoIntercomEvent.struTime.wYear, struVideoIntercomEvent.struTime.byMonth, struVideoIntercomEvent.struTime.byDay,
struVideoIntercomEvent.struTime.byHour, struVideoIntercomEvent.struTime.byMinute, struVideoIntercomEvent.struTime.bySecond,
struVideoIntercomEvent.byDevNumber, struVideoIntercomEvent.byEventType, struVideoIntercomEvent.uEventInfo.struAuthInfo.byAuthResult,
struVideoIntercomEvent.uEventInfo.struAuthInfo.byAuthType, struVideoIntercomEvent.uEventInfo.struAuthInfo.byCardNo);
}
else if (struVideoIntercomEvent.byEventType == 4)
{
sprintf(szInfoBuf, "Video Intercom Event Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] DevNumber[%s] EventType[%d] License[%s] Color[%d]",
struVideoIntercomEvent.struTime.wYear, struVideoIntercomEvent.struTime.byMonth, struVideoIntercomEvent.struTime.byDay,
struVideoIntercomEvent.struTime.byHour, struVideoIntercomEvent.struTime.byMinute, struVideoIntercomEvent.struTime.bySecond,
struVideoIntercomEvent.byDevNumber, struVideoIntercomEvent.byEventType, struVideoIntercomEvent.uEventInfo.struUploadPlateInfo.sLicense,
struVideoIntercomEvent.uEventInfo.struUploadPlateInfo.byColor);
}
else if (struVideoIntercomEvent.byEventType == 1)
{
sprintf(szInfoBuf, "Video Intercom Event Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] DevNumber[%s] EventType[%d], FloorNumber[%d], RoomNumber[%d], LockID[%d],LockName[%s],EmployeeNo[%s]",
struVideoIntercomEvent.struTime.wYear, struVideoIntercomEvent.struTime.byMonth, struVideoIntercomEvent.struTime.byDay,
struVideoIntercomEvent.struTime.byHour, struVideoIntercomEvent.struTime.byMinute, struVideoIntercomEvent.struTime.bySecond,
struVideoIntercomEvent.byDevNumber, struVideoIntercomEvent.byEventType,
struVideoIntercomEvent.uEventInfo.struUnlockRecord.nFloorNumber,
struVideoIntercomEvent.uEventInfo.struUnlockRecord.wRoomNumber,
struVideoIntercomEvent.uEventInfo.struUnlockRecord.wLockID,
struVideoIntercomEvent.uEventInfo.struUnlockRecord.byLockName,
struVideoIntercomEvent.uEventInfo.struUnlockRecord.byEmployeeNo);
}
else if (struVideoIntercomEvent.byEventType == 5 || struVideoIntercomEvent.byEventType == 6)
{
sprintf(szInfoBuf, "Video Intercom Event Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] DevNumber[%s] EventType[%d] CardNo[%s]",
struVideoIntercomEvent.struTime.wYear, struVideoIntercomEvent.struTime.byMonth, struVideoIntercomEvent.struTime.byDay,
struVideoIntercomEvent.struTime.byHour, struVideoIntercomEvent.struTime.byMinute, struVideoIntercomEvent.struTime.bySecond,
struVideoIntercomEvent.byDevNumber, struVideoIntercomEvent.byEventType,
struVideoIntercomEvent.uEventInfo.struSendCardInfo.byCardNo);
}
else
{
sprintf(szInfoBuf, "Video Intercom Event Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] DevNumber[%s] EventType[%d]",
struVideoIntercomEvent.struTime.wYear, struVideoIntercomEvent.struTime.byMonth, struVideoIntercomEvent.struTime.byDay,
struVideoIntercomEvent.struTime.byHour, struVideoIntercomEvent.struTime.byMinute, struVideoIntercomEvent.struTime.bySecond,
struVideoIntercomEvent.byDevNumber, struVideoIntercomEvent.byEventType);
}
if (struVideoIntercomEvent.dwIOTChannelNo != 0)
{
sprintf(szInfoBuf, "%d IOTChannelNo", struVideoIntercomEvent.dwIOTChannelNo);
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struVideoIntercomEvent.byEventType == 1 && struVideoIntercomEvent.uEventInfo.struUnlockRecord.dwPicDataLen > 0)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struVideoIntercomEvent.byPicTransType)
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
}
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struVideoIntercomEvent.uEventInfo.struUnlockRecord.pImage, struVideoIntercomEvent.uEventInfo.struUnlockRecord.dwPicDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
delete [] struVideoIntercomEvent.uEventInfo.struUnlockRecord.pImage;
struVideoIntercomEvent.uEventInfo.struUnlockRecord.pImage = NULL;
}
if (struVideoIntercomEvent.byEventType == 3 && struVideoIntercomEvent.uEventInfo.struAuthInfo.dwPicDataLen > 0)
{
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
char cFilename[256] = { 0 };
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s].jpg", cFilename, chTime);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struVideoIntercomEvent.uEventInfo.struAuthInfo.pImage, struVideoIntercomEvent.uEventInfo.struAuthInfo.dwPicDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
delete[] struVideoIntercomEvent.uEventInfo.struAuthInfo.pImage;
struVideoIntercomEvent.uEventInfo.struAuthInfo.pImage = NULL;
}
}
void CClientDemoDlg::ProcVideoIntercomAlarm(WPARAM wParam,LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_VIDEO_INTERCOM_ALARM struVideoIntercomAlarm = {0};
CTime time = CTime::GetCurrentTime();
memcpy(&struVideoIntercomAlarm, pAlarmInfo, sizeof(struVideoIntercomAlarm));
if (struVideoIntercomAlarm.byAlarmType == 1)
{
sprintf(szInfoBuf, "Video Intercom Alarm Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] DevNumber[%s] AlarmType[%d] ZoneName[%s] ZoneIndex[%d] ZoneType[%d] IOTChannelNo[%d]",
struVideoIntercomAlarm.struTime.wYear, struVideoIntercomAlarm.struTime.byMonth, struVideoIntercomAlarm.struTime.byDay,
struVideoIntercomAlarm.struTime.byHour, struVideoIntercomAlarm.struTime.byMinute, struVideoIntercomAlarm.struTime.bySecond,
struVideoIntercomAlarm.byDevNumber, struVideoIntercomAlarm.byAlarmType, struVideoIntercomAlarm.uAlarmInfo.struZoneAlarm.byZoneName,
struVideoIntercomAlarm.uAlarmInfo.struZoneAlarm.dwZonendex, struVideoIntercomAlarm.uAlarmInfo.struZoneAlarm.byZoneType,
struVideoIntercomAlarm.dwIOTChannelNo);
}
else
{
sprintf(szInfoBuf, "Video Intercom Alarm Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] DevNumber[%s] AlarmType[%d] LockID[%d] IOTChannelNo[%d]",
struVideoIntercomAlarm.struTime.wYear, struVideoIntercomAlarm.struTime.byMonth, struVideoIntercomAlarm.struTime.byDay,
struVideoIntercomAlarm.struTime.byHour, struVideoIntercomAlarm.struTime.byMinute, struVideoIntercomAlarm.struTime.bySecond,
struVideoIntercomAlarm.byDevNumber, struVideoIntercomAlarm.byAlarmType,
struVideoIntercomAlarm.wLockID, struVideoIntercomAlarm.dwIOTChannelNo);
if (struVideoIntercomAlarm.byAlarmType == 8)
{
CDlgVideoIntercomCall dlg;
dlg.m_iDevIndex = pAlarmDev->iDeviceIndex;
dlg.m_lUserID = m_iCardChanCount;
dlg.m_byRequestType = 1;
dlg.DoModal();
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcUploadNoticeData(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[4096] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_NOTICE_DATA struNoticeData = { 0 };
CTime time = CTime::GetCurrentTime();
memcpy(&struNoticeData, pAlarmInfo, sizeof(struNoticeData));
sprintf(szInfoBuf, "Notice Data Event Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] NoticeNumber[%s] NoticeTheme[%s] NoticeDetail[%s] Level[%d] PicNum[%d]",
struNoticeData.struTime.wYear, struNoticeData.struTime.byMonth, struNoticeData.struTime.byDay,
struNoticeData.struTime.byHour, struNoticeData.struTime.byMinute, struNoticeData.struTime.bySecond,
struNoticeData.byNoticeNumber, struNoticeData.byNoticeTheme, struNoticeData.byNoticeDetail, struNoticeData.byLevel, struNoticeData.byPicNum);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struNoticeData.byPicNum > 0)
{
int num = ulAlarmPic / 1000 + 1;
ulAlarmPic++;
char cFileDirectory[256] = { 0 };
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFileDirectory, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFileDirectory) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFileDirectory, NULL);
}
char cFileName[256] = { 0 };
for (int i = 0; i < MAX_NOTICE_PIC_NUM; i++)
{
if (struNoticeData.struNoticePic[i].dwPicDataLen > 0)
{
memset(cFileName, 0, 256);
sprintf(cFileName, "%s\\LocalTime[%s]No[%d].jpg", cFileDirectory, chTime, i);
hFile = CreateFile(cFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struNoticeData.struNoticePic[i].pPicData, struNoticeData.struNoticePic[i].dwPicDataLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
delete[] struNoticeData.struNoticePic[i].pPicData;
struNoticeData.struNoticePic[i].pPicData = NULL;
}
}
}
}
void CClientDemoDlg::ProcPeopleDetectionUpload(WPARAM wParam,LPARAM lParam)
{
char szInfoBuf[1024] = {0};
// char szAlarmInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_PEOPLE_DETECTION_RESULT struPeopleDetcetion = {0};
memcpy(&struPeopleDetcetion, pAlarmInfo, sizeof(struPeopleDetcetion));
// 打印信息
NET_DVR_TIME struAbsTime = {0};
struAbsTime.dwYear = GET_YEAR(struPeopleDetcetion.dwAbsTime);
struAbsTime.dwMonth = GET_MONTH(struPeopleDetcetion.dwAbsTime);
struAbsTime.dwDay = GET_DAY(struPeopleDetcetion.dwAbsTime);
struAbsTime.dwHour = GET_HOUR(struPeopleDetcetion.dwAbsTime);
struAbsTime.dwMinute = GET_MINUTE(struPeopleDetcetion.dwAbsTime);
struAbsTime.dwSecond = GET_SECOND(struPeopleDetcetion.dwAbsTime);
NET_DVR_TIME struRelativeTime = {0};
struRelativeTime.dwYear = GET_YEAR(struPeopleDetcetion.dwRelativeTime);
struRelativeTime.dwMonth = GET_MONTH(struPeopleDetcetion.dwRelativeTime);
struRelativeTime.dwDay = GET_DAY(struPeopleDetcetion.dwRelativeTime);
struRelativeTime.dwHour = GET_HOUR(struPeopleDetcetion.dwRelativeTime);
struRelativeTime.dwMinute = GET_MINUTE(struPeopleDetcetion.dwRelativeTime);
struRelativeTime.dwSecond = GET_SECOND(struPeopleDetcetion.dwRelativeTime);
// for (i = 0; i < 8; i++)
// {
// if (struPeopleDetcetion.struPeopleRegion[i].byNumber != 0)
// {
// sprintf(szAlarmInfoBuf, "RegionID:RegionNumberOfPeople [%d: %d],[%d: %d],[%d: %d],[%d: %d],[%d: %d],[%d: %d],[%d: %d],[%d: %d]", \
// struPeopleDetcetion.struPeopleRegion[0].byID, struPeopleDetcetion.struPeopleRegion[0].byNumber,
// struPeopleDetcetion.struPeopleRegion[1].byID, struPeopleDetcetion.struPeopleRegion[1].byNumber,
// struPeopleDetcetion.struPeopleRegion[2].byID, struPeopleDetcetion.struPeopleRegion[2].byNumber,
// struPeopleDetcetion.struPeopleRegion[3].byID, struPeopleDetcetion.struPeopleRegion[3].byNumber,
// struPeopleDetcetion.struPeopleRegion[4].byID, struPeopleDetcetion.struPeopleRegion[4].byNumber,
// struPeopleDetcetion.struPeopleRegion[5].byID, struPeopleDetcetion.struPeopleRegion[5].byNumber,
// struPeopleDetcetion.struPeopleRegion[6].byID, struPeopleDetcetion.struPeopleRegion[6].byNumber,
// struPeopleDetcetion.struPeopleRegion[7].byID, struPeopleDetcetion.struPeopleRegion[7].byNumber);
// }
//
// }
char cTempInfo[1024] = {0};
for (i = 0; i < MAX_PEOPLE_DETECTION_NUM; i++)
{
if (struPeopleDetcetion.struPeopleRegion[i].byNumber != 0)
{
sprintf(cTempInfo + strlen(cTempInfo), "RegionID[%d] RegionNumberOfPeople[%d] DressType[%d]", \
struPeopleDetcetion.struPeopleRegion[i].byID, struPeopleDetcetion.struPeopleRegion[i].byNumber, struPeopleDetcetion.struPeopleRegion[i].byDressType);
//cTempInfo += strlen(cTempInfo);
}
}
sprintf(szInfoBuf, "[people Detection Alarm Time] AlarmInfoBuf[%s] Abs[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] RelativeTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d] Dev[ip:%s,port:%d,ivmsChan:%d] PeopleAlarmType[%d]\n",\
cTempInfo
,struAbsTime.dwYear, struAbsTime.dwMonth, struAbsTime.dwDay, struAbsTime.dwHour,struAbsTime.dwMinute, struAbsTime.dwSecond, \
struRelativeTime.dwYear, struRelativeTime.dwMonth, struRelativeTime.dwDay, struRelativeTime.dwHour,struRelativeTime.dwMinute, struRelativeTime.dwSecond, \
struPeopleDetcetion.struDevInfo.struDevIP.sIpV4, struPeopleDetcetion.struDevInfo.wPort, struPeopleDetcetion.struDevInfo.byIvmsChannel,\
struPeopleDetcetion.byPeopleAlarmType);
for (i=0; i<MAX_PEOPLE_DETECTION_NUM; i++)
{
if (struPeopleDetcetion.struPeopleRegion[i].dwPicLen > 0 && struPeopleDetcetion.struPeopleRegion[i].pPicBuffer != NULL)
{
int num = ulAlarmPic/1000+1;
ulAlarmPic++;
char cFilename[256] = {0};
HANDLE hFile;
DWORD dwReturn;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
sprintf(cFilename, "%s\\%s[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, num);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\peopleDet_LocalTime[%s]_%d.jpg",cFilename, chTime, i);
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struPeopleDetcetion.struPeopleRegion[i].pPicBuffer, struPeopleDetcetion.struPeopleRegion[i].dwPicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcFiberConvertAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
char szAlarmInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iWinIndex = -1;
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_FIBER_CONVERT_ALARM struFiberConvertAlarm = {0};
memcpy(&struFiberConvertAlarm, pAlarmInfo, sizeof(struFiberConvertAlarm));
int iLen = sprintf(szInfoBuf, "[FIBER_CONVERT_ALARM]");
if (struFiberConvertAlarm.dwEventType == 1)
{
sprintf(szInfoBuf, "%sType:Alarm", szInfoBuf);
if (struFiberConvertAlarm.dwEvent == FC_OPTICAL_PORT_LOST)
{
sprintf(szInfoBuf, "%s Event:Optical port lost", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_ELECTRICAL_PORT_LOST)
{
sprintf(szInfoBuf, "%s Event:Electrical port lost", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_FUNC_CARD_LOST)
{
sprintf(szInfoBuf, "%s Event:Function card lost", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_CARD_DISCONNECTED)
{
sprintf(szInfoBuf, "%s Event:Card disconnected", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_MAX_TEMP_LIMITED)
{
sprintf(szInfoBuf, "%s Event:Maximum temperature limited", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_MIN_TEMP_LIMITED)
{
sprintf(szInfoBuf, "%s Event:Minimum temperature limited", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_MAX_VOLTAGE_LIMITED)
{
sprintf(szInfoBuf, "%s Event:Maximum voltage limited", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_MIN_VOLTAGE_LIMITED)
{
sprintf(szInfoBuf, "%s Event:Minimum voltage limited", szInfoBuf);
}
}
else if (struFiberConvertAlarm.dwEventType == 2)
{
sprintf(szInfoBuf, "%sType:Notification", szInfoBuf);
if (struFiberConvertAlarm.dwEvent == FC_OPTICAL_PORT_CONNECTED)
{
sprintf(szInfoBuf, "%s Event:Optical port connected", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_ELECTRICAL_PORT_CONNECTED)
{
sprintf(szInfoBuf, "%s Event:Electrical port connected", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_FUNC_CARD_INSERT)
{
sprintf(szInfoBuf, "%s Event:Function card insert", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_CARD_CONNECTED)
{
sprintf(szInfoBuf, "%s Event:Card connected", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_TEMP_RECOVERY)
{
sprintf(szInfoBuf, "%s Event:Temperature recovery", szInfoBuf);
}
else if (struFiberConvertAlarm.dwEvent == FC_VOLTAGE_RECOVERY)
{
sprintf(szInfoBuf, "%s Event:Voltage recovery", szInfoBuf);
}
}
if (struFiberConvertAlarm.byCardType == 1)
{
sprintf(szInfoBuf, "%s CardType:NetMgr card", szInfoBuf);
}
else if (struFiberConvertAlarm.byCardType == 2)
{
sprintf(szInfoBuf, "%s CardType:Function card", szInfoBuf);
}
else if (struFiberConvertAlarm.byCardType == 3)
{
sprintf(szInfoBuf, "%s CardType:Remote send card", szInfoBuf);
}
else if (struFiberConvertAlarm.byCardType == 4)
{
sprintf(szInfoBuf, "%s CardType:Device crate", szInfoBuf);
}
sprintf(szInfoBuf, "%s SlotNum:%d PortNo:%d Temp:%d Voltage:%d",
szInfoBuf, struFiberConvertAlarm.bySlotNum, struFiberConvertAlarm.byPortNo, struFiberConvertAlarm.byCurTemperature, struFiberConvertAlarm.wCurVoltage);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcFacecaptureStatistics(WPARAM wParam, LPARAM lParam)//人脸抓拍统计上传
{
char szInfoBuf[1024] = {0};
char szLan[128] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_FACECAPTURE_STATISTICS_RESULT struFacecapture = {0};
memcpy(&struFacecapture, pAlarmInfo, sizeof(struFacecapture));
g_StringLanType(szLan, "人脸抓拍统计上传","Face Capture Statistics Upload");
int len = 0,oldlen = 0,sexlen = 0;
len = sprintf(szInfoBuf, "%s: (开始时间:%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d,结束时间:%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d)\n", \
szLan, struFacecapture.struStartTime.wYear,struFacecapture.struStartTime.byMonth,struFacecapture.struStartTime.byDay,struFacecapture.struStartTime.byHour,\
struFacecapture.struStartTime.byMinute,struFacecapture.struStartTime.bySecond,struFacecapture.struEndTime.wYear,\
struFacecapture.struEndTime.byMonth,struFacecapture.struEndTime.byDay,struFacecapture.struEndTime.byHour,struFacecapture.struEndTime.byMinute,\
struFacecapture.struEndTime.bySecond);
if ((struFacecapture.byStatType >> 2) & 1)
{
oldlen = sprintf(szInfoBuf+len,"%s","年龄段有效");
}
if ((struFacecapture.byStatType >> 1) & 1)
{
sexlen = sprintf(szInfoBuf+len+oldlen,"%s","性别有效");
}
if (struFacecapture.byStatType & 1)
{
sprintf(szInfoBuf+len+oldlen+sexlen,"%s","人数有效");
}
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
char szTmpCN[200] = {0};
sprintf(szTmpCN, "统计人数:%d,少年:%d,青年:%d,中年:%d,老年:%d,儿童:%d,青少年:%d,壮年:%d,中老年:%d,男:%d,女:%d", struFacecapture.dwPeopleNum, struFacecapture.struAgeGroupParam.dwTeenage, \
struFacecapture.struAgeGroupParam.dwYouth, struFacecapture.struAgeGroupParam.dwMidLife, struFacecapture.struAgeGroupParam.dwElderly, \
struFacecapture.struAgeGroupParam.dwChild, struFacecapture.struAgeGroupParam.dwAdolescent, struFacecapture.struAgeGroupParam.dwPrime, struFacecapture.struAgeGroupParam.dwMidage,\
struFacecapture.struSexGroupParam.dwMale, struFacecapture.struSexGroupParam.dwFemale);
char szTmpEN[200] = {0};
sprintf(szTmpEN, "PeopleNum:%d,Teen:%d, Youth:%d,Midlife:%d, Elderly:%d,Child:%d,Adolescent:%d,Prime:%d,Midage:%d, male:%d,female:%d", struFacecapture.dwPeopleNum, struFacecapture.struAgeGroupParam.dwTeenage, \
struFacecapture.struAgeGroupParam.dwYouth, struFacecapture.struAgeGroupParam.dwMidLife, struFacecapture.struAgeGroupParam.dwElderly,\
struFacecapture.struAgeGroupParam.dwChild, struFacecapture.struAgeGroupParam.dwAdolescent, struFacecapture.struAgeGroupParam.dwPrime, struFacecapture.struAgeGroupParam.dwMidage, \
struFacecapture.struSexGroupParam.dwMale, struFacecapture.struSexGroupParam.dwFemale);
g_StringLanType(szInfoBuf, szTmpCN, szTmpEN);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcVideoParkingPoleAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_VIDEO_PARKING_POLE_ALARM struVideoParkingPoleAlarm = { 0 };
memcpy(&struVideoParkingPoleAlarm, pAlarmInfo, sizeof(struVideoParkingPoleAlarm));
g_StringLanType(szLan, "视频桩报警", "Video Parking Pole Alarm");
sprintf(szInfoBuf, "%s: Time[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d],ParkingNum[%s],AlarmType[%d]", szLan, \
struVideoParkingPoleAlarm.struTime.wYear, struVideoParkingPoleAlarm.struTime.byMonth, struVideoParkingPoleAlarm.struTime.byDay, \
struVideoParkingPoleAlarm.struTime.byHour, struVideoParkingPoleAlarm.struTime.byMinute, struVideoParkingPoleAlarm.struTime.bySecond, struVideoParkingPoleAlarm.struTime.wMilliSec, \
struVideoParkingPoleAlarm.byParkingNum, struVideoParkingPoleAlarm.byAlarmType);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcSwicthLampAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = {0};
g_StringLanType(szLan, "开关灯检测报警上传","Switch Lamp Detection");
NET_DVR_SWITCH_LAMP_ALARM struSwitchLamp = {0};
memset(&struSwitchLamp, 0, sizeof(struSwitchLamp));
memcpy(&struSwitchLamp, pAlarmInfo, sizeof(struSwitchLamp));
sprintf(szInfoBuf, "%s AlarmTime[%04d-%02d-%02d %02d:%02d:%02d], lamp Status:%d, PicDataLen:%d, DevInfo{DevIP:%s, Port:%d, Channel:%d, IvmsChannel:%d}",\
szLan, struSwitchLamp.struTime.wYear,struSwitchLamp.struTime.byMonth,struSwitchLamp.struTime.byDay,struSwitchLamp.struTime.byHour,\
struSwitchLamp.struTime.byMinute,struSwitchLamp.struTime.bySecond,struSwitchLamp.byLampStatus,\
struSwitchLamp.dwPicDataLen, struSwitchLamp.struDevInfo.struDevIP.sIpV4, struSwitchLamp.struDevInfo.wPort, struSwitchLamp.struDevInfo.byChannel,\
struSwitchLamp.struDevInfo.byIvmsChannel);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
if (struSwitchLamp.dwPicDataLen > 0 && struSwitchLamp.pPicData != NULL)
{
char cFilename[256] = {0};
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[SwitchLamp]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg",cFilename, chTime,rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struSwitchLamp.pPicData, struSwitchLamp.dwPicDataLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struSwitchLamp.dwPicDataLen )
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "SwitchLamp Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struSwitchLamp.dwPicDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struSwitchLamp.pPicData != NULL)
{
delete [] (struSwitchLamp.pPicData);
struSwitchLamp.pPicData = NULL;
}
}
void CClientDemoDlg::ProGateCardIndoAlarm( WPARAM wParam, LPARAM lParam )
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = {0};
g_StringLanType(szLan, "出入口卡片信息上传","Entrance card information upload");
NET_DVR_GATE_CARDINFO struGateCardInfo;
memset(&struGateCardInfo, 0, sizeof(struGateCardInfo));
memcpy(&struGateCardInfo, pAlarmInfo, sizeof(struGateCardInfo));
sprintf(szInfoBuf, "%s: DevInfo{DevIP:%s, Port:%d, Channel:%d, IvmsChannel:%d} RelativeTime:%d, AbsTime:%d, CardNo:%s, PassVehicleID:%s, InVehicleID:%s,\
LetPass:%d, CardType:%d",\
szLan, struGateCardInfo.struDevInfo.struDevIP.sIpV4, struGateCardInfo.struDevInfo.wPort, struGateCardInfo.struDevInfo.byChannel,\
struGateCardInfo.struDevInfo.byIvmsChannel, struGateCardInfo.dwRelativeTime, struGateCardInfo.dwAbsTime, struGateCardInfo.szCardNo,\
struGateCardInfo.szPassVehicleID, struGateCardInfo.szInVehicleID, struGateCardInfo.byLetPass, struGateCardInfo.byCardType);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
//月台作业上传
void CClientDemoDlg::ProLoadingDockOperateInfo(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = { 0 };
g_StringLanType(szLan, "月台作业上传", "loading dock operate information upload");
NET_LOADING_DOCK_OPERATEINFO struLoadingDockOperateInfo;
memset(&struLoadingDockOperateInfo, 0, sizeof(struLoadingDockOperateInfo));
memcpy(&struLoadingDockOperateInfo, pAlarmInfo, sizeof(struLoadingDockOperateInfo));
//显示报警信息
sprintf(szInfoBuf, "%s: AbsTime:%s, ParkingNo:%s, dwIndex:%d, sLicense:%s, CurrentWorkerNumber:%d, CurrentGoodsLoadingRate:%d\
byDoorsStatus:%d", \
szLan, struLoadingDockOperateInfo.byAbsTime, struLoadingDockOperateInfo.byParkingNo, struLoadingDockOperateInfo.dwIndex, struLoadingDockOperateInfo.sLicense, struLoadingDockOperateInfo.byCurrentWorkerNumber, struLoadingDockOperateInfo.byCurrentGoodsLoadingRate, \
struLoadingDockOperateInfo.byDoorsStatus);
//通道号
if (struLoadingDockOperateInfo.dwChannel > 0)
{
sprintf(szInfoBuf, "%s, channel:%d", szInfoBuf, struLoadingDockOperateInfo.dwChannel);
}
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
//保存图片
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
if (struLoadingDockOperateInfo.dwBackPicDataLength > 0 && struLoadingDockOperateInfo.pBackPicDataBuffer != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[LoadingDockOperateInfo]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struLoadingDockOperateInfo.pBackPicDataBuffer, struLoadingDockOperateInfo.dwBackPicDataLength, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struLoadingDockOperateInfo.dwBackPicDataLength)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "LoadingDockOperateInfo Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struLoadingDockOperateInfo.dwBackPicDataLength, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struLoadingDockOperateInfo.pBackPicDataBuffer != NULL)
{
delete[](struLoadingDockOperateInfo.pBackPicDataBuffer);
struLoadingDockOperateInfo.pBackPicDataBuffer = NULL;
}
}
void CClientDemoDlg::ProGateCardChargeAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = {0};
g_StringLanType(szLan, "出入口收费上传","Entrance Charge information upload");
NET_DVR_GATE_CHARGEINFO struGateChargeInfo;
memset(&struGateChargeInfo, 0, sizeof(struGateChargeInfo));
memcpy(&struGateChargeInfo, pAlarmInfo, sizeof(struGateChargeInfo));
sprintf(szInfoBuf, "%s:DevInfo{DevIP:%s,Port:%d,Channel:%d,IvmsChannel:%d}RelativeTime:%d,AbsTime:%d,sLicense:%s,CardNo:%s,\
Entrance:%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d,Departure:%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d,DepartureID:%s,EntranceID:%s,\
TotalCost:%d,OperateName:%s,ChargeRuleId:%d,VehicleType:%d",\
szLan, struGateChargeInfo.struDevInfo.struDevIP.sIpV4, struGateChargeInfo.struDevInfo.wPort, struGateChargeInfo.struDevInfo.byChannel,\
struGateChargeInfo.struDevInfo.byIvmsChannel, struGateChargeInfo.dwRelativeTime, struGateChargeInfo.dwAbsTime, struGateChargeInfo.sLicense,\
struGateChargeInfo.szCardNo,struGateChargeInfo.struEntranceTime.wYear,struGateChargeInfo.struEntranceTime.byMonth,\
struGateChargeInfo.struEntranceTime.byDay,struGateChargeInfo.struEntranceTime.byHour, struGateChargeInfo.struEntranceTime.byMinute,\
struGateChargeInfo.struEntranceTime.bySecond,struGateChargeInfo.struEntranceTime.wMilliSec,struGateChargeInfo.struDepartureTime.wYear,\
struGateChargeInfo.struDepartureTime.byMonth,struGateChargeInfo.struDepartureTime.byDay,struGateChargeInfo.struDepartureTime.byHour, \
struGateChargeInfo.struDepartureTime.byMinute,struGateChargeInfo.struDepartureTime.bySecond,struGateChargeInfo.struDepartureTime.wMilliSec,\
struGateChargeInfo.szDepartureID,struGateChargeInfo.szEntranceID,struGateChargeInfo.dwTotalCost,struGateChargeInfo.szOperateName,\
struGateChargeInfo.szOperateName,struGateChargeInfo.byChargeRuleId,struGateChargeInfo.byVehicleType);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProConferenceAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = {0};
NET_DVR_CONFERENCE_CALL_ALARM struConference = {0};
memcpy(&struConference, pAlarmInfo, sizeof(struConference));
if (struConference.byAlarmType == 1) //会议呼叫
{
g_StringLanType(szLan, "会议呼叫告警","Conference Call Alarm");
if (struConference.byCallType == 1)
{
sprintf(szInfoBuf, "%s: type:point to point, url:%s", szLan, struConference.struCallInfo.struTerminalCallInfo.byTermianlURL);
}
else if (struConference.byCallType == 2)
{
sprintf(szInfoBuf, "%s: type:conference call,ID:%s,name:%s,start:%4d-%2d-%2d %2d:%2d:%2d,end:%4d-%2d-%2d %2d:%2d:%2d", szLan,\
struConference.struCallInfo.struConferenceCallInfo.byConferenceID,\
struConference.struCallInfo.struConferenceCallInfo.byConferenceName,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwYear,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwMonth,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwDay,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwHour,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwMinute,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwSecond,\
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwYear,\
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwMonth,\
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwDay, \
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwHour,\
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwMinute,\
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwSecond);
}
}
else if (struConference.byAlarmType == 2) //呼叫状态切换
{
g_StringLanType(szLan, "呼叫状态切换告警", "Call Answer Alarm");
char szAnswerType[32] = {0};
if (struConference.byCallStatusSwitch == 1)
{
g_StringLanType(szAnswerType, "开始呼叫", "Start Call");
}
else if (struConference.byCallStatusSwitch == 2)
{
g_StringLanType(szAnswerType, "呼叫成功", "Call succeed");
}
else if (struConference.byCallStatusSwitch == 3)
{
g_StringLanType(szAnswerType, "呼叫结束", "Call over");
}
else if (struConference.byCallStatusSwitch == 4)
{
g_StringLanType(szAnswerType, "对端挂断", "Hang up");
}
if (struConference.byCallType == 1)
{
sprintf(szInfoBuf, "%s[%s]: type:point to point, url:%s", szLan, szAnswerType, struConference.struCallInfo.struTerminalCallInfo.byTermianlURL);
}
else if (struConference.byCallType == 2)
{
sprintf(szInfoBuf, "%s[%s]: type:conference call,ID:%s,name:%s,start:%4d-%2d-%2d %2d:%2d:%2d,end:%4d-%2d-%2d %2d:%2d:%2d", szLan, szAnswerType, \
struConference.struCallInfo.struConferenceCallInfo.byConferenceID,\
struConference.struCallInfo.struConferenceCallInfo.byConferenceName,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwYear,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwMonth,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwDay,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwHour,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwMinute,\
struConference.struCallInfo.struConferenceCallInfo.struStartTime.dwSecond,\
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwYear,\
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwMonth,\
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwDay, \
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwHour,\
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwMinute,\
struConference.struCallInfo.struConferenceCallInfo.struEndTime.dwSecond);
}
}
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcIDInfoAlarm(WPARAM wParam, LPARAM lParam)
{
//char szInfoBuf[1024] = {0};
char szTriggerTime[1024] = {0};
char szLan[128] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_ID_CARD_INFO_ALARM struIDCardInfo = {0};
memset(&struIDCardInfo, 0, sizeof(NET_DVR_ID_CARD_INFO_ALARM));
memcpy(&struIDCardInfo, pAlarmInfo, sizeof(NET_DVR_ID_CARD_INFO_ALARM));
g_StringLanType(szLan, "身份证信息上传", "ID Information upload");
CString szTmp = "";
szTmp.Format("%s", struIDCardInfo.struIDCardCfg.byName);
string szName = UTF82ASCII(szTmp);
szTmp.Format("%s", struIDCardInfo.struIDCardCfg.byAddr);
string szAddr = UTF82ASCII(szTmp);
szTmp.Format("%s", struIDCardInfo.struIDCardCfg.byIssuingAuthority);
string szIssuingAuthority = UTF82ASCII(szTmp);
sprintf(szTriggerTime, "%s start,name:%s,\r\nAddr:%s\r\nIssuingAuthority:%s\r\nID:%s,%d-%d-%d\r\nbyCardType:%d", szLan, szName.c_str(), szAddr.c_str(), szIssuingAuthority.c_str(),
struIDCardInfo.struIDCardCfg.byIDNum, struIDCardInfo.struIDCardCfg.struStartDate.wYear, struIDCardInfo.struIDCardCfg.struStartDate.byMonth,
struIDCardInfo.struIDCardCfg.struStartDate.byDay, struIDCardInfo.byCardType);
AddLog(iDeviceIndex, ALARM_INFO_T,szTriggerTime);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds);
do
{
if (struIDCardInfo.dwPicDataLen > 0 && struIDCardInfo.pPicData != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "Sensor");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.bin", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
break;
}
DWORD dwRet = WriteFile(hFile, struIDCardInfo.pPicData, struIDCardInfo.dwPicDataLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struIDCardInfo.dwPicDataLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "ID Card Info Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struIDCardInfo.dwPicDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
// 指纹数据
if (struIDCardInfo.dwFingerPrintDataLen > 0 && struIDCardInfo.pFingerPrintData != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "Sensor");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_FingerPrintData_%d.bin", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
break;
}
DWORD dwRet = WriteFile(hFile, struIDCardInfo.pFingerPrintData, struIDCardInfo.dwFingerPrintDataLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struIDCardInfo.dwFingerPrintDataLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "ID Card Info Fingerprint Data Write to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struIDCardInfo.dwFingerPrintDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
//抓拍图片数据
if (struIDCardInfo.dwCapturePicDataLen > 0 && struIDCardInfo.pCapturePicData != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "Sensor");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_CapturePic_%d.bin", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
break;
}
DWORD dwRet = WriteFile(hFile, struIDCardInfo.pCapturePicData, struIDCardInfo.dwCapturePicDataLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struIDCardInfo.dwCapturePicDataLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "ID Card Info Capture Picture Write to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struIDCardInfo.dwCapturePicDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
} while (0);
if (struIDCardInfo.pPicData != NULL)
{
delete[](struIDCardInfo.pPicData);
struIDCardInfo.pPicData = NULL;
}
if (struIDCardInfo.pFingerPrintData != NULL)
{
delete[](struIDCardInfo.pFingerPrintData);
struIDCardInfo.pFingerPrintData = NULL;
}
if (struIDCardInfo.pCapturePicData != NULL)
{
delete[](struIDCardInfo.pCapturePicData);
struIDCardInfo.pCapturePicData = NULL;
}
}
void CClientDemoDlg::ProcPassportAlarm(WPARAM wParam, LPARAM lParam)
{
//char szInfoBuf[1024] = {0};
char szTriggerTime[4 * 1024] = { 0 };
char szLan[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_PASSPORT_ALARM struPassportInfo = { 0 };
memset(&struPassportInfo, 0, sizeof(NET_DVR_PASSPORT_ALARM));
memcpy(&struPassportInfo, pAlarmInfo, sizeof(NET_DVR_PASSPORT_ALARM));
g_StringLanType(szLan, "护照信息上传", "Passport Information upload");
CString szTmp = "";
szTmp.Format("%s", struPassportInfo.struPassportInfo.byName);
string szName = UTF82ASCII(szTmp);
szTmp.Format("%s", struPassportInfo.struPassportInfo.byAddr);
string szAddr = UTF82ASCII(szTmp);
szTmp.Format("%s", struPassportInfo.struPassportInfo.byCountryIssue);
string szIssuingAuthority = UTF82ASCII(szTmp);
szTmp.Format("%s", struPassportInfo.struPassportInfo.byLocalName);
string szLocalName = UTF82ASCII(szTmp);
szTmp.Format("%s", struPassportInfo.struPassportInfo.byPlaceOfBirth);
string szPlaceOfBirth = UTF82ASCII(szTmp);
szTmp.Format("%s", struPassportInfo.struPassportInfo.byJob);
string szJob = UTF82ASCII(szTmp);
szTmp.Format("%s", struPassportInfo.struPassportInfo.byTitle);
string szTitle = UTF82ASCII(szTmp);
szTmp.Format("%s", struPassportInfo.struPassportInfo.byResume);
string szResume = UTF82ASCII(szTmp);
szTmp.Format("%s", struPassportInfo.struPassportInfo.byMonitoring);
string szMonitoring = UTF82ASCII(szTmp);
sprintf(szTriggerTime, "%s start,name:%s,%d-%d-%d\r\nAddr:%s\r\nIssuingAuthority:%s\r\nID:%s,%d-%d-%d\r\nbyCardType:%d\r\n\
localName:%s\r\nPlaceOfBirth:%s\r\nJob:%s\r\nTitle:%s\r\nResume:%s\r\nMonitoring:%s\r\n",
szLan, szName.c_str(), struPassportInfo.struPassportInfo.struBirth.wYear, struPassportInfo.struPassportInfo.struBirth.byMonth,
struPassportInfo.struPassportInfo.struBirth.byDay, szAddr.c_str(), szIssuingAuthority.c_str(),
struPassportInfo.struPassportInfo.byPassportNo, struPassportInfo.struPassportInfo.struExpireDate.wYear,
struPassportInfo.struPassportInfo.struExpireDate.byMonth, struPassportInfo.struPassportInfo.struExpireDate.byDay,
struPassportInfo.byCardType, szLocalName, szPlaceOfBirth, szJob, szTitle, szResume, szMonitoring);
AddLog(iDeviceIndex, ALARM_INFO_T, szTriggerTime);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
//人脸数据
do
{
if (struPassportInfo.dwFaceDataLen > 0 && struPassportInfo.pFaceData != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "Sensor");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_FaceData_%d.bin", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
break;
}
DWORD dwRet = WriteFile(hFile, struPassportInfo.pFaceData, struPassportInfo.dwFaceDataLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struPassportInfo.dwFaceDataLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "The Passport Face data Write to File Failed.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struPassportInfo.dwFaceDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
//证件图片数据
if (struPassportInfo.dwPicDataLen > 0 && struPassportInfo.pPicData != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "Sensor");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_IdentificationPhoto_%d.bin", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
break;
}
DWORD dwRet = WriteFile(hFile, struPassportInfo.pPicData, struPassportInfo.dwPicDataLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struPassportInfo.dwPicDataLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "The Passport Identification Photo Write to File Failed.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struPassportInfo.dwPicDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
//抓拍图片数据
if (struPassportInfo.dwCapturePicDataLen > 0 && struPassportInfo.pCapturePicData != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "Sensor");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_CapturePic_%d.bin", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
break;
}
DWORD dwRet = WriteFile(hFile, struPassportInfo.pCapturePicData, struPassportInfo.dwCapturePicDataLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struPassportInfo.dwCapturePicDataLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "The Passport Capture Picture Write to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struPassportInfo.dwCapturePicDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
} while (0);
if (struPassportInfo.pPicData != NULL)
{
delete[](struPassportInfo.pPicData);
struPassportInfo.pPicData = NULL;
}
if (struPassportInfo.pFaceData != NULL)
{
delete[](struPassportInfo.pFaceData);
struPassportInfo.pFaceData = NULL;
}
if (struPassportInfo.pCapturePicData != NULL)
{
delete[](struPassportInfo.pCapturePicData);
struPassportInfo.pCapturePicData = NULL;
}
}
void CClientDemoDlg::ProcPassNumInfoAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
char szTriggerTime[128] = {0};
char szLan[128] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_PASSNUM_INFO_ALARM struPassNumInfo = {0};
memcpy(&struPassNumInfo, pAlarmInfo, sizeof(NET_DVR_PASSNUM_INFO_ALARM));
g_StringLanType(szLan, "通行人数上报", "pass number Information upload");
sprintf(szTriggerTime, "%s start,EntryTimes:%d,ExitTimes:%d,TotalTimes:%d", szLan, struPassNumInfo.dwEntryTimes, struPassNumInfo.dwExitTimes, struPassNumInfo.dwTotalTimes);
AddLog(iDeviceIndex, ALARM_INFO_T,szTriggerTime);
}
void CClientDemoDlg::ProcStorageDetAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = {0};
char szLan[128] = {0};
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_STORAGE_DETECTION_ALARM struStorageDet = {0};
memcpy(&struStorageDet, pAlarmInfo, sizeof(NET_DVR_STORAGE_DETECTION_ALARM));
g_StringLanType(szLan, "存储智能检测报警上传", "Storage Detection");
sprintf(szInfoBuf, "%s RelativeTime[%d]AbsTime[%d]DevIP[%s]Port[%d]Channel[%d]CardID[%d]PowerLoss[%d]BadBlocks[%d]HealthState[%d]ResidualLife[%0.1f%]", szLan, \
struStorageDet.dwRelativeTime, struStorageDet.dwAbsTime, struStorageDet.struDevInfo.struDevIP.sIpV4, struStorageDet.struDevInfo.wPort, \
struStorageDet.struDevInfo.byChannel, struStorageDet.dwCardID, struStorageDet.wAbnormalPowerLoss, struStorageDet.wBadBlocks, struStorageDet.byHealthState,struStorageDet.fResidualLife * 100);
AddLog(iDeviceIndex, ALARM_INFO_T,szInfoBuf);
}
void CClientDemoDlg::ProcMVMRegisterInfo(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_MVMRegisterInfo struMVMRegisterInfo = { 0 };
memcpy(&struMVMRegisterInfo, pAlarmInfo, sizeof(NET_DVR_MVMRegisterInfo));
g_StringLanType(szLan, "地磁管理器注册信息", "MVM Register Info");
sprintf(szInfoBuf, "%s DetectorID[%s]ManagerID[%s]Sim[%s]LocalIP[0x%x]LocalIPMask[0x%x]LocalGateway[0x%x]DstIP[0x%x]LocalPort[%d]Firmware[%d-%d-%d]Version[%d.%d]", szLan, \
struMVMRegisterInfo.sDetectorID, struMVMRegisterInfo.sManagerID, struMVMRegisterInfo.sSim, struMVMRegisterInfo.dwLocalIP, struMVMRegisterInfo.dwLocalIPMask, \
struMVMRegisterInfo.dwLocalGateway, struMVMRegisterInfo.dwDstIP, struMVMRegisterInfo.wLocalPort, struMVMRegisterInfo.wFirmwareYear, struMVMRegisterInfo.byFirmwareMonth, \
struMVMRegisterInfo.byFirmwareDay, struMVMRegisterInfo.byMajorVersion, struMVMRegisterInfo.byMinorVersion);
sprintf(szInfoBuf, "%sMACAddr[", szInfoBuf);
for (int i = 0; i < 6; i++)
{
sprintf(szInfoBuf, "%s%x", szInfoBuf, struMVMRegisterInfo.byMACAddr[i]);
}
sprintf(szInfoBuf, "%s]", szInfoBuf);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcMVMStatusInfo(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_SingleMagneticStatus struMagneticStatus = { 0 };
memcpy(&struMagneticStatus, pAlarmInfo, sizeof(NET_DVR_SingleMagneticStatus));
g_StringLanType(szLan, "地磁管理器状态上报", "Magnetic Status Info");
sprintf(szInfoBuf, "%s DetectorID[%s]ManagerID[%s]ParkNum[%s]DetectorTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d]Rssi[%d]ParkinglotState[%d]BatteryState[%d]DeviceState[%d]CMD[%d]", szLan, \
struMagneticStatus.sDetectorID, struMagneticStatus.sManagerID, struMagneticStatus.sParkNum, struMagneticStatus.struDetectorTime.wYear, struMagneticStatus.struDetectorTime.byMonth, \
struMagneticStatus.struDetectorTime.byDay, struMagneticStatus.struDetectorTime.byHour, struMagneticStatus.struDetectorTime.byMinute, struMagneticStatus.struDetectorTime.bySecond, struMagneticStatus.struDetectorTime.wMilliSec, \
struMagneticStatus.dwRssi, struMagneticStatus.byParkinglotState, struMagneticStatus.byBatteryState, struMagneticStatus.byDeviceState, struMagneticStatus.byCMD);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcShipsDetAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
int iPort = pAlarmDev->wLinkPort;
char szLan[128] = { 0 };
g_StringLanType(szLan, "船只检测报警上传", "Ship detection alarm ");
NET_DVR_SHIPSDETECTION_ALARM struShipsDetection;
memset(&struShipsDetection, 0, sizeof(struShipsDetection));
memcpy(&struShipsDetection, pAlarmInfo, sizeof(struShipsDetection));
LPNET_DVR_SHIPSDETECTION_ALARM pShipsDetection = (LPNET_DVR_SHIPSDETECTION_ALARM)(pAlarmInfo);
sprintf(szInfoBuf, "flag[%d] [%2.2d%2.2d]%s: IPv4[%s] IPv6[%s] Port[%d] Channel[%d] IvmsChannel[%d] IvmsChannelEx[%d] RelativeTime[%d] AbsTime[%d] ShipsNum[%d] ShipsNumHead[%d] ShipsNumEnd[%d] SID[%d] sceneName[%s]", \
struShipsDetection.byTimeDiffFlag, struShipsDetection.cTimeDifferenceH, struShipsDetection.cTimeDifferenceM, \
szLan, struShipsDetection.struDevInfo.struDevIP.sIpV4, struShipsDetection.struDevInfo.struDevIP.byIPv6, struShipsDetection.struDevInfo.wPort, \
struShipsDetection.struDevInfo.byChannel, struShipsDetection.struDevInfo.byIvmsChannel, struShipsDetection.wDevInfoIvmsChannelEx,\
struShipsDetection.dwRelativeTime, struShipsDetection.dwAbsTime, \
struShipsDetection.byShipsNum, struShipsDetection.byShipsNumHead, struShipsDetection.byShipsNumEnd, struShipsDetection.bySID, struShipsDetection.szSceneName);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
for (int i = 0; i < struShipsDetection.byShipsNum; i++)
{
sprintf(szInfoBuf, "%s: shipsNum[%d] TriggerLineID[%d] ShipsLength[%0.1f] ShipsHeight[%0.1f] ShipsWidth[%0.1f] ShipsSpeed[%0.1f] ShipsDirection[%d] ShipsDetState[%d]", \
szLan, i + 1, struShipsDetection.struShipInfo[i].byTriggerLineID, struShipsDetection.struShipInfo[i].fShipsLength, struShipsDetection.struShipInfo[i].fShipsHeight, struShipsDetection.struShipInfo[i].fShipsWidth, \
struShipsDetection.struShipInfo[i].fShipsSpeed, struShipsDetection.struShipInfo[i].byShipsDirection, struShipsDetection.struShipInfo[i].byShipsDetState);
}
shipsDetectionToTxt(pShipsDetection, iDeviceIndex);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
if (struShipsDetection.dwPicLen > 0 && struShipsDetection.pPicBuffer != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%d][%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, "VisibleLight");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struShipsDetection.byPicTransType)
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
}
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struShipsDetection.pPicBuffer, struShipsDetection.dwPicLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struShipsDetection.dwPicLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Plate Picture Wtite to File Fail.System Error:%d, dwPlateBufferLen:%d, dwWrittenBytes:%d ", dwError, struShipsDetection.dwPicLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struShipsDetection.dwThermalPicLen > 0 && struShipsDetection.pThermalPicBuffer != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%d][%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, "ThermalImaging");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struShipsDetection.byPicTransType)
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
}
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struShipsDetection.pThermalPicBuffer, struShipsDetection.dwThermalPicLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struShipsDetection.dwThermalPicLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "PilotFace Picture Wtite to File Fail.System Error:%d, dwPilotFaceBufferLen:%d, dwWrittenBytes:%d ", dwError, struShipsDetection.dwThermalPicLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
//释放图片内存
if (struShipsDetection.pPicBuffer != NULL)
{
delete[](struShipsDetection.pPicBuffer);
struShipsDetection.pPicBuffer = NULL;
}
//释放图片内存
if (struShipsDetection.pThermalPicBuffer != NULL)
{
delete[](struShipsDetection.pThermalPicBuffer);
struShipsDetection.pThermalPicBuffer = NULL;
}
}
void CClientDemoDlg::shipsDetectionToTxt(LPNET_DVR_SHIPSDETECTION_ALARM pShipsDetection, int iDeviceIndex)
{
if (NULL == pShipsDetection)
{
return;
}
int i = 0;
int j = 0;
char sInfo[5120] = { 0 };
// NET_DVR_SHIPSDETECTION_ALARM
sprintf(sInfo, "NET_DVR_SHIPSDETECTION_ALARM \r\n");
sprintf(sInfo, "%s dwRelativeTime=%d \r\n", sInfo, pShipsDetection->dwRelativeTime);
sprintf(sInfo, "%s dwAbsTime=%d \r\n", sInfo, pShipsDetection->dwAbsTime);
sprintf(sInfo, "%s byShipsNum=%d \r\n", sInfo, pShipsDetection->byShipsNum);
sprintf(sInfo, "%s byShipsNumHead=%d \r\n", sInfo, pShipsDetection->byShipsNumHead);
sprintf(sInfo, "%s byShipsNumEnd=%d \r\n", sInfo, pShipsDetection->byShipsNumEnd);
sprintf(sInfo, "%s dwPicLen=%d \r\n", sInfo, pShipsDetection->dwPicLen);
sprintf(sInfo, "%s dwThermalPicLen=%d \r\n", sInfo, pShipsDetection->dwThermalPicLen);
//NET_VCA_DEV_INFO
sprintf(sInfo, "%s NET_VCA_DEV_INFO \r\n", sInfo);
sprintf(sInfo, "%s wPort=%d \r\n", sInfo, pShipsDetection->struDevInfo.wPort);
sprintf(sInfo, "%s byChannel=%d \r\n", sInfo, pShipsDetection->struDevInfo.byChannel);
sprintf(sInfo, "%s byIvmsChannel=%d \r\n", sInfo, pShipsDetection->struDevInfo.byIvmsChannel);
//NET_DVR_IPADDR
sprintf(sInfo, "%s NET_DVR_IPADDR \r\n", sInfo);
sprintf(sInfo, "%s sIpV4=%s \r\n", sInfo, pShipsDetection->struDevInfo.struDevIP.sIpV4);
sprintf(sInfo, "%s byIPv6=%s \r\n", sInfo, pShipsDetection->struDevInfo.struDevIP.byIPv6);
//NET_DVR_SHIPSINFO
for (i = 0; i < MAX_SHIPS_NUM; i++)
{
sprintf(sInfo, "%s NET_DVR_SHIPSINFO Ships Number[%d] \r\n", sInfo, i);
sprintf(sInfo, "%s fShipsLength=%0.1f \r\n", sInfo, pShipsDetection->struShipInfo[i].fShipsLength);
sprintf(sInfo, "%s fShipsHeight=%0.1f \r\n", sInfo, pShipsDetection->struShipInfo[i].fShipsHeight);
sprintf(sInfo, "%s fShipsWidth=%0.1f \r\n", sInfo, pShipsDetection->struShipInfo[i].fShipsWidth);
sprintf(sInfo, "%s fShipsSpeed=%0.1f \r\n", sInfo, pShipsDetection->struShipInfo[i].fShipsSpeed);
sprintf(sInfo, "%s byShipsDirection=%d \r\n", sInfo, pShipsDetection->struShipInfo[i].byShipsDirection);
sprintf(sInfo, "%s byShipsDetState=%d \r\n", sInfo, pShipsDetection->struShipInfo[i].byShipsDetState);
//NET_VCA_POLYGON
sprintf(sInfo, "%s NET_VCA_POLYGON dwPointNum=%d \r\n", sInfo, pShipsDetection->struShipInfo[i].struShipsRect.dwPointNum);
if (pShipsDetection->struShipInfo[i].struShipsRect.dwPointNum > 0 && pShipsDetection->struShipInfo[i].struShipsRect.dwPointNum <= VCA_MAX_POLYGON_POINT_NUM)
{
for (j = 0; j < pShipsDetection->struShipInfo[i].struShipsRect.dwPointNum; j++)
{
// NET_VCA_POINT
sprintf(sInfo, "%s NET_VCA_POINT fX=%0.3f \r\n", sInfo, pShipsDetection->struShipInfo[i].struShipsRect.struPos[j].fX);
sprintf(sInfo, "%s NET_VCA_POINT fY=%0.3f \r\n", sInfo, pShipsDetection->struShipInfo[i].struShipsRect.struPos[j].fY);
}
}
sprintf(sInfo, "%s TriggerLineID=%d \r\n", sInfo, pShipsDetection->struShipInfo[i].byTriggerLineID);
}
char cFilename[256] = { 0 };
sprintf(cFilename, "");
HANDLE hFile = NULL;
DWORD dwReturn = 0;
SYSTEMTIME t;
GetLocalTime(&t);
char chLocalTime[128];
sprintf(chLocalTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
// sprintf(cFilename, "%s\\LocalTime[%s].txt", cFilename, chLocalTime);
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "ShipsInfo");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\LocalTime[%s]_%d.txt", cFilename, chLocalTime, rand() % GetTickCount());
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, sInfo, 5120, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
UpdateData(FALSE);
}
void CClientDemoDlg::ProThermometryAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[2048] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = { 0 };
g_StringLanType(szLan, "温度报警上传", "Thermometry Alarm");
NET_DVR_THERMOMETRY_ALARM struThermometryAlarm;
memset(&struThermometryAlarm, 0, sizeof(struThermometryAlarm));
memcpy(&struThermometryAlarm, pAlarmInfo, sizeof(struThermometryAlarm));
if (0 == struThermometryAlarm.byRuleCalibType)
{
sprintf(szInfoBuf, "%s: Channel:%d, RuleID:%d,TemperatureSuddenChangeCycle:%d; TemperatureSuddenChangeValue:%f; ToleranceTemperature:%f, AlertFilteringTime:%d, AlarmFilteringTime:%d,ThermometryUnit:%d, PresetNo:%d, RuleTemperature:%.1f, CurrTemperature:%.1f, PTZ Info[Pan:%f, Tilt:%f, Zoom:%f], AlarmLevel:%d, \
AlarmType:%d, AlarmRule:%d, RuleCalibType:%d, Point[x:%f, y:%f], PicLen:%d, ThermalPicLen:%d, ThermalInfoLen:%d", szLan, \
struThermometryAlarm.dwChannel, struThermometryAlarm.byRuleID, struThermometryAlarm.dwTemperatureSuddenChangeCycle, struThermometryAlarm.fTemperatureSuddenChangeValue, struThermometryAlarm.fToleranceTemperature, struThermometryAlarm.dwAlertFilteringTime, struThermometryAlarm.dwAlarmFilteringTime, struThermometryAlarm.byThermometryUnit, struThermometryAlarm.wPresetNo, \
struThermometryAlarm.fRuleTemperature, struThermometryAlarm.fCurrTemperature, \
struThermometryAlarm.struPtzInfo.fPan, struThermometryAlarm.struPtzInfo.fTilt, struThermometryAlarm.struPtzInfo.fZoom, \
struThermometryAlarm.byAlarmLevel, struThermometryAlarm.byAlarmType, struThermometryAlarm.byAlarmRule, struThermometryAlarm.byRuleCalibType, \
struThermometryAlarm.struPoint.fX, struThermometryAlarm.struPoint.fY, struThermometryAlarm.dwPicLen, struThermometryAlarm.dwThermalPicLen, struThermometryAlarm.dwThermalInfoLen);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
else if (1 == struThermometryAlarm.byRuleCalibType || 2 == struThermometryAlarm.byRuleCalibType)
{
char szRegionInfo[512] = { 0 };
int iPointNum = struThermometryAlarm.struRegion.dwPointNum;
for (int i = 0; i < iPointNum; i++)
{
float fX = struThermometryAlarm.struRegion.struPos[i].fX;
float fY = struThermometryAlarm.struRegion.struPos[i].fY;
sprintf(szRegionInfo, "%sX%d:%f,Y%d:%f;", szRegionInfo, i + 1, fX, i + 1, fY);
}
sprintf(szInfoBuf, "%s: Channel:%d, RuleID:%d,TemperatureSuddenChangeCycle:%d; TemperatureSuddenChangeValue:%f; ToleranceTemperature:%f, AlertFilteringTime:%d, AlarmFilteringTime:%d,HighestPoint[x:%f, y:%f],ThermometryUnit:%d, PresetNo:%d, RuleTemperature:%.1f, CurrTemperature:%.1f, PTZ Info[Pan:%f, Tilt:%f, Zoom:%f], AlarmLevel:%d, \
AlarmType:%d, AlarmRule:%d, RuleCalibType:%d, Region[%s], PicLen:%d, ThermalPicLen:%d, ThermalInfoLen:%d", szLan, \
struThermometryAlarm.dwChannel, struThermometryAlarm.byRuleID, struThermometryAlarm.dwTemperatureSuddenChangeCycle, struThermometryAlarm.fTemperatureSuddenChangeValue, struThermometryAlarm.fToleranceTemperature, struThermometryAlarm.dwAlertFilteringTime, struThermometryAlarm.dwAlarmFilteringTime, struThermometryAlarm.struHighestPoint.fX, struThermometryAlarm.struHighestPoint.fY, struThermometryAlarm.byThermometryUnit, struThermometryAlarm.wPresetNo, \
struThermometryAlarm.fRuleTemperature, struThermometryAlarm.fCurrTemperature, struThermometryAlarm.struPtzInfo.fPan, struThermometryAlarm.struPtzInfo.fTilt, struThermometryAlarm.struPtzInfo.fZoom, \
struThermometryAlarm.byAlarmLevel, struThermometryAlarm.byAlarmType, struThermometryAlarm.byAlarmRule, struThermometryAlarm.byRuleCalibType, \
szRegionInfo, struThermometryAlarm.dwPicLen, struThermometryAlarm.dwThermalPicLen, struThermometryAlarm.dwThermalInfoLen);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
if (struThermometryAlarm.dwPicLen > 0 && struThermometryAlarm.pPicBuff != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[Thermometry]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struThermometryAlarm.byPicTransType)
{
sprintf(cFilename, "%s\\Pic[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\Pic[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
}
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struThermometryAlarm.pPicBuff, struThermometryAlarm.dwPicLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struThermometryAlarm.dwPicLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Thermometry Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struThermometryAlarm.dwPicLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struThermometryAlarm.dwThermalPicLen > 0 && struThermometryAlarm.pThermalPicBuff != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[Thermometry]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struThermometryAlarm.byPicTransType)
{
sprintf(cFilename, "%s\\ThermalPic[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\ThermalPic[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
}
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struThermometryAlarm.pThermalPicBuff, struThermometryAlarm.dwThermalPicLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struThermometryAlarm.dwThermalPicLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Thermometry Thermal Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struThermometryAlarm.dwThermalPicLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struThermometryAlarm.dwThermalInfoLen > 0 && struThermometryAlarm.pThermalInfoBuff != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[Thermometry]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\ThermalInfo[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struThermometryAlarm.pThermalInfoBuff, struThermometryAlarm.dwThermalInfoLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struThermometryAlarm.dwThermalInfoLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Thermometry Thermal Info Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struThermometryAlarm.dwThermalInfoLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struThermometryAlarm.pPicBuff != NULL)
{
delete[](struThermometryAlarm.pPicBuff);
struThermometryAlarm.pPicBuff = NULL;
}
if (struThermometryAlarm.pThermalPicBuff != NULL)
{
delete[](struThermometryAlarm.pThermalPicBuff);
struThermometryAlarm.pThermalPicBuff = NULL;
}
if (struThermometryAlarm.pThermalInfoBuff != NULL)
{
delete[](struThermometryAlarm.pThermalInfoBuff);
struThermometryAlarm.pThermalInfoBuff = NULL;
}
}
void CClientDemoDlg::ProBaseStationInfoAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[2048] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = { 0 };
g_StringLanType(szLan, "基站信息上传", "BaseStationInfo Alarm");
NET_DVR_BASE_STATION_INFO_ALARM struBaseStationInfoAlarm;
memset(&struBaseStationInfoAlarm, 0, sizeof(struBaseStationInfoAlarm));
memcpy(&struBaseStationInfoAlarm, pAlarmInfo, sizeof(struBaseStationInfoAlarm));
sprintf(szInfoBuf, "%s: Channel[%d] NetBarWaCode[%s] CollectionEquipmentID[%s] MCC[%s] MNC[%s] LAC[%s] CI[%s] BSCI[%s] BCCH[%s] LEV[%s] CollectionEquipmentLongitude[%s] CollectionEquipmentLatitude[%s] CaptureTime[%s]", szLan, \
struBaseStationInfoAlarm.dwChannel, struBaseStationInfoAlarm.sNetBarWaCode, struBaseStationInfoAlarm.sCollectionEquipmentID, struBaseStationInfoAlarm.sMCC, struBaseStationInfoAlarm.sMNC, struBaseStationInfoAlarm.sLAC, struBaseStationInfoAlarm.sCI, \
struBaseStationInfoAlarm.sBSCI, struBaseStationInfoAlarm.sBCCH, struBaseStationInfoAlarm.sLEV, struBaseStationInfoAlarm.sCollectionEquipmentLongitude, struBaseStationInfoAlarm.sCollectionEquipmentLatitude, struBaseStationInfoAlarm.sCaptureTime);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProThermometryDiffAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[2048] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = { 0 };
g_StringLanType(szLan, "温差报警上传", "Thermometry Difference Alarm");
NET_DVR_THERMOMETRY_DIFF_ALARM struThermometryAlarm;
memset(&struThermometryAlarm, 0, sizeof(struThermometryAlarm));
memcpy(&struThermometryAlarm, pAlarmInfo, sizeof(struThermometryAlarm));
if (0 == struThermometryAlarm.byRuleCalibType)
{
sprintf(szInfoBuf, "%s: Channel:%d, AlarmID1:%d, ToleranceTemperature:%f, AlarmFilteringTime:%d,AlarmID2:%d, PresetNo:%d, RuleTemperatureDiff:%.1f, CurTemperatureDiff:%.1f, \
AlarmLevel:%d, AlarmType:%d, AlarmRule:%d, RuleCalibType:%d, \
Point1[x:%f, y:%f], point2[x:%f, y:%f], PTZ Info[Pan:%f, Tilt:%f, Zoom:%f], PicLen:%d, \
ThermalPicLen:%d, ThermalInfoLen:%d, ThermometryUnit:%d", szLan, \
struThermometryAlarm.dwChannel, struThermometryAlarm.byAlarmID1, struThermometryAlarm.fToleranceTemperature, struThermometryAlarm.dwAlarmFilteringTime, struThermometryAlarm.byAlarmID2, struThermometryAlarm.wPresetNo, \
struThermometryAlarm.fRuleTemperatureDiff, struThermometryAlarm.fCurTemperatureDiff, \
struThermometryAlarm.byAlarmLevel, struThermometryAlarm.byAlarmType, struThermometryAlarm.byAlarmRule, struThermometryAlarm.byRuleCalibType, \
struThermometryAlarm.struPoint[0].fX, struThermometryAlarm.struPoint[0].fY, struThermometryAlarm.struPoint[1].fX, struThermometryAlarm.struPoint[1].fY, \
struThermometryAlarm.struPtzInfo.fPan, struThermometryAlarm.struPtzInfo.fTilt, struThermometryAlarm.struPtzInfo.fZoom, \
struThermometryAlarm.dwPicLen, struThermometryAlarm.dwThermalPicLen, struThermometryAlarm.dwThermalInfoLen, struThermometryAlarm.byThermometryUnit);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
else if (1 == struThermometryAlarm.byRuleCalibType || 2 == struThermometryAlarm.byRuleCalibType)
{
int i = 0;
char szRegionInfo[512] = { 0 };
int iPointNum = struThermometryAlarm.struRegion[0].dwPointNum;
for (i = 0; i < iPointNum; i++)
{
float fX = struThermometryAlarm.struRegion[0].struPos[i].fX;
float fY = struThermometryAlarm.struRegion[0].struPos[i].fY;
sprintf(szRegionInfo, "%sX%d:%f,Y%d:%f;", szRegionInfo, iPointNum + 1, fX, iPointNum + 1, fY);
}
char szRegionInfo1[512] = { 0 };
iPointNum = struThermometryAlarm.struRegion[1].dwPointNum;
for (i = 0; i < iPointNum; i++)
{
float fX = struThermometryAlarm.struRegion[1].struPos[i].fX;
float fY = struThermometryAlarm.struRegion[1].struPos[i].fY;
sprintf(szRegionInfo1, "%sX%d:%f,Y%d:%f;", szRegionInfo1, iPointNum + 1, fX, iPointNum + 1, fY);
}
sprintf(szInfoBuf, "%s: Channel:%d, AlarmID1:%d, AlarmID2:%d, ToleranceTemperature:%f, AlarmFilteringTime:%d,PresetNo:%d, RuleTemperatureDiff:%.1f, CurTemperatureDiff:%.1f, AlarmLevel:%d, AlarmType:%d, AlarmRule:%d, RuleCalibType:%d, \
Region1[%s], Region2[%s], PTZ Info[Pan:%f, Tilt:%f, Zoom:%f], PicLen:%d, ThermalPicLen:%d, ThermalInfoLen:%d, ThermometryUnit:%d", szLan, \
struThermometryAlarm.dwChannel, struThermometryAlarm.byAlarmID1, struThermometryAlarm.byAlarmID2, struThermometryAlarm.fToleranceTemperature, struThermometryAlarm.dwAlarmFilteringTime, struThermometryAlarm.wPresetNo, \
struThermometryAlarm.fRuleTemperatureDiff, struThermometryAlarm.fCurTemperatureDiff, \
struThermometryAlarm.byAlarmLevel, struThermometryAlarm.byAlarmType, struThermometryAlarm.byAlarmRule, struThermometryAlarm.byRuleCalibType, \
szRegionInfo, szRegionInfo1, \
struThermometryAlarm.struPtzInfo.fPan, struThermometryAlarm.struPtzInfo.fTilt, struThermometryAlarm.struPtzInfo.fZoom, \
struThermometryAlarm.dwPicLen, struThermometryAlarm.dwThermalPicLen, struThermometryAlarm.dwThermalInfoLen, struThermometryAlarm.byThermometryUnit);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
if (struThermometryAlarm.dwPicLen > 0 && struThermometryAlarm.pPicBuff != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[ThermometryDiff]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struThermometryAlarm.byPicTransType)
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\LocalTime[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
}
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struThermometryAlarm.pPicBuff, struThermometryAlarm.dwPicLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struThermometryAlarm.dwPicLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Thermometry Difference Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struThermometryAlarm.dwPicLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struThermometryAlarm.dwThermalPicLen > 0 && struThermometryAlarm.pThermalPicBuff != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[ThermometryDiff]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
if (struThermometryAlarm.byPicTransType)
{
sprintf(cFilename, "%s\\ThermalPic[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\ThermalPic[%s]_%d.jpg", cFilename, chTime, rand() % GetTickCount());
}
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struThermometryAlarm.pThermalPicBuff, struThermometryAlarm.dwThermalPicLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struThermometryAlarm.dwThermalPicLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Thermometry Difference Thermal Picture Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struThermometryAlarm.dwThermalPicLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struThermometryAlarm.dwThermalInfoLen > 0 && struThermometryAlarm.pThermalInfoBuff != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, "[ThermometryDiff]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\ThermalInfo[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struThermometryAlarm.pThermalInfoBuff, struThermometryAlarm.dwThermalInfoLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struThermometryAlarm.dwThermalInfoLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Thermometry Difference Thermal Info Wtite to File Fail.System Error:%d, dwPicLen:%d, pBuffer:%d ", dwError, struThermometryAlarm.dwThermalInfoLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
if (struThermometryAlarm.pPicBuff != NULL)
{
delete[](struThermometryAlarm.pPicBuff);
struThermometryAlarm.pPicBuff = NULL;
}
if (struThermometryAlarm.pThermalPicBuff != NULL)
{
delete[](struThermometryAlarm.pThermalPicBuff);
struThermometryAlarm.pThermalPicBuff = NULL;
}
if (struThermometryAlarm.pThermalInfoBuff != NULL)
{
delete[](struThermometryAlarm.pThermalInfoBuff);
struThermometryAlarm.pThermalInfoBuff = NULL;
}
}
void CClientDemoDlg::ProDiagnosisUpload(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szTime[128] = { 0 };
char szLan[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_DIAGNOSIS_UPLOAD struDiagnosisUpload = { 0 };
memcpy(&struDiagnosisUpload, pAlarmInfo, sizeof(NET_DVR_DIAGNOSIS_UPLOAD));
g_StringLanType(szLan, "诊断服务器结果信息上传", "Diagnosis Upload");
sprintf(szTime, "%d-%d-%d %d:%d:%d", struDiagnosisUpload.struCheckTime.dwYear, struDiagnosisUpload.struCheckTime.dwMonth, struDiagnosisUpload.struCheckTime.dwDay,
struDiagnosisUpload.struCheckTime.dwHour, struDiagnosisUpload.struCheckTime.dwMinute, struDiagnosisUpload.struCheckTime.dwSecond);
sprintf(szInfoBuf, "%s StreamID[%s]MonitorIP[%s]ChanIndex[%d]Width[%d]Height[%d]CheckTime[%s]Result[%d]", szLan, \
struDiagnosisUpload.sStreamID, struDiagnosisUpload.sMonitorIP, struDiagnosisUpload.dwChanIndex, struDiagnosisUpload.dwWidth, \
struDiagnosisUpload.dwHeight, szTime, struDiagnosisUpload.byResult);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
sprintf(szInfoBuf, "%s SignalResult[%d]BlurResult[%d]LumaResult[%d]ChromaResult[%d]SnowResult[%d]StreakResult[%d]FreezeResult[%d]PTZResult[%d]NapShotURL[%s]", szLan, \
struDiagnosisUpload.bySignalResult, struDiagnosisUpload.byBlurResult, struDiagnosisUpload.byLumaResult, struDiagnosisUpload.byChromaResult, \
struDiagnosisUpload.bySnowResult, struDiagnosisUpload.byStreakResult, struDiagnosisUpload.byFreezeResult, struDiagnosisUpload.byPTZResult, struDiagnosisUpload.sSNapShotURL);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcessWallConferenceAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szTime[128] = { 0 };
char szLan[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char *pAlarmInfo = (char *)(lParam);
DWORD dwLen = *(DWORD*)pAlarmInfo;
CFile file;
if (!file.Open("C:\\WallConferenceInfo.txt", CFile::modeWrite))
{
return;
}
file.SeekToEnd();
file.Write(pAlarmInfo + sizeof(DWORD), dwLen);
file.Close();
g_StringLanType(szLan, "开会的会议信息告警", "Wall Conference Alarm");
CTime time(NULL);
sprintf(szTime, "%d-%d-%d %d:%d:%d", time.GetYear(), time.GetMonth(), time.GetDay(),
time.GetHour(), time.GetMinute(), time.GetSecond());
sprintf(szInfoBuf, "%s DeviceIndex[%d] Alarm Time[%s]", szLan, iDeviceIndex, szTime);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProGPSStatusUpload(WPARAM wParam, LPARAM lParam)
{
char szLan[256] = { 0 };
char szLocateMode[64] = { 0 };
char szGPSTime[128] = { 0 };
char szInfoBuf[1024] = { 0 };
char szDegree[128] = { 0 };
char szUploadBuf[1024] = { 0 };
char szRetransFlag[32] = { 0 };
char szNeedsResponse[32] = { 0 };
char szType[32] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
LPNET_DVR_GPS_STATUS_ALARM pStruGPSStatusAlarm = (LPNET_DVR_GPS_STATUS_ALARM)pAlarmInfo;
g_StringLanType(szLan, "GPS状态上传", "GPS Status Upload");
sprintf(szGPSTime, "%d-%d-%d %d:%d:%d", pStruGPSStatusAlarm->struGPSTime.wYear,
pStruGPSStatusAlarm->struGPSTime.byMonth, pStruGPSStatusAlarm->struGPSTime.byDay,
pStruGPSStatusAlarm->struGPSTime.byHour, pStruGPSStatusAlarm->struGPSTime.byMinute,
pStruGPSStatusAlarm->struGPSTime.bySecond);
if (pStruGPSStatusAlarm->struGPSInfo.byDirection[0] == 0)
{
if (pStruGPSStatusAlarm->struGPSInfo.byDirection[1] == 0)
{
sprintf(szDegree, "%s %d %s %d", "East longitude", pStruGPSStatusAlarm->struGPSInfo.dwLatitude, "North latitude", pStruGPSStatusAlarm->struGPSInfo.dwLongitude);
}
if (pStruGPSStatusAlarm->struGPSInfo.byDirection[1] == 1)
{
sprintf(szDegree, "%s %d %s %d", "East longitude", pStruGPSStatusAlarm->struGPSInfo.dwLatitude, "South latitude", pStruGPSStatusAlarm->struGPSInfo.dwLongitude);
}
}
else if (pStruGPSStatusAlarm->struGPSInfo.byDirection[0] == 1)
{
if (pStruGPSStatusAlarm->struGPSInfo.byDirection[1] == 0)
{
sprintf(szDegree, "%s %d %s %d", "West longitude", pStruGPSStatusAlarm->struGPSInfo.dwLatitude, "North latitude", pStruGPSStatusAlarm->struGPSInfo.dwLongitude);
}
if (pStruGPSStatusAlarm->struGPSInfo.byDirection[1] == 1)
{
sprintf(szDegree, "%s %d %s %d", "West longitude", pStruGPSStatusAlarm->struGPSInfo.dwLatitude, "South latitude", pStruGPSStatusAlarm->struGPSInfo.dwLongitude);
}
}
switch (pStruGPSStatusAlarm->struGPSInfo.byLocateMode)
{
case 0:
g_StringLanType(szLocateMode, "自主定位", "self-localization");
break;
case 1:
g_StringLanType(szLocateMode, "差分", "difference");
break;
case 2:
g_StringLanType(szLocateMode, "估算", "estimate");
break;
case 3:
g_StringLanType(szLocateMode, "数据无效", "data is invalid");
break;
default:
break;
}
switch (pStruGPSStatusAlarm->byRetransFlag)
{
case 0:
g_StringLanType(szRetransFlag, "本条 GPS 为实时包", "GPS real-time package");
break;
case 1:
g_StringLanType(szRetransFlag, "本条 GPS 为重传包", "GPS retransmission package ");
break;
default:
break;
}
switch (pStruGPSStatusAlarm->byNeedsResponse)
{
case 0:
g_StringLanType(szNeedsResponse, "不需回应包", "no need respond package");
break;
case 1:
g_StringLanType(szNeedsResponse, "需回应包", "need respond package");
break;
default:
break;
}
switch (pStruGPSStatusAlarm->byType)
{
case 0:
g_StringLanType(szType, "无人机", "Unmanned aerial vehicle");
break;
default:
break;
}
sprintf(szInfoBuf, "%s: (GPS Time:[%s] GPS Direction:[%s] GPS LocateMode:[%s] HDOP:[%d] Height:[%d] Vehicle Speed:[%d] Vehicle Direction:[%d])\n",
szLan, szGPSTime, szDegree, szLocateMode, pStruGPSStatusAlarm->struGPSInfo.wHDOP, pStruGPSStatusAlarm->struGPSInfo.wHeight,
pStruGPSStatusAlarm->struGPSInfo.dwVehicleSpeed, pStruGPSStatusAlarm->struGPSInfo.dwVehicleDirection);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
sprintf(szUploadBuf, "%s: (RetransFlag:[%s] NeedsResponse:[%s] Type:[%s] BatteryRemaining:[%d] RollAngle:[%d] PitchAngle:[%d] RelativeHeight:[%d] VerticalSpeed:[%d])\n",
szLan, szRetransFlag, szNeedsResponse, szType, pStruGPSStatusAlarm->byBatteryRemaining, pStruGPSStatusAlarm->iRollAngle,
pStruGPSStatusAlarm->iPitchAngle, pStruGPSStatusAlarm->wRelativeHeight, pStruGPSStatusAlarm->wVerticalSpeed);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szUploadBuf);
}
void CClientDemoDlg::ProTagInfoUpload(WPARAM wParam, LPARAM lParam)
{
char szLan[256] = { 0 };
char szInfoBuf[1024] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int i = 0;
int iDeviceIndex = pAlarmDev->iDeviceIndex;
LPNET_DVR_TAG_INFO_ALARM pStruTagInfoAlarm = (LPNET_DVR_TAG_INFO_ALARM)pAlarmInfo;
g_StringLanType(szLan, "标签信息上传", "Tag Information Upload");
char szRfidInfo[180] = { 0 };
for (int index = 0; index < sizeof(pStruTagInfoAlarm->byRFIDInfo); ++index)
{
sprintf(szRfidInfo, "%s0x%02x ", szRfidInfo, pStruTagInfoAlarm->byRFIDInfo[index]);
}
sprintf(szInfoBuf, "%s Card No:[%s],Rssi:[%d],byIndexCode[%s],AcquisitionTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d],RFIDInfo[%s],RFIDInfoLen[%d],byVoltageLow[%d],byAlarmFlag[%d]\n",
szLan,
pStruTagInfoAlarm->byCardNo,
pStruTagInfoAlarm->iRssi,
pStruTagInfoAlarm->byIndexCode,
pStruTagInfoAlarm->struAcquisitionTime.wYear,
pStruTagInfoAlarm->struAcquisitionTime.byMonth,
pStruTagInfoAlarm->struAcquisitionTime.byDay,
pStruTagInfoAlarm->struAcquisitionTime.byHour,
pStruTagInfoAlarm->struAcquisitionTime.byMinute,
pStruTagInfoAlarm->struAcquisitionTime.bySecond,
pStruTagInfoAlarm->struAcquisitionTime.wMilliSec,
szRfidInfo,
pStruTagInfoAlarm->byRFIDInfoLen,
pStruTagInfoAlarm->byVoltageLow,
pStruTagInfoAlarm->byAlarmFlag);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcessInquestAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szStatus[256] = { 0 };
char szAlarmType[128] = { 0 };
char szLan[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_INQUEST_ALARM struTrayAbnormalAlarm = { 0 };
memcpy(&struTrayAbnormalAlarm, pAlarmInfo, sizeof(NET_DVR_INQUEST_ALARM));
g_StringLanType(szLan, "审讯主机报警上传", "Inquest Alarm Upload");
switch (struTrayAbnormalAlarm.dwAlarmType)
{
case 0:
g_StringLanType(szAlarmType, "光盘满报警", "Tray full");
break;
case 1:
g_StringLanType(szAlarmType, "光盘错误报警", "Tray error");
break;
default:
break;
}
sprintf(szInfoBuf, "%s: (Alarm type:[%s] Tray No.:[%d])\n", szLan, szAlarmType, struTrayAbnormalAlarm.byTrayNo);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProFaceSnapRawData(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_VCA_FACESNAP_RAWDATA_ALARM struFaceSnap = { 0 };
memcpy(&struFaceSnap, pAlarmInfo, sizeof(NET_VCA_FACESNAP_RAWDATA_ALARM));
g_StringLanType(szLan, "人脸Json报警", "Face Json Alarm");
sprintf(szInfoBuf, "%s: IPv4[%s] IPv6[%s] Port[%d] Channel[%d] IvmsChannel[%d] RelativeTime[%d] AbsTime[%d]", \
szLan, struFaceSnap.struDevInfo.struDevIP.sIpV4, struFaceSnap.struDevInfo.struDevIP.byIPv6, struFaceSnap.struDevInfo.wPort, \
struFaceSnap.struDevInfo.byChannel, struFaceSnap.struDevInfo.byIvmsChannel, struFaceSnap.dwRelativeTime, struFaceSnap.dwAbsTime);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
if (struFaceSnap.dwJsonDataLen > 0 && struFaceSnap.pJsonBuff != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\[%s]", g_struLocalParam.chPictureSavePath, "[FaceSnapJson]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\Json[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
delete[] struFaceSnap.pJsonBuff;
struFaceSnap.pJsonBuff = NULL;
return;
}
DWORD dwRet = WriteFile(hFile, struFaceSnap.pJsonBuff, struFaceSnap.dwJsonDataLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struFaceSnap.dwJsonDataLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Face Snap Json Info Wtite to File Fail.System Error:%d, dwJsonDataLen:%d, WrittenBytes:%d ", dwError, struFaceSnap.dwJsonDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
delete[] struFaceSnap.pJsonBuff;
struFaceSnap.pJsonBuff = NULL;
}
}
void CClientDemoDlg::ProcNetSwitchAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = { 0 };
g_StringLanType(szLan, "交换机端口检测报警上传", "Switch port detection");
NET_DVR_SWITCH_CONVERT_ALARM struSwitchAlarm = { 0 };
memset(&struSwitchAlarm, 0, sizeof(struSwitchAlarm));
memcpy(&struSwitchAlarm, pAlarmInfo, sizeof(struSwitchAlarm));
sprintf(szInfoBuf, "%s Port:%d, EventType:%d, Event:%d", szLan, struSwitchAlarm.byPortNo, struSwitchAlarm.dwEventType, struSwitchAlarm.dwEvent);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcessAlarmGps(WPARAM wParam, LPARAM lParam)
{
char szLan[256] = { 0 };
char szLocateMode[64] = { 0 };
char szGPSTime[512] = { 0 };
char szInfoBuf[1024] = { 0 };
char szDegree[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_GPSALARMINFO struGPSAlarm = { 0 };
memset(&struGPSAlarm, 0, sizeof(struGPSAlarm));
memcpy(&struGPSAlarm, pAlarmInfo, sizeof(struGPSAlarm));
g_StringLanType(szLan, "GPS报警信息上传", "GPS Alarm Information Upload");
sprintf(szGPSTime, "上传时间:%d-%d-%d %d:%d:%d", struGPSAlarm.struGpsTime.wYear,
struGPSAlarm.struGpsTime.byMonth, struGPSAlarm.struGpsTime.byDay,
struGPSAlarm.struGpsTime.byHour, struGPSAlarm.struGpsTime.byMinute,
struGPSAlarm.struGpsTime.bySecond);
if (struGPSAlarm.sDirection[0] == 'E')
{
if (struGPSAlarm.sDirection[1] == 'N')
{
sprintf(szDegree, "%s %d %s %d", "East longitude", struGPSAlarm.dwLongitude, "North latitude", struGPSAlarm.dwLatitude);
}
if (struGPSAlarm.sDirection[1] == 'S')
{
sprintf(szDegree, "%s %d %s %d", "East longitude", struGPSAlarm.dwLongitude, "South latitude", struGPSAlarm.dwLatitude);
}
}
else if (struGPSAlarm.sDirection[0] == 'W')
{
if (struGPSAlarm.sDirection[1] == 'N')
{
sprintf(szDegree, "%s %d %s %d", "West longitude", struGPSAlarm.dwLongitude, "North latitude", struGPSAlarm.dwLatitude);
}
if (struGPSAlarm.sDirection[1] == 'S')
{
sprintf(szDegree, "%s %d %s %d", "West longitude", struGPSAlarm.dwLongitude, "South latitude", struGPSAlarm.dwLatitude);
}
}
switch (struGPSAlarm.byLocateMode)
{
case 0:
g_StringLanType(szLocateMode, "自主定位", "self-localization");
break;
case 1:
g_StringLanType(szLocateMode, "差分", "difference");
break;
case 2:
g_StringLanType(szLocateMode, "估算", "estimate");
break;
case 3:
g_StringLanType(szLocateMode, "数据无效", "data is invalid");
break;
default:
break;
}
sprintf(szInfoBuf, "%s: DeviceID:[%s] GPS Time:[%s] GPS Direction:[%s] GPS LocateMode:[%s] TimeZone:[%d] Vehicle Direction:[%d] Satellites:[%d] Precision:[%d]\
Height:[%d] GPSSeq:[%d] Speed:[%d]", szLan, struGPSAlarm.byDeviceID, szGPSTime, szDegree, szLocateMode, struGPSAlarm.iTimeZone, struGPSAlarm.dwDirection,
struGPSAlarm.wSatellites, struGPSAlarm.wPrecision, struGPSAlarm.dwHeight, struGPSAlarm.dwGPSSeq, struGPSAlarm.wSpeed);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcessEventWithJsonData(WPARAM wParam, LPARAM lParam)
{
char szLan[64] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
int iPort = pAlarmDev->wLinkPort;
DWORD dwBufLen = pAlarmDev->dwBufLen;
int iChannelID = 0;
if ((iDeviceIndex != -1) && !(g_struDeviceInfo[iDeviceIndex].bAlarm) && iDeviceIndex < MAX_DEVICES)
{
g_struDeviceInfo[iDeviceIndex].bAlarm = TRUE;
::PostMessage(g_pMainDlg->m_hWnd, WM_CHANGE_DEVICE_ITEM_IMAGE, WPARAM(g_pMainDlg->GetDeviceItem(iDeviceIndex)), LPARAM(iDeviceIndex));
}
char szInfoBuf[128] = { 0 };
char* pCBBuf = new char[dwBufLen];
if (pCBBuf == NULL)
{
sprintf(szLan, "内存申请失败 EventJson dwBufLen:%d", dwBufLen);
AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
return;
}
memcpy(pCBBuf, pAlarmInfo, dwBufLen);
char *mfd = pCBBuf;
//analysisJson(pCBBuf, g_struLocalParam.chPictureSavePath);
char* boundary = get_boundary(pCBBuf);
int contentLen = 0;
int offsetLen = 0;
int i = 0;
while (1) {
char *type, *content;
mfd = mutipart_form_data(mfd, boundary, &type, &content, (dwBufLen - offsetLen), contentLen, offsetLen);
if (mfd == NULL) {
break;
}
// show
//printf("name=\"%s\" content=\"%s\"\n"/*, name*/, content);
//printf
cJSON *root;
root = cJSON_Parse(content);
if (!root)
{
OutputDebugString("get json root failed !\n");
}
else
{
cJSON *eventType = cJSON_GetObjectItem(root, "eventType");
if (!eventType)
{
OutputDebugString("get json eventType failed !\n");
cJSON *TargetList = cJSON_GetObjectItem(root, "Target");
if (TargetList != NULL)
{
int iCount = cJSON_GetArraySize(TargetList); /*获取数组长度*/
if (iCount > 0)
{
cJSON *Target = cJSON_GetArrayItem(TargetList, 0);
if (Target != NULL)
{
cJSON *recognitionType = cJSON_GetObjectItem(Target, "recognitionType");
if (recognitionType != NULL)
{
sprintf(szInfoBuf, "Json format alarm recognitionType:[%s] Broken:[%d]", recognitionType->valuestring, g_bJSONBroken);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
}
}
}
}
else
{
sprintf(szInfoBuf, "Json format alarm eventType:[%s]", eventType->valuestring);
g_pMainDlg->AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
cJSON *channelID = cJSON_GetObjectItem(root, "channelID");
if (!channelID)
{
OutputDebugString("get json channelID failed !\n");
}
else
{
iChannelID = channelID->valueint;
}
}
if (root)
{
cJSON_Delete(root);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
char cFilename[256] = { 0 };
sprintf(cFilename, "%s\\%s[%d]_channel[%d]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort, iChannelID);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\%s_%d.%s", cFilename, chTime, i, type);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, content, contentLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < contentLen)
{
DWORD dwError = GetLastError();
//g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Face Snap Json Info Wtite to File Fail.System Error:%d, dwJsonDataLen:%d, WrittenBytes:%d ", dwError, struFaceSnap.dwJsonDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
free(type);
free(content);
if (mfd == NULL) {
break;
i = 0;
}
i++;
}
if (pCBBuf != NULL)
{
delete[] pCBBuf;
pCBBuf = NULL;
}
if (boundary != NULL)
{
delete[] boundary;
boundary = NULL;
}
}
void CClientDemoDlg::ProcessEventWithJsonDataNoBoundary(WPARAM wParam, LPARAM lParam)
{
char szLan[64] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
DWORD dwBufLen = pAlarmDev->dwBufLen;
//将报警内容写入文件
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
char cFilename[256] = { 0 };
sprintf(cFilename, "%s\\%s", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\%s.json", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, pAlarmInfo, pAlarmDev->dwBufLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < pAlarmDev->dwBufLen)
{
DWORD dwError = GetLastError();
//g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Face Snap Json Info Wtite to File Fail.System Error:%d, dwJsonDataLen:%d, WrittenBytes:%d ", dwError, struFaceSnap.dwJsonDataLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
}
void CClientDemoDlg::ProFramesPeopleCounting(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_FRAMES_PEOPLE_COUNTING struFramesPeopleCounting = { 0 };
memcpy(&struFramesPeopleCounting, pAlarmInfo, sizeof(NET_DVR_FRAMES_PEOPLE_COUNTING));
g_StringLanType(szLan, "定制 单帧画面人数统计", "Frames People Counting Alarm");
sprintf(szInfoBuf, "%s: IPv4[%s] IPv6[%s] Port[%d] Channel[%d] IvmsChannel[%d] RelativeTime[%d] AbsTime[%d] PeopleCountingNum[%d]", \
szLan, struFramesPeopleCounting.struDevInfo.struDevIP.sIpV4, struFramesPeopleCounting.struDevInfo.struDevIP.byIPv6, struFramesPeopleCounting.struDevInfo.wPort, \
struFramesPeopleCounting.struDevInfo.byChannel, struFramesPeopleCounting.struDevInfo.byIvmsChannel, struFramesPeopleCounting.dwRelativeTime, struFramesPeopleCounting.dwAbsTime, struFramesPeopleCounting.dwPeopleCountingNum);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
if (struFramesPeopleCounting.dwPicLen > 0 && struFramesPeopleCounting.pPicBuffer != NULL)
{
char cFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\[%s]", g_struLocalParam.chPictureSavePath, "[FramesPeopleCounting]");
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\FramesPeopleCounting[%s]_%d.txt", cFilename, chTime, rand() % GetTickCount());
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, struFramesPeopleCounting.pPicBuffer, struFramesPeopleCounting.dwPicLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struFramesPeopleCounting.dwPicLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Frames People Counting Info Wtite to File Fail.System Error:%d, dwJsonDataLen:%d, WrittenBytes:%d ", dwError, struFramesPeopleCounting.dwPicLen, dwWrittenBytes);
}
CloseHandle(hFile);
hFile = NULL;
delete[] struFramesPeopleCounting.pPicBuffer;
struFramesPeopleCounting.pPicBuffer = NULL;
}
}
void CClientDemoDlg::ProcessClusterAlarm(WPARAM wParam, LPARAM lParam)
{
char szLan[64] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
DWORD dwBufLen = pAlarmDev->dwBufLen;
char* pCBBuf = new char[dwBufLen];
if (pCBBuf == NULL)
{
sprintf(szLan, "内存申请失败 EventCluster dwBufLen:%d", dwBufLen);
AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
return;
}
memcpy(pCBBuf, pAlarmInfo, dwBufLen);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
char cFilename[256] = { 0 };
sprintf(cFilename, "%s\\%s.%s", g_struLocalParam.chPictureSavePath, chTime, "xml");
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, pCBBuf, dwBufLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < dwBufLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Cluster alarm Write to File Fail.System Error:%d, dwDataLen:%d, WrittenBytes:%d ", dwError, dwBufLen, dwWrittenBytes);
}
AddLog(iDeviceIndex, ALARM_INFO_T, "Receive Cluster Alarm.Check in saved files");
CloseHandle(hFile);
hFile = NULL;
if (pCBBuf != NULL)
{
delete[] pCBBuf;
pCBBuf = NULL;
}
}
void CClientDemoDlg::ProcISAPIAlarm(WPARAM wParam, LPARAM lParam)
{
//char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
int iPort = pAlarmDev->wLinkPort;
NET_DVR_ALARM_ISAPI_INFO struISAPIAlarm = { 0 };
memcpy(&struISAPIAlarm, pAlarmInfo, sizeof(NET_DVR_ALARM_ISAPI_INFO));
g_StringLanType(szLan, "ISAPI报警上传", "ISAPI Alarm");
AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
if (struISAPIAlarm.pAlarmData != NULL)
{
char cFilename[256] = { 0 };
char cExt[12] = { 0 };
char cSubFilename[256] = { 0 };
DWORD dwWrittenBytes = 0;
sprintf(cFilename, "%s\\%s[%s][%d]", g_struLocalParam.chPictureSavePath, "ISAPIAlarmData", g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName, iPort);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
memcpy(cSubFilename, cFilename, 256);
if (struISAPIAlarm.byDataType == 2)
{
sprintf(cExt, "%s", "json");
}
else if (struISAPIAlarm.byDataType == 1)
{
sprintf(cExt, "%s", "xml");
}
else
{
sprintf(cExt, "%s", "txt");
}
// sprintf(cFilename, "%s\\ISAPI[%s]_%d.%s", cFilename, chTime, rand() % GetTickCount(), cExt);
//
// HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// if (hFile == INVALID_HANDLE_VALUE)
// {
// return;
// }
// DWORD dwRet = WriteFile(hFile, struISAPIAlarm.pAlarmData, struISAPIAlarm.dwAlarmDataLen, &dwWrittenBytes, NULL);
// if (dwRet == 0 || dwWrittenBytes < struISAPIAlarm.dwAlarmDataLen)
// {
// DWORD dwError = GetLastError();
// g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Frames People Counting Info Wtite to File Fail.System Error:%d, dwJsonDataLen:%d, WrittenBytes:%d ", dwError, struISAPIAlarm.dwAlarmDataLen, dwWrittenBytes);
// }
// CloseHandle(hFile);
sprintf(cFilename, "%s\\%s.%s", cFilename, "COMM_ISAPI_ALARM", cExt);
CFile file;
if (!file.Open(cFilename, CFile::modeNoTruncate | CFile::modeCreate | CFile::modeReadWrite))
{
return;
}
file.SeekToEnd();
file.Write(struISAPIAlarm.pAlarmData, struISAPIAlarm.dwAlarmDataLen);
char szEnd[3] = { 0 };
szEnd[0] = '\r';
szEnd[1] = '\n';
file.Write(szEnd, strlen(szEnd));
file.Close();
if (struISAPIAlarm.pPicPackData != NULL)
{
int i = 0;
while (i <= struISAPIAlarm.byPicturesNumber - 1)
{
DWORD dwWrittenBytes = 0;
if (1 == ((NET_DVR_ALARM_ISAPI_PICDATA *)struISAPIAlarm.pPicPackData)[i].byPicType)
{
sprintf(cFilename, "%s\\PicData[%s]_%s_%d.jpg", cSubFilename, chTime, ((NET_DVR_ALARM_ISAPI_PICDATA *)struISAPIAlarm.pPicPackData)[i].szFilename, rand() % GetTickCount());
}
else
{
sprintf(cFilename, "%s\\PicData[%s]_%s_%d.dat", cSubFilename, chTime, ((NET_DVR_ALARM_ISAPI_PICDATA *)struISAPIAlarm.pPicPackData)[i].szFilename, rand() % GetTickCount());
}
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwRet = WriteFile(hFile, ((NET_DVR_ALARM_ISAPI_PICDATA *)struISAPIAlarm.pPicPackData)[i].pPicData, ((NET_DVR_ALARM_ISAPI_PICDATA *)struISAPIAlarm.pPicPackData)[i].dwPicLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < ((NET_DVR_ALARM_ISAPI_PICDATA *)struISAPIAlarm.pPicPackData)[i].dwPicLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Frames People Counting Info Wtite to File Fail.System Error:%d, dwJsonDataLen:%d, WrittenBytes:%d ", dwError, ((NET_DVR_ALARM_ISAPI_PICDATA *)struISAPIAlarm.pPicPackData)[i].dwPicLen, dwWrittenBytes);
}
CloseHandle(hFile);
delete ((NET_DVR_ALARM_ISAPI_PICDATA *)struISAPIAlarm.pPicPackData)[i].pPicData;
i++;
}
delete struISAPIAlarm.pPicPackData;
}
delete struISAPIAlarm.pAlarmData;
}
}
void CClientDemoDlg::OnMenuSearchAlarm()
{
// TODO: 在此添加命令处理程序代码
CDlgAlarmInfo dlg;
dlg.m_iDevIndex = GetCurDeviceIndex();
dlg.m_lServerID = g_struDeviceInfo[dlg.m_iDevIndex].lLoginID;
dlg.DoModal();
}
void CClientDemoDlg::ProcHeatMapResultPDC(WPARAM wParam, LPARAM lParam)//热度图按人数统计数据上传事件 2018-06-05
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
char szAlarmType[128] = { 0 };
char cFilename[256] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_HEATMAP_RESULT_PDC struHeatMapResult = { 0 };
memset(&struHeatMapResult, 0, sizeof(NET_DVR_HEATMAP_RESULT_PDC));
memcpy(&struHeatMapResult, pAlarmInfo, sizeof(NET_DVR_HEATMAP_RESULT_PDC));
sprintf(cFilename, "No heat map");
int iArrayUnitType = struHeatMapResult.byArrayUnitType;
for (int i = 0; i < 2; i++)
{
if (struHeatMapResult.struSingleHeatMap[i].wArrayColumn > 0 && struHeatMapResult.struSingleHeatMap[i].wArrayLine > 0 && struHeatMapResult.struSingleHeatMap[i].pBuffer != NULL)
{
sprintf(cFilename, "%s\\%s", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\HeatMapValue_%d_[%s].txt", cFilename, i, chTime);
HANDLE hFile;
DWORD dwReturn = 0;
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struHeatMapResult.struSingleHeatMap[i].pBuffer, struHeatMapResult.struSingleHeatMap[i].wArrayColumn*struHeatMapResult.struSingleHeatMap[i].wArrayLine, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
}
g_StringLanType(szLan, "热度图按人数统计报警", "Heat Map Result PDC");
sprintf(szInfoBuf, "%s:[IP:%s Port:%d Channel:%d IvmsChannel:%d StartTime%d-%d-%d %d:%d:%d EndTime:%d-%d-%d %d:%d:%d BrokenNetHttp:%d] IvmsChannelEx[%d] CurNumber[%d] LeaveNumber[%d] SingleHeatMap[0]:ArrayLine:%d ArrayColumn:%d MaxHeatMapValue:%d MinHeatMapValue:%d TimeHeatMapValue:%d\
SingleHeatMap[1]:ArrayLine:%d ArrayColumn:%d MaxHeatMapValue:%d MinHeatMapValue:%d TimeHeatMapValue:%d ArrayUnitType:%d\n", \
szLan, struHeatMapResult.struDevInfo.struDevIP.sIpV4, struHeatMapResult.struDevInfo.wPort, struHeatMapResult.struDevInfo.byChannel, \
struHeatMapResult.struDevInfo.byIvmsChannel, struHeatMapResult.struStartTime.wYear, struHeatMapResult.struStartTime.byMonth, \
struHeatMapResult.struStartTime.byDay, struHeatMapResult.struStartTime.byHour, struHeatMapResult.struStartTime.byMinute, \
struHeatMapResult.struStartTime.bySecond, struHeatMapResult.struEndTime.wYear, struHeatMapResult.struEndTime.byMonth, struHeatMapResult.struEndTime.byDay, \
struHeatMapResult.struEndTime.byHour, struHeatMapResult.struEndTime.byMinute, struHeatMapResult.struEndTime.bySecond, struHeatMapResult.byBrokenNetHttp, struHeatMapResult.wDevInfoIvmsChannelEx, struHeatMapResult.wCurNumber, struHeatMapResult.wLeaveNumber, \
struHeatMapResult.struSingleHeatMap[0].wArrayLine, struHeatMapResult.struSingleHeatMap[0].wArrayColumn, struHeatMapResult.struSingleHeatMap[0].dwMaxHeatMapValue, struHeatMapResult.struSingleHeatMap[0].dwMinHeatMapValue, struHeatMapResult.struSingleHeatMap[0].dwTimeHeatMapValue, \
struHeatMapResult.struSingleHeatMap[1].wArrayLine, struHeatMapResult.struSingleHeatMap[1].wArrayColumn, struHeatMapResult.struSingleHeatMap[1].dwMaxHeatMapValue, struHeatMapResult.struSingleHeatMap[1].dwMinHeatMapValue, struHeatMapResult.struSingleHeatMap[1].dwTimeHeatMapValue, \
struHeatMapResult.byArrayUnitType);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcHeatMapResultDuration(WPARAM wParam, LPARAM lParam)//热度图按人员停留时间统计数据上传事件 2018-06-05
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
char szAlarmType[128] = { 0 };
char cFilename[256] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_HEATMAP_RESULT struHeatMapResult = { 0 };
memset(&struHeatMapResult, 0, sizeof(NET_DVR_HEATMAP_RESULT));
memcpy(&struHeatMapResult, pAlarmInfo, sizeof(NET_DVR_HEATMAP_RESULT));
sprintf(cFilename, "No heat map");
if (struHeatMapResult.wArrayColumn > 0 && struHeatMapResult.wArrayLine > 0 && struHeatMapResult.pBuffer != NULL)
{
sprintf(cFilename, "%s\\%s", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\HeatMapValue[%s].txt", cFilename, chTime);
HANDLE hFile;
DWORD dwReturn = 0;
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, struHeatMapResult.pBuffer, struHeatMapResult.wArrayColumn*struHeatMapResult.wArrayLine*struHeatMapResult.byArrayUnitType, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
g_StringLanType(szLan, "热度图按人员停留时间报警", "Heat Map Duration Result");
sprintf(szInfoBuf, "%s:[IP:%s Port:%d Channel:%d IvmsChannel:%d StartTime%d-%d-%d %d:%d:%d EndTime:%d-%d-%d %d:%d:%d ArrayLine:%d ArrayColumn:%d HeatMapPath:%s \
MaxHeatMapValue:%d MinHeatMapValue:%d TimeHeatMapValue:%d DetSceneID:%d BrokenNetHttp:%dIvmsChannel[%d]IvmsChannelEx[%d]TotalTime[%d]]ArrayUnitType[%d]n", \
szLan, struHeatMapResult.struDevInfo.struDevIP.sIpV4, struHeatMapResult.struDevInfo.wPort, struHeatMapResult.struDevInfo.byChannel, \
struHeatMapResult.struDevInfo.byIvmsChannel, struHeatMapResult.struStartTime.wYear, struHeatMapResult.struStartTime.byMonth, \
struHeatMapResult.struStartTime.byDay, struHeatMapResult.struStartTime.byHour, struHeatMapResult.struStartTime.byMinute, \
struHeatMapResult.struStartTime.bySecond, struHeatMapResult.struEndTime.wYear, struHeatMapResult.struEndTime.byMonth, struHeatMapResult.struEndTime.byDay, \
struHeatMapResult.struEndTime.byHour, struHeatMapResult.struEndTime.byMinute, struHeatMapResult.struEndTime.bySecond, struHeatMapResult.wArrayLine, \
struHeatMapResult.wArrayColumn, cFilename, struHeatMapResult.dwMaxHeatMapValue, struHeatMapResult.dwMinHeatMapValue, struHeatMapResult.dwTimeHeatMapValue, \
struHeatMapResult.byDetSceneID, struHeatMapResult.byBrokenNetHttp, struHeatMapResult.struDevInfo.byIvmsChannel, struHeatMapResult.wDevInfoIvmsChannelEx, struHeatMapResult.dwTotalTime, \
struHeatMapResult.byArrayUnitType);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcHeatMapResultIntersection(WPARAM wParam, LPARAM lParam)//路口分析热度值结果上传 2018-06-05
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
char szAlarmType[128] = { 0 };
char cFilename[256] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_DVR_HEATMAP_RESULT struHeatMapResult = { 0 };
memset(&struHeatMapResult, 0, sizeof(NET_DVR_HEATMAP_RESULT));
memcpy(&struHeatMapResult, pAlarmInfo, sizeof(NET_DVR_HEATMAP_RESULT));
if (struHeatMapResult.wArrayColumn > 0 && struHeatMapResult.wArrayLine > 0 && struHeatMapResult.pBuffer != NULL)
{
char szIntersectionValueBuf[1024] = { 0 };
int iLine = 65;
int iColumn = 65;
for (int i = 0; i < struHeatMapResult.wArrayLine; i++)
{
//先在第一行打印A-J
if (i == 0)
{
sprintf(szIntersectionValueBuf, " ");
for (int k = 0; k < struHeatMapResult.wArrayColumn; k++)
{
sprintf(szIntersectionValueBuf, "%s %c ", szIntersectionValueBuf, iLine);
iLine++;
}
sprintf(szIntersectionValueBuf, "%s\r\n", szIntersectionValueBuf);
}
//打印每一行数据,数据之前会先打印一个字母
for (int j = 0; j < struHeatMapResult.wArrayColumn; j++)
{
if (j == 0)
{
sprintf(szIntersectionValueBuf, "%s%c ", szIntersectionValueBuf, iColumn);
iColumn++;
}
sprintf(szIntersectionValueBuf, "%s %d |", szIntersectionValueBuf, *(struHeatMapResult.pBuffer + (i*struHeatMapResult.wArrayColumn + j)*struHeatMapResult.byArrayUnitType));
}
sprintf(szIntersectionValueBuf, "%s\r\n", szIntersectionValueBuf);
}
sprintf(szIntersectionValueBuf, "%s StartTime%d-%d-%d %d:%d:%d EndTime:%d-%d-%d %d:%d:%d", szIntersectionValueBuf, \
struHeatMapResult.struStartTime.wYear, struHeatMapResult.struStartTime.byMonth, struHeatMapResult.struStartTime.byDay, \
struHeatMapResult.struStartTime.byHour, struHeatMapResult.struStartTime.byMinute,struHeatMapResult.struStartTime.bySecond, \
struHeatMapResult.struEndTime.wYear, struHeatMapResult.struEndTime.byMonth, struHeatMapResult.struEndTime.byDay, \
struHeatMapResult.struEndTime.byHour, struHeatMapResult.struEndTime.byMinute, struHeatMapResult.struEndTime.bySecond);
sprintf(cFilename, "%s\\%s", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\HeatMapResultIntersectionValue[%s].txt", cFilename, chTime);
HANDLE hFile;
DWORD dwReturn = 0;
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
WriteFile(hFile, szIntersectionValueBuf, sizeof(szIntersectionValueBuf), &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
g_StringLanType(szLan, "路口分析热度值报警", "Heat Map Result Intersection");
sprintf(szInfoBuf, "%s:[IP:%s Port:%d Channel:%d IvmsChannel:%d StartTime%d-%d-%d %d:%d:%d EndTime:%d-%d-%d %d:%d:%d ArrayLine:%d ArrayColumn:%d HeatMapPath:%s \
MaxHeatMapValue:%d MinHeatMapValue:%d TimeHeatMapValue:%d DetSceneID:%d BrokenNetHttp:%dIvmsChannel[%d]IvmsChannelEx[%d]ArrayUnitType[%d]\n", \
szLan, struHeatMapResult.struDevInfo.struDevIP.sIpV4, struHeatMapResult.struDevInfo.wPort, struHeatMapResult.struDevInfo.byChannel, \
struHeatMapResult.struDevInfo.byIvmsChannel, struHeatMapResult.struStartTime.wYear, struHeatMapResult.struStartTime.byMonth, \
struHeatMapResult.struStartTime.byDay, struHeatMapResult.struStartTime.byHour, struHeatMapResult.struStartTime.byMinute, \
struHeatMapResult.struStartTime.bySecond, struHeatMapResult.struEndTime.wYear, struHeatMapResult.struEndTime.byMonth, struHeatMapResult.struEndTime.byDay, \
struHeatMapResult.struEndTime.byHour, struHeatMapResult.struEndTime.byMinute, struHeatMapResult.struEndTime.bySecond, struHeatMapResult.wArrayLine, \
struHeatMapResult.wArrayColumn, cFilename, struHeatMapResult.dwMaxHeatMapValue, struHeatMapResult.dwMinHeatMapValue, struHeatMapResult.dwTimeHeatMapValue, \
struHeatMapResult.byDetSceneID, struHeatMapResult.byBrokenNetHttp, struHeatMapResult.struDevInfo.byIvmsChannel, struHeatMapResult.wDevInfoIvmsChannelEx, \
struHeatMapResult.byArrayUnitType);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcAIOPVideo(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
char cFilename[256] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
DWORD dwBufLen = pAlarmDev->dwBufLen;
NET_AIOP_VIDEO_HEAD struHead = { 0 };
memset(&struHead, 0, sizeof(NET_AIOP_VIDEO_HEAD));
memcpy(&struHead, pAlarmInfo, sizeof(NET_AIOP_VIDEO_HEAD));
g_StringLanType(szLan, "AI开放平台接入,上传视频检测数据", "AIOP_VIDEO");
sprintf(szInfoBuf, "%s:channel:%d,Time:%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d, TaskID:%s, AIOPDataSize:%d, PictureSize:%d, MPID[%s] PresetIndex[%d]\n", \
szLan, struHead.dwChannel, struHead.struTime.wYear, struHead.struTime.wMonth, struHead.struTime.wDay, \
struHead.struTime.wHour, struHead.struTime.wMinute, struHead.struTime.wSecond, struHead.struTime.wMilliSec, \
struHead.szTaskID, struHead.dwAIOPDataSize, struHead.dwPictureSize, struHead.szMPID,struHead.dwPresetIndex);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struHead.dwAIOPDataSize > 0 && struHead.pBufferAIOPData != NULL)
{
sprintf(cFilename, "%s\\%s[AIOPVideo]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\AIOP_DATA[%s].txt", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, struHead.pBufferAIOPData, struHead.dwAIOPDataSize, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struHead.dwAIOPDataSize)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AIOPVideo alarm Write to File Fail.System Error:%d, dwAIOPDataSize:%d, WrittenBytes:%d ", dwError, struHead.dwAIOPDataSize, dwWrittenBytes);
}
AddLog(iDeviceIndex, ALARM_INFO_T, "Receive AIOP_DATA file.Check in saved files");
CloseHandle(hFile);
hFile = NULL;
}
if (struHead.dwPictureSize > 0 && struHead.pBufferPicture != NULL&&struHead.byPictureMode == 0)
{
sprintf(cFilename, "%s\\%s[AIOPVideo]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\AIOP_Pic[%s].jpg", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, struHead.pBufferPicture, struHead.dwPictureSize, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struHead.dwPictureSize)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AIOPVideo alarm Write to File Fail.System Error:%d, PictureSize:%d, WrittenBytes:%d ", dwError, struHead.dwPictureSize, dwWrittenBytes);
}
AddLog(iDeviceIndex, ALARM_INFO_T, "Receive AIOP_Pic.Check in saved files");
CloseHandle(hFile);
hFile = NULL;
}
else if (struHead.dwPictureSize > 0 && struHead.pBufferPicture != NULL&&struHead.byPictureMode == 1)
{
sprintf(cFilename, "%s\\%s[AIOPVideo]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\AIOPVideo_URL_PIC[%s].txt", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, struHead.pBufferPicture, struHead.dwPictureSize, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struHead.dwPictureSize)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AIOPPollingVideo alarm Write to File Fail.System Error:%d, AIOPDataSize:%d, WrittenBytes:%d ", dwError, struHead.dwPictureSize, dwWrittenBytes);
}
AddLog(iDeviceIndex, ALARM_INFO_T, "Receive AIOP_URL_Pic.Check in saved files");
CloseHandle(hFile);
hFile = NULL;
}
}
void CClientDemoDlg::ProcAIOPPicture(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
char cFilename[256] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
NET_AIOP_PICTURE_HEAD struHead = { 0 };
memset(&struHead, 0, sizeof(NET_AIOP_PICTURE_HEAD));
memcpy(&struHead, pAlarmInfo, sizeof(NET_AIOP_PICTURE_HEAD));
g_StringLanType(szLan, "AI开放平台接入,上传图片检测数据", "AIOP_PICTURE");
sprintf(szInfoBuf, "%s:Time:%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d, AIOPDataSize:%d, Status:%d, MPID:%s PresetIndex[%d]\n", \
szLan, struHead.struTime.wYear, struHead.struTime.wMonth, struHead.struTime.wDay, \
struHead.struTime.wHour, struHead.struTime.wMinute, struHead.struTime.wSecond, struHead.struTime.wMilliSec, \
struHead.dwAIOPDataSize, struHead.byStatus, struHead.szMPID, struHead.dwPresetIndex);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struHead.dwAIOPDataSize > 0 && struHead.pBufferAIOPData != NULL)
{
sprintf(cFilename, "%s\\%s[AIOPPic]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\AIOP_DATA[%s].txt", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, struHead.pBufferAIOPData, struHead.dwAIOPDataSize, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struHead.dwAIOPDataSize)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AIOPPicture alarm Write to File Fail.System Error:%d, AIOPDataSize:%d, WrittenBytes:%d ", dwError, struHead.dwAIOPDataSize, dwWrittenBytes);
}
AddLog(iDeviceIndex, ALARM_INFO_T, "Receive AIOP_DATA file.Check in saved files");
CloseHandle(hFile);
hFile = NULL;
}
}
void CClientDemoDlg::ProcTrafficCollect(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
char szAlarmType[128] = { 0 };
char cFilename[256] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
DWORD dwBufLen = pAlarmDev->dwBufLen;
NET_ITS_TRAFFIC_COLLECT struCollect = { 0 };
memset(&struCollect, 0, sizeof(NET_ITS_TRAFFIC_COLLECT));
memcpy(&struCollect, pAlarmInfo, sizeof(NET_ITS_TRAFFIC_COLLECT));
g_StringLanType(szLan, "Traffic Collect", "Traffic Collect");
sprintf(szInfoBuf, "%s:dwSize[%d],byMonitoringSiteID[%s],byDeviceID[%s],byLaneNum[%d],byDir[%d],byDetectType[%d],dwChannel[%d],struStartTime[%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d],dwSamplePeriod[%d]", \
szLan, struCollect.dwSize, struCollect.byMonitoringSiteID, struCollect.byDeviceID, struCollect.byLaneNum, struCollect.byDir, struCollect.byDetectType,
struCollect.dwChannel, struCollect.struStartTime.wYear, struCollect.struStartTime.wMonth, struCollect.struStartTime.wDay,
struCollect.struStartTime.wHour, struCollect.struStartTime.wMinute, struCollect.struStartTime.wSecond, struCollect.struStartTime.wMilliSec);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
for (int i = 0; i < 6; ++i)
{
sprintf(szInfoBuf, "struDriveChan[%d]:byDriveChan[%d],wCarFlux[%d],wPasserbyFlux[%d],wShayFlux[%d],fAverOccpancy[%f],wAverSpeed[%d],wAverCarDis[%d]", \
i, struCollect.struDriveChan[i].byDriveChan, struCollect.struDriveChan[i].wCarFlux, struCollect.struDriveChan[i].wPasserbyFlux,
struCollect.struDriveChan[i].wShayFlux, struCollect.struDriveChan[i].fAverOccpancy, struCollect.struDriveChan[i].wAverSpeed, struCollect.struDriveChan[i].wAverCarDis);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
}
void CClientDemoDlg::ProcessVcaDbdAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[2048] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = { 0 };
g_StringLanType(szLan, "VcaDbdAlarm", "VcaDbdAlarm");
NET_DVR_DBD_ALRAM_INFO struAlarmInfo = { 0 };
memset(&struAlarmInfo, 0, sizeof(struAlarmInfo));
memcpy(&struAlarmInfo, pAlarmInfo, sizeof(struAlarmInfo));
sprintf(szInfoBuf, "%s uSize[%d],byChannel[%d],byLevel[%d],struIpcInfo{struDevIP[%s],wPort[%d],byChannel[%d]},\
struPosInfo{bValid[%d],uLongitude[%d],uLatitude[%d],dwAltitude[%d],uVehicleSpeed[%d],uVehicleDirection[%d]},\
struPicInfo{uPicType[%d],uPicLen[%d],uTime[%d]},\
struAlarmState{bySmoke[%d],byPhone[%d],byTiredDriving[%d],byNoVisualFront[%d],byNoHead[%d],byWithoutBelt[%d],byPickingUpThing[%d],byYawn[%d],byEatOrDrink[%d],byChatting[%d],byTampering[%d],byWithoutUniform[%d]}",
szLan,
struAlarmInfo.dwSize,
struAlarmInfo.byChannel,
struAlarmInfo.byLevel,
struAlarmInfo.struIpcInfo.struDevIP.sIpV4,
struAlarmInfo.struIpcInfo.wPort, struAlarmInfo.struIpcInfo.byChannel,
struAlarmInfo.struPosInfo.bValid,
struAlarmInfo.struPosInfo.dwLongitude,
struAlarmInfo.struPosInfo.dwLatitude,
struAlarmInfo.struPosInfo.dwAltitude,
struAlarmInfo.struPosInfo.dwVehicleSpeed,
struAlarmInfo.struPosInfo.dwVehicleDirection,
struAlarmInfo.struPicInfo.dwPicType,
struAlarmInfo.struPicInfo.dwPicLen,
struAlarmInfo.struPicInfo.dwTime,
struAlarmInfo.struAlarmState.bySmoke,
struAlarmInfo.struAlarmState.byPhone,
struAlarmInfo.struAlarmState.byTiredDriving,
struAlarmInfo.struAlarmState.byNoVisualFront,
struAlarmInfo.struAlarmState.byNoHead,
struAlarmInfo.struAlarmState.byWithoutBelt,
struAlarmInfo.struAlarmState.byPickingUpThing,
struAlarmInfo.struAlarmState.byYawn,
struAlarmInfo.struAlarmState.byEatOrDrink,
struAlarmInfo.struAlarmState.byChatting,
struAlarmInfo.struAlarmState.byTampering,
struAlarmInfo.struAlarmState.byWithoutUniform);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
//保存图片和视频
char cFilename[256] = { 0 };
sprintf(cFilename, "%s\\%s", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
do{
if (struAlarmInfo.struPicInfo.dwPicLen > 0 && struAlarmInfo.struPicInfo.pPicBuf != NULL)
{
sprintf(cFilename, "%s\\VCA_DBD[%s].jpg", cFilename, chTime);
HANDLE hFile;
DWORD dwReturn = 0;
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
break;
}
WriteFile(hFile, struAlarmInfo.struPicInfo.pPicBuf, struAlarmInfo.struPicInfo.dwPicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struAlarmInfo.struPicInfo.dwVideoLen > 0 && struAlarmInfo.struPicInfo.pVideoBuf != NULL)
{
sprintf(cFilename, "%s\\VCA_DBD[%s].mp4", cFilename, chTime);
HANDLE hFile;
DWORD dwReturn = 0;
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
break;
}
WriteFile(hFile, struAlarmInfo.struPicInfo.pVideoBuf, struAlarmInfo.struPicInfo.dwVideoLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
} while (0);
if (struAlarmInfo.struPicInfo.pPicBuf != NULL)
{
delete[]struAlarmInfo.struPicInfo.pPicBuf;
struAlarmInfo.struPicInfo.pPicBuf = NULL;
}
if (struAlarmInfo.struPicInfo.pVideoBuf != NULL)
{
delete[]struAlarmInfo.struPicInfo.pVideoBuf;
struAlarmInfo.struPicInfo.pVideoBuf = NULL;
}
}
void CClientDemoDlg::ProcessVcaAdasAlarm(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[2048] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = { 0 };
g_StringLanType(szLan, "VcaAdasAlarm", "VcaAdasAlarm");
NET_DVR_ADAS_ALRAM_INFO struAlarmInfo = { 0 };
memset(&struAlarmInfo, 0, sizeof(struAlarmInfo));
memcpy(&struAlarmInfo, pAlarmInfo, sizeof(struAlarmInfo));
sprintf(szInfoBuf, "%s uSize[%d],byChannel[%d],struIpcInfo{struDevIP[%s],wPort[%d],byChannel[%d]},\
struPosInfo{bValid[%d],uLongitude[%d],uLatitude[%d],dwAltitude[%d],uVehicleSpeed[%d],uVehicleDirection[%d]},\
struPicInfo{uPicType[%d],uPicLen[%d],uTime[%d]},\
struAlarmState{fcw[%d],ldw[%d],hmw[%d],pcw[%d],bsd[%d]}",
szLan,
struAlarmInfo.dwSize,
struAlarmInfo.byChannel,
struAlarmInfo.struIpcInfo.struDevIP.sIpV4,
struAlarmInfo.struIpcInfo.wPort, struAlarmInfo.struIpcInfo.byChannel,
struAlarmInfo.struPosInfo.dwValid,
struAlarmInfo.struPosInfo.dwLongitude,
struAlarmInfo.struPosInfo.dwLatitude,
struAlarmInfo.struPosInfo.dwAltitude,
struAlarmInfo.struPosInfo.dwVehicleSpeed,
struAlarmInfo.struPosInfo.dwVehicleDirection,
struAlarmInfo.struPicInfo.dwPicType,
struAlarmInfo.struPicInfo.dwPicLen,
struAlarmInfo.struPicInfo.dwTime,
struAlarmInfo.struAlarmState.dwFcw,
struAlarmInfo.struAlarmState.dwLdw,
struAlarmInfo.struAlarmState.dwHmw,
struAlarmInfo.struAlarmState.dwPcw,
struAlarmInfo.struAlarmState.dwBsd);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
//保存图片和视频
char cFilename[256] = { 0 };
sprintf(cFilename, "%s\\%s", g_struLocalParam.chPictureSavePath, pAlarmDev->sDeviceIP);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
do{
if (struAlarmInfo.struPicInfo.dwPicLen > 0 && struAlarmInfo.struPicInfo.pPicBuf != NULL)
{
sprintf(cFilename, "%s\\VCA_ADAS[%s].jpg", cFilename, chTime);
HANDLE hFile;
DWORD dwReturn = 0;
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
break;
}
WriteFile(hFile, struAlarmInfo.struPicInfo.pPicBuf, struAlarmInfo.struPicInfo.dwPicLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
if (struAlarmInfo.struPicInfo.dwVideoLen > 0 && struAlarmInfo.struPicInfo.pVideoBuf != NULL)
{
sprintf(cFilename, "%s\\VCA_ADAS[%s].mp4", cFilename, chTime);
HANDLE hFile;
DWORD dwReturn = 0;
hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
break;
}
WriteFile(hFile, struAlarmInfo.struPicInfo.pVideoBuf, struAlarmInfo.struPicInfo.dwVideoLen, &dwReturn, NULL);
CloseHandle(hFile);
hFile = NULL;
}
} while (0);
if (struAlarmInfo.struPicInfo.pPicBuf != NULL)
{
delete[]struAlarmInfo.struPicInfo.pPicBuf;
struAlarmInfo.struPicInfo.pPicBuf = NULL;
}
if (struAlarmInfo.struPicInfo.pVideoBuf != NULL)
{
delete[]struAlarmInfo.struPicInfo.pVideoBuf;
struAlarmInfo.struPicInfo.pVideoBuf = NULL;
}
}
void CClientDemoDlg::ProcessVehRealtimeInfo(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[2048] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
char szLan[128] = { 0 };
g_StringLanType(szLan, "VehRealtimeInfo", "VehRealtimeInfo");
NET_DVR_VEH_REALTIME_DATA_INFO struVehRealtimeInfo = { 0 };
memset(&struVehRealtimeInfo, 0, sizeof(struVehRealtimeInfo));
memcpy(&struVehRealtimeInfo, pAlarmInfo, sizeof(struVehRealtimeInfo));
sprintf(szInfoBuf, "%s dwSize[%d],dwSpeedValue[%d],dwSpeedPulse[%d],byUpgPercent[%d],dwVideoLostChans[%d]",
szLan,
struVehRealtimeInfo.dwSize,
struVehRealtimeInfo.dwSpeedValue,
struVehRealtimeInfo.dwSpeedPulse,
struVehRealtimeInfo.byUpgPercent,
struVehRealtimeInfo.dwVideoLostChans);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
}
void CClientDemoDlg::ProcessSubCribeEvent(WPARAM wParam, LPARAM lParam)
{
char szLan[64] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
DWORD dwBufLen = pAlarmDev->dwBufLen;
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
char cFilename[256] = { 0 };
sprintf(cFilename, "%s\\%s", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
sprintf(cFilename, "%s\\%s.xml", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, pAlarmInfo, pAlarmDev->dwBufLen, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < dwBufLen)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "Subscribe failed event info Write to File Fail.System Error:%d, dwDataLen:%d, WrittenBytes:%d ", dwError, dwBufLen, dwWrittenBytes);
}
g_StringLanType(szLan, "订阅失败信息返回", "Subscribe failed event info");
AddLog(iDeviceIndex, ALARM_INFO_T, szLan);
CloseHandle(hFile);
hFile = NULL;
}
void CClientDemoDlg::ProcAIOPPollingSnap(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
char cFilename[256] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
DWORD dwBufLen = pAlarmDev->dwBufLen;
NET_AIOP_POLLING_SNAP_HEAD struHead = { 0 };
memset(&struHead, 0, sizeof(NET_AIOP_POLLING_SNAP_HEAD));
memcpy(&struHead, pAlarmInfo, sizeof(NET_AIOP_POLLING_SNAP_HEAD));
g_StringLanType(szLan, "AI开放平台接入,上传轮巡抓图图片检测数据", "AIOP_POLLING_SNAP");
sprintf(szInfoBuf, "%s:Time:%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d, channel:%d,TadkID:%s, AIOPDataSize:%d, MPID:%s PresetIndex[%d]\r", \
szLan, struHead.struTime.wYear, struHead.struTime.wMonth, struHead.struTime.wDay, \
struHead.struTime.wHour, struHead.struTime.wMinute, struHead.struTime.wSecond, struHead.struTime.wMilliSec, \
struHead.dwChannel, struHead.szTaskID, struHead.dwAIOPDataSize, struHead.szMPID,struHead.dwPresetIndex);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struHead.dwAIOPDataSize > 0 && struHead.pBufferAIOPData != NULL)
{
sprintf(cFilename, "%s\\%s[AIOPPollingSnap]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\AIOP_DATA[%s].txt", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, struHead.pBufferAIOPData, struHead.dwAIOPDataSize, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struHead.dwAIOPDataSize)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AIOPPollingSnap alarm Write to File Fail.System Error:%d, AIOPDataSize:%d, WrittenBytes:%d ", dwError, struHead.dwAIOPDataSize, dwWrittenBytes);
}
AddLog(iDeviceIndex, ALARM_INFO_T, "Receive AIOP_DATA file.Check in saved files");
CloseHandle(hFile);
hFile = NULL;
}
if (struHead.dwPictureSize > 0 && struHead.pBufferPicture != NULL&&struHead.byPictureMode==0)
{
sprintf(cFilename, "%s\\%s[AIOPPollingSnap]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\AIOP_POLLING_PICTURE[%s].jpg", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, struHead.pBufferPicture, struHead.dwPictureSize, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struHead.dwAIOPDataSize)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AIOPPollingSnap alarm Write to File Fail.System Error:%d, PictureSize:%d, WrittenBytes:%d ", dwError, struHead.dwPictureSize, dwWrittenBytes);
}
AddLog(iDeviceIndex, ALARM_INFO_T, "Receive AIOP_POLLING_PICTURE file.Check in saved files");
CloseHandle(hFile);
hFile = NULL;
}
else if (struHead.dwPictureSize > 0 && struHead.pBufferPicture != NULL&&struHead.byPictureMode == 1)
{
sprintf(cFilename, "%s\\%s[AIOPPollingSnap]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\AIOPPollingSnap_URL_PIC[%s].txt", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, struHead.pBufferPicture, struHead.dwPictureSize, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struHead.dwPictureSize)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AIOPPollingVideo alarm Write to File Fail.System Error:%d, AIOPDataSize:%d, WrittenBytes:%d ", dwError, struHead.dwPictureSize, dwWrittenBytes);
}
AddLog(iDeviceIndex, ALARM_INFO_T, "Receive AIOP_POLLING_URL_PICTURE file.Check in saved files");
CloseHandle(hFile);
hFile = NULL;
}
}
void CClientDemoDlg::ProcAIOPPollingVideo(WPARAM wParam, LPARAM lParam)
{
char szInfoBuf[1024] = { 0 };
char szLan[128] = { 0 };
char cFilename[256] = { 0 };
LPLOCAL_ALARM_INFO pAlarmDev = (LPLOCAL_ALARM_INFO)(wParam);
char *pAlarmInfo = (char *)(lParam);
int iDeviceIndex = pAlarmDev->iDeviceIndex;
DWORD dwBufLen = pAlarmDev->dwBufLen;
NET_AIOP_POLLING_VIDEO_HEAD struHead = { 0 };
memset(&struHead, 0, sizeof(NET_AIOP_POLLING_VIDEO_HEAD));
memcpy(&struHead, pAlarmInfo, sizeof(NET_AIOP_POLLING_VIDEO_HEAD));
g_StringLanType(szLan, "AI开放平台接入,上传视频轮训检测数据", "AIOP_POLLING_VIDEO");
sprintf(szInfoBuf, "%s:Time:%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d, channel:%d, TaskID:%s,AIOPDataSize:%d, PictureSize:%d, MPID:%s PresetIndex[%d]\n", \
szLan, struHead.struTime.wYear, struHead.struTime.wMonth, struHead.struTime.wDay, \
struHead.struTime.wHour, struHead.struTime.wMinute, struHead.struTime.wSecond, struHead.struTime.wMilliSec, \
struHead.dwChannel, struHead.szTaskID, struHead.dwAIOPDataSize, struHead.dwPictureSize, struHead.szMPID,struHead.dwPresetIndex);
AddLog(iDeviceIndex, ALARM_INFO_T, szInfoBuf);
if (struHead.dwAIOPDataSize > 0 && struHead.pBufferAIOPData != NULL)
{
sprintf(cFilename, "%s\\%s[AIOPPollingVideo]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\AIOP_DATA[%s].txt", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, struHead.pBufferAIOPData, struHead.dwAIOPDataSize, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struHead.dwAIOPDataSize)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AIOPPollingVideo alarm Write to File Fail.System Error:%d, AIOPDataSize:%d, WrittenBytes:%d ", dwError, struHead.dwAIOPDataSize, dwWrittenBytes);
}
AddLog(iDeviceIndex, ALARM_INFO_T, "Receive AIOP_DATA file.Check in saved files");
CloseHandle(hFile);
hFile = NULL;
}
if (struHead.dwPictureSize > 0 && struHead.pBufferPicture != NULL&&struHead.byPictureMode==0)
{
sprintf(cFilename, "%s\\%s[AIOPPollingVideo]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\AIOP_POLLING_VIDEO[%s].jpg", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, struHead.pBufferPicture, struHead.dwPictureSize, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struHead.dwAIOPDataSize)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AIOPPollingVideo alarm Write to File Fail.System Error:%d, AIOPPollingPictureSize:%d, WrittenBytes:%d ", dwError, struHead.dwPictureSize, dwWrittenBytes);
}
AddLog(iDeviceIndex, ALARM_INFO_T, "Receive AIOP_POLLING_VIDEO file.Check in saved files");
CloseHandle(hFile);
hFile = NULL;
}
else if (struHead.dwPictureSize > 0 && struHead.pBufferPicture != NULL&&struHead.byPictureMode == 1)
{
sprintf(cFilename, "%s\\%s[AIOPPollingVideo]", g_struLocalParam.chPictureSavePath, g_struDeviceInfo[iDeviceIndex].chDeviceIPInFileName);
if (GetFileAttributes(cFilename) != FILE_ATTRIBUTE_DIRECTORY)
{
CreateDirectory(cFilename, NULL);
}
SYSTEMTIME t;
GetLocalTime(&t);
char chTime[128];
sprintf(chTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
sprintf(cFilename, "%s\\AIOPPollingVideo_URL_PIC[%s].txt", cFilename, chTime);
HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return;
}
DWORD dwWrittenBytes = 0;
DWORD dwRet = WriteFile(hFile, struHead.pBufferPicture, struHead.dwPictureSize, &dwWrittenBytes, NULL);
if (dwRet == 0 || dwWrittenBytes < struHead.dwPictureSize)
{
DWORD dwError = GetLastError();
g_pMainDlg->AddLog(iDeviceIndex, OPERATION_FAIL_T, "AIOPPollingVideo alarm Write to File Fail.System Error:%d, AIOPDataSize:%d, WrittenBytes:%d ", dwError, struHead.dwPictureSize, dwWrittenBytes);
}
AddLog(iDeviceIndex, ALARM_INFO_T, "Receive AIOP_DATA file.Check in saved files");
CloseHandle(hFile);
hFile = NULL;
}
}
| [
"yyj8209@163.com"
] | yyj8209@163.com |
71aae707a37a8a181b0a945ac803a8e92a17bb7c | cb2c21441bea57d04e25d2bcb6bf3e41aad8e85e | /src/heightmap.h | f3894efba414914d11c9da233afd8467dc74c3df | [] | no_license | heitaoflower/hmm | 776576808fa05ad8905a25b1045635d3010e77c3 | 47906d42c1968c88339799437d099e3efb541a7e | refs/heads/master | 2020-07-11T03:28:28.921612 | 2019-08-26T03:30:43 | 2019-08-26T03:30:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 679 | h | #pragma once
#include <glm/glm.hpp>
#include <string>
#include <utility>
#include <vector>
class Heightmap {
public:
Heightmap(const std::string &path);
int Width() const {
return m_Width;
}
int Height() const {
return m_Height;
}
float At(const int x, const int y) const {
return m_Data[y * m_Width + x];
}
float At(const glm::ivec2 p) const {
return m_Data[p.y * m_Width + p.x];
}
std::pair<glm::ivec2, float> FindCandidate(
const glm::ivec2 p0,
const glm::ivec2 p1,
const glm::ivec2 p2) const;
private:
int m_Width;
int m_Height;
std::vector<float> m_Data;
};
| [
"fogleman@gmail.com"
] | fogleman@gmail.com |
30326183f91a7fa5f340d10c291805a764d559ea | 7abeae5aa8f2374df600b229b851d51b0a2ec025 | /FitSDKRelease_21.40.00/cpp/fit_monitoring_info_mesg_listener.hpp | c35aeeec721b0e46bf102e7eb46f511e30e8a7ac | [
"Apache-2.0"
] | permissive | JoyKuan/ArchitecturalDesign_AI | c66ffe0a98a67b6a36a6ffb60071e9a97de90014 | 71442dcfdba20564a772a6807e43cbb86dafc14d | refs/heads/main | 2023-02-28T07:45:46.378995 | 2021-02-02T21:54:55 | 2021-02-02T21:54:55 | 322,163,300 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,356 | hpp | ////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Garmin Canada Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2020 Garmin Canada Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 21.40Release
// Tag = production/akw/21.40.00-0-g813c158
////////////////////////////////////////////////////////////////////////////////
#if !defined(FIT_MONITORING_INFO_MESG_LISTENER_HPP)
#define FIT_MONITORING_INFO_MESG_LISTENER_HPP
#include "fit_monitoring_info_mesg.hpp"
namespace fit
{
class MonitoringInfoMesgListener
{
public:
virtual ~MonitoringInfoMesgListener() {}
virtual void OnMesg(MonitoringInfoMesg& mesg) = 0;
};
} // namespace fit
#endif // !defined(FIT_MONITORING_INFO_MESG_LISTENER_HPP)
| [
"kuanhuil@usc.edu"
] | kuanhuil@usc.edu |
05f5bf7d577bcb6b66963d940dd82237249ab1a7 | 3390f604b39fe90933bc4e919ba9d6720dc66537 | /src/robocontrol/controller/interrupt/Interrupt.h | 0e4d543fbdd9641553e4ed9f7623f7f87e871832 | [] | no_license | hiroshi-mikuriya/nxt | 880aa9ebee679797d8b2d5c25054e027857d2263 | edfd585548447117eb3605ef0f451c8bf8346629 | refs/heads/master | 2021-05-09T07:01:44.238374 | 2018-01-29T07:33:58 | 2018-01-29T07:33:58 | 119,347,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 673 | h | /*
* Interrupt.h
*
* Created on: 2012/07/31
* Author: HIROSHI MIKURIYA
*/
#ifndef INTERRUPT_H_
#define INTERRUPT_H_
#include "event/parts/EventParts.h"
namespace controller {
class Interrupt {
public:
/**
* イベントとそれが発生したときに行う動作のペア
*/
struct EventProcT {
event::parts::Event m_event;
void (*m_proc)();
};
private:
Interrupt();
bool m_enable;
EventProcT * m_begin;
EventProcT * m_end;
public:
static Interrupt & GetInstance();
void Do();
void Set(EventProcT * begin, EventProcT * end);
void Enable(bool enable);
};
} /* namespace controller */
#endif /* INTERRUPT_H_ */
| [
"hiroshi.mikuriya@fxat.co.jp"
] | hiroshi.mikuriya@fxat.co.jp |
1301827b851e9f84ac94b2a69def821bfcf5ebdc | 93aacecedc7c8214c9ca7171f081884f2a314699 | /PriorityQueue.h | 1cd737afeba3923a5e1fe2fa816672c3c5bde363 | [] | no_license | alkanalperen/Printer-Simulation | 8c375ab947ad3360d5b74a6e306b82090f2f1a5c | ef7552eef6cc34b823346962ca76d77847256ff8 | refs/heads/main | 2023-05-03T21:48:35.840994 | 2021-05-25T10:43:31 | 2021-05-25T10:43:31 | 370,655,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | h | /*
* Title: Heaps
* Author: Alperen Alkan
* ID: 21803216
* Section: 3
* Assignment: 3
* Description: main
*/
#ifndef HW3_PRIORITYQUEUE_H
#define HW3_PRIORITYQUEUE_H
#include "Heap.h"
#include "Request.h"
class PriorityQueue {
public:
// default constructor, copy constructor, and destructor
// are supplied by the compiler
// priority-queue operations:
bool pqIsEmpty() const;
void pqInsert(const Request& newItem); //throw (PQException);
void pqDelete( Request& priorityItem); //throw (PQException);
private:
Heap h;
};
#endif //HW3_PRIORITYQUEUE_H
| [
"noreply@github.com"
] | alkanalperen.noreply@github.com |
9e86ebed0c26e1c5c1a8210c35bbaf949f7c8497 | 8567438779e6af0754620a25d379c348e4cd5a5d | /net/tools/quic/test_tools/mock_quic_time_wait_list_manager.h | a2d7fa6cee481e4a158b9abfa0ecbb57fab4b94d | [
"BSD-3-Clause"
] | permissive | thngkaiyuan/chromium | c389ac4b50ccba28ee077cbf6115c41b547955ae | dab56a4a71f87f64ecc0044e97b4a8f247787a68 | refs/heads/master | 2022-11-10T02:50:29.326119 | 2017-04-08T12:28:57 | 2017-04-08T12:28:57 | 84,073,924 | 0 | 1 | BSD-3-Clause | 2022-10-25T19:47:15 | 2017-03-06T13:04:15 | null | UTF-8 | C++ | false | false | 2,218 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_TOOLS_QUIC_TEST_TOOLS_MOCK_QUIC_TIME_WAIT_LIST_MANAGER_H_
#define NET_TOOLS_QUIC_TEST_TOOLS_MOCK_QUIC_TIME_WAIT_LIST_MANAGER_H_
#include "net/tools/quic/quic_time_wait_list_manager.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace net {
namespace test {
class MockTimeWaitListManager : public QuicTimeWaitListManager {
public:
MockTimeWaitListManager(QuicPacketWriter* writer,
Visitor* visitor,
QuicConnectionHelperInterface* helper,
QuicAlarmFactory* alarm_factory);
~MockTimeWaitListManager() override;
MOCK_METHOD4(AddConnectionIdToTimeWait,
void(QuicConnectionId connection_id,
QuicVersion version,
bool connection_rejected_statelessly,
std::vector<std::unique_ptr<QuicEncryptedPacket>>*
termination_packets));
void QuicTimeWaitListManager_AddConnectionIdToTimeWait(
QuicConnectionId connection_id,
QuicVersion version,
bool connection_rejected_statelessly,
std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets) {
QuicTimeWaitListManager::AddConnectionIdToTimeWait(
connection_id, version, connection_rejected_statelessly,
termination_packets);
}
MOCK_METHOD5(ProcessPacket,
void(const QuicSocketAddress& server_address,
const QuicSocketAddress& client_address,
QuicConnectionId connection_id,
QuicPacketNumber packet_number,
const QuicEncryptedPacket& packet));
MOCK_METHOD4(SendVersionNegotiationPacket,
void(QuicConnectionId connection_id,
const QuicVersionVector& supported_versions,
const QuicSocketAddress& server_address,
const QuicSocketAddress& client_address));
};
} // namespace test
} // namespace net
#endif // NET_TOOLS_QUIC_TEST_TOOLS_MOCK_QUIC_TIME_WAIT_LIST_MANAGER_H_
| [
"hedonist.ky@gmail.com"
] | hedonist.ky@gmail.com |
2726825b4fafa2b60873b391ccfb3d492cf811ec | 5b7be40ce294fac1fb7ec6085d5705e2bf0fd890 | /src/3d-party/boundingmesh/SimpleOptimizer.h | f6e5cf30e43e443fcff96b9c76a8940ff01157a4 | [] | no_license | jedrzejowski/sokar-app | 97b7997cea12fbb0fd55f33b625b382ce1eeb7a4 | c918a3d5383c68b0f3fb042c014549fc25ba1991 | refs/heads/master | 2022-05-19T03:03:46.879716 | 2022-03-29T22:36:48 | 2022-03-29T22:36:48 | 132,521,466 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,896 | h | // Copyright (c) 2019, the boundingmesh authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this
// list of conditions and the following disclaimer in the documentation
// and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef BOUNDINGMESH_SIMPLEOPTIMIZER_H
#define BOUNDINGMESH_SIMPLEOPTIMIZER_H
#include "boundingmesh/OptimizerInterface.h"
namespace boundingmesh {
class SimpleOptimizer : public OptimizerInterface {
public:
bool optimize(const Matrix44& qem, const std::vector<Plane>& constraints,
bool constrain_outside_planes, Vector3* solution,
Real* cost) const final;
};
} // namespace boundingmesh
#endif // BOUNDINGMESH_SIMPLEOPTIMIZER_H
| [
"adam@jedrzejowski.pl"
] | adam@jedrzejowski.pl |
d9ee5273f6596417326b9459356bb714a4e25829 | 20a6df4c4c9183b80f23f2e77806e345c4ca1473 | /7. Speech Contest Process Management System/speechManager.cpp | 488dd05c0adaa16acc6174d9e5728aa1ea55e9b3 | [
"MIT"
] | permissive | weijiew/cpp-study-cases | a14627980ba622463bbf244a57b26796f508e003 | d204efa9a33f18ff7ebdec58bdba4056c25f464a | refs/heads/main | 2023-03-01T16:26:35.275203 | 2021-02-02T09:00:13 | 2021-02-02T09:00:13 | 308,617,811 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,185 | cpp | #include <iostream>
#include "speechManager.h"
SpeechManager::SpeechManager(){
this->initSpeech();
}
void SpeechManager::Show_Menu(){
cout << "**********************" << endl;
cout << "*** 欢迎参加演讲比赛 ***" << endl;
cout << "*** 1. 开始演讲比赛。***" << endl;
cout << "*** 2. 查看往届记录。***" << endl;
cout << "*** 3. 清空比赛记录。***" << endl;
cout << "*** 0. 退出比赛程序。***" << endl;
cout << "**********************" << endl;
cout << endl;
}
void SpeechManager::exitSystem(){
cout << "欢迎下次使用!" << endl;
system("pause");
exit(0);
}
void SpeechManager::initSpeech(){
this->v1.clear();
this->v2.clear();
this->vVictory.clear();
this->m_Speaker.clear();
// 初始化比赛轮次
this->m_Index = 1;
}
void SpeechManager::createSpeaker(){
string nameSeed = "ABCDEFGHIJKL";
for (int i = 0; i < nameSeed; i++){
string name = "选手";
name += nameSeed[i];
Speaker sp;
sp.m_Name = name;
for (int i = 0; i < 2; i++){
sp.m_Score[i] = 0;
}
}
}
SpeechManager::~SpeechManager(){
} | [
"836678589@qq.com"
] | 836678589@qq.com |
d809d4175f1a25df9c66db34f29fb78da7ccbb33 | 295356e2cf152ae3a24e78ea409b44e9ee7dccc3 | /ns-allinone-3.17/ns-3.17/src/lte/model/epc-ue-nas.cc | 7d3dafaf70d69901af5689e999118a00158a7cf1 | [] | no_license | evyhsu/ho-lte | 37dc21b3d35c3c1f46f65e644abed40594c2ddaf | 7c546549ff2299d826ea4149fc8743da4bef9da3 | refs/heads/master | 2021-01-10T20:08:41.571656 | 2014-04-24T02:33:57 | 2014-04-24T02:33:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,889 | cc | /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Nicola Baldo <nbaldo@cttc.es>
*/
#include <ns3/fatal-error.h>
#include <ns3/log.h>
#include <ns3/epc-helper.h>
#include "lte-enb-net-device.h"
#include "epc-ue-nas.h"
#include "lte-as-sap.h"
NS_LOG_COMPONENT_DEFINE ("EpcUeNas");
namespace ns3 {
const char* g_ueNasStateName[EpcUeNas::NUM_STATES] =
{
"OFF",
"ATTACHING",
"IDLE_REGISTERED",
"CONNECTING_TO_EPC",
"ACTIVE "
};
std::string ToString (EpcUeNas::State s)
{
return std::string (g_ueNasStateName[s]);
}
NS_OBJECT_ENSURE_REGISTERED (EpcUeNas);
EpcUeNas::EpcUeNas ()
: m_state (OFF),
m_asSapProvider (0),
m_bidCounter (0)
{
NS_LOG_FUNCTION (this);
m_asSapUser = new MemberLteAsSapUser<EpcUeNas> (this);
}
EpcUeNas::~EpcUeNas ()
{
NS_LOG_FUNCTION (this);
}
void
EpcUeNas::DoDispose ()
{
NS_LOG_FUNCTION (this);
delete m_asSapUser;
}
TypeId
EpcUeNas::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::EpcUeNas")
.SetParent<Object> ()
.AddConstructor<EpcUeNas> ()
.AddTraceSource ("StateTransition",
"fired upon every UE NAS state transition",
MakeTraceSourceAccessor (&EpcUeNas::m_stateTransitionCallback))
;
return tid;
}
void
EpcUeNas::SetDevice (Ptr<NetDevice> dev)
{
m_device = dev;
}
void
EpcUeNas::SetImsi (uint64_t imsi)
{
m_imsi = imsi;
NS_LOG_FUNCTION ("yen EpcUeNas::SetImsi :" << imsi);
}
/*-----------------------yen add---------------*/
void
EpcUeNas::SetMulticastGroup (uint16_t multicastgroup)
{
m_multicastgroup = multicastgroup;
NS_LOG_FUNCTION ("yen EpcUeNas::multicastgroup :" << multicastgroup);
}
void
EpcUeNas::SetAsSapProvider (LteAsSapProvider* s)
{
m_asSapProvider = s;
}
LteAsSapUser*
EpcUeNas::GetAsSapUser ()
{
return m_asSapUser;
}
void
EpcUeNas::SetForwardUpCallback (Callback <void, Ptr<Packet> > cb)
{
m_forwardUpCallback = cb;
}
void
EpcUeNas::Connect (uint16_t cellId, uint16_t earfcn)
{
NS_LOG_FUNCTION (this);
// since RRC Idle Mode cell selection is not supported yet, we
// force the UE RRC to be camped on a specific eNB
m_asSapProvider->ForceCampedOnEnb (cellId, earfcn);
// tell RRC to go into connected mode
m_asSapProvider->Connect ();
}
void
EpcUeNas::Disconnect ()
{
NS_LOG_FUNCTION (this);
m_asSapProvider->Disconnect ();
SwitchToState (OFF);
}
void
EpcUeNas::ActivateEpsBearer (EpsBearer bearer, Ptr<EpcTft> tft)
{
NS_LOG_FUNCTION (this);
switch (m_state)
{
case ACTIVE:
NS_FATAL_ERROR ("the necessary NAS signaling to activate a bearer after the initial context has already been setup is not implemented");
break;
default:
BearerToBeActivated btba;
btba.bearer = bearer;
btba.tft = tft;
m_bearersToBeActivatedList.push_back (btba);
break;
}
}
bool
EpcUeNas::Send (Ptr<Packet> packet)
{
NS_LOG_FUNCTION (this << packet);
switch (m_state)
{
case ACTIVE:
{
uint32_t id = m_tftClassifier.Classify (packet, EpcTft::UPLINK);
NS_ASSERT ((id & 0xFFFFFF00) == 0);
//yen
//NS_ASSERT ((id & 0xFFFF0000) == 0);
uint8_t bid = (uint8_t) (id & 0x000000FF);
//yen
NS_LOG_FUNCTION ("YEN EpcUeNas bid: " << bid << " id: " << id);
if (bid == 0)
{
return false;
}
else
{
m_asSapProvider->SendData (packet, bid);
return true;
}
}
break;
default:
NS_LOG_WARN (this << " NAS OFF, discarding packet");
return false;
break;
}
}
void
EpcUeNas::DoNotifyConnectionSuccessful ()
{
NS_LOG_FUNCTION (this);
SwitchToState (ACTIVE); // will eventually activate dedicated bearers
}
void
EpcUeNas::DoNotifyConnectionFailed ()
{
NS_FATAL_ERROR ("connection failed, it should not happen with the current model");
}
void
EpcUeNas::DoRecvData (Ptr<Packet> packet)
{
NS_LOG_FUNCTION (this);
m_forwardUpCallback (packet);
}
void
EpcUeNas::DoNotifyConnectionReleased ()
{
NS_LOG_FUNCTION (this);
SwitchToState (OFF);
}
void
EpcUeNas::DoActivateEpsBearer (EpsBearer bearer, Ptr<EpcTft> tft)
{
NS_LOG_FUNCTION (this);
NS_ASSERT_MSG (m_bidCounter < 11, "cannot have more than 11 EPS bearers");
uint8_t bid = ++m_bidCounter;
//yen
//uint8_t bid = 20;
m_tftClassifier.Add (tft, bid);
}
void
EpcUeNas::SwitchToState (State newState)
{
NS_LOG_FUNCTION (this << newState);
State oldState = m_state;
m_state = newState;
NS_LOG_INFO ("IMSI " << m_imsi << " NAS " << ToString (oldState) << " --> " << ToString (newState));
m_stateTransitionCallback (oldState, newState);
// actions to be done when entering a new state:
switch (m_state)
{
case ACTIVE:
for (std::list<BearerToBeActivated>::iterator it = m_bearersToBeActivatedList.begin ();
it != m_bearersToBeActivatedList.end ();
m_bearersToBeActivatedList.erase (it++))
{
DoActivateEpsBearer (it->bearer, it->tft);
}
break;
default:
break;
}
}
} // namespace ns3
| [
"yenchu@yenchu.(none)"
] | yenchu@yenchu.(none) |
91d91c7425c314687576d2273c498a36acbcf0ee | de3b2b924bf3498d9644fdbfec72514bba6d14d1 | /C++/invert_binary_tree.cpp | 2bac71a4b2a9c8adc4d3442d157557d456d61c02 | [] | no_license | eric82714/LeetCode_226--Invert-Binary-Tree | 39504af771abc846229311cd55b6bed4f6f6d523 | 5e3e0eb97bb4cb547ff04ef29a8ba22b9d7c8f83 | refs/heads/master | 2021-01-04T05:55:05.523985 | 2020-02-14T03:36:46 | 2020-02-14T03:36:46 | 240,418,068 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 539 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return NULL;
TreeNode* tmp;
tmp = root->right;
root->right = root->left;
root->left = tmp;
invertTree(root->right);
invertTree(root->left);
return root;
}
};
| [
"noreply@github.com"
] | eric82714.noreply@github.com |
bc8e054faaff94da0d5875c547ac4446e50e4a24 | 6a246869b9f099f043f3e6bd613fc90992ce19fe | /Talat/RectanglePawn.h | 4cf69785cf0fe3c410a467d4f072fa887a252cbe | [] | no_license | justcasualguy/Talat | ab9b531dcbc04c9803f76334c769d768684fe7d2 | 511972d100eda22061f5d6f682963ea36e8b0a82 | refs/heads/master | 2020-05-24T21:22:12.407155 | 2019-06-29T13:16:36 | 2019-06-29T13:16:36 | 180,581,354 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202 | h | #pragma once
#include "Pawn.h"
class RectanglePawn :public Pawn
{
public:
RectanglePawn();
RectanglePawn(Size size);
~RectanglePawn();
void draw(Board& board, COORD boardField,Color pawnColor);
};
| [
"kubachw@gmail.com"
] | kubachw@gmail.com |
9cff6751ec88c916865606b41c23733dc53d459d | 7ada3d5c958cfdaeefa3d67d0815bb027006f65f | /Engine/Engine/inc/Core/RTTI/RTTIEditorHelpers.h | d8295984da5411baf677dfcf1199444da644641a | [] | no_license | JSpink95/cypher | 55778e2db3a842b502027a8d429393837eed0bfb | d6567e685a03a033b3ab447a84ea1b999a76b3ad | refs/heads/master | 2020-11-27T11:55:41.064332 | 2020-02-20T17:17:37 | 2020-02-20T17:17:37 | 229,427,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,553 | h | //////////////////////////////////////////////////////////////////////////
// File : RTTIEditorHelpers.h
// Created By : Jack Spink
// Created On : [07/02/2020]
//////////////////////////////////////////////////////////////////////////
#pragma once
//////////////////////////////////////////////////////////////////////////
#include "Core/Types.h"
//////////////////////////////////////////////////////////////////////////
#include "Core/Utility/Console.h"
//////////////////////////////////////////////////////////////////////////
#include "Core/RTTI/RTTIObject.h"
#include "Core/RTTI/TypeRegister.h"
//////////////////////////////////////////////////////////////////////////
#include "imgui.h"
//////////////////////////////////////////////////////////////////////////
#include <string>
#include <algorithm>
//////////////////////////////////////////////////////////////////////////
class Mesh;
class Material;
struct ComponentId;
//////////////////////////////////////////////////////////////////////////
namespace RTTI
{
namespace Helper
{
bool ImGuiStringGetter(void* data, s32 idx, const char** out);
}
//////////////////////////////////////////////////////////////////////////
template<typename TValue>
void DisplayEdit(const std::string& id, TValue& value);
//////////////////////////////////////////////////////////////////////////
template<template<typename> typename TList, typename TValue>
void DisplayListEdit(const std::string& id, TList<TValue>& list, s32& selected);
template<template<typename, typename> typename TMap, typename TKey, typename TValue>
void DisplayMapEdit(const std::string& id, TMap<TKey, TValue>& map, TKey& newKeyId);
//////////////////////////////////////////////////////////////////////////
// specialised displays
template<> void DisplayEdit<bool>(const std::string& id, bool& editable);
template<> void DisplayEdit<s32>(const std::string& id, s32& editable);
template<> void DisplayEdit<f32>(const std::string& id, f32& editable);
template<> void DisplayEdit<float2>(const std::string& id, float2& editable);
template<> void DisplayEdit<float3>(const std::string& id, float3& editable);
template<> void DisplayEdit<std::string>(const std::string& id, std::string& editable);
template<> void DisplayEdit<Ref<Material>>(const std::string& id, Ref<Material>& editable);
template<> void DisplayEdit<Ref<Mesh>>(const std::string& id, Ref<Mesh>& editable);
template<> void DisplayEdit<Ref<RTTIObject>>(const std::string& id, Ref<RTTIObject>& value);
template<> void DisplayEdit<RTTIObject>(const std::string& id, RTTIObject& value);
template<> void DisplayEdit<ComponentId>(const std::string& id, ComponentId& value);
//////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////
template<typename TValue>
void RTTI::DisplayEdit(const std::string& id, TValue& value)
{
LOG_WARNING("Not implemented for this type.\n");
}
//////////////////////////////////////////////////////////////////////////
template<template<typename> typename TList, typename TValue>
void RTTI::DisplayListEdit(const std::string& id, TList<TValue>& list, s32& selected)
{
if (ImGui::TreeNode(id.c_str()))
{
std::vector<TypeBase*> types;
TypeRegister::GetRegisteredTypesOfBase<TValue::element_type>(types);
std::vector<std::string> strings;
std::transform(types.begin(), types.end(), std::back_inserter(strings), [](TypeBase* type) -> std::string { return type->GetTypeName(); });
ImGui::Combo("##list_types", &selected, RTTI::Helper::ImGuiStringGetter, &strings, strings.size());
ImGui::SameLine();
const bool add = ImGui::Button("+##add_item");
std::vector<TList<TValue>::iterator> idsToRemove;
for (s32 index = 0; index < list.size(); ++index)
{
const std::string elementId = std::to_string(index);
const std::string removeId = "-##id_" + elementId;
Ref<RTTIObject> value = list.at(index);
//if (ImGui::TreeNode(elementId.c_str()))
//{
// ImGui::TreePop();
//}
const bool remove = ImGui::Button(removeId.c_str());
ImGui::SameLine();
RTTI::DisplayEdit<Ref<RTTIObject>>("", value);
if (remove)
{
idsToRemove.push_back(list.begin() + index);
}
}
if (add)
{
TypeBase* newType = types.at(selected);
Ref<TValue::element_type> element;
element.reset((TValue::element_type*)newType->New());
list.push_back(element);
}
if (idsToRemove.size() > 0)
{
//std::sort(idsToRemove.begin(), idsToRemove.end(), std::less<s32>());
for (s32 idx = idsToRemove.size() - 1; idx >= 0; --idx)
{
TList<TValue>::iterator it = idsToRemove.at((u32)idx);
list.erase(it);
}
}
ImGui::TreePop();
}
}
//////////////////////////////////////////////////////////////////////////
template<template<typename, typename> typename TMap, typename TKey, typename TValue>
void RTTI::DisplayMapEdit(const std::string& id, TMap<TKey, TValue>& map, TKey& newKeyId)
{
if (ImGui::TreeNode(id.c_str()))
{
std::vector<TypeBase*> types;
TypeRegister::GetRegisteredTypesOfBase<TValue::element_type>(types);
std::vector<std::string> strings;
std::transform(types.begin(), types.end(), std::back_inserter(strings), [](TypeBase* type) -> std::string { return type->GetTypeName(); });
ImGui::Combo("##list_types", &selected, RTTI::Helper::ImGuiStringGetter, &strings, strings.size());
RTTI::DisplayEdit<TKey>(id + ":key", newKeyId);
ImGui::SameLine();
const bool add = ImGui::Button("+##add_item");
for (auto&[key, value] : map)
{
const std::string keyId = RTTI::ToString<TKey>(key) + "##key";
const std::string valueId = keyId + "##value";
if (ImGui::TreeNode(keyId.c_str()))
{
RTTI::DisplayEdit<Ref<RTTIObject>>(valueId, std::dynamic_pointer_cast<RTTIObject>(value));
ImGui::TreePop();
}
}
if (add)
{
}
ImGui::TreePop();
}
}
////////////////////////////////////////////////////////////////////////// | [
"jackspink95@gmail.com"
] | jackspink95@gmail.com |
b20244f6f19977708e40b574eae6ef959c767d09 | 01aec7177f473d28f8bc262c1a72418a97d3dd10 | /Thread examples-22-10-20(ipc,mutex,atomic)/Thread examples-22-10-20(ipc,mutex,atomic))/threadmutex.cpp | e8ef03cde2e05db0ee353c79a72838a571b315b3 | [] | no_license | 99002651/Advanced-cpp | 97559344dad89bfd32d1a775c36b619e66a287cb | 915c3a4088336829de16a3f3f0123c6adf54b60d | refs/heads/master | 2023-01-02T22:00:17.043467 | 2020-10-27T12:47:35 | 2020-10-27T12:47:35 | 307,698,483 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 570 | cpp | #include<iostream>
#include<thread>
#include<mutex>
std:: mutex mtx;
using namespace std;
constexpr int maxv=10000;
int val=100;
void fsample()
{
std::cout<<"thread a"<<"\n";
for(int i=1;i<=maxv;i++)
{mtx.lock();
val++;
mtx.unlock();}
}
void gsample()
{
std::cout<<"thread b"<<"\n";
for(int i=1;i<=maxv;i++)
{
mtx.lock();
val--;
mtx.unlock();}
}
int main()
{ std::cout<<" welcome"<<"\n";
std::thread t1(fsample);
std::thread t2(gsample);
t1.join();
t2.join();
std::cout<<val;
return 0;
} | [
"sandyadevi.golakoti@ltts.com"
] | sandyadevi.golakoti@ltts.com |
506837914b9836f1c9311c7d92775a691203bd4d | 9a0b53947648ffd90ef2ae4a09b604bfa3aa5ec7 | /ARRAYmpi2/ARRAYmpi2/arraympi.cpp | b1c54d2390d26f00dfd959767412deed65216a4d | [] | no_license | gideioanamaria/APD | da8bdba4e9fd4a30d1128e156fa705cbe92e1f69 | 911b2f4412831a0bef1e744b49f333efe4df56bd | refs/heads/master | 2021-01-24T18:26:41.358816 | 2017-05-31T18:52:54 | 2017-05-31T18:52:54 | 84,441,874 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,472 | cpp | #include <iostream>
#include "mpi.h"
using namespace std;
#define SIZE 4
#define N 16
int main (int argc, char *argv[])
{
int numprocs, rank, sendcount, recvcount;
int buf[N]={3,5,3,4,7,3,8,6,8,7,6,8,5,3,1,2};
int recvbuf[20];
int poz[N],nrcautat=3;
int j=0;
int rezultat[20];
int low=0;
int high=0;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
if(N%numprocs!=0){
cout<<"Numarul dat nu se imparte exact la numarul de procese!!"<<endl;
MPI_Finalize();
exit(0);
}
sendcount = N/numprocs;
recvcount = N/numprocs;
MPI_Scatter(buf,sendcount,MPI_INT,recvbuf,recvcount,MPI_INT,0,MPI_COMM_WORLD); //trimit cate o parte egala din vector la fiecare proces arr->recvbuf
printf("Procesul %d : %d %d %d %d \n ",rank,recvbuf[0],recvbuf[1],recvbuf[2],recvbuf[3]);
for(int i=0; i<recvcount; i++) {
if(nrcautat==recvbuf[i]){
poz[j]=i+(N/numprocs)*rank;
cout<<"ID PROCES "<<rank<<" Pozitia: "<< i + (N/numprocs)*rank<<endl;
j++;
}
}
MPI_Gather(poz,SIZE,MPI_INT,rezultat,SIZE,MPI_INT,0,MPI_COMM_WORLD);//procesul o aduna toate datele te la toate procesele si le pune intr-un vector
//if(rank==0){
if(j!=NULL){
cout<<"Pozitile pe care am gasit numarul in procesul " << rank <<" sunt: ";
for(int i=0;i<j;i++){
cout<<poz[i] <<" ";
}
}
else
cout <<"Number not found!";
//}
MPI_Finalize();
return 0;
} | [
"gidei_oanamaria@yahoo.com"
] | gidei_oanamaria@yahoo.com |
e33ad849a0bab55533ce6a33d8bf6f245441fde9 | eedd904304046caceb3e982dec1d829c529da653 | /clanlib/ClanLib-2.2.8/Sources/Display/ImageProviders/png_provider.cpp | c31d92d3697751003893a7e9fa8f178761fb8016 | [] | no_license | PaulFSherwood/cplusplus | b550a9a573e9bca5b828b10849663e40fd614ff0 | 999c4d18d2dd4d0dd855e1547d2d2ad5eddc6938 | refs/heads/master | 2023-06-07T09:00:20.421362 | 2023-05-21T03:36:50 | 2023-05-21T03:36:50 | 12,607,904 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,430 | cpp | /*
** ClanLib SDK
** Copyright (c) 1997-2011 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** (if your name is missing here, please add it)
** Harry Storbacka
*/
#include "Display/precomp.h"
#include "API/Core/System/exception.h"
#include "API/Core/IOData/virtual_file_system.h"
#include "API/Core/IOData/virtual_directory.h"
#include "API/Core/Text/string_help.h"
#include "API/Core/IOData/path_help.h"
#include "API/Display/ImageProviders/png_provider.h"
#include "png_provider_impl.h"
#include <cerrno>
#include <cstdio>
class CustomIOFunctions
{
public:
static void read(png_structp png_ptr, png_bytep data, png_size_t length);
static void write(png_structp png_ptr, png_bytep data, png_size_t length);
static void flush(png_structp png_ptr);
};
void CustomIOFunctions::read( png_structp png_ptr, png_bytep data, png_size_t length )
{
CL_IODevice *iodev = (CL_IODevice*)png_ptr->io_ptr;
iodev->read(data, length);
}
void CustomIOFunctions::write( png_structp png_ptr, png_bytep data, png_size_t length )
{
CL_IODevice *iodev = (CL_IODevice*)png_ptr->io_ptr;
iodev->write(data, length);
}
void CustomIOFunctions::flush( png_structp png_ptr )
{
// CL_IODevice doesn't have a flush().
}
/////////////////////////////////////////////////////////////////////////////
// CL_PNGProvider construction:
CL_PixelBuffer CL_PNGProvider::load(
const CL_String &filename,
const CL_VirtualDirectory &directory)
{
CL_PNGProvider_Impl png(filename, directory);
CL_PixelBuffer pbuff(png.width, png.height, png.sized_format, png.palette, png.get_data());
pbuff.set_colorkey(png.uses_src_colorkey(), png.get_src_colorkey());
return pbuff;
}
CL_PixelBuffer CL_PNGProvider::load(
const CL_String &fullname)
{
CL_String path = CL_PathHelp::get_fullpath(fullname, CL_PathHelp::path_type_file);
CL_String filename = CL_PathHelp::get_filename(fullname, CL_PathHelp::path_type_file);
CL_VirtualFileSystem vfs(path);
CL_VirtualDirectory dir = vfs.get_root_directory();
return CL_PNGProvider::load(filename, dir);
}
CL_PixelBuffer CL_PNGProvider::load(CL_IODevice &iodev)
{
CL_PNGProvider_Impl png(iodev);
CL_PixelBuffer pbuff(png.width, png.height, png.sized_format, png.palette, png.get_data());
pbuff.set_colorkey(png.uses_src_colorkey(), png.get_src_colorkey());
return pbuff;
}
void CL_PNGProvider::save(
CL_PixelBuffer buffer,
const CL_String &filename,
CL_VirtualDirectory &directory)
{
CL_IODevice file = directory.open_file(filename, CL_File::create_always);
save(buffer, file);
}
void CL_PNGProvider::save(
CL_PixelBuffer buffer,
const CL_String &fullname)
{
CL_String path = CL_PathHelp::get_fullpath(fullname, CL_PathHelp::path_type_file);
CL_String filename = CL_PathHelp::get_filename(fullname, CL_PathHelp::path_type_file);
CL_VirtualFileSystem vfs(path);
CL_VirtualDirectory dir = vfs.get_root_directory();
CL_PNGProvider::save(buffer, filename, dir);
}
void CL_PNGProvider::save(CL_PixelBuffer buffer, CL_IODevice &iodev)
{
if (buffer.get_format() != cl_abgr8)
{
CL_PixelBuffer newbuf(
buffer.get_width(),
buffer.get_height(),
cl_abgr8);
buffer.convert(newbuf);
buffer = newbuf;
}
png_structp png_ptr;
png_infop info_ptr;
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
info_ptr = png_create_info_struct(png_ptr);
png_set_read_fn(png_ptr, &iodev, &CustomIOFunctions::read);
png_set_write_fn(png_ptr, &iodev, &CustomIOFunctions::write, CustomIOFunctions::flush);
#ifndef PNG_COLOR_TYPE_RGBA
#define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
#endif
png_set_IHDR(
png_ptr, info_ptr,
buffer.get_width(), buffer.get_height(), 8 /* bitdepth */,
PNG_COLOR_TYPE_RGBA,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE,
PNG_FILTER_TYPE_BASE);
png_write_info(png_ptr, info_ptr);
png_uint_32 height = buffer.get_height();
png_uint_32 row_bytes = buffer.get_width()*4;
png_byte* image = new png_byte[height * row_bytes];
png_bytep* row_pointers = new png_bytep[height];
// fill the image with data
for (int i = 0; i < buffer.get_width()*buffer.get_height()*4; ++i)
image[i] = static_cast<unsigned char*>(buffer.get_data())[i];
// generate row pointers
for (unsigned int k = 0; k < height; k++)
row_pointers[k] = image + (k * row_bytes);
png_write_image(png_ptr, row_pointers);
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct( &png_ptr, &info_ptr );
delete[] image;
delete[] row_pointers;
}
| [
"paulfsherwood@gmail.com"
] | paulfsherwood@gmail.com |
8381175eba1d6009310cc6e02744e8870590bfcc | e6ec3326bfba74656e5beb7f1599a87e210cc86b | /threads/threadsgroup.cpp | 5a2550d239e83aaf5adcaf837cc3e1176b69505b | [] | no_license | fengjixuchui/syslib | 1d357983120386ab11d1a1cb64fd8ec30af24a56 | 8e3121e1d0cbd0021a155801badb53bd08fea6d9 | refs/heads/master | 2021-05-27T20:45:02.751275 | 2014-10-12T07:06:37 | 2014-10-12T07:06:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,068 | cpp | #include "sys_includes.h"
#include "syslib\criticalsections.h"
#include "syslib\mem.h"
#include "syslib\system.h"
#include "syslib\threadsgroup.h"
#include "threadsgroup.h"
SYSLIBFUNC(HANDLE) ThreadsGroup_Create()
{
THREADS_GROUP *lpGroup=(THREADS_GROUP*)MemAlloc(sizeof(THREADS_GROUP));
if (lpGroup)
InitializeSafeCriticalSection(&lpGroup->csGroup);
return (HANDLE)lpGroup;
}
SYSLIBFUNC(BOOL) ThreadsGroup_CreateThreadEx(HANDLE hGroup,SIZE_T dwStackSize,LPTHREAD_START_ROUTINE lpStartAddress,LPVOID lpParameter,LPDWORD lpThreadId,LPHANDLE lpThreadHandle,DWORD dwFlags)
{
BOOL bRet=false;
if (hGroup)
{
ThreadsGroup_CloseTerminatedHandles(hGroup);
THREADS_GROUP *lpGroup=(THREADS_GROUP*)hGroup;
EnterSafeCriticalSection(&lpGroup->csGroup);
{
if (lpGroup->dwCount < ARRAYSIZE(lpGroup->hThreads))
{
if (lpStartAddress)
{
HANDLE hThread;
if (dwFlags & THREADGROUP_SAFETHREAD)
hThread=SysCreateThreadSafe(NULL,dwStackSize,lpStartAddress,lpParameter,0,lpThreadId);
else
hThread=CreateThread(NULL,dwStackSize,lpStartAddress,lpParameter,0,lpThreadId);
if (hThread)
{
lpGroup->hThreads[lpGroup->dwCount++]=hThread;
if (lpThreadHandle)
DuplicateHandle(GetCurrentProcess(),hThread,GetCurrentProcess(),lpThreadHandle,0,FALSE,DUPLICATE_SAME_ACCESS);
bRet=true;
}
}
}
}
LeaveSafeCriticalSection(&lpGroup->csGroup);
}
return bRet;
}
SYSLIBFUNC(BOOL) ThreadsGroup_CreateThread(HANDLE hGroup,SIZE_T dwStackSize,LPTHREAD_START_ROUTINE lpStartAddress,LPVOID lpParameter,LPDWORD lpThreadId,LPHANDLE lpThreadHandle)
{
return ThreadsGroup_CreateThreadEx(hGroup,dwStackSize,lpStartAddress,lpParameter,lpThreadId,lpThreadHandle,THREADGROUP_SAFETHREAD);
}
SYSLIBFUNC(BOOL) ThreadsGroup_WaitForAllExit(HANDLE hGroup,DWORD dwTimeout)
{
BOOL bRet=false;
if (hGroup)
{
THREADS_GROUP *lpGroup=(THREADS_GROUP*)hGroup;
EnterSafeCriticalSection(&lpGroup->csGroup);
bRet=((lpGroup->dwCount == 0) || (SysWaitForMultipleObjects(lpGroup->dwCount,lpGroup->hThreads,TRUE,dwTimeout) == WAIT_OBJECT_0));
LeaveSafeCriticalSection(&lpGroup->csGroup);
}
return bRet;
}
SYSLIBFUNC(void) ThreadsGroup_CloseGroup(HANDLE hGroup)
{
if (hGroup)
{
THREADS_GROUP *lpGroup=(THREADS_GROUP*)hGroup;
EnterSafeCriticalSection(&lpGroup->csGroup);
{
for (DWORD i=0; i < lpGroup->dwCount; i++)
SysCloseHandle(lpGroup->hThreads[i]);
}
LeaveSafeCriticalSection(&lpGroup->csGroup);
DeleteSafeCriticalSection(&lpGroup->csGroup);
MemFree(hGroup);
}
return;
}
SYSLIBFUNC(void) ThreadsGroup_CloseGroupAndTerminateThreads(HANDLE hGroup)
{
if (hGroup)
{
THREADS_GROUP *lpGroup=(THREADS_GROUP*)hGroup;
EnterSafeCriticalSection(&lpGroup->csGroup);
{
for (DWORD i=0; i < lpGroup->dwCount; i++)
{
TerminateThread(lpGroup->hThreads[i],0xDEAD);
SysCloseHandle(lpGroup->hThreads[i]);
}
}
LeaveSafeCriticalSection(&lpGroup->csGroup);
DeleteSafeCriticalSection(&lpGroup->csGroup);
MemFree(hGroup);
}
return;
}
SYSLIBFUNC(void) ThreadsGroup_CloseTerminatedHandles(HANDLE hGroup)
{
if (hGroup)
{
THREADS_GROUP *lpGroup=(THREADS_GROUP*)hGroup;
EnterSafeCriticalSection(&lpGroup->csGroup);
{
DWORD j=0;
for(DWORD i=0; i < lpGroup->dwCount; i++)
{
if (lpGroup->hThreads[i] != NULL)
{
if (WaitForSingleObject(lpGroup->hThreads[i],0) == WAIT_OBJECT_0)
{
SysCloseHandle(lpGroup->hThreads[i]);
lpGroup->hThreads[i]=NULL;
}
else
{
lpGroup->hThreads[j]=lpGroup->hThreads[i];
j++;
}
}
}
lpGroup->dwCount=j;
}
LeaveSafeCriticalSection(&lpGroup->csGroup);
}
return;
}
SYSLIBFUNC(DWORD) ThreadsGroup_NumberOfActiveThreads(HANDLE hGroup)
{
DWORD dwCount=0;
if (hGroup)
{
THREADS_GROUP *lpGroup=(THREADS_GROUP*)hGroup;
EnterSafeCriticalSection(&lpGroup->csGroup);
{
for (DWORD i=0; i < lpGroup->dwCount; i++)
{
if ((lpGroup->hThreads[i] != NULL) && (WaitForSingleObject(lpGroup->hThreads[i],0) == WAIT_TIMEOUT))
dwCount++;
}
}
LeaveSafeCriticalSection(&lpGroup->csGroup);
}
return dwCount;
}
| [
"seledka"
] | seledka |
7f61d6df7cbf64257c7bccd4635eb159e65cbaad | 0e6ab2afe5c570f7fa5d8176dffbd0e1f7f6a9fb | /Exemplos de Provas/main_prova1_1_Q3.cpp | 2ee442a3b1bb0514471f00a48db424b8162c4bf0 | [] | no_license | fsofelipe/CompGraficaUFPel | 84c0dbf497828f5cd28edec83171ef7dad278900 | 0eb1a833c6d61eca728b99aa45c5638d2cbfa717 | refs/heads/master | 2020-03-07T00:07:23.437594 | 2018-04-16T12:41:59 | 2018-04-16T12:41:59 | 127,150,328 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,367 | cpp | // Include standard headers
#include <stdio.h>
#include <stdlib.h>
#include <vector>
// Include GLEW
#include <GL/glew.h>
// Include GLFW
#include <glfw3.h>
GLFWwindow* g_pWindow;
unsigned int g_nWidth = 1024, g_nHeight = 768;
// Include AntTweakBar
#include <AntTweakBar.h>
TwBar *g_pToolBar;
// Include GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace glm;
using namespace std;
#include <shader.hpp>
#include <texture.hpp>
#include <controls.hpp>
#include <objloader.hpp>
#include <vboindexer.hpp>
#include <glerror.hpp>
#include <math.h>
#define PI 3.14159265
void WindowSizeCallBack(GLFWwindow *pWindow, int nWidth, int nHeight) {
g_nWidth = nWidth;
g_nHeight = nHeight;
glViewport(0, 0, g_nWidth, g_nHeight);
TwWindowSize(g_nWidth, g_nHeight);
}
class model {
public:
std::vector<unsigned short> indices;
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_uvs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
glm::mat4 modelMatrix;
model(std::vector<glm::vec3> vertices, std::vector<glm::vec2> uvs, std::vector<glm::vec3> normals) {
indexVBO(vertices, uvs, normals, indices, indexed_vertices, indexed_uvs, indexed_normals);
// Load it into a VBO
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(glm::vec3), &indexed_vertices[0], GL_STATIC_DRAW);
glGenBuffers(1, &uvbuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glBufferData(GL_ARRAY_BUFFER, indexed_uvs.size() * sizeof(glm::vec2), &indexed_uvs[0], GL_STATIC_DRAW);
glGenBuffers(1, &normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(glm::vec3), &indexed_normals[0], GL_STATIC_DRAW);
// Generate a buffer for the indices as well
glGenBuffers(1, &elementbuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW);
modelMatrix = glm::mat4(1.0);
}
};
int main(void)
{
int nUseMouse = 0;
// Initialise GLFW
if (!glfwInit())
{
fprintf(stderr, "Failed to initialize GLFW\n");
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Open a window and create its OpenGL context
g_pWindow = glfwCreateWindow(g_nWidth, g_nHeight, "CG UFPel", NULL, NULL);
if (g_pWindow == NULL){
fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(g_pWindow);
// Initialize GLEW
glewExperimental = true; // Needed for core profile
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
return -1;
}
check_gl_error();//OpenGL error from GLEW
// Initialize the GUI
TwInit(TW_OPENGL_CORE, NULL);
TwWindowSize(g_nWidth, g_nHeight);
// Set GLFW event callbacks. I removed glfwSetWindowSizeCallback for conciseness
glfwSetMouseButtonCallback(g_pWindow, (GLFWmousebuttonfun)TwEventMouseButtonGLFW); // - Directly redirect GLFW mouse button events to AntTweakBar
glfwSetCursorPosCallback(g_pWindow, (GLFWcursorposfun)TwEventMousePosGLFW); // - Directly redirect GLFW mouse position events to AntTweakBar
glfwSetScrollCallback(g_pWindow, (GLFWscrollfun)TwEventMouseWheelGLFW); // - Directly redirect GLFW mouse wheel events to AntTweakBar
glfwSetKeyCallback(g_pWindow, (GLFWkeyfun)TwEventKeyGLFW); // - Directly redirect GLFW key events to AntTweakBar
glfwSetCharCallback(g_pWindow, (GLFWcharfun)TwEventCharGLFW); // - Directly redirect GLFW char events to AntTweakBar
glfwSetWindowSizeCallback(g_pWindow, WindowSizeCallBack);
//create the toolbar
g_pToolBar = TwNewBar("CG UFPel ToolBar");
// Add 'speed' to 'bar': it is a modifable (RW) variable of type TW_TYPE_DOUBLE. Its key shortcuts are [s] and [S].
double speed = 0.0;
TwAddVarRW(g_pToolBar, "speed", TW_TYPE_DOUBLE, &speed, " label='Rot speed' min=0 max=2 step=0.01 keyIncr=s keyDecr=S help='Rotation speed (turns/second)' ");
// Add 'bgColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color)
vec3 oColor(0.0f);
TwAddVarRW(g_pToolBar, "bgColor", TW_TYPE_COLOR3F, &oColor[0], " label='Background color' ");
// Ensure we can capture the escape key being pressed below
glfwSetInputMode(g_pWindow, GLFW_STICKY_KEYS, GL_TRUE);
glfwSetCursorPos(g_pWindow, g_nWidth / 2, g_nHeight / 2);
// Dark blue background
glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
// Cull triangles which normal is not towards the camera
glEnable(GL_CULL_FACE);
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
// Create and compile our GLSL program from the shaders
GLuint programID = LoadShaders("shaders/StandardShading.vertexshader", "shaders/StandardShading.fragmentshader");
// Get a handle for our "MVP" uniform
GLuint MatrixID = glGetUniformLocation(programID, "MVP");
GLuint ViewMatrixID = glGetUniformLocation(programID, "V");
GLuint ModelMatrixID = glGetUniformLocation(programID, "M");
// Load the texture
GLuint Texture = loadDDS("mesh/uvmap.DDS");
// Get a handle for our "myTextureSampler" uniform
GLuint TextureID = glGetUniformLocation(programID, "myTextureSampler");
// Read our .obj file
std::vector<glm::vec3> vertices;
std::vector<glm::vec2> uvs;
std::vector<glm::vec3> normals;
bool res = loadOBJ("mesh/suzanne.obj", vertices, uvs, normals);
std::vector<model> Modelos;
double tempo = 5.0, periodo = 15.0, dist = 3;
int qnt = 10 + 1;
for (int i = 0; i < qnt; i++)
Modelos.push_back(model(vertices, uvs, normals));
cout << Modelos.size() << endl;
//cout << sin(390.0 * PI / 180) << endl;
// Get a handle for our "LightPosition" uniform
glUseProgram(programID);
GLuint LightID = glGetUniformLocation(programID, "LightPosition_worldspace");
// For speed computation
double lastTime = glfwGetTime();
int nbFrames = 0;
double t = glfwGetTime();
double t_copy = t;
int j = 1;
do{
check_gl_error();
//use the control key to free the mouse
if (glfwGetKey(g_pWindow, GLFW_KEY_LEFT_CONTROL) != GLFW_PRESS)
nUseMouse = 0;
else
nUseMouse = 1;
// Measure speed
nbFrames++;
double currentTime = glfwGetTime();
if (currentTime - lastTime >= 1.0){ // If last prinf() was more than 1sec ago
// printf and reset
//printf("%f ms/frame\n", 1000.0 / double(nbFrames));
nbFrames = 0;
lastTime += 1.0;
}
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Use our shader
glUseProgram(programID);
if ((t + periodo) >= currentTime)
t = currentTime;
if (((t_copy + tempo) <= currentTime) && j < qnt) {
cout << currentTime << endl;
t_copy = currentTime;
Modelos[j].modelMatrix = Modelos[0].modelMatrix;
j++;
}
for (int i = 0; i < Modelos.size(); i++) {
if (i == 0) {
double angle = ((t * 360)/periodo);
double d = ((t * dist)/periodo);
Modelos[i].modelMatrix = glm::translate(glm::mat4(1.0), glm::vec3(d, sin(angle * PI / 180), 0));
}
// Compute the MVP matrix from keyboard and mouse input
computeMatricesFromInputs(nUseMouse, g_nWidth, g_nHeight);
glm::mat4 ProjectionMatrix = getProjectionMatrix();
glm::mat4 ViewMatrix = getViewMatrix();
glm::mat4 ModelMatrix = Modelos[i].modelMatrix;
glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;
// Send our transformation to the currently bound shader,
// in the "MVP" uniform
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]);
glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]);
glm::vec3 lightPos = glm::vec3(4, 4, 4);
glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z);
// Bind our texture in Texture Unit 0
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, Texture);
// Set our "myTextureSampler" sampler to user Texture Unit 0
glUniform1i(TextureID, 0);
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, Modelos[i].vertexbuffer);
glVertexAttribPointer(
0, // attribute
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 2nd attribute buffer : UVs
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, Modelos[i].uvbuffer);
glVertexAttribPointer(
1, // attribute
2, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 3rd attribute buffer : normals
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, Modelos[i].normalbuffer);
glVertexAttribPointer(
2, // attribute
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Index buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Modelos[i].elementbuffer);
// Draw the triangles !
glDrawElements(
GL_TRIANGLES, // mode
Modelos[i].indices.size(), // count
GL_UNSIGNED_SHORT, // type
(void*)0 // element array buffer offset
);
}
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
// Draw tweak bars
TwDraw();
// Swap buffers
glfwSwapBuffers(g_pWindow);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while (glfwGetKey(g_pWindow, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
glfwWindowShouldClose(g_pWindow) == 0);
for (int i = 0; i < Modelos.size(); i++) {
// Cleanup VBO and shader
glDeleteBuffers(1, &Modelos[i].vertexbuffer);
glDeleteBuffers(1, &Modelos[i].uvbuffer);
glDeleteBuffers(1, &Modelos[i].normalbuffer);
glDeleteBuffers(1, &Modelos[i].elementbuffer);
}
glDeleteProgram(programID);
glDeleteTextures(1, &Texture);
glDeleteVertexArrays(1, &VertexArrayID);
// Terminate AntTweakBar and GLFW
TwTerminate();
glfwTerminate();
return 0;
}
| [
"felipe.oliveira.tk@gmail.com"
] | felipe.oliveira.tk@gmail.com |
b789b294589486cf39b770752e8e8b474c7952b2 | 32f7ed22967a7e0f745f4938f9dd013a51af57ee | /clientsdk/GP_Client/Subject.h | 86d5755f19e4cebe9322e09eda768cee86182a82 | [] | no_license | stonejiang208/GP_Client | 1eb85ee51b52b49351e98ac843870d2ec231c8bb | 9d790adf20bbfb6b4a101734ad71825b70717c1c | refs/heads/master | 2021-01-10T03:05:09.273439 | 2015-05-27T09:11:52 | 2015-05-27T09:11:52 | 36,205,125 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 761 | h | // -*- C++ -*-
//===========================================================================
/* Time-stamp: <2015-05-26 00:10:54 by android> */
/* @file Subject.h
* $Id: Subject.h 2015-02-27 14:02:41 jiangtao
*
* @author:Stone Jiang<jiangtao@tao-studio.net>
*/
//===========================================================================
#ifndef SUBJECT_H
#define SUBJECT_H
#include <stddef.h>
#include <list>
#include "Namespace.h"
NS_GP_CLIENT_BEGIN
class Observer;
class Subject
{
public:
Subject ();
virtual ~Subject ();
public:
virtual int update_data (const char* data, size_t n) = 0;
void notify ();
void attach (Observer*);
void detach (Observer*);
private:
std::list <Observer*> observers_;
};
NS_GP_CLIENT_END
#endif /* SUBJECT_H */
| [
"jiangtao@tao-studio.net"
] | jiangtao@tao-studio.net |
29b37913bfe41f6acec66db5d983934a1735860e | e33b790ec7b22a4c2cfc470d46794e954a2e4a7d | /lib/PortAliases.cpp | f73a00c2ab583f5c003fbb4a108915156606bf18 | [
"LicenseRef-scancode-other-permissive"
] | permissive | caizikun/tool_axe | 0ae4abf3e7d5feb6280f37bbafe0f5b4bf1d8d9a | c1d7c0ad8095abc6733eb8df3bc0f4f72b3852d6 | refs/heads/master | 2020-03-20T10:40:53.686373 | 2018-05-30T13:46:20 | 2018-05-30T13:46:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 532 | cpp | // Copyright (c) 2012, Richard Osborne, All rights reserved
// This software is freely distributable under a derivative of the
// University of Illinois/NCSA Open Source License posted in
// LICENSE.txt and at <http://github.xcore.com/>
#include "PortAliases.h"
using namespace axe;
bool PortAliases::
lookup(const std::string &name, std::string &core, std::string &port) const
{
auto it = aliases.find(name);
if (it == aliases.end())
return false;
core = it->second.first;
port = it->second.second;
return true;
}
| [
"richard@xmos.com"
] | richard@xmos.com |
c03830f090c3f8d391a0b39556d3667a8507b300 | d6ad657a22a10a666898bc5d091e0f7df7766494 | /motor_frame/Arduino_Practice/LiquidHandlingRobot.cpp | 26f1860762b7f9c7d183df3f1c1df35f46f17e1b | [] | no_license | gsuematsu/Liquid-Handling-Robot | 493d53cd73717548109c9ec4a9bbfcef528d105c | ff41886ac4a9778a7568fb952d0758e420494bbb | refs/heads/master | 2021-07-06T19:39:25.007309 | 2020-09-21T00:27:25 | 2020-09-21T00:27:25 | 188,185,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,729 | cpp | #include <Arduino.h>
#include "LiquidHandlingRobot.h"
#define timeDelay 1700
StepperMotor::StepperMotor(int pinStep, int pinDir, int pinMinSwitch, int pinMaxSwitch) {
pinMode(pinStep, OUTPUT);
pinMode(pinDir, OUTPUT);
pinMode(pinMinSwitch, INPUT_PULLUP);
pinMode(pinMaxSwitch, INPUT_PULLUP);
m_pinStep = pinStep;
m_pinDir = pinDir;
m_pinMinSwitch = pinMinSwitch;
m_pinMaxSwitch = pinMaxSwitch;
m_pos = 1;
dest = 0;
millisPerStep = 1;
}
float StepperMotor::pos() {
return m_pos;
}
int StepperMotor::pinStep() {
return m_pinStep;
}
int StepperMotor::pinDir() {
return m_pinDir;
}
int StepperMotor::pinMinSwitch() {
return m_pinMinSwitch;
}
int StepperMotor::pinMaxSwitch() {
return m_pinMaxSwitch;
}
bool StepperMotor::isAtDest() {
float error = abs(dest - m_pos);
return error < millisPerStep;
}
bool StepperMotor::isAtHome(){
return digitalRead(m_pinMinSwitch);
}
void StepperMotor::updatePos() {
m_pos = dest;
}
void StepperMotor::justStepped() {
int sign = 1;
if (!digitalRead(m_pinDir)) {
sign = -1;
}
m_pos += (sign * millisPerStep);
}
MotorFrame::MotorFrame(StepperMotor xMotor, StepperMotor yMotor, StepperMotor zMotor): m_xMotor(xMotor), m_yMotor(yMotor), m_zMotor(zMotor) {
m_xMotor = xMotor;
m_yMotor = yMotor;
m_zMotor = zMotor;
m_homed = false;
m_xMaxSteps, m_yMaxSteps, m_zMaxSteps = 0;
m_xMaxMM = 150;
m_yMaxMM = 150;
m_zMaxMM = 50;
}
void MotorFrame::allPinsDir(bool value) {
digitalWrite(m_xMotor.pinDir(), value);
digitalWrite(m_yMotor.pinDir(), value);
digitalWrite(m_zMotor.pinDir(), value);
}
void MotorFrame::allPinsStep(bool value) {
digitalWrite(m_xMotor.pinStep(), value);
digitalWrite(m_yMotor.pinStep(), value);
digitalWrite(m_zMotor.pinStep(), value);
}
void MotorFrame::goToHome() {
m_xMotor.dest = 0;
m_yMotor.dest = 0;
m_zMotor.dest = 0;
allPinsDir(LOW);
while (!m_xMotor.isAtHome() || !m_yMotor.isAtHome() || !m_zMotor.isAtHome()) {
digitalWrite(m_xMotor.pinStep(), !m_xMotor.isAtHome());
digitalWrite(m_yMotor.pinStep(), !m_yMotor.isAtHome());
digitalWrite(m_zMotor.pinStep(), !m_zMotor.isAtHome());
delayMicroseconds(timeDelay);
allPinsStep(LOW);
if (digitalRead(m_xMotor.pinMinSwitch())) {
m_pos[0] = 0;
m_xMotor.updatePos();
}
if (digitalRead(m_yMotor.pinMinSwitch())) {
m_pos[1] = 0;
m_yMotor.updatePos();
}
if (digitalRead(m_zMotor.pinMinSwitch())) {
m_pos[2] = 0;
m_zMotor.updatePos();
}
}
m_homed = true;
allPinsDir(HIGH);
}
void MotorFrame::calibrate(float xScale, float yScale, float zScale) {
m_xMotor.millisPerStep = xScale;
m_yMotor.millisPerStep = yScale;
m_zMotor.millisPerStep = zScale;
}
boolean MotorFrame::calibrate() {
if (!m_homed) {
goToHome();
m_xMaxSteps = 0;
m_yMaxSteps = 0;
m_zMaxSteps = 0;
}
setDestAs(m_xMaxMM, m_yMaxMM, m_zMaxMM); // HACK
if (digitalRead(m_xMotor.pinMaxSwitch()) != 1) {
digitalWrite(m_xMotor.pinStep(), HIGH);
delayMicroseconds(timeDelay);
digitalWrite(m_xMotor.pinStep(), LOW);
m_xMaxSteps++;
}
if (digitalRead(m_yMotor.pinMaxSwitch()) != 0) {
digitalWrite(m_yMotor.pinStep(), HIGH);
delayMicroseconds(timeDelay);
digitalWrite(m_yMotor.pinStep(), LOW);
m_yMaxSteps++;
}
// if (m_zMotor.pinMaxSwitch() != 1) {
// digitalWrite(m_zMotor.pinStep(), HIGH);
// delayMicroseconds(timeDelay);
// digitalWrite(m_zMotor.pinStep(), LOW);
// zMaxSteps++;
// }
// TODO ADD Z CALIBRATION
if (digitalRead(m_xMotor.pinMaxSwitch()) == 1 && digitalRead(m_yMotor.pinMaxSwitch()) == 0)
{
// m_xmmps = m_xMaxMM / m_xMaxSteps;
// m_ymmps = m_yMaxMM / m_yMaxSteps;
m_xMotor.millisPerStep = m_xMaxMM / m_xMaxSteps;
m_yMotor.millisPerStep = m_yMaxMM / m_yMaxSteps;
//m_zMotor.millisPerStep = zScale;
return true;
}
return false;
}
void MotorFrame::showMaxSteps(){
Serial.print(m_xMaxSteps); Serial.print(' ');
Serial.print(m_yMaxSteps); Serial.print(' ');
Serial.println(m_zMaxSteps);
Serial.print(m_xMotor.millisPerStep); Serial.print(' ');
Serial.print(m_yMotor.millisPerStep); Serial.print(' ');
Serial.println(m_zMotor.millisPerStep);
}
void MotorFrame::goTo(float xDest, float yDest, float zDest) {
m_xMotor.dest = xDest;
m_yMotor.dest = yDest;
m_zMotor.dest = zDest;
digitalWrite(m_xMotor.pinDir(), (m_xMotor.dest - m_xMotor.pos()) > 0);
digitalWrite(m_yMotor.pinDir(), (m_yMotor.dest - m_yMotor.pos()) > 0);
digitalWrite(m_zMotor.pinDir(), (m_zMotor.dest - m_zMotor.pos()) > 0);
while (!m_xMotor.isAtDest() || !m_yMotor.isAtDest() || !m_zMotor.isAtDest()) {
digitalWrite(m_xMotor.pinStep(), !m_xMotor.isAtDest());
digitalWrite(m_yMotor.pinStep(), !m_yMotor.isAtDest());
digitalWrite(m_zMotor.pinStep(), !m_zMotor.isAtDest());
delayMicroseconds(timeDelay);
allPinsStep(LOW);
if (!m_xMotor.isAtDest()) {
m_xMotor.justStepped();
}
if (!m_yMotor.isAtDest()) {
m_yMotor.justStepped();
}
if (!m_zMotor.isAtDest()) {
m_zMotor.justStepped();
}
}
}
float MotorFrame::xPos() {
return m_xMotor.pos();
}
float MotorFrame::yPos() {
return m_yMotor.pos();
}
float MotorFrame::zPos() {
return m_zMotor.pos();
}
void MotorFrame::stepAll() {
digitalWrite(m_xMotor.pinStep(), !m_xMotor.isAtDest());
digitalWrite(m_yMotor.pinStep(), !m_yMotor.isAtDest());
digitalWrite(m_zMotor.pinStep(), !m_zMotor.isAtDest());
delayMicroseconds(timeDelay);
allPinsStep(LOW);
if (!m_xMotor.isAtDest()) {
m_xMotor.justStepped();
}
if (!m_yMotor.isAtDest()) {
m_yMotor.justStepped();
}
if (!m_zMotor.isAtDest()) {
m_zMotor.justStepped();
}
}
void MotorFrame::setDestAs(float xDest, float yDest, float zDest) {
m_xMotor.dest = xDest;
m_yMotor.dest = yDest;
m_zMotor.dest = zDest;
digitalWrite(m_xMotor.pinDir(), (m_xMotor.dest - m_xMotor.pos()) > 0);
digitalWrite(m_yMotor.pinDir(), (m_yMotor.dest - m_yMotor.pos()) > 0);
digitalWrite(m_zMotor.pinDir(), (m_zMotor.dest - m_zMotor.pos()) > 0);
}
bool MotorFrame::isAtDest() {
return (m_xMotor.isAtDest() && m_yMotor.isAtDest() && m_zMotor.isAtDest());
}
void MotorFrame::showPos(){
Serial.print(m_xMotor.pos()); Serial.print(' ');
Serial.print(m_yMotor.pos()); Serial.print(' ');
Serial.println(m_zMotor.pos());
}
WellPlate96::WellPlate96(float xPos, float yPos){
m_xPos = xPos;
m_yPos = yPos;
for(int i = 0; i < sizeof(m_volume)/sizeof(float); i++){
m_volume[i] = 0;
}
}
float WellPlate96::getVolume(int col){
return m_volume[col-1];
}
void serialDilution(int dilutionFactor, float volume, WellPlate wellPlate){
l
}
| [
"noreply@github.com"
] | gsuematsu.noreply@github.com |
7d981f136520ddf03d0f96f979989fad3ea2f7cf | 29f7ed9fa3dd0c8a71e01f71897ba06ee127049f | /Library/Foundation/Foundation/SharedLibrary/SharedLibrary.cpp | a6c7e525a8ebbebb239c67df6cfc5c9578aada61 | [] | no_license | solidusex/ragebtclient | 12324bf5832f88582f382dd1748390d3ff380b05 | dff62872e7d7036110f31595e31d674379019524 | refs/heads/master | 2021-01-02T13:00:31.849237 | 2012-02-15T19:29:27 | 2012-02-15T19:29:27 | 41,566,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,343 | cpp | /*
* The Foundation Library
* Copyright (c) 2007 by Solidus
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. It is provided "as is" without express
* or implied warranty.
*/
#include "SharedLibrary.h"
#if defined(OS_FAMILY_WINDOWS)
#include "Win/SharedLibraryImpl.h"
#else
#error NOT_SUPPORT_PLATFORM
#endif
namespace SharedLibrarySpace {
SharedLibrary::SharedLibrary(const std::string &path)
{
std::wstring tmp = FormatSpace::AnsiConverter::ToUnicode(path);
m_pimpl = new SharedLibraryImpl(tmp);
}
SharedLibrary::SharedLibrary(const std::wstring &path)
{
m_pimpl = new SharedLibraryImpl(path);
}
SharedLibrary::~SharedLibrary()
{
delete m_pimpl;
}
void* SharedLibrary::GetSymbolAddr(const std::string &name)
{
return m_pimpl->GetSymbolAddr(name);
}
void SharedLibrary::GetPath(std::wstring &path)
{
path = m_pimpl->GetPath();
}
void SharedLibrary::GetPath(std::string &path)
{
std::wstring tmp;
GetPath(tmp);
path = FormatSpace::UnicodeConverter::ToAnsi(tmp);
}
} | [
"SolidusSnakeEx@gmail.com"
] | SolidusSnakeEx@gmail.com |
f777a8a677b5164ea1ffbcacb4a13ca11cbfad7f | c45ed46065d8b78dac0dd7df1c95b944f34d1033 | /TC-SRM-562-div1-250/qiaoranliqu.cpp | 8190d52138959edb178299f492e0d25edf459db1 | [] | no_license | yzq986/cntt2016-hw1 | ed65a6b7ad3dfe86a4ff01df05b8fc4b7329685e | 12e799467888a0b3c99ae117cce84e8842d92337 | refs/heads/master | 2021-01-17T11:27:32.270012 | 2017-01-26T03:23:22 | 2017-01-26T03:23:22 | 84,036,200 | 0 | 0 | null | 2017-03-06T06:04:12 | 2017-03-06T06:04:12 | null | GB18030 | C++ | false | false | 1,424 | cpp | #include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#include<cmath>
#include<string>
#define ls (t<<1)
#define rs ((t<<1)+1)
#define mid ((l+r)>>1)
#define fi first
#define se second
#define mk make_pair
#define pb push_back
#define N 2005
#define M 200005
#define seed 23333
#define Mo 998244353
using namespace std;
int i,j,m,n,p,k;
int A[N][N],r[N],b[N],g[N];
void change(char x,int &y)
{
if (y==1) r[i]--;
if (y==2) b[i]--;
if (y==3) g[i]--;
if (x=='R') y=1,r[i]++;
if (x=='B') y=2,b[i]++;
if (x=='G') y=3,g[i]++;
}
class PastingPaintingDivOne{
public:
vector<long long> countColors(vector <string> clipboard, int T)
{
int n=clipboard.size(),m=clipboard[0].length();
for (i=1;i<=1000;++i) //暴力做前面几次操作
{
r[i]=r[i-1]; g[i]=g[i-1]; b[i]=b[i-1];
for (j=0;j<n;++j)
for (k=0;k<m;++k)
if (clipboard[j][k]!='.')
change(clipboard[j][k],A[j+i][k+i]);
}
vector<long long>ans;
if (T<=1000)
{
ans.pb(r[T]); ans.pb(g[T]); ans.pb(b[T]);
return ans;
} //对于后面的操作,增量都是不变的
ans.pb(r[1000]+1ll*(r[1000]-r[999])*(T-1000));
ans.pb(g[1000]+1ll*(g[1000]-g[999])*(T-1000));
ans.pb(b[1000]+1ll*(b[1000]-b[999])*(T-1000));
return ans;
}
};
| [
"857075272@qq.com"
] | 857075272@qq.com |
a8dd06ea6cb2d44137f0f3fb2ae99ded1bc34222 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5648941810974720_1/C++/Z0RR0/code2.cpp | d9574da6b532d779f30b62dd8bcd73294e0009ac | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,260 | cpp | #include <bits/stdc++.h>
#define rep(i,n) for(i=1;i<=n;i++)
#define Rep(i,n) for(i=0;i<n;i++)
#define For(i,a,b) for(i=a;i<=b;i++)
#define pb(x) push_back(x)
#define sz(x) x.size()
#define mem(ara,val) memset(ara,val,sizeof(ara))
#define eps 1e-9
#define si(x) scanf("%d",&x)
#define sii(x,y) scanf("%d %d",&x,&y)
#define siii(x,y,z) scanf("%d %d %d",&x,&y,&z)
#define sl(x) scanf("%lld",&x)
#define sll(x,y) scanf("%lld %lld",&x,&y)
#define slll(x,y,z) scanf("%lld %lld %lld",&x,&y,&z)
#define ss(ch) scanf("%s",ch)
#define pi(x) printf("%d",x)
#define pii(x,y) printf("%d %d",x,y)
#define piii(x,y,z) printf("%d %d %d",x,y,z)
#define pl(x) printf("%lld",x)
#define pll(x,y) printf("%lld %lld",x,y)
#define plll(x,y,z) printf("%lld %lld %lld",x,y,z)
#define ps(ch) printf("%s",ch)
#define Afridi 0
#define NL printf("\n")
#define debug(x,y) cout << x << " " << y << "\n"
#define Max 100005
#define INF INT_MAX
#define mod 1000000007
#define FI freopen("in.txt","r",stdin)
#define FO freopen("out.txt","w",stdout)
#define PI 3.14159265358979323846
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int UI;
using namespace std;
LL bigmod(LL b,int p)
{
if(p == 0)return 1;
LL my = bigmod(b,p/2);
my*=my;
my%=mod;
if(p & 1)my*=b,my%=mod;
return my;
}
int setb(int n,int pos)
{
return n=n | (1 << pos);
}
int resb(int n,int pos)
{
return n=n & ~(1 << pos);
}
bool checkb(int n,int pos)
{
return (bool)(n & (1 << pos));
}
int dick[] = {0,2,4,6,5,7,1,8,9,3};
char fuck[] = {'Z','W','U','X','F','V','O','G','I','T'};
int cnt[200];
int lol[100];
char str[200000];
char oh[10][10] = { "ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" };
int main()
{
//FI;
freopen("A-large.in","r",stdin);
freopen("outALarge.txt","w",stdout);
int t,T,i,j;
si(T);
rep(t,T)
{
ss(str);
int len = strlen(str);
mem(cnt,0);
mem(lol,0);
Rep(i,len)cnt[ str[i] ]++;
Rep(i,10)
{
int x = dick[i];
char c = fuck[i];
int my = cnt[ c ];
lol[x] = my;
//printf("%s %d\n",oh[x],my);
int l = strlen(oh[x]);
Rep(j,l)
{
cnt[ oh[x][j] ] -= my;
}
}
printf("Case #%d: ",t);
Rep(i,10)
{
for(j=1;j<=lol[i];j++)printf("%d",i);
}
NL;
}
return 0;
}
| [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
8a107c7cfe02e2edba174e65b57531fdd59f989c | c35c692e051e15199410385ec82845391ab84b84 | /src/robot_control_system_generator/sources/thirdparty/libyuv/libyuv_scale_argb.h | cfc95a50f1b954dc941f69e41604950d5928f685 | [] | no_license | pombreda/roboticsby | fc9b389d88f10109e937cc8125a818a209057ddb | 4789f8faf7e63dc0d675778d40c1e7b541e77d41 | refs/heads/master | 2021-01-22T03:39:27.354870 | 2015-02-23T11:33:52 | 2015-02-23T11:33:52 | 32,210,410 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,090 | h | /*
* Copyright 2012 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef INCLUDE_LIBYUV_SCALE_ARGB_H_ // NOLINT
#define INCLUDE_LIBYUV_SCALE_ARGB_H_
#include "libyuv_basic_types.h"
#include "libyuv_scale.h" // For FilterMode
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
LIBYUV_API
int ARGBScale(const uint8* src_argb, int src_stride_argb,
int src_width, int src_height,
uint8* dst_argb, int dst_stride_argb,
int dst_width, int dst_height,
enum FilterMode filtering);
// Clipped scale takes destination rectangle coordinates for clip values.
LIBYUV_API
int ARGBScaleClip(const uint8* src_argb, int src_stride_argb,
int src_width, int src_height,
uint8* dst_argb, int dst_stride_argb,
int dst_width, int dst_height,
int clip_x, int clip_y, int clip_width, int clip_height,
enum FilterMode filtering);
// TODO(fbarchard): Implement this.
// Scale with YUV conversion to ARGB and clipping.
LIBYUV_API
int YUVToARGBScaleClip(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint32 src_fourcc,
int src_width, int src_height,
uint8* dst_argb, int dst_stride_argb,
uint32 dst_fourcc,
int dst_width, int dst_height,
int clip_x, int clip_y, int clip_width, int clip_height,
enum FilterMode filtering);
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
#endif // INCLUDE_LIBYUV_SCALE_ARGB_H_ NOLINT
| [
"sgerasuto%tut.by@gtempaccount.com@9e829c2e-0fe7-11df-962a-0b01395cd2b2"
] | sgerasuto%tut.by@gtempaccount.com@9e829c2e-0fe7-11df-962a-0b01395cd2b2 |
f213f7843ce737ac315afd8b3d60959bee870afa | d939ea588d1b215261b92013e050993b21651f9a | /mgobe/src/v20201014/model/DescribeRoomRequest.cpp | f93ab698f084150a8a27eeb028e083f4a8fd4350 | [
"Apache-2.0"
] | permissive | chenxx98/tencentcloud-sdk-cpp | 374e6d1349f8992893ded7aa08f911dd281f1bda | a9e75d321d96504bc3437300d26e371f5f4580a0 | refs/heads/master | 2023-03-27T05:35:50.158432 | 2021-03-26T05:18:10 | 2021-03-26T05:18:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,968 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/mgobe/v20201014/model/DescribeRoomRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Mgobe::V20201014::Model;
using namespace rapidjson;
using namespace std;
DescribeRoomRequest::DescribeRoomRequest() :
m_gameIdHasBeenSet(false),
m_playerIdHasBeenSet(false),
m_roomIdHasBeenSet(false)
{
}
string DescribeRoomRequest::ToJsonString() const
{
Document d;
d.SetObject();
Document::AllocatorType& allocator = d.GetAllocator();
if (m_gameIdHasBeenSet)
{
Value iKey(kStringType);
string key = "GameId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_gameId.c_str(), allocator).Move(), allocator);
}
if (m_playerIdHasBeenSet)
{
Value iKey(kStringType);
string key = "PlayerId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_playerId.c_str(), allocator).Move(), allocator);
}
if (m_roomIdHasBeenSet)
{
Value iKey(kStringType);
string key = "RoomId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_roomId.c_str(), allocator).Move(), allocator);
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string DescribeRoomRequest::GetGameId() const
{
return m_gameId;
}
void DescribeRoomRequest::SetGameId(const string& _gameId)
{
m_gameId = _gameId;
m_gameIdHasBeenSet = true;
}
bool DescribeRoomRequest::GameIdHasBeenSet() const
{
return m_gameIdHasBeenSet;
}
string DescribeRoomRequest::GetPlayerId() const
{
return m_playerId;
}
void DescribeRoomRequest::SetPlayerId(const string& _playerId)
{
m_playerId = _playerId;
m_playerIdHasBeenSet = true;
}
bool DescribeRoomRequest::PlayerIdHasBeenSet() const
{
return m_playerIdHasBeenSet;
}
string DescribeRoomRequest::GetRoomId() const
{
return m_roomId;
}
void DescribeRoomRequest::SetRoomId(const string& _roomId)
{
m_roomId = _roomId;
m_roomIdHasBeenSet = true;
}
bool DescribeRoomRequest::RoomIdHasBeenSet() const
{
return m_roomIdHasBeenSet;
}
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
476b141de4907a0c3f0aa9c16391a12b45a29f0a | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/admin/activec/designer/vb98ctls/mssnapd/mssnapd/taskpvw.cpp | 4d21d14c5c9e5bc81cc47f235778c81fdcb8abe9 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 22,257 | cpp | //=--------------------------------------------------------------------------------------
// taskpvw.cpp
//=--------------------------------------------------------------------------------------
//
// Copyright (c) 1999, Microsoft Corporation.
// All Rights Reserved.
//
// Information Contained Herein Is Proprietary and Confidential.
//
//=------------------------------------------------------------------------------------=
//
// CSnapInDesigner implementation -- TaskpadView-related command handling
//=-------------------------------------------------------------------------------------=
#include "pch.h"
#include "common.h"
#include "TreeView.h"
#include "desmain.h"
#include "guids.h"
// for ASSERT and FAIL
//
SZTHISFILE
// Size for our character string buffers
const int kMaxBuffer = 512;
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::AddTaskpadView()
//=--------------------------------------------------------------------------------------
//
// Notes
//
HRESULT CSnapInDesigner::AddTaskpadView()
{
HRESULT hr = S_OK;
IViewDefs *piViewDefs = NULL;
ITaskpadViewDefs *piTaskpadViewDefs = NULL;
VARIANT vtEmpty;
ITaskpadViewDef *piTaskpadViewDef = NULL;
::VariantInit(&vtEmpty);
hr = GetOwningViewCollection(&piViewDefs);
IfFailGo(hr);
if (piViewDefs != NULL)
{
hr = piViewDefs->get_TaskpadViews(&piTaskpadViewDefs);
IfFailGo(hr);
if (piTaskpadViewDefs != NULL)
{
vtEmpty.vt = VT_ERROR;
vtEmpty.scode = DISP_E_PARAMNOTFOUND;
hr = piTaskpadViewDefs->Add(vtEmpty, vtEmpty, &piTaskpadViewDef);
IfFailGo(hr);
}
}
Error:
RELEASE(piTaskpadViewDef);
RELEASE(piTaskpadViewDefs);
RELEASE(piViewDefs);
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::OnAddTaskpadViewDef(CSelectionHolder *pParent, ITaskpadViewDef *piURLViewDef)
//=--------------------------------------------------------------------------------------
//
// Notes
//
// Invoked in response to an IObjectModelHost:Add() notification.
//
HRESULT CSnapInDesigner::OnAddTaskpadViewDef(CSelectionHolder *pParent, ITaskpadViewDef *piTaskpadViewDef)
{
HRESULT hr = S_OK;
CSelectionHolder *pTaskpadView = NULL;
IViewDefs *piViewDefs = NULL;
ITaskpadViewDefs *piTaskpadViewDefs = NULL;
ASSERT(NULL != pParent, "OnAddTaskpadViewDef: pParent is NULL");
ASSERT(NULL != pParent->m_piObject.m_piTaskpadViewDefs, "OnAddTaskpadViewDef: pParent->m_piObject.m_piTaskpadViewDefs is NULL");
switch (pParent->m_st)
{
case SEL_NODES_AUTO_CREATE_RTVW:
hr = pParent->m_piObject.m_piSnapInDef->get_ViewDefs(&piViewDefs);
IfFailGo(hr);
hr = piViewDefs->get_TaskpadViews(&piTaskpadViewDefs);
IfFailGo(hr);
break;
case SEL_VIEWS_TASK_PAD:
piTaskpadViewDefs = pParent->m_piObject.m_piTaskpadViewDefs;
piTaskpadViewDefs->AddRef();
break;
case SEL_NODES_ANY_VIEWS:
hr = pParent->m_piObject.m_piScopeItemDef->get_ViewDefs(&piViewDefs);
IfFailGo(hr);
hr = piViewDefs->get_TaskpadViews(&piTaskpadViewDefs);
IfFailGo(hr);
break;
default:
ASSERT(0, "OnAddTaskpadViewDef: Cannot determine owning collection");
goto Error;
}
hr = MakeNewTaskpadView(piTaskpadViewDefs, piTaskpadViewDef, &pTaskpadView);
IfFailGo(hr);
hr = InsertTaskpadViewInTree(pTaskpadView, pParent);
IfFailGo(hr);
hr = OnSelectionChanged(pTaskpadView);
IfFailGo(hr);
hr = m_pTreeView->SelectItem(pTaskpadView);
IfFailGo(hr);
hr = m_pTreeView->Edit(pTaskpadView);
IfFailGo(hr);
m_fDirty = TRUE;
Error:
RELEASE(piViewDefs);
RELEASE(piTaskpadViewDefs);
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::AddExistingTaskpadView(IViewDefs *piViewDefs, ITaskpadViewDef *piTaskpadViewDef)
//=--------------------------------------------------------------------------------------
//
// Notes
//
HRESULT CSnapInDesigner::AddExistingTaskpadView(IViewDefs *piViewDefs, ITaskpadViewDef *piTaskpadViewDef)
{
HRESULT hr = S_OK;
ITaskpadViewDefs *piTaskpadViewDefs = NULL;
hr = piViewDefs->get_TaskpadViews(&piTaskpadViewDefs);
IfFailGo(hr);
hr = piTaskpadViewDefs->AddFromMaster(piTaskpadViewDef);
IfFailGo(hr);
Error:
RELEASE(piTaskpadViewDefs);
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::RenameTaskpadView(CSelectionHolder *pTaskpadView, BSTR bstrNewName)
//=--------------------------------------------------------------------------------------
//
// Notes
//
HRESULT CSnapInDesigner::RenameTaskpadView(CSelectionHolder *pTaskpadView, BSTR bstrNewName)
{
HRESULT hr = S_OK;
TCHAR *pszName = NULL;
ASSERT(SEL_VIEWS_TASK_PAD_NAME == pTaskpadView->m_st, "RenameTaskpadView: wrong argument");
hr = m_piDesignerProgrammability->IsValidIdentifier(bstrNewName);
IfFailGo(hr);
if (S_FALSE == hr)
{
hr = SID_E_INVALIDARG;
goto Error;
}
hr = pTaskpadView->m_piObject.m_piTaskpadViewDef->put_Key(bstrNewName);
IfFailGo(hr);
hr = pTaskpadView->m_piObject.m_piTaskpadViewDef->put_Name(bstrNewName);
IfFailGo(hr);
hr = ANSIFromBSTR(bstrNewName, &pszName);
IfFailGo(hr);
// Rename all satellite views
hr = m_pTreeView->RenameAllSatelliteViews(pTaskpadView, pszName);
IfFailGo(hr);
// Rename the actual view
hr = m_pTreeView->ChangeText(pTaskpadView, pszName);
IfFailGo(hr);
Error:
if (NULL != pszName)
CtlFree(pszName);
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::DeleteTaskpadView(CSelectionHolder *pTaskpadView)
//=--------------------------------------------------------------------------------------
//
// Notes
//
HRESULT CSnapInDesigner::DeleteTaskpadView
(
CSelectionHolder *pTaskpadView
)
{
HRESULT hr = S_OK;
bool bIsSatelliteView = false;
IObjectModel *piObjectModel = NULL;
long lUsageCount = 0;
BSTR bstrName = NULL;
IViewDefs *piViewDefs = NULL;
ITaskpadViewDefs *piTaskpadViewDefs = NULL;
VARIANT vtKey;
::VariantInit(&vtKey);
// We allow any satellite view to be deleted
hr = IsSatelliteView(pTaskpadView);
IfFailGo(hr);
// But if it's a master with a UsageCount > 0 we don't allow deleting it.
if (S_FALSE == hr)
{
hr = pTaskpadView->m_piObject.m_piTaskpadViewDef->QueryInterface(IID_IObjectModel, reinterpret_cast<void **>(&piObjectModel));
IfFailGo(hr);
hr = piObjectModel->GetUsageCount(&lUsageCount);
IfFailGo(hr);
if (lUsageCount > 1)
{
(void)::SDU_DisplayMessage(IDS_VIEW_IN_USE, MB_OK | MB_ICONHAND, HID_mssnapd_ViewInUse, 0, DontAppendErrorInfo, NULL);
goto Error;
}
}
else
bIsSatelliteView = true;
hr = pTaskpadView->m_piObject.m_piTaskpadViewDef->get_Key(&bstrName);
IfFailGo(hr);
if (true == bIsSatelliteView)
{
hr = GetOwningViewCollection(pTaskpadView, &piViewDefs);
IfFailGo(hr);
}
else
{
hr = m_piSnapInDesignerDef->get_ViewDefs(&piViewDefs);
IfFailGo(hr);
}
if (piViewDefs != NULL)
{
hr = piViewDefs->get_TaskpadViews(&piTaskpadViewDefs);
IfFailGo(hr);
vtKey.vt = VT_BSTR;
vtKey.bstrVal = ::SysAllocString(bstrName);
if (NULL == vtKey.bstrVal)
{
hr = SID_E_OUTOFMEMORY;
EXCEPTION_CHECK(hr);
}
hr = piTaskpadViewDefs->Remove(vtKey);
IfFailGo(hr);
}
Error:
FREESTRING(bstrName);
RELEASE(piTaskpadViewDefs);
RELEASE(piViewDefs);
RELEASE(piObjectModel);
::VariantClear(&vtKey);
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::OnDeleteTaskpadView(CSelectionHolder *pTaskpadView)
//=--------------------------------------------------------------------------------------
//
// Notes
//
HRESULT CSnapInDesigner::OnDeleteTaskpadView
(
CSelectionHolder *pTaskpadView
)
{
HRESULT hr = S_OK;
CSelectionHolder *pParent = NULL;
bool bIsSatelliteView = false;
IViewDefs *piViewDefs = NULL;
ITaskpadViewDefs *piTaskpadViewDefs = NULL;
long lCount = 0;
hr = IsSatelliteView(pTaskpadView);
IfFailGo(hr);
bIsSatelliteView = (S_OK == hr) ? true : false;
if (true == bIsSatelliteView)
{
hr = GetOwningViewCollection(pTaskpadView, &piViewDefs);
IfFailGo(hr);
}
else
{
hr = m_piSnapInDesignerDef->get_ViewDefs(&piViewDefs);
IfFailGo(hr);
}
// Find out who the next selection should be
hr = m_pTreeView->GetParent(pTaskpadView, &pParent);
IfFailGo(hr);
// Delete the node from the tree
hr = m_pTreeView->DeleteNode(pTaskpadView);
IfFailGo(hr);
delete pTaskpadView;
// Select the next selection
if (NULL != piViewDefs)
{
hr = piViewDefs->get_TaskpadViews(&piTaskpadViewDefs);
IfFailGo(hr);
hr = piTaskpadViewDefs->get_Count(&lCount);
IfFailGo(hr);
if (0 == lCount)
{
hr = m_pTreeView->ChangeNodeIcon(pParent, kClosedFolderIcon);
IfFailGo(hr);
}
}
hr = m_pTreeView->SelectItem(pParent);
IfFailGo(hr);
hr = OnSelectionChanged(pParent);
IfFailGo(hr);
Error:
RELEASE(piTaskpadViewDefs);
RELEASE(piViewDefs);
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::ShowTaskpadViewProperties(ITaskpadViewDef *piTaskpadViewDef)
//=--------------------------------------------------------------------------------------
//
// Notes
//
HRESULT CSnapInDesigner::ShowTaskpadViewProperties
(
ITaskpadViewDef *piTaskpadViewDef
)
{
HRESULT hr = S_OK;
int iResult = 0;
OCPFIPARAMS ocpfiParams;
TCHAR szBuffer[kMaxBuffer + 1];
BSTR bstrCaption = NULL;
IUnknown *pUnk[1];
CLSID pageClsID[3];
hr = GetResourceString(IDS_TASK_PROPS, szBuffer, kMaxBuffer);
IfFailGo(hr);
hr = BSTRFromANSI(szBuffer, &bstrCaption);
IfFailGo(hr);
hr = piTaskpadViewDef->QueryInterface(IID_IUnknown, reinterpret_cast<void **>(&pUnk[0]));
IfFailGo(hr);
pageClsID[0] = CLSID_TaskpadViewDefGeneralPP;
pageClsID[1] = CLSID_TaskpadViewDefBackgroundPP;
pageClsID[2] = CLSID_TaskpadViewDefTasksPP;
::memset(&ocpfiParams, 0, sizeof(OCPFIPARAMS));
ocpfiParams.cbStructSize = sizeof(OCPFIPARAMS);
ocpfiParams.hWndOwner = m_hwnd;
ocpfiParams.x = 0;
ocpfiParams.y = 0;
ocpfiParams.lpszCaption = bstrCaption;
ocpfiParams.cObjects = 1;
ocpfiParams.lplpUnk = pUnk;
ocpfiParams.cPages = 3;
ocpfiParams.lpPages = pageClsID;
ocpfiParams.lcid = g_lcidLocale;
ocpfiParams.dispidInitialProperty = 0;
hr = ::OleCreatePropertyFrameIndirect(&ocpfiParams);
IfFailGo(hr);
Error:
RELEASE(pUnk[0]);
FREESTRING(bstrCaption);
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::MakeNewTaskpadView(ITaskpadViewDefs *piTaskpadViewDefs, ITaskpadViewDef *piTaskpadViewDef, CSelectionHolder **ppTaskpadView)
//=--------------------------------------------------------------------------------------
//
// Notes
//
HRESULT CSnapInDesigner::MakeNewTaskpadView
(
ITaskpadViewDefs *piTaskpadViewDefs,
ITaskpadViewDef *piTaskpadViewDef,
CSelectionHolder **ppTaskpadView
)
{
HRESULT hr = S_OK;
*ppTaskpadView = New CSelectionHolder(piTaskpadViewDef);
if (NULL == *ppTaskpadView)
{
hr = SID_E_OUTOFMEMORY;
EXCEPTION_CHECK_GO(hr);
}
hr = InitializeNewTaskpadView(piTaskpadViewDefs, *ppTaskpadView);
IfFailGo(hr);
Error:
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::InitializeNewTaskpadView(ITaskpadViewDefs *piTaskpadViewDefs, CSelectionHolder *pTaskpadView)
//=--------------------------------------------------------------------------------------
//
// Notes
//
HRESULT CSnapInDesigner::InitializeNewTaskpadView
(
ITaskpadViewDefs *piTaskpadViewDefs,
CSelectionHolder *pTaskpadView
)
{
HRESULT hr = S_OK;
IObjectModel *piObjectModel = NULL;
CSelectionHolder *pViewCollection = NULL;
int iResult = 0;
int iItemNumber = 0;
TCHAR szBuffer[kMaxBuffer + 1];
TCHAR szName[kMaxBuffer + 1];
BSTR bstrName = NULL;
bool bGood = false;
CSelectionHolder *pTaskpadViewDefClone = NULL;
ITaskpad *piTaskpad = NULL;
ASSERT(NULL != piTaskpadViewDefs, "InitializeNewTaskpadView: piTaskpadViewDefs is NULL");
ASSERT(NULL != pTaskpadView, "InitializeNewTaskpadView: pTaskpadView is NULL");
hr = piTaskpadViewDefs->QueryInterface(IID_IObjectModel, reinterpret_cast<void **>(&piObjectModel));
IfFailGo(hr);
hr = piObjectModel->GetCookie(reinterpret_cast<long *>(&pViewCollection));
IfFailGo(hr);
ASSERT(NULL != pViewCollection, "InitializeNewTaskpadView: Bad Cookie");
hr = IsSatelliteCollection(pViewCollection);
IfFailGo(hr);
if (S_FALSE == hr)
{
hr = GetResourceString(IDS_TASK_VIEW, szBuffer, kMaxBuffer);
IfFailGo(hr);
do {
iResult = _stprintf(szName, _T("%s%d"), szBuffer, ++iItemNumber);
if (iResult == 0)
{
hr = HRESULT_FROM_WIN32(::GetLastError());
EXCEPTION_CHECK(hr);
}
hr = m_pTreeView->FindLabelInTree(szName, &pTaskpadViewDefClone);
IfFailGo(hr);
if (S_FALSE == hr)
{
hr = BSTRFromANSI(szName, &bstrName);
IfFailGo(hr);
bGood = true;
break;
}
FREESTRING(bstrName);
} while (false == bGood);
hr = pTaskpadView->m_piObject.m_piTaskpadViewDef->put_Key(bstrName);
IfFailGo(hr);
hr = pTaskpadView->m_piObject.m_piTaskpadViewDef->put_Name(bstrName);
IfFailGo(hr);
hr = pTaskpadView->m_piObject.m_piTaskpadViewDef->get_Taskpad(&piTaskpad);
IfFailGo(hr);
hr = piTaskpad->put_Name(bstrName);
IfFailGo(hr);
}
hr = pTaskpadView->RegisterHolder();
IfFailGo(hr);
Error:
RELEASE(piTaskpad);
FREESTRING(bstrName);
RELEASE(piObjectModel);
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::InsertTaskpadViewInTree(CSelectionHolder *pTaskpadView, CSelectionHolder *pParent)
//=--------------------------------------------------------------------------------------
//
// Notes
//
HRESULT CSnapInDesigner::InsertTaskpadViewInTree
(
CSelectionHolder *pTaskpadView,
CSelectionHolder *pParent
)
{
HRESULT hr = S_OK;
BSTR bstrName = NULL;
TCHAR *pszName = NULL;
hr = pTaskpadView->m_piObject.m_piTaskpadViewDef->get_Key(&bstrName);
IfFailGo(hr);
hr = ANSIFromBSTR(bstrName, &pszName);
IfFailGo(hr);
hr = m_pTreeView->AddNode(pszName, pParent, kTaskpadIcon, pTaskpadView);
IfFailGo(hr);
Error:
if (pszName != NULL)
CtlFree(pszName);
FREESTRING(bstrName);
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
//=--------------------------------------------------------------------------------------
// Support functions to manipulate IViewDef's
// Searching
//=--------------------------------------------------------------------------------------
//=--------------------------------------------------------------------------------------
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::GetOwningViewCollection(IViewDefs **ppiViewDefs)
//=--------------------------------------------------------------------------------------
//
// Notes
//
HRESULT CSnapInDesigner::GetOwningViewCollection
(
IViewDefs **ppiViewDefs
)
{
HRESULT hr = S_OK;
hr = GetOwningViewCollection(m_pCurrentSelection, ppiViewDefs);
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::GetOwningViewCollection(CSelectionHolder *pView, IViewDefs **ppiViewDefs)
//=--------------------------------------------------------------------------------------
//
// Notes
//
HRESULT CSnapInDesigner::GetOwningViewCollection
(
CSelectionHolder *pView,
IViewDefs **ppiViewDefs
)
{
HRESULT hr = S_OK;
CSelectionHolder *pParent = NULL;
ISnapInDef *piSnapInDef = NULL;
switch (pView->m_st)
{
case SEL_NODES_AUTO_CREATE_ROOT:
case SEL_NODES_AUTO_CREATE_RTVW:
hr = m_piSnapInDesignerDef->get_SnapInDef(&piSnapInDef);
IfFailGo(hr);
hr = piSnapInDef->get_ViewDefs(ppiViewDefs);
IfFailGo(hr);
break;
case SEL_NODES_ANY_VIEWS:
case SEL_VIEWS_LIST_VIEWS_NAME:
case SEL_VIEWS_OCX_NAME:
case SEL_VIEWS_URL_NAME:
case SEL_VIEWS_TASK_PAD_NAME:
hr = m_pTreeView->GetParent(pView, &pParent);
IfFailGo(hr);
switch (pParent->m_st)
{
case SEL_NODES_ANY_NAME:
case SEL_NODES_ANY_VIEWS:
hr = pParent->m_piObject.m_piScopeItemDef->get_ViewDefs(ppiViewDefs);
IfFailGo(hr);
break;
case SEL_NODES_AUTO_CREATE_RTVW:
hr = m_piSnapInDesignerDef->get_SnapInDef(&piSnapInDef);
IfFailGo(hr);
hr = piSnapInDef->get_ViewDefs(ppiViewDefs);
IfFailGo(hr);
break;
default:
ASSERT(0, "Unexpected parent");
}
break;
case SEL_NODES_ANY_NAME:
hr = pView->m_piObject.m_piScopeItemDef->get_ViewDefs(ppiViewDefs);
IfFailGo(hr);
break;
case SEL_VIEWS_ROOT:
hr = m_piSnapInDesignerDef->get_ViewDefs(ppiViewDefs);
IfFailGo(hr);
break;
case SEL_VIEWS_LIST_VIEWS:
case SEL_VIEWS_OCX:
case SEL_VIEWS_URL:
case SEL_VIEWS_TASK_PAD:
hr = m_piSnapInDesignerDef->get_ViewDefs(ppiViewDefs);
IfFailGo(hr);
break;
}
Error:
RELEASE(piSnapInDef);
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::IsSatelliteView(CSelectionHolder *pView)
//=--------------------------------------------------------------------------------------
//
// Notes
//
// Return S_OK if this view is part of a satellite collection, S_FALSE otherwise.
//
HRESULT CSnapInDesigner::IsSatelliteView(CSelectionHolder *pView)
{
HRESULT hr = S_OK;
CSelectionHolder *pParent = NULL;
hr = m_pTreeView->GetParent(pView, &pParent);
IfFailGo(hr);
switch (pParent->m_st)
{
case SEL_VIEWS_LIST_VIEWS:
case SEL_VIEWS_OCX:
case SEL_VIEWS_URL:
case SEL_VIEWS_TASK_PAD:
hr = S_FALSE;
break;
}
Error:
RRETURN(hr);
}
//=--------------------------------------------------------------------------------------
// CSnapInDesigner::IsSatelliteCollection(CSelectionHolder *pViewCollection)
//=--------------------------------------------------------------------------------------
//
// Notes
//
// Return S_OK if collection is a satellite collection, S_FALSE otherwise.
//
HRESULT CSnapInDesigner::IsSatelliteCollection(CSelectionHolder *pViewCollection)
{
HRESULT hr = S_OK;
CSelectionHolder *pParent = NULL;
switch (pViewCollection->m_st)
{
// Possible parent nodes of a view:
case SEL_NODES_AUTO_CREATE_RTVW:
// Anything off of SnapIn/Auto-Create/Static Node/Views is a satellite collection
break;
case SEL_NODES_ANY_VIEWS:
// Anything off of SnapIn/Auto-Create/Static Node/<name>/Views, recursively, and
// anything off of SnapIn/Other/<name>/Views is a satellite collection
break;
case SEL_VIEWS_LIST_VIEWS:
case SEL_VIEWS_OCX:
case SEL_VIEWS_URL:
case SEL_VIEWS_TASK_PAD:
// If these depend off of SnapIn/Views then they are NOT a satellite collection
hr = m_pTreeView->GetParent(pViewCollection, &pParent);
IfFailGo(hr);
switch (pParent->m_st)
{
case SEL_VIEWS_ROOT:
hr = S_FALSE;
break;
}
break;
default:
ASSERT(0, "IsSatelliteCollection: wrong argument");
}
Error:
RRETURN(hr);
}
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
1a33ab73f5248e86562bc32400e8370a88be3e5a | c636136096c92ddb07ce97d3960bf0289d70b57a | /Medusa/Medusa/Resource/Image/DynamicAtlasRGBAImage.cpp | 7b7b3f1e96f2eaf88716ed6432a9b715c1423b9b | [
"MIT"
] | permissive | johndpope/Medusa | 6a5a08e0c3f216dcab3b23db2f7bcf4d05845bce | 22aa6719a001330fea51a6822fec01150eb8aabc | refs/heads/master | 2020-12-30T20:51:14.718429 | 2015-12-15T12:31:22 | 2015-12-15T12:31:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,459 | cpp | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaPreCompiled.h"
#include "DynamicAtlasRGBAImage.h"
#include "Core/Geometry/Size3.h"
#include "Resource/Image/ImageFactory.h"
MEDUSA_BEGIN;
DynamicAtlasRGBAImage::DynamicAtlasRGBAImage(const FileIdRef& fileId,Size2U initImageSize,Size2U maxImageSize,GraphicsInternalFormat internalFormat,GraphicsPixelFormat imageFormat,bool isPreMultiplyAlpha )
:RGBAImage(fileId,initImageSize,internalFormat,imageFormat,isPreMultiplyAlpha),
mPack(initImageSize),mMaxImageSize(maxImageSize)
{
mImageData.ClearZero();
}
DynamicAtlasRGBAImage::~DynamicAtlasRGBAImage(void)
{
}
bool DynamicAtlasRGBAImage::AddImageRect(const Size2U& size,int pitch,const MemoryByteData& imageData,GraphicsPixelFormat pixelFormat,GraphicsPixelDataType srcDataType,
Rect2U& outRect, bool isFlipY/*=false*/,GraphicsPixelConvertMode mode/*=PixelConvertMode::Normal*/)
{
RETURN_FALSE_IF(size>mMaxImageSize);
outRect=mPack.Insert(size,SkylineBinPack::LevelChoiceHeuristic::LevelBottomLeft);
if (outRect!=Rect2U::Zero)
{
outRect.Size-=1; //should -1 to remove edge
CopyImage(outRect,imageData,pixelFormat,srcDataType,pitch,isFlipY,mode);
return true;
}
RETURN_FALSE_IF(mImageSize>=mMaxImageSize); //is full
//try to expand
//1.new a bigger image
Size2U newImageSize=mImageSize;
do
{
newImageSize.Width=Math::Min((uint)Math::NextPOT(newImageSize.Width),mMaxImageSize.Width);
newImageSize.Height=Math::Min((uint)Math::NextPOT(newImageSize.Height),mMaxImageSize.Width);
mPack.GrowSize(mImageSize); //not re layout the original rects,maybe do it in the future
outRect=mPack.Insert(size,SkylineBinPack::LevelChoiceHeuristic::LevelBottomLeft);
if (outRect!=Rect2U::Zero)
{
MemoryByteData newImageData=MemoryByteData::Alloc(mImageSize.Area()*BytesPerComponent());
//2.copy image data to new image
ImageFactory::CopyImage(newImageData,mPixelFormat,mPixelDataType,newImageSize,Rect2U(Point2F::Zero,mImageSize),mImageData,mPixelFormat,mPixelDataType,0,false,GraphicsPixelConvertMode::Normal);
mImageSize=newImageSize;
mImageData=newImageData;
//draw new image
outRect.Size-=1;//should -1 to remove edge
CopyImage(outRect,imageData,pixelFormat,srcDataType,pitch,isFlipY,mode);
return true;
}
} while (newImageSize<mMaxImageSize);
return false;
}
MEDUSA_END; | [
"fjz13@live.cn"
] | fjz13@live.cn |
c6776b65c567b5da17feecfeecbeaad8568b6284 | 02ce8a5d3386aa639ef1c2c2fdd6da8d0de158f9 | /ACE-5.6.1/ACE_wrappers/apps/drwho/SM_Client.cpp | bf0cb5194912d62f67a17d583bcf7497ebf21a44 | [] | no_license | azraelly/knetwork | 932e27a22b1ee621742acf57618083ecab23bca1 | 69e30ee08d0c8e66c1cfb00d7ae3ba6983ff935c | refs/heads/master | 2021-01-20T13:48:24.909756 | 2010-07-03T13:59:39 | 2010-07-03T13:59:39 | 39,634,314 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,607 | cpp | // $Id: SM_Client.cpp 53169 2003-11-01 11:15:26Z dhinton $
#include "Options.h"
#include "PMC_All.h"
#include "PMC_Flo.h"
#include "PMC_Usr.h"
#include "PMC_Ruser.h"
#include "SM_Client.h"
#include "ace/Log_Msg.h"
#include "ace/OS_Memory.h"
// Call-back function that invokes the appropriate decode function.
int
SM_Client::demux (char *packet,
int &packet_length)
{
if (this->pm_client->decode (packet, packet_length) < 0)
return -1;
else
return 1;
}
// Call-back function that invokes the appropriate encode function.
int
SM_Client::mux (char *packet, int &packet_length)
{
switch (Options::protocol_type)
{
case Options::PROTO_USR:
ACE_NEW_RETURN (this->pm_client,
PMC_Usr (Options::user_name),
-1);
break;
case Options::PROTO_ALL:
ACE_NEW_RETURN (this->pm_client,
PMC_All,
-1);
break;
case Options::PROTO_FLO:
ACE_NEW_RETURN (this->pm_client,
PMC_Flo,
-1);
break;
case Options::PROTO_RUSER:
ACE_NEW_RETURN (this->pm_client,
PMC_Ruser,
-1);
break;
default:
ACE_DEBUG ((LM_DEBUG,
"%s: bad protocol\n",
Options::program_name));
return -1;
}
if (this->pm_client->encode (packet, packet_length) < 0)
return -1;
return 1;
}
SM_Client::SM_Client (void)
{
}
SM_Client::~SM_Client (void)
{
}
void
SM_Client::process (void)
{
this->pm_client->process ();
}
| [
"yuwuxiong2010@gmail.com"
] | yuwuxiong2010@gmail.com |
dfd10c58409d0c0d60ce79143f87fa8f6d719bb3 | a4d25420e402f9a1dd69b950372f5c496127db7a | /MyView.cpp | a2f1b2f2e557edab36423f32abe0830d0f3db0f9 | [] | no_license | PieTurri/Game-2D | 793b309b70039ea9c5d6395fedc9acebd6ce583c | 8116a58692fc11c666391a714642309f95ec9182 | refs/heads/master | 2021-10-27T05:51:28.732244 | 2019-04-16T12:52:35 | 2019-04-16T12:52:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | cpp | //
// Created by leogori on 28/02/19.
//
#include "MyView.h"
#include <iostream>
#include <tgmath.h>
#include "Knight.h"
using namespace std;
MyView::MyView() {}
void MyView::followHero() {
Hero* sub= dynamic_cast<Hero*>(subject);
Vector2f range = sub->getPosition() - getCenter();
if(!sub->getDirDown()&&!sub->getDirRight()&&!sub->getDirLeft()&&!sub->getDirUp()) {
times = clock.getElapsedTime();
float l = (float) sqrt(pow(range.x, 2) + pow(range.y, 2));
if (times.asMilliseconds() > 0) {
if (abs(l) > 0.5) {
move(range.x / l, range.y / l);
}
clock.restart();
}
}
else{
if(abs(range.x)<=64&&abs(range.y)<=64)
speed=sub->getSpeed()/2;
else
speed=sub->getSpeed();
if(sub->getDirUp())
move(0,-speed);
if(sub->getDirDown())
move(0,speed);
if(sub->getDirLeft())
move(-speed,0);
if(sub->getDirRight())
move(speed,0);
}
}
void MyView::update(Subject *s) {
if(subject==s)
followHero();
}
void MyView::setSubject(Subject *subject) {
this->subject=subject;
subject->addObserver(this);
}
| [
"leonardogori@hotmail.it"
] | leonardogori@hotmail.it |
5aee861dcaa1eedef5aacb58a4fe90f58ec946b3 | 481f3c6b713379912988084cf10810e7d9a74fd0 | /services/image_annotation/annotator_unittest.cc | 62bad57482339822654afb7bb6a09055dd16f9c5 | [
"MPL-2.0-no-copyleft-exception",
"LicenseRef-scancode-unknown-license-reference",
"AGPL-3.0-only",
"LGPL-2.1-only",
"GPL-2.0-only",
"MPL-2.0",
"BSD-3-Clause"
] | permissive | huhisoft/huhi-android | bab71148730ff68b770f56b93b731302528045ec | 1c00f05a2ab19f0d6acf42331931de61555a93e8 | refs/heads/master | 2023-01-13T11:26:25.618267 | 2019-11-11T04:09:38 | 2019-11-11T04:09:38 | 219,455,870 | 0 | 4 | BSD-3-Clause | 2022-12-10T08:31:33 | 2019-11-04T08:48:00 | null | UTF-8 | C++ | false | false | 85,986 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/image_annotation/annotator.h"
#include <cstring>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/optional.h"
#include "base/strings/stringprintf.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "mojo/public/cpp/bindings/binding_set.h"
#include "net/base/net_errors.h"
#include "net/http/http_status_code.h"
#include "services/data_decoder/public/cpp/test_data_decoder_service.h"
#include "services/data_decoder/public/mojom/constants.mojom.h"
#include "services/data_decoder/public/mojom/json_parser.mojom.h"
#include "services/image_annotation/image_annotation_metrics.h"
#include "services/image_annotation/public/mojom/image_annotation.mojom.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader.mojom-shared.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/mojom/service.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace image_annotation {
namespace {
using base::Bucket;
using testing::ElementsAre;
using testing::Eq;
using testing::IsEmpty;
using testing::SizeIs;
using testing::UnorderedElementsAre;
MATCHER_P3(AnnotatorEq, type, score, text, "") {
return (arg.type == type && arg.score == score && arg.text == text);
}
constexpr char kTestServerUrl[] = "https://ia-pa.googleapis.com/v1/annotation";
// Example image URLs.
constexpr char kImage1Url[] = "https://www.example.com/image1.jpg";
constexpr char kImage2Url[] = "https://www.example.com/image2.jpg";
constexpr char kImage3Url[] = "https://www.example.com/image3.jpg";
// Example server requests / responses.
// Template for a request for a single image.
constexpr char kTemplateRequest[] = R"(
{
"imageRequests": [{
"imageId": "%s",
"imageBytes": "%s",
"engineParameters": [
{"ocrParameters": {}},
{"descriptionParameters": {}}
]
}]
}
)";
// Batch request for |kImage1Url|, |kImage2Url| and |kImage3Url|.
constexpr char kBatchRequest[] = R"(
{
"imageRequests": [
{
"imageId": "https://www.example.com/image3.jpg",
"imageBytes": "BwgJ",
"engineParameters": [
{"ocrParameters": {}},
{"descriptionParameters": {}}
]
},
{
"imageId": "https://www.example.com/image2.jpg",
"imageBytes": "BAUG",
"engineParameters": [
{"ocrParameters": {}},
{"descriptionParameters": {}}
]
},
{
"imageId": "https://www.example.com/image1.jpg",
"imageBytes": "AQID",
"engineParameters": [
{"ocrParameters": {}},
{"descriptionParameters": {}}
]
}
]
})";
// Successful OCR text extraction for |kImage1Url| with no descriptions.
constexpr char kOcrSuccessResponse[] = R"(
{
"results": [
{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [
{
"words": [
{
"detectedText": "Region",
"confidenceScore": 1.0
},
{
"detectedText": "1",
"confidenceScore": 1.0
}
]
},
{
"words": [
{
"detectedText": "Region",
"confidenceScore": 1.0
},
{
"detectedText": "2",
"confidenceScore": 1.0
}
]
}
]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {}
}
}
]
}
]
}
)";
// Batch response containing successful annotations for |kImage1Url| and
// |kImage2Url|, and a failure for |kImage3Url|.
//
// The results also appear "out of order" (i.e. image 2 comes before image 1).
constexpr char kBatchResponse[] = R"(
{
"results": [
{
"imageId": "https://www.example.com/image2.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "2",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {}
}
}
]
},
{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {}
}
}
]
},
{
"imageId": "https://www.example.com/image3.jpg",
"engineResults": [
{
"status": {
"code": 8,
"message": "Resource exhausted"
},
"ocrEngine": {}
},
{
"status": {
"code": 8,
"message": "Resource exhausted"
},
"descriptionEngine": {}
}
]
}
]
})";
constexpr base::TimeDelta kThrottle = base::TimeDelta::FromSeconds(1);
// The minimum dimension required for description annotation.
constexpr int32_t kDescDim = Annotator::kDescMinDimension;
// The description language to use in tests that don't exercise
// language-handling logic.
constexpr char kDescLang[] = "";
// An image processor that holds and exposes the callbacks it is passed.
class TestImageProcessor : public mojom::ImageProcessor {
public:
TestImageProcessor() = default;
mojom::ImageProcessorPtr GetPtr() {
mojom::ImageProcessorPtr ptr;
bindings_.AddBinding(this, mojo::MakeRequest(&ptr));
return ptr;
}
void Reset() {
bindings_.CloseAllBindings();
callbacks_.clear();
}
void GetJpgImageData(GetJpgImageDataCallback callback) override {
callbacks_.push_back(std::move(callback));
}
std::vector<GetJpgImageDataCallback>& callbacks() { return callbacks_; }
private:
std::vector<GetJpgImageDataCallback> callbacks_;
mojo::BindingSet<mojom::ImageProcessor> bindings_;
DISALLOW_COPY_AND_ASSIGN(TestImageProcessor);
};
// A class that supports test URL loading for the "server" use case: where
// all request URLs have the same prefix and differ only in suffix and body
// content.
class TestServerURLLoaderFactory {
public:
TestServerURLLoaderFactory(const std::string& server_url_prefix)
: server_url_prefix_(server_url_prefix),
shared_loader_factory_(
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&loader_factory_)) {}
const std::vector<network::TestURLLoaderFactory::PendingRequest>& requests() {
return *loader_factory_.pending_requests();
}
// Expects that the earliest received request has the given URL, headers and
// body, and replies with the given response.
//
// |expected_headers| is a map from header key string to either:
// a) a null optional, if the given header should not be present, or
// b) a non-null optional, if the given header should be present and match
// the optional value.
//
// Consumes the earliest received request (i.e. a subsequent call will apply
// to the second-earliest received request and so on).
void ExpectRequestAndSimulateResponse(
const std::string& expected_url_suffix,
const std::map<std::string, base::Optional<std::string>>&
expected_headers,
const std::string& expected_body,
const std::string& response,
const net::HttpStatusCode response_code) {
const std::string expected_url = server_url_prefix_ + expected_url_suffix;
const std::vector<network::TestURLLoaderFactory::PendingRequest>&
pending_requests = *loader_factory_.pending_requests();
CHECK(!pending_requests.empty());
const network::ResourceRequest& request = pending_requests.front().request;
// Assert that the earliest request is for the given URL.
CHECK_EQ(request.url, GURL(expected_url));
// Expect that specified headers are accurate.
for (const auto& kv : expected_headers) {
if (kv.second.has_value()) {
std::string actual_value;
EXPECT_THAT(request.headers.GetHeader(kv.first, &actual_value),
Eq(true));
EXPECT_THAT(actual_value, Eq(*kv.second));
} else {
EXPECT_THAT(request.headers.HasHeader(kv.first), Eq(false));
}
}
// Extract request body.
std::string actual_body;
if (request.request_body) {
const std::vector<network::DataElement>* const elements =
request.request_body->elements();
// We only support the simplest body structure.
CHECK(elements && elements->size() == 1 &&
(*elements)[0].type() == network::mojom::DataElementType::kBytes);
actual_body =
std::string((*elements)[0].bytes(), (*elements)[0].length());
}
EXPECT_THAT(actual_body, Eq(expected_body));
// Guaranteed to match the first request based on URL.
loader_factory_.SimulateResponseForPendingRequest(expected_url, response,
response_code);
}
scoped_refptr<network::SharedURLLoaderFactory> AsSharedURLLoaderFactory() {
return shared_loader_factory_;
}
private:
const std::string server_url_prefix_;
network::TestURLLoaderFactory loader_factory_;
scoped_refptr<network::SharedURLLoaderFactory> shared_loader_factory_;
DISALLOW_COPY_AND_ASSIGN(TestServerURLLoaderFactory);
};
// Returns a "canonically" formatted version of a JSON string by parsing and
// then rewriting it.
std::string ReformatJson(const std::string& in) {
const std::unique_ptr<base::Value> json =
base::JSONReader::ReadDeprecated(in);
CHECK(json);
std::string out;
base::JSONWriter::Write(*json, &out);
return out;
}
// Receives the result of an annotation request and writes the result data into
// the given variables.
void ReportResult(base::Optional<mojom::AnnotateImageError>* const error,
std::vector<mojom::Annotation>* const annotations,
mojom::AnnotateImageResultPtr result) {
if (result->which() == mojom::AnnotateImageResult::Tag::ERROR_CODE) {
*error = result->get_error_code();
} else {
// If annotations exists, then it is not empty.
ASSERT_THAT(result->get_annotations(), Not(IsEmpty()));
for (const auto& annotation_ptr : result->get_annotations()) {
annotations->push_back(*annotation_ptr);
}
}
}
} // namespace
// Test that annotation works for one client, and that the cache is populated.
TEST(AnnotatorTest, OcrSuccessAndCache) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor;
// First call performs original image annotation.
{
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(
kImage1Url, kDescLang, processor.GetPtr(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made.
const std::string request =
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID"));
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */, request, kOcrSuccessResponse,
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
ASSERT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(annotations,
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr,
1.0, "Region 1\nRegion 2")));
// Metrics should have been logged for the major actions of the service.
histogram_tester.ExpectUniqueSample(metrics_internal::kCacheHit, false, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kPixelFetchSuccess,
true, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerRequestSize,
request.size() / 1024, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(
metrics_internal::kServerHttpResponseCode, net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerResponseSize,
std::strlen(kOcrSuccessResponse), 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kJsonParseSuccess,
true, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false,
1);
}
// Second call uses cached results.
{
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(
kImage1Url, kDescLang, processor.GetPtr(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Pixels shouldn't be requested.
ASSERT_THAT(processor.callbacks(), IsEmpty());
// Results should have been directly returned without any server call.
ASSERT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(annotations,
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr,
1.0, "Region 1\nRegion 2")));
// Metrics should have been logged for a cache hit.
EXPECT_THAT(histogram_tester.GetAllSamples(metrics_internal::kCacheHit),
UnorderedElementsAre(Bucket(false, 1), Bucket(true, 1)));
}
}
// Test that description annotations are successfully returned.
TEST(AnnotatorTest, DescriptionSuccess) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPtr(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [
{
"type": "CAPTION",
"text": "This is an example image.",
"score": 0.9
},
{
"type": "LABEL",
"text": "Example image",
"score": 1.0
}
]
}
}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
ASSERT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(
annotations,
UnorderedElementsAre(
AnnotatorEq(mojom::AnnotationType::kOcr, 1.0, ""),
AnnotatorEq(mojom::AnnotationType::kCaption, 0.9,
"This is an example image."),
AnnotatorEq(mojom::AnnotationType::kLabel, 1.0, "Example image")));
// Metrics about the description results should have been logged.
histogram_tester.ExpectUniqueSample(
metrics_internal::kImageRequestIncludesDesc, true, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence,
"DescCaption"),
90, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "DescLabel"),
100, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescCaption"),
false, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescLabel"),
false, 1);
}
// Test that the specialized OCR result takes precedence.
TEST(AnnotatorTest, DoubleOcrResult) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPtr(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "Region 1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [
{
"type": "CAPTION",
"text": "This is an example image.",
"score": 0.9
},
{
"type": "OCR",
"text": "R3gi0n I",
"score": 1.0
}
]
}
}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
ASSERT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(annotations,
UnorderedElementsAre(
AnnotatorEq(mojom::AnnotationType::kOcr, 1.0, "Region 1"),
AnnotatorEq(mojom::AnnotationType::kCaption, 0.9,
"This is an example image.")));
// Metrics about the returned results should have been logged.
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence,
"DescCaption"),
90, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "DescOcr"),
100, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescCaption"),
false, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescOcr"), false,
1);
}
// Test that HTTP failure is gracefully handled.
TEST(AnnotatorTest, HttpError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPtr(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
"", net::HTTP_INTERNAL_SERVER_ERROR);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
EXPECT_THAT(error, Eq(mojom::AnnotateImageError::kFailure));
EXPECT_THAT(annotations, IsEmpty());
// Metrics about the HTTP request failure should have been logged.
histogram_tester.ExpectUniqueSample(
metrics_internal::kServerNetError,
net::Error::ERR_HTTP_RESPONSE_CODE_FAILURE, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_INTERNAL_SERVER_ERROR, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kClientResult,
ClientResult::kFailed, 1);
}
// Test that backend failure is gracefully handled.
TEST(AnnotatorTest, BackendError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPtr(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {
"code": 8,
"message": "Resource exhausted"
},
"ocrEngine": {}
},
{
"status": {
"code": 8,
"messages": "Resource exhausted"
},
"descriptionEngine": {}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called
// with an error status.
EXPECT_THAT(error, Eq(mojom::AnnotateImageError::kFailure));
EXPECT_THAT(annotations, IsEmpty());
// Metrics about the backend failure should have been logged.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
8 /* Failed RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
8 /* Failed RPC status */, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kClientResult,
ClientResult::kFailed, 1);
}
// Test that partial results are returned if the OCR backend fails.
TEST(AnnotatorTest, OcrBackendError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPtr(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {
"code": 8,
"message": "Resource exhausted"
},
"ocrEngine": {}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [{
"type": "CAPTION",
"text": "This is an example image.",
"score": 0.9
}]
}
}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
EXPECT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(annotations, UnorderedElementsAre(
AnnotatorEq(mojom::AnnotationType::kCaption, 0.9,
"This is an example image.")));
// Metrics about the partial results should have been logged.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
8 /* Failed RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence,
"DescCaption"),
90, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescCaption"),
false, 1);
}
// Test that partial results are returned if the description backend fails.
TEST(AnnotatorTest, DescriptionBackendError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPtr(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {
"code": 8,
"message": "Resource exhausted"
},
"descriptionEngine": {}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called.
EXPECT_THAT(error, Eq(base::nullopt));
EXPECT_THAT(annotations, UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "1")));
// Metrics about the partial results should have been logged.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
8 /* Failed RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false, 1);
}
// Test that server failure (i.e. nonsense response) is gracefully handled.
TEST(AnnotatorTest, ServerError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPtr(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made; respond with nonsense string.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
"Hello, world!", net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called
// with an error status.
EXPECT_THAT(error, Eq(mojom::AnnotateImageError::kFailure));
EXPECT_THAT(annotations, IsEmpty());
// Metrics about the invalid response format should have been logged.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kJsonParseSuccess,
false, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kClientResult,
ClientResult::kFailed, 1);
}
// Test that adult content returns an error.
TEST(AnnotatorTest, AdultError) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor;
base::Optional<mojom::AnnotateImageError> error;
std::vector<mojom::Annotation> annotations;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPtr(),
base::BindOnce(&ReportResult, &error, &annotations));
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": []
}
},
{
"status": {},
"descriptionEngine": {
"failureReason": "ADULT"
}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// HTTP response should have completed and callback should have been called
// with an error status.
EXPECT_THAT(error, Eq(mojom::AnnotateImageError::kAdult));
EXPECT_THAT(annotations, IsEmpty());
// Metrics about the adult error should have been logged.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kDescFailure,
DescFailureReason::kAdult, 1);
}
// Test that work is reassigned if a processor fails.
TEST(AnnotatorTest, ProcessorFails) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor[3];
base::Optional<mojom::AnnotateImageError> error[3];
std::vector<mojom::Annotation> annotations[3];
for (int i = 0; i < 3; ++i) {
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[i].GetPtr(),
base::BindOnce(&ReportResult, &error[i], &annotations[i]));
}
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for image 1's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
// Make processor 1 fail by returning empty bytes.
std::move(processor[0].callbacks()[0]).Run({}, 0, 0);
processor[0].callbacks().pop_back();
test_task_env.RunUntilIdle();
// Annotator should have asked processor 2 for image 1's pixels.
ASSERT_THAT(processor[0].callbacks(), IsEmpty());
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
// Send back image data.
std::move(processor[1].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request for image 1 should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called all callbacks, but request 1 received an error
// when we returned empty bytes.
ASSERT_THAT(error, ElementsAre(mojom::AnnotateImageError::kFailure,
base::nullopt, base::nullopt));
EXPECT_THAT(annotations[0], IsEmpty());
EXPECT_THAT(annotations[1],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
EXPECT_THAT(annotations[2],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
// Metrics about the pixel fetch failure should have been logged.
EXPECT_THAT(
histogram_tester.GetAllSamples(metrics_internal::kPixelFetchSuccess),
UnorderedElementsAre(Bucket(false, 1), Bucket(true, 1)));
EXPECT_THAT(histogram_tester.GetAllSamples(metrics_internal::kClientResult),
UnorderedElementsAre(
Bucket(static_cast<int32_t>(ClientResult::kFailed), 1),
Bucket(static_cast<int32_t>(ClientResult::kSucceeded), 2)));
}
// Test a case that was previously buggy: when one client requests annotations,
// then fails local processing, then another client makes the same request.
TEST(AnnotatorTest, ProcessorFailedPreviously) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor[2];
base::Optional<mojom::AnnotateImageError> error[2];
std::vector<mojom::Annotation> annotations[2];
// Processor 1 makes a request for annotation of a given image.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[0].GetPtr(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for the image's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
// Make processor 1 fail by returning empty bytes.
std::move(processor[0].callbacks()[0]).Run({}, 0, 0);
processor[0].callbacks().pop_back();
test_task_env.RunUntilIdle();
// Processor 2 makes a request for annotation of the same image.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[1].GetPtr(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 2 for the image's pixels.
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
// Send back image data.
std::move(processor[1].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request for image 1 should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called all callbacks, but request 1 received an error
// when we returned empty bytes.
ASSERT_THAT(error,
ElementsAre(mojom::AnnotateImageError::kFailure, base::nullopt));
EXPECT_THAT(annotations[0], IsEmpty());
EXPECT_THAT(annotations[1],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
}
// Test that work is reassigned if processor dies.
TEST(AnnotatorTest, ProcessorDies) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor[3];
base::Optional<mojom::AnnotateImageError> error[3];
std::vector<mojom::Annotation> annotations[3];
for (int i = 0; i < 3; ++i) {
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[i].GetPtr(),
base::BindOnce(&ReportResult, &error[i], &annotations[i]));
}
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for image 1's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
// Kill processor 1.
processor[0].Reset();
test_task_env.RunUntilIdle();
// Annotator should have asked processor 2 for image 1's pixels.
ASSERT_THAT(processor[0].callbacks(), IsEmpty());
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
// Send back image data.
std::move(processor[1].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// HTTP request for image 1 should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called all callbacks, but request 1 was canceled when
// we reset processor 1.
ASSERT_THAT(error, ElementsAre(mojom::AnnotateImageError::kCanceled,
base::nullopt, base::nullopt));
EXPECT_THAT(annotations[0], IsEmpty());
EXPECT_THAT(annotations[1],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
EXPECT_THAT(annotations[2],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
// Metrics about the client cancelation should have been logged.
EXPECT_THAT(histogram_tester.GetAllSamples(metrics_internal::kClientResult),
UnorderedElementsAre(
Bucket(static_cast<int32_t>(ClientResult::kCanceled), 1),
Bucket(static_cast<int32_t>(ClientResult::kSucceeded), 2)));
}
// Test that multiple concurrent requests are handled in the same batch.
TEST(AnnotatorTest, ConcurrentSameBatch) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
3 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor[3];
base::Optional<mojom::AnnotateImageError> error[3];
std::vector<mojom::Annotation> annotations[3];
// Request OCR for images 1, 2 and 3.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[0].GetPtr(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
annotator.AnnotateImage(
kImage2Url, kDescLang, processor[1].GetPtr(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
annotator.AnnotateImage(
kImage3Url, kDescLang, processor[2].GetPtr(),
base::BindOnce(&ReportResult, &error[2], &annotations[2]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for image 1's pixels, processor
// 2 for image 2's pixels and processor 3 for image 3's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
ASSERT_THAT(processor[2].callbacks(), SizeIs(1));
// Send back image data.
std::move(processor[0].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[0].callbacks().pop_back();
std::move(processor[1].callbacks()[0]).Run({4, 5, 6}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
std::move(processor[2].callbacks()[0]).Run({7, 8, 9}, kDescDim, kDescDim);
processor[2].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// A single HTTP request for all images should have been sent.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */, ReformatJson(kBatchRequest),
kBatchResponse, net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called each callback with its corresponding text or
// failure.
ASSERT_THAT(error, ElementsAre(base::nullopt, base::nullopt,
mojom::AnnotateImageError::kFailure));
EXPECT_THAT(annotations[0], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "1")));
EXPECT_THAT(annotations[1], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "2")));
EXPECT_THAT(annotations[2], IsEmpty());
// Metrics should have been logged for a single server response with multiple
// results included.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 1);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 1);
EXPECT_THAT(histogram_tester.GetAllSamples(base::StringPrintf(
metrics_internal::kAnnotationStatus, "Ocr")),
UnorderedElementsAre(Bucket(8 /* Failed RPC status */, 1),
Bucket(0 /* OK RPC status */, 2)));
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
2);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false, 2);
EXPECT_THAT(histogram_tester.GetAllSamples(metrics_internal::kClientResult),
UnorderedElementsAre(
Bucket(static_cast<int32_t>(ClientResult::kFailed), 1),
Bucket(static_cast<int32_t>(ClientResult::kSucceeded), 2)));
}
// Test that multiple concurrent requests are handled in separate batches.
TEST(AnnotatorTest, ConcurrentSeparateBatches) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
3 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor[2];
base::Optional<mojom::AnnotateImageError> error[2];
std::vector<mojom::Annotation> annotations[2];
// Request OCR for image 1.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[0].GetPtr(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for image 1's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
// Send back image 1 data.
std::move(processor[0].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[0].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// Request OCR for image 2.
annotator.AnnotateImage(
kImage2Url, kDescLang, processor[1].GetPtr(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 2 for image 2's pixels.
ASSERT_THAT(processor[0].callbacks(), IsEmpty());
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
// Send back image 2 data.
std::move(processor[1].callbacks()[0]).Run({4, 5, 6}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
test_task_env.RunUntilIdle();
// Only the HTTP request for image 1 should have been made (the service is
// still waiting to make the batch that will include the request for image
// 2).
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
R"({
"results": [{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {}
}
}
]
}]
})",
net::HTTP_OK);
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// Now the HTTP request for image 2 should have been made.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage2Url, "BAUG")),
R"({
"results": [{
"imageId": "https://www.example.com/image2.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "2",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {}
}
}
]
}]
})",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called each callback with its corresponding text.
ASSERT_THAT(error, ElementsAre(base::nullopt, base::nullopt));
EXPECT_THAT(annotations[0], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "1")));
EXPECT_THAT(annotations[1], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "2")));
// Metrics should have been logged for two server responses.
histogram_tester.ExpectUniqueSample(metrics_internal::kServerNetError,
net::Error::OK, 2);
histogram_tester.ExpectUniqueSample(metrics_internal::kServerHttpResponseCode,
net::HTTP_OK, 2);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 2);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
2);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false, 2);
histogram_tester.ExpectUniqueSample(metrics_internal::kClientResult,
ClientResult::kSucceeded, 2);
}
// Test that work is not duplicated if it is already ongoing.
TEST(AnnotatorTest, DuplicateWork) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor[4];
base::Optional<mojom::AnnotateImageError> error[4];
std::vector<mojom::Annotation> annotations[4];
// First request annotation of the image with processor 1.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[0].GetPtr(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for the image's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
ASSERT_THAT(processor[3].callbacks(), IsEmpty());
// Now request annotation of the image with processor 2.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[1].GetPtr(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
test_task_env.RunUntilIdle();
// Annotator *should not* have asked processor 2 for the image's pixels (since
// processor 1 is already handling that).
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
ASSERT_THAT(processor[3].callbacks(), IsEmpty());
// Get processor 1 to reply with bytes for the image.
std::move(processor[0].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[0].callbacks().pop_back();
test_task_env.RunUntilIdle();
// Now request annotation of the image with processor 3.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[2].GetPtr(),
base::BindOnce(&ReportResult, &error[2], &annotations[2]));
test_task_env.RunUntilIdle();
// Annotator *should not* have asked processor 3 for the image's pixels (since
// it has already has the pixels in the HTTP request queue).
ASSERT_THAT(processor[0].callbacks(), IsEmpty());
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
ASSERT_THAT(processor[3].callbacks(), IsEmpty());
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
// Allow batch HTTP request to be sent off and then request annotation of the
// image with processor 4.
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
EXPECT_THAT(test_url_factory.requests(), SizeIs(1));
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[3].GetPtr(),
base::BindOnce(&ReportResult, &error[3], &annotations[3]));
test_task_env.RunUntilIdle();
// Annotator *should not* have asked processor 4 for the image's pixels (since
// an HTTP request for the image is already in process).
ASSERT_THAT(processor[0].callbacks(), IsEmpty());
ASSERT_THAT(processor[1].callbacks(), IsEmpty());
ASSERT_THAT(processor[2].callbacks(), IsEmpty());
ASSERT_THAT(processor[3].callbacks(), IsEmpty());
// HTTP request for the image should have been made (with bytes obtained from
// processor 1).
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called all callbacks with annotation results.
ASSERT_THAT(error, ElementsAre(base::nullopt, base::nullopt, base::nullopt,
base::nullopt));
EXPECT_THAT(annotations[0],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
EXPECT_THAT(annotations[1],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
EXPECT_THAT(annotations[2],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
EXPECT_THAT(annotations[3],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0,
"Region 1\nRegion 2")));
// Metrics should have been logged for a single pixel fetch.
histogram_tester.ExpectUniqueSample(metrics_internal::kPixelFetchSuccess,
true, 1);
}
// Test that the description engine is not requested for images that violate
// model policy (i.e. are too small or have too-high an aspect ratio).
TEST(AnnotatorTest, DescPolicy) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
3 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor[3];
base::Optional<mojom::AnnotateImageError> error[3];
std::vector<mojom::Annotation> annotations[3];
// Request annotation for images 1, 2 and 3.
annotator.AnnotateImage(
kImage1Url, kDescLang, processor[0].GetPtr(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
annotator.AnnotateImage(
kImage2Url, kDescLang, processor[1].GetPtr(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
annotator.AnnotateImage(
kImage3Url, kDescLang, processor[2].GetPtr(),
base::BindOnce(&ReportResult, &error[2], &annotations[2]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 for image 1's pixels, processor
// 2 for image 2's pixels and processor 3 for image 3's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
ASSERT_THAT(processor[2].callbacks(), SizeIs(1));
// Send back image data.
//
// Image 1 is (just) within policy. Image 2 violates policy because it is too
// small. Image 3 is large enough, but violates policy because of its aspect
// ratio.
std::move(processor[0].callbacks()[0])
.Run({1, 2, 3}, Annotator::kDescMinDimension,
Annotator::kDescMinDimension);
processor[0].callbacks().pop_back();
std::move(processor[1].callbacks()[0])
.Run({4, 5, 6}, Annotator::kDescMinDimension,
Annotator::kDescMinDimension - 1);
processor[1].callbacks().pop_back();
std::move(processor[2].callbacks()[0])
.Run({7, 8, 9},
static_cast<int32_t>(Annotator::kDescMinDimension *
Annotator::kDescMaxAspectRatio) +
1,
Annotator::kDescMinDimension);
processor[2].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// A single HTTP request for all images should have been sent.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
// Only image 1 includes a description request (as the other two violate
// one of the policies).
ReformatJson(R"(
{
"imageRequests": [
{
"imageId": "https://www.example.com/image3.jpg",
"imageBytes": "BwgJ",
"engineParameters": [
{"ocrParameters": {}}
]
},
{
"imageId": "https://www.example.com/image2.jpg",
"imageBytes": "BAUG",
"engineParameters": [
{"ocrParameters": {}}
]
},
{
"imageId": "https://www.example.com/image1.jpg",
"imageBytes": "AQID",
"engineParameters": [
{"ocrParameters": {}},
{"descriptionParameters": {}}
]
}
]
}
)"),
R"(
{
"results": [
{
"imageId": "https://www.example.com/image2.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "2",
"confidenceScore": 1.0
}]
}]
}
}
]
},
{
"imageId": "https://www.example.com/image1.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [{
"type": "CAPTION",
"text": "This is an example image.",
"score": 1.0
}]
}
}
}
]
},
{
"imageId": "https://www.example.com/image3.jpg",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "3",
"confidenceScore": 1.0
}]
}]
}
}
]
}
]
}
)",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called each callback with its corresponding results.
ASSERT_THAT(error, ElementsAre(base::nullopt, base::nullopt, base::nullopt));
EXPECT_THAT(
annotations[0],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0, "1"),
AnnotatorEq(mojom::AnnotationType::kCaption, 1.0,
"This is an example image.")));
EXPECT_THAT(annotations[1], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "2")));
EXPECT_THAT(annotations[2], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "3")));
// Metrics should have been logged for the 3 OCR results and 1 description
// result.
EXPECT_THAT(histogram_tester.GetAllSamples(
metrics_internal::kImageRequestIncludesDesc),
UnorderedElementsAre(Bucket(false, 2), Bucket(true, 1)));
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Ocr"),
0 /* OK RPC status */, 3);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationStatus, "Desc"),
0 /* OK RPC status */, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence, "Ocr"), 100,
3);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationConfidence,
"DescCaption"),
100, 1);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "Ocr"), false, 3);
histogram_tester.ExpectUniqueSample(
base::StringPrintf(metrics_internal::kAnnotationEmpty, "DescCaption"),
false, 1);
}
// Test that description language preferences are sent to the server.
TEST(AnnotatorTest, DescLanguage) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
data_decoder::TestDataDecoderService test_dd_service;
base::HistogramTester histogram_tester;
Annotator annotator(
GURL(kTestServerUrl), std::string() /* api_key */, kThrottle,
3 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(), test_dd_service.connector());
TestImageProcessor processor[3];
base::Optional<mojom::AnnotateImageError> error[3];
std::vector<mojom::Annotation> annotations[3];
// Request annotation for one image in two languages, and one other image in
// one language.
annotator.AnnotateImage(
kImage1Url, "fr", processor[0].GetPtr(),
base::BindOnce(&ReportResult, &error[0], &annotations[0]));
annotator.AnnotateImage(
kImage1Url, "en-AU", processor[1].GetPtr(),
base::BindOnce(&ReportResult, &error[1], &annotations[1]));
annotator.AnnotateImage(
kImage2Url, "en-US", processor[2].GetPtr(),
base::BindOnce(&ReportResult, &error[2], &annotations[2]));
test_task_env.RunUntilIdle();
// Annotator should have asked processor 1 and 2 for image 1's pixels and
// processor 3 for image 2's pixels.
ASSERT_THAT(processor[0].callbacks(), SizeIs(1));
ASSERT_THAT(processor[1].callbacks(), SizeIs(1));
ASSERT_THAT(processor[2].callbacks(), SizeIs(1));
// Send back image data. Image 2 is out of policy.
std::move(processor[0].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[0].callbacks().pop_back();
std::move(processor[1].callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor[1].callbacks().pop_back();
std::move(processor[2].callbacks()[0])
.Run({4, 5, 6}, Annotator::kDescMinDimension - 1,
Annotator::kDescMinDimension);
processor[2].callbacks().pop_back();
test_task_env.RunUntilIdle();
// No request should be sent yet (because service is waiting to batch up
// multiple requests).
EXPECT_THAT(test_url_factory.requests(), IsEmpty());
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
// A single HTTP request for all images should have been sent.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {} /* expected_headers */,
// Image requests should include the preferred language in their image IDs
// and description parameters (except for image 2 which should not include
// description parameters).
ReformatJson(R"(
{
"imageRequests": [
{
"imageId": "https://www.example.com/image2.jpg en-US",
"imageBytes": "BAUG",
"engineParameters": [
{"ocrParameters": {}}
]
},
{
"imageId": "https://www.example.com/image1.jpg en-AU",
"imageBytes": "AQID",
"engineParameters": [
{"ocrParameters": {}},
{
"descriptionParameters": {
"preferredLanguages": ["en-AU"]
}
}
]
},
{
"imageId": "https://www.example.com/image1.jpg fr",
"imageBytes": "AQID",
"engineParameters": [
{"ocrParameters": {}},
{
"descriptionParameters": {
"preferredLanguages": ["fr"]
}
}
]
}
]
}
)"),
R"(
{
"results": [
{
"imageId": "https://www.example.com/image1.jpg en-AU",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [{
"type": "CAPTION",
"text": "This is an example image.",
"score": 1.0
}]
}
}
}
]
},
{
"imageId": "https://www.example.com/image1.jpg fr",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "1",
"confidenceScore": 1.0
}]
}]
}
},
{
"status": {},
"descriptionEngine": {
"descriptionList": {
"descriptions": [{
"type": "CAPTION",
"text": "Ceci est un exemple d'image.",
"score": 1.0
}]
}
}
}
]
},
{
"imageId": "https://www.example.com/image2.jpg en-US",
"engineResults": [
{
"status": {},
"ocrEngine": {
"ocrRegions": [{
"words": [{
"detectedText": "2",
"confidenceScore": 1.0
}]
}]
}
}
]
}
]
}
)",
net::HTTP_OK);
test_task_env.RunUntilIdle();
// Annotator should have called each callback with its corresponding results.
ASSERT_THAT(error, ElementsAre(base::nullopt, base::nullopt, base::nullopt));
EXPECT_THAT(
annotations[0],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0, "1"),
AnnotatorEq(mojom::AnnotationType::kCaption, 1.0,
"Ceci est un exemple d'image.")));
EXPECT_THAT(
annotations[1],
UnorderedElementsAre(AnnotatorEq(mojom::AnnotationType::kOcr, 1.0, "1"),
AnnotatorEq(mojom::AnnotationType::kCaption, 1.0,
"This is an example image.")));
EXPECT_THAT(annotations[2], UnorderedElementsAre(AnnotatorEq(
mojom::AnnotationType::kOcr, 1.0, "2")));
}
// Test that the specified API key is sent, but only to Google-associated server
// domains.
TEST(AnnotatorTest, ApiKey) {
base::test::TaskEnvironment test_task_env(
base::test::TaskEnvironment::TimeSource::MOCK_TIME);
data_decoder::TestDataDecoderService test_dd_service;
// A call to a secure Google-owner server URL should include the specified API
// key.
{
TestServerURLLoaderFactory test_url_factory(
"https://ia-pa.googleapis.com/v1/");
Annotator annotator(GURL(kTestServerUrl), "my_api_key", kThrottle,
1 /* batch_size */, 1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
test_dd_service.connector());
TestImageProcessor processor;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPtr(),
base::DoNothing());
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made with the API key included.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {{Annotator::kGoogApiKeyHeader, "my_api_key"}},
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
}
// A call to a Google-owned server URL should not include the API key if the
// requests are made insecurely.
{
// Note: not HTTPS.
TestServerURLLoaderFactory test_url_factory(
"http://ia-pa.googleapis.com/v1/");
Annotator annotator(GURL("http://ia-pa.googleapis.com/v1/annotation"),
"my_api_key", kThrottle, 1 /* batch_size */,
1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
test_dd_service.connector());
TestImageProcessor processor;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPtr(),
base::DoNothing());
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made without the API key included.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {{Annotator::kGoogApiKeyHeader, base::nullopt}},
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
}
// A call to a non-Google-owned URL should not include the API key.
{
TestServerURLLoaderFactory test_url_factory("https://datascraper.com/");
Annotator annotator(GURL("https://datascraper.com/annotation"),
"my_api_key", kThrottle, 1 /* batch_size */,
1.0 /* min_ocr_confidence */,
test_url_factory.AsSharedURLLoaderFactory(),
test_dd_service.connector());
TestImageProcessor processor;
annotator.AnnotateImage(kImage1Url, kDescLang, processor.GetPtr(),
base::DoNothing());
test_task_env.RunUntilIdle();
// Annotator should have asked processor for pixels.
ASSERT_THAT(processor.callbacks(), SizeIs(1));
// Send back image data.
std::move(processor.callbacks()[0]).Run({1, 2, 3}, kDescDim, kDescDim);
processor.callbacks().pop_back();
test_task_env.FastForwardBy(base::TimeDelta::FromSeconds(1));
test_task_env.RunUntilIdle();
// HTTP request should have been made without the API key included.
test_url_factory.ExpectRequestAndSimulateResponse(
"annotation", {{Annotator::kGoogApiKeyHeader, base::nullopt}},
ReformatJson(base::StringPrintf(kTemplateRequest, kImage1Url, "AQID")),
kOcrSuccessResponse, net::HTTP_OK);
}
}
} // namespace image_annotation
| [
"huhibrowser@gmail.com"
] | huhibrowser@gmail.com |
b974402a2c5f40cf2ef56e34330d9259baca94b5 | 8cd51af419cd7dda12e0ece4ab37c1987f69bb51 | /src/BlueMotor.cpp | c6071a557e96ff48430c5f489bd31724327a540e | [] | no_license | sandman-code/Lab6 | 900c911491a5cf95b76d022734387082e3479e82 | 528c4264365773baed11bf644a943b905fed2486 | refs/heads/main | 2023-04-02T14:55:46.551762 | 2021-03-27T19:48:54 | 2021-03-27T19:48:54 | 346,200,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,073 | cpp | #include "BlueMotor.h"
#include <Romi32U4.h>
#include <PID.h>
// variables for the counter of controlling the encoder
const char X = 5;
int errorCount = 0;
int oldValue = 0;
long count = 0;
const int DBdiff = 40;
char encoderArray[4][4] = {
{0, 1, -1, X},
{-1, 0, X, 0},
{1, X, 0, -1},
{X, -1, 1, 0}};
// the differnt sates for the move to function
enum States
{
Start,
clockwise,
counterclockwise,
stop
} armState;
PID controlPID(400.0, -400.0, 25, 20, 10);
//initilizes all the pins and the interupts
void Bluemotor::initilize()
{ //outputs and inputs to controller the blue motor
pinMode(PWM, OUTPUT);
pinMode(AIN1, OUTPUT);
pinMode(AIN2, OUTPUT);
pinMode(ENCA, INPUT);
pinMode(ENCB, INPUT);
motors.setEfforts(0, 0);
//interupts to count the encoder
pinMode(2, INPUT);
pinMode(3, INPUT);
attachInterrupt(digitalPinToInterrupt(2), isr, CHANGE);
attachInterrupt(digitalPinToInterrupt(3), isr, CHANGE);
//initlize the differnt states
armState = Start;
};
//The intrupt service routune
void Bluemotor::isr()
{ //shifts the bits left deping on the reading of the second pin, looks up the value in the array
int newValue = (digitalRead(3) << 1) | digitalRead(2);
char value = encoderArray[oldValue][newValue];
//if the number changed add or subtract, or if the value did not change add add one to errorcount
if (value == X)
{
errorCount++;
}
else
{
count -= value;
}
oldValue = newValue;
}
//will change the mover the motor clockwiseor counterclockwise and adjust the speed
void Bluemotor::setEffort(int effort, bool clockwise)
{
//turn clockwise
if (clockwise)
{
digitalWrite(AIN1, HIGH);
digitalWrite(AIN2, LOW);
}
//do not turn
else if (effort == 0)
{
digitalWrite(AIN1, LOW);
digitalWrite(AIN2, LOW);
}
//turn counter clockwise
else
{
digitalWrite(AIN1, LOW);
digitalWrite(AIN2, HIGH);
}
//validaadates the effort number and sends a PWM to the motor
int value = constrain(effort, 0, 400);
OCR1C = value;
}
//sorts the inital effort for direction and speed
void Bluemotor::setEffort(int effort)
{
//turn clockwise
if (effort < 0)
{
setEffort(-effort, true);
}
//turn counterclockwise or stop
else
{
setEffort(effort, false);
}
}
void Bluemotor::setEffortWithoutDB(int effort)
{
//turn clockwise
if (effort < 0)
{
setEffortWithoutDB(-effort, true);
}
//turn counterclockwise or stop
else
{
setEffortWithoutDB(effort, false);
}
}
//reports back the position of the motor
long Bluemotor::getPosition()
{
return count;
}
//resets the position count of the encouder to count that as the new base position
void Bluemotor::reset()
{
count = 0;
}
void Bluemotor::setEffortWithoutDB(int effort, bool clockwise)
{
//turn clockwise
if (clockwise)
{
digitalWrite(AIN1, HIGH);
digitalWrite(AIN2, LOW);
}
//do not turn
else if (effort == 0)
{
digitalWrite(AIN1, LOW);
digitalWrite(AIN2, LOW);
}
//turn counter clockwise
else
{
digitalWrite(AIN1, LOW);
digitalWrite(AIN2, HIGH);
}
//validaadates the effort number and sends a PWM to the motor
int value = constrain(effort + DBdiff, 0, 400);
Serial.println(value);
OCR1C = value;
}
//moves the mover a certion amount depening on the position input
void Bluemotor::moveTo(long position)
{ //initlizes a Bluemotor varible and grabs the current posiotn of the encoder
setEffortWithoutDB(controlPID.calculate(position, getPosition()));
}
void Bluemotor::goToRelease()
{
moveTo(7250);
}
void Bluemotor::goTo45()
{
moveTo(3590);
}
void Bluemotor::goTo25()
{
moveTo(7260);
}
void Bluemotor::home()
{
Bluemotor blue;
if (digitalRead(limit))
blue.setEffort(0);
else
{
blue.setEffort(-200);
}
count = 0;
} | [
"cade3217@gmail.com"
] | cade3217@gmail.com |
1e0bce8126a319655c5c70cae2fbdca49911dee8 | e4355967555857fd536787dce39ca30426ffa702 | /YouLe/You_系统模块/系统模块/辅助工具/视频服务/Include/IniFile.cpp | 22747af4885b20cb9485639317482683d736d85c | [] | no_license | herox25000/oathx-ogrex-editor | f0fd6044f8065db9cb50a80376e52f502734e877 | f645c7997f27e11a9063a0d352accd98a474cef1 | refs/heads/master | 2020-12-24T14:35:34.912603 | 2013-08-24T06:20:06 | 2013-08-24T06:20:06 | 32,935,652 | 6 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 1,415 | cpp | #include "StdAfx.h"
#include "IniFile.h"
CIniFile::CIniFile(void)
{
ZeroMemory( m_FileName, sizeof(m_FileName) );
}
CIniFile::~CIniFile(void)
{
}
void CIniFile::Load( LPCTSTR FileName )
{
lstrcpy( m_FileName, FileName );
}
int CIniFile::GetInt(LPCTSTR pszSectionName, LPCTSTR pszKeyName)
{
return GetPrivateProfileInt(pszSectionName, pszKeyName, 0, m_FileName);
}
int CIniFile::SetInt(LPCTSTR pszSectionName, LPCTSTR pszKeyName, int nValue)
{
TCHAR szInt[10];
wsprintf(szInt, _T("%d"), nValue);
int err = WritePrivateProfileString(pszSectionName, pszKeyName, szInt, m_FileName);
err = GetLastError();
return 0;
}
int CIniFile::GetString(LPCTSTR pszSectionName, LPCTSTR pszKeyName, LPTSTR pszBuffer, int nLen)
{
return GetPrivateProfileString(pszSectionName, pszKeyName, NULL, pszBuffer, nLen, m_FileName);
}
/*
int CIniFile::GetString(CString strSectionName, CString strKeyName, CString &strBuffer,int nLen)
{
char *pszBuffer = new char[nLen];
int n = GetPrivateProfileString(strSectionName, strKeyName, NULL, pszBuffer, nLen, m_FileName);
if(n<=0)
strBuffer = "";
else
strBuffer = pszBuffer;
delete []pszBuffer;
return n;
}
*/
int CIniFile::SetString(LPCTSTR pszSectionName, LPCTSTR pszKeyName, LPCTSTR pszBuffer)
{
return WritePrivateProfileString(pszSectionName, pszKeyName, pszBuffer,m_FileName);
} | [
"ydxl2011@yahoo.cn@a113e17c-5e0c-ebba-c532-3ad10810a225"
] | ydxl2011@yahoo.cn@a113e17c-5e0c-ebba-c532-3ad10810a225 |
10031c2a3d5684eaad7817d0ff0a5d4d25506aed | 9d199804ea3aca63762a6779570cfb482c605834 | /DigitalSimulator/sources/Application/Objects/plugin/dll/SimpleType/ObjectPluginManager.cpp | 52e19eda95eec62bbea5cc4034cee386c045d761 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | hupfdule/DigitalSimulator | 6a9a9e43f2f6a9bab620b0190e8991b6c55e54bb | 3b789dcae9adb977bbed681c4459e74bf5f4bf62 | refs/heads/master | 2020-06-20T06:17:40.835154 | 2015-05-24T06:37:48 | 2015-05-24T06:37:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,440 | cpp | /* NO WARRANTY
*
* BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO
* WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
* LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS
* AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO
* THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD
* THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
* NECESSARY SERVICING, REPAIR OR CORRECTION.
*
* IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
* WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY
* AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES,
* INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
* DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
* (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
* RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES
* OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
* PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGES.
*/
#pragma warning(disable : 4786)
#include "stdafx.h"
#include "ObjectPluginManager.h"
#include "Application\Debug\LogManager.h"
DynamicLibraryMap ObjectPluginManager::m_pluginMap;
#include "Application\Objects\buildin\digital\ElectricNodeContext.h"
#pragma TODO("Einen Dialog anlegen welcher alle geladenen PlugIns anzeigt (mit Attribute)")
//----------------------------------------------------------------------------
void ObjectPluginManager::registerPlugin(CString id, DynamicLibrary *lib){
//----------------------------------------------------------------------------
PROC_TRACE;
m_pluginMap[id]=lib;
}
//----------------------------------------------------------------------------
void ObjectPluginManager::removePlugin(CString){
//----------------------------------------------------------------------------
PROC_TRACE;
#pragma TODO("function 'ObjectPluginManager::removePlugin(CString)' not implemented")
}
//----------------------------------------------------------------------------
StringArray ObjectPluginManager::getAllPlugins(){
//----------------------------------------------------------------------------
PROC_TRACE;
StringArray x;
DynamicLibraryMap::iterator theIterator;
theIterator = m_pluginMap.begin();
while(theIterator != m_pluginMap.end()){
x.push_back((LPCSTR)(*theIterator).first);
theIterator++;
}
return x;
}
//----------------------------------------------------------------------------
bool ObjectPluginManager::isObjectNameFree(CString name){
//----------------------------------------------------------------------------
PROC_TRACE;
DynamicLibraryMap::iterator theIterator;
CString item;
CString group;
CElectricNodeContext* pContext;
POSITION pos = g_contextMap->GetStartPosition();
while( pos != NULL ) {
g_contextMap->GetNextAssoc( pos, item, pContext );
if(pContext && item!=CString("OBJ_GENERIC") && item==name){
return false;
}
}
return true;
}
//----------------------------------------------------------------------------
void ObjectPluginManager::clear(){
//----------------------------------------------------------------------------
PROC_TRACE;
DynamicLibraryMap::iterator theIterator;
theIterator = m_pluginMap.begin();
while(theIterator != m_pluginMap.end()){
((*theIterator).second)->Unload();
theIterator++;
}
m_pluginMap.clear();
}
//----------------------------------------------------------------------------
IPluginBase* ObjectPluginManager::createInstance(CString contextName, CString inter/*face*/){
//----------------------------------------------------------------------------
PROC_TRACE;
IPluginBase *in = NULL;;
if(contextName != ""){
DynamicLibrary *lib = m_pluginMap[contextName];
if(lib!=NULL){
if (lib->CreateInterface(inter,reinterpret_cast<IPluginBase**>(&in))){
// hipp
}
else{
in = NULL;
}
}
}
return in;
}
| [
"a.herz@freegroup.de"
] | a.herz@freegroup.de |
7aa8a842ec1fb6184a881afc0bb60155f13c0636 | b8231d5bb8341e3067051c812f284254b13e0b1b | /Algorithms/513.Find_Bottom_Left_Tree_Value.cpp | 635f15b89abac22bad6bc765b29f480613ce1e0a | [] | no_license | icoty/LeetCode | 8ceb401841aa2b3cbcfbab907af5ac26aa3fd064 | 38083236ebfc197c77ff2a85b5e42834b8916320 | refs/heads/master | 2020-04-05T14:40:54.811234 | 2019-04-14T05:04:29 | 2019-04-14T05:04:29 | 156,935,383 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,341 | cpp | #include "AllInclude.h"
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
int ret;
while(!q.empty()){
ret = q.front()->val;
int len = q.size();
for(int i = 0; i < len; ++i){
if(q.front()->left)
q.push(q.front()->left);
if(q.front()->right)
q.push(q.front()->right);
q.pop();
}
}
return ret;
}
};
void trimLeftTrailingSpaces(string &input) {
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
return !isspace(ch);
}));
}
void trimRightTrailingSpaces(string &input) {
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
return !isspace(ch);
}).base(), input.end());
}
TreeNode* stringToTreeNode(string input) {
trimLeftTrailingSpaces(input);
trimRightTrailingSpaces(input);
input = input.substr(1, input.length() - 2);
if (!input.size()) {
return nullptr;
}
string item;
stringstream ss;
ss.str(input);
getline(ss, item, ',');
TreeNode* root = new TreeNode(stoi(item));
queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
while (true) {
TreeNode* node = nodeQueue.front();
nodeQueue.pop();
if (!getline(ss, item, ',')) {
break;
}
trimLeftTrailingSpaces(item);
if (item != "null") {
int leftNumber = stoi(item);
node->left = new TreeNode(leftNumber);
nodeQueue.push(node->left);
}
if (!getline(ss, item, ',')) {
break;
}
trimLeftTrailingSpaces(item);
if (item != "null") {
int rightNumber = stoi(item);
node->right = new TreeNode(rightNumber);
nodeQueue.push(node->right);
}
}
return root;
}
int main() {
string line;
while (getline(cin, line)) {
TreeNode* root = stringToTreeNode(line);
int ret = Solution().findBottomLeftValue(root);
string out = to_string(ret);
cout << out << endl;
}
return 0;
}
| [
"icoty.yangy@gmail.com"
] | icoty.yangy@gmail.com |
59f27268aa051284c4f2168af91a1ded1058e93f | 42aaa7f06f8c7a6bd5e7691ccaa4150dbe2c7160 | /src/md5.cpp | b3eba2c7abd76e2b59e4954c161807375d8a3cd2 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | OatBran/FFNx | a19a26b8f2c94bc53cb4e0c28d25bb1712bed0be | 8053c85e3f1b2e64f327f5ddaa09fe8637a85dae | refs/heads/master | 2022-07-12T00:19:54.289987 | 2020-05-07T07:23:22 | 2020-05-07T07:23:22 | 261,897,276 | 0 | 0 | MIT | 2020-05-06T22:58:52 | 2020-05-06T22:58:52 | null | UTF-8 | C++ | false | false | 11,421 | cpp | /* MD5
converted to C++ class by Frank Thilo (thilo@unix-ag.org)
for bzflag (http://www.bzflag.org)
based on:
md5.h and md5.c
reference implemantion of RFC 1321
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
/* interface header */
#include "md5.h"
/* system implementation headers */
#include <cstdio>
// Constants for MD5Transform routine.
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
///////////////////////////////////////////////
// F, G, H and I are basic MD5 functions.
inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) {
return x & y | ~x & z;
}
inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) {
return x & z | y & ~z;
}
inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) {
return x ^ y ^ z;
}
inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) {
return y ^ (x | ~z);
}
// rotate_left rotates x left n bits.
inline MD5::uint4 MD5::rotate_left(uint4 x, int n) {
return (x << n) | (x >> (32 - n));
}
// FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
// Rotation is separate from addition to prevent recomputation.
inline void MD5::FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
a = rotate_left(a + F(b, c, d) + x + ac, s) + b;
}
inline void MD5::GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
a = rotate_left(a + G(b, c, d) + x + ac, s) + b;
}
inline void MD5::HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
a = rotate_left(a + H(b, c, d) + x + ac, s) + b;
}
inline void MD5::II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
a = rotate_left(a + I(b, c, d) + x + ac, s) + b;
}
//////////////////////////////////////////////
// default ctor, just initailize
MD5::MD5()
{
init();
}
//////////////////////////////////////////////
// nifty shortcut ctor, compute MD5 for string and finalize it right away
MD5::MD5(const std::string& text)
{
init();
update(text.c_str(), text.length());
finalize();
}
//////////////////////////////
void MD5::init()
{
finalized = false;
count[0] = 0;
count[1] = 0;
// load magic initialization constants.
state[0] = 0x67452301;
state[1] = 0xefcdab89;
state[2] = 0x98badcfe;
state[3] = 0x10325476;
}
MD5::MD5(char* Input, long length)
{
init();
update(Input, length);
finalize();
}
MD5::MD5(unsigned char* Input, long length)
{
init();
update(Input, length);
finalize();
}
//////////////////////////////
// decodes input (unsigned char) into output (uint4). Assumes len is a multiple of 4.
void MD5::decode(uint4 output[], const uint1 input[], size_type len)
{
for (unsigned int i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((uint4)input[j]) | (((uint4)input[j + 1]) << 8) |
(((uint4)input[j + 2]) << 16) | (((uint4)input[j + 3]) << 24);
}
//////////////////////////////
// encodes input (uint4) into output (unsigned char). Assumes len is
// a multiple of 4.
void MD5::encode(uint1 output[], const uint4 input[], size_type len)
{
for (size_type i = 0, j = 0; j < len; i++, j += 4) {
output[j] = input[i] & 0xff;
output[j + 1] = (input[i] >> 8) & 0xff;
output[j + 2] = (input[i] >> 16) & 0xff;
output[j + 3] = (input[i] >> 24) & 0xff;
}
}
//////////////////////////////
// apply MD5 algo on a block
void MD5::transform(const uint1 block[blocksize])
{
uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
decode(x, block, blocksize);
/* Round 1 */
FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */
FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */
FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */
FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */
FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */
FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */
FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */
FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */
FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */
FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */
FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */
GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */
GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */
GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */
GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */
GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */
GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */
GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */
GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */
GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */
GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */
HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */
HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */
HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */
HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */
HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */
HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */
HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */
HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */
HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */
II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */
II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */
II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */
II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */
II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */
II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */
II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */
II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */
II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
// Zeroize sensitive information.
memset(x, 0, sizeof x);
}
//////////////////////////////
// MD5 block update operation. Continues an MD5 message-digest
// operation, processing another message block
void MD5::update(const unsigned char input[], size_type length)
{
// compute number of bytes mod 64
size_type index = count[0] / 8 % blocksize;
// Update number of bits
if ((count[0] += (length << 3)) < (length << 3))
count[1]++;
count[1] += (length >> 29);
// number of bytes we need to fill in buffer
size_type firstpart = 64 - index;
size_type i;
// transform as many times as possible.
if (length >= firstpart)
{
// fill buffer first, transform
memcpy(&buffer[index], input, firstpart);
transform(buffer);
// transform chunks of blocksize (64 bytes)
for (i = firstpart; i + blocksize <= length; i += blocksize)
transform(&input[i]);
index = 0;
}
else
i = 0;
// buffer remaining input
memcpy(&buffer[index], &input[i], length - i);
}
//////////////////////////////
// for convenience provide a verson with signed char
void MD5::update(const char input[], size_type length)
{
update((const unsigned char*)input, length);
}
//////////////////////////////
// MD5 finalization. Ends an MD5 message-digest operation, writing the
// the message digest and zeroizing the context.
MD5& MD5::finalize()
{
static unsigned char padding[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
if (!finalized) {
// Save number of bits
unsigned char bits[8];
encode(bits, count, 8);
// pad out to 56 mod 64.
size_type index = count[0] / 8 % 64;
size_type padLen = (index < 56) ? (56 - index) : (120 - index);
update(padding, padLen);
// Append length (before padding)
update(bits, 8);
// Store state in digest
encode(digest, state, 16);
// Zeroize sensitive information.
memset(buffer, 0, sizeof buffer);
memset(count, 0, sizeof count);
finalized = true;
}
return *this;
}
//////////////////////////////
// return hex representation of digest as string
std::string MD5::hexdigest() const
{
if (!finalized)
return "";
char buf[33];
for (int i = 0; i < 16; i++)
sprintf(buf + i * 2, "%02x", digest[i]);
buf[32] = 0;
return std::string(buf);
}
//////////////////////////////
std::ostream& operator<<(std::ostream& out, MD5 md5)
{
return out << md5.hexdigest();
}
//////////////////////////////
std::string md5(const std::string str)
{
MD5 md5 = MD5(str);
return md5.hexdigest();
}
std::string md5(char* Input, long length)
{
MD5 md5 = MD5(Input, length);
return md5.hexdigest();
}
| [
"info@julianxhokaxhiu.com"
] | info@julianxhokaxhiu.com |
371356a02a0ecbd581e1e5b800e341aa30d6115f | 323379c8ea06b5527d5a41ceb75e11b40fe3bc60 | /include/daface_det.h | 796ee4b6cc53b56c273590153307ee40f1ace79a | [] | no_license | LHQ0308/DAFace | bce8d43dac811ccfd5554ada986bda81e657ee18 | 3401e9e6804f705c548b99cee195b930d24152df | refs/heads/master | 2020-04-27T23:36:23.634854 | 2017-06-05T15:09:26 | 2017-06-05T15:09:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | h | /******************************************************************************
* FileName: dafece_det.h
* Author: binLearning
* Version: 1.0.0
*
* Description: use seeta-face to detect face region & 5 facial points
*****************************************************************************/
#ifndef _DAFACE_DET_H_
#define _DAFACE_DET_H_
#include <string>
void DafaceDet(std::string dir_src, std::string dir_dst);
#endif
| [
"binLearning@163.com"
] | binLearning@163.com |
d63ff4bbfd799ec498e73745a4c865cf4d09ebe4 | a0b0eb383ecfeaeed3d2b0271657a0c32472bf8e | /lydsy/3289.cpp | d9c1a338639d27b15797ec4a29f3faa512fe0c45 | [
"Apache-2.0"
] | permissive | tangjz/acm-icpc | 45764d717611d545976309f10bebf79c81182b57 | f1f3f15f7ed12c0ece39ad0dd044bfe35df9136d | refs/heads/master | 2023-04-07T10:23:07.075717 | 2022-12-24T15:30:19 | 2022-12-26T06:22:53 | 13,367,317 | 53 | 20 | Apache-2.0 | 2022-12-26T06:22:54 | 2013-10-06T18:57:09 | C++ | UTF-8 | C++ | false | false | 1,351 | cpp | #include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 50001;
int n, q, a[maxn], tot, que[maxn], sqn, bit[maxn], L, R, tmp, ans[maxn];
struct Query
{
int id, l, r;
bool operator < (const Query &t) const
{
if(l / sqn != t.l / sqn)
return l < t.l;
return r < t.r;
}
} Q[maxn];
void add(int x, int v)
{
for( ; x <= tot; x += x & -x)
bit[x] += v;
}
int sum(int x)
{
int ret = 0;
for( ; x > 0; x -= x & -x)
ret += bit[x];
return ret;
}
int main()
{
scanf("%d", &n);
sqn = sqrt(n + 0.1);
for(int i = 1; i <= n; ++i)
{
scanf("%d", a + i);
que[tot++] = a[i];
}
sort(que, que + tot);
tot = unique(que, que + tot) - que;
for(int i = 1; i <= n; ++i)
a[i] = lower_bound(que, que + tot, a[i]) - que + 1;
scanf("%d", &q);
for(int i = 0; i < q; ++i)
{
Q[i].id = i;
scanf("%d%d", &Q[i].l, &Q[i].r);
}
sort(Q, Q + q);
L = 1;
for(int i = 0; i < q; ++i)
{
for( ; L < Q[i].l; ++L)
{
tmp -= sum(a[L] - 1);
add(a[L], -1);
}
for( ; L > Q[i].l; --L)
{
tmp += sum(a[L - 1] - 1);
add(a[L - 1], 1);
}
for( ; R < Q[i].r; ++R)
{
tmp += R - L + 1 - sum(a[R + 1]);
add(a[R + 1], 1);
}
for( ; R > Q[i].r; --R)
{
tmp -= R - L + 1 - sum(a[R]);
add(a[R], -1);
}
ans[Q[i].id] = tmp;
}
for(int i = 0; i < q; ++i)
printf("%d\n", ans[i]);
return 0;
}
| [
"t251346744@gmail.com"
] | t251346744@gmail.com |
1cd156015f91f7919303425e309add6d39bf7546 | 8ae31e5db1f7c25b6ce1c708655ab55c15dde14e | /比赛/学校/2019-7-8测试/2.画长方形1/rectangle1.cpp | cbebb9a43965ff11af2ee982e498cfeebcc192f2 | [] | no_license | LeverImmy/Codes | 99786afd826ae786b5024a3a73c8f92af09aae5d | ca28e61f55977e5b45d6731bc993c66e09f716a3 | refs/heads/master | 2020-09-03T13:00:29.025752 | 2019-12-16T12:11:23 | 2019-12-16T12:11:23 | 219,466,644 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | cpp | #include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <cctype>
#define rgi register int
#define il inline
#define ll long long
using namespace std;
il int read()
{
rgi x = 0, f = 0, ch;
while(!isdigit(ch = getchar())) f |= ch == '-';
while(isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return f ? -x : x;
}
const char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int main()
{
int n = 25, m = 18;
for(rgi i = 1; i <= n; ++i)
{
for(rgi j = 1; j <= m; ++j)
{
if(j >= i)
{
printf("%c", alpha[j - i]);
}
else
printf("%c", alpha[i - j]);
}
puts("");
}
return 0;
}
| [
"506503360@qq.com"
] | 506503360@qq.com |
6d9487cc0a43f7e3be51a405efd00cf272cda969 | 671a050aa02e80543218dfd739a63109cabe17a9 | /Graph/BellmanFord.cpp | a5c06a6f87a6c41aa64897a548423f924eb67071 | [] | no_license | SooKim1110/algorithm-for-tests | 83fcb701caa75ad03b4a4f375fa002761810c713 | 0161703768cd3b050447e4f2b021cb19e3725fc6 | refs/heads/master | 2023-08-17T11:11:27.560180 | 2021-10-07T04:30:50 | 2021-10-07T04:30:50 | 291,279,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,808 | cpp | // 문제 출처 https://www.acmicpc.net/problem/11657
// 난이도: ***
// < 타임머신 >
// 문제 요약: 1번 도시에서 나머지 도시로 가는 가장 빠른 시간을 구하기 (음수 간선 존재)
// 주의점
// 1) 벨만포드 - O(VE) (O(V^3)) 모든 간선을 확인하는 것을 n-1번 반복. 최대 n-1 개의 간선을 거쳐야 최소 거리를 구할 수 있으므로.
// 2) 다익스트라와 달리 음수 간선이 존재해도 된다(다익스트라는 그리디 방식이므로 안됨.). 하지만 비효율적.
// 3) 음의 사이클 존재하는지 알 수 있다. n-1번이 아닌 n번 반복했을 때 거리 달라지면 음의 사이클 존재.
// +) 1번 시작이 아닌 전체 그래프에서 음의 사이클 존재 여부 알고 싶을때 -> dist[x] != inf 지우기 (inf 설정 이유가 단절을 표시하기 위해)
#include <iostream>
#include <vector>
using namespace std;
struct Edge {
int from;
int to;
int cost;
};
long long dist[501];
long long inf = 1000000000;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n,m;
cin >> n >> m;
vector<Edge> e(m);
for (int i = 0; i<m; i++){
cin >> e[i].from >> e[i].to >> e[i].cost;
}
for (int i = 1; i<=n; i++){
dist[i] = inf;
}
//1번 노드에서 출발
dist[1] = 0;
bool neg_cycle = false;
for (int i = 1; i<=n; i++){
for (int j = 0; j< m; j++){
int x = e[j].from;
int y = e[j].to;
int z = e[j].cost;
if (dist[x] != inf && dist[y] > dist[x] + z){
dist[y] = dist[x]+ z;
if (i == n) neg_cycle = true;
}
}
}
if (neg_cycle) cout << "-1" << '\n';
else{
for (int i = 2; i<=n; i++){
if (dist[i] == inf) cout << "-1" << '\n';
else cout << dist[i] << '\n';
}
}
return 0;
} | [
"ohjskim@naver.com"
] | ohjskim@naver.com |
784a33f7a6915bef853b522959aee47133c2f194 | 6670724130458d10b458b4f23ee995c4ef0ef242 | /MegaProject/Controller/StructureController.cpp | c1abb4f5bf36948e5fcb2eef4eaad3ac089c0857 | [] | no_license | AarooneyFarr/MegaProject | d54154e45b61f0e50e2a65caa04ea0b738b5900b | f89a67360999e6fb98a960e63114560fbb581c45 | refs/heads/master | 2021-01-12T10:32:21.684192 | 2017-05-26T15:55:08 | 2017-05-26T15:55:08 | 81,345,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,897 | cpp | //
// StructureController.cpp
// MegaProject
//
// Created by Farr, Aaron on 2/8/17.
// Copyright © 2017 Farr, Aaron. All rights reserved.
//
#include "../Model/IntNodeArray.hpp"
#include "StructureController.hpp"
#include <iostream>
#include "../Model/Timer.hpp"
#include "../Model/List.hpp"
#include "../Model/Meme.hpp"
#include "../Model/Tree.hpp"
#include "../Model/BinarySearchTree.hpp"
#include "../Model/Graph.hpp"
using namespace std;
StructureController :: StructureController()
{
wordNode = Node<string>("derpy");
numberNode = Node<int>();
this->numberArray = Array<int>(9);
}
void StructureController :: testArrayTemplate()
{
cout << "Array Template" << endl;
Timer arrayTimer;
arrayTimer.startTimer();
int test [9];
arrayTimer.stopTimer();
arrayTimer.displayTimerInformation();
arrayTimer.resetTimer();
arrayTimer.startTimer();
numberArray = Array<int>(9);
arrayTimer.stopTimer();
arrayTimer.displayTimerInformation();
}
void StructureController :: testAdvancedFeatures()
{
int showDestructor = 0;
if(showDestructor <1)
{
Array<string> words = Array<string>(4);
cout << "There should be messages about destuctor next." << endl;
}
Array<string> words = Array<string>(4);
words.setAtIndex(0, "at zero");
words.setAtIndex(3, "in the last spot");
Array<string> copiedWords = Array<string>(words);
cout << "These should match: " << endl;
cout << words.getFromIndex(0) << " should be the same as " << copiedWords.getFromIndex(0) << endl;
copiedWords.setAtIndex(3,"Changed the contents of the copied Array");
}
void StructureController :: testIntArray()
{
cout << "Creating an IntNodeArray" << endl;
IntNodeArray temp = IntNodeArray(3);
for(int spot = 0; spot < 3; spot++)
{
temp.setAtIndex(spot,spot);
}
for(int spot = 0; spot < temp.getSize(); spot++)
{
cout << temp.getFromIndex(spot) << " is at " << spot << endl;
}
}
void StructureController:: testNodeTypes()
{
}
void StructureController :: start()
{
//cout << "Going to test the IntNodeArray" << endl;
//testIntArray();
//cout << "Finished IntNodeArray" << endl;
// testListIntro();
//testListTiming();
//testMemeQueue();
//testLists();
//testIntStack();
testBinarySearchTreeOperations();
//testGraph();
//testHashTable();
}
void StructureController :: testListIntro()
{
List<int> sample;
sample.addFront(2);
sample.addEnd(3);
sample.addFront(1);
cout << "this should go 1, 2, 3." << endl;
}
void StructureController :: testListTiming()
{
DoubleList<int> timingList;
for(int index = 0; index < 10000; index++)
{
timingList.add(rand());
}
long slowTime [1000];
long fastTime [1000];
double averageSlow = 0.00, averageFast = 0.00;
Timer doubleTimer;
for(int index = 0; index < 1000; index++)
{
int randomIndex = rand() % 10000;
doubleTimer.startTimer();
timingList.getFromIndex(randomIndex);
doubleTimer.stopTimer();
slowTime[index] = doubleTimer.getExecutionTimeInMicroseconds();
doubleTimer.resetTimer();
doubleTimer.startTimer();
timingList.getFromIndexFast(randomIndex);
doubleTimer.stopTimer();
fastTime[index] = doubleTimer.getExecutionTimeInMicroseconds();
doubleTimer.resetTimer();
averageSlow += slowTime[index];
averageFast += fastTime[index];
}
averageSlow = averageSlow/1000.00;
averageFast = averageFast/1000.00;
cout << "The average speed for the getFromIndex method was: " << averageSlow << " microseconds."<< endl;
cout << "The average speed for the getFromIndexFast method was: " << averageFast << " microseconds."<< endl;
cout << "A time savings?? of: " << averageSlow - averageFast << " microseconds."<< endl;
}
void StructureController :: testMemeQueue()
{
Meme firstMeme("toddler fist! with pinwheel");
Queue<Meme> memeQueue;
memeQueue.add(firstMeme);
memeQueue.add(firstMeme);
Meme secondMeme;
secondMeme.setDankness(8453);
memeQueue.enqueue(secondMeme);
memeQueue.peek();
cout << "Size should be 3 and is: " << memeQueue.getSize() << endl;
memeQueue.remove(0);
cout << "Size should be 2 and is: " << memeQueue.getSize() << endl;
Meme temp = memeQueue.dequeue();
cout << "this should be 27 and is: " << temp.getDankness() << endl;
}
void StructureController :: testLists()
{
List<int> sample;
sample.addFront(2);
sample.addFront(1);
sample.addEnd(3);
sample.setAtIndex(2,5);
sample.remove(0);
sample.addAtIndex(0,0);
cout << "This should be 1 and is: "<< sample.contains(2) << endl;
cout << "This should be 025 and is: " << sample.getFromIndex(0) << sample.getFromIndex(1) << sample.getFromIndex(2) << endl;
cout << "This should be 0 and is: " << sample.getFromIndex(0) << endl;
}
void StructureController :: testIntStack()
{
int firstInt = 1;
Stack<int> intStack;
intStack.push(firstInt);
int secondInt = 2;
intStack.push(secondInt);
intStack.pop();
cout << "This should be 1 and is " << intStack.peek() << endl;
intStack.add(2);
intStack.remove(1);
}
void StructureController :: testGraph()
{
Graph<string> words;
words.addVertex("Aaron");
words.addVertex("Thomas");
words.addVertex("Harry");
words.addVertex("Bekah");
words.addVertex("Rachel");
words.addEdge(0,1);
words.addEdge(1,2);
words.addEdge(2,3);
words.addEdge(3,4);
words.addEdge(4,0);
words.depthFirstTraversal(words,0);
words.breadthFirstTraversal(words,0);
}
void StructureController :: testHashTable()
{
HashTable<string> hashWords;
hashWords.add("derpy");
hashWords.add("is");
hashWords.add("ammars");
hashWords.add("middle");
hashWords.add("name");
hashWords.add("just");
hashWords.add("in");
hashWords.add("case");
hashWords.add("you");
hashWords.add("didn't");
hashWords.add("know");
hashWords.displayContents();
}
void StructureController :: testBinarySearchTreeOperations()
{
BinarySearchTree<int> numbers;
numbers.insert(9843);
numbers.insert(10);
numbers.insert(43);
numbers.insert(-123);
numbers.insert(23465);
numbers.insert(10); // won't go in
numbers.insert(43243);
numbers.insert(-45677654);
numbers.insert(92165);
cout << "Size should be 8 and is: " << numbers.getSize() << endl;
cout << "In order traversal should be: \n\t-45677654 \n\t-123 \n\t10 \n\t43 \n\t9843 \n\t23465 \n\t43243 \n\t92165" << endl;
numbers.inOrderTraversal();
cout << "Post order traversal should be \n\t-45677654 \n\t-123 \n\t43 \n\t10 \n\t92165 \n\t43243 \n\t23465 \n\t9843" << endl;
numbers.postOrderTraversal();
numbers.remove(-45677654);
cout << "Size should be 7 and is: " << numbers.getSize() << endl;
cout << "Pre order traversal should be \n\t9843 \n\t10 \n\t-123 \n\t43 \n\t23465 \n\t43243 \n\t92165" << endl;
numbers.preOrderTraversal();
numbers.remove(10);
cout << "Size should be 6 and is: " << numbers.getSize() << endl;
cout << "Pre order traversal should be \n\t9843 \n\t-123 \n\t43 \n\t23465 \n\t43243 \n\t92165" << endl;
numbers.preOrderTraversal();
cout << "Height should be 4 and is: " << numbers.getHeight() << endl;
cout << "Balanced should be false || 0 and is: " << numbers.isBalanced() << endl;
}
| [
"Aarooney.Farr@gmail.com"
] | Aarooney.Farr@gmail.com |
8a0f63848a79adbbdad77f97e9e74a0d9c906c07 | c4790552abc608f491b7ac2a0b6dcd5826a5bd7c | /463D.cpp | 33753bcf4896797df5c23d1f1a40401e9d2b1f0c | [] | no_license | jeffry1829/ojcode | bd03df14360e5c00e6463c3621de0cfeef88bb11 | 18a6fa3aa59e0d9c274f44f7dea060f70c91cbe8 | refs/heads/master | 2023-02-27T00:27:04.856978 | 2021-02-04T09:20:58 | 2021-02-04T09:20:58 | 286,199,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,276 | cpp | #pragma GCC optimize(1)
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-ffast-math")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-funroll-loops")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-fschedule-insns")
#pragma GCC optimize("inline-functions")
#pragma GCC optimize("-ftree-tail-merge")
#pragma GCC optimize("-fschedule-insns2")
#pragma GCC optimize("-fstrict-aliasing")
#pragma GCC optimize("-falign-functions")
#pragma GCC optimize("-fcse-follow-jumps")
#pragma GCC optimize("-fsched-interblock")
#pragma GCC optimize("-fpartial-inlining")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("-freorder-functions")
#pragma GCC optimize("-findirect-inlining")
#pragma GCC optimize("-fhoist-adjacent-loads")
#pragma GCC optimize("-frerun-cse-after-loop")
#pragma GCC optimize("inline-small-functions")
#pragma GCC optimize("-finline-small-functions")
#pragma GCC optimize("-ftree-switch-conversion")
#pragma GCC optimize("-foptimize-sibling-calls")
#pragma GCC optimize("-fexpensive-optimizations")
#pragma GCC optimize("inline-functions-called-once")
#pragma GCC optimize("-fdelete-null-pointer-checks")
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i=a;i<n;i++)
#define per(i,a,n) for(int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
typedef double db;
mt19937 mrand(random_device{}());
const ll mod=1000000007;
int rnd(int x){return mrand()%x;}
ll powmod(ll a,ll b){ll res=1;a%=mod;assert(b>=0);for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a, ll b){return b?gcd(b,a%b):a;}
#define rank oiajgpowsdjg
const int N = 100;
int parent[N], rank[N];
inline void dsinit(int n) {for (int i = 0; i < n; i++)parent[i] = i;memset(rank, 0, sizeof rank);}
inline int dsfind(int e) {return parent[e] == e ? e : parent[e] = dsfind(parent[e]);}
inline void dsunion(int s1, int s2) {if (rank[s1] < rank[s2])swap(s1, s2);parent[s2] = s1;if (rank[s1] == rank[s2]) rank[s1]++;}
//head
const int _n=1010;
int n,k,s[5][_n],dp[_n],rs[5][_n];
inline bool f(int x,int y){
rep(i,1,k)if(rs[i][x]>=rs[i][y])return 0;
return 1;
}
main(void) {cin.tie(0);ios_base::sync_with_stdio(0);
cin>>n>>k;
rep(i,0,k)rep(j,0,n)cin>>s[i][j];
rep(i,0,k)rep(j,0,n)rs[i][s[i][j]]=j;
rep(i,0,n)dp[i]=1;
rep(i,1,n)rep(j,0,i)if(f(s[0][j],s[0][i]))dp[i]=max(dp[i],dp[j]+1);
int ans=1;rep(i,0,n)ans=max(ans,dp[i]);
cout<<ans<<'\n';
return 0;
} | [
"jeffry1829@gmail.com"
] | jeffry1829@gmail.com |
8666123ad3e969130b2e2c9ba54925e911cd7d65 | c2908e289990da7c4745043bf07bcf02ac6b950d | /include/LuaGlue/LuaGlueNewIndexMethod.h | 96200a3eeb230d17ee4368fb09f73bfbc16dc7b0 | [
"Zlib"
] | permissive | nkutty/LuaGlue | 92dbde30f42dd984230a03824481aad71ff95e84 | 7866cde9c86ca3cfc7298ea90c609c15f2b16d33 | refs/heads/master | 2021-01-16T00:12:27.852165 | 2014-06-03T21:37:34 | 2014-06-03T21:37:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,845 | h | #ifndef LUAGLUE_NEWINDEX_METHOD_H_GUARD
#define LUAGLUE_NEWINDEX_METHOD_H_GUARD
#include <lua.hpp>
#include <string>
#include <tuple>
#include <utility>
#include "LuaGlue/LuaGlueObject.h"
#include "LuaGlue/LuaGlueApplyTuple.h"
#include "LuaGlue/LuaGlueBase.h"
template<typename _Class>
class LuaGlueClass;
template<typename _Value, typename _Class, typename _Key>
class LuaGlueNewIndexMethod : public LuaGlueMethodBase
{
public:
typedef _Class ClassType;
typedef void (_Class::*MethodType)(_Key, _Value);
LuaGlueNewIndexMethod(LuaGlueClass<_Class> *luaClass, const std::string &name, MethodType &&fn) : glueClass(luaClass), name_(name), fn(std::forward<MethodType>(fn))
{ }
~LuaGlueNewIndexMethod() {}
std::string name() { return name_; }
bool glue(LuaGlueBase *luaGlue)
{
lua_pushlightuserdata(luaGlue->state(), this);
lua_pushcclosure(luaGlue->state(), &lua_call_func, 1);
lua_setfield(luaGlue->state(), -2, name_.c_str());
return true;
}
private:
LuaGlueClass<_Class> *glueClass;
std::string name_;
MethodType fn;
std::tuple<_Key, _Value> args;
int invoke(lua_State *state)
{
auto base = GetLuaUdata(state, 1, glueClass->name().c_str());
if(base->isSharedPtr())
{
auto obj = *CastLuaGlueObjectShared(ClassType, base);
lua_remove(state, 1);
applyTuple(glueClass->luaGlue(), state, obj, fn, args);
}
else
{
auto obj = *CastLuaGlueObject(ClassType, base);
lua_remove(state, 1);
applyTuple(glueClass->luaGlue(), state, obj, fn, args);
}
lua_pop(state, 2);
return 0;
}
static int lua_call_func(lua_State *state)
{
auto mimp = (LuaGlueNewIndexMethod<_Value, _Class, _Key> *)lua_touserdata(state, lua_upvalueindex(1));
return mimp->invoke(state);
}
};
#endif /* LUAGLUE_NEWINDEX_METHOD_H_GUARD */
| [
"thomas@fjellstrom.ca"
] | thomas@fjellstrom.ca |
efd3530542bbc554a982e6eb9c3904a0c0c522f7 | 935c73c085973689f73d2e3e7d604efec2122cfb | /src/WindHorn/WHSurface.cpp | b9f7e3c6e9aa98470cf2ea77feb89a58c0a19f31 | [] | no_license | AlanMiu/mir2-cpp | d0d91b05b2d0218464b51a4a156ed8da19505965 | a33a92aa01b03a45b0911e51c642740d8612fc77 | refs/heads/master | 2022-04-16T21:54:24.449441 | 2017-09-14T17:26:52 | 2017-09-14T17:26:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,309 | cpp | /******************************************************************************************************************
Module Name:
Author:
Date:
[Date][Modifier] : Modified contents
*******************************************************************************************************************/
#include "StdAfx.h"
#include "WHEngine.h"
/******************************************************************************************************************
Function Name : CWHSurface::ReleaseSurface()
Author :
Date :
Purpose :
Return : BOOL
[Date][Modifier] : Modified contents
*******************************************************************************************************************/
BOOL CWHSurface::ReleaseSurface()
{
if ( m_pDDS )
{
m_pDDS->Release();
m_pDDS = NULL;
return TRUE;
}
return FALSE;
}
/******************************************************************************************************************
Function Name : CWHSurface::CreateOffScreenSurface()
Author :
Date :
Purpose :
Params : LPDIRECTDRAW7 pDD
DWORD dwXSize
DWORD dwYSize
Return : BOOL
[Date][Modifier] : Modified contents
*******************************************************************************************************************/
BOOL CWHSurface::CreateOffScreenSurface(LPDIRECTDRAW7 pDD, DWORD dwXSize, DWORD dwYSize)
{
HRESULT hr;
DDSURFACEDESC2 ddsd;
ZeroMemory(&ddsd, sizeof(DDSURFACEDESC2));
ddsd.dwSize = sizeof(DDSURFACEDESC2);
ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
ddsd.dwWidth = dwXSize;
ddsd.dwHeight = dwYSize;
hr = pDD->CreateSurface(&ddsd, &m_pDDS, NULL);
if ( hr != DD_OK ) return FALSE;
return TRUE;
}
/******************************************************************************************************************
Function Name : CWHSurface::CopyImageToSurface()
Author :
Date :
Purpose :
Params : DWORD dwSrcWidth
DWORD dwSrcHeight
WORD* pwSrc
Return : BOOL
[Date][Modifier] : Modified contents
*******************************************************************************************************************/
BOOL CWHSurface::CopyImageToSurface(DWORD dwSrcWidth, DWORD dwSrcHeight, WORD* pwSrc)
{
DDSURFACEDESC2 ddsd;
WORD* pwdDst = NULL;
ZeroMemory(&ddsd, sizeof(DDSURFACEDESC2));
ddsd.dwSize = sizeof(DDSURFACEDESC2);
if (m_pDDS->Lock(NULL, &ddsd, DDLOCK_WAIT, NULL) == DD_OK)
{
pwdDst = (WORD*)ddsd.lpSurface;
CopyMemory(pwdDst, pwSrc, dwSrcWidth * dwSrcHeight * sizeof(WORD));
m_pDDS->Unlock(NULL);
DDCOLORKEY ddck;
ddck.dwColorSpaceLowValue = RGB( 0, 0, 0);
ddck.dwColorSpaceHighValue = RGB(10, 10, 10);
m_pDDS->SetColorKey(DDCKEY_SRCBLT, &ddck);
return TRUE;
}
return FALSE;
}
| [
"baiyqukq@163.com"
] | baiyqukq@163.com |
56b5bb84b36043c1bc1f9b87393fbe1c3d28df70 | bb93dfb72f4747ba8bd2088e57dc078c4127fe81 | /Classes/ControlesEscena.cpp | f7e6f80d19e1fd9ac8f9dfd650fcdeee64cf9784 | [] | no_license | bertito1995/DWv1.0 | 72fe5666fbd2927409bd7d1f190deda070f52edf | 1106da32676016fc3c6c2a535fb3f2426896ad52 | refs/heads/master | 2021-01-10T14:07:44.956940 | 2016-01-12T14:43:24 | 2016-01-12T14:43:24 | 45,998,647 | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 2,162 | cpp | #include "ControlesEscena.h"
#include "cocos2d.h"
#include "MenuEscena.h"
USING_NS_CC;
Scene *ControlesEscena::createScene()
{
auto scene = Scene::create();
auto layer = ControlesEscena::create();
scene->addChild(layer);
return scene;
}
bool ControlesEscena::init()
{
Size tamaņoPantalla = Director::getInstance()->getVisibleSize();
Sprite *resetBoton = Sprite::create("imagenes/gui/reset.png");
resetBoton->setScaleX(tamaņoPantalla.width / resetBoton->getContentSize().width * 0.1);
resetBoton->setScaleY(tamaņoPantalla.height / resetBoton->getContentSize().height * 0.1);
resetBoton->setPosition(Point((tamaņoPantalla.width - (resetBoton->getScaleX() * resetBoton->getContentSize().width / 2)), (resetBoton->getScaleY() * resetBoton->getContentSize().height) / 2));
addChild(resetBoton, 1);
Sprite *fondo = Sprite::create("imagenes/gui/controlesScene.png");
fondo->setPosition(Point((tamaņoPantalla.width / 2), (tamaņoPantalla.height / 2)));
addChild(fondo, 0);
auto event_listener = EventListenerTouchAllAtOnce::create();
event_listener->onTouchesBegan = [=](const std::vector<Touch*>& pTouches, Event* event)
{
auto touch = *pTouches.begin();
auto openGl_location = touch->getLocation();
float distancia;
distancia = resetBoton->getPosition().getDistance(touch->getLocation());
if (distancia < 30)
{
Sprite* aux = Sprite::create("imagenes/gui/resetPulsado.png");
resetBoton->setTexture(aux->getTexture());
return;
}
};
event_listener->onTouchesEnded = [=](const std::vector<Touch*>& pTouches, Event* event)
{
auto touch = *pTouches.begin();
auto openGl_location = touch->getLocation();
float distancia;
distancia = resetBoton->getPosition().getDistance(touch->getLocation());
if (distancia < 30)
{
menu();
return;
}
};
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(event_listener, fondo);
return true;
}
void ControlesEscena::menu()
{
Director::getInstance()->popScene();
}
void ControlesEscena::menuCloseCallback(Ref* pSender)
{
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
} | [
"thejavato@gmail.com"
] | thejavato@gmail.com |
49b52a9c8f9e6b2f002d9d552c3a439e8ca595b6 | 1ad14377c65c624aac3de787e86ad232faacf8e6 | /gameNode.cpp | 62db8091d1bf521b4e2798e1a23fbe6e4b5a0d66 | [] | no_license | juh1128/SGA-Monarch2Weeks | 5c5aba87619da193314679951034617e8e365dbe | f77c799572f21c5350cce2eed5a4aeb31b690e6e | refs/heads/master | 2021-10-08T22:53:39.082264 | 2018-12-18T18:28:32 | 2018-12-18T18:28:32 | 106,794,815 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,072 | cpp | #include "stdafx.h"
#include "gameNode.h"
gameNode::gameNode()
{
}
gameNode::~gameNode()
{
}
HRESULT gameNode::init(void)
{
_managerInit = false;
return S_OK;
}
HRESULT gameNode::init(bool managerInit)
{
_managerInit = managerInit;
if (_managerInit)
{
KEYMANAGER->init();
IMAGEMANAGER->init();
SOUNDMANAGER->init();
TIMEMANAGER->init();
CAMERA->init();
//EFFECTMANAGER->init();
}
return S_OK;
}
//메모리 해제
void gameNode::release(void)
{
if (_managerInit)
{
KEYMANAGER->releaseSingleton();
IMAGEMANAGER->releaseSingleton();
SOUNDMANAGER->releaseSingleton();
TIMEMANAGER->releaseSingleton();
CAMERA->releaseSingleton();
//EFFECTMANAGER->releaseSingleton();
}
}
//업데이트
void gameNode::update(void)
{
}
//그리기
void gameNode::render(void)
{
}
LRESULT gameNode::MainProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
switch (iMessage)
{
case WM_MOUSEMOVE:
_ptMouse.x = static_cast<float>LOWORD(lParam);
_ptMouse.y = static_cast<float>HIWORD(lParam);
break;
//사이즈 변경 시 체크
case WM_SIZE:
{
UINT width = LOWORD(lParam);
UINT height = HIWORD(lParam);
IMAGEMANAGER->onResize(width, height);
}
break;
case WM_LBUTTONDOWN:
KEYMANAGER->setKeyState(VK_LBUTTON, true);
break;
case WM_LBUTTONUP:
KEYMANAGER->setKeyState(VK_LBUTTON, false);
break;
case WM_RBUTTONDOWN:
KEYMANAGER->setKeyState(VK_RBUTTON, true);
break;
case WM_RBUTTONUP:
KEYMANAGER->setKeyState(VK_RBUTTON, false);
break;
case WM_KEYDOWN:
KEYMANAGER->setKeyState(wParam, true);
break;
case WM_KEYUP:
KEYMANAGER->setKeyState(wParam, false);
break;
//휠에 따라서 줌인 줌아웃
case WM_MOUSEWHEEL:
{
float zoom = CAMERA->getZoom();
float zoomUnit = 0.1f;
if ((short)HIWORD(wParam) < 0)
{
CAMERA->setZoom(zoom - zoomUnit);
}
else
{
CAMERA->setZoom(zoom + zoomUnit);
}
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return (DefWindowProc(hWnd, iMessage, wParam, lParam));
}
| [
"juh17@naver.com"
] | juh17@naver.com |
65336427007e9d4ac03288573a3cb3c5bae1aa62 | 0769bb399c7ef945e91d3a2dc227d08214438795 | /BilliardsGame/SceneManager.h | 70c95e7ad325046bfafe2bc0b16d2cd86c83796d | [] | no_license | ogasho/BilliardsGameDX | 307353762d4c9a0147c7fac12dc849dcabbc6207 | 52e9f7f41c7bfe8b5f2fcc37c0e7ffaa7b23a522 | refs/heads/master | 2021-01-13T13:56:56.313095 | 2016-12-14T16:37:42 | 2016-12-14T16:37:42 | 72,931,827 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 753 | h | /* シーン遷移管理クラス */
// 現在動作しているシーンの監視、切り替えを行う
#pragma once
#include <d3d11.h>
enum class SceneID;
class DX11Manager;
class ShaderManager;
class SceneBase;
class SceneNineBall;
class InputManager;
class SceneManager
{
public:
SceneManager();
~SceneManager();
bool Init(SceneID firstScene, DX11Manager* dx3D, const InputManager* inputManager, const ShaderManager* shaderManager);
bool UpdateChangeScene(DX11Manager* dx3D, const InputManager* inputManager, const ShaderManager* shaderManager);
bool Frame();
bool Render(DX11Manager* dx3D);
bool IsChangeScene(){ return m_isChangeScene; }
private:
bool m_isChangeScene;
SceneID m_currentSceneID;
SceneBase* m_currentScene;
};
| [
"ogasho100@yahoo.co.jp"
] | ogasho100@yahoo.co.jp |
2f583eb76e3667b8daf962694ba8f8b6a8c7b18c | 5f13d88fd0457bf8fe3845435d039f4e315191d9 | /include/peli/json/value.h | 20901a4dd0bd6b0ee4abd1b778b595fa16e5c465 | [
"Apache-2.0"
] | permissive | aclex/peli | 149d198875a42395ecf8f5c9546291cb9096f826 | 189eb3d902feac9ea4b54c9116419d0eaf71ffff | refs/heads/master | 2023-05-26T18:06:02.534043 | 2023-05-23T21:45:15 | 2023-05-23T21:45:15 | 38,453,766 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,396 | h | /*
* This file is part of Peli - universal JSON interaction library
* Copyright (C) 2014-2022 Alexey Chernov <4ernov@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PELI_JSON_VALUE_H
#define PELI_JSON_VALUE_H
#include <string>
#include <type_traits>
#include <peli/value_basics.h>
#include <peli/json/object.h>
#include <peli/json/array.h>
#include <peli/json/number.h>
namespace peli
{
/** \brief Types and functions for [JSON](http://json.org/) interaction. */
namespace json
{
/** [JSON](http://json.org/) value uniform representation.
*
* In fact it's just a tiny shell around variant type used, and
* this is to allow recursive inclusion of variants.
*
* \tparam Ch character type.
*/
template<typename Ch> class basic_value : public peli::variant_type
<
bool,
json::number,
std::basic_string<Ch>,
json::basic_array<Ch>,
json::basic_object<Ch>
>
{
public:
/** \brief Underlying variant type. */
using variant_type = peli::variant_type
<
bool,
json::number,
std::basic_string<Ch>,
json::basic_array<Ch>,
json::basic_object<Ch>
>;
using variant_type::variant_type;
/** \brief Checks if the value is null (as per [JSON](http://json.org/) specification). */
bool null() const noexcept
{
return peli::is_empty(*this);
}
/** \brief Parses null-terminated string.
*
* \param str null-terminated string to parse.
*/
static basic_value parse(const Ch* const str);
/** \brief Parses std::basic_string<>.
*
* \param str string to parse.
*/
static basic_value parse(const std::basic_string<Ch>& str);
#ifdef CXX_STD_17
/** \brief Parses std::basic_string_view<>.
*
* \param str string_view to parse.
*/
static basic_value parse(const std::basic_string_view<Ch> sv);
#endif
};
/** \brief `basic_value` specialization for `char`. */
typedef basic_value<char> value;
/** \brief `basic_value` specialization for `wchar_t`. */
typedef basic_value<wchar_t> wvalue;
/** \brief Small factory method to create uninitialized value of the given type.
*
* \tparam T type the value to construct of.
* \tparam ValueType value type to create (e.g. some character specialization
* of `basic_value<>`).
*/
template<typename T, class ValueType = value> inline ValueType make_value()
{
return ValueType(T());
}
/** \brief Prints the content of the specified value to string.
*
* \tparam Ch character type.
* \param v value to print.
* \param pretty flag to enable pretty printing.
*
* \return string containing textual content of the specified value.
*
* \sa peli::json::pretty()
*/
template<typename Ch> std::basic_string<Ch> to_string(const basic_value<Ch>& v, const bool pretty = false);
}
}
#include <peli/json/value.tcc>
#endif // PELI_JSON_VALUE_H
| [
"4ernov@gmail.com"
] | 4ernov@gmail.com |
71e904e953ef060125282d63d417c56096d557fb | 270906a92f36f1ced4e5ab71a20efc367dad0c0b | /include/anvil/RPC/ServerExample.hpp | 06677cae8adbf536e3ff1883f83ccf27236ffbc5 | [
"Apache-2.0"
] | permissive | asmith-git/anvil | 69c0c71df2eb81195bbce586061905972e79d682 | 6a0ead54fa870cb0b3159fb40387e8dc239e37af | refs/heads/master | 2023-09-06T00:48:49.659072 | 2023-08-28T16:55:21 | 2023-08-28T16:55:21 | 112,432,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,736 | hpp | //Copyright 2023 Adam G. Smith
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http ://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
#ifndef ANVIL_RPC_SERVER_EXAMPLE_HPP
#define ANVIL_RPC_SERVER_EXAMPLE_HPP
#include <atomic>
#include <thread>
#include "anvil/RPC/Server.hpp"
#include "anvil/byte-pipe/BytePipeWriter.hpp"
#include "anvil/byte-pipe/BytePipeReader.hpp"
#include "anvil/byte-pipe/BytePipeTCP.hpp"
#include "anvil/byte-pipe/BytePipeJSON.hpp"
namespace anvil { namespace RPC {
class ANVIL_DLL_EXPORT ServerConnection {
private:
Server& _server;
std::thread _thread;
std::atomic_int32_t _signal;
protected:
virtual void ReadDataFromClient(BytePipe::Parser& parser) = 0;
virtual void SendDataToClient(const BytePipe::Value& response) = 0;
public:
ServerConnection(Server& server);
virtual ~ServerConnection();
};
class ANVIL_DLL_EXPORT ServerJsonTCP final : public ServerConnection {
private:
std::unique_ptr<BytePipe::TCPServerPipe> _tcp;
BytePipe::JsonWriter _json_writer;
BytePipe::TCPPort _port;
protected:
void ReadDataFromClient(BytePipe::Parser& parser) final;
void SendDataToClient(const BytePipe::Value& response) final;
public:
ServerJsonTCP(Server& server, BytePipe::TCPPort server_port);
virtual ~ServerJsonTCP();
};
}}
#endif
| [
"adam.george.smith@btinternet.com"
] | adam.george.smith@btinternet.com |
6dd1e909acf995e4486d7048c082f9b5b9b44fd2 | 46a924618d0b248acad0a44f92aad10072ef7bb0 | /src/cppruntime/include/runtimetest/system/ProcessJSystemConstants.hpp | 5ed44a90d332449110c3db958338b1c5556783f5 | [
"Apache-2.0"
] | permissive | mattunlv/ProcessJ | 48dfc6aa5f59f51bb86155de84185c8e941c51e7 | 57d6ae2d120bd58978195d133924b4eefc4bc844 | refs/heads/main | 2023-06-24T05:57:57.176316 | 2023-05-06T04:17:23 | 2023-05-06T04:17:23 | 454,967,668 | 1 | 0 | Apache-2.0 | 2022-08-30T20:39:25 | 2022-02-02T23:19:40 | Java | UTF-8 | C++ | false | false | 942 | hpp | /*!
*
* ProcessJSystem::Constants declaration. Defines constants that are used throughout
* the ProcessJSystem to promote refactorablility
*
* \author Carlos L. Cuenca
* \date 03/13/2022
* \version 1.0.0
*/
#ifndef UNLV_PROCESS_J_SYSTEM_CONSTANTS_HPP
#define UNLV_PROCESS_J_SYSTEM_CONSTANTS_HPP
namespace ProcessJSystem {
/// -------
/// Strings
static SimpleString AssertionErrorSubscriptOperatorDoesNotThrowExceptionMessage = "Error: Subscript operator does not throw exception with invalid indices.";
static SimpleString AssertionErrorAreNotEqualMessage = "Error: Instances are not equal." ;
static SimpleString AssertionErrorAreEqualMessage = "Error: Instances are equal." ;
/// ----------
/// Characters
static Character NewLine = '\n';
}
#endif
| [
"cuenca.cl@gmail.com"
] | cuenca.cl@gmail.com |
509f60ff2136e2720fdad04f975d0870625c1ca3 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5670465267826688_0/C++/laoriu/C.cpp | 050fef85bb1e14486c3296baf85c44417723cd76 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,530 | cpp | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 10000 + 10;
int f[MAXN];
bool ok[MAXN];
void convert_to_num(string &s) {
for(int i = 0; i < s.length(); i++) {
if (s[i] == 'i') s[i] = '2';
else if (s[i] == 'j') s[i] = '3';
else if (s[i] == 'k') s[i] = '4';
}
}
int sign(int x) {
if (x > 0) return 1;
if (x < 0) return -1;
return 0;
}
int main()
{
int tab[5][5] = {{},
{0, 1, 2, 3, 4},
{0, 2, -1, 4, -3},
{0, 3, -4, -1, 2},
{0, 4, 3, -2, -1}};
freopen("C-small-attempt0.in", "r", stdin);
freopen("C.out", "w", stdout);
int test;
cin >> test;
for(int tc = 1; tc <= test; tc++) {
int L, X;
cin >> L >> X;
string seed;
cin >> seed;
convert_to_num(seed);
string s = "";
for(int i = 0; i < X; i++) s += seed;
int n = s.length();
f[0] = 1;
for(int i = 1; i <= n; i++) {
int j = s[i - 1] - '0';
f[i] = sign(f[i - 1]) * tab[abs(f[i - 1])][j];
//cout << i << " " << f[i] << endl;
}
for(int i = 0; i <= n; i++) ok[i] = false;
bool ok_i = (f[1] == 2);
for(int i = 2; i <= n; i++) {
ok[i] = ok[i - 1] | ((f[i] == 4) && (ok_i));
ok_i = ok_i | (f[i] == 2);
}
string result = ((f[n] == -1) && (ok[n - 1])) ? "YES" : "NO";
cout << "Case #" << tc << ": " << result << endl;
}
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
6df358d5f86de64408285763f66508e1e2e706b5 | ce1cc211b951de557fc7bdc41d59591aa131bb8b | /sources/seating_arrangement/tests.cpp | 4b31190cb874e2339f54cf952027e7c5fa2c691c | [
"MIT"
] | permissive | jacek143/kata | ac09203fe1462f7f80cd0015b6f5fce86079021f | 57784b1d6139c6f7cb8be0ebd3fee162f1d5e558 | refs/heads/master | 2020-08-01T00:20:51.224732 | 2020-04-13T09:24:02 | 2020-04-13T11:07:10 | 210,797,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,821 | cpp | #include "seating_arrangement.h"
#include "gtest/gtest.h"
using seating_arrangement::getFacingSeatNumber;
using seating_arrangement::getSeatType;
using seating_arrangement::SeatType;
using seating_arrangement::solveProblem;
using std::string;
class SeatingArrangement : public ::testing::Test {
public:
void expectSeatsMapped(unsigned frontFacing, unsigned rearFacing) {
EXPECT_EQ(getFacingSeatNumber(frontFacing), rearFacing);
EXPECT_EQ(frontFacing, getFacingSeatNumber(rearFacing));
}
};
TEST_F(SeatingArrangement, firstCompartment) {
expectSeatsMapped(3, 10);
expectSeatsMapped(2, 11);
expectSeatsMapped(1, 12);
}
TEST_F(SeatingArrangement, secondCompartment) {
expectSeatsMapped(6, 7);
expectSeatsMapped(5, 8);
expectSeatsMapped(4, 9);
}
TEST_F(SeatingArrangement, thirdCompartment) {
expectSeatsMapped(15, 22);
expectSeatsMapped(14, 23);
expectSeatsMapped(13, 24);
}
TEST_F(SeatingArrangement, fourthCompartment) {
expectSeatsMapped(18, 19);
expectSeatsMapped(17, 20);
expectSeatsMapped(16, 21);
}
TEST_F(SeatingArrangement, windowSeat) {
EXPECT_EQ(SeatType::WINDOW, getSeatType(1));
EXPECT_EQ(SeatType::WINDOW, getSeatType(6));
EXPECT_EQ(SeatType::WINDOW, getSeatType(7));
EXPECT_EQ(SeatType::WINDOW, getSeatType(12));
EXPECT_EQ(SeatType::WINDOW, getSeatType(108));
}
TEST_F(SeatingArrangement, middleSeat) {
EXPECT_EQ(SeatType::MIDDLE, getSeatType(2));
EXPECT_EQ(SeatType::MIDDLE, getSeatType(5));
EXPECT_EQ(SeatType::MIDDLE, getSeatType(107));
}
TEST_F(SeatingArrangement, aisleleSeat) {
EXPECT_EQ(SeatType::AISLE, getSeatType(3));
EXPECT_EQ(SeatType::AISLE, getSeatType(106));
}
TEST_F(SeatingArrangement, completeAnswer) {
EXPECT_EQ("48 WS", solveProblem(37));
EXPECT_EQ("58 AS", solveProblem(51));
EXPECT_EQ("89 MS", solveProblem(92));
}
| [
"jacek143@gmail.com"
] | jacek143@gmail.com |
819ac6f75766c6d13ad29807994285aa502c13b5 | e36906be9399685b0d03daffec9c33735eda8ba1 | /src/python/tests/main.cpp | f0b5c8cbadb2760814ad090816db526dc371268f | [] | no_license | ybouret/yocto4 | 20deaa21c1ed4f52d5d6a7991450d90103a7fe8e | c02aa079d21cf9828f188153e5d65c1f0d62021c | refs/heads/master | 2020-04-06T03:34:11.834637 | 2016-09-09T14:41:55 | 2016-09-09T14:41:55 | 33,724,799 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 118 | cpp | #include "yocto/utest/driver.hpp"
YOCTO_UNIT_TEST_INIT(8)
{
YOCTO_UNIT_TEST_DECL(vm);
}
YOCTO_UNIT_TEST_EXEC()
| [
"yann.bouret@gmail.com@6d5338fb-0854-7327-6163-5cad528299e9"
] | yann.bouret@gmail.com@6d5338fb-0854-7327-6163-5cad528299e9 |
6bed07d565bb6b1fcb55e3b62c7551eb21b38cde | 9a488a219a4f73086dc704c163d0c4b23aabfc1f | /tags/Release-1_0_0/src/FbTk/XmbFontImp.hh | 992fa903347cbfbf9d9163fd4a8b060d256e01cb | [
"MIT"
] | permissive | BackupTheBerlios/fluxbox-svn | 47b8844b562f56d02b211fd4323c2a761b473d5b | 3ac62418ccf8ffaddbf3c181f28d2f652543f83f | refs/heads/master | 2016-09-05T14:55:27.249504 | 2007-12-14T23:27:57 | 2007-12-14T23:27:57 | 40,667,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,313 | hh | // XmbFontImp.hh for FbTk fluxbox toolkit
// Copyright (c) 2002-2003 Henrik Kinnunen (fluxgen at fluxbox dot org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id$
#ifndef FBTK_XMBFONTIMP_HH
#define FBTK_XMBFONTIMP_HH
#include "FontImp.hh"
#include <X11/Xlib.h>
namespace FbTk {
/// multibyte font implementation for FbTk
class XmbFontImp:public FbTk::FontImp {
public:
XmbFontImp(const char *fontname, bool utf8);
~XmbFontImp();
bool load(const std::string &name);
virtual void drawText(const FbDrawable &w, int screen, GC gc, const FbString &text, size_t len, int x, int y, FbTk::Orientation orient);
unsigned int textWidth(const FbString &text, unsigned int len) const;
unsigned int height() const;
int ascent() const { return m_setextents ? -m_setextents->max_ink_extent.y : 0; }
int descent() const { return m_setextents ? m_setextents->max_ink_extent.height + m_setextents->max_ink_extent.y : 0; }
bool loaded() const { return m_fontset != 0; }
bool utf8() const { return m_utf8mode; }
bool validOrientation(FbTk::Orientation orient) { return true; }; // rotated on demand
private:
XFontSet m_fontset;
XFontSetExtents *m_setextents;
bool m_utf8mode;
};
} // end namespace FbTk
#endif // FBTK_XMBFONTIMP_HH
| [
"fluxgen@54ec5f11-9ae8-0310-9a2b-99d706b22625"
] | fluxgen@54ec5f11-9ae8-0310-9a2b-99d706b22625 |
9cea57f5438f0240f26cbb12c22722827e788c7d | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /iai/src/v20180301/model/AnalyzeDenseLandmarksRequest.cpp | 9a657776dd3492ceec8f98d3472e79049d75cde4 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 4,527 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/iai/v20180301/model/AnalyzeDenseLandmarksRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Iai::V20180301::Model;
using namespace std;
AnalyzeDenseLandmarksRequest::AnalyzeDenseLandmarksRequest() :
m_modeHasBeenSet(false),
m_imageHasBeenSet(false),
m_urlHasBeenSet(false),
m_faceModelVersionHasBeenSet(false),
m_needRotateDetectionHasBeenSet(false)
{
}
string AnalyzeDenseLandmarksRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_modeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Mode";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_mode, allocator);
}
if (m_imageHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Image";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_image.c_str(), allocator).Move(), allocator);
}
if (m_urlHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Url";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_url.c_str(), allocator).Move(), allocator);
}
if (m_faceModelVersionHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "FaceModelVersion";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_faceModelVersion.c_str(), allocator).Move(), allocator);
}
if (m_needRotateDetectionHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "NeedRotateDetection";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_needRotateDetection, allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
uint64_t AnalyzeDenseLandmarksRequest::GetMode() const
{
return m_mode;
}
void AnalyzeDenseLandmarksRequest::SetMode(const uint64_t& _mode)
{
m_mode = _mode;
m_modeHasBeenSet = true;
}
bool AnalyzeDenseLandmarksRequest::ModeHasBeenSet() const
{
return m_modeHasBeenSet;
}
string AnalyzeDenseLandmarksRequest::GetImage() const
{
return m_image;
}
void AnalyzeDenseLandmarksRequest::SetImage(const string& _image)
{
m_image = _image;
m_imageHasBeenSet = true;
}
bool AnalyzeDenseLandmarksRequest::ImageHasBeenSet() const
{
return m_imageHasBeenSet;
}
string AnalyzeDenseLandmarksRequest::GetUrl() const
{
return m_url;
}
void AnalyzeDenseLandmarksRequest::SetUrl(const string& _url)
{
m_url = _url;
m_urlHasBeenSet = true;
}
bool AnalyzeDenseLandmarksRequest::UrlHasBeenSet() const
{
return m_urlHasBeenSet;
}
string AnalyzeDenseLandmarksRequest::GetFaceModelVersion() const
{
return m_faceModelVersion;
}
void AnalyzeDenseLandmarksRequest::SetFaceModelVersion(const string& _faceModelVersion)
{
m_faceModelVersion = _faceModelVersion;
m_faceModelVersionHasBeenSet = true;
}
bool AnalyzeDenseLandmarksRequest::FaceModelVersionHasBeenSet() const
{
return m_faceModelVersionHasBeenSet;
}
int64_t AnalyzeDenseLandmarksRequest::GetNeedRotateDetection() const
{
return m_needRotateDetection;
}
void AnalyzeDenseLandmarksRequest::SetNeedRotateDetection(const int64_t& _needRotateDetection)
{
m_needRotateDetection = _needRotateDetection;
m_needRotateDetectionHasBeenSet = true;
}
bool AnalyzeDenseLandmarksRequest::NeedRotateDetectionHasBeenSet() const
{
return m_needRotateDetectionHasBeenSet;
}
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
e03ce96bd4dcb5f926317b7f92f8d6f4318649f2 | 13733f7ccd0746696dc259883258ab58765fa002 | /CrossBridge_9/CrossBridge/CrossBridge2.cpp | ed6275fa901fa146679c6798ec647092083dd304 | [] | no_license | dxu1962/MyCode1962 | a934731eae8cd239cdecb61be7949b948f693eb7 | 95ce7c31be6acb8eb0756551fc820ff583f259a4 | refs/heads/master | 2020-05-25T23:01:59.105155 | 2019-05-22T14:28:33 | 2019-05-22T14:28:33 | 188,026,611 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | cpp | #include "stdafx.h"
#include "CrossBridge2.h"
CrossBridge2::CrossBridge2(pair_vec &vec)
{
m_mem_vec = vec;
m_n = 2;
if ((signed int)vec.size() < 2)
throw "Number of team members is wrong!";
}
int CrossBridge2::TimetoTake()
{
RecordActions(true, m_mem_vec[0], m_mem_vec[1]);
return m_mem_vec[1].second;
}
| [
"noreply@github.com"
] | dxu1962.noreply@github.com |
e6467faf33c38a35d91275972be8acdb7169b9fc | 0ddc636e228e5b93737f22f6edd6c51317f81cfc | /busitem_prod.h | 23d1be240e8d91f1e5856e69bd54727f1c61fc97 | [] | no_license | victronenergy/dbus_qwacs | 429dd33e12f7d3d6776360414be60f434009f411 | 8c6c800f77edd528d7ae395aeea23485be6d8de5 | refs/heads/master | 2021-01-18T21:47:09.899977 | 2020-07-14T10:34:03 | 2020-07-14T10:34:03 | 16,987,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 820 | h | #ifndef BUSITEMPROD_H
#define BUSITEMPROD_H
#include "busitem_adaptor.h"
class BusItemProd : public QObject
{
Q_OBJECT
Q_PROPERTY(QDBusVariant value READ getValue)
public:
BusItemProd(QObject *parent = 0);
BusItemProd(const QVariant &value, QObject *parent = 0);
BusItemProd(const QString &value, QObject *parent = 0);
~BusItemProd();
void setValue(const QVariant &value);
void setText(const QString &text);
void invalidate();
public slots:
QDBusVariant getValue() { return QDBusVariant(mValue); }
QString getText() { return mText; }
void propertiesUpdated();
signals:
void PropertiesChanged(const QVariantMap &changes);
private:
static QStringList invalidValue;
BusItemAdaptor* mBusItem;
QVariantMap mChanges;
//bool mInitialized;
QVariant mValue;
QString mText;
};
#endif // BUSITEMPROD_H
| [
"mmulder@victronenergy.com"
] | mmulder@victronenergy.com |
bec408a9cdf61df1e23efd633395536d4e67a55c | 4d430e7af78988fcf2e60a7f36c99a32e133dfc9 | /hihocoder/no1531.cpp | b7cad1f6138337b2f662de7ab319711a490921f8 | [] | no_license | SFZhang26/Algorithm | f67974ec0bca1814bf69c9dbaa1788fbe6be6853 | 94d7f5a79a4e517291f035759185fd9f1a03f797 | refs/heads/master | 2021-03-31T01:58:23.182696 | 2017-11-08T09:18:44 | 2017-11-08T09:18:44 | 83,506,627 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,892 | cpp | #include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <map>
#include <string>
#include <bitset>
#include <set>
using namespace std;
typedef long long ll;
int n, k;
int u, x;
int pic[7]; //fruit + animal
vector<vector<int>> history(11, vector<int>(7, 0));
vector<ll> card(10, 1e7);
ll card_num = 0;
int turn = 0;
void reset() {
for (int i = 0; i < 7; i++) pic[i] = 0;
card_num = 0;
history = vector<vector<int>>(11, vector<int>(7, 0));
}
bool judge() {
for (int i = 0; i < 4; i++) {
if (pic[i] == 5) return true;
}
if (pic[4]>0 && (pic[0]>0 || pic[1]>0 || pic[2]>0) && pic[3] == 0) {
return true;
}
if (pic[5] > 0 && (pic[0] > 0 || pic[3] > 0 || pic[2] > 0) && pic[1] == 0) {
return true;
}
if (pic[6] > 0 && (pic[0] > 0 || pic[1] > 0 || pic[2] > 0 || pic[3]>0)) {
return true;
}
return false;
}
void bell(int index) {
if (judge()) {
card[index] += card_num;
reset();
}
else {
for (int i = 0; i < n; i++) {
card[i]++;
}
card[index] -= n;
}
turn = u;
}
int main() {
scanf("%d %d", &n, &k);
for (int i = 0; i < k; i++) {
char s[10];
scanf("%s %d", s, &u);
if (strcmp(s, "Fruit") == 0) {
card_num++;
card[turn]--;
vector<int> cur(7, 0);
for (int j = 0; j < u; j++) {
scanf("%d", &x);
cur[x] ++;
}
for (int j = 0; j < 7; j++) {
pic[j] += (cur[j] - history[turn][j]);
}
history[turn] = cur;
turn = (turn + 1) % n;
}
else if (strcmp(s, "Animal") == 0) {
card_num++;
card[turn]--;
for (int j = 0; j < 7; j++) {
pic[j] -= history[turn][j];
history[turn][j] = 0;
}
history[turn][4 + u] = 1;
pic[4 + u] ++;
turn = (turn + 1) % n;
}
else {
bell(u);
}
}
for (int i = 0; i < n; i++) {
cout << card[i] << endl;
}
return 0;
} | [
"sf_zhang26@163.com"
] | sf_zhang26@163.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.