PageRenderTime 95ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/v2-28/mh/bin/mh

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

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