# Multithreaded UDP server.

import socket
import sys
import struct
import math
import threading
import time
import Queue
import array

class trigThread( threading.Thread):
  def run(self):
    sendTrig=0
    while 1:
      try: tflg,s,ipadr,hid=msgq.get(False)
      except Queue.Empty: pass

      if tflg != None: sendTrig=tflg
      if sendTrig == 1:
        rdat=struct.pack('BBBB',1,hid,0x81,0)
        s.sendto(rdat,0,ipadr)
      else: break

      time.sleep( 2)

def gotMessage( data,ipadr,s):
  print "data length is ",len(data)
  vers=struct.unpack('b',data[0])
  hmid=struct.unpack('b',data[1])
  code=struct.unpack('b',data[2])
  xxxx=struct.unpack('b',data[3])
  rdat=struct.pack('BBBB',vers[0],hmid[0],code[0]+0x80,xxxx[0])
  if len(data) == 4: idat=struct.unpack('I',data)
  elif len(data) == 8:
    idat=struct.unpack('II',data)
    rdat+=struct.pack('I',idat[1])
    hdat=data[4:5]
    rix =struct.unpack('H',data[4:6])
    rval=struct.unpack('H',data[6:8])
 
  print "Data received from ", ipadr
  print 'vers=%d,hmid=%d,code=0x%x,xxxx=%d' % \
    (vers[0],hmid[0],code[0],xxxx[0])

  if hmid[0] != hmId:
    print "Bad hmid=",hmid[0],"received.  Acceptable value is",hmId
    return

  if code[0] > 0x01 and code[0]<0x7: rstr=''
  elif code[0] == 0x07:
    rstr=''
    msgq.put((1,s,ipadr,hmId))
    trigThread().start()
  elif code[0] == 0x08:
    rstr=''
    msgq.put((0,s,ipadr,hmId))
  elif code[0] == 0x11:
    rstr=''
    if rix[0]>=0 and rix[0]<2:
      hmrg[rix[0]]=rval[0]
  elif code[0] == 0x13:
    rstr=''
    if rix[0]>=0 and rix[0]<10:
      trrw[rix[0]]=rval[0]
  elif code[0] == 0x16:
    rstr=''
    if rix[0]>=0 and rix[0]<2: pwmr[rix[0]]=rval[0]
  elif code[0] == 0x17:
    rstr=''
    if rix[0]>=0 and rix[0]<4: wfmr[rix[0]]=rval[0]
  elif code[0] == 0x41:
    rstr1=struct.pack('I',4)
    rstr2="MARX  P2"
    rstr3=struct.pack('I',0x20100609)
    rstr4=struct.pack('hhhh',hmrg[0],hmrg[1],0x3f,0xfea)
    rstr=rstr1+rstr2+rstr3+rstr4

  elif code[0] == 0x42: rstr=struct.pack('BBBB',0x21,0x22,0x23,0x24)
  elif code[0] == 0x43: rstr=struct.pack('BBBB',0x31,0x32,0x33,0x34)
  elif code[0] == 0x44: rstr=struct.pack('BBBB',0x41,0x42,0x43,0x44)
  elif code[0] == 0x45: rstr=struct.pack('BBBB',0x51,0x52,0x53,0x54)
  elif code[0] == 0x46: rstr=struct.pack('BBBB',0x61,0x62,0x63,0x64)
  elif code[0] == 0x47: rstr=struct.pack('BBBB',0x71,0x72,0x73,0x74)
  elif code[0] == 0x48:
    rstr1=struct.pack('hhhhhhhh',4095,0,300,400,500,600,700,800)
    rstr2=struct.pack('hhhh',4095,0,1300,1400)
    rstr=rstr1+rstr2
  elif code[0] == 0x49:
    rstr1=struct.pack('BBBB',0x91,0x92,0x93,0x94)
    rstr2=struct.pack('BBBB',0x95,0x96,0x97,0x98)
    rstr3=struct.pack('BBBB',0x99,0x9a,0x9b,0x9c)
    rstr=rstr1+rstr2+rstr3
  elif code[0] == 0x4a: rstr=struct.pack('BBBB',0xa1,0xa2,0xa3,0xa4)
  elif code[0] == 0x4b:
    rstr1=struct.pack('hhhhh',trrw[0],trrw[1],trrw[2],trrw[3],trrw[4])
    rstr2=struct.pack('hhhhh',trrw[5],trrw[6],trrw[7],trrw[8],trrw[9])
    rstr3=struct.pack('hhhh', trro[0],trro[1],trro[2],trro[3])
    rstr4=struct.pack('hhh',  trro[4],trro[5],trro[6])
    rstr=rstr1+rstr2+rstr3+rstr4
  elif code[0] == 0x4c:
    rstr=struct.pack('BBBB',0xc1,0xc2,0xc3,0xc4)
  elif code[0] == 0x4d:
    rstr=struct.pack('BBBB',0xd1,0xd2,0xd3,0xd4)
  elif code[0] == 0x4e:
    rstr=struct.pack('hh',pwmr[0],pwmr[1])
    print rstr
  elif code[0] == 0x4f: rstr=struct.pack('hh',pwmr[0],pwmr[1])
  elif code[0] == 0x50: rstr=struct.pack('hhhh',wfmr[0],wfmr[1],wfmr[2],wfmr[3])
  elif code[0] == 0x51:
#    rstr1=struct.pack('hhhhhhhh',200,250,300,350,400,450,500,550)
#    rstr2=struct.pack('hhhhhhhh',550,550,550,550,400,400,400,400)
#    rstr3=struct.pack('hhhhhhhh',400,400,400,400,550,550,550,550)
#    rstr4=struct.pack('hhhhhhhh',550,500,450,400,350,300,250,200)
#    rstr=rstr1+rstr2+rstr3+rstr4
    rstr=struct.pack('h',0)
    for i in range(1,512):
      rstr+=struct.pack('h',i)

  else: print 'code 0x%x unrecognized' % code; rstr=''

  if rstr != '': rdat+=rstr

  s.sendto(rdat,0,ipadr)

def mainLoop( s):
  while 1:
    data,ipadr=s.recvfrom(2048)
    if not data: break
    else: gotMessage( data,ipadr,s)

  s.close()

if __name__=="__main__":
  # It takes up to three command line arguments:
  # [arg1 [arg2 [arg3]]], where
  # arg1 is the IP address of the host on which this is run
  # arg2 is the port number used by this script
  # arg3 is the hardware manager identifier assigned to this simulator.
  #--------------------------------------------------------------------
  if len(sys.argv) < 2:
    host,port,hmId="localhost",9999,1
  elif len(sys.argv)==2:
    host,port,hmId=sys.argv[1],9999,1
  elif len(sys.argv)==3:
    host,port,hmId=sys.argv[1],int(sys.argv[2]),1
  else:
    host,port,hmId=sys.argv[1],int(sys.argv[2]),int(sys.argv[3])

  trrw=array.array('h',[0,0,0,0,0,0,0,0,0,0])
  trro=array.array('h',[0x138,0x9c,0x9c,0x138,0x9c,0x9c,0x9c])
  wfmr=array.array('h',[0,0,0,0])
  pwmr=array.array('h',[0,0])
  hmrg=array.array('h',[0,0])
  wfmb=array.array('h')

  msgq=Queue.Queue(0)
  addr = (host,port)
  print "host =", host, "port =", port, "hmId =", hmId

  UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  UDPSock.bind(addr)
  mainLoop( UDPSock)
