วันพฤหัสบดีที่ 4 มิถุนายน พ.ศ. 2558

[Mini Project Chapter 4 : การอ่านข้อมูลจาก UDP Socketและส่งไป Plot บนเว็บ] เกมฝึกทักษะและเสริมสร้างพัฒนาการสำหรับเด็ก

          ในส่วนนี้จะกล่าวถึงการทำงานของโค้ด Python ที่ทำหน้าที่รับข้อมูลคะแนนที่ผู้ใช้เล่นได้ในแต่ละรอบจาก UDP Socket และนำข้อมูลที่ได้นั้นส่งไปเก็บข้อมูลบน Iot Cloud Service ของ Plotly เพื่อที่จะเก็บข้อมูลคะแนนที่เคยเล่นเอาไว้เป็นสถิติ เพื่อที่จะดูพัฒนาการในการเล่นเกมของผู้ใช้งาน
           เริ่มจากการต่อสาย LAN เข้ากับคอมพิวเตอร์ที่ใช้เป็น Client จากนั้นใช้โค้ดการทำงานภาษา Python ในการอ่านค่าจาก UDP Socket และส่งให้กับ Iot Cloud Service โดยโค้ดการทำงานดังนี้


1:  import plotly          # (*) Import plotly package
2:  import plotly.plotly as py   # (*) To communicate with Plotly's server, sign in with credentials file
3:  import plotly.tools as tls   # (*) Useful Python/Plotly tools
4:  from plotly.graph_objs import * # (*) Graph objects to piece together plots
5:  import datetime         # (*) Import module keep track and format current time
6:  import time, httplib, urllib, socket,SocketServer,time
โค้ดการทำงาน Python ส่วนที่ 1
          การทำงานของโค้ดส่วนนี้จะทำการ Import Library ต่างๆ ที่จะใช้งานคือ Library ของ plotly ที่จะใช้ในการ Plot กราฟข้อมูลไปเก็บบน Iot Cloud service ของ Plotly(สามารถ Install Plotly Python package จาก https://plot.ly/python/getting-started/ ) และ Library ในการใช้งาน Socket Server ซึ่งจะใช้งานในการอ่านข้อมูลจาก UDP Socket


7:  py.sign_in("xxxxxxxxxx", "xxxxxxxxxx")  #sign in to plot.ly(Insert Username and API Key)
8:  token = ["2tgsdih6ho","f3zhp2rx41","73dbddj1k4","rdtg9mdrr1"]  #Token in your plotly that you want to use
9:  stream_id1 = token[0]    # Get stream id from stream id list
10:  # Make instance of stream id object
11:  stream1 = Stream(        
12:    token=stream_id1,      # (!) link stream id to 'token' key
13:    maxpoints=50        # (!) keep a max of 50 pts on screen
14:  )
15:  # Initialize trace of streaming plot by embedding the unique stream_id
16:  trace1 = Scatter(        
17:    x=[],
18:    y=[],
19:    mode='lines+markers',
20:    stream=stream1       # (!) embed stream id, 1 per trace
21:  )
โค้ดการทำงาน Python ส่วนที่ 2
          การทำงานของโค้ดส่วนนี้จะทำการ Sign in เข้าไปที่ User name และ API Key ของผู้ใช้งานบน Plot.ly จากนั้นทำการประกาศ Token ที่ต้องการให้ไปเก็บข้อมูล และสร้าง Object Stream โดยกำหนดหนดค่า Token และ ขอบเขตของจุดบนกราฟ และทำการสร้าง Scatter เริ่มต้นที่จะใช้สำหรับกราฟ


22:  print 'Server started...' #print server start
23:  host, port = '0.0.0.0',12450 #set host and port
24:  server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) #Create UDP Socket
25:  server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)  #Set option of the Socket
26:  server.bind((host,port))
27:  server.settimeout(5)  #Set timeout of server
โค้ดการทำงาน Python ส่วนที่ 3
          การทำงานของโค้ดส่วนนี้จะเป็นการทำงานเกี่ยวกับการสร้างและกำหนดค่าเริ่มต้นให้กับ Socket Server โดยเริ่มจากการกำหนด IP และ port ของฝั่ง Server ที่ต้องการจะรับข้อมูล(ในโค้ดนี้ใช้ IP เป็น 0.0.0.0 จะทำการ bind จาก IP ของเครื่องคอมพิวเตอร์ทั้งหมด) จากนั้นทำการสร้าง Socket Server


28:  data = Data([trace1])  #Create array of data
29:  layout = Layout(title='Score' )  # Add title to layout object
30:  fig = Figure(data=data, layout=layout) # Make a figure object
31:  unique_url = py.plot(fig, filename='Your Scores') # (@) Send fig to Plotly, initialize streaming plot, open new tab
32:  s1 = py.Stream(stream_id1) #Create stream
33:  s1.open() # (@) Open the stream
34:  time.sleep(5) # Delay start of stream by 5 sec (time to switch tabs)
35:  i=0
โค้ดการทำงาน Python ส่วนที่ 4
          การทำงานของโค้ดส่วนนี้จะเป็นการทำงานเกี่ยวกับการกำหนดค่าเริ่มต้นให้กับการ plot กราฟของ Plotly โดยเริ่มจากการกำหนด Array ข้อมูลที่จะ plot กราฟ และทำการกำหนดชื่อ ให้ส่วนต่างๆแล้วทำการสร้าง Object Stream ทีจะใช้สำหรับ plot กราฟแบบ Streaming Graph


36:  while True:
37:    try:  
38:      (received, addr) = server.recvfrom(65535)  #Get message from UDP socket
39:      server.sendto(received,addr)        #Send message back to client
40:      print i, ': received from ', str(addr), 'data is ', received  #print message that received from client
41:      i+=1
42:      time.sleep(1)
43:      point = int(received)
44:      print point
45:      x=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') #Get date and time values for X-axis data
46:      y1=point  #Set point(score) value for Y-axis
47:      s1.write(dict(x=x,y=y1))  #Add X and Y to plot on web
48:      time.sleep(5)
49:    except socket.timeout:
50:       print "Timeout"
51:       pass
52:    except KeyboardInterrupt as ex:
53:      print ex
54:      s1.close()
โค้ดการทำงาน Python ส่วนที่ 5
          การทำงานของโค้ดส่วนนี้จะเป็นการทำงานส่วนหลักที่เป็น while loop วนไปเรื่อยๆ โดยจะเริ่มจากการอ่านค่าข้อมูลที่รับได้มาจาก UDP Socket แล้วส่งข้อความกลับไป จากนั้นนำข้อมูลคะแนนที่ได้เป็น String แปลงเป็นข้อมูลชนิด Integer และทำการ Get ค่าเวลาและวันที่มาเก็บไว้จากนั้นทำการนำค่าเวลาละวันที่ไปกำหนดให้เป็นข้อมูลในแกน X และค่าคะแนนที่ได้ไปกำหนดให้เป็นข้อมูลของแกน Y และส่งไปเก็บบน Plotly และในส่วนสุดท้ายเป็นการทำ Except 2 อย่างคือเมื่อ Socket timeout ให้ทำการ Print คำว่า "Timeout" อีกหนึงอย่างือเมื่อมีการรับ Interrupt ที่เกิดจากการกด Keyboard

ไม่มีความคิดเห็น:

แสดงความคิดเห็น