-
Notifications
You must be signed in to change notification settings - Fork 1
/
73_MPD.pm
2598 lines (2278 loc) · 88.6 KB
/
73_MPD.pm
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
################################################################
#
# $Id: 73_MPD.pm 23900 2022-12-09 Beta-User + JensS fixes + database (forum #130801) $
#
# (c) 2014 Copyright: Wzut
# All rights reserved
#
# FHEM Forum : http://forum.fhem.de/index.php/topic,18517.msg400328.html#msg400328
#
# This code is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# The GNU General Public License can be found at
# http://www.gnu.org/copyleft/gpl.html.
# A copy is found in the textfile GPL.txt and important notices to the license
# from the author is found in LICENSE.txt distributed with these scripts.
# This script is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
################################################################
# Version 1.6 - 31.12.17 remove telnet, add BlockingInformParent
# Version 1.5 - 26.01.17 add playlist bookmarks, change XML to JSON
# Version 1.43 - 18.01.17 add channelUp and channelDown
# Version 1.42 - 15.01.17 add Cover and playlist_json
# Version 1.41 - 12.01.17 add rawTitle
# Version 1.4 - 11.01.17 add mute, ctp, seekcur, Fix LWP:: , album cover
# Version 1.32 - 03.01.17
# Version 1.31 - 30.12.16
# Version 1.3 - 14.12.16
# Version 1.2 - 10.04.16
# Version 1.1 - 03.02.16
# Version 1.01 - 18.08.14
# add set toggle command
# Version 1.0 - 21.02.14
# add german doc , readings & state times only on change, devStateIcon
# Version 0.95 - 17.02.14
# add command set IdleNow
# Version 0.9 - 15.02.14
# Version 0.8 - 01.02.14 , first version
package main;
use strict;
use warnings;
use Time::HiRes qw(gettimeofday);
use URI::Escape;
#use POSIX;
use Blocking; # http://www.fhemwiki.de/wiki/Blocking_Call
use IO::Socket;
use Getopt::Std;
use HttpUtils;
use HTML::Entities;
use Cwd 'abs_path';
use JSON;
sub MPD_html($);
my %gets = (
"music:noArg" => "",
"playlists:noArg" => "",
"playlistinfo:noArg" => "",
"statusRequest:noArg" => "",
"currentsong:noArg" => "",
"outputs:noArg" => "",
"bookmarks:noArg" => ""
);
my %sets = (
"play" => "",
"clear:noArg" => "",
"stop:noArg" => "",
"pause:noArg" => "",
"previous:noArg" => "",
"next:noArg" => "",
"random:noArg" => "",
"repeat:noArg" => "",
"volume:slider,0,1,100" => "",
"volumeUp:noArg" => "",
"volumeDown:noArg" => "",
"playlist" => "",
"playfile" => "",
"updateDb:noArg" => "",
"mpdCMD" => "",
"reset:noArg" => "",
"single:noArg" => "",
"IdleNow:noArg" => "",
"toggle:noArg" => "",
"clear_readings:noArg" => "",
"mute:on,off,toggle" => "",
"seekcur" => "",
"forward:noArg" => "",
"rewind:noArg" => "",
"channel" => "",
"channelUp:noArg" => "",
"channelDown:noArg" => "",
"save_bookmark:noArg" => "",
"load_bookmark" => "",
"active:noArg" => "",
"inactive:noArg" => "",
);
use constant clb => "command_list_begin\n";
use constant cle => "status\nstats\ncurrentsong\ncommand_list_end";
use constant lfm_artist => "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&format=json&api_key=";
use constant lfm_album => "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&format=json&api_key=";
my @Cover;
###################################
sub MPD_Initialize($)
{
my ($hash) = @_;
my $name = $hash->{NAME};
$hash->{GetFn} = "MPD_Get";
$hash->{SetFn} = "MPD_Set";
$hash->{DefFn} = "MPD_Define";
$hash->{UndefFn} = "MPD_Undef";
$hash->{ShutdownFn} = "MPD_Undef";
$hash->{AttrFn} = "MPD_Attr";
$hash->{AttrList} = "disable:0,1 password loadMusic:0,1 loadPlaylists:0,1 volumeStep:1,2,5,10 titleSplit:1,0 ".
"timeout waits stateMusic:0,1 statePlaylists:0,1 lastfm_api_key image_size:-1,0,1,2,3 ".
"cache artist_summary:0,1 artist_content:0,1 player:mpd,mopidy,forked-daapd ".
"unknown_artist_image bookmarkDir autoBookmark:0,1 seekStepThreshold seekStep seekStepSmall ".
"no_playlistcollection:0,1 ".$readingFnAttributes;
$hash->{FW_summaryFn} = "MPD_summaryFn";
}
sub MPD_updateConfig($)
{
# this routine is called 5 sec after the last define of a restart
# this gives FHEM sufficient time to fill in attributes
my ($hash) = @_;
my $name = $hash->{NAME};
if (!$init_done)
{
RemoveInternalTimer($hash);
InternalTimer(gettimeofday()+5,"MPD_updateConfig", $hash, 0);
return;
}
my $error;
$hash->{".playlist"} = "";
$hash->{".playlists"} = "";
$hash->{".musiclist"} = "";
$hash->{".music"} = "";
$hash->{".outputs"} = "";
$hash->{".lasterror"} = "";
$hash->{PRESENCE} = "absent";
$hash->{".volume"} = -1;
$hash->{".artist"} = "";
$hash->{".album"} = "";
$hash->{".playlist_crc"} = 0;
$hash->{helper}{playlistcollection}{val} = -1;
$hash->{".password"} = AttrVal($name, "password", "");
$hash->{TIMEOUT} = AttrVal($name, 'timeout', 0.7);
$hash->{".sMusicL"} = AttrVal($name, "stateMusic", 1);
$hash->{".sPlayL"} = AttrVal($name, "statePlaylists", 1);
$hash->{".apikey"} = AttrVal($name, "lastfm_api_key", "f3a26c7c8b4c4306bc382557d5c04ad5");
$hash->{".player"} = AttrVal($name, "player", "mpd");
delete($gets{"music:noArg"}) if ($hash->{".player"} eq "mopidy");
## kommen wir via reset Kommando ?
if ($hash->{".reset"})
{
$hash->{".reset"} = 0;
RemoveInternalTimer($hash);
if(defined($hash->{IPID}))
{
BlockingKill($hash->{helper}{RUNNING_PID});
Log3 $name,4, "$name, Idle Kill PID : ".$hash->{IPID};
delete $hash->{helper}{RUNNING_PID};
delete $hash->{IPID};
Log3 $name,4,"$name, Reset done";
}
}
return undef if (IsDisabled($name) == 3);
if (IsDisabled($name))
{
readingsSingleUpdate($hash,"state","disabled",1);
return undef;
}
MPD_ClearReadings($hash); # beim Starten etwas aufräumen
readingsBeginUpdate($hash);
readingsBulkUpdate($hash,"playlist_json","");
readingsBulkUpdate($hash,"playlist_num","-1");
readingsBulkUpdate($hash,"playlistname","");
readingsBulkUpdate($hash,"playlistinfo","");
readingsBulkUpdate($hash,"playlistcollection","");
readingsEndUpdate($hash,0);
MPD_Outputs_Status($hash);
mpd_cmd($hash, clb.cle) if ReadingsVal($name,'presence','none') ne 'absent';
if ($hash->{".volume"} eq "0")
{ # ist Mute aktiv oder soll sie mit Absicht 0 sein ?
# neuen Restore Wert zu Sicherheit erfinden
$hash->{"mute"} = 50;
}
else
{ # wir haben irgend eine Lautstärke
$hash->{"mute"} = -1;
if (ReadingsVal($name,"mute","on") eq "on")
{ # das passt so nicht zusammen !
readingsSingleUpdate($hash,"mute","off",1);
}
}
if ((AttrVal($name, "icon_size", -1) > -1) && (AttrVal($name, "cache", "") ne ""))
{
my $cache = AttrVal($name, "cache", "");
unless(-e ("./www/".$cache) or mkdir ("./www/".$cache))
{
#Verzeichnis anlegen gescheitert
Log3 $name,3,"$name, Could not create directory: www/$cache";
}
}
if (MPD_try_idle($hash))
{
# Playlisten und Musik Dir laden ?
# nicht bei Player mopidy, listall wird von ihm nicht unterstützt !
if ((AttrVal($name, 'loadMusic', '0') eq '1') && !$error && ($hash->{'.player'} ne 'mopidy')) # Beta-User: listall is deprecated on the MPD side, see docu at https://mpd.readthedocs.io/en/latest/protocol.html#the-music-database
{
$error = mpd_cmd($hash, "i|listall|music");
Log3 $name,3,"$name, error loading music -> $error" if ($error);
readingsSingleUpdate($hash,"last_error",$error,1) if ($error);
}
if ((AttrVal($name, "loadPlaylists", "1") eq "1") && !$error)
{
$error = mpd_cmd($hash, "i|listplaylists|playlists");
Log3 $name,3,"$name, error loading playlists -> $error" if ($error);
readingsSingleUpdate($hash,"last_error",$error,1) if ($error);
}
}
else { readingsSingleUpdate($hash,"state","error",1);}
return undef;
}
sub MPD_Define($$)
{
my ($hash, $def) = @_;
my $name = $hash->{NAME};
my @a = split("[ \t][ \t]*", $def);
return "Usage: define <name> $name [<MPD ip-address>] [<MPD port-nr>]" if(int(@a) > 4);
$hash->{HOST} = (defined($a[2])) ? $a[2] : "127.0.0.1";
$hash->{PORT} = (defined($a[3])) ? $a[3] : "6600" ;
$hash->{".reset"} = 0;
Log3 $name,3,"$name, Device defined.";
readingsSingleUpdate($hash,"state","defined",1);
$attr{$name}{devStateIcon} = 'play:rc_PLAY:stop stop:rc_STOP:play pause:rc_PAUSE:pause error:icoBlitz' unless (exists($attr{$name}{devStateIcon}));
$attr{$name}{icon} = 'it_radio' unless (exists($attr{$name}{icon}));
$attr{$name}{titleSplit} = '1' unless (exists($attr{$name}{titleSplit}));
$attr{$name}{player} = 'mpd' unless (exists($attr{$name}{player}));
$attr{$name}{loadPlaylists}= '1' unless (exists($attr{$name}{loadPlaylists}));
$attr{$name}{unknown_artist_image} = '/fhem/icons/1px-spacer' unless (exists($attr{$name}{unknown_artist_image}));
#$attr{$name}{cache} = 'lfm' unless (exists($attr{$name}{cache}));
#$attr{$name}{loadMusic} = '1' unless (exists($attr{$name}{loadMusic})) && ($attr{$name}{player} ne 'mopidy');
#DevIo_CloseDev($hash); das wird irgendwann auch mal kommen ... :)
$hash->{DeviceName} = $hash->{HOST}.":".$hash->{PORT};
RemoveInternalTimer($hash);
InternalTimer(gettimeofday()+5, "MPD_updateConfig", $hash, 0);
return undef;
}
sub MPD_Undef ($$)
{
my ($hash, $arg) = @_;
RemoveInternalTimer($hash);
if(defined($hash->{helper}{RUNNING_PID}))
{
BlockingKill($hash->{helper}{RUNNING_PID});
}
return undef;
}
sub MPD_Attr (@)
{
my ($cmd, $name, $attrName, $attrVal) = @_;
my $hash = $defs{$name};
my $error;
if ($cmd eq "set")
{
if ($attrName eq "timeout")
{
if (int($attrVal) < 1) {$attrVal = 1;}
$hash->{TIMEOUT} = $attrVal;
$_[3] = $attrVal;
}
elsif ($attrName eq "password")
{
$hash->{".password"} = $attrVal;
$_[3] = $attrVal;
}
elsif (($attrName eq "disable") && ($attrVal == 1))
{
readingsSingleUpdate($hash,"state","disabled",1);
$_[3] = $attrVal;
}
elsif (($attrName eq "disable") && ($attrVal == 0))
{
return if !$init_done;
$attr{$name}{disable} = $attrVal;
readingsSingleUpdate($hash,"state","reset",1);
$hash->{".reset"} = 1;
MPD_updateConfig($hash);
}
elsif ($attrName eq "statePlaylists")
{
$attr{$name}{statePlaylists} = $attrVal;
$hash->{".sPlayL"}=$attrVal;
}
elsif ($attrName eq "stateMusic")
{
$attr{$name}{stateMusic} = $attrVal;
$hash->{".sMusicL"}=$attrVal;
}
elsif ($attrName eq "player")
{
$attr{$name}{player} = $attrVal;
$hash->{".player"}=$attrVal;
}
elsif ($attrName eq "bookmarkDir")
{
my $abs_path = abs_path($attrVal);
unless(-e ($abs_path ) or mkdir ($abs_path ))
{
$error = "could not access or create bookmark directory $abs_path";
#Verzeichnis anlegen gescheitert
Log3 $name,3,"$name, error $error";
readingsSingleUpdate($hash,"last_error",$error,1);
return $error;
}
$_[3] = $abs_path; # Absoluten Pfad im Attribut speichern.
}
elsif ($attrName eq "cache")
{
unless(-e ("./www/".$attrVal) or mkdir ("./www/".$attrVal))
{
$error = "could not access or create directory: www/$attrVal";
#Verzeichnis anlegen gescheitert
Log3 $name,3,"$name, error $error";
readingsSingleUpdate($hash,"last_error",$error,1);
return $error;
}
$_[3] = $attrVal;
}
}
elsif ($cmd eq "del")
{
if ($attrName eq "disable")
{
$attr{$name}{disable} = 0;
readingsSingleUpdate($hash,"state","reset",1);
$hash->{".reset"}=1;
MPD_updateConfig($hash);
}
elsif ($attrName eq "statePlaylists") { $hash->{".sPlayL"} = 1; }
elsif ($attrName eq "stateMusic") { $hash->{".sMusicL"} = 1; }
elsif ($attrName eq "player") { $hash->{".player"} = "mpd"; }
}
return undef;
}
sub MPD_ClearReadings($)
{
my ($hash)= @_;
readingsBeginUpdate($hash);
if ($hash->{".player"} eq "forked-daapd")
{
readingsBulkUpdate($hash,"albumartistsort","");
readingsBulkUpdate($hash,"artistsort","");
}
#readingsBulkUpdate($hash,"albumartist","");
readingsBulkUpdate($hash,"Album","");
readingsBulkUpdate($hash,"Artist","");
readingsBulkUpdate($hash,"file","");
readingsBulkUpdate($hash,"Genre","");
readingsBulkUpdate($hash,"Last-Modified","");
readingsBulkUpdate($hash,"Title","");
readingsBulkUpdate($hash,"Name","");
readingsBulkUpdate($hash,"Date","");
readingsBulkUpdate($hash,"Track","");
readingsBulkUpdate($hash,"Cover","");
readingsBulkUpdate($hash,"artist_summary","") if (AttrVal($hash->{NAME}, "artist_summary",""));
readingsBulkUpdate($hash,"artist_content","") if (AttrVal($hash->{NAME}, "artist_content",""));
readingsEndUpdate($hash, 1);
return;
}
sub MPD_Set($@)
{
my ($hash, @a)= @_;
my $name= $hash->{NAME};
my $ret ;
my $channel_cmd = 0;
my $val;
return join(" ", sort keys %sets) if(@a < 2);
my $cmd = $a[1];
if ($cmd eq "active")
{
readingsSingleUpdate($hash, "state", "active", 1);
$hash->{".reset"} = 1;
MPD_updateConfig($hash);
return undef;
}
return "active" if(IsDisabled($name));
return join(" ", sort keys %sets) if ($cmd eq "?");
if ($cmd eq "mpdCMD")
{
my $sub;
shift @a;
shift @a;
$sub = join (" ", @a);
return $name." ".$sub.":\n".mpd_cmd($hash, "i|$sub|x");
}
my $subcmd = (defined($a[2])) ? $a[2] : "";
return undef if ($subcmd eq '---'); # erster Eintrag im select Feld ignorieren
my $step = int(AttrVal($name, 'volumeStep', 5)); # vllt runtersetzen auf default = 2 ?
my $vol_now = $hash->{'.volume'} // 0;
$vol_now = int($vol_now);
my $vol_new;
if ($cmd eq "reset") { $hash->{".reset"} = 1; MPD_updateConfig($hash); return undef;}
if ($cmd eq "pause") { $ret = mpd_cmd($hash, clb."pause\n".cle); return $ret; }
if ($cmd eq "update") { $ret = mpd_cmd($hash, clb."update\n".cle); return $ret; }
if ($cmd eq "stop")
{
readingsBeginUpdate($hash);
readingsBulkUpdate($hash,"artist_image",AttrVal($name,"unknown_artist_image","/fhem/icons/1px-spacer"));
readingsBulkUpdate($hash,"artist_image_html","");
readingsBulkUpdate($hash,"album_image",AttrVal($name,"unknown_artist_image","/fhem/icons/1px-spacer"));
readingsBulkUpdate($hash,"album_image_html","");
readingsBulkUpdate($hash,"audio","");
readingsBulkUpdate($hash,"bitrate","");
readingsBulkUpdate($hash,"rawTitle","");
readingsBulkUpdate($hash,"Album","");
readingsBulkUpdate($hash,"Track","");
readingsBulkUpdate($hash,"Cover","");
readingsBulkUpdate($hash,"elapsed","");
readingsEndUpdate($hash, 1);
$ret = mpd_cmd($hash, clb."stop\n".cle);
return $ret;
}
if ($cmd eq "toggle")
{
$ret = mpd_cmd($hash, clb."play\n".cle) if (($hash->{STATE} eq "stop") || ($hash->{STATE} eq "pause"));
if ($hash->{STATE} eq "play")
{
readingsBeginUpdate($hash);
readingsBulkUpdate($hash,"artist_image",AttrVal($name,"unknown_artist_image","/fhem/icons/1px-spacer"));
readingsBulkUpdate($hash,"artist_image_html","");
readingsBulkUpdate($hash,"album_image",AttrVal($name,"unknown_artist_image","/fhem/icons/1px-spacer"));
readingsBulkUpdate($hash,"album_image_html","");
readingsBulkUpdate($hash,"Cover","");
readingsEndUpdate($hash, 1);
$ret = mpd_cmd($hash, clb."stop\n".cle);
}
}
if ($cmd eq "previous")
{
if (ReadingsNum($name,"song",0) > 0)
{
MPD_ClearReadings($hash);
return mpd_cmd($hash, clb."previous\n".cle);
}
else { return undef; }
}
if ($cmd eq "next")
{
if (ReadingsNum($name,"nextsong",0) != ReadingsNum($name,"song",0))
{
MPD_ClearReadings($hash);
return mpd_cmd($hash, clb."next\n".cle);
}
else { return undef; }
}
if ($cmd eq "random")
{
$val = (ReadingsNum($name,"random",0)) ? "0" : "1";
$ret = mpd_cmd($hash, clb."random $val\n".cle);
}
if ($cmd eq "repeat")
{
$val = (ReadingsNum($name,"repeat",0)) ? "0" : "1";
$ret = mpd_cmd($hash, clb."repeat $val\n".cle);
}
if ($cmd eq "single")
{
$val = (ReadingsNum($name,"single",0)) ? "0" : "1";
$ret = mpd_cmd($hash, clb."single $val\n".cle);
}
if ($cmd eq "clear")
{
MPD_ClearReadings($hash);
$ret = mpd_cmd($hash, clb."clear\n".cle);
$hash->{".music"} = "";
$hash->{".playlist"} = "";
}
if ($cmd eq "volume")
{
if (int($subcmd) > 100) { $vol_new = "100"; }
elsif (int($subcmd) < 0) { $vol_new = "0"; }
else { $vol_new = $subcmd; }
# sollte nun zwischen 0 und 100 sein
}
if ($cmd eq "volumeUp") { $vol_new = (($vol_now + $step) <= 100) ? $vol_now+$step : "100"; }
if ($cmd eq "volumeDown") { $vol_new = (($vol_now - $step) >= 0) ? $vol_now-$step : " 0"; }
if ($cmd eq "mute")
{
my $mute_state = ReadingsVal($name,"mute","");
my $mute = $mute_state;
if (($subcmd eq "on") && ($mute_state eq "off")){ $vol_new = "0"; $hash->{"mute"} = $vol_now; $mute="on"; }
elsif (($subcmd eq "off") && ($mute_state eq "on")) { $vol_new = $hash->{"mute"}; $hash->{"mute"} = -1; $mute="off"; }
elsif ($subcmd eq "toggle")
{
if ($mute_state eq "on") { $vol_new = $hash->{"mute"}; $hash->{"mute"} = -1; $mute="off";}
elsif ($mute_state eq "off") { $vol_new = "0"; $hash->{"mute"} = $vol_now; $mute="on";}
}
readingsSingleUpdate($hash,"mute",$mute,1);
}
# muessen wir die Laustärke verändern ?
if (defined($vol_new))
{
$ret = mpd_cmd($hash, clb."setvol $vol_new\n".cle);
}
# einfaches Play bzw Play Listenplatz Nr. ?
if ($cmd eq "play")
{
MPD_ClearReadings($hash);
$ret = mpd_cmd($hash,clb."play $subcmd\n".cle);
}
if (($cmd eq "forward") || ($cmd eq "rewind"))
{
my ($elapsed,$total) = split (":",ReadingsVal($name,"time",""));
$total=int($total);
return undef if( !defined($total) || $total <= 0);
my $percent = $elapsed / $total;
my $step = 0.01*(0.01*AttrVal($name,"seekStepThreshold",0) > $percent ? AttrVal($name,"seekStepSmall",3) : AttrVal($name,"seekStep",7));
$percent +=$step if $cmd eq "forward";
$percent -=$step if $cmd eq "rewind";
$percent = 0 if $percent < 0;
$percent = 0.99 if $percent > 0.99;
$cmd = "seekcur";
$subcmd=int($percent*$total);
}
if ($cmd eq "seekcur")
{
if ((int($hash->{SUBVERSION}) < 20) && (AttrVal($name,"player","mpd") eq "mpd"))
{
$ret = "command $cmd needs a MPD version of 0.20.0 or greater ! (is ".$hash->{VERSION}.")";
Log3 $name,3,"$name, $ret";
readingsSingleUpdate($hash,"last_error",$ret,1);
}
else
{
if($subcmd=~/^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$/) # Matches valid time given as [[hh:]mm:]ss
{
$subcmd=(defined($1) ? $1 : 0)*3600+(defined($2) ? $2 : 0)*60+$3; # Sekunden ausrechnen
}
else { $subcmd--; $subcmd++; } # sicherstellen das subcmd numerisch ist
if ( $subcmd > 0 )
{ $ret = mpd_cmd($hash,clb."seekcur $subcmd\n".cle) ; } # ungetestet !
else { $ret = undef; }
}
}
if ($cmd eq "IdleNow")
{
return "$name: sorry, a Idle process is always running with pid ".$hash->{IPID} if(defined($hash->{IPID}));
MPD_try_idle($hash);
return undef;
}
if ($cmd eq "clear_readings")
{
MPD_ClearReadings($hash);
return undef;
}
# die ersten beiden brauchen wir nicht mehr
shift @a;
shift @a;
# den Rest als ein String
$subcmd = join(" ",@a);
if ($cmd eq "save_bookmark")
{
return "unknown playlist !" if ($hash->{".playlist"} eq "");
return "you can't save bookmarks on unknown playlists or radio streams !" if (ReadingsVal($name,"currentTrackProvider","Radio") eq "Radio");
my $bm_dir = AttrVal($name, "bookmarkDir","");
return "please set attribute bookmarkDir first, saving is disabled !" if ($bm_dir eq "");
my $state;
$state->{playlistname} = $hash->{".playlist"};
$state->{songnumber} = ReadingsNum($name,"Pos",0);
$state->{songposition} = ReadingsVal($name,"time","")=~/^(\d+):\d+$/ ? $1 : 0; # get elapsed seconds from time reading
my $fname = $hash->{".playlist"};
#$fname =~ s/[^A-Za-z0-9\-\.]//g; # ensure to use only valid characters for filenames
$fname = $bm_dir."/".$fname;
if (!open (FILE , "> ".$fname))
{
$ret = "save_bookmark error saving $fname : ".$!;
readingsSingleUpdate($hash,"last_error",$ret,1);
Log3 $name, 2, "$name, $ret";
}
else
{
print FILE encode_json($state);
close(FILE);
Log3 $name, 4, "$name, save_bookmark ".$subcmd."saved bookmark $fname";
}
if ($ret)
{
Log3 $name, 3, "$name, $ret";
readingsSingleUpdate($hash,"last_error",$ret,1);
return $ret ;
}
}
if ($cmd eq "load_bookmark")
{
return "unknown playlist" if (($hash->{".playlist"} eq "") && ($subcmd eq ""));
return "you can't load bookmarks for radio streams !" if ((ReadingsVal($name,"currentTrackProvider","Radio") eq "Radio") && ($subcmd eq ""));
my $bm_dir = AttrVal($name, "bookmarkDir","");
return format_get_output("Get Bookmark","attribute bookmarkDir not set, loading disabled") if ($bm_dir eq "");
my $state;
my $data;
my $fname = ($subcmd eq "") ? $hash->{".playlist"} : $subcmd;
#$fname =~ s/[^A-Za-z0-9\-\.]//g; # ensure to use only valid characters for filenames
$fname = $bm_dir."/".$fname;
if (-e $fname) # gibt es überhaupt eine Bookmark ?
{
if (!open (FILE , $fname))
{
$ret = "error reading $fname: ".$!;
Log3 $name, 4, "$name, $ret";
readingsSingleUpdate($hash,"last_error",$ret,1);
}
else
{
while(<FILE>){ $data = $data.$_;}
close (FILE);
eval { $state = decode_json($data); 1; } or do
{
$ret = "invalid content in playlist bookmark file";
Log3 $name, 2, "$name, $ret";
readingsSingleUpdate($hash,"last_error",$ret,1);
};
}
if (!$ret) # bis jetzt wohl ohne Fehler ...
{
$state->{songnumber} += 0; # ensure it is numeric
$state->{songposition}+= 0;
# wechsele auf die neue Playliste ?
Log3 $name, 4, "$name, load_bookmark $fname - Song:".$state->{songnumber}." - Pos:".$state->{songposition};
if ($subcmd ne "")
{
$subcmd = $state->{playlistname}."|".$state->{songnumber}."|".$state->{songposition};
$cmd = "playlist";
Log3 $name, 4, "$name, load_bookmark new cmd -> playlist ".$subcmd;
}
else
{
Log3 $name, 4, "$name, load_bookmark new cmd -> play & seekcur";
$ret = mpd_cmd($hash,"play ".$state->{songnumber});
$ret .= mpd_cmd($hash,"seekcur ".$state->{songposition}) if (($state->{songposition} > 9) && (int($hash->{SUBVERSION}) > 19));
}
}
} else { $ret = "no bookmark $fname found"; }
if ($ret)
{
Log3 $name, 3, "$name, $ret";
readingsSingleUpdate($hash,"last_error",$ret,1);
return $ret ;
}
}
if ($cmd eq "channel")
{
if ( $subcmd <= $hash->{helper}{playlistcollection}{val})
{
$cmd = "playlist";
$subcmd = $hash->{helper}{playlistcollection}{$subcmd};
$channel_cmd = 1;
}
}
if ($cmd eq "channelUp")
{
my $i = ReadingsNum($name,"playlist_num",-1);
$i++;
if ($i <= $hash->{helper}{playlistcollection}{val})
{
$cmd = "playlist";
$subcmd = $hash->{helper}{playlistcollection}{$i};
$channel_cmd = 1;
}
}
if ($cmd eq "channelDown")
{
my $i = ReadingsNum($name,"playlist_num",0);
$i--;
if ($i > -1)
{
$cmd = "playlist";
$subcmd = $hash->{helper}{playlistcollection}{$i};
$channel_cmd = 1;
}
}
if ($cmd eq "playlist")
{
return "$name : no playlist name !" if (!$subcmd);
my ($list,$song,$pos) = split("\\|",$subcmd);
$song = "0" if (!$song);
$pos = "0" if (!$pos);
my $error;
my $nr = -1;
# ToDo : prüfen ob es Liste überhaupt gibt !
# nicht schön aber vermeidet den Fehler
# PERL WARNING: main::MPD_Set() called too early to check prototype at ./FHEM/73_MPD.pm line 771, <$fh> line 412
MPD_SaveBookmark($hash) if(AttrVal($name,"autoBookmark","0") eq "1");
MPD_ClearReadings($hash);
$hash->{".music"} = "";
$hash->{".playlist"} = $list; # interne Playlisten Verwaltung
readingsSingleUpdate($hash,"playlistname",$subcmd,1);
$ret = mpd_cmd($hash, clb."stop\nclear\nload \"$list\"\nplay $song\n".cle);
if (int($pos > 9))
{
$ret .= mpd_cmd($hash,"seekcur ".$pos) if (int($hash->{SUBVERSION}) > 19);
}
# welche Listen Nr ?
for (my $i=0; $i <= $hash->{helper}{playlistcollection}{val}; $i++)
{
$nr = $i if ($hash->{helper}{playlistcollection}{$i} eq $subcmd);
}
readingsSingleUpdate($hash,"playlist_num",$nr,1) if ($nr > -1);
my $json = ReadingsVal($name,"playlist_json","");
if ($json ne "")
{
undef(@Cover);
my $result;
eval {
$result = decode_json($json);
1;
} or do
{
$error = "invalid playlist_json: $json";
Log3 $name, 3, "$name, $error";
readingsSingleUpdate($hash,"last_error",$error,1);
return $error;
};
foreach (@$result)
{
push(@Cover, $_->{'Cover'});
Log3 $name, 5, "$name, Cover : ".$_->{'Cover'};
}
}
return $ret;
}
if ($cmd eq "playfile")
{
return "$name, no File !" if (!$subcmd);
MPD_ClearReadings($hash);
$hash->{".playlist"} = "";
readingsSingleUpdate($hash,"playlistname","",1);
$hash->{".music"} = $subcmd; # interne Song Verwaltung
$ret = mpd_cmd($hash, clb."stop\nclear\nadd \"$subcmd\"\nplay\n".cle);
}
if ($cmd eq "updateDb")
{
$ret = mpd_cmd($hash, clb."rescan\n".cle);
}
if ($cmd eq "inactive")
{
mpd_cmd($hash, clb."stop\nclear\n".cle);
MPD_ClearReadings($hash);
readingsSingleUpdate($hash, "state", "inactive", 1);
$hash->{STATE} = "inactive";
$hash->{".reset"} = 1;
MPD_updateConfig($hash);
return undef;
}
if (substr($cmd,0,13) eq "outputenabled")
{
my $oid = substr($cmd,13);
if ($subcmd eq "1")
{
$ret = mpd_cmd($hash, "i|enableoutput $oid|x");
Log3 $name , 5, "$name, enableoutput $oid | $subcmd";
}
else
{
$ret = mpd_cmd($hash, "i|disableoutput $oid|x");
Log3 $name , 5 ,"$name, disableoutput $oid | $subcmd";
}
MPD_Outputs_Status($hash);
}
return $ret;
}
sub MPD_Get($@)
{
my ($hash, @a)= @_;
my $name= $hash->{NAME};
my $ret;
my $cmd;
return "get $name needs at least one argument" if(int(@a) < 2);
$cmd = $a[1];
return(MPD_html($hash)) if ($cmd eq "webrc");
return "no get cmd on a disabled device !" if(IsDisabled($name));
if ($cmd eq "playlists")
{
$hash->{".playlists"} = "";
#mpd_cmd($hash, "i|lsinfo|playlists");
mpd_cmd($hash, "i|listplaylists|playlists");
return format_get_output("Playlists",$hash->{".playlists"});
}
if ($cmd eq "music")
{
return "Command is not supported by player mopidy !" if ($hash->{".player"} eq "mopidy");
$hash->{".musiclist"} = "";
mpd_cmd($hash, "i|listall|music");
return format_get_output("Music",$hash->{".musiclist"});
}
if ($cmd eq "statusRequest")
{
mpd_cmd($hash, clb.cle);
$ret = mpd_cmd($hash, "i|".clb.cle."|x|s");
return format_get_output("Status Request", $ret) if($ret);
return undef;
}
if ($cmd eq "bookmarks")
{
my $bm_dir = AttrVal($name, "bookmarkDir","");
return format_get_output("Get Bookmarks","attribute bookmarkDir not set !") if ($bm_dir eq "");
opendir(DIR,$bm_dir);
while(my $d = readdir(DIR)) {$ret .= $d."\n" if (($d ne "..") && ($d ne "."));}
closedir(DIR);
return format_get_output("Get Bookmarks",$ret) if($ret);
return undef;
}
if ($cmd eq "outputs")
{
MPD_Outputs_Status($hash);
return format_get_output("Outputs", $hash->{".outputs"});
}
return format_get_output("Current Song", mpd_cmd($hash, "i|currentsong|x")) if ($cmd eq "currentsong");
return format_get_output("Playlist Info",mpd_cmd($hash, "i|playlistinfo|x")) if ($cmd eq "playlistinfo");
return "$name get with unknown argument $cmd, choose one of " . join(" ", sort keys %gets);
}
sub format_get_output($$)
{
my ($head,$ret)= @_;
my $width = 10;
my @arr = split("\n",$ret);
#my @sort = sort(@arr);
foreach(@arr) { $width = length($_) if(length($_) > $width); }
return $head."\n".("-" x $width)."\n".$ret;
}
sub MPD_Outputs_Status($)
{
my ($hash)= @_;
my $name = $hash->{NAME};
return if ReadingsVal($name,'presence','none') eq 'absent';
$hash->{".outputs"} = mpd_cmd($hash, "i|outputs|x");
my @outp = split("\n" , $hash->{".outputs"});
readingsBeginUpdate($hash);
my $outpid = "0";
foreach (@outp)
{
my @val = split(": " , $_);
next if !defined $val[1];
Log3 $name, 4 ,"$name, MPD_Outputs_Status -> $val[0] = $val[1]";
$outpid = ($val[0] eq "outputid") ? $val[1] : $outpid;
readingsBulkUpdate($hash,$val[0].$outpid,$val[1]) if ($val[0] ne "outputid");
$sets{$val[0].$outpid.":0,1"} = "" if ($val[0] eq "outputenabled");
}
readingsEndUpdate($hash, 1);
}
sub mpd_cmd($$)
{
my ($hash,$a)= @_;
my $output = "";
my $sp1;
my $sp2;
my $artist;
my $album;
my $name_ = "";
my $title = "";
my $exot = "";
my $rawTitle;