-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.py
More file actions
236 lines (199 loc) · 6.79 KB
/
backend.py
File metadata and controls
236 lines (199 loc) · 6.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
from flask import Flask, jsonify, request
from flask_cors import CORS
import pigpio
import time
import threading
import socket
import board
import busio
import adafruit_bus_device.i2c_device as i2c_device
from adafruit_ads1x15.ads1115 import ADS1115
from adafruit_ads1x15.analog_in import AnalogIn
import random
import paho.mqtt.client as pmc
import json as json_player
# VARIABLE PIGPIO
pi = pigpio.pi()
i2c = busio.I2C(board.SCL, board.SDA)
matrix = i2c_device.I2CDevice(i2c, 0x70)
R,G,B = 21,20,16
BUZZER = 19
ads = ADS1115(i2c)
# Flask
app = Flask(__name__)
CORS(app)
# MQQT Variables
Broker = "10.10.21.144"
GAME_TOPIC = "map"
PORT = 1883
# Donne des joueurs
player1_data = {
"player1_scores" : None,
# "isReady" : False
}
player2_data = {
"player2_scores" : None,
# "isReady" : False
}
# Initialisation de la matrix 8x8
matrix.write(bytes([0x21]))
matrix.write(bytes([0x81]))
matrix.write(bytes([0xEF]))
# les déclarations de pi
pi.set_mode(R, pigpio.OUTPUT)
pi.set_mode(G, pigpio.OUTPUT)
pi.set_mode(B, pigpio.OUTPUT)
pi.set_mode(BUZZER, pigpio.OUTPUT)
x = AnalogIn(ads, 0)
y = AnalogIn(ads, 1)
global game_timer
game_timer = 15
# --- CONFIGURATION ---
global NUM_TARGETS
MOVE_SPEED = 0.4
CENTER_VAL = 13250
DEAD_ZONE = 8000
NUM_TARGETS = 10 # Set how many dots you want
buzzer_triggered = False
# list for the map
global targets
targets = []
# Initial for the dot
global dot_x
dot_x = 0.0
global dot_y
dot_y = 7.0
# Function to return color of rgb with r,g,b = 1 or 0
def led_state(r,g,b):
pi.write(R,r)
pi.write(G,g)
pi.write(B,b)
# Function to clear the matrix board
def clearMatrix():
with matrix as mem:
mem.write(bytearray([0x00] * 17))
time.sleep(0.5)
# Fonction to calculate the movement of the joystick
def calculate_step(raw_value):
diff = raw_value - CENTER_VAL
if abs(diff) < DEAD_ZONE: return 0
return (diff / 16000) * MOVE_SPEED
def connexion(client, userdata, flags, code, properties):
if code == 0:
mqtt_client.subscribe("map")
else:
print("Erreur code %d\n", code)
def reception_msg(cl,userdata,msg):
message = msg.payload.decode()
if "player1_score" in message:
player1_score = message.split(":").pop().replace("}", "")
player1_data['player1_scores'] = player1_score
elif "player2_score" in message:
player2_score = message.split(":").pop().replace("}", "")
player2_data['player2_scores'] = player2_score
else:
print("Reçu:", message)
def map_display(num_targets):
global targets
targets = [[random.randint(0, 7), random.randint(0, 7)] for _ in range(num_targets)]
targets1 = [[random.randint(0, 7), random.randint(0, 7)] for _ in range(num_targets)]
targets2 = [[random.randint(0, 7), random.randint(0, 7)] for _ in range(num_targets)]
payload = {
"type": "MAP_DATA",
"targets": targets,
"targets1": targets1,
"targets2": targets2,
}
return json_player.dumps(payload)
mqtt_client = pmc.Client(pmc.CallbackAPIVersion.VERSION2)
mqtt_client.on_connect = connexion
mqtt_client.on_message = reception_msg
mqtt_client.connect(Broker, PORT)
threading.Thread(target=mqtt_client.loop_forever, daemon=True).start()
game_state = 'Connected'
@app.route('/api/get_game_state', methods=['GET'])
def get_game_state():
global score
global game_state
global buzzer_triggered
global player2_score
global game_timer
mqtt_client.on_message = reception_msg
player1_score = player1_data['player1_scores']
player2_score = player2_data['player2_scores']
# bleue = en_jeux, blanc = connected
if game_state == "Connected":
led_state(0,0,0)
else:
led_state(1,1,1)
pi.write(BUZZER,0)
return jsonify({'game_state': game_state, 'player1_score': player1_score, 'player2_score': player2_score}),200
@app.route('/api/set_game_state', methods=['POST'])
def set_game_state():
global game_state
global dot_x
global dot_y
global score
global targets
scores = 0
rounds = 0
if request.method == "POST":
json = request.get_json()
if 'game_state' in json and 'difficulty' in json:
if json['game_state'] == 'start':
game_state = 'Game Started'
clearMatrix()
if json['difficulty'] == 'Easy':
NUM_TARGETS = 5
elif json['difficulty'] == 'Normal':
NUM_TARGETS = 7
elif json['difficulty'] == 'Hard':
NUM_TARGETS = 10
print(NUM_TARGETS)
mqtt_client.publish(GAME_TOPIC, map_display(NUM_TARGETS))
led_state(1,1,0)
pi.write(BUZZER,1)
time.sleep(1)
pi.write(BUZZER,0)
# # Setup Matrix
# with matrix as mem:
# mem.write(bytes([0x21]))
# mem.write(bytes([0x81]))
# mem.write(bytes([0xEF]))
# try:
# # 3. WIN CONDITION
# if not targets:
# print("Level Cleared! Spawning new wave...")
# time.sleep(1)
# rounds += 1
# mqtt_client.publish(GAME_TOPIC, map_display(NUM_TARGETS))
# print(f"Rounds : {rounds}")
# if rounds == 3:
# print("Fin du programme")
# player1_data["player1_scores"] = scores
# json_payload = str(player1_data)
# mqtt_client.publish(GAME_TOPIC, json_payload)
# with matrix as mem:
# mem.write(bytearray([0x00] * 17))
# game_state = "Connected"
# time.sleep(0.02)
# except:
# clearMatrix()
# game_state = "Connected"
elif json['game_state'] == 'restart' or json['game_state'] == 'end':
end_payload = {
"type" : "GAME_STATE",
"game_state" : "end"
}
mqtt_client.publish(GAME_TOPIC, "end")
game_state = 'Connected'
clearMatrix()
else:
return jsonify({'Erreur': 'Mauvaise valeur'}),500
else:
return jsonify({'Erreur': 'Requete invalide'}),500
else:
return jsonify({'Erreur': 'Requetes POST seulement'}),500
return jsonify({'game_state': game_state}),200
if __name__ == '__main__':
app.run(host='192.168.18.1', port=5000) # host='192.168.18.1'