hub server

This commit is contained in:
moxitech 2024-11-06 21:11:51 +07:00
parent dcdb360612
commit c22cfef855
13 changed files with 492 additions and 92 deletions

30
TODO.md
View File

@ -36,36 +36,34 @@ Quic select - быстрые действия
Структура данных сервера websocket :: Структура данных сервера websocket ::
``` ```
Соединение: Хаб-комната:
Пользователи: [ Пользователи: [
Пользователь: { Пользователь: {
Id: Id:int
TimeActivate: ts(int64) Coordinate:[int,int,int]
TimeActivate: int64
IsActive: bool IsActive: bool
IsCreator? bool IsCreator? bool
...
} }
], ],
Карта: {
Имя <DbTemplateName|CustomNameFromUser>
Координаты: [{...}],
}
БПЛА: [ БПЛА: [
БПЛА: { БПЛА: {
Id: Id:int
Name: Name:string
Coordinate:[int,int,int]
Checked:{UserId, expire} Checked:{UserId, expire}
{coords...} SignalRadius:string
{params...} SignalFrequrency:int
} }
] ]
Базовые_станции: [ Базовые_станции: [
BaseStation: { BaseStation: {
Id: Id:int
Name: Name:string
Checked:{UserId, expire} Checked:{UserId, expire}
{coords...} AntennaDirection:[int,int,int]
{params...} SignalRadius:string
SignalFrequrency:int
} }
] ]
ts_update: ts_update:

View File

@ -1,4 +0,0 @@
!1 => Написать хук для воспроизведения симуляции
!2 =>

View File

@ -65,10 +65,10 @@ services:
- dns_net - dns_net
restart: always restart: always
socket: publisher:
container_name: dns-socket container_name: dns-publisher
build: build:
context: ./src/socket context: ./src/microservices/publisher
dockerfile: Dockerfile dockerfile: Dockerfile
env_file: ".env" env_file: ".env"
ports: ports:

14
docs/authors/Authors.md Normal file
View File

@ -0,0 +1,14 @@
### Авторы проекта
> Moxitech - Грицков Никита - @moxitech
> 1
>
>
>
>

View File

@ -0,0 +1,311 @@
package main
import (
"encoding/json"
"fmt"
"sync"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
)
type Event struct {
Type string `json:"type"` // Тип события: "update", "create", "delete"
ObjectType string `json:"object_type"` // Тип объекта: "uav", "base_station"
Payload interface{} `json:"payload"` // Данные конкретного объекта
}
type Hub struct {
clients map[*websocket.Conn]bool
broadcast chan Event
register chan *websocket.Conn
unregister chan *websocket.Conn
hubRooms map[string]*HubRoom
mu sync.Mutex
}
type HubRoom struct {
Users []User `json:"users"`
UAVs []UAV `json:"uavs"`
BaseStations []BaseStation `json:"baseStations"`
TsUpdate int64 `json:"ts_update"`
}
type User struct {
Id int `json:"id"`
TimeActivate int64 `json:"timeActivate"`
IsActive bool `json:"isActive"`
IsCreator bool `json:"isCreator,omitempty"`
}
type UAV struct {
Id int `json:"id"`
Name string `json:"name"`
Coordinate [3]int `json:"coordinate"`
Checked struct {
UserId int64 `json:"userId"`
Expire int64 `json:"expire"`
} `json:"checked"`
SignalRadius string `json:"signalRadius"`
SignalFrequency int `json:"signalFrequency"`
MeshName string `json:"meshName"`
}
type BaseStation struct {
Id int `json:"id"`
Name string `json:"name"`
Checked struct {
UserId int64 `json:"userId"`
Expire int64 `json:"expire"`
} `json:"checked"`
AntennaDirection [3]int `json:"antennaDirection"`
SignalRadius string `json:"signalRadius"`
SignalFrequency int `json:"signalFrequency"`
}
func newHub() *Hub {
return &Hub{
clients: make(map[*websocket.Conn]bool),
broadcast: make(chan Event),
register: make(chan *websocket.Conn),
unregister: make(chan *websocket.Conn),
hubRooms: make(map[string]*HubRoom),
}
}
func (h *Hub) run() {
for {
select {
case client := <-h.register:
h.mu.Lock()
h.clients[client] = true
// При подключении клиента отправляем все данные комнаты
for _, room := range h.hubRooms {
roomData, err := json.Marshal(room)
if err != nil {
fmt.Println("Error marshalling room data:", err)
continue
}
if err := client.WriteMessage(websocket.TextMessage, roomData); err != nil {
client.Close()
delete(h.clients, client)
}
}
h.mu.Unlock()
case client := <-h.unregister:
h.mu.Lock()
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
client.Close()
}
h.mu.Unlock()
case event := <-h.broadcast:
h.mu.Lock()
for client := range h.clients {
eventData, err := json.Marshal(event)
if err != nil {
fmt.Println("Error marshalling event:", err)
continue
}
if err := client.WriteMessage(websocket.TextMessage, eventData); err != nil {
client.Close()
delete(h.clients, client)
}
}
h.mu.Unlock()
}
}
}
func (h *Hub) handleMessage(c *websocket.Conn, msg []byte) {
var event Event
err := json.Unmarshal(msg, &event)
if err != nil {
fmt.Println("Error unmarshalling message:", err)
return
}
// Обработка событий в зависимости от типа объекта и типа действия
switch event.Type {
case "update":
h.handleUpdate(event)
case "create":
h.handleCreate(event)
case "delete":
h.handleDelete(event)
default:
fmt.Println("Unknown event type:", event.Type)
}
// После обработки, передаем событие всем клиентам
h.broadcast <- event
}
func (h *Hub) handleUpdate(event Event) {
h.mu.Lock()
defer h.mu.Unlock()
switch event.ObjectType {
case "uav":
var uav UAV
if err := mapToStruct(event.Payload, &uav); err == nil {
// Найдите и обновите UAV в hubRooms
for _, room := range h.hubRooms {
for i, existingUAV := range room.UAVs {
if existingUAV.Id == uav.Id {
room.UAVs[i] = uav
h.broadcast <- Event{Type: "update", ObjectType: "uav", Payload: uav}
break
}
}
}
fmt.Println("Updating UAV", uav.Id)
}
case "base_station":
var station BaseStation
if err := mapToStruct(event.Payload, &station); err == nil {
// Найдите и обновите BaseStation в hubRooms
for _, room := range h.hubRooms {
for i, existingStation := range room.BaseStations {
if existingStation.Id == station.Id {
room.BaseStations[i] = station
h.broadcast <- Event{Type: "update", ObjectType: "base_station", Payload: station}
break
}
}
}
fmt.Println("Updating BaseStation", station.Id)
}
}
}
func (h *Hub) handleCreate(event Event) {
h.mu.Lock()
defer h.mu.Unlock()
switch event.ObjectType {
case "uav":
var uav UAV
if err := mapToStruct(event.Payload, &uav); err == nil {
// Добавьте новый UAV в hubRooms
for _, room := range h.hubRooms {
room.UAVs = append(room.UAVs, uav)
h.broadcast <- Event{Type: "create", ObjectType: "uav", Payload: uav}
}
fmt.Println("Creating UAV", uav.Id)
}
case "base_station":
var station BaseStation
if err := mapToStruct(event.Payload, &station); err == nil {
// Добавьте новую BaseStation в hubRooms
for _, room := range h.hubRooms {
room.BaseStations = append(room.BaseStations, station)
h.broadcast <- Event{Type: "create", ObjectType: "base_station", Payload: station}
}
fmt.Println("Creating BaseStation", station.Id)
}
}
}
func (h *Hub) handleDelete(event Event) {
h.mu.Lock()
defer h.mu.Unlock()
switch event.ObjectType {
case "uav":
var uav UAV
if err := mapToStruct(event.Payload, &uav); err == nil {
// Удалите UAV из hubRooms
for _, room := range h.hubRooms {
for i, existingUAV := range room.UAVs {
if existingUAV.Id == uav.Id {
room.UAVs = append(room.UAVs[:i], room.UAVs[i+1:]...)
h.broadcast <- Event{Type: "delete", ObjectType: "uav", Payload: uav}
break
}
}
}
fmt.Println("Deleting UAV", uav.Id)
}
case "base_station":
var station BaseStation
if err := mapToStruct(event.Payload, &station); err == nil {
// Удалите BaseStation из hubRooms
for _, room := range h.hubRooms {
for i, existingStation := range room.BaseStations {
if existingStation.Id == station.Id {
room.BaseStations = append(room.BaseStations[:i], room.BaseStations[i+1:]...)
h.broadcast <- Event{Type: "delete", ObjectType: "base_station", Payload: station}
break
}
}
}
fmt.Println("Deleting BaseStation", station.Id)
}
}
}
func mapToStruct(input interface{}, output interface{}) error {
jsonData, err := json.Marshal(input)
if err != nil {
return err
}
return json.Unmarshal(jsonData, output)
}
func (h *Hub) createRoom(c *fiber.Ctx) error {
roomId := c.Params("roomId")
h.mu.Lock()
defer h.mu.Unlock()
if _, exists := h.hubRooms[roomId]; exists {
return c.Status(fiber.StatusConflict).JSON(fiber.Map{
"error": "Room already exists",
})
}
h.hubRooms[roomId] = &HubRoom{
Users: []User{},
UAVs: []UAV{},
BaseStations: []BaseStation{},
TsUpdate: time.Now().Unix(),
}
return c.Status(fiber.StatusCreated).JSON(fiber.Map{
"message": "Room created successfully",
"roomId": roomId,
})
}
func main() {
app := fiber.New(fiber.Config{
AppName: "DRONE NETWORK SIMULATOR HUB - RUNNER",
Prefork: false,
})
hub := newHub()
go hub.run()
app.Get("/ws", websocket.New(func(c *websocket.Conn) {
hub.register <- c
defer func() { hub.unregister <- c }()
for {
_, msg, err := c.ReadMessage()
if err != nil {
break
}
hub.handleMessage(c, msg)
}
}))
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("WebSocket server is running. Connect to /ws using a WebSocket client.")
})
app.Post("/rooms/:roomId", hub.createRoom)
fmt.Println("Server is running on http://localhost:8899")
if err := app.Listen(":8899"); err != nil {
panic(err)
}
}

View File

@ -0,0 +1,96 @@
#### Создание нового UAV
```
{
"type": "create",
"object_type": "uav",
"payload": {
"id": 1,
"name": "UAV-01",
"coordinate": [100, 200, 300],
"checked": {
"userId": 1,
"expire": 1672531500
},
"signalRadius": "100m",
"signalFrequency": 2400,
"meshName": "Mesh-01"
}
}
```
### Обновление UAV
```
{
"type": "update",
"object_type": "uav",
"payload": {
"id": 1,
"name": "UAV-01",
"coordinate": [150, 250, 350],
"checked": {
"userId": 1,
"expire": 1672531600
},
"signalRadius": "120m",
"signalFrequency": 2450,
"meshName": "Mesh-01"
}
}
```
### Удаление UAV
```
{
"type": "delete",
"object_type": "uav",
"payload": {
"id": 1
}
}
```
### Создание новой базовой станции
```
{
"type": "create",
"object_type": "base_station",
"payload": {
"id": 1,
"name": "BaseStation-01",
"checked": {
"userId": 1,
"expire": 1672531700
},
"antennaDirection": [0, 0, 1],
"signalRadius": "500m",
"signalFrequency": 1800
}
}
```
### Обновление базовой станции
```
{
"type": "update",
"object_type": "base_station",
"payload": {
"id": 1,
"name": "BaseStation-01-Updated",
"checked": {
"userId": 2,
"expire": 1672531800
},
"antennaDirection": [1, 0, 0],
"signalRadius": "550m",
"signalFrequency": 1850
}
}
```
### Удаление базовой станции
```
{
"type": "delete",
"object_type": "base_station",
"payload": {
"id": 1
}
}
```

View File

@ -0,0 +1,21 @@
module git.moxitech.ru/moxitech/hub-go
go 1.23.2
require (
github.com/andybalholm/brotli v1.0.5 // indirect
github.com/fasthttp/websocket v1.5.3 // indirect
github.com/gofiber/fiber/v2 v2.52.5 // indirect
github.com/gofiber/websocket/v2 v2.2.1 // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/klauspost/compress v1.17.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.51.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/sys v0.15.0 // indirect
)

View File

@ -0,0 +1,33 @@
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/fasthttp/websocket v1.5.3 h1:TPpQuLwJYfd4LJPXvHDYPMFWbLjsT91n3GpWtCQtdek=
github.com/fasthttp/websocket v1.5.3/go.mod h1:46gg/UBmTU1kUaTcwQXpUxtRwG2PvIZYeA8oL6vF3Fs=
github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo=
github.com/gofiber/fiber/v2 v2.52.5/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
github.com/gofiber/websocket/v2 v2.2.1 h1:C9cjxvloojayOp9AovmpQrk8VqvVnT8Oao3+IUygH7w=
github.com/gofiber/websocket/v2 v2.2.1/go.mod h1:Ao/+nyNnX5u/hIFPuHl28a+NIkrqK7PRimyKaj4JxVU=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM=
github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee h1:8Iv5m6xEo1NR1AvpV+7XmhI4r39LGNzwUL4YpMuL5vk=
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee/go.mod h1:qwtSXrKuJh/zsFQ12yEE89xfCrGKK63Rr7ctU/uCo4g=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=

View File

@ -11,76 +11,7 @@ import (
"os" "os"
) )
// var wg sync.WaitGroup = sync.WaitGroup{}
// func main() {
// // Пример карты высот, замените на настоящие данные
// heightData := [][]float64{
// {0, 10, 15, 20},
// {5, 15, 25, 30},
// {10, 20, 35, 40},
// {15, 25, 40, 50},
// }
// // Определяем карту высот
// mapObj := &simulator.Map{
// Name: "Example Map",
// MinBound: [3]float64{-1000, -1000, 0},
// MaxBound: [3]float64{1000, 1000, 500},
// HeightData: heightData,
// }
// // Определяем дронов
// drones := []*simulator.Drone{
// {
// ID: 1,
// Name: "Drone 1",
// Coords: [3]float64{100, 100, 50},
// Params: simulator.DroneParams{
// AntennaRadius: 500,
// AntennaDirection: [3]float64{1, 0, 0},
// Waypoints: [][3]float64{{200, 200, 50}},
// Speed: 10,
// MeshName: "MeshA",
// },
// },
// }
// // Определяем базовые станции
// baseStations := []*simulator.BaseStation{
// {
// ID: 1,
// Name: "BaseStation1",
// Coords: [3]float64{0, 0, 0},
// Params: simulator.BaseStationParams{
// AntennaRadius: 2000,
// AntennaDirection: [3]float64{1, 0, 0},
// },
// },
// }
// // Создаем симуляцию
// sim := &simulator.NetworkSimulation{
// Map: mapObj,
// Drones: drones,
// BaseStations: baseStations,
// TimeStep: 2,
// }
// // Запуск симуляции на 300 секунд
// result_sim := sim.Simulate(300)
// result := u_sorting.SortMap(result_sim)
// for time, state := range result {
// for localstate, f := range state {
// fmt.Printf("%v| %v sec :: %v\n", time, localstate, f)
// }
// }
// }
func main() { func main() {
// JSON_L1_TEST
// data := json.T_CreateApproximateJsonStruct_l1()
// fmt.Println(data)
// RANDOM_STRING_TEST
// fmt.Println(randomizer.GenerateRandomString())
FlushLogo() FlushLogo()
D_EXPORT_VARS() D_EXPORT_VARS()
err := database.NewDBConnection() err := database.NewDBConnection()