Changed blocking read requests to poll master
authorMoritz Rosenthal <moritz@major-tom.(none)>
Thu, 8 Dec 2011 23:12:40 +0000 (00:12 +0100)
committerMoritz Rosenthal <moritz@major-tom.(none)>
Thu, 8 Dec 2011 23:12:40 +0000 (00:12 +0100)
two.py

diff --git a/two.py b/two.py
index 82b5e75..00582cc 100644 (file)
--- a/two.py
+++ b/two.py
@@ -7,55 +7,80 @@ import string
 import ow
 import time
 import os
+import re
 
 import ssl
 import pprint
 
-HOST="irc.hackint.eu"
-PORT=9999
-NICK="lisaBOT"
+import select
+
+HOST="irc.freenode.net"
+PORT=6697
+NICK="lisaBOT123"
 IDENT="Lisa"
-PW="hackquarter4ever"
+PW=""
 REALNAME="Bot"
 CHAN="#lisaBOTChan"
 readbuffer=""
 
-
-#read config
-if len(sys.argv) != 2:
-  print "Usage:" + sys.argv[0] +  " Filename"
-
-
-ow.init('u')
-
-userHash = {}
-try:
-  with open( sys.argv[1] , "r" ) as fd :
-    for i in fd.readlines():
-      try:
-        userHash[int(i.split(';')[0].strip())] = [i.split(';')[1].strip(),False]
-      except:
-        print "Could not parse file"
-        print sys.exc_info()[0]
-        sys.exit(-1)
-except:
-  print "FATAL ERROR"
-  print sys.exc_info()[0]
-  sys.exit(-1)
-
-alteListe = set()
-
-#end setup 
+def buf2sock (buf, newline="\r\n"):
+    lines = buf.split(newline)[:-1]
+    buf = buf[buf.rfind(newline)+2:]
+    return lines, buf
+
+def enter_irc_chan (host, port, channel, nick="lisa", ident="lisa", password="", realname="Bot"):
+    # open ssl socket
+    s = ssl.wrap_socket(socket.socket(socket.AF_INET))
+    s.connect((host, port))
+
+    buf = ""
+    lines = []
+    
+    poll_fds = {}
+    
+    # register poll on socket
+    p = select.poll()
+    p.register(s.fileno(), select.POLLIN | select.POLLPRI | select.POLLHUP)
+        
+    run = True
+    while run:
+        #wait for poll
+        evlist = p.poll(10000)
+        # test if event occured 
+        if len(evlist) > 0:
+            for fd, event in evlist:
+                if fd == s.fileno():
+                    if event & select.POLLIN or event & select.POLLPRI:
+                        lines, buf = buf2sock(buf + s.recv(1024))
+                        for line in lines:
+    #                        print repr(line)
+                            reg = re.match(":?(?P<r_host>[^ ]*) (?P<msg_type>[^ ]*) (?P<receiver>[^ ]*) :?(?P<msg>.*)", line.strip())
+                            if reg:
+                                print "%s: %s" % (reg.group("receiver"), reg.group("msg"))
+                                if reg.group("msg") == "*** Checking Ident":
+                                    print "Sending Ident..." 
+                                    s.send("NICK %s\r\n" % nick)
+                                    s.send("USER %s 0 0 :%s \r\n" % (ident, realname))
+                                if reg.group("msg") == "+Zi":
+                                    return s
+                    if event & select.POLLHUP:
+                        printf("Socket hangup");
+                        s.close()
+                        run = False
+        else:
+            s.close()
+            run = False
+    return None
 
 #function 
 def process(diff):
-  global s 
-  for i in diff:
-    userHash[i][1] = not userHash[i][1]
+    global s 
+    for i in diff:
+        userHash[i][1] = not userHash[i][1]
     if userHash[i][1]:
-      s.send("PRIVMSG %s :%s\r\n" % (CHAN, "!join " + userHash[i][0]))
+        s.send("PRIVMSG %s :%s\r\n" % (CHAN, "!join " + userHash[i][0]))
     else:
-      s.send("PRIVMSG %s :%s\r\n" % (CHAN, "!part " + userHash[i][0]))
+        s.send("PRIVMSG %s :%s\r\n" % (CHAN, "!part " + userHash[i][0]))
 
 def process1wire():
   global alteListe
@@ -78,56 +103,95 @@ def process1wire():
     ow.finish()
     sys.exit(0) 
 
+if __name__ == "__main__":
+    sensor_present = True
+    #read config
+    if len(sys.argv) != 2:
+        print "Usage:" + sys.argv[0] +  " Filename"
 
-s = ssl.wrap_socket(socket.socket(socket.AF_INET))
-#context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
-#context.verify_mode = ssl.CERT_NONE
-#s = context.wrap_socket(socket.socket(socket.AF_INET))
-s.connect((HOST, PORT))
-s.send("NICK %s\r\n" % NICK)
-s.send("USER %s 8 * : %s \r\n" % (IDENT, REALNAME))
-
-
-line = False
-
-while not line or not line[0]=="PING":
-  readbuffer=readbuffer+s.recv(1024)
-  temp=string.split(readbuffer, "\n")
-  readbuffer=temp.pop( )
-
-  for line in temp:
-    print line
-    line=string.rstrip(line)
-    line=string.split(line)
-    if(line[0]=="PING"):
-      s.send("PONG %s\r\n" % line[1])
-      print "Pong send"
-
-
-s.send("PRIVMSG Nickserv : identify %s\r\n" % (PW))
-s.send("JOIN :%s\r\n" % CHAN)
-
-
-#s.send("PRIVMSG %s :%s\r\n" % (CHAN, "Hello There!"))
-#s.send("PRIVMSG %s :%s\r\n" % (CHAN, "I am a bot"))
+    try:
+        ow.init('u')
+    except ow.exNoController:
+        sensor_present = False
 
-s.settimeout(1)
+    userHash = {}
+    try:
+        with open( sys.argv[1] , "r" ) as fd :
+            for i in fd.readlines():
+                try:
+                    userHash[int(i.split(';')[0].strip())] = [i.split(';')[1].strip(),False]
+                except:
+                    print "Could not parse file"
+                    print sys.exc_info()[0]
+                    sys.exit(-1)
+    except:
+        print "FATAL ERROR"
+        print sys.exc_info()[0]
+        sys.exit(-1)
 
-while 1:
-  try:
-    readbuffer=readbuffer+s.recv(1024)
-    temp=string.split(readbuffer, "\n")
-    readbuffer=temp.pop( )
-
-    for line in temp:
-      print line
-      line=string.rstrip(line)
-      line=string.split(line)
-
-      if(line[0]=="PING"):
-        s.send("PONG %s\r\n" % line[1])
-        print "Pong send"
-  except socket.timeout:
-    process1wire()
-  except ssl.SSLError:
-    process1wire()
+    alteListe = set()
+    
+    sfd = 0
+
+    #end setup 
+    line = False
+
+    p = select.poll()
+    buf = ""
+    linebuf = []
+    s = None
+
+    while 1:
+        if s == None:
+            s = enter_irc_chan(HOST, PORT, CHAN, nick="lisaBOT123")
+            if s != None:
+                sfb = s.fileno()
+                if PW:
+                    s.send("PRIVMSG Nickserv : identify %s\r\n" % (PW))
+                s.send("JOIN :%s\r\n" % CHAN)
+#                s.settimeout(1)
+                p.register(sfb, select.POLLIN | select.POLLPRI | select.POLLHUP)
+            else:
+                time.sleep(10)
+        else:
+            evlist = p.poll(100)
+            if len(evlist) == 0 and sensor_present:
+                process1wire()
+            else:
+                for fd, event in evlist:
+                    if event & (select.POLLIN | select.POLLPRI):
+                        lines, buf = buf2sock(buf + s.recv(1024))
+                        for line in lines:
+                            reg = re.match(":?(?P<r_host>[^ ]*) (?P<msg_type>[^ ]*) (?P<receiver>[^ ]*) :?(?P<msg>.*)", line.strip())
+                            if reg:
+                                print "%s: %s" % (reg.group("receiver"), reg.group("msg"))
+                                continue
+                            reg = re.match("PING :?(?P<r_host>[^ ]*)", line.strip())
+                            if reg:
+                                s.send("PONG %s\r\n" % (reg.group("r_host")))
+                                print "Answered PING"
+                                continue
+                            print "Unknown command: %s" % line
+                    elif event & select.POLLHUP:
+                        p.unregister(sfb)
+                        s.close()
+                        s = None
+                    else:
+                        print "%d: %d" % (fd, event)
+#    try:
+#        readbuffer=readbuffer+s.recv(1024)
+#        temp=string.split(readbuffer, "\n")
+#        readbuffer=temp.pop( )
+#
+#        for line in temp:
+#            print line
+#            line=string.rstrip(line)
+#            line=string.split(line)
+#
+#            if(line[0]=="PING"):
+#                s.send("PONG %s\r\n" % line[1])
+#                print "Pong send"
+#    except socket.timeout:
+#        process1wire()
+#    except ssl.SSLError:
+#        process1wire()