Skip to content

Commit

Permalink
finish
Browse files Browse the repository at this point in the history
  • Loading branch information
vanguardmaster01 committed Sep 16, 2023
1 parent 15400f4 commit de4703d
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 43 deletions.
Binary file modified DbFuncs/sql.db
Binary file not shown.
53 changes: 44 additions & 9 deletions api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from dotenv import load_dotenv
load_dotenv()
from config.global_vars import global_ads, global_machines, global_produts
from config.utils import lockList, stopWebsocket
from config.utils import lockList


hostName = os.environ.get('hostName')
Expand All @@ -41,6 +41,8 @@ def send_get_ads_info():
# Send an HTTP GET request to a URL of your choice
response = requests.post(hostName + url, verify=False)

if lockList[1]:
return
# Check the response status code
if response.status_code == 200:
responseData = response.json() # {status : , message : , details : [{},]}
Expand All @@ -50,6 +52,8 @@ def send_get_ads_info():
db.delete_ads()
params = Ad(0, adData['type'], base64.b64decode(adData['content']))
global_ads.append(params)
if lockList[1]:
return
db.insert_ads(params)
else:
print(f"Request failed with status code: {response.status_code}")
Expand All @@ -61,6 +65,9 @@ def send_get_machine_info():
url = "/api/machine/get_machine_info"
response = requests.post(hostName + url, verify=False)

if lockList[1]:
return

# Check the response status code
if response.status_code == 200:
responseData = response.json() # {status : , message : , details : [{},]}
Expand All @@ -73,6 +80,8 @@ def send_get_machine_info():

global_machines.append(params)

if lockList[1]:
break
db.insert_machine(params)
else:
print(f"Request failed with status code: {response.status_code}")
Expand All @@ -82,6 +91,8 @@ def send_get_products_info():

# Send an HTTP GET request to a URL of your choice
response = requests.post(hostName + url, verify=False)
if lockList[1]:
return

# Check the response status code
if response.status_code == 200:
Expand All @@ -93,13 +104,16 @@ def send_get_products_info():
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 lockList[1]:
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()
Expand All @@ -110,7 +124,7 @@ async def connect_to_server():
ssl_context.verify_mode = ssl.CERT_NONE

print("wss thread id", threading.get_native_id())

try:
async with websockets.connect('wss://212.224.86.112:8443', ssl = ssl_context) as websocket:
print('connected')
Expand All @@ -125,14 +139,24 @@ async def connect_to_server():

machineConnectStatus = responseData['status']
token = responseData['token']
cnt = 0

if machineConnectStatus == 'success':
while True:

if stopWebsocket:
print('http_request_close')
if lockList[1]:
break

if cnt % 50 != 0:
time.sleep(0.1)
cnt = cnt+1
continue

cnt = cnt+1
# print(f'stopConnncet: {stopConnect}')
# if stopConnect:
# print('http_request_close')
# break

statusData = {
'action': "MachineSendStatus",
'payload': {
Expand All @@ -142,11 +166,20 @@ async def connect_to_server():
}
}
await websocket.send(json.dumps(statusData))
if (lockList[1]):
break

statusResponse = await websocket.recv()
if lockList[1]:
break

statusResponseData = json.loads(statusResponse)
print(f'send_websockrt_every10s')
machineGetStatus = statusResponseData['status']
machineGetType = statusResponseData['type']

if lockList[1]:
break

if machineGetStatus == 1:
lockList[0].acquire()
Expand All @@ -158,17 +191,19 @@ async def connect_to_server():
send_get_products_info()
lockList[0].release()

time.sleep(600)
else:
pass

if stopWebsocket:
print('websocket_close')
await websocket.close()
# if stopConnect:
# print('websocket_close')
# await websocket.close()
except:
pass
# global_ads = db.get_ad()
# global_produts = db.get_products()
# global_machines = db.get_machines()
lockList[1] = 2

def close_connect():
pass
# asyncio.get_event_loop().run_until_complete(connect_to_server())
5 changes: 3 additions & 2 deletions config/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def write_to_file(data, filename):
def initLock(lock):
global lockList
lockList.append(lock)
def initThreadLock(lock):
global lockList
lockList.append(lock)


stopWebsocket = False
2 changes: 1 addition & 1 deletion kv/list.kv
Original file line number Diff line number Diff line change
Expand Up @@ -258,4 +258,4 @@ WindowManager:

<CountNumber>:
<RoundedBorderGrid>:
<ImageScrollView>:
<ImageScrollView>:
80 changes: 49 additions & 31 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,29 @@
from kivy.clock import Clock
import threading
import time
from config.utils import initLock
from config.utils import stopWebsocket
from config.utils import initLock, initThreadLock, lockList
from kivy.config import Config
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.progressbar import ProgressBar
from kivy.uix.popup import Popup
from contextlib import suppress


_thread = None
stop_thread = False
loop = None
delta = 0


def between_callback():
global stop_thread
# global stop_thread
global loop
# while not stop_thread:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

loop.create_task(api.connect_to_server())
loop.run_forever()
# loop.close()
loop.run_until_complete(api.connect_to_server())


class WindowManager(ScreenManager):
Expand Down Expand Up @@ -70,12 +73,13 @@ def build(self):

print("main thread id", threading.get_native_id())
initLock(threading.Lock())
initThreadLock(0)

#connect db
db.openDatabase()

# _thread = threading.Thread(target=between_callback)
# _thread.start()
_thread = threading.Thread(target=between_callback)
_thread.start()

width = int(os.environ.get('screenX'))
height = int(os.environ.get('screenY'))
Expand All @@ -84,12 +88,7 @@ def build(self):

Config.set('graphics', 'width', width)
Config.set('graphics', 'height', height)
Config.set('graphics', 'custom_titlebar', '1')
Config.write()

# Window.size = (width, height)

# asyncio.get_event_loop().run_until_complete(api.connect_to_server())

sm.add_widget(adScreen)
sm.add_widget(listScreen)
Expand All @@ -101,42 +100,61 @@ def build(self):
listScreen.bind(on_touch_down=self.touch_screen)
itemScreen.bind(on_touch_down=self.touch_screen)

Window.bind(on_request_close=self.on_request_close)


return sm

# if user action, .....
def touch_screen(self, instance, touch):
global delta
delta = 0


def on_stop(self):
print('here')
def wait_apithread_stop(self, td):
global _thread
global stop_thread
global loop

stopWebsocket = True
# stop_thread = True

_thread.join(1)

# process = multiprocessing.current_process()
# process.kill()

loop.stop()

print('222')

try:
_thread.join(0.1)
if lockList[1] == 2:
_thread.join()
self.stopEvent.cancel()
self.stop()
except RuntimeError:
pass

# if nothing action for 1 min, display ad
def count_time(self, dt):
global delta
delta += 1
print(f'delta:{delta}')
if delta > 10:
if delta > 10000:
sm.current = 'Ad'
listScreen.clear_widgets()
listScreen.__init__()
itemScreen.clear_widgets()
itemScreen.__init__()
delta = 0

def on_request_close(self, *args):
print('request_close')
self.textpopup(title='Exit', text='Are you sure?')
return True

def wait_threadstop(self, *args):
lockList[1] = 1
self.stopEvent = Clock.schedule_interval(self.wait_apithread_stop, 0.2)

def textpopup(self, title='', text=''):
box = BoxLayout(orientation='vertical')
box.add_widget(Label(text=text))
mybutton = Button(text='OK', size_hint=(1, 0.5))
# box.add_widget(progress_bar)
box.add_widget(mybutton)
popup = Popup(title=title, content=box, size_hint=(None, None), size=(300, 150), auto_dismiss = False)
mybutton.bind(on_release=self.wait_threadstop)
popup.open()

if __name__ == '__main__':
MainApp().run()
db.closeDatabase()
Empty file added requirement.txt
Empty file.

0 comments on commit de4703d

Please sign in to comment.