MC Add if event announce, update device state + clean code + allow message after wakeup

This commit is contained in:
Thomas Fransolet 2021-03-26 16:25:01 +01:00
parent edb7f41494
commit d69799eb7e
4 changed files with 82 additions and 58 deletions

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace MyCore.Interfaces.Models.Providers.Zigbee.Zigbee2Mqtt
{
public class Zigbee2MqttEvent
{
public Data data { get; set; }
public string type { get; set; }
}
public class Data
{
public string friendly_name { get; set; }
public string ieee_address { get; set; }
}
}

View File

@ -74,8 +74,22 @@ namespace Mqtt.Client.AspNetCore.Services
// For check if not doubled message (example : motion double true value) // For check if not doubled message (example : motion double true value)
var test = currentTime - lastTimeTopic; var test = currentTime - lastTimeTopic;
var isWakeUpMessage = false;
// if wakeup => Not drop wakeup message
try
{
var deserialzed = JsonConvert.DeserializeObject<Dictionary<string, object>>(payload);
if (deserialzed != null) {
isWakeUpMessage = (string)deserialzed["action"] == "wakeup";
}
} catch (Exception ex)
{
}
// Less than one second between two messages from a same device // Less than one second between two messages from a same device
if (!(lastTopic == topic && test <= 1000)) if (!(lastTopic == topic && test <= 500))
{ {
if (_actionService != null) if (_actionService != null)
{ {
@ -125,8 +139,10 @@ namespace Mqtt.Client.AspNetCore.Services
break; break;
} }
lastTimeTopic = DateTimeOffset.Now.ToUnixTimeMilliseconds(); if (!isWakeUpMessage) {
lastTopic = topic; lastTimeTopic = DateTimeOffset.Now.ToUnixTimeMilliseconds();
lastTopic = topic;
}
return null; return null;
} }
@ -182,15 +198,6 @@ namespace Mqtt.Client.AspNetCore.Services
await mqttClient.PublishAsync(mqttMessage); await mqttClient.PublishAsync(mqttMessage);
} }
public static List<Zigbee2MqttDevice> GetDevices()
{
return devices;
}
public static List<Zigbee2MqttDevice> GetDevicesNew()
{
return devicesNew;
}
public static void SetServices(DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, ActionService _ActionService, AutomationDatabaseService _AutomationDatabaseService, string UserId) public static void SetServices(DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService, ActionService _ActionService, AutomationDatabaseService _AutomationDatabaseService, string UserId)
{ {
_deviceDatabaseService = _DeviceDatabaseService; _deviceDatabaseService = _DeviceDatabaseService;
@ -201,17 +208,5 @@ namespace Mqtt.Client.AspNetCore.Services
_actionService = _ActionService; _actionService = _ActionService;
userId = UserId; userId = UserId;
} }
public static async Task<List<Zigbee2MqttDevice>> AskDevicesAsync()
{
await PublishMessage("zigbee2mqtt/bridge/config/devices/get", "");
// WARNING BAD CODE BELOW
while (devices.Count <= 0) {
// wait
}
return devices;
}
} }
} }

View File

@ -1,6 +1,7 @@
using Mqtt.Client.AspNetCore.Services; using Mqtt.Client.AspNetCore.Services;
using MyCore.Interfaces.DTO; using MyCore.Interfaces.DTO;
using MyCore.Interfaces.Models; using MyCore.Interfaces.Models;
using MyCore.Interfaces.Models.Providers.Zigbee.Zigbee2Mqtt;
using MyCore.Service.Services; using MyCore.Service.Services;
using MyCore.Services.MyControlPanel; using MyCore.Services.MyControlPanel;
using Newtonsoft.Json; using Newtonsoft.Json;
@ -33,7 +34,7 @@ namespace MyCore.Services.Devices
switch (providerFromTopic) { switch (providerFromTopic) {
case "zigbee2mqtt": case "zigbee2mqtt":
UpdateZigbee2MqttConfigAsync(topic, message, userId, _DeviceDatabaseService, _GroupDatabaseService, _ProviderDatabaseService, _LocationDatabaseService); UpdateZigbee2MqttConfigOrStateAsync(topic, message, userId, _DeviceDatabaseService, _GroupDatabaseService, _ProviderDatabaseService, _LocationDatabaseService);
break; break;
default: default:
break; break;
@ -567,7 +568,7 @@ namespace MyCore.Services.Devices
} }
} }
public static async Task UpdateZigbee2MqttConfigAsync(string topic, string message, string userId, DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService) { public static async Task UpdateZigbee2MqttConfigOrStateAsync(string topic, string message, string userId, DeviceDatabaseService _DeviceDatabaseService, GroupDatabaseService _GroupDatabaseService, ProviderDatabaseService _ProviderDatabaseService, LocationDatabaseService _LocationDatabaseService) {
// update zigbee2mqqtt config // update zigbee2mqqtt config
switch (topic) switch (topic)
{ {
@ -607,8 +608,8 @@ namespace MyCore.Services.Devices
{ {
var groups = _GroupDatabaseService.GetByType(userId, "zigbee2mqtt"); var groups = _GroupDatabaseService.GetByType(userId, "zigbee2mqtt");
// Compare the groups from MyCore and the group we received, if something diff in one group => Hard refresh (delete, new) // Compare the groups from MyCore and the group we received, if something diff in one group => Hard refresh (delete, new)
// TODO : wait for new devices // TODO : Test with new devices
// GroupService.CompareGroupsFromZigbee2Mqtt(userId, groups, groupsConvert, _DeviceDatabaseService, _GroupDatabaseService); GroupService.CompareGroupsFromZigbee2Mqtt(userId, groups, groupsConvert, _DeviceDatabaseService, _GroupDatabaseService);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -616,6 +617,39 @@ namespace MyCore.Services.Devices
Console.WriteLine($"Error during retrieving groups ! Exception: {ex}"); Console.WriteLine($"Error during retrieving groups ! Exception: {ex}");
} }
break; break;
case "zigbee2mqtt/bridge/event":
try
{
var eventConvert = JsonConvert.DeserializeObject<Zigbee2MqttEvent>(message);
if (eventConvert.data?.ieee_address != null) {
var zigbeeDevice = _DeviceDatabaseService.GetByServiceIdentification(eventConvert.data.ieee_address);
if (zigbeeDevice != null && eventConvert.type == "device_announce") // Check if we can not hardcode that..
{
var status = new List<State>();
var state = new State();
state.Name = "state";
state.Value = "on";
status.Add(state);
var buildRequest = new Dictionary<string, object>();
buildRequest.Add(state.Name, state.Value);
// Update device state !
zigbeeDevice.LastState = JsonConvert.SerializeObject(buildRequest);
zigbeeDevice.LastStateDate = DateTime.Now;
_DeviceDatabaseService.Update(zigbeeDevice);
// Check if all group has the same state // Not needed as we test the first device of a group
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error during retrieving event ! Exception: {ex}");
}
break;
} }
} }
} }

View File

@ -5,7 +5,7 @@ info:
description: API description description: API description
version: Version Pre-Alpha version: Version Pre-Alpha
servers: servers:
- url: 'http://localhost:25049' - url: 'http://192.168.31.140'
paths: paths:
/api/books: /api/books:
get: get:
@ -916,16 +916,15 @@ paths:
tags: tags:
- User - User
summary: 'Get a list of user ' summary: 'Get a list of user '
operationId: User_GetAll operationId: User_Get
responses: responses:
'200': '200':
description: '' description: ''
content: content:
application/json: application/octet-stream:
schema: schema:
type: array type: string
items: format: binary
$ref: '#/components/schemas/UserInfo'
security: security:
- bearer: [] - bearer: []
post: post:
@ -973,7 +972,7 @@ paths:
tags: tags:
- User - User
summary: 'Get a specific user ' summary: 'Get a specific user '
operationId: User_Get operationId: User_Get2
parameters: parameters:
- name: id - name: id
in: path in: path
@ -1142,7 +1141,7 @@ paths:
content: content:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/TokenDTO' $ref: '#/components/schemas/LoginDTO'
'401': '401':
description: Invalid credentials description: Invalid credentials
content: content:
@ -2806,28 +2805,6 @@ components:
lastName: lastName:
type: string type: string
nullable: true nullable: true
TokenDTO:
type: object
additionalProperties: false
properties:
access_token:
type: string
nullable: true
refresh_token:
type: string
nullable: true
scope:
type: string
nullable: true
token_type:
type: string
nullable: true
expires_in:
type: integer
format: int32
expiration:
type: string
format: date-time
RoomSummaryDTO: RoomSummaryDTO:
type: object type: object
additionalProperties: false additionalProperties: false