Best K6 code snippet using ws.On
ws.go
Source:ws.go
...116 return fmt.Errorf("address cannot empty")117 }118 this.addr = address119 ws := utils.NewWebSocketClient()120 ws.OnMessage = this.onMessage121 ws.OnError = this.GetOnError()122 ws.OnConnect = this.GetOnConnect()123 ws.OnClose = this.GetOnClose()124 err := ws.Connect(address)125 if err != nil {126 return err127 }128 this.setWsClient(ws)129 return nil130}131func (this *WSClient) GetDefaultReqTimeout() time.Duration {132 this.lock.RLock()133 defer this.lock.RUnlock()134 return this.defReqTimeout135}136func (this *WSClient) SetDefaultReqTimeout(timeout time.Duration) {137 this.lock.Lock()138 defer this.lock.Unlock()139 this.defReqTimeout = timeout140}141func (this *WSClient) GetHeartbeatInterval() int {142 this.lock.RLock()143 defer this.lock.RUnlock()144 return this.heartbeatInterval145}146func (this *WSClient) SetHeartbeatInterval(interval int) {147 this.lock.Lock()148 defer this.lock.Unlock()149 this.heartbeatInterval = interval150}151func (this *WSClient) GetHeartbeatTimeout() int {152 this.lock.RLock()153 defer this.lock.RUnlock()154 return this.heartbeatTimeout155}156func (this *WSClient) SetHeartbeatTimeout(timeout int) {157 this.lock.Lock()158 defer this.lock.Unlock()159 this.heartbeatTimeout = timeout160}161func (this *WSClient) updateLastHeartbeatTime() {162 this.lock.Lock()163 defer this.lock.Unlock()164 this.lastHeartbeatTime = time.Now()165}166func (this *WSClient) getLastHeartbeatTime() time.Time {167 this.lock.RLock()168 defer this.lock.RUnlock()169 return this.lastHeartbeatTime170}171func (this *WSClient) updateLastRecvTime() {172 this.lock.Lock()173 defer this.lock.Unlock()174 this.lastRecvTime = time.Now()175}176func (this *WSClient) getLastRecvTime() time.Time {177 this.lock.RLock()178 defer this.lock.RUnlock()179 return this.lastRecvTime180}181func (this *WSClient) GetOnConnect() func(address string) {182 this.lock.RLock()183 defer this.lock.RUnlock()184 if this.onConnect != nil {185 return this.onConnect186 }187 return this.onDefConnect188}189func (this *WSClient) SetOnConnect(f func(address string)) {190 this.lock.Lock()191 defer this.lock.Unlock()192 this.onConnect = f193 ws := this.getWsClient()194 if ws != nil {195 ws.OnConnect = f196 }197}198func (this *WSClient) GetOnClose() func(address string) {199 this.lock.RLock()200 defer this.lock.RUnlock()201 if this.onClose != nil {202 return this.onClose203 }204 return this.onDefClose205}206func (this *WSClient) SetOnClose(f func(address string)) {207 this.lock.Lock()208 defer this.lock.Unlock()209 this.onClose = f210 ws := this.getWsClient()211 if ws != nil {212 ws.OnClose = f213 }214}215func (this *WSClient) GetOnError() func(address string, er error) {216 this.lock.RLock()217 defer this.lock.RUnlock()218 if this.onError != nil {219 return this.onError220 }221 return this.onDefError222}223func (this *WSClient) SetOnError(f func(address string, err error)) {224 this.lock.Lock()225 defer this.lock.Unlock()226 this.onError = f227 ws := this.getWsClient()228 if ws != nil {229 ws.OnError = f230 }231}232func (this *WSClient) onMessage(data []byte) {233 this.updateLastHeartbeatTime()234 this.updateLastRecvTime()235 select {236 case this.recvCh <- data:237 case <-this.exitCh:238 return239 }240}241func (this *WSClient) onDefError(address string, err error) {242 fmt.Printf("WSClient OnError address:%s error:%s\n", address, err)243}244func (this *WSClient) onDefConnect(address string) {245 fmt.Printf("WSClient OnConnect address:%s connect success\n", address)246}247func (this *WSClient) onDefClose(address string) {248 fmt.Printf("WSClient OnClose address:%s close success\n", address)249}250func (this *WSClient) start() {251 heartbeatTimer := time.NewTicker(time.Second)252 defer heartbeatTimer.Stop()253 for {254 select {255 case <-this.exitCh:256 return257 case data := <-this.recvCh:258 wsResp := &WSResponse{}259 err := json.Unmarshal(data, wsResp)260 if err != nil {261 this.GetOnError()(this.addr, fmt.Errorf("json.Unmarshal WSResponse error:%s", err))262 } else {263 go this.onAction(wsResp)264 }265 case <-heartbeatTimer.C:266 now := time.Now()267 if int(now.Sub(this.getLastRecvTime()).Seconds()) >= this.GetHeartbeatTimeout() {268 go this.reconnect()269 this.updateLastRecvTime()270 } else if int(now.Sub(this.getLastHeartbeatTime()).Seconds()) >= this.GetHeartbeatInterval() {271 go this.sendHeartbeat()272 this.updateLastHeartbeatTime()273 }274 }275 }276}277func (this *WSClient) reconnect() {278 ws := this.getWsClient()279 if ws != nil {280 this.setWsClient(nil)281 err := ws.Close()282 if err != nil {283 this.GetOnError()(this.addr, fmt.Errorf("close error:%s", err))284 }285 ws.OnMessage = nil286 }287 err := this.Connect(this.addr)288 if err != nil {289 this.GetOnError()(this.addr, fmt.Errorf("connect error:%s", err))290 return291 }292 err = this.reSubscribe()293 if err != nil {294 this.GetOnError()(this.addr, fmt.Errorf("reSubscribe:%v error:%s", this.subStatus, err))295 }296}297func (this *WSClient) onAction(resp *WSResponse) {298 if resp.Id == "" {299 switch resp.Action {300 case WS_SUB_ACTION_RAW_BLOCK:301 this.onRawBlockAction(resp)302 case WS_SUB_ACTION_BLOCK_TX_HASH:303 this.onBlockTxHashesAction(resp)304 case WS_SUB_ACTION_NOTIFY:305 this.onSmartContractEventAction(resp)306 case WS_SUB_ACTION_LOG:307 this.onSmartContractEventLogAction(resp)308 default:309 this.GetOnError()(this.addr, fmt.Errorf("unknown subscribe action:%s", resp.Action))310 }311 return312 }313 req := this.getReq(resp.Id)314 if req == nil {315 return316 }317 select {318 case req.ResCh <- resp:319 case <-this.exitCh:320 return321 }322 this.delReq(resp.Id)323}324func (this *WSClient) onRawBlockAction(resp *WSResponse) {325 block, err := utils.GetBlock(resp.Result)326 if err != nil {327 this.GetOnError()(this.addr, fmt.Errorf("onRawBlockAction error:%s", err))328 return329 }330 select {331 case this.actionCh <- &WSAction{332 Action: sdkcom.WS_SUBSCRIBE_ACTION_BLOCK,333 Result: block,334 }:335 case <-this.exitCh:336 return337 }338}339func (this *WSClient) onBlockTxHashesAction(resp *WSResponse) {340 blockTxHashes, err := utils.GetBlockTxHashes(resp.Result)341 if err != nil {342 this.GetOnError()(this.addr, fmt.Errorf("onBlockTxHashesAction error:%s", err))343 return344 }345 select {346 case this.actionCh <- &WSAction{347 Action: sdkcom.WS_SUBSCRIBE_ACTION_BLOCK_TX_HASH,348 Result: blockTxHashes,349 }:350 case <-this.exitCh:351 return352 }353}354func (this *WSClient) onSmartContractEventAction(resp *WSResponse) {355 event, err := utils.GetSmartContractEvent(resp.Result)356 if err != nil {357 this.GetOnError()(this.addr, fmt.Errorf("onSmartContractEventAction error:%s", err))358 return359 }360 select {361 case this.actionCh <- &WSAction{362 Action: sdkcom.WS_SUBSCRIBE_ACTION_EVENT_NOTIFY,363 Result: event,364 }:365 case <-this.exitCh:366 return367 }368}369func (this *WSClient) onSmartContractEventLogAction(resp *WSResponse) {370 log, err := utils.GetSmartContractEventLog(resp.Result)371 if err != nil {372 this.GetOnError()(this.addr, fmt.Errorf("onSmartContractEventLogAction error:%s", err))373 return374 }375 select {376 case this.actionCh <- &WSAction{377 Action: sdkcom.WS_SUBSCRIBE_ACTION_EVENT_LOG,378 Result: log,379 }:380 case <-this.exitCh:381 return382 }383}384func (this *WSClient) AddContractFilter(contractAddress string) error {385 if this.subStatus.HasContractFilter(contractAddress) {386 return nil...
web_socket_op.go
Source:web_socket_op.go
1package ws2import (3 "container/list"4 "encoding/json"5 "fmt"6 "reflect"7 "strings"8 "time"9 "github.com/gorilla/websocket"10 "github.com/gostudys/huobi_uclient_golang/sdk/linearswap"11 "github.com/gostudys/huobi_uclient_golang/sdk/log"12 "github.com/gostudys/huobi_uclient_golang/sdk/reqbuilder"13 "github.com/gostudys/huobi_uclient_golang/sdk/wsbase"14)15type MethonInfo struct {16 fun interface{}17 param reflect.Type18}19func (wsOp *MethonInfo) Init(fun interface{}, param reflect.Type) *MethonInfo {20 wsOp.fun = fun21 wsOp.param = param22 return wsOp23}24type WebSocketOp struct {25 host string26 path string27 conn *websocket.Conn28 accessKey string29 secretKey string30 autoConnect bool31 allSubStrs list.List32 onSubCallbackFuns map[string]*MethonInfo33 onReqCallbackFuns map[string]*MethonInfo34 authOk bool35}36func (wsOp *WebSocketOp) open(path string, host string, accessKey string, secretKey string, autoConnect bool) bool {37 if host == "" {38 wsOp.host = linearswap.LINEAR_SWAP_DEFAULT_HOST39 }40 wsOp.host = host41 wsOp.path = path42 wsOp.accessKey = accessKey43 wsOp.secretKey = secretKey44 wsOp.autoConnect = autoConnect45 ret := wsOp.connServer()46 if ret {47 wsOp.allSubStrs = list.List{}48 wsOp.onSubCallbackFuns = make(map[string]*MethonInfo)49 wsOp.onReqCallbackFuns = make(map[string]*MethonInfo)50 }51 return ret52}53func (wsOp *WebSocketOp) close() {54 wsOp.conn.Close()55 wsOp.conn = nil56}57func (wsOp *WebSocketOp) connServer() bool {58 url := fmt.Sprintf("wss://%s%s", wsOp.host, wsOp.path)59 var err error60 wsOp.conn, _, err = websocket.DefaultDialer.Dial(url, nil)61 if err != nil {62 log.Error("WebSocket connected error: %s", err)63 return false64 }65 log.Info("WebSocket connected")66 wsOp.conn.SetCloseHandler(wsOp.onClose)67 go wsOp.readLoop(wsOp.conn)68 if wsOp.accessKey == "" && wsOp.secretKey == "" {69 wsOp.authOk = true70 return true71 }72 wsOp.authOk = false73 return wsOp.sendAuth(wsOp.conn, wsOp.host, wsOp.path, wsOp.accessKey, wsOp.secretKey)74}75func (wsOp *WebSocketOp) onClose(code int, text string) error {76 log.Info("WebSocket close.")77 wsOp.conn = nil78 if wsOp.autoConnect {79 if !wsOp.connServer() {80 return fmt.Errorf("reconnect server error")81 }82 }83 return fmt.Errorf("")84}85func (wsOp *WebSocketOp) sendAuth(conn *websocket.Conn, host string, path string, accessKey string, secretKey string) bool {86 if conn == nil {87 log.Error("websocket conn is null")88 return false89 }90 timestamp := time.Now().UTC().Format("2006-01-02T15:04:05")91 req := new(reqbuilder.GetRequest).Init()92 req.AddParam("AccessKeyId", accessKey)93 req.AddParam("SignatureMethod", "HmacSHA256")94 req.AddParam("SignatureVersion", "2")95 req.AddParam("Timestamp", timestamp)96 sign := new(reqbuilder.Signer).Init(secretKey)97 signature := sign.Sign("GET", host, path, req.BuildParams())98 auth := wsbase.WSAuthData{99 Op: "auth",100 AtType: "api",101 AccessKeyId: accessKey,102 SignatureMethod: "HmacSHA256",103 SignatureVersion: "2",104 Timestamp: timestamp,105 Signature: signature}106 jdata, error := json.Marshal(&auth)107 if error != nil {108 log.Error("Auth to json error.")109 return false110 }111 conn.WriteMessage(websocket.TextMessage, jdata)112 return true113}114func (wsOp *WebSocketOp) readLoop(conn *websocket.Conn) {115 for conn != nil {116 msgType, buf, err := conn.ReadMessage()117 if err != nil {118 log.Error("Read error: %s", err)119 wsOp.close()120 break121 }122 var message string123 if msgType == websocket.BinaryMessage {124 message, err = wsbase.GZipDecompress(buf)125 if err != nil {126 log.Error("UnGZip data error: %s", err)127 continue128 }129 } else if msgType == websocket.TextMessage {130 message = string(buf)131 }132 var jdata map[string]interface{}133 err = json.Unmarshal([]byte(message), &jdata)134 if err != nil {135 log.Error("msg to map[string]json.RawMessage error: %s", err)136 continue137 }138 if ts, found := jdata["ping"]; found { // market heartbeat139 ts = int64(ts.(float64))140 //log.Info("WebSocket received data: \"ping\":%d", ts)141 pongData := fmt.Sprintf("{\"pong\":%d }", ts)142 wsOp.conn.WriteMessage(websocket.TextMessage, []byte(pongData))143 //log.Info("WebSocket replied data: %s", pongData)144 } else if op, found := jdata["op"]; found {145 switch op {146 case "ping": // order heartbeat147 ts := jdata["ts"]148 //log.Info("WebSocket received data, { \"op\":\"%s\", \"ts\": \"%s\" }", op, ts)149 pongData := fmt.Sprintf("{ \"op\":\"pong\", \"ts\": \"%s\" }", ts)150 wsOp.conn.WriteMessage(websocket.TextMessage, []byte(pongData))151 //log.Info("WebSocket replied data, %s", pongData)152 case "close":153 log.Error("Some error occurres when authentication in server side.")154 case "error":155 log.Error("Illegal op or internal error, but websoket is still connected.")156 case "auth":157 code := int64(jdata["err-code"].(float64))158 if code == 0 {159 log.Info("Authentication success.")160 wsOp.authOk = true161 for e := wsOp.allSubStrs.Front(); e != nil; e = e.Next() {162 wsOp.conn.WriteMessage(websocket.TextMessage, []byte(e.Value.(string)))163 }164 } else {165 msg := jdata["err-msg"].(string)166 log.Error("Authentication failure: %d/%s", code, msg)167 wsOp.close()168 }169 case "notify":170 topic := jdata["topic"].(string)171 wsOp.handleSubCallbackFun(topic, message, jdata)172 case "sub":173 topic := jdata["topic"]174 log.Info("sub: \"%s\"", topic)175 case "unsub":176 topic := jdata["topic"].(string)177 log.Info("unsub: \"%s\"", topic)178 if _, found := wsOp.onSubCallbackFuns[topic]; found {179 delete(wsOp.onSubCallbackFuns, topic)180 }181 default:182 log.Info("WebSocket received unknow data: %s", jdata)183 }184 } else if topic, found := jdata["subbed"]; found { // sub success reply185 log.Info("\"subbed\": \"%s\"", topic)186 } else if topic, found := jdata["unsubbed"]; found { // unsub success reply187 log.Info("\"unsubbed\": \"%s\"", topic)188 if _, found := wsOp.onSubCallbackFuns[topic.(string)]; found {189 delete(wsOp.onSubCallbackFuns, topic.(string))190 }191 } else if topic, found := jdata["ch"]; found { // market sub reply data192 wsOp.handleSubCallbackFun(topic.(string), message, jdata)193 } else if topic, found := jdata["rep"]; found { // market request reply data194 wsOp.handleReqCallbackFun(topic.(string), message, jdata)195 } else if code, found := jdata["err-code"]; found { // market request reply data196 code = code197 msg := jdata["err-msg"]198 log.Error("%d:%s", code, msg)199 } else {200 log.Info("WebSocket received unknow data: %s", jdata)201 }202 }203}204func (wsOp *WebSocketOp) handleSubCallbackFun(ch string, data string, jdata map[string]interface{}) {205 var mi *MethonInfo = nil206 ch = strings.ToLower(ch)207 if _, found := wsOp.onSubCallbackFuns[ch]; found {208 mi = wsOp.onSubCallbackFuns[ch]209 } else if ch == "accounts" || ch == "positions" { // isolated210 data_array := jdata["data"].([]interface{})211 contract_code := data_array[0].(map[string]interface{})["contract_code"].(string)212 contract_code = strings.ToLower(contract_code)213 full_ch := fmt.Sprintf("%s.%s", ch, contract_code)214 if _, found := wsOp.onSubCallbackFuns[full_ch]; found {215 mi = wsOp.onSubCallbackFuns[full_ch]216 } else if _, found := wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]; found {217 mi = wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]218 }219 } else if strings.HasPrefix(ch, "orders.") {220 if _, found := wsOp.onSubCallbackFuns["orders.*"]; found {221 mi = wsOp.onSubCallbackFuns["orders.*"]222 }223 } else if strings.HasPrefix(ch, "matchorders.") {224 if _, found := wsOp.onSubCallbackFuns["matchorders.*"]; found {225 mi = wsOp.onSubCallbackFuns["matchorders.*"]226 }227 } else if strings.HasPrefix(ch, "trigger_order.") {228 if _, found := wsOp.onSubCallbackFuns["trigger_order.*"]; found {229 mi = wsOp.onSubCallbackFuns["trigger_order.*"]230 }231 } else if ch == "accounts_cross" { // isolated232 data_array := jdata["data"].([]interface{})233 margin_account := data_array[0].(map[string]interface{})["margin_account"].(string)234 margin_account = strings.ToLower(margin_account)235 full_ch := fmt.Sprintf("%s.%s", ch, margin_account)236 if _, found := wsOp.onSubCallbackFuns[full_ch]; found {237 mi = wsOp.onSubCallbackFuns[full_ch]238 } else if _, found := wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]; found {239 mi = wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]240 }241 } else if ch == "positions_cross" {242 data_array := jdata["data"].([]interface{})243 contract_code := data_array[0].(map[string]interface{})["contract_code"].(string)244 contract_code = strings.ToLower(contract_code)245 full_ch := fmt.Sprintf("%s.%s", ch, contract_code)246 if _, found := wsOp.onSubCallbackFuns[full_ch]; found {247 mi = wsOp.onSubCallbackFuns[full_ch]248 } else if _, found := wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]; found {249 mi = wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]250 }251 } else if strings.HasPrefix(ch, "orders_cross.") {252 if _, found := wsOp.onSubCallbackFuns["orders_cross.*"]; found {253 mi = wsOp.onSubCallbackFuns["orders_cross.*"]254 }255 } else if strings.HasPrefix(ch, "matchorders_cross.") {256 if _, found := wsOp.onSubCallbackFuns["matchorders_cross.*"]; found {257 mi = wsOp.onSubCallbackFuns["matchorders_cross.*"]258 }259 } else if strings.HasPrefix(ch, "trigger_order_cross.") {260 if _, found := wsOp.onSubCallbackFuns["trigger_order_cross.*"]; found {261 mi = wsOp.onSubCallbackFuns["trigger_order_cross.*"]262 }263 } else if strings.HasSuffix(ch, ".liquidation_orders") { // General264 if _, found := wsOp.onSubCallbackFuns["public.*.liquidation_orders"]; found {265 mi = wsOp.onSubCallbackFuns["public.*.liquidation_orders"]266 }267 } else if strings.HasSuffix(ch, ".funding_rate") {268 if _, found := wsOp.onSubCallbackFuns["public.*.funding_rate"]; found {269 mi = wsOp.onSubCallbackFuns["public.*.funding_rate"]270 }271 } else if strings.HasSuffix(ch, ".contract_info") {272 if _, found := wsOp.onSubCallbackFuns["public.*.contract_info"]; found {273 mi = wsOp.onSubCallbackFuns["public.*.contract_info"]274 }275 }276 if mi == nil {277 log.Error("no callback function to handle: %s", jdata)278 return279 }280 wsOp.runFunction(mi, data)281}282func (wsOp *WebSocketOp) handleReqCallbackFun(ch string, data string, jdata map[string]interface{}) {283 var mi *MethonInfo = nil284 var found = false285 ch = strings.ToLower(ch)286 if mi, found = wsOp.onReqCallbackFuns[ch]; !found {287 log.Error("no callback function to handle: %s", jdata)288 return289 }290 if mi == nil {291 log.Error("no callback function to handle: %s", jdata)292 return293 }294 wsOp.runFunction(mi, data)295}296func (wsOp *WebSocketOp) runFunction(mi *MethonInfo, data string) {297 param := reflect.New(mi.param).Interface()298 json.Unmarshal([]byte(data), ¶m)299 rargs := make([]reflect.Value, 1)300 rargs[0] = reflect.ValueOf(param)301 fun := reflect.ValueOf(mi.fun)302 fun.Call(rargs)303}304func (wsOp *WebSocketOp) sub(subStr []byte, ch string, fun interface{}, param reflect.Type) bool {305 for !wsOp.authOk {306 time.Sleep(10)307 }308 ch = strings.ToLower(ch)309 var mi *MethonInfo = nil310 var found bool311 if mi, found = wsOp.onSubCallbackFuns[ch]; found {312 mi = new(MethonInfo).Init(fun, param)313 wsOp.onSubCallbackFuns[ch] = mi314 return true315 }316 wsOp.conn.WriteMessage(websocket.TextMessage, subStr)317 log.Info("websocket has send data: %s", subStr)318 wsOp.allSubStrs.PushBack(string(subStr))319 mi = new(MethonInfo).Init(fun, param)320 wsOp.onSubCallbackFuns[ch] = mi321 return true322}323func (wsOp *WebSocketOp) unsub(unsubStr []byte, ch string) bool {324 for !wsOp.authOk {325 time.Sleep(10)326 }327 ch = strings.ToLower(ch)328 if _, found := wsOp.onSubCallbackFuns[ch]; !found {329 return true330 }331 wsOp.conn.WriteMessage(websocket.TextMessage, unsubStr)332 log.Info("websocket has send data: %s", unsubStr)333 var next *list.Element334 for e := wsOp.allSubStrs.Front(); e != nil; e = next {335 next = e.Next()336 val := e.Value.(string)337 if val == string(unsubStr) {338 wsOp.allSubStrs.Remove(e)339 }340 }341 return true342}343func (wsOp *WebSocketOp) req(subStr []byte, ch string, fun interface{}, param reflect.Type) bool {344 for !wsOp.authOk {345 time.Sleep(10)346 }347 ch = strings.ToLower(ch)348 var mi *MethonInfo = nil349 var found bool350 if mi, found = wsOp.onReqCallbackFuns[ch]; found {351 mi = new(MethonInfo).Init(fun, param)352 wsOp.onReqCallbackFuns[ch] = mi353 return true354 }355 wsOp.conn.WriteMessage(websocket.TextMessage, subStr)356 log.Info("websocket has send data: %s", subStr)357 mi = new(MethonInfo).Init(fun, param)358 wsOp.onReqCallbackFuns[ch] = mi359 return true360}361func (wsOp *WebSocketOp) unreq(unsubStr []byte, ch string) bool {362 for !wsOp.authOk {363 time.Sleep(10)364 }365 ch = strings.ToLower(ch)366 if _, found := wsOp.onReqCallbackFuns[ch]; !found {367 return true368 }369 wsOp.conn.WriteMessage(websocket.TextMessage, unsubStr)370 log.Info("websocket has send data: %s", unsubStr)371 return true372}...
rpiswitch.go
Source:rpiswitch.go
...29echo 4 > unexport30*/31var ctrlC = false32const (33 On = "ON"34 Off = "OFF"35)36var (37 url, user, pass, dev *string38 port *int39 test, checkstate *bool40 currentState string41 wsErr error42 wg sync.WaitGroup43)44const (45 pingInterval = 10 * 6046)47func main() {48 pin := checkArgs()49 // Ctrl-C Handler50 ctrlCHandler()51 // Mainloop with Reconnect on Error52 for {53 wsErr = nil54 startWebsocket(pin)55 log.Println("Reconnect ...")56 log.Println("We wait for all goroutines to terminate")57 wg.Wait()58 time.Sleep(time.Second * 1)59 }60}61func basicAuth(username, password string) string {62 auth := username + ":" + password63 return base64.StdEncoding.EncodeToString([]byte(auth))64}65func startWebsocket(pin rpio.Pin) {66 log.Println("Connecting to " + *url)67 config, _ := websocket.NewConfig(*url, "http://localhost/")68 config.Header.Add("Authorization", "Basic "+basicAuth(*user, *pass))69 ws, err := websocket.DialConfig(config)70 if err != nil {71 wsErr = err72 return73 }74 // websocket receive handler75 go websocketHandler(ws, pin)76 // Marker, Pinger -> to see that program is working77 go markHandler(ws)78 // connect79 sendToWebsocket(ws, &devcom.DevProto{80 Action: devcom.Connect,81 Device: devcom.Device{82 ID: *dev,83 },84 PayLoad: getState(pin),85 })86 // Loop Forever87 for {88 // if device is switchable via hard-wired-switch89 if *checkstate {90 newstate := getState(pin)91 log.Printf("State from switch: %s > from server %s\n", newstate, currentState)92 if newstate != currentState {93 log.Println("NEW STATE FROM SWITCH: " + newstate)94 transmitState(newstate, ws, dev)95 currentState = newstate96 }97 }98 //error on websocket99 if wsErr != nil {100 log.Println("error - we close the connection")101 ws.Close()102 return103 }104 if ctrlC {105 cleanUpAndExit(ws, dev)106 }107 time.Sleep(1 * time.Second)108 }109}110func websocketHandler(ws *websocket.Conn, pin rpio.Pin) {111 wg.Add(1)112 defer wg.Done()113 for {114 var incoming devcom.DevProto115 err := websocket.JSON.Receive(ws, &incoming)116 if wsErr != nil {117 log.Printf("Leaving Receiver, due to error: %v ", wsErr)118 return119 }120 if err != nil {121 wsErr = err122 log.Printf("Receive Error (we are leaving): %v %+v", ws, err)123 return124 }125 log.Printf("we received: %+v\n", incoming)126 switch incoming.Action {127 // stateupdate received128 case devcom.StateUpdate:129 switch incoming.PayLoad {130 case On:131 setState(pin, On)132 case Off:133 setState(pin, Off)134 }135 case devcom.Ping:136 sendToWebsocket(ws, &devcom.DevProto{137 Action: devcom.Pong,138 })139 }140 }141}142func transmitState(state string, ws *websocket.Conn, dev *string) {143 sendToWebsocket(ws, &devcom.DevProto{144 Action: devcom.SetState,145 Device: devcom.Device{146 ID: *dev,147 },148 PayLoad: state,149 })150}151func sendToWebsocket(ws *websocket.Conn, command *devcom.DevProto) {152 log.Printf("Sending %+v ...\n", command)153 err := websocket.JSON.Send(ws, command)154 if err != nil {155 wsErr = err156 log.Printf("Error: %+v", err)157 }158}159func openPin(pin uint) rpio.Pin {160 log.Printf("Opening RPI Port %d\n", pin)161 err := rpio.Open()162 if err != nil {163 log.Fatal("Error opening", "port", pin)164 }165 result := rpio.Pin(pin)166 result.Output()167 return result168}169func getState(pin rpio.Pin) string {170 x := pin.Read()171 var state string172 if x == 1 {173 state = Off174 } else {175 state = On176 }177 return state178}179func setState(pin rpio.Pin, state string) {180 if state != getState(pin) {181 log.Println("Set Switch " + state)182 if state == On {183 pin.Low()184 } else {185 pin.High()186 }187 }188 currentState = state189}190func checkArgs() rpio.Pin {191 url = flag.String("url", "wss://2e1512f0-d590-4eed-bb41-9ad3abd03edf.pub.cloud.scaleway.com/sh/Main/DeviceFeed", "websocket url")192 user = flag.String("user", "", "username for accessing device")193 pass = flag.String("pass", "", "password for accessing device")194 dev = flag.String("device", "", "device name (e.g. device-1)")195 port = flag.Int("port", 0, "raspberr-pi gpio port")196 test = flag.Bool("test", false, "test gpio port")197 checkstate = flag.Bool("checkstate", false, "periodically check state of device and notify change of state")198 flag.Parse()199 exitErr(*port == 0, "Port not set")200 pin := openPin(uint(*port))201 if *test {202 fn := func(s string) {203 log.Println(s)204 setState(pin, s)205 log.Println("Current State: " + getState(pin) + "\n")206 time.Sleep(5 * time.Second)207 }208 for _, s := range []string{On, Off, On, Off} {209 fn(s)210 }211 os.Exit(0)212 }213 exitErr(*url == "", "URL not set")214 exitErr(*user == "", "User not set")215 exitErr(*pass == "", "Password not set")216 exitErr(*dev == "", "Device not set")217 return pin218}219func exitErr(cond bool, err string) {220 if cond {221 flag.PrintDefaults()222 log.Fatal(err)...
On
Using AI Code Generation
1ws.On("open", func() {2 log.Println("connected")3 ws.Emit("message", "Hello World")4})5ws.On("error", func(err error) {6 log.Println("error:", err)7})8ws.On("close", func() {9 log.Println("closed")10})11ws.On("message", func(msg string) {12 log.Println("message:", msg)13})14ws.On("message", func(msg []byte) {15 log.Println("message:", msg)16})17ws.On("open", func() {18 log.Println("connected")19 ws.Emit("message", "Hello World")20})21ws.On("error", func(err error) {22 log.Println("error:", err)23})24ws.On("close", func() {25 log.Println("closed")26})27ws.On("message", func(msg string) {28 log.Println("message:", msg)29})30ws.On("message", func(msg []byte) {31 log.Println("message:", msg)32})33ws.On("open", func() {34 log.Println("connected")35 ws.Emit("message", "Hello World")36})37ws.On("error", func(err error) {38 log.Println("error:", err)39})40ws.On("close", func() {41 log.Println("closed")42})43ws.On("message", func(msg string) {44 log.Println("message:", msg)45})46ws.On("message", func(msg []byte) {47 log.Println("message:", msg)48})49ws.On("open", func() {50 log.Println("connected")51 ws.Emit("message", "Hello World")52})53ws.On("error", func(err error) {54 log.Println("error:", err)55})56ws.On("close", func() {57 log.Println("closed")58})59ws.On("message", func(msg string) {60 log.Println("message:", msg)61})62ws.On("message", func(msg []byte) {63 log.Println("message:", msg)64})65ws.On("open", func() {66 log.Println("connected")67 ws.Emit("message", "Hello World")68})69ws.On("error", func(err error) {
On
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 fmt.Println("Hello world")5 })6 http.ListenAndServe(":8080", nil)7}8import (9func main() {10 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {11 fmt.Println("Hello world")12 })13 http.ListenAndServe(":8080", nil)14}15import (16func main() {17 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {18 fmt.Println("Hello world")19 })20 http.ListenAndServe(":8080", nil)21}22import (23func main() {24 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {25 fmt.Println("Hello world")26 })27 http.ListenAndServe(":8080", nil)28}29import (30func main() {31 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {32 fmt.Println("Hello world")33 })34 http.ListenAndServe(":8080", nil)35}36import (37func main() {38 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {39 fmt.Println("Hello world")40 })41 http.ListenAndServe(":8080", nil)42}43import (44func main() {45 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
On
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 http.ServeFile(w, r, "index.html")5 })6 http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {7 conn, err := (&websocket.Upgrader{8 CheckOrigin: func(r *http.Request) bool {9 },10 }).Upgrade(w, r, nil)11 if err != nil {12 fmt.Println(err)13 }14 defer conn.Close()15 conn.WriteJSON("Hello")16 conn.On("message", func(msg string) {17 fmt.Println(msg)18 })19 })20 http.ListenAndServe(":8080", nil)21}22 ws.onmessage = function (event) {23 console.log(event.data);24 };25 ws.onopen = function () {26 ws.send("Hello");27 };28import (29func main() {30 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {31 http.ServeFile(w, r, "index.html")32 })33 http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {34 conn, err := (&websocket.Upgrader{35 CheckOrigin: func(r *http.Request) bool {36 },37 }).Upgrade(w, r, nil)38 if err != nil {39 fmt.Println(err)40 }
On
Using AI Code Generation
1func main() {2 ws := websocket.New()3 ws.On("message", func(msg string) {4 fmt.Println(msg)5 })6}7func main() {8 ws := websocket.New()9 ws.On("message", func(msg string) {10 fmt.Println(msg)11 })12}13func main() {14 ws := websocket.New()15 ws.On("message", func(msg string) {16 fmt.Println(msg)17 })18}19func main() {20 ws := websocket.New()21 ws.On("message", func(msg string) {22 fmt.Println(msg)23 })24}25func main() {26 ws := websocket.New()27 ws.On("message", func(msg string) {28 fmt.Println(msg)29 })30}31func main() {32 ws := websocket.New()33 ws.On("message", func(msg string) {34 fmt.Println(msg)35 })36}37func main() {38 ws := websocket.New()39 ws.On("message", func(msg string) {40 fmt.Println(msg)41 })42}43func main() {44 ws := websocket.New()45 ws.On("message", func(msg string) {46 fmt.Println(msg)47 })48}49func main() {50 ws := websocket.New()51 ws.On("message", func(msg string) {52 fmt.Println(msg)53 })54}
On
Using AI Code Generation
1ws.On("message", func(msg string) {2 fmt.Println("message received:" + msg)3})4ws.Emit("message", "hello")5ws.Close()6ws.Close()7ws.On("message", func(msg string) {8 fmt.Println("message received:" + msg)9})10ws.Emit("message", "hello")11ws.Close()12ws.On("message", func(msg string) {13 fmt.Println("message received:" + msg)14})15ws.Emit("message", "hello")16ws.Close()17ws.On("message", func(msg string) {18 fmt.Println("message received:" + msg)19})20ws.Emit("message", "hello")21ws.Close()22ws.On("message", func(msg string) {23 fmt.Println("message received:" + msg)24})25ws.Emit("message", "hello")26ws.Close()27ws.On("message", func(msg string) {28 fmt.Println("message received:" + msg)29})30ws.Emit("message", "hello")31ws.Close()32ws.On("message", func(msg string) {33 fmt.Println("message received:" + msg)34})35ws.Emit("message", "hello")36ws.Close()
On
Using AI Code Generation
1func main() {2 server := ws.NewServer()3 server.On(ws.OnConnection, func(c *ws.Connection) {4 fmt.Println("A client connected from", c.IP)5 c.On(ws.OnMessage, func(msg string) {6 fmt.Println(msg)7 c.Send(msg)8 })9 })10 server.Listen(8000)11}12func main() {13 if err != nil {14 panic(err)15 }16 c.On(ws.OnMessage, func(msg string) {17 fmt.Println(msg)18 })19 c.Send("Hello, world!")20 select {}21}22func main() {23 if err != nil {24 panic(err)25 }26 c.On(ws.OnMessage, func(msg string) {27 fmt.Println(msg)28 })29 c.Send("Hello, world!")30 select {}31}32func main() {33 if err != nil {34 panic(err)35 }36 c.On(ws.OnMessage, func(msg string) {37 fmt.Println(msg)38 })39 c.Send("Hello, world!")
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!