Skip to content

Commit e2fac31

Browse files
authored
Merge pull request #18 from vxshug/main
fix active time
2 parents bc66925 + f04736f commit e2fac31

7 files changed

Lines changed: 102 additions & 73 deletions

File tree

devices_manager/src/man/mqtt.rs

Lines changed: 62 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,25 @@
1-
use std::str::FromStr;
2-
use std::string::FromUtf8Error;
1+
use crate::event::config_cache;
32
use crate::load::{load_config, MqttConfig};
3+
use crate::man::data::DownloadData;
4+
use crate::man::gw::{DataWrapper, GwCmd, GwCmdResponse, ShellCmd};
5+
use crate::man::lora::{LoRaNode, LoRaNodeManager};
6+
use crate::man::Id;
7+
use crate::protocol::mqtt::{LinkRx, LinkTx, Notification};
48
use crate::{DeviceError, DeviceResult, GLOBAL_DOWNLOAD_RESPONSE, GLOBAL_STATE};
5-
use derive_new::new;
6-
use rumqttc::{Event, Incoming, MqttOptions, QoS};
7-
use std::sync::Mutex;
8-
use std::time::Duration;
99
use base64::Engine;
1010
use bytes::Bytes;
11+
use common_define::db::{DbErr, DeviceLoraGateColumn, DeviceLoraGateEntity, Eui};
12+
use common_define::event::DownloadMessage;
13+
use derive_new::new;
14+
use rumqttc::{Event, Incoming, MqttOptions, QoS};
1115
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
1216
use serde::{Deserialize, Serialize};
17+
use std::str::FromStr;
18+
use std::string::FromUtf8Error;
19+
use std::sync::Mutex;
20+
use std::time::Duration;
1321
use tokio::sync::mpsc;
1422
use tracing::{debug, error, info, trace, warn};
15-
use common_define::db::{DbErr, DeviceLoraGateColumn, DeviceLoraGateEntity, Eui};
16-
use common_define::event::DownloadMessage;
17-
use crate::event::config_cache;
18-
use crate::man::data::DownloadData;
19-
use crate::man::gw::{DataWrapper, GwCmd, GwCmdResponse, ShellCmd};
20-
use crate::man::Id;
21-
use crate::man::lora::{LoRaNode, LoRaNodeManager};
22-
use crate::protocol::mqtt::{LinkRx, LinkTx, Notification};
23-
2423

2524
#[derive(Debug, Deserialize, Serialize)]
2625
pub struct ForwardResult {
@@ -74,7 +73,6 @@ pub enum MqttError {
7473
}
7574

7675
impl MqPublisher {
77-
7876
pub fn new(client: LinkTx) -> MqPublisher {
7977
MqPublisher { client: Mutex::new(client) }
8078
}
@@ -88,21 +86,32 @@ impl MqPublisher {
8886
pub struct MessageProcessor {
8987
rx: LinkRx,
9088
sender: mpsc::Sender<MqttMessage>,
91-
down: mpsc::Sender<DownloadMessage>
89+
down: mpsc::Sender<DownloadMessage>,
9290
}
9391

9492
impl MessageProcessor {
95-
pub fn new_with_sender(rx: LinkRx, sender: mpsc::Sender<MqttMessage>, down: mpsc::Sender<DownloadMessage>) -> Self {
93+
pub fn new_with_sender(
94+
rx: LinkRx,
95+
sender: mpsc::Sender<MqttMessage>,
96+
down: mpsc::Sender<DownloadMessage>,
97+
) -> Self {
9698
Self { sender, rx, down }
9799
}
98100

99-
100101
pub async fn start(mut self) {
101102
while let Ok(message) = self.rx.next().await {
102103
if let Some(Notification::Forward(publish)) = message {
104+
let down = self.down.clone();
103105
match String::from_utf8(publish.publish.topic.to_vec()) {
104106
Ok(topic) => {
105-
tokio::spawn(process_mqtt(MqttMessage::new(topic, publish.publish.payload), self.down.clone()));
107+
tokio::spawn(async move {
108+
if let Err(e) =
109+
process_mqtt(MqttMessage::new(topic, publish.publish.payload), down)
110+
.await
111+
{
112+
warn!("mqtt payload: {}", e)
113+
}
114+
});
106115
}
107116
Err(_) => {
108117
warn!("Snap Mqtt message contained invalid UTF-8");
@@ -113,7 +122,10 @@ impl MessageProcessor {
113122
}
114123
}
115124

116-
async fn process_mqtt(message: MqttMessage, down: mpsc::Sender<DownloadMessage>) -> Result<(), MqttError> {
125+
async fn process_mqtt(
126+
message: MqttMessage,
127+
down: mpsc::Sender<DownloadMessage>,
128+
) -> Result<(), MqttError> {
117129
let mut topic = message.topic.splitn(3, '/');
118130
topic.next();
119131
if let Some(user_id) = topic.next() {
@@ -130,8 +142,12 @@ async fn process_mqtt(message: MqttMessage, down: mpsc::Sender<DownloadMessage>)
130142
}
131143
Ok(())
132144
}
133-
async fn process_downlink(user_id: Id, message: MqttMessage, down: mpsc::Sender<DownloadMessage>) -> Result<(), MqttError> {
134-
let mut topic = message.topic.split( '/');
145+
async fn process_downlink(
146+
user_id: Id,
147+
message: MqttMessage,
148+
down: mpsc::Sender<DownloadMessage>,
149+
) -> Result<(), MqttError> {
150+
let mut topic = message.topic.split('/');
135151
topic.next();
136152
topic.next();
137153
topic.next();
@@ -142,15 +158,11 @@ async fn process_downlink(user_id: Id, message: MqttMessage, down: mpsc::Sender<
142158
if let Some(node) = LoRaNodeManager::get_node_by_eui(eui).await? {
143159
if node.info.user_id == Some(user_id) {
144160
let data: ForwardPayload = serde_json::from_slice(&message.payload)?;
145-
down.send(DownloadMessage {
146-
eui,
147-
port: data.port,
148-
data: data.payload,
149-
}).await;
161+
down.send(DownloadMessage { eui, port: data.port, data: data.payload }).await;
150162
let rx = GLOBAL_DOWNLOAD_RESPONSE.add(eui);
151163
let topic = format!("user/{}/device/{}/forward_result", user_id, eui);
152164
if data.timeout > 60 {
153-
return Ok(())
165+
return Ok(());
154166
}
155167
match rx {
156168
Some(rx) => {
@@ -159,10 +171,16 @@ async fn process_downlink(user_id: Id, message: MqttMessage, down: mpsc::Sender<
159171
Ok(Ok(response)) => {
160172
let payload = serde_json::to_string(&ForwardResult {
161173
port: response.1,
162-
payload: base64::engine::general_purpose::STANDARD.encode(response.0.as_slice()),
163-
status: 0
174+
payload: base64::engine::general_purpose::STANDARD
175+
.encode(response.0.as_slice()),
176+
status: 0,
164177
})?;
165-
GLOBAL_STATE.mq.publish(crate::integration::mqtt::MqttMessage::new(payload, topic)).await?;
178+
GLOBAL_STATE
179+
.mq
180+
.publish(crate::integration::mqtt::MqttMessage::new(
181+
payload, topic,
182+
))
183+
.await?;
166184
}
167185
_ => {
168186
GLOBAL_DOWNLOAD_RESPONSE.get(eui);
@@ -173,9 +191,12 @@ async fn process_downlink(user_id: Id, message: MqttMessage, down: mpsc::Sender<
173191
let payload = serde_json::to_string(&ForwardResult {
174192
port: 0,
175193
payload: "".to_string(),
176-
status: -1
194+
status: -1,
177195
})?;
178-
GLOBAL_STATE.mq.publish(crate::integration::mqtt::MqttMessage::new(payload, topic)).await?;
196+
GLOBAL_STATE
197+
.mq
198+
.publish(crate::integration::mqtt::MqttMessage::new(payload, topic))
199+
.await?;
179200
}
180201
}
181202
}
@@ -184,16 +205,20 @@ async fn process_downlink(user_id: Id, message: MqttMessage, down: mpsc::Sender<
184205
Ok(())
185206
}
186207
async fn process_gateway(user_id: Id, message: MqttMessage) -> Result<(), MqttError> {
187-
let mut topic = message.topic.split( '/');
208+
let mut topic = message.topic.split('/');
188209
topic.next();
189210
topic.next();
190211
topic.next();
191212
let eui_s = topic.next().ok_or(MqttError::EuiNotFound)?;
192213
let action = topic.next().ok_or(MqttError::ActionNotFound)?;
193214
if "up" == action {
194-
let cmd: GwCmdResponse = serde_json::from_slice(message.payload.as_ref()).map_err(|e| MqttError::SerdeError(e))?;
215+
let cmd: GwCmdResponse = serde_json::from_slice(message.payload.as_ref())
216+
.map_err(|e| MqttError::SerdeError(e))?;
195217
let eui = Eui::from_str(eui_s)?;
196-
let gate = DeviceLoraGateEntity::find().filter(DeviceLoraGateColumn::Eui.eq(eui)).one(&GLOBAL_STATE.db).await?;
218+
let gate = DeviceLoraGateEntity::find()
219+
.filter(DeviceLoraGateColumn::Eui.eq(eui))
220+
.one(&GLOBAL_STATE.db)
221+
.await?;
197222
if let Some(gate) = gate {
198223
match cmd {
199224
GwCmdResponse::ShellCmd(DataWrapper { id, data }) => {}

devices_manager/src/protocol/mqtt/server/router.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -435,7 +435,7 @@ impl Router {
435435
assert_eq!(self.obufs.insert(outgoing), connection_id);
436436

437437
self.connection_map.insert(client_id.clone(), connection_id);
438-
info!(connection_id, "Client connection registered");
438+
debug!(connection_id, "Client connection registered");
439439

440440
assert_eq!(self.ackslog.insert(ackslog), connection_id);
441441
assert_eq!(self.scheduler.add(tracker), connection_id);
@@ -731,7 +731,7 @@ impl Router {
731731
tracing::info_span!("subscribe", topic = f.path, pkid = subscribe.pkid);
732732
let _guard = span.enter();
733733

734-
info!("Adding subscription on topic {}", f.path);
734+
debug!("Adding subscription on topic {}", f.path);
735735
let connection = self.connections.get_mut(id).unwrap();
736736

737737
if let Err(e) = validate_subscription(connection, f) {

devices_manager/src/protocol/mqtt/server/server.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use tokio::net::{TcpListener, TcpStream};
99
use tokio::time;
1010
use tokio::time::error::Elapsed;
1111
use tracing::{error, info, field, Instrument, Span};
12+
use tracing::log::debug;
1213
use uuid::Uuid;
1314
use ws_stream_tungstenite::WsStream;
1415
use crate::protocol::mqtt::{version, ConnectionId};
@@ -127,7 +128,7 @@ impl Server {
127128
};
128129
}
129130

130-
info!(
131+
debug!(
131132
name=?self.config.name, ?addr, count, tenant=?tenant_id, "accept"
132133
);
133134

migration/src/m20240904_020441_create_table.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,7 @@ mod device {
227227
.col(big_key_auto(SnapIntegrationMqtt::Id))
228228
.col(big_integer(SnapIntegrationMqtt::UserId))
229229
.col(text(SnapIntegrationMqtt::MqttType))
230+
.col(text(SnapIntegrationMqtt::Name))
230231
.col(text(SnapIntegrationMqtt::Username))
231232
.col(text(SnapIntegrationMqtt::Password))
232233
.col(boolean(SnapIntegrationMqtt::Enable))
@@ -500,8 +501,9 @@ mod device {
500501
enum SnapIntegrationMqtt {
501502
Table,
502503
Id,
503-
MqttType,
504504
UserId,
505+
MqttType,
506+
Name,
505507
Username,
506508
Password,
507509
Enable,

snap_api/src/service/device/device.rs

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
use common_define::db::{DecodeScriptColumn, DecodeScriptEntity, DeviceAuthorityActiveModel, DeviceAuthorityColumn, DeviceAuthorityEntity, DeviceAuthorityModel, DeviceDataEntity, DeviceDataModel, DeviceFunctionColumn, DeviceFunctionEntity, DeviceFunctionModel, DeviceLoraGateActiveModel, DeviceLoraGateColumn, DeviceLoraGateEntity, DeviceLoraGateModel, DeviceLoraNodeColumn, DeviceLoraNodeEntity, DeviceLoraNodeModel, DevicesActiveModel, DevicesColumn, DevicesEntity, DevicesModel, Eui, Key, LoRaAddr, SnapDeviceColumn, SnapDeviceDataNameColumn, SnapDeviceDataNameEntity, SnapDeviceEntity, SnapDeviceModel};
1+
use common_define::db::{
2+
DecodeScriptColumn, DecodeScriptEntity, DeviceAuthorityActiveModel, DeviceAuthorityColumn,
3+
DeviceAuthorityEntity, DeviceAuthorityModel, DeviceDataEntity, DeviceDataModel,
4+
DeviceFunctionColumn, DeviceFunctionEntity, DeviceFunctionModel, DeviceLoraGateActiveModel,
5+
DeviceLoraGateColumn, DeviceLoraGateEntity, DeviceLoraGateModel, DeviceLoraNodeColumn,
6+
DeviceLoraNodeEntity, DeviceLoraNodeModel, DevicesActiveModel, DevicesColumn, DevicesEntity,
7+
DevicesModel, Eui, Key, LoRaAddr, SnapDeviceColumn, SnapDeviceDataNameColumn,
8+
SnapDeviceDataNameEntity, SnapDeviceEntity, SnapDeviceModel,
9+
};
210
use common_define::decode::LastDecodeData;
311
use common_define::lora::{LoRaJoinType, LoRaRegion};
412
use common_define::product::{DeviceType, ProductType, ShareType};
@@ -16,20 +24,20 @@ use serde_json::Value;
1624
use std::collections::HashMap;
1725
use tracing::{debug, instrument};
1826

27+
use super::DeviceService;
1928
use crate::cache::DeviceCache;
2029
use crate::error::ApiError;
2130
use crate::error::ApiResult;
22-
use crate::{
23-
get_lang, tt, AppState, CurrentUser, DEVICE_DATA_RAW_SQL, MODEL_MAP, SEA_ORMDB_BACKEND,
24-
};
2531
use crate::gw_conf::GwConfig;
26-
use super::DeviceService;
2732
use crate::service::data::query::{DataDeviceOneResponse, TimeDate};
2833
use crate::service::data::DataService;
2934
use crate::service::device::group::{DeviceGroupResp, DeviceGroupService};
3035
use crate::service::lorawan::{LoRaGateService, LoRaNodeService, ReqLoraGateway, ReqLoraNode};
3136
use crate::service::mqtt::{MQTTService, ReqMQTT};
3237
use crate::service::snap::{ReqSnap, SnapDeviceService, SnapJoinParameter};
38+
use crate::{
39+
get_lang, tt, AppState, CurrentUser, DEVICE_DATA_RAW_SQL, MODEL_MAP, SEA_ORMDB_BACKEND,
40+
};
3341

3442
#[derive(Serialize)]
3543
pub(crate) struct DeviceIoResp {
@@ -628,31 +636,24 @@ impl DeviceService {
628636
redis: &mut R,
629637
conn: &C,
630638
) -> ApiResult<DeviceCache> {
631-
match DeviceCache::load_by_user_id(user_id, redis).await? {
632-
Some(cache) => Ok(cache),
633-
None => {
634-
let devices = DeviceAuthorityEntity::find()
635-
.filter(
636-
DeviceAuthorityColumn::ShareId
637-
.eq(user_id)
638-
.and(DeviceAuthorityColumn::ShareType.eq(ShareType::User.as_ref())),
639-
)
640-
.find_also_related(DevicesEntity)
641-
.all(conn)
642-
.await?;
643-
let devices = devices
644-
.into_iter()
645-
.filter_map(|item| match item.1 {
646-
Some(device) => Some(DeviceWithAuth { device, auth: item.0 }),
647-
None => None,
648-
})
649-
.collect::<Vec<_>>();
650-
let device_cache = DeviceCache::new(devices);
651-
debug!("update device cache");
652-
device_cache.save_by_user_id(user_id, redis).await?;
653-
Ok(device_cache)
654-
}
655-
}
639+
let devices = DeviceAuthorityEntity::find()
640+
.filter(
641+
DeviceAuthorityColumn::ShareId
642+
.eq(user_id)
643+
.and(DeviceAuthorityColumn::ShareType.eq(ShareType::User.as_ref())),
644+
)
645+
.find_also_related(DevicesEntity)
646+
.all(conn)
647+
.await?;
648+
let devices = devices
649+
.into_iter()
650+
.filter_map(|item| match item.1 {
651+
Some(device) => Some(DeviceWithAuth { device, auth: item.0 }),
652+
None => None,
653+
})
654+
.collect::<Vec<_>>();
655+
let device_cache = DeviceCache::new(devices);
656+
Ok(device_cache)
656657
}
657658
pub(crate) async fn query_all_with_ids<C: ConnectionTrait>(
658659
user_id: Id,
@@ -922,7 +923,6 @@ impl DeviceService {
922923
let mut gate = gate.into_active_model();
923924
if let Some(region) = info.region {
924925
gate.region = ActiveValue::Set(region);
925-
926926
}
927927
gate.update(conn).await?;
928928
}

snap_api/src/service/user/auth.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ pub(crate) async fn auth(
133133
}
134134
}
135135
}
136-
info!("auth success: {}", user.id);
136+
debug!("request user id: {}, username: {}, path: {}", user.id, user.name, req.uri().path_and_query().map(|x| x.as_str()).unwrap_or_default());
137137
Ok(run_with_user(user.id, user.name, next.run(req)).await)
138138
}
139139
Err(e) => Ok(e.into_response()),

snap_proto/build.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ fn main() {
1717
.field_attribute("manager.GwConfig.trust_mode", r#"#[serde(skip_serializing_if = "Option::is_none")]"#)
1818
.field_attribute("manager.GwConfig.api_token", r#"#[serde(skip_serializing_if = "Option::is_none")]"#)
1919
.field_attribute("manager.GwConfig.cert", r#"#[serde(skip_serializing_if = "Option::is_none")]"#)
20+
.field_attribute("manager.GwConfig.client_cert", r#"#[serde(skip_serializing_if = "Option::is_none")]"#)
2021
.compile_protos(&["proto/manager.proto"], &["proto"])
2122
.unwrap();
2223
}

0 commit comments

Comments
 (0)