-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
223 lines (182 loc) · 7.41 KB
/
api.py
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
# from websocket import create_connection
import requests
import time
import json
import asyncio
import websockets
import certifi
from model.Machine import Machine
from model.Ad import Ad
from model.Product import Product
from DbFuncs import db
import base64
import ssl
import certifi
import os
import threading
from dotenv import load_dotenv
load_dotenv()
from config.global_vars import global_ads, global_machines, global_produts
from config.utils import setThreadStatus, getThreadStatus, THREAD_INIT, THREAD_RUNNING, THREAD_STOPPING, THREAD_FINISHED
from config.utils import getDBLock, DBLOCK_ADS, DBLOCK_MACHINE, DBLOCK_PRODUCT
from websockets.exceptions import ConnectionClosed
hostName = os.environ.get('hostName')
# requestTimeStep = int(os.environ.get('requestTimeStep'))
def send_get_ads_info():
url = "/api/machine/get_ads_info"
# Send an HTTP GET request to a URL of your choice
response = requests.post(hostName + url, verify=False)
if getThreadStatus() == THREAD_STOPPING:
return
# Check the response status code
if response.status_code == 200:
responseData = response.json() # {status : , message : , details : [{},]}
adData = responseData['details']
# params = Ad(0, adData['type'], bytes(adData['content'], 'utf-8'))
global_ads = []
db.delete_ads()
params = Ad(0, adData['type'], base64.b64decode(adData['content']))
global_ads.append(params)
if getThreadStatus() == THREAD_STOPPING:
return
db.insert_ads(params)
else:
print(f"Request failed with status code: {response.status_code}")
def send_get_machine_info():
# Send an HTTP GET request to a URL of your choice
url = "/api/machine/get_machine_info"
response = requests.post(hostName + url, verify=False)
if getThreadStatus() == THREAD_STOPPING:
return
# Check the response status code
if response.status_code == 200:
responseData = response.json() # {status : , message : , details : [{},]}
machineData = responseData['details']
global_machines = []
# delete machine table
db.delete_machines()
for item in machineData:
params = Machine(0, item['name'], item['unit'], item['value'], base64.b64decode(item['thumbnail']))
global_machines.append(params)
if getThreadStatus() == THREAD_STOPPING:
return
db.insert_machine(params)
else:
print(f"Request failed with status code: {response.status_code}")
def send_get_products_info():
url = "/api/machine/get_product_info"
# Send an HTTP GET request to a URL of your choice
response = requests.post(hostName + url, verify=False)
if getThreadStatus() == THREAD_STOPPING:
return
# Check the response status code
if response.status_code == 200:
productData = response.json() # {status : , message : , details : [{},]}
global_produts = []
# delete products table
db.delete_products()
for item in productData:
params = Product(0, item['itemno'], item['name'], base64.b64decode(item['thumbnail']), item['nicotine'], item['batterypack'],
item['tankvolumn'], item['price'], item['currency'], item['caution'], item['stock'])
global_produts.append(params)
if getThreadStatus() == THREAD_STOPPING:
break
db.insert_product(params)
else:
print(f"Request failed with status code: {response.status_code}")
def send_sell_product():
url = "api/machine/sell_product"
websocket=None
async def connect_to_server():
# ssl_context = ssl.create_default_context()
# ssl_context.load_verify_locations(certifi.where())
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
print("wss thread id", threading.get_native_id())
setThreadStatus(THREAD_RUNNING)
cnt = 0
try:
websocket = await websockets.connect('wss://212.224.86.112:8443', ssl = ssl_context)
except:
pass
while True:
try:
if getThreadStatus() == THREAD_STOPPING:
break
if cnt % 50 != 0:
time.sleep(0.1)
cnt = (cnt+1) % 50
print('cnt', cnt)
continue
cnt = (cnt+1) % 50
# async with websockets.connect('wss://212.224.86.112:8443', ssl = ssl_context) as websocket:
if getThreadStatus() == THREAD_STOPPING:
break
sendData = {'action': 'MachineConnect'}
await websocket.send(json.dumps(sendData))
if getThreadStatus() == THREAD_STOPPING:
break
# Receive data
response = await websocket.recv()
responseData = json.loads(response)
print(f"Received data: {responseData}")
machineConnectStatus = responseData['status']
token = responseData['token']
if getThreadStatus() == THREAD_STOPPING:
break
if machineConnectStatus == 'success':
statusData = {
'action': "MachineSendStatus",
'payload': {
'serialno': "123-456-678",
'temparature': "XXX",
'token': token,
}
}
await websocket.send(json.dumps(statusData))
if getThreadStatus() == THREAD_STOPPING:
break
statusResponse = await websocket.recv()
if getThreadStatus() == THREAD_STOPPING:
break
statusResponseData = json.loads(statusResponse)
print(f'send_websockrt_every10s')
machineGetStatus = statusResponseData['status']
machineGetType = statusResponseData['type']
if getThreadStatus() == THREAD_STOPPING:
break
if machineGetStatus == 1:
if 'ads' in machineGetType:
getDBLock(DBLOCK_ADS).acquire()
try:
send_get_ads_info()
except:
pass
getDBLock(DBLOCK_ADS).release()
if 'machine' in machineGetType:
getDBLock(DBLOCK_MACHINE).acquire()
try:
send_get_machine_info()
except:
pass
getDBLock(DBLOCK_MACHINE).release()
if 'product' in machineGetType:
getDBLock(DBLOCK_PRODUCT).acquire()
try:
send_get_products_info()
except:
pass
getDBLock(DBLOCK_PRODUCT).release()
except (ConnectionClosed):
try:
websocket = await websockets.connect('wss://212.224.86.112:8443', ssl = ssl_context)
except:
pass
try:
websocket.close()
except:
pass
setThreadStatus(THREAD_FINISHED)
def close_connect():
pass