Skip to content

Commit d6e054b

Browse files
committed
refactor: improve connection error handling and clean up unused code and comments
1 parent 9c9bbfc commit d6e054b

5 files changed

Lines changed: 105 additions & 105 deletions

File tree

cmd/main.go

Lines changed: 26 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,40 +4,37 @@ import (
44
"flag"
55
"fmt"
66
"log"
7-
"os"
8-
"os/signal"
9-
"syscall"
107
"time"
118

129
"github.com/kbhuyan/emu"
1310
)
1411

15-
func waitingToBeTerminate(device emu.Emu) {
16-
// Create a channel to receive signals.
17-
sigChan := make(chan os.Signal, 1)
18-
19-
// Notify the channel of specific signals.
20-
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
21-
22-
fmt.Println("Program is running. Press Ctrl+C to interrupt.")
23-
24-
// Block until a signal is received.
25-
sig := <-sigChan
26-
27-
// Handle the signal.
28-
switch sig {
29-
case syscall.SIGINT:
30-
fmt.Println("SIGINT received. Exiting...")
31-
device.Close()
32-
os.Exit(0)
33-
case syscall.SIGTERM:
34-
fmt.Println("SIGTERM received. Exiting...")
35-
device.Close()
36-
os.Exit(0)
37-
default:
38-
fmt.Println("Unexpected signal received.")
39-
}
40-
}
12+
// func waitingToBeTerminate(device emu.Emu) {
13+
// // Create a channel to receive signals.
14+
// sigChan := make(chan os.Signal, 1)
15+
16+
// // Notify the channel of specific signals.
17+
// signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
18+
19+
// fmt.Println("Program is running. Press Ctrl+C to interrupt.")
20+
21+
// // Block until a signal is received.
22+
// sig := <-sigChan
23+
24+
// // Handle the signal.
25+
// switch sig {
26+
// case syscall.SIGINT:
27+
// fmt.Println("SIGINT received. Exiting...")
28+
// device.Close()
29+
// os.Exit(0)
30+
// case syscall.SIGTERM:
31+
// fmt.Println("SIGTERM received. Exiting...")
32+
// device.Close()
33+
// os.Exit(0)
34+
// default:
35+
// fmt.Println("Unexpected signal received.")
36+
// }
37+
// }
4138

4239
func main() {
4340
// Configure command-line flags

config.go

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -173,21 +173,21 @@ var (
173173
GET_CONN_STATUS: emuGetConnStatus,
174174
}
175175

176-
cmdRspMap = map[emuCommandName]emuMessageName{
177-
emuRestart: emuAck,
178-
emuGetDeviceInfo: emuDeviceInfo,
179-
emuGetNetworkInfo: emuNetworkInfo,
180-
emuGetTime: emuTimeCluster,
181-
emuGetConnStatus: emuConnectionStatus,
182-
emuGetMessage: emuMessageCluster,
183-
emuGetFastPollStatus: emuFastPollStatus,
184-
emuGetCurrentSummationDelivered: emuCurrentSummationDelivered,
185-
emuGetInstantaneousDemand: emuInstantaneousDemand,
186-
emuGetLocalAttributes: emuAck,
187-
emuGetPriceBlocks: emuAck,
188-
emuGetSchedule: emuAck,
189-
emuGetProfileData: emuAck,
190-
}
176+
// cmdRspMap = map[emuCommandName]emuMessageName{
177+
// emuRestart: emuAck,
178+
// emuGetDeviceInfo: emuDeviceInfo,
179+
// emuGetNetworkInfo: emuNetworkInfo,
180+
// emuGetTime: emuTimeCluster,
181+
// emuGetConnStatus: emuConnectionStatus,
182+
// emuGetMessage: emuMessageCluster,
183+
// emuGetFastPollStatus: emuFastPollStatus,
184+
// emuGetCurrentSummationDelivered: emuCurrentSummationDelivered,
185+
// emuGetInstantaneousDemand: emuInstantaneousDemand,
186+
// emuGetLocalAttributes: emuAck,
187+
// emuGetPriceBlocks: emuAck,
188+
// emuGetSchedule: emuAck,
189+
// emuGetProfileData: emuAck,
190+
// }
191191

192192
attribTypeMap = map[emuMessageAttribute]atrribType{
193193
emuDeviceMacId: STRING,

emu.go

Lines changed: 44 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,10 @@ func (e *emuImpl) Close() {
196196
InfoLogger.Println("closing the emu session.")
197197
e.cancel()
198198
time.Sleep(closingGracePeriord)
199-
e.conn.Close()
199+
err := e.conn.Close()
200+
if err != nil {
201+
ErrorLogger.Printf("Close error: %v", err)
202+
}
200203
}
201204

202205
// func (e *emuImpl) GetCumulativeEnergyConsumption() (*CumulativeEnergyConsumption, error) {
@@ -250,7 +253,8 @@ func (e *emuImpl) reader() {
250253
break
251254
}
252255
rp.process(line)
253-
if rp.state == RspReceived {
256+
switch rp.state {
257+
case RspReceived:
254258
//For internal commands e.g. Demand and Contineous etc
255259
if e.cmdState != nil && e.cmdState.status == CmdSent {
256260
//check if response is for the command
@@ -275,7 +279,7 @@ func (e *emuImpl) reader() {
275279
WarningLogger.Printf("Ignoring, %s cannot be processed for API message", rp.resp.GetName())
276280
}
277281
rp = newResponseProcessor()
278-
} else if rp.state == RspError {
282+
case RspError:
279283
WarningLogger.Printf("Abandoning processing response: [%s, %+v]\n", rp.state, rp.resp)
280284
rp = newResponseProcessor()
281285
}
@@ -390,9 +394,9 @@ type commandState struct {
390394
command Command
391395
}
392396

393-
func newCommandState() *commandState {
394-
return &commandState{status: CmdUnknown}
395-
}
397+
// func newCommandState() *commandState {
398+
// return &commandState{status: CmdUnknown}
399+
// }
396400

397401
func newResponseProcessor() *responseProcessor {
398402
return &responseProcessor{state: RspPending, resp: &messageImpl{Attribs: make(map[emuMessageAttribute]any)}}
@@ -505,37 +509,37 @@ func (rp *responseProcessor) process(line string) {
505509
}
506510
}
507511

508-
func (rp *responseProcessor) processv2(line string) {
509-
//if state is RspReceiving then look for stopResponseTag and attributes
510-
//else ignore line as it start to receive in the middle of an response
511-
switch rp.state {
512-
case RspPending:
513-
if tag, ok := rp.startResponseTag(line); ok {
514-
rp.state = RspReceiving
515-
rp.resp.Name = tag
516-
} else {
517-
WarningLogger.Printf("starting to receive in the middle of the message, ignoring. line: %s", line)
518-
}
519-
case RspReceiving:
520-
if tag, ok := rp.stopResponseTag(line); ok {
521-
if rp.resp.Name == tag {
522-
rp.state = RspReceived
523-
} else {
524-
WarningLogger.Printf("invalid end of response %s received. expecting[%s, %+v]. line: %s", tag, rp.resp.GetName(), rp.state, line)
525-
rp.state = RspError
526-
}
527-
} else {
528-
//parse xml element from the line with <key>vale</key>
529-
//add key and value to the response Attribs[key] = value
530-
key, value, err := rp.getAttrib(line)
531-
if err != nil {
532-
WarningLogger.Printf("abandoning message %s as xml parse error:%v while processing. line: %s", rp.resp.GetName(), err, line)
533-
rp.state = RspError
534-
} else {
535-
rp.resp.Attribs[key] = value
536-
}
537-
}
538-
default:
539-
ErrorLogger.Printf("invalid response state %+v to receive. line: %s", rp.state, line)
540-
}
541-
}
512+
// func (rp *responseProcessor) processv2(line string) {
513+
// //if state is RspReceiving then look for stopResponseTag and attributes
514+
// //else ignore line as it start to receive in the middle of an response
515+
// switch rp.state {
516+
// case RspPending:
517+
// if tag, ok := rp.startResponseTag(line); ok {
518+
// rp.state = RspReceiving
519+
// rp.resp.Name = tag
520+
// } else {
521+
// WarningLogger.Printf("starting to receive in the middle of the message, ignoring. line: %s", line)
522+
// }
523+
// case RspReceiving:
524+
// if tag, ok := rp.stopResponseTag(line); ok {
525+
// if rp.resp.Name == tag {
526+
// rp.state = RspReceived
527+
// } else {
528+
// WarningLogger.Printf("invalid end of response %s received. expecting[%s, %+v]. line: %s", tag, rp.resp.GetName(), rp.state, line)
529+
// rp.state = RspError
530+
// }
531+
// } else {
532+
// //parse xml element from the line with <key>vale</key>
533+
// //add key and value to the response Attribs[key] = value
534+
// key, value, err := rp.getAttrib(line)
535+
// if err != nil {
536+
// WarningLogger.Printf("abandoning message %s as xml parse error:%v while processing. line: %s", rp.resp.GetName(), err, line)
537+
// rp.state = RspError
538+
// } else {
539+
// rp.resp.Attribs[key] = value
540+
// }
541+
// }
542+
// default:
543+
// ErrorLogger.Printf("invalid response state %+v to receive. line: %s", rp.state, line)
544+
// }
545+
// }

logger.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,16 @@ func init() {
1818
initLog(logFile, LOG_ERROR)
1919
}
2020

21-
func enableLogger(l *log.Logger) {
22-
l.SetOutput(logFile)
23-
}
24-
func disableLogger(l *log.Logger) {
25-
l.SetOutput(io.Discard)
26-
}
21+
// func enableLogger(l *log.Logger) {
22+
// l.SetOutput(logFile)
23+
// }
24+
// func disableLogger(l *log.Logger) {
25+
// l.SetOutput(io.Discard)
26+
// }
2727

2828
func initLog(file io.Writer, l LogLevel) {
2929
logFile = file
30-
var debugFile, infoFile, warningFile, errorFile io.Writer = io.Discard, io.Discard, io.Discard, io.Discard
30+
var debugFile, infoFile, warningFile, errorFile = io.Discard, io.Discard, io.Discard, io.Discard
3131
switch l {
3232
case LOG_ALL:
3333
debugFile, infoFile, warningFile, errorFile = file, file, file, file

util.go

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package emu
33
import (
44
"fmt"
55
"math"
6-
"reflect"
76
"time"
87
)
98

@@ -97,17 +96,17 @@ func getCorrectTimeStamp(ts int64) int64 {
9796
return time.Unix(ts, 0).AddDate(30, 0, -1).Unix()
9897
}
9998

100-
func structToMap(obj interface{}) map[string]interface{} {
101-
out := make(map[string]interface{})
102-
val := reflect.ValueOf(obj)
103-
if val.Kind() == reflect.Ptr {
104-
val = val.Elem()
105-
}
99+
// func structToMap(obj interface{}) map[string]interface{} {
100+
// out := make(map[string]interface{})
101+
// val := reflect.ValueOf(obj)
102+
// if val.Kind() == reflect.Ptr {
103+
// val = val.Elem()
104+
// }
106105

107-
for i := 0; i < val.NumField(); i++ {
108-
field := val.Type().Field(i)
109-
fieldValue := val.Field(i).Interface()
110-
out[field.Name] = fieldValue
111-
}
112-
return out
113-
}
106+
// for i := 0; i < val.NumField(); i++ {
107+
// field := val.Type().Field(i)
108+
// fieldValue := val.Field(i).Interface()
109+
// out[field.Name] = fieldValue
110+
// }
111+
// return out
112+
// }

0 commit comments

Comments
 (0)