PageRenderTime 79ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/v2-32/mh/bin/mh

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

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