Guest User

dth2.py source code

a guest
May 8th, 2012
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.19 KB | None | 0 0
  1. # Scratch Mirror
  2. # Version 1.5.0
  3. # Originally by: Magnie. Modified by bobbybee for use in FireMMO
  4.  
  5. import socket # Network base
  6. import time # For delaying purposes mostly.
  7. import threading # So it can send and receive at the same time anytime.
  8. import array
  9.  
  10. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
  11. # CHOST is the IP Scratch is running on, if you are running it    #
  12. # on this computer, then the IP is 127.0.0.1                      #
  13. # Theoretically you could run this Mirror on another computer.    #
  14. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
  15. # CPOST is the port Scratch is listening on, the default is       #
  16. # 42001. Usually this is only change by a Scratcher who knows a   #
  17. # about Squeak and networking with sockets.                       #
  18. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
  19. CHOST = '127.0.0.1'
  20. CPORT = 42001
  21.  
  22. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
  23. # SHOST is the IP the server is running on.                       #
  24. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
  25. # SPORT is the port that the server is using. 42002 is the        #
  26. # unofficial port for Scratch Servers. The host will need to make #
  27. # sure to port-forward the port so people can connect from the    #
  28. # internet.                                                       #
  29. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
  30. SHOST = '96.127.188.39'
  31. SPORT = 8089
  32.  
  33. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
  34. # Some extra settings that are more for advanced users are below. #
  35. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
  36.  
  37. # Time between checking the threads for broken ones.
  38. THREADCHECK = 5
  39.  
  40.  
  41.  
  42. class Client(threading.Thread): # This class listens for messages sent from Scratch and sends it to the Server.
  43.     def parse_message(self, message):
  44.         if message:
  45.             sensors = {}
  46.             broadcasts = []
  47.  
  48.             commands = []
  49.             i = 0
  50.             while True:
  51.                 length = ord(message[i]) + ord(message[i+1]) + ord(message[i+2]) + ord(message[i+3])
  52.            
  53.                 command = message[i + 4:i + length + 4]
  54.                 commands.append(command)
  55.                 if (i + length + 4) < len(message):
  56.                     i = (i+4) + length
  57.                 else:
  58.                     del command
  59.                     break
  60.            
  61.                 for command in commands:
  62.                     if command[0] == 'b':
  63.                         command = command.split('"')
  64.                         command.pop(0)
  65.                         broadcasts.append(command[0])
  66.                
  67.                     elif command[0] == 's':
  68.                         command = command.split('"')
  69.                         command.pop(0)
  70.                         try:
  71.                             command.remove(' ')
  72.                         except ValueError:
  73.                             pass
  74.                     sensors[command[0]] = command[1]
  75.        
  76.                 return dict([('sensor-update', sensors), ('broadcast', broadcasts)])
  77.         else:
  78.             return None
  79.     def sendScratchCommand(self, cmd):
  80.         n = len(cmd)
  81.         a = array('c')
  82.         a.append(chr((n >> 24) & 0xFF))
  83.         a.append(chr((n >> 16) & 0xFF))
  84.         a.append(chr((n >>  8) & 0xFF))
  85.         a.append(chr(n & 0xFF))
  86.         server.sock.send(a.tostring() + cmd)
  87.    
  88.     def __init__(self, CHOST, CPORT):
  89.         threading.Thread.__init__(self) # Initialize it, basically just separate it from the main thread.
  90.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Defines the type of connection ( UPD, TCP on IPv4 or IPv6 )
  91.         print("Connecting to Scratch...")
  92.         self.sock.connect((CHOST, CPORT)) # Connect to Scratch
  93.         print("Connected to Scratch!")
  94.        
  95.     def run(self):
  96.         global running
  97.         print "Listening for Scratch messages."
  98.         while running:
  99.             data = self.sock.recv(1024) # Wait for something to be sent to the mirror
  100.            
  101.             data = self.parse_message(data)
  102.             for sensor in data['sensor-update']:
  103.                 if sensor == "packet":
  104.                     self.send(data['sensor-update'][sensor])
  105.  
  106.    
  107.     def send(self, message):
  108.         server.sock.send(message) # Send the data to the server.
  109.  
  110. class Server(threading.Thread): # This class listens for messages from the Server and sends it to Scratch.
  111.     def sendScratchCommand(self, cmd):
  112.         n = len(cmd)
  113.         a = []
  114.         a.append(chr((n >> 24) & 0xFF))
  115.         a.append(chr((n >> 16) & 0xFF))
  116.         a.append(chr((n >>  8) & 0xFF))
  117.         a.append(chr(n & 0xFF))
  118.         scratch.sock.send(''.join(a) + cmd)
  119.     def __init__(self, SHOST, SPORT):
  120.         threading.Thread.__init__(self) # Initialize it, basically just separate it from the main thread.
  121.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Defines the type of connection ( UPD, TCP on IPv4 or IPv6 )
  122.         print("Connecting to Scratch Server...")
  123.         self.sock.connect((SHOST, SPORT)) # Connect to the Server.
  124.         print("Connected to Server!")
  125.        
  126.     def run(self):  
  127.         global running
  128.         print "Listening for Server messages."
  129.         while running:    
  130.             data = self.sock.recv(1024) # Listens for messages sent from the Server.
  131.         print(data);
  132.         self.sendScratchCommand("sensor-update packet \""+data+"\"");
  133.         self.sendScratchCommand("broadcast dataready")
  134.    
  135.     def send(self, message):
  136.         scratch.sock.send(message) # Sends messages to Scratch.
  137.  
  138. running = 1
  139. scratch = Client(CHOST, CPORT) # Start up the class for Scratch
  140. scratch.start() # This starts the 'run' function.
  141.  
  142. server = Server(SHOST, SPORT) # Start up the class for Server
  143. server.start() # This starts the 'run' function on the class as well.
  144.  
  145. while running:
  146.     time.sleep(THREADCHECK) # The longer the wait time, the less CPU is used I think.
  147.     try: # Check if the either thread died ( or exists anymore ).
  148.         if scratch:
  149.             pass
  150.     except Exception, e:
  151.         print e
  152.         running = 0Xff
Advertisement
Add Comment
Please, Sign In to add comment