upload NK server code

This commit is contained in:
Torma Kristóf 2020-07-13 19:42:06 +02:00
parent 2255b0fa39
commit 52db1f209e
5 changed files with 119 additions and 0 deletions

View File

@ -0,0 +1,21 @@
import websocket_server
import event_hub_listener
from multiprocessing import Process
def start_WS_server():
websocket_server.start_websocket_server()
def run_HUB_receiver():
event_hub_listener.start_event_hub_listener()
def runInParallel(*fns):
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()
if __name__ == '__main__':
runInParallel(start_WS_server, run_HUB_receiver)

View File

@ -0,0 +1,26 @@
from azure.iot.hub import IoTHubRegistryManager
from azure.iot.hub.models import CloudToDeviceMethod, CloudToDeviceMethodResult
CONNECTION_STRING = "HostName=AgriHub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=v0auIwbmqfBDz3BY8aZtbnOzg8+6119LWylk1Jq1G0A="
DEVICE_ID = "Guard_Node_00001"
METHOD_PAYLOAD = "server_to_device_message"
def send_to_device(request_name):
try:
# Create IoTHubRegistryManager
registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
# Call the direct method.
deviceMethod = CloudToDeviceMethod(method_name=request_name, payload=METHOD_PAYLOAD)
print ( "Device Method called" )
print ( "Device Method name : {0}".format(request_name) )
print ( "Device Method payload : {0}".format(METHOD_PAYLOAD) )
response = registry_manager.invoke_device_method(DEVICE_ID, deviceMethod)
print ( "Response status : {0}".format(response.status) )
print ( "Response payload : {0}".format(response.payload) )
except Exception as ex:
print ( "Unexpected error {0}".format(ex) )
return
except KeyboardInterrupt:
print ( "IoTHubDeviceMethod sample stopped" )

View File

@ -0,0 +1,34 @@
import logging
import json
import donwlink_message
import asyncio
from azure.eventhub import EventHubConsumerClient
connection_str = "Endpoint=sb://ihsuprodamres091dednamespace.servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=v0auIwbmqfBDz3BY8aZtbnOzg8+6119LWylk1Jq1G0A=;EntityPath=iothub-ehub-agrihub-3199035-0595c5c32a"
consumer_group = '$Default'
eventhub_name = 'iothub-ehub-agrihub-3199035-0595c5c32a'
client = EventHubConsumerClient.from_connection_string(connection_str, consumer_group, eventhub_name=eventhub_name)
logger = logging.getLogger("azure.eventhub")
logging.basicConfig(level=logging.INFO)
def background(f):
def wrapped(*args, **kwargs):
return asyncio.get_event_loop().run_in_executor(None, f, *args, *kwargs)
return wrapped
def on_event(partition_context, event):
#logger.info("Received event from partition {}".format(partition_context.partition_id))
#print("PartitionContext: ", partition_context)
partition_context.update_checkpoint(event)
#print(event)
print("JSON: -->",event.body_as_json(encoding='UTF-8'))
message_arrrived = event.body_as_json(encoding='UTF-8')
if message_arrrived["st"] > 5:
request_sample()
@background
def request_sample():
donwlink_message.send_to_device("RequestAudioSample")
def start_event_hub_listener():
client.receive( on_event=on_event, partition_id="0")

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,37 @@
import asyncio
import websockets
import cnn_classifier
import donwlink_message
import numpy as np
from scipy.io import wavfile
server_classifier=None
server_ip="192.168.1.71"
server_port=8765
model_struct = 'model_mukcso_batch256.json'
model_weights = "best_model_mukcso_batch256.h5"
def background(f):
def wrapped(*args, **kwargs):
return asyncio.get_event_loop().run_in_executor(None, f, *args, *kwargs)
return wrapped
async def service(websocket, path):
buf = await websocket.recv()
decoded = np.frombuffer(buf, dtype=np.int16)
print("Wav arrived!")
wavfile.write("arrived.wav", 44100, decoded.astype(np.int16))
await websocket.send("Wav arrived to Server.")
prediction=server_classifier.predict("arrived.wav")
if prediction[0] == 'sturnus':
alert()
@background
def alert():
donwlink_message.send_to_device("RequestAlert")
def start_websocket_server():
global server_classifier
server_classifier = cnn_classifier.classifier(model_struct,model_weights)
start_server = websockets.serve(service, server_ip, server_port)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()