current state

This commit is contained in:
Askill 2022-06-12 17:05:04 +02:00
parent b642014c8b
commit 29e361591f
4 changed files with 52 additions and 13 deletions

3
.gitignore vendored
View File

@ -133,3 +133,6 @@ dmypy.json
.pyre/
go/state.json
python/logo.png
python/images/2.jpg
python/images/1.jpg
.vscode/launch.json

View File

@ -33,7 +33,23 @@ export default {
"#CF6EE4",
"#820080"
]
async function load() {
let url = 'http://localhost:8080/getAll';
let obj = null;
try {
obj = await (await fetch(url)).json();
} catch(e) {
console.log('error');
}
return obj
}
for(const pixel in load() ){
ctx.fillStyle = colorpalettte[parseInt(pixel["color"])];
ctx.fillRect(pixel["y"], pixel["x"], 1, 1);
}
wsConnection.onopen = (e) => {
console.log(`wsConnection open`, e);
};

View File

@ -9,6 +9,7 @@ import (
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/gorilla/websocket"
@ -79,12 +80,26 @@ func get(w http.ResponseWriter, r *http.Request) {
copy(tmpImage.Pixels, img.Pixels)
}
}
func enableCors(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
}
func getAll(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(img)
}
func sendPing(ticker *time.Ticker, c *websocket.Conn, mutex *sync.Mutex) {
for range ticker.C {
mutex.Lock()
defer mutex.Unlock()
if err := c.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
fmt.Println("Error while sending ping")
return
}
}
}
func set(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
@ -94,8 +109,14 @@ func set(w http.ResponseWriter, r *http.Request) {
c.SetReadLimit(maxMessageSize)
c.SetPongHandler(func(string) error { c.SetReadDeadline(time.Now().Add(pongWait)); return nil })
ticker := time.NewTicker(pingPeriod / 2)
defer c.Close()
defer ticker.Stop()
mutex := sync.Mutex{}
go sendPing(ticker, c, &mutex)
for {
mt, msg, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
@ -108,7 +129,10 @@ func set(w http.ResponseWriter, r *http.Request) {
json.Unmarshal(msg, &message)
status := img.SetPixel(message)
mutex.Lock()
err = c.WriteMessage(1, []byte(strconv.Itoa(status)))
mutex.Unlock()
}
}

View File

@ -59,7 +59,8 @@ def closest_match(rgb, color_map):
return min(range(len(rgb_colors)), key=lambda i: eucleadian_distance(rgb, color_map[i]))
async def sender(img):
async with websockets.connect("ws://localhost:8080/set") as websocket:
async with websockets.connect("ws://localhost:8080/set", timeout=600) as websocket:
while True:
rx = random.randint(0, 999)
ry = random.randint(0, 999)
@ -72,7 +73,7 @@ async def sender(img):
)
await websocket.send(json.dumps(message.__dict__))
succ = await websocket.recv()
if succ == "1":
if succ != "0":
print(message, "was not set")
@ -85,24 +86,19 @@ async def client():
i+=1
x = pixel(**json.loads(await websocket.recv()))
image[x.x][x.y] = rgb_colors[x.color]
#if i% 5000 == 0:
# cv2.imshow("changes x", image)
# cv2.waitKey(10) & 0XFF
await websocket.send("1")
#print(i, x)
async def main():
img= Image.open('./2.jpg')
img= Image.open('./python/images/2.jpg')
img= img.resize((1000, 1000), Image.ANTIALIAS)
img = np.array(img)
coros = [sender(img) for _ in range(100)]
coros.append(client())
returns = await asyncio.gather(*coros)
_ = await asyncio.gather(*coros)
def asyncMain(x):
asyncio.get_event_loop().run_until_complete(main())
if __name__ == "__main__":
with Pool(12) as p:
print(p.map(asyncMain, [() for _ in range(12)]))
#asyncMain(0)
#with Pool(12) as p:
# print(p.map(asyncMain, [() for _ in range(12)]))
asyncMain(0)