PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/v2-29/mh/bin/mh

#
Perl | 1639 lines | 1231 code | 200 blank | 208 comment | 224 complexity | 410db3e73a4f103af5e4a6ee024de4f2 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.0, GPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. #!/usr/bin/perl
  2. # -*- Perl -*-
  3. # Last change Time-stamp: <2000-10-01 18:13:57 winter>
  4. #---------------------------------------------------------------------------
  5. # File:
  6. # mh
  7. # Description:
  8. # A perl script that does home control functions
  9. # Author:
  10. # Bruce Winter bruce@misterhouse.net
  11. # Latest version:
  12. # http://misterhouse.net
  13. #
  14. # Change log:
  15. # - 03/07/98 Created from house_menu.
  16. # - The rest of the change log is at the bottom of this file.
  17. #
  18. # Documentation is in mh/docs/mh.html (from mh.pod) and mh/docs/install.html
  19. #
  20. # This free software is licensed under the terms of the GNU public license.
  21. # Copyright 1998-2000 Bruce Winter
  22. #
  23. #---------------------------------------------------------------------------
  24. use strict;
  25. my ($Pgm_Name, $Revision, $usage);
  26. # So we can get at it from other packages
  27. use vars qw(%config_parms %config_parms_startup $Pgm_Path $Version $Version_date);
  28. BEGIN {
  29. ($Version) = q$Revision: 110 $ =~ /: (\S+)/; # Auto-updated by CVS
  30. $0 = $ENV{sourceExe} if $ENV{sourceExe}; # perl2exe fills this in
  31. ($Pgm_Path, $Pgm_Name) = $0 =~ /^(.*)[\\\/]([^.]+)/i;
  32. ($Pgm_Name) = $0 =~ /([^.]+)/i unless $Pgm_Name;
  33. $Pgm_Name = 'mh' if $ENV{sourceExe}; # Since we sometimes rename mh.exe
  34. unless ($Pgm_Path) {
  35. use Cwd;
  36. $Pgm_Path = cwd();
  37. # When we do system calls in Dos, we need \, not /
  38. $Pgm_Path =~ tr!\/!\\! if $^O eq "MSWin32";
  39. }
  40. $usage =<<eof;
  41. Description:
  42. $Pgm_Name is a perl program for time, event, web, and voice based home control
  43. functions. Configuration is controled in the \\mh\\bin\\$Pgm_Name.ini file.
  44. See the \\mh\\docs\\$Pgm_Name.html for more info.
  45. Usage:
  46. $Pgm_Name [options] [files]
  47. Where options can be any of the parms listed in the \\mh\\bin\\$Pgm_Name.ini file
  48. Examples usage:
  49. $Pgm_Name
  50. $Pgm_Name -help
  51. $Pgm_Name -tk 0 -code_dir c:\\mh\\code\\test
  52. $Pgm_Name -log_file test1.log -debug 1 test1.pl
  53. eof
  54. }
  55. # Use var instead of my so we can get these in the http_server.pl scripts
  56. use vars qw($Time_Start_time $Time_Stop_time $Time_Increment $Time_Startup $Time_Startup_time $Time_Boot_time $Time_Uptime_Seconds);
  57. use vars qw($Time_Sunrise $Time_Sunrise_Twilight $Time_Sunset $Time_Sunset_Twilight %Moon $Time_Now $Time_Date $Date_Now $Date_Now_Speakable $Year_Month_Now);
  58. use vars qw($Time $Second $Minute $Hour $Mday $Wday $Day $Month $Year);
  59. use vars qw($New_Second $New_Minute $New_Hour $New_Day $New_Week $New_Month $New_Year);
  60. use vars qw($Season $Weekday $Weekend $Holiday $Time_Of_Day);
  61. use vars qw($Startup $Reload $Reread $Loop_Count $Last_Response $Category);
  62. use vars qw($Version_tk $Password);
  63. my ($Pgm_PathU);
  64. my (@Loop_Speeds, $Loop_Sleep_Time, $Loop_Tk_Passes);
  65. my ($Loop_Speed);
  66. my (@Requested_Files, @Print_Log, @Display_Log, @Speak_Log);
  67. my ($exit_flag, $xcmd_file, %file_code_times, %file_code_times2, %file_change_times);
  68. my (%User_Code, @Loop_Code, @Sub_Code, %Run_Members, @Item_Code, @Item_Code_Objects);
  69. my ($user_code, $user_code_last_good);
  70. my (%objects_by_object_name, %file_by_object_name, %files_by_webname);
  71. my (%object_names_by_file, %object_names_by_type, %object_names_by_webname, $pause_mode);
  72. my (%prev_serial_event, @Generic_Serial_Ports, @Server_Ports, , %Local_Addresses, @Local_Addresses, @Password_Allow_Clients);
  73. my ($CON_IN, $CON_OUT);
  74. #use vars '$CON_IN', '$CON_OUT';
  75. my($state, $temp); # Some generic useful vars
  76. use vars '%Tk_objects', '%Tk_results', '@Tk_widgets', '@Object_Types'; # So we can use in http_server
  77. use vars '$MW'; # So that programs that we 'do' can use the top window
  78. use vars '%Serial_Ports'; # So we can get at it from the Serial_Item package.
  79. use vars '%Socket_Ports';
  80. use vars '%Save';
  81. use vars '%Info', '$OS_win';
  82. use vars '%Password_Allow'; # So we can see check it from http_server.pl
  83. use vars '$Pgm_Root'; # So we can see it in eval var subs in read_parms
  84. use vars '$DNS_resolver';
  85. # Pre-declare these so we don't fail on non-windows platforms
  86. sub Win32::GetOSVersion;
  87. sub Win32::FsType;
  88. sub Win32::GetCwd;
  89. sub Win32::LoginName;
  90. sub Win32::NodeName;
  91. sub Win32::IsWinNT;
  92. sub Win32::IsWin95;
  93. sub Win32::GetTickCount;
  94. sub Win32::DriveInfo::DrivesInUse;
  95. &setup;
  96. &read_code; # Load all menus
  97. &monitor_commands;
  98. BEGIN {
  99. &check_for_run_cmd;
  100. &print_version;
  101. &check_usage;
  102. &setup_INC;
  103. &read_parms;
  104. &use_conditional_modules;
  105. print "Loading other modules\n";
  106. sub check_for_run_cmd {
  107. # This lets us use mh as a perl interpreter for running arbitrary perl code
  108. if ($ARGV[0] and $ARGV[0] eq '-run') {
  109. # @ARGV = split(/[, ]/, $config_parms{run_parms});
  110. shift @ARGV;
  111. my $pgm = shift @ARGV;
  112. my $pgm_path = $pgm;
  113. # Best to change to the mh bin dir, so their Paths are correct.
  114. # $pgm_path = "$Pgm_Path/$pgm" unless -e $pgm_path;
  115. chdir $Pgm_Path unless -e $pgm_path;
  116. unless (-e $pgm_path) {
  117. print "\nCan not find -run pgm: $pgm\n\n";
  118. exit;
  119. }
  120. print "\nRunning: $pgm_path @ARGV\n";
  121. $0 = $pgm; # Reset program name from mh to $pgm
  122. do "$pgm_path";
  123. print "Error with $pgm: $@\n" if $@;
  124. print "\nDone running: $pgm\n";
  125. exit;
  126. }
  127. }
  128. sub print_version {
  129. $Version_date= localtime((stat $0)[9]);
  130. # perl2exe sets this var
  131. if ($ENV{sourceExe}) {
  132. $Version_date= localtime((stat $ENV{sourceExe})[9]);
  133. $Version .= " (compiled)" unless $Version =~ /compiled/;
  134. }
  135. ($Pgm_PathU = $Pgm_Path) =~ tr/\\/\//;
  136. $Pgm_Root = "$Pgm_PathU/..";
  137. $OS_win = ($^O eq "MSWin32") ? 1 : 0;
  138. # Win95: MSWin32 Win95 B 4 0 67306684 1 FAT32
  139. # Win98: MSWin32 Win95 4 10 67766222 1 FAT
  140. if ($OS_win) {
  141. $Info{OS_version} = join(' ', Win32::GetOSVersion);
  142. $Info{OS_name} = 'NT' if Win32::IsWinNT;
  143. $Info{OS_name} = 'Win95' if Win32::IsWin95;
  144. $Info{OS_filesystem} = Win32::FsType;
  145. $Info{User} = Win32::LoginName;
  146. $Info{Machine} = Win32::NodeName;
  147. }
  148. else {
  149. $Info{OS_name} = $^O;
  150. $Info{User} = $ENV{USER};
  151. $Info{Machine} = $ENV{HOSTNAME};
  152. }
  153. print "\nCommand: $Pgm_Name @ARGV\n";
  154. print "Pgm path : $Pgm_Path\n";
  155. print "Pgm version: $Version Last updated: $Version_date\n";
  156. $Info{Perl_version} = $];
  157. # BuildNumber doesn't work with perl2exe compile :(
  158. # - use eval to avoid problems with earlier version (e.g. build 502)
  159. $Info{Perl_version} .= " Build " . eval "&Win32::BuildNumber()" if $OS_win and !$ENV{sourceExe};
  160. print "Perl version: $Info{Perl_version}\n";
  161. print "OS version: $^O $Info{OS_name} $Info{OS_version} $Info{OS_filesystem}\n";
  162. print "Other : user=$Info{User} pid=$$ box=$Info{Machine} cpu=$ENV{PROCESSOR_ARCHITECTURE}-$ENV{PROCESSOR_LEVEL}\n";
  163. print "\n";
  164. }
  165. sub check_usage {
  166. # Get legal options from .ini file
  167. # my $parmfile = $Pgm_PathU . "/$Pgm_Name.ini";
  168. my $parmfile = $Pgm_PathU . "/mh.ini";
  169. open (PARMS, $parmfile) or die "Error, could not open parmfile $parmfile: $!\n";
  170. my @parms;
  171. while (<PARMS>) {
  172. push(@parms, "$1=s") if /^([^\s\#]+) *=/;
  173. }
  174. close PARMS;
  175. # print "db parms=@parms\n";
  176. use Getopt::Long;
  177. if (!&GetOptions(\%config_parms_startup, "h", "help", "run=s", "run_parms=s", @parms) or
  178. ($config_parms_startup{h} or $config_parms_startup{help})) {
  179. print $usage;
  180. exit;
  181. }
  182. }
  183. sub setup_INC {
  184. print "Setting up INC path ...";
  185. # Note, use lib messes up perl2exe, but eval use lib does not. Either use
  186. # eval use lib (only once, because it is slow in perl2exe) or comment out use lib
  187. # when compiling and use perl5lib env. Yuck.
  188. # - can not seem to get perl2exe to honor this. Guess we have to make sure
  189. # everything is compile by adding it to lib/mh_perl2exe_list.pl
  190. # eval "use lib '$Pgm_PathU/../lib', '$Pgm_PathU/../lib/site', '$Pgm_PathU', '../lib', '../lib/site', '.'";
  191. # eval "use lib '$Pgm_PathU/../lib', '$Pgm_PathU/../lib/site', '$Pgm_PathU'";
  192. # Use a push instead of a use lib, so we make sure the site perl libs come first, not last
  193. # - We need to support perl 5.005 and 5.6 at the same time. 5.005 win32 binaries
  194. # are distributed with mh (so user does not have to install them).
  195. # 5.6 users will be required to install them
  196. push (@INC, "$Pgm_PathU/../lib", "$Pgm_PathU/../lib/site", "$Pgm_PathU");
  197. # print "Error in use lib: $@\n" if $@; # Dang .. this error check messes up the compiled version!?? Gives 'can not find lib.pm' message
  198. print " done\n";
  199. require 'handy_utilities.pl'; # For misc. functions (e.g. time/date stamp routines)
  200. }
  201. sub read_parms {
  202. my $debug = 1 if $config_parms_startup{debug} and $config_parms_startup{debug} eq 'startup';
  203. &main::read_mh_opts(\%config_parms, $Pgm_PathU, $debug);
  204. # We need to honor starup parms, but a total reset messes up the tk debug button interface
  205. # %config_parms = (%config_parms, %config_parms_startup); # Last one (startup parms) wins
  206. for my $parm (keys %config_parms_startup) {
  207. $config_parms{$parm} = $config_parms_startup{$parm};
  208. }
  209. print "Code Directory: $config_parms{code_dir}\n";
  210. }
  211. sub use_conditional_modules {
  212. if ($config_parms{diagnostics} or $config_parms{w}) {
  213. print "Perl diaganotics module (perl -w) has been turned on\n";
  214. eval 'use diagnostics' if $config_parms{diagnostics};
  215. }
  216. # disable diagnostics;
  217. # This must be in a BEGIN in order for the 'use' to be conditional
  218. if ($OS_win) {
  219. print "Loading Windows modules\n";
  220. # Must use 'my_use' (evals) so unix doesn't croak on missing modules
  221. # Not sure what we gain/loose with ole lite
  222. # &my_use("Win32::DUN"); # Interface to rasdial
  223. &my_use("Win32::DriveInfo"); # For disk space free/total
  224. eval "use Win32::Console";
  225. print "\nError in loading module=Win32::Console:\n $@\n" if $@;
  226. &my_use("Win32::OLE");
  227. # &my_use("Win32::OLE qw(EVENTS)"); # EVENTS forces single-threaded apartment, so outlook.pl MAPI works
  228. # &my_use("Win32::OLE::lite");
  229. &my_use("Win32::Process");
  230. &my_use("Win32::Registry");
  231. # Note: Must use eval, not my_use, or exported pgms are not seen :(
  232. # - setupsup is not yet available for perl 5.6
  233. # - BuildNumber doesn't work with perl2exe compile
  234. # - Loaded from: http://jenda.krynicky.cz/perl/
  235. eval "use Win32::Setupsup qw(WaitForAnyWindow SendKeys)" if $ENV{sourceExe} or &Win32::BuildNumber() < 600;
  236. print "\nError in loading module=Win32::Setupsup:\n $@\n" if $@;
  237. eval "use Win32::Sound";
  238. print "\nError in loading module=Win32::Sound:\n $@\n" if $@;
  239. &my_use("Win32::SerialPort");
  240. &my_use("Win32::SoundEx"); # For Volume control
  241. &my_use("File::DosGlob 'glob'"); # Allow for globbing without perlglob.exe
  242. }
  243. else { # load the mutually-exclusive non-Windows modules
  244. &my_use("Device::SerialPort"); # Unix Posix verion of Win32 SerialPort
  245. }
  246. if ($config_parms{tk}) {
  247. print "Loading Tk modules ";
  248. eval "use Tk";
  249. # eval "use Tk qw/DoOneEvent DONT_WAIT ALL_EVENTS/";
  250. $Version_tk = $Tk::VERSION;
  251. print "Version $Tk::VERSION\n";
  252. if ($@) {
  253. print "\nError, perl Tk module is not installed.\nTk windows will be disabled with the -tk 0 option. Error:$@\n\n";
  254. $config_parms{tk} = 0;
  255. }
  256. else {
  257. &my_use("Display");
  258. }
  259. }
  260. }
  261. } # End BEGIN
  262. sub setup {
  263. print "Starting setup\n";
  264. $| = 1; # Turn on command buffering (e.g. flush on every print)
  265. my $logfile = $config_parms{log_file};
  266. $config_parms{log}++ if $logfile;
  267. $config_parms{log_file} = $Pgm_PathU . "/../mh.log" unless $config_parms{log_file};
  268. my $print_log = $Pgm_PathU . "/../mh.print.log";
  269. rename $print_log, $print_log . ".old";
  270. open PRINTLOG, ">$print_log" or die "Error, could not open print lotfile $print_log: $!\n";
  271. if ($config_parms{log}) {
  272. print "Output will be logged into $logfile\n";
  273. open STDOUT, ">$logfile" or die "Error, could not open logfile $logfile: $!\n";
  274. &print_version;
  275. }
  276. use Astro::MoonPhase;
  277. use Astro::SunTime;
  278. # use Barcode;
  279. use File::Basename;
  280. use File::Copy; # So we copy files
  281. use Fcntl; # To enable O_RDWR|O_CREAT
  282. # use Date::Parse; # For str2time
  283. # use Data::Dumper qw(Dumper DumperX);
  284. # use FreezeThaw qw(freeze thaw cmpStr safeFreeze cmpStrHard);
  285. use IO::Socket;
  286. use LWP::Simple; # For pgms like set_clock that need to grab data from urls
  287. # use MIME::Base64; # Needed for uudecode/uuencode in http_server and mhsend_server
  288. use Net::FTP; # For uploading stuff
  289. use Text::Wrap;
  290. use Time::Local; # For timelocal
  291. if ($config_parms{DNS_server}) {
  292. print "Loading DNS code ...";
  293. &my_use("Net::DNS::Resolver"); # for doing reverse DNS search
  294. $DNS_resolver = new Net::DNS::Resolver;
  295. $DNS_resolver->nameservers(split(',', $config_parms{DNS_server}));
  296. print " DNS set to $config_parms{DNS_server}\n";
  297. }
  298. &my_use("DB_File"); # Need by get_tv_grid
  299. use Timer; # This needs to be first, as it is used in Voice_Cmd (and elsewhere?)
  300. use File_Item;
  301. use Generic_Item;
  302. use Group;
  303. use IR_Item;
  304. # &my_use("Serial_Item"); # So we can add debug to Serial_Item.pm when running mh.exe
  305. use Serial_Item;
  306. use X10_Items;
  307. use iButton;
  308. use Hardware::iButton::Connection;
  309. use Socket_Item;
  310. use Process_Item;
  311. use Voice_Cmd;
  312. use Voice_Text;
  313. use Caller_ID;
  314. use constant; # To keep perl2exe happy
  315. use constant ON => 'on';
  316. use constant OFF => 'off';
  317. use constant STATUS => 'status';
  318. use constant OPEN => 'open';
  319. use constant CLOSE => 'close';
  320. use constant OPENED => 'opened';
  321. use constant CLOSED => 'closed';
  322. require 'handy_net_utilities.pl'; # For misc. net functions (e.g. net_mail_read)
  323. require 'console_utils.pl';
  324. require 'http_server.pl';
  325. if ($OS_win) {
  326. # These are the modules that perl2exe can not find on its own
  327. # Note: tk windows starts faster in mh.exe if we run this,
  328. # even though they are included with the perl2exe_include!
  329. # require 'mh_perl2exe_list.pl';
  330. #perl2exe_include mh_perl2exe_list.pl
  331. no strict 'subs'; # For non-win OS
  332. if (1) {
  333. $CON_IN = new Win32::Console STD_INPUT_HANDLE;
  334. $CON_OUT= new Win32::Console STD_OUTPUT_HANDLE;
  335. $CON_OUT->Title("Mister House");
  336. # use vars '$FG_WHITE', '$BG_CYAN';
  337. # &explodeAttr($CON_OUT, $FG_WHITE | $BG_CYAN);
  338. # $CON_OUT->Attr($FG_WHITE | $BG_CYAN);
  339. }
  340. }
  341. $SIG{INT} = \&sig_handler; # Exit cleanly with CTL-C
  342. $SIG{BREAK} = \&sig_handler if $OS_win; # Exit cleanly with BREAK
  343. $SIG{KILL} = \&sig_handler; # Exit cleanly with a kill signal
  344. $SIG{HUP} = \&read_code if !$OS_win; # Reload code (alias mhreload per info in mh.ini file)
  345. $SIG{PIPE} = \&sig_handler_pipe; # Web browsers can shut down sockets while we are sending data
  346. $SIG{CHLD} = 'IGNORE'; # So we don't create zombies when forking
  347. $config_parms{code_dir} = $Pgm_PathU . "/../code" unless $config_parms{code_dir};
  348. # Make various directories, if missing
  349. mkdir ("$config_parms{data_dir}/logs", 0777) unless -d "$config_parms{data_dir}/logs";
  350. mkdir ("$config_parms{data_dir}/web", 0777) unless -d "$config_parms{data_dir}/web";
  351. mkdir ("$config_parms{html_dir}/tv", 0777) unless -d "$config_parms{html_dir}/tv";
  352. mkdir ("$config_parms{html_dir}/tv/clicktv", 0777) unless -d "$config_parms{html_dir}/tv/clicktv";
  353. open(ERROR_LOG, ">>$config_parms{code_dir}/mh_temp.error_log") or
  354. print "Error, could not open error log $config_parms{code_dir}/-error_log-: $!\n";
  355. &add_hook_code;
  356. # print "parms=", join(":", %config_parms), "\n";
  357. if ($config_parms{voice_cmd}) {
  358. &Voice_Cmd::init;
  359. }
  360. if ($config_parms{voice_text}) {
  361. &Voice_Text::init;
  362. }
  363. # Find all defined socket and serial ports
  364. for my $parm (keys %config_parms) {
  365. next unless $config_parms{$parm}; # Ingore blank parms
  366. push(@Server_Ports, $1) if $parm =~ /(http)_port/;
  367. push(@Server_Ports, $1) if $parm =~ /(server\S+)_port/;
  368. push(@Generic_Serial_Ports, $1) if $parm =~ /(serial\S+)_port/;
  369. }
  370. # print "Server ports defined: @Server_Ports\n" if @Server_Ports;
  371. # print "Generic serial ports defined: @Generic_Serial_Ports\n" if @Generic_Serial_Ports;
  372. # print "Creating socket server ports: @Server_Ports\n" if @Server_Ports;
  373. print "Creating socket and serial objects\n";
  374. for my $port_name (@Server_Ports) {
  375. my $port = $config_parms{$port_name . "_port"};
  376. my $proto = $config_parms{$port_name . "_protocol"};
  377. my $datatype = $config_parms{$port_name . "_datatype"};
  378. $proto = 'tcp' unless $proto;
  379. $datatype = 'buffered' if $port_name eq 'http';
  380. $datatype = 'buffered' if $config_parms{$port_name . "_buffer"}; # Grandfathered syntax
  381. $datatype = '' unless $datatype;
  382. printf " - creating %-15s on %3s %5s %s\n", $port_name, $proto, $port, $datatype;
  383. $Socket_Ports{$port_name}{protocol} = $proto;
  384. $Socket_Ports{$port_name}{datatype} = $datatype;
  385. if ($proto eq 'tcp') {
  386. $Socket_Ports{$port_name}{sock} = new IO::Socket::INET->new(LocalPort => $port, Proto => 'tcp', Reuse => 1, Listen => 10) or
  387. die "Couldn't start a tcp server on $port_name $port: $@\nTo get mh to run, blank out or change the ${port}_port in mh.ini\n";
  388. } elsif ($proto eq 'udp') {
  389. $Socket_Ports{$port_name}{sock} = new IO::Socket::INET->new(LocalPort => $port, Proto => 'udp') or
  390. die "Couldn't start a udp server on $port_name $port: $@\n";
  391. $Socket_Ports{$port_name}{socka} = $Socket_Ports{$port_name}{sock}; # UDP ports are always "active"
  392. } else {
  393. die "Unknown protocol for $port_name \n";
  394. }
  395. }
  396. for my $port_name (@Generic_Serial_Ports) {
  397. &serial_port_create($port_name, $config_parms{$port_name . "_port"},
  398. $config_parms{$port_name . "_baudrate"},
  399. $config_parms{$port_name . "_handshake"},
  400. $config_parms{$port_name . "_datatype"});
  401. }
  402. # Create managed serial and server ports
  403. # This makes it easy to add new modules
  404. # for new serial/socket devices.
  405. # Manager must be available in lib directory
  406. # (e.g. Compool.pm)
  407. for my $parm (keys %config_parms) {
  408. next unless $config_parms{$parm};
  409. if ($parm =~ /^(\S+)_(serial|server)_port/) {
  410. if (-e "$Pgm_PathU/../lib/$1.pm") {
  411. print "Found managed $2 port=$1\nMH will now require $1.pm and call $1::$2_startup($parm)\n"
  412. if $config_parms{debug} eq 'startup';
  413. require "$1.pm";
  414. eval "&$1::$2_startup('$parm')";
  415. print "Startup errror on &$1::$2_startup('$parm'): $@\n" if $@;
  416. }
  417. else {
  418. print "No $1.pm file found for $parm\n";
  419. }
  420. }
  421. }
  422. if ($config_parms{weeder_port}) {
  423. $config_parms{weeder_baudrate} = 1200 unless $config_parms{weeder_baudrate};
  424. &serial_port_create('weeder', $config_parms{weeder_port}, $config_parms{weeder_baudrate}, 'dtr');
  425. $Serial_Ports{weeder}{process_data} = 1;
  426. }
  427. if ($config_parms{cm11_port}) {
  428. require 'ControlX10/CM11.pm';
  429. &serial_port_create('cm11', $config_parms{cm11_port}, 4800, 'none');
  430. }
  431. if ($config_parms{Homevision_port}) {
  432. require 'Homevision.pm';
  433. my($speed) = $config_parms{Homevision_baudrate} || 9600;
  434. if (&serial_port_create('Homevision', $config_parms{Homevision_port}, $speed, 'none')) {
  435. &Homevision::init($Serial_Ports{Homevision}{object}); # Turn on Echo mode
  436. }
  437. }
  438. if ($config_parms{Marrick_port}) {
  439. require 'Marrick.pm';
  440. my($speed) = $config_parms{Marrick_baudrate} || 9600;
  441. if (&serial_port_create('Marrick', $config_parms{Marrick_port}, $speed, 'none')) {
  442. &Marrick::init($Serial_Ports{Marrick}{object});
  443. }
  444. }
  445. if ($config_parms{HomeBase_port}) {
  446. require 'HomeBase.pm';
  447. my($speed) = $config_parms{HomeBase_baudrate} || 9600;
  448. if (&serial_port_create('HomeBase', $config_parms{HomeBase_port}, $speed, 'none')) {
  449. &HomeBase::init($Serial_Ports{HomeBase}{object}); # Turn on Echo mode
  450. }
  451. }
  452. if ($config_parms{ncpuxa_port}) {
  453. require 'ncpuxa_mh.pm';
  454. &ncpuxa_mh::init($config_parms{ncpuxa_port}); # Create socket connection
  455. }
  456. if ($config_parms{ibutton_port}) {
  457. &my_use("Hardware::iButton::Connection;");
  458. &iButton::connect($config_parms{ibutton_port});
  459. }
  460. # Do this one last, as it can share a serial port.
  461. if ($config_parms{cm17_port}) {
  462. require 'ControlX10/CM17.pm';
  463. &serial_port_create('cm17', $config_parms{cm17_port});
  464. }
  465. if($config_parms{weather_sblog_file} or
  466. $config_parms{weather_vwlog_file} or
  467. $config_parms{serial_wx200}) {
  468. require 'Weather.pm';
  469. &Weather_Data::Init();
  470. }
  471. if ($OS_win) {
  472. $Time_Boot_time = 0; # Gettickcount starts at computer boot
  473. }
  474. elsif ($^O eq 'linux') {
  475. # Linux output:
  476. # uptime: 2 hours 10:38pm up 2:10, 6 users, load average: 0.83, 0.45, 0.18
  477. # /proc/stat: cpu 10339 0
  478. # /proc/pid/stat: 732 (ghx2) S 565 732 376 1025 561 256 529 0 1194 0 142 35 0 0 0 0 0 0 499881 6688768 905 2147483647 134512640 134754096 3221224640 3221223956 1075917534 0 0 69632 17479 3222448608 0 0 17
  479. # Not sure if 1st number
  480. open(UPTIME, "/proc/uptime") or print "\nError: can't open /proc/uptime ($!)\n";
  481. my ($uptime, $idletime) = (<UPTIME> =~ /(\S+) (\S+)/);
  482. close UPTIME;
  483. $Time_Boot_time = time - $uptime;
  484. }
  485. $exit_flag = 0;
  486. $config_parms{sleep_time} = 50 unless defined $config_parms{sleep_time};
  487. $Loop_Sleep_Time = $config_parms{sleep_time};
  488. $config_parms{tk_passes} = 10 unless $config_parms{tk_passes};
  489. $config_parms{tk_font} = 'Times 10 bold' unless $config_parms{tk_font};
  490. $config_parms{tk_font_fixed} = 'Courier 10 bold' unless $config_parms{tk_font_fixed};
  491. $Loop_Tk_Passes = $config_parms{tk_passes};
  492. $Time = time;
  493. ($Second, $Minute, $Hour, $Mday, $Month, $Year) = localtime $Time; # Needed in my_str2time;
  494. $Time_Date = &time_date_stamp($config_parms{time_format_log} , $Time); # Needed by print_log
  495. $Month++;
  496. # Configure 'fast test mode' parms
  497. $Time_Increment = ($config_parms{time_increment}) ? $config_parms{time_increment} : 60;
  498. if ($config_parms{time_start} =~ /\S/) {
  499. $Loop_Sleep_Time = 0;
  500. $Loop_Tk_Passes = 1;
  501. $Time_Start_time = &my_str2time($config_parms{time_start});
  502. $Time = $Time_Start_time - $Time_Increment; # Cause we start the loop with an increment
  503. print "time_start=$config_parms{time_start} -> $Time_Start_time \n";
  504. }
  505. if ($config_parms{time_stop} =~ /\S/) {
  506. $Loop_Sleep_Time = 0;
  507. $Loop_Tk_Passes = 1;
  508. $Time_Stop_time = &my_str2time($config_parms{time_stop});
  509. $Time_Stop_time += 3600*24 if $Time_Stop_time < $Time_Start_time;
  510. print "time_stop =$config_parms{time_stop} -> $Time_Stop_time \n";
  511. }
  512. $Time_Startup_time = $Time;
  513. $Time_Startup = &time_date_stamp(9, $Time_Startup_time);
  514. $Startup = 1;
  515. if ($config_parms{pid_file}) {
  516. print "Process id $$ written to $config_parms{pid_file}\n";
  517. &file_write($config_parms{pid_file}, $$);
  518. }
  519. if ($config_parms{tk}) {
  520. &tk_setup_windows;
  521. }
  522. # $xcmd_file = "$config_parms{temp_dir}/house_cmd.cmd" if $config_parms{xcmd_file};
  523. # print "X command file: $config_parms{xcmd_file}\n" if $config_parms{xcmd_file};
  524. # Use eval to change $ENV{temp} to the real value ... this is done in read_opts now
  525. # eval "\$config_parms{xcmd_file} = qq[$config_parms{xcmd_file}]";
  526. print "External command file (xcmd_file): $config_parms{xcmd_file}\n" if $config_parms{xcmd_file};
  527. $config_parms{html_dir} = $config_parms{html_root} if $config_parms{html_root}; # Grandfather in the old name for this parm
  528. print "HTML file : $config_parms{html_dir}/$config_parms{html_file}\n";
  529. print "\nError, HTML file not found: $config_parms{html_dir}/$config_parms{html_file}\n\n" unless -e "$config_parms{html_dir}/$config_parms{html_file}";
  530. @Requested_Files = @ARGV;
  531. &password_read;
  532. srand(time() ^ ($$ + ($$ << 15)) ); # Set the randum number seed, used in time_random;
  533. $config_parms{max_log_entries} = 50 unless defined $config_parms{max_log_entries};
  534. $config_parms{max_state_log_entries} = 10 unless defined $config_parms{max_state_log_entries};
  535. $config_parms{time_format_log} = 12 unless $config_parms{time_format_log};
  536. print "Done with setup\n\n";
  537. }
  538. # The remaining subroutines are in alphabetical order
  539. # This code allows us to add dynamic user code hooks at various places.
  540. my (%hook_pointers, %hook_pointers_persistent, %hook_locations, %hook_parms);
  541. sub add_hook_code {
  542. %hook_locations = ( MainLoop_pre => 1, MainLoop_post => 1,
  543. Serial_match => 1,
  544. Reload_pre => 1, Reload_post => 1,
  545. Play_pre => 1, Play_post => 1,
  546. Speak_pre => 1, Speak_post => 1
  547. );
  548. for my $location (keys %hook_locations){
  549. my($accessors) = "
  550. sub ${location}_add_hook { return add_hook_ ( '$location', \@_ ) }
  551. sub ${location}_drop_hook { return drop_hook_( '$location', \@_ ) }
  552. sub ${location}_get_hooks { return get_hooks_( '$location' ) }
  553. sub ${location}_hooks { return run_hooks_( '$location', \@_ ) }
  554. ";
  555. eval $accessors;
  556. die "Eval error $@\n" if $@;
  557. }
  558. sub add_hook_ {
  559. my($location, $hook, $persistent, @parms) = @_;
  560. unless( defined( $hook_locations{$location} ) ){
  561. warn "Invalid hook location $location\n";
  562. return 0;
  563. }
  564. unless( ref $hook eq 'CODE' ){
  565. warn "Hook must be a code reference: hook=$hook\n";
  566. return 0;
  567. }
  568. $hook_pointers{$location} = [] unless defined ($hook_pointers{$location});
  569. push( @{$hook_pointers{$location}}, $hook );
  570. push( @{$hook_pointers_persistent{$location}}, $hook ) if $persistent;
  571. @{$hook_parms{$hook}} = @parms;
  572. return 1;
  573. }
  574. sub drop_hook_ {
  575. my($location, $hook ) = @_;
  576. unless( defined( $hook_locations{$location} ) ){
  577. warn "Invalid hook location $location\n";
  578. return 0;
  579. }
  580. if( defined ($hook_pointers{$location}) ){
  581. my($h)=$hook_pointers{$location};
  582. my($i)=-1;
  583. for ( $i=$#{$h}; $i >= 0; $i-- ) {
  584. last if ($hook == $h->[$i] );
  585. }
  586. # delete if the index returned is in range
  587. if ($i >=0 and $i <= $#{$h} ){
  588. splice( @{$h}, $i, 1 );
  589. return 1;
  590. }
  591. }
  592. warn "specified hook not found: $location\n";
  593. return 0;
  594. }
  595. sub get_hooks_ {
  596. my($location) = @_;
  597. return defined $hook_pointers{$location} ? @{$hook_pointers{$location}} : ();
  598. }
  599. # call all hooks with user specified args, if any
  600. sub run_hooks_ {
  601. # my($location) = @_;
  602. my $location = shift @_;
  603. for my $hook (&get_hooks_($location)){
  604. # Allow for parms passed in mh, and parms specified
  605. # with addhook.
  606. my @parms = (@_, @{$hook_parms{$hook}});
  607. &$hook(@parms);
  608. }
  609. }
  610. # This will keep hook code defined with the persistent
  611. # flag (e.g. module code that is defined on startup).
  612. # All other user code is undefed.
  613. sub reset_hook_code {
  614. for my $location (keys %hook_locations) {
  615. if ($hook_pointers_persistent{$location}) {
  616. @{$hook_pointers{$location}} = @{$hook_pointers_persistent{$location}};
  617. }
  618. else {
  619. delete $hook_pointers{$location};
  620. }
  621. }
  622. }
  623. }
  624. sub browser {
  625. my ($file) = @_;
  626. # Don't need this ... run look at search path
  627. # unless (-f $config_parms{browser} or lc($config_parms{browser}) eq 'explorer') {
  628. # &print_log("Could not find html browser file: $config_parms{browser}");
  629. # return;
  630. # }
  631. # Translate unix/perl / to dos \
  632. $file =~ s|/|\\|g if $OS_win and $file !~ /^http/i;
  633. run qq[$config_parms{browser} "$file"];
  634. }
  635. my ($loop_tickcount1, $loop_tickcount_total);
  636. sub check_for_action {
  637. &exit_pgm if $exit_flag;
  638. my $loop_tickcount1 = &get_tickcount;
  639. # Do window loop here, to check for pause mode exit
  640. if ($MW) {
  641. $Loop_Tk_Passes = 100 if $Loop_Tk_Passes >100; # Make sure we don't have too many passes
  642. $Loop_Tk_Passes = 1 if $Loop_Tk_Passes < 1; # Make sure we make at least one pass
  643. for (1 .. $Loop_Tk_Passes) {
  644. my $tk_activity;
  645. $tk_activity = DoOneEvent(0xFF); # Avoid Constants ... we get compile errors if -tk 0
  646. # $tk_activity = DoOneEvent(DONT_WAIT | ALL_EVENTS);
  647. # $tk_activity = DoOneEvent(0x1E);
  648. # $tk_activity = DoOneEvent(0x02);
  649. }
  650. }
  651. &check_for_keyboard_input;
  652. return if $pause_mode;
  653. &set_global_vars;
  654. &Process_Item::harvest; # Check for done processes
  655. &Generic_Item::reset_states; # Reset states for all objects that are 'ISA Item' objects
  656. &Voice_Cmd::check_for_voice_cmd; # Do this even if VR is not installed, so we can do web and manual run_voice_cmd
  657. &check_for_serial_data if %Serial_Ports;
  658. &check_for_socket_data if %Socket_Ports;
  659. &check_for_timer_actions;
  660. &check_for_external_command_file;
  661. &MainLoop_pre_hooks(); # Created by &add_hooks
  662. # Use eval to catch minor errors without abending
  663. # - about 10% slower (170 -> 150)
  664. &eval_user_code_loop;
  665. # &loop_code;
  666. &MainLoop_post_hooks(); # Created by &add_hooks
  667. # Do the tk_setup_cascade_menus AFTER the first eval code, so we can test Tk widget objects
  668. if ($MW) {
  669. &tk_setup_cascade_menus if $Reload;
  670. &tk_setup_geometry if $Reread;
  671. }
  672. $loop_tickcount_total += &get_tickcount - $loop_tickcount1;
  673. if ($Reread) {
  674. $Startup = 0; $Reload = 0; $Reread = 0;
  675. }
  676. }
  677. sub check_for_cm11_data {
  678. my $data = &ControlX10::CM11::read($Serial_Ports{cm11}{object}, 1);
  679. return unless $data;
  680. my $data_d = unpack('C', $data); # Convert from string to decimal
  681. # Check for the official 0x5a=90 string and 0xa5=165 (I have seen this!)
  682. print "mh CM11 data=$data data_d=$data_d\n" if $config_parms{debug} eq 'X10' and $data;
  683. # if ($data_d == 0x5a) {
  684. if ($data_d == 0x5a or $data_d == 0xa5) {
  685. if ($data = &ControlX10::CM11::receive_buffer($Serial_Ports{cm11}{object})) {
  686. # Process status requests
  687. if ($data =~ /STATUS/) {
  688. my ($house, $device, $state) = $data =~ /(\S)(\S)STATUS_(\S+)/;
  689. $state = 'J' if $state eq 'ON';
  690. $state = 'K' if $state eq 'OFF';
  691. my $event_data = 'X' . $house . $device . $house . $state;
  692. if (my @refs = &Serial_Item::serial_items_by_id($event_data)) {
  693. for my $ref (@refs) {
  694. if ($state = $$ref{state_by_id}{$event_data}) {
  695. # set_receive $ref $state;
  696. $ref->{state} = $state;
  697. print "CM11 Status results: data=$data event_data=$event_data state=$state\n"
  698. if $config_parms{debug} eq 'X10';
  699. }
  700. }
  701. }
  702. else {
  703. &print_log("Status request on undefined state: data=$data event_data=$event_data");
  704. }
  705. }
  706. else {
  707. &process_serial_data("X" . $data);
  708. }
  709. }
  710. }
  711. }
  712. sub check_for_external_command_file {
  713. my ($cmd, $cmd_num, $ref, $said);
  714. my $xcmd_file = $config_parms{xcmd_file};
  715. # Checking for a file is pretty slow ...
  716. return unless $New_Second;
  717. # Note: Check for non-zero size, not -e. Zero length files cause a loop!
  718. if ($xcmd_file and -s $xcmd_file) {
  719. &print_log("External command file found: $xcmd_file");
  720. unless (open(XCMD, $xcmd_file)) {
  721. print "\nWarning, can not open file $xcmd_file: $!\n";
  722. return;
  723. }
  724. $cmd = <XCMD>;
  725. chomp($cmd);
  726. close XCMD;
  727. next unless $cmd;
  728. unlink $xcmd_file;
  729. &process_external_command($cmd, 1);
  730. }
  731. }
  732. sub check_for_generic_serial_data {
  733. my ($port_name) = @_;
  734. my $data;
  735. unless ($data = $Serial_Ports{$port_name}{object}->input) {
  736. # If we do not do this, we may get endless error messages.
  737. $Serial_Ports{$port_name}{object}->reset_error;
  738. }
  739. $Serial_Ports{$port_name}{data} .= $data if $data;
  740. print " serial name=$port_name type=$Serial_Ports{$port_name}{datatype} data2=$Serial_Ports{$port_name}{data}...\n"
  741. if $data and ($config_parms{debug} eq 'serial' or $config_parms{debug} eq $port_name);
  742. # Check to see if we have a carrage return yet
  743. if ($Serial_Ports{$port_name}{data} and
  744. (!defined $Serial_Ports{$port_name}{datatype} or $Serial_Ports{$port_name}{datatype} ne 'raw')) {
  745. while (my($record, $remainder) = $Serial_Ports{$port_name}{data} =~ /(.+?)[\r\n]+(.*)/s) {
  746. &print_log("Data from $port_name: $record. remainder=$remainder.") if $config_parms{debug} eq 'serial';
  747. $Serial_Ports{$port_name}{data_record} = $record;
  748. $Serial_Ports{$port_name}{data} = $remainder;
  749. if ($Serial_Ports{$port_name}{process_data}) {
  750. &process_serial_data($record);
  751. }
  752. else {
  753. last; # Only process one data_record per user_code loop
  754. }
  755. }
  756. }
  757. }
  758. sub check_for_Homevision_data {
  759. my $data = &Homevision::read($Serial_Ports{Homevision}{object});
  760. if ($data) {
  761. print "Homevision data=$data\n" if $config_parms{debug} =~ /homevision|serial/i;
  762. &process_serial_data($data);
  763. }
  764. }
  765. sub check_for_ncpuxa_data {
  766. my $data = &ncpuxa_mh::read($config_parms{ncpuxa_port});
  767. if ($data) {
  768. print "ncpuxa data=$data\n" if $config_parms{debug} =~ /ncpuxa|serial/i;
  769. &process_serial_data($data);
  770. }
  771. }
  772. sub check_for_HomeBase_data {
  773. my $data = &HomeBase::read($Serial_Ports{HomeBase}{object});
  774. if ($data) {
  775. print "HomeBase x10 data=$data\n" if $config_parms{debug} eq 'homebase';
  776. &process_serial_data("X" . $data);
  777. }
  778. }
  779. sub check_for_keyboard_input {
  780. my $key;
  781. # return; # Console off for now.
  782. # Need to find a way to do this in Linux
  783. return unless $OS_win;
  784. for(0..$CON_IN->GetEvents()-1) {
  785. # Event data: 1, keyup_down, key_repeat_count, id1, id2, id3, id4
  786. # id1 seems to cover all the keys (e.g. 112 is F1, a=65, A=65)
  787. # id2 seems to be keyboard positional (e.g. a=30, s=31)
  788. # id3 seems to be ascii (a=97, A=65)
  789. my @event = $CON_IN->Input();
  790. $key = $event[3] if $event[1];
  791. }
  792. return unless $key;
  793. my %keymap = ('F1: Reload' => 'F1', 'F2: Pause' => 'F2', 'F3: Exit' => 'F3',
  794. 'F4: Debug' => 'F4', 'F5: Logging' => 'F5',
  795. 112 => 'F1', 113 => 'F2', 114 => 'F3',
  796. 115 => 'F4', 116 => 'F5');
  797. if ($key == 13) { # Enter Key -> display simple menu
  798. my ($oldX, $oldY, $oldS, $oldV) = $CON_OUT->Cursor();
  799. my $oldmode = $CON_IN->Mode();
  800. my $choice = &choose_menu($CON_IN, $CON_OUT,
  801. "F1: Reload", "F2: Pause", "F3: Exit",
  802. "F4: Debug", "F5: Logging");
  803. $CON_IN->Mode($oldmode);
  804. $CON_OUT->Cursor($oldX, $oldY, $oldS, $oldV);
  805. $key = $keymap{$choice};
  806. print "action=$choice key=$key\n";
  807. }
  808. else {
  809. $key = $keymap{$key} if $keymap{$key};
  810. }
  811. if ($key eq 'F1') {
  812. print "Key F1 pressed. Reloading code\n";
  813. read_code();
  814. }
  815. elsif ($key eq 'F2') {
  816. print "Key F2 pressed.\n";
  817. &pause;
  818. }
  819. elsif ($key eq 'F3') {
  820. print "Key F3 pressed. Exiting\n";
  821. &exit_pgm;
  822. }
  823. elsif ($key eq 'F4') {
  824. &toggle_debug;
  825. }
  826. elsif ($key eq 'F5') {
  827. &toggle_log;
  828. }
  829. elsif ($key) {
  830. print "key press: $key\n" if $config_parms{debug} eq 'misc';
  831. }
  832. }
  833. sub toggle_debug {
  834. $config_parms{debug} = ($config_parms{debug}) ? 0 : 1;
  835. my $state = ($config_parms{debug}) ? 'on' : 'off';
  836. print "Key F4 pressed. Debug turned $state.\n";
  837. }
  838. sub toggle_log {
  839. $config_parms{log} = ($config_parms{log}) ? 0 : 1;
  840. my ($state, $logfile);
  841. if ($config_parms{log}) {
  842. $state = 'on';
  843. $logfile = $config_parms{log_file};
  844. $logfile = 'mh_log.txt' unless $logfile;
  845. print "Key F5 pressed. Output will be logged into $logfile\n";
  846. &print_log("Key F5 pressed. Output will be logged into $logfile");
  847. open(OLDOUT, ">&STDOUT"); # Copy old handle
  848. open(OLDERR, ">&STDERR"); # Copy old handle
  849. open STDOUT, ">>$logfile" or print "\nError, could not open logfile $logfile: $!\n";
  850. $| = 1; # Turn on command buffering (e.g. flush on every print)
  851. open(STDERR, ">&STDOUT");
  852. }
  853. else {
  854. $state = 'off';
  855. print "Key F5 pressed. Output will no longer be logged to $logfile\n";
  856. close STDOUT;
  857. open(STDERR, ">&OLDERR");
  858. open(STDOUT, ">&OLDOUT");
  859. close OLDOUT;
  860. close OLDERR;
  861. print "STDOUT has been restored\n";
  862. &print_log("STDOUT has been restored");
  863. }
  864. }
  865. my @serial_data_buffer;
  866. sub check_for_serial_data {
  867. # Process remaining serial items from previous pass
  868. if (my $data = shift @serial_data_buffer) {
  869. print "Running serial_data_buffer string: $data\n" if $config_parms{debug} eq 'X10';
  870. &process_serial_data($data, 1);
  871. return;
  872. }
  873. &check_for_cm11_data if $Serial_Ports{cm11}{object};
  874. &check_for_Homevision_data if $Serial_Ports{Homevision}{object};
  875. &check_for_HomeBase_data if $Serial_Ports{HomeBase}{object};
  876. &check_for_ncpuxa_data if $config_parms{ncpuxa_port};
  877. &check_for_generic_serial_data('weeder') if $Serial_Ports{weeder}{object};
  878. for my $port_name (@Generic_Serial_Ports) {
  879. &check_for_generic_serial_data($port_name) if $Serial_Ports{$port_name}{object};
  880. }
  881. # Leave this under user control?
  882. # &iButton::monitor if $config_parms{ibutton_port} and if $New_Second;
  883. }
  884. my ($leave_socket_open_passes, $leave_socket_open_action);
  885. sub check_for_socket_data {
  886. # Time to finish the http GET from 2 passes ago with a list of spoken data
  887. if ($leave_socket_open_passes and --$leave_socket_open_passes == 0 and my $sock = $Socket_Ports{http}{socka}) {
  888. print "closing http port with action: $leave_socket_open_action\n" if $config_parms{debug} eq 'http';
  889. my @data = eval($leave_socket_open_action);
  890. print "Error in http lso action: $@\n" if $@;
  891. my $html = &html_page("", @data);
  892. print $sock $html;
  893. &socket_close('http');
  894. }
  895. my (@ports_with_data, @active_ports);
  896. # See which ports are active
  897. # - could probably use a smarter select check here, rather than loop for each port
  898. for my $port_name (keys %Socket_Ports) {
  899. next unless my $sock = $Socket_Ports{$port_name}{sock};
  900. $Socket_Ports{$port_name}{inactive_this_pass} = 0;
  901. if ($Socket_Ports{$port_name}{socka}) {
  902. push(@active_ports, $port_name);
  903. $Socket_Ports{$port_name}{active_this_pass} = 0;
  904. }
  905. else {
  906. if (my $nfound = &socket_has_data($sock)) {
  907. my $new_sock = $sock->accept();
  908. next unless $new_sock; # Can be undef it socket was killed
  909. $new_sock->autoflush(1); # Not sure if this does anything?
  910. $Socket_Ports{$port_name}{socka} = $new_sock;
  911. $Socket_Ports{$port_name}{active_this_pass} = 1;
  912. delete $Socket_Ports{$port_name}{data}; # Delete data from previous session
  913. push(@active_ports, $port_name);
  914. # Log the address of the client
  915. my $peer = $new_sock->peername;
  916. my ($port, $iaddr) = unpack_sockaddr_in($peer) if $peer;
  917. my $client_ip_address = inet_ntoa($iaddr) if $iaddr;
  918. $Socket_Ports{$port_name}{client_ip_address} = $client_ip_address;
  919. logit("$config_parms{data_dir}/logs/server.$Year_Month_Now.log", "$port_name $client_ip_address");
  920. print "\n$port_name active sock=$new_sock client=$client_ip_address.\n" if $config_parms{debug} eq $port_name;
  921. }
  922. }
  923. }
  924. # See if any active ports have data ... this could be rolled into previous loop
  925. for my $port_name (@active_ports) {
  926. my $sock = $Socket_Ports{$port_name}{socka};
  927. if (my $nfound = &socket_has_data($sock)) {
  928. print "\n$port_name nfound=$nfound\n" if $config_parms{debug} eq $port_name;
  929. if ($nfound < 0) {
  930. # Note, must do a shutdown here ... a close does not close handles
  931. # from &run (system start) processes !?! ... maybe IO sockets do not need this?
  932. # Not sure how to shutdown IO handles ... this gives 'bad symbol on filehandle' error
  933. # shutdown($sock->fileno(), 2); # "how": 0=no more receives, 1=sends, 2=both
  934. print "1 closing socket port $port_name\n" if $config_parms{debug} eq $port_name;
  935. &socket_close($port_name);
  936. }
  937. else {
  938. push(@ports_with_data, $port_name);
  939. }
  940. }
  941. }
  942. # Get data from active ports
  943. for my $port_name (@ports_with_data) {
  944. my $sock = $Socket_Ports{$port_name}{socka};
  945. my $data;
  946. # Buffered mode means only read one line per pass
  947. # - This allows user code the option of reading port with <>
  948. # - Assumes clients will send a line at a time, so will not block
  949. if ($Socket_Ports{$port_name}{datatype} and $Socket_Ports{$port_name}{datatype} eq 'buffered') {
  950. $data = <$sock>;
  951. }
  952. else {
  953. # 1500 is ethernet packet size
  954. my $from_saddr = recv($sock, $data, 1500, 0);
  955. # Store udp from_* data
  956. if ($Socket_Ports{$port_name}{protocol} and $Socket_Ports{$port_name}{protocol} eq 'udp') {
  957. (my $from_port, my $from_ip) = sockaddr_in($from_saddr);
  958. $Socket_Ports{$port_name}{from_port} = $from_port;
  959. $Socket_Ports{$port_name}{from_ip} = $from_ip;
  960. }
  961. }
  962. print "\n sock=$sock lso=$leave_socket_open_passes data=$data.\n" if $config_parms{debug} eq $port_name;
  963. # Need to do this or the socket never closes!
  964. # For some reason, nfound = 1 (instead of -1) unless we do this.
  965. # In other words, a telnet disconnect will leave nfound=1, but no data.
  966. # When telnet closes, byte IS defined, but is empty, so check on ''
  967. if (!defined $data or $data eq '') {
  968. print "closing socket port $port_name\n" if $config_parms{debug} eq $port_name;
  969. &socket_close($port_name);
  970. }
  971. $Socket_Ports{$port_name}{data} .= $data if defined $data;
  972. print "$port_name data=$Socket_Ports{$port_name}{data}..\n" if $config_parms{debug} eq $port_name;
  973. # If raw mode, return data as is
  974. if ($Socket_Ports{$port_name}{datatype} and $Socket_Ports{$port_name}{datatype} eq 'raw') {
  975. # $Socket_Ports{$port_name}{data_record} = $data; # No not break data on newlines
  976. next;
  977. }
  978. if (my $echo = $config_parms{"${port_name}_echo"}) {
  979. # Need to loop thru $data here, one byte at a time
  980. my $byte = $data;
  981. # bs = 8, del=127
  982. my $char = unpack('C', $byte);
  983. # Allow us to pick our echo character (e.g. '*')
  984. $byte = $echo unless $echo == 1 or $char eq 8;
  985. next if $char eq 8;
  986. print $sock $byte unless $char eq 13 or $char eq 10;
  987. }
  988. # Break data on newlines
  989. next unless $Socket_Ports{$port_name}{data};
  990. while (my($record, $remainder) = $Socket_Ports{$port_name}{data} =~ /(.+?)[\r\n]+(.*)/) {
  991. if ($config_parms{debug} eq $port_name) {
  992. print "$port_name record=$record. hex=", unpack('H*', $record), "\n";
  993. print "$port_name remainder=$remainder. hex=", unpack('H*', $remainder), "\n";
  994. }
  995. $Socket_Ports{$port_name}{data_record} = $record;
  996. $Socket_Ports{$port_name}{data} = $remainder;
  997. if ($port_name eq 'http') {
  998. if ($record =~ /^ *GET /) {
  999. ($leave_socket_open_passes, $leave_socket_open_action) = &process_http_request($sock, $record);
  1000. print "db lso=$leave_socket_open_passes sock=$sock.\n" if $config_parms{debug} eq $port_name;
  1001. unless ($leave_socket_open_passes) {
  1002. print "4 closing socket port $port_name\n" if $config_parms{debug} eq $port_name;
  1003. # We must sleep here for a bit, or else Netscape sometimes
  1004. # says 'Document contains no data'.
  1005. select undef, undef, undef, .010;
  1006. &socket_close($port_name);
  1007. }
  1008. }
  1009. else {
  1010. # Do nothing with non-GET http requests
  1011. # print $sock ">$record";
  1012. }
  1013. }
  1014. else {
  1015. # 10/99 Comment out \r\n print ... what needed this?? Messed up viavoice server
  1016. # print $sock "\r\n";
  1017. #

Large files files are truncated, but you can click here to view the full file