Commit 5c343bd8 authored by captainwong's avatar captainwong

update java demo

parent b8d0dbdc
......@@ -23,6 +23,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "server_demo", "server_demo\
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ademco_java", "javademo\cpp\ademco_java.vcxproj", "{B323151B-AD89-4545-B95E-E2442A7961BB}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "server_demo_libevent", "server_demo_libevent\server_demo_libevent.vcxproj", "{AD6D6F3B-B39D-4F70-9940-3AB4FC870974}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -105,6 +107,16 @@ Global
{B323151B-AD89-4545-B95E-E2442A7961BB}.Release|x64.Build.0 = Release|x64
{B323151B-AD89-4545-B95E-E2442A7961BB}.Release|x86.ActiveCfg = Release|Win32
{B323151B-AD89-4545-B95E-E2442A7961BB}.Release|x86.Build.0 = Release|Win32
{AD6D6F3B-B39D-4F70-9940-3AB4FC870974}.Debug|Any CPU.ActiveCfg = Debug|Win32
{AD6D6F3B-B39D-4F70-9940-3AB4FC870974}.Debug|x64.ActiveCfg = Debug|x64
{AD6D6F3B-B39D-4F70-9940-3AB4FC870974}.Debug|x64.Build.0 = Debug|x64
{AD6D6F3B-B39D-4F70-9940-3AB4FC870974}.Debug|x86.ActiveCfg = Debug|Win32
{AD6D6F3B-B39D-4F70-9940-3AB4FC870974}.Debug|x86.Build.0 = Debug|Win32
{AD6D6F3B-B39D-4F70-9940-3AB4FC870974}.Release|Any CPU.ActiveCfg = Release|Win32
{AD6D6F3B-B39D-4F70-9940-3AB4FC870974}.Release|x64.ActiveCfg = Release|x64
{AD6D6F3B-B39D-4F70-9940-3AB4FC870974}.Release|x64.Build.0 = Release|x64
{AD6D6F3B-B39D-4F70-9940-3AB4FC870974}.Release|x86.ActiveCfg = Release|Win32
{AD6D6F3B-B39D-4F70-9940-3AB4FC870974}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......
......@@ -29,7 +29,7 @@
2. 使用 `Visual Studio 2019` 打开 `ademco_hb.sln`, 以 `Release/x64` 编译 `ademco_java` 项目,可能需要修改项目属性 `C/C++` --> `Additional Include Directories`,将与 `Java` 相关的路径修改,生成 `x64/Release/ademco_java.dll`
3. `javac javademo/jni/SimpleServer.java` 编译示例
3. `javac -encoding utf-8 javademo/jni/SimpleServer.java` 编译示例
4. `java javademo.jni.SimpleServer 12345` 进行测试
......
......@@ -29,8 +29,23 @@ public class SimpleServerThread extends Thread {
.digit(s.charAt(i + 1), 16));
}
return b;
}
}
public static String printable_bytes(byte[] b){
String HEX_STRING = "0123456789ABCDEF";
String s = "";
for(int i = 0; i < b.length; i++){
byte c = b[i];
if(32 <= c && c <= 127){
s += (char)c;
}else{
s += "\\x" + HEX_STRING.charAt(b[i] >>> 4);
s += HEX_STRING.charAt(b[i] & 0x0F);
}
}
return s;
}
public void run() {
......@@ -94,15 +109,25 @@ public class SimpleServerThread extends Thread {
System.out.println("Found gg: " + gg);
System.out.println("Found zone: " + zone);
// 主机状态改变间隔超过5秒,则触发一次远程控制命令发送给主机
if(ademco_event == 3400 || ademco_event == 1400){
long now = System.currentTimeMillis();
if(now - lastTimeStatusChange > 5000){
lastTimeStatusChange = now;
String cmd = lib.pack2(seq+1, acct, ademco_id16, ademco_event == 3400 ? 1400 : 3400, gg, zone, "123456");
System.out.println("sending command:" + cmd);
byte[] data = hexStringToByteArray(cmd);
output.write(data);
output.flush();
if(ademco_event == 3400){ // 布防则发撤防命令
String cmd = lib.pack2(seq+1, acct, ademco_id16, 1400, 0, 0, "123456");
byte[] data = hexStringToByteArray(cmd);
System.out.println("sending 1400 command:" + printable_bytes(data));
output.write(data);
output.flush();
}else{ // 撤防就发布防命令
String cmd = lib.pack(seq+1, acct, ademco_id16, 3400, 0, 0);
System.out.println("sending 3400 command:" + cmd);
writer.write(ack);
writer.flush();
}
}
}
}else{
......
......@@ -28,9 +28,15 @@
using namespace ademco;
void op_usage()
{
printf("Press A for Arm, D for Disarm, E for Emergency, Q for Quit\n");
}
void usage(const char* name)
{
printf("Usage: %s listening_port\nWhile connection established, press A for Arm, D for Disarm, E for Emergency, Q for Quit\n", name);
printf("Usage: %s listening_port\n", name);
op_usage();
}
constexpr size_t BUFF_SIZE = 4096;
......@@ -307,7 +313,7 @@ int main(int argc, char** argv)
worker.join();
break;
} else {
printf("Press A for Arm, D for Disarm, E for Emergency, Q for Quit\n");
op_usage();
}
}
......
#ifndef _WIN32
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#else
# ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
# endif
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
#endif
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#include <thread>
#include <vector>
#include <mutex>
#include <string>
#include <event2/listener.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#if !defined(LIBEVENT_VERSION_NUMBER) || LIBEVENT_VERSION_NUMBER < 0x02010100
#error "This version of Libevent is not supported; Get 2.1.1-alpha or later."
#endif
#define DISABLE_JLIB_LOG2
#include <ademco_packet.h>
using namespace ademco;
void op_usage()
{
printf("Press A for Arm, D for Disarm, E for Emergency, Q for Quit\n");
}
void usage(const char* name)
{
printf("Usage: %s listening_port\n", name);
op_usage();
}
struct Client {
int fd = 0;
std::string acct = {};
int ademco_id = 0;
};
void readcb(struct bufferevent* bev, void* user_data)
{
//evbuffer_add_buffer(bufferevent_get_output(bev), bufferevent_get_input(bev));
}
void eventcb(struct bufferevent* bev, short events, void* user_data)
{
int fd = bufferevent_getfd(bev);
printf("eventcb events=%04X\n", events);
if (events & BEV_EVENT_EOF) {
} else if (events & (BEV_EVENT_WRITING)) {
printf("Got an error while writing #%d.\n", fd);
} else if (events & (BEV_EVENT_ERROR)) {
printf("Got an error on the connection %d: %s\n",
fd, strerror(errno));
}
printf("Connection #%d closed.\n", fd);
bufferevent_free(bev);
}
void accept_cb(evconnlistener* listener, evutil_socket_t fd, sockaddr* addr, int socklen, void* context)
{
char str[INET_ADDRSTRLEN] = { 0 };
auto sin = (sockaddr_in*)addr;
inet_ntop(AF_INET, &sin->sin_addr, str, INET_ADDRSTRLEN);
printf("accpet TCP connection from: %s:%d\n", str, sin->sin_port);
//evutil_make_socket_nonblocking(fd);
auto base = evconnlistener_get_base(listener);
auto bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
if (!bev) {
fprintf(stderr, "Error constructing bufferevent!\n");
event_base_loopbreak(base);
return;
}
bufferevent_setcb(bev, readcb, nullptr, eventcb, nullptr);
bufferevent_enable(bev, EV_WRITE | EV_READ);
}
void accpet_error_cb(evconnlistener* listener, void* context)
{
auto base = evconnlistener_get_base(listener);
int err = EVUTIL_SOCKET_ERROR();
fprintf(stderr, "accpet_error_cb:%d:%s\n", err, evutil_socket_error_to_string(err));
event_base_loopexit(base, nullptr);
}
int main(int argc, char** argv)
{
#ifdef _WIN32
WSADATA wsa_data;
WSAStartup(0x0201, &wsa_data);
#endif
int port = 12345;
if (argc > 1) {
port = atoi(argv[1]);
if (port <= 0 || port > 65535) {
puts("Invalid port");
return 1;
}
}
sockaddr_in sin = { 0 };
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(port);
printf("using libevent %s\n", event_get_version());
auto base = event_base_new();
if (!base) {
fprintf(stderr, "init libevent failed\n");
return -1;
}
auto listener = evconnlistener_new_bind(base,
accept_cb,
nullptr,
LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE,
-1, // backlog, -1 for default
(sockaddr*)(&sin),
sizeof(sin));
if (!listener) {
fprintf(stderr, "create listener failed\n");
return -1;
}
printf("%s is listening on port %d\n", argv[0], port);
evconnlistener_set_error_cb(listener, accpet_error_cb);
event_base_dispatch(base);
return 0;
}
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{ad6d6f3b-b39d-4f70-9940-3ab4fc870974}</ProjectGuid>
<RootNamespace>serverdemolibevent</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(SolutionDir)..\include;$(DEVLIBS)\libevent-2.1.12-stable-install\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>$(DEVLIBS)\libevent-2.1.12-stable-install\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>event_core.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(DEVLIBS)\libevent-2.1.12-stable-install\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(DEVLIBS)\libevent-2.1.12-stable-install\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="server_demo_libevent.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="server_demo_libevent.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment