@@ -42,6 +42,27 @@ struct Args {
42
42
period : Option < Duration > ,
43
43
}
44
44
45
+ struct ConnectionListener {
46
+ tx : tokio:: sync:: mpsc:: Sender < ClientState > ,
47
+ }
48
+
49
+ impl ConnectionListener {
50
+ fn create ( ) -> ( Self , tokio:: sync:: mpsc:: Receiver < ClientState > ) {
51
+ let ( tx, rx) = tokio:: sync:: mpsc:: channel ( 32 ) ;
52
+ ( Self { tx } , rx)
53
+ }
54
+ }
55
+
56
+ impl Listener < ClientState > for ConnectionListener {
57
+ fn update ( & mut self , state : ClientState ) -> MaybeAsync < ( ) > {
58
+ let tx = self . tx . clone ( ) ;
59
+ let future = async move {
60
+ let _ = tx. try_send ( state) ;
61
+ } ;
62
+ MaybeAsync :: asynchronous ( future)
63
+ }
64
+ }
65
+
45
66
impl Args {
46
67
fn new ( address : SocketAddr , id : UnitId , command : Command , period : Option < Duration > ) -> Self {
47
68
Self {
@@ -68,16 +89,30 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
68
89
Ok ( ( ) )
69
90
}
70
91
71
- async fn run ( ) -> Result < ( ) , Error > {
92
+ async fn run ( ) -> Result < ( ) , Box < dyn std :: error :: Error > > {
72
93
let args = parse_args ( ) ?;
94
+
95
+ let ( listener, mut rx) = ConnectionListener :: create ( ) ;
96
+
73
97
let mut channel = spawn_tcp_client_task (
74
98
HostAddr :: ip ( args. address . ip ( ) , args. address . port ( ) ) ,
75
99
1 ,
76
100
default_retry_strategy ( ) ,
77
101
AppDecodeLevel :: DataValues . into ( ) ,
78
- None ,
102
+ Some ( Box :: new ( listener ) ) ,
79
103
) ;
80
104
channel. enable ( ) . await ?;
105
+
106
+ ' connect: loop {
107
+ let state = rx. recv ( ) . await . expect ( "should never be empty" ) ;
108
+ tracing:: info!( "state: {state:?}" ) ;
109
+ match state {
110
+ ClientState :: Disabled | ClientState :: Connecting => { }
111
+ ClientState :: Connected => break ' connect,
112
+ _ => return Err ( "unable to connect" . into ( ) ) ,
113
+ }
114
+ }
115
+
81
116
let params = RequestParam :: new ( args. id , Duration :: from_secs ( 1 ) ) ;
82
117
83
118
match args. period {
@@ -93,7 +128,7 @@ async fn run_command(
93
128
command : & Command ,
94
129
channel : & mut Channel ,
95
130
params : RequestParam ,
96
- ) -> Result < ( ) , Error > {
131
+ ) -> Result < ( ) , Box < dyn std :: error :: Error > > {
97
132
match command {
98
133
Command :: ReadCoils ( range) => {
99
134
for x in channel. read_coils ( params, * range) . await ? {
0 commit comments