-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
332 lines (289 loc) · 9.03 KB
/
main.go
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os/exec"
"strconv"
"strings"
"sync"
"time"
contract "github.com/NetSepio/dwifi-client/callcontract"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/fatih/color"
"golang.org/x/net/websocket"
)
type DeviceInfo struct {
MACAddress string `json:"macAddress"`
IPAddress string `json:"ipAddress"`
ConnectedAt time.Time `json:"connectedAt"`
TotalConnectedTime time.Duration `json:"totalConnectedTime"`
Connected bool `json:"connected"`
LastChecked time.Time `json:"lastChecked"`
DefaultGateway string `json:"defaultGateway"`
Manufacturer string `json:"manufacturer"`
InterfaceName string `json:"interfaceName"`
HostSSID string `json:"hostSSID"`
}
type WiFiData struct {
ID uint `json:"id" gorm:"primaryKey"`
Gateway string `json:"gateway"`
Status []DeviceInfo `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Password string `json:"password"`
PricePerMin string `json:"price_per_min"`
ChainName string `json:"chain_name"`
}
type NearbyNetwork struct {
SSID string `json:"ssid"`
SignalStrength int `json:"signalStrength"`
BSSID string `json:"bssid"`
Channel string `json:"channel"`
Frequency string `json:"frequency"`
Rate string `json:"rate"`
Security string `json:"security"`
Gateway string `json:"gateway"`
PricePerMin string `json:"price_per_min"`
ChainName string `json:"chain_name"`
}
type CurrentWiFi struct {
SSID string `json:"ssid"`
BSSID string `json:"bssid"`
Signal string `json:"signal"`
Frequency string `json:"frequency"`
Rate string `json:"rate"`
Security string `json:"security"`
}
var wifiDataList []WiFiData
var mu sync.Mutex
func ConnectToWiFi(ssid, password string) error {
cmd := exec.Command("nmcli", "dev", "wifi", "connect", ssid, "password", password)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to connect to WiFi network: %s, %w", string(output), err)
}
return nil
}
func ScanNearbyNetworks() ([]NearbyNetwork, error) {
cmd := exec.Command("nmcli", "-t", "-f", "SSID,SIGNAL,BSSID,CHAN,FREQ,RATE,SECURITY", "dev", "wifi")
output, err := cmd.Output()
if err != nil {
return nil, err
}
var networks []NearbyNetwork
lines := strings.Split(string(output), "\n")
for _, line := range lines {
if line == "" {
continue
}
parts := strings.Split(line, ":")
if len(parts) < 7 {
continue
}
signalStrength, err := strconv.Atoi(parts[1])
if err != nil {
continue
}
networks = append(networks, NearbyNetwork{
SSID: parts[0],
SignalStrength: signalStrength,
BSSID: parts[2],
Channel: parts[3],
Frequency: parts[4],
Rate: parts[5],
Security: parts[6],
})
}
mu.Lock()
defer mu.Unlock()
for i, network := range networks {
for _, data := range wifiDataList {
for _, status := range data.Status {
if status.HostSSID == network.SSID {
networks[i].Gateway = data.Gateway
networks[i].PricePerMin = data.PricePerMin
networks[i].ChainName = data.ChainName
}
}
}
}
return networks, nil
}
func getCurrentWiFi(w http.ResponseWriter, r *http.Request) {
cmd := exec.Command("bash", "-c", "nmcli -t -f NAME connection show --active | grep -v '^lo$'")
output, err := cmd.Output()
if err != nil {
log.Fatalf("cmd.Run() failed with %s\n", err)
}
fmt.Printf("Active connection: %s\n", output)
ssid := strings.TrimSpace(string(output))
response := struct {
SSID string `json:"ssid"`
}{
SSID: ssid,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func disconnectAndPay(w http.ResponseWriter, r *http.Request) {
var requestData struct {
SSID string `json:"ssid"`
WalletAddress string `json:"walletAddress"`
PrivateKey string `json:"privateKey"`
}
if err := json.NewDecoder(r.Body).Decode(&requestData); err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
return
}
client, err := ethclient.Dial("https://rpcpc1-qa.agung.peaq.network")
if err != nil {
http.Error(w, fmt.Sprintf("Failed to connect to the Ethereum client: %v", err), http.StatusInternalServerError)
return
}
privateKey, err := crypto.HexToECDSA(requestData.PrivateKey)
if err != nil {
http.Error(w, fmt.Sprintf("Error loading private key: %v", err), http.StatusInternalServerError)
return
}
userWalletAddress := common.HexToAddress(requestData.WalletAddress)
txHash, minedHash, err := contract.MintAndPay(client, userWalletAddress, privateKey)
if err != nil {
http.Error(w, fmt.Sprintf("Error in payment process: %v", err), http.StatusInternalServerError)
return
}
cmd := exec.Command("nmcli", "-t", "-f", "DEVICE,TYPE", "device")
output, err := cmd.Output()
if err != nil {
http.Error(w, fmt.Sprintf("Error getting device list: %v", err), http.StatusInternalServerError)
return
}
var wifiDevice string
lines := strings.Split(string(output), "\n")
for _, line := range lines {
parts := strings.Split(line, ":")
if len(parts) == 2 && parts[1] == "wifi" {
wifiDevice = parts[0]
break
}
}
if wifiDevice == "" {
http.Error(w, "No WiFi device found", http.StatusInternalServerError)
return
}
cmd = exec.Command("nmcli", "device", "disconnect", wifiDevice)
err = cmd.Run()
if err != nil {
http.Error(w, fmt.Sprintf("Error disconnecting from WiFi: %v", err), http.StatusInternalServerError)
return
}
response := struct {
Message string `json:"message"`
TxHash string `json:"txHash"`
MinedHash string `json:"minedHash"`
}{
Message: "Successfully disconnected from WiFi and completed payment",
TxHash: txHash,
MinedHash: minedHash,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func handleWebSocket(ws *websocket.Conn) {
var buffer string
for {
var msg string
if err := websocket.Message.Receive(ws, &msg); err != nil {
color.Red("Failed to receive message: %v", err)
return
}
buffer += msg
if json.Valid([]byte(buffer)) {
var newWiFiData WiFiData
if err := json.Unmarshal([]byte(buffer), &newWiFiData); err != nil {
color.Red("Failed to unmarshal message: %v", err)
buffer = ""
continue
}
mu.Lock()
found := false
for i, data := range wifiDataList {
if data.ID == newWiFiData.ID {
wifiDataList[i] = newWiFiData
found = true
break
}
}
if !found {
wifiDataList = append(wifiDataList, newWiFiData)
}
// color.Yellow("Received WiFi data for ID: %d, SSID: %s, Gateway: %s,Price_per_min: %s, Chain: %s",
// newWiFiData.ID, newWiFiData.Status[0].HostSSID, newWiFiData.Gateway, newWiFiData.PricePerMin, newWiFiData.ChainName)
mu.Unlock()
buffer = ""
}
}
}
func main() {
color.Cyan("Connecting to WebSocket...")
origin := "http://localhost/"
url := "wss://dev.gateway.erebrus.io/api/v1.0/nodedwifi/stream"
ws, err := websocket.Dial(url, "", origin)
if err != nil {
color.Red("Failed to connect to WebSocket: %v", err)
return
}
defer ws.Close()
fmt.Println(color.HiMagentaString("__________________________________________________________________________________________________\n"))
go handleWebSocket(ws)
http.HandleFunc("/wifi-networks", func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(wifiDataList)
})
http.HandleFunc("/scan-nearby-networks", func(w http.ResponseWriter, r *http.Request) {
networks, err := ScanNearbyNetworks()
if err != nil {
http.Error(w, fmt.Sprintf("failed to scan nearby networks: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(networks)
})
http.HandleFunc("/connect-wifi", func(w http.ResponseWriter, r *http.Request) {
var requestData struct {
SSID string `json:"ssid"`
}
if err := json.NewDecoder(r.Body).Decode(&requestData); err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
return
}
mu.Lock()
var password string
for _, data := range wifiDataList {
for _, status := range data.Status {
if status.HostSSID == requestData.SSID {
password = data.Password
break
}
}
}
mu.Unlock()
err := ConnectToWiFi(requestData.SSID, password)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintln(w, "WiFi connection attempt completed. Please check your network status.")
})
http.HandleFunc("/current-wifi", getCurrentWiFi)
http.HandleFunc("/disconnect-and-pay", disconnectAndPay)
fs := http.FileServer(http.Dir("./frontend"))
http.Handle("/", fs)
fmt.Println("Server is running on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}