-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
227 lines (178 loc) · 7.59 KB
/
server.py
File metadata and controls
227 lines (178 loc) · 7.59 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
from flask import Flask
from flask_cors import CORS
from ctypes import *
import time
app = Flask(__name__)
CORS(app)
# Load WaveForms SDK
dwf = cdll.LoadLibrary("libdwf.so")
hdwf = c_int()
version = create_string_buffer(32)
dwf.FDwfGetVersion(version)
print("WaveForms SDK version:", version.value.decode())
# Open the first AD2 device
dwf.FDwfDeviceOpen(c_int(-1), byref(hdwf))
if hdwf.value == 0:
raise Exception("Failed to open AD2 device")
# Disable auto-configuration to prevent device from resetting state
# This ensures digital I/O and analog outputs remain stable
dwf.FDwfDeviceAutoConfigureSet(hdwf, c_int(0))
print("AD2 device opened successfully (auto-configure disabled for stability)")
ACTIVE_LOW = True # True for INPUT_PULLUP (most Arduino/AVR), False for pull-down logic
# Track current pin states (bitmask)
current_output_state = 0
current_enable_state = 0
# Initialize button pins to "released" state on startup
def init_button(pin):
global current_output_state, current_enable_state
# Enable this pin as output
current_enable_state |= (1 << pin)
dwf.FDwfDigitalIOOutputEnableSet(hdwf, c_uint32(current_enable_state))
# Set to released state
if ACTIVE_LOW:
current_output_state |= (1 << pin) # Set HIGH (released)
else:
current_output_state &= ~(1 << pin) # Set LOW (released)
dwf.FDwfDigitalIOOutputSet(hdwf, c_uint32(current_output_state))
dwf.FDwfDigitalIOConfigure(hdwf)
print(f"Button pin {pin} initialized to released state")
# Track initialized channels to avoid re-initializing
initialized_channels = set()
# Potentiometer control via Analog Output Channels
def init_potentiometer(channel):
"""Initialize analog output channel for DC voltage output (simulating potentiometer)"""
if channel in initialized_channels:
return # Already initialized
ch = c_int(channel)
# Configure for DC output
dwf.FDwfAnalogOutNodeEnableSet(hdwf, ch, c_int(0), c_int(1)) # Enable carrier node
dwf.FDwfAnalogOutNodeFunctionSet(hdwf, ch, c_int(0), c_int(0)) # DC function
dwf.FDwfAnalogOutNodeOffsetSet(hdwf, ch, c_int(0), c_double(0.0)) # Start at 0V
dwf.FDwfAnalogOutRunSet(hdwf, ch, c_double(0.0)) # Run continuously
dwf.FDwfAnalogOutConfigure(hdwf, ch, c_int(3)) # Start and keep running (mode 3)
initialized_channels.add(channel)
print(f"Potentiometer W{channel + 1} (channel {channel}) initialized to 0V")
def set_potentiometer_voltage(channel, voltage):
"""Set the potentiometer voltage (0V to 3.3V typical for AVR analog input)"""
ch = c_int(channel)
# Clamp voltage to safe range for AVR (0-3.3V)
voltage = max(0.0, min(3.3, voltage))
# Ensure channel is initialized first
init_potentiometer(channel)
dwf.FDwfAnalogOutNodeOffsetSet(hdwf, ch, c_int(0), c_double(voltage))
dwf.FDwfAnalogOutConfigure(hdwf, ch, c_int(3)) # Update with mode 3 (keep running)
print(f"W{channel + 1} set to {voltage:.2f}V ({(voltage/3.3)*100:.0f}%)")
return voltage
def press_button(pin):
global current_output_state, current_enable_state
print(f"[DEBUG] Pressing button on pin {pin}")
# Enable this pin as output
current_enable_state |= (1 << pin)
dwf.FDwfDigitalIOOutputEnableSet(hdwf, c_uint32(current_enable_state))
# Set this pin to pressed state (LOW for active-low, HIGH for active-high)
if ACTIVE_LOW:
current_output_state &= ~(1 << pin) # Clear bit = LOW
else:
current_output_state |= (1 << pin) # Set bit = HIGH
dwf.FDwfDigitalIOOutputSet(hdwf, c_uint32(current_output_state))
result = dwf.FDwfDigitalIOConfigure(hdwf)
if result == 0:
print(f"[ERROR] Failed to configure digital IO for pin {pin}")
else:
print(f"[SUCCESS] Pin {pin} pressed (state: 0x{current_output_state:X})")
def release_button(pin):
global current_output_state, current_enable_state
print(f"[DEBUG] Releasing button on pin {pin}")
# Keep pin as output
current_enable_state |= (1 << pin)
dwf.FDwfDigitalIOOutputEnableSet(hdwf, c_uint32(current_enable_state))
# Set this pin to released state (HIGH for active-low, LOW for active-high)
if ACTIVE_LOW:
current_output_state |= (1 << pin) # Set bit = HIGH
else:
current_output_state &= ~(1 << pin) # Clear bit = LOW
dwf.FDwfDigitalIOOutputSet(hdwf, c_uint32(current_output_state))
result = dwf.FDwfDigitalIOConfigure(hdwf)
if result == 0:
print(f"[ERROR] Failed to configure digital IO for pin {pin}")
else:
print(f"[SUCCESS] Pin {pin} released (state: 0x{current_output_state:X})")
@app.route("/press", methods=["POST"])
def api_press():
from flask import request
data = request.get_json()
if not data or 'pin' not in data:
return {"error": "pin parameter required"}, 400
try:
pin = int(data['pin'])
# Initialize pin on first use
init_button(pin)
press_button(pin)
return {"status": "pressed", "pin": pin}
except ValueError:
return {"error": "pin must be a number"}, 400
@app.route("/release", methods=["POST"])
def api_release():
from flask import request
data = request.get_json()
if not data or 'pin' not in data:
return {"error": "pin parameter required"}, 400
try:
pin = int(data['pin'])
release_button(pin)
return {"status": "released", "pin": pin}
except ValueError:
return {"error": "pin must be a number"}, 400
@app.route("/toggle", methods=["POST"])
def api_toggle():
from flask import request
data = request.get_json()
if not data or 'pin' not in data:
return {"error": "pin parameter required"}, 400
try:
pin = int(data['pin'])
# Initialize pin on first use
init_button(pin)
press_button(pin)
time.sleep(0.05)
release_button(pin)
return {"status": "toggled", "pin": pin}
except ValueError:
return {"error": "pin must be a number"}, 400
@app.route("/", methods=["GET"])
def api_health():
return {
"status": "ok",
"message": "Digilent AD2 Server Running",
"device_handle": hdwf.value
}
@app.route("/potentiometer/set", methods=["POST"])
def api_set_potentiometer():
from flask import request
data = request.get_json()
if not data or 'voltage' not in data or 'channel' not in data:
return {"error": "voltage and channel parameters required"}, 400
try:
channel = int(data['channel'])
voltage = float(data['voltage'])
actual_voltage = set_potentiometer_voltage(channel, voltage)
return {"channel": channel, "voltage": actual_voltage, "status": "set"}
except ValueError:
return {"error": "channel and voltage must be numbers"}, 400
@app.route("/potentiometer/percent", methods=["POST"])
def api_set_potentiometer_percent():
from flask import request
data = request.get_json()
if not data or 'percent' not in data or 'channel' not in data:
return {"error": "percent and channel parameters required"}, 400
try:
channel = int(data['channel'])
percent = float(data['percent'])
percent = max(0.0, min(100.0, percent))
voltage = (percent / 100.0) * 3.3
actual_voltage = set_potentiometer_voltage(channel, voltage)
return {"channel": channel, "percent": percent, "voltage": actual_voltage, "status": "set"}
except ValueError:
return {"error": "channel and percent must be numbers"}, 400
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5005)