96_SIP.pm 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975
  1. ###############################################################################
  2. #
  3. # $Id: 96_SIP.pm 15354 2017-10-30 13:41:59Z Wzut $
  4. # 96_SIP.pm
  5. # Based on FB_SIP from werner.meines@web.de
  6. #
  7. # Forum : https://forum.fhem.de/index.php/topic,67443.0.html
  8. #
  9. ###############################################################################
  10. #
  11. # (c) 2017 Copyright: Wzut & plin
  12. # All rights reserved
  13. #
  14. # This script is free software; you can redistribute it and/or modify
  15. # it under the terms of the GNU General Public License as published by
  16. # the Free Software Foundation; either version 2 of the License, or
  17. # (at your option) any later version.
  18. #
  19. # The GNU General Public License can be found at
  20. # http://www.gnu.org/copyleft/gpl.html.
  21. # A copy is found in the textfile GPL.txt and imPORTant notices to the license
  22. # from the author is found in LICENSE.txt distributed with these scripts.
  23. #
  24. # This script is distributed in the hope that it will be useful,
  25. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. # GNU General Public License for more details.
  28. #
  29. ##################################################################################
  30. #######################################################################
  31. # need: Net::SIP (cpan install Net::SIP)
  32. #
  33. #
  34. # convert audio to PCM 8000 :
  35. # sox <file>.wav -t raw -r 8000 -c 1 -e a-law <file>.alaw
  36. # oder
  37. # sox <file> -r 8000 -c 1 -e a-law <file>.wav
  38. #
  39. ########################################################################
  40. package main;
  41. use strict;
  42. use warnings;
  43. use POSIX qw( strftime );
  44. use Net::SIP qw//;
  45. use Net::SIP::Packet;
  46. use IO::Socket;
  47. use Socket;
  48. use Net::Domain qw(hostname hostfqdn);
  49. use Blocking; # http://www.fhemwiki.de/wiki/Blocking_Call
  50. #use Data::Dumper;
  51. my $sip_version ="V1.61 / 30.10.17";
  52. my $ua; # SIP user agent
  53. my @fifo;
  54. my %sets = (
  55. "call" => "",
  56. "listen:noArg" => "",
  57. "reject:noArg" => "",
  58. "reset:noArg" => "",
  59. "fetch:noArg" => "",
  60. "password" => ""
  61. );
  62. sub SIP_Initialize($$)
  63. {
  64. my ($hash) = @_;
  65. $hash->{DefFn} = "SIP_Define";
  66. $hash->{UndefFn} = "SIP_Undef";
  67. $hash->{ShutdownFn} = "SIP_Undef";
  68. $hash->{SetFn} = "SIP_Set";
  69. $hash->{GetFn} = "SIP_Get";
  70. $hash->{NotifyFn} = "SIP_Notify";
  71. $hash->{AttrFn} = "SIP_Attr";
  72. $hash->{AttrList} = "sip_watch_listen ". #
  73. "sip_ringtime ". #
  74. "sip_waittime ". #
  75. "sip_ip ". #
  76. "sip_port ". #
  77. "sip_user ". #
  78. "sip_registrar ". #
  79. "sip_from ". #
  80. "sip_call_audio_delay:0,0.25,0.5,0.75,1,1.25,1.5,1.75,2,2.25,2.5,2.75,3 ". #
  81. "sip_audiofile_call ". #
  82. "sip_audiofile_dtmf ". #
  83. "sip_audiofile_ok ". #
  84. "sip_audiofile_wfp ". # CE
  85. "sip_dtmf_size:1,2,3,4 ". #
  86. "sip_dtmf_send:audio,rfc2833 ". #
  87. "sip_dtmf_loop:once,loop ". #
  88. "sip_listen:none,dtmf,wfp,echo ". #
  89. "sip_filter ". #
  90. "sip_blocking ". #
  91. "sip_elbc:yes,no ". #
  92. "sip_force_interval ". #
  93. "T2S_Device ". #
  94. "T2S_Timeout ". #
  95. "audio_converter:sox,ffmpeg ". #
  96. "disabled:0,1 ".$readingFnAttributes;
  97. }
  98. sub SIP_Define($$)
  99. {
  100. my ($hash, $def) = @_;
  101. my @a = split("[ \t][ \t]*", $def);
  102. my $name = shift @a;
  103. my $addr = "0.0.0.0";
  104. $hash->{STATE} = "defined";
  105. $hash->{VERSION} = $sip_version;
  106. $hash->{NOTIFYDEV} = "global";
  107. $hash->{".reset"} = 0;
  108. $attr{$name}{sip_ringtime} = '3' unless (exists($attr{$name}{sip_ringtime}));
  109. $attr{$name}{sip_user} = '620' unless (exists($attr{$name}{sip_user}));
  110. $attr{$name}{sip_registrar} = 'fritz.box' unless (exists($attr{$name}{sip_registrar}));
  111. $attr{$name}{sip_listen} = 'none' unless (exists($attr{$name}{sip_listen}));
  112. $attr{$name}{sip_dtmf_size} = '2' unless (exists($attr{$name}{sip_dtmf_size}));
  113. $attr{$name}{sip_dtmf_loop} = 'once' unless (exists($attr{$name}{sip_dtmf_loop}));
  114. $attr{$name}{sip_dtmf_send} = 'audio' unless (exists($attr{$name}{sip_dtmf_send}));
  115. $attr{$name}{sip_elbc} = 'yes' unless (exists($attr{$name}{sip_elbc}));
  116. $attr{$name}{sip_from} = 'sip:'.$attr{$name}{sip_user}.'@'.$attr{$name}{sip_registrar} unless (exists($attr{$name}{sip_from}));
  117. unless (exists($attr{$name}{sip_ip}))
  118. {
  119. eval { $addr = inet_ntoa(scalar(gethostbyname(hostfqdn()))); };
  120. if ($@)
  121. {
  122. Log3 $name,2,"$name, please check your FQDN hostname -> $@";
  123. eval { $addr = inet_ntoa(scalar(gethostbyname(hostname()))); };
  124. Log3 $name,2,"$name, please check your hostname -> ".$@ if ($@);
  125. }
  126. $attr{$name}{sip_ip} = $addr;
  127. }
  128. RemoveInternalTimer($hash);
  129. InternalTimer(gettimeofday()+5, "SIP_updateConfig", $hash);
  130. return undef;
  131. }
  132. sub SIP_Notify($$)
  133. {
  134. # $hash is my hash, $dev_hash is the hash of the changed device
  135. my ($hash, $dev_hash) = @_;
  136. my $events = deviceEvents($dev_hash,0);
  137. return undef if ($dev_hash->{NAME} ne AttrVal($hash->{NAME},"T2S_Device",""));
  138. my $val = ReadingsVal($dev_hash->{NAME},"lastFilename","");
  139. return undef if ((!$val) || (index(@{$events}[0],"lastFilename") == -1));
  140. if (defined($hash->{audio1}) ||
  141. defined($hash->{audio2}) ||
  142. defined($hash->{audio3}) ||
  143. (defined($hash->{callnr}) && defined($hash->{ringtime})))
  144. { SIP_wait_for_t2s($hash);}
  145. return undef;
  146. }
  147. sub SIP_Attr (@)
  148. {
  149. my ($cmd, $name, $attrName, $attrVal) = @_;
  150. my $hash = $defs{$name};
  151. #Log3 $name,5,"$name , SIP_Attr : $cmd, $attrName, $attrVal";
  152. if ($cmd eq "set")
  153. {
  154. if (substr($attrName ,0,4) eq "sip_")
  155. {
  156. $_[3] = $attrVal;
  157. $hash->{".reset"} = 1 if defined($hash->{LPID});
  158. }
  159. elsif (($attrName eq "disable") && ($attrVal == 1))
  160. {
  161. readingsSingleUpdate($hash,"state","disabled",1);
  162. $_[3] = $attrVal;
  163. $hash->{".reset"} = 1 if defined($hash->{LPID});
  164. }
  165. elsif ($attrName eq "audio_converter")
  166. {
  167. my $res = qx(which $attrVal);
  168. $res =~ s/\n//;
  169. $hash->{AC} = ($res) ? $res : undef;
  170. }
  171. elsif ($attrName eq "T2S_Device")
  172. {
  173. $_[3] = $attrVal;
  174. $hash->{NOTIFYDEV} = $attrVal;
  175. }
  176. }
  177. elsif ($cmd eq "del")
  178. {
  179. if (substr($attrName,0,4) eq "sip_")
  180. {
  181. $_[3] = $attrVal;
  182. $hash->{".reset"} = 1 if defined($hash->{LPID});
  183. }
  184. elsif ($attrName eq "audio_converter")
  185. {
  186. $_[3] = $attrVal;
  187. delete $hash->{AC};
  188. }
  189. elsif ($attrName eq "T2S_Device")
  190. {
  191. $_[3] = $attrVal;
  192. delete $hash->{NOTIFYDEV};
  193. }
  194. }
  195. if ($hash->{".reset"})
  196. {
  197. Log3 $name,5,"$name , SIP_Attr : reset";
  198. InternalTimer(gettimeofday()+1,"SIP_updateConfig",$hash);
  199. }
  200. return undef;
  201. }
  202. sub SIP_updateConfig($)
  203. {
  204. # this routine is called 5 sec after the last define of a restart
  205. # this gives FHEM sufficient time to fill in attributes
  206. my ($hash) = @_;
  207. my $name = $hash->{NAME};
  208. my $error;
  209. if (!$init_done)
  210. {
  211. RemoveInternalTimer($hash);
  212. InternalTimer(gettimeofday()+5,"SIP_updateConfig", $hash);
  213. return;
  214. }
  215. ## kommen wir via reset Kommando ?
  216. if ($hash->{".reset"})
  217. {
  218. $hash->{".reset"} = 0;
  219. RemoveInternalTimer($hash);
  220. if(defined($hash->{LPID}))
  221. {
  222. Log3 $name,4, "$name, Listen Kill PID : ".$hash->{LPID};
  223. BlockingKill($hash->{helper}{LISTEN_PID});
  224. delete $hash->{helper}{LISTEN_PID};
  225. delete $hash->{LPID};
  226. readingsSingleUpdate($hash,"listen_alive","no",1);
  227. Log3 $name,4,"$name, Reset Listen done";
  228. }
  229. if(defined($hash->{CPID}))
  230. {
  231. Log3 $name,4, "$name, CALL Kill PID : ".$hash->{CPID};
  232. BlockingKill($hash->{helper}{CALL_PID});
  233. delete $hash->{helper}{CALL_PID};
  234. delete $hash->{CPID};
  235. Log3 $name,4,"$name, Reset Call done";
  236. }
  237. }
  238. if (IsDisabled($name))
  239. {
  240. readingsSingleUpdate($hash,"state","disabled",1);
  241. return undef;
  242. }
  243. my $t2s = AttrVal($name,"T2S_Device",undef);
  244. $hash->{NOTIFYDEV} = $t2s if defined($t2s);
  245. if (AttrVal($name,"audio_converter","") && defined($t2s))
  246. {
  247. my $converter = AttrVal($name,"audio_converter","");
  248. my $res = qx(which $converter);
  249. $res =~ s/\n//;
  250. $hash->{AC} = ($res) ? $res : undef;
  251. }
  252. if (AttrVal($name,"sip_listen", "none") ne "none")
  253. {
  254. $error = SIP_try_listen($hash);
  255. if ($error)
  256. {
  257. Log3 $name, 1, $name.", listen -> $error";
  258. readingsBeginUpdate($hash);
  259. readingsBulkUpdate($hash,"state","error");
  260. readingsBulkUpdate($hash,"last_error",$error);
  261. readingsBulkUpdate($hash,"listen_alive","no");
  262. readingsEndUpdate($hash, 1 );
  263. return undef;
  264. }
  265. }
  266. else
  267. {
  268. readingsBeginUpdate($hash);
  269. readingsBulkUpdate($hash,"state","initialized");
  270. readingsBulkUpdate($hash,"listen_alive","no");
  271. readingsEndUpdate($hash, 1 );
  272. }
  273. return undef;
  274. }
  275. sub SIP_Register($$$)
  276. {
  277. my ($hash,$port,$type) = @_;
  278. my $name = $hash->{NAME};
  279. $hash->{LPID} = $$;
  280. my $logname = $name."[".$hash->{LPID}."]";
  281. my $ip = AttrVal($name,"sip_ip","");
  282. return "missing attribute sip_ip" if (!$ip);
  283. return "this is the IP address of your registrar , not your FHEM !" if ($ip eq AttrVal($name,"sip_registrar",""));
  284. return "invalid IP address $ip" if (($ip eq "0.0.0.0") || ($ip eq "127.0.0.1"));
  285. my $leg = IO::Socket::INET->new(Proto => 'udp', LocalHost => $ip, LocalPort => $port);
  286. # if port is already used try another one
  287. if (!$leg)
  288. {
  289. Log3 $name,2,"$logname, cannot open port $port at $ip: $!";
  290. $port += 10;
  291. $leg = IO::Socket::INET->new(
  292. Proto => 'udp',
  293. LocalHost => $ip,
  294. LocalPort => $port) || return "can't open port ".($port-10)." or $port at $ip: $!";
  295. Log3 $name,2,"$logname, using secundary port $port with IP $ip";
  296. }
  297. close($leg);
  298. $leg = $ip.":".$port;
  299. my $registrar = AttrVal($name,"sip_registrar","fritz.box");
  300. my $user = AttrVal($name,"sip_user","620");
  301. my $from = AttrVal($name,"sip_from","sip:".$user."@".$registrar);
  302. # create new agent
  303. $ua = Net::SIP::Simple->new(
  304. registrar => $registrar,
  305. domain => $registrar,
  306. leg => $leg,
  307. from => $from,
  308. auth => [ $user , SIP_readPassword($name) ]);
  309. # Register agent
  310. # optional registration
  311. my $sub_register;
  312. $sub_register = sub
  313. {
  314. my $expire = $ua->register(registrar => $registrar ) || return "registration failed: ".$ua->error;
  315. my $cmd = "ps -e | grep '".$hash->{parent}." '";
  316. my $result = qx($cmd);
  317. if (index($result,"perl") == -1)
  318. {
  319. Log3 $name,1,"$logname, can´t find my parent ".$hash->{parent}." in process list !";
  320. die;
  321. }
  322. Log3 $name,4,"$logname, register new expire : ".FmtDateTime(time()+$expire);
  323. if (AttrVal($name,"sip_listen","none") ne "none")
  324. { SIP_telnet($hash,"set $name state $type\nset $name listen_alive PID_".$hash->{LPID}."\nset $name expire $expire\nexit\n"); }
  325. else
  326. { SIP_telnet($hash,"set $name state $type\nexit\n"); }
  327. # need to refresh registration periodically
  328. $ua->add_timer( $expire/2, $sub_register );
  329. };
  330. $sub_register->();
  331. if($ua->register) # returned expires time or undef if failed
  332. {
  333. return 0;
  334. }
  335. my $ret = ($ua->error) ? $ua->error : "registration error";
  336. return $ret;
  337. }
  338. sub SIP_CALLStart($)
  339. {
  340. my ($arg) = @_;
  341. return unless(defined($arg));
  342. my ($name,$nr,$ringtime,$msg,$repeat) = split("\\|",$arg);
  343. my $hash = $defs{$name};
  344. my $logname = $name."[".$$."]";
  345. $hash->{telnetPort}= undef;
  346. $ua = undef;
  347. my $rtp_done = 0;
  348. my $dtmf = 'ABCD*#123--4567890';
  349. my $port = AttrVal($name,"sip_port",0);
  350. my $delay = AttrVal($name,"sip_call_audio_delay",0); # Verzoegerung in 1/4 Sekunden Schritten
  351. my $w = ($delay) ? -1 : 0;
  352. my $fi = 0;
  353. #$repeat = 0 if (!$repeat);
  354. my $packets = int($delay)*50;
  355. my $timeout = 0;
  356. my $final;
  357. my $peer_hangup;
  358. my $peer_hangup2;
  359. my $stopvar;
  360. my $state;
  361. my $no_answer;
  362. my $call;
  363. my $codec;
  364. my $call_established;
  365. my @files;
  366. my $anz;
  367. my $stat;
  368. my $ph_ok = 0;
  369. my $sound_of_silence = sub
  370. {
  371. return unless $packets-- > 0;
  372. return chr(0) x 160; # 160 bytes for PCMU/8000 = 1/50 Sekunde Sound
  373. };
  374. $hash->{parent} = getppid();
  375. Log3 $name,4,"$logname, my parent is ".$hash->{parent};
  376. $hash->{telnetPort} = SIP_telnetPort();
  377. return $name."|no telnet port without password found" if (!$hash->{telnetPort});
  378. if (!$port)
  379. {
  380. srand $$;
  381. $port = int(rand(500)+44000);
  382. Log3 $name,4,"$logname, using random port $port";
  383. }
  384. my $error = SIP_Register($hash,$port,"calling");
  385. return $name."|0|CallRegister: $error" if ($error);
  386. if ((substr($msg,0,1) ne "-") && $msg)
  387. {
  388. $codec = "PCMA/8000" if ($msg =~ /\.al(.+)$/);
  389. $codec = "PCMU/8000" if ($msg =~ /\.ul(.+)$/);
  390. return $name."|0|CallStart: please use filetype .alaw (for a-law) or .ulaw (for u-law)" if !defined($codec);
  391. push @files,$sound_of_silence if ($delay);
  392. if ($repeat < 0) { $repeat = $repeat * -1; $ph_ok= 1; }
  393. for(my $i=0; $i<=$repeat; $i++) { push @files,$msg; }
  394. $anz = @files;
  395. Log3 $name,4,"$logname, CallStart with $anz files - first file : $files[0] - $codec , repeat $repeat";
  396. $call = $ua->invite( $nr,
  397. init_media => $ua->rtp('send_recv', $files[0]),
  398. cb_rtp_done => \$rtp_done,
  399. cb_final => sub { my ($status,$self,%info) = @_;
  400. $final = $info{code};
  401. $stat = $status;
  402. Log3 $name,4,"$logname, cb_final - status : $status" if (!defined($final));
  403. Log3 $name,4,"$logname, cb_final - status : $status - final : $final" if (defined($final));
  404. if (($status eq "FAIL") && defined($final))
  405. {
  406. if (int($final) == 481) { SIP_telnet($hash,"set $name call_state ringing\nexit\n"); }
  407. elsif (int($final) == 486) { $fi=1 ; } # Anruf abgelehnt
  408. }
  409. elsif (($status eq "OK") && !defined($final) && !$call_established) # der Angrufene hat abgenommen
  410. {
  411. Log3 $name,4, $logname.", call established";
  412. SIP_telnet($hash,"set $name call_state established\nexit\n");
  413. $call_established++; # nur 1x , bei mehr als einem File kommen wir ofters hier vorbei
  414. }
  415. },
  416. recv_bye => \$peer_hangup,
  417. #ring_time => 5,
  418. #cb_noanswer => \$no_answer, klappt hier nicht wir gehen ueber add_timer
  419. rtp_param => [8, 160, 160/8000, $codec]) || return $name."|0|invite failed: ".$ua->error;
  420. }
  421. else
  422. {
  423. $dtmf = (substr($msg,0,1) eq "-") ? substr($msg,1) : $dtmf;
  424. Log3 $name,4,"$logname, CallStart DTMF : $dtmf";
  425. $delay = 0; # wenn delay sein muss dann ueber DTMF ----
  426. $repeat = 0; # keine Wiederholungen
  427. $call = $ua->invite($nr,
  428. init_media => $ua->rtp( 'recv_echo',undef,0 ),
  429. rtp_param => [0, 160, 160/8000, 'PCMU/8000'],
  430. cb_final => sub { my ($status,$self,%info) = @_;
  431. $final = $info{code};
  432. Log3 $name,4,"$logname, cb_final - Status : $status" if (!defined($final));
  433. Log3 $name,4,"$logname, cb_final - status : $status - final : $final" if (defined($final));
  434. if (($status eq "FAIL") && defined($final))
  435. {
  436. if (int($final) == 481) { SIP_telnet($hash,"set $name call_state ringing\nexit\n"); }
  437. elsif (int($final) == 486) { $fi=1 };
  438. }
  439. elsif (($status eq "OK") && !defined($final)) # der Angrufene hat abgenommen
  440. {
  441. Log3 $name,4, $logname.", call established";
  442. SIP_telnet($hash,"set $name call_state established\nexit\n");
  443. }
  444. },
  445. #cb_noanswer => \$no_answer,
  446. #ring_time => 5, siehe oben -> add_timer
  447. cb_cleanup => sub {0},
  448. recv_bye => \$peer_hangup) || return $name."|0|invite failed ".$ua->error;
  449. if (AttrVal($name,"sip_dtmf_send","audio") eq "audio")
  450. { $call->dtmf( $dtmf, methods => 'audio', duration => 500, cb_final => \$rtp_done); }
  451. else { $call->dtmf( $dtmf, cb_final => \$rtp_done); }
  452. }
  453. return "$name|0|invite call failed ".$call->error if ($call->error);
  454. Log3 $name,4,"$logname, calling : $nr";
  455. SIP_telnet($hash,"set $name call_state calling $nr\nexit\n");
  456. #return "$name|1|no answer" if ($no_answer);
  457. $ua->add_timer($ringtime,\$stopvar);
  458. $ua->loop( \$stopvar,\$peer_hangup,\$rtp_done,\$fi );
  459. $timeout = 1 if defined($stopvar); # hat der bereits zugeschlagen ?
  460. Log3 $name,5,"$logname, 0. Ende des ersten Loops";
  461. Log3 $name,5,"$logname, 1. rtp_done : $rtp_done" if defined($rtp_done);
  462. Log3 $name,5,"$logname, 2. fi : $fi" if defined($fi);
  463. Log3 $name,5,"$logname, 3. timeout : $timeout";
  464. Log3 $name,5,"$logname, 4. peer_hangup : $peer_hangup" if defined($peer_hangup);
  465. # Lebt der Call noch und gibt es ueberhaupt etwas zum wiederholen ?
  466. while ( !$peer_hangup && !$peer_hangup2 && !$fi && !$stopvar && $msg && ($anz > 1))
  467. {
  468. shift(@files); # done with file
  469. @files || last; # raus hier sobald kein File mehr da ist
  470. Log3 $name,4,"$logname, next file : $files[0]" if defined($files[0]);
  471. Log3 $name,3,"$logname, opps no file" if !defined($files[0]);
  472. # re-invite on current call for next file
  473. $rtp_done = undef; # wichtig ! u.U. haengen wir hier fest wenn der Anrufer jetzt auflegt
  474. select(undef, undef, undef, 0.1); # minimale pause
  475. $call->reinvite(
  476. init_media => $ua->rtp('send_recv', $files[0]),
  477. #rtp_param => [0, 160, 160/8000, 'PCMU/8000'], unebeding weglassen ! fuehrt zu Verzerrungen bei der Wiedergabe :(
  478. cb_rtp_done => \$rtp_done,
  479. recv_bye => \$peer_hangup2, # FIXME: do we need to repeat this? Wzut : I think so ...
  480. ) || return $name."|0|reinvite failed: ".$ua->error;
  481. $ua->loop( \$rtp_done,\$peer_hangup2,\$peer_hangup,\$stopvar );
  482. Log3 $name,4,"$logname, loop rtp_done : $rtp_done" if defined($rtp_done);
  483. $w++;
  484. }
  485. $timeout = 1 if defined($stopvar); # nach eventuellen reinvte nochmal testen
  486. # timeout or dtmf done, hang up
  487. if ( $timeout || $rtp_done)
  488. {
  489. $stopvar = undef;
  490. $call->bye( cb_final => \$stopvar );
  491. $ua->loop( \$stopvar );
  492. }
  493. Log3 $name,5,"$logname, RTP done : $rtp_done" if defined($rtp_done);
  494. Log3 $name,5,"$logname, Hangup : $peer_hangup" if defined($peer_hangup);
  495. Log3 $name,5,"$logname, Hangup2 : $peer_hangup2" if defined($peer_hangup2);
  496. Log3 $name,5,"$logname, Timeout : $timeout";
  497. Log3 $name,5,"$logname, Final : $final" if defined($final);
  498. Log3 $name,5,"$logname, while : $w" if defined($w);
  499. Log3 $name,5,"$logname, Status : $stat" if defined($stat);
  500. if (defined($rtp_done))
  501. {
  502. if ($rtp_done eq "OK") {return $name."|1|ok";} # kein Audio
  503. else
  504. {
  505. if (defined($final))
  506. {
  507. my $txt;
  508. $txt = "canceled" if (int($final) == 486);
  509. $txt = "no answer" if (int($final) == 487);
  510. $txt = "declined" if (int($final) == 603);
  511. return $name."|1|$txt" if $txt;
  512. }
  513. else {return $name."|1|ok" if ($rtp_done !=0);}
  514. }
  515. }
  516. # immer noch kein richtiger Test zur Rueckgabe ?
  517. $final = "unknown" if (!defined($final) && !$timeout);
  518. $final = "timeout" if (!defined($final) && $timeout);
  519. $final = "peer hangup" if defined($peer_hangup);
  520. $final = "peer_hangup" if defined($peer_hangup2); # ts,ts hat der doch glatt im reinvite noch abgebochen
  521. # geben wir doch ok zurueck wenn er sich die Nachricht min 1x angehört hat
  522. return $name."|1|ok peer hangup" if ($ph_ok && defined($peer_hangup2) && ($stat eq "OK") && ($w>0)); # bei delay 1x mehr !
  523. return $name."|1|".$final;
  524. }
  525. sub SIP_CALLDone($)
  526. {
  527. my ($string) = @_;
  528. return unless(defined($string));
  529. my @r = split("\\|",$string);
  530. my $hash = $defs{$r[0]};
  531. my $error = (defined($r[1])) ? $r[1] : "0";
  532. my $final = (defined($r[2])) ? $r[2] : "???";
  533. my $name = $hash->{NAME};
  534. my $success = (substr($final,0,2) eq "ok") ? 1 : 0;
  535. my @a;
  536. Log3 $name, 4,"$name, CALLDone -> $string";
  537. my $calltime = time() - $hash->{helper}{CALL_START};
  538. delete($hash->{helper}{CALL_PID}) if (defined($hash->{helper}{CALL_PID}));
  539. delete($hash->{CPID}) if (defined($hash->{CPID}));
  540. delete $hash->{lastnr} if (defined($hash->{lastnr}));
  541. delete($hash->{helper}{CALL_START}) if (defined($hash->{helper}{CALL_START}));
  542. if ($error ne "1")
  543. {
  544. readingsBeginUpdate($hash);
  545. readingsBulkUpdate($hash, "call","done");
  546. readingsBulkUpdate($hash, "call_time",int($calltime)) if defined($calltime);
  547. readingsBulkUpdate($hash, "last_error",$final);
  548. readingsBulkUpdate($hash, "call_state","fail");
  549. readingsBulkUpdate($hash, "call_success","0");
  550. readingsBulkUpdate($hash, "state",$hash->{'.oldstate'}) if defined($hash->{'.oldstate'});
  551. readingsEndUpdate($hash, 1);
  552. }
  553. else
  554. {
  555. readingsBeginUpdate($hash);
  556. readingsBulkUpdate($hash, "call","done");
  557. readingsBulkUpdate($hash, "call_state",lc($final));
  558. readingsBulkUpdate($hash, "call_success",$success);
  559. readingsBulkUpdate($hash, "call_time",int($calltime)) if defined($calltime);
  560. readingsBulkUpdate($hash, "state",$hash->{'.oldstate'}) if defined($hash->{'.oldstate'});
  561. readingsEndUpdate($hash, 1);
  562. }
  563. my (undef,$nr,$ringtime,$msg,$repeat,$force) = split("\\|",$hash->{CALL}); # zerlegen wir den Original Call
  564. if ($force && !$success)
  565. {
  566. #$repeat = "0" if (!defined($repeat) || ($repeat eq "")) ;
  567. $repeat++; $repeat--;
  568. $force =~ s/^\&//;
  569. $force++; $force--;
  570. my $nr2 = $nr;
  571. $nr2 =~ tr/0-9//cd;
  572. my $t = ($force) ? $force : int(AttrVal($name,"sip_force_interval",60));
  573. my $time_s = strftime("\%H:\%M:\%S", gmtime($t));
  574. $error = CommandDefine(undef, "at_forcecall_".$nr2." at +".$time_s." set $name call $nr $ringtime $msg *".$repeat." &".$t);
  575. if (!$error) { $attr{"at_forcecall_".$nr2}{room} = AttrVal($name,"room","Unsorted"); }
  576. else { Log3 $name,2,"$name, $error"; }
  577. Log3 $name,4,"$name, at_forcecall_".$nr2." at +".$time_s." set $name call $nr $ringtime $msg *".$repeat." &".$force;
  578. }
  579. my $nextcall = shift @fifo; # sind da noch Calls in der Queue ?
  580. if ($nextcall)
  581. {
  582. @a = split(" ",$nextcall);
  583. $error = SIP_Set($hash,@a);
  584. Log3 $name,3,"$name, error setting nextcall $nextcall -> $error" if ($error);
  585. return undef;
  586. } else { Log3 $name,5,"$name, fifo is empty"; }
  587. if (exists($hash->{'.elbc'}))
  588. {
  589. @a = (undef,"listen");
  590. Log3 $name,4,"$name, try restarting listen process after call ends";
  591. $error = SIP_Set($hash,@a);
  592. Log3 $name,3,"$name, error restarting listen -> $error" if ($error);
  593. delete $hash->{'.elbc'};
  594. } else { Log3 $name,5,"$name, no elbc"; }
  595. delete $hash->{CALL};
  596. return undef;
  597. }
  598. #####################################
  599. sub SIP_Set($@)
  600. {
  601. my ($hash, @a) = @_;
  602. my $name = $hash->{NAME};
  603. my $cmd = (defined($a[1])) ? $a[1] : "?";
  604. my $subcmd;
  605. my $ret;
  606. return join(" ", sort keys %sets) if ($cmd eq "?");
  607. if (($cmd eq "call") || ($cmd eq "listen"))
  608. {
  609. my $pwd = SIP_readPassword($name);
  610. unless (defined $pwd)
  611. {
  612. my $ret = "Error: no SIP user password set. Please define it with 'set $name password Your_SIP_User_Password'";
  613. Log3 $name,2,"$name, $ret";
  614. return $ret;
  615. }
  616. }
  617. if ($cmd eq "call")
  618. {
  619. my $nr = (defined($a[2])) ? $a[2] : "";
  620. my $ringtime = (defined($a[3])) ? $a[3] : 30;
  621. my $msg = (defined($a[4])) ? $a[4] : AttrVal($name, "sip_audiofile_call", "");
  622. return "missing target call number" if (!$nr);
  623. return "invalid max time : $ringtime" unless $ringtime =~ m/^\d+$/;
  624. if (exists($hash->{CPID}))
  625. {
  626. return "there is already a call activ for target $nr" if (defined($hash->{lastnr}) && ($hash->{lastnr} eq $nr));
  627. my $call = join(" ",@a);
  628. push (@fifo,$call);
  629. Log3 $name ,4,"$name, add call $call to fifo so we can do it later !";
  630. return undef;
  631. }
  632. my $anz = @a;
  633. $anz--; # letztes Element
  634. my $force = (substr($a[$anz],0,1) eq "&") ? $a[$anz] : 0;
  635. $anz-- if ($force); # checken wir dann noch auf repeat
  636. my $repeat = 0;
  637. if (substr($a[$anz],0,1) eq "*")
  638. {
  639. $repeat = $a[$anz];
  640. $repeat =~ s/^\*//;
  641. $repeat ++; $repeat --;
  642. } # * weg , Rest als Int
  643. Log3 $name,3,"$name, force call" if ($force);
  644. Log3 $name,4,"$name, msg will be repeat $repeat times" if ($repeat);
  645. if (exists($hash->{LPID}) && (AttrVal($name,"sip_elbc","no") ne "no"))
  646. {
  647. Log3 $name,4,"$name, listen process ".$hash->{LPID}." must be killed befor we start a new call !";
  648. BlockingKill($hash->{helper}{LISTEN_PID});
  649. delete $hash->{helper}{LISTEN_PID};
  650. delete $hash->{LPID};
  651. readingsSingleUpdate($hash,"listen_alive","no",1);
  652. $hash->{'.elbc'} = 1; # haben wir gerade einen listen Prozess abgeschossen ?
  653. }
  654. if ($msg)
  655. {
  656. if (substr($msg,0,1) eq "-")
  657. {
  658. Log3 $name, 4, $name.", message DTMF = $msg";
  659. }
  660. elsif (substr($msg,0,1) eq "!") # Text2Speech Text ?
  661. {
  662. shift @a;
  663. shift @a;
  664. $a[0] = "t2s_name"; # ist egal wird eh verworfen
  665. $a[1] = "tts"; # Kommando des Set Befehls
  666. $a[2] =~ s/^\!//; # das ! muss weg
  667. pop @a if ($force); # das & muss ggf. auch noch weg
  668. pop @a if ($repeat); # das * muss ggf. auch weg
  669. # die nachsten vier brauchen wir unbedingt fuer T2S
  670. $hash->{callnr} = $nr;
  671. $hash->{ringtime} = $ringtime;
  672. $hash->{forcecall} = $force;
  673. $hash->{repeat} = $repeat;
  674. my $ret = SIP_create_T2S_File($hash,@a); # na dann lege schon mal los
  675. return $ret if defined($ret); # Das ging leider schief
  676. readingsSingleUpdate($hash,"call_state","waiting T2S",0);
  677. RemoveInternalTimer($hash);
  678. # geben wir T2S mal ein paar Sekunden
  679. InternalTimer(gettimeofday()+int(AttrVal($name,"T2S_Timeout",5)), "SIP_wait_for_t2s", $hash);
  680. return undef;
  681. }
  682. elsif (-e $msg)
  683. {
  684. Log3 $name, 4, $name.", audio file $msg found";
  685. return "unknown audio type, please use only .alaw or .ulaw" if (($msg !~ /\.al(.+)$/) && ($msg !~ /\.ul(.+)$/));
  686. }
  687. else
  688. {
  689. $ret = "audio file $msg not found";
  690. readingsBulkUpdate($hash, "last_error",$ret);
  691. Log3 $name, 3, "$name, $ret !";
  692. $hash->{repeat} = 0;
  693. $hash->{forcecall} = 0;
  694. $msg = "";
  695. }
  696. }
  697. else { Log3 $name, 4, $name.", calling $nr, ringtime: $ringtime , no message"; }
  698. $hash->{lastnr} = $nr;
  699. my $arg = "$name|$nr|$ringtime|$msg|$repeat"; # da muss force nicht mit
  700. Log3 $name, 4, "$name, $arg";
  701. #BlockingCall($blockingFn, $arg, $finishFn, $timeout, $abortFn, $abortArg);
  702. $hash->{helper}{CALL_PID} = BlockingCall("SIP_CALLStart",$arg, "SIP_CALLDone") unless(exists($hash->{helper}{CALL_PID}));
  703. if($hash->{helper}{CALL_PID})
  704. {
  705. $hash->{CPID} = $hash->{helper}{CALL_PID}{pid};
  706. $hash->{CALL} = $arg."|$force"; # hier retten wir aber force
  707. Log3 $name, 4, "$name, call -> ".$hash->{CALL};
  708. Log3 $name, 5, "$name, call has pid ".$hash->{CPID};
  709. $hash->{helper}{CALL_START} = time();
  710. readingsBeginUpdate($hash);
  711. readingsBulkUpdate($hash, "call_state","invite");
  712. readingsBulkUpdate($hash, "call",$nr);
  713. readingsEndUpdate($hash, 1);
  714. $hash->{'.oldstate'} = ReadingsVal($name,"state",undef);
  715. return undef;
  716. }
  717. else
  718. { # das war wohl nix :(
  719. Log3 $name, 3, "$name, CALL process start failed, arg : $arg";
  720. $ret = "can't execute call number $nr as NonBlockingCall";
  721. readingsBeginUpdate($hash);
  722. readingsBulkUpdate($hash, "last_error",$ret);
  723. readingsBulkUpdate($hash, "call_state","fail");
  724. readingsEndUpdate($hash, 1);
  725. delete $hash->{lastnr} if (defined($hash->{lastnr}));
  726. return $ret;
  727. }
  728. }
  729. elsif ($cmd eq "listen")
  730. {
  731. my $type = AttrVal($name,"sip_listen","none");
  732. return "there is already a listen process running with pid ".$hash->{LPID} if exists($hash->{LPID});
  733. return "please set attr sip_listen to dtmf or wfp or echo first" if (AttrVal($name,"sip_listen","none") eq "none");
  734. $ret = SIP_try_listen($hash);
  735. if ($ret)
  736. {
  737. Log3 $name, 1, $name.", listen -> $ret";
  738. readingsBeginUpdate($hash);
  739. readingsBulkUpdate($hash,"state","error");
  740. readingsBulkUpdate($hash,"last_error",$ret);
  741. readingsBulkUpdate($hash,"listen_alive","no");
  742. readingsEndUpdate($hash, 1 );
  743. return $ret;
  744. }
  745. return undef;
  746. }
  747. elsif (($cmd eq "dtmf_event") && defined($a[2]))
  748. {
  749. readingsSingleUpdate($hash, "dtmf",$a[2],1);
  750. return undef;
  751. }
  752. elsif ($cmd eq "fetch")
  753. {
  754. readingsSingleUpdate($hash, "caller","fetch",1);
  755. return undef;
  756. }
  757. elsif ($cmd eq "reject")
  758. {
  759. readingsSingleUpdate($hash, "caller","reject",1);
  760. return undef;
  761. }
  762. elsif ($cmd eq "reset")
  763. {
  764. $hash->{".reset"} = 1;
  765. SIP_updateConfig($hash);
  766. return undef;
  767. }
  768. # die ersten beiden brauchen wir nicht mehr
  769. shift @a;
  770. shift @a;
  771. # den Rest als ein String
  772. $subcmd = join(" ",@a);
  773. if ($cmd eq "state")
  774. {
  775. readingsSingleUpdate($hash, "state",$subcmd,1);
  776. return undef;
  777. }
  778. elsif ($cmd eq "listen_alive")
  779. {
  780. readingsSingleUpdate($hash, "listen_alive",$subcmd,1);
  781. return undef;
  782. }
  783. elsif ($cmd eq "expire")
  784. {
  785. readingsSingleUpdate($hash, "expire",$subcmd,1);
  786. return undef;
  787. }
  788. elsif ($cmd eq "caller")
  789. {
  790. readingsSingleUpdate($hash, "caller",$subcmd,1);
  791. return undef;
  792. }
  793. elsif ($cmd eq "caller_state")
  794. {
  795. readingsSingleUpdate($hash, "caller_state",$subcmd,1);
  796. return undef;
  797. }
  798. elsif ($cmd eq "call_state")
  799. {
  800. readingsSingleUpdate($hash, "call_state",$subcmd,1);
  801. return undef;
  802. }
  803. elsif ($cmd eq "caller_time")
  804. {
  805. readingsSingleUpdate($hash, "caller_time",$subcmd,1);
  806. return undef;
  807. }
  808. elsif ($cmd eq "password")
  809. {
  810. return SIP_storePassword($name,$subcmd);
  811. }
  812. return "Unknown argument: $cmd, choose one of ".join(" ", sort keys %sets);
  813. }
  814. sub SIP_Get($@)
  815. {
  816. my ($hash, @a) = @_;
  817. my $name = $hash->{NAME};
  818. my $cmd = $a[1];
  819. return ReadingsVal($name,"caller","???") if ($cmd eq "caller");
  820. #return "Unknown argument: $cmd, choose one of caller:noArg";
  821. return undef;
  822. }
  823. sub SIP_Undef($$)
  824. {
  825. my ($hash, $name) = @_;
  826. $ua->cleanup if (defined($ua));
  827. BlockingKill($hash->{helper}{LISTEN_PID}) if (defined($hash->{helper}{LISTEN_PID}));
  828. #RemoveInternalTimer($hash);
  829. #RemoveInternalTimer($name);
  830. return undef;
  831. }
  832. sub SIP_ListenStart($)
  833. {
  834. my ($name) = @_;
  835. return unless(defined($name));
  836. my $logname = $name."[".$$."]";
  837. my $hash = $defs{$name}; # $hash / $name gueltig in diesem Block
  838. $hash->{parent} = getppid();
  839. Log3 $name,4,"$logname, my parent is ".$hash->{parent};
  840. $hash->{telnetPort} = undef;
  841. my $dtmfloop; # Ende-Flag für die DTMF-Schleife
  842. my $okloop; # Ende-Flag für die OK-Ansage
  843. my $okloopbye = 0; # Ende-Flag für recv_bye währne der OK-Ansage
  844. my $byebye = 0; # Anrufer hat aufgelegt
  845. my $packets = 50;
  846. my $block_it;
  847. my $sub_create;
  848. my $sub_invite_wfp;
  849. my $sub_filter;
  850. my $sub_bye;
  851. my $sub_dtmf;
  852. my $send_something;
  853. $hash->{telnetPort} = SIP_telnetPort();
  854. return $name."|no telnet port without password found" if (!$hash->{telnetPort});
  855. my $port = AttrVal($name,"sip_port",0);
  856. if (!$port)
  857. {
  858. srand $$;
  859. $port = int(rand(500)+44500);
  860. Log3 $name,4,"$logname, using random port $port";
  861. }
  862. else { $port += 10; }
  863. $ua = undef;
  864. my $error = SIP_Register($hash,$port,"listen_".AttrVal($name,"sip_listen",""));
  865. return $name."|ListenRegister: $error" if ($error);
  866. my $msg1 = AttrVal($name, "sip_audiofile_dtmf", "");
  867. my $msg2 = AttrVal($name, "sip_audiofile_ok", "");
  868. my $msg3 = AttrVal($name, "sip_audiofile_wfp", "");
  869. $msg1 = $hash->{audio1} if (defined($hash->{audio1}) && $msg1);
  870. $msg1 = SIP_check_file($hash,$msg1) if (!defined($hash->{audio1}) && $msg1);;
  871. $msg2 = $hash->{audio2} if (defined($hash->{audio2}) && $msg2);
  872. $msg2 = SIP_check_file($hash,$msg2) if (!defined($hash->{audio2}) && $msg2);;
  873. $msg3 = $hash->{audio3} if (defined($hash->{audio3}) && $msg3);
  874. $msg3 = SIP_check_file($hash,$msg3) if (!defined($hash->{audio3}) && $msg3);;
  875. Log3 $name,4,"$logname, using $msg1 for audio_dtmf" if ($msg1);
  876. Log3 $name,4,"$logname, using $msg2 for audio_ok" if ($msg2);
  877. Log3 $name,4,"$logname, using $msg3 for audio_wfp" if ($msg3);
  878. $hash->{dtmf} = 0;
  879. $hash->{dtmf_event} = "";
  880. $hash->{old} ="-";
  881. $send_something = sub
  882. {
  883. return unless $packets-- > 0;
  884. my $buf = sprintf "%010d",$packets;
  885. $buf .= "1234567890" x 15;
  886. return $buf; # 160 bytes for PCMU/8000
  887. };
  888. $sub_dtmf = sub
  889. {
  890. my ($event,$dur) = @_;
  891. Log3 $name,5,"$logname, DTMF Event: $event - $dur ms";
  892. return if (int($dur) < 100);
  893. if ($event eq "#")
  894. {
  895. $hash->{dtmf} = 1;
  896. $hash->{dtmf_event} = "";
  897. $hash->{old} = $event;
  898. return;
  899. }
  900. if (($event ne $hash->{old}) && $hash->{dtmf})
  901. {
  902. $hash->{dtmf} ++;
  903. $hash->{old} = $event;
  904. $hash->{dtmf_event} .= $event;
  905. Log3 $name,5,"$logname, DTMF: ".$hash->{dtmf_event}." , Anz: ".$hash->{dtmf};
  906. if ($hash->{dtmf} > int(AttrVal($name,"sip_dtmf_size",2)))
  907. {
  908. SIP_telnet($hash,"set $name dtmf_event ".$hash->{dtmf_event}."\n");
  909. $hash->{dtmf} = 0;
  910. $hash->{dtmf_event} = "";
  911. $hash->{old} = "-";
  912. $dtmfloop = 1;
  913. }
  914. }
  915. return;
  916. };
  917. $sub_create = sub
  918. {
  919. my ($call,$request,$leg,$from) = @_;
  920. $hash->{call} = $call;
  921. $hash->{request} = $request;
  922. $hash->{leg} = $leg;
  923. $hash->{from} = $from;
  924. Log3 $name,4,"$logname, cb_create : ".$request->method;
  925. my $response = ($block_it) ? $request->create_response('487','Request Terminated') : $request->create_response('180','Ringing');
  926. $call->{endpoint}->new_response( $call->{ctx},$response,$leg,$from );
  927. 1;
  928. };
  929. $sub_invite_wfp = sub
  930. {
  931. my ($a,$b,$c,$d) = @_;
  932. my $waittime = int(AttrVal($name, "sip_waittime", 10));
  933. my $i;
  934. $packets = 50;
  935. for($i=1; $i<=$waittime; $i++)
  936. {
  937. if ($block_it) #und gleich wieder weg
  938. {
  939. sleep int(AttrVal($name, "sip_waittime", 2)); # kleine Pause
  940. last;
  941. }
  942. Log3 $name, 4,"$logname, SIP_invite -> ringing $i";
  943. SIP_telnet($hash,"set $name caller_state ringing_$i\nexit\n");
  944. sleep 1;
  945. ######## $$$ read state of my device
  946. my $action = SIP_telnet($hash,"get $name caller\n");
  947. if ( $action eq "fetch" )
  948. {
  949. Log3 $name, 4,"$logname, SIP_invite fetch !";
  950. SIP_telnet($hash,"set $name caller_state fetching\nexit\n");
  951. last;
  952. }
  953. elsif ( $action eq "reject" )
  954. {
  955. Log3 $name, 4,"$logname, SIP_invite block !";
  956. SIP_telnet($hash,"set $name caller_state rejected\nexit\n");
  957. my $call = $hash->{call};
  958. my $request = $hash->{request};
  959. my $leg = $hash->{leg};
  960. my $from = $hash->{from};
  961. my $response = $request->create_response('603','Declined');
  962. $call->{endpoint}->new_response( $call->{ctx},$response,$leg,$from );
  963. last;
  964. }
  965. }
  966. SIP_telnet($hash, "set $name caller none\nset $name caller_state waiting\nexit\n") if (($i>$waittime) || $block_it);
  967. return 0;
  968. };
  969. $sub_filter = sub
  970. {
  971. my ($a,$b) = @_;
  972. Log3 $name, 5, "$logname, SIP_filter : a:$a | b:$b";
  973. $block_it = 0; #
  974. my ($caller,undef) = split("\;", $a);
  975. my @callers;
  976. $caller =~ s/\"//g;
  977. $caller =~ s/\>//g;
  978. $caller =~ s/\<//g; # fhem mag keine <> in ReadingsVal :(
  979. $caller = "???" if (!$caller);
  980. SIP_telnet($hash, "set $name caller $caller\nexit\n");
  981. my ($callnr,undef) = split("\@", $caller);
  982. my $block = AttrVal($name,"sip_blocking",undef);
  983. if (defined($block))
  984. {
  985. my @blockers = split (/,/,$block);
  986. foreach (@blockers)
  987. {
  988. if ((index($callnr, $_) > -1) || ($_ eq ".*"))
  989. {
  990. SIP_telnet($hash,"set $name caller_state blocking\nexit\n");
  991. Log3 $name, 4, "$logname, blocking $callnr found on $block";
  992. $block_it = 1;
  993. #$byebye = 1;
  994. }
  995. }
  996. }
  997. my $filter = AttrVal($name,"sip_filter",undef);
  998. if (defined($filter))
  999. {
  1000. @callers = split (/,/,$filter);
  1001. foreach (@callers) { return 1 if (index($callnr, $_) > -1); }
  1002. SIP_telnet($hash,"set $name caller_state ignoring\nexit\n");
  1003. Log3 $name, 4, "$logname, ignoring $callnr number not found in $filter";
  1004. return 0;
  1005. }
  1006. return 1;
  1007. };
  1008. $sub_bye = sub
  1009. {
  1010. my ($event) = @_;
  1011. Log3 $name, 5, "$logname, SIP_bye : $event";
  1012. my $calltime = int(time()-$hash->{CALL_START});
  1013. SIP_telnet($hash, "set $name caller none\nset $name caller_state hangup\nset $name caller_time $calltime\nexit\n") ;
  1014. $byebye = 1;
  1015. return 1;
  1016. };
  1017. ################
  1018. if (AttrVal($name,"sip_listen", "none") eq "dtmf")
  1019. {
  1020. $hash->{dtmf} = 0;
  1021. $dtmfloop = 0; # Ende-Flag für die DTMF-Schleife
  1022. $okloop = 0; # Ende-Flag für die OK-Ansage
  1023. $okloopbye = 0; # Ende-Flag für recv_bye währne der OK-Ansage
  1024. $byebye = 0; # Anrufer hat aufgelegt
  1025. while(1)
  1026. {
  1027. my $call;
  1028. $hash->{dtmf} = 0;
  1029. $hash->{dtmf_event} = "";
  1030. $hash->{old} ="-";
  1031. SIP_telnet($hash, "set $name caller none\nset $name caller_state waitting\nexit\n") ;
  1032. $ua->listen (cb_create => \&$sub_create,
  1033. cb_invite => sub {
  1034. if (!$block_it)
  1035. {
  1036. SIP_telnet($hash,"set $name caller_state ringing\nexit\n");
  1037. sleep int(AttrVal($name, "sip_ringtime", 3)); #Anrufer hört das typische Klingeln wenn die Gegenseite nicht abnimmt
  1038. }
  1039. },
  1040. filter => \&$sub_filter,
  1041. cb_established => sub {
  1042. (my $status,$call) = @_;
  1043. if (!$block_it)
  1044. {
  1045. $hash->{CALL_START} = time();
  1046. SIP_telnet($hash,"set $name caller_state established\nexit\n"); return 1;
  1047. }
  1048. else {
  1049. sleep 1;
  1050. #SIP_telnet($hash, "set $name caller none\nset $name caller_state waitting\nexit\n") ;
  1051. return 0; }
  1052. } # sobald invite verlassen wird, wird in cb_established verzweigt
  1053. );
  1054. $ua->loop(\$call);
  1055. # Der SIP-Client ist jetzt im echo-Modus und zwar so lange, bis der Anrufer auflegt,
  1056. # das bekommen wir durch recv_bye mit
  1057. my $dtmf_loop = 1; # für jeden Anruf neu setzen
  1058. while ($dtmf_loop) # Schleife für Code-Ansage, DTMF-Erkennung, okay-Ansage
  1059. {
  1060. $dtmfloop = 0;
  1061. $okloop = 0;
  1062. $okloopbye = 0;
  1063. $call->reinvite(
  1064. init_media => $ua->rtp('send_recv',($msg1) ? $msg1 : $send_something),
  1065. rtp_param => [8, 160, 160/8000, 'PCMA/8000'],
  1066. cb_rtp_done => sub { $packets = 25; },
  1067. cb_dtmf => \&$sub_dtmf,
  1068. recv_bye => \&$sub_bye,
  1069. );
  1070. $ua->loop(\$dtmfloop, \$byebye);
  1071. if (!$byebye)
  1072. { # Anrufer hat nicht aufgelegt
  1073. $call->reinvite(
  1074. init_media => $ua->rtp('send_recv',($msg2) ? $msg2 : $send_something),
  1075. rtp_param => [8, 160, 160/8000, 'PCMA/8000'],
  1076. cb_rtp_done => sub { select(undef, undef, undef, 0.1); $okloop = 1; $packets = 50;},
  1077. recv_bye => sub { $okloopbye = 1; },
  1078. cb_cleanup => sub {0},
  1079. );
  1080. $ua->loop(\$okloop,\$okloopbye); # ohne diese loop endet der Anruf sofort
  1081. }
  1082. else { $dtmf_loop = 0; } # Schleife beenden, Anrufer hat aufgelegt
  1083. if ( ( defined $okloopbye && $okloopbye ) || $byebye )
  1084. { # wenn jemand mitten im "okay" auflegt
  1085. $dtmf_loop = 0; # beende die inner loop
  1086. $byebye = 1;
  1087. }
  1088. else { $dtmf_loop = ((AttrVal($name,"sip_dtmf_loop","once") eq 'once')) ? 0 : 1;
  1089. my $calltime = int(time()-$hash->{CALL_START});
  1090. SIP_telnet($hash, "set $name caller_state hangup\nset $name caller_time $calltime\nexit\n") if(!$dtmf_loop);
  1091. } # führt ggf. zum Schleifenende
  1092. } # end inner loop
  1093. if (!$byebye)
  1094. { # Anrufer hat nicht aufgelegt und nur ein DTMF angefordert
  1095. my $hanguploop;
  1096. $call->bye( cb_final => \$hanguploop );
  1097. $ua->loop( \$hanguploop );
  1098. }
  1099. } # while(1)
  1100. }
  1101. elsif (AttrVal($name,"sip_listen", "none") eq "wfp")
  1102. {
  1103. $ua->listen(
  1104. cb_create => \&$sub_create,
  1105. cb_invite => \&$sub_invite_wfp,
  1106. cb_established => sub { $hash->{CALL_START} = time(); },
  1107. filter => \&$sub_filter,
  1108. recv_bye => \&$sub_bye,
  1109. init_media => $ua->rtp('send_recv',($msg3) ? $msg3 : $send_something),
  1110. #cb_rtp_done => sub { $packets = 50; return 1;},
  1111. rtp_param => [8, 160, 160/8000, 'PCMA/8000']
  1112. ); # options are invite and hangup
  1113. }
  1114. elsif (AttrVal($name,"sip_listen", "none") eq "echo")
  1115. {
  1116. $ua->listen(
  1117. filter => \&$sub_filter,
  1118. cb_create => \&$sub_create,
  1119. cb_invite => sub {
  1120. if (!$block_it)
  1121. {
  1122. SIP_telnet($hash,"set $name caller_state ringing\nexit\n");
  1123. sleep int(AttrVal($name, "sip_ringtime", 3)); #Anrufer hört das typische Klingeln wenn die Gegenseite nicht abnimmt
  1124. }
  1125. },
  1126. cb_established => sub { $hash->{CALL_START} = time(); },
  1127. init_media => $ua->rtp( 'recv_echo',undef,0 ),
  1128. rtp_param => [8, 160, 160/8000, 'PCMA/8000'],
  1129. recv_bye => \&$sub_bye,
  1130. );
  1131. }
  1132. else { return $name."|end"; }
  1133. $ua->loop;
  1134. return $name."|end"; # hier sollten wir eigentlich nie himkommen !
  1135. }
  1136. sub SIP_ListenDone($)
  1137. {
  1138. my ($string) = @_;
  1139. return unless(defined($string));
  1140. my @r = split("\\|",$string);
  1141. my $hash = $defs{$r[0]};
  1142. my $ret = (defined($r[1])) ? $r[1] : "unknown error";
  1143. my $name = $hash->{NAME};
  1144. Log3 $name, 5,"$name, ListenDone -> $string";
  1145. delete($hash->{helper}{LISTEN_PID});
  1146. delete $hash->{LPID};
  1147. RemoveInternalTimer($name);
  1148. if ($ret ne "end")
  1149. {
  1150. readingsBeginUpdate($hash);
  1151. readingsBulkUpdate($hash,"state","error");
  1152. readingsBulkUpdate($hash,"last_error",$ret);
  1153. readingsBulkUpdate($hash,"listen_alive","no");
  1154. readingsEndUpdate($hash, 1 );
  1155. Log3 $name, 3 , "$name, listen error -> $ret";
  1156. return if(IsDisabled($name));
  1157. InternalTimer(gettimeofday()+AttrVal($name, "sip_watch_listen", 60), "SIP_try_listen", $hash);
  1158. }
  1159. else
  1160. {
  1161. readingsBeginUpdate($hash);
  1162. readingsBulkUpdate($hash,"state","ListenDone");
  1163. readingsBulkUpdate($hash,"listen_alive","no");
  1164. readingsEndUpdate($hash, 1 );
  1165. return if(IsDisabled($name));
  1166. return if(!AttrVal($name, "sip_dtmf", 0));
  1167. SIP_try_listen($hash);
  1168. }
  1169. return;
  1170. }
  1171. sub SIP_try_listen($)
  1172. {
  1173. my ($hash) = @_;
  1174. my $name = $hash->{NAME};
  1175. my $waits = AttrVal($name, "sip_watch_listen", 60);
  1176. my $audio1 = AttrVal($name, "sip_audiofile_dtmf","-");
  1177. my $audio2 = AttrVal($name, "sip_audiofile_ok", "-");
  1178. my $audio3 = AttrVal($name, "sip_audiofile_wfp", "-");
  1179. my @a = ("tts","tts", "-");;
  1180. if (AttrVal($name,"sip_listen","none") eq "dtmf")
  1181. {
  1182. if ((substr($audio1,0,1) eq "!") && !defined($hash->{audio1})) # muss erst T2S gefragt werden ?
  1183. {
  1184. $audio1 =~ s/^\!//;
  1185. $hash->{audio1} = $audio1;
  1186. $a[2] = $audio1;
  1187. Log3 $name ,4,"$name, hole $audio1";
  1188. }
  1189. elsif ((substr($audio2,0,1) eq "!") && !defined($hash->{audio2})) # muss erst T2S gefragt werden ?
  1190. {
  1191. $audio2 =~ s/^\!//;
  1192. $hash->{audio2} = $audio2;
  1193. $a[2] = $audio2;
  1194. Log3 $name ,4,"$name, hole $audio2";
  1195. }
  1196. }
  1197. elsif ((substr($audio3,0,1) eq "!") && !defined($hash->{audio3}) && (AttrVal($name,"sip_listen","none") eq "wfp")) # muss erst T2S gefragt werden ?
  1198. {
  1199. $audio3 =~ s/^\!//;
  1200. $hash->{audio3} = $audio3;
  1201. $a[2] = $audio3;
  1202. Log3 $name ,4,"$name, hole $audio3";
  1203. }
  1204. if ($a[2] ne "-")
  1205. {
  1206. my $ret = SIP_create_T2S_File($hash,@a);
  1207. if ($ret)
  1208. {
  1209. delete $hash->{audio1} if defined($hash->{audio1});
  1210. delete $hash->{audio2} if defined($hash->{audio2});
  1211. delete $hash->{audio3} if defined($hash->{audio3});
  1212. return $ret;
  1213. }
  1214. #starte die Überwachung von T2S
  1215. RemoveInternalTimer($hash);
  1216. InternalTimer(gettimeofday()+int(AttrVal($name,"T2S_Timeout",5)), "SIP_watchdog_T2S", $hash);
  1217. return undef;
  1218. }
  1219. $hash->{helper}{LISTEN_PID} = BlockingCall("SIP_ListenStart",$name, "SIP_ListenDone") unless(exists($hash->{helper}{LISTEN_PID}));
  1220. if ($hash->{helper}{LISTEN_PID})
  1221. {
  1222. $hash->{LPID} = $hash->{helper}{LISTEN_PID}{pid};
  1223. Log3 $name, 4 , $name.", Listen new PID : ".$hash->{LPID};
  1224. RemoveInternalTimer($name);
  1225. InternalTimer(gettimeofday()+$waits, "SIP_watch_listen", $name); # starte die Überwachung
  1226. delete $hash->{audio1};
  1227. delete $hash->{audio2};
  1228. delete $hash->{audio3};
  1229. return 0;
  1230. }
  1231. else
  1232. {
  1233. Log3 $name, 2 , $name.", Listen Start failed, waiting $waits seconds for next try";
  1234. RemoveInternalTimer($hash);
  1235. InternalTimer(gettimeofday()+$waits, "SIP_try_listen", $hash);
  1236. return "Listen Start failed";
  1237. }
  1238. }
  1239. sub SIP_watch_listen($)
  1240. {
  1241. # Lebt denn der Listen Prozess überhaupt noch ?
  1242. my ($name) = @_;
  1243. my $hash = $defs{$name};
  1244. my $listen_dead = 0;
  1245. RemoveInternalTimer($name);
  1246. return if (IsDisabled($name));
  1247. return if (!defined($hash->{LPID}));
  1248. my $cmd = "ps -e | grep '".$hash->{LPID}." '";
  1249. my $result = qx($cmd);
  1250. my $age = int(ReadingsAge($name, "expire", 0));
  1251. my $maxage = int(ReadingsNum($name,"expire",300)*0.7);
  1252. my $alive = ReadingsVal($name,"listen_alive","no");
  1253. my $waits = AttrVal($name, "sip_watch_listen", 60);
  1254. if (($age > $maxage) && ($alive ne "no")) # nach expire/2 Sekunden sollte sich der listen Prozess erneut melden
  1255. {
  1256. Log3 $name, 2 , "$name, expire timestamp is $age seconds old, restarting listen process";
  1257. readingsSingleUpdate($hash,"listen_alive","no",1);
  1258. $alive = "no";
  1259. }
  1260. elsif (index($result,"perl") == -1)
  1261. {
  1262. Log3 $name, 2 , $name.", cant find listen process ".$hash->{LPID}." in process list !";
  1263. $alive = "no";;
  1264. }
  1265. else { Log3 $name, 5 , $name.", listen process ".$hash->{LPID}." found"; }
  1266. if ($alive eq "no")
  1267. {
  1268. BlockingKill($hash->{helper}{LISTEN_PID});
  1269. delete $hash->{helper}{LISTEN_PID};
  1270. delete $hash->{LPID};
  1271. InternalTimer(gettimeofday()+2, "SIP_try_listen", $hash, 0);
  1272. }
  1273. InternalTimer(gettimeofday()+$waits, "SIP_watch_listen", $name, 0);
  1274. return;
  1275. }
  1276. sub SIP_wait_for_t2s($)
  1277. {
  1278. my ($hash) = @_;
  1279. my $name = $hash->{NAME};
  1280. RemoveInternalTimer($hash);
  1281. my $t2s_name = AttrVal($name,"T2S_Device",undef);
  1282. my $file = ReadingsVal($t2s_name,"lastFilename","");
  1283. my $msg = "";
  1284. Log3 $name,4,"$name, wait_for_t2s file : $file";
  1285. if ($file)
  1286. {
  1287. Log3 $name,4,"$name, new T2S file $file";
  1288. my $out = $file;
  1289. $out =~ s/mp3/alaw/;
  1290. if (-e $out)
  1291. {
  1292. Log3 $name,5,"$name, not converted using $out from cache";
  1293. $msg = $out;
  1294. }
  1295. else
  1296. {
  1297. my $ret;
  1298. my $cmd;
  1299. my $converter = AttrVal($name,"audio_converter","sox");
  1300. if (($converter eq "sox") && defined($hash->{AC}))
  1301. {
  1302. $cmd = $hash->{AC}." ".$file." -t raw -r 8000 -c 1 -e a-law ".$out;
  1303. Log3 $name,5,"$name, $cmd";
  1304. $_ = qx($cmd);
  1305. }
  1306. elsif (($converter eq "ffmpeg") && defined($hash->{AC}))
  1307. {
  1308. $cmd = $hash->{AC}." -v quiet -y -i ".$file." -f alaw -ar 8000 ".$out;
  1309. Log3 $name,5,"$name, $cmd";
  1310. $_ = qx($cmd);
  1311. }
  1312. if ($_)
  1313. {
  1314. Log3 $name,4,"$name, $converter : $_ , $?";
  1315. readingsSingleUpdate($hash,"last_error","$converter error $_",1);
  1316. }
  1317. else { $msg = $out; }
  1318. }
  1319. }
  1320. else
  1321. {
  1322. Log3 $name,3,"$name, timeout waiting for T2S";
  1323. readingsSingleUpdate($hash,"call_state","T2S timeout",1);
  1324. }
  1325. if ($msg && defined($hash->{audio3}))
  1326. {
  1327. $hash->{audio3} = $msg;
  1328. SIP_try_listen($hash);
  1329. return undef;
  1330. }
  1331. if ($msg && defined($hash->{audio2}))
  1332. {
  1333. $hash->{audio2} = $msg;
  1334. SIP_try_listen($hash);
  1335. return undef;
  1336. }
  1337. if ($msg && defined($hash->{audio1}))
  1338. {
  1339. $hash->{audio1} = $msg;
  1340. SIP_try_listen($hash);
  1341. return undef;
  1342. }
  1343. # nun aber calling
  1344. my $repeat = "*".$hash->{repeat};
  1345. my @a;
  1346. if ($hash->{forcecall})
  1347. { @a = ($name,"call",$hash->{callnr}, $hash->{ringtime},$msg,$repeat,$hash->{forcecall}) ; }
  1348. else
  1349. { @a = ($name,"call",$hash->{callnr}, $hash->{ringtime},$msg,$repeat) ; }
  1350. delete($hash->{callnr});
  1351. delete($hash->{ringtime});
  1352. delete($hash->{forcecall});
  1353. delete($hash->{repeat});
  1354. my $ret = SIP_Set($hash , @a);
  1355. Log3 $name,3,"$name, error T2S Call : $ret" if defined($ret);
  1356. return undef;
  1357. }
  1358. sub SIP_telnetPort()
  1359. {
  1360. foreach my $d (sort keys %defs)
  1361. {
  1362. my $h = $defs{$d};
  1363. next if(!$h->{TYPE} || $h->{TYPE} ne "telnet" || $h->{SNAME});
  1364. next if($attr{$d}{SSL} || AttrVal($d, "allowfrom", "127.0.0.1") ne "127.0.0.1");
  1365. next if($h->{DEF} !~ m/^\d+( global)?$/);
  1366. next if($h->{DEF} =~ m/IPV6/);
  1367. my %cDev = ( SNAME=>$d, TYPE=>$h->{TYPE}, NAME=>$d.time() );
  1368. next if(Authenticate(\%cDev, undef) == 2); # Needs password
  1369. #$hash->{telnetPort} = $defs{$d}{"PORT"};
  1370. #last;
  1371. return $defs{$d}{"PORT"};
  1372. }
  1373. return 0;
  1374. }
  1375. sub SIP_telnet($$)
  1376. {
  1377. my ($hash,$cmd) = @_;
  1378. my $name = $hash->{NAME};
  1379. my $logname = $name."[".$$."]";
  1380. my $txt = $cmd;
  1381. $txt =~ s/\n/ /g;
  1382. Log3 $name, 5, "$logname, telnet : $txt";
  1383. my $sock = IO::Socket::INET->new(
  1384. PeerHost => "127.0.0.1",
  1385. PeerPort => $hash->{telnetPort},
  1386. Proto => 'tcp',
  1387. Timeout => 2);
  1388. if ($sock)
  1389. {
  1390. print $sock "$cmd";
  1391. if (substr($cmd,0,3) eq "get")
  1392. {
  1393. while (<$sock>) { last if $_ ; } # end of output
  1394. #$_ =~ s/.* //; # ?? warum ?
  1395. $_ =~ s/\n//;
  1396. print $sock "exit\n";
  1397. }
  1398. close($sock);
  1399. return $_;
  1400. }
  1401. return undef;
  1402. }
  1403. ######################################################
  1404. # storePW & readPW Code geklaut aus 72_FRITZBOX.pm :)
  1405. ######################################################
  1406. sub SIP_storePassword($$)
  1407. {
  1408. my ($name, $password) = @_;
  1409. my $index = "SIP_".$name."_passwd";
  1410. my $key = getUniqueId().$index;
  1411. my $e_pwd = "";
  1412. if (eval "use Digest::MD5;1")
  1413. {
  1414. $key = Digest::MD5::md5_hex(unpack "H*", $key);
  1415. $key .= Digest::MD5::md5_hex($key);
  1416. }
  1417. for my $char (split //, $password)
  1418. {
  1419. my $encode=chop($key);
  1420. $e_pwd.=sprintf("%.2x",ord($char)^ord($encode));
  1421. $key=$encode.$key;
  1422. }
  1423. my $error = setKeyValue($index, $e_pwd);
  1424. return "error while saving SIP user password : $error" if(defined($error));
  1425. return "SIP user password successfully saved in FhemUtils/uniqueID Key $index";
  1426. }
  1427. sub SIP_readPassword($)
  1428. {
  1429. my ($name) = @_;
  1430. my $index = "SIP_".$name."_passwd";
  1431. my $key = getUniqueId().$index;
  1432. my ($password, $error);
  1433. #Log3 $name,5,"$name, read SIP user password from FhemUtils/uniqueID Key $key";
  1434. ($error, $password) = getKeyValue($index);
  1435. if ( defined($error) )
  1436. {
  1437. Log3 $name,3, "$name, cant't read SIP user password from FhemUtils/uniqueID: $error";
  1438. return undef;
  1439. }
  1440. if ( defined($password) )
  1441. {
  1442. if (eval "use Digest::MD5;1")
  1443. {
  1444. $key = Digest::MD5::md5_hex(unpack "H*", $key);
  1445. $key .= Digest::MD5::md5_hex($key);
  1446. }
  1447. my $dec_pwd = '';
  1448. for my $char (map { pack('C', hex($_)) } ($password =~ /(..)/g))
  1449. {
  1450. my $decode=chop($key);
  1451. $dec_pwd.=chr(ord($char)^ord($decode));
  1452. $key=$decode.$key;
  1453. }
  1454. return $dec_pwd;
  1455. }
  1456. else
  1457. {
  1458. Log3 $name,3,"$name, no SIP user password found in FhemUtils/uniqueID";
  1459. return undef;
  1460. }
  1461. }
  1462. #####################################
  1463. sub SIP_check_file($$)
  1464. {
  1465. my ($hash,$file) = @_;
  1466. my $name = $hash->{NAME};
  1467. my $logname = $name."[".$$."]";
  1468. if (substr($file,0,1) eq "!")
  1469. {
  1470. Log3 $name,3,"$logname, Text : $file found, ignoring it";
  1471. return "";
  1472. }
  1473. if (!-e $file)
  1474. {
  1475. Log3 $name,3,"$logname, audio file $file not found, ignoring it";
  1476. return "";
  1477. }
  1478. if (($file !~ /\.al(.+)$/) && ($file !~ /\.ul(.+)$/))
  1479. {
  1480. Log3 $name,3,"$logname, audio file $file not type .alaw or .ulaw, ignoring it";
  1481. return "";
  1482. }
  1483. return $file;
  1484. }
  1485. sub SIP_create_T2S_File($@)
  1486. {
  1487. my ($hash,@a) = @_;
  1488. my $name = $hash->{NAME};
  1489. my $t2s_name = AttrVal($name,"T2S_Device",undef);
  1490. return "attr T2S_Device not set !" if !defined($t2s_name);
  1491. my $t2s_hash = $defs{$t2s_name};
  1492. return "T2S_Device $t2s_name not found" if !defined($t2s_hash);
  1493. return "attr audio_converter not set" if !AttrVal($name,"audio_converter","");
  1494. return "external sox or ffmpeg programm not found, please install sox or ffmpeg first and set attr audio_converter" if !defined($hash->{AC});
  1495. my $t2s_file = ReadingsVal($t2s_name,"lastFilename",undef);
  1496. Log3 $name,3,"$name, Reading lastFilename not found at device $t2s_name, are you using a old version ?" if !defined($t2s_file);
  1497. readingsSingleUpdate($t2s_hash,"lastFilename","",0);
  1498. my $ret = Text2Speech_Set($t2s_hash, @a); # na dann lege schon mal los
  1499. if (defined($ret))
  1500. {
  1501. Log3 $name,3,"$name, T2S error : $ret";
  1502. readingsSingleUpdate($hash,"last_error",$ret,0);
  1503. return $ret; # Das ging leider schief
  1504. }
  1505. return undef; # alles klar
  1506. }
  1507. sub SIP_watchdog_T2S($)
  1508. {
  1509. my ($hash) = @_;
  1510. my $name = $hash->{NAME};
  1511. Log3 $name,3,"$name, Timeout waiting for T2S";
  1512. if (defined($hash->{audio1}))
  1513. {
  1514. $hash->{audio1}="!T2S Timeout";
  1515. SIP_try_listen($hash);
  1516. return undef;
  1517. }
  1518. if (defined($hash->{audio2}))
  1519. {
  1520. $hash->{audio2}="!T2S Timeout";
  1521. SIP_try_listen($hash);
  1522. return undef;
  1523. }
  1524. if (defined($hash->{audio3}))
  1525. {
  1526. $hash->{audio3}="!T2S Timeout";
  1527. SIP_try_listen($hash);
  1528. return undef;
  1529. }
  1530. }
  1531. 1;
  1532. =pod
  1533. =item helper
  1534. =item summary SIP device
  1535. =item summary_DE SIP Ger&auml;t
  1536. =begin html
  1537. <a name="SIP"></a>
  1538. <h3>SIP</h3>
  1539. <ul>
  1540. Define a SIP-Client device.
  1541. <br><br>
  1542. <a name="SIPdefine"></a>
  1543. <b>Define</b>
  1544. <ul>
  1545. <code>define &lt;name&gt; SIP</code>
  1546. <br><br>
  1547. Example:
  1548. <ul>
  1549. <code>define MySipClient SIP</code><br>
  1550. </ul>
  1551. </ul>
  1552. <br>
  1553. <a name="SIPset"></a>
  1554. <b>Set</b>
  1555. <ul>
  1556. <li>
  1557. <code>set &lt;name&gt; &lt;SIP password&gt;</code><br>
  1558. Stores the password for the SIP users. Without stored password the functions set call and set listen are blocked !<br>
  1559. IMPORTANT : if you rename the fhem Device you must set the password again!
  1560. </li>
  1561. <li>
  1562. <code>set &lt;name&gt; reset</code><br>
  1563. Stop any listen process and initialize device.<br>
  1564. </li>
  1565. <li>
  1566. <code>set &lt;name&gt; call &lt;number&gt [&lt;maxtime&gt;] [&lt;message&gt;]</code><br>
  1567. Start a call to the given number.<br>
  1568. Optionally you can supply a max time. Default is 30.
  1569. Optionally you can supply a message which is either a full path to an audio file or a relativ path starting from the home directory of the fhem.pl.
  1570. </li>
  1571. <li>
  1572. <code>set &lt;name&gt; listen</code><br>
  1573. attr sip_listen = dtmf :<br>
  1574. Start a listening process that receives calls. The device goes into an echo mode when a call comes in. If you press # on the keypad followed by 2 numbers and hang up the reading <b>dtmf</b> will reflect that number.<br>
  1575. attr sip_listen = wfp :<br>
  1576. Start a listening process that waits for incoming calls. If a call comes in for the SIP-Client the state will change to <b>ringing</b>. If you manually set the state to <b>fetch</b> the call will be picked up and the sound file given in attribute sip_audiofile will be played to the caller. After that the devive will go gack into state <b>listenwfp</b>.<br>
  1577. </li>
  1578. </ul>
  1579. <br>
  1580. <a name="SIPattr"></a>
  1581. <b>Attributes</b>
  1582. <ul>
  1583. <li><a href="#sip_audiofile_wfp">sip_audiofile_wfp</a><br>
  1584. Audio file that will be played after <b>fetch</b> command. The audio file has to be generated via <br>
  1585. sox &lt;file&gt;.wav -t raw -r 8000 -c 1 -e a-law &lt;file&gt;.al<br>
  1586. since only raw audio format is supported.
  1587. </li>
  1588. <li><a href="#sip_audiofile_call">sip_audiofile_call</a></li>
  1589. <li><a href="#sip_audiofile_dtmf">sip_audiofile_dtmf</a></li>
  1590. <li><a href="#sip_audiofile_ok">sip_audiofile_ok</a></li>
  1591. <li><a href="#sip_listen">sip_listen</a>(none , dtmf , wfp)</li>
  1592. <li><a name="#sip_from">sip_from</a><br>
  1593. My sip client info, defaults to sip:620@fritz.box
  1594. </li>
  1595. <li><a name="#sip_ip">sip_ip</a><br>
  1596. external IP address of the FHEM server.
  1597. </li>
  1598. <li><a name="#sip_port">sip_port</a><br>
  1599. Optionally portnumber used for sip client<br>
  1600. If attribute is not set a random port number between 44000 and 45000 will be used
  1601. </li>
  1602. <li><a name="#sip_registrar">sip_registrar</a><br>
  1603. Hostname or IP address of the SIP server you are connecting to, defaults to fritz.box.
  1604. </li>
  1605. <li><a name="#sip_ringtime">sip_ringtime</a><br>
  1606. Ringtime for incomming calls (dtmf &wfp)
  1607. </li>
  1608. <li><a name="#sip_user">sip_user</a><br>
  1609. User name of the SIP client, defaults to 620.
  1610. </li>
  1611. <li><a name="#sip_waittime">sip_waittime</a><br>
  1612. Maximum waiting time in state listen_for_wfp it will wait to pick up the call.
  1613. </li>
  1614. <li><a name="#sip_dtmf_size">sip_dtmf_size</a><br>
  1615. 1 to 4 , default is 2 ...
  1616. </li>
  1617. <li><a name="#sip_dtmf_loop">sip_dtmf_loop</a><br>
  1618. once or loop , default once ...
  1619. </li>
  1620. </ul>
  1621. <br>
  1622. </ul>
  1623. =end html
  1624. =begin html_DE
  1625. <a name="SIP"></a>
  1626. <h3>SIP</h3>
  1627. <ul>
  1628. Definiert ein SIP-Client Device.
  1629. <br><br>
  1630. <a name="SIPdefine"></a>
  1631. <b>Define</b>
  1632. <ul>
  1633. <code>define &lt;name&gt; SIP</code>
  1634. <br><br>
  1635. Beispiel:
  1636. <ul>
  1637. <code>define MySipClient SIP</code><br>
  1638. </ul>
  1639. </ul>
  1640. <br>
  1641. <a name="SIPset"></a>
  1642. <b>Set</b>
  1643. <ul>
  1644. <li>
  1645. <code>set &lt;name&gt; &lt;SIP Passwort&gt;</code><br>
  1646. Speichert das Passwort des SIP Users. Ohne gespeichertes Passwort sind die set call und set listen Funktionen gesperrt !<br>
  1647. WICHTIG : wird das SIP Device umbenannt muss dieser Befehl unbedingt wiederholt werden !
  1648. </li>
  1649. <li>
  1650. <code>set &lt;name&gt; reset</code><br>
  1651. Stoppt laufende listen-Prozess und initalisiert das Device.<br>
  1652. </li>
  1653. <li>
  1654. <code>set &lt;name&gt; call &lt;nummer&gt; [&lt;maxtime&gt;] [&lt;nachricht&gt;]</code><br>
  1655. Startet einen Anruf an die angegebene Nummer.<br>
  1656. Optional kann die maximale Zeit angegeben werden. Default ist 30.<br>
  1657. Optional kann eine Nachricht in Form eines Audiofiles angegeben werden . Das File ist mit dem vollen Pfad oder dem relativen ab dem Verzeichnis mit fhem.pl anzugeben..
  1658. </li>
  1659. <li>
  1660. <code>set &lt;name&gt; listen</code><br>
  1661. Attribut sip_listen = dtmf :
  1662. Der SIP-Client wird in einen Status versetzt in dem er Anrufe annimmt. Der Ton wird als Echo zurückgespielt. Über die Eingabe von # gefolgt von 2 unterschiedlichen Zahlen und anschließendem Auflegen kann eine Zahl in das Reading <b>dtmf</b> übergeben werden.<br>
  1663. Attribut sip_listen = wfp :
  1664. Der SIP-Client wird in einen Status versetzt in dem er auf Anrufe wartet. Erfolgt an Anruf an den Client, wechselt der Status zu <b>ringing</b>. Nun kann das Gespräch via set-Command <b>fetch</b> angenommen werden. Das als sip_audiofile angegebene File wird abgespielt. Anschließend wechselt der Status wieder zu <b>listenwfp</b>.<br>
  1665. </li>
  1666. </ul>
  1667. <br>
  1668. <a name="SIPattr"></a>
  1669. <b>Attributes</b>
  1670. <ul>
  1671. <li><a name="#sip_user">sip_user</a><br>
  1672. User Name des SIP-Clients. Default ist 620 (Fritzbox erstes SIP Telefon)
  1673. </li>
  1674. <li><a name="#sip_registrar">sip_registrar</a><br>
  1675. Hostname oder IP-Addresse des SIP-Servers mit dem sich das Modul verbinden soll. (Default fritz.box)
  1676. </li>
  1677. <li><a name="#sip_from">sip_from</a><br>
  1678. SIP-Client-Info. Syntax : sip:sip_user@sip_registrar Default ist sip:620@fritz.box
  1679. </li>
  1680. <li><a name="#sip_ip">sip_ip</a><br>
  1681. Die IP-Addresse von FHEM im Heimnetz. Solange das Attribut nicht gesetzt ist versucht das Modul diese beim Start zu ermitteln.
  1682. </li>
  1683. <li><a name="#sip_port">sip_port</a><br>
  1684. Optinale Portnummer die vom Modul benutzt wird.<br>
  1685. Wenn dem Attribut kein Wert zugewiesen wurde verwendet das Modul eine zuf&auml;llige Portnummer zwichen 44000 und 45000
  1686. </li>
  1687. <li><b>Audiofiles</b>
  1688. Audiofiles k&ouml;nnen einfach mit dem externen Programm sox erzeugt werden :<br>
  1689. sox &lt;file&gt;.wav -t raw -r 8000 -c 1 -e a-law &lt;file&gt;.al<br>
  1690. Unterst&uuml;tzt werden nur die beiden RAW Audio Formate a-law und u-law !<br>
  1691. Statt eines echten Audiofiles kann auch eine Text2Speech Nachricht eingetragen werden.<br>
  1692. Bsp : attr mySIP sip_audiofile_call !Hier ist dein FHEM Server
  1693. </li>
  1694. <li><a href="#sip_audiofile_wfp">sip_audiofile_wfp</a><br>
  1695. Audiofile das nach dem Command <b>fetch</b> abgespielt wird.
  1696. </li>
  1697. <li><a href="#sip_audiofile_call">sip_audiofile_call</a></li>
  1698. Audiofile das dem Angerufenen bei set call vorgespielt wird.
  1699. <li><a href="#sip_audiofile_dtmf">sip_audiofile_dtmf</a></li>
  1700. Audiofile das dem Anrufer bei listen_for_dtmf abgespielt wird.
  1701. <li><a href="#sip_audiofile_ok">sip_audiofile_ok</a></li>
  1702. Audiofile das bei erkannter DTMF Sequenz abgespielt wird.
  1703. <li><a href="#sip_listen">sip_listen</a> (none , dtmf, wfp)</li>
  1704. <li><a name="#sip_ringtime">sip_ringtime</a><br>
  1705. Klingelzeit für eingehende Anrufe bei listen_for_dtmf
  1706. </li>
  1707. <li><a name="#sip_dtmf_size">sip_dtmf_size</a><br>
  1708. 1 bis 4 , default 2 Legt die L&auml;ge des erwartenden DTMF Events fest.
  1709. </li>
  1710. <li><a name="#sip_dtmf_loop">sip_dtmf_loop</a><br>
  1711. once oder loop , default once ...
  1712. </li>
  1713. <li><a name="#sip_waittime">sip_waittime</a><br>
  1714. Maximale Wartezeit im Status listen_for_wfp bis das Gespr&auml;ch automatisch angenommen wird.
  1715. </li>
  1716. <li>T2S_Device<br>
  1717. Name des Text2Speech Devices (Wird nur ben&ouml;tigt wenn Sprachnachrichten statt Audiofiles verwendet werden)
  1718. </li>
  1719. <li>T2S_Timeout<br>
  1720. Wartezeit in Sekunden wie lange maximal auf Text2Speech gewartet wird.
  1721. </li>
  1722. <li>audo_converter<br>sox oder ffmpeg, default sox<br>
  1723. Ist f&uml;r Text2Speech unbedingt erforderlich um die mp3 Dateien in Raw Audio umzuwandeln.<br>
  1724. Installation z.B. mit sudo apt-get install sox und noch die mp3 Unterst&uuml;tzung mit sudo apt-get install libsox-fmt-mp3
  1725. </li>
  1726. </ul>
  1727. <br>
  1728. </ul>
  1729. =end html_DE
  1730. =cut