1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
//! Data types that daemon uses for core functions
use std::collections::HashMap;
use std::sync::Arc;
use serde::{Serialize, Deserialize};
use streamduck_core::versions::SOCKET_API;
use crate::core_manager::CoreManager;
use crate::socket::{check_packet_for_data, parse_packet_to_data, send_packet, SocketData, SocketHandle, SocketListener, SocketPacket};
use strum_macros::Display;
use streamduck_core::core::button::Button;
use streamduck_core::core::methods::{add_component, button_action, clear_button, CoreHandle, get_button, get_component_values, get_current_screen, get_stack, load_panels, pop_screen, push_screen, remove_component, replace_screen, save_panels, set_brightness, set_button, set_component_value};
use streamduck_core::core::RawButtonPanel;
use streamduck_core::modules::{ModuleManager, PluginMetadata};
use streamduck_core::modules::components::{ComponentDefinition, UIValue};
use streamduck_core::util::{button_to_raw, make_button_unique, make_panel_unique, panel_to_raw};
use crate::config::{Config, ConfigError, DeviceConfig};

/// Listener for daemon types
pub struct DaemonListener {
    pub core_manager: Arc<CoreManager>,
    pub module_manager: Arc<ModuleManager>,
    pub config: Arc<Config>,
}

impl SocketListener for DaemonListener {
    fn message(&self, socket: SocketHandle, packet: SocketPacket) {
        // Version
        process_for_type::<SocketAPIVersion>(self,socket, &packet);

        // Device management
        process_for_type::<ListDevices>(self,socket, &packet);
        process_for_type::<GetDevice>(self,socket, &packet);
        process_for_type::<AddDevice>(self,socket, &packet);
        process_for_type::<RemoveDevice>(self,socket, &packet);

        // Device configuration
        process_for_type::<ReloadDeviceConfigsResult>(self, socket, &packet);
        process_for_type::<ReloadDeviceConfig>(self, socket, &packet);
        process_for_type::<SaveDeviceConfigsResult>(self, socket, &packet);
        process_for_type::<SaveDeviceConfig>(self, socket, &packet);

        process_for_type::<GetDeviceConfig>(self, socket, &packet);

        process_for_type::<ImportDeviceConfig>(self, socket, &packet);
        process_for_type::<ExportDeviceConfig>(self, socket, &packet);

        process_for_type::<SetBrightness>(self, socket, &packet);

        // Module management
        process_for_type::<ListModules>(self,socket, &packet);
        process_for_type::<ListComponents>(self,socket, &packet);

        process_for_type::<GetModuleValues>(self,socket, &packet);
        process_for_type::<SetModuleValue>(self,socket, &packet);

        // Panel management
        process_for_type::<GetStack>(self, socket, &packet);
        process_for_type::<GetCurrentScreen>(self, socket, &packet);

        process_for_type::<GetButton>(self, socket, &packet);
        process_for_type::<SetButton>(self, socket, &packet);
        process_for_type::<ClearButton>(self, socket, &packet);

        process_for_type::<NewButton>(self, socket, &packet);
        process_for_type::<NewButtonFromComponent>(self, socket, &packet);

        process_for_type::<AddComponent>(self, socket, &packet);
        process_for_type::<GetComponentValues>(self, socket, &packet);
        process_for_type::<SetComponentValue>(self, socket, &packet);
        process_for_type::<RemoveComponent>(self, socket, &packet);

        process_for_type::<PushScreen>(self, socket, &packet);
        process_for_type::<PopScreen>(self, socket, &packet);
        process_for_type::<ForciblyPopScreen>(self, socket, &packet);
        process_for_type::<ReplaceScreen>(self, socket, &packet);
        process_for_type::<ResetStack>(self, socket, &packet);

        process_for_type::<CommitChangesToConfig>(self, socket, &packet);

        process_for_type::<DoButtonAction>(self, socket, &packet);
    }
}

trait DaemonRequest {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket);
}

fn process_for_type<T: DaemonRequest + SocketData>(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
    if packet.ty == T::NAME {
        T::process(listener, handle, packet);
    }
}

// Version

/// Request for socket API version
#[derive(Serialize, Deserialize)]
pub struct SocketAPIVersion {
    pub version: String
}

impl SocketData for SocketAPIVersion {
    const NAME: &'static str = "socket_version";
}

impl DaemonRequest for SocketAPIVersion {
    fn process(_listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if check_packet_for_data::<SocketAPIVersion>(&packet) {
            send_packet(handle, &packet, &SocketAPIVersion {
                version: SOCKET_API.1.to_string()
            }).ok();
        }
    }
}

// Device management

/// Request for getting device list
#[derive(Serialize, Deserialize)]
pub struct ListDevices {
    pub devices: Vec<Device>
}

impl SocketData for ListDevices {
    const NAME: &'static str = "list_devices";
}

impl DaemonRequest for ListDevices {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if check_packet_for_data::<ListDevices>(&packet) {
            let mut devices = vec![];

            // Connected devices
            for device in listener.core_manager.list_added_devices().values() {
                devices.push(Device {
                    device_type: DeviceType::from_pid(device.pid),
                    serial_number: device.serial.clone(),
                    managed: true,
                    online: !device.core.is_closed()
                })
            }

            // Available devices
            for (_, pid, serial) in listener.core_manager.list_available_devices() {
                devices.push(Device {
                    device_type: DeviceType::from_pid(pid),
                    serial_number: serial,
                    managed: false,
                    online: true
                })
            }

            send_packet(handle, &packet, &ListDevices {
                devices
            }).ok();
        }
    }
}

/// Device struct
#[derive(Serialize, Deserialize)]
pub struct Device {
    /// Device type
    pub device_type: DeviceType,
    /// Serial number of the streamdeck
    pub serial_number: String,
    /// If the device was added to managed device list
    pub managed: bool,
    /// If the device is online
    pub online: bool,
}

/// Streamdeck types
#[derive(Serialize, Deserialize, Display)]
pub enum DeviceType {
    Unknown,
    Mini,
    Original,
    OriginalV2,
    XL
}

impl DeviceType {
    /// Gets device type from PID of the device
    pub fn from_pid(pid: u16) -> DeviceType {
        match pid {
            streamduck_core::streamdeck::pids::ORIGINAL => DeviceType::Original,
            streamduck_core::streamdeck::pids::ORIGINAL_V2 => DeviceType::OriginalV2,
            streamduck_core::streamdeck::pids::MINI => DeviceType::Mini,
            streamduck_core::streamdeck::pids::XL => DeviceType::XL,
            _ => DeviceType::Unknown,
        }
    }
}

/// Request for getting a device
#[derive(Serialize, Deserialize)]
pub struct GetDevice {
    pub serial_number: String
}

impl SocketData for GetDevice {
    const NAME: &'static str = "get_device";
}

/// Response of GetDevice request
#[derive(Serialize, Deserialize)]
pub enum GetDeviceResult {
    /// Sent when device is found
    Found(Device),

    /// Send when device wasn't found
    NotFound
}

impl SocketData for GetDeviceResult {
    const NAME: &'static str = "get_device";
}

impl DaemonRequest for GetDevice {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(get_request) = parse_packet_to_data::<GetDevice>(&packet) {
            let result = if let Some(device) = listener.core_manager.get_device(&get_request.serial_number) {
                GetDeviceResult::Found(Device {
                    device_type: DeviceType::from_pid(device.pid),
                    serial_number: device.serial,
                    managed: true,
                    online: !device.core.is_closed()
                })
            } else {
                GetDeviceResult::NotFound
            };

            send_packet(handle, &packet, &result).ok();
        }
    }
}


/// Request for adding a device
#[derive(Serialize, Deserialize)]
pub struct AddDevice {
    pub serial_number: String,
}

impl SocketData for AddDevice {
    const NAME: &'static str = "add_device";
}

/// Response of AddDevice request
#[derive(Serialize, Deserialize)]
pub enum AddDeviceResult {
    /// Sent if device is already added
    AlreadyRegistered,

    /// Sent if device wasn't found
    NotFound,

    /// Sent on success
    Added
}

impl SocketData for AddDeviceResult {
    const NAME: &'static str = "add_device";
}

impl DaemonRequest for AddDevice {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(add_request) = parse_packet_to_data::<AddDevice>(&packet) {
            if listener.core_manager.get_device(&add_request.serial_number).is_none() {
                for (vid, pid, serial) in listener.core_manager.list_available_devices() {
                    if add_request.serial_number == serial {
                        listener.core_manager.add_device(vid, pid, &serial);
                        send_packet(handle, &packet, &AddDeviceResult::Added).ok();
                        return;
                    }
                }

                send_packet(handle, &packet, &AddDeviceResult::NotFound).ok();
            } else {
                send_packet(handle, &packet, &AddDeviceResult::AlreadyRegistered).ok();
            }
        }
    }
}

/// Request for removing a device
#[derive(Serialize, Deserialize)]
pub struct RemoveDevice {
    pub serial_number: String,
}

impl SocketData for RemoveDevice {
    const NAME: &'static str = "remove_device";
}

/// Response of RemoveDevice request
#[derive(Serialize, Deserialize)]
pub enum RemoveDeviceResult {
    /// Sent if device already wasn't added
    NotRegistered,

    /// Sent on success
    Removed
}

impl SocketData for RemoveDeviceResult {
    const NAME: &'static str = "remove_device";
}

impl DaemonRequest for RemoveDevice {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(remove_request) = parse_packet_to_data::<RemoveDevice>(&packet) {
            if listener.core_manager.get_device(&remove_request.serial_number).is_some() {
                listener.core_manager.remove_device(&remove_request.serial_number);
                send_packet(handle, &packet, &RemoveDeviceResult::Removed).ok();
            } else {
                send_packet(handle, &packet, &RemoveDeviceResult::NotRegistered).ok();
            }
        }
    }
}

// Device configuration
/// Request for reloading all device configs
#[derive(Serialize, Deserialize)]
pub enum ReloadDeviceConfigsResult {
    /// Sent if error happened while reloading configs
    ConfigError,

    /// Sent if successfully reloaded configs
    Reloaded,
}

impl SocketData for ReloadDeviceConfigsResult {
    const NAME: &'static str = "reload_device_configs";
}

impl DaemonRequest for ReloadDeviceConfigsResult {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if check_packet_for_data::<ReloadDeviceConfigsResult>(packet) {
            match listener.config.reload_device_configs() {
                Ok(_) => {
                    for (serial, device) in listener.core_manager.list_added_devices() {
                        if !device.core.is_closed() {
                            if let Some(dvc_cfg) = listener.config.get_device_config(&serial) {
                                let wrapped_core = CoreHandle::wrap(device.core);

                                load_panels(&wrapped_core, make_panel_unique(dvc_cfg.layout));
                                wrapped_core.core().mark_for_redraw()
                            }
                        }
                    }

                    send_packet(handle, packet, &ReloadDeviceConfigsResult::Reloaded).ok();
                },
                Err(err) => {
                    log::error!("Error encountered while reloading configs: {:?}", err);
                    send_packet(handle, packet, &ReloadDeviceConfigsResult::ConfigError).ok();
                }
            };
        }
    }
}

/// Request for reloading device config for specific device
#[derive(Serialize, Deserialize)]
pub struct ReloadDeviceConfig {
    pub serial_number: String
}

/// Response of ReloadDeviceConfig request
#[derive(Serialize, Deserialize)]
pub enum ReloadDeviceConfigResult {
    /// Sent if error happened while reloading configs
    ConfigError,

    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully reloaded configs
    Reloaded,
}

impl SocketData for ReloadDeviceConfig {
    const NAME: &'static str = "reload_device_config";
}

impl SocketData for ReloadDeviceConfigResult {
    const NAME: &'static str = "reload_device_config";
}

impl DaemonRequest for ReloadDeviceConfig {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<ReloadDeviceConfig>(packet) {
            match listener.config.reload_device_config(&request.serial_number) {
                Ok(_) => {
                    if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                        if !device.core.is_closed() {
                            if let Some(dvc_cfg) = listener.config.get_device_config(&request.serial_number) {
                                let wrapped_core = CoreHandle::wrap(device.core);

                                load_panels(&wrapped_core, make_panel_unique(dvc_cfg.layout));
                                wrapped_core.core().mark_for_redraw();
                            }
                        }
                    }

                    send_packet(handle, packet, &ReloadDeviceConfigResult::Reloaded).ok();
                },
                Err(err) => {
                    if let ConfigError::DeviceNotFound = err {
                        send_packet(handle, packet, &ReloadDeviceConfigResult::DeviceNotFound).ok();
                    } else {
                        log::error!("Error encountered while reloading config for {}: {:?}", request.serial_number, err);
                        send_packet(handle, packet, &ReloadDeviceConfigResult::ConfigError).ok();
                    }
                }
            }
        }
    }
}

/// Request for saving all device configs
#[derive(Serialize, Deserialize)]
pub enum SaveDeviceConfigsResult {
    /// Sent if error happened while saving configs
    ConfigError,

    /// Sent if successfully saved all configs
    Saved,
}

impl SocketData for SaveDeviceConfigsResult {
    const NAME: &'static str = "save_device_configs";
}

impl DaemonRequest for SaveDeviceConfigsResult {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if check_packet_for_data::<SaveDeviceConfigsResult>(packet) {
            match listener.config.save_device_configs() {
                Ok(_) => {
                    send_packet(handle, packet, &SaveDeviceConfigsResult::Saved).ok();
                },
                Err(err) => {
                    log::error!("Error encountered while saving configs: {:?}", err);
                    send_packet(handle, packet, &SaveDeviceConfigsResult::ConfigError).ok();
                }
            };
        }
    }
}

/// Request for saving device config for specific device
#[derive(Serialize, Deserialize)]
pub struct SaveDeviceConfig {
    pub serial_number: String,
}

/// Response of SaveDeviceConfig request
#[derive(Serialize, Deserialize)]
pub enum SaveDeviceConfigResult {
    /// Sent if error happened while saving config
    ConfigError,

    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully saved
    Saved,
}

impl SocketData for SaveDeviceConfig {
    const NAME: &'static str = "save_device_config";
}

impl SocketData for SaveDeviceConfigResult {
    const NAME: &'static str = "save_device_config";
}

impl DaemonRequest for SaveDeviceConfig {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<SaveDeviceConfig>(packet) {
            match listener.config.save_device_config(&request.serial_number) {
                Ok(_) => {
                    send_packet(handle, packet, &SaveDeviceConfigResult::Saved).ok();
                },
                Err(err) => {
                    if let ConfigError::DeviceNotFound = err {
                        send_packet(handle, packet, &SaveDeviceConfigResult::DeviceNotFound).ok();
                    } else {
                        log::error!("Error encountered while saving config for {}: {:?}", request.serial_number, err);
                        send_packet(handle, packet, &SaveDeviceConfigResult::ConfigError).ok();
                    }
                }
            }
        }
    }
}

/// Request for exporting device config for specific device
#[derive(Serialize, Deserialize)]
pub struct GetDeviceConfig {
    pub serial_number: String,
}

/// Response of GetDeviceConfig request
#[derive(Serialize, Deserialize)]
pub enum GetDeviceConfigResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully exported
    Config(DeviceConfig),
}

impl SocketData for GetDeviceConfig {
    const NAME: &'static str = "get_device_config";
}

impl SocketData for GetDeviceConfigResult {
    const NAME: &'static str = "get_device_config";
}

impl DaemonRequest for GetDeviceConfig {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<GetDeviceConfig>(packet) {
            if let Some(config) = listener.config.get_device_config(&request.serial_number) {
                send_packet(handle, packet, &GetDeviceConfigResult::Config(config)).ok();
            } else {
                send_packet(handle, packet, &GetDeviceConfigResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for exporting device config for specific device
#[derive(Serialize, Deserialize)]
pub struct ExportDeviceConfig {
    pub serial_number: String,
}

/// Response of ExportDeviceConfig request
#[derive(Serialize, Deserialize)]
pub enum ExportDeviceConfigResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully exported
    Exported(String),
}

impl SocketData for ExportDeviceConfig {
    const NAME: &'static str = "export_device_config";
}

impl SocketData for ExportDeviceConfigResult {
    const NAME: &'static str = "export_device_config";
}

impl DaemonRequest for ExportDeviceConfig {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<ExportDeviceConfig>(packet) {
            if let Some(config) = listener.config.get_device_config(&request.serial_number) {
                send_packet(handle, packet, &ExportDeviceConfigResult::Exported(serde_json::to_string(&config).unwrap())).ok();
            } else {
                send_packet(handle, packet, &ExportDeviceConfigResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for saving device config for specific device
#[derive(Serialize, Deserialize)]
pub struct ImportDeviceConfig {
    pub serial_number: String,
    pub config: String,
}

/// Response of ImportDeviceConfig request
#[derive(Serialize, Deserialize)]
pub enum ImportDeviceConfigResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if config was invalid
    InvalidConfig,

    /// Sent if config failed to save
    FailedToSave,

    /// Sent if successfully imported
    Imported,
}

impl SocketData for ImportDeviceConfig {
    const NAME: &'static str = "import_device_config";
}

impl SocketData for ImportDeviceConfigResult {
    const NAME: &'static str = "import_device_config";
}

impl DaemonRequest for ImportDeviceConfig {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<ImportDeviceConfig>(packet) {
            if let Ok(mut config) = serde_json::from_str::<DeviceConfig>(&request.config) {
                if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                    config.serial = device.serial.clone();
                    config.vid = device.vid;
                    config.pid = device.pid;

                    listener.config.set_device_config(&request.serial_number, config.clone());

                    match listener.config.save_device_config(&request.serial_number) {
                        Ok(_) => {
                            let wrapped_core = CoreHandle::wrap(device.core);

                            load_panels(&wrapped_core, make_panel_unique(config.layout));
                            wrapped_core.core().mark_for_redraw();

                            send_packet(handle, packet, &ImportDeviceConfigResult::Imported).ok();
                        }

                        Err(err) => {
                            match err {
                                ConfigError::IoError(_) | ConfigError::ParseError(_) => {
                                    send_packet(handle, packet, &ImportDeviceConfigResult::FailedToSave).ok();
                                }

                                ConfigError::DeviceNotFound => {
                                    send_packet(handle, packet, &ImportDeviceConfigResult::DeviceNotFound).ok();
                                }
                            }
                        }
                    }
                } else {
                    send_packet(handle, packet, &ImportDeviceConfigResult::DeviceNotFound).ok();
                }
            } else {
                send_packet(handle, packet, &ImportDeviceConfigResult::InvalidConfig).ok();
            }
        }
    }
}

/// Request for setting device's brightness
#[derive(Serialize, Deserialize)]
pub struct SetBrightness {
    pub serial_number: String,
    pub brightness: u8,
}

/// Response of SetBrightness request
#[derive(Serialize, Deserialize)]
pub enum SetBrightnessResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if brightness was successfully set
    Set,
}

impl SocketData for SetBrightness {
    const NAME: &'static str = "set_brightness";
}

impl SocketData for SetBrightnessResult {
    const NAME: &'static str = "set_brightness";
}

impl DaemonRequest for SetBrightness {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<SetBrightness>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                // Setting brightness
                let wrapped_core = CoreHandle::wrap(device.core);
                set_brightness(&wrapped_core, request.brightness);

                // Updating current device config
                if let Some(mut config) = listener.config.get_device_config(&request.serial_number) {
                    config.brightness = request.brightness;

                    listener.config.set_device_config(&request.serial_number, config);
                }

                send_packet(handle, packet, &SetBrightnessResult::Set).ok();
            } else {
                send_packet(handle, packet, &SetBrightnessResult::DeviceNotFound).ok();
            }
        }
    }
}

// Module management
/// Request for getting all loaded modules
#[derive(Serialize, Deserialize)]
pub struct ListModules {
    pub modules: Vec<PluginMetadata>
}

impl SocketData for ListModules {
    const NAME: &'static str = "list_modules";
}

impl DaemonRequest for ListModules {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if check_packet_for_data::<ListModules>(&packet) {
            let modules = listener.module_manager.get_module_list()
                .iter()
                .map(|m| m.metadata())
                .collect::<Vec<PluginMetadata>>();

            send_packet(handle, &packet, &ListModules {
                modules
            }).ok();
        }
    }
}

/// Request for getting all components defined by all modules
#[derive(Serialize, Deserialize)]
pub struct ListComponents {
    /// Hashmap of module name to component map
    pub components: HashMap<String, HashMap<String, ComponentDefinition>>
}

impl SocketData for ListComponents {
    const NAME: &'static str = "list_components";
}

impl DaemonRequest for ListComponents {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if check_packet_for_data::<ListComponents>(&packet) {
            let components = listener.module_manager.get_components_list_by_modules()
                .into_iter()
                .map(|(n, c)| (n, c.into_iter().collect()))
                .collect();

            send_packet(handle, packet, &ListComponents {
                components
            }).ok();
        }
    }
}

/// Request for adding components onto buttons
#[derive(Serialize, Deserialize)]
pub struct GetModuleValues {
    pub module_name: String,
}

/// Response of AddComponent request
#[derive(Serialize, Deserialize)]
pub enum GetModuleValuesResult {
    /// Sent if module wasn't found
    ModuleNotFound,

    /// Sent if module values were successfully retrieved
    Values(Vec<UIValue>),
}

impl SocketData for GetModuleValues {
    const NAME: &'static str = "get_module_values";
}

impl SocketData for GetModuleValuesResult {
    const NAME: &'static str = "get_module_values";
}

impl DaemonRequest for GetModuleValues {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<GetModuleValues>(packet) {
            for module in listener.module_manager.get_module_list() {
                if module.name() == request.module_name {
                    let values = module.settings();
                    send_packet(handle, packet, &GetModuleValuesResult::Values(values)).ok();
                    return;
                }
            }

            send_packet(handle, packet, &GetModuleValuesResult::ModuleNotFound).ok();
        }
    }
}

/// Request for adding components onto buttons
#[derive(Serialize, Deserialize)]
pub struct SetModuleValue {
    pub module_name: String,
    pub value: Vec<UIValue>,
}

/// Response of AddComponent request
#[derive(Serialize, Deserialize)]
pub enum SetModuleValueResult {
    /// Sent if module wasn't found
    ModuleNotFound,

    /// Sent if module value was successfully set
    Set
}

impl SocketData for SetModuleValue {
    const NAME: &'static str = "set_module_value";
}

impl SocketData for SetModuleValueResult {
    const NAME: &'static str = "set_module_value";
}

impl DaemonRequest for SetModuleValue {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<SetModuleValue>(packet) {
            for module in listener.module_manager.get_module_list() {
                if module.name() == request.module_name {
                    module.set_setting(request.value);
                    send_packet(handle, packet, &SetModuleValueResult::Set).ok();
                    return;
                }
            }

            send_packet(handle, packet, &SetModuleValueResult::ModuleNotFound).ok();
        }
    }
}

// Panel management
/// Request for getting current stack on a device
#[derive(Serialize, Deserialize)]
pub struct GetStack {
    pub serial_number: String
}

/// Response of GetStack request
#[derive(Serialize, Deserialize)]
pub enum GetStackResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully got stack
    Stack(Vec<RawButtonPanel>)
}

impl SocketData for GetStack {
    const NAME: &'static str = "get_stack";
}

impl SocketData for GetStackResult {
    const NAME: &'static str = "get_stack";
}

impl DaemonRequest for GetStack {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<GetStack>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                let mut raw_stack = vec![];

                for stack_item in get_stack(&wrapped_core) {
                    let raw_item = panel_to_raw(&stack_item);
                    raw_stack.push(raw_item);
                }

                send_packet(handle, packet, &GetStackResult::Stack(raw_stack)).ok();
            } else {
                send_packet(handle, packet, &GetStackResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for getting current screen on a device
#[derive(Serialize, Deserialize)]
pub struct GetCurrentScreen {
    pub serial_number: String
}

/// Response of GetCurrentScreen request
#[derive(Serialize, Deserialize)]
pub enum GetCurrentScreenResult {
    /// Sent if there's no screen
    NoScreen,

    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully got the stack
    Screen(RawButtonPanel)
}

impl SocketData for GetCurrentScreen {
    const NAME: &'static str = "get_current_screen";
}

impl SocketData for GetCurrentScreenResult {
    const NAME: &'static str = "get_current_screen";
}

impl DaemonRequest for GetCurrentScreen {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<GetCurrentScreen>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                if let Some(screen) = get_current_screen(&wrapped_core) {
                    send_packet(handle, packet, &GetCurrentScreenResult::Screen(panel_to_raw(&screen))).unwrap();
                } else {
                    send_packet(handle, packet, &GetCurrentScreenResult::NoScreen).ok();
                }
            } else {
                send_packet(handle, packet, &GetCurrentScreenResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for getting a button from current screen on a device
#[derive(Serialize, Deserialize)]
pub struct GetButton {
    pub serial_number: String,
    pub key: u8
}

/// Response of GetButton request
#[derive(Serialize, Deserialize)]
pub enum GetButtonResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if there's no button there
    NoButton,

    /// Sent if successfully got the button
    Button(Button)
}

impl SocketData for GetButton {
    const NAME: &'static str = "get_button";
}

impl SocketData for GetButtonResult {
    const NAME: &'static str = "get_button";
}

impl DaemonRequest for GetButton {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<GetButton>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                if let Some(button) = get_button(&wrapped_core, request.key) {
                    send_packet(handle, packet, &GetButtonResult::Button(button_to_raw(&button))).ok();
                } else {
                    send_packet(handle, packet, &GetButtonResult::NoButton).ok();
                }
            } else {
                send_packet(handle, packet, &GetButtonResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for setting a button on current screen on a device
#[derive(Serialize, Deserialize)]
pub struct SetButton {
    pub serial_number: String,
    pub key: u8,
    pub button: Button
}

/// Response of SetButton request
#[derive(Serialize, Deserialize)]
pub enum SetButtonResult {
    /// Sent if there's no screen to set to
    NoScreen,

    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully set the button
    Set
}

impl SocketData for SetButton {
    const NAME: &'static str = "set_button";
}

impl SocketData for SetButtonResult {
    const NAME: &'static str = "set_button";
}

impl DaemonRequest for SetButton {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<SetButton>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                if set_button(&wrapped_core, request.key, make_button_unique(request.button)) {
                    send_packet(handle, packet, &SetButtonResult::Set).ok();
                } else {
                    send_packet(handle, packet, &SetButtonResult::NoScreen).ok();
                }
            } else {
                send_packet(handle, packet, &SetButtonResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for clearing a button on current screen on a device
#[derive(Serialize, Deserialize)]
pub struct ClearButton {
    pub serial_number: String,
    pub key: u8,
}

/// Response of ClearButton request
#[derive(Serialize, Deserialize)]
pub enum ClearButtonResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if there's no screen, or there's no button to clear
    FailedToClear,

    /// Sent if successfully set the button
    Cleared
}

impl SocketData for ClearButton {
    const NAME: &'static str = "clear_button";
}

impl SocketData for ClearButtonResult {
    const NAME: &'static str = "clear_button";
}

impl DaemonRequest for ClearButton {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<ClearButton>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                if clear_button(&wrapped_core, request.key) {
                    send_packet(handle, packet, &ClearButtonResult::Cleared).ok();
                } else {
                    send_packet(handle, packet, &ClearButtonResult::FailedToClear).ok();
                }
            } else {
                send_packet(handle, packet, &ClearButtonResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for adding a new empty button
#[derive(Serialize, Deserialize)]
pub struct NewButton {
    pub serial_number: String,
    pub key: u8,
}

/// Response of NewButton request
#[derive(Serialize, Deserialize)]
pub enum NewButtonResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if button failed to be created on specified spot
    FailedToCreate,

    /// Sent if button was successfully created
    Created,
}

impl SocketData for NewButton {
    const NAME: &'static str = "new_button";
}

impl SocketData for NewButtonResult {
    const NAME: &'static str = "new_button";
}

impl DaemonRequest for NewButton {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<NewButton>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                if set_button(&wrapped_core, request.key, make_button_unique(Button::new())) {
                    send_packet(handle, packet, &NewButtonResult::Created).ok();
                } else {
                    send_packet(handle, packet, &NewButtonResult::FailedToCreate).ok();
                }
            } else {
                send_packet(handle, packet, &NewButtonResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for adding a new empty button
#[derive(Serialize, Deserialize)]
pub struct NewButtonFromComponent {
    pub serial_number: String,
    pub key: u8,
    pub component_name: String,
}

/// Response of NewButton request
#[derive(Serialize, Deserialize)]
pub enum NewButtonFromComponentResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if component wasn't found
    ComponentNotFound,

    /// Sent if button failed to be created on specified spot
    FailedToCreate,

    /// Sent if button was successfully created
    Created,
}

impl SocketData for NewButtonFromComponent {
    const NAME: &'static str = "new_button_from_component";
}

impl SocketData for NewButtonFromComponentResult {
    const NAME: &'static str = "new_button_from_component";
}

impl DaemonRequest for NewButtonFromComponent {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<NewButtonFromComponent>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                let map = listener.module_manager.get_components_list_by_modules();

                for (module_name, component_list) in map {
                    for (component_name, definition) in component_list {
                        if request.component_name == component_name {
                            let module = listener.module_manager.get_module(&module_name).unwrap();

                            let mut button = Button::new();
                            button.insert_component(definition.default_looks).ok();

                            module.add_component(wrapped_core.clone_for(&module), &mut button, &component_name);

                            if set_button(&wrapped_core, request.key, make_button_unique(button)) {
                                send_packet(handle, packet, &NewButtonFromComponentResult::Created).ok();
                            } else {
                                send_packet(handle, packet, &NewButtonFromComponentResult::FailedToCreate).ok();
                            }

                            return;
                        }
                    }
                }

                send_packet(handle, packet, &NewButtonFromComponentResult::ComponentNotFound).ok();
            } else {
                send_packet(handle, packet, &NewButtonFromComponentResult::DeviceNotFound).ok();
            }
        }
    }
}

// Components
/// Request for adding components onto buttons
#[derive(Serialize, Deserialize)]
pub struct AddComponent {
    pub serial_number: String,
    pub key: u8,
    pub component_name: String,
}

/// Response of AddComponent request
#[derive(Serialize, Deserialize)]
pub enum AddComponentResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if failed to add component
    FailedToAdd,

    /// Sent if component was successfully added
    Added,
}

impl SocketData for AddComponent {
    const NAME: &'static str = "add_component";
}

impl SocketData for AddComponentResult {
    const NAME: &'static str = "add_component";
}

impl DaemonRequest for AddComponent {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<AddComponent>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                if add_component(&wrapped_core, request.key, &request.component_name) {
                    send_packet(handle, packet, &AddComponentResult::Added).ok();
                } else {
                    send_packet(handle, packet, &AddComponentResult::FailedToAdd).ok();
                }
            } else {
                send_packet(handle, packet, &AddComponentResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for adding components onto buttons
#[derive(Serialize, Deserialize)]
pub struct GetComponentValues {
    pub serial_number: String,
    pub key: u8,
    pub component_name: String,
}

/// Response of AddComponent request
#[derive(Serialize, Deserialize)]
pub enum GetComponentValuesResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if failed to get component values
    FailedToGet,

    /// Sent if component values were successfully retrieved
    Values(Vec<UIValue>),
}

impl SocketData for GetComponentValues {
    const NAME: &'static str = "get_component_values";
}

impl SocketData for GetComponentValuesResult {
    const NAME: &'static str = "get_component_values";
}

impl DaemonRequest for GetComponentValues {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<GetComponentValues>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                let values = get_component_values(&wrapped_core, request.key, &request.component_name);

                if let Some(values) = values {
                    send_packet(handle, packet, &GetComponentValuesResult::Values(values)).ok();
                } else {
                    send_packet(handle, packet, &GetComponentValuesResult::FailedToGet).ok();
                }
            } else {
                send_packet(handle, packet, &GetComponentValuesResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for adding components onto buttons
#[derive(Serialize, Deserialize)]
pub struct SetComponentValue {
    pub serial_number: String,
    pub key: u8,
    pub component_name: String,
    pub value: Vec<UIValue>,
}

/// Response of AddComponent request
#[derive(Serialize, Deserialize)]
pub enum SetComponentValueResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if failed to set component parameter
    FailedToSet,

    /// Sent if component value was successfully set
    Set,
}

impl SocketData for SetComponentValue {
    const NAME: &'static str = "set_component_value";
}

impl SocketData for SetComponentValueResult {
    const NAME: &'static str = "set_component_value";
}

impl DaemonRequest for SetComponentValue {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<SetComponentValue>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                if set_component_value(&wrapped_core, request.key, &request.component_name, request.value) {
                    send_packet(handle, packet, &SetComponentValueResult::Set).ok();
                } else {
                    send_packet(handle, packet, &SetComponentValueResult::FailedToSet).ok();
                }
            } else {
                send_packet(handle, packet, &SetComponentValueResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for adding components onto buttons
#[derive(Serialize, Deserialize)]
pub struct RemoveComponent {
    pub serial_number: String,
    pub key: u8,
    pub component_name: String,
}

/// Response of AddComponent request
#[derive(Serialize, Deserialize)]
pub enum RemoveComponentResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if failed to remove component
    FailedToRemove,

    /// Sent if component value was successfully set
    Removed,
}

impl SocketData for RemoveComponent {
    const NAME: &'static str = "remove_component";
}

impl SocketData for RemoveComponentResult {
    const NAME: &'static str = "remove_component";
}

impl DaemonRequest for RemoveComponent {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<RemoveComponent>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                if remove_component(&wrapped_core, request.key, &request.component_name) {
                    send_packet(handle, packet, &RemoveComponentResult::Removed).ok();
                } else {
                    send_packet(handle, packet, &RemoveComponentResult::FailedToRemove).ok();
                }
            } else {
                send_packet(handle, packet, &RemoveComponentResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for pushing a new screen on a device
#[derive(Serialize, Deserialize)]
pub struct PushScreen {
    pub serial_number: String,
    pub screen: RawButtonPanel
}

/// Response of PushScreen request
#[derive(Serialize, Deserialize)]
pub enum PushScreenResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully pushed a screen
    Pushed
}

impl SocketData for PushScreen {
    const NAME: &'static str = "push_screen";
}

impl SocketData for PushScreenResult {
    const NAME: &'static str = "push_screen";
}

impl DaemonRequest for PushScreen {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<PushScreen>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                push_screen(&wrapped_core, make_panel_unique(request.screen));
                send_packet(handle, packet, &PushScreenResult::Pushed).ok();
            } else {
                send_packet(handle, packet, &PushScreenResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for popping top-most screen on a device
#[derive(Serialize, Deserialize)]
pub struct PopScreen {
    pub serial_number: String
}

/// Response of PopScreen request
#[derive(Serialize, Deserialize)]
pub enum PopScreenResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if current screen is the only one remaining
    OnlyOneRemaining,

    /// Sent if successfully popped a screen
    Popped
}

impl SocketData for PopScreen {
    const NAME: &'static str = "pop_screen";
}

impl SocketData for PopScreenResult {
    const NAME: &'static str = "pop_screen";
}

impl DaemonRequest for PopScreen {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<PopScreen>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let count = {
                    let stack = device.core.current_stack.lock().unwrap();
                    stack.len()
                };

                let wrapped_core = CoreHandle::wrap(device.core);

                if count > 1 {
                    pop_screen(&wrapped_core);
                    send_packet(handle, packet, &PopScreenResult::Popped).ok();
                } else {
                    send_packet(handle, packet, &PopScreenResult::OnlyOneRemaining).ok();
                }
            } else {
                send_packet(handle, packet, &PopScreenResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for popping top-most screen on a device, even if it's the only one remaining
#[derive(Serialize, Deserialize)]
pub struct ForciblyPopScreen {
    pub serial_number: String
}

/// Response of PopScreen request
#[derive(Serialize, Deserialize)]
pub enum ForciblyPopScreenResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully popped a screen
    Popped
}

impl SocketData for ForciblyPopScreen {
    const NAME: &'static str = "force_pop_screen";
}

impl SocketData for ForciblyPopScreenResult {
    const NAME: &'static str = "force_pop_screen";
}

impl DaemonRequest for ForciblyPopScreen {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<ForciblyPopScreen>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                pop_screen(&wrapped_core);
                send_packet(handle, packet, &ForciblyPopScreenResult::Popped).ok();
            } else {
                send_packet(handle, packet, &ForciblyPopScreenResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for replacing a screen on a device
#[derive(Serialize, Deserialize)]
pub struct ReplaceScreen {
    pub serial_number: String,
    pub screen: RawButtonPanel
}

/// Response of ReplaceScreen request
#[derive(Serialize, Deserialize)]
pub enum ReplaceScreenResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully replaced the screen
    Replaced
}

impl SocketData for ReplaceScreen {
    const NAME: &'static str = "replace_screen";
}

impl SocketData for ReplaceScreenResult {
    const NAME: &'static str = "replace_screen";
}

impl DaemonRequest for ReplaceScreen {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<ReplaceScreen>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                replace_screen(&wrapped_core, make_panel_unique(request.screen));
                send_packet(handle, packet, &ReplaceScreenResult::Replaced).ok();
            } else {
                send_packet(handle, packet, &ReplaceScreenResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for replacing a screen on a device
#[derive(Serialize, Deserialize)]
pub struct ResetStack {
    pub serial_number: String,
    pub screen: RawButtonPanel
}

/// Response of ReplaceScreen request
#[derive(Serialize, Deserialize)]
pub enum ResetStackResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully reset stack with a screen
    Reset
}

impl SocketData for ResetStack {
    const NAME: &'static str = "reset_stack";
}

impl SocketData for ResetStackResult {
    const NAME: &'static str = "reset_stack";
}

impl DaemonRequest for ResetStack {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<ResetStack>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                load_panels(&wrapped_core, make_panel_unique(request.screen));
                send_packet(handle, packet, &ResetStackResult::Reset).ok();
            } else {
                send_packet(handle, packet, &ResetStackResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for committing all changes of the stack to device config
#[derive(Serialize, Deserialize)]
pub struct CommitChangesToConfig {
    pub serial_number: String
}

/// Response of CommitChangesToConfig request
#[derive(Serialize, Deserialize)]
pub enum CommitChangesToConfigResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully committed changes
    Committed
}

impl SocketData for CommitChangesToConfig {
    const NAME: &'static str = "commit_changes";
}

impl SocketData for CommitChangesToConfigResult {
    const NAME: &'static str = "commit_changes";
}

impl DaemonRequest for CommitChangesToConfig {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<CommitChangesToConfig>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                let stack = save_panels(&wrapped_core);

                if let Some(mut config) = listener.config.get_device_config(&request.serial_number) {
                    config.layout = panel_to_raw(&stack);
                    listener.config.set_device_config(&request.serial_number, config);

                    send_packet(handle, packet, &CommitChangesToConfigResult::Committed).ok();
                } else {
                    send_packet(handle, packet, &CommitChangesToConfigResult::DeviceNotFound).ok();
                }
            } else {
                send_packet(handle, packet, &CommitChangesToConfigResult::DeviceNotFound).ok();
            }
        }
    }
}

/// Request for simulating a press on a button on current screen for a device
#[derive(Serialize, Deserialize)]
pub struct DoButtonAction {
    pub serial_number: String,
    pub key: u8,
}

/// Response of DoButtonAction request
#[derive(Serialize, Deserialize)]
pub enum DoButtonActionResult {
    /// Sent if device wasn't found
    DeviceNotFound,

    /// Sent if successfully activated a button
    Activated
}

impl SocketData for DoButtonAction {
    const NAME: &'static str = "do_button_action";
}

impl SocketData for DoButtonActionResult {
    const NAME: &'static str = "do_button_action";
}

impl DaemonRequest for DoButtonAction {
    fn process(listener: &DaemonListener, handle: SocketHandle, packet: &SocketPacket) {
        if let Ok(request) = parse_packet_to_data::<DoButtonAction>(packet) {
            if let Some(device) = listener.core_manager.get_device(&request.serial_number) {
                let wrapped_core = CoreHandle::wrap(device.core);

                button_action(&wrapped_core, request.key);
                send_packet(handle, packet, &DoButtonActionResult::Activated).ok();
            } else {
                send_packet(handle, packet, &DoButtonActionResult::DeviceNotFound).ok();
            }
        }
    }
}