Skip to menu

Robotics with Object Pascal

Controls

# This is needed for accessing sensor data which library supports only python or c++

 

import socket            # For UDP Communication to PC
import struct            # For ??
import sys               # For sys.stderr (Print to screen)

myip = '127.0.0.1'       # Development Mode (Local IP)
machinename = 'SENSE-NET'

message    = ''
old_ar_rcv = ''
shortstr   = ''
multicast_group = (myip, 6767)   # Actual Run Mode in PI (PC(Overmind)'s IP)
sockettimeout = 2.2

# Create the datagram socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Set a timeout so the socket does not block indefinitely when trying
# to receive data.
sock.settimeout(sockettimeout)  # original (0.2)

# Set the time-to-live for messages to 1 so they do not go past the
# local network segment.
ttl = struct.pack('b', 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)

try:
   # Send data to multicast group
   # bytesToSend = str.encode(msgFromServer)
   sent = sock.sendto(str.encode(machinename), multicast_group)
   
   while True:   #keep going
      try:
         # Get message from Arduino
#         ar_rcv = ar_port.readline()  # read 30 characters
#         ar_rcv = ar_rcv.strip('\n')
#         if len(ar_rcv) < 2:
#            ar_rcv = old_ar_rcv
#         else:
#            if old_ar_rcv != ar_rcv :
#               print >> sys.stderr, ar_rcv
#               old_ar_rcv = ar_rcv   
#               sent == sock.sendto(ar_rcv, multicast_group)
               # to write to arduino, use: ar_port.write('My Message')            

         data, server = sock.recvfrom(10)
         
         # print >> sys.stderr, 'received "%s" from %s' % (data, server)  
         if data != '.':
            if message != data :
               message = ''
            #   ar_port.write(data)
               print >> sys.stderr, 'to ar. "%s" ' % (data)
            #   print('to ar. "%s" ' % (data))
               sent == sock.sendto(str.encode(data), multicast_group)
               message = data
      except socket.timeout:
         print >> sys.stderr, 'UDP Timeout' % (data, server)
         #print('UDP Timeout')
         break
      else:
         if data != '.':   # If data from Overmind is not '.'
            #i = 1   # dummy, do nothing
            print >> sys.stderr, 'received "%s" from %s' % (data, server)

finally:
   print >>sys.stderr, 'closing socket'
   #print('Error : closing socket')
   sock.close()
   exit()