feat: modbus

This commit is contained in:
dawnwinterLiu 2024-03-07 10:10:25 +08:00
parent d6978b09d7
commit 92352345fa
46 changed files with 5034 additions and 48 deletions

View File

@ -103,4 +103,36 @@
<img src="https://dgiot-1253666439.cos.ap-shanghai-fsi.myqcloud.com/atom/viewps.jpg" width = "100%" />
## **六gRPC**
### 1:grpc介绍
gRPC是一个高性能开源和通用的RPC框架基于Protobuf序列化协议开发且支持众多开发语言。gRPC基于以下理念定义一个服务指定其能够被远程调用的方法包含参数和返回类型。在服务端实现这个接口。并运行一个gRPC服务器来处理客户端调用。在客户端拥有一个存根能够向服务端一样的方法。
### 2:dgiot_grpc_python连接
![1.png](http://dgiot-1253666439.cos.ap-shanghai-fsi.myqcloud.com/dgiot_web/doc_gjb/grpc/1.png)
### 3:Dgiot客户端
dgiot通过grpc与其他语言相互通信以及函数调用。在dgiot中以一个grpc通道处理所有交互。而grpc相关函数定义在dgiot_dlink下分为login,logout,send三个函数。
![1.png](http://dgiot-1253666439.cos.ap-shanghai-fsi.myqcloud.com/dgiot_web/doc_gjb/grpc/2.png)
+ login
login函数用于登录grpc服务端其参数为ClinetId为客户端编号。建立grpc通道后将会在通道启动时以通道id为ClinetId登录python服务器。
+ send
send函数用于向python客户端发送消息。send函数位于通道的handle_message函数中。在通道接收到消息并且匹配上Message中内容后即可根据消息内容执行send函数调用python服务。
send函数以map的格式发送消息消息在发送前将经过base64编码。
+ logout
logout函数用于断开与python服务的连接一般在通道的关闭函数stop中调用。
### 4:Python 程序文件
python程序示例位于插件\priv\example\python3目录下其目录结构如下
![1.png](http://dgiot-1253666439.cos.ap-shanghai-fsi.myqcloud.com/dgiot_web/doc_gjb/grpc/3.png)
运行dlink_server文件即可启动python服务接收信息函数位于Dlink类下SayHello方法。其接收request和context两个参数参数含义如下
+ 1.request接收参数request下name属性为接收到的信息。
+ 2.context接收参数当前的环境
通过对request.name使用base64解码并转为字典后即可获取原本的信息。
![1.png](http://dgiot-1253666439.cos.ap-shanghai-fsi.myqcloud.com/dgiot_web/doc_gjb/grpc/4.png)
接收参数后通过HelloReply的message字段返回一条信息
![1.png](http://dgiot-1253666439.cos.ap-shanghai-fsi.myqcloud.com/dgiot_web/doc_gjb/grpc/5.png)
完整交互结果如下图:
![1.png](http://dgiot-1253666439.cos.ap-shanghai-fsi.myqcloud.com/dgiot_web/doc_gjb/grpc/6.png)
### 5:gRPC官方文档
https://grpc.io/docs/

View File

@ -1,4 +1,4 @@
-define(ATOMGIT, <<"ATOMGIT">>).
-define(atomgit, <<"atomgit">>).
-record(state, {
id,

View File

@ -0,0 +1,23 @@
.rebar3
_*
.eunit
*.o
*.beam
*.plt
*.swp
*.swo
.erlang.cookie
ebin
log
erl_crash.dump
.rebar
logs
_build
.idea
*.iml
rebar3.crashdump
*~
rebar.lock
src/route_guide_pb.erl
src/routeguide_route_guide_bhvr.erl
src/routeguide_route_guide_client.erl

View File

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2021, JianBo He <heeejianbo@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.

View File

@ -0,0 +1,53 @@
# route_guide
The example application for grpc
## Build
```
rebar3 compile
```
## Usage
1. Start the rebar3 shell
```
rebar3 shell
```
2. Start the `route_guide` services in the rebar3 shell
```erl
1> route_guide:start_services().
Start service route_guide on 10000 successfully!
```
3. Start the client channel
```erl
2> route_guide:start_client_channel().
Start client channel channel1 for http://127.0.0.1:10000 successfully!
```
4. Call the `get_feature` method of route_guide services
```erl
3> routeguide_route_guide_client:get_feature(#{latitude => 1, longitude => 1}, #{channel => channel1}).
{ok,#{name => <<>>},
[{<<"grpc-message">>,<<>>},{<<"grpc-status">>,<<"0">>}]}
```
## Project Structure
```
├── priv
│   └── route_guide.proto %% The grpc services defined file
└── src
├── route_guide.app.src
├── route_guide.erl %% mainly example codes
├── route_guide_pb.erl %% generated by gpb
├── route_guide_svr.erl %% the route_guide service implementation
├── routeguide_route_guide_bhvr.erl %% generated by grpc-plugin
└── routeguide_route_guide_client.erl %% generated by grpc-plugin
```

View File

@ -0,0 +1,125 @@
// Copyright 2015, Google 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 Google 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.routeguide";
option java_outer_classname = "RouteGuideProto";
package routeguide;
// Interface exported by the server.
service RouteGuide {
// A simple RPC.
//
// Obtains the feature at a given position.
//
// A feature with an empty name is returned if there's no feature at the given
// position.
rpc GetFeature(Point) returns (Feature) {}
// A server-to-client streaming RPC.
//
// Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a
// repeated field), as the rectangle may cover a large area and contain a
// huge number of features.
rpc ListFeatures(Rectangle) returns (stream Feature) {}
// A client-to-server streaming RPC.
//
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
// A Bidirectional streaming RPC.
//
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
}
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
message Point {
int32 latitude = 1;
int32 longitude = 2;
}
// A latitude-longitude rectangle, represented as two diagonally opposite
// points "lo" and "hi".
message Rectangle {
// One corner of the rectangle.
Point lo = 1;
// The other corner of the rectangle.
Point hi = 2;
}
// A feature names something at a given point.
//
// If a feature could not be named, the name is empty.
message Feature {
// The name of the feature.
string name = 1;
// The point where the feature is detected.
Point location = 2;
}
// A RouteNote is a message sent while at a given point.
message RouteNote {
// The location from which the message is sent.
Point location = 1;
// The message to be sent.
string message = 2;
}
// A RouteSummary is received in response to a RecordRoute rpc.
//
// It contains the number of individual points received, the number of
// detected features, and the total distance covered as the cumulative sum of
// the distance between each point.
message RouteSummary {
// The number of points received.
int32 point_count = 1;
// The number of known features passed while traversing the route.
int32 feature_count = 2;
// The distance covered in metres.
int32 distance = 3;
// The duration of the traversal in seconds.
int32 elapsed_time = 4;
}

View File

@ -0,0 +1,22 @@
{erl_opts, [debug_info]}.
{plugins,
[rebar3_proper,
{grpc_plugin, {git, "https://gitee.com/fastdgiot/grpc_plugin.git", {tag, "v0.10.3"}}}
]}.
{deps,
[{grpc, {git, "https://gitee.com/fastdgiot/grpc-erl", {tag, "0.6.4"}}}
]}.
{grpc,
[ {type, all}
, {protos, ["priv/"]}
, {out_dir, "src/"}
, {gpb_opts, [{module_name_suffix, "_pb"}]}
]}.
{provider_hooks,
[{pre, [{compile, {grpc, gen}},
{clean, {grpc, clean}}]}
]}.

Binary file not shown.

View File

@ -0,0 +1,11 @@
{application, route_guide,
[{description, "An OTP application"},
{vsn, "0.1.0"},
{registered, []},
{mod, {route_guide, []}},
{applications, [kernel,stdlib,grpc]},
{env,[]},
{modules, []},
{licenses, ["Apache 2.0"]},
{links, []}
]}.

View File

@ -0,0 +1,64 @@
-module(route_guide).
-behaviour(supervisor).
-behaviour(application).
-export([start/2, stop/1]).
-export([init/1]).
-export([start_services/0, start_client_channel/0,
stop_services/0, stop_client_channel/0]).
%%--------------------------------------------------------------------
%% APIs
-define(SERVER_NAME, route_guide).
-define(CHANN_NAME, channel1).
start_services() ->
Services = #{protos => [route_guide_pb],
services => #{'routeguide.RouteGuide' => route_guide_svr}
},
Options = [],
{ok, _} = grpc:start_server(?SERVER_NAME, 10000, Services, Options),
io:format("Start service ~s on 10000 successfully!~n", [?SERVER_NAME]).
start_client_channel() ->
ClientOps = #{},
SvrAddr = "http://127.0.0.1:10000",
{ok, _} = grpc_client_sup:create_channel_pool(
?CHANN_NAME,
SvrAddr,
ClientOps
),
io:format("Start client channel ~s for ~s successfully!~n~n"
"Call the 'routeguide_route_guide_client' module exported functions "
"to use it. e.g:~n"
" routeguide_route_guide_client:get_feature(#{latitude => 1"
", longitude => 1}, #{channel => channel1}).~n",
[?CHANN_NAME, SvrAddr]).
stop_services() ->
grpc:stop_server(?SERVER_NAME).
stop_client_channel() ->
grpc_client_sup:stop_channel_pool(?CHANN_NAME).
%%--------------------------------------------------------------------
%% APIs for application
start(_StartType, _StartArgs) ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
stop(_State) ->
ok.
%%--------------------------------------------------------------------
%% callbacks for supervisor
init([]) ->
SupFlags = #{strategy => one_for_all,
intensity => 0,
period => 1},
ChildSpecs = [],
{ok, {SupFlags, ChildSpecs}}.

View File

@ -0,0 +1,56 @@
-module(route_guide_svr).
-behavior(routeguide_route_guide_bhvr).
-compile(export_all).
-compile(nowarn_export_all).
-define(LOG(Fmt, Args), io:format(standard_error, "[Svr] " ++ Fmt, Args)).
%%--------------------------------------------------------------------
%% Callbacks
get_feature(Request, _Md) ->
?LOG("~p: ~0p~n", [?FUNCTION_NAME, Request]),
{ok, #{}, _Md}.
list_features(Stream, _Md) ->
{eos, [Request], NStream} = grpc_stream:recv(Stream),
?LOG("~p: ~0p~n", [?FUNCTION_NAME, Request]),
grpc_stream:reply(Stream, [#{name => "City1", location => #{latitude => 1, longitude => 1}}]),
grpc_stream:reply(Stream, [#{name => "City2", location => #{latitude => 2, longitude => 2}}]),
grpc_stream:reply(Stream, [#{name => "City3", location => #{latitude => 3, longitude => 3}}]),
{ok, NStream}.
record_route(Stream, _Md) ->
LoopRecv = fun _Lp(St, Acc) ->
case grpc_stream:recv(St) of
{more, Reqs, NSt} ->
?LOG("~p: ~0p~n", [?FUNCTION_NAME, Reqs]),
_Lp(NSt, Acc ++ Reqs);
{eos, Reqs, NSt} ->
?LOG("~p: ~0p~n", [?FUNCTION_NAME, Reqs]),
{NSt, Acc ++ Reqs}
end
end,
{NStream, Points} = LoopRecv(Stream, []),
grpc_stream:reply(NStream, #{point_count => length(Points)}),
{ok, NStream}.
route_chat(Stream, _Md) ->
grpc_stream:reply(Stream, [#{name => "City1", location => #{latitude => 1, longitude => 1}}]),
grpc_stream:reply(Stream, [#{name => "City2", location => #{latitude => 2, longitude => 2}}]),
LoopRecv = fun _Lp(St) ->
case grpc_stream:recv(St) of
{more, Reqs, NSt} ->
?LOG("~p: ~0p~n", [?FUNCTION_NAME, Reqs]),
_Lp(NSt);
{eos, Reqs, NSt} ->
?LOG("~p: ~0p~n", [?FUNCTION_NAME, Reqs]),
NSt
end
end,
NStream = LoopRecv(Stream),
grpc_stream:reply(NStream, [#{name => "City3", location => #{latitude => 3, longitude => 3}}]),
{ok, NStream}.

View File

@ -0,0 +1,100 @@
/*
* Copyright 2015 The gRPC Authors
*
* 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.
*/
package io.grpc.examples.helloworld;
import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* https://github.com/grpc/grpc-java/blob/v1.47.0/examples/src/main/java/io/grpc/examples/helloworld/HelloWorldClient.java
* A simple client that requests a greeting from the {@link HelloWorldServer}.
*/
public class HelloWorldClient {
private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
private final GreeterGrpc.GreeterBlockingStub blockingStub;
/** Construct client for accessing HelloWorld server using the existing channel. */
public HelloWorldClient(Channel channel) {
// 'channel' here is a Channel, not a ManagedChannel, so it is not this code's responsibility to
// shut it down.
// Passing Channels to code makes code easier to test and makes it easier to reuse Channels.
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
/** Say hello to server. */
public void greet(String name) {
logger.info("Will try to greet " + name + " ...");
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response;
try {
response = blockingStub.sayHello(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
logger.info("Greeting: " + response.getMessage());
}
/**
* Greet server. If provided, the first element of {@code args} is the name to use in the
* greeting. The second argument is the target server.
*/
public static void main(String[] args) throws Exception {
String user = "world";
// Access a service running on the local machine on port 50051
String target = "localhost:50051";
// Allow passing in the user and target strings as command line arguments
if (args.length > 0) {
if ("--help".equals(args[0])) {
System.err.println("Usage: [name [target]]");
System.err.println("");
System.err.println(" name The name you wish to be greeted by. Defaults to " + user);
System.err.println(" target The server to connect to. Defaults to " + target);
System.exit(1);
}
user = args[0];
}
if (args.length > 1) {
target = args[1];
}
// Create a communication channel to the server, known as a Channel. Channels are thread-safe
// and reusable. It is common to create channels at the beginning of your application and reuse
// them until the application shuts down.
ManagedChannel channel = ManagedChannelBuilder.forTarget(target)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext()
.build();
try {
HelloWorldClient client = new HelloWorldClient(channel);
client.greet(user);
} finally {
// ManagedChannels use resources like threads and TCP connections. To prevent leaking these
// resources the channel should be shut down when it will no longer be used. If it may be used
// again leave it running.
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
}
}

View File

@ -0,0 +1,91 @@
/*
* Copyright 2015 The gRPC Authors
*
* 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.
*/
package io.grpc.examples.helloworld;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
/**
* https://github.com/grpc/grpc-java/blob/v1.47.0/examples/src/main/java/io/grpc/examples/helloworld/HelloWorldClient.java
* Server that manages startup/shutdown of a {@code Greeter} server.
*/
public class HelloWorldServer {
private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());
private Server server;
private void start() throws IOException {
/* The port on which the server should run */
int port = 50051;
server = ServerBuilder.forPort(port)
.addService(new GreeterImpl())
.build()
.start();
logger.info("Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
try {
HelloWorldServer.this.stop();
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
System.err.println("*** server shut down");
}
});
}
private void stop() throws InterruptedException {
if (server != null) {
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
}
}
/**
* Await termination on the main thread since the grpc library uses daemon threads.
*/
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
/**
* Main launches the server from the command line.
*/
public static void main(String[] args) throws IOException, InterruptedException {
final HelloWorldServer server = new HelloWorldServer();
server.start();
server.blockUntilShutdown();
}
static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
}

View File

@ -0,0 +1,96 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.dgiot.dataserver</groupId>
<artifactId>grpcserver</artifactId>
<version>1.0-SNAPSHOT</version>
<name>grpcserver</name>
<description>grpcserver project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<protobuf.version>3.19.4</protobuf.version>
<grpc.version>1.26.0</grpc.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${protobuf.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-all</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- os系统信息插件, protobuf-maven-plugin需要获取系统信息下载相应的protobuf程序 -->
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
<!-- proto文件目录 -->
<protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot>
<!-- 生成的Java文件目录 -->
<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
<clearOutputDirectory>false</clearOutputDirectory>
<!--<outputDirectory>${project.build.directory}/generated-sources/protobuf</outputDirectory>-->
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,136 @@
package com.dgiot.dataserver.grpcserver;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.examples.dlink.DlinkGrpc;
import io.grpc.examples.dlink.HelloRequest;
import io.grpc.examples.dlink.HelloReply;
import io.grpc.examples.dlink.HealthCheckRequest;
import io.grpc.examples.dlink.HealthCheckResponse;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
/**
* 服务端
*/
public class TestServer {
//定义端口
private final int port = 50051;
//服务
private Server server;
//启动服务,并且接受请求
private void start() throws IOException {
server = ServerBuilder.forPort(port).addService(new DlinkImpl()).build().start();
System.out.println("服务开始启动-------");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("------shutting down gRPC server since JVM is shutting down-------");
TestServer.this.stop();
System.err.println("------server shut down------");
}
});
}
//stop服务
private void stop() {
if (server != null) {
server.shutdown();
}
}
//server阻塞到程序退出
private void blockUntilShutdown() throws InterruptedException {
if (server!=null){
server.awaitTermination();
}
}
//实现服务接口的类
private class DlinkImpl extends DlinkGrpc.DlinkImplBase {
// Sends a greeting
@Override
public void sayHello (HelloRequest request, StreamObserver<HelloReply> responseObserver) {
HelloReply build = HelloReply.newBuilder().setMessage(request.getName()).build();
//onNext()方法向客户端返回结果
responseObserver.onNext(build);
//告诉客户端这次调用已经完成
responseObserver.onCompleted();
}
// If the requested service is unknown, the call will fail with status
// NOT_FOUND.
@Override
public void check(HealthCheckRequest checkRequest, StreamObserver<HealthCheckResponse> responseObserver) {
System.out.println("健康检查:"+ checkRequest.getService());
HealthCheckResponse.ServingStatus servingStatus =getServingStatus(checkRequest);
HealthCheckResponse response = HealthCheckResponse.newBuilder()
.setStatus(servingStatus)
.build();
//onNext()方法向客户端返回结果
responseObserver.onNext(response);
//告诉客户端这次调用已经完成
responseObserver.onCompleted();
}
// Performs a watch for the serving status of the requested service.
// The server will immediately send back a message indicating the current
// serving status. It will then subsequently send a new message whenever
// the service's serving status changes.
//
// If the requested service is unknown when the call is received, the
// server will send a message setting the serving status to
// SERVICE_UNKNOWN but will *not* terminate the call. If at some
// future point, the serving status of the service becomes known, the
// server will send a new message with the service's serving status.
//
// If the call terminates with status UNIMPLEMENTED, then clients
// should assume this method is not supported and should not retry the
// call. If the call terminates with any other status (including OK),
// clients should retry the call with appropriate exponential backoff.
@Override
public void watch(HealthCheckRequest checkRequest, StreamObserver<HealthCheckResponse> responseObserver) {
System.out.println("健康检查 Stream:"+ checkRequest.getService());
HealthCheckResponse.ServingStatus servingStatus =getServingStatus(checkRequest);
HealthCheckResponse response = HealthCheckResponse.newBuilder()
.setStatus(servingStatus)
.build();
responseObserver.onNext(response);
}
private HealthCheckResponse.ServingStatus getServingStatus(HealthCheckRequest request){
HealthCheckResponse.ServingStatus servingStatus;
String service = request.getService();
switch(service){
case"":
servingStatus = HealthCheckResponse.ServingStatus.SERVING;
break;
case"mysql":
servingStatus = HealthCheckResponse.ServingStatus.SERVING; //checkMySQL();
break;
case"redis":
servingStatus = HealthCheckResponse.ServingStatus.SERVING;//checkRedis();
break;
default:
servingStatus = HealthCheckResponse.ServingStatus.UNKNOWN;
break;
}
return servingStatus;
}
}
public static void main(String[] args) throws IOException, InterruptedException {
final TestServer server=new TestServer();
server.start();
server.blockUntilShutdown();
}
}

View File

@ -0,0 +1,517 @@
package io.grpc.examples.dlink;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
* The dlink service definition.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.26.0)",
comments = "Source: dlink.proto")
public final class DlinkGrpc {
private DlinkGrpc() {}
public static final String SERVICE_NAME = "dgiot.Dlink";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<io.grpc.examples.dlink.HelloRequest,
io.grpc.examples.dlink.HelloReply> getSayHelloMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "SayHello",
requestType = io.grpc.examples.dlink.HelloRequest.class,
responseType = io.grpc.examples.dlink.HelloReply.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.grpc.examples.dlink.HelloRequest,
io.grpc.examples.dlink.HelloReply> getSayHelloMethod() {
io.grpc.MethodDescriptor<io.grpc.examples.dlink.HelloRequest, io.grpc.examples.dlink.HelloReply> getSayHelloMethod;
if ((getSayHelloMethod = DlinkGrpc.getSayHelloMethod) == null) {
synchronized (DlinkGrpc.class) {
if ((getSayHelloMethod = DlinkGrpc.getSayHelloMethod) == null) {
DlinkGrpc.getSayHelloMethod = getSayHelloMethod =
io.grpc.MethodDescriptor.<io.grpc.examples.dlink.HelloRequest, io.grpc.examples.dlink.HelloReply>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "SayHello"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
io.grpc.examples.dlink.HelloRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
io.grpc.examples.dlink.HelloReply.getDefaultInstance()))
.setSchemaDescriptor(new DlinkMethodDescriptorSupplier("SayHello"))
.build();
}
}
}
return getSayHelloMethod;
}
private static volatile io.grpc.MethodDescriptor<io.grpc.examples.dlink.HealthCheckRequest,
io.grpc.examples.dlink.HealthCheckResponse> getCheckMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "Check",
requestType = io.grpc.examples.dlink.HealthCheckRequest.class,
responseType = io.grpc.examples.dlink.HealthCheckResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<io.grpc.examples.dlink.HealthCheckRequest,
io.grpc.examples.dlink.HealthCheckResponse> getCheckMethod() {
io.grpc.MethodDescriptor<io.grpc.examples.dlink.HealthCheckRequest, io.grpc.examples.dlink.HealthCheckResponse> getCheckMethod;
if ((getCheckMethod = DlinkGrpc.getCheckMethod) == null) {
synchronized (DlinkGrpc.class) {
if ((getCheckMethod = DlinkGrpc.getCheckMethod) == null) {
DlinkGrpc.getCheckMethod = getCheckMethod =
io.grpc.MethodDescriptor.<io.grpc.examples.dlink.HealthCheckRequest, io.grpc.examples.dlink.HealthCheckResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "Check"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
io.grpc.examples.dlink.HealthCheckRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
io.grpc.examples.dlink.HealthCheckResponse.getDefaultInstance()))
.setSchemaDescriptor(new DlinkMethodDescriptorSupplier("Check"))
.build();
}
}
}
return getCheckMethod;
}
private static volatile io.grpc.MethodDescriptor<io.grpc.examples.dlink.HealthCheckRequest,
io.grpc.examples.dlink.HealthCheckResponse> getWatchMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "Watch",
requestType = io.grpc.examples.dlink.HealthCheckRequest.class,
responseType = io.grpc.examples.dlink.HealthCheckResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.SERVER_STREAMING)
public static io.grpc.MethodDescriptor<io.grpc.examples.dlink.HealthCheckRequest,
io.grpc.examples.dlink.HealthCheckResponse> getWatchMethod() {
io.grpc.MethodDescriptor<io.grpc.examples.dlink.HealthCheckRequest, io.grpc.examples.dlink.HealthCheckResponse> getWatchMethod;
if ((getWatchMethod = DlinkGrpc.getWatchMethod) == null) {
synchronized (DlinkGrpc.class) {
if ((getWatchMethod = DlinkGrpc.getWatchMethod) == null) {
DlinkGrpc.getWatchMethod = getWatchMethod =
io.grpc.MethodDescriptor.<io.grpc.examples.dlink.HealthCheckRequest, io.grpc.examples.dlink.HealthCheckResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.SERVER_STREAMING)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "Watch"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
io.grpc.examples.dlink.HealthCheckRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
io.grpc.examples.dlink.HealthCheckResponse.getDefaultInstance()))
.setSchemaDescriptor(new DlinkMethodDescriptorSupplier("Watch"))
.build();
}
}
}
return getWatchMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static DlinkStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<DlinkStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<DlinkStub>() {
@java.lang.Override
public DlinkStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new DlinkStub(channel, callOptions);
}
};
return DlinkStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static DlinkBlockingStub newBlockingStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<DlinkBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<DlinkBlockingStub>() {
@java.lang.Override
public DlinkBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new DlinkBlockingStub(channel, callOptions);
}
};
return DlinkBlockingStub.newStub(factory, channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static DlinkFutureStub newFutureStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<DlinkFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<DlinkFutureStub>() {
@java.lang.Override
public DlinkFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new DlinkFutureStub(channel, callOptions);
}
};
return DlinkFutureStub.newStub(factory, channel);
}
/**
* <pre>
* The dlink service definition.
* </pre>
*/
public static abstract class DlinkImplBase implements io.grpc.BindableService {
/**
* <pre>
* Sends a greeting
* </pre>
*/
public void sayHello(io.grpc.examples.dlink.HelloRequest request,
io.grpc.stub.StreamObserver<io.grpc.examples.dlink.HelloReply> responseObserver) {
asyncUnimplementedUnaryCall(getSayHelloMethod(), responseObserver);
}
/**
* <pre>
* If the requested service is unknown, the call will fail with status
* NOT_FOUND.
* </pre>
*/
public void check(io.grpc.examples.dlink.HealthCheckRequest request,
io.grpc.stub.StreamObserver<io.grpc.examples.dlink.HealthCheckResponse> responseObserver) {
asyncUnimplementedUnaryCall(getCheckMethod(), responseObserver);
}
/**
* <pre>
* Performs a watch for the serving status of the requested service.
* The server will immediately send back a message indicating the current
* serving status. It will then subsequently send a new message whenever
* the service's serving status changes.
* If the requested service is unknown when the call is received, the
* server will send a message setting the serving status to
* SERVICE_UNKNOWN but will *not* terminate the call. If at some
* future point, the serving status of the service becomes known, the
* server will send a new message with the service's serving status.
* If the call terminates with status UNIMPLEMENTED, then clients
* should assume this method is not supported and should not retry the
* call. If the call terminates with any other status (including OK),
* clients should retry the call with appropriate exponential backoff.
* </pre>
*/
public void watch(io.grpc.examples.dlink.HealthCheckRequest request,
io.grpc.stub.StreamObserver<io.grpc.examples.dlink.HealthCheckResponse> responseObserver) {
asyncUnimplementedUnaryCall(getWatchMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getSayHelloMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.examples.dlink.HelloRequest,
io.grpc.examples.dlink.HelloReply>(
this, METHODID_SAY_HELLO)))
.addMethod(
getCheckMethod(),
asyncUnaryCall(
new MethodHandlers<
io.grpc.examples.dlink.HealthCheckRequest,
io.grpc.examples.dlink.HealthCheckResponse>(
this, METHODID_CHECK)))
.addMethod(
getWatchMethod(),
asyncServerStreamingCall(
new MethodHandlers<
io.grpc.examples.dlink.HealthCheckRequest,
io.grpc.examples.dlink.HealthCheckResponse>(
this, METHODID_WATCH)))
.build();
}
}
/**
* <pre>
* The dlink service definition.
* </pre>
*/
public static final class DlinkStub extends io.grpc.stub.AbstractAsyncStub<DlinkStub> {
private DlinkStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected DlinkStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new DlinkStub(channel, callOptions);
}
/**
* <pre>
* Sends a greeting
* </pre>
*/
public void sayHello(io.grpc.examples.dlink.HelloRequest request,
io.grpc.stub.StreamObserver<io.grpc.examples.dlink.HelloReply> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getSayHelloMethod(), getCallOptions()), request, responseObserver);
}
/**
* <pre>
* If the requested service is unknown, the call will fail with status
* NOT_FOUND.
* </pre>
*/
public void check(io.grpc.examples.dlink.HealthCheckRequest request,
io.grpc.stub.StreamObserver<io.grpc.examples.dlink.HealthCheckResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getCheckMethod(), getCallOptions()), request, responseObserver);
}
/**
* <pre>
* Performs a watch for the serving status of the requested service.
* The server will immediately send back a message indicating the current
* serving status. It will then subsequently send a new message whenever
* the service's serving status changes.
* If the requested service is unknown when the call is received, the
* server will send a message setting the serving status to
* SERVICE_UNKNOWN but will *not* terminate the call. If at some
* future point, the serving status of the service becomes known, the
* server will send a new message with the service's serving status.
* If the call terminates with status UNIMPLEMENTED, then clients
* should assume this method is not supported and should not retry the
* call. If the call terminates with any other status (including OK),
* clients should retry the call with appropriate exponential backoff.
* </pre>
*/
public void watch(io.grpc.examples.dlink.HealthCheckRequest request,
io.grpc.stub.StreamObserver<io.grpc.examples.dlink.HealthCheckResponse> responseObserver) {
asyncServerStreamingCall(
getChannel().newCall(getWatchMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* <pre>
* The dlink service definition.
* </pre>
*/
public static final class DlinkBlockingStub extends io.grpc.stub.AbstractBlockingStub<DlinkBlockingStub> {
private DlinkBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected DlinkBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new DlinkBlockingStub(channel, callOptions);
}
/**
* <pre>
* Sends a greeting
* </pre>
*/
public io.grpc.examples.dlink.HelloReply sayHello(io.grpc.examples.dlink.HelloRequest request) {
return blockingUnaryCall(
getChannel(), getSayHelloMethod(), getCallOptions(), request);
}
/**
* <pre>
* If the requested service is unknown, the call will fail with status
* NOT_FOUND.
* </pre>
*/
public io.grpc.examples.dlink.HealthCheckResponse check(io.grpc.examples.dlink.HealthCheckRequest request) {
return blockingUnaryCall(
getChannel(), getCheckMethod(), getCallOptions(), request);
}
/**
* <pre>
* Performs a watch for the serving status of the requested service.
* The server will immediately send back a message indicating the current
* serving status. It will then subsequently send a new message whenever
* the service's serving status changes.
* If the requested service is unknown when the call is received, the
* server will send a message setting the serving status to
* SERVICE_UNKNOWN but will *not* terminate the call. If at some
* future point, the serving status of the service becomes known, the
* server will send a new message with the service's serving status.
* If the call terminates with status UNIMPLEMENTED, then clients
* should assume this method is not supported and should not retry the
* call. If the call terminates with any other status (including OK),
* clients should retry the call with appropriate exponential backoff.
* </pre>
*/
public java.util.Iterator<io.grpc.examples.dlink.HealthCheckResponse> watch(
io.grpc.examples.dlink.HealthCheckRequest request) {
return blockingServerStreamingCall(
getChannel(), getWatchMethod(), getCallOptions(), request);
}
}
/**
* <pre>
* The dlink service definition.
* </pre>
*/
public static final class DlinkFutureStub extends io.grpc.stub.AbstractFutureStub<DlinkFutureStub> {
private DlinkFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected DlinkFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new DlinkFutureStub(channel, callOptions);
}
/**
* <pre>
* Sends a greeting
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.examples.dlink.HelloReply> sayHello(
io.grpc.examples.dlink.HelloRequest request) {
return futureUnaryCall(
getChannel().newCall(getSayHelloMethod(), getCallOptions()), request);
}
/**
* <pre>
* If the requested service is unknown, the call will fail with status
* NOT_FOUND.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.examples.dlink.HealthCheckResponse> check(
io.grpc.examples.dlink.HealthCheckRequest request) {
return futureUnaryCall(
getChannel().newCall(getCheckMethod(), getCallOptions()), request);
}
}
private static final int METHODID_SAY_HELLO = 0;
private static final int METHODID_CHECK = 1;
private static final int METHODID_WATCH = 2;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final DlinkImplBase serviceImpl;
private final int methodId;
MethodHandlers(DlinkImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_SAY_HELLO:
serviceImpl.sayHello((io.grpc.examples.dlink.HelloRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.examples.dlink.HelloReply>) responseObserver);
break;
case METHODID_CHECK:
serviceImpl.check((io.grpc.examples.dlink.HealthCheckRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.examples.dlink.HealthCheckResponse>) responseObserver);
break;
case METHODID_WATCH:
serviceImpl.watch((io.grpc.examples.dlink.HealthCheckRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.examples.dlink.HealthCheckResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
private static abstract class DlinkBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier {
DlinkBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return io.grpc.examples.dlink.DlinkProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("Dlink");
}
}
private static final class DlinkFileDescriptorSupplier
extends DlinkBaseDescriptorSupplier {
DlinkFileDescriptorSupplier() {}
}
private static final class DlinkMethodDescriptorSupplier
extends DlinkBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final String methodName;
DlinkMethodDescriptorSupplier(String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (DlinkGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new DlinkFileDescriptorSupplier())
.addMethod(getSayHelloMethod())
.addMethod(getCheckMethod())
.addMethod(getWatchMethod())
.build();
}
}
}
return result;
}
}

View File

@ -0,0 +1,92 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dlink.proto
package io.grpc.examples.dlink;
public final class DlinkProto {
private DlinkProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_dgiot_HelloRequest_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_dgiot_HelloRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_dgiot_HelloReply_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_dgiot_HelloReply_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_dgiot_HealthCheckRequest_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_dgiot_HealthCheckRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_dgiot_HealthCheckResponse_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_dgiot_HealthCheckResponse_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\013dlink.proto\022\005dgiot\"\034\n\014HelloRequest\022\014\n\004" +
"name\030\001 \001(\t\"\035\n\nHelloReply\022\017\n\007message\030\001 \001(" +
"\t\"%\n\022HealthCheckRequest\022\017\n\007service\030\001 \001(\t" +
"\"\240\001\n\023HealthCheckResponse\0228\n\006status\030\001 \001(\016" +
"2(.dgiot.HealthCheckResponse.ServingStat" +
"us\"O\n\rServingStatus\022\013\n\007UNKNOWN\020\000\022\013\n\007SERV" +
"ING\020\001\022\017\n\013NOT_SERVING\020\002\022\023\n\017SERVICE_UNKNOW" +
"N\020\0032\277\001\n\005Dlink\0224\n\010SayHello\022\023.dgiot.HelloR" +
"equest\032\021.dgiot.HelloReply\"\000\022>\n\005Check\022\031.d" +
"giot.HealthCheckRequest\032\032.dgiot.HealthCh" +
"eckResponse\022@\n\005Watch\022\031.dgiot.HealthCheck" +
"Request\032\032.dgiot.HealthCheckResponse0\001B.\n" +
"\026io.grpc.examples.dlinkB\nDlinkProtoP\001\242\002\005" +
"dlinkb\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
});
internal_static_dgiot_HelloRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_dgiot_HelloRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_dgiot_HelloRequest_descriptor,
new java.lang.String[] { "Name", });
internal_static_dgiot_HelloReply_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_dgiot_HelloReply_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_dgiot_HelloReply_descriptor,
new java.lang.String[] { "Message", });
internal_static_dgiot_HealthCheckRequest_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_dgiot_HealthCheckRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_dgiot_HealthCheckRequest_descriptor,
new java.lang.String[] { "Service", });
internal_static_dgiot_HealthCheckResponse_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_dgiot_HealthCheckResponse_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_dgiot_HealthCheckResponse_descriptor,
new java.lang.String[] { "Status", });
}
// @@protoc_insertion_point(outer_class_scope)
}

View File

@ -0,0 +1,557 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dlink.proto
package io.grpc.examples.dlink;
/**
* Protobuf type {@code dgiot.HealthCheckRequest}
*/
public final class HealthCheckRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:dgiot.HealthCheckRequest)
HealthCheckRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use HealthCheckRequest.newBuilder() to construct.
private HealthCheckRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private HealthCheckRequest() {
service_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new HealthCheckRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private HealthCheckRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
service_ = s;
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HealthCheckRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HealthCheckRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.grpc.examples.dlink.HealthCheckRequest.class, io.grpc.examples.dlink.HealthCheckRequest.Builder.class);
}
public static final int SERVICE_FIELD_NUMBER = 1;
private volatile java.lang.Object service_;
/**
* <code>string service = 1;</code>
* @return The service.
*/
@java.lang.Override
public java.lang.String getService() {
java.lang.Object ref = service_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
service_ = s;
return s;
}
}
/**
* <code>string service = 1;</code>
* @return The bytes for service.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getServiceBytes() {
java.lang.Object ref = service_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
service_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(service_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, service_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(service_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, service_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof io.grpc.examples.dlink.HealthCheckRequest)) {
return super.equals(obj);
}
io.grpc.examples.dlink.HealthCheckRequest other = (io.grpc.examples.dlink.HealthCheckRequest) obj;
if (!getService()
.equals(other.getService())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + SERVICE_FIELD_NUMBER;
hash = (53 * hash) + getService().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.grpc.examples.dlink.HealthCheckRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HealthCheckRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HealthCheckRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HealthCheckRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HealthCheckRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HealthCheckRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HealthCheckRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HealthCheckRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static io.grpc.examples.dlink.HealthCheckRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HealthCheckRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static io.grpc.examples.dlink.HealthCheckRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HealthCheckRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.grpc.examples.dlink.HealthCheckRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code dgiot.HealthCheckRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:dgiot.HealthCheckRequest)
io.grpc.examples.dlink.HealthCheckRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HealthCheckRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HealthCheckRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.grpc.examples.dlink.HealthCheckRequest.class, io.grpc.examples.dlink.HealthCheckRequest.Builder.class);
}
// Construct using io.grpc.examples.dlink.HealthCheckRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
service_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HealthCheckRequest_descriptor;
}
@java.lang.Override
public io.grpc.examples.dlink.HealthCheckRequest getDefaultInstanceForType() {
return io.grpc.examples.dlink.HealthCheckRequest.getDefaultInstance();
}
@java.lang.Override
public io.grpc.examples.dlink.HealthCheckRequest build() {
io.grpc.examples.dlink.HealthCheckRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public io.grpc.examples.dlink.HealthCheckRequest buildPartial() {
io.grpc.examples.dlink.HealthCheckRequest result = new io.grpc.examples.dlink.HealthCheckRequest(this);
result.service_ = service_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.grpc.examples.dlink.HealthCheckRequest) {
return mergeFrom((io.grpc.examples.dlink.HealthCheckRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.grpc.examples.dlink.HealthCheckRequest other) {
if (other == io.grpc.examples.dlink.HealthCheckRequest.getDefaultInstance()) return this;
if (!other.getService().isEmpty()) {
service_ = other.service_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.grpc.examples.dlink.HealthCheckRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.grpc.examples.dlink.HealthCheckRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object service_ = "";
/**
* <code>string service = 1;</code>
* @return The service.
*/
public java.lang.String getService() {
java.lang.Object ref = service_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
service_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string service = 1;</code>
* @return The bytes for service.
*/
public com.google.protobuf.ByteString
getServiceBytes() {
java.lang.Object ref = service_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
service_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string service = 1;</code>
* @param value The service to set.
* @return This builder for chaining.
*/
public Builder setService(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
service_ = value;
onChanged();
return this;
}
/**
* <code>string service = 1;</code>
* @return This builder for chaining.
*/
public Builder clearService() {
service_ = getDefaultInstance().getService();
onChanged();
return this;
}
/**
* <code>string service = 1;</code>
* @param value The bytes for service to set.
* @return This builder for chaining.
*/
public Builder setServiceBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
service_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:dgiot.HealthCheckRequest)
}
// @@protoc_insertion_point(class_scope:dgiot.HealthCheckRequest)
private static final io.grpc.examples.dlink.HealthCheckRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.grpc.examples.dlink.HealthCheckRequest();
}
public static io.grpc.examples.dlink.HealthCheckRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<HealthCheckRequest>
PARSER = new com.google.protobuf.AbstractParser<HealthCheckRequest>() {
@java.lang.Override
public HealthCheckRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new HealthCheckRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<HealthCheckRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<HealthCheckRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public io.grpc.examples.dlink.HealthCheckRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}

View File

@ -0,0 +1,21 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dlink.proto
package io.grpc.examples.dlink;
public interface HealthCheckRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:dgiot.HealthCheckRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <code>string service = 1;</code>
* @return The service.
*/
java.lang.String getService();
/**
* <code>string service = 1;</code>
* @return The bytes for service.
*/
com.google.protobuf.ByteString
getServiceBytes();
}

View File

@ -0,0 +1,649 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dlink.proto
package io.grpc.examples.dlink;
/**
* Protobuf type {@code dgiot.HealthCheckResponse}
*/
public final class HealthCheckResponse extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:dgiot.HealthCheckResponse)
HealthCheckResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use HealthCheckResponse.newBuilder() to construct.
private HealthCheckResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private HealthCheckResponse() {
status_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new HealthCheckResponse();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private HealthCheckResponse(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 8: {
int rawValue = input.readEnum();
status_ = rawValue;
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HealthCheckResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HealthCheckResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.grpc.examples.dlink.HealthCheckResponse.class, io.grpc.examples.dlink.HealthCheckResponse.Builder.class);
}
/**
* Protobuf enum {@code dgiot.HealthCheckResponse.ServingStatus}
*/
public enum ServingStatus
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <code>UNKNOWN = 0;</code>
*/
UNKNOWN(0),
/**
* <code>SERVING = 1;</code>
*/
SERVING(1),
/**
* <code>NOT_SERVING = 2;</code>
*/
NOT_SERVING(2),
/**
* <pre>
* Used only by the Watch method.
* </pre>
*
* <code>SERVICE_UNKNOWN = 3;</code>
*/
SERVICE_UNKNOWN(3),
UNRECOGNIZED(-1),
;
/**
* <code>UNKNOWN = 0;</code>
*/
public static final int UNKNOWN_VALUE = 0;
/**
* <code>SERVING = 1;</code>
*/
public static final int SERVING_VALUE = 1;
/**
* <code>NOT_SERVING = 2;</code>
*/
public static final int NOT_SERVING_VALUE = 2;
/**
* <pre>
* Used only by the Watch method.
* </pre>
*
* <code>SERVICE_UNKNOWN = 3;</code>
*/
public static final int SERVICE_UNKNOWN_VALUE = 3;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static ServingStatus valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static ServingStatus forNumber(int value) {
switch (value) {
case 0: return UNKNOWN;
case 1: return SERVING;
case 2: return NOT_SERVING;
case 3: return SERVICE_UNKNOWN;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<ServingStatus>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
ServingStatus> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<ServingStatus>() {
public ServingStatus findValueByNumber(int number) {
return ServingStatus.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return io.grpc.examples.dlink.HealthCheckResponse.getDescriptor().getEnumTypes().get(0);
}
private static final ServingStatus[] VALUES = values();
public static ServingStatus valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private ServingStatus(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:dgiot.HealthCheckResponse.ServingStatus)
}
public static final int STATUS_FIELD_NUMBER = 1;
private int status_;
/**
* <code>.dgiot.HealthCheckResponse.ServingStatus status = 1;</code>
* @return The enum numeric value on the wire for status.
*/
@java.lang.Override public int getStatusValue() {
return status_;
}
/**
* <code>.dgiot.HealthCheckResponse.ServingStatus status = 1;</code>
* @return The status.
*/
@java.lang.Override public io.grpc.examples.dlink.HealthCheckResponse.ServingStatus getStatus() {
@SuppressWarnings("deprecation")
io.grpc.examples.dlink.HealthCheckResponse.ServingStatus result = io.grpc.examples.dlink.HealthCheckResponse.ServingStatus.valueOf(status_);
return result == null ? io.grpc.examples.dlink.HealthCheckResponse.ServingStatus.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (status_ != io.grpc.examples.dlink.HealthCheckResponse.ServingStatus.UNKNOWN.getNumber()) {
output.writeEnum(1, status_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (status_ != io.grpc.examples.dlink.HealthCheckResponse.ServingStatus.UNKNOWN.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, status_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof io.grpc.examples.dlink.HealthCheckResponse)) {
return super.equals(obj);
}
io.grpc.examples.dlink.HealthCheckResponse other = (io.grpc.examples.dlink.HealthCheckResponse) obj;
if (status_ != other.status_) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + STATUS_FIELD_NUMBER;
hash = (53 * hash) + status_;
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.grpc.examples.dlink.HealthCheckResponse parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HealthCheckResponse parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HealthCheckResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HealthCheckResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HealthCheckResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HealthCheckResponse parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HealthCheckResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HealthCheckResponse parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static io.grpc.examples.dlink.HealthCheckResponse parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HealthCheckResponse parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static io.grpc.examples.dlink.HealthCheckResponse parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HealthCheckResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.grpc.examples.dlink.HealthCheckResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code dgiot.HealthCheckResponse}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:dgiot.HealthCheckResponse)
io.grpc.examples.dlink.HealthCheckResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HealthCheckResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HealthCheckResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.grpc.examples.dlink.HealthCheckResponse.class, io.grpc.examples.dlink.HealthCheckResponse.Builder.class);
}
// Construct using io.grpc.examples.dlink.HealthCheckResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
status_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HealthCheckResponse_descriptor;
}
@java.lang.Override
public io.grpc.examples.dlink.HealthCheckResponse getDefaultInstanceForType() {
return io.grpc.examples.dlink.HealthCheckResponse.getDefaultInstance();
}
@java.lang.Override
public io.grpc.examples.dlink.HealthCheckResponse build() {
io.grpc.examples.dlink.HealthCheckResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public io.grpc.examples.dlink.HealthCheckResponse buildPartial() {
io.grpc.examples.dlink.HealthCheckResponse result = new io.grpc.examples.dlink.HealthCheckResponse(this);
result.status_ = status_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.grpc.examples.dlink.HealthCheckResponse) {
return mergeFrom((io.grpc.examples.dlink.HealthCheckResponse)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.grpc.examples.dlink.HealthCheckResponse other) {
if (other == io.grpc.examples.dlink.HealthCheckResponse.getDefaultInstance()) return this;
if (other.status_ != 0) {
setStatusValue(other.getStatusValue());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.grpc.examples.dlink.HealthCheckResponse parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.grpc.examples.dlink.HealthCheckResponse) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int status_ = 0;
/**
* <code>.dgiot.HealthCheckResponse.ServingStatus status = 1;</code>
* @return The enum numeric value on the wire for status.
*/
@java.lang.Override public int getStatusValue() {
return status_;
}
/**
* <code>.dgiot.HealthCheckResponse.ServingStatus status = 1;</code>
* @param value The enum numeric value on the wire for status to set.
* @return This builder for chaining.
*/
public Builder setStatusValue(int value) {
status_ = value;
onChanged();
return this;
}
/**
* <code>.dgiot.HealthCheckResponse.ServingStatus status = 1;</code>
* @return The status.
*/
@java.lang.Override
public io.grpc.examples.dlink.HealthCheckResponse.ServingStatus getStatus() {
@SuppressWarnings("deprecation")
io.grpc.examples.dlink.HealthCheckResponse.ServingStatus result = io.grpc.examples.dlink.HealthCheckResponse.ServingStatus.valueOf(status_);
return result == null ? io.grpc.examples.dlink.HealthCheckResponse.ServingStatus.UNRECOGNIZED : result;
}
/**
* <code>.dgiot.HealthCheckResponse.ServingStatus status = 1;</code>
* @param value The status to set.
* @return This builder for chaining.
*/
public Builder setStatus(io.grpc.examples.dlink.HealthCheckResponse.ServingStatus value) {
if (value == null) {
throw new NullPointerException();
}
status_ = value.getNumber();
onChanged();
return this;
}
/**
* <code>.dgiot.HealthCheckResponse.ServingStatus status = 1;</code>
* @return This builder for chaining.
*/
public Builder clearStatus() {
status_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:dgiot.HealthCheckResponse)
}
// @@protoc_insertion_point(class_scope:dgiot.HealthCheckResponse)
private static final io.grpc.examples.dlink.HealthCheckResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.grpc.examples.dlink.HealthCheckResponse();
}
public static io.grpc.examples.dlink.HealthCheckResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<HealthCheckResponse>
PARSER = new com.google.protobuf.AbstractParser<HealthCheckResponse>() {
@java.lang.Override
public HealthCheckResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new HealthCheckResponse(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<HealthCheckResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<HealthCheckResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public io.grpc.examples.dlink.HealthCheckResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}

View File

@ -0,0 +1,20 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dlink.proto
package io.grpc.examples.dlink;
public interface HealthCheckResponseOrBuilder extends
// @@protoc_insertion_point(interface_extends:dgiot.HealthCheckResponse)
com.google.protobuf.MessageOrBuilder {
/**
* <code>.dgiot.HealthCheckResponse.ServingStatus status = 1;</code>
* @return The enum numeric value on the wire for status.
*/
int getStatusValue();
/**
* <code>.dgiot.HealthCheckResponse.ServingStatus status = 1;</code>
* @return The status.
*/
io.grpc.examples.dlink.HealthCheckResponse.ServingStatus getStatus();
}

View File

@ -0,0 +1,565 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dlink.proto
package io.grpc.examples.dlink;
/**
* <pre>
* The response message containing the greetings
* </pre>
*
* Protobuf type {@code dgiot.HelloReply}
*/
public final class HelloReply extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:dgiot.HelloReply)
HelloReplyOrBuilder {
private static final long serialVersionUID = 0L;
// Use HelloReply.newBuilder() to construct.
private HelloReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private HelloReply() {
message_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new HelloReply();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private HelloReply(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
message_ = s;
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HelloReply_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HelloReply_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.grpc.examples.dlink.HelloReply.class, io.grpc.examples.dlink.HelloReply.Builder.class);
}
public static final int MESSAGE_FIELD_NUMBER = 1;
private volatile java.lang.Object message_;
/**
* <code>string message = 1;</code>
* @return The message.
*/
@java.lang.Override
public java.lang.String getMessage() {
java.lang.Object ref = message_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
message_ = s;
return s;
}
}
/**
* <code>string message = 1;</code>
* @return The bytes for message.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getMessageBytes() {
java.lang.Object ref = message_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
message_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(message_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, message_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(message_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, message_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof io.grpc.examples.dlink.HelloReply)) {
return super.equals(obj);
}
io.grpc.examples.dlink.HelloReply other = (io.grpc.examples.dlink.HelloReply) obj;
if (!getMessage()
.equals(other.getMessage())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + MESSAGE_FIELD_NUMBER;
hash = (53 * hash) + getMessage().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.grpc.examples.dlink.HelloReply parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HelloReply parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HelloReply parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HelloReply parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HelloReply parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HelloReply parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HelloReply parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HelloReply parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static io.grpc.examples.dlink.HelloReply parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HelloReply parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static io.grpc.examples.dlink.HelloReply parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HelloReply parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.grpc.examples.dlink.HelloReply prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* The response message containing the greetings
* </pre>
*
* Protobuf type {@code dgiot.HelloReply}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:dgiot.HelloReply)
io.grpc.examples.dlink.HelloReplyOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HelloReply_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HelloReply_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.grpc.examples.dlink.HelloReply.class, io.grpc.examples.dlink.HelloReply.Builder.class);
}
// Construct using io.grpc.examples.dlink.HelloReply.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
message_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HelloReply_descriptor;
}
@java.lang.Override
public io.grpc.examples.dlink.HelloReply getDefaultInstanceForType() {
return io.grpc.examples.dlink.HelloReply.getDefaultInstance();
}
@java.lang.Override
public io.grpc.examples.dlink.HelloReply build() {
io.grpc.examples.dlink.HelloReply result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public io.grpc.examples.dlink.HelloReply buildPartial() {
io.grpc.examples.dlink.HelloReply result = new io.grpc.examples.dlink.HelloReply(this);
result.message_ = message_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.grpc.examples.dlink.HelloReply) {
return mergeFrom((io.grpc.examples.dlink.HelloReply)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.grpc.examples.dlink.HelloReply other) {
if (other == io.grpc.examples.dlink.HelloReply.getDefaultInstance()) return this;
if (!other.getMessage().isEmpty()) {
message_ = other.message_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.grpc.examples.dlink.HelloReply parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.grpc.examples.dlink.HelloReply) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object message_ = "";
/**
* <code>string message = 1;</code>
* @return The message.
*/
public java.lang.String getMessage() {
java.lang.Object ref = message_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
message_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string message = 1;</code>
* @return The bytes for message.
*/
public com.google.protobuf.ByteString
getMessageBytes() {
java.lang.Object ref = message_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
message_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string message = 1;</code>
* @param value The message to set.
* @return This builder for chaining.
*/
public Builder setMessage(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
message_ = value;
onChanged();
return this;
}
/**
* <code>string message = 1;</code>
* @return This builder for chaining.
*/
public Builder clearMessage() {
message_ = getDefaultInstance().getMessage();
onChanged();
return this;
}
/**
* <code>string message = 1;</code>
* @param value The bytes for message to set.
* @return This builder for chaining.
*/
public Builder setMessageBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
message_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:dgiot.HelloReply)
}
// @@protoc_insertion_point(class_scope:dgiot.HelloReply)
private static final io.grpc.examples.dlink.HelloReply DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.grpc.examples.dlink.HelloReply();
}
public static io.grpc.examples.dlink.HelloReply getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<HelloReply>
PARSER = new com.google.protobuf.AbstractParser<HelloReply>() {
@java.lang.Override
public HelloReply parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new HelloReply(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<HelloReply> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<HelloReply> getParserForType() {
return PARSER;
}
@java.lang.Override
public io.grpc.examples.dlink.HelloReply getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}

View File

@ -0,0 +1,21 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dlink.proto
package io.grpc.examples.dlink;
public interface HelloReplyOrBuilder extends
// @@protoc_insertion_point(interface_extends:dgiot.HelloReply)
com.google.protobuf.MessageOrBuilder {
/**
* <code>string message = 1;</code>
* @return The message.
*/
java.lang.String getMessage();
/**
* <code>string message = 1;</code>
* @return The bytes for message.
*/
com.google.protobuf.ByteString
getMessageBytes();
}

View File

@ -0,0 +1,565 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dlink.proto
package io.grpc.examples.dlink;
/**
* <pre>
* The request message containing the user's name.
* </pre>
*
* Protobuf type {@code dgiot.HelloRequest}
*/
public final class HelloRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:dgiot.HelloRequest)
HelloRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use HelloRequest.newBuilder() to construct.
private HelloRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private HelloRequest() {
name_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new HelloRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private HelloRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HelloRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HelloRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.grpc.examples.dlink.HelloRequest.class, io.grpc.examples.dlink.HelloRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
* <code>string name = 1;</code>
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
* <code>string name = 1;</code>
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof io.grpc.examples.dlink.HelloRequest)) {
return super.equals(obj);
}
io.grpc.examples.dlink.HelloRequest other = (io.grpc.examples.dlink.HelloRequest) obj;
if (!getName()
.equals(other.getName())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.grpc.examples.dlink.HelloRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HelloRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HelloRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HelloRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HelloRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.grpc.examples.dlink.HelloRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.grpc.examples.dlink.HelloRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HelloRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static io.grpc.examples.dlink.HelloRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HelloRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static io.grpc.examples.dlink.HelloRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.grpc.examples.dlink.HelloRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.grpc.examples.dlink.HelloRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* The request message containing the user's name.
* </pre>
*
* Protobuf type {@code dgiot.HelloRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:dgiot.HelloRequest)
io.grpc.examples.dlink.HelloRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HelloRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HelloRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.grpc.examples.dlink.HelloRequest.class, io.grpc.examples.dlink.HelloRequest.Builder.class);
}
// Construct using io.grpc.examples.dlink.HelloRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
name_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.grpc.examples.dlink.DlinkProto.internal_static_dgiot_HelloRequest_descriptor;
}
@java.lang.Override
public io.grpc.examples.dlink.HelloRequest getDefaultInstanceForType() {
return io.grpc.examples.dlink.HelloRequest.getDefaultInstance();
}
@java.lang.Override
public io.grpc.examples.dlink.HelloRequest build() {
io.grpc.examples.dlink.HelloRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public io.grpc.examples.dlink.HelloRequest buildPartial() {
io.grpc.examples.dlink.HelloRequest result = new io.grpc.examples.dlink.HelloRequest(this);
result.name_ = name_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.grpc.examples.dlink.HelloRequest) {
return mergeFrom((io.grpc.examples.dlink.HelloRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.grpc.examples.dlink.HelloRequest other) {
if (other == io.grpc.examples.dlink.HelloRequest.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.grpc.examples.dlink.HelloRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.grpc.examples.dlink.HelloRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
* <code>string name = 1;</code>
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string name = 1;</code>
* @return The bytes for name.
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string name = 1;</code>
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
* <code>string name = 1;</code>
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <code>string name = 1;</code>
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:dgiot.HelloRequest)
}
// @@protoc_insertion_point(class_scope:dgiot.HelloRequest)
private static final io.grpc.examples.dlink.HelloRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.grpc.examples.dlink.HelloRequest();
}
public static io.grpc.examples.dlink.HelloRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<HelloRequest>
PARSER = new com.google.protobuf.AbstractParser<HelloRequest>() {
@java.lang.Override
public HelloRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new HelloRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<HelloRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<HelloRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public io.grpc.examples.dlink.HelloRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}

View File

@ -0,0 +1,21 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dlink.proto
package io.grpc.examples.dlink;
public interface HelloRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:dgiot.HelloRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <code>string name = 1;</code>
* @return The name.
*/
java.lang.String getName();
/**
* <code>string name = 1;</code>
* @return The bytes for name.
*/
com.google.protobuf.ByteString
getNameBytes();
}

View File

@ -0,0 +1,64 @@
// copy from: https://grpc.io/docs/what-is-grpc/introduction/
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.dlink";
option java_outer_classname = "DlinkProto";
option objc_class_prefix = "dlink";
package dgiot;
// The dlink service definition.
service Dlink {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// If the requested service is unknown, the call will fail with status
// NOT_FOUND.
rpc Check(HealthCheckRequest) returns (HealthCheckResponse);
// Performs a watch for the serving status of the requested service.
// The server will immediately send back a message indicating the current
// serving status. It will then subsequently send a new message whenever
// the service's serving status changes.
//
// If the requested service is unknown when the call is received, the
// server will send a message setting the serving status to
// SERVICE_UNKNOWN but will *not* terminate the call. If at some
// future point, the serving status of the service becomes known, the
// server will send a new message with the service's serving status.
//
// If the call terminates with status UNIMPLEMENTED, then clients
// should assume this method is not supported and should not retry the
// call. If the call terminates with any other status (including OK),
// clients should retry the call with appropriate exponential backoff.
rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse);
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
message HealthCheckRequest {
string service = 1;
}
message HealthCheckResponse {
enum ServingStatus {
UNKNOWN = 0;
SERVING = 1;
NOT_SERVING = 2;
SERVICE_UNKNOWN = 3; // Used only by the Watch method.
}
ServingStatus status = 1;
}

View File

@ -0,0 +1,12 @@
spring.application.name=DgIoT_Grpc
logging.config=classpath:logback.xml
#################################### please modify config below #####################################
server.port=50051

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="120 seconds">
<property name="log.base" value="logs"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} [%level] %logger{96}:[%line] - %msg%n
</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="LOGFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.base}/dbapi-standalone.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${log.base}/dbapi-standalone.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxHistory>168</maxHistory>
<maxFileSize>200MB</maxFileSize>
</rollingPolicy>
<encoder>
<pattern>
%date{yyyy-MM-dd HH:mm:ss.SSS} [%level] %logger{96}:[%line] - %msg%n
</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<logger name="org.apache.zookeeper" level="WARN"/>
<logger name="org.apache.hbase" level="WARN"/>
<logger name="org.apache.hadoop" level="WARN"/>
<root level="INFO">
<appender-ref ref="STDOUT"/>
<appender-ref ref="LOGFILE"/>
</root>
</configuration>

View File

@ -0,0 +1,60 @@
package com.dgiot.dataserver.test;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.examples.dlink.DlinkGrpc;
import io.grpc.examples.dlink.HelloRequest;
import io.grpc.examples.dlink.HelloReply;
import io.grpc.examples.dlink.HealthCheckRequest;
import io.grpc.examples.dlink.HealthCheckResponse;
import java.util.concurrent.TimeUnit;
import java.util.Iterator;
/**
* 客户端
*/
public class TestClient {
private final ManagedChannel channel;
private final DlinkGrpc.DlinkBlockingStub blockingStub;
private static final String host="127.0.0.1";
private static final int ip=50051;
public TestClient(String host,int port){
//usePlaintext表示明文传输否则需要配置ssl
//channel 表示通信通道
// channel= ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();
channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build();
//存根
blockingStub=DlinkGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public void testSayHello(String name){
HelloRequest request=HelloRequest.newBuilder().setName(name).build();
HelloReply response=blockingStub.sayHello(request);
System.out.println(response.getMessage());
}
public void testCheck(String name){
HealthCheckRequest request=HealthCheckRequest.newBuilder().build();
HealthCheckResponse response=blockingStub.check(request);
System.out.println(response.getStatus().toString());
}
public void testWatch(String name){
HealthCheckRequest request=HealthCheckRequest.newBuilder().build();
Iterator<HealthCheckResponse> response =blockingStub.watch(request);
while (response.hasNext()) {
System.out.println(response.next());
}
}
public static void main(String[] args) {
TestClient client=new TestClient(host,ip);
for (int i=0;i<=5;i++){
client.testSayHello("<<<<<result>>>>>:"+i);
}
}
}

View File

@ -0,0 +1,50 @@
<?php
// GENERATED CODE -- DO NOT EDIT!
// Original file comments:
// Copyright 2015 gRPC authors.
//
// 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.
//
namespace dlink;
/**
* The greeting service definition.
*/
class GreeterClient extends \Grpc\BaseStub {
/**
* @param string $hostname hostname
* @param array $opts channel options
* @param \Grpc\Channel $channel (optional) re-use channel object
*/
public function __construct($hostname, $opts, $channel = null) {
parent::__construct($hostname, $opts, $channel);
}
/**
* Sends a greeting
* @param \dlink\HelloRequest $argument input argument
* @param array $metadata metadata
* @param array $options call options
* @return \Grpc\UnaryCall
*/
public function SayHello(\dlink\HelloRequest $argument,
$metadata = [], $options = []) {
return $this->_simpleRequest('/dlink.Greeter/SayHello',
$argument,
['\dlink\HelloReply', 'decode'],
$metadata, $options);
}
}

View File

@ -0,0 +1,58 @@
<?php
// GENERATED CODE -- DO NOT EDIT!
// Original file comments:
// Copyright 2015 gRPC authors.
//
// 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.
//
namespace dlink;
/**
* The greeting service definition.
*/
class GreeterStub {
/**
* Sends a greeting
* @param \Helloworld\HelloRequest $request client request
* @param \Grpc\ServerContext $context server request context
* @return \Helloworld\HelloReply for response data, null if if error occured
* initial metadata (if any) and status (if not ok) should be set to $context
*/
public function SayHello(
\dlink\HelloRequest $request,
\Grpc\ServerContext $context
): ?\dlink\HelloReply {
$context->setStatus(\Grpc\Status::unimplemented());
return null;
}
/**
* Get the method descriptors of the service for server registration
*
* @return array of \Grpc\MethodDescriptor for the service methods
*/
public final function getMethodDescriptors(): array
{
return [
'/dlink.Greeter/SayHello' => new \Grpc\MethodDescriptor(
$this,
'SayHello',
'\dlink\HelloRequest',
\Grpc\MethodDescriptor::UNARY_CALL
),
];
}
}

View File

@ -0,0 +1,60 @@
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: dlink.proto
namespace Helloworld;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* The response message containing the greetings
*
* Generated from protobuf message <code>dlink.HelloReply</code>
*/
class HelloReply extends \Google\Protobuf\Internal\Message
{
/**
* Generated from protobuf field <code>string message = 1;</code>
*/
protected $message = '';
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $message
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Helloworld::initOnce();
parent::__construct($data);
}
/**
* Generated from protobuf field <code>string message = 1;</code>
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* Generated from protobuf field <code>string message = 1;</code>
* @param string $var
* @return $this
*/
public function setMessage($var)
{
GPBUtil::checkString($var, True);
$this->message = $var;
return $this;
}
}

View File

@ -0,0 +1,60 @@
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: helloworld.proto
namespace Helloworld;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* The request message containing the user's name.
*
* Generated from protobuf message <code>helloworld.HelloRequest</code>
*/
class HelloRequest extends \Google\Protobuf\Internal\Message
{
/**
* Generated from protobuf field <code>string name = 1;</code>
*/
protected $name = '';
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $name
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Helloworld::initOnce();
parent::__construct($data);
}
/**
* Generated from protobuf field <code>string name = 1;</code>
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Generated from protobuf field <code>string name = 1;</code>
* @param string $var
* @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
return $this;
}
}

View File

@ -0,0 +1,275 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: dlink.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='dlink.proto',
package='dgiot',
syntax='proto3',
serialized_options=b'\n\026io.grpc.examples.dlinkB\nDlinkProtoP\001\242\002\005dlink',
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n\x0b\x64link.proto\x12\x05\x64giot\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t\"%\n\x12HealthCheckRequest\x12\x0f\n\x07service\x18\x01 \x01(\t\"\xa0\x01\n\x13HealthCheckResponse\x12\x38\n\x06status\x18\x01 \x01(\x0e\x32(.dgiot.HealthCheckResponse.ServingStatus\"O\n\rServingStatus\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x0b\n\x07SERVING\x10\x01\x12\x0f\n\x0bNOT_SERVING\x10\x02\x12\x13\n\x0fSERVICE_UNKNOWN\x10\x03\x32\xbf\x01\n\x05\x44link\x12\x34\n\x08SayHello\x12\x13.dgiot.HelloRequest\x1a\x11.dgiot.HelloReply\"\x00\x12>\n\x05\x43heck\x12\x19.dgiot.HealthCheckRequest\x1a\x1a.dgiot.HealthCheckResponse\x12@\n\x05Watch\x12\x19.dgiot.HealthCheckRequest\x1a\x1a.dgiot.HealthCheckResponse0\x01\x42.\n\x16io.grpc.examples.dlinkB\nDlinkProtoP\x01\xa2\x02\x05\x64linkb\x06proto3'
)
_HEALTHCHECKRESPONSE_SERVINGSTATUS = _descriptor.EnumDescriptor(
name='ServingStatus',
full_name='dgiot.HealthCheckResponse.ServingStatus',
filename=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
values=[
_descriptor.EnumValueDescriptor(
name='UNKNOWN', index=0, number=0,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='SERVING', index=1, number=1,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='NOT_SERVING', index=2, number=2,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='SERVICE_UNKNOWN', index=3, number=3,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
],
containing_type=None,
serialized_options=None,
serialized_start=204,
serialized_end=283,
)
_sym_db.RegisterEnumDescriptor(_HEALTHCHECKRESPONSE_SERVINGSTATUS)
_HELLOREQUEST = _descriptor.Descriptor(
name='HelloRequest',
full_name='dgiot.HelloRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='dgiot.HelloRequest.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=22,
serialized_end=50,
)
_HELLOREPLY = _descriptor.Descriptor(
name='HelloReply',
full_name='dgiot.HelloReply',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='message', full_name='dgiot.HelloReply.message', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=52,
serialized_end=81,
)
_HEALTHCHECKREQUEST = _descriptor.Descriptor(
name='HealthCheckRequest',
full_name='dgiot.HealthCheckRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='service', full_name='dgiot.HealthCheckRequest.service', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=83,
serialized_end=120,
)
_HEALTHCHECKRESPONSE = _descriptor.Descriptor(
name='HealthCheckResponse',
full_name='dgiot.HealthCheckResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='status', full_name='dgiot.HealthCheckResponse.status', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
_HEALTHCHECKRESPONSE_SERVINGSTATUS,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=123,
serialized_end=283,
)
_HEALTHCHECKRESPONSE.fields_by_name['status'].enum_type = _HEALTHCHECKRESPONSE_SERVINGSTATUS
_HEALTHCHECKRESPONSE_SERVINGSTATUS.containing_type = _HEALTHCHECKRESPONSE
DESCRIPTOR.message_types_by_name['HelloRequest'] = _HELLOREQUEST
DESCRIPTOR.message_types_by_name['HelloReply'] = _HELLOREPLY
DESCRIPTOR.message_types_by_name['HealthCheckRequest'] = _HEALTHCHECKREQUEST
DESCRIPTOR.message_types_by_name['HealthCheckResponse'] = _HEALTHCHECKRESPONSE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
HelloRequest = _reflection.GeneratedProtocolMessageType('HelloRequest', (_message.Message,), {
'DESCRIPTOR' : _HELLOREQUEST,
'__module__' : 'dlink_pb2'
# @@protoc_insertion_point(class_scope:dgiot.HelloRequest)
})
_sym_db.RegisterMessage(HelloRequest)
HelloReply = _reflection.GeneratedProtocolMessageType('HelloReply', (_message.Message,), {
'DESCRIPTOR' : _HELLOREPLY,
'__module__' : 'dlink_pb2'
# @@protoc_insertion_point(class_scope:dgiot.HelloReply)
})
_sym_db.RegisterMessage(HelloReply)
HealthCheckRequest = _reflection.GeneratedProtocolMessageType('HealthCheckRequest', (_message.Message,), {
'DESCRIPTOR' : _HEALTHCHECKREQUEST,
'__module__' : 'dlink_pb2'
# @@protoc_insertion_point(class_scope:dgiot.HealthCheckRequest)
})
_sym_db.RegisterMessage(HealthCheckRequest)
HealthCheckResponse = _reflection.GeneratedProtocolMessageType('HealthCheckResponse', (_message.Message,), {
'DESCRIPTOR' : _HEALTHCHECKRESPONSE,
'__module__' : 'dlink_pb2'
# @@protoc_insertion_point(class_scope:dgiot.HealthCheckResponse)
})
_sym_db.RegisterMessage(HealthCheckResponse)
DESCRIPTOR._options = None
_DLINK = _descriptor.ServiceDescriptor(
name='Dlink',
full_name='dgiot.Dlink',
file=DESCRIPTOR,
index=0,
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_start=286,
serialized_end=477,
methods=[
_descriptor.MethodDescriptor(
name='SayHello',
full_name='dgiot.Dlink.SayHello',
index=0,
containing_service=None,
input_type=_HELLOREQUEST,
output_type=_HELLOREPLY,
serialized_options=None,
create_key=_descriptor._internal_create_key,
),
_descriptor.MethodDescriptor(
name='Check',
full_name='dgiot.Dlink.Check',
index=1,
containing_service=None,
input_type=_HEALTHCHECKREQUEST,
output_type=_HEALTHCHECKRESPONSE,
serialized_options=None,
create_key=_descriptor._internal_create_key,
),
_descriptor.MethodDescriptor(
name='Watch',
full_name='dgiot.Dlink.Watch',
index=2,
containing_service=None,
input_type=_HEALTHCHECKREQUEST,
output_type=_HEALTHCHECKRESPONSE,
serialized_options=None,
create_key=_descriptor._internal_create_key,
),
])
_sym_db.RegisterServiceDescriptor(_DLINK)
DESCRIPTOR.services_by_name['Dlink'] = _DLINK
# @@protoc_insertion_point(module_scope)

View File

@ -0,0 +1,153 @@
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import dlink_pb2 as dlink__pb2
class DlinkStub(object):
"""The dlink service definition.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.SayHello = channel.unary_unary(
'/dgiot.Dlink/SayHello',
request_serializer=dlink__pb2.HelloRequest.SerializeToString,
response_deserializer=dlink__pb2.HelloReply.FromString,
)
self.Check = channel.unary_unary(
'/dgiot.Dlink/Check',
request_serializer=dlink__pb2.HealthCheckRequest.SerializeToString,
response_deserializer=dlink__pb2.HealthCheckResponse.FromString,
)
self.Watch = channel.unary_stream(
'/dgiot.Dlink/Watch',
request_serializer=dlink__pb2.HealthCheckRequest.SerializeToString,
response_deserializer=dlink__pb2.HealthCheckResponse.FromString,
)
class DlinkServicer(object):
"""The dlink service definition.
"""
def SayHello(self, request, context):
"""Sends a greeting
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Check(self, request, context):
"""If the requested service is unknown, the call will fail with status
NOT_FOUND.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Watch(self, request, context):
"""Performs a watch for the serving status of the requested service.
The server will immediately send back a message indicating the current
serving status. It will then subsequently send a new message whenever
the service's serving status changes.
If the requested service is unknown when the call is received, the
server will send a message setting the serving status to
SERVICE_UNKNOWN but will *not* terminate the call. If at some
future point, the serving status of the service becomes known, the
server will send a new message with the service's serving status.
If the call terminates with status UNIMPLEMENTED, then clients
should assume this method is not supported and should not retry the
call. If the call terminates with any other status (including OK),
clients should retry the call with appropriate exponential backoff.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_DlinkServicer_to_server(servicer, server):
rpc_method_handlers = {
'SayHello': grpc.unary_unary_rpc_method_handler(
servicer.SayHello,
request_deserializer=dlink__pb2.HelloRequest.FromString,
response_serializer=dlink__pb2.HelloReply.SerializeToString,
),
'Check': grpc.unary_unary_rpc_method_handler(
servicer.Check,
request_deserializer=dlink__pb2.HealthCheckRequest.FromString,
response_serializer=dlink__pb2.HealthCheckResponse.SerializeToString,
),
'Watch': grpc.unary_stream_rpc_method_handler(
servicer.Watch,
request_deserializer=dlink__pb2.HealthCheckRequest.FromString,
response_serializer=dlink__pb2.HealthCheckResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'dgiot.Dlink', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class Dlink(object):
"""The dlink service definition.
"""
@staticmethod
def SayHello(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/dgiot.Dlink/SayHello',
dlink__pb2.HelloRequest.SerializeToString,
dlink__pb2.HelloReply.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def Check(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/dgiot.Dlink/Check',
dlink__pb2.HealthCheckRequest.SerializeToString,
dlink__pb2.HealthCheckResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def Watch(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_stream(request, target, '/dgiot.Dlink/Watch',
dlink__pb2.HealthCheckRequest.SerializeToString,
dlink__pb2.HealthCheckResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

View File

@ -0,0 +1,47 @@
# Copyright 2015 gRPC authors.
#
# 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.
"""The Python implementation of the GRPC helloworld.Greeter server."""
import json
from concurrent import futures
import logging
import grpc
import dlink_pb2
import dlink_pb2_grpc
import base64
import datetime
class Dlink(dlink_pb2_grpc.DlinkServicer):
def SayHello(self, request, context):
print(datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))
print( request.name)
print( context)
json_request = json.loads(base64.b64decode(request.name).decode("utf-8"))
print(json_request)
return dlink_pb2.HelloReply(message="parameter received")
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
dlink_pb2_grpc.add_DlinkServicer_to_server(Dlink(), server)
server.add_insecure_port('[::]:30051')
server.start()
server.wait_for_termination()
if __name__ == '__main__':
logging.basicConfig()
serve()

View File

@ -1,5 +1,5 @@
{application, dgiot_atomgit,
[{description, "DGIOT ATOMGIT"},
[{description, "DGIOT atomgit"},
{vsn, "4.3.0"},
{registered, []},
{mod, {dgiot_atomgit_app, []}},

View File

@ -21,7 +21,7 @@
-include_lib("dgiot/include/dgiot_socket.hrl").
-include_lib("dgiot/include/logger.hrl").
-include("dgiot_atomgit.hrl").
-define(TYPE, <<"ATOMGIT">>).
-define(TYPE, <<"atomgit">>).
%% API
-export([start/2]).
@ -33,10 +33,10 @@
cType => ?TYPE,
type => ?PROTOCOL_CHL,
title => #{
zh => <<"ATOMGIT测试通道"/utf8>>
zh => <<"atomgit测试通道"/utf8>>
},
description => #{
zh => <<"ATOMGIT测试通道"/utf8>>
zh => <<"atomgit测试通道"/utf8>>
}
}).
%%

View File

@ -17,7 +17,7 @@
-module(dgiot_atomgit_decoder).
-include_lib("dgiot_atomgit.hrl").
-include_lib("dgiot/include/logger.hrl").
-protocol([?ATOMGIT]).
-protocol([?atomgit]).
-define(CRLF, "\r\n").
%% API
-export([parse_frame/2, to_frame/1]).

View File

@ -113,9 +113,23 @@ handle_message({sync_parse, Pid, 'after', get, Token, <<"View">>, #{<<"data">> :
dgiot_parse_hook:publish(Pid, ResBody1),
{ok, State};
handle_message({sync_parse, _Pid, 'after', post, _Token, <<"View">>, QueryData}, State) ->
%% io:format("~s ~p ~p ~p ~n", [?FILE, ?LINE, _Pid, QueryData]),
handle_message({sync_parse, _Pid, 'after', post, SessionToken, <<"View">>, #{<<"objectId">> := ViewId} = QueryData}, State) ->
%% io:format("~s ~p ~p ~p ~n", [?FILE, ?LINE, SessionToken, QueryData]),
dgiot_view:post('after', QueryData),
case dgiot_auth:get_session(dgiot_utils:to_binary(SessionToken)) of
#{<<"roles">> := Roles} ->
maps:fold(fun(RoleId, _, _) ->
dgiot_parse:update_object(<<"_Role">>, RoleId, #{
<<"views">> => #{
<<"__op">> => <<"AddRelation">>,
<<"objects">> => [#{
<<"__type">> => <<"Pointer">>,
<<"className">> => <<"View">>,
<<"objectId">> => ViewId}]}})
end, [], Roles);
_ ->
pass
end,
{ok, State};
handle_message({sync_parse, _Pid, 'after', put, _Token, <<"View">>, QueryData}, State) ->

View File

@ -34,7 +34,7 @@ get_device_card(Channel, ProductId, DeviceId, Args) ->
Chartdata = get_card(ProductId, Results, DeviceId, Args, dgiot_data:get({shard_storage, ProductId})),
{ok, #{<<"data">> => Chartdata}}.
decode_shard_data(Data) ->
decode_shard_data(Data, Result) ->
case binary:split(Data, <<$,>>, [global, trim]) of
List when length(List) > 0 ->
lists:foldl(fun(<<Len:1/binary, Rest/binary>>, Acc) ->
@ -45,9 +45,9 @@ decode_shard_data(Data) ->
_ ->
Acc
end
end, #{}, List);
end, Result, List);
_ ->
#{}
Result
end.
%% dgiot_data:get({shard_storage, <<"857ed41119">>}).
@ -64,9 +64,9 @@ get_card(ProductId, Results, DeviceId, Args, true) ->
Acc
end
end, <<>>, lists:seq(1, maps:size(Result))),
NewResult = dgiot_dlink_proctol:parse_payload(ProductId, decode_shard_data(Buff)),
NewResult = dgiot_dlink_proctol:parse_payload(ProductId, decode_shard_data(Buff, Result)),
%% io:format("success NewResult = ~ts~n", [unicode:characters_to_list(dgiot_json:encode(NewResult))]),
get_card(ProductId, [NewResult#{<<"createdat">> => Createdat}], DeviceId, Args, false);
get_card(ProductId, [dgiot_map:merge(NewResult#{<<"createdat">> => Createdat}, Result)], DeviceId, Args, false);
get_card(ProductId, Results, DeviceId, Args, _) ->
[Result | _] = Results,
@ -132,10 +132,12 @@ get_card(ProductId, Results, DeviceId, Args, _) ->
%% {Color, _, _} = dgiot_device:get_color(DeviceId, Identifier),
{Value, Number} =
case maps:find(Identifier, Result) of
error ->
{ok, null} ->
{<<>>, <<"--">>};
{ok, V} ->
{V, dgiot_product_tdengine:check_field(Typea, V, #{<<"datatype">> => DataType, <<"specs">> => Specs, <<"deviceid">> => DeviceId})}
{V, dgiot_product_tdengine:check_field(Typea, V, #{<<"datatype">> => DataType, <<"specs">> => Specs, <<"deviceid">> => DeviceId})};
_ ->
{<<>>, <<"--">>}
end,
Acc ++ [#{<<"identifier">> => Identifier, <<"name">> => Name,
<<"type">> => Typea, <<"number">> => Number, <<"value">> => Value,

View File

@ -78,7 +78,7 @@ handle_info({tcp, Buff}, #dclient{channel = ChannelId,
erlang:send_after(Freq * 1000, self(), read),
{noreply, Dclient#dclient{child = ChildState#{di => StartAddr, data => <<>>}}};
_ ->
erlang:send_after(1 * 1500, self(), read),
erlang:send_after(1 * 1000, self(), read),
{noreply, Dclient#dclient{child = ChildState#{di => Address + Step, data => <<OldData/binary, Data/binary>>}}}
end;

View File

@ -29,7 +29,7 @@
build_req_message/1,
get_addr/4,
set_addr/3,
shard_data/1,
shard_data/2,
change_data/2
]
).
@ -308,7 +308,7 @@ parse_frame(StartAddr, FileName, Data) ->
{Value1, _Rest} ->
Value1;
_ ->
V
null
end;
_ ->
null
@ -323,7 +323,7 @@ parse_frame(StartAddr, FileName, Data) ->
%% io:format("~s ~p ~p => ~p => ~p => ~p => ~p => ~p ~n", [?FILE, ?LINE, NewAddress, IntOffset, NewIntOffset, IntLen, V, Value1]),
Value1;
_ ->
V
null
end;
_ ->
null
@ -344,6 +344,10 @@ parse_frame(StartAddr, FileName, Data) ->
DeviceId = dgiot_parse_id:get_deviceid(ProductId1, Devaddr1),
%% NewAck = change_data(ProductId1, Ack),
CacheAck = dgiot_task:merge_cache_data(ProductId1, Ack, -1),
NewResult = dgiot_dlink_proctol:parse_payload(ProductId1, CacheAck),
Props = dgiot_task:get_props(ProductId1),
Calculated = get_calculated(ProductId1, Devaddr1, NewResult, Props),
dgiot_task:save_cache_data(ProductId1, CacheAck),
BinData =
maps:fold(fun(K, V, Acc) ->
@ -352,7 +356,8 @@ parse_frame(StartAddr, FileName, Data) ->
BinV = dgiot_utils:to_binary(V),
<<Acc/binary, Len/binary, BinK/binary, BinV/binary, ",">>
end, <<>>, CacheAck),
Shard_data = modbus_tcp:shard_data(BinData),
Shard_data = modbus_tcp:shard_data(BinData, Calculated),
case dgiot_data:get({modbus_tcp, dgiot_datetime:now_secs()}) of
not_find ->
spawn(fun() ->
@ -372,8 +377,8 @@ parse_frame(StartAddr, FileName, Data) ->
end, #{}, AllData),
NewAllData.
shard_data(Data) ->
shard_data(Data, 1, #{}).
shard_data(Data, Acc) ->
shard_data(Data, 1, Acc).
shard_data(<<>>, _, Acc) ->
Acc;
@ -546,6 +551,8 @@ modbus_tcp_decoder(ProductId, Slaveid, Address, Data, Acc1) ->
maps:merge(Acc, Value);
{Value, _Rest} ->
Acc#{Identifier => Value};
null ->
Acc;
_ ->
Acc
end;
@ -606,6 +613,8 @@ format_value(Buff, #{<<"identifier">> := BitIdentifier,
case format_value(V, X, Props) of
{Value1, _Rest} ->
Value1;
null ->
null;
_ ->
V
end;
@ -614,6 +623,8 @@ format_value(Buff, #{<<"identifier">> := BitIdentifier,
case format_value(V, X, Props) of
{Value1, _Rest} ->
Value1;
null ->
null;
_ ->
V
end
@ -716,8 +727,12 @@ format_value(Buff, #{<<"dataSource">> := #{
IntNum = dgiot_utils:to_int(Num),
Size = IntNum * 4 * 8,
<<H:2/binary, L:2/binary, Rest/binary>> = Buff,
<<Value:Size/float>> = <<H/binary, L/binary>>,
{Value, Rest};
case catch <<H/binary, L/binary>> of
<<Value:Size/float>> ->
{Value, Rest};
_ ->
null
end;
format_value(Buff, #{<<"dataSource">> := #{
<<"registersnumber">> := Num,
@ -726,14 +741,18 @@ format_value(Buff, #{<<"dataSource">> := #{
IntNum = dgiot_utils:to_int(Num),
Size = IntNum * 4 * 8,
<<H:2/binary, L:2/binary, Rest/binary>> = Buff,
<<Value:Size/float>> = <<L/binary, H/binary>>,
{Value, Rest};
case catch <<L/binary, H/binary>> of
<<Value:Size/float>> ->
{Value, Rest};
_ ->
null
end;
%% @todo
format_value(Buff, #{<<"identifier">> := Field, <<"originaltype">> := Originaltype}, _Props) ->
?LOG(error, "Field ~p originaltype ~p", [Field, Originaltype]),
format_value(_Buff, #{<<"identifier">> := _Field, <<"originaltype">> := _Originaltype}, _Props) ->
%% ?LOG(error, "Field ~p originaltype ~p", [Field, Originaltype]),
%% throw({field_error, <<Field/binary, "_", Originaltype/binary, " is not validate">>}),
{<<"">>, Buff}.
null.
%%
get_len(IntNum, <<"bool">>) ->
@ -785,3 +804,33 @@ get_addr(ChannelId, Min, Max, Step) ->
set_addr(ChannelId, Min, Max) ->
dgiot_data:set_consumer(?consumer(ChannelId), Min, Max).
get_calculated(ProductId, DevAddr, Calculated, Props) ->
lists:foldl(fun(X, Acc) ->
case X of
#{<<"isaccumulate">> := true,
<<"isstorage">> := true,
<<"identifier">> := Identifier,
<<"dataForm">> := #{<<"strategy">> := <<"计算值"/utf8>>},
<<"dataSource">> := #{<<"key">> := Key} = DataSource
} ->
case maps:get(Key, Calculated, not_find) of
not_find ->
Acc;
KeyValue ->
dgiot_task:get_statistic(ProductId, DevAddr, Key, Identifier, dgiot_utils:to_int(KeyValue), DataSource, Acc)
end;
#{<<"isstorage">> := true,
<<"identifier">> := Identifier
} ->
case maps:get(Identifier, Calculated, not_find) of
not_find ->
Acc;
Value ->
Acc#{Identifier => Value}
end;
_ ->
Acc
end
end, #{}, Props).

View File

@ -20,8 +20,8 @@
-include_lib("dgiot_bridge/include/dgiot_bridge.hrl").
-export([start/1, start/2, send/3, get_pnque_len/1, save_pnque/4, get_pnque/1, del_pnque/1, save_td/4, merge_cache_data/3, save_cache_data/2]).
-export([get_props/1, get_control/3, get_collection/4, get_calculated/4, get_instruct/2, get_storage/2, string2value/2, string2value/3]).
-export([save_td_no_match/4]).
-export([get_props/1, get_control/3, get_collection/4, get_calculated/4, get_instruct/2, get_storage/2, string2value/2, string2value/3, get_statistic/7]).
-export([save_td_no_match/4, get_last_value/4]).
%%
-protocol_type(#{
@ -155,8 +155,9 @@ compare(_, _, _) ->
%%
%% select last(devaddr) as devaddr FROM _24b9b4bc50._1c9966755d;
get_last_value(ProductId, DevAddr, Identifier) ->
case dgiot_data:get({last_value, ProductId, DevAddr, Identifier}) of
%% dgiot_data:get({last_value, <<"857ed41119">>, <<"PDJ">>, <<"m583_10">>, <<"bc11c_failnum">>})
get_last_value(ProductId, DevAddr, Key, Identifier) ->
case dgiot_data:get({last_value, ProductId, DevAddr, Key, Identifier}) of
not_find ->
case dgiot_tdengine:get_channel(ProductId) of
{ok, Channel} ->
@ -180,38 +181,51 @@ get_last_value(ProductId, DevAddr, Identifier) ->
end.
%%
get_statistic(ProductId, DevAddr, Identifier, KeyValue, #{<<"type">> := <<"duration">>, <<"comparetype">> := Comparetype, <<"value">> := Value}, Acc) ->
Last_Value = get_last_value(ProductId, DevAddr, Identifier),
get_statistic(ProductId, DevAddr, Key, Identifier, KeyValue, #{<<"type">> := <<"duration">>, <<"comparetype">> := Comparetype, <<"value">> := Value}, Acc) ->
Last_Value = get_last_value(ProductId, DevAddr, Key, Identifier),
case compare(KeyValue, Comparetype, dgiot_utils:to_int(Value)) of
true ->
Last_Value = get_last_value(ProductId, DevAddr, Identifier),
Time =
case dgiot_data:get({last_time, ProductId, DevAddr, Identifier}) of
case dgiot_data:get({last_time, ProductId, DevAddr, Key, Identifier}) of
{true, OldTime} ->
dgiot_datetime:now_secs() - OldTime;
_ ->
0
end,
dgiot_data:insert({last_time, ProductId, DevAddr, Identifier}, {true, dgiot_datetime:now_secs()}),
dgiot_data:insert({last_value, ProductId, DevAddr, Identifier}, Last_Value + Time),
dgiot_data:insert({last_time, ProductId, DevAddr, Key, Identifier}, {true, dgiot_datetime:now_secs()}),
dgiot_data:insert({last_value, ProductId, DevAddr, Key, Identifier}, Last_Value + Time),
Acc#{Identifier => Last_Value + Time};
_ ->
dgiot_data:insert({last_time, ProductId, DevAddr, Identifier}, {false, dgiot_datetime:now_secs()}),
dgiot_data:insert({last_time, ProductId, DevAddr, Key, Identifier}, {false, dgiot_datetime:now_secs()}),
dgiot_data:insert({last_value, ProductId, DevAddr, Key, Identifier}, Last_Value),
Acc#{Identifier => Last_Value}
end;
%%
get_statistic(ProductId, DevAddr, Identifier, KeyValue, #{<<"type">> := <<"frequency">>, <<"comparetype">> := Comparetype, <<"value">> := Value}, Acc) ->
Num = get_last_value(ProductId, DevAddr, Identifier),
case compare(KeyValue, Comparetype, Value) of
%% dgiot_data:get({last_flag, <<"857ed41119">>, <<"PDJ">>, <<"m583_10">>, <<"bc11c_failnum">>}).
get_statistic(ProductId, DevAddr, Key, Identifier, KeyValue, #{<<"type">> := <<"frequency">>, <<"comparetype">> := Comparetype, <<"value">> := Value}, Acc) ->
Num = get_last_value(ProductId, DevAddr, Key, Identifier),
case compare(KeyValue, Comparetype, dgiot_utils:to_int(Value)) of
true ->
dgiot_data:insert({last_value, ProductId, DevAddr, Identifier}, Num + 1),
Acc#{Identifier => Num + 1};
case dgiot_data:get({last_flag, ProductId, DevAddr, Key, Identifier}) of
not_find when Num =:= 0 ->
dgiot_data:insert({last_value, ProductId, DevAddr, Key, Identifier}, Num + 1),
dgiot_data:insert({last_flag, ProductId, DevAddr, Key, Identifier}, true),
Acc#{Identifier => Num + 1};
false ->
dgiot_data:insert({last_value, ProductId, DevAddr, Key, Identifier}, Num + 1),
dgiot_data:insert({last_flag, ProductId, DevAddr, Key, Identifier}, true),
Acc#{Identifier => Num + 1};
_ ->
Acc#{Identifier => Num}
end;
_ ->
dgiot_data:insert({last_value, ProductId, DevAddr, Key, Identifier}, Num),
dgiot_data:insert({last_flag, ProductId, DevAddr, Key, Identifier}, false),
Acc#{Identifier => Num}
end;
get_statistic(_, _, _, _, _, Acc) ->
get_statistic(_, _, _, _, _, _, Acc) ->
Acc.
%%
@ -232,7 +246,7 @@ get_calculated(ProductId, DevAddr, Calculated, Props) ->
not_find ->
Acc;
KeyValue ->
get_statistic(ProductId, DevAddr, Identifier, dgiot_utils:to_int(KeyValue), DataSource, Acc)
get_statistic(ProductId, DevAddr, Key, Identifier, dgiot_utils:to_int(KeyValue), DataSource, Acc)
end;
#{<<"isstorage">> := true,
<<"identifier">> := Identifier,

View File

@ -941,6 +941,7 @@ function atomgit_plugin() {
if [ -d ${script_dir}/apps/dgiot_atomgit/ ]; then
mv ${script_dir}/apps/dgiot_atomgit ${script_dir}/apps/dgiot_${dgiotmd5}
for file in `find ${script_dir}/apps/dgiot_${dgiotmd5}/ -type f`; do
if [[ $file != *HJ212-2017.pdf* ]]; then
new_name=$(echo "$file" | sed "s/atomgit/${dgiotmd5}/")
echo -e "$(date +%F_%T) $LINENO: ${GREEN} file= $file${NC}"
sed -i "s/atomgit/${dgiotmd5}/g" $file
@ -951,6 +952,7 @@ function atomgit_plugin() {
echo -e "$(date +%F_%T) $LINENO: ${GREEN} new_name= ${new_name}${NC}"
mv "${file}" "${new_name}"
fi
fi
done
sed -i "s/atomgit/${dgiotmd5}/g" ${script_dir}/rebar.config.erl
sed -i "s/atomgit/${dgiotmd5}/g" ${script_dir}/data/loaded_plugins.tmpl

View File

@ -271,7 +271,6 @@ relx_apps(ReleaseType) ->
, jsx
, jesse
, jwerl
, odbc
, erlydtl
, erlport
, ecpool