import os
import RPi.GPIO as GPIO
import time
import urllib.request
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
#**************************************************************************
#****** all pin numbers defined in this section ***************************
#**************************************************************************
ldr_input = 40
#reads the reading of the LDR matrix
fireball = 38
#pushbutton and led for spell 1
lightning = 37
#pushbutton for spell 2
frost = 33
#pushbutton and timeout led for spell 3
laser_out = 29
#pin for laser output, 'on/off'
left_shoulder_1 = 22
left_shoulder_2 = 18
#pins for the 2 vibration motors on the left shoulder
right_shoulder_1 = 16
right_shoulder_2 = 12
#pins for the 2 vibration motors on the right shoulder
abdomen_1 = 15
abdomen_2 = 7
#pins for the 2 vibration motors on abdomen
delta_value = 20000
#this is the threshold value for the LDR input, if the LDR input
#changes by delta_value or more, we will conclude that the opponent's
#spell hit
healthLed_red = 23
healthLed_Green = 24
Health_points = 100
#**************************************************************************
#************ all pins initialized in this section ************************
#**************************************************************************
GPIO.setup(ldr_input, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(fireball, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(lightning, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(frost, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
#the pull_up_down argument controls the state of internal resistors
GPIO.setup(laser_out, GPIO.OUT)
GPIO.setup(left_shoulder_1, GPIO.OUT)
GPIO.setup(left_shoulder_2, GPIO.OUT)
GPIO.setup(right_shoulder_1, GPIO.OUT)
GPIO.setup(right_shoulder_2, GPIO.OUT)
GPIO.setup(abdomen_1, GPIO.OUT)
GPIO.setup(abdomen_2, GPIO.OUT)
GPIO.setup(healthLed_Green, GPIO.OUT)
GPIO.setup(healthLed_red, GPIO.OUT)
#**************************************************************************
#**************************************************************************
#************************* all Functions go here **************************
#**************************************************************************
def LDR_resistance():
#this function measures the time it takes to charge the capacitor,
#calculates the corresponding value of resistance of LDR,
#And then returns it
mpin = 11
tpin = 13
cap = 0.000001
adj = 2.130620985
i=0
t=0
while(i<11):
GPIO.setup(mpin, GPIO.OUT)
GPIO.setup(tpin, GPIO.OUT)
GPIO.output(mpin, False)
GPIO.output(tpin, False)
GPIO.setup(mpin, GPIO.IN)
GPIO.output(tpin, True)
startTime = time.time()
endtime = time.time()
while(GPIO.input(mpin) == GPIO.LOW):
endtime = time.time()
MeasureResistance = endtime - startTime
res = (MeasureResistance/cap)*adj
i = i + 1
t = t + res
if(i == 10):
t = t / i
return t
def Read_data():
#this function reads the spell cast from the other RPi by requesting
#access from its server
#it returns a string corresponding to the spell cast by the other person
myfile = open('live_ip.txt')
ip = myfile.read()
ip=str(ip)
link = 'http://'+ip+':8080'
f = urllib.request.urlopen(link)
data = f.read().decode('utf-8')
myfile.close()
return str(data)
def change_server_data(spell):
#This function changes spell name present on the running
#server created by the file server.py
file = open("../server.py", 'r')
data = file.read()
file.close()
start = data.find("return")
end = data.find("\n", start)
start += 8
end = end-1
new_data = data[:start] + str(spell) + data[end:]
file = open("../server.py", 'w')
file.write(new_data)
file.close()
def initGame():
# server always gets initialized at the beginning of the game
#when RPi is switched on, no need for the code to do that here
#get the IP of the second RPi, use the OS module to do so
os.system("python3 /home/pi/Desktop/assets/get_ip.py")
#check if the correct ip was found
myfile = open('live_ip.txt')
ip = myfile.read()
myfile.close()
chech_var = os.system('ping '+str(ip)+' -c 1')
if(chech_var==0):
#ping was successful, IP found correctly
GPIO.output(healthLed_Green, GPIO.HIGH)
GPIO.output(healthLed_red, GPIO.LOW)
return
else:
#ping not successful, try to find the live IP again
initGame()
return
def laser_Flash(spell):
time1 = None
if(str(spell) == 'lightning'):
time1 = 0.5
elif(str(spell)== 'fireball'):
time1 = 1
else:
time1 = 1.5
GPIO.output(laser_out, GPIO.HIGH)
time.sleep(time)
GPIO.output(laser_out, GPIO.LOW)
if __name__ == "__main__":
#initialize the game
initGame()
#switch on the green Health LED
GPIO.output(healthLed_Green, GPIO.HIGH)
#now the main game loop comes
while True:
#read the LDR reading
ldr_reading = LDR_resistance()
print(ldr_reading)
if(ldr_reading < delta_value):
#means that a hit was detected
#read the spell which hit you
opponent_casted = Read_data()
print(opponent_casted)
if(opponent_casted == 'lightning'):
Health_points -= 20
#Give the haptic feedback
for i in range(0,3):
GPIO.output(abdomen_1, GPIO.HIGH)
GPIO.output(abdomen_2, GPIO.HIGH)
time.sleep(0.2)
GPIO.output(abdomen_1, GPIO.LOW)
GPIO.output(abdomen_2, GPIO.LOW)
time.sleep(0.1)
elif(opponent_casted == 'fireball'):
Health_points -= 12.5
#give haptic feedback
GPIO.output(right_shoulder_1, GPIO.HIGH)
GPIO.output(right_shoulder_2, GPIO.HIGH)
time.sleep(2)
GPIO.output(right_shoulder_1, GPIO.LOW)
GPIO.output(right_shoulder_2, GPIO.LOW)
else:
Health_points -= 5
#frost detected
#give haptic feedback
GPIO.output(left_shoulder_1, GPIO.HIGH)
GPIO.output(left_shoulder_2, GPIO.HIGH)
time.sleep(1)
GPIO.output(left_shoulder_1, GPIO.LOW)
GPIO.output(left_shoulder_2, GPIO.LOW)
if(Health_points <= 0):
#switch of the green led and light up the red one
#exit and break from the main game loop
GPIO.output(healthLed_Green, GPIO.LOW)
GPIO.output(healthLed_red, GPIO.HIGH)
break
else:
#check if any button was pressed to cast a spell
if( GPIO.input(fireball)==GPIO.HIGH and GPIO.input(frost)==GPIO.LOW and GPIO.input(lightning)==GPIO.LOW ):
#Only fireball was cast, no other button was pressed
change_server_data("fireball")
time.sleep(0.1)
laser_Flash('fireball')
if( GPIO.input(fireball)==GPIO.LOW and GPIO.input(frost)==GPIO.LOW and GPIO.input(lightning)==GPIO.HIGH ):
#Only fireball was cast, no other button was pressed
change_server_data("lightning")
time.sleep(0.1)
laser_Flash('lightning')
if( GPIO.input(fireball)==GPIO.LOW and GPIO.input(frost)==GPIO.HIGH and GPIO.input(lightning)==GPIO.LOW ):
#Only fireball was cast, no other button was pressed
change_server_data("frost")
time.sleep(0.1)
laser_Flash('frost')
while(True):
print("GameOver")
GPIO.output(24, False)
GPIO.output(23, GPIO.HIGH)
print("hello")
time.sleep(1)
#!/usr/bin/python
import web
urls=(
'/','index'
)
class index:
def GET(self):
return "sdhifgweifbwivi"
if __name__ == "__main__":
app=web.application(urls,globals())
app.run()
import os
import socket
import multiprocessing
import subprocess
import urllib
import requests
def pinger(job_q, results_q):
"""
Do Ping
:param job_q:
:param results_q:
:return:
"""
DEVNULL = open(os.devnull, 'w')
while True:
ip = job_q.get()
if ip is None:
break
try:
subprocess.check_call(['ping', '-c1', ip], stdout=DEVNULL)
results_q.put(ip)
except:
pass
def get_my_ip():
"""
Find my IP address
:return:
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
def map_network(pool_size=255):
"""
Maps the network
:param pool_size: amount of parallel ping processes
:return: list of valid ip addresses
"""
ip_list = list()
# get my IP and compose a base like 192.168.1.xxx
ip_parts = get_my_ip().split('.')
base_ip = ip_parts[0] + '.' + ip_parts[1] + '.' + ip_parts[2] +'.'
# prepare the jobs queue
jobs = multiprocessing.Queue()
results = multiprocessing.Queue()
pool = [multiprocessing.Process(target=pinger, args=(jobs, results)) for i in range(pool_size)]
for p in pool:
p.start()
# cue hte ping processes
for i in range(1, 255):
jobs.put(base_ip + '{0}'.format(i))
for p in pool:
jobs.put(None)
for p in pool:
p.join()
# collect the results
while not results.empty():
ip = results.get()
if(ip!=get_my_ip()):
ip_list.append(ip)
return ip_list
if __name__ == '__main__':
lst = map_network()
myfile = open('live_ip.txt','w')
live_ip = None
for ip in lst:
link = "http://"+ip+":8080"
try :
f=urllib.request.urlopen(link)
live_ip = ip
myfile.write(live_ip)
except:
continue
myfile.close()