Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions src/grpc_json_server/generated/comms_pb2.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

65 changes: 54 additions & 11 deletions src/grpc_json_server/generated/comms_pb2_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
)


class NeuroEvolutionStub(object):
class CommunicationStub(object):
"""Missing associated documentation comment in .proto file."""

def __init__(self, channel):
Expand All @@ -35,13 +35,18 @@ def __init__(self, channel):
channel: A grpc.Channel.
"""
self.FetchEnvironmentStream = channel.unary_stream(
'/comms.NeuroEvolution/FetchEnvironmentStream',
'/comms.Communication/FetchEnvironmentStream',
request_serializer=comms__pb2.Command.SerializeToString,
response_deserializer=comms__pb2.Environment.FromString,
response_deserializer=comms__pb2.JSONData.FromString,
_registered_method=True)
self.FetchNeuralNet = channel.unary_unary(
'/comms.Communication/FetchNeuralNet',
request_serializer=comms__pb2.ID.SerializeToString,
response_deserializer=comms__pb2.JSONData.FromString,
_registered_method=True)


class NeuroEvolutionServicer(object):
class CommunicationServicer(object):
"""Missing associated documentation comment in .proto file."""

def FetchEnvironmentStream(self, request, context):
Expand All @@ -50,23 +55,34 @@ def FetchEnvironmentStream(self, request, context):
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')

def FetchNeuralNet(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')


def add_NeuroEvolutionServicer_to_server(servicer, server):
def add_CommunicationServicer_to_server(servicer, server):
rpc_method_handlers = {
'FetchEnvironmentStream': grpc.unary_stream_rpc_method_handler(
servicer.FetchEnvironmentStream,
request_deserializer=comms__pb2.Command.FromString,
response_serializer=comms__pb2.Environment.SerializeToString,
response_serializer=comms__pb2.JSONData.SerializeToString,
),
'FetchNeuralNet': grpc.unary_unary_rpc_method_handler(
servicer.FetchNeuralNet,
request_deserializer=comms__pb2.ID.FromString,
response_serializer=comms__pb2.JSONData.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'comms.NeuroEvolution', rpc_method_handlers)
'comms.Communication', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
server.add_registered_method_handlers('comms.NeuroEvolution', rpc_method_handlers)
server.add_registered_method_handlers('comms.Communication', rpc_method_handlers)


# This class is part of an EXPERIMENTAL API.
class NeuroEvolution(object):
class Communication(object):
"""Missing associated documentation comment in .proto file."""

@staticmethod
Expand All @@ -83,9 +99,36 @@ def FetchEnvironmentStream(request,
return grpc.experimental.unary_stream(
request,
target,
'/comms.NeuroEvolution/FetchEnvironmentStream',
'/comms.Communication/FetchEnvironmentStream',
comms__pb2.Command.SerializeToString,
comms__pb2.Environment.FromString,
comms__pb2.JSONData.FromString,
options,
channel_credentials,
insecure,
call_credentials,
compression,
wait_for_ready,
timeout,
metadata,
_registered_method=True)

@staticmethod
def FetchNeuralNet(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(
request,
target,
'/comms.Communication/FetchNeuralNet',
comms__pb2.ID.SerializeToString,
comms__pb2.JSONData.FromString,
options,
channel_credentials,
insecure,
Expand Down
4 changes: 2 additions & 2 deletions src/gui/WebClient/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub async fn getConnection()->Result<CommunicationClient<Channel>,tonic::transpo
Ok(())
}*/

pub async fn getSimStream(connection:CommunicationClient<Channel>,sender:Sender<JsonData>)->Result<(),Box<dyn std::error::Error>>{
pub async fn getSimStream(mut connection:CommunicationClient<Channel>,sender:Sender<JsonData>)->Result<(),Box<dyn std::error::Error>>{
let request = Request::new(Command{
r#in:"start".into(),
});
Expand All @@ -35,7 +35,7 @@ pub async fn getSimStream(connection:CommunicationClient<Channel>,sender:Sender<
Ok(())
}

pub async fn getNeuralNet(connection:&mut CommunicationClient<Channel>,agent:i32)->JsonData{
pub async fn getNeuralNet(mut connection: CommunicationClient<Channel>,agent:i32)->JsonData{
let request = Request::new(Id{r#id:agent,});
let netString = connection.fetch_neural_net(request).await.unwrap().into_inner();
netString
Expand Down
25 changes: 13 additions & 12 deletions src/gui/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@

use crate::WebClient::comms::communication_client::CommunicationClient;
use crate::WebClient::comms::JsonData;
use crate::WebClient::comms::JsonData;
use iced::Executor;
use tokio::runtime::Runtime;
use tonic::{Request, Status};
use iced::widget::canvas::{Canvas, Fill, Frame, Geometry, Path};
use iced::widget::{button, canvas, column, row, text, Column, Row};
use iced::Executor;
use iced::{mouse, Color, Length, Point, Rectangle, Renderer, Size, Subscription, Theme};
use tokio::runtime::Runtime;
use tokio::sync::mpsc;
use tokio::sync::mpsc::{Receiver, Sender};
use tonic::{Request, Status};
use WebClient::getConnection;
mod WebClient;
mod neural_net;
Expand All @@ -34,7 +33,7 @@ struct View {
simulation_data: SimulationData,
receiver: Option<Receiver<JsonData>>,
sender: Option<Sender<JsonData>>,
connection: Option<CommunicationClient<Channel>>
connection: Option<CommunicationClient<Channel>>,
}
#[derive(Default, Clone)]
struct SimulationView {
Expand Down Expand Up @@ -75,7 +74,6 @@ struct Agent {
struct SimulationData {
agents: Vec<Agent>,
shapes: Vec<Shape>,
layers: Vec<Layer>,
}

pub fn main() -> iced::Result {
Expand All @@ -99,7 +97,7 @@ impl View {
simulation_data: SimulationData::default(),
receiver: Some(recv),
sender: Some(send),
connection: Some(conn)
connection: Some(conn),
}
}
fn view(&self) -> Column<Message> {
Expand Down Expand Up @@ -152,8 +150,11 @@ impl View {
}
Message::SimStart => {
let rt = Runtime::new().unwrap();
let cloneConn = *self.connection.as_mut().unwrap().clone();
rt.spawn(async { WebClient::getSimStream(cloneConn, self.sender.unwrap()); });
let cloneConn = self.connection.as_mut().unwrap().clone();
let cloneSend = self.sender.as_mut().unwrap().clone();
rt.spawn(async move {
WebClient::getSimStream(cloneConn, cloneSend).await;
});
}
Message::SimPause => {}
Message::SimEnd => {}
Expand Down Expand Up @@ -297,16 +298,16 @@ impl View {
]
}
"#;*/

let received = &self.receiver.as_mut().unwrap().blocking_recv().unwrap().json_data;//should block until sim starts
let json_data: SimulationData =
serde_json::from_str(&self.receiver.as_mut().unwrap().recv().unwrap().json_data)
serde_json::from_str(&received)
.expect("Failed to parse JSON");
json_data
}
fn update_simulation_data(&mut self, simulation_data: SimulationData) {
self.simulation_data = simulation_data;
self.agent_view.color = Color::from_rgb(0.0, 1.0, 0.0);
self.nn_view.update_network(&self.simulation_data.layers);
//self.nn_view.update_network(&self.simulation_data.layers);
self.sim_view.update_sim(&self.simulation_data.shapes);
}
fn subscription(&self) -> Subscription<Message> {
Expand Down
5 changes: 5 additions & 0 deletions src/simulation/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,11 @@ def get_collisions(self):

return self.state.collisions

def getAgentRenderData(self):
return {"id":self.id,"x":self.pos[0],"y":self.pos[1],"color":"white"}



def solve_collision(self):
for collision in self.state.collisions[:]:
if collision.shape == "circle":
Expand Down
4 changes: 3 additions & 1 deletion src/simulation/enviroment.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,4 +287,6 @@ def run(self):
# Find the fittest predator and prey
# Find amount of food left
# self.view(real_time=True)
messageChannel.put()
sendData = {"agents":self.agents,"shapes":self.obstacles}
print(sendData)
#messageChannel.put(sendData)
7 changes: 5 additions & 2 deletions src/simulation/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@
import json
import time
import threading
from .generated import json_transfer_pb2, json_transfer_pb2_grpc
from .generated import comms_pb2
from .generated import comms_pb2_grpc
from messenger import messageChannel


class JsonTransferService(json_transfer_pb2_grpc.JsonTransferServicer):
class CommunicationService(comms_pb2_grpc.CommunicationServicer):
def FetchNeuralNet(slef,request,context):
print("here")
def FetchEnvironmentStream(self, request, context):
while messageChannel.empty == False:
data = messageChannel.get()
Expand Down
6 changes: 6 additions & 0 deletions src/simulation/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,9 @@ def __init__(self, shape, radius, width, height, pos):
self.width = width
self.height = height
self.pos = pos

def getRenderData(self):
if self.shape == "Circle":
return {"type":"Circle","x":self.pos[0],"y":self.pos[1],"radius":self.radius,"Color":"green"}
else:
return {"type":"Rectangle","x":self.pos[0],"y":self.pos[1],"witdth":self.width,"height":self.height,"Color":"red"}