Skip to content

Commit

Permalink
web connect
Browse files Browse the repository at this point in the history
  • Loading branch information
vanguardmaster01 committed Sep 15, 2023
1 parent dc2d64d commit 441259b
Show file tree
Hide file tree
Showing 16 changed files with 294 additions and 126 deletions.
5 changes: 1 addition & 4 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,4 @@ DbFuncs/__pycache__/
model/__pycache__/

# ignore __pycache__ directory
__pycache__/

# ignore test directory
test/
__pycache__/
79 changes: 54 additions & 25 deletions DbFuncs/db.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import sqlite3
import datetime
from config import utils
import os

# import os
# import sys
Expand All @@ -22,8 +23,8 @@ def insert_ads(ad):
insert_query = """insert into ads (type, content)
values (?, ?)"""

blodData = utils.convert_to_blod_data(ad.content)
data = (ad.type, (blodData))
# blodData = utils.convert_to_blod_data(ad.content)
data = (ad.type, ad.content)

cursor.execute(insert_query, data)

Expand All @@ -47,10 +48,11 @@ def insert_machine(machine):
conn = sqlite3.connect(utils.dbPath)
cursor = conn.cursor()

insert_query = """insert into machines (name, unit, value)
values (?, ?, ?)"""

data = (machine.name, machine.unit, machine.value)
insert_query = """insert into machines (name, unit, value, thumbnail)
values (?, ?, ?, ?)"""

# blodData = utils.convert_to_blod_data(machine.thumbnail)
data = (machine.name, machine.unit, machine.value, machine.thumbnail)

cursor.execute(insert_query, data)

Expand All @@ -76,13 +78,14 @@ def insert_product(product):
conn = sqlite3.connect(utils.dbPath)
cursor = conn.cursor()

insert_query = """insert into products (itemno, name, thumbnail, nicotine, batterypack, tankvolumn, price, currency, caution)
values (?, ?, ?, ?, ?, ?, ?, ?, ?)"""
imageBlob = utils.convert_to_blod_data(product.thumbnail)
data = (product.itemno, product.name, (imageBlob), product.nicotine, product.batterypack, product.tankvolumn, product.price, product.currency, product.caution)
insert_query = """insert into products (itemno, name, thumbnail, nicotine, batterypack, tankvolumn, price, currency, caution, stock)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
# imageBlob = utils.convert_to_blod_data(product.thumbnail)
data = (product.itemno, product.name, product.thumbnail, product.nicotine, product.batterypack,
product.tankvolumn, product.price, product.currency, product.caution, product.stock)
cursor.execute(insert_query, data)

print("inserted successfully")
print("inserted product successfully")

conn.commit()
cursor.close()
Expand Down Expand Up @@ -156,7 +159,9 @@ def get_product(id):
cursor.execute(select_query, (id,))
record = cursor.fetchone()

product = convert_to_product(record)
product = None
if record:
product = convert_to_product(record)

conn.commit()
cursor.close()
Expand All @@ -181,8 +186,10 @@ def get_ad():
cursor.execute(select_query)
record = cursor.fetchone()

ad = convert_to_ad(record)
print(f'len(ad):{ad.type}')
ad = None
if record:
ad = convert_to_ad(record)

conn.commit()
cursor.close()

Expand All @@ -206,7 +213,9 @@ def get_ad_row(id):
cursor.execute(select_query, (id,))
record = cursor.fetchone()

ad = convert_to_ad(record)
ad = None
if record:
ad = convert_to_ad(record)

conn.commit()
cursor.close()
Expand All @@ -223,29 +232,31 @@ def get_ad_row(id):


# get Ad
def get_machine(id):
def get_machines():
try:
conn = sqlite3.connect(utils.dbPath)
cursor = conn.cursor()

select_query = '''select * from machines where id = ?'''
cursor.execute(select_query, (id,))
record = cursor.fetchone()
select_query = '''select * from machines'''
cursor.execute(select_query)
record = cursor.fetchall()

machine = convert_to_machine(record)
machines = []
for item in record:
machine = convert_to_machine(item)
machines.append(machine)

conn.commit()
cursor.close()

except sqlite3.Error as error:
print('get_machine_fail', error)
machine = None
finally:
if conn:
conn.close()
print('connection is closed')

return machine
return machines

def get_product_count():
try:
Expand Down Expand Up @@ -307,9 +318,28 @@ def delete_ads():
conn.close()
print('connection is closed')

# delete Ads
def delete_products():
try:
conn = sqlite3.connect(utils.dbPath)
cursor = conn.cursor()

delete_query = '''delete from products'''
cursor.execute(delete_query)

conn.commit()
cursor.close()

except sqlite3.Error as error:
print('delete_products_fail', error)
finally:
if conn:
conn.close()
print('connection is closed')

def convert_to_product(record):
product = Product(record[0], record[1], record[2], record[3], record[4],
record[5], record[6], record[7], record[8], record[9])
record[5], record[6], record[7], record[8], record[9], record[10])

return product

Expand All @@ -318,6 +348,5 @@ def convert_to_ad(record):
return ad

def convert_to_machine(record):
machine = Machine(record[0], record[1], record[2], record[3])
machine = Machine(record[0], record[1], record[2], record[3], record[4])
return machine

6 changes: 4 additions & 2 deletions DbFuncs/db_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ def create_product_table_if_not_exists():
tankvolumn TEXT NOT NULL,
price REAL NOT NULL,
currency TEXT NOT NULL,
caution TEXT NOT NULL
caution TEXT NOT NULL,
stock INTEGER NOT NULL
)'''

# Create a users table
Expand Down Expand Up @@ -79,7 +80,8 @@ def create_machine_table_if_not_exists():
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
unit TEXT NOT NULL,
value TEXT NOT NULL
value TEXT NOT NULL,
thumbnail BLOB NOT NULL
)'''

# Create a users table
Expand Down
7 changes: 1 addition & 6 deletions DbFuncs/db_get_list_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ def insert_ads(ad):

insert_query = """insert into ads (type, content)
values (?, ?)"""

blodData = convert_to_blod_data(ad.content)
print(blodData)
data = (ad.type, (blodData))

cursor.execute(insert_query, data)
Expand All @@ -94,8 +94,3 @@ def insert_ads(ad):
conn.close()
print('connection is closed')
return False

# update_product(1, '../img/owl.jpg', 500)
ad = Ad(1, 'PPT', '../222.pptx')
insert_ads(ad)
# db.get_ad_row(31)
Binary file modified DbFuncs/sql.db
Binary file not shown.
9 changes: 5 additions & 4 deletions ad.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import base64
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.videoplayer import VideoPlayer
from kivy.uix.video import Video
from kivy.uix.image import Image
from pptx import Presentation
from config import utils
Expand All @@ -25,14 +26,14 @@ def __init__(self, **kwargs):
Clock.schedule_once(self.retrieve_layout)

def retrieve_layout(self, dt):
ad = db.get_ad_row(35)
ad = db.get_ad()
if ad:
if ad.type == 'MP4':
temp_file = './img/ad.mp4'
path = os.path.dirname(__file__)
temp_file = path + '/img/ad.mp4'
utils.write_to_file(ad.content, temp_file)

videoPlayerLayout = VideoPlayerLayout(temp_file)
print(f'self.manager{self.manager}')
videoPlayerLayout.manager = self.manager
videoPlayerLayout.bind(on_touch_up=videoPlayerLayout.on_video_touch_up)

Expand Down Expand Up @@ -96,7 +97,7 @@ def __init__(self, temp_file, **kwargs):
self.temp_file = temp_file

# Create a VideoPlayer widget
self.player = VideoPlayer(source=temp_file, state='play',
self.player = Video(source=temp_file, state='play',
options={'eos': 'loop'})

# Add the VideoPlayer widget to the BoxLayout
Expand Down
125 changes: 125 additions & 0 deletions api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# 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

hostName = 'https://212.224.86.112:8443'

# def create_connect():
# ws = create_connection("ws://echo.websocket.events/")
# print(ws.recv())
# print("Sending 'Hello, World'...")
# ws.send("Hello, World")
# print("Sent")
# print("Receiving...")
# result = ws.recv()
# print("Received '%s'" % result)
# ws.close()

async def connect_to_server():
ssl_context = ssl.create_default_context()
ssl_context.load_verify_locations(certifi.where())

async with websockets.connect('wss://212.224.86.112:8443', ssl = ssl_context) as websocket:
sendData = {'action': 'MachineConnect'}
await websocket.send(json.dumps(sendData))

# Receive data
response = await websocket.recv()
responseData = json.loads(response)

print(f"Received: {response}")
print(f"Received data: {responseData}")

if responseData['status']:
while True:
statusData = {
'action': "MachineSendStatus",
'payload': {
'serialno': "123-456-678",
'temparature': "XXX",
'token': responseData['token'],
}
}
await websocket.send(json.dumps(statusData))
statusResponse = await websocket.recv()
statusResponseData = json.loads(statusResponse)

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


async def connect_and_send():
async with websockets.connect('wss://example.com/ws') as websocket:
await websocket.send("Hello, server!")

# asyncio.get_event_loop().run_until_complete(connect_and_send())

def send_get_machine_info():
# delete machine table
db.delete_machines()

# Send an HTTP GET request to a URL of your choice
url = "/api/machine/get_machine_info"
response = requests.post(hostName + url, verify=False)

# Check the response status code
if response.status_code == 200:
responseData = response.json() # {status : , message : , details : [{},]}
machineData = responseData['details']
for item in machineData:
params = Machine(0, item['name'], item['unit'], item['value'], base64.b64decode(item['thumbnail']))
db.insert_machine(params)
else:
print(f"Request failed with status code: {response.status_code}")

def send_get_ads_info():
url = "/api/machine/get_ads_info"
db.delete_ads()
# Send an HTTP GET request to a URL of your choice
response = requests.post(hostName + url, verify=False)

# 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'))
params = Ad(0, adData['type'], base64.b64decode(adData['content']))
db.insert_ads(params)
else:
print(f"Request failed with status code: {response.status_code}")

def send_get_products_info():
url = "/api/machine/get_product_info"
# delete machine table
db.delete_products()

# Send an HTTP GET request to a URL of your choice
response = requests.post(hostName + url, verify=False)

# Check the response status code
if response.status_code == 200:
productData = response.json() # {status : , message : , details : [{},]}
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'])
db.insert_product(params)
else:
print(f"Request failed with status code: {response.status_code}")

def send_sell_product():
url = "api/machine/sell_product"


# send_get_machine_info()
# send_get_products_info()
# send_get_ads_info()
Loading

0 comments on commit 441259b

Please sign in to comment.