Commit 5e88b02f1e7fc7c840e43b3d856de1bd23d156a3

Authored by Andrew Shvayka
1 parent 8c481f20

Revert commit for Device State: 494bb544

Showing 31 changed files with 43 additions and 760 deletions
@@ -94,5 +94,3 @@ CREATE TABLE IF NOT EXISTS thingsboard.rule_node ( @@ -94,5 +94,3 @@ CREATE TABLE IF NOT EXISTS thingsboard.rule_node (
94 PRIMARY KEY (id) 94 PRIMARY KEY (id)
95 ); 95 );
96 96
97 -ALTER TABLE thingsboard.device ADD last_connect bigint;  
98 -ALTER TABLE thingsboard.device ADD last_update bigint;  
@@ -35,7 +35,4 @@ CREATE TABLE IF NOT EXISTS rule_node ( @@ -35,7 +35,4 @@ CREATE TABLE IF NOT EXISTS rule_node (
35 name varchar(255), 35 name varchar(255),
36 debug_mode boolean, 36 debug_mode boolean,
37 search_text varchar(255) 37 search_text varchar(255)
38 -);  
39 -  
40 -ALTER TABLE device ADD COLUMN IF NOT EXISTS last_connect BIGINT;  
41 -ALTER TABLE device ADD COLUMN IF NOT EXISTS last_update BIGINT;  
  38 +);
@@ -45,7 +45,6 @@ import org.thingsboard.server.dao.audit.AuditLogService; @@ -45,7 +45,6 @@ import org.thingsboard.server.dao.audit.AuditLogService;
45 import org.thingsboard.server.dao.customer.CustomerService; 45 import org.thingsboard.server.dao.customer.CustomerService;
46 import org.thingsboard.server.dao.dashboard.DashboardService; 46 import org.thingsboard.server.dao.dashboard.DashboardService;
47 import org.thingsboard.server.dao.device.DeviceCredentialsService; 47 import org.thingsboard.server.dao.device.DeviceCredentialsService;
48 -import org.thingsboard.server.dao.device.DeviceOfflineService;  
49 import org.thingsboard.server.dao.device.DeviceService; 48 import org.thingsboard.server.dao.device.DeviceService;
50 import org.thingsboard.server.dao.exception.DataValidationException; 49 import org.thingsboard.server.dao.exception.DataValidationException;
51 import org.thingsboard.server.dao.exception.IncorrectParameterException; 50 import org.thingsboard.server.dao.exception.IncorrectParameterException;
@@ -136,9 +135,6 @@ public abstract class BaseController { @@ -136,9 +135,6 @@ public abstract class BaseController {
136 protected AuditLogService auditLogService; 135 protected AuditLogService auditLogService;
137 136
138 @Autowired 137 @Autowired
139 - protected DeviceOfflineService offlineService;  
140 -  
141 - @Autowired  
142 protected DeviceStateService deviceStateService; 138 protected DeviceStateService deviceStateService;
143 139
144 @ExceptionHandler(ThingsboardException.class) 140 @ExceptionHandler(ThingsboardException.class)
@@ -25,9 +25,6 @@ import org.thingsboard.server.common.data.EntitySubtype; @@ -25,9 +25,6 @@ import org.thingsboard.server.common.data.EntitySubtype;
25 import org.thingsboard.server.common.data.EntityType; 25 import org.thingsboard.server.common.data.EntityType;
26 import org.thingsboard.server.common.data.audit.ActionType; 26 import org.thingsboard.server.common.data.audit.ActionType;
27 import org.thingsboard.server.common.data.device.DeviceSearchQuery; 27 import org.thingsboard.server.common.data.device.DeviceSearchQuery;
28 -import org.thingsboard.server.common.data.device.DeviceStatusQuery;  
29 -import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;  
30 -import org.thingsboard.server.common.data.exception.ThingsboardException;  
31 import org.thingsboard.server.common.data.id.CustomerId; 28 import org.thingsboard.server.common.data.id.CustomerId;
32 import org.thingsboard.server.common.data.id.DeviceId; 29 import org.thingsboard.server.common.data.id.DeviceId;
33 import org.thingsboard.server.common.data.id.TenantId; 30 import org.thingsboard.server.common.data.id.TenantId;
@@ -37,6 +34,8 @@ import org.thingsboard.server.common.data.security.Authority; @@ -37,6 +34,8 @@ import org.thingsboard.server.common.data.security.Authority;
37 import org.thingsboard.server.common.data.security.DeviceCredentials; 34 import org.thingsboard.server.common.data.security.DeviceCredentials;
38 import org.thingsboard.server.dao.exception.IncorrectParameterException; 35 import org.thingsboard.server.dao.exception.IncorrectParameterException;
39 import org.thingsboard.server.dao.model.ModelConstants; 36 import org.thingsboard.server.dao.model.ModelConstants;
  37 +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
  38 +import org.thingsboard.server.common.data.exception.ThingsboardException;
40 import org.thingsboard.server.service.security.model.SecurityUser; 39 import org.thingsboard.server.service.security.model.SecurityUser;
41 40
42 import java.util.ArrayList; 41 import java.util.ArrayList;
@@ -70,7 +69,7 @@ public class DeviceController extends BaseController { @@ -70,7 +69,7 @@ public class DeviceController extends BaseController {
70 device.setTenantId(getCurrentUser().getTenantId()); 69 device.setTenantId(getCurrentUser().getTenantId());
71 if (getCurrentUser().getAuthority() == Authority.CUSTOMER_USER) { 70 if (getCurrentUser().getAuthority() == Authority.CUSTOMER_USER) {
72 if (device.getId() == null || device.getId().isNullUid() || 71 if (device.getId() == null || device.getId().isNullUid() ||
73 - device.getCustomerId() == null || device.getCustomerId().isNullUid()) { 72 + device.getCustomerId() == null || device.getCustomerId().isNullUid()) {
74 throw new ThingsboardException("You don't have permission to perform this operation!", 73 throw new ThingsboardException("You don't have permission to perform this operation!",
75 ThingsboardErrorCode.PERMISSION_DENIED); 74 ThingsboardErrorCode.PERMISSION_DENIED);
76 } else { 75 } else {
@@ -374,32 +373,4 @@ public class DeviceController extends BaseController { @@ -374,32 +373,4 @@ public class DeviceController extends BaseController {
374 throw handleException(e); 373 throw handleException(e);
375 } 374 }
376 } 375 }
377 -  
378 - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")  
379 - @RequestMapping(value = "/device/offline", method = RequestMethod.GET)  
380 - @ResponseBody  
381 - public List<Device> getOfflineDevices(@RequestParam("contactType") DeviceStatusQuery.ContactType contactType,  
382 - @RequestParam("threshold") long threshold) throws ThingsboardException {  
383 - try {  
384 - TenantId tenantId = getCurrentUser().getTenantId();  
385 - ListenableFuture<List<Device>> offlineDevices = offlineService.findOfflineDevices(tenantId.getId(), contactType, threshold);  
386 - return checkNotNull(offlineDevices.get());  
387 - } catch (Exception e) {  
388 - throw handleException(e);  
389 - }  
390 - }  
391 -  
392 - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")  
393 - @RequestMapping(value = "/device/online", method = RequestMethod.GET)  
394 - @ResponseBody  
395 - public List<Device> getOnlineDevices(@RequestParam("contactType") DeviceStatusQuery.ContactType contactType,  
396 - @RequestParam("threshold") long threshold) throws ThingsboardException {  
397 - try {  
398 - TenantId tenantId = getCurrentUser().getTenantId();  
399 - ListenableFuture<List<Device>> offlineDevices = offlineService.findOnlineDevices(tenantId.getId(), contactType, threshold);  
400 - return checkNotNull(offlineDevices.get());  
401 - } catch (Exception e) {  
402 - throw handleException(e);  
403 - }  
404 - }  
405 } 376 }
@@ -262,7 +262,7 @@ public class DefaultDeviceStateService implements DeviceStateService { @@ -262,7 +262,7 @@ public class DefaultDeviceStateService implements DeviceStateService {
262 state.setInactivityTimeout(inactivityTimeout); 262 state.setInactivityTimeout(inactivityTimeout);
263 boolean oldActive = state.isActive(); 263 boolean oldActive = state.isActive();
264 state.setActive(ts < state.getLastActivityTime() + state.getInactivityTimeout()); 264 state.setActive(ts < state.getLastActivityTime() + state.getInactivityTimeout());
265 - if (!oldActive && state.isActive()) { 265 + if (!oldActive && state.isActive() || oldActive && !state.isActive()) {
266 saveAttribute(deviceId, ACTIVITY_STATE, state.isActive()); 266 saveAttribute(deviceId, ACTIVITY_STATE, state.isActive());
267 } 267 }
268 } 268 }
@@ -333,10 +333,6 @@ public class DefaultDeviceStateService implements DeviceStateService { @@ -333,10 +333,6 @@ public class DefaultDeviceStateService implements DeviceStateService {
333 }); 333 });
334 } 334 }
335 335
336 - private long getLastPersistTime(List<AttributeKvEntry> attributes) {  
337 - return attributes.stream().map(AttributeKvEntry::getLastUpdateTs).max(Long::compare).orElse(0L);  
338 - }  
339 -  
340 private long getAttributeValue(List<AttributeKvEntry> attributes, String attributeName, long defaultValue) { 336 private long getAttributeValue(List<AttributeKvEntry> attributes, String attributeName, long defaultValue) {
341 for (AttributeKvEntry attribute : attributes) { 337 for (AttributeKvEntry attribute : attributes) {
342 if (attribute.getKey().equals(attributeName)) { 338 if (attribute.getKey().equals(attributeName)) {
1 -/**  
2 - * Copyright © 2016-2018 The Thingsboard Authors  
3 - *  
4 - * Licensed under the Apache License, Version 2.0 (the "License");  
5 - * you may not use this file except in compliance with the License.  
6 - * You may obtain a copy of the License at  
7 - *  
8 - * http://www.apache.org/licenses/LICENSE-2.0  
9 - *  
10 - * Unless required by applicable law or agreed to in writing, software  
11 - * distributed under the License is distributed on an "AS IS" BASIS,  
12 - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
13 - * See the License for the specific language governing permissions and  
14 - * limitations under the License.  
15 - */  
16 -package org.thingsboard.server.system;  
17 -  
18 -import com.fasterxml.jackson.core.type.TypeReference;  
19 -import com.google.common.collect.ImmutableMap;  
20 -import org.junit.Before;  
21 -import org.junit.Test;  
22 -import org.thingsboard.server.common.data.Device;  
23 -import org.thingsboard.server.common.data.security.DeviceCredentials;  
24 -import org.thingsboard.server.controller.AbstractControllerTest;  
25 -  
26 -import java.util.List;  
27 -import java.util.UUID;  
28 -import java.util.concurrent.TimeUnit;  
29 -  
30 -import static org.junit.Assert.assertEquals;  
31 -  
32 -public class BaseDeviceOfflineTest extends AbstractControllerTest {  
33 -  
34 - private Device deviceA;  
35 - private Device deviceB;  
36 - private DeviceCredentials credA;  
37 - private DeviceCredentials credB;  
38 -  
39 - @Before  
40 - public void before() throws Exception {  
41 - loginTenantAdmin();  
42 - deviceA = createDevice("DevA", "VMS");  
43 - credA = getCredentials(deviceA.getUuidId());  
44 - deviceB = createDevice("DevB", "SOLAR");  
45 - credB = getCredentials(deviceB.getUuidId());  
46 - }  
47 -  
48 - @Test  
49 - public void offlineDevicesCanBeFoundByLastConnectField() throws Exception {  
50 - makeDeviceContact(credA);  
51 - Thread.sleep(1000);  
52 - makeDeviceContact(credB);  
53 - Thread.sleep(100);  
54 - List<Device> devices = doGetTyped("/api/device/offline?contactType=CONNECT&threshold=700", new TypeReference<List<Device>>() {  
55 - });  
56 -  
57 - assertEquals(devices.toString(),1, devices.size());  
58 - assertEquals("DevA", devices.get(0).getName());  
59 - }  
60 -  
61 - @Test  
62 - public void offlineDevicesCanBeFoundByLastUpdateField() throws Exception {  
63 - makeDeviceUpdate(credA);  
64 - Thread.sleep(1000);  
65 - makeDeviceUpdate(credB);  
66 - makeDeviceContact(credA);  
67 - Thread.sleep(100);  
68 - List<Device> devices = doGetTyped("/api/device/offline?contactType=UPLOAD&threshold=700", new TypeReference<List<Device>>() {  
69 - });  
70 -  
71 - assertEquals(devices.toString(),1, devices.size());  
72 - assertEquals("DevA", devices.get(0).getName());  
73 - }  
74 -  
75 - @Test  
76 - public void onlineDevicesCanBeFoundByLastConnectField() throws Exception {  
77 - makeDeviceContact(credB);  
78 - Thread.sleep(1000);  
79 - makeDeviceContact(credA);  
80 - Thread.sleep(100);  
81 - List<Device> devices = doGetTyped("/api/device/online?contactType=CONNECT&threshold=700", new TypeReference<List<Device>>() {  
82 - });  
83 -  
84 - assertEquals(devices.toString(),1, devices.size());  
85 - assertEquals("DevA", devices.get(0).getName());  
86 - }  
87 -  
88 - @Test  
89 - public void onlineDevicesCanBeFoundByLastUpdateField() throws Exception {  
90 - makeDeviceUpdate(credB);  
91 - Thread.sleep(1000);  
92 - makeDeviceUpdate(credA);  
93 - makeDeviceContact(credB);  
94 - Thread.sleep(100);  
95 - List<Device> devices = doGetTyped("/api/device/online?contactType=UPLOAD&threshold=700", new TypeReference<List<Device>>() {  
96 - });  
97 -  
98 - assertEquals(devices.toString(),1, devices.size());  
99 - assertEquals("DevA", devices.get(0).getName());  
100 - }  
101 -  
102 - private Device createDevice(String name, String type) throws Exception {  
103 - Device device = new Device();  
104 - device.setName(name);  
105 - device.setType(type);  
106 - long currentTime = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(10);  
107 - device.setLastConnectTs(currentTime);  
108 - device.setLastUpdateTs(currentTime);  
109 - return doPost("/api/device", device, Device.class);  
110 - }  
111 -  
112 - private DeviceCredentials getCredentials(UUID deviceId) throws Exception {  
113 - return doGet("/api/device/" + deviceId.toString() + "/credentials", DeviceCredentials.class);  
114 - }  
115 -  
116 - private void makeDeviceUpdate(DeviceCredentials credentials) throws Exception {  
117 - doPost("/api/v1/" + credentials.getCredentialsId() + "/attributes", ImmutableMap.of("keyA", "valueA"), new String[]{});  
118 - }  
119 -  
120 - private void makeDeviceContact(DeviceCredentials credentials) throws Exception {  
121 - doGet("/api/v1/" + credentials.getCredentialsId() + "/attributes?clientKeys=keyA,keyB,keyC");  
122 - }  
123 -}  
@@ -15,7 +15,6 @@ @@ -15,7 +15,6 @@
15 */ 15 */
16 package org.thingsboard.server.system; 16 package org.thingsboard.server.system;
17 17
18 -import com.google.common.collect.ImmutableMap;  
19 import org.junit.Before; 18 import org.junit.Before;
20 import org.junit.Test; 19 import org.junit.Test;
21 import org.springframework.test.web.servlet.ResultActions; 20 import org.springframework.test.web.servlet.ResultActions;
@@ -29,9 +28,6 @@ import java.util.Map; @@ -29,9 +28,6 @@ import java.util.Map;
29 import java.util.Random; 28 import java.util.Random;
30 import java.util.concurrent.atomic.AtomicInteger; 29 import java.util.concurrent.atomic.AtomicInteger;
31 30
32 -import static org.junit.Assert.assertEquals;  
33 -import static org.junit.Assert.assertNotNull;  
34 -import static org.junit.Assert.assertTrue;  
35 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; 31 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
36 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; 32 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
37 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 33 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -52,9 +48,6 @@ public abstract class BaseHttpDeviceApiTest extends AbstractControllerTest { @@ -52,9 +48,6 @@ public abstract class BaseHttpDeviceApiTest extends AbstractControllerTest {
52 device = new Device(); 48 device = new Device();
53 device.setName("My device"); 49 device.setName("My device");
54 device.setType("default"); 50 device.setType("default");
55 - long currentTime = System.currentTimeMillis();  
56 - device.setLastConnectTs(currentTime);  
57 - device.setLastUpdateTs(currentTime);  
58 device = doPost("/api/device", device, Device.class); 51 device = doPost("/api/device", device, Device.class);
59 52
60 deviceCredentials = 53 deviceCredentials =
@@ -74,34 +67,6 @@ public abstract class BaseHttpDeviceApiTest extends AbstractControllerTest { @@ -74,34 +67,6 @@ public abstract class BaseHttpDeviceApiTest extends AbstractControllerTest {
74 doGetAsync("/api/v1/" + deviceCredentials.getCredentialsId() + "/attributes?clientKeys=keyA,keyB,keyC").andExpect(status().isOk()); 67 doGetAsync("/api/v1/" + deviceCredentials.getCredentialsId() + "/attributes?clientKeys=keyA,keyB,keyC").andExpect(status().isOk());
75 } 68 }
76 69
77 - @Test  
78 - public void deviceLastContactAndUpdateFieldsAreUpdated() throws Exception {  
79 - Device actualDevice = doGet("/api/device/" + this.device.getId(), Device.class);  
80 - Long initConnectTs = actualDevice.getLastConnectTs();  
81 - Long initUpdateTs = actualDevice.getLastUpdateTs();  
82 - assertNotNull(initConnectTs);  
83 - assertNotNull(initUpdateTs);  
84 - Thread.sleep(50);  
85 -  
86 - doPost("/api/v1/" + deviceCredentials.getCredentialsId() + "/attributes", ImmutableMap.of("keyA", "valueA"), new String[]{});  
87 - actualDevice = doGet("/api/device/" + this.device.getId(), Device.class);  
88 - Long postConnectTs = actualDevice.getLastConnectTs();  
89 - Long postUpdateTs = actualDevice.getLastUpdateTs();  
90 - System.out.println(postConnectTs + " - " + postUpdateTs + " -> " + (postConnectTs - initConnectTs) + " : " + (postUpdateTs - initUpdateTs));  
91 - assertTrue(postConnectTs > initConnectTs);  
92 - assertEquals(postConnectTs, postUpdateTs);  
93 - Thread.sleep(50);  
94 -  
95 - doGet("/api/v1/" + deviceCredentials.getCredentialsId() + "/attributes?clientKeys=keyA,keyB,keyC");  
96 - Thread.sleep(50);  
97 - actualDevice = doGet("/api/device/" + this.device.getId(), Device.class);  
98 - Long getConnectTs = actualDevice.getLastConnectTs();  
99 - Long getUpdateTs = actualDevice.getLastUpdateTs();  
100 - assertTrue(getConnectTs > postConnectTs);  
101 - assertEquals(getUpdateTs, postUpdateTs);  
102 -  
103 - }  
104 -  
105 protected ResultActions doGetAsync(String urlTemplate, Object... urlVariables) throws Exception { 70 protected ResultActions doGetAsync(String urlTemplate, Object... urlVariables) throws Exception {
106 MockHttpServletRequestBuilder getRequest; 71 MockHttpServletRequestBuilder getRequest;
107 getRequest = get(urlTemplate, urlVariables); 72 getRequest = get(urlTemplate, urlVariables);
1 -/**  
2 - * Copyright © 2016-2018 The Thingsboard Authors  
3 - *  
4 - * Licensed under the Apache License, Version 2.0 (the "License");  
5 - * you may not use this file except in compliance with the License.  
6 - * You may obtain a copy of the License at  
7 - *  
8 - * http://www.apache.org/licenses/LICENSE-2.0  
9 - *  
10 - * Unless required by applicable law or agreed to in writing, software  
11 - * distributed under the License is distributed on an "AS IS" BASIS,  
12 - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
13 - * See the License for the specific language governing permissions and  
14 - * limitations under the License.  
15 - */  
16 -package org.thingsboard.server.system.nosql;  
17 -  
18 -import org.thingsboard.server.dao.service.DaoNoSqlTest;  
19 -import org.thingsboard.server.system.BaseDeviceOfflineTest;  
20 -  
21 -@DaoNoSqlTest  
22 -public class DeviceOfflineNoSqlTest extends BaseDeviceOfflineTest {  
23 -}  
1 -/**  
2 - * Copyright © 2016-2018 The Thingsboard Authors  
3 - *  
4 - * Licensed under the Apache License, Version 2.0 (the "License");  
5 - * you may not use this file except in compliance with the License.  
6 - * You may obtain a copy of the License at  
7 - *  
8 - * http://www.apache.org/licenses/LICENSE-2.0  
9 - *  
10 - * Unless required by applicable law or agreed to in writing, software  
11 - * distributed under the License is distributed on an "AS IS" BASIS,  
12 - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
13 - * See the License for the specific language governing permissions and  
14 - * limitations under the License.  
15 - */  
16 -package org.thingsboard.server.system.sql;  
17 -  
18 -import org.thingsboard.server.dao.service.DaoSqlTest;  
19 -import org.thingsboard.server.system.BaseDeviceOfflineTest;  
20 -  
21 -@DaoSqlTest  
22 -public class DeviceOfflineSqlTest extends BaseDeviceOfflineTest {  
23 -}  
@@ -31,8 +31,6 @@ public class Device extends SearchTextBasedWithAdditionalInfo<DeviceId> implemen @@ -31,8 +31,6 @@ public class Device extends SearchTextBasedWithAdditionalInfo<DeviceId> implemen
31 private CustomerId customerId; 31 private CustomerId customerId;
32 private String name; 32 private String name;
33 private String type; 33 private String type;
34 - private Long lastConnectTs;  
35 - private Long lastUpdateTs;  
36 34
37 public Device() { 35 public Device() {
38 super(); 36 super();
@@ -83,22 +81,6 @@ public class Device extends SearchTextBasedWithAdditionalInfo<DeviceId> implemen @@ -83,22 +81,6 @@ public class Device extends SearchTextBasedWithAdditionalInfo<DeviceId> implemen
83 this.type = type; 81 this.type = type;
84 } 82 }
85 83
86 - public Long getLastConnectTs() {  
87 - return lastConnectTs;  
88 - }  
89 -  
90 - public void setLastConnectTs(Long lastConnectTs) {  
91 - this.lastConnectTs = lastConnectTs;  
92 - }  
93 -  
94 - public Long getLastUpdateTs() {  
95 - return lastUpdateTs;  
96 - }  
97 -  
98 - public void setLastUpdateTs(Long lastUpdateTs) {  
99 - this.lastUpdateTs = lastUpdateTs;  
100 - }  
101 -  
102 @Override 84 @Override
103 public String getSearchText() { 85 public String getSearchText() {
104 return getName(); 86 return getName();
@@ -119,10 +101,6 @@ public class Device extends SearchTextBasedWithAdditionalInfo<DeviceId> implemen @@ -119,10 +101,6 @@ public class Device extends SearchTextBasedWithAdditionalInfo<DeviceId> implemen
119 builder.append(getAdditionalInfo()); 101 builder.append(getAdditionalInfo());
120 builder.append(", createdTime="); 102 builder.append(", createdTime=");
121 builder.append(createdTime); 103 builder.append(createdTime);
122 - builder.append(", lastUpdateTs=");  
123 - builder.append(lastUpdateTs);  
124 - builder.append(", lastConnectTs=");  
125 - builder.append(lastConnectTs);  
126 builder.append(", id="); 104 builder.append(", id=");
127 builder.append(id); 105 builder.append(id);
128 builder.append("]"); 106 builder.append("]");
1 -/**  
2 - * Copyright © 2016-2018 The Thingsboard Authors  
3 - *  
4 - * Licensed under the Apache License, Version 2.0 (the "License");  
5 - * you may not use this file except in compliance with the License.  
6 - * You may obtain a copy of the License at  
7 - *  
8 - * http://www.apache.org/licenses/LICENSE-2.0  
9 - *  
10 - * Unless required by applicable law or agreed to in writing, software  
11 - * distributed under the License is distributed on an "AS IS" BASIS,  
12 - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
13 - * See the License for the specific language governing permissions and  
14 - * limitations under the License.  
15 - */  
16 -package org.thingsboard.server.common.data.device;  
17 -  
18 -import lombok.AllArgsConstructor;  
19 -import lombok.Data;  
20 -import lombok.ToString;  
21 -  
22 -@Data  
23 -@AllArgsConstructor  
24 -@ToString  
25 -public class DeviceStatusQuery {  
26 -  
27 - private Status status;  
28 - private ContactType contactType;  
29 - private long threshold;  
30 -  
31 -  
32 - public enum Status {  
33 - ONLINE, OFFLINE  
34 - }  
35 -  
36 - public enum ContactType {  
37 - CONNECT, UPLOAD  
38 - }  
39 -  
40 -}  
@@ -15,9 +15,9 @@ @@ -15,9 +15,9 @@
15 */ 15 */
16 package org.thingsboard.server.dao.device; 16 package org.thingsboard.server.dao.device;
17 17
18 -import com.datastax.driver.core.*;  
19 -import com.datastax.driver.core.querybuilder.Clause;  
20 -import com.datastax.driver.core.querybuilder.QueryBuilder; 18 +import com.datastax.driver.core.ResultSet;
  19 +import com.datastax.driver.core.ResultSetFuture;
  20 +import com.datastax.driver.core.Statement;
21 import com.datastax.driver.core.querybuilder.Select; 21 import com.datastax.driver.core.querybuilder.Select;
22 import com.datastax.driver.mapping.Result; 22 import com.datastax.driver.mapping.Result;
23 import com.google.common.base.Function; 23 import com.google.common.base.Function;
@@ -28,11 +28,9 @@ import org.springframework.stereotype.Component; @@ -28,11 +28,9 @@ import org.springframework.stereotype.Component;
28 import org.thingsboard.server.common.data.Device; 28 import org.thingsboard.server.common.data.Device;
29 import org.thingsboard.server.common.data.EntitySubtype; 29 import org.thingsboard.server.common.data.EntitySubtype;
30 import org.thingsboard.server.common.data.EntityType; 30 import org.thingsboard.server.common.data.EntityType;
31 -import org.thingsboard.server.common.data.device.DeviceStatusQuery;  
32 import org.thingsboard.server.common.data.page.TextPageLink; 31 import org.thingsboard.server.common.data.page.TextPageLink;
33 import org.thingsboard.server.dao.DaoUtil; 32 import org.thingsboard.server.dao.DaoUtil;
34 import org.thingsboard.server.dao.model.EntitySubtypeEntity; 33 import org.thingsboard.server.dao.model.EntitySubtypeEntity;
35 -import org.thingsboard.server.dao.model.ModelConstants;  
36 import org.thingsboard.server.dao.model.nosql.DeviceEntity; 34 import org.thingsboard.server.dao.model.nosql.DeviceEntity;
37 import org.thingsboard.server.dao.nosql.CassandraAbstractSearchTextDao; 35 import org.thingsboard.server.dao.nosql.CassandraAbstractSearchTextDao;
38 import org.thingsboard.server.dao.util.NoSqlDao; 36 import org.thingsboard.server.dao.util.NoSqlDao;
@@ -159,7 +157,7 @@ public class CassandraDeviceDao extends CassandraAbstractSearchTextDao<DeviceEnt @@ -159,7 +157,7 @@ public class CassandraDeviceDao extends CassandraAbstractSearchTextDao<DeviceEnt
159 if (result != null) { 157 if (result != null) {
160 List<EntitySubtype> entitySubtypes = new ArrayList<>(); 158 List<EntitySubtype> entitySubtypes = new ArrayList<>();
161 result.all().forEach((entitySubtypeEntity) -> 159 result.all().forEach((entitySubtypeEntity) ->
162 - entitySubtypes.add(entitySubtypeEntity.toEntitySubtype()) 160 + entitySubtypes.add(entitySubtypeEntity.toEntitySubtype())
163 ); 161 );
164 return entitySubtypes; 162 return entitySubtypes;
165 } else { 163 } else {
@@ -169,68 +167,4 @@ public class CassandraDeviceDao extends CassandraAbstractSearchTextDao<DeviceEnt @@ -169,68 +167,4 @@ public class CassandraDeviceDao extends CassandraAbstractSearchTextDao<DeviceEnt
169 }); 167 });
170 } 168 }
171 169
172 - @Override  
173 - public ListenableFuture<List<Device>> findDevicesByTenantIdAndStatus(UUID tenantId, DeviceStatusQuery statusQuery) {  
174 - log.debug("Try to find [{}] devices by tenantId [{}]", statusQuery.getStatus(), tenantId);  
175 -  
176 - Select select = select().from(DEVICE_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME).allowFiltering();  
177 - Select.Where query = select.where();  
178 - query.and(eq(DEVICE_TENANT_ID_PROPERTY, tenantId));  
179 - Clause clause = statusClause(statusQuery);  
180 - query.and(clause);  
181 - return findListByStatementAsync(query);  
182 - }  
183 -  
184 - @Override  
185 - public ListenableFuture<List<Device>> findDevicesByTenantIdTypeAndStatus(UUID tenantId, String type, DeviceStatusQuery statusQuery) {  
186 - log.debug("Try to find [{}] devices by tenantId [{}] and type [{}]", statusQuery.getStatus(), tenantId, type);  
187 -  
188 - Select select = select().from(DEVICE_BY_TENANT_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME).allowFiltering();  
189 - Select.Where query = select.where()  
190 - .and(eq(DEVICE_TENANT_ID_PROPERTY, tenantId))  
191 - .and(eq(DEVICE_TYPE_PROPERTY, type));  
192 -  
193 - query.and(statusClause(statusQuery));  
194 - return findListByStatementAsync(query);  
195 - }  
196 -  
197 -  
198 - @Override  
199 - public void saveDeviceStatus(Device device) {  
200 - PreparedStatement statement = prepare("insert into " +  
201 - "device (id, tenant_id, customer_id, type, last_connect, last_update) values (?, ?, ?, ?, ?, ?)");  
202 - BoundStatement boundStatement = statement.bind(device.getUuidId(), device.getTenantId().getId(), device.getCustomerId().getId(),  
203 - device.getType(), device.getLastConnectTs(), device.getLastUpdateTs());  
204 - ResultSetFuture resultSetFuture = executeAsyncWrite(boundStatement);  
205 - Futures.withFallback(resultSetFuture, t -> {  
206 - log.error("Can't update device status for [{}]", device, t);  
207 - throw new IllegalArgumentException("Can't update device status for {" + device + "}", t);  
208 - });  
209 - }  
210 -  
211 - private String getStatusProperty(DeviceStatusQuery statusQuery) {  
212 - switch (statusQuery.getContactType()) {  
213 - case UPLOAD:  
214 - return DEVICE_LAST_UPDATE_PROPERTY;  
215 - case CONNECT:  
216 - return DEVICE_LAST_CONNECT_PROPERTY;  
217 - }  
218 - return null;  
219 - }  
220 -  
221 - private Clause statusClause(DeviceStatusQuery statusQuery) {  
222 - long minTime = System.currentTimeMillis() - statusQuery.getThreshold();  
223 - String statusProperty = getStatusProperty(statusQuery);  
224 - if (statusProperty != null) {  
225 - switch (statusQuery.getStatus()) {  
226 - case ONLINE:  
227 - return gt(statusProperty, minTime);  
228 - case OFFLINE:  
229 - return lt(statusProperty, minTime);  
230 - }  
231 - }  
232 - log.error("Could not build status query from [{}]", statusQuery);  
233 - throw new IllegalStateException("Could not build status query for device []");  
234 - }  
235 -  
236 } 170 }
@@ -18,7 +18,6 @@ package org.thingsboard.server.dao.device; @@ -18,7 +18,6 @@ package org.thingsboard.server.dao.device;
18 import com.google.common.util.concurrent.ListenableFuture; 18 import com.google.common.util.concurrent.ListenableFuture;
19 import org.thingsboard.server.common.data.Device; 19 import org.thingsboard.server.common.data.Device;
20 import org.thingsboard.server.common.data.EntitySubtype; 20 import org.thingsboard.server.common.data.EntitySubtype;
21 -import org.thingsboard.server.common.data.device.DeviceStatusQuery;  
22 import org.thingsboard.server.common.data.page.TextPageLink; 21 import org.thingsboard.server.common.data.page.TextPageLink;
23 import org.thingsboard.server.dao.Dao; 22 import org.thingsboard.server.dao.Dao;
24 23
@@ -28,6 +27,7 @@ import java.util.UUID; @@ -28,6 +27,7 @@ import java.util.UUID;
28 27
29 /** 28 /**
30 * The Interface DeviceDao. 29 * The Interface DeviceDao.
  30 + *
31 */ 31 */
32 public interface DeviceDao extends Dao<Device> { 32 public interface DeviceDao extends Dao<Device> {
33 33
@@ -52,7 +52,7 @@ public interface DeviceDao extends Dao<Device> { @@ -52,7 +52,7 @@ public interface DeviceDao extends Dao<Device> {
52 * Find devices by tenantId, type and page link. 52 * Find devices by tenantId, type and page link.
53 * 53 *
54 * @param tenantId the tenantId 54 * @param tenantId the tenantId
55 - * @param type the type 55 + * @param type the type
56 * @param pageLink the page link 56 * @param pageLink the page link
57 * @return the list of device objects 57 * @return the list of device objects
58 */ 58 */
@@ -61,7 +61,7 @@ public interface DeviceDao extends Dao<Device> { @@ -61,7 +61,7 @@ public interface DeviceDao extends Dao<Device> {
61 /** 61 /**
62 * Find devices by tenantId and devices Ids. 62 * Find devices by tenantId and devices Ids.
63 * 63 *
64 - * @param tenantId the tenantId 64 + * @param tenantId the tenantId
65 * @param deviceIds the device Ids 65 * @param deviceIds the device Ids
66 * @return the list of device objects 66 * @return the list of device objects
67 */ 67 */
@@ -70,9 +70,9 @@ public interface DeviceDao extends Dao<Device> { @@ -70,9 +70,9 @@ public interface DeviceDao extends Dao<Device> {
70 /** 70 /**
71 * Find devices by tenantId, customerId and page link. 71 * Find devices by tenantId, customerId and page link.
72 * 72 *
73 - * @param tenantId the tenantId 73 + * @param tenantId the tenantId
74 * @param customerId the customerId 74 * @param customerId the customerId
75 - * @param pageLink the page link 75 + * @param pageLink the page link
76 * @return the list of device objects 76 * @return the list of device objects
77 */ 77 */
78 List<Device> findDevicesByTenantIdAndCustomerId(UUID tenantId, UUID customerId, TextPageLink pageLink); 78 List<Device> findDevicesByTenantIdAndCustomerId(UUID tenantId, UUID customerId, TextPageLink pageLink);
@@ -80,10 +80,10 @@ public interface DeviceDao extends Dao<Device> { @@ -80,10 +80,10 @@ public interface DeviceDao extends Dao<Device> {
80 /** 80 /**
81 * Find devices by tenantId, customerId, type and page link. 81 * Find devices by tenantId, customerId, type and page link.
82 * 82 *
83 - * @param tenantId the tenantId 83 + * @param tenantId the tenantId
84 * @param customerId the customerId 84 * @param customerId the customerId
85 - * @param type the type  
86 - * @param pageLink the page link 85 + * @param type the type
  86 + * @param pageLink the page link
87 * @return the list of device objects 87 * @return the list of device objects
88 */ 88 */
89 List<Device> findDevicesByTenantIdAndCustomerIdAndType(UUID tenantId, UUID customerId, String type, TextPageLink pageLink); 89 List<Device> findDevicesByTenantIdAndCustomerIdAndType(UUID tenantId, UUID customerId, String type, TextPageLink pageLink);
@@ -92,9 +92,9 @@ public interface DeviceDao extends Dao<Device> { @@ -92,9 +92,9 @@ public interface DeviceDao extends Dao<Device> {
92 /** 92 /**
93 * Find devices by tenantId, customerId and devices Ids. 93 * Find devices by tenantId, customerId and devices Ids.
94 * 94 *
95 - * @param tenantId the tenantId 95 + * @param tenantId the tenantId
96 * @param customerId the customerId 96 * @param customerId the customerId
97 - * @param deviceIds the device Ids 97 + * @param deviceIds the device Ids
98 * @return the list of device objects 98 * @return the list of device objects
99 */ 99 */
100 ListenableFuture<List<Device>> findDevicesByTenantIdCustomerIdAndIdsAsync(UUID tenantId, UUID customerId, List<UUID> deviceIds); 100 ListenableFuture<List<Device>> findDevicesByTenantIdCustomerIdAndIdsAsync(UUID tenantId, UUID customerId, List<UUID> deviceIds);
@@ -103,7 +103,7 @@ public interface DeviceDao extends Dao<Device> { @@ -103,7 +103,7 @@ public interface DeviceDao extends Dao<Device> {
103 * Find devices by tenantId and device name. 103 * Find devices by tenantId and device name.
104 * 104 *
105 * @param tenantId the tenantId 105 * @param tenantId the tenantId
106 - * @param name the device name 106 + * @param name the device name
107 * @return the optional device object 107 * @return the optional device object
108 */ 108 */
109 Optional<Device> findDeviceByTenantIdAndName(UUID tenantId, String name); 109 Optional<Device> findDeviceByTenantIdAndName(UUID tenantId, String name);
@@ -114,31 +114,4 @@ public interface DeviceDao extends Dao<Device> { @@ -114,31 +114,4 @@ public interface DeviceDao extends Dao<Device> {
114 * @return the list of tenant device type objects 114 * @return the list of tenant device type objects
115 */ 115 */
116 ListenableFuture<List<EntitySubtype>> findTenantDeviceTypesAsync(UUID tenantId); 116 ListenableFuture<List<EntitySubtype>> findTenantDeviceTypesAsync(UUID tenantId);
117 -  
118 - /**  
119 - * Find devices by tenantId, statusQuery and page link.  
120 - *  
121 - * @param tenantId the tenantId  
122 - * @param statusQuery the page link  
123 - * @return the list of device objects  
124 - */  
125 - ListenableFuture<List<Device>> findDevicesByTenantIdAndStatus(UUID tenantId, DeviceStatusQuery statusQuery);  
126 -  
127 - /**  
128 - * Find devices by tenantId, type, statusQuery and page link.  
129 - *  
130 - * @param tenantId the tenantId  
131 - * @param type the type  
132 - * @param statusQuery the page link  
133 - * @return the list of device objects  
134 - */  
135 - ListenableFuture<List<Device>> findDevicesByTenantIdTypeAndStatus(UUID tenantId, String type, DeviceStatusQuery statusQuery);  
136 -  
137 -  
138 - /**  
139 - * Update device last contact and update timestamp async  
140 - *  
141 - * @param device the device object  
142 - */  
143 - void saveDeviceStatus(Device device);  
144 } 117 }
1 -/**  
2 - * Copyright © 2016-2018 The Thingsboard Authors  
3 - *  
4 - * Licensed under the Apache License, Version 2.0 (the "License");  
5 - * you may not use this file except in compliance with the License.  
6 - * You may obtain a copy of the License at  
7 - *  
8 - * http://www.apache.org/licenses/LICENSE-2.0  
9 - *  
10 - * Unless required by applicable law or agreed to in writing, software  
11 - * distributed under the License is distributed on an "AS IS" BASIS,  
12 - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
13 - * See the License for the specific language governing permissions and  
14 - * limitations under the License.  
15 - */  
16 -package org.thingsboard.server.dao.device;  
17 -  
18 -import com.google.common.util.concurrent.ListenableFuture;  
19 -import org.thingsboard.server.common.data.Device;  
20 -import org.thingsboard.server.common.data.device.DeviceStatusQuery;  
21 -  
22 -import java.util.List;  
23 -import java.util.UUID;  
24 -  
25 -public interface DeviceOfflineService {  
26 -  
27 - void online(Device device, boolean isUpdate);  
28 -  
29 - void offline(Device device);  
30 -  
31 - ListenableFuture<List<Device>> findOfflineDevices(UUID tenantId, DeviceStatusQuery.ContactType contactType, long offlineThreshold);  
32 -  
33 - ListenableFuture<List<Device>> findOnlineDevices(UUID tenantId, DeviceStatusQuery.ContactType contactType, long offlineThreshold);  
34 -}  
1 -/**  
2 - * Copyright © 2016-2018 The Thingsboard Authors  
3 - *  
4 - * Licensed under the Apache License, Version 2.0 (the "License");  
5 - * you may not use this file except in compliance with the License.  
6 - * You may obtain a copy of the License at  
7 - *  
8 - * http://www.apache.org/licenses/LICENSE-2.0  
9 - *  
10 - * Unless required by applicable law or agreed to in writing, software  
11 - * distributed under the License is distributed on an "AS IS" BASIS,  
12 - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
13 - * See the License for the specific language governing permissions and  
14 - * limitations under the License.  
15 - */  
16 -package org.thingsboard.server.dao.device;  
17 -  
18 -import com.google.common.util.concurrent.ListenableFuture;  
19 -import org.springframework.beans.factory.annotation.Autowired;  
20 -import org.springframework.stereotype.Service;  
21 -import org.thingsboard.server.common.data.Device;  
22 -import org.thingsboard.server.common.data.device.DeviceStatusQuery;  
23 -  
24 -import java.util.List;  
25 -import java.util.UUID;  
26 -  
27 -import static org.thingsboard.server.common.data.device.DeviceStatusQuery.Status.OFFLINE;  
28 -import static org.thingsboard.server.common.data.device.DeviceStatusQuery.Status.ONLINE;  
29 -  
30 -@Service  
31 -public class DeviceOfflineServiceImpl implements DeviceOfflineService {  
32 -  
33 - @Autowired  
34 - private DeviceDao deviceDao;  
35 -  
36 - @Override  
37 - public void online(Device device, boolean isUpdate) {  
38 - long current = System.currentTimeMillis();  
39 - device.setLastConnectTs(current);  
40 - if(isUpdate) {  
41 - device.setLastUpdateTs(current);  
42 - }  
43 - deviceDao.saveDeviceStatus(device);  
44 - }  
45 -  
46 - @Override  
47 - public void offline(Device device) {  
48 - online(device, false);  
49 - }  
50 -  
51 - @Override  
52 - public ListenableFuture<List<Device>> findOfflineDevices(UUID tenantId, DeviceStatusQuery.ContactType contactType, long offlineThreshold) {  
53 - DeviceStatusQuery statusQuery = new DeviceStatusQuery(OFFLINE, contactType, offlineThreshold);  
54 - return deviceDao.findDevicesByTenantIdAndStatus(tenantId, statusQuery);  
55 - }  
56 -  
57 - @Override  
58 - public ListenableFuture<List<Device>> findOnlineDevices(UUID tenantId, DeviceStatusQuery.ContactType contactType, long offlineThreshold) {  
59 - DeviceStatusQuery statusQuery = new DeviceStatusQuery(ONLINE, contactType, offlineThreshold);  
60 - return deviceDao.findDevicesByTenantIdAndStatus(tenantId, statusQuery);  
61 - }  
62 -}  
@@ -133,8 +133,6 @@ public class ModelConstants { @@ -133,8 +133,6 @@ public class ModelConstants {
133 public static final String DEVICE_NAME_PROPERTY = "name"; 133 public static final String DEVICE_NAME_PROPERTY = "name";
134 public static final String DEVICE_TYPE_PROPERTY = "type"; 134 public static final String DEVICE_TYPE_PROPERTY = "type";
135 public static final String DEVICE_ADDITIONAL_INFO_PROPERTY = ADDITIONAL_INFO_PROPERTY; 135 public static final String DEVICE_ADDITIONAL_INFO_PROPERTY = ADDITIONAL_INFO_PROPERTY;
136 - public static final String DEVICE_LAST_CONNECT_PROPERTY = "last_connect";  
137 - public static final String DEVICE_LAST_UPDATE_PROPERTY = "last_update";  
138 136
139 public static final String DEVICE_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME = "device_by_tenant_and_search_text"; 137 public static final String DEVICE_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME = "device_by_tenant_and_search_text";
140 public static final String DEVICE_BY_TENANT_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME = "device_by_tenant_by_type_and_search_text"; 138 public static final String DEVICE_BY_TENANT_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME = "device_by_tenant_by_type_and_search_text";
@@ -63,12 +63,6 @@ public final class DeviceEntity implements SearchTextEntity<Device> { @@ -63,12 +63,6 @@ public final class DeviceEntity implements SearchTextEntity<Device> {
63 @Column(name = DEVICE_ADDITIONAL_INFO_PROPERTY, codec = JsonCodec.class) 63 @Column(name = DEVICE_ADDITIONAL_INFO_PROPERTY, codec = JsonCodec.class)
64 private JsonNode additionalInfo; 64 private JsonNode additionalInfo;
65 65
66 - @Column(name = DEVICE_LAST_CONNECT_PROPERTY)  
67 - private Long lastConnectTs;  
68 -  
69 - @Column(name = DEVICE_LAST_UPDATE_PROPERTY)  
70 - private Long lastUpdateTs;  
71 -  
72 public DeviceEntity() { 66 public DeviceEntity() {
73 super(); 67 super();
74 } 68 }
@@ -86,8 +80,6 @@ public final class DeviceEntity implements SearchTextEntity<Device> { @@ -86,8 +80,6 @@ public final class DeviceEntity implements SearchTextEntity<Device> {
86 this.name = device.getName(); 80 this.name = device.getName();
87 this.type = device.getType(); 81 this.type = device.getType();
88 this.additionalInfo = device.getAdditionalInfo(); 82 this.additionalInfo = device.getAdditionalInfo();
89 - this.lastConnectTs = device.getLastConnectTs();  
90 - this.lastUpdateTs = device.getLastUpdateTs();  
91 } 83 }
92 84
93 public UUID getId() { 85 public UUID getId() {
@@ -137,23 +129,7 @@ public final class DeviceEntity implements SearchTextEntity<Device> { @@ -137,23 +129,7 @@ public final class DeviceEntity implements SearchTextEntity<Device> {
137 public void setAdditionalInfo(JsonNode additionalInfo) { 129 public void setAdditionalInfo(JsonNode additionalInfo) {
138 this.additionalInfo = additionalInfo; 130 this.additionalInfo = additionalInfo;
139 } 131 }
140 -  
141 - public Long getLastConnectTs() {  
142 - return lastConnectTs;  
143 - }  
144 -  
145 - public void setLastConnectTs(Long lastConnectTs) {  
146 - this.lastConnectTs = lastConnectTs;  
147 - }  
148 -  
149 - public Long getLastUpdateTs() {  
150 - return lastUpdateTs;  
151 - }  
152 -  
153 - public void setLastUpdateTs(Long lastUpdateTs) {  
154 - this.lastUpdateTs = lastUpdateTs;  
155 - }  
156 - 132 +
157 @Override 133 @Override
158 public String getSearchTextSource() { 134 public String getSearchTextSource() {
159 return getName(); 135 return getName();
@@ -181,8 +157,6 @@ public final class DeviceEntity implements SearchTextEntity<Device> { @@ -181,8 +157,6 @@ public final class DeviceEntity implements SearchTextEntity<Device> {
181 device.setName(name); 157 device.setName(name);
182 device.setType(type); 158 device.setType(type);
183 device.setAdditionalInfo(additionalInfo); 159 device.setAdditionalInfo(additionalInfo);
184 - device.setLastConnectTs(lastConnectTs);  
185 - device.setLastUpdateTs(lastUpdateTs);  
186 return device; 160 return device;
187 } 161 }
188 162
@@ -34,9 +34,6 @@ import javax.persistence.Column; @@ -34,9 +34,6 @@ import javax.persistence.Column;
34 import javax.persistence.Entity; 34 import javax.persistence.Entity;
35 import javax.persistence.Table; 35 import javax.persistence.Table;
36 36
37 -import static org.thingsboard.server.dao.model.ModelConstants.DEVICE_LAST_CONNECT_PROPERTY;  
38 -import static org.thingsboard.server.dao.model.ModelConstants.DEVICE_LAST_UPDATE_PROPERTY;  
39 -  
40 @Data 37 @Data
41 @EqualsAndHashCode(callSuper = true) 38 @EqualsAndHashCode(callSuper = true)
42 @Entity 39 @Entity
@@ -63,12 +60,6 @@ public final class DeviceEntity extends BaseSqlEntity<Device> implements SearchT @@ -63,12 +60,6 @@ public final class DeviceEntity extends BaseSqlEntity<Device> implements SearchT
63 @Column(name = ModelConstants.DEVICE_ADDITIONAL_INFO_PROPERTY) 60 @Column(name = ModelConstants.DEVICE_ADDITIONAL_INFO_PROPERTY)
64 private JsonNode additionalInfo; 61 private JsonNode additionalInfo;
65 62
66 - @Column(name = DEVICE_LAST_CONNECT_PROPERTY)  
67 - private Long lastConnectTs;  
68 -  
69 - @Column(name = DEVICE_LAST_UPDATE_PROPERTY)  
70 - private Long lastUpdateTs;  
71 -  
72 public DeviceEntity() { 63 public DeviceEntity() {
73 super(); 64 super();
74 } 65 }
@@ -86,8 +77,6 @@ public final class DeviceEntity extends BaseSqlEntity<Device> implements SearchT @@ -86,8 +77,6 @@ public final class DeviceEntity extends BaseSqlEntity<Device> implements SearchT
86 this.name = device.getName(); 77 this.name = device.getName();
87 this.type = device.getType(); 78 this.type = device.getType();
88 this.additionalInfo = device.getAdditionalInfo(); 79 this.additionalInfo = device.getAdditionalInfo();
89 - this.lastConnectTs = device.getLastConnectTs();  
90 - this.lastUpdateTs = device.getLastUpdateTs();  
91 } 80 }
92 81
93 @Override 82 @Override
@@ -113,8 +102,6 @@ public final class DeviceEntity extends BaseSqlEntity<Device> implements SearchT @@ -113,8 +102,6 @@ public final class DeviceEntity extends BaseSqlEntity<Device> implements SearchT
113 device.setName(name); 102 device.setName(name);
114 device.setType(type); 103 device.setType(type);
115 device.setAdditionalInfo(additionalInfo); 104 device.setAdditionalInfo(additionalInfo);
116 - device.setLastConnectTs(lastConnectTs);  
117 - device.setLastUpdateTs(lastUpdateTs);  
118 return device; 105 return device;
119 } 106 }
120 } 107 }
@@ -79,28 +79,4 @@ public interface DeviceRepository extends CrudRepository<DeviceEntity, String> { @@ -79,28 +79,4 @@ public interface DeviceRepository extends CrudRepository<DeviceEntity, String> {
79 List<DeviceEntity> findDevicesByTenantIdAndCustomerIdAndIdIn(String tenantId, String customerId, List<String> deviceIds); 79 List<DeviceEntity> findDevicesByTenantIdAndCustomerIdAndIdIn(String tenantId, String customerId, List<String> deviceIds);
80 80
81 List<DeviceEntity> findDevicesByTenantIdAndIdIn(String tenantId, List<String> deviceIds); 81 List<DeviceEntity> findDevicesByTenantIdAndIdIn(String tenantId, List<String> deviceIds);
82 -  
83 - @Query("SELECT d FROM DeviceEntity d WHERE d.tenantId = :tenantId AND d.lastConnectTs > :time")  
84 - List<DeviceEntity> findConnectOnlineByTenantId(@Param("tenantId") String tenantId, @Param("time") long time);  
85 -  
86 - @Query("SELECT d FROM DeviceEntity d WHERE d.tenantId = :tenantId AND d.lastConnectTs < :time")  
87 - List<DeviceEntity> findConnectOfflineByTenantId(@Param("tenantId") String tenantId, @Param("time") long time);  
88 -  
89 - @Query("SELECT d FROM DeviceEntity d WHERE d.tenantId = :tenantId AND d.lastUpdateTs > :time")  
90 - List<DeviceEntity> findUpdateOnlineByTenantId(@Param("tenantId") String tenantId, @Param("time") long time);  
91 -  
92 - @Query("SELECT d FROM DeviceEntity d WHERE d.tenantId = :tenantId AND d.lastUpdateTs < :time")  
93 - List<DeviceEntity> findUpdateOfflineByTenantId(@Param("tenantId") String tenantId, @Param("time") long time);  
94 -  
95 - @Query("SELECT d FROM DeviceEntity d WHERE d.tenantId = :tenantId AND d.lastConnectTs > :time AND d.type = :type")  
96 - List<DeviceEntity> findConnectOnlineByTenantIdAndType(@Param("tenantId") String tenantId, @Param("time") long time, @Param("type") String type);  
97 -  
98 - @Query("SELECT d FROM DeviceEntity d WHERE d.tenantId = :tenantId AND d.lastConnectTs < :time AND d.type = :type")  
99 - List<DeviceEntity> findConnectOfflineByTenantIdAndType(@Param("tenantId") String tenantId, @Param("time") long time, @Param("type") String type);  
100 -  
101 - @Query("SELECT d FROM DeviceEntity d WHERE d.tenantId = :tenantId AND d.lastUpdateTs > :time AND d.type = :type")  
102 - List<DeviceEntity> findUpdateOnlineByTenantIdAndType(@Param("tenantId") String tenantId, @Param("time") long time, @Param("type") String type);  
103 -  
104 - @Query("SELECT d FROM DeviceEntity d WHERE d.tenantId = :tenantId AND d.lastUpdateTs < :time AND d.type = :type")  
105 - List<DeviceEntity> findUpdateOfflineByTenantIdAndType(@Param("tenantId") String tenantId, @Param("time") long time, @Param("type") String type);  
106 } 82 }
@@ -15,9 +15,7 @@ @@ -15,9 +15,7 @@
15 */ 15 */
16 package org.thingsboard.server.dao.sql.device; 16 package org.thingsboard.server.dao.sql.device;
17 17
18 -import com.google.common.util.concurrent.Futures;  
19 import com.google.common.util.concurrent.ListenableFuture; 18 import com.google.common.util.concurrent.ListenableFuture;
20 -import lombok.extern.slf4j.Slf4j;  
21 import org.springframework.beans.factory.annotation.Autowired; 19 import org.springframework.beans.factory.annotation.Autowired;
22 import org.springframework.data.domain.PageRequest; 20 import org.springframework.data.domain.PageRequest;
23 import org.springframework.data.repository.CrudRepository; 21 import org.springframework.data.repository.CrudRepository;
@@ -26,7 +24,6 @@ import org.thingsboard.server.common.data.Device; @@ -26,7 +24,6 @@ import org.thingsboard.server.common.data.Device;
26 import org.thingsboard.server.common.data.EntitySubtype; 24 import org.thingsboard.server.common.data.EntitySubtype;
27 import org.thingsboard.server.common.data.EntityType; 25 import org.thingsboard.server.common.data.EntityType;
28 import org.thingsboard.server.common.data.UUIDConverter; 26 import org.thingsboard.server.common.data.UUIDConverter;
29 -import org.thingsboard.server.common.data.device.DeviceStatusQuery;  
30 import org.thingsboard.server.common.data.id.TenantId; 27 import org.thingsboard.server.common.data.id.TenantId;
31 import org.thingsboard.server.common.data.page.TextPageLink; 28 import org.thingsboard.server.common.data.page.TextPageLink;
32 import org.thingsboard.server.dao.DaoUtil; 29 import org.thingsboard.server.dao.DaoUtil;
@@ -46,7 +43,6 @@ import static org.thingsboard.server.dao.model.ModelConstants.NULL_UUID_STR; @@ -46,7 +43,6 @@ import static org.thingsboard.server.dao.model.ModelConstants.NULL_UUID_STR;
46 */ 43 */
47 @Component 44 @Component
48 @SqlDao 45 @SqlDao
49 -@Slf4j  
50 public class JpaDeviceDao extends JpaAbstractSearchTextDao<DeviceEntity, Device> implements DeviceDao { 46 public class JpaDeviceDao extends JpaAbstractSearchTextDao<DeviceEntity, Device> implements DeviceDao {
51 47
52 @Autowired 48 @Autowired
@@ -128,73 +124,6 @@ public class JpaDeviceDao extends JpaAbstractSearchTextDao<DeviceEntity, Device> @@ -128,73 +124,6 @@ public class JpaDeviceDao extends JpaAbstractSearchTextDao<DeviceEntity, Device>
128 return service.submit(() -> convertTenantDeviceTypesToDto(tenantId, deviceRepository.findTenantDeviceTypes(fromTimeUUID(tenantId)))); 124 return service.submit(() -> convertTenantDeviceTypesToDto(tenantId, deviceRepository.findTenantDeviceTypes(fromTimeUUID(tenantId))));
129 } 125 }
130 126
131 - @Override  
132 - public ListenableFuture<List<Device>> findDevicesByTenantIdAndStatus(UUID tenantId, DeviceStatusQuery statusQuery) {  
133 - String strTenantId = fromTimeUUID(tenantId);  
134 - long minTime = System.currentTimeMillis() - statusQuery.getThreshold();  
135 - switch (statusQuery.getStatus()) {  
136 - case OFFLINE: {  
137 - switch (statusQuery.getContactType()) {  
138 - case UPLOAD:  
139 - return service.submit(() -> DaoUtil.convertDataList(deviceRepository.findUpdateOfflineByTenantId(strTenantId, minTime)));  
140 - case CONNECT:  
141 - return service.submit(() -> DaoUtil.convertDataList(deviceRepository.findConnectOfflineByTenantId(strTenantId, minTime)));  
142 - }  
143 - break;  
144 - }  
145 - case ONLINE: {  
146 - switch (statusQuery.getContactType()) {  
147 - case UPLOAD:  
148 - return service.submit(() -> DaoUtil.convertDataList(deviceRepository.findUpdateOnlineByTenantId(strTenantId, minTime)));  
149 - case CONNECT:  
150 - return service.submit(() -> DaoUtil.convertDataList(deviceRepository.findConnectOnlineByTenantId(strTenantId, minTime)));  
151 - }  
152 - break;  
153 - }  
154 - }  
155 -  
156 - log.error("Could not build status query from [{}]", statusQuery);  
157 - throw new IllegalStateException("Could not build status query for device []");  
158 - }  
159 -  
160 - @Override  
161 - public ListenableFuture<List<Device>> findDevicesByTenantIdTypeAndStatus(UUID tenantId, String type, DeviceStatusQuery statusQuery) {  
162 - String strTenantId = fromTimeUUID(tenantId);  
163 - long minTime = System.currentTimeMillis() - statusQuery.getThreshold();  
164 - switch (statusQuery.getStatus()) {  
165 - case OFFLINE: {  
166 - switch (statusQuery.getContactType()) {  
167 - case UPLOAD:  
168 - return service.submit(() -> DaoUtil.convertDataList(deviceRepository.findUpdateOfflineByTenantIdAndType(strTenantId, minTime, type)));  
169 - case CONNECT:  
170 - return service.submit(() -> DaoUtil.convertDataList(deviceRepository.findConnectOfflineByTenantIdAndType(strTenantId, minTime, type)));  
171 - }  
172 - break;  
173 - }  
174 - case ONLINE: {  
175 - switch (statusQuery.getContactType()) {  
176 - case UPLOAD:  
177 - return service.submit(() -> DaoUtil.convertDataList(deviceRepository.findUpdateOnlineByTenantIdAndType(strTenantId, minTime, type)));  
178 - case CONNECT:  
179 - return service.submit(() -> DaoUtil.convertDataList(deviceRepository.findConnectOnlineByTenantIdAndType(strTenantId, minTime, type)));  
180 - }  
181 - break;  
182 - }  
183 - }  
184 -  
185 - log.error("Could not build status query from [{}]", statusQuery);  
186 - throw new IllegalStateException("Could not build status query for device []");  
187 - }  
188 -  
189 - @Override  
190 - public void saveDeviceStatus(Device device) {  
191 - ListenableFuture<Device> future = service.submit(() -> save(device));  
192 - Futures.withFallback(future, t -> {  
193 - log.error("Can't update device status for [{}]", device, t);  
194 - throw new IllegalArgumentException("Can't update device status for {" + device + "}", t);  
195 - });  
196 - }  
197 -  
198 private List<EntitySubtype> convertTenantDeviceTypesToDto(UUID tenantId, List<String> types) { 127 private List<EntitySubtype> convertTenantDeviceTypesToDto(UUID tenantId, List<String> types) {
199 List<EntitySubtype> list = Collections.emptyList(); 128 List<EntitySubtype> list = Collections.emptyList();
200 if (types != null && !types.isEmpty()) { 129 if (types != null && !types.isEmpty()) {
@@ -159,8 +159,6 @@ CREATE TABLE IF NOT EXISTS thingsboard.device ( @@ -159,8 +159,6 @@ CREATE TABLE IF NOT EXISTS thingsboard.device (
159 type text, 159 type text,
160 search_text text, 160 search_text text,
161 additional_info text, 161 additional_info text,
162 - last_connect bigint,  
163 - last_update bigint,  
164 PRIMARY KEY (id, tenant_id, customer_id, type) 162 PRIMARY KEY (id, tenant_id, customer_id, type)
165 ); 163 );
166 164
@@ -118,9 +118,7 @@ CREATE TABLE IF NOT EXISTS device ( @@ -118,9 +118,7 @@ CREATE TABLE IF NOT EXISTS device (
118 type varchar(255), 118 type varchar(255),
119 name varchar(255), 119 name varchar(255),
120 search_text varchar(255), 120 search_text varchar(255),
121 - tenant_id varchar(31),  
122 - last_connect bigint,  
123 - last_update bigint 121 + tenant_id varchar(31)
124 ); 122 );
125 123
126 CREATE TABLE IF NOT EXISTS device_credentials ( 124 CREATE TABLE IF NOT EXISTS device_credentials (
@@ -59,6 +59,9 @@ public class TbMsgToEmailNodeTest { @@ -59,6 +59,9 @@ public class TbMsgToEmailNodeTest {
59 initWithScript(); 59 initWithScript();
60 metaData.putValue("username", "oreo"); 60 metaData.putValue("username", "oreo");
61 metaData.putValue("userEmail", "user@email.io"); 61 metaData.putValue("userEmail", "user@email.io");
  62 + metaData.putValue("name", "temp");
  63 + metaData.putValue("passed", "5");
  64 + metaData.putValue("count", "100");
62 TbMsg msg = new TbMsg(UUIDs.timeBased(), "USER", originator, metaData, rawJson, ruleChainId, ruleNodeId, 0L); 65 TbMsg msg = new TbMsg(UUIDs.timeBased(), "USER", originator, metaData, rawJson, ruleChainId, ruleNodeId, 0L);
63 66
64 emailNode.onMsg(ctx, msg); 67 emailNode.onMsg(ctx, msg);
@@ -91,9 +94,9 @@ public class TbMsgToEmailNodeTest { @@ -91,9 +94,9 @@ public class TbMsgToEmailNodeTest {
91 try { 94 try {
92 TbMsgToEmailNodeConfiguration config = new TbMsgToEmailNodeConfiguration(); 95 TbMsgToEmailNodeConfiguration config = new TbMsgToEmailNodeConfiguration();
93 config.setFromTemplate("test@mail.org"); 96 config.setFromTemplate("test@mail.org");
94 - config.setToTemplate("$metadata.userEmail");  
95 - config.setSubjectTemplate("Hi $metadata.username there");  
96 - config.setBodyTemplate("$msg.name is to high. Current $msg.passed and $msg.complex.count"); 97 + config.setToTemplate("${userEmail}");
  98 + config.setSubjectTemplate("Hi ${username} there");
  99 + config.setBodyTemplate("${name} is to high. Current ${passed} and ${count}");
97 ObjectMapper mapper = new ObjectMapper(); 100 ObjectMapper mapper = new ObjectMapper();
98 TbNodeConfiguration nodeConfiguration = new TbNodeConfiguration(mapper.valueToTree(config)); 101 TbNodeConfiguration nodeConfiguration = new TbNodeConfiguration(mapper.valueToTree(config));
99 102
@@ -35,7 +35,6 @@ import org.thingsboard.server.common.transport.SessionMsgProcessor; @@ -35,7 +35,6 @@ import org.thingsboard.server.common.transport.SessionMsgProcessor;
35 import org.thingsboard.server.common.transport.adaptor.AdaptorException; 35 import org.thingsboard.server.common.transport.adaptor.AdaptorException;
36 import org.thingsboard.server.common.transport.auth.DeviceAuthService; 36 import org.thingsboard.server.common.transport.auth.DeviceAuthService;
37 import org.thingsboard.server.common.transport.quota.QuotaService; 37 import org.thingsboard.server.common.transport.quota.QuotaService;
38 -import org.thingsboard.server.dao.device.DeviceOfflineService;  
39 import org.thingsboard.server.transport.coap.adaptors.CoapTransportAdaptor; 38 import org.thingsboard.server.transport.coap.adaptors.CoapTransportAdaptor;
40 import org.thingsboard.server.transport.coap.session.CoapExchangeObserverProxy; 39 import org.thingsboard.server.transport.coap.session.CoapExchangeObserverProxy;
41 import org.thingsboard.server.transport.coap.session.CoapSessionCtx; 40 import org.thingsboard.server.transport.coap.session.CoapSessionCtx;
@@ -54,17 +53,15 @@ public class CoapTransportResource extends CoapResource { @@ -54,17 +53,15 @@ public class CoapTransportResource extends CoapResource {
54 private final SessionMsgProcessor processor; 53 private final SessionMsgProcessor processor;
55 private final DeviceAuthService authService; 54 private final DeviceAuthService authService;
56 private final QuotaService quotaService; 55 private final QuotaService quotaService;
57 - private final DeviceOfflineService offlineService;  
58 private final Field observerField; 56 private final Field observerField;
59 private final long timeout; 57 private final long timeout;
60 58
61 public CoapTransportResource(SessionMsgProcessor processor, DeviceAuthService authService, CoapTransportAdaptor adaptor, String name, 59 public CoapTransportResource(SessionMsgProcessor processor, DeviceAuthService authService, CoapTransportAdaptor adaptor, String name,
62 - long timeout, QuotaService quotaService, DeviceOfflineService offlineService) { 60 + long timeout, QuotaService quotaService) {
63 super(name); 61 super(name);
64 this.processor = processor; 62 this.processor = processor;
65 this.authService = authService; 63 this.authService = authService;
66 this.quotaService = quotaService; 64 this.quotaService = quotaService;
67 - this.offlineService = offlineService;  
68 this.adaptor = adaptor; 65 this.adaptor = adaptor;
69 this.timeout = timeout; 66 this.timeout = timeout;
70 // This is important to turn off existing observable logic in 67 // This is important to turn off existing observable logic in
@@ -171,7 +168,6 @@ public class CoapTransportResource extends CoapResource { @@ -171,7 +168,6 @@ public class CoapTransportResource extends CoapResource {
171 case TO_SERVER_RPC_REQUEST: 168 case TO_SERVER_RPC_REQUEST:
172 ctx.setSessionType(SessionType.SYNC); 169 ctx.setSessionType(SessionType.SYNC);
173 msg = adaptor.convertToActorMsg(ctx, type, request); 170 msg = adaptor.convertToActorMsg(ctx, type, request);
174 - offlineService.online(ctx.getDevice(), true);  
175 break; 171 break;
176 case SUBSCRIBE_ATTRIBUTES_REQUEST: 172 case SUBSCRIBE_ATTRIBUTES_REQUEST:
177 case SUBSCRIBE_RPC_COMMANDS_REQUEST: 173 case SUBSCRIBE_RPC_COMMANDS_REQUEST:
@@ -179,13 +175,11 @@ public class CoapTransportResource extends CoapResource { @@ -179,13 +175,11 @@ public class CoapTransportResource extends CoapResource {
179 advanced.setObserver(new CoapExchangeObserverProxy(systemObserver, ctx)); 175 advanced.setObserver(new CoapExchangeObserverProxy(systemObserver, ctx));
180 ctx.setSessionType(SessionType.ASYNC); 176 ctx.setSessionType(SessionType.ASYNC);
181 msg = adaptor.convertToActorMsg(ctx, type, request); 177 msg = adaptor.convertToActorMsg(ctx, type, request);
182 - offlineService.online(ctx.getDevice(), false);  
183 break; 178 break;
184 case UNSUBSCRIBE_ATTRIBUTES_REQUEST: 179 case UNSUBSCRIBE_ATTRIBUTES_REQUEST:
185 case UNSUBSCRIBE_RPC_COMMANDS_REQUEST: 180 case UNSUBSCRIBE_RPC_COMMANDS_REQUEST:
186 ctx.setSessionType(SessionType.ASYNC); 181 ctx.setSessionType(SessionType.ASYNC);
187 msg = adaptor.convertToActorMsg(ctx, type, request); 182 msg = adaptor.convertToActorMsg(ctx, type, request);
188 - offlineService.online(ctx.getDevice(), false);  
189 break; 183 break;
190 default: 184 default:
191 log.trace("[{}] Unsupported msg type: {}", ctx.getSessionId(), type); 185 log.trace("[{}] Unsupported msg type: {}", ctx.getSessionId(), type);
@@ -27,7 +27,6 @@ import org.springframework.stereotype.Service; @@ -27,7 +27,6 @@ import org.springframework.stereotype.Service;
27 import org.thingsboard.server.common.transport.SessionMsgProcessor; 27 import org.thingsboard.server.common.transport.SessionMsgProcessor;
28 import org.thingsboard.server.common.transport.auth.DeviceAuthService; 28 import org.thingsboard.server.common.transport.auth.DeviceAuthService;
29 import org.thingsboard.server.common.transport.quota.QuotaService; 29 import org.thingsboard.server.common.transport.quota.QuotaService;
30 -import org.thingsboard.server.dao.device.DeviceOfflineService;  
31 import org.thingsboard.server.transport.coap.adaptors.CoapTransportAdaptor; 30 import org.thingsboard.server.transport.coap.adaptors.CoapTransportAdaptor;
32 31
33 import javax.annotation.PostConstruct; 32 import javax.annotation.PostConstruct;
@@ -58,9 +57,6 @@ public class CoapTransportService { @@ -58,9 +57,6 @@ public class CoapTransportService {
58 @Autowired(required = false) 57 @Autowired(required = false)
59 private QuotaService quotaService; 58 private QuotaService quotaService;
60 59
61 - @Autowired(required = false)  
62 - private DeviceOfflineService offlineService;  
63 -  
64 60
65 @Value("${coap.bind_address}") 61 @Value("${coap.bind_address}")
66 private String host; 62 private String host;
@@ -90,7 +86,7 @@ public class CoapTransportService { @@ -90,7 +86,7 @@ public class CoapTransportService {
90 86
91 private void createResources() { 87 private void createResources() {
92 CoapResource api = new CoapResource(API); 88 CoapResource api = new CoapResource(API);
93 - api.add(new CoapTransportResource(processor, authService, adaptor, V1, timeout, quotaService, offlineService)); 89 + api.add(new CoapTransportResource(processor, authService, adaptor, V1, timeout, quotaService));
94 server.add(api); 90 server.add(api);
95 } 91 }
96 92
@@ -15,7 +15,6 @@ @@ -15,7 +15,6 @@
15 */ 15 */
16 package org.thingsboard.server.transport.coap; 16 package org.thingsboard.server.transport.coap;
17 17
18 -import com.google.common.util.concurrent.ListenableFuture;  
19 import lombok.extern.slf4j.Slf4j; 18 import lombok.extern.slf4j.Slf4j;
20 import org.eclipse.californium.core.CoapClient; 19 import org.eclipse.californium.core.CoapClient;
21 import org.eclipse.californium.core.CoapResponse; 20 import org.eclipse.californium.core.CoapResponse;
@@ -32,7 +31,6 @@ import org.springframework.test.annotation.DirtiesContext; @@ -32,7 +31,6 @@ import org.springframework.test.annotation.DirtiesContext;
32 import org.springframework.test.annotation.DirtiesContext.ClassMode; 31 import org.springframework.test.annotation.DirtiesContext.ClassMode;
33 import org.springframework.test.context.junit4.SpringRunner; 32 import org.springframework.test.context.junit4.SpringRunner;
34 import org.thingsboard.server.common.data.Device; 33 import org.thingsboard.server.common.data.Device;
35 -import org.thingsboard.server.common.data.device.DeviceStatusQuery;  
36 import org.thingsboard.server.common.data.id.CustomerId; 34 import org.thingsboard.server.common.data.id.CustomerId;
37 import org.thingsboard.server.common.data.id.DeviceId; 35 import org.thingsboard.server.common.data.id.DeviceId;
38 import org.thingsboard.server.common.data.id.TenantId; 36 import org.thingsboard.server.common.data.id.TenantId;
@@ -53,7 +51,6 @@ import org.thingsboard.server.common.transport.SessionMsgProcessor; @@ -53,7 +51,6 @@ import org.thingsboard.server.common.transport.SessionMsgProcessor;
53 import org.thingsboard.server.common.transport.auth.DeviceAuthResult; 51 import org.thingsboard.server.common.transport.auth.DeviceAuthResult;
54 import org.thingsboard.server.common.transport.auth.DeviceAuthService; 52 import org.thingsboard.server.common.transport.auth.DeviceAuthService;
55 import org.thingsboard.server.common.transport.quota.QuotaService; 53 import org.thingsboard.server.common.transport.quota.QuotaService;
56 -import org.thingsboard.server.dao.device.DeviceOfflineService;  
57 54
58 import java.util.ArrayList; 55 import java.util.ArrayList;
59 import java.util.List; 56 import java.util.List;
@@ -140,31 +137,6 @@ public class CoapServerTest { @@ -140,31 +137,6 @@ public class CoapServerTest {
140 public static QuotaService quotaService() { 137 public static QuotaService quotaService() {
141 return key -> false; 138 return key -> false;
142 } 139 }
143 -  
144 - @Bean  
145 - public static DeviceOfflineService offlineService() {  
146 - return new DeviceOfflineService() {  
147 - @Override  
148 - public void online(Device device, boolean isUpdate) {  
149 -  
150 - }  
151 -  
152 - @Override  
153 - public void offline(Device device) {  
154 -  
155 - }  
156 -  
157 - @Override  
158 - public ListenableFuture<List<Device>> findOfflineDevices(UUID tenantId, DeviceStatusQuery.ContactType contactType, long offlineThreshold) {  
159 - return null;  
160 - }  
161 -  
162 - @Override  
163 - public ListenableFuture<List<Device>> findOnlineDevices(UUID tenantId, DeviceStatusQuery.ContactType contactType, long offlineThreshold) {  
164 - return null;  
165 - }  
166 - };  
167 - }  
168 } 140 }
169 141
170 @Autowired 142 @Autowired
@@ -26,7 +26,6 @@ import org.springframework.http.ResponseEntity; @@ -26,7 +26,6 @@ import org.springframework.http.ResponseEntity;
26 import org.springframework.util.StringUtils; 26 import org.springframework.util.StringUtils;
27 import org.springframework.web.bind.annotation.*; 27 import org.springframework.web.bind.annotation.*;
28 import org.springframework.web.context.request.async.DeferredResult; 28 import org.springframework.web.context.request.async.DeferredResult;
29 -import org.thingsboard.server.common.data.Device;  
30 import org.thingsboard.server.common.data.security.DeviceTokenCredentials; 29 import org.thingsboard.server.common.data.security.DeviceTokenCredentials;
31 import org.thingsboard.server.common.msg.core.*; 30 import org.thingsboard.server.common.msg.core.*;
32 import org.thingsboard.server.common.msg.session.AdaptorToSessionActorMsg; 31 import org.thingsboard.server.common.msg.session.AdaptorToSessionActorMsg;
@@ -37,7 +36,6 @@ import org.thingsboard.server.common.transport.SessionMsgProcessor; @@ -37,7 +36,6 @@ import org.thingsboard.server.common.transport.SessionMsgProcessor;
37 import org.thingsboard.server.common.transport.adaptor.JsonConverter; 36 import org.thingsboard.server.common.transport.adaptor.JsonConverter;
38 import org.thingsboard.server.common.transport.auth.DeviceAuthService; 37 import org.thingsboard.server.common.transport.auth.DeviceAuthService;
39 import org.thingsboard.server.common.transport.quota.QuotaService; 38 import org.thingsboard.server.common.transport.quota.QuotaService;
40 -import org.thingsboard.server.dao.device.DeviceOfflineService;  
41 import org.thingsboard.server.transport.http.session.HttpSessionCtx; 39 import org.thingsboard.server.transport.http.session.HttpSessionCtx;
42 40
43 import javax.servlet.http.HttpServletRequest; 41 import javax.servlet.http.HttpServletRequest;
@@ -65,9 +63,6 @@ public class DeviceApiController { @@ -65,9 +63,6 @@ public class DeviceApiController {
65 @Autowired(required = false) 63 @Autowired(required = false)
66 private QuotaService quotaService; 64 private QuotaService quotaService;
67 65
68 - @Autowired(required = false)  
69 - private DeviceOfflineService offlineService;  
70 -  
71 @RequestMapping(value = "/{deviceToken}/attributes", method = RequestMethod.GET, produces = "application/json") 66 @RequestMapping(value = "/{deviceToken}/attributes", method = RequestMethod.GET, produces = "application/json")
72 public DeferredResult<ResponseEntity> getDeviceAttributes(@PathVariable("deviceToken") String deviceToken, 67 public DeferredResult<ResponseEntity> getDeviceAttributes(@PathVariable("deviceToken") String deviceToken,
73 @RequestParam(value = "clientKeys", required = false, defaultValue = "") String clientKeys, 68 @RequestParam(value = "clientKeys", required = false, defaultValue = "") String clientKeys,
@@ -87,7 +82,7 @@ public class DeviceApiController { @@ -87,7 +82,7 @@ public class DeviceApiController {
87 Set<String> sharedKeySet = !StringUtils.isEmpty(sharedKeys) ? new HashSet<>(Arrays.asList(sharedKeys.split(","))) : null; 82 Set<String> sharedKeySet = !StringUtils.isEmpty(sharedKeys) ? new HashSet<>(Arrays.asList(sharedKeys.split(","))) : null;
88 request = new BasicGetAttributesRequest(0, clientKeySet, sharedKeySet); 83 request = new BasicGetAttributesRequest(0, clientKeySet, sharedKeySet);
89 } 84 }
90 - process(ctx, request, false); 85 + process(ctx, request);
91 } else { 86 } else {
92 responseWriter.setResult(new ResponseEntity<>(HttpStatus.UNAUTHORIZED)); 87 responseWriter.setResult(new ResponseEntity<>(HttpStatus.UNAUTHORIZED));
93 } 88 }
@@ -105,7 +100,7 @@ public class DeviceApiController { @@ -105,7 +100,7 @@ public class DeviceApiController {
105 HttpSessionCtx ctx = getHttpSessionCtx(responseWriter); 100 HttpSessionCtx ctx = getHttpSessionCtx(responseWriter);
106 if (ctx.login(new DeviceTokenCredentials(deviceToken))) { 101 if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
107 try { 102 try {
108 - process(ctx, JsonConverter.convertToAttributes(new JsonParser().parse(json)), true); 103 + process(ctx, JsonConverter.convertToAttributes(new JsonParser().parse(json)));
109 } catch (IllegalStateException | JsonSyntaxException ex) { 104 } catch (IllegalStateException | JsonSyntaxException ex) {
110 responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST)); 105 responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
111 } 106 }
@@ -125,7 +120,7 @@ public class DeviceApiController { @@ -125,7 +120,7 @@ public class DeviceApiController {
125 HttpSessionCtx ctx = getHttpSessionCtx(responseWriter); 120 HttpSessionCtx ctx = getHttpSessionCtx(responseWriter);
126 if (ctx.login(new DeviceTokenCredentials(deviceToken))) { 121 if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
127 try { 122 try {
128 - process(ctx, JsonConverter.convertToTelemetry(new JsonParser().parse(json)), true); 123 + process(ctx, JsonConverter.convertToTelemetry(new JsonParser().parse(json)));
129 } catch (IllegalStateException | JsonSyntaxException ex) { 124 } catch (IllegalStateException | JsonSyntaxException ex) {
130 responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST)); 125 responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
131 } 126 }
@@ -155,7 +150,7 @@ public class DeviceApiController { @@ -155,7 +150,7 @@ public class DeviceApiController {
155 if (ctx.login(new DeviceTokenCredentials(deviceToken))) { 150 if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
156 try { 151 try {
157 JsonObject response = new JsonParser().parse(json).getAsJsonObject(); 152 JsonObject response = new JsonParser().parse(json).getAsJsonObject();
158 - process(ctx, new ToDeviceRpcResponseMsg(requestId, response.toString()), true); 153 + process(ctx, new ToDeviceRpcResponseMsg(requestId, response.toString()));
159 } catch (IllegalStateException | JsonSyntaxException ex) { 154 } catch (IllegalStateException | JsonSyntaxException ex) {
160 responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST)); 155 responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
161 } 156 }
@@ -178,7 +173,7 @@ public class DeviceApiController { @@ -178,7 +173,7 @@ public class DeviceApiController {
178 JsonObject request = new JsonParser().parse(json).getAsJsonObject(); 173 JsonObject request = new JsonParser().parse(json).getAsJsonObject();
179 process(ctx, new ToServerRpcRequestMsg(0, 174 process(ctx, new ToServerRpcRequestMsg(0,
180 request.get("method").getAsString(), 175 request.get("method").getAsString(),
181 - request.get("params").toString()), true); 176 + request.get("params").toString()));
182 } catch (IllegalStateException | JsonSyntaxException ex) { 177 } catch (IllegalStateException | JsonSyntaxException ex) {
183 responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST)); 178 responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
184 } 179 }
@@ -204,7 +199,7 @@ public class DeviceApiController { @@ -204,7 +199,7 @@ public class DeviceApiController {
204 HttpSessionCtx ctx = getHttpSessionCtx(responseWriter, timeout); 199 HttpSessionCtx ctx = getHttpSessionCtx(responseWriter, timeout);
205 if (ctx.login(new DeviceTokenCredentials(deviceToken))) { 200 if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
206 try { 201 try {
207 - process(ctx, msg, false); 202 + process(ctx, msg);
208 } catch (IllegalStateException | JsonSyntaxException ex) { 203 } catch (IllegalStateException | JsonSyntaxException ex) {
209 responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST)); 204 responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
210 } 205 }
@@ -222,10 +217,9 @@ public class DeviceApiController { @@ -222,10 +217,9 @@ public class DeviceApiController {
222 return new HttpSessionCtx(processor, authService, responseWriter, timeout != 0 ? timeout : defaultTimeout); 217 return new HttpSessionCtx(processor, authService, responseWriter, timeout != 0 ? timeout : defaultTimeout);
223 } 218 }
224 219
225 - private void process(HttpSessionCtx ctx, FromDeviceMsg request, boolean isUpdate) { 220 + private void process(HttpSessionCtx ctx, FromDeviceMsg request) {
226 AdaptorToSessionActorMsg msg = new BasicAdaptorToSessionActorMsg(ctx, request); 221 AdaptorToSessionActorMsg msg = new BasicAdaptorToSessionActorMsg(ctx, request);
227 processor.process(new BasicToDeviceActorSessionMsg(ctx.getDevice(), msg)); 222 processor.process(new BasicToDeviceActorSessionMsg(ctx.getDevice(), msg));
228 - offlineService.online(ctx.getDevice(), isUpdate);  
229 } 223 }
230 224
231 private boolean quotaExceeded(HttpServletRequest request, DeferredResult<ResponseEntity> responseWriter) { 225 private boolean quotaExceeded(HttpServletRequest request, DeferredResult<ResponseEntity> responseWriter) {
@@ -37,7 +37,6 @@ import org.thingsboard.server.common.transport.adaptor.AdaptorException; @@ -37,7 +37,6 @@ import org.thingsboard.server.common.transport.adaptor.AdaptorException;
37 import org.thingsboard.server.common.transport.auth.DeviceAuthService; 37 import org.thingsboard.server.common.transport.auth.DeviceAuthService;
38 import org.thingsboard.server.common.transport.quota.QuotaService; 38 import org.thingsboard.server.common.transport.quota.QuotaService;
39 import org.thingsboard.server.dao.EncryptionUtil; 39 import org.thingsboard.server.dao.EncryptionUtil;
40 -import org.thingsboard.server.dao.device.DeviceOfflineService;  
41 import org.thingsboard.server.dao.device.DeviceService; 40 import org.thingsboard.server.dao.device.DeviceService;
42 import org.thingsboard.server.dao.relation.RelationService; 41 import org.thingsboard.server.dao.relation.RelationService;
43 import org.thingsboard.server.transport.mqtt.adaptors.MqttTransportAdaptor; 42 import org.thingsboard.server.transport.mqtt.adaptors.MqttTransportAdaptor;
@@ -73,14 +72,13 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @@ -73,14 +72,13 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
73 private final DeviceAuthService authService; 72 private final DeviceAuthService authService;
74 private final RelationService relationService; 73 private final RelationService relationService;
75 private final QuotaService quotaService; 74 private final QuotaService quotaService;
76 - private final DeviceOfflineService offlineService;  
77 private final SslHandler sslHandler; 75 private final SslHandler sslHandler;
78 private volatile boolean connected; 76 private volatile boolean connected;
79 private volatile InetSocketAddress address; 77 private volatile InetSocketAddress address;
80 private volatile GatewaySessionCtx gatewaySessionCtx; 78 private volatile GatewaySessionCtx gatewaySessionCtx;
81 79
82 public MqttTransportHandler(SessionMsgProcessor processor, DeviceService deviceService, DeviceAuthService authService, RelationService relationService, 80 public MqttTransportHandler(SessionMsgProcessor processor, DeviceService deviceService, DeviceAuthService authService, RelationService relationService,
83 - MqttTransportAdaptor adaptor, SslHandler sslHandler, QuotaService quotaService, DeviceOfflineService offlineService) { 81 + MqttTransportAdaptor adaptor, SslHandler sslHandler, QuotaService quotaService) {
84 this.processor = processor; 82 this.processor = processor;
85 this.deviceService = deviceService; 83 this.deviceService = deviceService;
86 this.relationService = relationService; 84 this.relationService = relationService;
@@ -90,7 +88,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @@ -90,7 +88,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
90 this.sessionId = deviceSessionCtx.getSessionId().toUidStr(); 88 this.sessionId = deviceSessionCtx.getSessionId().toUidStr();
91 this.sslHandler = sslHandler; 89 this.sslHandler = sslHandler;
92 this.quotaService = quotaService; 90 this.quotaService = quotaService;
93 - this.offlineService = offlineService;  
94 } 91 }
95 92
96 @Override 93 @Override
@@ -132,13 +129,11 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @@ -132,13 +129,11 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
132 case PINGREQ: 129 case PINGREQ:
133 if (checkConnected(ctx)) { 130 if (checkConnected(ctx)) {
134 ctx.writeAndFlush(new MqttMessage(new MqttFixedHeader(PINGRESP, false, AT_MOST_ONCE, false, 0))); 131 ctx.writeAndFlush(new MqttMessage(new MqttFixedHeader(PINGRESP, false, AT_MOST_ONCE, false, 0)));
135 - offlineService.online(deviceSessionCtx.getDevice(), false);  
136 } 132 }
137 break; 133 break;
138 case DISCONNECT: 134 case DISCONNECT:
139 if (checkConnected(ctx)) { 135 if (checkConnected(ctx)) {
140 processDisconnect(ctx); 136 processDisconnect(ctx);
141 - offlineService.offline(deviceSessionCtx.getDevice());  
142 } 137 }
143 break; 138 break;
144 default: 139 default:
@@ -190,28 +185,23 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @@ -190,28 +185,23 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
190 try { 185 try {
191 if (topicName.equals(DEVICE_TELEMETRY_TOPIC)) { 186 if (topicName.equals(DEVICE_TELEMETRY_TOPIC)) {
192 msg = adaptor.convertToActorMsg(deviceSessionCtx, POST_TELEMETRY_REQUEST, mqttMsg); 187 msg = adaptor.convertToActorMsg(deviceSessionCtx, POST_TELEMETRY_REQUEST, mqttMsg);
193 - offlineService.online(deviceSessionCtx.getDevice(), true);  
194 } else if (topicName.equals(DEVICE_ATTRIBUTES_TOPIC)) { 188 } else if (topicName.equals(DEVICE_ATTRIBUTES_TOPIC)) {
195 msg = adaptor.convertToActorMsg(deviceSessionCtx, POST_ATTRIBUTES_REQUEST, mqttMsg); 189 msg = adaptor.convertToActorMsg(deviceSessionCtx, POST_ATTRIBUTES_REQUEST, mqttMsg);
196 - offlineService.online(deviceSessionCtx.getDevice(), true);  
197 } else if (topicName.startsWith(DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX)) { 190 } else if (topicName.startsWith(DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX)) {
198 msg = adaptor.convertToActorMsg(deviceSessionCtx, GET_ATTRIBUTES_REQUEST, mqttMsg); 191 msg = adaptor.convertToActorMsg(deviceSessionCtx, GET_ATTRIBUTES_REQUEST, mqttMsg);
199 if (msgId >= 0) { 192 if (msgId >= 0) {
200 ctx.writeAndFlush(createMqttPubAckMsg(msgId)); 193 ctx.writeAndFlush(createMqttPubAckMsg(msgId));
201 } 194 }
202 - offlineService.online(deviceSessionCtx.getDevice(), false);  
203 } else if (topicName.startsWith(DEVICE_RPC_RESPONSE_TOPIC)) { 195 } else if (topicName.startsWith(DEVICE_RPC_RESPONSE_TOPIC)) {
204 msg = adaptor.convertToActorMsg(deviceSessionCtx, TO_DEVICE_RPC_RESPONSE, mqttMsg); 196 msg = adaptor.convertToActorMsg(deviceSessionCtx, TO_DEVICE_RPC_RESPONSE, mqttMsg);
205 if (msgId >= 0) { 197 if (msgId >= 0) {
206 ctx.writeAndFlush(createMqttPubAckMsg(msgId)); 198 ctx.writeAndFlush(createMqttPubAckMsg(msgId));
207 } 199 }
208 - offlineService.online(deviceSessionCtx.getDevice(), true);  
209 } else if (topicName.startsWith(DEVICE_RPC_REQUESTS_TOPIC)) { 200 } else if (topicName.startsWith(DEVICE_RPC_REQUESTS_TOPIC)) {
210 msg = adaptor.convertToActorMsg(deviceSessionCtx, TO_SERVER_RPC_REQUEST, mqttMsg); 201 msg = adaptor.convertToActorMsg(deviceSessionCtx, TO_SERVER_RPC_REQUEST, mqttMsg);
211 if (msgId >= 0) { 202 if (msgId >= 0) {
212 ctx.writeAndFlush(createMqttPubAckMsg(msgId)); 203 ctx.writeAndFlush(createMqttPubAckMsg(msgId));
213 } 204 }
214 - offlineService.online(deviceSessionCtx.getDevice(), true);  
215 } 205 }
216 } catch (AdaptorException e) { 206 } catch (AdaptorException e) {
217 log.warn("[{}] Failed to process publish msg [{}][{}]", sessionId, topicName, msgId, e); 207 log.warn("[{}] Failed to process publish msg [{}][{}]", sessionId, topicName, msgId, e);
@@ -260,7 +250,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @@ -260,7 +250,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
260 } 250 }
261 } 251 }
262 ctx.writeAndFlush(createSubAckMessage(mqttMsg.variableHeader().messageId(), grantedQoSList)); 252 ctx.writeAndFlush(createSubAckMessage(mqttMsg.variableHeader().messageId(), grantedQoSList));
263 - offlineService.online(deviceSessionCtx.getDevice(), false);  
264 } 253 }
265 254
266 private void processUnsubscribe(ChannelHandlerContext ctx, MqttUnsubscribeMessage mqttMsg) { 255 private void processUnsubscribe(ChannelHandlerContext ctx, MqttUnsubscribeMessage mqttMsg) {
@@ -284,7 +273,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @@ -284,7 +273,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
284 } 273 }
285 } 274 }
286 ctx.writeAndFlush(createUnSubAckMessage(mqttMsg.variableHeader().messageId())); 275 ctx.writeAndFlush(createUnSubAckMessage(mqttMsg.variableHeader().messageId()));
287 - offlineService.online(deviceSessionCtx.getDevice(), false);  
288 } 276 }
289 277
290 private MqttMessage createUnSubAckMessage(int msgId) { 278 private MqttMessage createUnSubAckMessage(int msgId) {
@@ -316,7 +304,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @@ -316,7 +304,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
316 ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_ACCEPTED)); 304 ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_ACCEPTED));
317 connected = true; 305 connected = true;
318 checkGatewaySession(); 306 checkGatewaySession();
319 - offlineService.online(deviceSessionCtx.getDevice(), false);  
320 } 307 }
321 } 308 }
322 309
@@ -328,7 +315,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @@ -328,7 +315,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
328 ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_ACCEPTED)); 315 ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_ACCEPTED));
329 connected = true; 316 connected = true;
330 checkGatewaySession(); 317 checkGatewaySession();
331 - offlineService.online(deviceSessionCtx.getDevice(), false);  
332 } else { 318 } else {
333 ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_REFUSED_NOT_AUTHORIZED)); 319 ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_REFUSED_NOT_AUTHORIZED));
334 ctx.close(); 320 ctx.close();
@@ -379,9 +365,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @@ -379,9 +365,6 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
379 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 365 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
380 log.error("[{}] Unexpected Exception", sessionId, cause); 366 log.error("[{}] Unexpected Exception", sessionId, cause);
381 ctx.close(); 367 ctx.close();
382 - if(deviceSessionCtx.getDevice() != null) {  
383 - offlineService.offline(deviceSessionCtx.getDevice());  
384 - }  
385 } 368 }
386 369
387 private static MqttSubAckMessage createSubAckMessage(Integer msgId, List<Integer> grantedQoSList) { 370 private static MqttSubAckMessage createSubAckMessage(Integer msgId, List<Integer> grantedQoSList) {
@@ -420,8 +403,7 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @@ -420,8 +403,7 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
420 if (infoNode != null) { 403 if (infoNode != null) {
421 JsonNode gatewayNode = infoNode.get("gateway"); 404 JsonNode gatewayNode = infoNode.get("gateway");
422 if (gatewayNode != null && gatewayNode.asBoolean()) { 405 if (gatewayNode != null && gatewayNode.asBoolean()) {
423 - gatewaySessionCtx = new GatewaySessionCtx(processor, deviceService, authService,  
424 - relationService, deviceSessionCtx, offlineService); 406 + gatewaySessionCtx = new GatewaySessionCtx(processor, deviceService, authService, relationService, deviceSessionCtx);
425 } 407 }
426 } 408 }
427 } 409 }
@@ -429,8 +411,5 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement @@ -429,8 +411,5 @@ public class MqttTransportHandler extends ChannelInboundHandlerAdapter implement
429 @Override 411 @Override
430 public void operationComplete(Future<? super Void> future) throws Exception { 412 public void operationComplete(Future<? super Void> future) throws Exception {
431 processor.process(SessionCloseMsg.onError(deviceSessionCtx.getSessionId())); 413 processor.process(SessionCloseMsg.onError(deviceSessionCtx.getSessionId()));
432 - if(deviceSessionCtx.getDevice() != null) {  
433 - offlineService.offline(deviceSessionCtx.getDevice());  
434 - }  
435 } 414 }
436 } 415 }
@@ -24,7 +24,6 @@ import io.netty.handler.ssl.SslHandler; @@ -24,7 +24,6 @@ import io.netty.handler.ssl.SslHandler;
24 import org.thingsboard.server.common.transport.SessionMsgProcessor; 24 import org.thingsboard.server.common.transport.SessionMsgProcessor;
25 import org.thingsboard.server.common.transport.auth.DeviceAuthService; 25 import org.thingsboard.server.common.transport.auth.DeviceAuthService;
26 import org.thingsboard.server.common.transport.quota.QuotaService; 26 import org.thingsboard.server.common.transport.quota.QuotaService;
27 -import org.thingsboard.server.dao.device.DeviceOfflineService;  
28 import org.thingsboard.server.dao.device.DeviceService; 27 import org.thingsboard.server.dao.device.DeviceService;
29 import org.thingsboard.server.dao.relation.RelationService; 28 import org.thingsboard.server.dao.relation.RelationService;
30 import org.thingsboard.server.transport.mqtt.adaptors.MqttTransportAdaptor; 29 import org.thingsboard.server.transport.mqtt.adaptors.MqttTransportAdaptor;
@@ -43,11 +42,10 @@ public class MqttTransportServerInitializer extends ChannelInitializer<SocketCha @@ -43,11 +42,10 @@ public class MqttTransportServerInitializer extends ChannelInitializer<SocketCha
43 private final MqttTransportAdaptor adaptor; 42 private final MqttTransportAdaptor adaptor;
44 private final MqttSslHandlerProvider sslHandlerProvider; 43 private final MqttSslHandlerProvider sslHandlerProvider;
45 private final QuotaService quotaService; 44 private final QuotaService quotaService;
46 - private final DeviceOfflineService offlineService;  
47 45
48 public MqttTransportServerInitializer(SessionMsgProcessor processor, DeviceService deviceService, DeviceAuthService authService, RelationService relationService, 46 public MqttTransportServerInitializer(SessionMsgProcessor processor, DeviceService deviceService, DeviceAuthService authService, RelationService relationService,
49 MqttTransportAdaptor adaptor, MqttSslHandlerProvider sslHandlerProvider, 47 MqttTransportAdaptor adaptor, MqttSslHandlerProvider sslHandlerProvider,
50 - QuotaService quotaService, DeviceOfflineService offlineService) { 48 + QuotaService quotaService) {
51 this.processor = processor; 49 this.processor = processor;
52 this.deviceService = deviceService; 50 this.deviceService = deviceService;
53 this.authService = authService; 51 this.authService = authService;
@@ -55,7 +53,6 @@ public class MqttTransportServerInitializer extends ChannelInitializer<SocketCha @@ -55,7 +53,6 @@ public class MqttTransportServerInitializer extends ChannelInitializer<SocketCha
55 this.adaptor = adaptor; 53 this.adaptor = adaptor;
56 this.sslHandlerProvider = sslHandlerProvider; 54 this.sslHandlerProvider = sslHandlerProvider;
57 this.quotaService = quotaService; 55 this.quotaService = quotaService;
58 - this.offlineService = offlineService;  
59 } 56 }
60 57
61 @Override 58 @Override
@@ -70,7 +67,7 @@ public class MqttTransportServerInitializer extends ChannelInitializer<SocketCha @@ -70,7 +67,7 @@ public class MqttTransportServerInitializer extends ChannelInitializer<SocketCha
70 pipeline.addLast("encoder", MqttEncoder.INSTANCE); 67 pipeline.addLast("encoder", MqttEncoder.INSTANCE);
71 68
72 MqttTransportHandler handler = new MqttTransportHandler(processor, deviceService, authService, relationService, 69 MqttTransportHandler handler = new MqttTransportHandler(processor, deviceService, authService, relationService,
73 - adaptor, sslHandler, quotaService, offlineService); 70 + adaptor, sslHandler, quotaService);
74 71
75 pipeline.addLast(handler); 72 pipeline.addLast(handler);
76 ch.closeFuture().addListener(handler); 73 ch.closeFuture().addListener(handler);
@@ -30,7 +30,6 @@ import org.springframework.stereotype.Service; @@ -30,7 +30,6 @@ import org.springframework.stereotype.Service;
30 import org.thingsboard.server.common.transport.SessionMsgProcessor; 30 import org.thingsboard.server.common.transport.SessionMsgProcessor;
31 import org.thingsboard.server.common.transport.auth.DeviceAuthService; 31 import org.thingsboard.server.common.transport.auth.DeviceAuthService;
32 import org.thingsboard.server.common.transport.quota.QuotaService; 32 import org.thingsboard.server.common.transport.quota.QuotaService;
33 -import org.thingsboard.server.dao.device.DeviceOfflineService;  
34 import org.thingsboard.server.dao.device.DeviceService; 33 import org.thingsboard.server.dao.device.DeviceService;
35 import org.thingsboard.server.dao.relation.RelationService; 34 import org.thingsboard.server.dao.relation.RelationService;
36 import org.thingsboard.server.transport.mqtt.adaptors.MqttTransportAdaptor; 35 import org.thingsboard.server.transport.mqtt.adaptors.MqttTransportAdaptor;
@@ -70,9 +69,6 @@ public class MqttTransportService { @@ -70,9 +69,6 @@ public class MqttTransportService {
70 @Autowired(required = false) 69 @Autowired(required = false)
71 private QuotaService quotaService; 70 private QuotaService quotaService;
72 71
73 - @Autowired(required = false)  
74 - private DeviceOfflineService offlineService;  
75 -  
76 @Value("${mqtt.bind_address}") 72 @Value("${mqtt.bind_address}")
77 private String host; 73 private String host;
78 @Value("${mqtt.bind_port}") 74 @Value("${mqtt.bind_port}")
@@ -110,7 +106,7 @@ public class MqttTransportService { @@ -110,7 +106,7 @@ public class MqttTransportService {
110 b.group(bossGroup, workerGroup) 106 b.group(bossGroup, workerGroup)
111 .channel(NioServerSocketChannel.class) 107 .channel(NioServerSocketChannel.class)
112 .childHandler(new MqttTransportServerInitializer(processor, deviceService, authService, relationService, 108 .childHandler(new MqttTransportServerInitializer(processor, deviceService, authService, relationService,
113 - adaptor, sslHandlerProvider, quotaService, offlineService)); 109 + adaptor, sslHandlerProvider, quotaService));
114 110
115 serverChannel = b.bind(host, port).sync().channel(); 111 serverChannel = b.bind(host, port).sync().channel();
116 log.info("Mqtt transport started!"); 112 log.info("Mqtt transport started!");
@@ -36,7 +36,6 @@ import org.thingsboard.server.common.transport.SessionMsgProcessor; @@ -36,7 +36,6 @@ import org.thingsboard.server.common.transport.SessionMsgProcessor;
36 import org.thingsboard.server.common.transport.adaptor.AdaptorException; 36 import org.thingsboard.server.common.transport.adaptor.AdaptorException;
37 import org.thingsboard.server.common.transport.adaptor.JsonConverter; 37 import org.thingsboard.server.common.transport.adaptor.JsonConverter;
38 import org.thingsboard.server.common.transport.auth.DeviceAuthService; 38 import org.thingsboard.server.common.transport.auth.DeviceAuthService;
39 -import org.thingsboard.server.dao.device.DeviceOfflineService;  
40 import org.thingsboard.server.dao.device.DeviceService; 39 import org.thingsboard.server.dao.device.DeviceService;
41 import org.thingsboard.server.dao.relation.RelationService; 40 import org.thingsboard.server.dao.relation.RelationService;
42 import org.thingsboard.server.transport.mqtt.MqttTransportHandler; 41 import org.thingsboard.server.transport.mqtt.MqttTransportHandler;
@@ -62,17 +61,14 @@ public class GatewaySessionCtx { @@ -62,17 +61,14 @@ public class GatewaySessionCtx {
62 private final DeviceService deviceService; 61 private final DeviceService deviceService;
63 private final DeviceAuthService authService; 62 private final DeviceAuthService authService;
64 private final RelationService relationService; 63 private final RelationService relationService;
65 - private final DeviceOfflineService offlineService;  
66 private final Map<String, GatewayDeviceSessionCtx> devices; 64 private final Map<String, GatewayDeviceSessionCtx> devices;
67 private ChannelHandlerContext channel; 65 private ChannelHandlerContext channel;
68 66
69 - public GatewaySessionCtx(SessionMsgProcessor processor, DeviceService deviceService, DeviceAuthService authService,  
70 - RelationService relationService, DeviceSessionCtx gatewaySessionCtx, DeviceOfflineService offlineService) { 67 + public GatewaySessionCtx(SessionMsgProcessor processor, DeviceService deviceService, DeviceAuthService authService, RelationService relationService, DeviceSessionCtx gatewaySessionCtx) {
71 this.processor = processor; 68 this.processor = processor;
72 this.deviceService = deviceService; 69 this.deviceService = deviceService;
73 this.authService = authService; 70 this.authService = authService;
74 this.relationService = relationService; 71 this.relationService = relationService;
75 - this.offlineService = offlineService;  
76 this.gateway = gatewaySessionCtx.getDevice(); 72 this.gateway = gatewaySessionCtx.getDevice();
77 this.gatewaySessionId = gatewaySessionCtx.getSessionId(); 73 this.gatewaySessionId = gatewaySessionCtx.getSessionId();
78 this.devices = new HashMap<>(); 74 this.devices = new HashMap<>();
@@ -102,7 +98,6 @@ public class GatewaySessionCtx { @@ -102,7 +98,6 @@ public class GatewaySessionCtx {
102 log.debug("[{}] Added device [{}] to the gateway session", gatewaySessionId, deviceName); 98 log.debug("[{}] Added device [{}] to the gateway session", gatewaySessionId, deviceName);
103 processor.process(new BasicToDeviceActorSessionMsg(device, new BasicAdaptorToSessionActorMsg(ctx, new AttributesSubscribeMsg()))); 99 processor.process(new BasicToDeviceActorSessionMsg(device, new BasicAdaptorToSessionActorMsg(ctx, new AttributesSubscribeMsg())));
104 processor.process(new BasicToDeviceActorSessionMsg(device, new BasicAdaptorToSessionActorMsg(ctx, new RpcSubscribeMsg()))); 100 processor.process(new BasicToDeviceActorSessionMsg(device, new BasicAdaptorToSessionActorMsg(ctx, new RpcSubscribeMsg())));
105 - offlineService.online(device, false);  
106 } 101 }
107 } 102 }
108 103
@@ -112,7 +107,6 @@ public class GatewaySessionCtx { @@ -112,7 +107,6 @@ public class GatewaySessionCtx {
112 if (deviceSessionCtx != null) { 107 if (deviceSessionCtx != null) {
113 processor.process(SessionCloseMsg.onDisconnect(deviceSessionCtx.getSessionId())); 108 processor.process(SessionCloseMsg.onDisconnect(deviceSessionCtx.getSessionId()));
114 deviceSessionCtx.setClosed(true); 109 deviceSessionCtx.setClosed(true);
115 - offlineService.offline(deviceSessionCtx.getDevice());  
116 log.debug("[{}] Removed device [{}] from the gateway session", gatewaySessionId, deviceName); 110 log.debug("[{}] Removed device [{}] from the gateway session", gatewaySessionId, deviceName);
117 } else { 111 } else {
118 log.debug("[{}] Device [{}] was already removed from the gateway session", gatewaySessionId, deviceName); 112 log.debug("[{}] Device [{}] was already removed from the gateway session", gatewaySessionId, deviceName);
@@ -123,7 +117,6 @@ public class GatewaySessionCtx { @@ -123,7 +117,6 @@ public class GatewaySessionCtx {
123 public void onGatewayDisconnect() { 117 public void onGatewayDisconnect() {
124 devices.forEach((k, v) -> { 118 devices.forEach((k, v) -> {
125 processor.process(SessionCloseMsg.onDisconnect(v.getSessionId())); 119 processor.process(SessionCloseMsg.onDisconnect(v.getSessionId()));
126 - offlineService.offline(v.getDevice());  
127 }); 120 });
128 } 121 }
129 122
@@ -145,7 +138,6 @@ public class GatewaySessionCtx { @@ -145,7 +138,6 @@ public class GatewaySessionCtx {
145 GatewayDeviceSessionCtx deviceSessionCtx = devices.get(deviceName); 138 GatewayDeviceSessionCtx deviceSessionCtx = devices.get(deviceName);
146 processor.process(new BasicToDeviceActorSessionMsg(deviceSessionCtx.getDevice(), 139 processor.process(new BasicToDeviceActorSessionMsg(deviceSessionCtx.getDevice(),
147 new BasicAdaptorToSessionActorMsg(deviceSessionCtx, request))); 140 new BasicAdaptorToSessionActorMsg(deviceSessionCtx, request)));
148 - offlineService.online(deviceSessionCtx.getDevice(), true);  
149 } 141 }
150 } else { 142 } else {
151 throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); 143 throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json);
@@ -162,7 +154,6 @@ public class GatewaySessionCtx { @@ -162,7 +154,6 @@ public class GatewaySessionCtx {
162 GatewayDeviceSessionCtx deviceSessionCtx = devices.get(deviceName); 154 GatewayDeviceSessionCtx deviceSessionCtx = devices.get(deviceName);
163 processor.process(new BasicToDeviceActorSessionMsg(deviceSessionCtx.getDevice(), 155 processor.process(new BasicToDeviceActorSessionMsg(deviceSessionCtx.getDevice(),
164 new BasicAdaptorToSessionActorMsg(deviceSessionCtx, new ToDeviceRpcResponseMsg(requestId, data)))); 156 new BasicAdaptorToSessionActorMsg(deviceSessionCtx, new ToDeviceRpcResponseMsg(requestId, data))));
165 - offlineService.online(deviceSessionCtx.getDevice(), true);  
166 } else { 157 } else {
167 throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); 158 throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json);
168 } 159 }
@@ -185,7 +176,6 @@ public class GatewaySessionCtx { @@ -185,7 +176,6 @@ public class GatewaySessionCtx {
185 GatewayDeviceSessionCtx deviceSessionCtx = devices.get(deviceName); 176 GatewayDeviceSessionCtx deviceSessionCtx = devices.get(deviceName);
186 processor.process(new BasicToDeviceActorSessionMsg(deviceSessionCtx.getDevice(), 177 processor.process(new BasicToDeviceActorSessionMsg(deviceSessionCtx.getDevice(),
187 new BasicAdaptorToSessionActorMsg(deviceSessionCtx, request))); 178 new BasicAdaptorToSessionActorMsg(deviceSessionCtx, request)));
188 - offlineService.online(deviceSessionCtx.getDevice(), true);  
189 } 179 }
190 } else { 180 } else {
191 throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); 181 throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json);
@@ -220,7 +210,6 @@ public class GatewaySessionCtx { @@ -220,7 +210,6 @@ public class GatewaySessionCtx {
220 processor.process(new BasicToDeviceActorSessionMsg(deviceSessionCtx.getDevice(), 210 processor.process(new BasicToDeviceActorSessionMsg(deviceSessionCtx.getDevice(),
221 new BasicAdaptorToSessionActorMsg(deviceSessionCtx, request))); 211 new BasicAdaptorToSessionActorMsg(deviceSessionCtx, request)));
222 ack(msg); 212 ack(msg);
223 - offlineService.online(deviceSessionCtx.getDevice(), false);  
224 } else { 213 } else {
225 throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); 214 throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json);
226 } 215 }