55 HubConnectionState ,
66 LogLevel ,
77} from '@microsoft/signalr' ;
8- import { browser , dev } from '$app/environment' ;
8+ import { dev } from '$app/environment' ;
99import { PUBLIC_BACKEND_API_DOMAIN } from '$env/static/public' ;
10- import { UserStore } from '$lib/stores/UserStore' ;
1110import { toast } from 'svelte-sonner' ;
1211import { type Readable , get , writable } from 'svelte/store' ;
1312import { handleSignalrDeviceState } from './handlers/DeviceStatus' ;
@@ -21,7 +20,7 @@ import {
2120const signalr_connection = writable < HubConnection | null > ( null ) ;
2221const signalr_state = writable < HubConnectionState > ( HubConnectionState . Disconnected ) ;
2322
24- async function create_signalr_connection ( ) {
23+ export async function initializeSignalR ( ) {
2524 let connection = get ( signalr_connection ) ;
2625 if ( connection ) {
2726 return ;
@@ -62,16 +61,30 @@ async function create_signalr_connection() {
6261
6362 signalr_connection . set ( connection ) ;
6463
65- await connection . start ( ) ;
64+ try {
65+ await connection . start ( ) ;
66+ signalr_state . set ( HubConnectionState . Connected ) ;
67+ } catch ( error ) {
68+ console . error ( error ) ;
69+ toast . error ( 'Failed to connect to server!' ) ;
70+ signalr_state . set ( HubConnectionState . Disconnected ) ;
71+ }
6672}
6773
68- function destroy_signalr_connection ( ) {
69- if ( signalr_connection ) {
74+ export async function destroySignalR ( ) {
75+ if ( ! signalr_connection ) return ;
76+
77+ try {
7078 const connection = get ( signalr_connection ) ;
7179 if ( connection ) {
72- connection . stop ( ) ;
73- signalr_connection . set ( null ) ;
80+ await connection . stop ( ) ;
7481 }
82+ } catch ( error ) {
83+ console . error ( error ) ;
84+ toast . error ( 'Encountered error while disconnecting from server!' ) ;
85+ } finally {
86+ signalr_connection . set ( null ) ;
87+ signalr_state . set ( HubConnectionState . Disconnected ) ;
7588 }
7689}
7790
@@ -82,23 +95,3 @@ export const SignalR_State = {
8295export const SignalR_Connection = {
8396 subscribe : signalr_connection . subscribe ,
8497} as Readable < HubConnection | null > ;
85-
86- export function initializeSignalR ( ) {
87- if ( ! browser ) return ;
88-
89- UserStore . subscribe ( ( { self } ) => {
90- if ( self === null ) {
91- destroy_signalr_connection ( ) ;
92- } else {
93- create_signalr_connection ( )
94- . then ( ( ) => {
95- signalr_state . set ( HubConnectionState . Connected ) ;
96- } )
97- . catch ( ( e ) => {
98- console . error ( e ) ;
99- toast . error ( 'Failed to connect to server!' ) ;
100- signalr_state . set ( HubConnectionState . Disconnected ) ;
101- } ) ;
102- }
103- } ) ;
104- }
0 commit comments