Python/Basic/chick_python_exam/Unit1_basic/EXE/BS switching v1/BS.py
2024-06-27 15:41:10 +08:00

50 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
'''
Program: BS.py (Report bugs/comments to chikh@yuntech.edu.tw)
Function: 發送端程式,模擬訊息發送端的行為;訊息的內容設為當下感測到的溫度值(以隨機產生的亂數作替代)
將把溫度值打包成為字串的一部分,再透過網路機制把訊息字串傳送至接收端,隨即等候對方回應
'''
import socket #引入網路連線所需的套件,傳送/接收訊息之用
import time #引入時間套件將呼叫sleep()函數
import random #引入隨機亂數相關套件將呼叫uniform()函數
import sys
import os
IP = 'localhost' #本機網路位址(IP address)
#IP = '140.125.21.42' #對方端裝置的IP address
port = 20001 #對方(收端)程式所用埠號
peerEndpoint = (IP,port) #端點:(對方IP地址,埠號)
netLink = socket.socket(family=socket.AF_INET,type=socket.SOCK_DGRAM) #創建網路連線所需的資料結構
netLink.setblocking(False)
print("*** 基地台週期發送信標 ***\n");
if len(sys.argv) < 4:
BSid = int(input("輸入基地台編號(0/1) ==> "))
BSx, BSy = input("輸入基地台x y座標 ==> ").split()
BSx, BSy = int(BSx), int(BSy)
else:
BSid, BSx, BSy = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])
print("BS%d已啟動,地理位置(%d,%d)"%(BSid,BSx,BSy))
os.system("title "+ "BS%d監控視窗"%BSid)
logFile = open("BS%d.txt"%BSid,"w")
while True:
ts = time.time()
msg = "%d %f %d %d"%(BSid,ts,BSx,BSy)
logFile.write("%f "%ts)
data = msg.encode("utf-8")
netLink.sendto(data,peerEndpoint)
print("BS"+msg,sep="")
try:
msgReceived, _ = netLink.recvfrom(1024)
if msgReceived == b'quit': break
except:
time.sleep(0.5)
logFile.close()
print("BS%d關閉"%BSid)